summaryrefslogtreecommitdiff
path: root/chromium/content
diff options
context:
space:
mode:
authorAllan Sandfeld Jensen <allan.jensen@qt.io>2018-05-15 10:20:33 +0200
committerAllan Sandfeld Jensen <allan.jensen@qt.io>2018-05-15 10:28:57 +0000
commitd17ea114e5ef69ad5d5d7413280a13e6428098aa (patch)
tree2c01a75df69f30d27b1432467cfe7c1467a498da /chromium/content
parent8c5c43c7b138c9b4b0bf56d946e61d3bbc111bec (diff)
downloadqtwebengine-chromium-d17ea114e5ef69ad5d5d7413280a13e6428098aa.tar.gz
BASELINE: Update Chromium to 67.0.3396.47
Change-Id: Idcb1341782e417561a2473eeecc82642dafda5b7 Reviewed-by: Michal Klocek <michal.klocek@qt.io>
Diffstat (limited to 'chromium/content')
-rw-r--r--chromium/content/BUILD.gn6
-rw-r--r--chromium/content/DEPS8
-rw-r--r--chromium/content/OWNERS4
-rw-r--r--chromium/content/app/BUILD.gn9
-rw-r--r--chromium/content/app/DEPS1
-rw-r--r--chromium/content/app/OWNERS1
-rw-r--r--chromium/content/app/android/content_child_process_service_delegate.cc2
-rw-r--r--chromium/content/app/android/content_main.cc1
-rw-r--r--chromium/content/app/android/library_loader_hooks.cc2
-rw-r--r--chromium/content/app/content_main_runner.cc241
-rw-r--r--chromium/content/app/sandbox_helper_win.cc3
-rw-r--r--chromium/content/browser/BUILD.gn191
-rw-r--r--chromium/content/browser/DEPS174
-rw-r--r--chromium/content/browser/accessibility/accessibility_event_recorder.h11
-rw-r--r--chromium/content/browser/accessibility/accessibility_event_recorder_win.cc18
-rw-r--r--chromium/content/browser/accessibility/accessibility_tree_formatter.cc1
-rw-r--r--chromium/content/browser/accessibility/accessibility_tree_formatter_auralinux.cc1
-rw-r--r--chromium/content/browser/accessibility/accessibility_tree_formatter_blink.cc34
-rw-r--r--chromium/content/browser/accessibility/accessibility_tree_formatter_browser.cc1
-rw-r--r--chromium/content/browser/accessibility/accessibility_tree_formatter_win.cc1
-rw-r--r--chromium/content/browser/accessibility/accessibility_ui.cc19
-rw-r--r--chromium/content/browser/accessibility/accessibility_win_browsertest.cc1
-rw-r--r--chromium/content/browser/accessibility/aom_browsertest.cc97
-rw-r--r--chromium/content/browser/accessibility/browser_accessibility.cc51
-rw-r--r--chromium/content/browser/accessibility/browser_accessibility.h4
-rw-r--r--chromium/content/browser/accessibility/browser_accessibility_android.cc20
-rw-r--r--chromium/content/browser/accessibility/browser_accessibility_cocoa.mm60
-rw-r--r--chromium/content/browser/accessibility/browser_accessibility_com_win.cc13
-rw-r--r--chromium/content/browser/accessibility/browser_accessibility_com_win.h13
-rw-r--r--chromium/content/browser/accessibility/browser_accessibility_manager.h4
-rw-r--r--chromium/content/browser/accessibility/browser_accessibility_position.cc2
-rw-r--r--chromium/content/browser/accessibility/browser_accessibility_state_impl.cc2
-rw-r--r--chromium/content/browser/accessibility/captioning_controller.cc114
-rw-r--r--chromium/content/browser/accessibility/captioning_controller.h55
-rw-r--r--chromium/content/browser/accessibility/dump_accessibility_browsertest_base.cc21
-rw-r--r--chromium/content/browser/accessibility/dump_accessibility_browsertest_base.h2
-rw-r--r--chromium/content/browser/accessibility/dump_accessibility_events_browsertest.cc12
-rw-r--r--chromium/content/browser/accessibility/dump_accessibility_tree_browsertest.cc14
-rw-r--r--chromium/content/browser/accessibility/fullscreen_browsertest.cc4
-rw-r--r--chromium/content/browser/accessibility/snapshot_ax_tree_browsertest.cc131
-rw-r--r--chromium/content/browser/accessibility/web_contents_accessibility_android.cc2
-rw-r--r--chromium/content/browser/android/app_web_message_port.h2
-rw-r--r--chromium/content/browser/android/browser_startup_controller.cc2
-rw-r--r--chromium/content/browser/android/content_feature_list.cc2
-rw-r--r--chromium/content/browser/android/content_video_view.cc19
-rw-r--r--chromium/content/browser/android/content_video_view.h11
-rw-r--r--chromium/content/browser/android/content_view_core.cc579
-rw-r--r--chromium/content/browser/android/content_view_core.h171
-rw-r--r--chromium/content/browser/android/dialog_overlay_impl.cc1
-rw-r--r--chromium/content/browser/android/gesture_listener_manager.cc170
-rw-r--r--chromium/content/browser/android/gesture_listener_manager.h34
-rw-r--r--chromium/content/browser/android/ime_adapter_android.cc35
-rw-r--r--chromium/content/browser/android/ime_adapter_android.h1
-rw-r--r--chromium/content/browser/android/java/gin_java_bridge_dispatcher_host.cc1
-rw-r--r--chromium/content/browser/android/java/gin_java_bridge_message_filter.cc2
-rw-r--r--chromium/content/browser/android/java/gin_java_method_invocation_helper.cc1
-rw-r--r--chromium/content/browser/android/java/gin_java_method_invocation_helper_unittest.cc1
-rw-r--r--chromium/content/browser/android/java/gin_java_script_to_java_types_coercion.cc1
-rw-r--r--chromium/content/browser/android/overscroll_controller_android.cc12
-rw-r--r--chromium/content/browser/android/overscroll_controller_android_unittest.cc11
-rw-r--r--chromium/content/browser/android/select_popup.cc172
-rw-r--r--chromium/content/browser/android/select_popup.h63
-rw-r--r--chromium/content/browser/android/selection/OWNERS1
-rw-r--r--chromium/content/browser/android/selection/composited_touch_handle_drawable.cc (renamed from chromium/content/browser/android/composited_touch_handle_drawable.cc)2
-rw-r--r--chromium/content/browser/android/selection/composited_touch_handle_drawable.h (renamed from chromium/content/browser/android/composited_touch_handle_drawable.h)6
-rw-r--r--chromium/content/browser/android/selection/selection_popup_controller.cc (renamed from chromium/content/browser/android/selection_popup_controller.cc)42
-rw-r--r--chromium/content/browser/android/selection/selection_popup_controller.h (renamed from chromium/content/browser/android/selection_popup_controller.h)15
-rw-r--r--chromium/content/browser/android/selection/smart_selection_client.cc (renamed from chromium/content/browser/android/smart_selection_client.cc)3
-rw-r--r--chromium/content/browser/android/selection/smart_selection_client.h (renamed from chromium/content/browser/android/smart_selection_client.h)6
-rw-r--r--chromium/content/browser/android/synchronous_compositor_browser_filter.cc1
-rw-r--r--chromium/content/browser/android/synchronous_compositor_host.cc15
-rw-r--r--chromium/content/browser/android/synchronous_compositor_host.h22
-rw-r--r--chromium/content/browser/android/text_suggestion_host_android.h4
-rw-r--r--chromium/content/browser/android/text_suggestion_host_mojo_impl_android.h2
-rw-r--r--chromium/content/browser/android/url_request_content_job.cc15
-rw-r--r--chromium/content/browser/android/url_request_content_job.h1
-rw-r--r--chromium/content/browser/android/url_request_content_job_unittest.cc41
-rw-r--r--chromium/content/browser/appcache/appcache.cc44
-rw-r--r--chromium/content/browser/appcache/appcache.h4
-rw-r--r--chromium/content/browser/appcache/appcache_backend_impl.cc1
-rw-r--r--chromium/content/browser/appcache/appcache_backend_impl.h2
-rw-r--r--chromium/content/browser/appcache/appcache_database.cc82
-rw-r--r--chromium/content/browser/appcache/appcache_database.h28
-rw-r--r--chromium/content/browser/appcache/appcache_database_unittest.cc38
-rw-r--r--chromium/content/browser/appcache/appcache_disk_cache.cc18
-rw-r--r--chromium/content/browser/appcache/appcache_disk_cache.h6
-rw-r--r--chromium/content/browser/appcache/appcache_disk_cache_unittest.cc5
-rw-r--r--chromium/content/browser/appcache/appcache_group.cc21
-rw-r--r--chromium/content/browser/appcache/appcache_group.h6
-rw-r--r--chromium/content/browser/appcache/appcache_histograms.cc30
-rw-r--r--chromium/content/browser/appcache/appcache_histograms.h20
-rw-r--r--chromium/content/browser/appcache/appcache_host.cc13
-rw-r--r--chromium/content/browser/appcache/appcache_host.h9
-rw-r--r--chromium/content/browser/appcache/appcache_internals_ui.cc14
-rw-r--r--chromium/content/browser/appcache/appcache_quota_client.cc14
-rw-r--r--chromium/content/browser/appcache/appcache_quota_client.h2
-rw-r--r--chromium/content/browser/appcache/appcache_quota_client_unittest.cc2
-rw-r--r--chromium/content/browser/appcache/appcache_request_handler.cc12
-rw-r--r--chromium/content/browser/appcache/appcache_request_handler.h6
-rw-r--r--chromium/content/browser/appcache/appcache_request_handler_unittest.cc1
-rw-r--r--chromium/content/browser/appcache/appcache_response.h2
-rw-r--r--chromium/content/browser/appcache/appcache_service_impl.cc27
-rw-r--r--chromium/content/browser/appcache/appcache_service_impl.h3
-rw-r--r--chromium/content/browser/appcache/appcache_service_unittest.cc14
-rw-r--r--chromium/content/browser/appcache/appcache_storage.cc17
-rw-r--r--chromium/content/browser/appcache/appcache_storage.h27
-rw-r--r--chromium/content/browser/appcache/appcache_storage_impl.cc252
-rw-r--r--chromium/content/browser/appcache/appcache_storage_impl.h3
-rw-r--r--chromium/content/browser/appcache/appcache_storage_impl_unittest.cc65
-rw-r--r--chromium/content/browser/appcache/appcache_storage_unittest.cc18
-rw-r--r--chromium/content/browser/appcache/appcache_subresource_url_factory.cc10
-rw-r--r--chromium/content/browser/appcache/appcache_update_job.cc166
-rw-r--r--chromium/content/browser/appcache/appcache_update_job.h8
-rw-r--r--chromium/content/browser/appcache/appcache_update_job_unittest.cc40
-rw-r--r--chromium/content/browser/appcache/appcache_update_url_loader_request.cc10
-rw-r--r--chromium/content/browser/appcache/appcache_update_url_loader_request.h1
-rw-r--r--chromium/content/browser/appcache/appcache_url_loader_job.cc16
-rw-r--r--chromium/content/browser/appcache/appcache_url_loader_job.h11
-rw-r--r--chromium/content/browser/appcache/appcache_url_request_job.cc6
-rw-r--r--chromium/content/browser/appcache/appcache_working_set.cc9
-rw-r--r--chromium/content/browser/appcache/appcache_working_set.h17
-rw-r--r--chromium/content/browser/appcache/chrome_appcache_service.cc2
-rw-r--r--chromium/content/browser/appcache/chrome_appcache_service_unittest.cc30
-rw-r--r--chromium/content/browser/appcache/mock_appcache_service.cc3
-rw-r--r--chromium/content/browser/appcache/mock_appcache_service.h2
-rw-r--r--chromium/content/browser/appcache/mock_appcache_storage.cc26
-rw-r--r--chromium/content/browser/appcache/mock_appcache_storage.h10
-rw-r--r--chromium/content/browser/background_fetch/DEPS2
-rw-r--r--chromium/content/browser/background_fetch/OWNERS3
-rw-r--r--chromium/content/browser/background_fetch/background_fetch.proto58
-rw-r--r--chromium/content/browser/background_fetch/background_fetch_context.cc28
-rw-r--r--chromium/content/browser/background_fetch/background_fetch_context.h16
-rw-r--r--chromium/content/browser/background_fetch/background_fetch_data_manager.cc85
-rw-r--r--chromium/content/browser/background_fetch/background_fetch_data_manager.h17
-rw-r--r--chromium/content/browser/background_fetch/background_fetch_data_manager_unittest.cc155
-rw-r--r--chromium/content/browser/background_fetch/background_fetch_delegate_proxy.cc42
-rw-r--r--chromium/content/browser/background_fetch/background_fetch_delegate_proxy.h10
-rw-r--r--chromium/content/browser/background_fetch/background_fetch_delegate_proxy_unittest.cc49
-rw-r--r--chromium/content/browser/background_fetch/background_fetch_embedded_worker_test_helper.cc2
-rw-r--r--chromium/content/browser/background_fetch/background_fetch_event_dispatcher.cc9
-rw-r--r--chromium/content/browser/background_fetch/background_fetch_job_controller.cc10
-rw-r--r--chromium/content/browser/background_fetch/background_fetch_job_controller.h5
-rw-r--r--chromium/content/browser/background_fetch/background_fetch_job_controller_unittest.cc2
-rw-r--r--chromium/content/browser/background_fetch/background_fetch_registration_id.cc2
-rw-r--r--chromium/content/browser/background_fetch/background_fetch_registration_notifier.h2
-rw-r--r--chromium/content/browser/background_fetch/background_fetch_registration_notifier_unittest.cc2
-rw-r--r--chromium/content/browser/background_fetch/background_fetch_scheduler_unittest.cc6
-rw-r--r--chromium/content/browser/background_fetch/background_fetch_service_impl.cc23
-rw-r--r--chromium/content/browser/background_fetch/background_fetch_service_impl.h8
-rw-r--r--chromium/content/browser/background_fetch/background_fetch_service_unittest.cc60
-rw-r--r--chromium/content/browser/background_fetch/background_fetch_test_base.cc10
-rw-r--r--chromium/content/browser/background_fetch/mock_background_fetch_delegate.cc4
-rw-r--r--chromium/content/browser/background_fetch/mock_background_fetch_delegate.h3
-rw-r--r--chromium/content/browser/background_fetch/storage/README.md2
-rw-r--r--chromium/content/browser/background_fetch/storage/cleanup_task.cc9
-rw-r--r--chromium/content/browser/background_fetch/storage/create_metadata_task.cc (renamed from chromium/content/browser/background_fetch/storage/create_registration_task.cc)101
-rw-r--r--chromium/content/browser/background_fetch/storage/create_metadata_task.h64
-rw-r--r--chromium/content/browser/background_fetch/storage/create_registration_task.h62
-rw-r--r--chromium/content/browser/background_fetch/storage/database_task.h2
-rw-r--r--chromium/content/browser/background_fetch/storage/delete_registration_task.cc13
-rw-r--r--chromium/content/browser/background_fetch/storage/get_developer_ids_task.h2
-rw-r--r--chromium/content/browser/background_fetch/storage/get_metadata_task.cc (renamed from chromium/content/browser/background_fetch/storage/get_registration_task.cc)64
-rw-r--r--chromium/content/browser/background_fetch/storage/get_metadata_task.h66
-rw-r--r--chromium/content/browser/background_fetch/storage/get_registration_task.h63
-rw-r--r--chromium/content/browser/background_fetch/storage/mark_registration_for_deletion_task.cc12
-rw-r--r--chromium/content/browser/background_fetch/storage/update_registration_ui_task.cc96
-rw-r--r--chromium/content/browser/background_fetch/storage/update_registration_ui_task.h58
-rw-r--r--chromium/content/browser/background_sync/background_sync_browsertest.cc1
-rw-r--r--chromium/content/browser/background_sync/background_sync_context.h2
-rw-r--r--chromium/content/browser/background_sync/background_sync_manager.cc4
-rw-r--r--chromium/content/browser/background_sync/background_sync_manager.h4
-rw-r--r--chromium/content/browser/background_sync/background_sync_manager_unittest.cc6
-rw-r--r--chromium/content/browser/background_sync/background_sync_registration.h2
-rw-r--r--chromium/content/browser/background_sync/background_sync_service_impl.h2
-rw-r--r--chromium/content/browser/background_sync/background_sync_service_impl_unittest.cc2
-rw-r--r--chromium/content/browser/bad_message.h5
-rw-r--r--chromium/content/browser/blob_storage/blob_dispatcher_host.cc24
-rw-r--r--chromium/content/browser/blob_storage/blob_internals_url_loader.cc2
-rw-r--r--chromium/content/browser/blob_storage/blob_registry_wrapper.h2
-rw-r--r--chromium/content/browser/blob_storage/blob_url_loader_factory.cc2
-rw-r--r--chromium/content/browser/blob_storage/blob_url_unittest.cc13
-rw-r--r--chromium/content/browser/blob_storage/chrome_blob_storage_context.cc30
-rw-r--r--chromium/content/browser/blob_storage/chrome_blob_storage_context.h7
-rw-r--r--chromium/content/browser/bluetooth/README.md2
-rw-r--r--chromium/content/browser/bluetooth/bluetooth_allowed_devices.h2
-rw-r--r--chromium/content/browser/bluetooth/bluetooth_blocklist.h2
-rw-r--r--chromium/content/browser/bluetooth/bluetooth_device_chooser_controller.cc27
-rw-r--r--chromium/content/browser/bluetooth/bluetooth_device_chooser_controller.h20
-rw-r--r--chromium/content/browser/bluetooth/bluetooth_metrics.h2
-rw-r--r--chromium/content/browser/bluetooth/frame_connected_bluetooth_devices.cc1
-rw-r--r--chromium/content/browser/bluetooth/frame_connected_bluetooth_devices.h2
-rw-r--r--chromium/content/browser/bluetooth/frame_connected_bluetooth_devices_unittest.cc1
-rw-r--r--chromium/content/browser/bluetooth/web_bluetooth_service_impl.cc16
-rw-r--r--chromium/content/browser/bluetooth/web_bluetooth_service_impl.h4
-rw-r--r--chromium/content/browser/broadcast_channel/broadcast_channel_provider.h2
-rw-r--r--chromium/content/browser/browser_child_process_host_impl.cc42
-rw-r--r--chromium/content/browser/browser_child_process_host_impl.h4
-rw-r--r--chromium/content/browser/browser_context.cc31
-rw-r--r--chromium/content/browser/browser_main_loop.cc274
-rw-r--r--chromium/content/browser/browser_main_loop.h40
-rw-r--r--chromium/content/browser/browser_main_loop_unittest.cc2
-rw-r--r--chromium/content/browser/browser_main_runner.cc6
-rw-r--r--chromium/content/browser/browser_plugin/browser_plugin_embedder.cc13
-rw-r--r--chromium/content/browser/browser_plugin/browser_plugin_embedder.h2
-rw-r--r--chromium/content/browser/browser_plugin/browser_plugin_guest.cc77
-rw-r--r--chromium/content/browser/browser_plugin/browser_plugin_guest.h22
-rw-r--r--chromium/content/browser/browser_plugin/browser_plugin_message_filter.cc1
-rw-r--r--chromium/content/browser/browser_plugin/browser_plugin_message_filter.h1
-rw-r--r--chromium/content/browser/browser_process_sub_thread.cc138
-rw-r--r--chromium/content/browser/browser_process_sub_thread.h54
-rw-r--r--chromium/content/browser/browser_side_navigation_browsertest.cc12
-rw-r--r--chromium/content/browser/browser_thread_impl.cc534
-rw-r--r--chromium/content/browser/browser_thread_impl.h99
-rw-r--r--chromium/content/browser/browser_thread_unittest.cc24
-rw-r--r--chromium/content/browser/browser_url_handler_impl_unittest.cc4
-rw-r--r--chromium/content/browser/browsing_data/browsing_data_filter_builder_impl.cc15
-rw-r--r--chromium/content/browser/browsing_data/browsing_data_filter_builder_impl.h2
-rw-r--r--chromium/content/browser/browsing_data/browsing_data_remover_impl.cc58
-rw-r--r--chromium/content/browser/browsing_data/browsing_data_remover_impl.h5
-rw-r--r--chromium/content/browser/browsing_data/browsing_data_remover_impl_unittest.cc2
-rw-r--r--chromium/content/browser/browsing_data/clear_site_data_throttle_browsertest.cc3
-rw-r--r--chromium/content/browser/browsing_data/clear_site_data_throttle_unittest.cc1
-rw-r--r--chromium/content/browser/browsing_data/conditional_cache_deletion_helper_browsertest.cc3
-rw-r--r--chromium/content/browser/browsing_instance.cc2
-rw-r--r--chromium/content/browser/cache_storage/cache_storage.cc40
-rw-r--r--chromium/content/browser/cache_storage/cache_storage.h17
-rw-r--r--chromium/content/browser/cache_storage/cache_storage_blob_to_disk_cache.cc6
-rw-r--r--chromium/content/browser/cache_storage/cache_storage_blob_to_disk_cache.h2
-rw-r--r--chromium/content/browser/cache_storage/cache_storage_blob_to_disk_cache_unittest.cc1
-rw-r--r--chromium/content/browser/cache_storage/cache_storage_cache.cc116
-rw-r--r--chromium/content/browser/cache_storage/cache_storage_cache.h24
-rw-r--r--chromium/content/browser/cache_storage/cache_storage_cache_unittest.cc263
-rw-r--r--chromium/content/browser/cache_storage/cache_storage_dispatcher_host.cc655
-rw-r--r--chromium/content/browser/cache_storage/cache_storage_dispatcher_host.h183
-rw-r--r--chromium/content/browser/cache_storage/cache_storage_manager.cc9
-rw-r--r--chromium/content/browser/cache_storage/cache_storage_manager.h2
-rw-r--r--chromium/content/browser/cache_storage/cache_storage_manager_unittest.cc25
-rw-r--r--chromium/content/browser/cache_storage/cache_storage_operation_unittest.cc1
-rw-r--r--chromium/content/browser/cache_storage/cache_storage_quota_client.cc2
-rw-r--r--chromium/content/browser/cache_storage/cache_storage_quota_client.h2
-rw-r--r--chromium/content/browser/cache_storage/cache_storage_scheduler.cc1
-rw-r--r--chromium/content/browser/child_process_launcher.cc24
-rw-r--r--chromium/content/browser/child_process_launcher.h9
-rw-r--r--chromium/content/browser/child_process_launcher_helper.cc58
-rw-r--r--chromium/content/browser/child_process_launcher_helper.h8
-rw-r--r--chromium/content/browser/child_process_launcher_helper_android.cc24
-rw-r--r--chromium/content/browser/child_process_launcher_helper_fuchsia.cc18
-rw-r--r--chromium/content/browser/child_process_launcher_helper_linux.cc14
-rw-r--r--chromium/content/browser/child_process_launcher_helper_mac.cc14
-rw-r--r--chromium/content/browser/child_process_launcher_helper_win.cc17
-rw-r--r--chromium/content/browser/child_process_security_policy_browsertest.cc15
-rw-r--r--chromium/content/browser/child_process_security_policy_impl.cc7
-rw-r--r--chromium/content/browser/compositor/browser_compositor_output_surface.cc1
-rw-r--r--chromium/content/browser/compositor/gpu_browser_compositor_output_surface.h2
-rw-r--r--chromium/content/browser/compositor/gpu_process_transport_factory.cc32
-rw-r--r--chromium/content/browser/compositor/gpu_process_transport_factory.h1
-rw-r--r--chromium/content/browser/compositor/offscreen_browser_compositor_output_surface.h2
-rw-r--r--chromium/content/browser/compositor/reflector_impl.cc1
-rw-r--r--chromium/content/browser/compositor/reflector_impl_unittest.cc4
-rw-r--r--chromium/content/browser/compositor/software_browser_compositor_output_surface.h2
-rw-r--r--chromium/content/browser/compositor/software_browser_compositor_output_surface_unittest.cc1
-rw-r--r--chromium/content/browser/compositor/viz_process_transport_factory.cc74
-rw-r--r--chromium/content/browser/compositor/viz_process_transport_factory.h19
-rw-r--r--chromium/content/browser/cross_site_transfer_browsertest.cc22
-rw-r--r--chromium/content/browser/dedicated_worker/dedicated_worker_host.h2
-rw-r--r--chromium/content/browser/device_sensors/DEPS3
-rw-r--r--chromium/content/browser/device_sensors/device_sensor_browsertest.cc244
-rw-r--r--chromium/content/browser/devtools/BUILD.gn19
-rw-r--r--chromium/content/browser/devtools/browser_devtools_agent_host.cc16
-rw-r--r--chromium/content/browser/devtools/browser_devtools_agent_host.h2
-rw-r--r--chromium/content/browser/devtools/devtools_agent_host_impl.cc56
-rw-r--r--chromium/content/browser/devtools/devtools_agent_host_impl.h11
-rw-r--r--chromium/content/browser/devtools/devtools_frame_trace_recorder_for_viz.cc118
-rw-r--r--chromium/content/browser/devtools/devtools_frame_trace_recorder_for_viz.h49
-rw-r--r--chromium/content/browser/devtools/devtools_frontend_host_impl.cc2
-rw-r--r--chromium/content/browser/devtools/devtools_frontend_host_impl.h2
-rw-r--r--chromium/content/browser/devtools/devtools_http_handler.cc9
-rw-r--r--chromium/content/browser/devtools/devtools_interceptor_controller.cc2
-rw-r--r--chromium/content/browser/devtools/devtools_io_context.cc1
-rw-r--r--chromium/content/browser/devtools/devtools_manager.cc1
-rw-r--r--chromium/content/browser/devtools/devtools_network_interceptor.cc49
-rw-r--r--chromium/content/browser/devtools/devtools_network_interceptor.h24
-rw-r--r--chromium/content/browser/devtools/devtools_pipe_handler.cc1
-rw-r--r--chromium/content/browser/devtools/devtools_session.cc14
-rw-r--r--chromium/content/browser/devtools/devtools_session.h9
-rw-r--r--chromium/content/browser/devtools/devtools_target_registry.cc1
-rw-r--r--chromium/content/browser/devtools/devtools_traceable_screenshot.h4
-rw-r--r--chromium/content/browser/devtools/devtools_url_interceptor_request_job.cc69
-rw-r--r--chromium/content/browser/devtools/devtools_url_interceptor_request_job.h4
-rw-r--r--chromium/content/browser/devtools/devtools_url_loader_interceptor.cc1170
-rw-r--r--chromium/content/browser/devtools/devtools_url_loader_interceptor.h68
-rw-r--r--chromium/content/browser/devtools/devtools_url_request_interceptor.cc36
-rw-r--r--chromium/content/browser/devtools/devtools_video_consumer.cc169
-rw-r--r--chromium/content/browser/devtools/devtools_video_consumer.h104
-rw-r--r--chromium/content/browser/devtools/devtools_video_consumer_browsertest.cc128
-rw-r--r--chromium/content/browser/devtools/devtools_video_consumer_unittest.cc394
-rw-r--r--chromium/content/browser/devtools/protocol/browser_handler.cc2
-rw-r--r--chromium/content/browser/devtools/protocol/browser_handler.h2
-rw-r--r--chromium/content/browser/devtools/protocol/devtools_download_manager_delegate.cc2
-rw-r--r--chromium/content/browser/devtools/protocol/devtools_protocol_browsertest.cc158
-rw-r--r--chromium/content/browser/devtools/protocol/emulation_handler.cc32
-rw-r--r--chromium/content/browser/devtools/protocol/emulation_handler.h2
-rw-r--r--chromium/content/browser/devtools/protocol/input_handler.cc6
-rw-r--r--chromium/content/browser/devtools/protocol/input_handler.h9
-rw-r--r--chromium/content/browser/devtools/protocol/native_input_event_builder_mac.mm2
-rw-r--r--chromium/content/browser/devtools/protocol/network_handler.cc846
-rw-r--r--chromium/content/browser/devtools/protocol/network_handler.h13
-rw-r--r--chromium/content/browser/devtools/protocol/page_handler.cc7
-rw-r--r--chromium/content/browser/devtools/protocol/page_handler.h4
-rw-r--r--chromium/content/browser/devtools/protocol/security_handler.cc8
-rw-r--r--chromium/content/browser/devtools/protocol/service_worker_handler.cc10
-rw-r--r--chromium/content/browser/devtools/protocol/storage_handler.cc6
-rw-r--r--chromium/content/browser/devtools/protocol/system_info_handler.cc1
-rw-r--r--chromium/content/browser/devtools/protocol/target_auto_attacher.cc5
-rw-r--r--chromium/content/browser/devtools/protocol/tethering_handler.cc3
-rw-r--r--chromium/content/browser/devtools/protocol/tracing_handler.cc178
-rw-r--r--chromium/content/browser/devtools/protocol/tracing_handler.h23
-rw-r--r--chromium/content/browser/devtools/protocol/tracing_handler_unittest.cc3
-rw-r--r--chromium/content/browser/devtools/protocol_config.json2
-rw-r--r--chromium/content/browser/devtools/render_frame_devtools_agent_host.cc88
-rw-r--r--chromium/content/browser/devtools/render_frame_devtools_agent_host.h12
-rw-r--r--chromium/content/browser/devtools/service_worker_devtools_agent_host.cc3
-rw-r--r--chromium/content/browser/devtools/service_worker_devtools_agent_host.h4
-rw-r--r--chromium/content/browser/devtools/service_worker_devtools_manager.h2
-rw-r--r--chromium/content/browser/devtools/shared_worker_devtools_agent_host.cc3
-rw-r--r--chromium/content/browser/devtools/shared_worker_devtools_agent_host.h4
-rw-r--r--chromium/content/browser/do_not_track_browsertest.cc89
-rw-r--r--chromium/content/browser/dom_storage/dom_storage_browsertest.cc1
-rw-r--r--chromium/content/browser/dom_storage/dom_storage_context_impl.cc2
-rw-r--r--chromium/content/browser/dom_storage/dom_storage_context_wrapper.cc18
-rw-r--r--chromium/content/browser/dom_storage/dom_storage_context_wrapper.h8
-rw-r--r--chromium/content/browser/dom_storage/dom_storage_message_filter.cc1
-rw-r--r--chromium/content/browser/dom_storage/dom_storage_session.cc164
-rw-r--r--chromium/content/browser/dom_storage/dom_storage_session.h86
-rw-r--r--chromium/content/browser/dom_storage/local_storage_context_mojo.cc25
-rw-r--r--chromium/content/browser/dom_storage/local_storage_context_mojo.h2
-rw-r--r--chromium/content/browser/dom_storage/local_storage_context_mojo_unittest.cc4
-rw-r--r--chromium/content/browser/dom_storage/session_storage_context_mojo.cc2
-rw-r--r--chromium/content/browser/dom_storage/session_storage_context_mojo.h10
-rw-r--r--chromium/content/browser/dom_storage/session_storage_database.cc2
-rw-r--r--chromium/content/browser/dom_storage/session_storage_namespace_impl.cc141
-rw-r--r--chromium/content/browser/dom_storage/session_storage_namespace_impl.h49
-rw-r--r--chromium/content/browser/download/base_file.cc535
-rw-r--r--chromium/content/browser/download/base_file.h267
-rw-r--r--chromium/content/browser/download/base_file_posix.cc44
-rw-r--r--chromium/content/browser/download/base_file_unittest.cc759
-rw-r--r--chromium/content/browser/download/base_file_win.cc328
-rw-r--r--chromium/content/browser/download/base_file_win_unittest.cc116
-rw-r--r--chromium/content/browser/download/blob_download_url_loader_factory_getter.cc38
-rw-r--r--chromium/content/browser/download/blob_download_url_loader_factory_getter.h40
-rw-r--r--chromium/content/browser/download/byte_stream_input_stream.cc59
-rw-r--r--chromium/content/browser/download/byte_stream_input_stream.h43
-rw-r--r--chromium/content/browser/download/docs/save-page-as.md8
-rw-r--r--chromium/content/browser/download/download_browsertest.cc261
-rw-r--r--chromium/content/browser/download/download_destination_observer.h49
-rw-r--r--chromium/content/browser/download/download_file.h110
-rw-r--r--chromium/content/browser/download/download_file_factory.cc25
-rw-r--r--chromium/content/browser/download/download_file_factory.h42
-rw-r--r--chromium/content/browser/download/download_file_impl.cc908
-rw-r--r--chromium/content/browser/download/download_file_impl.h373
-rw-r--r--chromium/content/browser/download/download_file_unittest.cc1093
-rw-r--r--chromium/content/browser/download/download_interrupt_reasons_utils.cc157
-rw-r--r--chromium/content/browser/download/download_interrupt_reasons_utils.h40
-rw-r--r--chromium/content/browser/download/download_item_factory.h86
-rw-r--r--chromium/content/browser/download/download_item_impl.cc2571
-rw-r--r--chromium/content/browser/download/download_item_impl.h772
-rw-r--r--chromium/content/browser/download/download_item_impl_delegate.cc90
-rw-r--r--chromium/content/browser/download/download_item_impl_delegate.h110
-rw-r--r--chromium/content/browser/download/download_item_impl_unittest.cc2468
-rw-r--r--chromium/content/browser/download/download_job.cc117
-rw-r--r--chromium/content/browser/download/download_job.h84
-rw-r--r--chromium/content/browser/download/download_job_factory.cc120
-rw-r--r--chromium/content/browser/download/download_job_factory.h37
-rw-r--r--chromium/content/browser/download/download_job_impl.cc22
-rw-r--r--chromium/content/browser/download/download_job_impl.h35
-rw-r--r--chromium/content/browser/download/download_job_unittest.cc43
-rw-r--r--chromium/content/browser/download/download_manager_impl.cc441
-rw-r--r--chromium/content/browser/download/download_manager_impl.h108
-rw-r--r--chromium/content/browser/download/download_manager_impl_unittest.cc193
-rw-r--r--chromium/content/browser/download/download_request_core.cc29
-rw-r--r--chromium/content/browser/download/download_request_core.h1
-rw-r--r--chromium/content/browser/download/download_request_core_unittest.cc3
-rw-r--r--chromium/content/browser/download/download_resource_handler.cc5
-rw-r--r--chromium/content/browser/download/download_response_handler.cc225
-rw-r--r--chromium/content/browser/download/download_response_handler.h106
-rw-r--r--chromium/content/browser/download/download_utils.cc359
-rw-r--r--chromium/content/browser/download/download_utils.h44
-rw-r--r--chromium/content/browser/download/download_worker.cc164
-rw-r--r--chromium/content/browser/download/download_worker.h95
-rw-r--r--chromium/content/browser/download/drag_download_file.h1
-rw-r--r--chromium/content/browser/download/drag_download_file_browsertest.cc4
-rw-r--r--chromium/content/browser/download/mhtml_generation_browsertest.cc12
-rw-r--r--chromium/content/browser/download/mhtml_generation_manager.cc79
-rw-r--r--chromium/content/browser/download/mhtml_generation_manager.h6
-rw-r--r--chromium/content/browser/download/mock_download_file.cc51
-rw-r--r--chromium/content/browser/download/mock_download_file.h81
-rw-r--r--chromium/content/browser/download/mock_download_item_impl.cc39
-rw-r--r--chromium/content/browser/download/mock_download_item_impl.h123
-rw-r--r--chromium/content/browser/download/mock_download_job.cc14
-rw-r--r--chromium/content/browser/download/mock_download_job.h46
-rw-r--r--chromium/content/browser/download/network_download_url_loader_factory_getter.cc27
-rw-r--r--chromium/content/browser/download/network_download_url_loader_factory_getter.h35
-rw-r--r--chromium/content/browser/download/parallel_download_job.cc313
-rw-r--r--chromium/content/browser/download/parallel_download_job.h110
-rw-r--r--chromium/content/browser/download/parallel_download_job_unittest.cc543
-rw-r--r--chromium/content/browser/download/parallel_download_utils.cc225
-rw-r--r--chromium/content/browser/download/parallel_download_utils.h102
-rw-r--r--chromium/content/browser/download/parallel_download_utils_unittest.cc400
-rw-r--r--chromium/content/browser/download/resource_downloader.cc215
-rw-r--r--chromium/content/browser/download/resource_downloader.h127
-rw-r--r--chromium/content/browser/download/save_file.cc6
-rw-r--r--chromium/content/browser/download/save_file.h5
-rw-r--r--chromium/content/browser/download/save_file_manager.cc271
-rw-r--r--chromium/content/browser/download/save_file_manager.h61
-rw-r--r--chromium/content/browser/download/save_file_resource_handler.cc128
-rw-r--r--chromium/content/browser/download/save_file_resource_handler.h100
-rw-r--r--chromium/content/browser/download/save_package.cc24
-rw-r--r--chromium/content/browser/download/save_package.h27
-rw-r--r--chromium/content/browser/download/save_package_download_job.cc20
-rw-r--r--chromium/content/browser/download/save_package_download_job.h32
-rw-r--r--chromium/content/browser/download/save_types.cc3
-rw-r--r--chromium/content/browser/download/save_types.h3
-rw-r--r--chromium/content/browser/download/url_download_handler.h39
-rw-r--r--chromium/content/browser/download/url_downloader.cc20
-rw-r--r--chromium/content/browser/download/url_downloader.h8
-rw-r--r--chromium/content/browser/download/url_downloader_factory.cc34
-rw-r--r--chromium/content/browser/download/url_downloader_factory.h30
-rw-r--r--chromium/content/browser/field_trial_recorder.cc1
-rw-r--r--chromium/content/browser/file_url_loader_factory.cc5
-rw-r--r--chromium/content/browser/fileapi/DEPS2
-rw-r--r--chromium/content/browser/fileapi/browser_file_system_helper.cc7
-rw-r--r--chromium/content/browser/fileapi/fileapi_message_filter.cc5
-rw-r--r--chromium/content/browser/fileapi/fileapi_message_filter.h6
-rw-r--r--chromium/content/browser/find_request_manager.h2
-rw-r--r--chromium/content/browser/find_request_manager_browsertest.cc17
-rw-r--r--chromium/content/browser/frame_host/cross_process_frame_connector.cc58
-rw-r--r--chromium/content/browser/frame_host/cross_process_frame_connector.h15
-rw-r--r--chromium/content/browser/frame_host/data_url_navigation_browsertest.cc2
-rw-r--r--chromium/content/browser/frame_host/data_url_navigation_throttle.cc13
-rw-r--r--chromium/content/browser/frame_host/debug_urls.cc26
-rw-r--r--chromium/content/browser/frame_host/frame_tree.cc8
-rw-r--r--chromium/content/browser/frame_host/frame_tree.h3
-rw-r--r--chromium/content/browser/frame_host/frame_tree_browsertest.cc6
-rw-r--r--chromium/content/browser/frame_host/frame_tree_node.cc12
-rw-r--r--chromium/content/browser/frame_host/frame_tree_node.h19
-rw-r--r--chromium/content/browser/frame_host/frame_tree_node_blame_context_unittest.cc4
-rw-r--r--chromium/content/browser/frame_host/frame_tree_unittest.cc36
-rw-r--r--chromium/content/browser/frame_host/input/legacy_ipc_frame_input_handler.cc14
-rw-r--r--chromium/content/browser/frame_host/interstitial_page_impl.cc6
-rw-r--r--chromium/content/browser/frame_host/interstitial_page_impl.h1
-rw-r--r--chromium/content/browser/frame_host/interstitial_page_impl_browsertest.cc2
-rw-r--r--chromium/content/browser/frame_host/keep_alive_handle_factory.cc20
-rw-r--r--chromium/content/browser/frame_host/mixed_content_navigation_throttle.h2
-rw-r--r--chromium/content/browser/frame_host/navigation_controller_impl.cc2
-rw-r--r--chromium/content/browser/frame_host/navigation_controller_impl_browsertest.cc134
-rw-r--r--chromium/content/browser/frame_host/navigation_controller_impl_unittest.cc10
-rw-r--r--chromium/content/browser/frame_host/navigation_entry_screenshot_manager.cc7
-rw-r--r--chromium/content/browser/frame_host/navigation_handle_impl.cc171
-rw-r--r--chromium/content/browser/frame_host/navigation_handle_impl.h52
-rw-r--r--chromium/content/browser/frame_host/navigation_handle_impl_browsertest.cc198
-rw-r--r--chromium/content/browser/frame_host/navigation_handle_impl_unittest.cc2
-rw-r--r--chromium/content/browser/frame_host/navigation_request.cc111
-rw-r--r--chromium/content/browser/frame_host/navigation_request.h15
-rw-r--r--chromium/content/browser/frame_host/navigation_request_info.cc20
-rw-r--r--chromium/content/browser/frame_host/navigation_request_info.h9
-rw-r--r--chromium/content/browser/frame_host/navigator.cc3
-rw-r--r--chromium/content/browser/frame_host/navigator.h13
-rw-r--r--chromium/content/browser/frame_host/navigator_delegate.cc4
-rw-r--r--chromium/content/browser/frame_host/navigator_delegate.h4
-rw-r--r--chromium/content/browser/frame_host/navigator_impl.cc65
-rw-r--r--chromium/content/browser/frame_host/navigator_impl.h7
-rw-r--r--chromium/content/browser/frame_host/popup_menu_helper_mac.h8
-rw-r--r--chromium/content/browser/frame_host/popup_menu_helper_mac.mm14
-rw-r--r--chromium/content/browser/frame_host/render_frame_host_android.cc4
-rw-r--r--chromium/content/browser/frame_host/render_frame_host_android.h4
-rw-r--r--chromium/content/browser/frame_host/render_frame_host_delegate.cc1
-rw-r--r--chromium/content/browser/frame_host/render_frame_host_delegate.h20
-rw-r--r--chromium/content/browser/frame_host/render_frame_host_feature_policy_unittest.cc6
-rw-r--r--chromium/content/browser/frame_host/render_frame_host_impl.cc342
-rw-r--r--chromium/content/browser/frame_host/render_frame_host_impl.h101
-rw-r--r--chromium/content/browser/frame_host/render_frame_host_impl_browsertest.cc101
-rw-r--r--chromium/content/browser/frame_host/render_frame_host_manager.cc120
-rw-r--r--chromium/content/browser/frame_host/render_frame_host_manager.h24
-rw-r--r--chromium/content/browser/frame_host/render_frame_host_manager_browsertest.cc259
-rw-r--r--chromium/content/browser/frame_host/render_frame_host_manager_unittest.cc22
-rw-r--r--chromium/content/browser/frame_host/render_frame_message_filter.cc37
-rw-r--r--chromium/content/browser/frame_host/render_frame_message_filter.h15
-rw-r--r--chromium/content/browser/frame_host/render_frame_message_filter_browsertest.cc1
-rw-r--r--chromium/content/browser/frame_host/render_frame_proxy_host.h2
-rw-r--r--chromium/content/browser/frame_host/render_widget_host_view_guest.cc119
-rw-r--r--chromium/content/browser/frame_host/render_widget_host_view_guest.h18
-rw-r--r--chromium/content/browser/frame_host/render_widget_host_view_guest_unittest.cc19
-rw-r--r--chromium/content/browser/generic_sensor/generic_sensor_browsertest.cc (renamed from chromium/content/browser/generic_sensor_browsertest.cc)142
-rw-r--r--chromium/content/browser/generic_sensor/sensor_provider_proxy_impl.cc15
-rw-r--r--chromium/content/browser/geolocation/geolocation_service_impl.cc2
-rw-r--r--chromium/content/browser/geolocation/geolocation_service_impl.h2
-rw-r--r--chromium/content/browser/geolocation/geolocation_service_impl_unittest.cc8
-rw-r--r--chromium/content/browser/gpu/browser_gpu_channel_host_factory.cc2
-rw-r--r--chromium/content/browser/gpu/browser_gpu_memory_buffer_manager.cc59
-rw-r--r--chromium/content/browser/gpu/browser_gpu_memory_buffer_manager.h25
-rw-r--r--chromium/content/browser/gpu/compositor_util.cc69
-rw-r--r--chromium/content/browser/gpu/gpu_client.cc40
-rw-r--r--chromium/content/browser/gpu/gpu_client.h7
-rw-r--r--chromium/content/browser/gpu/gpu_data_manager_impl.cc33
-rw-r--r--chromium/content/browser/gpu/gpu_data_manager_impl.h18
-rw-r--r--chromium/content/browser/gpu/gpu_data_manager_impl_private.cc114
-rw-r--r--chromium/content/browser/gpu/gpu_data_manager_impl_private.h14
-rw-r--r--chromium/content/browser/gpu/gpu_feature_checker_impl.cc2
-rw-r--r--chromium/content/browser/gpu/gpu_internals_ui.cc28
-rw-r--r--chromium/content/browser/gpu/gpu_ipc_browsertests.cc58
-rw-r--r--chromium/content/browser/gpu/gpu_process_host.cc144
-rw-r--r--chromium/content/browser/gpu/gpu_process_host.h23
-rw-r--r--chromium/content/browser/gpu/in_process_gpu_thread_browsertests.cc1
-rw-r--r--chromium/content/browser/histogram_internals_url_loader.cc6
-rw-r--r--chromium/content/browser/histogram_synchronizer.cc6
-rw-r--r--chromium/content/browser/host_zoom_level_context.cc2
-rw-r--r--chromium/content/browser/host_zoom_map_impl_unittest.cc13
-rw-r--r--chromium/content/browser/host_zoom_map_observer.cc2
-rw-r--r--chromium/content/browser/hyphenation/DEPS2
-rw-r--r--chromium/content/browser/hyphenation/hyphenation_impl.cc1
-rw-r--r--chromium/content/browser/hyphenation/hyphenation_impl.h2
-rw-r--r--chromium/content/browser/image_capture/image_capture_impl.cc7
-rw-r--r--chromium/content/browser/image_capture/image_capture_impl.h2
-rw-r--r--chromium/content/browser/indexed_db/cursor_impl.cc1
-rw-r--r--chromium/content/browser/indexed_db/database_impl.cc10
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_active_blob_registry_unittest.cc33
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_backing_store.cc9
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_backing_store_unittest.cc3
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_browsertest.cc2
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_callbacks.cc2
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_callbacks.h1
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_class_factory.h2
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_cleanup_on_io_error_unittest.cc1
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_context_impl.cc3
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_cursor.cc2
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_cursor.h2
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_data_format_version.cc2
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_data_loss_info.h2
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_database.cc3
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_database.h2
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_database_unittest.cc1
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_dispatcher_host.cc1
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_dispatcher_host_unittest.cc20
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_factory_impl.cc3
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_factory_unittest.cc5
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_index_writer.cc1
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_internals_ui.cc17
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_leveldb_coding.cc1
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_metadata_coding.cc2
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_observer.h2
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_quota_client.cc2
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_quota_client.h2
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_quota_client_unittest.cc1
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_tombstone_sweeper.h4
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_tombstone_sweeper_unittest.cc3
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_transaction.cc3
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_transaction.h2
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_transaction_coordinator.cc2
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_transaction_unittest.cc3
-rw-r--r--chromium/content/browser/indexed_db/indexed_db_unittest.cc1
-rw-r--r--chromium/content/browser/indexed_db/leveldb/leveldb_database.cc24
-rw-r--r--chromium/content/browser/indexed_db/leveldb/leveldb_database.h8
-rw-r--r--chromium/content/browser/indexed_db/leveldb/leveldb_transaction.cc4
-rw-r--r--chromium/content/browser/indexed_db/leveldb/leveldb_transaction_unittest.cc1
-rw-r--r--chromium/content/browser/indexed_db/list_set_unittest.cc1
-rw-r--r--chromium/content/browser/indexed_db/mock_browsertest_indexed_db_class_factory.h2
-rw-r--r--chromium/content/browser/installedapp/installed_app_provider_impl_default.h4
-rw-r--r--chromium/content/browser/isolated_origin_browsertest.cc50
-rw-r--r--chromium/content/browser/keyboard_lock/keyboard_lock_service_impl.cc64
-rw-r--r--chromium/content/browser/keyboard_lock/keyboard_lock_service_impl.h10
-rw-r--r--chromium/content/browser/keyboard_lock_browsertest.cc605
-rw-r--r--chromium/content/browser/leveldb_wrapper_impl.cc48
-rw-r--r--chromium/content/browser/leveldb_wrapper_impl.h20
-rw-r--r--chromium/content/browser/leveldb_wrapper_impl_unittest.cc4
-rw-r--r--chromium/content/browser/linux_ipc_browsertest.cc12
-rw-r--r--chromium/content/browser/loader/OWNERS1
-rw-r--r--chromium/content/browser/loader/cors_file_origin_browsertest.cc211
-rw-r--r--chromium/content/browser/loader/cross_origin_read_blocking_explainer.md719
-rw-r--r--chromium/content/browser/loader/cross_site_document_blocking_browsertest.cc140
-rw-r--r--chromium/content/browser/loader/cross_site_document_resource_handler.cc335
-rw-r--r--chromium/content/browser/loader/cross_site_document_resource_handler.h28
-rw-r--r--chromium/content/browser/loader/cross_site_document_resource_handler_unittest.cc314
-rw-r--r--chromium/content/browser/loader/data_pipe_to_source_stream.cc4
-rw-r--r--chromium/content/browser/loader/detachable_resource_handler.cc1
-rw-r--r--chromium/content/browser/loader/detachable_resource_handler_unittest.cc1
-rw-r--r--chromium/content/browser/loader/downloaded_temp_file_impl.cc1
-rw-r--r--chromium/content/browser/loader/intercepting_resource_handler.cc1
-rw-r--r--chromium/content/browser/loader/intercepting_resource_handler_unittest.cc1
-rw-r--r--chromium/content/browser/loader/loader_delegate.h15
-rw-r--r--chromium/content/browser/loader/merkle_integrity_source_stream.cc227
-rw-r--r--chromium/content/browser/loader/merkle_integrity_source_stream.h55
-rw-r--r--chromium/content/browser/loader/merkle_integrity_source_stream_unittest.cc337
-rw-r--r--chromium/content/browser/loader/mime_sniffing_resource_handler.cc4
-rw-r--r--chromium/content/browser/loader/mime_sniffing_resource_handler.h2
-rw-r--r--chromium/content/browser/loader/mime_sniffing_resource_handler_unittest.cc3
-rw-r--r--chromium/content/browser/loader/mock_resource_loader.cc1
-rw-r--r--chromium/content/browser/loader/mojo_async_resource_handler.cc21
-rw-r--r--chromium/content/browser/loader/mojo_async_resource_handler_unittest.cc18
-rw-r--r--chromium/content/browser/loader/navigation_loader_interceptor.cc (renamed from chromium/content/browser/loader/url_loader_request_handler.cc)6
-rw-r--r--chromium/content/browser/loader/navigation_loader_interceptor.h (renamed from chromium/content/browser/loader/url_loader_request_handler.h)19
-rw-r--r--chromium/content/browser/loader/navigation_resource_handler.cc9
-rw-r--r--chromium/content/browser/loader/navigation_url_loader.cc8
-rw-r--r--chromium/content/browser/loader/navigation_url_loader_delegate.h1
-rw-r--r--chromium/content/browser/loader/navigation_url_loader_impl.cc4
-rw-r--r--chromium/content/browser/loader/navigation_url_loader_impl.h1
-rw-r--r--chromium/content/browser/loader/navigation_url_loader_impl_core.cc10
-rw-r--r--chromium/content/browser/loader/navigation_url_loader_impl_core.h1
-rw-r--r--chromium/content/browser/loader/navigation_url_loader_network_service.cc534
-rw-r--r--chromium/content/browser/loader/navigation_url_loader_network_service.h8
-rw-r--r--chromium/content/browser/loader/navigation_url_loader_network_service_unittest.cc39
-rw-r--r--chromium/content/browser/loader/navigation_url_loader_unittest.cc10
-rw-r--r--chromium/content/browser/loader/prefetch_browsertest.cc5
-rw-r--r--chromium/content/browser/loader/prefetch_url_loader.cc18
-rw-r--r--chromium/content/browser/loader/prefetch_url_loader.h26
-rw-r--r--chromium/content/browser/loader/prefetch_url_loader_service.cc31
-rw-r--r--chromium/content/browser/loader/prefetch_url_loader_service.h10
-rw-r--r--chromium/content/browser/loader/redirect_to_file_resource_handler_unittest.cc1
-rw-r--r--chromium/content/browser/loader/resource_dispatcher_host_browsertest.cc22
-rw-r--r--chromium/content/browser/loader/resource_dispatcher_host_impl.cc243
-rw-r--r--chromium/content/browser/loader/resource_dispatcher_host_impl.h80
-rw-r--r--chromium/content/browser/loader/resource_dispatcher_host_unittest.cc127
-rw-r--r--chromium/content/browser/loader/resource_hints_impl.cc1
-rw-r--r--chromium/content/browser/loader/resource_loader.cc31
-rw-r--r--chromium/content/browser/loader/resource_loader.h4
-rw-r--r--chromium/content/browser/loader/resource_loader_delegate.h5
-rw-r--r--chromium/content/browser/loader/resource_loader_unittest.cc4
-rw-r--r--chromium/content/browser/loader/resource_message_filter.cc6
-rw-r--r--chromium/content/browser/loader/resource_request_info_impl.cc7
-rw-r--r--chromium/content/browser/loader/resource_request_info_impl.h8
-rw-r--r--chromium/content/browser/loader/resource_requester_info.cc26
-rw-r--r--chromium/content/browser/loader/resource_scheduler_browsertest.cc1
-rw-r--r--chromium/content/browser/loader/source_stream_to_data_pipe.cc3
-rw-r--r--chromium/content/browser/loader/temporary_file_stream.cc4
-rw-r--r--chromium/content/browser/loader/test_resource_handler.cc1
-rw-r--r--chromium/content/browser/loader/upload_data_stream_builder.cc2
-rw-r--r--chromium/content/browser/loader/url_loader_factory_impl.cc1
-rw-r--r--chromium/content/browser/loader/url_loader_factory_impl_unittest.cc10
-rw-r--r--chromium/content/browser/loader_delegate_impl.cc6
-rw-r--r--chromium/content/browser/loader_delegate_impl.h13
-rw-r--r--chromium/content/browser/locks/lock_manager.cc3
-rw-r--r--chromium/content/browser/locks/lock_manager.h2
-rw-r--r--chromium/content/browser/mach_broker_mac.h18
-rw-r--r--chromium/content/browser/mach_broker_mac.mm31
-rw-r--r--chromium/content/browser/manifest/manifest_browsertest.cc9
-rw-r--r--chromium/content/browser/manifest/manifest_icon_downloader.cc8
-rw-r--r--chromium/content/browser/manifest/manifest_icon_selector.cc2
-rw-r--r--chromium/content/browser/manifest/manifest_manager_host.cc13
-rw-r--r--chromium/content/browser/manifest/manifest_manager_host.h6
-rw-r--r--chromium/content/browser/media/android/browser_media_player_manager.cc12
-rw-r--r--chromium/content/browser/media/android/browser_surface_view_manager.cc11
-rw-r--r--chromium/content/browser/media/android/media_resource_getter_impl.cc253
-rw-r--r--chromium/content/browser/media/android/media_resource_getter_impl.h12
-rw-r--r--chromium/content/browser/media/audible_metrics.cc2
-rw-r--r--chromium/content/browser/media/audible_metrics.h4
-rw-r--r--chromium/content/browser/media/audio_stream_monitor.h2
-rw-r--r--chromium/content/browser/media/audio_stream_monitor_unittest.cc2
-rw-r--r--chromium/content/browser/media/capture/audio_mirroring_manager.cc54
-rw-r--r--chromium/content/browser/media/capture/audio_mirroring_manager.h25
-rw-r--r--chromium/content/browser/media/capture/audio_mirroring_manager_unittest.cc9
-rw-r--r--chromium/content/browser/media/capture/aura_window_capture_machine.cc2
-rw-r--r--chromium/content/browser/media/capture/cursor_renderer.cc1
-rw-r--r--chromium/content/browser/media/capture/cursor_renderer_aura.cc1
-rw-r--r--chromium/content/browser/media/capture/cursor_renderer_mac.mm1
-rw-r--r--chromium/content/browser/media/capture/cursor_renderer_mac_unittest.mm1
-rw-r--r--chromium/content/browser/media/capture/desktop_capture_device.cc37
-rw-r--r--chromium/content/browser/media/capture/desktop_capture_device.h2
-rw-r--r--chromium/content/browser/media/capture/desktop_capture_device_unittest.cc2
-rw-r--r--chromium/content/browser/media/capture/fake_webcontent_capture_machine.cc1
-rw-r--r--chromium/content/browser/media/capture/frame_sink_video_capture_device.cc8
-rw-r--r--chromium/content/browser/media/capture/frame_sink_video_capture_device_unittest.cc5
-rw-r--r--chromium/content/browser/media/capture/screen_capture_device_android.cc1
-rw-r--r--chromium/content/browser/media/capture/screen_capture_device_android_unittest.cc1
-rw-r--r--chromium/content/browser/media/capture/web_contents_video_capture_device_browsertest.cc4
-rw-r--r--chromium/content/browser/media/cdm_file_impl.cc14
-rw-r--r--chromium/content/browser/media/encrypted_media_browsertest.cc58
-rw-r--r--chromium/content/browser/media/key_system_support_impl.cc25
-rw-r--r--chromium/content/browser/media/media_browsertest.cc2
-rw-r--r--chromium/content/browser/media/media_canplaytype_browsertest.cc2
-rw-r--r--chromium/content/browser/media/media_color_browsertest.cc2
-rw-r--r--chromium/content/browser/media/media_devices_permission_checker.cc6
-rw-r--r--chromium/content/browser/media/media_devices_permission_checker_unittest.cc4
-rw-r--r--chromium/content/browser/media/media_interface_proxy.cc44
-rw-r--r--chromium/content/browser/media/media_interface_proxy.h10
-rw-r--r--chromium/content/browser/media/media_internals.cc9
-rw-r--r--chromium/content/browser/media/media_internals_handler.cc7
-rw-r--r--chromium/content/browser/media/media_internals_ui.cc1
-rw-r--r--chromium/content/browser/media/media_internals_unittest.cc2
-rw-r--r--chromium/content/browser/media/media_redirect_browsertest.cc2
-rw-r--r--chromium/content/browser/media/media_source_browsertest.cc2
-rw-r--r--chromium/content/browser/media/media_web_contents_observer.cc64
-rw-r--r--chromium/content/browser/media/media_web_contents_observer.h17
-rw-r--r--chromium/content/browser/media/midi_host.cc1
-rw-r--r--chromium/content/browser/media/session/audio_focus_manager.cc1
-rw-r--r--chromium/content/browser/media/session/media_session_impl.cc20
-rw-r--r--chromium/content/browser/media/session/media_session_impl.h5
-rw-r--r--chromium/content/browser/media/session/media_session_impl_browsertest.cc18
-rw-r--r--chromium/content/browser/media/session/media_session_impl_service_routing_unittest.cc3
-rw-r--r--chromium/content/browser/media/session/media_session_impl_uma_unittest.cc2
-rw-r--r--chromium/content/browser/media/session/media_session_service_impl.h2
-rw-r--r--chromium/content/browser/media/session/media_session_uma_helper.cc3
-rw-r--r--chromium/content/browser/media/session/media_session_uma_helper.h4
-rw-r--r--chromium/content/browser/media/url_provision_fetcher.cc1
-rw-r--r--chromium/content/browser/memory/memory_coordinator_impl.cc31
-rw-r--r--chromium/content/browser/memory/memory_coordinator_impl.h7
-rw-r--r--chromium/content/browser/memory/memory_coordinator_impl_browsertest.cc17
-rw-r--r--chromium/content/browser/memory/memory_coordinator_impl_unittest.cc19
-rw-r--r--chromium/content/browser/memory/memory_monitor_chromeos.cc1
-rw-r--r--chromium/content/browser/memory/memory_monitor_linux.cc1
-rw-r--r--chromium/content/browser/message_port_provider.cc2
-rw-r--r--chromium/content/browser/mime_registry_impl.cc1
-rw-r--r--chromium/content/browser/mime_registry_impl.h2
-rw-r--r--chromium/content/browser/mojo_sandbox_browsertest.cc9
-rw-r--r--chromium/content/browser/net/accept_header_browsertest.cc4
-rw-r--r--chromium/content/browser/net/network_quality_observer_impl.cc1
-rw-r--r--chromium/content/browser/net/network_quality_observer_impl_unittest.cc7
-rw-r--r--chromium/content/browser/net/quota_policy_cookie_store.cc23
-rw-r--r--chromium/content/browser/net/reporting_service_proxy.cc7
-rw-r--r--chromium/content/browser/net/reporting_service_proxy.h2
-rw-r--r--chromium/content/browser/network_service_client.cc79
-rw-r--r--chromium/content/browser/network_service_client.h10
-rw-r--r--chromium/content/browser/network_service_restart_browsertest.cc219
-rw-r--r--chromium/content/browser/notifications/DEPS2
-rw-r--r--chromium/content/browser/notifications/OWNERS2
-rw-r--r--chromium/content/browser/notifications/blink_notification_service_impl.cc88
-rw-r--r--chromium/content/browser/notifications/blink_notification_service_impl.h24
-rw-r--r--chromium/content/browser/notifications/blink_notification_service_impl_unittest.cc215
-rw-r--r--chromium/content/browser/notifications/notification_database.cc2
-rw-r--r--chromium/content/browser/notifications/notification_database_data_unittest.cc2
-rw-r--r--chromium/content/browser/notifications/notification_event_dispatcher_impl.h2
-rw-r--r--chromium/content/browser/notifications/notification_event_dispatcher_impl_unittest.cc2
-rw-r--r--chromium/content/browser/notifications/notification_message_filter.cc2
-rw-r--r--chromium/content/browser/notifications/notification_message_filter.h2
-rw-r--r--chromium/content/browser/notifications/platform_notification_context_impl.cc4
-rw-r--r--chromium/content/browser/notifications/platform_notification_context_impl.h2
-rw-r--r--chromium/content/browser/notifications/platform_notification_context_unittest.cc12
-rw-r--r--chromium/content/browser/oop_browsertest.cc1
-rw-r--r--chromium/content/browser/origin_manifest/origin_manifest_parser.h2
-rw-r--r--chromium/content/browser/payments/OWNERS1
-rw-r--r--chromium/content/browser/payments/payment_app.proto2
-rw-r--r--chromium/content/browser/payments/payment_app_browsertest.cc4
-rw-r--r--chromium/content/browser/payments/payment_app_content_unittest_base.cc7
-rw-r--r--chromium/content/browser/payments/payment_app_content_unittest_base.h2
-rw-r--r--chromium/content/browser/payments/payment_app_context_impl.h2
-rw-r--r--chromium/content/browser/payments/payment_app_database.cc179
-rw-r--r--chromium/content/browser/payments/payment_app_database.h39
-rw-r--r--chromium/content/browser/payments/payment_app_info_fetcher.cc6
-rw-r--r--chromium/content/browser/payments/payment_app_installer.cc40
-rw-r--r--chromium/content/browser/payments/payment_app_installer.h6
-rw-r--r--chromium/content/browser/payments/payment_app_provider_impl.cc161
-rw-r--r--chromium/content/browser/payments/payment_app_provider_impl.h17
-rw-r--r--chromium/content/browser/payments/payment_app_provider_impl_unittest.cc31
-rw-r--r--chromium/content/browser/payments/payment_instrument_icon_fetcher.h2
-rw-r--r--chromium/content/browser/payments/payment_manager.cc10
-rw-r--r--chromium/content/browser/payments/payment_manager.h3
-rw-r--r--chromium/content/browser/payments/payment_manager_unittest.cc17
-rw-r--r--chromium/content/browser/permissions/permission_service_context.h2
-rw-r--r--chromium/content/browser/permissions/permission_service_impl.cc12
-rw-r--r--chromium/content/browser/permissions/permission_service_impl.h2
-rw-r--r--chromium/content/browser/picture_in_picture/OWNERS4
-rw-r--r--chromium/content/browser/picture_in_picture/overlay_surface_embedder.cc40
-rw-r--r--chromium/content/browser/picture_in_picture/overlay_surface_embedder.h41
-rw-r--r--chromium/content/browser/picture_in_picture/picture_in_picture_window_controller_impl.cc106
-rw-r--r--chromium/content/browser/picture_in_picture/picture_in_picture_window_controller_impl.h62
-rw-r--r--chromium/content/browser/plugin_private_storage_helper.cc14
-rw-r--r--chromium/content/browser/plugin_private_storage_helper.h2
-rw-r--r--chromium/content/browser/plugin_service_impl.cc44
-rw-r--r--chromium/content/browser/plugin_service_impl.h24
-rw-r--r--chromium/content/browser/plugin_service_impl_browsertest.cc174
-rw-r--r--chromium/content/browser/pointer_lock_browsertest.cc105
-rw-r--r--chromium/content/browser/posix_file_descriptor_info_impl.cc1
-rw-r--r--chromium/content/browser/power_monitor_browsertest.cc28
-rw-r--r--chromium/content/browser/ppapi_plugin_process_host.cc45
-rw-r--r--chromium/content/browser/ppapi_plugin_process_host.h19
-rw-r--r--chromium/content/browser/presentation/presentation_service_impl.cc11
-rw-r--r--chromium/content/browser/presentation/presentation_service_impl.h6
-rw-r--r--chromium/content/browser/presentation/presentation_service_impl_unittest.cc5
-rw-r--r--chromium/content/browser/push_messaging/OWNERS4
-rw-r--r--chromium/content/browser/push_messaging/push_messaging_manager.cc34
-rw-r--r--chromium/content/browser/quota_dispatcher_host.cc23
-rw-r--r--chromium/content/browser/quota_dispatcher_host.h2
-rw-r--r--chromium/content/browser/renderer_host/DEPS6
-rw-r--r--chromium/content/browser/renderer_host/browser_compositor_view_mac.h30
-rw-r--r--chromium/content/browser/renderer_host/browser_compositor_view_mac.mm89
-rw-r--r--chromium/content/browser/renderer_host/clipboard_host_impl.cc1
-rw-r--r--chromium/content/browser/renderer_host/clipboard_host_impl.h2
-rw-r--r--chromium/content/browser/renderer_host/compositor_impl_android.cc73
-rw-r--r--chromium/content/browser/renderer_host/compositor_impl_android.h25
-rw-r--r--chromium/content/browser/renderer_host/compositor_impl_android_browsertest.cc170
-rw-r--r--chromium/content/browser/renderer_host/compositor_resize_lock_unittest.cc1
-rw-r--r--chromium/content/browser/renderer_host/cursor_manager.cc30
-rw-r--r--chromium/content/browser/renderer_host/cursor_manager.h20
-rw-r--r--chromium/content/browser/renderer_host/cursor_manager_unittest.cc8
-rw-r--r--chromium/content/browser/renderer_host/delegated_frame_host.cc123
-rw-r--r--chromium/content/browser/renderer_host/delegated_frame_host.h14
-rw-r--r--chromium/content/browser/renderer_host/direct_manipulation_browsertest.cc329
-rw-r--r--chromium/content/browser/renderer_host/display_util.cc14
-rw-r--r--chromium/content/browser/renderer_host/frame_connector_delegate.cc28
-rw-r--r--chromium/content/browser/renderer_host/frame_connector_delegate.h26
-rw-r--r--chromium/content/browser/renderer_host/frame_token_message_queue.cc49
-rw-r--r--chromium/content/browser/renderer_host/frame_token_message_queue.h26
-rw-r--r--chromium/content/browser/renderer_host/frame_token_message_queue_unittest.cc665
-rw-r--r--chromium/content/browser/renderer_host/input/compositor_event_ack_browsertest.cc (renamed from chromium/content/browser/renderer_host/input/non_blocking_event_browsertest.cc)124
-rw-r--r--chromium/content/browser/renderer_host/input/fling_browsertest.cc162
-rw-r--r--chromium/content/browser/renderer_host/input/fling_controller.cc250
-rw-r--r--chromium/content/browser/renderer_host/input/fling_controller.h42
-rw-r--r--chromium/content/browser/renderer_host/input/fling_controller_unittest.cc276
-rw-r--r--chromium/content/browser/renderer_host/input/gesture_event_queue.cc27
-rw-r--r--chromium/content/browser/renderer_host/input/gesture_event_queue.h10
-rw-r--r--chromium/content/browser/renderer_host/input/gesture_event_queue_unittest.cc169
-rw-r--r--chromium/content/browser/renderer_host/input/input_disposition_handler.h2
-rw-r--r--chromium/content/browser/renderer_host/input/input_router.h5
-rw-r--r--chromium/content/browser/renderer_host/input/input_router_client.h5
-rw-r--r--chromium/content/browser/renderer_host/input/input_router_impl.cc43
-rw-r--r--chromium/content/browser/renderer_host/input/input_router_impl.h11
-rw-r--r--chromium/content/browser/renderer_host/input/input_router_impl_unittest.cc147
-rw-r--r--chromium/content/browser/renderer_host/input/interaction_mq_dynamic_browsertest.cc7
-rw-r--r--chromium/content/browser/renderer_host/input/legacy_input_router_impl.cc38
-rw-r--r--chromium/content/browser/renderer_host/input/legacy_input_router_impl.h12
-rw-r--r--chromium/content/browser/renderer_host/input/legacy_input_router_impl_perftest.cc7
-rw-r--r--chromium/content/browser/renderer_host/input/legacy_input_router_impl_unittest.cc148
-rw-r--r--chromium/content/browser/renderer_host/input/legacy_ipc_widget_input_handler.cc22
-rw-r--r--chromium/content/browser/renderer_host/input/main_thread_event_queue_browsertest.cc2
-rw-r--r--chromium/content/browser/renderer_host/input/mock_input_router_client.cc2
-rw-r--r--chromium/content/browser/renderer_host/input/mock_input_router_client.h1
-rw-r--r--chromium/content/browser/renderer_host/input/motion_event_web.h2
-rw-r--r--chromium/content/browser/renderer_host/input/mouse_wheel_event_queue.cc21
-rw-r--r--chromium/content/browser/renderer_host/input/mouse_wheel_event_queue.h2
-rw-r--r--chromium/content/browser/renderer_host/input/mouse_wheel_event_queue_unittest.cc30
-rw-r--r--chromium/content/browser/renderer_host/input/mouse_wheel_phase_handler.cc41
-rw-r--r--chromium/content/browser/renderer_host/input/mouse_wheel_phase_handler.h11
-rw-r--r--chromium/content/browser/renderer_host/input/mouse_wheel_rails_filter_mac.h2
-rw-r--r--chromium/content/browser/renderer_host/input/passthrough_touch_event_queue.cc1
-rw-r--r--chromium/content/browser/renderer_host/input/passthrough_touch_event_queue.h2
-rw-r--r--chromium/content/browser/renderer_host/input/passthrough_touch_event_queue_unittest.cc4
-rw-r--r--chromium/content/browser/renderer_host/input/scroll_latency_browsertest.cc1
-rw-r--r--chromium/content/browser/renderer_host/input/synthetic_gesture_controller_unittest.cc2
-rw-r--r--chromium/content/browser/renderer_host/input/synthetic_gesture_target_android.cc8
-rw-r--r--chromium/content/browser/renderer_host/input/synthetic_gesture_target_base.cc2
-rw-r--r--chromium/content/browser/renderer_host/input/synthetic_gesture_target_mac.mm16
-rw-r--r--chromium/content/browser/renderer_host/input/synthetic_pointer_action.cc2
-rw-r--r--chromium/content/browser/renderer_host/input/synthetic_pointer_action_unittest.cc4
-rw-r--r--chromium/content/browser/renderer_host/input/synthetic_pointer_driver.cc1
-rw-r--r--chromium/content/browser/renderer_host/input/synthetic_smooth_move_gesture.h2
-rw-r--r--chromium/content/browser/renderer_host/input/synthetic_tap_gesture.cc2
-rw-r--r--chromium/content/browser/renderer_host/input/synthetic_touchpad_pinch_gesture.h2
-rw-r--r--chromium/content/browser/renderer_host/input/synthetic_touchscreen_pinch_gesture.h2
-rw-r--r--chromium/content/browser/renderer_host/input/timeout_monitor.cc5
-rw-r--r--chromium/content/browser/renderer_host/input/timeout_monitor.h2
-rw-r--r--chromium/content/browser/renderer_host/input/touch_action_browsertest.cc25
-rw-r--r--chromium/content/browser/renderer_host/input/touch_action_filter.cc35
-rw-r--r--chromium/content/browser/renderer_host/input/touch_action_filter.h7
-rw-r--r--chromium/content/browser/renderer_host/input/touch_action_filter_unittest.cc2
-rw-r--r--chromium/content/browser/renderer_host/input/touch_emulator.cc24
-rw-r--r--chromium/content/browser/renderer_host/input/touch_emulator.h4
-rw-r--r--chromium/content/browser/renderer_host/input/touch_emulator_client.h4
-rw-r--r--chromium/content/browser/renderer_host/input/touch_emulator_unittest.cc4
-rw-r--r--chromium/content/browser/renderer_host/input/touch_input_browsertest.cc2
-rw-r--r--chromium/content/browser/renderer_host/input/touch_selection_controller_client_aura.cc21
-rw-r--r--chromium/content/browser/renderer_host/input/touch_selection_controller_client_aura_browsertest.cc5
-rw-r--r--chromium/content/browser/renderer_host/input/touch_selection_controller_client_child_frame.cc14
-rw-r--r--chromium/content/browser/renderer_host/input/touch_selection_controller_client_manager_android.cc6
-rw-r--r--chromium/content/browser/renderer_host/input/touch_timeout_handler.cc1
-rw-r--r--chromium/content/browser/renderer_host/input/touchpad_tap_suppression_controller.h2
-rw-r--r--chromium/content/browser/renderer_host/input/web_input_event_builders_android.cc11
-rw-r--r--chromium/content/browser/renderer_host/input/web_input_event_builders_android.h12
-rw-r--r--chromium/content/browser/renderer_host/input/web_input_event_builders_android_unittest.cc2
-rw-r--r--chromium/content/browser/renderer_host/input/web_input_event_builders_mac.h8
-rw-r--r--chromium/content/browser/renderer_host/input/web_input_event_builders_mac.mm11
-rw-r--r--chromium/content/browser/renderer_host/input/web_input_event_util_unittest.cc10
-rw-r--r--chromium/content/browser/renderer_host/input/wheel_scroll_latching_browsertest.cc10
-rw-r--r--chromium/content/browser/renderer_host/legacy_render_widget_host_win.cc111
-rw-r--r--chromium/content/browser/renderer_host/legacy_render_widget_host_win.h20
-rw-r--r--chromium/content/browser/renderer_host/media/audio_input_delegate_impl_unittest.cc162
-rw-r--r--chromium/content/browser/renderer_host/media/audio_input_renderer_host.cc1
-rw-r--r--chromium/content/browser/renderer_host/media/audio_input_renderer_host_unittest.cc1
-rw-r--r--chromium/content/browser/renderer_host/media/audio_output_authorization_handler.cc1
-rw-r--r--chromium/content/browser/renderer_host/media/audio_output_authorization_handler_unittest.cc2
-rw-r--r--chromium/content/browser/renderer_host/media/audio_output_delegate_impl.cc35
-rw-r--r--chromium/content/browser/renderer_host/media/audio_output_delegate_impl.h10
-rw-r--r--chromium/content/browser/renderer_host/media/audio_output_delegate_impl_unittest.cc107
-rw-r--r--chromium/content/browser/renderer_host/media/audio_renderer_host.cc10
-rw-r--r--chromium/content/browser/renderer_host/media/audio_renderer_host.h3
-rw-r--r--chromium/content/browser/renderer_host/media/audio_renderer_host_unittest.cc8
-rw-r--r--chromium/content/browser/renderer_host/media/fake_video_capture_device_launcher.cc2
-rw-r--r--chromium/content/browser/renderer_host/media/in_process_video_capture_provider.h1
-rw-r--r--chromium/content/browser/renderer_host/media/media_devices_dispatcher_host.cc83
-rw-r--r--chromium/content/browser/renderer_host/media/media_devices_dispatcher_host.h12
-rw-r--r--chromium/content/browser/renderer_host/media/media_devices_dispatcher_host_unittest.cc9
-rw-r--r--chromium/content/browser/renderer_host/media/media_devices_manager.cc199
-rw-r--r--chromium/content/browser/renderer_host/media/media_devices_manager.h22
-rw-r--r--chromium/content/browser/renderer_host/media/media_devices_manager_unittest.cc29
-rw-r--r--chromium/content/browser/renderer_host/media/media_stream_dispatcher_host_unittest.cc2
-rw-r--r--chromium/content/browser/renderer_host/media/media_stream_manager.cc27
-rw-r--r--chromium/content/browser/renderer_host/media/media_stream_manager_unittest.cc1
-rw-r--r--chromium/content/browser/renderer_host/media/media_stream_track_metrics_host.cc27
-rw-r--r--chromium/content/browser/renderer_host/media/media_stream_track_metrics_host.h17
-rw-r--r--chromium/content/browser/renderer_host/media/media_stream_ui_proxy.cc2
-rw-r--r--chromium/content/browser/renderer_host/media/media_stream_ui_proxy_unittest.cc34
-rw-r--r--chromium/content/browser/renderer_host/media/peer_connection_tracker_host.cc27
-rw-r--r--chromium/content/browser/renderer_host/media/peer_connection_tracker_host.h1
-rw-r--r--chromium/content/browser/renderer_host/media/render_frame_audio_input_stream_factory_unittest.cc14
-rw-r--r--chromium/content/browser/renderer_host/media/renderer_audio_output_stream_factory_context_impl.cc9
-rw-r--r--chromium/content/browser/renderer_host/media/video_capture_browsertest.cc3
-rw-r--r--chromium/content/browser/renderer_host/media/video_capture_buffer_pool_unittest.cc1
-rw-r--r--chromium/content/browser/renderer_host/media/video_capture_controller.cc5
-rw-r--r--chromium/content/browser/renderer_host/media/video_capture_controller_event_handler.h2
-rw-r--r--chromium/content/browser/renderer_host/media/video_capture_controller_unittest.cc3
-rw-r--r--chromium/content/browser/renderer_host/media/video_capture_gpu_jpeg_decoder.cc4
-rw-r--r--chromium/content/browser/renderer_host/media/video_capture_host.cc2
-rw-r--r--chromium/content/browser/renderer_host/media/video_capture_host.h2
-rw-r--r--chromium/content/browser/renderer_host/media/video_capture_manager.cc1
-rw-r--r--chromium/content/browser/renderer_host/media/video_capture_manager_unittest.cc1
-rw-r--r--chromium/content/browser/renderer_host/media/video_capture_provider.h1
-rw-r--r--chromium/content/browser/renderer_host/media/video_capture_unittest.cc5
-rw-r--r--chromium/content/browser/renderer_host/offscreen_canvas_provider_impl.h2
-rw-r--r--chromium/content/browser/renderer_host/offscreen_canvas_provider_impl_unittest.cc6
-rw-r--r--chromium/content/browser/renderer_host/offscreen_canvas_surface_impl.cc1
-rw-r--r--chromium/content/browser/renderer_host/offscreen_canvas_surface_impl.h2
-rw-r--r--chromium/content/browser/renderer_host/overscroll_configuration.cc87
-rw-r--r--chromium/content/browser/renderer_host/overscroll_controller.cc83
-rw-r--r--chromium/content/browser/renderer_host/overscroll_controller.h20
-rw-r--r--chromium/content/browser/renderer_host/overscroll_controller_delegate.h12
-rw-r--r--chromium/content/browser/renderer_host/overscroll_controller_unittest.cc241
-rw-r--r--chromium/content/browser/renderer_host/p2p/socket_dispatcher_host.cc16
-rw-r--r--chromium/content/browser/renderer_host/p2p/socket_host_tcp.cc3
-rw-r--r--chromium/content/browser/renderer_host/p2p/socket_host_tcp_server_unittest.cc2
-rw-r--r--chromium/content/browser/renderer_host/p2p/socket_host_test_utils.cc2
-rw-r--r--chromium/content/browser/renderer_host/p2p/socket_host_throttler.cc8
-rw-r--r--chromium/content/browser/renderer_host/p2p/socket_host_throttler.h4
-rw-r--r--chromium/content/browser/renderer_host/p2p/socket_host_udp.cc20
-rw-r--r--chromium/content/browser/renderer_host/p2p/socket_host_udp.h1
-rw-r--r--chromium/content/browser/renderer_host/p2p/socket_host_udp_unittest.cc20
-rw-r--r--chromium/content/browser/renderer_host/pepper/browser_ppapi_host_impl.cc1
-rw-r--r--chromium/content/browser/renderer_host/pepper/browser_ppapi_host_impl.h2
-rw-r--r--chromium/content/browser/renderer_host/pepper/content_browser_pepper_host_factory.cc1
-rw-r--r--chromium/content/browser/renderer_host/pepper/pepper_external_file_ref_backend.cc18
-rw-r--r--chromium/content/browser/renderer_host/pepper/pepper_file_io_host.cc27
-rw-r--r--chromium/content/browser/renderer_host/pepper/pepper_internal_file_ref_backend.cc6
-rw-r--r--chromium/content/browser/renderer_host/pepper/pepper_network_monitor_host.cc10
-rw-r--r--chromium/content/browser/renderer_host/pepper/pepper_network_monitor_host.h7
-rw-r--r--chromium/content/browser/renderer_host/pepper/pepper_network_proxy_host.cc2
-rw-r--r--chromium/content/browser/renderer_host/pepper/pepper_network_proxy_host.h2
-rw-r--r--chromium/content/browser/renderer_host/pepper/pepper_print_settings_manager.cc8
-rw-r--r--chromium/content/browser/renderer_host/pepper/pepper_printing_host_unittest.cc2
-rw-r--r--chromium/content/browser/renderer_host/pepper/pepper_renderer_connection.cc1
-rw-r--r--chromium/content/browser/renderer_host/pepper/pepper_socket_utils.cc1
-rw-r--r--chromium/content/browser/renderer_host/pepper/pepper_udp_socket_message_filter.cc6
-rw-r--r--chromium/content/browser/renderer_host/pepper/pepper_vpn_provider_message_filter_chromeos.cc1
-rw-r--r--chromium/content/browser/renderer_host/popup_window_mac.h41
-rw-r--r--chromium/content/browser/renderer_host/popup_window_mac.mm120
-rw-r--r--chromium/content/browser/renderer_host/render_frame_metadata_provider_impl.cc58
-rw-r--r--chromium/content/browser/renderer_host/render_frame_metadata_provider_impl.h33
-rw-r--r--chromium/content/browser/renderer_host/render_message_filter.cc21
-rw-r--r--chromium/content/browser/renderer_host/render_message_filter.h11
-rw-r--r--chromium/content/browser/renderer_host/render_process_host_browsertest.cc364
-rw-r--r--chromium/content/browser/renderer_host/render_process_host_impl.cc727
-rw-r--r--chromium/content/browser/renderer_host/render_process_host_impl.h143
-rw-r--r--chromium/content/browser/renderer_host/render_process_host_unittest.cc201
-rw-r--r--chromium/content/browser/renderer_host/render_view_host_delegate.h2
-rw-r--r--chromium/content/browser/renderer_host/render_view_host_delegate_view.h4
-rw-r--r--chromium/content/browser/renderer_host/render_view_host_impl.cc40
-rw-r--r--chromium/content/browser/renderer_host/render_view_host_impl.h12
-rw-r--r--chromium/content/browser/renderer_host/render_view_host_unittest.cc7
-rw-r--r--chromium/content/browser/renderer_host/render_widget_helper.h2
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_delegate.cc9
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_delegate.h29
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_impl.cc396
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_impl.h85
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_input_event_router.cc117
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_input_event_router.h2
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_input_event_router_unittest.cc114
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_ns_view_bridge.h101
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_ns_view_bridge.mm286
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_ns_view_client.h192
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_owner_delegate.h4
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_unittest.cc62
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_view_android.cc480
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_view_android.h34
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_view_aura.cc366
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_view_aura.h53
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc785
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_view_base.cc163
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_view_base.h81
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_view_base_unittest.cc2
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_view_browsertest.cc10
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_view_child_frame.cc233
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_view_child_frame.h41
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_view_child_frame_browsertest.cc6
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_view_child_frame_unittest.cc71
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_view_cocoa.h225
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_view_cocoa.mm1878
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_view_event_handler.cc81
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_view_event_handler.h32
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_view_mac.h444
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_view_mac.mm3268
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_view_mac_browsertest.mm66
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_view_mac_dictionary_helper.h50
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_view_mac_dictionary_helper.mm30
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_view_mac_editcommand_helper.h5
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_view_mac_editcommand_helper.mm20
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_view_mac_editcommand_helper_unittest.mm24
-rw-r--r--chromium/content/browser/renderer_host/render_widget_host_view_mac_unittest.mm435
-rw-r--r--chromium/content/browser/renderer_host/render_widget_targeter.cc9
-rw-r--r--chromium/content/browser/renderer_host/render_widget_targeter.h3
-rw-r--r--chromium/content/browser/renderer_host/text_input_client_mac.h48
-rw-r--r--chromium/content/browser/renderer_host/text_input_client_mac.mm73
-rw-r--r--chromium/content/browser/renderer_host/text_input_client_mac_unittest.mm32
-rw-r--r--chromium/content/browser/renderer_host/text_input_client_message_filter.h1
-rw-r--r--chromium/content/browser/renderer_host/text_input_client_message_filter.mm21
-rw-r--r--chromium/content/browser/renderer_host/ui_events_helper.cc3
-rw-r--r--chromium/content/browser/renderer_host/web_database_host_impl.cc6
-rw-r--r--chromium/content/browser/renderer_host/web_database_host_impl.h2
-rw-r--r--chromium/content/browser/renderer_host/webmenurunner_mac.mm7
-rw-r--r--chromium/content/browser/renderer_interface_binders.cc37
-rw-r--r--chromium/content/browser/resolve_proxy_msg_helper.h2
-rw-r--r--chromium/content/browser/resolve_proxy_msg_helper_unittest.cc10
-rw-r--r--chromium/content/browser/resource_context_impl.cc1
-rw-r--r--chromium/content/browser/resources/gpu/info_view.js1
-rw-r--r--chromium/content/browser/resources/media/peer_connection_update_table.js4
-rw-r--r--chromium/content/browser/sandbox_host_linux.h2
-rw-r--r--chromium/content/browser/sandbox_ipc_linux.cc8
-rw-r--r--chromium/content/browser/sandbox_parameters_mac.mm11
-rw-r--r--chromium/content/browser/screen_orientation/OWNERS2
-rw-r--r--chromium/content/browser/screen_orientation/screen_orientation_delegate_android.h2
-rw-r--r--chromium/content/browser/screen_orientation/screen_orientation_provider.cc2
-rw-r--r--chromium/content/browser/screen_orientation/screen_orientation_provider.h2
-rw-r--r--chromium/content/browser/screen_orientation/screen_orientation_provider_unittest.cc2
-rw-r--r--chromium/content/browser/security_exploit_browsertest.cc7
-rw-r--r--chromium/content/browser/service_manager/common_browser_interfaces.cc5
-rw-r--r--chromium/content/browser/service_manager/service_manager_context.cc10
-rw-r--r--chromium/content/browser/service_worker/DEPS2
-rw-r--r--chromium/content/browser/service_worker/OWNERS8
-rw-r--r--chromium/content/browser/service_worker/embedded_worker_instance.cc26
-rw-r--r--chromium/content/browser/service_worker/embedded_worker_instance.h16
-rw-r--r--chromium/content/browser/service_worker/embedded_worker_instance_unittest.cc14
-rw-r--r--chromium/content/browser/service_worker/embedded_worker_registry.cc35
-rw-r--r--chromium/content/browser/service_worker/embedded_worker_registry.h9
-rw-r--r--chromium/content/browser/service_worker/embedded_worker_test_helper.cc9
-rw-r--r--chromium/content/browser/service_worker/embedded_worker_test_helper.h6
-rw-r--r--chromium/content/browser/service_worker/payment_handler_support.h2
-rw-r--r--chromium/content/browser/service_worker/service_worker_browsertest.cc281
-rw-r--r--chromium/content/browser/service_worker/service_worker_cache_writer.cc8
-rw-r--r--chromium/content/browser/service_worker/service_worker_client_utils.cc30
-rw-r--r--chromium/content/browser/service_worker/service_worker_client_utils.h17
-rw-r--r--chromium/content/browser/service_worker/service_worker_content_settings_proxy_impl.h2
-rw-r--r--chromium/content/browser/service_worker/service_worker_context_core.cc105
-rw-r--r--chromium/content/browser/service_worker/service_worker_context_core.h54
-rw-r--r--chromium/content/browser/service_worker/service_worker_context_core_observer.h2
-rw-r--r--chromium/content/browser/service_worker/service_worker_context_request_handler.cc3
-rw-r--r--chromium/content/browser/service_worker/service_worker_context_request_handler_unittest.cc3
-rw-r--r--chromium/content/browser/service_worker/service_worker_context_unittest.cc26
-rw-r--r--chromium/content/browser/service_worker/service_worker_context_watcher.cc5
-rw-r--r--chromium/content/browser/service_worker/service_worker_context_watcher.h2
-rw-r--r--chromium/content/browser/service_worker/service_worker_context_watcher_unittest.cc6
-rw-r--r--chromium/content/browser/service_worker/service_worker_context_wrapper.cc71
-rw-r--r--chromium/content/browser/service_worker/service_worker_context_wrapper.h25
-rw-r--r--chromium/content/browser/service_worker/service_worker_controllee_request_handler.cc15
-rw-r--r--chromium/content/browser/service_worker/service_worker_controllee_request_handler.h2
-rw-r--r--chromium/content/browser/service_worker/service_worker_controllee_request_handler_unittest.cc3
-rw-r--r--chromium/content/browser/service_worker/service_worker_data_pipe_reader.cc4
-rw-r--r--chromium/content/browser/service_worker/service_worker_data_pipe_reader.h2
-rw-r--r--chromium/content/browser/service_worker/service_worker_data_pipe_reader_unittest.cc2
-rw-r--r--chromium/content/browser/service_worker/service_worker_database.cc4
-rw-r--r--chromium/content/browser/service_worker/service_worker_database.h2
-rw-r--r--chromium/content/browser/service_worker/service_worker_database_unittest.cc4
-rw-r--r--chromium/content/browser/service_worker/service_worker_dispatcher_host.cc135
-rw-r--r--chromium/content/browser/service_worker/service_worker_dispatcher_host.h38
-rw-r--r--chromium/content/browser/service_worker/service_worker_dispatcher_host_unittest.cc9
-rw-r--r--chromium/content/browser/service_worker/service_worker_fetch_dispatcher.cc6
-rw-r--r--chromium/content/browser/service_worker/service_worker_fetch_dispatcher.h4
-rw-r--r--chromium/content/browser/service_worker/service_worker_handle.cc77
-rw-r--r--chromium/content/browser/service_worker/service_worker_handle.h58
-rw-r--r--chromium/content/browser/service_worker/service_worker_handle_unittest.cc76
-rw-r--r--chromium/content/browser/service_worker/service_worker_info.cc4
-rw-r--r--chromium/content/browser/service_worker/service_worker_info.h2
-rw-r--r--chromium/content/browser/service_worker/service_worker_installed_script_loader.cc11
-rw-r--r--chromium/content/browser/service_worker/service_worker_installed_script_loader.h8
-rw-r--r--chromium/content/browser/service_worker/service_worker_installed_script_reader.cc16
-rw-r--r--chromium/content/browser/service_worker/service_worker_installed_scripts_sender.h2
-rw-r--r--chromium/content/browser/service_worker/service_worker_installed_scripts_sender_unittest.cc2
-rw-r--r--chromium/content/browser/service_worker/service_worker_internals_ui.cc52
-rw-r--r--chromium/content/browser/service_worker/service_worker_job_coordinator.cc14
-rw-r--r--chromium/content/browser/service_worker/service_worker_job_coordinator.h11
-rw-r--r--chromium/content/browser/service_worker/service_worker_job_unittest.cc116
-rw-r--r--chromium/content/browser/service_worker/service_worker_lifetime_tracker.cc2
-rw-r--r--chromium/content/browser/service_worker/service_worker_lifetime_tracker.h5
-rw-r--r--chromium/content/browser/service_worker/service_worker_metrics.cc24
-rw-r--r--chromium/content/browser/service_worker/service_worker_metrics.h3
-rw-r--r--chromium/content/browser/service_worker/service_worker_navigation_handle.h6
-rw-r--r--chromium/content/browser/service_worker/service_worker_navigation_loader.cc22
-rw-r--r--chromium/content/browser/service_worker/service_worker_navigation_loader.h28
-rw-r--r--chromium/content/browser/service_worker/service_worker_navigation_loader_unittest.cc27
-rw-r--r--chromium/content/browser/service_worker/service_worker_new_script_loader.cc92
-rw-r--r--chromium/content/browser/service_worker/service_worker_new_script_loader.h4
-rw-r--r--chromium/content/browser/service_worker/service_worker_new_script_loader_unittest.cc23
-rw-r--r--chromium/content/browser/service_worker/service_worker_process_manager.cc9
-rw-r--r--chromium/content/browser/service_worker/service_worker_process_manager_unittest.cc7
-rw-r--r--chromium/content/browser/service_worker/service_worker_provider_host.cc238
-rw-r--r--chromium/content/browser/service_worker/service_worker_provider_host.h193
-rw-r--r--chromium/content/browser/service_worker/service_worker_provider_host_unittest.cc58
-rw-r--r--chromium/content/browser/service_worker/service_worker_quota_client.h2
-rw-r--r--chromium/content/browser/service_worker/service_worker_read_from_cache_job_unittest.cc2
-rw-r--r--chromium/content/browser/service_worker/service_worker_register_job.cc26
-rw-r--r--chromium/content/browser/service_worker/service_worker_register_job.h12
-rw-r--r--chromium/content/browser/service_worker/service_worker_registration.cc6
-rw-r--r--chromium/content/browser/service_worker/service_worker_registration.h2
-rw-r--r--chromium/content/browser/service_worker/service_worker_registration_object_host.cc3
-rw-r--r--chromium/content/browser/service_worker/service_worker_registration_object_host.h2
-rw-r--r--chromium/content/browser/service_worker/service_worker_registration_status.cc2
-rw-r--r--chromium/content/browser/service_worker/service_worker_registration_status.h2
-rw-r--r--chromium/content/browser/service_worker/service_worker_registration_unittest.cc4
-rw-r--r--chromium/content/browser/service_worker/service_worker_request_handler.cc43
-rw-r--r--chromium/content/browser/service_worker/service_worker_request_handler.h14
-rw-r--r--chromium/content/browser/service_worker/service_worker_script_loader_factory.cc2
-rw-r--r--chromium/content/browser/service_worker/service_worker_storage.cc23
-rw-r--r--chromium/content/browser/service_worker/service_worker_storage_unittest.cc13
-rw-r--r--chromium/content/browser/service_worker/service_worker_test_utils.cc3
-rw-r--r--chromium/content/browser/service_worker/service_worker_test_utils.h2
-rw-r--r--chromium/content/browser/service_worker/service_worker_type_converters.h4
-rw-r--r--chromium/content/browser/service_worker/service_worker_unregister_job.cc14
-rw-r--r--chromium/content/browser/service_worker/service_worker_unregister_job.h6
-rw-r--r--chromium/content/browser/service_worker/service_worker_url_job_wrapper.h2
-rw-r--r--chromium/content/browser/service_worker/service_worker_url_request_job_unittest.cc9
-rw-r--r--chromium/content/browser/service_worker/service_worker_version.cc119
-rw-r--r--chromium/content/browser/service_worker/service_worker_version.h47
-rw-r--r--chromium/content/browser/service_worker/service_worker_version_unittest.cc87
-rw-r--r--chromium/content/browser/service_worker/service_worker_write_to_cache_job.cc39
-rw-r--r--chromium/content/browser/service_worker/service_worker_write_to_cache_job_unittest.cc2
-rw-r--r--chromium/content/browser/shared_worker/DEPS5
-rw-r--r--chromium/content/browser/shared_worker/shared_worker_connector_impl.cc2
-rw-r--r--chromium/content/browser/shared_worker/shared_worker_content_settings_proxy_impl.h2
-rw-r--r--chromium/content/browser/shared_worker/shared_worker_host.cc42
-rw-r--r--chromium/content/browser/shared_worker/shared_worker_host.h31
-rw-r--r--chromium/content/browser/shared_worker/shared_worker_instance.h6
-rw-r--r--chromium/content/browser/shared_worker/shared_worker_script_loader.cc203
-rw-r--r--chromium/content/browser/shared_worker/shared_worker_script_loader.h106
-rw-r--r--chromium/content/browser/shared_worker/shared_worker_script_loader_factory.cc69
-rw-r--r--chromium/content/browser/shared_worker/shared_worker_script_loader_factory.h59
-rw-r--r--chromium/content/browser/shared_worker/shared_worker_service_impl.cc91
-rw-r--r--chromium/content/browser/shared_worker/shared_worker_service_impl.h17
-rw-r--r--chromium/content/browser/shared_worker/shared_worker_service_impl_unittest.cc7
-rw-r--r--chromium/content/browser/shared_worker/worker_browsertest.cc2
-rw-r--r--chromium/content/browser/site_instance_impl.cc48
-rw-r--r--chromium/content/browser/site_instance_impl_unittest.cc28
-rw-r--r--chromium/content/browser/site_per_process_browsertest.cc1499
-rw-r--r--chromium/content/browser/site_per_process_hit_test_browsertest.cc599
-rw-r--r--chromium/content/browser/site_per_process_mac_browsertest.mm1
-rw-r--r--chromium/content/browser/speech/speech_recognition_browsertest.cc143
-rw-r--r--chromium/content/browser/speech/speech_recognition_dispatcher_host.cc139
-rw-r--r--chromium/content/browser/speech/speech_recognition_dispatcher_host.h19
-rw-r--r--chromium/content/browser/speech/speech_recognition_engine.cc17
-rw-r--r--chromium/content/browser/speech/speech_recognition_engine.h4
-rw-r--r--chromium/content/browser/speech/speech_recognition_manager_impl.cc248
-rw-r--r--chromium/content/browser/speech/speech_recognition_manager_impl.h21
-rw-r--r--chromium/content/browser/speech/speech_recognizer_impl.cc1
-rw-r--r--chromium/content/browser/ssl/ssl_manager.cc4
-rw-r--r--chromium/content/browser/startup_task_runner.cc2
-rw-r--r--chromium/content/browser/startup_task_runner.h2
-rw-r--r--chromium/content/browser/startup_task_runner_unittest.cc20
-rw-r--r--chromium/content/browser/storage_partition_impl.cc86
-rw-r--r--chromium/content/browser/storage_partition_impl.h9
-rw-r--r--chromium/content/browser/storage_partition_impl_map.cc21
-rw-r--r--chromium/content/browser/storage_partition_impl_map_unittest.cc8
-rw-r--r--chromium/content/browser/storage_partition_impl_unittest.cc30
-rw-r--r--chromium/content/browser/streams/OWNERS3
-rw-r--r--chromium/content/browser/streams/stream.cc10
-rw-r--r--chromium/content/browser/streams/stream_context.cc5
-rw-r--r--chromium/content/browser/streams/stream_url_request_job_unittest.cc1
-rw-r--r--chromium/content/browser/theme_helper_mac.h2
-rw-r--r--chromium/content/browser/top_document_isolation_browsertest.cc12
-rw-r--r--chromium/content/browser/tracing/background_tracing_manager_browsertest.cc6
-rw-r--r--chromium/content/browser/tracing/background_tracing_manager_impl.cc34
-rw-r--r--chromium/content/browser/tracing/background_tracing_rule.h1
-rw-r--r--chromium/content/browser/tracing/etw_tracing_agent_win.cc4
-rw-r--r--chromium/content/browser/tracing/memory_instrumentation_browsertest.cc27
-rw-r--r--chromium/content/browser/tracing/memory_tracing_browsertest.cc18
-rw-r--r--chromium/content/browser/tracing/power_tracing_agent.cc4
-rw-r--r--chromium/content/browser/tracing/tracing_controller_browsertest.cc41
-rw-r--r--chromium/content/browser/tracing/tracing_controller_impl.cc13
-rw-r--r--chromium/content/browser/tracing/tracing_controller_impl.h8
-rw-r--r--chromium/content/browser/tracing/tracing_controller_impl_data_endpoint.cc3
-rw-r--r--chromium/content/browser/tracing/tracing_ui.cc9
-rw-r--r--chromium/content/browser/url_loader_factory_getter.cc103
-rw-r--r--chromium/content/browser/url_loader_factory_getter.h40
-rw-r--r--chromium/content/browser/utility_process_host.cc (renamed from chromium/content/browser/utility_process_host_impl.cc)157
-rw-r--r--chromium/content/browser/utility_process_host.h (renamed from chromium/content/browser/utility_process_host_impl.h)85
-rw-r--r--chromium/content/browser/utility_process_host_browsertest.cc (renamed from chromium/content/browser/utility_process_host_impl_browsertest.cc)24
-rw-r--r--chromium/content/browser/utility_process_host_client.h (renamed from chromium/content/public/browser/utility_process_host_client.h)6
-rw-r--r--chromium/content/browser/utility_process_mojo_client_browsertest.cc172
-rw-r--r--chromium/content/browser/vibration_browsertest.cc2
-rw-r--r--chromium/content/browser/wake_lock/wake_lock_browsertest.cc2
-rw-r--r--chromium/content/browser/web_contents/aura/gesture_nav_simple.cc33
-rw-r--r--chromium/content/browser/web_contents/aura/gesture_nav_simple.h10
-rw-r--r--chromium/content/browser/web_contents/aura/gesture_nav_simple_unittest.cc360
-rw-r--r--chromium/content/browser/web_contents/aura/overscroll_navigation_overlay_unittest.cc6
-rw-r--r--chromium/content/browser/web_contents/aura/overscroll_window_animation.cc12
-rw-r--r--chromium/content/browser/web_contents/aura/overscroll_window_animation.h11
-rw-r--r--chromium/content/browser/web_contents/aura/overscroll_window_animation_unittest.cc34
-rw-r--r--chromium/content/browser/web_contents/aura/overscroll_window_delegate.cc6
-rw-r--r--chromium/content/browser/web_contents/aura/overscroll_window_delegate_unittest.cc6
-rw-r--r--chromium/content/browser/web_contents/web_contents_android.cc63
-rw-r--r--chromium/content/browser/web_contents/web_contents_android.h3
-rw-r--r--chromium/content/browser/web_contents/web_contents_impl.cc582
-rw-r--r--chromium/content/browser/web_contents/web_contents_impl.h125
-rw-r--r--chromium/content/browser/web_contents/web_contents_impl_browsertest.cc442
-rw-r--r--chromium/content/browser/web_contents/web_contents_impl_unittest.cc212
-rw-r--r--chromium/content/browser/web_contents/web_contents_view_android.cc70
-rw-r--r--chromium/content/browser/web_contents/web_contents_view_android.h21
-rw-r--r--chromium/content/browser/web_contents/web_contents_view_aura.cc73
-rw-r--r--chromium/content/browser/web_contents/web_contents_view_aura.h20
-rw-r--r--chromium/content/browser/web_contents/web_contents_view_aura_browsertest.cc33
-rw-r--r--chromium/content/browser/web_contents/web_contents_view_aura_unittest.cc29
-rw-r--r--chromium/content/browser/web_contents/web_contents_view_mac.mm51
-rw-r--r--chromium/content/browser/web_contents/web_contents_view_mac_unittest.mm44
-rw-r--r--chromium/content/browser/web_contents/web_drag_dest_mac.mm2
-rw-r--r--chromium/content/browser/web_contents/web_drag_utils_win.h2
-rw-r--r--chromium/content/browser/web_contents_binding_set_browsertest.cc1
-rw-r--r--chromium/content/browser/web_package/mock_signed_exchange_handler.cc7
-rw-r--r--chromium/content/browser/web_package/mock_signed_exchange_handler.h9
-rw-r--r--chromium/content/browser/web_package/signed_exchange_cert_fetcher.cc169
-rw-r--r--chromium/content/browser/web_package/signed_exchange_cert_fetcher.h36
-rw-r--r--chromium/content/browser/web_package/signed_exchange_cert_fetcher_factory.cc65
-rw-r--r--chromium/content/browser/web_package/signed_exchange_cert_fetcher_factory.h48
-rw-r--r--chromium/content/browser/web_package/signed_exchange_cert_fetcher_unittest.cc336
-rw-r--r--chromium/content/browser/web_package/signed_exchange_certificate_chain.cc126
-rw-r--r--chromium/content/browser/web_package/signed_exchange_certificate_chain.h48
-rw-r--r--chromium/content/browser/web_package/signed_exchange_certificate_chain_fuzzer.cc17
-rw-r--r--chromium/content/browser/web_package/signed_exchange_certificate_chain_unittest.cc267
-rw-r--r--chromium/content/browser/web_package/signed_exchange_consts.h14
-rw-r--r--chromium/content/browser/web_package/signed_exchange_handler.cc506
-rw-r--r--chromium/content/browser/web_package/signed_exchange_handler.h125
-rw-r--r--chromium/content/browser/web_package/signed_exchange_handler_unittest.cc355
-rw-r--r--chromium/content/browser/web_package/signed_exchange_header.cc375
-rw-r--r--chromium/content/browser/web_package/signed_exchange_header.h47
-rw-r--r--chromium/content/browser/web_package/signed_exchange_header_parser.cc125
-rw-r--r--chromium/content/browser/web_package/signed_exchange_header_parser.h33
-rw-r--r--chromium/content/browser/web_package/signed_exchange_header_parser_unittest.cc252
-rw-r--r--chromium/content/browser/web_package/signed_exchange_header_unittest.cc212
-rw-r--r--chromium/content/browser/web_package/signed_exchange_parser.cc23
-rw-r--r--chromium/content/browser/web_package/signed_exchange_parser.h122
-rw-r--r--chromium/content/browser/web_package/signed_exchange_signature_verifier.cc292
-rw-r--r--chromium/content/browser/web_package/signed_exchange_signature_verifier.h41
-rw-r--r--chromium/content/browser/web_package/signed_exchange_signature_verifier_unittest.cc149
-rw-r--r--chromium/content/browser/web_package/signed_exchange_url_loader_factory_for_non_network_service.cc2
-rw-r--r--chromium/content/browser/web_package/signed_exchange_url_loader_factory_for_non_network_service.h7
-rw-r--r--chromium/content/browser/web_package/signed_exchange_utils.cc24
-rw-r--r--chromium/content/browser/web_package/signed_exchange_utils.h27
-rw-r--r--chromium/content/browser/web_package/web_package_context_impl.cc22
-rw-r--r--chromium/content/browser/web_package/web_package_context_impl.h24
-rw-r--r--chromium/content/browser/web_package/web_package_loader.cc50
-rw-r--r--chromium/content/browser/web_package/web_package_loader.h33
-rw-r--r--chromium/content/browser/web_package/web_package_prefetch_handler.cc11
-rw-r--r--chromium/content/browser/web_package/web_package_prefetch_handler.h9
-rw-r--r--chromium/content/browser/web_package/web_package_request_handler.cc18
-rw-r--r--chromium/content/browser/web_package/web_package_request_handler.h25
-rw-r--r--chromium/content/browser/web_package/web_package_request_handler_browsertest.cc100
-rw-r--r--chromium/content/browser/webauth/OWNERS6
-rw-r--r--chromium/content/browser/webauth/authenticator_impl.cc437
-rw-r--r--chromium/content/browser/webauth/authenticator_impl.h82
-rw-r--r--chromium/content/browser/webauth/authenticator_impl_unittest.cc800
-rw-r--r--chromium/content/browser/webauth/authenticator_type_converters.cc164
-rw-r--r--chromium/content/browser/webauth/authenticator_type_converters.h94
-rw-r--r--chromium/content/browser/webauth/scoped_virtual_authenticator_environment.cc119
-rw-r--r--chromium/content/browser/webauth/scoped_virtual_authenticator_environment.h81
-rw-r--r--chromium/content/browser/webauth/virtual_authenticator.cc82
-rw-r--r--chromium/content/browser/webauth/virtual_authenticator.h68
-rw-r--r--chromium/content/browser/webauth/virtual_discovery.cc52
-rw-r--r--chromium/content/browser/webauth/virtual_discovery.h53
-rw-r--r--chromium/content/browser/webauth/webauth_browsertest.cc706
-rw-r--r--chromium/content/browser/webrtc/webrtc_audio_debug_recordings_browsertest.cc18
-rw-r--r--chromium/content/browser/webrtc/webrtc_browsertest.cc8
-rw-r--r--chromium/content/browser/webrtc/webrtc_capture_from_element_browsertest.cc2
-rw-r--r--chromium/content/browser/webrtc/webrtc_content_browsertest_base.cc2
-rw-r--r--chromium/content/browser/webrtc/webrtc_event_log_manager.cc669
-rw-r--r--chromium/content/browser/webrtc/webrtc_event_log_manager.h366
-rw-r--r--chromium/content/browser/webrtc/webrtc_event_log_manager_common.cc52
-rw-r--r--chromium/content/browser/webrtc/webrtc_event_log_manager_common.h182
-rw-r--r--chromium/content/browser/webrtc/webrtc_event_log_manager_unittest.cc2454
-rw-r--r--chromium/content/browser/webrtc/webrtc_event_log_uploader.cc43
-rw-r--r--chromium/content/browser/webrtc/webrtc_event_log_uploader.h68
-rw-r--r--chromium/content/browser/webrtc/webrtc_getusermedia_browsertest.cc11
-rw-r--r--chromium/content/browser/webrtc/webrtc_internals.cc25
-rw-r--r--chromium/content/browser/webrtc/webrtc_internals.h18
-rw-r--r--chromium/content/browser/webrtc/webrtc_internals_message_handler.cc40
-rw-r--r--chromium/content/browser/webrtc/webrtc_internals_message_handler_unittest.cc5
-rw-r--r--chromium/content/browser/webrtc/webrtc_internals_ui.cc1
-rw-r--r--chromium/content/browser/webrtc/webrtc_internals_unittest.cc12
-rw-r--r--chromium/content/browser/webrtc/webrtc_local_event_log_manager.cc249
-rw-r--r--chromium/content/browser/webrtc/webrtc_local_event_log_manager.h92
-rw-r--r--chromium/content/browser/webrtc/webrtc_media_recorder_browsertest.cc62
-rw-r--r--chromium/content/browser/webrtc/webrtc_remote_event_log_manager.cc537
-rw-r--r--chromium/content/browser/webrtc/webrtc_remote_event_log_manager.h238
-rw-r--r--chromium/content/browser/webrtc/webrtc_stress_pause_browsertest.cc2
-rw-r--r--chromium/content/browser/webrtc/webrtc_stress_resolution_switch_browsertest.cc2
-rw-r--r--chromium/content/browser/webrtc/webrtc_stress_source_switch_browsertest.cc2
-rw-r--r--chromium/content/browser/websockets/OWNERS1
-rw-r--r--chromium/content/browser/websockets/README.md2
-rw-r--r--chromium/content/browser/websockets/websocket_impl.cc533
-rw-r--r--chromium/content/browser/websockets/websocket_impl.h112
-rw-r--r--chromium/content/browser/websockets/websocket_manager.cc208
-rw-r--r--chromium/content/browser/websockets/websocket_manager.h59
-rw-r--r--chromium/content/browser/websockets/websocket_manager_unittest.cc184
-rw-r--r--chromium/content/browser/webui/content_web_ui_controller_factory.cc2
-rw-r--r--chromium/content/browser/webui/generic_handler.cc5
-rw-r--r--chromium/content/browser/webui/url_data_manager.cc1
-rw-r--r--chromium/content/browser/webui/url_data_manager_backend.cc9
-rw-r--r--chromium/content/browser/webui/web_ui_data_source_impl.cc24
-rw-r--r--chromium/content/browser/webui/web_ui_data_source_impl.h14
-rw-r--r--chromium/content/browser/webui/web_ui_impl.cc21
-rw-r--r--chromium/content/browser/webui/web_ui_impl.h13
-rw-r--r--chromium/content/browser/webui/web_ui_mojo_browsertest.cc1
-rw-r--r--chromium/content/browser/webui/web_ui_url_loader_factory.cc51
-rw-r--r--chromium/content/browser/webui/web_ui_url_loader_factory_internal.h (renamed from chromium/content/browser/webui/web_ui_url_loader_factory.h)8
-rw-r--r--chromium/content/browser/zygote_host/zygote_host_impl_linux.cc4
-rw-r--r--chromium/content/child/BUILD.gn22
-rw-r--r--chromium/content/child/assert_matching_enums.cc10
-rw-r--r--chromium/content/child/blink_platform_impl.cc55
-rw-r--r--chromium/content/child/blink_platform_impl.h9
-rw-r--r--chromium/content/child/blink_platform_impl_unittest.cc4
-rw-r--r--chromium/content/child/browser_font_resource_trusted.cc14
-rw-r--r--chromium/content/child/child_process_sandbox_support_impl_linux.cc8
-rw-r--r--chromium/content/child/child_process_sandbox_support_impl_mac.cc45
-rw-r--r--chromium/content/child/child_process_sandbox_support_impl_mac.h18
-rw-r--r--chromium/content/child/child_thread_impl.cc37
-rw-r--r--chromium/content/child/child_thread_impl.h17
-rw-r--r--chromium/content/child/content_child_helpers.cc65
-rw-r--r--chromium/content/child/content_child_helpers.h20
-rw-r--r--chromium/content/child/dwrite_font_proxy/dwrite_font_proxy_init_impl_win.cc2
-rw-r--r--chromium/content/child/font_warmup_win.cc37
-rw-r--r--chromium/content/child/image_decoder.cc6
-rw-r--r--chromium/content/child/runtime_features.cc48
-rw-r--r--chromium/content/child/scoped_web_callbacks.h2
-rw-r--r--chromium/content/child/service_factory.cc1
-rw-r--r--chromium/content/child/webfallbackthemeengine_impl.cc4
-rw-r--r--chromium/content/child/webfallbackthemeengine_impl.h2
-rw-r--r--chromium/content/child/webthemeengine_impl_android.cc4
-rw-r--r--chromium/content/child/webthemeengine_impl_android.h2
-rw-r--r--chromium/content/child/webthemeengine_impl_default.cc4
-rw-r--r--chromium/content/child/webthemeengine_impl_default.h2
-rw-r--r--chromium/content/child/webthemeengine_impl_mac.h2
-rw-r--r--chromium/content/common/BUILD.gn73
-rw-r--r--chromium/content/common/DEPS137
-rw-r--r--chromium/content/common/accessibility_messages.h10
-rw-r--r--chromium/content/common/all_messages.h2
-rw-r--r--chromium/content/common/android/browser_side_navigation_policy_android.cc21
-rw-r--r--chromium/content/common/associated_interface_provider_impl.cc19
-rw-r--r--chromium/content/common/associated_interface_provider_impl.h16
-rw-r--r--chromium/content/common/associated_interface_registry_impl.h2
-rw-r--r--chromium/content/common/background_fetch/DEPS2
-rw-r--r--chromium/content/common/background_fetch/background_fetch_struct_traits.h2
-rw-r--r--chromium/content/common/background_fetch/background_fetch_types.typemap4
-rw-r--r--chromium/content/common/bluetooth/web_bluetooth_device_id.typemap2
-rw-r--r--chromium/content/common/bluetooth/web_bluetooth_device_id_struct_traits.h2
-rw-r--r--chromium/content/common/browser_plugin/browser_plugin_messages.h29
-rw-r--r--chromium/content/common/cache_storage/cache_storage.typemap2
-rw-r--r--chromium/content/common/cache_storage/cache_storage_messages.h196
-rw-r--r--chromium/content/common/cache_storage/cache_storage_mojom_traits.h2
-rw-r--r--chromium/content/common/child_control.mojom1
-rw-r--r--chromium/content/common/common_param_traits_unittest.cc6
-rw-r--r--chromium/content/common/content_constants_internal.cc2
-rw-r--r--chromium/content/common/content_constants_internal.h3
-rw-r--r--chromium/content/common/content_ipc_logging.cc2
-rw-r--r--chromium/content/common/content_message_generator.h19
-rw-r--r--chromium/content/common/content_param_traits.cc8
-rw-r--r--chromium/content/common/content_param_traits.h2
-rw-r--r--chromium/content/common/content_param_traits_macros.h14
-rw-r--r--chromium/content/common/content_security_policy/csp_source_list_unittest.cc8
-rw-r--r--chromium/content/common/content_security_policy_header.h2
-rw-r--r--chromium/content/common/cross_site_document_classifier.cc369
-rw-r--r--chromium/content/common/cross_site_document_classifier.h87
-rw-r--r--chromium/content/common/cross_site_document_classifier_unittest.cc216
-rw-r--r--chromium/content/common/cursors/DEPS2
-rw-r--r--chromium/content/common/cursors/webcursor.cc2
-rw-r--r--chromium/content/common/cursors/webcursor_android.cc2
-rw-r--r--chromium/content/common/cursors/webcursor_aura.cc2
-rw-r--r--chromium/content/common/cursors/webcursor_aurawin.cc2
-rw-r--r--chromium/content/common/cursors/webcursor_aurax11.cc2
-rw-r--r--chromium/content/common/cursors/webcursor_mac.mm4
-rw-r--r--chromium/content/common/cursors/webcursor_ozone.cc2
-rw-r--r--chromium/content/common/cursors/webcursor_unittest.cc2
-rw-r--r--chromium/content/common/dom_storage/dom_storage_messages.h2
-rw-r--r--chromium/content/common/drag_messages.h2
-rw-r--r--chromium/content/common/drag_traits.h2
-rw-r--r--chromium/content/common/dwrite_font_proxy.mojom8
-rw-r--r--chromium/content/common/file_utilities.mojom8
-rw-r--r--chromium/content/common/fileapi/file_system_messages.h20
-rw-r--r--chromium/content/common/font_list_mac.mm1
-rw-r--r--chromium/content/common/font_list_win.cc1
-rw-r--r--chromium/content/common/font_loader_dispatcher_mac.cc36
-rw-r--r--chromium/content/common/font_loader_dispatcher_mac.h39
-rw-r--r--chromium/content/common/font_loader_mac.mojom14
-rw-r--r--chromium/content/common/frame.mojom55
-rw-r--r--chromium/content/common/frame_messages.h124
-rw-r--r--chromium/content/common/frame_owner_properties.h4
-rw-r--r--chromium/content/common/frame_replication_state.cc4
-rw-r--r--chromium/content/common/frame_replication_state.h6
-rw-r--r--chromium/content/common/frame_resize_params.cc19
-rw-r--r--chromium/content/common/frame_resize_params.h47
-rw-r--r--chromium/content/common/indexed_db/indexed_db.mojom11
-rw-r--r--chromium/content/common/indexed_db/indexed_db.typemap2
-rw-r--r--chromium/content/common/indexed_db/indexed_db_key.h2
-rw-r--r--chromium/content/common/indexed_db/indexed_db_key_path.h2
-rw-r--r--chromium/content/common/indexed_db/indexed_db_key_range.cc2
-rw-r--r--chromium/content/common/input/event_with_latency_info.h6
-rw-r--r--chromium/content/common/input/event_with_latency_info_unittest.cc5
-rw-r--r--chromium/content/common/input/gesture_event_stream_validator.cc25
-rw-r--r--chromium/content/common/input/gesture_event_stream_validator.h3
-rw-r--r--chromium/content/common/input/ime_text_span_conversions.cc76
-rw-r--r--chromium/content/common/input/ime_text_span_conversions.h14
-rw-r--r--chromium/content/common/input/input_event_ack.h2
-rw-r--r--chromium/content/common/input/input_event_stream_validator.cc21
-rw-r--r--chromium/content/common/input/input_event_stream_validator.h7
-rw-r--r--chromium/content/common/input/input_event_struct_traits.cc15
-rw-r--r--chromium/content/common/input/input_handler.mojom5
-rw-r--r--chromium/content/common/input/input_param_traits_unittest.cc13
-rw-r--r--chromium/content/common/input/sync_compositor_messages.h2
-rw-r--r--chromium/content/common/input/synchronous_compositor.mojom4
-rw-r--r--chromium/content/common/input/synthetic_pointer_action_params.cc10
-rw-r--r--chromium/content/common/input/synthetic_pointer_action_params.h11
-rw-r--r--chromium/content/common/input/synthetic_web_input_event_builders.cc10
-rw-r--r--chromium/content/common/input/synthetic_web_input_event_builders.h10
-rw-r--r--chromium/content/common/input/touch_event_stream_validator.cc2
-rw-r--r--chromium/content/common/input/touch_event_stream_validator.h2
-rw-r--r--chromium/content/common/input/web_touch_event_traits.cc2
-rw-r--r--chromium/content/common/input/web_touch_event_traits.h2
-rw-r--r--chromium/content/common/input_messages.h7
-rw-r--r--chromium/content/common/leveldb_wrapper.mojom5
-rw-r--r--chromium/content/common/mac/attributed_string_coder.h2
-rw-r--r--chromium/content/common/mac/attributed_string_coder.mm6
-rw-r--r--chromium/content/common/mac/font_loader.h11
-rw-r--r--chromium/content/common/mac/font_loader.mm10
-rw-r--r--chromium/content/common/manifest_share_target_util_unittest.cc266
-rw-r--r--chromium/content/common/media/media_devices.typemap3
-rw-r--r--chromium/content/common/media/media_devices_typemap_traits.cc39
-rw-r--r--chromium/content/common/media/media_devices_typemap_traits.h10
-rw-r--r--chromium/content/common/media/media_player_delegate_messages.h11
-rw-r--r--chromium/content/common/media/media_player_messages_android.h2
-rw-r--r--chromium/content/common/media/media_session.typemap2
-rw-r--r--chromium/content/common/media/media_session_struct_traits.h2
-rw-r--r--chromium/content/common/media/media_stream.mojom10
-rw-r--r--chromium/content/common/media/media_stream_track_metrics_host_messages.h25
-rw-r--r--chromium/content/common/media/peer_connection_tracker_messages.h10
-rw-r--r--chromium/content/common/native_types.typemap20
-rw-r--r--chromium/content/common/native_types_mac.typemap6
-rw-r--r--chromium/content/common/navigation_params.h7
-rw-r--r--chromium/content/common/navigation_params.mojom6
-rw-r--r--chromium/content/common/navigation_params.typemap6
-rw-r--r--chromium/content/common/net/url_fetcher.cc1
-rw-r--r--chromium/content/common/notifications/DEPS2
-rw-r--r--chromium/content/common/notifications/notification_struct_traits.h3
-rw-r--r--chromium/content/common/notifications/notification_struct_traits_unittest.cc2
-rw-r--r--chromium/content/common/notifications/notification_types.typemap4
-rw-r--r--chromium/content/common/origin_trials/OWNERS4
-rw-r--r--chromium/content/common/origin_trials/trial_policy_impl.cc2
-rw-r--r--chromium/content/common/origin_trials/trial_policy_impl.h2
-rw-r--r--chromium/content/common/page_messages.h8
-rw-r--r--chromium/content/common/page_state.mojom8
-rw-r--r--chromium/content/common/page_state_serialization.cc9
-rw-r--r--chromium/content/common/page_state_serialization.h6
-rw-r--r--chromium/content/common/pepper_file_util.h2
-rw-r--r--chromium/content/common/pepper_plugin_list.h2
-rw-r--r--chromium/content/common/pepper_renderer_instance_data.h2
-rw-r--r--chromium/content/common/plugin_list.cc2
-rw-r--r--chromium/content/common/plugin_list.h2
-rw-r--r--chromium/content/common/presentation/presentation.typemap2
-rw-r--r--chromium/content/common/presentation/presentation_struct_traits.h2
-rw-r--r--chromium/content/common/push_messaging.mojom1
-rw-r--r--chromium/content/common/push_messaging.typemap4
-rw-r--r--chromium/content/common/push_messaging_param_traits.cc4
-rw-r--r--chromium/content/common/render_frame_metadata.mojom22
-rw-r--r--chromium/content/common/render_frame_metadata_struct_traits.cc7
-rw-r--r--chromium/content/common/render_frame_metadata_struct_traits.h17
-rw-r--r--chromium/content/common/render_message_filter.mojom18
-rw-r--r--chromium/content/common/render_widget_window_tree_client_factory.mojom4
-rw-r--r--chromium/content/common/renderer.mojom15
-rw-r--r--chromium/content/common/resize_params.cc4
-rw-r--r--chromium/content/common/resize_params.h16
-rw-r--r--chromium/content/common/resource_messages.h2
-rw-r--r--chromium/content/common/sandbox_init_mac.cc38
-rw-r--r--chromium/content/common/sandbox_mac_fontloading_unittest.mm9
-rw-r--r--chromium/content/common/sandbox_mac_unittest_helper.mm3
-rw-r--r--chromium/content/common/service_manager/service_manager_connection_impl.cc1
-rw-r--r--chromium/content/common/service_worker/controller_service_worker.mojom10
-rw-r--r--chromium/content/common/service_worker/dispatch_fetch_event_params.mojom2
-rw-r--r--chromium/content/common/service_worker/embedded_worker.mojom32
-rw-r--r--chromium/content/common/service_worker/embedded_worker_messages.h25
-rw-r--r--chromium/content/common/service_worker/service_worker_container.mojom27
-rw-r--r--chromium/content/common/service_worker/service_worker_event_dispatcher.mojom48
-rw-r--r--chromium/content/common/service_worker/service_worker_fetch_request.typemap2
-rw-r--r--chromium/content/common/service_worker/service_worker_fetch_request_mojom_traits.h2
-rw-r--r--chromium/content/common/service_worker/service_worker_fetch_response.typemap3
-rw-r--r--chromium/content/common/service_worker/service_worker_fetch_response_callback.mojom16
-rw-r--r--chromium/content/common/service_worker/service_worker_fetch_response_mojom_traits.cc2
-rw-r--r--chromium/content/common/service_worker/service_worker_fetch_response_mojom_traits.h4
-rw-r--r--chromium/content/common/service_worker/service_worker_loader_helpers.cc9
-rw-r--r--chromium/content/common/service_worker/service_worker_loader_helpers.h2
-rw-r--r--chromium/content/common/service_worker/service_worker_messages.h20
-rw-r--r--chromium/content/common/service_worker/service_worker_provider.mojom16
-rw-r--r--chromium/content/common/service_worker/service_worker_provider_host_info.h8
-rw-r--r--chromium/content/common/service_worker/service_worker_provider_struct_traits.h2
-rw-r--r--chromium/content/common/service_worker/service_worker_types.cc13
-rw-r--r--chromium/content/common/service_worker/service_worker_types.h20
-rw-r--r--chromium/content/common/service_worker/service_worker_utils.h2
-rw-r--r--chromium/content/common/shared_worker/shared_worker.mojom2
-rw-r--r--chromium/content/common/shared_worker/shared_worker_client.mojom4
-rw-r--r--chromium/content/common/shared_worker/shared_worker_connector.mojom2
-rw-r--r--chromium/content/common/shared_worker/shared_worker_factory.mojom30
-rw-r--r--chromium/content/common/shared_worker/shared_worker_host.mojom2
-rw-r--r--chromium/content/common/shared_worker/shared_worker_info.mojom4
-rw-r--r--chromium/content/common/single_request_url_loader_factory.cc7
-rw-r--r--chromium/content/common/single_request_url_loader_factory.h6
-rw-r--r--chromium/content/common/speech_recognition_messages.h22
-rw-r--r--chromium/content/common/throttling_url_loader.cc55
-rw-r--r--chromium/content/common/throttling_url_loader.h35
-rw-r--r--chromium/content/common/throttling_url_loader_unittest.cc75
-rw-r--r--chromium/content/common/unique_name_helper.cc7
-rw-r--r--chromium/content/common/unique_name_helper_unittest.cc1
-rw-r--r--chromium/content/common/url_loader_factory_bundle.cc5
-rw-r--r--chromium/content/common/url_loader_factory_bundle.h11
-rw-r--r--chromium/content/common/url_schemes.cc74
-rw-r--r--chromium/content/common/view_messages.h76
-rw-r--r--chromium/content/common/wrapper_shared_url_loader_factory.cc2
-rw-r--r--chromium/content/common/wrapper_shared_url_loader_factory.h11
-rw-r--r--chromium/content/gpu/BUILD.gn4
-rw-r--r--chromium/content/gpu/gpu_child_thread.cc9
-rw-r--r--chromium/content/gpu/gpu_child_thread.h2
-rw-r--r--chromium/content/gpu/gpu_main.cc2
-rw-r--r--chromium/content/gpu/gpu_sandbox_hook_linux.cc2
-rw-r--r--chromium/content/gpu/gpu_service_factory.cc8
-rw-r--r--chromium/content/gpu/gpu_service_factory.h2
-rw-r--r--chromium/content/ppapi_plugin/BUILD.gn6
-rw-r--r--chromium/content/ppapi_plugin/ppapi_blink_platform_impl.cc12
-rw-r--r--chromium/content/ppapi_plugin/ppapi_plugin_main.cc2
-rw-r--r--chromium/content/ppapi_plugin/ppapi_thread.cc72
-rw-r--r--chromium/content/public/android/BUILD.gn31
-rw-r--r--chromium/content/public/app/BUILD.gn1
-rw-r--r--chromium/content/public/app/mojo/content_browser_manifest.json19
-rw-r--r--chromium/content/public/app/mojo/content_renderer_manifest.json11
-rw-r--r--chromium/content/public/app/mojo/content_utility_manifest.json10
-rw-r--r--chromium/content/public/app/mojo/context_snapshot_manifest.json9
-rw-r--r--chromium/content/public/app/mojo/snapshot_blob_manifest.json8
-rw-r--r--chromium/content/public/browser/BUILD.gn19
-rw-r--r--chromium/content/public/browser/android/synchronous_compositor.h6
-rw-r--r--chromium/content/public/browser/appcache_service.h3
-rw-r--r--chromium/content/public/browser/background_fetch_delegate.h12
-rw-r--r--chromium/content/public/browser/blob_handle.h2
-rw-r--r--chromium/content/public/browser/browser_context.h4
-rw-r--r--chromium/content/public/browser/browser_ipc_logging.h2
-rw-r--r--chromium/content/public/browser/browser_message_filter.cc2
-rw-r--r--chromium/content/public/browser/browser_plugin_guest_manager.cc5
-rw-r--r--chromium/content/public/browser/browser_plugin_guest_manager.h2
-rw-r--r--chromium/content/public/browser/browser_thread.h34
-rw-r--r--chromium/content/public/browser/browser_thread_delegate.h14
-rw-r--r--chromium/content/public/browser/browsing_data_filter_builder.h6
-rw-r--r--chromium/content/public/browser/child_process_launcher_utils.h24
-rw-r--r--chromium/content/public/browser/content_browser_client.cc54
-rw-r--r--chromium/content/public/browser/content_browser_client.h94
-rw-r--r--chromium/content/public/browser/devtools_agent_host.h6
-rw-r--r--chromium/content/public/browser/devtools_manager_delegate.cc8
-rw-r--r--chromium/content/public/browser/devtools_manager_delegate.h8
-rw-r--r--chromium/content/public/browser/download_manager.cc15
-rw-r--r--chromium/content/public/browser/download_manager.h34
-rw-r--r--chromium/content/public/browser/gpu_data_manager.h11
-rw-r--r--chromium/content/public/browser/gpu_data_manager_observer.h10
-rw-r--r--chromium/content/public/browser/gpu_utils.cc2
-rw-r--r--chromium/content/public/browser/login_delegate.h (renamed from chromium/content/public/browser/resource_dispatcher_host_login_delegate.h)16
-rw-r--r--chromium/content/public/browser/media_controller.h44
-rw-r--r--chromium/content/public/browser/media_session.h3
-rw-r--r--chromium/content/public/browser/native_web_keyboard_event.h2
-rw-r--r--chromium/content/public/browser/navigation_handle.cc2
-rw-r--r--chromium/content/public/browser/navigation_handle.h8
-rw-r--r--chromium/content/public/browser/notification_types.h40
-rw-r--r--chromium/content/public/browser/overlay_window.h54
-rw-r--r--chromium/content/public/browser/overscroll_configuration.h50
-rw-r--r--chromium/content/public/browser/page_navigator.cc12
-rw-r--r--chromium/content/public/browser/page_navigator.h6
-rw-r--r--chromium/content/public/browser/payment_app_provider.h14
-rw-r--r--chromium/content/public/browser/permission_manager.h15
-rw-r--r--chromium/content/public/browser/picture_in_picture_window_controller.h53
-rw-r--r--chromium/content/public/browser/platform_notification_service.h2
-rw-r--r--chromium/content/public/browser/plugin_service.h15
-rw-r--r--chromium/content/public/browser/presentation_screen_availability_listener.h2
-rw-r--r--chromium/content/public/browser/presentation_service_delegate.h12
-rw-r--r--chromium/content/public/browser/provision_fetcher_impl.cc1
-rw-r--r--chromium/content/public/browser/push_messaging_service.cc4
-rw-r--r--chromium/content/public/browser/render_frame_host.h9
-rw-r--r--chromium/content/public/browser/render_process_host.h87
-rw-r--r--chromium/content/public/browser/render_process_host_observer.h2
-rw-r--r--chromium/content/public/browser/render_view_host.h10
-rw-r--r--chromium/content/public/browser/render_widget_host.h8
-rw-r--r--chromium/content/public/browser/render_widget_host_view.h63
-rw-r--r--chromium/content/public/browser/render_widget_host_view_mac_delegate.h36
-rw-r--r--chromium/content/public/browser/resource_dispatcher_host_delegate.cc6
-rw-r--r--chromium/content/public/browser/resource_dispatcher_host_delegate.h6
-rw-r--r--chromium/content/public/browser/resource_request_info.h14
-rw-r--r--chromium/content/public/browser/screen_orientation_delegate.h2
-rw-r--r--chromium/content/public/browser/security_style_explanation.h2
-rw-r--r--chromium/content/public/browser/security_style_explanations.h2
-rw-r--r--chromium/content/public/browser/service_worker_context.h2
-rw-r--r--chromium/content/public/browser/site_isolation_policy.cc (renamed from chromium/content/browser/site_isolation_policy.cc)40
-rw-r--r--chromium/content/public/browser/site_isolation_policy.h (renamed from chromium/content/browser/site_isolation_policy.h)10
-rw-r--r--chromium/content/public/browser/site_isolation_policy_unittest.cc (renamed from chromium/content/browser/site_isolation_policy_unittest.cc)2
-rw-r--r--chromium/content/public/browser/speech_recognition_manager.h18
-rw-r--r--chromium/content/public/browser/speech_recognition_session_context.cc9
-rw-r--r--chromium/content/public/browser/speech_recognition_session_context.h18
-rw-r--r--chromium/content/public/browser/storage_partition.h15
-rw-r--r--chromium/content/public/browser/stored_payment_app.h5
-rw-r--r--chromium/content/public/browser/touch_selection_controller_client_manager.h2
-rw-r--r--chromium/content/public/browser/utility_process_host.h88
-rw-r--r--chromium/content/public/browser/utility_process_mojo_client.h185
-rw-r--r--chromium/content/public/browser/web_contents.h98
-rw-r--r--chromium/content/public/browser/web_contents_binding_set.h1
-rw-r--r--chromium/content/public/browser/web_contents_delegate.cc7
-rw-r--r--chromium/content/public/browser/web_contents_delegate.h32
-rw-r--r--chromium/content/public/browser/web_contents_observer.h14
-rw-r--r--chromium/content/public/browser/web_package_context.h31
-rw-r--r--chromium/content/public/browser/web_ui.h5
-rw-r--r--chromium/content/public/browser/web_ui_data_source.h15
-rw-r--r--chromium/content/public/browser/web_ui_url_loader_factory.h27
-rw-r--r--chromium/content/public/browser/webrtc_event_logger.cc29
-rw-r--r--chromium/content/public/browser/webrtc_event_logger.h151
-rw-r--r--chromium/content/public/browser/webrtc_log.h2
-rw-r--r--chromium/content/public/child/BUILD.gn2
-rw-r--r--chromium/content/public/child/child_thread.h26
-rw-r--r--chromium/content/public/common/BUILD.gn43
-rw-r--r--chromium/content/public/common/appcache_info.h2
-rw-r--r--chromium/content/public/common/appcache_info.mojom8
-rw-r--r--chromium/content/public/common/browser_side_navigation_policy.cc6
-rw-r--r--chromium/content/public/common/common_param_traits_macros.h44
-rw-r--r--chromium/content/public/common/content_features.cc322
-rw-r--r--chromium/content/public/common/content_features.h57
-rw-r--r--chromium/content/public/common/content_switches.cc64
-rw-r--r--chromium/content/public/common/content_switches.h16
-rw-r--r--chromium/content/public/common/context_menu_params.h4
-rw-r--r--chromium/content/public/common/cursor_info.h2
-rw-r--r--chromium/content/public/common/drop_data.h2
-rw-r--r--chromium/content/public/common/feature_h264_with_openh264_ffmpeg.h4
-rw-r--r--chromium/content/public/common/font_cache_win.mojom4
-rw-r--r--chromium/content/public/common/manifest.h8
-rw-r--r--chromium/content/public/common/manifest.typemap2
-rw-r--r--chromium/content/public/common/manifest_share_target_util.cc127
-rw-r--r--chromium/content/public/common/manifest_share_target_util.h37
-rw-r--r--chromium/content/public/common/manifest_struct_traits.cc10
-rw-r--r--chromium/content/public/common/manifest_struct_traits.h7
-rw-r--r--chromium/content/public/common/manifest_util.h4
-rw-r--r--chromium/content/public/common/menu_item.h2
-rw-r--r--chromium/content/public/common/mhtml_generation_params.h2
-rw-r--r--chromium/content/public/common/pepper_plugin_info.h2
-rw-r--r--chromium/content/public/common/presentation_connection_message.cc5
-rw-r--r--chromium/content/public/common/previews_state.h2
-rw-r--r--chromium/content/public/common/push_messaging_status.mojom54
-rw-r--r--chromium/content/public/common/referrer.h2
-rw-r--r--chromium/content/public/common/referrer.typemap2
-rw-r--r--chromium/content/public/common/referrer_struct_traits.h4
-rw-r--r--chromium/content/public/common/resource_load_info.mojom51
-rw-r--r--chromium/content/public/common/resource_usage_reporter_type_converters.h2
-rw-r--r--chromium/content/public/common/sandbox_init.h5
-rw-r--r--chromium/content/public/common/sandboxed_process_launcher_delegate.cc2
-rw-r--r--chromium/content/public/common/sandboxed_process_launcher_delegate.h2
-rw-r--r--chromium/content/public/common/shared_url_loader_factory.cc28
-rw-r--r--chromium/content/public/common/shared_url_loader_factory.h68
-rw-r--r--chromium/content/public/common/storage_quota_params.h2
-rw-r--r--chromium/content/public/common/transferrable_url_loader.mojom17
-rw-r--r--chromium/content/public/common/url_constants.cc10
-rw-r--r--chromium/content/public/common/url_constants.h10
-rw-r--r--chromium/content/public/common/url_loader_throttle.cc8
-rw-r--r--chromium/content/public/common/url_loader_throttle.h9
-rw-r--r--chromium/content/public/common/url_utils.cc12
-rw-r--r--chromium/content/public/common/weak_wrapper_shared_url_loader_factory.cc (renamed from chromium/content/common/weak_wrapper_shared_url_loader_factory.cc)4
-rw-r--r--chromium/content/public/common/weak_wrapper_shared_url_loader_factory.h (renamed from chromium/content/common/weak_wrapper_shared_url_loader_factory.h)12
-rw-r--r--chromium/content/public/common/web_preferences.cc17
-rw-r--r--chromium/content/public/common/web_preferences.h12
-rw-r--r--chromium/content/public/common/webplugininfo.cc21
-rw-r--r--chromium/content/public/common/webplugininfo.h6
-rw-r--r--chromium/content/public/common/webplugininfo.typemap1
-rw-r--r--chromium/content/public/common/webplugininfo_param_traits.h3
-rw-r--r--chromium/content/public/common/zygote_features.gni2
-rw-r--r--chromium/content/public/common/zygote_handle.h2
-rw-r--r--chromium/content/public/gpu/content_gpu_client.h6
-rw-r--r--chromium/content/public/renderer/BUILD.gn8
-rw-r--r--chromium/content/public/renderer/associated_resource_fetcher.h4
-rw-r--r--chromium/content/public/renderer/content_renderer_client.cc38
-rw-r--r--chromium/content/public/renderer/content_renderer_client.h53
-rw-r--r--chromium/content/public/renderer/document_state.h2
-rw-r--r--chromium/content/public/renderer/media_stream_audio_sink.cc4
-rw-r--r--chromium/content/public/renderer/media_stream_sink.h4
-rw-r--r--chromium/content/public/renderer/media_stream_utils.cc8
-rw-r--r--chromium/content/public/renderer/media_stream_video_sink.h2
-rw-r--r--chromium/content/public/renderer/render_frame.h18
-rw-r--r--chromium/content/public/renderer/render_frame_observer.h16
-rw-r--r--chromium/content/public/renderer/request_peer.h8
-rw-r--r--chromium/content/public/renderer/resource_fetcher.h9
-rw-r--r--chromium/content/public/renderer/url_loader_throttle_provider.h4
-rw-r--r--chromium/content/public/renderer/window_features_converter.h4
-rw-r--r--chromium/content/public/utility/utility_thread.h19
-rw-r--r--chromium/content/renderer/BUILD.gn71
-rw-r--r--chromium/content/renderer/DEPS3
-rw-r--r--chromium/content/renderer/PRESUBMIT.py48
-rwxr-xr-xchromium/content/renderer/PRESUBMIT_test.py36
-rw-r--r--chromium/content/renderer/accessibility/aom_content_ax_tree.cc10
-rw-r--r--chromium/content/renderer/accessibility/aom_content_ax_tree.h4
-rw-r--r--chromium/content/renderer/accessibility/blink_ax_enum_conversion.cc9
-rw-r--r--chromium/content/renderer/accessibility/blink_ax_enum_conversion.h2
-rw-r--r--chromium/content/renderer/accessibility/blink_ax_tree_source.cc46
-rw-r--r--chromium/content/renderer/accessibility/blink_ax_tree_source.h4
-rw-r--r--chromium/content/renderer/accessibility/render_accessibility_impl.cc35
-rw-r--r--chromium/content/renderer/accessibility/render_accessibility_impl.h8
-rw-r--r--chromium/content/renderer/accessibility/render_accessibility_impl_browsertest.cc10
-rw-r--r--chromium/content/renderer/android/disambiguation_popup_helper.cc2
-rw-r--r--chromium/content/renderer/android/disambiguation_popup_helper.h2
-rw-r--r--chromium/content/renderer/android/disambiguation_popup_helper_unittest.cc4
-rw-r--r--chromium/content/renderer/android/renderer_date_time_picker.cc8
-rw-r--r--chromium/content/renderer/android/renderer_date_time_picker.h2
-rw-r--r--chromium/content/renderer/android/synchronous_compositor_filter.cc1
-rw-r--r--chromium/content/renderer/android/synchronous_layer_tree_frame_sink.cc1
-rw-r--r--chromium/content/renderer/appcache/appcache_frontend_impl.cc2
-rw-r--r--chromium/content/renderer/appcache/web_application_cache_host_impl.cc8
-rw-r--r--chromium/content/renderer/appcache/web_application_cache_host_impl.h8
-rw-r--r--chromium/content/renderer/blink_platform_audio_hardware_browsertest.cc2
-rw-r--r--chromium/content/renderer/blob_storage/webblobregistry_impl.cc4
-rw-r--r--chromium/content/renderer/blob_storage/webblobregistry_impl.h2
-rw-r--r--chromium/content/renderer/bmp_image_decoder_unittest.cc2
-rw-r--r--chromium/content/renderer/browser_plugin/browser_plugin.cc103
-rw-r--r--chromium/content/renderer/browser_plugin/browser_plugin.h32
-rw-r--r--chromium/content/renderer/browser_render_view_browsertest.cc8
-rw-r--r--chromium/content/renderer/cache_storage/cache_storage_dispatcher.cc670
-rw-r--r--chromium/content/renderer/cache_storage/cache_storage_dispatcher.h234
-rw-r--r--chromium/content/renderer/cache_storage/cache_storage_message_filter.cc38
-rw-r--r--chromium/content/renderer/cache_storage/cache_storage_message_filter.h33
-rw-r--r--chromium/content/renderer/cache_storage/webserviceworkercachestorage_impl.cc465
-rw-r--r--chromium/content/renderer/cache_storage/webserviceworkercachestorage_impl.h79
-rw-r--r--chromium/content/renderer/child_frame_compositing_helper.cc10
-rw-r--r--chromium/content/renderer/child_frame_compositing_helper.h3
-rw-r--r--chromium/content/renderer/clipboard_utils.cc4
-rw-r--r--chromium/content/renderer/content_security_policy_util.h2
-rw-r--r--chromium/content/renderer/cursor_utils.cc2
-rw-r--r--chromium/content/renderer/device_sensors/device_motion_event_pump.cc4
-rw-r--r--chromium/content/renderer/device_sensors/device_motion_event_pump.h2
-rw-r--r--chromium/content/renderer/device_sensors/device_motion_event_pump_unittest.cc38
-rw-r--r--chromium/content/renderer/device_sensors/device_orientation_event_pump.cc2
-rw-r--r--chromium/content/renderer/device_sensors/device_orientation_event_pump.h4
-rw-r--r--chromium/content/renderer/device_sensors/device_orientation_event_pump_unittest.cc40
-rw-r--r--chromium/content/renderer/device_sensors/device_sensor_event_pump.h10
-rw-r--r--chromium/content/renderer/device_sensors/fake_sensor_and_provider.cc241
-rw-r--r--chromium/content/renderer/device_sensors/fake_sensor_and_provider.h136
-rw-r--r--chromium/content/renderer/devtools/render_widget_screen_metrics_emulator.h2
-rw-r--r--chromium/content/renderer/dom_automation_controller.cc4
-rw-r--r--chromium/content/renderer/dom_serializer_browsertest.cc28
-rw-r--r--chromium/content/renderer/dom_storage/DEPS3
-rw-r--r--chromium/content/renderer/dom_storage/dom_storage_cached_area.cc46
-rw-r--r--chromium/content/renderer/dom_storage/dom_storage_cached_area.h18
-rw-r--r--chromium/content/renderer/dom_storage/dom_storage_cached_area_unittest.cc37
-rw-r--r--chromium/content/renderer/dom_storage/dom_storage_dispatcher.cc44
-rw-r--r--chromium/content/renderer/dom_storage/dom_storage_proxy.h10
-rw-r--r--chromium/content/renderer/dom_storage/local_storage_area.cc2
-rw-r--r--chromium/content/renderer/dom_storage/local_storage_area.h2
-rw-r--r--chromium/content/renderer/dom_storage/local_storage_cached_area.cc112
-rw-r--r--chromium/content/renderer/dom_storage/local_storage_cached_area.h13
-rw-r--r--chromium/content/renderer/dom_storage/local_storage_cached_area_unittest.cc4
-rw-r--r--chromium/content/renderer/dom_storage/local_storage_cached_areas.cc24
-rw-r--r--chromium/content/renderer/dom_storage/local_storage_cached_areas.h9
-rw-r--r--chromium/content/renderer/dom_storage/local_storage_cached_areas_unittest.cc2
-rw-r--r--chromium/content/renderer/dom_storage/local_storage_namespace.cc4
-rw-r--r--chromium/content/renderer/dom_storage/local_storage_namespace.h4
-rw-r--r--chromium/content/renderer/dom_storage/session_web_storage_namespace_impl.cc4
-rw-r--r--chromium/content/renderer/dom_storage/session_web_storage_namespace_impl.h4
-rw-r--r--chromium/content/renderer/dom_storage/webstoragearea_impl.cc2
-rw-r--r--chromium/content/renderer/dom_storage/webstoragearea_impl.h4
-rw-r--r--chromium/content/renderer/dom_storage/webstoragenamespace_impl.cc4
-rw-r--r--chromium/content/renderer/dom_storage/webstoragenamespace_impl.h2
-rw-r--r--chromium/content/renderer/drop_data_builder.cc10
-rw-r--r--chromium/content/renderer/effective_connection_type_helper.cc13
-rw-r--r--chromium/content/renderer/effective_connection_type_helper.h2
-rw-r--r--chromium/content/renderer/external_popup_menu.cc4
-rw-r--r--chromium/content/renderer/external_popup_menu.h6
-rw-r--r--chromium/content/renderer/external_popup_menu_browsertest.cc4
-rw-r--r--chromium/content/renderer/fetchers/associated_resource_fetcher_impl.cc31
-rw-r--r--chromium/content/renderer/fetchers/associated_resource_fetcher_impl.h4
-rw-r--r--chromium/content/renderer/fetchers/manifest_fetcher.cc8
-rw-r--r--chromium/content/renderer/fetchers/manifest_fetcher.h2
-rw-r--r--chromium/content/renderer/fetchers/multi_resolution_image_resource_fetcher.cc24
-rw-r--r--chromium/content/renderer/fetchers/multi_resolution_image_resource_fetcher.h10
-rw-r--r--chromium/content/renderer/fetchers/resource_fetcher_browsertest.cc7
-rw-r--r--chromium/content/renderer/fetchers/resource_fetcher_impl.cc21
-rw-r--r--chromium/content/renderer/fetchers/resource_fetcher_impl.h4
-rw-r--r--chromium/content/renderer/file_info_util.cc2
-rw-r--r--chromium/content/renderer/fileapi/file_system_dispatcher.cc22
-rw-r--r--chromium/content/renderer/fileapi/file_system_dispatcher.h42
-rw-r--r--chromium/content/renderer/fileapi/webfilesystem_impl.cc26
-rw-r--r--chromium/content/renderer/fileapi/webfilesystem_impl.h2
-rw-r--r--chromium/content/renderer/fileapi/webfilewriter_base.cc6
-rw-r--r--chromium/content/renderer/fileapi/webfilewriter_base.h2
-rw-r--r--chromium/content/renderer/fileapi/webfilewriter_base_unittest.cc6
-rw-r--r--chromium/content/renderer/frame_blame_context.cc4
-rw-r--r--chromium/content/renderer/frame_owner_properties.cc4
-rw-r--r--chromium/content/renderer/frame_owner_properties.h2
-rw-r--r--chromium/content/renderer/gamepad_shared_memory_reader.cc4
-rw-r--r--chromium/content/renderer/gin_browsertest.cc6
-rw-r--r--chromium/content/renderer/gpu/OWNERS3
-rw-r--r--chromium/content/renderer/gpu/actions_parser.cc8
-rw-r--r--chromium/content/renderer/gpu/compositor_dependencies.h6
-rw-r--r--chromium/content/renderer/gpu/frame_swap_message_queue.cc5
-rw-r--r--chromium/content/renderer/gpu/frame_swap_message_queue.h3
-rw-r--r--chromium/content/renderer/gpu/frame_swap_message_queue_unittest.cc1
-rw-r--r--chromium/content/renderer/gpu/gpu_benchmarking_extension.cc38
-rw-r--r--chromium/content/renderer/gpu/queue_message_swap_promise.cc7
-rw-r--r--chromium/content/renderer/gpu/queue_message_swap_promise.h3
-rw-r--r--chromium/content/renderer/gpu/queue_message_swap_promise_unittest.cc8
-rw-r--r--chromium/content/renderer/gpu/render_widget_compositor.cc107
-rw-r--r--chromium/content/renderer/gpu/render_widget_compositor.h3
-rw-r--r--chromium/content/renderer/gpu/render_widget_compositor_unittest.cc3
-rw-r--r--chromium/content/renderer/history_entry.cc3
-rw-r--r--chromium/content/renderer/history_entry.h4
-rw-r--r--chromium/content/renderer/history_serialization.cc16
-rw-r--r--chromium/content/renderer/ico_image_decoder_unittest.cc2
-rw-r--r--chromium/content/renderer/image_capture/image_capture_frame_grabber.cc10
-rw-r--r--chromium/content/renderer/image_capture/image_capture_frame_grabber.h2
-rw-r--r--chromium/content/renderer/image_downloader/image_downloader_base.cc45
-rw-r--r--chromium/content/renderer/image_downloader/image_downloader_base.h21
-rw-r--r--chromium/content/renderer/image_downloader/image_downloader_impl.cc5
-rw-r--r--chromium/content/renderer/image_downloader/single_image_downloader.cc5
-rw-r--r--chromium/content/renderer/in_process_renderer_thread.cc2
-rw-r--r--chromium/content/renderer/indexed_db/indexed_db_callbacks_impl.cc10
-rw-r--r--chromium/content/renderer/indexed_db/indexed_db_database_callbacks_impl.cc6
-rw-r--r--chromium/content/renderer/indexed_db/indexed_db_dispatcher.cc4
-rw-r--r--chromium/content/renderer/indexed_db/indexed_db_dispatcher.h4
-rw-r--r--chromium/content/renderer/indexed_db/indexed_db_key_builders.cc12
-rw-r--r--chromium/content/renderer/indexed_db/indexed_db_key_builders.h2
-rw-r--r--chromium/content/renderer/indexed_db/mock_webidbcallbacks.h12
-rw-r--r--chromium/content/renderer/indexed_db/webidbcursor_impl.cc15
-rw-r--r--chromium/content/renderer/indexed_db/webidbcursor_impl.h8
-rw-r--r--chromium/content/renderer/indexed_db/webidbcursor_impl_unittest.cc5
-rw-r--r--chromium/content/renderer/indexed_db/webidbdatabase_impl.cc28
-rw-r--r--chromium/content/renderer/indexed_db/webidbdatabase_impl.h6
-rw-r--r--chromium/content/renderer/indexed_db/webidbdatabase_impl_unittest.cc8
-rw-r--r--chromium/content/renderer/indexed_db/webidbfactory_impl.cc4
-rw-r--r--chromium/content/renderer/indexed_db/webidbfactory_impl.h6
-rw-r--r--chromium/content/renderer/input/frame_input_handler_impl.cc18
-rw-r--r--chromium/content/renderer/input/input_event_filter.cc6
-rw-r--r--chromium/content/renderer/input/input_event_filter.h3
-rw-r--r--chromium/content/renderer/input/input_event_filter_unittest.cc3
-rw-r--r--chromium/content/renderer/input/input_handler_manager.cc26
-rw-r--r--chromium/content/renderer/input/input_handler_manager.h11
-rw-r--r--chromium/content/renderer/input/input_handler_manager_client.h3
-rw-r--r--chromium/content/renderer/input/input_handler_wrapper.cc6
-rw-r--r--chromium/content/renderer/input/input_handler_wrapper.h1
-rw-r--r--chromium/content/renderer/input/main_thread_event_queue.cc17
-rw-r--r--chromium/content/renderer/input/main_thread_event_queue.h8
-rw-r--r--chromium/content/renderer/input/main_thread_event_queue_task.h4
-rw-r--r--chromium/content/renderer/input/main_thread_event_queue_unittest.cc17
-rw-r--r--chromium/content/renderer/input/render_widget_input_handler.cc28
-rw-r--r--chromium/content/renderer/input/render_widget_input_handler.h2
-rw-r--r--chromium/content/renderer/input/render_widget_input_handler_delegate.h2
-rw-r--r--chromium/content/renderer/input/scoped_web_input_event_with_latency_info.h8
-rw-r--r--chromium/content/renderer/input/widget_input_handler_impl.cc37
-rw-r--r--chromium/content/renderer/input/widget_input_handler_manager.cc39
-rw-r--r--chromium/content/renderer/input/widget_input_handler_manager.h9
-rw-r--r--chromium/content/renderer/installedapp/related_apps_fetcher.cc8
-rw-r--r--chromium/content/renderer/installedapp/related_apps_fetcher.h2
-rw-r--r--chromium/content/renderer/internal_document_state_data.cc2
-rw-r--r--chromium/content/renderer/internal_document_state_data.h2
-rw-r--r--chromium/content/renderer/java/gin_java_bridge_dispatcher.cc4
-rw-r--r--chromium/content/renderer/java/gin_java_bridge_object.cc4
-rw-r--r--chromium/content/renderer/java/gin_java_function_invocation_helper.cc1
-rw-r--r--chromium/content/renderer/loader/child_url_loader_factory_bundle.cc121
-rw-r--r--chromium/content/renderer/loader/child_url_loader_factory_bundle.h13
-rw-r--r--chromium/content/renderer/loader/ftp_directory_listing_response_delegate.cc6
-rw-r--r--chromium/content/renderer/loader/ftp_directory_listing_response_delegate.h2
-rw-r--r--chromium/content/renderer/loader/request_extra_data.cc4
-rw-r--r--chromium/content/renderer/loader/request_extra_data.h20
-rw-r--r--chromium/content/renderer/loader/resource_dispatcher.cc140
-rw-r--r--chromium/content/renderer/loader/resource_dispatcher.h52
-rw-r--r--chromium/content/renderer/loader/resource_dispatcher_unittest.cc18
-rw-r--r--chromium/content/renderer/loader/shared_memory_data_consumer_handle.h2
-rw-r--r--chromium/content/renderer/loader/shared_memory_data_consumer_handle_unittest.cc3
-rw-r--r--chromium/content/renderer/loader/site_isolation_stats_gatherer.cc256
-rw-r--r--chromium/content/renderer/loader/site_isolation_stats_gatherer.h102
-rw-r--r--chromium/content/renderer/loader/site_isolation_stats_gatherer_browsertest.cc207
-rw-r--r--chromium/content/renderer/loader/site_isolation_stats_gatherer_unittest.cc26
-rw-r--r--chromium/content/renderer/loader/sync_load_context.cc144
-rw-r--r--chromium/content/renderer/loader/sync_load_context.h67
-rw-r--r--chromium/content/renderer/loader/sync_load_response.cc5
-rw-r--r--chromium/content/renderer/loader/sync_load_response.h19
-rw-r--r--chromium/content/renderer/loader/test_request_peer.cc9
-rw-r--r--chromium/content/renderer/loader/test_request_peer.h2
-rw-r--r--chromium/content/renderer/loader/tracked_child_url_loader_factory_bundle.cc27
-rw-r--r--chromium/content/renderer/loader/tracked_child_url_loader_factory_bundle.h15
-rw-r--r--chromium/content/renderer/loader/url_loader_client_impl.cc18
-rw-r--r--chromium/content/renderer/loader/url_loader_client_impl.h15
-rw-r--r--chromium/content/renderer/loader/url_loader_client_impl_unittest.cc41
-rw-r--r--chromium/content/renderer/loader/url_response_body_consumer.cc11
-rw-r--r--chromium/content/renderer/loader/url_response_body_consumer_unittest.cc13
-rw-r--r--chromium/content/renderer/loader/web_data_consumer_handle_impl.h2
-rw-r--r--chromium/content/renderer/loader/web_data_consumer_handle_impl_unittest.cc3
-rw-r--r--chromium/content/renderer/loader/web_url_loader_impl.cc210
-rw-r--r--chromium/content/renderer/loader/web_url_loader_impl.h33
-rw-r--r--chromium/content/renderer/loader/web_url_loader_impl_unittest.cc66
-rw-r--r--chromium/content/renderer/loader/web_url_request_util.cc152
-rw-r--r--chromium/content/renderer/loader/web_url_request_util.h4
-rw-r--r--chromium/content/renderer/loader/weburlresponse_extradata_impl.h2
-rw-r--r--chromium/content/renderer/manifest/manifest_change_notifier.cc8
-rw-r--r--chromium/content/renderer/manifest/manifest_manager.cc10
-rw-r--r--chromium/content/renderer/manifest/manifest_manager.h2
-rw-r--r--chromium/content/renderer/manifest/manifest_parser.cc28
-rw-r--r--chromium/content/renderer/manifest/manifest_parser.h10
-rw-r--r--chromium/content/renderer/manifest/manifest_parser_unittest.cc108
-rw-r--r--chromium/content/renderer/media/android/media_player_renderer_client_factory.cc1
-rw-r--r--chromium/content/renderer/media/android/renderer_media_player_manager.cc16
-rw-r--r--chromium/content/renderer/media/android/renderer_media_player_manager.h7
-rw-r--r--chromium/content/renderer/media/android/stream_texture_factory.cc1
-rw-r--r--chromium/content/renderer/media/android/stream_texture_wrapper_impl_unittest.cc2
-rw-r--r--chromium/content/renderer/media/audio_decoder.cc4
-rw-r--r--chromium/content/renderer/media/audio_decoder_fuzzer.cpp45
-rw-r--r--chromium/content/renderer/media/audio_input_ipc_factory.cc1
-rw-r--r--chromium/content/renderer/media/audio_output_ipc_factory.cc4
-rw-r--r--chromium/content/renderer/media/audio_renderer_sink_cache.h2
-rw-r--r--chromium/content/renderer/media/audio_renderer_sink_cache_impl.cc3
-rw-r--r--chromium/content/renderer/media/audio_renderer_sink_cache_impl.h2
-rw-r--r--chromium/content/renderer/media/audio_renderer_sink_cache_unittest.cc163
-rw-r--r--chromium/content/renderer/media/cdm/pepper_cdm_wrapper.h51
-rw-r--r--chromium/content/renderer/media/cdm/pepper_cdm_wrapper_impl.cc98
-rw-r--r--chromium/content/renderer/media/cdm/pepper_cdm_wrapper_impl.h78
-rw-r--r--chromium/content/renderer/media/cdm/ppapi_decryptor.cc472
-rw-r--r--chromium/content/renderer/media/cdm/ppapi_decryptor.h168
-rw-r--r--chromium/content/renderer/media/cdm/render_cdm_factory.cc83
-rw-r--r--chromium/content/renderer/media/cdm/render_cdm_factory.h57
-rw-r--r--chromium/content/renderer/media/gpu/gpu_video_accelerator_factories_impl.cc108
-rw-r--r--chromium/content/renderer/media/gpu/gpu_video_accelerator_factories_impl.h25
-rw-r--r--chromium/content/renderer/media/media_factory.cc71
-rw-r--r--chromium/content/renderer/media/media_factory.h23
-rw-r--r--chromium/content/renderer/media/media_interface_factory.cc9
-rw-r--r--chromium/content/renderer/media/media_interface_factory.h3
-rw-r--r--chromium/content/renderer/media/media_permission_dispatcher.cc5
-rw-r--r--chromium/content/renderer/media/media_permission_dispatcher.h2
-rw-r--r--chromium/content/renderer/media/midi/midi_message_filter.h2
-rw-r--r--chromium/content/renderer/media/midi/renderer_webmidiaccessor_impl.h4
-rw-r--r--chromium/content/renderer/media/mojo_audio_input_ipc.cc5
-rw-r--r--chromium/content/renderer/media/mojo_audio_input_ipc.h3
-rw-r--r--chromium/content/renderer/media/mojo_audio_output_ipc.cc39
-rw-r--r--chromium/content/renderer/media/mojo_audio_output_ipc.h11
-rw-r--r--chromium/content/renderer/media/mojo_audio_output_ipc_unittest.cc61
-rw-r--r--chromium/content/renderer/media/pepper/pepper_to_video_track_adapter.cc6
-rw-r--r--chromium/content/renderer/media/pepper/pepper_to_video_track_adapter_unittest.cc9
-rw-r--r--chromium/content/renderer/media/pepper/video_track_to_pepper_adapter.cc6
-rw-r--r--chromium/content/renderer/media/pepper/video_track_to_pepper_adapter.h2
-rw-r--r--chromium/content/renderer/media/pepper/video_track_to_pepper_adapter_unittest.cc2
-rw-r--r--chromium/content/renderer/media/render_media_log.cc2
-rw-r--r--chromium/content/renderer/media/render_media_log.h4
-rw-r--r--chromium/content/renderer/media/render_media_log_unittest.cc2
-rw-r--r--chromium/content/renderer/media/renderer_webaudiodevice_impl.cc4
-rw-r--r--chromium/content/renderer/media/renderer_webaudiodevice_impl.h4
-rw-r--r--chromium/content/renderer/media/renderer_webmediaplayer_delegate.cc21
-rw-r--r--chromium/content/renderer/media/renderer_webmediaplayer_delegate.h6
-rw-r--r--chromium/content/renderer/media/renderer_webmediaplayer_delegate_browsertest.cc2
-rw-r--r--chromium/content/renderer/media/stream/apply_constraints_processor.cc41
-rw-r--r--chromium/content/renderer/media/stream/apply_constraints_processor.h9
-rw-r--r--chromium/content/renderer/media/stream/media_stream_audio_processor_options.h2
-rw-r--r--chromium/content/renderer/media/stream/media_stream_audio_processor_unittest.cc5
-rw-r--r--chromium/content/renderer/media/stream/media_stream_audio_source.cc4
-rw-r--r--chromium/content/renderer/media/stream/media_stream_audio_source.h4
-rw-r--r--chromium/content/renderer/media/stream/media_stream_audio_track.cc2
-rw-r--r--chromium/content/renderer/media/stream/media_stream_audio_unittest.cc4
-rw-r--r--chromium/content/renderer/media/stream/media_stream_center.cc16
-rw-r--r--chromium/content/renderer/media/stream/media_stream_center.h6
-rw-r--r--chromium/content/renderer/media/stream/media_stream_constraints_util.cc2
-rw-r--r--chromium/content/renderer/media/stream/media_stream_constraints_util.h6
-rw-r--r--chromium/content/renderer/media/stream/media_stream_constraints_util_audio.cc4
-rw-r--r--chromium/content/renderer/media/stream/media_stream_constraints_util_audio.h2
-rw-r--r--chromium/content/renderer/media/stream/media_stream_constraints_util_audio_unittest.cc6
-rw-r--r--chromium/content/renderer/media/stream/media_stream_constraints_util_sets.cc2
-rw-r--r--chromium/content/renderer/media/stream/media_stream_constraints_util_video_content.cc32
-rw-r--r--chromium/content/renderer/media/stream/media_stream_constraints_util_video_content.h5
-rw-r--r--chromium/content/renderer/media/stream/media_stream_constraints_util_video_content_unittest.cc9
-rw-r--r--chromium/content/renderer/media/stream/media_stream_constraints_util_video_device.cc22
-rw-r--r--chromium/content/renderer/media/stream/media_stream_constraints_util_video_device.h2
-rw-r--r--chromium/content/renderer/media/stream/media_stream_constraints_util_video_device_unittest.cc18
-rw-r--r--chromium/content/renderer/media/stream/media_stream_device_observer_unittest.cc2
-rw-r--r--chromium/content/renderer/media/stream/media_stream_registry_interface.h2
-rw-r--r--chromium/content/renderer/media/stream/media_stream_renderer_factory_impl.cc2
-rw-r--r--chromium/content/renderer/media/stream/media_stream_source.h2
-rw-r--r--chromium/content/renderer/media/stream/media_stream_track.h2
-rw-r--r--chromium/content/renderer/media/stream/media_stream_video_capturer_source.cc2
-rw-r--r--chromium/content/renderer/media/stream/media_stream_video_capturer_source_unittest.cc4
-rw-r--r--chromium/content/renderer/media/stream/media_stream_video_renderer_sink.h2
-rw-r--r--chromium/content/renderer/media/stream/media_stream_video_renderer_sink_unittest.cc4
-rw-r--r--chromium/content/renderer/media/stream/media_stream_video_source.h6
-rw-r--r--chromium/content/renderer/media/stream/media_stream_video_source_unittest.cc14
-rw-r--r--chromium/content/renderer/media/stream/media_stream_video_track.cc1
-rw-r--r--chromium/content/renderer/media/stream/media_stream_video_track.h2
-rw-r--r--chromium/content/renderer/media/stream/media_stream_video_track_unittest.cc8
-rw-r--r--chromium/content/renderer/media/stream/mock_constraint_factory.h2
-rw-r--r--chromium/content/renderer/media/stream/mock_media_stream_registry.cc8
-rw-r--r--chromium/content/renderer/media/stream/processed_local_audio_source.h2
-rw-r--r--chromium/content/renderer/media/stream/processed_local_audio_source_unittest.cc4
-rw-r--r--chromium/content/renderer/media/stream/remote_media_stream_track_adapter.cc2
-rw-r--r--chromium/content/renderer/media/stream/remote_media_stream_track_adapter.h4
-rw-r--r--chromium/content/renderer/media/stream/track_audio_renderer.h2
-rw-r--r--chromium/content/renderer/media/stream/user_media_client_impl.cc44
-rw-r--r--chromium/content/renderer/media/stream/user_media_client_impl.h18
-rw-r--r--chromium/content/renderer/media/stream/user_media_client_impl_unittest.cc48
-rw-r--r--chromium/content/renderer/media/stream/user_media_processor.cc102
-rw-r--r--chromium/content/renderer/media/stream/user_media_processor.h21
-rw-r--r--chromium/content/renderer/media/stream/video_track_adapter.cc4
-rw-r--r--chromium/content/renderer/media/stream/webaudio_media_stream_source.h6
-rw-r--r--chromium/content/renderer/media/stream/webmediaplayer_ms.cc157
-rw-r--r--chromium/content/renderer/media/stream/webmediaplayer_ms.h10
-rw-r--r--chromium/content/renderer/media/stream/webmediaplayer_ms_compositor.cc40
-rw-r--r--chromium/content/renderer/media/stream/webmediaplayer_ms_compositor.h3
-rw-r--r--chromium/content/renderer/media/stream/webmediaplayer_ms_unittest.cc105
-rw-r--r--chromium/content/renderer/media/video_capture_impl.cc4
-rw-r--r--chromium/content/renderer/media/video_capture_impl.h2
-rw-r--r--chromium/content/renderer/media/video_capture_impl_manager_unittest.cc24
-rw-r--r--chromium/content/renderer/media/video_capture_impl_unittest.cc4
-rw-r--r--chromium/content/renderer/media/web_media_element_source_utils.cc6
-rw-r--r--chromium/content/renderer/media/webrtc/media_stream_remote_video_source.cc7
-rw-r--r--chromium/content/renderer/media/webrtc/media_stream_remote_video_source.h2
-rw-r--r--chromium/content/renderer/media/webrtc/media_stream_remote_video_source_unittest.cc8
-rw-r--r--chromium/content/renderer/media/webrtc/media_stream_track_metrics.cc26
-rw-r--r--chromium/content/renderer/media/webrtc/media_stream_track_metrics.h5
-rw-r--r--chromium/content/renderer/media/webrtc/media_stream_video_webrtc_sink.h2
-rw-r--r--chromium/content/renderer/media/webrtc/media_stream_video_webrtc_sink_unittest.cc2
-rw-r--r--chromium/content/renderer/media/webrtc/mock_peer_connection_dependency_factory.cc25
-rw-r--r--chromium/content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h21
-rw-r--r--chromium/content/renderer/media/webrtc/mock_peer_connection_impl.cc20
-rw-r--r--chromium/content/renderer/media/webrtc/mock_peer_connection_impl.h6
-rw-r--r--chromium/content/renderer/media/webrtc/mock_web_rtc_peer_connection_handler_client.cc6
-rw-r--r--chromium/content/renderer/media/webrtc/mock_web_rtc_peer_connection_handler_client.h8
-rw-r--r--chromium/content/renderer/media/webrtc/peer_connection_dependency_factory.cc30
-rw-r--r--chromium/content/renderer/media/webrtc/peer_connection_dependency_factory_unittest.cc4
-rw-r--r--chromium/content/renderer/media/webrtc/peer_connection_tracker.cc27
-rw-r--r--chromium/content/renderer/media/webrtc/peer_connection_tracker.h6
-rw-r--r--chromium/content/renderer/media/webrtc/peer_connection_tracker_unittest.cc6
-rw-r--r--chromium/content/renderer/media/webrtc/rtc_certificate.h2
-rw-r--r--chromium/content/renderer/media/webrtc/rtc_certificate_generator.cc7
-rw-r--r--chromium/content/renderer/media/webrtc/rtc_certificate_generator.h6
-rw-r--r--chromium/content/renderer/media/webrtc/rtc_data_channel_handler.h4
-rw-r--r--chromium/content/renderer/media/webrtc/rtc_data_channel_handler_unittest.cc2
-rw-r--r--chromium/content/renderer/media/webrtc/rtc_dtmf_sender_handler.h4
-rw-r--r--chromium/content/renderer/media/webrtc/rtc_error.cc61
-rw-r--r--chromium/content/renderer/media/webrtc/rtc_error.h21
-rw-r--r--chromium/content/renderer/media/webrtc/rtc_peer_connection_handler.cc239
-rw-r--r--chromium/content/renderer/media/webrtc/rtc_peer_connection_handler.h12
-rw-r--r--chromium/content/renderer/media/webrtc/rtc_peer_connection_handler_unittest.cc65
-rw-r--r--chromium/content/renderer/media/webrtc/rtc_rtp_contributing_source.h2
-rw-r--r--chromium/content/renderer/media/webrtc/rtc_rtp_parameters.cc158
-rw-r--r--chromium/content/renderer/media/webrtc/rtc_rtp_parameters.h33
-rw-r--r--chromium/content/renderer/media/webrtc/rtc_rtp_parameters_unittest.cc165
-rw-r--r--chromium/content/renderer/media/webrtc/rtc_rtp_receiver.cc207
-rw-r--r--chromium/content/renderer/media/webrtc/rtc_rtp_receiver.h28
-rw-r--r--chromium/content/renderer/media/webrtc/rtc_rtp_receiver_unittest.cc174
-rw-r--r--chromium/content/renderer/media/webrtc/rtc_rtp_sender.cc103
-rw-r--r--chromium/content/renderer/media/webrtc/rtc_rtp_sender.h22
-rw-r--r--chromium/content/renderer/media/webrtc/rtc_rtp_sender_unittest.cc93
-rw-r--r--chromium/content/renderer/media/webrtc/rtc_stats.cc40
-rw-r--r--chromium/content/renderer/media/webrtc/rtc_stats.h30
-rw-r--r--chromium/content/renderer/media/webrtc/rtc_video_decoder_unittest.cc2
-rw-r--r--chromium/content/renderer/media/webrtc/rtc_video_encoder_factory.cc2
-rw-r--r--chromium/content/renderer/media/webrtc/rtc_video_encoder_unittest.cc1
-rw-r--r--chromium/content/renderer/media/webrtc/test/webrtc_stats_report_obtainer.cc40
-rw-r--r--chromium/content/renderer/media/webrtc/test/webrtc_stats_report_obtainer.h58
-rw-r--r--chromium/content/renderer/media/webrtc/webrtc_audio_device_impl.h4
-rw-r--r--chromium/content/renderer/media/webrtc/webrtc_audio_renderer.cc5
-rw-r--r--chromium/content/renderer/media/webrtc/webrtc_audio_renderer.h2
-rw-r--r--chromium/content/renderer/media/webrtc/webrtc_audio_renderer_unittest.cc8
-rw-r--r--chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter.cc7
-rw-r--r--chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter.h2
-rw-r--r--chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter_map.cc4
-rw-r--r--chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter_map.h2
-rw-r--r--chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter_map_unittest.cc14
-rw-r--r--chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter_unittest.cc20
-rw-r--r--chromium/content/renderer/media/webrtc/webrtc_media_stream_track_adapter.cc5
-rw-r--r--chromium/content/renderer/media/webrtc/webrtc_media_stream_track_adapter.h4
-rw-r--r--chromium/content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map.h2
-rw-r--r--chromium/content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map_unittest.cc10
-rw-r--r--chromium/content/renderer/media/webrtc/webrtc_media_stream_track_adapter_unittest.cc10
-rw-r--r--chromium/content/renderer/media/webrtc/webrtc_set_remote_description_observer_unittest.cc4
-rw-r--r--chromium/content/renderer/media/webrtc/webrtc_uma_histograms.cc24
-rw-r--r--chromium/content/renderer/media/webrtc/webrtc_uma_histograms.h25
-rw-r--r--chromium/content/renderer/media/webrtc/webrtc_uma_histograms_unittest.cc46
-rw-r--r--chromium/content/renderer/media/webrtc/webrtc_video_capturer_adapter.h2
-rw-r--r--chromium/content/renderer/media/webrtc_local_audio_source_provider.cc6
-rw-r--r--chromium/content/renderer/media/webrtc_local_audio_source_provider.h6
-rw-r--r--chromium/content/renderer/media/webrtc_local_audio_source_provider_unittest.cc6
-rw-r--r--chromium/content/renderer/media_capture_from_element/canvas_capture_handler.cc11
-rw-r--r--chromium/content/renderer/media_capture_from_element/canvas_capture_handler.h6
-rw-r--r--chromium/content/renderer/media_capture_from_element/canvas_capture_handler_unittest.cc10
-rw-r--r--chromium/content/renderer/media_capture_from_element/html_audio_element_capturer_source.cc2
-rw-r--r--chromium/content/renderer/media_capture_from_element/html_audio_element_capturer_source_unittest.cc10
-rw-r--r--chromium/content/renderer/media_capture_from_element/html_video_element_capturer_source.cc8
-rw-r--r--chromium/content/renderer/media_capture_from_element/html_video_element_capturer_source.h2
-rw-r--r--chromium/content/renderer/media_capture_from_element/html_video_element_capturer_source_unittest.cc10
-rw-r--r--chromium/content/renderer/media_recorder/audio_track_recorder.h2
-rw-r--r--chromium/content/renderer/media_recorder/audio_track_recorder_unittest.cc10
-rw-r--r--chromium/content/renderer/media_recorder/h264_encoder.h2
-rw-r--r--chromium/content/renderer/media_recorder/media_recorder_handler.cc10
-rw-r--r--chromium/content/renderer/media_recorder/media_recorder_handler.h4
-rw-r--r--chromium/content/renderer/media_recorder/media_recorder_handler_unittest.cc24
-rw-r--r--chromium/content/renderer/media_recorder/video_track_recorder.cc1
-rw-r--r--chromium/content/renderer/media_recorder/video_track_recorder.h4
-rw-r--r--chromium/content/renderer/media_recorder/video_track_recorder_unittest.cc16
-rw-r--r--chromium/content/renderer/media_recorder/vpx_encoder.h6
-rw-r--r--chromium/content/renderer/mojo/blink_interface_provider_impl.h2
-rw-r--r--chromium/content/renderer/mojo/blink_interface_registry_impl.h2
-rw-r--r--chromium/content/renderer/mouse_lock_dispatcher.cc2
-rw-r--r--chromium/content/renderer/mouse_lock_dispatcher_browsertest.cc2
-rw-r--r--chromium/content/renderer/mus/BUILD.gn2
-rw-r--r--chromium/content/renderer/mus/mus_embedded_frame.cc3
-rw-r--r--chromium/content/renderer/mus/render_widget_window_tree_client_factory.cc1
-rw-r--r--chromium/content/renderer/mus/renderer_window_tree_client.cc39
-rw-r--r--chromium/content/renderer/mus/renderer_window_tree_client.h11
-rw-r--r--chromium/content/renderer/net_info_helper.h2
-rw-r--r--chromium/content/renderer/notifications/notification_data_conversions.cc10
-rw-r--r--chromium/content/renderer/notifications/notification_data_conversions.h2
-rw-r--r--chromium/content/renderer/notifications/notification_data_conversions_unittest.cc6
-rw-r--r--chromium/content/renderer/notifications/notification_dispatcher.cc6
-rw-r--r--chromium/content/renderer/notifications/notification_dispatcher.h4
-rw-r--r--chromium/content/renderer/notifications/notification_manager.cc4
-rw-r--r--chromium/content/renderer/notifications/notification_manager.h2
-rw-r--r--chromium/content/renderer/origin_trials/web_trial_token_validator_impl.cc4
-rw-r--r--chromium/content/renderer/origin_trials/web_trial_token_validator_impl.h2
-rw-r--r--chromium/content/renderer/p2p/ipc_network_manager.cc12
-rw-r--r--chromium/content/renderer/p2p/ipc_network_manager_unittest.cc48
-rw-r--r--chromium/content/renderer/pepper/OWNERS1
-rw-r--r--chromium/content/renderer/pepper/content_decryptor_delegate.cc1318
-rw-r--r--chromium/content/renderer/pepper/content_decryptor_delegate.h261
-rw-r--r--chromium/content/renderer/pepper/content_renderer_pepper_host_factory.cc8
-rw-r--r--chromium/content/renderer/pepper/event_conversion.cc10
-rw-r--r--chromium/content/renderer/pepper/event_conversion.h2
-rw-r--r--chromium/content/renderer/pepper/host_array_buffer_var.h2
-rw-r--r--chromium/content/renderer/pepper/host_dispatcher_wrapper.cc4
-rw-r--r--chromium/content/renderer/pepper/host_globals.cc15
-rw-r--r--chromium/content/renderer/pepper/host_globals.h2
-rw-r--r--chromium/content/renderer/pepper/message_channel.cc4
-rw-r--r--chromium/content/renderer/pepper/message_channel.h2
-rw-r--r--chromium/content/renderer/pepper/pepper_compositor_host.cc7
-rw-r--r--chromium/content/renderer/pepper/pepper_file_chooser_host.cc6
-rw-r--r--chromium/content/renderer/pepper/pepper_file_system_host.cc6
-rw-r--r--chromium/content/renderer/pepper/pepper_graphics_2d_host.cc57
-rw-r--r--chromium/content/renderer/pepper/pepper_graphics_2d_host.h26
-rw-r--r--chromium/content/renderer/pepper/pepper_media_device_manager.cc9
-rw-r--r--chromium/content/renderer/pepper/pepper_media_device_manager.h11
-rw-r--r--chromium/content/renderer/pepper/pepper_media_stream_audio_track_host.h2
-rw-r--r--chromium/content/renderer/pepper/pepper_media_stream_video_track_host.h2
-rw-r--r--chromium/content/renderer/pepper/pepper_plugin_instance_impl.cc217
-rw-r--r--chromium/content/renderer/pepper/pepper_plugin_instance_impl.h74
-rw-r--r--chromium/content/renderer/pepper/pepper_plugin_registry.cc19
-rw-r--r--chromium/content/renderer/pepper/pepper_plugin_registry.h19
-rw-r--r--chromium/content/renderer/pepper/pepper_url_loader_host.cc35
-rw-r--r--chromium/content/renderer/pepper/pepper_url_loader_host.h2
-rw-r--r--chromium/content/renderer/pepper/pepper_url_request_unittest.cc8
-rw-r--r--chromium/content/renderer/pepper/pepper_video_encoder_host.cc1
-rw-r--r--chromium/content/renderer/pepper/pepper_webplugin_impl.cc28
-rw-r--r--chromium/content/renderer/pepper/pepper_webplugin_impl.h2
-rw-r--r--chromium/content/renderer/pepper/pepper_webplugin_impl_browsertest.cc2
-rw-r--r--chromium/content/renderer/pepper/pepper_websocket_host.cc10
-rw-r--r--chromium/content/renderer/pepper/pepper_websocket_host.h4
-rw-r--r--chromium/content/renderer/pepper/plugin_instance_throttler_impl.cc12
-rw-r--r--chromium/content/renderer/pepper/plugin_instance_throttler_impl_unittest.cc6
-rw-r--r--chromium/content/renderer/pepper/plugin_module.cc11
-rw-r--r--chromium/content/renderer/pepper/plugin_module.h10
-rw-r--r--chromium/content/renderer/pepper/plugin_power_saver_helper.cc2
-rw-r--r--chromium/content/renderer/pepper/plugin_power_saver_helper_browsertest.cc6
-rw-r--r--chromium/content/renderer/pepper/ppb_broker_impl.cc4
-rw-r--r--chromium/content/renderer/pepper/ppb_flash_message_loop_impl.cc2
-rw-r--r--chromium/content/renderer/pepper/ppb_graphics_3d_impl.cc10
-rw-r--r--chromium/content/renderer/pepper/ppb_image_data_impl.cc1
-rw-r--r--chromium/content/renderer/pepper/ppb_var_deprecated_impl.cc10
-rw-r--r--chromium/content/renderer/pepper/renderer_ppapi_host_impl.cc8
-rw-r--r--chromium/content/renderer/pepper/resource_converter.cc14
-rw-r--r--chromium/content/renderer/pepper/resource_creation_impl.cc10
-rw-r--r--chromium/content/renderer/pepper/resource_creation_impl.h2
-rw-r--r--chromium/content/renderer/pepper/url_request_info_util.cc20
-rw-r--r--chromium/content/renderer/pepper/url_response_info_util.cc10
-rw-r--r--chromium/content/renderer/pepper/v8_var_converter.cc4
-rw-r--r--chromium/content/renderer/pepper/video_decoder_shim.cc14
-rw-r--r--chromium/content/renderer/presentation/presentation_dispatcher.cc4
-rw-r--r--chromium/content/renderer/presentation/presentation_dispatcher.h2
-rw-r--r--chromium/content/renderer/push_messaging/push_messaging_client.cc16
-rw-r--r--chromium/content/renderer/push_messaging/push_messaging_client.h4
-rw-r--r--chromium/content/renderer/push_messaging/push_provider.cc6
-rw-r--r--chromium/content/renderer/push_messaging/push_provider.h4
-rw-r--r--chromium/content/renderer/render_frame_impl.cc628
-rw-r--r--chromium/content/renderer/render_frame_impl.h119
-rw-r--r--chromium/content/renderer/render_frame_impl_browsertest.cc84
-rw-r--r--chromium/content/renderer/render_frame_metadata_observer_impl.cc62
-rw-r--r--chromium/content/renderer/render_frame_metadata_observer_impl.h16
-rw-r--r--chromium/content/renderer/render_frame_proxy.cc90
-rw-r--r--chromium/content/renderer/render_frame_proxy.h34
-rw-r--r--chromium/content/renderer/render_process_impl.cc46
-rw-r--r--chromium/content/renderer/render_thread_impl.cc274
-rw-r--r--chromium/content/renderer/render_thread_impl.h50
-rw-r--r--chromium/content/renderer/render_thread_impl_browsertest.cc97
-rw-r--r--chromium/content/renderer/render_thread_impl_discardable_memory_browsertest.cc32
-rw-r--r--chromium/content/renderer/render_view_browsertest.cc111
-rw-r--r--chromium/content/renderer/render_view_browsertest_mac.mm6
-rw-r--r--chromium/content/renderer/render_view_fuchsia.cc2
-rw-r--r--chromium/content/renderer/render_view_impl.cc342
-rw-r--r--chromium/content/renderer/render_view_impl.h53
-rw-r--r--chromium/content/renderer/render_view_impl_android.cc2
-rw-r--r--chromium/content/renderer/render_view_linux.cc2
-rw-r--r--chromium/content/renderer/render_view_win.cc4
-rw-r--r--chromium/content/renderer/render_widget.cc177
-rw-r--r--chromium/content/renderer/render_widget.h92
-rw-r--r--chromium/content/renderer/render_widget_browsertest.cc9
-rw-r--r--chromium/content/renderer/render_widget_fullscreen_pepper.cc29
-rw-r--r--chromium/content/renderer/render_widget_fullscreen_pepper.h2
-rw-r--r--chromium/content/renderer/render_widget_mouse_lock_dispatcher.cc8
-rw-r--r--chromium/content/renderer/render_widget_unittest.cc23
-rw-r--r--chromium/content/renderer/renderer_blink_platform_impl.cc172
-rw-r--r--chromium/content/renderer/renderer_blink_platform_impl.h28
-rw-r--r--chromium/content/renderer/renderer_main.cc55
-rw-r--r--chromium/content/renderer/renderer_main_platform_delegate_android.cc3
-rw-r--r--chromium/content/renderer/renderer_main_platform_delegate_win.cc4
-rw-r--r--chromium/content/renderer/renderer_webapplicationcachehost_impl.cc6
-rw-r--r--chromium/content/renderer/renderer_webcookiejar_impl.h2
-rw-r--r--chromium/content/renderer/resource_timing_info_conversions.cc6
-rw-r--r--chromium/content/renderer/resource_timing_info_conversions.h2
-rw-r--r--chromium/content/renderer/sad_plugin.h2
-rw-r--r--chromium/content/renderer/savable_resources.cc18
-rw-r--r--chromium/content/renderer/savable_resources.h2
-rw-r--r--chromium/content/renderer/savable_resources_browsertest.cc4
-rw-r--r--chromium/content/renderer/scheduler/OWNERS6
-rw-r--r--chromium/content/renderer/service_worker/controller_service_worker_connector.cc8
-rw-r--r--chromium/content/renderer/service_worker/controller_service_worker_connector.h4
-rw-r--r--chromium/content/renderer/service_worker/embedded_worker_instance_client_impl.cc29
-rw-r--r--chromium/content/renderer/service_worker/embedded_worker_instance_client_impl.h11
-rw-r--r--chromium/content/renderer/service_worker/service_worker_context_client.cc94
-rw-r--r--chromium/content/renderer/service_worker/service_worker_context_client.h26
-rw-r--r--chromium/content/renderer/service_worker/service_worker_context_client_unittest.cc60
-rw-r--r--chromium/content/renderer/service_worker/service_worker_dispatcher.cc24
-rw-r--r--chromium/content/renderer/service_worker/service_worker_dispatcher.h21
-rw-r--r--chromium/content/renderer/service_worker/service_worker_dispatcher_unittest.cc11
-rw-r--r--chromium/content/renderer/service_worker/service_worker_fetch_context_impl.cc17
-rw-r--r--chromium/content/renderer/service_worker/service_worker_fetch_context_impl.h16
-rw-r--r--chromium/content/renderer/service_worker/service_worker_message_filter.cc10
-rw-r--r--chromium/content/renderer/service_worker/service_worker_message_filter.h4
-rw-r--r--chromium/content/renderer/service_worker/service_worker_network_provider.cc182
-rw-r--r--chromium/content/renderer/service_worker/service_worker_network_provider.h47
-rw-r--r--chromium/content/renderer/service_worker/service_worker_provider_context.cc27
-rw-r--r--chromium/content/renderer/service_worker/service_worker_provider_context.h16
-rw-r--r--chromium/content/renderer/service_worker/service_worker_provider_context_unittest.cc88
-rw-r--r--chromium/content/renderer/service_worker/service_worker_subresource_loader.cc99
-rw-r--r--chromium/content/renderer/service_worker/service_worker_subresource_loader.h35
-rw-r--r--chromium/content/renderer/service_worker/service_worker_subresource_loader_unittest.cc110
-rw-r--r--chromium/content/renderer/service_worker/service_worker_timeout_timer.cc7
-rw-r--r--chromium/content/renderer/service_worker/service_worker_timeout_timer.h5
-rw-r--r--chromium/content/renderer/service_worker/service_worker_timeout_timer_unittest.cc8
-rw-r--r--chromium/content/renderer/service_worker/service_worker_type_converters.h10
-rw-r--r--chromium/content/renderer/service_worker/service_worker_type_util.cc9
-rw-r--r--chromium/content/renderer/service_worker/thread_safe_script_container.h2
-rw-r--r--chromium/content/renderer/service_worker/web_service_worker_impl.cc32
-rw-r--r--chromium/content/renderer/service_worker/web_service_worker_impl.h20
-rw-r--r--chromium/content/renderer/service_worker/web_service_worker_installed_scripts_manager_impl.cc2
-rw-r--r--chromium/content/renderer/service_worker/web_service_worker_installed_scripts_manager_impl.h4
-rw-r--r--chromium/content/renderer/service_worker/web_service_worker_provider_impl.cc17
-rw-r--r--chromium/content/renderer/service_worker/web_service_worker_provider_impl.h15
-rw-r--r--chromium/content/renderer/service_worker/web_service_worker_registration_impl.cc7
-rw-r--r--chromium/content/renderer/service_worker/web_service_worker_registration_impl.h8
-rw-r--r--chromium/content/renderer/service_worker/worker_fetch_context_impl.cc43
-rw-r--r--chromium/content/renderer/service_worker/worker_fetch_context_impl.h29
-rw-r--r--chromium/content/renderer/shared_worker/embedded_shared_worker_stub.cc124
-rw-r--r--chromium/content/renderer/shared_worker/embedded_shared_worker_stub.h47
-rw-r--r--chromium/content/renderer/shared_worker/shared_worker_client_impl.cc2
-rw-r--r--chromium/content/renderer/shared_worker/shared_worker_client_impl.h2
-rw-r--r--chromium/content/renderer/shared_worker/shared_worker_factory_impl.cc9
-rw-r--r--chromium/content/renderer/shared_worker/shared_worker_factory_impl.h6
-rw-r--r--chromium/content/renderer/shared_worker/shared_worker_repository.cc2
-rw-r--r--chromium/content/renderer/shared_worker/shared_worker_repository.h4
-rw-r--r--chromium/content/renderer/skia_benchmarking_extension.cc8
-rw-r--r--chromium/content/renderer/speech_recognition_dispatcher.cc70
-rw-r--r--chromium/content/renderer/speech_recognition_dispatcher.h30
-rw-r--r--chromium/content/renderer/stats_collection_controller.cc7
-rw-r--r--chromium/content/renderer/storage_util.cc4
-rw-r--r--chromium/content/renderer/text_input_client_observer.cc14
-rw-r--r--chromium/content/renderer/text_input_client_observer.h2
-rw-r--r--chromium/content/renderer/v8_value_converter_impl.cc5
-rw-r--r--chromium/content/renderer/v8_value_converter_impl_unittest.cc1
-rw-r--r--chromium/content/renderer/web_database_observer_impl.cc4
-rw-r--r--chromium/content/renderer/web_database_observer_impl.h4
-rw-r--r--chromium/content/renderer/web_frame_utils.cc6
-rw-r--r--chromium/content/renderer/web_ui_extension.cc17
-rw-r--r--chromium/content/renderer/webfileutilities_impl.cc8
-rw-r--r--chromium/content/renderer/webfileutilities_impl.h4
-rw-r--r--chromium/content/renderer/webgraphicscontext3d_provider_impl.cc7
-rw-r--r--chromium/content/renderer/webgraphicscontext3d_provider_impl.h3
-rw-r--r--chromium/content/renderer/webpublicsuffixlist_impl.h2
-rw-r--r--chromium/content/renderer/webscrollbarbehavior_impl_aura.cc4
-rw-r--r--chromium/content/renderer/webscrollbarbehavior_impl_aura.h2
-rw-r--r--chromium/content/renderer/webscrollbarbehavior_impl_mac.h2
-rw-r--r--chromium/content/renderer/worker_thread_message_filter.cc8
-rw-r--r--chromium/content/renderer/worker_thread_message_filter.h4
-rw-r--r--chromium/content/shell/BUILD.gn70
-rw-r--r--chromium/content/shell/android/BUILD.gn12
-rw-r--r--chromium/content/shell/common/layout_test.mojom24
-rw-r--r--chromium/content/shell/common/layout_test/OWNERS2
-rw-r--r--chromium/content/shell/common/layout_test/fake_bluetooth_chooser.mojom68
-rw-r--r--chromium/content/shell/common/layout_test/layout_test_messages.h7
-rw-r--r--chromium/content/shell/common/shell_content_client.cc2
-rw-r--r--chromium/content/shell/common/shell_messages.h18
-rw-r--r--chromium/content/shell/common/shell_switches.cc4
-rw-r--r--chromium/content/shell/common/shell_switches.h1
-rw-r--r--chromium/content/shell/shell_resources.grd1
-rw-r--r--chromium/content/shell/test_runner/BUILD.gn13
-rw-r--r--chromium/content/test/BUILD.gn148
-rw-r--r--chromium/content/test/fuzzer/BUILD.gn65
-rw-r--r--chromium/content/utility/BUILD.gn10
-rw-r--r--chromium/content/utility/utility_blink_platform_impl.cc2
-rw-r--r--chromium/content/utility/utility_blink_platform_with_sandbox_support_impl.cc120
-rw-r--r--chromium/content/utility/utility_blink_platform_with_sandbox_support_impl.h42
-rw-r--r--chromium/content/utility/utility_service_factory.cc2
-rw-r--r--chromium/content/utility/utility_thread_impl.cc45
-rw-r--r--chromium/content/utility/utility_thread_impl.h21
-rw-r--r--chromium/content/zygote/zygote_main_linux.cc120
2313 files changed, 51826 insertions, 55228 deletions
diff --git a/chromium/content/BUILD.gn b/chromium/content/BUILD.gn
index 20929097aab..7c567481db6 100644
--- a/chromium/content/BUILD.gn
+++ b/chromium/content/BUILD.gn
@@ -4,7 +4,7 @@
import("//tools/grit/grit_rule.gni")
import("//build/config/nacl/config.gni")
-import("//ppapi/features/features.gni")
+import("//ppapi/buildflags/buildflags.gni")
# Applied by targets internal to content.
config("content_implementation") {
@@ -100,8 +100,8 @@ if (is_component_build) {
set_sources_assignment_filter(sources_assignment_filter)
deps = [
"//base",
- "//media:media_features",
- "//sandbox:sandbox_features",
+ "//media:media_buildflags",
+ "//sandbox:sandbox_buildflags",
"//sandbox/linux:sandbox",
"//services/service_manager/sandbox",
]
diff --git a/chromium/content/DEPS b/chromium/content/DEPS
index ec5951a2f87..c11b886fbd6 100644
--- a/chromium/content/DEPS
+++ b/chromium/content/DEPS
@@ -19,13 +19,15 @@ include_rules = [
"-components",
# Content can depend on components that are:
# 1) related to the implementation of the web platform
- # 2) shared code between third_party/WebKit and content
+ # 2) shared code between third_party/blink and content
# It should not depend on chrome features or implementation details, i.e. the
# original components/ directories which was code split out from chrome/ to be
# shared with iOS. This includes, but isn't limited to, browser features such
# as autofill or extensions, and chrome implementation details such as
# settings, packaging details, installation or crash reporting.
+ "+components/services/filesystem",
+
"+crypto",
"+grit/blink_resources.h",
"+grit/content_strings.h",
@@ -74,7 +76,7 @@ include_rules = [
"+third_party/webrtc",
"+third_party/webrtc_overrides",
"+third_party/zlib/google",
- "+third_party/WebKit/public",
+ "+third_party/blink/public",
"+ui/accelerated_widget_mac",
"+ui/accessibility",
@@ -119,7 +121,7 @@ include_rules = [
]
specific_include_rules = {
- ".*_browsertest[a-z_]*\.(cc|h)": [
+ ".*_browsertest[a-z_]*\.(cc|h|mm)": [
# content -> content/shell dependency is disallowed, except browser tests.
"+content/shell/browser",
"+content/shell/common",
diff --git a/chromium/content/OWNERS b/chromium/content/OWNERS
index 0b7cd022292..53d2f572750 100644
--- a/chromium/content/OWNERS
+++ b/chromium/content/OWNERS
@@ -17,6 +17,10 @@ piman@chromium.org
# structural changes, please get a review from a reviewer in this file.
per-file BUILD.gn=*
+# For threading (BrowserThread, BrowserMainLoop, TaskScheduler, etc.)
+per-file *browser_main_loop*=gab@chromium.org
+per-file *browser_thread*=gab@chromium.org
+
# Mac Sandbox profiles.
per-file *.sb=set noparent
per-file *.sb=rsesek@chromium.org
diff --git a/chromium/content/app/BUILD.gn b/chromium/content/app/BUILD.gn
index e2f66c5a431..8d8f2826384 100644
--- a/chromium/content/app/BUILD.gn
+++ b/chromium/content/app/BUILD.gn
@@ -4,7 +4,7 @@
import("//build/config/chrome_build.gni")
import("//build/config/features.gni")
-import("//ppapi/features/features.gni")
+import("//ppapi/buildflags/buildflags.gni")
# Implements "content_main" given the defines and visibility. On Windows this
# is compiled with a different define for browser and child, but all code needs
@@ -32,8 +32,8 @@ template("implement_content_app") {
"//services/service_manager/embedder",
"//services/service_manager/public/mojom",
"//services/service_manager/runner/common",
- "//mojo/edk/system",
- "//ppapi/features",
+ "//mojo/edk",
+ "//ppapi/buildflags",
"//ui/base",
"//ui/gfx",
"//ui/gfx/geometry",
@@ -53,7 +53,6 @@ template("implement_content_app") {
"//device/bluetooth",
"//device/gamepad",
"//device/geolocation",
- "//device/sensors",
"//device/usb",
"//gpu",
"//media",
@@ -68,7 +67,7 @@ template("implement_content_app") {
]
}
- if (is_linux && enable_plugins) {
+ if (!is_multi_dll_chrome && enable_plugins) {
content_app_deps += [ "//content/ppapi_plugin:ppapi_plugin_sources" ]
}
diff --git a/chromium/content/app/DEPS b/chromium/content/app/DEPS
index b562b5a3061..1020b8e9075 100644
--- a/chromium/content/app/DEPS
+++ b/chromium/content/app/DEPS
@@ -4,7 +4,6 @@ include_rules = [
"+device/bluetooth",
"+device/gamepad",
"+device/geolocation",
- "+device/sensors",
"+device/usb",
# For loading V8's initial snapshot from external files.
"+gin/public/isolate_holder.h",
diff --git a/chromium/content/app/OWNERS b/chromium/content/app/OWNERS
index 92c84d9e8a8..66daea88ea2 100644
--- a/chromium/content/app/OWNERS
+++ b/chromium/content/app/OWNERS
@@ -1,2 +1,3 @@
jcivelli@chromium.org
rockot@chromium.org
+per-file sandbox_helper_win.cc=file://sandbox/win/OWNERS
diff --git a/chromium/content/app/android/content_child_process_service_delegate.cc b/chromium/content/app/android/content_child_process_service_delegate.cc
index 0204ab95503..e1952b748fd 100644
--- a/chromium/content/app/android/content_child_process_service_delegate.cc
+++ b/chromium/content/app/android/content_child_process_service_delegate.cc
@@ -114,7 +114,7 @@ void JNI_ContentChildProcessServiceDelegate_InternalInitChildProcess(
gpu::ScopedSurfaceRequestConduit::SetInstance(
g_child_process_surface_manager.Pointer());
- base::android::MemoryPressureListenerAndroid::RegisterSystemCallback(env);
+ base::android::MemoryPressureListenerAndroid::Initialize(env);
}
} // namespace
diff --git a/chromium/content/app/android/content_main.cc b/chromium/content/app/android/content_main.cc
index 664f0464833..fbd2b1b1677 100644
--- a/chromium/content/app/android/content_main.cc
+++ b/chromium/content/app/android/content_main.cc
@@ -5,7 +5,6 @@
#include <memory>
#include "base/lazy_instance.h"
-#include "base/memory/ptr_util.h"
#include "base/trace_event/trace_event.h"
#include "content/app/content_service_manager_main_delegate.h"
#include "content/public/app/content_main.h"
diff --git a/chromium/content/app/android/library_loader_hooks.cc b/chromium/content/app/android/library_loader_hooks.cc
index 9db1995783d..82f5c7aeed8 100644
--- a/chromium/content/app/android/library_loader_hooks.cc
+++ b/chromium/content/app/android/library_loader_hooks.cc
@@ -14,7 +14,7 @@ namespace content {
bool LibraryLoaded(JNIEnv* env, jclass clazz) {
// Enable startup tracing asap to avoid early TRACE_EVENT calls being ignored.
- tracing::EnableStartupTracingIfNeeded(true /* can_access_file_system */);
+ tracing::EnableStartupTracingIfNeeded();
// Android's main browser loop is custom so we set the browser
// name here as early as possible.
diff --git a/chromium/content/app/content_main_runner.cc b/chromium/content/app/content_main_runner.cc
index 00864253f7c..d1e6e7d28d4 100644
--- a/chromium/content/app/content_main_runner.cc
+++ b/chromium/content/app/content_main_runner.cc
@@ -52,15 +52,17 @@
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
#include "content/public/common/sandbox_init.h"
-#include "content/public/common/zygote_features.h"
+#include "content/public/common/zygote_buildflags.h"
#include "gin/v8_initializer.h"
#include "media/base/media.h"
-#include "media/media_features.h"
-#include "ppapi/features/features.h"
+#include "media/media_buildflags.h"
+#include "ppapi/buildflags/buildflags.h"
#include "services/service_manager/embedder/switches.h"
#include "services/service_manager/sandbox/sandbox_type.h"
#include "ui/base/ui_base_paths.h"
#include "ui/base/ui_base_switches.h"
+#include "ui/display/display_switches.h"
+#include "ui/gfx/switches.h"
#if defined(OS_WIN)
#include <malloc.h>
@@ -92,6 +94,33 @@
#endif // OS_POSIX
+#if defined(OS_LINUX)
+#include "base/native_library.h"
+#include "base/rand_util.h"
+#include "content/common/font_config_ipc_linux.h"
+#include "content/public/common/common_sandbox_support_linux.h"
+#include "third_party/blink/public/platform/web_font_render_style.h"
+#include "third_party/boringssl/src/include/openssl/crypto.h"
+#include "third_party/boringssl/src/include/openssl/rand.h"
+#include "third_party/skia/include/ports/SkFontConfigInterface.h"
+#include "third_party/skia/include/ports/SkFontMgr.h"
+#include "third_party/skia/include/ports/SkFontMgr_android.h"
+
+#if BUILDFLAG(ENABLE_PLUGINS)
+#include "content/common/pepper_plugin_list.h"
+#include "content/public/common/pepper_plugin_info.h"
+#endif
+
+#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
+#include "content/public/common/cdm_info.h"
+#include "content/public/common/content_client.h"
+#endif
+
+#if BUILDFLAG(ENABLE_WEBRTC)
+#include "third_party/webrtc_overrides/init_webrtc.h" // nogncheck
+#endif
+#endif // OS_LINUX
+
#if !defined(CHROME_MULTIPLE_DLL_BROWSER)
#include "content/public/gpu/content_gpu_client.h"
#include "content/public/renderer/content_renderer_client.h"
@@ -106,12 +135,21 @@
#if !defined(CHROME_MULTIPLE_DLL_BROWSER) && !defined(CHROME_MULTIPLE_DLL_CHILD)
#include "content/browser/gpu/gpu_main_thread_factory.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
-#include "content/browser/utility_process_host_impl.h"
+#include "content/browser/utility_process_host.h"
#include "content/gpu/in_process_gpu_thread.h"
#include "content/renderer/in_process_renderer_thread.h"
#include "content/utility/in_process_utility_thread.h"
#endif
+#if BUILDFLAG(USE_ZYGOTE_HANDLE)
+#include "content/browser/sandbox_host_linux.h"
+#include "content/browser/zygote_host/zygote_communication_linux.h"
+#include "content/browser/zygote_host/zygote_host_impl_linux.h"
+#include "content/public/common/common_sandbox_support_linux.h"
+#include "content/public/common/zygote_handle.h"
+#include "media/base/media_switches.h"
+#endif
+
namespace content {
extern int GpuMain(const content::MainFunctionParams&);
#if BUILDFLAG(ENABLE_PLUGINS)
@@ -233,6 +271,170 @@ void InitializeV8IfNeeded(const base::CommandLine& command_line,
#endif // V8_USE_EXTERNAL_STARTUP_DATA
}
+#if BUILDFLAG(USE_ZYGOTE_HANDLE)
+pid_t LaunchZygoteHelper(base::CommandLine* cmd_line,
+ base::ScopedFD* control_fd) {
+ // Append any switches from the browser process that need to be forwarded on
+ // to the zygote/renderers.
+ static const char* const kForwardSwitches[] = {
+ switches::kAndroidFontsPath, switches::kClearKeyCdmPathForTesting,
+ switches::kEnableHeapProfiling,
+ switches::kEnableLogging, // Support, e.g., --enable-logging=stderr.
+ // Need to tell the zygote that it is headless so that we don't try to use
+ // the wrong type of main delegate.
+ switches::kHeadless,
+ // Zygote process needs to know what resources to have loaded when it
+ // becomes a renderer process.
+ switches::kForceDeviceScaleFactor, switches::kLoggingLevel,
+ switches::kPpapiInProcess, switches::kRegisterPepperPlugins, switches::kV,
+ switches::kVModule,
+ };
+ cmd_line->CopySwitchesFrom(*base::CommandLine::ForCurrentProcess(),
+ kForwardSwitches, arraysize(kForwardSwitches));
+
+ GetContentClient()->browser()->AppendExtraCommandLineSwitches(cmd_line, -1);
+
+ // Start up the sandbox host process and get the file descriptor for the
+ // sandboxed processes to talk to it.
+ base::FileHandleMappingVector additional_remapped_fds;
+ additional_remapped_fds.emplace_back(
+ SandboxHostLinux::GetInstance()->GetChildSocket(), GetSandboxFD());
+
+ return ZygoteHostImpl::GetInstance()->LaunchZygote(
+ cmd_line, control_fd, std::move(additional_remapped_fds));
+}
+
+// Initializes the Zygote sandbox host. No thread should be created before this
+// call, as InitializeZygoteSandboxForBrowserProcess() will end-up using fork().
+void InitializeZygoteSandboxForBrowserProcess(
+ const base::CommandLine& parsed_command_line) {
+ TRACE_EVENT0("startup", "SetupSandbox");
+ // SandboxHostLinux needs to be initialized even if the sandbox and
+ // zygote are both disabled. It initializes the sandboxed process socket.
+ SandboxHostLinux::GetInstance()->Init();
+
+ if (parsed_command_line.HasSwitch(switches::kNoZygote) &&
+ !parsed_command_line.HasSwitch(switches::kNoSandbox)) {
+ LOG(ERROR) << "--no-sandbox should be used together with --no--zygote";
+ exit(EXIT_FAILURE);
+ }
+
+ // Tickle the zygote host so it forks now.
+ ZygoteHostImpl::GetInstance()->Init(parsed_command_line);
+ ZygoteHandle generic_zygote =
+ CreateGenericZygote(base::BindOnce(LaunchZygoteHelper));
+
+ // TODO(kerrnel): Investigate doing this without the ZygoteHostImpl as a
+ // proxy. It is currently done this way due to concerns about race
+ // conditions.
+ ZygoteHostImpl::GetInstance()->SetRendererSandboxStatus(
+ generic_zygote->GetSandboxStatus());
+}
+#endif // BUILDFLAG(USE_ZYGOTE_HANDLE)
+
+#if defined(OS_LINUX)
+
+#if BUILDFLAG(ENABLE_PLUGINS)
+// Loads the (native) libraries but does not initialize them (i.e., does not
+// call PPP_InitializeModule). This is needed by the zygote on Linux to get
+// access to the plugins before entering the sandbox.
+void PreloadPepperPlugins() {
+ std::vector<PepperPluginInfo> plugins;
+ ComputePepperPluginList(&plugins);
+ for (const auto& plugin : plugins) {
+ if (!plugin.is_internal) {
+ base::NativeLibraryLoadError error;
+ base::NativeLibrary library =
+ base::LoadNativeLibrary(plugin.path, &error);
+ VLOG_IF(1, !library) << "Unable to load plugin " << plugin.path.value()
+ << " " << error.ToString();
+
+ ignore_result(library); // Prevent release-mode warning.
+ }
+ }
+}
+#endif
+
+#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
+// Loads registered library CDMs but does not initialize them. This is needed by
+// the zygote on Linux to get access to the CDMs before entering the sandbox.
+void PreloadLibraryCdms() {
+ std::vector<CdmInfo> cdms;
+ GetContentClient()->AddContentDecryptionModules(&cdms, nullptr);
+ for (const auto& cdm : cdms) {
+ base::NativeLibraryLoadError error;
+ base::NativeLibrary library = base::LoadNativeLibrary(cdm.path, &error);
+ VLOG_IF(1, !library) << "Unable to load CDM " << cdm.path.value()
+ << " (error: " << error.ToString() << ")";
+ ignore_result(library); // Prevent release-mode warning.
+ }
+}
+#endif // BUILDFLAG(ENABLE_LIBRARY_CDMS)
+
+#if BUILDFLAG(USE_ZYGOTE_HANDLE)
+void PreSandboxInit() {
+#if defined(ARCH_CPU_ARM_FAMILY)
+ // On ARM, BoringSSL requires access to /proc/cpuinfo to determine processor
+ // features. Query this before entering the sandbox.
+ CRYPTO_library_init();
+#endif
+
+ // Pass BoringSSL a copy of the /dev/urandom file descriptor so RAND_bytes
+ // will work inside the sandbox.
+ RAND_set_urandom_fd(base::GetUrandomFD());
+
+#if BUILDFLAG(ENABLE_PLUGINS)
+ // Ensure access to the Pepper plugins before the sandbox is turned on.
+ PreloadPepperPlugins();
+#endif
+#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
+ // Ensure access to the library CDMs before the sandbox is turned on.
+ PreloadLibraryCdms();
+#endif
+#if BUILDFLAG(ENABLE_WEBRTC)
+ InitializeWebRtcModule();
+#endif
+
+ SkFontConfigInterface::SetGlobal(new FontConfigIPC(GetSandboxFD()))->unref();
+
+ // Set the android SkFontMgr for blink. We need to ensure this is done
+ // before the sandbox is initialized to allow the font manager to access
+ // font configuration files on disk.
+ if (base::CommandLine::ForCurrentProcess()->HasSwitch(
+ switches::kAndroidFontsPath)) {
+ std::string android_fonts_dir =
+ base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
+ switches::kAndroidFontsPath);
+
+ if (android_fonts_dir.size() > 0 && android_fonts_dir.back() != '/')
+ android_fonts_dir += '/';
+
+ SkFontMgr_Android_CustomFonts custom;
+ custom.fSystemFontUse =
+ SkFontMgr_Android_CustomFonts::SystemFontUse::kOnlyCustom;
+ custom.fBasePath = android_fonts_dir.c_str();
+
+ std::string font_config;
+ std::string fallback_font_config;
+ if (android_fonts_dir.find("kitkat") != std::string::npos) {
+ font_config = android_fonts_dir + "system_fonts.xml";
+ fallback_font_config = android_fonts_dir + "fallback_fonts.xml";
+ custom.fFallbackFontsXml = fallback_font_config.c_str();
+ } else {
+ font_config = android_fonts_dir + "fonts.xml";
+ custom.fFallbackFontsXml = nullptr;
+ }
+ custom.fFontsXml = font_config.c_str();
+ custom.fIsolated = true;
+
+ blink::WebFontRenderStyle::SetSkiaFontManager(
+ SkFontMgr_New_Android(&custom));
+ }
+}
+#endif // BUILDFLAG(USE_ZYGOTE_HANDLE)
+
+#endif // OS_LINUX
+
} // namespace
#if !defined(CHROME_MULTIPLE_DLL_CHILD)
@@ -321,6 +523,10 @@ int RunZygote(ContentMainDelegate* delegate) {
media::InitializeMediaLibrary();
}
+#if defined(OS_LINUX)
+ PreSandboxInit();
+#endif
+
// This function call can return multiple times, once per fork().
if (!ZygoteMain(std::move(zygote_fork_delegates)))
return 1;
@@ -336,6 +542,10 @@ int RunZygote(ContentMainDelegate* delegate) {
command_line.GetSwitchValueASCII(switches::kProcessType);
ContentClientInitializer::Set(process_type, delegate);
+#if !defined(OS_ANDROID)
+ tracing::EnableStartupTracingIfNeeded();
+#endif // !OS_ANDROID
+
MainFunctionParams main_params(command_line);
main_params.zygote_child = true;
@@ -362,7 +572,7 @@ int RunZygote(ContentMainDelegate* delegate) {
static void RegisterMainThreadFactories() {
#if !defined(CHROME_MULTIPLE_DLL_BROWSER) && !defined(CHROME_MULTIPLE_DLL_CHILD)
- UtilityProcessHostImpl::RegisterUtilityMainThreadFactory(
+ UtilityProcessHost::RegisterUtilityMainThreadFactory(
CreateInProcessUtilityThread);
RenderProcessHostImpl::RegisterRendererMainThreadFactory(
CreateInProcessRendererThread);
@@ -544,12 +754,11 @@ class ContentMainRunnerImpl : public ContentMainRunner {
// Enable startup tracing asap to avoid early TRACE_EVENT calls being
// ignored. For Android, startup tracing is enabled in an even earlier place
// content/app/android/library_loader_hooks.cc.
- // Zygote process does not have file thread and renderer process on Win10
- // cannot access the file system.
- // TODO(ssid): Check if other processes can enable startup tracing here.
- bool can_access_file_system = (process_type != switches::kZygoteProcess &&
- process_type != switches::kRendererProcess);
- tracing::EnableStartupTracingIfNeeded(can_access_file_system);
+ //
+ // Startup tracing flags are not (and should not) passed to Zygote
+ // processes. We will enable tracing when forked, if needed.
+ if (process_type != switches::kZygoteProcess)
+ tracing::EnableStartupTracingIfNeeded();
#endif // !OS_ANDROID
#if defined(OS_WIN)
@@ -673,6 +882,16 @@ class ContentMainRunnerImpl : public ContentMainRunner {
if (delegate_)
delegate_->SandboxInitialized(process_type);
+#if BUILDFLAG(USE_ZYGOTE_HANDLE)
+ if (process_type.empty()) {
+ // The sandbox host needs to be initialized before forking a thread to
+ // start the ServiceManager, and after setting up the sandbox and invoking
+ // SandboxInitialized().
+ InitializeZygoteSandboxForBrowserProcess(
+ *base::CommandLine::ForCurrentProcess());
+ }
+#endif // BUILDFLAG(USE_ZYGOTE_HANDLE)
+
// Return -1 to indicate no early termination.
return -1;
}
diff --git a/chromium/content/app/sandbox_helper_win.cc b/chromium/content/app/sandbox_helper_win.cc
index 3791888e11e..233edc396ab 100644
--- a/chromium/content/app/sandbox_helper_win.cc
+++ b/chromium/content/app/sandbox_helper_win.cc
@@ -16,8 +16,7 @@ void InitializeSandboxInfo(sandbox::SandboxInterfaceInfo* info) {
} else {
// Ensure the proper mitigations are enforced for the browser process.
sandbox::ApplyProcessMitigationsToCurrentProcess(
- sandbox::MITIGATION_DEP |
- sandbox::MITIGATION_DEP_NO_ATL_THUNK |
+ sandbox::MITIGATION_DEP | sandbox::MITIGATION_DEP_NO_ATL_THUNK |
sandbox::MITIGATION_HARDEN_TOKEN_IL_POLICY);
// Note: these mitigations are "post-startup". Some mitigations that need
// to be enabled sooner (e.g. MITIGATION_EXTENSION_POINT_DISABLE) are done
diff --git a/chromium/content/browser/BUILD.gn b/chromium/content/browser/BUILD.gn
index f5732f9c25c..a967e1b15f3 100644
--- a/chromium/content/browser/BUILD.gn
+++ b/chromium/content/browser/BUILD.gn
@@ -11,9 +11,9 @@ import("//content/public/common/zygote_features.gni")
import("//gpu/vulkan/features.gni")
import("//media/media_options.gni")
import("//net/features.gni")
-import("//ppapi/features/features.gni")
-import("//printing/features/features.gni")
-import("//third_party/WebKit/public/public_features.gni")
+import("//ppapi/buildflags/buildflags.gni")
+import("//printing/buildflags/buildflags.gni")
+import("//third_party/blink/public/public_features.gni")
import("//tools/ipc_fuzzer/ipc_fuzzer.gni")
jumbo_source_set("browser") {
@@ -48,8 +48,6 @@ jumbo_source_set("browser") {
"//components/download/public/common:public",
"//components/download/quarantine",
"//components/filename_generation",
- "//components/filesystem:lib",
- "//components/leveldb:lib",
"//components/link_header_util",
"//components/metrics",
"//components/metrics:single_sample_metrics",
@@ -57,6 +55,8 @@ jumbo_source_set("browser") {
"//components/offline_pages/buildflags",
"//components/offline_pages/core/request_header",
"//components/rappor",
+ "//components/services/filesystem:lib",
+ "//components/services/leveldb:lib",
"//components/tracing",
"//components/tracing:startup_tracing",
"//components/url_formatter",
@@ -79,10 +79,10 @@ jumbo_source_set("browser") {
"//content/browser/service_worker:service_worker_proto",
"//content/browser/speech/proto",
"//content/common",
- "//content/common:features",
+ "//content/common:buildflags",
"//content/common:mojo_bindings",
"//content/public/common:common_sources",
- "//content/public/common:zygote_features",
+ "//content/public/common:zygote_buildflags",
"//crypto",
"//device/bluetooth",
"//device/fido",
@@ -96,27 +96,27 @@ jumbo_source_set("browser") {
"//gpu/command_buffer/client:raster_interface",
"//gpu/ipc/common:gpu_preferences_util",
"//gpu/ipc/host",
- "//gpu/vulkan:features",
+ "//gpu/vulkan:buildflags",
"//media",
- "//media:media_features",
+ "//media:media_buildflags",
"//media/capture",
"//media/midi",
"//media/midi:mojo",
- "//media/mojo:features",
+ "//media/mojo:buildflags",
"//media/mojo/clients:jpeg_decode_accelerator",
"//media/mojo/interfaces",
"//media/mojo/interfaces:constants",
"//media/mojo/services",
"//mojo/common",
"//mojo/common:values_struct_traits",
- "//mojo/edk/system",
+ "//mojo/edk",
"//mojo/public/cpp/bindings",
"//mojo/public/js:resources",
"//net",
"//net:extras",
"//net:http_server",
- "//ppapi/features",
- "//printing/features",
+ "//ppapi/buildflags",
+ "//printing/buildflags",
"//services/audio:lib",
"//services/audio/public/cpp",
"//services/audio/public/mojom:constants",
@@ -159,14 +159,14 @@ jumbo_source_set("browser") {
"//sql",
"//storage/browser",
"//storage/common",
- "//third_party/WebKit/public:blink_headers",
- "//third_party/WebKit/public:core_mojo_bindings",
- "//third_party/WebKit/public:features",
- "//third_party/WebKit/public:mojo_bindings",
- "//third_party/WebKit/public:resources",
- "//third_party/WebKit/public:scaled_resources",
- "//third_party/WebKit/public/common",
"//third_party/angle:angle_common",
+ "//third_party/blink/public:blink_headers",
+ "//third_party/blink/public:buildflags",
+ "//third_party/blink/public:core_mojo_bindings",
+ "//third_party/blink/public:mojo_bindings",
+ "//third_party/blink/public:resources",
+ "//third_party/blink/public:scaled_resources",
+ "//third_party/blink/public/common",
"//third_party/boringssl",
"//third_party/brotli:dec",
"//third_party/icu",
@@ -203,11 +203,11 @@ jumbo_source_set("browser") {
]
public_deps = [
- ":accessibility_flags",
+ ":accessibility_buildflags",
"//ipc",
"//media/mojo/interfaces:remoting",
- "//third_party/WebKit/public:media_devices_mojo_bindings",
- "//third_party/WebKit/public:offscreen_canvas_mojo_bindings",
+ "//third_party/blink/public:media_devices_mojo_bindings",
+ "//third_party/blink/public:offscreen_canvas_mojo_bindings",
"//third_party/leveldatabase",
]
@@ -426,8 +426,8 @@ jumbo_source_set("browser") {
"background_fetch/background_fetch_service_impl.h",
"background_fetch/storage/cleanup_task.cc",
"background_fetch/storage/cleanup_task.h",
- "background_fetch/storage/create_registration_task.cc",
- "background_fetch/storage/create_registration_task.h",
+ "background_fetch/storage/create_metadata_task.cc",
+ "background_fetch/storage/create_metadata_task.h",
"background_fetch/storage/database_helpers.cc",
"background_fetch/storage/database_helpers.h",
"background_fetch/storage/database_task.cc",
@@ -436,10 +436,12 @@ jumbo_source_set("browser") {
"background_fetch/storage/delete_registration_task.h",
"background_fetch/storage/get_developer_ids_task.cc",
"background_fetch/storage/get_developer_ids_task.h",
- "background_fetch/storage/get_registration_task.cc",
- "background_fetch/storage/get_registration_task.h",
+ "background_fetch/storage/get_metadata_task.cc",
+ "background_fetch/storage/get_metadata_task.h",
"background_fetch/storage/mark_registration_for_deletion_task.cc",
"background_fetch/storage/mark_registration_for_deletion_task.h",
+ "background_fetch/storage/update_registration_ui_task.cc",
+ "background_fetch/storage/update_registration_ui_task.h",
"background_sync/background_sync_context.cc",
"background_sync/background_sync_context.h",
"background_sync/background_sync_manager.cc",
@@ -575,8 +577,6 @@ jumbo_source_set("browser") {
"devtools/devtools_agent_host_impl.h",
"devtools/devtools_frame_trace_recorder.cc",
"devtools/devtools_frame_trace_recorder.h",
- "devtools/devtools_frame_trace_recorder_for_viz.cc",
- "devtools/devtools_frame_trace_recorder_for_viz.h",
"devtools/devtools_http_handler.cc",
"devtools/devtools_http_handler.h",
"devtools/devtools_interceptor_controller.cc",
@@ -598,8 +598,12 @@ jumbo_source_set("browser") {
"devtools/devtools_traceable_screenshot.h",
"devtools/devtools_url_interceptor_request_job.cc",
"devtools/devtools_url_interceptor_request_job.h",
+ "devtools/devtools_url_loader_interceptor.cc",
+ "devtools/devtools_url_loader_interceptor.h",
"devtools/devtools_url_request_interceptor.cc",
"devtools/devtools_url_request_interceptor.h",
+ "devtools/devtools_video_consumer.cc",
+ "devtools/devtools_video_consumer.h",
"devtools/forwarding_agent_host.cc",
"devtools/forwarding_agent_host.h",
"devtools/protocol/browser_handler.cc",
@@ -674,8 +678,6 @@ jumbo_source_set("browser") {
"dom_storage/dom_storage_message_filter.h",
"dom_storage/dom_storage_namespace.cc",
"dom_storage/dom_storage_namespace.h",
- "dom_storage/dom_storage_session.cc",
- "dom_storage/dom_storage_session.h",
"dom_storage/dom_storage_task_runner.cc",
"dom_storage/dom_storage_task_runner.h",
"dom_storage/local_storage_context_mojo.cc",
@@ -688,30 +690,11 @@ jumbo_source_set("browser") {
"dom_storage/session_storage_database_adapter.h",
"dom_storage/session_storage_namespace_impl.cc",
"dom_storage/session_storage_namespace_impl.h",
- "download/base_file.cc",
- "download/base_file.h",
- "download/base_file_posix.cc",
- "download/base_file_win.cc",
- "download/download_destination_observer.h",
- "download/download_file.h",
- "download/download_file_factory.cc",
- "download/download_file_factory.h",
- "download/download_file_impl.cc",
- "download/download_file_impl.h",
- "download/download_interrupt_reasons_utils.cc",
- "download/download_interrupt_reasons_utils.h",
- "download/download_item_factory.h",
- "download/download_item_impl.cc",
- "download/download_item_impl.h",
- "download/download_item_impl_delegate.cc",
- "download/download_item_impl_delegate.h",
+ "download/blob_download_url_loader_factory_getter.cc",
+ "download/blob_download_url_loader_factory_getter.h",
+ "download/byte_stream_input_stream.cc",
+ "download/byte_stream_input_stream.h",
"download/download_item_utils.cc",
- "download/download_job.cc",
- "download/download_job.h",
- "download/download_job_factory.cc",
- "download/download_job_factory.h",
- "download/download_job_impl.cc",
- "download/download_job_impl.h",
"download/download_manager_impl.cc",
"download/download_manager_impl.h",
"download/download_request_core.cc",
@@ -721,12 +704,8 @@ jumbo_source_set("browser") {
"download/download_request_utils.cc",
"download/download_resource_handler.cc",
"download/download_resource_handler.h",
- "download/download_response_handler.cc",
- "download/download_response_handler.h",
"download/download_utils.cc",
"download/download_utils.h",
- "download/download_worker.cc",
- "download/download_worker.h",
"download/drag_download_file.cc",
"download/drag_download_file.h",
"download/drag_download_util.cc",
@@ -735,29 +714,22 @@ jumbo_source_set("browser") {
"download/mhtml_extra_parts_impl.h",
"download/mhtml_generation_manager.cc",
"download/mhtml_generation_manager.h",
- "download/parallel_download_job.cc",
- "download/parallel_download_job.h",
- "download/parallel_download_utils.cc",
- "download/parallel_download_utils.h",
- "download/resource_downloader.cc",
- "download/resource_downloader.h",
+ "download/network_download_url_loader_factory_getter.cc",
+ "download/network_download_url_loader_factory_getter.h",
"download/save_file.cc",
"download/save_file.h",
"download/save_file_manager.cc",
"download/save_file_manager.h",
- "download/save_file_resource_handler.cc",
- "download/save_file_resource_handler.h",
"download/save_item.cc",
"download/save_item.h",
"download/save_package.cc",
"download/save_package.h",
- "download/save_package_download_job.cc",
- "download/save_package_download_job.h",
"download/save_types.cc",
"download/save_types.h",
- "download/url_download_handler.h",
"download/url_downloader.cc",
"download/url_downloader.h",
+ "download/url_downloader_factory.cc",
+ "download/url_downloader_factory.h",
"field_trial_recorder.cc",
"field_trial_recorder.h",
"file_url_loader_factory.cc",
@@ -985,6 +957,8 @@ jumbo_source_set("browser") {
"loader/mime_sniffing_resource_handler.h",
"loader/mojo_async_resource_handler.cc",
"loader/mojo_async_resource_handler.h",
+ "loader/navigation_loader_interceptor.cc",
+ "loader/navigation_loader_interceptor.h",
"loader/navigation_metrics.cc",
"loader/navigation_metrics.h",
"loader/navigation_resource_handler.cc",
@@ -1040,8 +1014,6 @@ jumbo_source_set("browser") {
"loader/upload_data_stream_builder.h",
"loader/url_loader_factory_impl.cc",
"loader/url_loader_factory_impl.h",
- "loader/url_loader_request_handler.cc",
- "loader/url_loader_request_handler.h",
"loader/wake_lock_resource_throttle.cc",
"loader/wake_lock_resource_throttle.h",
"loader_delegate_impl.cc",
@@ -1198,6 +1170,10 @@ jumbo_source_set("browser") {
"permissions/permission_service_context.h",
"permissions/permission_service_impl.cc",
"permissions/permission_service_impl.h",
+ "picture_in_picture/overlay_surface_embedder.cc",
+ "picture_in_picture/overlay_surface_embedder.h",
+ "picture_in_picture/picture_in_picture_window_controller_impl.cc",
+ "picture_in_picture/picture_in_picture_window_controller_impl.h",
"presentation/presentation_service_impl.cc",
"presentation/presentation_service_impl.h",
"push_messaging/push_messaging_context.cc",
@@ -1436,8 +1412,6 @@ jumbo_source_set("browser") {
"renderer_host/render_widget_host_view_child_frame.h",
"renderer_host/render_widget_host_view_mac.h",
"renderer_host/render_widget_host_view_mac.mm",
- "renderer_host/render_widget_host_view_mac_dictionary_helper.h",
- "renderer_host/render_widget_host_view_mac_dictionary_helper.mm",
"renderer_host/render_widget_host_view_mac_editcommand_helper.h",
"renderer_host/render_widget_host_view_mac_editcommand_helper.mm",
"renderer_host/render_widget_targeter.cc",
@@ -1585,12 +1559,14 @@ jumbo_source_set("browser") {
"shared_worker/shared_worker_host.h",
"shared_worker/shared_worker_instance.cc",
"shared_worker/shared_worker_instance.h",
+ "shared_worker/shared_worker_script_loader.cc",
+ "shared_worker/shared_worker_script_loader.h",
+ "shared_worker/shared_worker_script_loader_factory.cc",
+ "shared_worker/shared_worker_script_loader_factory.h",
"shared_worker/shared_worker_service_impl.cc",
"shared_worker/shared_worker_service_impl.h",
"site_instance_impl.cc",
"site_instance_impl.h",
- "site_isolation_policy.cc",
- "site_isolation_policy.h",
"speech/speech_recognition_dispatcher_host.cc",
"speech/speech_recognition_dispatcher_host.h",
"speech/speech_recognition_manager_impl.cc",
@@ -1648,8 +1624,8 @@ jumbo_source_set("browser") {
"tracing/tracing_ui.h",
"url_loader_factory_getter.cc",
"url_loader_factory_getter.h",
- "utility_process_host_impl.cc",
- "utility_process_host_impl.h",
+ "utility_process_host.cc",
+ "utility_process_host.h",
"wake_lock/wake_lock_context_host.cc",
"wake_lock/wake_lock_context_host.h",
"web_contents/aura/gesture_nav_simple.cc",
@@ -1683,6 +1659,10 @@ jumbo_source_set("browser") {
"web_contents/web_drag_utils_win.h",
"web_package/signed_exchange_cert_fetcher.cc",
"web_package/signed_exchange_cert_fetcher.h",
+ "web_package/signed_exchange_cert_fetcher_factory.cc",
+ "web_package/signed_exchange_cert_fetcher_factory.h",
+ "web_package/signed_exchange_certificate_chain.cc",
+ "web_package/signed_exchange_certificate_chain.h",
"web_package/signed_exchange_consts.h",
"web_package/signed_exchange_handler.cc",
"web_package/signed_exchange_handler.h",
@@ -1690,12 +1670,14 @@ jumbo_source_set("browser") {
"web_package/signed_exchange_header.h",
"web_package/signed_exchange_header_parser.cc",
"web_package/signed_exchange_header_parser.h",
- "web_package/signed_exchange_parser.cc",
- "web_package/signed_exchange_parser.h",
"web_package/signed_exchange_signature_verifier.cc",
"web_package/signed_exchange_signature_verifier.h",
"web_package/signed_exchange_url_loader_factory_for_non_network_service.cc",
"web_package/signed_exchange_url_loader_factory_for_non_network_service.h",
+ "web_package/signed_exchange_utils.cc",
+ "web_package/signed_exchange_utils.h",
+ "web_package/web_package_context_impl.cc",
+ "web_package/web_package_context_impl.h",
"web_package/web_package_loader.cc",
"web_package/web_package_loader.h",
"web_package/web_package_prefetch_handler.cc",
@@ -1704,8 +1686,6 @@ jumbo_source_set("browser") {
"web_package/web_package_request_handler.h",
"websockets/websocket_handshake_request_info_impl.cc",
"websockets/websocket_handshake_request_info_impl.h",
- "websockets/websocket_impl.cc",
- "websockets/websocket_impl.h",
"websockets/websocket_manager.cc",
"websockets/websocket_manager.h",
"webui/content_web_ui_controller_factory.cc",
@@ -1730,7 +1710,7 @@ jumbo_source_set("browser") {
"webui/web_ui_impl.h",
"webui/web_ui_message_handler.cc",
"webui/web_ui_url_loader_factory.cc",
- "webui/web_ui_url_loader_factory.h",
+ "webui/web_ui_url_loader_factory_internal.h",
"zygote_host/zygote_communication_linux.cc",
"zygote_host/zygote_communication_linux.h",
"zygote_host/zygote_host_impl_linux.cc",
@@ -1818,12 +1798,6 @@ jumbo_source_set("browser") {
"renderer_host/p2p/socket_host_throttler.h",
"renderer_host/p2p/socket_host_udp.cc",
"renderer_host/p2p/socket_host_udp.h",
- "webrtc/webrtc_event_log_manager.cc",
- "webrtc/webrtc_event_log_manager.h",
- "webrtc/webrtc_event_log_manager_common.cc",
- "webrtc/webrtc_event_log_manager_common.h",
- "webrtc/webrtc_event_log_uploader.cc",
- "webrtc/webrtc_event_log_uploader.h",
"webrtc/webrtc_internals.cc",
"webrtc/webrtc_internals.h",
"webrtc/webrtc_internals_message_handler.cc",
@@ -1831,10 +1805,6 @@ jumbo_source_set("browser") {
"webrtc/webrtc_internals_ui.cc",
"webrtc/webrtc_internals_ui.h",
"webrtc/webrtc_internals_ui_observer.h",
- "webrtc/webrtc_local_event_log_manager.cc",
- "webrtc/webrtc_local_event_log_manager.h",
- "webrtc/webrtc_remote_event_log_manager.cc",
- "webrtc/webrtc_remote_event_log_manager.h",
]
deps += [
@@ -2062,10 +2032,10 @@ jumbo_source_set("browser") {
"accessibility/browser_accessibility_android.h",
"accessibility/browser_accessibility_manager_android.cc",
"accessibility/browser_accessibility_manager_android.h",
+ "accessibility/captioning_controller.cc",
+ "accessibility/captioning_controller.h",
"accessibility/web_contents_accessibility_android.cc",
"accessibility/web_contents_accessibility_android.h",
- "android/composited_touch_handle_drawable.cc",
- "android/composited_touch_handle_drawable.h",
"android/content_view_core.cc",
"android/content_view_core.h",
"android/content_view_render_view.cc",
@@ -2108,10 +2078,14 @@ jumbo_source_set("browser") {
"android/overscroll_controller_android.h",
"android/render_widget_host_connector.cc",
"android/render_widget_host_connector.h",
- "android/selection_popup_controller.cc",
- "android/selection_popup_controller.h",
- "android/smart_selection_client.cc",
- "android/smart_selection_client.h",
+ "android/select_popup.cc",
+ "android/select_popup.h",
+ "android/selection/composited_touch_handle_drawable.cc",
+ "android/selection/composited_touch_handle_drawable.h",
+ "android/selection/selection_popup_controller.cc",
+ "android/selection/selection_popup_controller.h",
+ "android/selection/smart_selection_client.cc",
+ "android/selection/smart_selection_client.h",
"android/synchronous_compositor_browser_filter.cc",
"android/synchronous_compositor_browser_filter.h",
"android/synchronous_compositor_host.cc",
@@ -2214,6 +2188,14 @@ jumbo_source_set("browser") {
# Most webauth code is non-Android
"webauth/authenticator_impl.cc",
"webauth/authenticator_impl.h",
+ "webauth/authenticator_type_converters.cc",
+ "webauth/authenticator_type_converters.h",
+ "webauth/scoped_virtual_authenticator_environment.cc",
+ "webauth/scoped_virtual_authenticator_environment.h",
+ "webauth/virtual_authenticator.cc",
+ "webauth/virtual_authenticator.h",
+ "webauth/virtual_discovery.cc",
+ "webauth/virtual_discovery.h",
]
deps += [ "//third_party/flac" ]
}
@@ -2229,6 +2211,15 @@ jumbo_source_set("browser") {
"QuartzCore.framework",
"IOSurface.framework",
]
+ sources += [
+ "renderer_host/popup_window_mac.h",
+ "renderer_host/popup_window_mac.mm",
+ "renderer_host/render_widget_host_ns_view_bridge.h",
+ "renderer_host/render_widget_host_ns_view_bridge.mm",
+ "renderer_host/render_widget_host_ns_view_client.h",
+ "renderer_host/render_widget_host_view_cocoa.h",
+ "renderer_host/render_widget_host_view_cocoa.mm",
+ ]
}
if (is_chromeos) {
@@ -2372,8 +2363,8 @@ jumbo_source_set("browser") {
}
}
-buildflag_header("accessibility_flags") {
- header = "accessibility_flags.h"
+buildflag_header("accessibility_buildflags") {
+ header = "accessibility_buildflags.h"
header_dir = "content/browser/accessibility"
flags = [ "USE_ATK=$use_atk" ]
}
diff --git a/chromium/content/browser/DEPS b/chromium/content/browser/DEPS
index 3bb22b753ce..df2d78160a9 100644
--- a/chromium/content/browser/DEPS
+++ b/chromium/content/browser/DEPS
@@ -7,8 +7,8 @@ include_rules = [
"+components/download/public/common",
"+components/download/quarantine/quarantine.h",
"+components/filename_generation",
- "+components/filesystem",
- "+components/leveldb",
+ "+components/services/filesystem",
+ "+components/services/leveldb",
"+components/link_header_util",
"+components/metrics",
"+components/metrics:single_sample_metrics",
@@ -30,7 +30,6 @@ include_rules = [
"+device/gamepad", # For gamepad API
"+device/geolocation/public/cpp",
"+device/nfc",
- "+device/sensors",
"+device/vr", # For WebVR API
# This can only be used on POSIX, in particular it mustn't be used on Windows
# in the browser DLL.
@@ -65,93 +64,94 @@ include_rules = [
# No inclusion of WebKit from the browser, other than the ones in
# WebKit/public/{mojom,common}, or the ones that are strictly enum/POD,
# header-only types, and some selected common code.
- "-third_party/WebKit",
- "+third_party/WebKit/public/common",
- "+third_party/WebKit/public/mojom",
- "+third_party/WebKit/public/platform/WebAddressSpace.h",
- "+third_party/WebKit/public/platform/WebContentSecurityPolicy.h",
- "+third_party/WebKit/public/platform/WebCursorInfo.h",
- "+third_party/WebKit/public/platform/WebDisplayMode.h",
- "+third_party/WebKit/public/platform/WebDragOperation.h",
- "+third_party/WebKit/public/platform/WebFocusType.h",
- "+third_party/WebKit/public/platform/WebFullscreenVideoStatus.h",
- "+third_party/WebKit/public/platform/WebGestureEvent.h",
- "+third_party/WebKit/public/platform/WebInputEvent.h",
- "+third_party/WebKit/public/platform/WebInsecureRequestPolicy.h",
- "+third_party/WebKit/public/platform/WebIntrinsicSizingInfo.h",
- "+third_party/WebKit/public/platform/WebKeyboardEvent.h",
- "+third_party/WebKit/public/platform/WebMixedContentContextType.h",
- "+third_party/WebKit/public/platform/WebMouseEvent.h",
- "+third_party/WebKit/public/platform/WebMouseWheelEvent.h",
- "+third_party/WebKit/public/platform/WebPageVisibilityState.h",
- "+third_party/WebKit/public/platform/WebReferrerPolicy.h",
- "+third_party/WebKit/public/platform/WebRemoteFrameProperties.h",
- "+third_party/WebKit/public/platform/WebScreenInfo.h",
- "+third_party/WebKit/public/platform/WebScrollIntoViewParams.h",
- "+third_party/WebKit/public/platform/WebSecurityStyle.h",
- "+third_party/WebKit/public/platform/WebSuddenTerminationDisablerType.h",
- "+third_party/WebKit/public/platform/WebTouchEvent.h",
- "+third_party/WebKit/public/platform/WebTextInputType.h",
- "+third_party/WebKit/public/platform/mac/WebScrollbarTheme.h",
- "+third_party/WebKit/public/platform/modules/locks/lock_manager.mojom.h",
- "+third_party/WebKit/public/platform/modules/indexeddb/WebIDBDatabaseException.h",
- "+third_party/WebKit/public/platform/modules/indexeddb/WebIDBTypes.h",
- "+third_party/WebKit/public/platform/modules/notifications/WebNotificationConstants.h",
- "+third_party/WebKit/public/platform/modules/screen_orientation/WebLockOrientationError.h",
- "+third_party/WebKit/public/platform/modules/screen_orientation/WebScreenOrientationLockType.h",
- "+third_party/WebKit/public/platform/modules/screen_orientation/WebScreenOrientationType.h",
- "+third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerError.h",
- "+third_party/WebKit/public/public_features.h",
- "+third_party/WebKit/public/web/devtools_agent.mojom.h",
- "+third_party/WebKit/public/web/devtools_frontend.mojom.h",
- "+third_party/WebKit/public/web/WebAXEnums.h",
- "+third_party/WebKit/public/web/WebConsoleMessage.h",
- "+third_party/WebKit/public/web/WebContextMenuData.h",
- "+third_party/WebKit/public/web/WebDeviceEmulationParams.h",
- "+third_party/WebKit/public/web/WebDragStatus.h",
- "+third_party/WebKit/public/web/WebFindOptions.h",
- "+third_party/WebKit/public/web/WebFrameSerializerCacheControlPolicy.h",
- "+third_party/WebKit/public/web/WebImeTextSpan.h",
- "+third_party/WebKit/public/web/WebMediaPlayerAction.h",
- "+third_party/WebKit/public/web/WebPluginAction.h",
- "+third_party/WebKit/public/web/WebPopupType.h",
- "+third_party/WebKit/public/web/WebSerializedScriptValueVersion.h",
- "+third_party/WebKit/public/web/WebSharedWorkerCreationContextType.h",
- "+third_party/WebKit/public/web/WebSharedWorkerCreationErrors.h",
- "+third_party/WebKit/public/web/WebTextDirection.h",
- "+third_party/WebKit/public/web/WebTreeScopeType.h",
- "+third_party/WebKit/public/web/WebTriggeringEventInfo.h",
+ "-third_party/blink",
+ "+third_party/blink/public/common",
+ "+third_party/blink/public/mojom",
+ "+third_party/blink/public/platform/WebAddressSpace.h",
+ "+third_party/blink/public/platform/web_content_security_policy.h",
+ "+third_party/blink/public/platform/web_cursor_info.h",
+ "+third_party/blink/public/platform/web_display_mode.h",
+ "+third_party/blink/public/platform/web_drag_operation.h",
+ "+third_party/blink/public/platform/web_focus_type.h",
+ "+third_party/blink/public/platform/web_fullscreen_video_status.h",
+ "+third_party/blink/public/platform/web_gesture_event.h",
+ "+third_party/blink/public/platform/web_input_event.h",
+ "+third_party/blink/public/platform/web_insecure_request_policy.h",
+ "+third_party/blink/public/platform/web_intrinsic_sizing_info.h",
+ "+third_party/blink/public/platform/web_keyboard_event.h",
+ "+third_party/blink/public/platform/web_mixed_content_context_type.h",
+ "+third_party/blink/public/platform/web_mouse_event.h",
+ "+third_party/blink/public/platform/web_mouse_wheel_event.h",
+ "+third_party/blink/public/platform/WebPageVisibilityState.h",
+ "+third_party/blink/public/platform/web_referrer_policy.h",
+ "+third_party/blink/public/platform/WebRemoteFrameProperties.h",
+ "+third_party/blink/public/platform/web_screen_info.h",
+ "+third_party/blink/public/platform/web_scroll_into_view_params.h",
+ "+third_party/blink/public/platform/web_security_style.h",
+ "+third_party/blink/public/platform/web_sudden_termination_disabler_type.h",
+ "+third_party/blink/public/platform/web_touch_event.h",
+ "+third_party/blink/public/platform/web_text_input_type.h",
+ "+third_party/blink/public/platform/mac/web_scrollbar_theme.h",
+ "+third_party/blink/public/platform/modules/locks/lock_manager.mojom.h",
+ "+third_party/blink/public/platform/modules/indexeddb/web_idb_database_exception.h",
+ "+third_party/blink/public/platform/modules/indexeddb/web_idb_types.h",
+ "+third_party/blink/public/platform/modules/notifications/web_notification_constants.h",
+ "+third_party/blink/public/platform/modules/screen_orientation/web_lock_orientation_error.h",
+ "+third_party/blink/public/platform/modules/screen_orientation/web_screen_orientation_lock_type.h",
+ "+third_party/blink/public/platform/modules/screen_orientation/web_screen_orientation_type.h",
+ "+third_party/blink/public/platform/modules/serviceworker/web_service_worker_error.h",
+ "+third_party/blink/public/public_buildflags.h",
+ "+third_party/blink/public/web/devtools_agent.mojom.h",
+ "+third_party/blink/public/web/devtools_frontend.mojom.h",
+ "+third_party/blink/public/web/web_ax_enums.h",
+ "+third_party/blink/public/web/web_console_message.h",
+ "+third_party/blink/public/web/web_context_menu_data.h",
+ "+third_party/blink/public/web/web_device_emulation_params.h",
+ "+third_party/blink/public/web/web_drag_status.h",
+ "+third_party/blink/public/web/web_find_options.h",
+ "+third_party/blink/public/web/web_frame_serializer_cache_control_policy.h",
+ "+third_party/blink/public/web/web_ime_text_span.h",
+ "+third_party/blink/public/web/web_media_player_action.h",
+ "+third_party/blink/public/web/web_plugin_action.h",
+ "+third_party/blink/public/web/web_popup_type.h",
+ "+third_party/blink/public/web/web_serialized_script_value_version.h",
+ "+third_party/blink/public/web/WebSharedWorkerCreationContextType.h",
+ "+third_party/blink/public/web/WebSharedWorkerCreationErrors.h",
+ "+third_party/blink/public/web/web_text_direction.h",
+ "+third_party/blink/public/web/web_tree_scope_type.h",
+ "+third_party/blink/public/web/web_triggering_event_info.h",
# Allow mojo generated files in WebKit. These files use STL types and
# don't use WTF types.
- "+third_party/WebKit/public/platform/dedicated_worker_factory.mojom.h",
- "+third_party/WebKit/public/platform/input_host.mojom.h",
- "+third_party/WebKit/public/platform/input_messages.mojom.h",
- "+third_party/WebKit/public/platform/mime_registry.mojom.h",
- "+third_party/WebKit/public/platform/modules/background_sync/background_sync.mojom.h",
- "+third_party/WebKit/public/platform/modules/bluetooth/web_bluetooth.mojom.h",
- "+third_party/WebKit/public/platform/modules/broadcastchannel/broadcast_channel.mojom.h",
- "+third_party/WebKit/public/platform/modules/cache_storage/cache_storage.mojom.h",
- "+third_party/WebKit/public/platform/modules/geolocation/geolocation_service.mojom.h",
- "+third_party/WebKit/public/platform/modules/installedapp/installed_app_provider.mojom.h",
- "+third_party/WebKit/public/platform/modules/installedapp/related_application.mojom.h",
- "+third_party/WebKit/public/platform/modules/keyboard_lock/keyboard_lock.mojom.h",
- "+third_party/WebKit/public/platform/modules/manifest/manifest_manager.mojom.h",
- "+third_party/WebKit/public/platform/modules/mediasession/media_session.mojom.h",
- "+third_party/WebKit/public/platform/modules/mediastream/media_devices.mojom.h",
- "+third_party/WebKit/public/platform/modules/notifications/notification_service.mojom.h",
- "+third_party/WebKit/public/platform/modules/offscreencanvas/offscreen_canvas_surface.mojom.h",
- "+third_party/WebKit/public/platform/modules/payments/payment_app.mojom.h",
- "+third_party/WebKit/public/platform/modules/permissions/permission.mojom.h",
- "+third_party/WebKit/public/platform/modules/permissions/permission_status.mojom.h",
- "+third_party/WebKit/public/platform/modules/presentation/presentation.mojom.h",
- "+third_party/WebKit/public/platform/modules/webauth/authenticator.mojom.h",
- "+third_party/WebKit/public/platform/modules/webdatabase/web_database.mojom.h",
- "+third_party/WebKit/public/platform/modules/websockets/websocket.mojom.h",
- "+third_party/WebKit/public/platform/oom_intervention.mojom.h",
- "+third_party/WebKit/public/platform/reporting.mojom.h",
- "+third_party/WebKit/public/platform/web_feature.mojom.h",
- "+third_party/WebKit/public/web/commit_result.mojom.h",
+ "+third_party/blink/public/platform/dedicated_worker_factory.mojom.h",
+ "+third_party/blink/public/platform/input_host.mojom.h",
+ "+third_party/blink/public/platform/input_messages.mojom.h",
+ "+third_party/blink/public/platform/mime_registry.mojom.h",
+ "+third_party/blink/public/platform/modules/background_sync/background_sync.mojom.h",
+ "+third_party/blink/public/platform/modules/bluetooth/web_bluetooth.mojom.h",
+ "+third_party/blink/public/platform/modules/broadcastchannel/broadcast_channel.mojom.h",
+ "+third_party/blink/public/platform/modules/cache_storage/cache_storage.mojom.h",
+ "+third_party/blink/public/platform/modules/geolocation/geolocation_service.mojom.h",
+ "+third_party/blink/public/platform/modules/installedapp/installed_app_provider.mojom.h",
+ "+third_party/blink/public/platform/modules/installedapp/related_application.mojom.h",
+ "+third_party/blink/public/platform/modules/keyboard_lock/keyboard_lock.mojom.h",
+ "+third_party/blink/public/platform/modules/manifest/manifest_manager.mojom.h",
+ "+third_party/blink/public/platform/modules/mediasession/media_session.mojom.h",
+ "+third_party/blink/public/platform/modules/mediastream/media_devices.mojom.h",
+ "+third_party/blink/public/platform/modules/notifications/notification_service.mojom.h",
+ "+third_party/blink/public/platform/modules/offscreencanvas/offscreen_canvas_surface.mojom.h",
+ "+third_party/blink/public/platform/modules/payments/payment_app.mojom.h",
+ "+third_party/blink/public/platform/modules/permissions/permission.mojom.h",
+ "+third_party/blink/public/platform/modules/permissions/permission_status.mojom.h",
+ "+third_party/blink/public/platform/modules/presentation/presentation.mojom.h",
+ "+third_party/blink/public/platform/modules/webauth/authenticator.mojom.h",
+ "+third_party/blink/public/platform/modules/webauth/virtual_authenticator.mojom.h",
+ "+third_party/blink/public/platform/modules/webdatabase/web_database.mojom.h",
+ "+third_party/blink/public/platform/modules/websockets/websocket.mojom.h",
+ "+third_party/blink/public/platform/oom_intervention.mojom.h",
+ "+third_party/blink/public/platform/reporting.mojom.h",
+ "+third_party/blink/public/platform/web_feature.mojom.h",
+ "+third_party/blink/public/web/commit_result.mojom.h",
# DO NOT ADD ANY CHROME OR COMPONENTS INCLUDES HERE!!!
# See https://sites.google.com/a/chromium.org/dev/developers/content-module
diff --git a/chromium/content/browser/accessibility/accessibility_event_recorder.h b/chromium/content/browser/accessibility/accessibility_event_recorder.h
index 22ed1f98a18..7ff5879926e 100644
--- a/chromium/content/browser/accessibility/accessibility_event_recorder.h
+++ b/chromium/content/browser/accessibility/accessibility_event_recorder.h
@@ -40,8 +40,12 @@ class AccessibilityEventRecorder {
base::ProcessId pid);
virtual ~AccessibilityEventRecorder();
+ void set_only_web_events(bool only_web_events) {
+ only_web_events_ = only_web_events;
+ }
+
void ListenToEvents(AccessibilityEventCallback callback) {
- callback_ = callback;
+ callback_ = std::move(callback);
}
// Access the vector of human-readable event logs, one string per event.
@@ -54,12 +58,13 @@ class AccessibilityEventRecorder {
void OnEvent(std::string event);
BrowserAccessibilityManager* manager_;
-
- DISALLOW_COPY_AND_ASSIGN(AccessibilityEventRecorder);
+ bool only_web_events_ = false;
private:
std::vector<std::string> event_logs_;
AccessibilityEventCallback callback_;
+
+ DISALLOW_COPY_AND_ASSIGN(AccessibilityEventRecorder);
};
} // namespace content
diff --git a/chromium/content/browser/accessibility/accessibility_event_recorder_win.cc b/chromium/content/browser/accessibility/accessibility_event_recorder_win.cc
index 0f1dde514c7..b1f5295d639 100644
--- a/chromium/content/browser/accessibility/accessibility_event_recorder_win.cc
+++ b/chromium/content/browser/accessibility/accessibility_event_recorder_win.cc
@@ -23,6 +23,7 @@
#include "content/browser/accessibility/browser_accessibility_win.h"
#include "third_party/iaccessible2/ia2_api_all.h"
#include "ui/base/win/atl_module.h"
+#include "ui/gfx/win/hwnd_util.h"
namespace content {
@@ -204,6 +205,23 @@ void AccessibilityEventRecorderWin::OnWinEventHook(
return;
}
+ if (only_web_events_) {
+ std::string hwnd_class_name = base::UTF16ToUTF8(gfx::GetClassName(hwnd));
+ if (hwnd_class_name != "Chrome_RenderWidgetHostHWND")
+ return;
+
+ Microsoft::WRL::ComPtr<IServiceProvider> service_provider;
+ hr = iaccessible->QueryInterface(service_provider.GetAddressOf());
+ if (!SUCCEEDED(hr))
+ return;
+
+ Microsoft::WRL::ComPtr<IAccessible> content_document;
+ hr = service_provider->QueryService(GUID_IAccessibleContentDocument,
+ content_document.GetAddressOf());
+ if (!SUCCEEDED(hr))
+ return;
+ }
+
std::string event_str = AccessibilityEventToStringUTF8(event);
if (event_str.empty()) {
VLOG(1) << "Ignoring event " << event;
diff --git a/chromium/content/browser/accessibility/accessibility_tree_formatter.cc b/chromium/content/browser/accessibility/accessibility_tree_formatter.cc
index f7d4159ef4c..d5cfe4df644 100644
--- a/chromium/content/browser/accessibility/accessibility_tree_formatter.cc
+++ b/chromium/content/browser/accessibility/accessibility_tree_formatter.cc
@@ -10,7 +10,6 @@
#include <utility>
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/pattern.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
diff --git a/chromium/content/browser/accessibility/accessibility_tree_formatter_auralinux.cc b/chromium/content/browser/accessibility/accessibility_tree_formatter_auralinux.cc
index b8ed49ddcc3..568088325e4 100644
--- a/chromium/content/browser/accessibility/accessibility_tree_formatter_auralinux.cc
+++ b/chromium/content/browser/accessibility/accessibility_tree_formatter_auralinux.cc
@@ -7,7 +7,6 @@
#include <utility>
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
diff --git a/chromium/content/browser/accessibility/accessibility_tree_formatter_blink.cc b/chromium/content/browser/accessibility/accessibility_tree_formatter_blink.cc
index 9e36b555f92..569515a57cb 100644
--- a/chromium/content/browser/accessibility/accessibility_tree_formatter_blink.cc
+++ b/chromium/content/browser/accessibility/accessibility_tree_formatter_blink.cc
@@ -9,7 +9,6 @@
#include <utility>
-#include "base/memory/ptr_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
@@ -174,7 +173,7 @@ void AccessibilityTreeFormatterBlink::AddProperties(
dict->SetString("language", language);
for (int32_t state_index = static_cast<int32_t>(ax::mojom::State::kNone);
- state_index <= static_cast<int32_t>(ax::mojom::State::kLast);
+ state_index <= static_cast<int32_t>(ax::mojom::State::kMaxValue);
++state_index) {
auto state = static_cast<ax::mojom::State>(state_index);
if (node.HasState(state))
@@ -186,7 +185,8 @@ void AccessibilityTreeFormatterBlink::AddProperties(
for (int32_t attr_index =
static_cast<int32_t>(ax::mojom::StringAttribute::kNone);
- attr_index <= static_cast<int32_t>(ax::mojom::StringAttribute::kLast);
+ attr_index <=
+ static_cast<int32_t>(ax::mojom::StringAttribute::kMaxValue);
++attr_index) {
auto attr = static_cast<ax::mojom::StringAttribute>(attr_index);
if (attr != ax::mojom::StringAttribute::kFontFamily &&
@@ -198,7 +198,7 @@ void AccessibilityTreeFormatterBlink::AddProperties(
for (int32_t attr_index =
static_cast<int32_t>(ax::mojom::IntAttribute::kNone);
- attr_index <= static_cast<int32_t>(ax::mojom::IntAttribute::kLast);
+ attr_index <= static_cast<int32_t>(ax::mojom::IntAttribute::kMaxValue);
++attr_index) {
auto attr = static_cast<ax::mojom::IntAttribute>(attr_index);
if (node.HasIntAttribute(attr)) {
@@ -209,16 +209,17 @@ void AccessibilityTreeFormatterBlink::AddProperties(
for (int32_t attr_index =
static_cast<int32_t>(ax::mojom::FloatAttribute::kNone);
- attr_index <= static_cast<int32_t>(ax::mojom::FloatAttribute::kLast);
+ attr_index <= static_cast<int32_t>(ax::mojom::FloatAttribute::kMaxValue);
++attr_index) {
auto attr = static_cast<ax::mojom::FloatAttribute>(attr_index);
- if (node.HasFloatAttribute(attr) && isfinite(node.GetFloatAttribute(attr)))
+ if (node.HasFloatAttribute(attr) &&
+ std::isfinite(node.GetFloatAttribute(attr)))
dict->SetDouble(ui::ToString(attr), node.GetFloatAttribute(attr));
}
for (int32_t attr_index =
static_cast<int32_t>(ax::mojom::BoolAttribute::kNone);
- attr_index <= static_cast<int32_t>(ax::mojom::BoolAttribute::kLast);
+ attr_index <= static_cast<int32_t>(ax::mojom::BoolAttribute::kMaxValue);
++attr_index) {
auto attr = static_cast<ax::mojom::BoolAttribute>(attr_index);
if (node.HasBoolAttribute(attr))
@@ -227,7 +228,8 @@ void AccessibilityTreeFormatterBlink::AddProperties(
for (int32_t attr_index =
static_cast<int32_t>(ax::mojom::IntListAttribute::kNone);
- attr_index <= static_cast<int32_t>(ax::mojom::IntListAttribute::kLast);
+ attr_index <=
+ static_cast<int32_t>(ax::mojom::IntListAttribute::kMaxValue);
++attr_index) {
auto attr = static_cast<ax::mojom::IntListAttribute>(attr_index);
if (node.HasIntListAttribute(attr)) {
@@ -264,7 +266,7 @@ void AccessibilityTreeFormatterBlink::AddProperties(
std::vector<std::string> actions_strings;
for (int32_t action_index =
static_cast<int32_t>(ax::mojom::Action::kNone) + 1;
- action_index <= static_cast<int32_t>(ax::mojom::Action::kLast);
+ action_index <= static_cast<int32_t>(ax::mojom::Action::kMaxValue);
++action_index) {
auto action = static_cast<ax::mojom::Action>(action_index);
if (node.HasAction(action))
@@ -294,7 +296,7 @@ base::string16 AccessibilityTreeFormatterBlink::ProcessTreeForOutput(
WriteAttribute(true, base::UTF16ToUTF8(role_value), &line);
for (int state_index = static_cast<int32_t>(ax::mojom::State::kNone);
- state_index <= static_cast<int32_t>(ax::mojom::State::kLast);
+ state_index <= static_cast<int32_t>(ax::mojom::State::kMaxValue);
++state_index) {
auto state = static_cast<ax::mojom::State>(state_index);
const base::Value* value;
@@ -343,7 +345,8 @@ base::string16 AccessibilityTreeFormatterBlink::ProcessTreeForOutput(
WriteAttribute(false, "transform", &line);
for (int attr_index = static_cast<int32_t>(ax::mojom::StringAttribute::kNone);
- attr_index <= static_cast<int32_t>(ax::mojom::StringAttribute::kLast);
+ attr_index <=
+ static_cast<int32_t>(ax::mojom::StringAttribute::kMaxValue);
++attr_index) {
auto attr = static_cast<ax::mojom::StringAttribute>(attr_index);
std::string string_value;
@@ -356,7 +359,7 @@ base::string16 AccessibilityTreeFormatterBlink::ProcessTreeForOutput(
}
for (int attr_index = static_cast<int32_t>(ax::mojom::IntAttribute::kNone);
- attr_index <= static_cast<int32_t>(ax::mojom::IntAttribute::kLast);
+ attr_index <= static_cast<int32_t>(ax::mojom::IntAttribute::kMaxValue);
++attr_index) {
auto attr = static_cast<ax::mojom::IntAttribute>(attr_index);
std::string string_value;
@@ -369,7 +372,7 @@ base::string16 AccessibilityTreeFormatterBlink::ProcessTreeForOutput(
}
for (int attr_index = static_cast<int32_t>(ax::mojom::BoolAttribute::kNone);
- attr_index <= static_cast<int32_t>(ax::mojom::BoolAttribute::kLast);
+ attr_index <= static_cast<int32_t>(ax::mojom::BoolAttribute::kMaxValue);
++attr_index) {
auto attr = static_cast<ax::mojom::BoolAttribute>(attr_index);
bool bool_value;
@@ -382,7 +385,7 @@ base::string16 AccessibilityTreeFormatterBlink::ProcessTreeForOutput(
}
for (int attr_index = static_cast<int32_t>(ax::mojom::FloatAttribute::kNone);
- attr_index <= static_cast<int32_t>(ax::mojom::FloatAttribute::kLast);
+ attr_index <= static_cast<int32_t>(ax::mojom::FloatAttribute::kMaxValue);
++attr_index) {
auto attr = static_cast<ax::mojom::FloatAttribute>(attr_index);
double float_value;
@@ -395,7 +398,8 @@ base::string16 AccessibilityTreeFormatterBlink::ProcessTreeForOutput(
for (int attr_index =
static_cast<int32_t>(ax::mojom::IntListAttribute::kNone);
- attr_index <= static_cast<int32_t>(ax::mojom::IntListAttribute::kLast);
+ attr_index <=
+ static_cast<int32_t>(ax::mojom::IntListAttribute::kMaxValue);
++attr_index) {
auto attr = static_cast<ax::mojom::IntListAttribute>(attr_index);
const base::ListValue* value;
diff --git a/chromium/content/browser/accessibility/accessibility_tree_formatter_browser.cc b/chromium/content/browser/accessibility/accessibility_tree_formatter_browser.cc
index f62e4d4d4c6..fa5142f04df 100644
--- a/chromium/content/browser/accessibility/accessibility_tree_formatter_browser.cc
+++ b/chromium/content/browser/accessibility/accessibility_tree_formatter_browser.cc
@@ -4,7 +4,6 @@
#include "content/browser/accessibility/accessibility_tree_formatter_browser.h"
-#include "base/memory/ptr_util.h"
namespace content {
diff --git a/chromium/content/browser/accessibility/accessibility_tree_formatter_win.cc b/chromium/content/browser/accessibility/accessibility_tree_formatter_win.cc
index 3d33fbb3098..10b1967d4b5 100644
--- a/chromium/content/browser/accessibility/accessibility_tree_formatter_win.cc
+++ b/chromium/content/browser/accessibility/accessibility_tree_formatter_win.cc
@@ -14,7 +14,6 @@
#include <utility>
#include "base/files/file_path.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
diff --git a/chromium/content/browser/accessibility/accessibility_ui.cc b/chromium/content/browser/accessibility/accessibility_ui.cc
index 04239e6cd9e..945acc066ab 100644
--- a/chromium/content/browser/accessibility/accessibility_ui.cc
+++ b/chromium/content/browser/accessibility/accessibility_ui.cc
@@ -26,6 +26,7 @@
#include "content/browser/webui/web_ui_data_source_impl.h"
#include "content/common/view_message_enums.h"
#include "content/grit/content_resources.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/favicon_status.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/render_process_host.h"
@@ -228,19 +229,21 @@ void AccessibilityUIMessageHandler::RegisterMessages() {
web_ui()->RegisterMessageCallback(
"toggleAccessibility",
- base::Bind(&AccessibilityUIMessageHandler::ToggleAccessibility,
- base::Unretained(this)));
+ base::BindRepeating(&AccessibilityUIMessageHandler::ToggleAccessibility,
+ base::Unretained(this)));
web_ui()->RegisterMessageCallback(
- "setGlobalFlag", base::Bind(&AccessibilityUIMessageHandler::SetGlobalFlag,
- base::Unretained(this)));
+ "setGlobalFlag",
+ base::BindRepeating(&AccessibilityUIMessageHandler::SetGlobalFlag,
+ base::Unretained(this)));
web_ui()->RegisterMessageCallback(
"requestWebContentsTree",
- base::Bind(&AccessibilityUIMessageHandler::RequestWebContentsTree,
- base::Unretained(this)));
+ base::BindRepeating(
+ &AccessibilityUIMessageHandler::RequestWebContentsTree,
+ base::Unretained(this)));
web_ui()->RegisterMessageCallback(
"requestNativeUITree",
- base::Bind(&AccessibilityUIMessageHandler::RequestNativeUITree,
- base::Unretained(this)));
+ base::BindRepeating(&AccessibilityUIMessageHandler::RequestNativeUITree,
+ base::Unretained(this)));
}
void AccessibilityUIMessageHandler::ToggleAccessibility(
diff --git a/chromium/content/browser/accessibility/accessibility_win_browsertest.cc b/chromium/content/browser/accessibility/accessibility_win_browsertest.cc
index 61abcad9255..5d928bb9524 100644
--- a/chromium/content/browser/accessibility/accessibility_win_browsertest.cc
+++ b/chromium/content/browser/accessibility/accessibility_win_browsertest.cc
@@ -11,7 +11,6 @@
#include <vector>
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/process/process_handle.h"
#include "base/strings/pattern.h"
#include "base/strings/string_number_conversions.h"
diff --git a/chromium/content/browser/accessibility/aom_browsertest.cc b/chromium/content/browser/accessibility/aom_browsertest.cc
new file mode 100644
index 00000000000..0a614f8f0a5
--- /dev/null
+++ b/chromium/content/browser/accessibility/aom_browsertest.cc
@@ -0,0 +1,97 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "base/logging.h"
+#include "content/browser/accessibility/browser_accessibility.h"
+#include "content/browser/accessibility/browser_accessibility_manager.h"
+#include "content/browser/web_contents/web_contents_impl.h"
+#include "content/public/common/content_switches.h"
+#include "content/public/test/browser_test_utils.h"
+#include "content/public/test/content_browser_test.h"
+#include "content/public/test/content_browser_test_utils.h"
+#include "content/public/test/test_utils.h"
+#include "content/shell/browser/shell.h"
+#include "content/test/accessibility_browser_test_utils.h"
+#include "net/base/data_url.h"
+#include "net/test/embedded_test_server/embedded_test_server.h"
+#include "testing/gtest/include/gtest/gtest.h"
+#include "url/gurl.h"
+
+namespace content {
+
+namespace {
+
+class AccessibilityObjectModelBrowserTest : public ContentBrowserTest {
+ public:
+ AccessibilityObjectModelBrowserTest() {}
+ ~AccessibilityObjectModelBrowserTest() override {}
+
+ void SetUpCommandLine(base::CommandLine* command_line) override {
+ ContentBrowserTest::SetUpCommandLine(command_line);
+ base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
+ switches::kEnableBlinkFeatures, "AccessibilityObjectModel");
+ }
+
+ protected:
+ BrowserAccessibility* FindNode(ax::mojom::Role role,
+ const std::string& name) {
+ BrowserAccessibility* root = GetManager()->GetRoot();
+ CHECK(root);
+ return FindNodeInSubtree(*root, role, name);
+ }
+
+ BrowserAccessibilityManager* GetManager() {
+ WebContentsImpl* web_contents =
+ static_cast<WebContentsImpl*>(shell()->web_contents());
+ return web_contents->GetRootBrowserAccessibilityManager();
+ }
+
+ private:
+ BrowserAccessibility* FindNodeInSubtree(BrowserAccessibility& node,
+ ax::mojom::Role role,
+ const std::string& name) {
+ if (node.GetRole() == role &&
+ node.GetStringAttribute(ax::mojom::StringAttribute::kName) == name)
+ return &node;
+ for (unsigned int i = 0; i < node.PlatformChildCount(); ++i) {
+ BrowserAccessibility* result =
+ FindNodeInSubtree(*node.PlatformGetChild(i), role, name);
+ if (result)
+ return result;
+ }
+ return nullptr;
+ }
+};
+
+} // namespace
+
+IN_PROC_BROWSER_TEST_F(AccessibilityObjectModelBrowserTest,
+ EventListenerOnVirtualNode) {
+ ASSERT_TRUE(embedded_test_server()->Start());
+ NavigateToURL(shell(), GURL(url::kAboutBlankURL));
+
+ AccessibilityNotificationWaiter waiter(shell()->web_contents(),
+ ui::kAXModeComplete,
+ ax::mojom::Event::kLoadComplete);
+ GURL url(embedded_test_server()->GetURL(
+ "/accessibility/aom/event-listener-on-virtual-node.html"));
+ NavigateToURL(shell(), url);
+ waiter.WaitForNotification();
+
+ BrowserAccessibility* button = FindNode(ax::mojom::Role::kButton, "FocusMe");
+ ASSERT_NE(nullptr, button);
+
+ BrowserAccessibility* link = FindNode(ax::mojom::Role::kLink, "ClickMe");
+ ASSERT_NE(nullptr, link);
+
+ AccessibilityNotificationWaiter waiter2(
+ shell()->web_contents(), ui::kAXModeComplete, ax::mojom::Event::kFocus);
+ GetManager()->DoDefaultAction(*link);
+ waiter2.WaitForNotification();
+
+ BrowserAccessibility* focus = GetManager()->GetFocus();
+ EXPECT_EQ(focus->GetId(), button->GetId());
+}
+
+} // namespace content
diff --git a/chromium/content/browser/accessibility/browser_accessibility.cc b/chromium/content/browser/accessibility/browser_accessibility.cc
index c50392f26e2..bfd96ed1eb6 100644
--- a/chromium/content/browser/accessibility/browser_accessibility.cc
+++ b/chromium/content/browser/accessibility/browser_accessibility.cc
@@ -957,33 +957,32 @@ BrowserAccessibility::GetTargetForNativeAccessibilityEvent() {
bool BrowserAccessibility::AccessibilityPerformAction(
const ui::AXActionData& data) {
- if (data.action == ax::mojom::Action::kDoDefault) {
- manager_->DoDefaultAction(*this);
- return true;
- }
-
- if (data.action == ax::mojom::Action::kFocus) {
- manager_->SetFocus(*this);
- return true;
- }
-
- if (data.action == ax::mojom::Action::kScrollToPoint) {
- // target_point is in screen coordinates. We need to convert this to frame
- // coordinates because that's what BrowserAccessiblity cares about.
- gfx::Point target =
- data.target_point -
- manager_->GetRootManager()->GetViewBounds().OffsetFromOrigin();
-
- manager_->ScrollToPoint(*this, target);
- return true;
- }
-
- if (data.action == ax::mojom::Action::kScrollToMakeVisible) {
- manager_->ScrollToMakeVisible(*this, data.target_rect);
- return true;
+ switch (data.action) {
+ case ax::mojom::Action::kDoDefault:
+ manager_->DoDefaultAction(*this);
+ return true;
+ case ax::mojom::Action::kFocus:
+ manager_->SetFocus(*this);
+ return true;
+ case ax::mojom::Action::kScrollToPoint: {
+ // target_point is in screen coordinates. We need to convert this to
+ // frame coordinates because that's what BrowserAccessiblity cares about.
+ gfx::Point target =
+ data.target_point -
+ manager_->GetRootManager()->GetViewBounds().OffsetFromOrigin();
+
+ manager_->ScrollToPoint(*this, target);
+ return true;
+ }
+ case ax::mojom::Action::kScrollToMakeVisible:
+ manager_->ScrollToMakeVisible(*this, data.target_rect);
+ return true;
+ case ax::mojom::Action::kSetValue:
+ manager_->SetValue(*this, data.value);
+ return true;
+ default:
+ return false;
}
-
- return false;
}
bool BrowserAccessibility::ShouldIgnoreHoveredStateForTesting() {
diff --git a/chromium/content/browser/accessibility/browser_accessibility.h b/chromium/content/browser/accessibility/browser_accessibility.h
index a0bb8dd80a7..2f74f6021c5 100644
--- a/chromium/content/browser/accessibility/browser_accessibility.h
+++ b/chromium/content/browser/accessibility/browser_accessibility.h
@@ -15,10 +15,10 @@
#include "base/strings/string16.h"
#include "base/strings/string_split.h"
#include "build/build_config.h"
-#include "content/browser/accessibility/accessibility_flags.h"
+#include "content/browser/accessibility/accessibility_buildflags.h"
#include "content/browser/accessibility/browser_accessibility_position.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/web/WebAXEnums.h"
+#include "third_party/blink/public/web/web_ax_enums.h"
#include "ui/accessibility/ax_node.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/accessibility/ax_range.h"
diff --git a/chromium/content/browser/accessibility/browser_accessibility_android.cc b/chromium/content/browser/accessibility/browser_accessibility_android.cc
index a5e20453650..01a094c10bc 100644
--- a/chromium/content/browser/accessibility/browser_accessibility_android.cc
+++ b/chromium/content/browser/accessibility/browser_accessibility_android.cc
@@ -289,7 +289,7 @@ bool BrowserAccessibilityAndroid::IsScrollable() const {
}
bool BrowserAccessibilityAndroid::IsSelected() const {
- return HasState(ax::mojom::State::kSelected);
+ return GetBoolAttribute(ax::mojom::BoolAttribute::kSelected);
}
bool BrowserAccessibilityAndroid::IsSlider() const {
@@ -1432,15 +1432,7 @@ bool BrowserAccessibilityAndroid::IsIframe() const {
}
bool BrowserAccessibilityAndroid::ShouldExposeValueAsName() const {
- base::string16 value = GetValue();
- if (value.empty())
- return false;
-
- if (HasState(ax::mojom::State::kEditable))
- return true;
-
switch (GetRole()) {
- case ax::mojom::Role::kPopUpButton:
case ax::mojom::Role::kTextField:
case ax::mojom::Role::kTextFieldWithComboBox:
return true;
@@ -1448,6 +1440,16 @@ bool BrowserAccessibilityAndroid::ShouldExposeValueAsName() const {
break;
}
+ if (HasState(ax::mojom::State::kEditable))
+ return true;
+
+ base::string16 value = GetValue();
+ if (value.empty())
+ return false;
+
+ if (GetRole() == ax::mojom::Role::kPopUpButton)
+ return true;
+
return false;
}
diff --git a/chromium/content/browser/accessibility/browser_accessibility_cocoa.mm b/chromium/content/browser/accessibility/browser_accessibility_cocoa.mm
index 4cff922f28a..2fba090c047 100644
--- a/chromium/content/browser/accessibility/browser_accessibility_cocoa.mm
+++ b/chromium/content/browser/accessibility/browser_accessibility_cocoa.mm
@@ -69,12 +69,14 @@ NSString* const NSAccessibilityDropEffectsAttribute = @"AXDropEffects";
NSString* const NSAccessibilityEditableAncestorAttribute =
@"AXEditableAncestor";
NSString* const NSAccessibilityGrabbedAttribute = @"AXGrabbed";
+NSString* const NSAccessibilityHasPopupAttribute = @"AXHasPopup";
NSString* const NSAccessibilityHighestEditableAncestorAttribute =
@"AXHighestEditableAncestor";
NSString* const NSAccessibilityInvalidAttribute = @"AXInvalid";
NSString* const NSAccessibilityIsMultiSelectableAttribute =
@"AXIsMultiSelectable";
NSString* const NSAccessibilityLoadingProgressAttribute = @"AXLoadingProgress";
+NSString* const NSAccessibilityOwnsAttribute = @"AXOwns";
NSString* const
NSAccessibilityUIElementCountForSearchPredicateParameterizedAttribute =
@"AXUIElementCountForSearchPredicate";
@@ -583,6 +585,7 @@ NSString* const NSAccessibilityRequiredAttributeChrome = @"AXRequired";
{NSAccessibilityFocusedAttribute, @"focused"},
{NSAccessibilityGrabbedAttribute, @"grabbed"},
{NSAccessibilityHeaderAttribute, @"header"},
+ {NSAccessibilityHasPopupAttribute, @"hasPopup"},
{NSAccessibilityHelpAttribute, @"help"},
{NSAccessibilityHighestEditableAncestorAttribute,
@"highestEditableAncestor"},
@@ -598,6 +601,7 @@ NSString* const NSAccessibilityRequiredAttributeChrome = @"AXRequired";
{NSAccessibilityMinValueAttribute, @"minValue"},
{NSAccessibilityNumberOfCharactersAttribute, @"numberOfCharacters"},
{NSAccessibilityOrientationAttribute, @"orientation"},
+ {NSAccessibilityOwnsAttribute, @"owns"},
{NSAccessibilityParentAttribute, @"parent"},
{NSAccessibilityPlaceholderValueAttribute, @"placeholderValue"},
{NSAccessibilityPositionAttribute, @"position"},
@@ -1108,6 +1112,13 @@ NSString* const NSAccessibilityRequiredAttributeChrome = @"AXRequired";
return [NSNumber numberWithBool:NO];
}
+- (NSNumber*)hasPopup {
+ if (![self instanceActive])
+ return nil;
+ return browserAccessibility_->HasState(ax::mojom::State::kHaspopup) ? @YES
+ : @NO;
+}
+
- (id)header {
if (![self instanceActive])
return nil;
@@ -1360,6 +1371,40 @@ NSString* const NSAccessibilityRequiredAttributeChrome = @"AXRequired";
return @"";
}
+- (id)owns {
+ if (![self instanceActive])
+ return nil;
+
+ //
+ // If the active descendant points to an element in a container with
+ // selectable children, add the "owns" relationship to point to that
+ // container. That's the only way activeDescendant is actually
+ // supported with VoiceOver.
+ //
+
+ int activeDescendantId;
+ if (!browserAccessibility_->GetIntAttribute(
+ ax::mojom::IntAttribute::kActivedescendantId, &activeDescendantId))
+ return nil;
+
+ BrowserAccessibilityManager* manager = browserAccessibility_->manager();
+ BrowserAccessibility* activeDescendant =
+ manager->GetFromID(activeDescendantId);
+ if (!activeDescendant)
+ return nil;
+
+ BrowserAccessibility* container = activeDescendant->PlatformGetParent();
+ while (container &&
+ !ui::IsContainerWithSelectableChildrenRole(container->GetRole()))
+ container = container->PlatformGetParent();
+ if (!container)
+ return nil;
+
+ NSMutableArray* ret = [[[NSMutableArray alloc] init] autorelease];
+ [ret addObject:ToBrowserAccessibilityCocoa(container)];
+ return ret;
+}
+
- (NSNumber*)numberOfCharacters {
if (![self instanceActive])
return nil;
@@ -1837,7 +1882,7 @@ NSString* const NSAccessibilityRequiredAttributeChrome = @"AXRequired";
for (uint32_t index = 0; index < childCount; ++index) {
BrowserAccessibility* child =
browserAccessibility_->PlatformGetChild(index);
- if (child->HasState(ax::mojom::State::kSelected))
+ if (child->GetBoolAttribute(ax::mojom::BoolAttribute::kSelected))
[ret addObject:ToBrowserAccessibilityCocoa(child)];
}
@@ -2112,7 +2157,8 @@ NSString* const NSAccessibilityRequiredAttributeChrome = @"AXRequired";
value = 2;
break;
default:
- value = GetState(browserAccessibility_, ax::mojom::State::kSelected)
+ value = browserAccessibility_->GetBoolAttribute(
+ ax::mojom::BoolAttribute::kSelected)
? 1
: 0;
break;
@@ -2983,6 +3029,10 @@ NSString* const NSAccessibilityRequiredAttributeChrome = @"AXRequired";
[ret addObjectsFromArray:@[ NSAccessibilityGrabbedAttribute ]];
}
+ if (browserAccessibility_->HasState(ax::mojom::State::kHaspopup)) {
+ [ret addObjectsFromArray:@[ NSAccessibilityHasPopupAttribute ]];
+ }
+
// Add expanded attribute only if it has expanded or collapsed state.
if (GetState(browserAccessibility_, ax::mojom::State::kExpanded) ||
GetState(browserAccessibility_, ax::mojom::State::kCollapsed)) {
@@ -3008,6 +3058,12 @@ NSString* const NSAccessibilityRequiredAttributeChrome = @"AXRequired";
[ret addObjectsFromArray:@[ NSAccessibilityLanguageAttribute ]];
}
+ if ([self internalRole] == ax::mojom::Role::kTextFieldWithComboBox) {
+ [ret addObjectsFromArray:@[
+ NSAccessibilityOwnsAttribute,
+ ]];
+ }
+
// Title UI Element.
if (browserAccessibility_->HasIntListAttribute(
ax::mojom::IntListAttribute::kLabelledbyIds) &&
diff --git a/chromium/content/browser/accessibility/browser_accessibility_com_win.cc b/chromium/content/browser/accessibility/browser_accessibility_com_win.cc
index 92fed23a7d2..a0738c7e24b 100644
--- a/chromium/content/browser/accessibility/browser_accessibility_com_win.cc
+++ b/chromium/content/browser/accessibility/browser_accessibility_com_win.cc
@@ -43,19 +43,6 @@ using BrowserAccessibilityPositionInstance =
using AXPlatformRange =
ui::AXRange<BrowserAccessibilityPositionInstance::element_type>;
-// These nonstandard GUIDs are taken directly from the Mozilla sources
-// (accessible/src/msaa/nsAccessNodeWrap.cpp); some documentation is here:
-// http://developer.mozilla.org/en/Accessibility/AT-APIs/ImplementationFeatures/MSAA
-const GUID GUID_ISimpleDOM = {0x0c539790,
- 0x12e4,
- 0x11cf,
- {0xb6, 0x61, 0x00, 0xaa, 0x00, 0x4c, 0xd6, 0xd8}};
-const GUID GUID_IAccessibleContentDocument = {
- 0xa5d8e1f3,
- 0x3571,
- 0x4d8f,
- {0x95, 0x21, 0x07, 0xed, 0x28, 0xfb, 0x07, 0x2e}};
-
void AddAccessibilityModeFlags(ui::AXMode mode_flags) {
BrowserAccessibilityStateImpl::GetInstance()->AddAccessibilityModeFlags(
mode_flags);
diff --git a/chromium/content/browser/accessibility/browser_accessibility_com_win.h b/chromium/content/browser/accessibility/browser_accessibility_com_win.h
index 2a86324f644..4d6ce30ac99 100644
--- a/chromium/content/browser/accessibility/browser_accessibility_com_win.h
+++ b/chromium/content/browser/accessibility/browser_accessibility_com_win.h
@@ -27,6 +27,19 @@
#include "ui/accessibility/platform/ax_platform_node_delegate.h"
#include "ui/accessibility/platform/ax_platform_node_win.h"
+// These nonstandard GUIDs are taken directly from the Mozilla sources
+// (accessible/src/msaa/nsAccessNodeWrap.cpp); some documentation is here:
+// http://developer.mozilla.org/en/Accessibility/AT-APIs/ImplementationFeatures/MSAA
+const GUID GUID_ISimpleDOM = {0x0c539790,
+ 0x12e4,
+ 0x11cf,
+ {0xb6, 0x61, 0x00, 0xaa, 0x00, 0x4c, 0xd6, 0xd8}};
+const GUID GUID_IAccessibleContentDocument = {
+ 0xa5d8e1f3,
+ 0x3571,
+ 0x4d8f,
+ {0x95, 0x21, 0x07, 0xed, 0x28, 0xfb, 0x07, 0x2e}};
+
namespace ui {
enum TextBoundaryDirection;
enum TextBoundaryType;
diff --git a/chromium/content/browser/accessibility/browser_accessibility_manager.h b/chromium/content/browser/accessibility/browser_accessibility_manager.h
index 17912e34801..276eb429ba0 100644
--- a/chromium/content/browser/accessibility/browser_accessibility_manager.h
+++ b/chromium/content/browser/accessibility/browser_accessibility_manager.h
@@ -14,11 +14,11 @@
#include "base/containers/hash_tables.h"
#include "base/macros.h"
#include "build/build_config.h"
-#include "content/browser/accessibility/accessibility_flags.h"
+#include "content/browser/accessibility/accessibility_buildflags.h"
#include "content/browser/accessibility/browser_accessibility_position.h"
#include "content/common/content_export.h"
#include "content/public/browser/ax_event_notification_details.h"
-#include "third_party/WebKit/public/web/WebAXEnums.h"
+#include "third_party/blink/public/web/web_ax_enums.h"
#include "ui/accessibility/ax_action_data.h"
#include "ui/accessibility/ax_event_generator.h"
#include "ui/accessibility/ax_node_data.h"
diff --git a/chromium/content/browser/accessibility/browser_accessibility_position.cc b/chromium/content/browser/accessibility/browser_accessibility_position.cc
index b7f027966f5..74ba6636e49 100644
--- a/chromium/content/browser/accessibility/browser_accessibility_position.cc
+++ b/chromium/content/browser/accessibility/browser_accessibility_position.cc
@@ -6,7 +6,7 @@
#include "base/strings/string_util.h"
#include "build/build_config.h"
-#include "content/browser/accessibility/accessibility_flags.h"
+#include "content/browser/accessibility/accessibility_buildflags.h"
#include "content/browser/accessibility/browser_accessibility.h"
#include "content/browser/accessibility/browser_accessibility_manager.h"
#include "ui/accessibility/ax_enums.mojom.h"
diff --git a/chromium/content/browser/accessibility/browser_accessibility_state_impl.cc b/chromium/content/browser/accessibility/browser_accessibility_state_impl.cc
index b403657f0ba..0c5ec83a271 100644
--- a/chromium/content/browser/accessibility/browser_accessibility_state_impl.cc
+++ b/chromium/content/browser/accessibility/browser_accessibility_state_impl.cc
@@ -129,7 +129,7 @@ bool BrowserAccessibilityStateImpl::IsAccessibleBrowser() {
void BrowserAccessibilityStateImpl::AddHistogramCallback(
base::Closure callback) {
- histogram_callbacks_.push_back(callback);
+ histogram_callbacks_.push_back(std::move(callback));
}
void BrowserAccessibilityStateImpl::UpdateHistogramsForTesting() {
diff --git a/chromium/content/browser/accessibility/captioning_controller.cc b/chromium/content/browser/accessibility/captioning_controller.cc
new file mode 100644
index 00000000000..3e1967f9565
--- /dev/null
+++ b/chromium/content/browser/accessibility/captioning_controller.cc
@@ -0,0 +1,114 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/accessibility/captioning_controller.h"
+
+#include "base/android/jni_string.h"
+#include "content/browser/web_contents/web_contents_impl.h"
+#include "content/common/frame_messages.h"
+#include "jni/CaptioningController_jni.h"
+
+using base::android::AttachCurrentThread;
+using base::android::ConvertJavaStringToUTF8;
+using base::android::JavaParamRef;
+using base::android::JavaRef;
+using base::android::ScopedJavaLocalRef;
+
+namespace content {
+
+namespace {
+
+int GetRenderProcessIdFromRenderViewHost(RenderViewHost* host) {
+ DCHECK(host);
+ RenderProcessHost* render_process = host->GetProcess();
+ DCHECK(render_process);
+ if (render_process->HasConnection())
+ return render_process->GetHandle();
+ return 0;
+}
+
+} // namespace
+
+CaptioningController::CaptioningController(JNIEnv* env,
+ const JavaRef<jobject>& obj,
+ WebContents* web_contents)
+ : WebContentsObserver(web_contents), java_ref_(env, obj) {}
+
+CaptioningController::~CaptioningController() {
+ JNIEnv* env = AttachCurrentThread();
+ ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
+ if (!obj.is_null())
+ Java_CaptioningController_onDestroy(env, obj);
+}
+
+void CaptioningController::RenderViewReady() {
+ JNIEnv* env = AttachCurrentThread();
+ ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
+ if (!obj.is_null())
+ Java_CaptioningController_onRenderProcessChange(env, obj);
+}
+
+void CaptioningController::RenderViewHostChanged(RenderViewHost* old_host,
+ RenderViewHost* new_host) {
+ int old_pid = 0;
+ if (old_host) {
+ old_pid = GetRenderProcessIdFromRenderViewHost(old_host);
+ }
+ int new_pid =
+ GetRenderProcessIdFromRenderViewHost(web_contents()->GetRenderViewHost());
+ if (new_pid != old_pid) {
+ JNIEnv* env = AttachCurrentThread();
+ ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
+ if (!obj.is_null())
+ Java_CaptioningController_onRenderProcessChange(env, obj);
+ }
+}
+
+void CaptioningController::WebContentsDestroyed() {
+ delete this;
+}
+
+void CaptioningController::SetTextTrackSettings(
+ JNIEnv* env,
+ const JavaParamRef<jobject>& obj,
+ jboolean textTracksEnabled,
+ const JavaParamRef<jstring>& textTrackBackgroundColor,
+ const JavaParamRef<jstring>& textTrackFontFamily,
+ const JavaParamRef<jstring>& textTrackFontStyle,
+ const JavaParamRef<jstring>& textTrackFontVariant,
+ const JavaParamRef<jstring>& textTrackTextColor,
+ const JavaParamRef<jstring>& textTrackTextShadow,
+ const JavaParamRef<jstring>& textTrackTextSize) {
+ FrameMsg_TextTrackSettings_Params params;
+ params.text_tracks_enabled = textTracksEnabled;
+ params.text_track_background_color =
+ ConvertJavaStringToUTF8(env, textTrackBackgroundColor);
+ params.text_track_font_family =
+ ConvertJavaStringToUTF8(env, textTrackFontFamily);
+ params.text_track_font_style =
+ ConvertJavaStringToUTF8(env, textTrackFontStyle);
+ params.text_track_font_variant =
+ ConvertJavaStringToUTF8(env, textTrackFontVariant);
+ params.text_track_text_color =
+ ConvertJavaStringToUTF8(env, textTrackTextColor);
+ params.text_track_text_shadow =
+ ConvertJavaStringToUTF8(env, textTrackTextShadow);
+ params.text_track_text_size = ConvertJavaStringToUTF8(env, textTrackTextSize);
+ static_cast<WebContentsImpl*>(web_contents())
+ ->GetMainFrame()
+ ->SetTextTrackSettings(params);
+}
+
+jlong JNI_CaptioningController_Init(
+ JNIEnv* env,
+ const JavaParamRef<jobject>& obj,
+ const JavaParamRef<jobject>& jweb_contents) {
+ WebContentsImpl* web_contents = static_cast<WebContentsImpl*>(
+ WebContents::FromJavaWebContents(jweb_contents));
+ CHECK(web_contents);
+ return reinterpret_cast<intptr_t>(
+ new CaptioningController(env, obj, web_contents));
+}
+
+} // namespace content
diff --git a/chromium/content/browser/accessibility/captioning_controller.h b/chromium/content/browser/accessibility/captioning_controller.h
new file mode 100644
index 00000000000..7878045c96d
--- /dev/null
+++ b/chromium/content/browser/accessibility/captioning_controller.h
@@ -0,0 +1,55 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_BROWSER_ACCESSIBILITY_CAPTIONING_CONTROLLER_H_
+#define CONTENT_BROWSER_ACCESSIBILITY_CAPTIONING_CONTROLLER_H_
+
+#include "base/android/jni_android.h"
+#include "base/android/jni_weak_ref.h"
+#include "base/android/scoped_java_ref.h"
+#include "base/macros.h"
+#include "content/public/browser/web_contents_observer.h"
+
+namespace content {
+
+class WebContents;
+
+// System captioning bridge for Android. Owns itself, and gets destroyed
+// together with WebContents.
+class CaptioningController : public WebContentsObserver {
+ public:
+ CaptioningController(JNIEnv* env,
+ const base::android::JavaRef<jobject>& obj,
+ WebContents* web_contents);
+
+ ~CaptioningController() override;
+
+ void SetTextTrackSettings(
+ JNIEnv* env,
+ const base::android::JavaParamRef<jobject>& obj,
+ jboolean textTracksEnabled,
+ const base::android::JavaParamRef<jstring>& textTrackBackgroundColor,
+ const base::android::JavaParamRef<jstring>& textTrackFontFamily,
+ const base::android::JavaParamRef<jstring>& textTrackFontStyle,
+ const base::android::JavaParamRef<jstring>& textTrackFontVariant,
+ const base::android::JavaParamRef<jstring>& textTrackTextColor,
+ const base::android::JavaParamRef<jstring>& textTrackTextShadow,
+ const base::android::JavaParamRef<jstring>& textTrackTextSize);
+
+ private:
+ // WebContentsObserver implementation.
+ void RenderViewReady() override;
+ void RenderViewHostChanged(RenderViewHost* old_host,
+ RenderViewHost* new_host) override;
+ void WebContentsDestroyed() override;
+
+ // A weak reference to the Java CaptioningController object.
+ JavaObjectWeakGlobalRef java_ref_;
+
+ DISALLOW_COPY_AND_ASSIGN(CaptioningController);
+};
+
+} // namespace content
+
+#endif // CONTENT_BROWSER_ACCESSIBILITY_CAPTIONING_CONTROLLER_H_
diff --git a/chromium/content/browser/accessibility/dump_accessibility_browsertest_base.cc b/chromium/content/browser/accessibility/dump_accessibility_browsertest_base.cc
index 768ebc90d04..c97d5c92642 100644
--- a/chromium/content/browser/accessibility/dump_accessibility_browsertest_base.cc
+++ b/chromium/content/browser/accessibility/dump_accessibility_browsertest_base.cc
@@ -355,6 +355,8 @@ void DumpAccessibilityTestBase::RunTestForPlatform(
// Call the subclass to dump the output.
std::vector<std::string> actual_lines = Dump();
+ std::string actual_contents_for_output =
+ base::JoinString(actual_lines, "\n") + "\n";
// Perform a diff (or write the initial baseline).
std::vector<std::string> expected_lines = base::SplitString(
@@ -394,19 +396,18 @@ void DumpAccessibilityTestBase::RunTestForPlatform(
diff += "------\n";
diff += actual_contents;
LOG(ERROR) << "Diff:\n" << diff;
-
- if (base::CommandLine::ForCurrentProcess()->HasSwitch(
- switches::kGenerateAccessibilityTestExpectations)) {
- base::ThreadRestrictions::ScopedAllowIO allow_io_to_write_expected_file;
- CHECK(base::WriteFile(expected_file, actual_contents.c_str(),
- actual_contents.size()) ==
- static_cast<int>(actual_contents.size()));
- LOG(INFO) << "Wrote expectations to: "
- << expected_file.LossyDisplayName();
- }
} else {
LOG(INFO) << "Test output matches expectations.";
}
+
+ if (base::CommandLine::ForCurrentProcess()->HasSwitch(
+ switches::kGenerateAccessibilityTestExpectations)) {
+ base::ScopedAllowBlockingForTesting allow_blocking;
+ CHECK(base::WriteFile(expected_file, actual_contents_for_output.c_str(),
+ actual_contents_for_output.size()) ==
+ static_cast<int>(actual_contents_for_output.size()));
+ LOG(INFO) << "Wrote expectations to: " << expected_file.LossyDisplayName();
+ }
}
} // namespace content
diff --git a/chromium/content/browser/accessibility/dump_accessibility_browsertest_base.h b/chromium/content/browser/accessibility/dump_accessibility_browsertest_base.h
index 5db8c81c084..0dfb953b1a4 100644
--- a/chromium/content/browser/accessibility/dump_accessibility_browsertest_base.h
+++ b/chromium/content/browser/accessibility/dump_accessibility_browsertest_base.h
@@ -22,6 +22,8 @@ namespace content {
//
// The system was inspired by WebKit/Blink LayoutTests, but customized for
// testing accessibility in Chromium.
+//
+// See content/test/data/accessibility/readme.md for an overview.
class DumpAccessibilityTestBase : public ContentBrowserTest {
public:
DumpAccessibilityTestBase();
diff --git a/chromium/content/browser/accessibility/dump_accessibility_events_browsertest.cc b/chromium/content/browser/accessibility/dump_accessibility_events_browsertest.cc
index 91050816aef..09c6ba4cdf1 100644
--- a/chromium/content/browser/accessibility/dump_accessibility_events_browsertest.cc
+++ b/chromium/content/browser/accessibility/dump_accessibility_events_browsertest.cc
@@ -29,6 +29,8 @@ namespace content {
typedef AccessibilityTreeFormatter::Filter Filter;
+// See content/test/data/accessibility/readme.md for an overview.
+//
// Tests that the right platform-specific accessibility events are fired
// in response to things that happen in a web document.
//
@@ -62,6 +64,9 @@ typedef AccessibilityTreeFormatter::Filter Filter;
class DumpAccessibilityEventsTest : public DumpAccessibilityTestBase {
public:
void AddDefaultFilters(std::vector<Filter>* filters) override {
+ // Suppress spurious focus events on the document object.
+ filters->push_back(Filter(
+ base::ASCIIToUTF16("EVENT_OBJECT_FOCUS*DOCUMENT*"), Filter::DENY));
}
std::vector<std::string> Dump() override;
@@ -81,6 +86,7 @@ std::vector<std::string> DumpAccessibilityEventsTest::Dump() {
std::unique_ptr<AccessibilityEventRecorder> event_recorder(
AccessibilityEventRecorder::Create(
web_contents->GetRootBrowserAccessibilityManager(), pid));
+ event_recorder->set_only_web_events(true);
// Save a copy of the accessibility tree (as a text dump); we'll
// log this for the user later if the test fails.
@@ -126,6 +132,12 @@ std::vector<std::string> DumpAccessibilityEventsTest::Dump() {
result.push_back(event_logs[i]);
}
}
+
+ // Sort the logs so that results are predictable. There are too many
+ // nondeterministic things that affect the exact order of events fired,
+ // so these tests shouldn't be used to make assertions about event order.
+ std::sort(result.begin(), result.end());
+
return result;
}
diff --git a/chromium/content/browser/accessibility/dump_accessibility_tree_browsertest.cc b/chromium/content/browser/accessibility/dump_accessibility_tree_browsertest.cc
index d3573959c46..41d6b68e6ff 100644
--- a/chromium/content/browser/accessibility/dump_accessibility_tree_browsertest.cc
+++ b/chromium/content/browser/accessibility/dump_accessibility_tree_browsertest.cc
@@ -43,6 +43,8 @@ namespace content {
typedef AccessibilityTreeFormatter::Filter Filter;
+// See content/test/data/accessibility/readme.md for an overview.
+//
// This test takes a snapshot of the platform BrowserAccessibility tree and
// tests it against an expected baseline.
//
@@ -356,10 +358,17 @@ IN_PROC_BROWSER_TEST_F(DumpAccessibilityTreeTest, AccessibilityAriaAlert) {
RunAriaTest(FILE_PATH_LITERAL("aria-alert.html"));
}
+#if defined(OS_WIN)
+IN_PROC_BROWSER_TEST_F(DumpAccessibilityTreeTest,
+ DISABLED_AccessibilityAriaAlertDialog) {
+ RunAriaTest(FILE_PATH_LITERAL("aria-alertdialog.html"));
+}
+#else
IN_PROC_BROWSER_TEST_F(DumpAccessibilityTreeTest,
AccessibilityAriaAlertDialog) {
RunAriaTest(FILE_PATH_LITERAL("aria-alertdialog.html"));
}
+#endif
IN_PROC_BROWSER_TEST_F(DumpAccessibilityTreeTest,
AccessibilityAriaApplication) {
@@ -417,6 +426,11 @@ IN_PROC_BROWSER_TEST_F(DumpAccessibilityTreeTest, AccessibilityAriaCombobox) {
}
IN_PROC_BROWSER_TEST_F(DumpAccessibilityTreeTest,
+ AccessibilityAriaOnePointOneCombobox) {
+ RunAriaTest(FILE_PATH_LITERAL("aria1.1-combobox.html"));
+}
+
+IN_PROC_BROWSER_TEST_F(DumpAccessibilityTreeTest,
AccessibilityAriaComplementary) {
RunAriaTest(FILE_PATH_LITERAL("aria-complementary.html"));
}
diff --git a/chromium/content/browser/accessibility/fullscreen_browsertest.cc b/chromium/content/browser/accessibility/fullscreen_browsertest.cc
index e22667f40d0..dbc3358655b 100644
--- a/chromium/content/browser/accessibility/fullscreen_browsertest.cc
+++ b/chromium/content/browser/accessibility/fullscreen_browsertest.cc
@@ -106,7 +106,9 @@ IN_PROC_BROWSER_TEST_F(AccessibilityFullscreenBrowserTest,
EXPECT_EQ(1, CountLinks(manager->GetRoot()));
}
-IN_PROC_BROWSER_TEST_F(AccessibilityFullscreenBrowserTest, InsideIFrame) {
+// Fails flakily on all platforms: crbug.com/825735
+IN_PROC_BROWSER_TEST_F(AccessibilityFullscreenBrowserTest,
+ DISABLED_InsideIFrame) {
ASSERT_TRUE(embedded_test_server()->Start());
FakeFullscreenDelegate delegate;
diff --git a/chromium/content/browser/accessibility/snapshot_ax_tree_browsertest.cc b/chromium/content/browser/accessibility/snapshot_ax_tree_browsertest.cc
index b3ef560870c..2d43f8bc888 100644
--- a/chromium/content/browser/accessibility/snapshot_ax_tree_browsertest.cc
+++ b/chromium/content/browser/accessibility/snapshot_ax_tree_browsertest.cc
@@ -68,15 +68,16 @@ class SnapshotAXTreeBrowserTest : public ContentBrowserTest {
IN_PROC_BROWSER_TEST_F(SnapshotAXTreeBrowserTest,
SnapshotAccessibilityTreeFromWebContents) {
GURL url("data:text/html,<button>Click</button>");
- NavigateToURL(shell(), url);
+ EXPECT_TRUE(NavigateToURL(shell(), url));
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
AXTreeSnapshotWaiter waiter;
web_contents->RequestAXTreeSnapshot(
- base::Bind(&AXTreeSnapshotWaiter::ReceiveSnapshot,
- base::Unretained(&waiter)));
+ base::BindOnce(&AXTreeSnapshotWaiter::ReceiveSnapshot,
+ base::Unretained(&waiter)),
+ ui::kAXModeComplete);
waiter.Wait();
// Dump the whole tree if one of the assertions below fails
@@ -97,8 +98,9 @@ IN_PROC_BROWSER_TEST_F(SnapshotAXTreeBrowserTest,
SnapshotAccessibilityTreeFromMultipleFrames) {
ASSERT_TRUE(embedded_test_server()->Start());
- NavigateToURL(shell(), embedded_test_server()->GetURL(
- "/accessibility/snapshot/outer.html"));
+ EXPECT_TRUE(NavigateToURL(
+ shell(),
+ embedded_test_server()->GetURL("/accessibility/snapshot/outer.html")));
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
@@ -110,8 +112,9 @@ IN_PROC_BROWSER_TEST_F(SnapshotAXTreeBrowserTest,
AXTreeSnapshotWaiter waiter;
web_contents->RequestAXTreeSnapshot(
- base::Bind(&AXTreeSnapshotWaiter::ReceiveSnapshot,
- base::Unretained(&waiter)));
+ base::BindOnce(&AXTreeSnapshotWaiter::ReceiveSnapshot,
+ base::Unretained(&waiter)),
+ ui::kAXModeComplete);
waiter.Wait();
// Dump the whole tree if one of the assertions below fails
@@ -142,4 +145,118 @@ IN_PROC_BROWSER_TEST_F(SnapshotAXTreeBrowserTest,
dump);
}
+// This tests to make sure that RequestAXTreeSnapshot() correctly traverses
+// inner contents, as used in features like <webview>.
+IN_PROC_BROWSER_TEST_F(SnapshotAXTreeBrowserTest,
+ SnapshotAccessibilityTreeWithInnerContents) {
+ ASSERT_TRUE(embedded_test_server()->Start());
+
+ EXPECT_TRUE(NavigateToURL(
+ shell(),
+ embedded_test_server()->GetURL("/accessibility/snapshot/outer.html")));
+
+ WebContentsImpl* web_contents =
+ static_cast<WebContentsImpl*>(shell()->web_contents());
+ FrameTreeNode* root_frame = web_contents->GetFrameTree()->root();
+
+ NavigateFrameToURL(root_frame->child_at(0), GURL("data:text/plain,Alpha"));
+
+ WebContentsImpl* inner_contents =
+ static_cast<WebContentsImpl*>(CreateAndAttachInnerContents(
+ root_frame->child_at(1)->current_frame_host()));
+ NavigateFrameToURL(
+ inner_contents->GetFrameTree()->root(),
+ embedded_test_server()->GetURL("/accessibility/snapshot/inner.html"));
+
+ AXTreeSnapshotWaiter waiter;
+ web_contents->RequestAXTreeSnapshot(
+ base::BindOnce(&AXTreeSnapshotWaiter::ReceiveSnapshot,
+ base::Unretained(&waiter)),
+ ui::kAXModeComplete);
+ waiter.Wait();
+
+ // Dump the whole tree if one of the assertions below fails
+ // to aid in debugging why it failed.
+ SCOPED_TRACE(waiter.snapshot().ToString());
+
+ ui::AXTree tree(waiter.snapshot());
+ ui::AXNode* root = tree.root();
+ std::string dump;
+ DumpRolesAndNamesAsText(root, 0, &dump);
+ EXPECT_EQ(
+ "rootWebArea\n"
+ " genericContainer\n"
+ " button 'Before'\n"
+ " iframe\n"
+ " rootWebArea\n"
+ " pre\n"
+ " staticText 'Alpha'\n"
+ " button 'Middle'\n"
+ " iframe\n"
+ " rootWebArea\n"
+ " genericContainer\n"
+ " button 'Inside Before'\n"
+ " iframe\n"
+ " rootWebArea\n"
+ " button 'Inside After'\n"
+ " button 'After'\n",
+ dump);
+}
+
+// This tests to make sure that snapshotting with different modes gives
+// different results. This is not intended to ensure that specific modes give
+// specific attributes, but merely to ensure that the mode parameter makes a
+// difference.
+IN_PROC_BROWSER_TEST_F(SnapshotAXTreeBrowserTest,
+ SnapshotAccessibilityTreeModes) {
+ GURL url("data:text/html,<button>Click</button>");
+ EXPECT_TRUE(NavigateToURL(shell(), url));
+
+ WebContentsImpl* web_contents =
+ static_cast<WebContentsImpl*>(shell()->web_contents());
+
+ AXTreeSnapshotWaiter waiter_complete;
+ web_contents->RequestAXTreeSnapshot(
+ base::BindOnce(&AXTreeSnapshotWaiter::ReceiveSnapshot,
+ base::Unretained(&waiter_complete)),
+ ui::kAXModeComplete);
+ waiter_complete.Wait();
+ const std::vector<ui::AXNodeData>& complete_nodes =
+ waiter_complete.snapshot().nodes;
+
+ // Dump the whole tree if one of the assertions below fails
+ // to aid in debugging why it failed.
+ SCOPED_TRACE(waiter_complete.snapshot().ToString());
+
+ AXTreeSnapshotWaiter waiter_contents;
+ web_contents->RequestAXTreeSnapshot(
+ base::BindOnce(&AXTreeSnapshotWaiter::ReceiveSnapshot,
+ base::Unretained(&waiter_contents)),
+ ui::AXMode::kWebContents);
+ waiter_contents.Wait();
+ const std::vector<ui::AXNodeData>& contents_nodes =
+ waiter_contents.snapshot().nodes;
+
+ // Dump the whole tree if one of the assertions below fails
+ // to aid in debugging why it failed.
+ SCOPED_TRACE(waiter_contents.snapshot().ToString());
+
+ // The two snapshot passes walked the tree in the same order, so comparing
+ // element to element is possible by walking the snapshots in parallel.
+
+ auto total_attribute_count = [](const ui::AXNodeData& node_data) {
+ return node_data.string_attributes.size() +
+ node_data.int_attributes.size() + node_data.float_attributes.size() +
+ node_data.bool_attributes.size() +
+ node_data.intlist_attributes.size() +
+ node_data.stringlist_attributes.size() +
+ node_data.html_attributes.size();
+ };
+
+ ASSERT_EQ(complete_nodes.size(), contents_nodes.size());
+ for (size_t i = 0; i < complete_nodes.size(); ++i)
+ EXPECT_LT(total_attribute_count(contents_nodes[i]),
+ total_attribute_count(complete_nodes[i]));
+}
+
} // namespace content
diff --git a/chromium/content/browser/accessibility/web_contents_accessibility_android.cc b/chromium/content/browser/accessibility/web_contents_accessibility_android.cc
index c2d3d1bf8cf..5e7ccb79c98 100644
--- a/chromium/content/browser/accessibility/web_contents_accessibility_android.cc
+++ b/chromium/content/browser/accessibility/web_contents_accessibility_android.cc
@@ -1085,7 +1085,7 @@ void WebContentsAccessibilityAndroid::OnAutofillPopupDisplayed(
ax_node_data.SetName("Autofill");
ax_node_data.SetRestriction(ax::mojom::Restriction::kReadOnly);
ax_node_data.AddState(ax::mojom::State::kFocusable);
- ax_node_data.AddState(ax::mojom::State::kSelectable);
+ ax_node_data.AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, false);
g_autofill_popup_proxy_node_ax_node->SetData(ax_node_data);
g_autofill_popup_proxy_node->Init(root_manager_,
g_autofill_popup_proxy_node_ax_node);
diff --git a/chromium/content/browser/android/app_web_message_port.h b/chromium/content/browser/android/app_web_message_port.h
index e94cb4ac637..2dd94028094 100644
--- a/chromium/content/browser/android/app_web_message_port.h
+++ b/chromium/content/browser/android/app_web_message_port.h
@@ -6,7 +6,7 @@
#define CONTENT_BROWSER_ANDROID_APP_WEB_MESSAGE_PORT_H_
#include "base/android/jni_weak_ref.h"
-#include "third_party/WebKit/public/common/message_port/message_port_channel.h"
+#include "third_party/blink/public/common/message_port/message_port_channel.h"
namespace content {
diff --git a/chromium/content/browser/android/browser_startup_controller.cc b/chromium/content/browser/android/browser_startup_controller.cc
index 7a8bb0b76df..67c5bb1167e 100644
--- a/chromium/content/browser/android/browser_startup_controller.cc
+++ b/chromium/content/browser/android/browser_startup_controller.cc
@@ -8,7 +8,7 @@
#include "base/android/jni_string.h"
#include "content/browser/android/content_startup_flags.h"
#include "content/browser/browser_main_loop.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#include "jni/BrowserStartupController_jni.h"
diff --git a/chromium/content/browser/android/content_feature_list.cc b/chromium/content/browser/android/content_feature_list.cc
index 9cdddbefcc4..2cff63192ea 100644
--- a/chromium/content/browser/android/content_feature_list.cc
+++ b/chromium/content/browser/android/content_feature_list.cc
@@ -22,7 +22,7 @@ namespace {
// this array may either refer to features defined in the header of this file or
// in other locations in the code base (e.g. content_features.h).
const base::Feature* kFeaturesExposedToJava[] = {
- &kEnhancedSelectionInsertionHandle, &kRequestUnbufferedDispatch,
+ &kEnhancedSelectionInsertionHandle,
};
const base::Feature* FindFeatureExposedToJava(const std::string& feature_name) {
diff --git a/chromium/content/browser/android/content_video_view.cc b/chromium/content/browser/android/content_video_view.cc
index 9df12f90ff6..f057fe9e734 100644
--- a/chromium/content/browser/android/content_video_view.cc
+++ b/chromium/content/browser/android/content_video_view.cc
@@ -5,6 +5,7 @@
#include "content/browser/android/content_video_view.h"
#include "base/metrics/histogram_macros.h"
+#include "content/public/browser/web_contents.h"
#include "jni/ContentVideoView_jni.h"
using base::android::AttachCurrentThread;
@@ -37,13 +38,13 @@ ContentVideoView* ContentVideoView::GetInstance() {
}
ContentVideoView::ContentVideoView(Client* client,
- ContentViewCore* content_view_core,
+ WebContents* web_contents,
const JavaRef<jobject>& video_embedder,
const gfx::Size& video_natural_size)
: client_(client), weak_factory_(this) {
DCHECK(!g_content_video_view);
j_content_video_view_ =
- CreateJavaObject(content_view_core, video_embedder, video_natural_size);
+ CreateJavaObject(web_contents, video_embedder, video_natural_size);
g_content_video_view = this;
}
@@ -151,21 +152,21 @@ void ContentVideoView::RecordExitFullscreenPlayback(
}
JavaObjectWeakGlobalRef ContentVideoView::CreateJavaObject(
- ContentViewCore* content_view_core,
+ WebContents* web_contents,
const JavaRef<jobject>& j_content_video_view_embedder,
const gfx::Size& video_natural_size) {
JNIEnv* env = AttachCurrentThread();
- base::android::ScopedJavaLocalRef<jobject> j_content_view_core =
- content_view_core->GetJavaObject();
+ base::android::ScopedJavaLocalRef<jobject> j_web_contents =
+ web_contents->GetJavaWebContents();
- if (j_content_view_core.is_null())
+ if (j_web_contents.is_null())
return JavaObjectWeakGlobalRef(env, nullptr);
return JavaObjectWeakGlobalRef(
env, Java_ContentVideoView_createContentVideoView(
- env, j_content_view_core, j_content_video_view_embedder,
- reinterpret_cast<intptr_t>(this),
- video_natural_size.width(), video_natural_size.height())
+ env, j_web_contents, j_content_video_view_embedder,
+ reinterpret_cast<intptr_t>(this), video_natural_size.width(),
+ video_natural_size.height())
.obj());
}
} // namespace content
diff --git a/chromium/content/browser/android/content_video_view.h b/chromium/content/browser/android/content_video_view.h
index 6d10e88cd3b..e070327c1a7 100644
--- a/chromium/content/browser/android/content_video_view.h
+++ b/chromium/content/browser/android/content_video_view.h
@@ -11,11 +11,16 @@
#include "base/android/scoped_java_ref.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
-#include "content/browser/android/content_view_core.h"
#include "ui/gl/android/scoped_java_surface.h"
+namespace gfx {
+class Size;
+}
+
namespace content {
+class WebContents;
+
// Native mirror of ContentVideoView.java. This class is responsible for
// creating the Java video view and passing changes in player status to it.
// This class must be used on the UI thread.
@@ -43,7 +48,7 @@ class ContentVideoView {
};
explicit ContentVideoView(Client* client,
- ContentViewCore* content_view_core,
+ WebContents* web_contents,
const base::android::JavaRef<jobject>& embedder,
const gfx::Size& video_natural_size);
~ContentVideoView();
@@ -90,7 +95,7 @@ class ContentVideoView {
private:
// Creates the corresponding ContentVideoView Java object.
JavaObjectWeakGlobalRef CreateJavaObject(
- ContentViewCore* content_view_core,
+ WebContents* web_contents,
const base::android::JavaRef<jobject>& j_content_video_view_embedder,
const gfx::Size& video_natural_size);
diff --git a/chromium/content/browser/android/content_view_core.cc b/chromium/content/browser/android/content_view_core.cc
index 98295d26c89..37e331fec3a 100644
--- a/chromium/content/browser/android/content_view_core.cc
+++ b/chromium/content/browser/android/content_view_core.cc
@@ -4,182 +4,37 @@
#include "content/browser/android/content_view_core.h"
-#include <stddef.h>
-
#include "base/android/jni_android.h"
-#include "base/android/jni_array.h"
-#include "base/android/jni_string.h"
-#include "base/android/scoped_java_ref.h"
-#include "base/command_line.h"
-#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/metrics/histogram_macros.h"
#include "base/metrics/user_metrics.h"
-#include "base/strings/string_util.h"
-#include "base/values.h"
#include "cc/layers/layer.h"
-#include "cc/layers/solid_color_layer.h"
-#include "components/viz/common/frame_sinks/begin_frame_args.h"
-#include "content/browser/android/interstitial_page_delegate_android.h"
#include "content/browser/frame_host/interstitial_page_impl.h"
-#include "content/browser/media/media_web_contents_observer.h"
-#include "content/browser/renderer_host/compositor_impl_android.h"
-#include "content/browser/renderer_host/input/web_input_event_builders_android.h"
-#include "content/browser/renderer_host/render_view_host_impl.h"
-#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_view_android.h"
-#include "content/browser/web_contents/web_contents_android.h"
+#include "content/browser/web_contents/web_contents_impl.h"
#include "content/browser/web_contents/web_contents_view_android.h"
-#include "content/common/frame_messages.h"
-#include "content/common/input_messages.h"
-#include "content/common/view_messages.h"
-#include "content/public/browser/android/compositor.h"
-#include "content/public/browser/browser_context.h"
-#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/favicon_status.h"
-#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_view_host.h"
-#include "content/public/browser/ssl_host_state_delegate.h"
-#include "content/public/browser/web_contents.h"
#include "content/public/common/content_client.h"
-#include "content/public/common/content_switches.h"
-#include "content/public/common/menu_item.h"
-#include "content/public/common/use_zoom_for_dsf_policy.h"
#include "content/public/common/user_agent.h"
#include "jni/ContentViewCoreImpl_jni.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
-#include "ui/android/view_android.h"
#include "ui/android/window_android.h"
-#include "ui/events/android/gesture_event_type.h"
-#include "ui/events/blink/blink_event_util.h"
-#include "ui/events/blink/web_input_event_traits.h"
-#include "ui/events/event_utils.h"
-#include "ui/events/gesture_detection/motion_event.h"
-#include "ui/gfx/android/java_bitmap.h"
-#include "ui/gfx/geometry/point_conversions.h"
-#include "ui/gfx/geometry/size_conversions.h"
-#include "ui/gfx/geometry/size_f.h"
using base::android::AttachCurrentThread;
-using base::android::ConvertJavaStringToUTF16;
-using base::android::ConvertJavaStringToUTF8;
-using base::android::ConvertUTF16ToJavaString;
-using base::android::ConvertUTF8ToJavaString;
using base::android::JavaParamRef;
using base::android::JavaRef;
using base::android::ScopedJavaLocalRef;
-using blink::WebGestureEvent;
-using blink::WebInputEvent;
namespace content {
namespace {
-// Describes the type and enabled state of a select popup item.
-//
-// A Java counterpart will be generated for this enum.
-// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.content.browser.input
-enum PopupItemType {
- // Popup item is of type group
- POPUP_ITEM_TYPE_GROUP,
-
- // Popup item is disabled
- POPUP_ITEM_TYPE_DISABLED,
-
- // Popup item is enabled
- POPUP_ITEM_TYPE_ENABLED,
-};
-
-const void* const kContentViewUserDataKey = &kContentViewUserDataKey;
-
-int GetRenderProcessIdFromRenderViewHost(RenderViewHost* host) {
- DCHECK(host);
- RenderProcessHost* render_process = host->GetProcess();
- DCHECK(render_process);
- if (render_process->HasConnection())
- return render_process->GetHandle();
- return 0;
-}
-
-int ToGestureEventType(WebInputEvent::Type type) {
- switch (type) {
- case WebInputEvent::kGestureScrollBegin:
- return ui::GESTURE_EVENT_TYPE_SCROLL_START;
- case WebInputEvent::kGestureScrollEnd:
- return ui::GESTURE_EVENT_TYPE_SCROLL_END;
- case WebInputEvent::kGestureScrollUpdate:
- return ui::GESTURE_EVENT_TYPE_SCROLL_BY;
- case WebInputEvent::kGestureFlingStart:
- return ui::GESTURE_EVENT_TYPE_FLING_START;
- case WebInputEvent::kGestureFlingCancel:
- return ui::GESTURE_EVENT_TYPE_FLING_CANCEL;
- case WebInputEvent::kGestureShowPress:
- return ui::GESTURE_EVENT_TYPE_SHOW_PRESS;
- case WebInputEvent::kGestureTap:
- return ui::GESTURE_EVENT_TYPE_SINGLE_TAP_CONFIRMED;
- case WebInputEvent::kGestureTapUnconfirmed:
- return ui::GESTURE_EVENT_TYPE_SINGLE_TAP_UNCONFIRMED;
- case WebInputEvent::kGestureTapDown:
- return ui::GESTURE_EVENT_TYPE_TAP_DOWN;
- case WebInputEvent::kGestureTapCancel:
- return ui::GESTURE_EVENT_TYPE_TAP_CANCEL;
- case WebInputEvent::kGestureDoubleTap:
- return ui::GESTURE_EVENT_TYPE_DOUBLE_TAP;
- case WebInputEvent::kGestureLongPress:
- return ui::GESTURE_EVENT_TYPE_LONG_PRESS;
- case WebInputEvent::kGestureLongTap:
- return ui::GESTURE_EVENT_TYPE_LONG_TAP;
- case WebInputEvent::kGesturePinchBegin:
- return ui::GESTURE_EVENT_TYPE_PINCH_BEGIN;
- case WebInputEvent::kGesturePinchEnd:
- return ui::GESTURE_EVENT_TYPE_PINCH_END;
- case WebInputEvent::kGesturePinchUpdate:
- return ui::GESTURE_EVENT_TYPE_PINCH_BY;
- case WebInputEvent::kGestureTwoFingerTap:
- default:
- NOTREACHED() << "Invalid source gesture type: "
- << WebInputEvent::GetName(type);
- return -1;
- }
+RenderWidgetHostViewAndroid* GetRenderWidgetHostViewFromHost(
+ RenderViewHost* host) {
+ return static_cast<RenderWidgetHostViewAndroid*>(
+ host->GetWidget()->GetView());
}
} // namespace
-// Enables a callback when the underlying WebContents is destroyed, to enable
-// nulling the back-pointer.
-class ContentViewCore::ContentViewUserData
- : public base::SupportsUserData::Data {
- public:
- explicit ContentViewUserData(ContentViewCore* content_view_core)
- : content_view_core_(content_view_core) {}
-
- ~ContentViewUserData() override {
- // TODO(joth): When chrome has finished removing the TabContents class (see
- // crbug.com/107201) consider inverting relationship, so ContentViewCore
- // would own WebContents. That effectively implies making the WebContents
- // destructor private on Android.
- delete content_view_core_;
- }
-
- ContentViewCore* get() const { return content_view_core_; }
-
- private:
- // Not using scoped_ptr as ContentViewCore destructor is private.
- ContentViewCore* content_view_core_;
-
- DISALLOW_IMPLICIT_CONSTRUCTORS(ContentViewUserData);
-};
-
-// static
-ContentViewCore* ContentViewCore::FromWebContents(
- content::WebContents* web_contents) {
- ContentViewCore::ContentViewUserData* data =
- static_cast<ContentViewCore::ContentViewUserData*>(
- web_contents->GetUserData(kContentViewUserDataKey));
- return data ? data->get() : NULL;
-}
-
ContentViewCore::ContentViewCore(JNIEnv* env,
const JavaRef<jobject>& obj,
WebContents* web_contents,
@@ -189,7 +44,6 @@ ContentViewCore::ContentViewCore(JNIEnv* env,
web_contents_(static_cast<WebContentsImpl*>(web_contents)),
dpi_scale_(dpi_scale),
device_orientation_(0) {
- GetViewAndroid()->SetLayer(cc::Layer::Create());
// Currently, the only use case we have for overriding a user agent involves
// spoofing a desktop Linux user agent for "Request desktop site".
@@ -199,16 +53,10 @@ ContentViewCore::ContentViewCore(JNIEnv* env,
std::string product = content::GetContentClient()->GetProduct();
std::string spoofed_ua =
BuildUserAgentFromOSAndProduct(kLinuxInfoStr, product);
- web_contents->SetUserAgentOverride(spoofed_ua);
-
- InitWebContents();
+ web_contents->SetUserAgentOverride(spoofed_ua, false);
}
ContentViewCore::~ContentViewCore() {
- for (auto* host : web_contents_->GetAllRenderWidgetHosts()) {
- static_cast<RenderWidgetHostViewAndroid*>(host->GetView())
- ->OnContentViewCoreDestroyed();
- }
JNIEnv* env = base::android::AttachCurrentThread();
ScopedJavaLocalRef<jobject> j_obj = java_ref_.get(env);
java_ref_.reset();
@@ -235,20 +83,6 @@ void ContentViewCore::UpdateWindowAndroid(
window->AddChild(view);
}
-base::android::ScopedJavaLocalRef<jobject>
-ContentViewCore::GetWebContentsAndroid(JNIEnv* env,
- const JavaParamRef<jobject>& obj) {
- return web_contents_->GetJavaWebContents();
-}
-
-base::android::ScopedJavaLocalRef<jobject>
-ContentViewCore::GetJavaWindowAndroid(JNIEnv* env,
- const JavaParamRef<jobject>& obj) {
- if (!GetWindowAndroid())
- return ScopedJavaLocalRef<jobject>();
- return GetWindowAndroid()->GetJavaObject();
-}
-
void ContentViewCore::OnJavaContentViewCoreDestroyed(
JNIEnv* env,
const JavaParamRef<jobject>& obj) {
@@ -256,63 +90,29 @@ void ContentViewCore::OnJavaContentViewCoreDestroyed(
java_ref_.reset();
// Java peer has gone, ContentViewCore is not functional and waits to
// be destroyed with WebContents.
- // We need to reset WebContentsViewAndroid's reference, otherwise, there
- // could have call in when swapping the WebContents,
- // see http://crbug.com/383939 .
- DCHECK(web_contents_);
- static_cast<WebContentsViewAndroid*>(
- static_cast<WebContentsImpl*>(web_contents_)->GetView())
- ->SetContentViewCore(NULL);
-}
-
-void ContentViewCore::InitWebContents() {
DCHECK(web_contents_);
- static_cast<WebContentsViewAndroid*>(
- static_cast<WebContentsImpl*>(web_contents_)->GetView())
- ->SetContentViewCore(this);
- DCHECK(!web_contents_->GetUserData(kContentViewUserDataKey));
- web_contents_->SetUserData(kContentViewUserDataKey,
- std::make_unique<ContentViewUserData>(this));
}
void ContentViewCore::RenderViewReady() {
- JNIEnv* env = AttachCurrentThread();
- ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
- if (!obj.is_null())
- Java_ContentViewCoreImpl_onRenderProcessChange(env, obj);
-
if (device_orientation_ != 0)
SendOrientationChangeEventInternal();
}
+void ContentViewCore::WebContentsDestroyed() {
+ delete this;
+}
+
void ContentViewCore::RenderViewHostChanged(RenderViewHost* old_host,
RenderViewHost* new_host) {
- int old_pid = 0;
if (old_host) {
- old_pid = GetRenderProcessIdFromRenderViewHost(old_host);
-
- RenderWidgetHostViewAndroid* view =
- static_cast<RenderWidgetHostViewAndroid*>(
- old_host->GetWidget()->GetView());
+ auto* view = GetRenderWidgetHostViewFromHost(old_host);
if (view)
- view->SetContentViewCore(NULL);
+ view->UpdateNativeViewTree(nullptr);
- view = static_cast<RenderWidgetHostViewAndroid*>(
- new_host->GetWidget()->GetView());
+ view = GetRenderWidgetHostViewFromHost(new_host);
if (view)
- view->SetContentViewCore(this);
- }
- int new_pid =
- GetRenderProcessIdFromRenderViewHost(web_contents_->GetRenderViewHost());
- if (new_pid != old_pid) {
- // Notify the Java side that the renderer process changed.
- JNIEnv* env = AttachCurrentThread();
- ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
- if (!obj.is_null()) {
- Java_ContentViewCoreImpl_onRenderProcessChange(env, obj);
- }
+ view->UpdateNativeViewTree(GetViewAndroid());
}
-
SetFocusInternal(GetViewAndroid()->HasFocus());
}
@@ -332,174 +132,6 @@ RenderWidgetHostViewAndroid* ContentViewCore::GetRenderWidgetHostViewAndroid()
return static_cast<RenderWidgetHostViewAndroid*>(rwhv);
}
-ScopedJavaLocalRef<jobject> ContentViewCore::GetJavaObject() {
- JNIEnv* env = AttachCurrentThread();
- return java_ref_.get(env);
-}
-
-jint ContentViewCore::GetBackgroundColor(JNIEnv* env, jobject obj) {
- RenderWidgetHostViewAndroid* rwhva = GetRenderWidgetHostViewAndroid();
- if (!rwhva)
- return SK_ColorWHITE;
- return rwhva->GetCachedBackgroundColor();
-}
-
-// All positions and sizes (except |top_shown_pix|) are in CSS pixels.
-// Note that viewport_width/height is a best effort based.
-// ContentViewCore has the actual information about the physical viewport size.
-void ContentViewCore::UpdateFrameInfo(const gfx::Vector2dF& scroll_offset,
- float page_scale_factor,
- const float min_page_scale,
- const float max_page_scale,
- const gfx::SizeF& content_size,
- const gfx::SizeF& viewport_size,
- const float content_offset,
- const float top_shown_pix,
- bool top_changed,
- bool is_mobile_optimized_hint) {
- JNIEnv* env = AttachCurrentThread();
- ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
- if (obj.is_null() || !GetWindowAndroid())
- return;
-
- GetViewAndroid()->UpdateFrameInfo({viewport_size, content_offset});
-
- // Current viewport size in css.
- gfx::SizeF view_size = gfx::SizeF(gfx::ScaleToCeiledSize(
- GetViewportSizePix(), 1.0f / (dpi_scale() * page_scale_factor)));
-
- // Adjust content size to be always at least as big as the actual
- // viewport (as set by onSizeChanged).
- float content_width = std::max(content_size.width(), view_size.width());
- float content_height = std::max(content_size.height(), view_size.height());
-
- Java_ContentViewCoreImpl_updateFrameInfo(
- env, obj, scroll_offset.x(), scroll_offset.y(), page_scale_factor,
- min_page_scale, max_page_scale, content_width, content_height,
- viewport_size.width(), viewport_size.height(), top_shown_pix, top_changed,
- is_mobile_optimized_hint);
-}
-
-void ContentViewCore::ShowSelectPopupMenu(RenderFrameHost* frame,
- const gfx::Rect& bounds,
- const std::vector<MenuItem>& items,
- int selected_item,
- bool multiple,
- bool right_aligned) {
- JNIEnv* env = AttachCurrentThread();
- ScopedJavaLocalRef<jobject> j_obj = java_ref_.get(env);
- if (j_obj.is_null())
- return;
-
- // For multi-select list popups we find the list of previous selections by
- // iterating through the items. But for single selection popups we take the
- // given |selected_item| as is.
- ScopedJavaLocalRef<jintArray> selected_array;
- if (multiple) {
- std::unique_ptr<jint[]> native_selected_array(new jint[items.size()]);
- size_t selected_count = 0;
- for (size_t i = 0; i < items.size(); ++i) {
- if (items[i].checked)
- native_selected_array[selected_count++] = i;
- }
-
- selected_array =
- ScopedJavaLocalRef<jintArray>(env, env->NewIntArray(selected_count));
- env->SetIntArrayRegion(selected_array.obj(), 0, selected_count,
- native_selected_array.get());
- } else {
- selected_array = ScopedJavaLocalRef<jintArray>(env, env->NewIntArray(1));
- jint value = selected_item;
- env->SetIntArrayRegion(selected_array.obj(), 0, 1, &value);
- }
-
- ScopedJavaLocalRef<jintArray> enabled_array(env,
- env->NewIntArray(items.size()));
- std::vector<base::string16> labels;
- labels.reserve(items.size());
- for (size_t i = 0; i < items.size(); ++i) {
- labels.push_back(items[i].label);
- jint enabled = (items[i].type == MenuItem::GROUP
- ? POPUP_ITEM_TYPE_GROUP
- : (items[i].enabled ? POPUP_ITEM_TYPE_ENABLED
- : POPUP_ITEM_TYPE_DISABLED));
- env->SetIntArrayRegion(enabled_array.obj(), i, 1, &enabled);
- }
- ScopedJavaLocalRef<jobjectArray> items_array(
- base::android::ToJavaArrayOfStrings(env, labels));
- ui::ViewAndroid* view = GetViewAndroid();
- select_popup_ = view->AcquireAnchorView();
- const ScopedJavaLocalRef<jobject> popup_view = select_popup_.view();
- if (popup_view.is_null())
- return;
- // |bounds| is in physical pixels if --use-zoom-for-dsf is enabled. Otherwise,
- // it is in DIP pixels.
- gfx::RectF bounds_dip = gfx::RectF(bounds);
- if (IsUseZoomForDSFEnabled())
- bounds_dip.Scale(1 / dpi_scale_);
- view->SetAnchorRect(popup_view, bounds_dip);
- Java_ContentViewCoreImpl_showSelectPopup(
- env, j_obj, popup_view, reinterpret_cast<intptr_t>(frame), items_array,
- enabled_array, multiple, selected_array, right_aligned);
-}
-
-void ContentViewCore::HideSelectPopupMenu() {
- JNIEnv* env = AttachCurrentThread();
- ScopedJavaLocalRef<jobject> j_obj = java_ref_.get(env);
- if (!j_obj.is_null())
- Java_ContentViewCoreImpl_hideSelectPopup(env, j_obj);
- select_popup_.Reset();
-}
-
-bool ContentViewCore::FilterInputEvent(const blink::WebInputEvent& event) {
- if (event.GetType() != WebInputEvent::kGestureTap &&
- event.GetType() != WebInputEvent::kGestureLongTap &&
- event.GetType() != WebInputEvent::kGestureLongPress &&
- event.GetType() != WebInputEvent::kMouseDown)
- return false;
-
- JNIEnv* env = AttachCurrentThread();
- ScopedJavaLocalRef<jobject> j_obj = java_ref_.get(env);
- if (j_obj.is_null())
- return false;
-
- GetViewAndroid()->RequestFocus();
-
- if (event.GetType() == WebInputEvent::kMouseDown)
- return false;
-
- const blink::WebGestureEvent& gesture =
- static_cast<const blink::WebGestureEvent&>(event);
- int gesture_type = ToGestureEventType(event.GetType());
- return Java_ContentViewCoreImpl_filterTapOrPressEvent(
- env, j_obj, gesture_type, gesture.x * dpi_scale(),
- gesture.y * dpi_scale());
-}
-
-void ContentViewCore::RequestDisallowInterceptTouchEvent() {
- JNIEnv* env = AttachCurrentThread();
- ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
- if (!obj.is_null())
- Java_ContentViewCoreImpl_requestDisallowInterceptTouchEvent(env, obj);
-}
-
-gfx::Size ContentViewCore::GetViewportSizePix() const {
- JNIEnv* env = AttachCurrentThread();
- ScopedJavaLocalRef<jobject> j_obj = java_ref_.get(env);
- if (j_obj.is_null())
- return gfx::Size();
- return gfx::Size(Java_ContentViewCoreImpl_getViewportWidthPix(env, j_obj),
- Java_ContentViewCoreImpl_getViewportHeightPix(env, j_obj));
-}
-
-int ContentViewCore::GetMouseWheelMinimumGranularity() const {
- JNIEnv* env = AttachCurrentThread();
- ScopedJavaLocalRef<jobject> j_obj = java_ref_.get(env);
- if (j_obj.is_null())
- return 0;
- return Java_ContentViewCoreImpl_getMouseWheelTickMultiplier(env, j_obj);
-}
-
void ContentViewCore::SendScreenRectsAndResizeWidget() {
RenderWidgetHostViewAndroid* view = GetRenderWidgetHostViewAndroid();
if (view) {
@@ -521,32 +153,6 @@ ui::ViewAndroid* ContentViewCore::GetViewAndroid() const {
// Methods called from Java via JNI
// ----------------------------------------------------------------------------
-void ContentViewCore::SelectPopupMenuItems(
- JNIEnv* env,
- const JavaParamRef<jobject>& obj,
- jlong selectPopupSourceFrame,
- const JavaParamRef<jintArray>& indices) {
- RenderFrameHostImpl* rfhi =
- reinterpret_cast<RenderFrameHostImpl*>(selectPopupSourceFrame);
- DCHECK(rfhi);
- if (indices == NULL) {
- rfhi->DidCancelPopupMenu();
- return;
- }
-
- int selected_count = env->GetArrayLength(indices);
- std::vector<int> selected_indices;
- jint* indices_ptr = env->GetIntArrayElements(indices, NULL);
- for (int i = 0; i < selected_count; ++i)
- selected_indices.push_back(indices_ptr[i]);
- env->ReleaseIntArrayElements(indices, indices_ptr, JNI_ABORT);
- rfhi->DidSelectPopupMenuItems(selected_indices);
-}
-
-WebContents* ContentViewCore::GetWebContents() const {
- return web_contents_;
-}
-
void ContentViewCore::SetFocus(JNIEnv* env,
const JavaParamRef<jobject>& obj,
jboolean focused) {
@@ -593,87 +199,6 @@ void ContentViewCore::SendOrientationChangeEvent(
}
}
-WebGestureEvent ContentViewCore::MakeGestureEvent(WebInputEvent::Type type,
- int64_t time_ms,
- float x,
- float y) const {
- return WebGestureEventBuilder::Build(type, time_ms / 1000.0, x / dpi_scale(),
- y / dpi_scale());
-}
-
-void ContentViewCore::SendGestureEvent(const blink::WebGestureEvent& event) {
- RenderWidgetHostViewAndroid* rwhv = GetRenderWidgetHostViewAndroid();
- if (rwhv)
- rwhv->SendGestureEvent(event);
-}
-
-void ContentViewCore::ScrollBegin(JNIEnv* env,
- const JavaParamRef<jobject>& obj,
- jlong time_ms,
- jfloat x,
- jfloat y,
- jfloat hintx,
- jfloat hinty,
- jboolean target_viewport,
- jboolean from_gamepad) {
- WebGestureEvent event =
- MakeGestureEvent(WebInputEvent::kGestureScrollBegin, time_ms, x, y);
- event.data.scroll_begin.delta_x_hint = hintx / dpi_scale();
- event.data.scroll_begin.delta_y_hint = hinty / dpi_scale();
- event.data.scroll_begin.target_viewport = target_viewport;
-
- if (from_gamepad)
- event.source_device = blink::kWebGestureDeviceSyntheticAutoscroll;
-
- SendGestureEvent(event);
-}
-
-void ContentViewCore::ScrollEnd(JNIEnv* env,
- const JavaParamRef<jobject>& obj,
- jlong time_ms) {
- WebGestureEvent event =
- MakeGestureEvent(WebInputEvent::kGestureScrollEnd, time_ms, 0, 0);
- SendGestureEvent(event);
-}
-
-void ContentViewCore::ScrollBy(JNIEnv* env,
- const JavaParamRef<jobject>& obj,
- jlong time_ms,
- jfloat x,
- jfloat y,
- jfloat dx,
- jfloat dy) {
- WebGestureEvent event =
- MakeGestureEvent(WebInputEvent::kGestureScrollUpdate, time_ms, x, y);
- event.data.scroll_update.delta_x = -dx / dpi_scale();
- event.data.scroll_update.delta_y = -dy / dpi_scale();
-
- SendGestureEvent(event);
-}
-
-void ContentViewCore::DoubleTap(JNIEnv* env,
- const JavaParamRef<jobject>& obj,
- jlong time_ms,
- jfloat x,
- jfloat y) {
- WebGestureEvent event =
- MakeGestureEvent(WebInputEvent::kGestureDoubleTap, time_ms, x, y);
- // Set the tap count to 1 even for DoubleTap, in order to be consistent with
- // double tap behavior on a mobile viewport. See crbug.com/234986 for context.
- event.data.tap.tap_count = 1;
-
- SendGestureEvent(event);
-}
-
-void ContentViewCore::SetTextHandlesTemporarilyHidden(
- JNIEnv* env,
- const JavaParamRef<jobject>& obj,
- jboolean hidden) {
- RenderWidgetHostViewAndroid* rwhv = GetRenderWidgetHostViewAndroid();
- if (rwhv)
- rwhv->SetTextHandlesTemporarilyHidden(hidden);
-}
-
void ContentViewCore::ResetGestureDetection(JNIEnv* env,
const JavaParamRef<jobject>& obj) {
RenderWidgetHostViewAndroid* rwhv = GetRenderWidgetHostViewAndroid();
@@ -699,44 +224,6 @@ void ContentViewCore::SetMultiTouchZoomSupportEnabled(
rwhv->SetMultiTouchZoomSupportEnabled(enabled);
}
-void ContentViewCore::OnTouchDown(
- const base::android::ScopedJavaLocalRef<jobject>& event) {
- JNIEnv* env = AttachCurrentThread();
- ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
- if (obj.is_null())
- return;
- Java_ContentViewCoreImpl_onTouchDown(env, obj, event);
-}
-
-void ContentViewCore::SetTextTrackSettings(
- JNIEnv* env,
- const JavaParamRef<jobject>& obj,
- jboolean textTracksEnabled,
- const JavaParamRef<jstring>& textTrackBackgroundColor,
- const JavaParamRef<jstring>& textTrackFontFamily,
- const JavaParamRef<jstring>& textTrackFontStyle,
- const JavaParamRef<jstring>& textTrackFontVariant,
- const JavaParamRef<jstring>& textTrackTextColor,
- const JavaParamRef<jstring>& textTrackTextShadow,
- const JavaParamRef<jstring>& textTrackTextSize) {
- FrameMsg_TextTrackSettings_Params params;
- params.text_tracks_enabled = textTracksEnabled;
- params.text_track_background_color =
- ConvertJavaStringToUTF8(env, textTrackBackgroundColor);
- params.text_track_font_family =
- ConvertJavaStringToUTF8(env, textTrackFontFamily);
- params.text_track_font_style =
- ConvertJavaStringToUTF8(env, textTrackFontStyle);
- params.text_track_font_variant =
- ConvertJavaStringToUTF8(env, textTrackFontVariant);
- params.text_track_text_color =
- ConvertJavaStringToUTF8(env, textTrackTextColor);
- params.text_track_text_shadow =
- ConvertJavaStringToUTF8(env, textTrackTextShadow);
- params.text_track_text_size = ConvertJavaStringToUTF8(env, textTrackTextSize);
- web_contents_->GetMainFrame()->SetTextTrackSettings(params);
-}
-
void ContentViewCore::SendOrientationChangeEventInternal() {
RenderWidgetHostViewAndroid* rwhv = GetRenderWidgetHostViewAndroid();
if (rwhv)
@@ -745,28 +232,6 @@ void ContentViewCore::SendOrientationChangeEventInternal() {
static_cast<WebContentsImpl*>(web_contents())->OnScreenOrientationChange();
}
-jboolean ContentViewCore::UsingSynchronousCompositing(
- JNIEnv* env,
- const base::android::JavaParamRef<jobject>& obj) {
- return content::GetContentClient()->UsingSynchronousCompositing();
-}
-
-void ContentViewCore::HidePopupsAndPreserveSelection() {
- JNIEnv* env = AttachCurrentThread();
- ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
- if (obj.is_null())
- return;
-
- Java_ContentViewCoreImpl_hidePopupsAndPreserveSelection(env, obj);
-}
-
-void ContentViewCore::WebContentsDestroyed() {
- WebContentsViewAndroid* wcva = static_cast<WebContentsViewAndroid*>(
- static_cast<WebContentsImpl*>(web_contents())->GetView());
- DCHECK(wcva);
- wcva->SetContentViewCore(NULL);
-}
-
// This is called for each ContentView.
jlong JNI_ContentViewCoreImpl_Init(
JNIEnv* env,
@@ -792,20 +257,4 @@ jlong JNI_ContentViewCoreImpl_Init(
return reinterpret_cast<intptr_t>(view);
}
-static ScopedJavaLocalRef<jobject>
-JNI_ContentViewCoreImpl_FromWebContentsAndroid(
- JNIEnv* env,
- const JavaParamRef<jclass>& clazz,
- const JavaParamRef<jobject>& jweb_contents) {
- WebContents* web_contents = WebContents::FromJavaWebContents(jweb_contents);
- if (!web_contents)
- return ScopedJavaLocalRef<jobject>();
-
- ContentViewCore* view = ContentViewCore::FromWebContents(web_contents);
- if (!view)
- return ScopedJavaLocalRef<jobject>();
-
- return view->GetJavaObject();
-}
-
} // namespace content
diff --git a/chromium/content/browser/android/content_view_core.h b/chromium/content/browser/android/content_view_core.h
index 37ae62fc89a..36373ad9fa9 100644
--- a/chromium/content/browser/android/content_view_core.h
+++ b/chromium/content/browser/android/content_view_core.h
@@ -5,61 +5,35 @@
#ifndef CONTENT_BROWSER_ANDROID_CONTENT_VIEW_CORE_H_
#define CONTENT_BROWSER_ANDROID_CONTENT_VIEW_CORE_H_
-#include <stdint.h>
-
-#include <memory>
-#include <vector>
-
#include "base/android/jni_android.h"
#include "base/android/jni_weak_ref.h"
#include "base/android/scoped_java_ref.h"
-#include "base/compiler_specific.h"
-#include "base/i18n/rtl.h"
#include "base/macros.h"
-#include "base/process/process.h"
-#include "content/browser/renderer_host/render_widget_host_view_android.h"
-#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/browser/web_contents_observer.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
-#include "ui/android/view_android.h"
-#include "ui/gfx/geometry/rect.h"
-#include "ui/gfx/geometry/rect_f.h"
-#include "ui/gfx/selection_bound.h"
-#include "url/gurl.h"
namespace ui {
+class ViewAndroid;
class WindowAndroid;
}
namespace content {
-class RenderFrameHost;
class RenderWidgetHostViewAndroid;
-struct MenuItem;
+class WebContentsImpl;
class ContentViewCore : public WebContentsObserver {
public:
- static ContentViewCore* FromWebContents(WebContents* web_contents);
ContentViewCore(JNIEnv* env,
const base::android::JavaRef<jobject>& obj,
WebContents* web_contents,
float dpi_scale);
- base::android::ScopedJavaLocalRef<jobject> GetJavaObject();
- WebContents* GetWebContents() const;
- ui::WindowAndroid* GetWindowAndroid() const;
+ ~ContentViewCore() override;
// --------------------------------------------------------------------------
// Methods called from Java via JNI
// --------------------------------------------------------------------------
- base::android::ScopedJavaLocalRef<jobject> GetWebContentsAndroid(
- JNIEnv* env,
- const base::android::JavaParamRef<jobject>& obj);
- base::android::ScopedJavaLocalRef<jobject> GetJavaWindowAndroid(
- JNIEnv* env,
- const base::android::JavaParamRef<jobject>& obj);
-
void UpdateWindowAndroid(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj,
@@ -68,14 +42,6 @@ class ContentViewCore : public WebContentsObserver {
JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj);
- // Notifies the ContentViewCore that items were selected in the currently
- // showing select popup.
- void SelectPopupMenuItems(
- JNIEnv* env,
- const base::android::JavaParamRef<jobject>& obj,
- jlong selectPopupSourceFrame,
- const base::android::JavaParamRef<jintArray>& indices);
-
// Returns the amount of the top controls height if controls are in the state
// of shrinking Blink's view size, otherwise 0.
int GetTopControlsShrinkBlinkHeightPixForTesting(
@@ -86,43 +52,6 @@ class ContentViewCore : public WebContentsObserver {
JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj,
jint orientation);
- jboolean SendMouseWheelEvent(JNIEnv* env,
- const base::android::JavaParamRef<jobject>& obj,
- jlong time_ms,
- jfloat x,
- jfloat y,
- jfloat ticks_x,
- jfloat ticks_y,
- jfloat pixels_per_tick);
- void ScrollBegin(JNIEnv* env,
- const base::android::JavaParamRef<jobject>& obj,
- jlong time_ms,
- jfloat x,
- jfloat y,
- jfloat hintx,
- jfloat hinty,
- jboolean target_viewport,
- jboolean from_gamepad);
- void ScrollEnd(JNIEnv* env,
- const base::android::JavaParamRef<jobject>& obj,
- jlong time_ms);
- void ScrollBy(JNIEnv* env,
- const base::android::JavaParamRef<jobject>& obj,
- jlong time_ms,
- jfloat x,
- jfloat y,
- jfloat dx,
- jfloat dy);
- void DoubleTap(JNIEnv* env,
- const base::android::JavaParamRef<jobject>& obj,
- jlong time_ms,
- jfloat x,
- jfloat y);
-
- void SetTextHandlesTemporarilyHidden(
- JNIEnv* env,
- const base::android::JavaParamRef<jobject>& obj,
- jboolean hidden);
void ResetGestureDetection(JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj);
@@ -143,83 +72,7 @@ class ContentViewCore : public WebContentsObserver {
const base::android::JavaParamRef<jobject>& obj,
jfloat dipScale);
- jint GetBackgroundColor(JNIEnv* env, jobject obj);
-
- void SetTextTrackSettings(
- JNIEnv* env,
- const base::android::JavaParamRef<jobject>& obj,
- jboolean textTracksEnabled,
- const base::android::JavaParamRef<jstring>& textTrackBackgroundColor,
- const base::android::JavaParamRef<jstring>& textTrackFontFamily,
- const base::android::JavaParamRef<jstring>& textTrackFontStyle,
- const base::android::JavaParamRef<jstring>& textTrackFontVariant,
- const base::android::JavaParamRef<jstring>& textTrackTextColor,
- const base::android::JavaParamRef<jstring>& textTrackTextShadow,
- const base::android::JavaParamRef<jstring>& textTrackTextSize);
-
- void SetBackgroundOpaque(JNIEnv* env,
- const base::android::JavaParamRef<jobject>& jobj,
- jboolean opaque);
-
- jboolean UsingSynchronousCompositing(
- JNIEnv* env,
- const base::android::JavaParamRef<jobject>& obj);
-
- // --------------------------------------------------------------------------
- // Public methods that call to Java via JNI
- // --------------------------------------------------------------------------
-
- void HidePopupsAndPreserveSelection();
-
- // Creates a popup menu with |items|.
- // |multiple| defines if it should support multi-select.
- // If not |multiple|, |selected_item| sets the initially selected item.
- // Otherwise, item's "checked" flag selects it.
- void ShowSelectPopupMenu(RenderFrameHost* frame,
- const gfx::Rect& bounds,
- const std::vector<MenuItem>& items,
- int selected_item,
- bool multiple,
- bool right_aligned);
- // Hides a visible popup menu.
- void HideSelectPopupMenu();
-
- // All sizes and offsets are in CSS pixels (except |top_show_pix|)
- // as cached by the renderer.
- void UpdateFrameInfo(const gfx::Vector2dF& scroll_offset,
- float page_scale_factor,
- float min_page_scale,
- float max_page_scale,
- const gfx::SizeF& content_size,
- const gfx::SizeF& viewport_size,
- const float top_content_offset,
- const float top_shown_pix,
- bool top_changed,
- bool is_mobile_optimized_hint);
-
- void RequestDisallowInterceptTouchEvent();
- bool FilterInputEvent(const blink::WebInputEvent& event);
-
- // Returns the context with which the ContentViewCore was created, typically
- // the Activity context.
- base::android::ScopedJavaLocalRef<jobject> GetContext() const;
-
- // --------------------------------------------------------------------------
- // Methods called from native code
- // --------------------------------------------------------------------------
-
- int GetMouseWheelMinimumGranularity() const;
-
- void UpdateCursor(const content::CursorInfo& info);
- void OnTouchDown(const base::android::ScopedJavaLocalRef<jobject>& event);
-
- ui::ViewAndroid* GetViewAndroid() const;
-
private:
- class ContentViewUserData;
-
- friend class ContentViewUserData;
- ~ContentViewCore() override;
// WebContentsObserver implementation.
void RenderViewReady() override;
@@ -231,19 +84,12 @@ class ContentViewCore : public WebContentsObserver {
// Other private methods and data
// --------------------------------------------------------------------------
- void InitWebContents();
void SendScreenRectsAndResizeWidget();
- RenderWidgetHostViewAndroid* GetRenderWidgetHostViewAndroid() const;
-
- blink::WebGestureEvent MakeGestureEvent(blink::WebInputEvent::Type type,
- int64_t time_ms,
- float x,
- float y) const;
-
- gfx::Size GetViewportSizePix() const;
+ ui::ViewAndroid* GetViewAndroid() const;
+ ui::WindowAndroid* GetWindowAndroid() const;
- void SendGestureEvent(const blink::WebGestureEvent& event);
+ RenderWidgetHostViewAndroid* GetRenderWidgetHostViewAndroid() const;
// Update focus state of the RenderWidgetHostView.
void SetFocusInternal(bool focused);
@@ -251,14 +97,9 @@ class ContentViewCore : public WebContentsObserver {
// Send device_orientation_ to renderer.
void SendOrientationChangeEventInternal();
- float dpi_scale() const { return dpi_scale_; }
-
// A weak reference to the Java ContentViewCore object.
JavaObjectWeakGlobalRef java_ref_;
- // Select popup view
- ui::ViewAndroid::ScopedAnchorView select_popup_;
-
// Reference to the current WebContents used to determine how and what to
// display in the ContentViewCore.
WebContentsImpl* web_contents_;
diff --git a/chromium/content/browser/android/dialog_overlay_impl.cc b/chromium/content/browser/android/dialog_overlay_impl.cc
index 4e496302e07..8335d3bf14e 100644
--- a/chromium/content/browser/android/dialog_overlay_impl.cc
+++ b/chromium/content/browser/android/dialog_overlay_impl.cc
@@ -7,6 +7,7 @@
#include "content/browser/frame_host/render_frame_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_view_base.h"
#include "content/browser/web_contents/web_contents_impl.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents_delegate.h"
#include "gpu/ipc/common/gpu_surface_tracker.h"
#include "jni/DialogOverlayImpl_jni.h"
diff --git a/chromium/content/browser/android/gesture_listener_manager.cc b/chromium/content/browser/android/gesture_listener_manager.cc
index 29b93365bfa..1eeb5d41b40 100644
--- a/chromium/content/browser/android/gesture_listener_manager.cc
+++ b/chromium/content/browser/android/gesture_listener_manager.cc
@@ -7,10 +7,12 @@
#include "content/browser/android/gesture_listener_manager.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/browser/web_contents/web_contents_view_android.h"
-#include "content/public/browser/web_contents.h"
+#include "content/public/browser/navigation_handle.h"
+#include "content/public/browser/web_contents_observer.h"
#include "jni/GestureListenerManagerImpl_jni.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/events/android/gesture_event_type.h"
+#include "ui/gfx/geometry/size_f.h"
using blink::WebGestureEvent;
using blink::WebInputEvent;
@@ -21,10 +23,88 @@ using base::android::ScopedJavaLocalRef;
namespace content {
+namespace {
+
+int ToGestureEventType(WebInputEvent::Type type) {
+ switch (type) {
+ case WebInputEvent::kGestureScrollBegin:
+ return ui::GESTURE_EVENT_TYPE_SCROLL_START;
+ case WebInputEvent::kGestureScrollEnd:
+ return ui::GESTURE_EVENT_TYPE_SCROLL_END;
+ case WebInputEvent::kGestureScrollUpdate:
+ return ui::GESTURE_EVENT_TYPE_SCROLL_BY;
+ case WebInputEvent::kGestureFlingStart:
+ return ui::GESTURE_EVENT_TYPE_FLING_START;
+ case WebInputEvent::kGestureFlingCancel:
+ return ui::GESTURE_EVENT_TYPE_FLING_CANCEL;
+ case WebInputEvent::kGestureShowPress:
+ return ui::GESTURE_EVENT_TYPE_SHOW_PRESS;
+ case WebInputEvent::kGestureTap:
+ return ui::GESTURE_EVENT_TYPE_SINGLE_TAP_CONFIRMED;
+ case WebInputEvent::kGestureTapUnconfirmed:
+ return ui::GESTURE_EVENT_TYPE_SINGLE_TAP_UNCONFIRMED;
+ case WebInputEvent::kGestureTapDown:
+ return ui::GESTURE_EVENT_TYPE_TAP_DOWN;
+ case WebInputEvent::kGestureTapCancel:
+ return ui::GESTURE_EVENT_TYPE_TAP_CANCEL;
+ case WebInputEvent::kGestureDoubleTap:
+ return ui::GESTURE_EVENT_TYPE_DOUBLE_TAP;
+ case WebInputEvent::kGestureLongPress:
+ return ui::GESTURE_EVENT_TYPE_LONG_PRESS;
+ case WebInputEvent::kGestureLongTap:
+ return ui::GESTURE_EVENT_TYPE_LONG_TAP;
+ case WebInputEvent::kGesturePinchBegin:
+ return ui::GESTURE_EVENT_TYPE_PINCH_BEGIN;
+ case WebInputEvent::kGesturePinchEnd:
+ return ui::GESTURE_EVENT_TYPE_PINCH_END;
+ case WebInputEvent::kGesturePinchUpdate:
+ return ui::GESTURE_EVENT_TYPE_PINCH_BY;
+ case WebInputEvent::kGestureTwoFingerTap:
+ default:
+ NOTREACHED() << "Invalid source gesture type: "
+ << WebInputEvent::GetName(type);
+ return -1;
+ }
+}
+
+} // namespace
+
+// Reset scroll, hide popups on navigation finish/render process gone event.
+class GestureListenerManager::ResetScrollObserver : public WebContentsObserver {
+ public:
+ ResetScrollObserver(WebContents* web_contents,
+ GestureListenerManager* manager);
+
+ void DidFinishNavigation(NavigationHandle* navigation_handle) override;
+ void RenderProcessGone(base::TerminationStatus status) override;
+
+ private:
+ GestureListenerManager* const manager_;
+ DISALLOW_COPY_AND_ASSIGN(ResetScrollObserver);
+};
+
+GestureListenerManager::ResetScrollObserver::ResetScrollObserver(
+ WebContents* web_contents,
+ GestureListenerManager* manager)
+ : WebContentsObserver(web_contents), manager_(manager) {}
+
+void GestureListenerManager::ResetScrollObserver::DidFinishNavigation(
+ NavigationHandle* navigation_handle) {
+ manager_->OnNavigationFinished(navigation_handle);
+}
+
+void GestureListenerManager::ResetScrollObserver::RenderProcessGone(
+ base::TerminationStatus status) {
+ manager_->OnRenderProcessGone();
+}
+
GestureListenerManager::GestureListenerManager(JNIEnv* env,
const JavaParamRef<jobject>& obj,
- WebContents* web_contents)
- : RenderWidgetHostConnector(web_contents), java_ref_(env, obj) {}
+ WebContentsImpl* web_contents)
+ : RenderWidgetHostConnector(web_contents),
+ reset_scroll_observer_(new ResetScrollObserver(web_contents, this)),
+ web_contents_(web_contents),
+ java_ref_(env, obj) {}
GestureListenerManager::~GestureListenerManager() {
JNIEnv* env = AttachCurrentThread();
@@ -98,6 +178,64 @@ void GestureListenerManager::DidStopFlinging() {
Java_GestureListenerManagerImpl_onFlingEnd(env, j_obj);
}
+bool GestureListenerManager::FilterInputEvent(const WebInputEvent& event) {
+ if (event.GetType() != WebInputEvent::kGestureTap &&
+ event.GetType() != WebInputEvent::kGestureLongTap &&
+ event.GetType() != WebInputEvent::kGestureLongPress &&
+ event.GetType() != WebInputEvent::kMouseDown)
+ return false;
+
+ JNIEnv* env = AttachCurrentThread();
+ ScopedJavaLocalRef<jobject> j_obj = java_ref_.get(env);
+ if (j_obj.is_null())
+ return false;
+
+ web_contents_->GetNativeView()->RequestFocus();
+
+ if (event.GetType() == WebInputEvent::kMouseDown)
+ return false;
+
+ const WebGestureEvent& gesture = static_cast<const WebGestureEvent&>(event);
+ int gesture_type = ToGestureEventType(event.GetType());
+ float dip_scale = web_contents_->GetNativeView()->GetDipScale();
+ return Java_GestureListenerManagerImpl_filterTapOrPressEvent(
+ env, j_obj, gesture_type, gesture.PositionInWidget().x * dip_scale,
+ gesture.PositionInWidget().y * dip_scale);
+}
+
+// All positions and sizes (except |top_shown_pix|) are in CSS pixels.
+// Note that viewport_width/height is a best effort based.
+void GestureListenerManager::UpdateScrollInfo(
+ const gfx::Vector2dF& scroll_offset,
+ float page_scale_factor,
+ const float min_page_scale,
+ const float max_page_scale,
+ const gfx::SizeF& content,
+ const gfx::SizeF& viewport,
+ const float content_offset,
+ const float top_shown_pix,
+ bool top_changed) {
+ JNIEnv* env = AttachCurrentThread();
+ ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
+ if (obj.is_null())
+ return;
+
+ web_contents_->GetNativeView()->UpdateFrameInfo({viewport, content_offset});
+ Java_GestureListenerManagerImpl_updateScrollInfo(
+ env, obj, scroll_offset.x(), scroll_offset.y(), page_scale_factor,
+ min_page_scale, max_page_scale, content.width(), content.height(),
+ viewport.width(), viewport.height(), top_shown_pix, top_changed);
+}
+
+void GestureListenerManager::UpdateOnTouchDown() {
+ JNIEnv* env = AttachCurrentThread();
+ ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
+ if (obj.is_null())
+ return;
+
+ Java_GestureListenerManagerImpl_updateOnTouchDown(env, obj);
+}
+
void GestureListenerManager::UpdateRenderProcessConnection(
RenderWidgetHostViewAndroid* old_rwhva,
RenderWidgetHostViewAndroid* new_rwhva) {
@@ -108,6 +246,27 @@ void GestureListenerManager::UpdateRenderProcessConnection(
}
}
+void GestureListenerManager::OnNavigationFinished(
+ NavigationHandle* navigation_handle) {
+ if (navigation_handle->IsInMainFrame() && navigation_handle->HasCommitted() &&
+ !navigation_handle->IsSameDocument()) {
+ ResetPopupsAndInput(false);
+ }
+}
+
+void GestureListenerManager::OnRenderProcessGone() {
+ ResetPopupsAndInput(true);
+}
+
+void GestureListenerManager::ResetPopupsAndInput(bool render_process_gone) {
+ JNIEnv* env = AttachCurrentThread();
+ ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
+ if (obj.is_null())
+ return;
+ Java_GestureListenerManagerImpl_resetPopupsAndInput(env, obj,
+ render_process_gone);
+}
+
jlong JNI_GestureListenerManagerImpl_Init(
JNIEnv* env,
const JavaParamRef<jobject>& obj,
@@ -116,7 +275,8 @@ jlong JNI_GestureListenerManagerImpl_Init(
CHECK(web_contents) << "Should be created with a valid WebContents.";
// Owns itself and gets destroyed when |WebContentsDestroyed| is called.
- auto* manager = new GestureListenerManager(env, obj, web_contents);
+ auto* manager = new GestureListenerManager(
+ env, obj, static_cast<WebContentsImpl*>(web_contents));
manager->Initialize();
return reinterpret_cast<intptr_t>(manager);
}
diff --git a/chromium/content/browser/android/gesture_listener_manager.h b/chromium/content/browser/android/gesture_listener_manager.h
index f3bf7b8275e..693a9b7beed 100644
--- a/chromium/content/browser/android/gesture_listener_manager.h
+++ b/chromium/content/browser/android/gesture_listener_manager.h
@@ -15,29 +15,59 @@ namespace blink {
class WebGestureEvent;
}
+namespace gfx {
+class SizeF;
+class Vector2dF;
+} // namespace gfx
+
namespace content {
-class WebContents;
+class NavigationHandle;
+class WebContentsImpl;
// Native class for GestureListenerManagerImpl.
class GestureListenerManager : public RenderWidgetHostConnector {
public:
GestureListenerManager(JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj,
- WebContents* web_contents);
+ WebContentsImpl* web_contents);
~GestureListenerManager() override;
void Reset(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj);
void GestureEventAck(const blink::WebGestureEvent& event,
InputEventAckState ack_result);
void DidStopFlinging();
+ bool FilterInputEvent(const blink::WebInputEvent& event);
+
+ // All sizes and offsets are in CSS pixels (except |top_show_pix|)
+ // as cached by the renderer.
+ void UpdateScrollInfo(const gfx::Vector2dF& scroll_offset,
+ float page_scale_factor,
+ const float min_page_scale,
+ const float max_page_scale,
+ const gfx::SizeF& content,
+ const gfx::SizeF& viewport,
+ const float content_offset,
+ const float top_shown_pix,
+ bool top_changed);
+ void UpdateOnTouchDown();
// RendetWidgetHostConnector implementation.
void UpdateRenderProcessConnection(
RenderWidgetHostViewAndroid* old_rwhva,
RenderWidgetHostViewAndroid* new_rhwva) override;
+ void OnNavigationFinished(NavigationHandle* navigation_handle);
+ void OnRenderProcessGone();
+
private:
+ class ResetScrollObserver;
+
+ void ResetPopupsAndInput(bool render_process_gone);
+
+ std::unique_ptr<ResetScrollObserver> reset_scroll_observer_;
+ WebContentsImpl* web_contents_;
+
// A weak reference to the Java GestureListenerManager object.
JavaObjectWeakGlobalRef java_ref_;
diff --git a/chromium/content/browser/android/ime_adapter_android.cc b/chromium/content/browser/android/ime_adapter_android.cc
index 82f32a98ac1..ed271d17508 100644
--- a/chromium/content/browser/android/ime_adapter_android.cc
+++ b/chromium/content/browser/android/ime_adapter_android.cc
@@ -25,8 +25,8 @@
#include "content/public/browser/native_web_keyboard_event.h"
#include "content/public/browser/web_contents.h"
#include "jni/ImeAdapterImpl_jni.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
-#include "third_party/WebKit/public/platform/WebTextInputType.h"
+#include "third_party/blink/public/platform/web_input_event.h"
+#include "third_party/blink/public/platform/web_text_input_type.h"
#include "ui/base/ime/ime_text_span.h"
using base::android::AttachCurrentThread;
@@ -87,7 +87,7 @@ void JNI_ImeAdapterImpl_AppendBackgroundColorSpan(JNIEnv*,
reinterpret_cast<std::vector<ui::ImeTextSpan>*>(ime_text_spans_ptr);
ime_text_spans->push_back(ui::ImeTextSpan(
ui::ImeTextSpan::Type::kComposition, static_cast<unsigned>(start),
- static_cast<unsigned>(end), SK_ColorTRANSPARENT, false,
+ static_cast<unsigned>(end), ui::ImeTextSpan::Thickness::kNone,
static_cast<unsigned>(background_color), SK_ColorTRANSPARENT,
std::vector<std::string>()));
}
@@ -115,10 +115,12 @@ void JNI_ImeAdapterImpl_AppendSuggestionSpan(
reinterpret_cast<std::vector<ui::ImeTextSpan>*>(ime_text_spans_ptr);
std::vector<std::string> suggestions_vec;
AppendJavaStringArrayToStringVector(env, suggestions, &suggestions_vec);
- ime_text_spans->push_back(ui::ImeTextSpan(
+ ui::ImeTextSpan ime_text_span = ui::ImeTextSpan(
type, static_cast<unsigned>(start), static_cast<unsigned>(end),
- static_cast<unsigned>(underline_color), true, SK_ColorTRANSPARENT,
- static_cast<unsigned>(suggestion_highlight_color), suggestions_vec));
+ ui::ImeTextSpan::Thickness::kThick, SK_ColorTRANSPARENT,
+ static_cast<unsigned>(suggestion_highlight_color), suggestions_vec);
+ ime_text_span.underline_color = static_cast<unsigned>(underline_color);
+ ime_text_spans->push_back(ime_text_span);
}
// Callback from Java to convert UnderlineSpan data to a
@@ -134,8 +136,8 @@ void JNI_ImeAdapterImpl_AppendUnderlineSpan(JNIEnv*,
reinterpret_cast<std::vector<ui::ImeTextSpan>*>(ime_text_spans_ptr);
ime_text_spans->push_back(ui::ImeTextSpan(
ui::ImeTextSpan::Type::kComposition, static_cast<unsigned>(start),
- static_cast<unsigned>(end), SK_ColorBLACK, false, SK_ColorTRANSPARENT,
- SK_ColorTRANSPARENT, std::vector<std::string>()));
+ static_cast<unsigned>(end), ui::ImeTextSpan::Thickness::kThin,
+ SK_ColorTRANSPARENT, SK_ColorTRANSPARENT, std::vector<std::string>()));
}
ImeAdapterAndroid::ImeAdapterAndroid(JNIEnv* env,
@@ -192,6 +194,14 @@ void ImeAdapterAndroid::UpdateAfterViewSizeChanged() {
Java_ImeAdapterImpl_updateAfterViewSizeChanged(env, obj);
}
+void ImeAdapterAndroid::UpdateOnTouchDown() {
+ JNIEnv* env = AttachCurrentThread();
+ ScopedJavaLocalRef<jobject> obj = java_ime_adapter_.get(env);
+ if (obj.is_null())
+ return;
+ Java_ImeAdapterImpl_updateOnTouchDown(env, obj);
+}
+
void ImeAdapterAndroid::UpdateFrameInfo(
const gfx::SelectionBound& selection_start,
float dip_scale,
@@ -257,7 +267,7 @@ void ImeAdapterAndroid::SetComposingText(JNIEnv* env,
if (ime_text_spans.empty()) {
ime_text_spans.push_back(
ui::ImeTextSpan(ui::ImeTextSpan::Type::kComposition, 0, text16.length(),
- SK_ColorBLACK, false, SK_ColorTRANSPARENT,
+ ui::ImeTextSpan::Thickness::kThin, SK_ColorTRANSPARENT,
SK_ColorTRANSPARENT, std::vector<std::string>()));
}
@@ -379,9 +389,10 @@ void ImeAdapterAndroid::SetComposingRegion(JNIEnv*,
return;
std::vector<ui::ImeTextSpan> ime_text_spans;
- ime_text_spans.push_back(ui::ImeTextSpan(
- ui::ImeTextSpan::Type::kComposition, 0, end - start, SK_ColorBLACK, false,
- SK_ColorTRANSPARENT, SK_ColorTRANSPARENT, std::vector<std::string>()));
+ ime_text_spans.push_back(
+ ui::ImeTextSpan(ui::ImeTextSpan::Type::kComposition, 0, end - start,
+ ui::ImeTextSpan::Thickness::kThin, SK_ColorTRANSPARENT,
+ SK_ColorTRANSPARENT, std::vector<std::string>()));
rfh->GetFrameInputHandler()->SetCompositionFromExistingText(start, end,
ime_text_spans);
diff --git a/chromium/content/browser/android/ime_adapter_android.h b/chromium/content/browser/android/ime_adapter_android.h
index 58891af03b9..2b16c70e86b 100644
--- a/chromium/content/browser/android/ime_adapter_android.h
+++ b/chromium/content/browser/android/ime_adapter_android.h
@@ -106,6 +106,7 @@ class CONTENT_EXPORT ImeAdapterAndroid : public RenderWidgetHostConnector {
void UpdateState(const TextInputState& state);
void UpdateAfterViewSizeChanged();
+ void UpdateOnTouchDown();
void AdvanceFocusInForm(JNIEnv*,
const base::android::JavaParamRef<jobject>&,
diff --git a/chromium/content/browser/android/java/gin_java_bridge_dispatcher_host.cc b/chromium/content/browser/android/java/gin_java_bridge_dispatcher_host.cc
index 2cfda325630..4d6da9cf913 100644
--- a/chromium/content/browser/android/java/gin_java_bridge_dispatcher_host.cc
+++ b/chromium/content/browser/android/java/gin_java_bridge_dispatcher_host.cc
@@ -6,7 +6,6 @@
#include "base/android/jni_android.h"
#include "base/android/scoped_java_ref.h"
-#include "base/memory/ptr_util.h"
#include "build/build_config.h"
#include "content/browser/android/java/gin_java_bound_object_delegate.h"
#include "content/browser/android/java/gin_java_bridge_message_filter.h"
diff --git a/chromium/content/browser/android/java/gin_java_bridge_message_filter.cc b/chromium/content/browser/android/java/gin_java_bridge_message_filter.cc
index 84eb03266fc..33051e165fa 100644
--- a/chromium/content/browser/android/java/gin_java_bridge_message_filter.cc
+++ b/chromium/content/browser/android/java/gin_java_bridge_message_filter.cc
@@ -5,11 +5,11 @@
#include "content/browser/android/java/gin_java_bridge_message_filter.h"
#include "base/auto_reset.h"
-#include "base/memory/ptr_util.h"
#include "build/build_config.h"
#include "content/browser/android/java/gin_java_bridge_dispatcher_host.h"
#include "content/browser/android/java/java_bridge_thread.h"
#include "content/common/gin_java_bridge_messages.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents.h"
diff --git a/chromium/content/browser/android/java/gin_java_method_invocation_helper.cc b/chromium/content/browser/android/java/gin_java_method_invocation_helper.cc
index a62516cb760..8b17a5cc322 100644
--- a/chromium/content/browser/android/java/gin_java_method_invocation_helper.cc
+++ b/chromium/content/browser/android/java/gin_java_method_invocation_helper.cc
@@ -11,7 +11,6 @@
#include "base/android/event_log.h"
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
-#include "base/memory/ptr_util.h"
#include "content/browser/android/java/gin_java_script_to_java_types_coercion.h"
#include "content/browser/android/java/java_method.h"
#include "content/common/android/gin_java_bridge_value.h"
diff --git a/chromium/content/browser/android/java/gin_java_method_invocation_helper_unittest.cc b/chromium/content/browser/android/java/gin_java_method_invocation_helper_unittest.cc
index 8f2f58c7bf1..0787e336590 100644
--- a/chromium/content/browser/android/java/gin_java_method_invocation_helper_unittest.cc
+++ b/chromium/content/browser/android/java/gin_java_method_invocation_helper_unittest.cc
@@ -10,7 +10,6 @@
#include "base/android/jni_android.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/values.h"
#include "content/common/android/gin_java_bridge_value.h"
#include "testing/gtest/include/gtest/gtest.h"
diff --git a/chromium/content/browser/android/java/gin_java_script_to_java_types_coercion.cc b/chromium/content/browser/android/java/gin_java_script_to_java_types_coercion.cc
index d84a12f39c7..af827187dad 100644
--- a/chromium/content/browser/android/java/gin_java_script_to_java_types_coercion.cc
+++ b/chromium/content/browser/android/java/gin_java_script_to_java_types_coercion.cc
@@ -11,7 +11,6 @@
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
diff --git a/chromium/content/browser/android/overscroll_controller_android.cc b/chromium/content/browser/android/overscroll_controller_android.cc
index 912c9813bb0..c9d2bd85183 100644
--- a/chromium/content/browser/android/overscroll_controller_android.cc
+++ b/chromium/content/browser/android/overscroll_controller_android.cc
@@ -6,14 +6,13 @@
#include "base/android/build_info.h"
#include "base/command_line.h"
-#include "base/memory/ptr_util.h"
#include "cc/layers/layer.h"
#include "components/viz/common/quads/compositor_frame_metadata.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/use_zoom_for_dsf_policy.h"
-#include "third_party/WebKit/public/platform/WebGestureEvent.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_gesture_event.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/android/edge_effect.h"
#include "ui/android/edge_effect_l.h"
#include "ui/android/resources/resource_manager.h"
@@ -33,18 +32,17 @@ using ui::OverscrollRefresh;
namespace content {
namespace {
-// Used for conditional creation of EdgeEffect types for the overscroll glow.
-const int kAndroidLSDKVersion = 21;
-
// If the glow effect alpha is greater than this value, the refresh effect will
// be suppressed. This value was experimentally determined to provide a
// reasonable balance between avoiding accidental refresh activation and
// minimizing the wait required to refresh after the glow has been triggered.
const float kMinGlowAlphaToDisableRefreshOnL = 0.085f;
+// Used for conditional creation of EdgeEffect types for the overscroll glow.
bool IsAndroidLOrNewer() {
static bool android_l_or_newer =
- base::android::BuildInfo::GetInstance()->sdk_int() >= kAndroidLSDKVersion;
+ base::android::BuildInfo::GetInstance()->sdk_int() >=
+ base::android::SDK_VERSION_LOLLIPOP;
return android_l_or_newer;
}
diff --git a/chromium/content/browser/android/overscroll_controller_android_unittest.cc b/chromium/content/browser/android/overscroll_controller_android_unittest.cc
index d43297d7254..8750391986b 100644
--- a/chromium/content/browser/android/overscroll_controller_android_unittest.cc
+++ b/chromium/content/browser/android/overscroll_controller_android_unittest.cc
@@ -5,13 +5,12 @@
#include "content/browser/android/overscroll_controller_android.h"
#include <memory>
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "cc/layers/layer.h"
#include "content/public/common/use_zoom_for_dsf_policy.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebGestureEvent.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_gesture_event.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/android/overscroll_glow.h"
#include "ui/android/overscroll_refresh.h"
#include "ui/android/resources/resource_manager_impl.h"
@@ -35,7 +34,11 @@ namespace {
class MockCompositor : public WindowAndroidCompositor {
public:
~MockCompositor() override {}
- void AttachLayerForReadback(scoped_refptr<cc::Layer>) override {}
+ base::WeakPtr<ui::WindowAndroidCompositor> GetWeakPtr() override {
+ return nullptr;
+ }
+ void IncrementReadbackRequestCount() override {}
+ void DecrementReadbackRequestCount() override {}
void RequestCopyOfOutputOnRootLayer(
std::unique_ptr<viz::CopyOutputRequest>) override {}
void SetNeedsAnimate() override {}
diff --git a/chromium/content/browser/android/select_popup.cc b/chromium/content/browser/android/select_popup.cc
new file mode 100644
index 00000000000..1ec666da9e6
--- /dev/null
+++ b/chromium/content/browser/android/select_popup.cc
@@ -0,0 +1,172 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/android/select_popup.h"
+
+#include "base/android/jni_android.h"
+#include "base/android/jni_string.h"
+#include "base/android/scoped_java_ref.h"
+#include "content/browser/web_contents/web_contents_impl.h"
+#include "content/browser/web_contents/web_contents_view_android.h"
+#include "content/public/browser/render_frame_host.h"
+#include "content/public/common/menu_item.h"
+#include "content/public/common/use_zoom_for_dsf_policy.h"
+#include "jni/SelectPopup_jni.h"
+#include "ui/android/window_android.h"
+#include "ui/gfx/geometry/rect_f.h"
+
+using base::android::AttachCurrentThread;
+using base::android::JavaParamRef;
+using base::android::ScopedJavaLocalRef;
+
+namespace content {
+
+namespace {
+
+// Describes the type and enabled state of a select popup item.
+//
+// A Java counterpart will be generated for this enum.
+// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.content.browser.input
+enum PopupItemType {
+ // Popup item is of type group
+ POPUP_ITEM_TYPE_GROUP,
+
+ // Popup item is disabled
+ POPUP_ITEM_TYPE_DISABLED,
+
+ // Popup item is enabled
+ POPUP_ITEM_TYPE_ENABLED,
+};
+
+} // namespace
+
+jlong JNI_SelectPopup_Init(JNIEnv* env,
+ const JavaParamRef<jobject>& obj,
+ const JavaParamRef<jobject>& jweb_contents) {
+ WebContents* web_contents = WebContents::FromJavaWebContents(jweb_contents);
+ DCHECK(web_contents);
+
+ auto* wc_impl = static_cast<WebContentsImpl*>(web_contents);
+ auto* wcv = static_cast<WebContentsViewAndroid*>(wc_impl->GetView());
+
+ // Owned by |WebContentsViewAndroid|.
+ auto select_popup = std::make_unique<SelectPopup>(env, obj, wc_impl);
+ SelectPopup* select_popup_ptr = select_popup.get();
+ wcv->SetSelectPopup(std::move(select_popup));
+ return reinterpret_cast<intptr_t>(select_popup_ptr);
+}
+
+SelectPopup::SelectPopup(JNIEnv* env,
+ const JavaParamRef<jobject>& obj,
+ WebContentsImpl* web_contents)
+ : web_contents_(web_contents), java_obj_(env, obj) {}
+
+SelectPopup::~SelectPopup() {
+ JNIEnv* env = AttachCurrentThread();
+ ScopedJavaLocalRef<jobject> j_obj = java_obj_.get(env);
+ if (j_obj.is_null())
+ return;
+ Java_SelectPopup_destroy(env, j_obj);
+}
+
+void SelectPopup::ShowMenu(RenderFrameHost* frame,
+ const gfx::Rect& bounds,
+ const std::vector<MenuItem>& items,
+ int selected_item,
+ bool multiple,
+ bool right_aligned) {
+ JNIEnv* env = AttachCurrentThread();
+ ScopedJavaLocalRef<jobject> j_obj = java_obj_.get(env);
+ if (j_obj.is_null())
+ return;
+
+ // For multi-select list popups we find the list of previous selections by
+ // iterating through the items. But for single selection popups we take the
+ // given |selected_item| as is.
+ ScopedJavaLocalRef<jintArray> selected_array;
+ if (multiple) {
+ std::unique_ptr<jint[]> native_selected_array(new jint[items.size()]);
+ size_t selected_count = 0;
+ for (size_t i = 0; i < items.size(); ++i) {
+ if (items[i].checked)
+ native_selected_array[selected_count++] = i;
+ }
+
+ selected_array =
+ ScopedJavaLocalRef<jintArray>(env, env->NewIntArray(selected_count));
+ env->SetIntArrayRegion(selected_array.obj(), 0, selected_count,
+ native_selected_array.get());
+ } else {
+ selected_array = ScopedJavaLocalRef<jintArray>(env, env->NewIntArray(1));
+ jint value = selected_item;
+ env->SetIntArrayRegion(selected_array.obj(), 0, 1, &value);
+ }
+
+ ScopedJavaLocalRef<jintArray> enabled_array(env,
+ env->NewIntArray(items.size()));
+ std::vector<base::string16> labels;
+ labels.reserve(items.size());
+ for (size_t i = 0; i < items.size(); ++i) {
+ labels.push_back(items[i].label);
+ jint enabled = (items[i].type == MenuItem::GROUP
+ ? POPUP_ITEM_TYPE_GROUP
+ : (items[i].enabled ? POPUP_ITEM_TYPE_ENABLED
+ : POPUP_ITEM_TYPE_DISABLED));
+ env->SetIntArrayRegion(enabled_array.obj(), i, 1, &enabled);
+ }
+ ScopedJavaLocalRef<jobjectArray> items_array(
+ base::android::ToJavaArrayOfStrings(env, labels));
+ ui::ViewAndroid* view = web_contents_->GetNativeView();
+ popup_view_ = view->AcquireAnchorView();
+ const ScopedJavaLocalRef<jobject> popup_view = popup_view_.view();
+ if (popup_view.is_null())
+ return;
+ // |bounds| is in physical pixels if --use-zoom-for-dsf is enabled. Otherwise,
+ // it is in DIP pixels.
+ gfx::RectF bounds_dip = gfx::RectF(bounds);
+ if (IsUseZoomForDSFEnabled())
+ bounds_dip.Scale(1 / web_contents_->GetNativeView()->GetDipScale());
+ view->SetAnchorRect(popup_view, bounds_dip);
+ Java_SelectPopup_show(env, j_obj, popup_view,
+ reinterpret_cast<intptr_t>(frame), items_array,
+ enabled_array, multiple, selected_array, right_aligned);
+}
+
+void SelectPopup::HideMenu() {
+ JNIEnv* env = AttachCurrentThread();
+ ScopedJavaLocalRef<jobject> j_obj = java_obj_.get(env);
+ if (!j_obj.is_null())
+ Java_SelectPopup_hideWithoutCancel(env, j_obj);
+ popup_view_.Reset();
+}
+
+void SelectPopup::SelectMenuItems(JNIEnv* env,
+ const JavaParamRef<jobject>& obj,
+ jlong selectPopupSourceFrame,
+ const JavaParamRef<jintArray>& indices) {
+ RenderFrameHostImpl* rfhi =
+ reinterpret_cast<RenderFrameHostImpl*>(selectPopupSourceFrame);
+ DCHECK(rfhi);
+ if (indices == NULL) {
+ rfhi->DidCancelPopupMenu();
+ return;
+ }
+
+ int selected_count = env->GetArrayLength(indices);
+ std::vector<int> selected_indices;
+ jint* indices_ptr = env->GetIntArrayElements(indices, NULL);
+ for (int i = 0; i < selected_count; ++i)
+ selected_indices.push_back(indices_ptr[i]);
+ env->ReleaseIntArrayElements(indices, indices_ptr, JNI_ABORT);
+ rfhi->DidSelectPopupMenuItems(selected_indices);
+}
+
+base::android::ScopedJavaLocalRef<jobject> SelectPopup::GetWindowAndroid(
+ JNIEnv* env,
+ const JavaParamRef<jobject>& obj) {
+ auto* window = web_contents_->GetNativeView()->GetWindowAndroid();
+ return window ? window->GetJavaObject() : ScopedJavaLocalRef<jobject>();
+}
+
+} // namespace content
diff --git a/chromium/content/browser/android/select_popup.h b/chromium/content/browser/android/select_popup.h
new file mode 100644
index 00000000000..bef949c1ae9
--- /dev/null
+++ b/chromium/content/browser/android/select_popup.h
@@ -0,0 +1,63 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_BROWSER_ANDROID_SELECT_POPUP_H_
+#define CONTENT_BROWSER_ANDROID_SELECT_POPUP_H_
+
+#include <jni.h>
+
+#include "base/android/jni_weak_ref.h"
+#include "base/android/scoped_java_ref.h"
+#include "ui/android/view_android.h"
+
+namespace gfx {
+class Rect;
+}
+
+namespace content {
+
+class RenderFrameHost;
+class WebContentsImpl;
+struct MenuItem;
+
+class SelectPopup {
+ public:
+ SelectPopup(JNIEnv* env,
+ const base::android::JavaParamRef<jobject>& obj,
+ WebContentsImpl* web_contents);
+ base::android::ScopedJavaLocalRef<jobject> GetWindowAndroid(
+ JNIEnv* env,
+ const base::android::JavaParamRef<jobject>& obj);
+ ~SelectPopup();
+
+ // Creates a popup menu with |items|.
+ // |multiple| defines if it should support multi-select.
+ // If not |multiple|, |selected_item| sets the initially selected item.
+ // Otherwise, item's "checked" flag selects it.
+ void ShowMenu(RenderFrameHost* frame,
+ const gfx::Rect& bounds,
+ const std::vector<MenuItem>& items,
+ int selected_item,
+ bool multiple,
+ bool right_aligned);
+ // Hides a visible popup menu.
+ void HideMenu();
+
+ // Notifies that items were selected in the currently showing select popup.
+ void SelectMenuItems(JNIEnv* env,
+ const base::android::JavaParamRef<jobject>& obj,
+ jlong selectPopupSourceFrame,
+ const base::android::JavaParamRef<jintArray>& indices);
+
+ private:
+ WebContentsImpl* web_contents_;
+ JavaObjectWeakGlobalRef java_obj_;
+
+ // Select popup view
+ ui::ViewAndroid::ScopedAnchorView popup_view_;
+};
+
+} // namespace content
+
+#endif // CONTENT_BROWSER_ANDROID_SELECT_POPUP_H_
diff --git a/chromium/content/browser/android/selection/OWNERS b/chromium/content/browser/android/selection/OWNERS
new file mode 100644
index 00000000000..4943accdb87
--- /dev/null
+++ b/chromium/content/browser/android/selection/OWNERS
@@ -0,0 +1 @@
+amaralp@chromium.org
diff --git a/chromium/content/browser/android/composited_touch_handle_drawable.cc b/chromium/content/browser/android/selection/composited_touch_handle_drawable.cc
index a48b0fa125d..30651710d63 100644
--- a/chromium/content/browser/android/composited_touch_handle_drawable.cc
+++ b/chromium/content/browser/android/selection/composited_touch_handle_drawable.cc
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "content/browser/android/composited_touch_handle_drawable.h"
+#include "content/browser/android/selection/composited_touch_handle_drawable.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
diff --git a/chromium/content/browser/android/composited_touch_handle_drawable.h b/chromium/content/browser/android/selection/composited_touch_handle_drawable.h
index 12d753dce47..0e4b6a23933 100644
--- a/chromium/content/browser/android/composited_touch_handle_drawable.h
+++ b/chromium/content/browser/android/selection/composited_touch_handle_drawable.h
@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef CONTENT_BROWSER_ANDROID_COMPOSITED_TOUCH_HANDLE_DRAWABLE_H_
-#define CONTENT_BROWSER_ANDROID_COMPOSITED_TOUCH_HANDLE_DRAWABLE_H_
+#ifndef CONTENT_BROWSER_ANDROID_SELECTION_COMPOSITED_TOUCH_HANDLE_DRAWABLE_H_
+#define CONTENT_BROWSER_ANDROID_SELECTION_COMPOSITED_TOUCH_HANDLE_DRAWABLE_H_
#include "ui/touch_selection/touch_handle.h"
@@ -47,4 +47,4 @@ class CompositedTouchHandleDrawable : public ui::TouchHandleDrawable {
} // namespace content
-#endif // CONTENT_BROWSER_ANDROID_COMPOSITED_TOUCH_HANDLE_DRAWABLE_H_
+#endif // CONTENT_BROWSER_ANDROID_SELECTION_COMPOSITED_TOUCH_HANDLE_DRAWABLE_H_
diff --git a/chromium/content/browser/android/selection_popup_controller.cc b/chromium/content/browser/android/selection/selection_popup_controller.cc
index 4ebfcfcd238..b36782f64f8 100644
--- a/chromium/content/browser/android/selection_popup_controller.cc
+++ b/chromium/content/browser/android/selection/selection_popup_controller.cc
@@ -2,17 +2,18 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "content/browser/android/selection_popup_controller.h"
+#include "content/browser/android/selection/selection_popup_controller.h"
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/android/scoped_java_ref.h"
-#include "content/browser/android/composited_touch_handle_drawable.h"
+#include "content/browser/android/selection/composited_touch_handle_drawable.h"
#include "content/browser/renderer_host/render_widget_host_view_android.h"
#include "content/browser/web_contents/web_contents_impl.h"
+#include "content/browser/web_contents/web_contents_view_android.h"
#include "content/public/common/context_menu_params.h"
#include "jni/SelectionPopupControllerImpl_jni.h"
-#include "third_party/WebKit/public/web/WebContextMenuData.h"
+#include "third_party/blink/public/web/web_context_menu_data.h"
#include "ui/gfx/geometry/point_conversions.h"
using base::android::AttachCurrentThread;
@@ -24,7 +25,7 @@ using blink::WebContextMenuData;
namespace content {
-void JNI_SelectionPopupControllerImpl_Init(
+jlong JNI_SelectionPopupControllerImpl_Init(
JNIEnv* env,
const JavaParamRef<jobject>& obj,
const JavaParamRef<jobject>& jweb_contents) {
@@ -32,7 +33,9 @@ void JNI_SelectionPopupControllerImpl_Init(
DCHECK(web_contents);
// Owns itself and gets destroyed when |WebContentsDestroyed| is called.
- (new SelectionPopupController(env, obj, web_contents))->Initialize();
+ auto* controller = new SelectionPopupController(env, obj, web_contents);
+ controller->Initialize();
+ return reinterpret_cast<intptr_t>(controller);
}
SelectionPopupController::SelectionPopupController(
@@ -41,6 +44,9 @@ SelectionPopupController::SelectionPopupController(
WebContents* web_contents)
: RenderWidgetHostConnector(web_contents) {
java_obj_ = JavaObjectWeakGlobalRef(env, obj);
+ auto* wcva = static_cast<WebContentsViewAndroid*>(
+ static_cast<WebContentsImpl*>(web_contents)->GetView());
+ wcva->set_selection_popup_controller(this);
}
ScopedJavaLocalRef<jobject> SelectionPopupController::GetContext() const {
@@ -53,6 +59,14 @@ ScopedJavaLocalRef<jobject> SelectionPopupController::GetContext() const {
return Java_SelectionPopupControllerImpl_getContext(env, obj);
}
+void SelectionPopupController::SetTextHandlesTemporarilyHidden(
+ JNIEnv* env,
+ const JavaParamRef<jobject>& obj,
+ jboolean hidden) {
+ if (rwhva_)
+ rwhva_->SetTextHandlesTemporarilyHidden(hidden);
+}
+
std::unique_ptr<ui::TouchHandleDrawable>
SelectionPopupController::CreateTouchHandleDrawable() {
ScopedJavaLocalRef<jobject> activityContext = GetContext();
@@ -95,6 +109,7 @@ void SelectionPopupController::UpdateRenderProcessConnection(
old_rwhva->set_selection_popup_controller(nullptr);
if (new_rwhva)
new_rwhva->set_selection_popup_controller(this);
+ rwhva_ = new_rwhva;
}
void SelectionPopupController::OnSelectionEvent(
@@ -175,25 +190,24 @@ bool SelectionPopupController::ShowSelectionMenu(
return true;
}
-void SelectionPopupController::OnShowUnhandledTapUIIfNeeded(int x_px,
- int y_px) {
+void SelectionPopupController::OnSelectWordAroundCaretAck(bool did_select,
+ int start_adjust,
+ int end_adjust) {
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jobject> obj = java_obj_.get(env);
if (obj.is_null())
return;
- Java_SelectionPopupControllerImpl_onShowUnhandledTapUIIfNeeded(
- env, obj, static_cast<jint>(x_px), static_cast<jint>(y_px));
+ Java_SelectionPopupControllerImpl_onSelectWordAroundCaretAck(
+ env, obj, did_select, start_adjust, end_adjust);
}
-void SelectionPopupController::OnSelectWordAroundCaretAck(bool did_select,
- int start_adjust,
- int end_adjust) {
+void SelectionPopupController::HidePopupsAndPreserveSelection() {
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jobject> obj = java_obj_.get(env);
if (obj.is_null())
return;
- Java_SelectionPopupControllerImpl_onSelectWordAroundCaretAck(
- env, obj, did_select, start_adjust, end_adjust);
+
+ Java_SelectionPopupControllerImpl_hidePopupsAndPreserveSelection(env, obj);
}
} // namespace content
diff --git a/chromium/content/browser/android/selection_popup_controller.h b/chromium/content/browser/android/selection/selection_popup_controller.h
index 624ce0ac49f..900cfbbda56 100644
--- a/chromium/content/browser/android/selection_popup_controller.h
+++ b/chromium/content/browser/android/selection/selection_popup_controller.h
@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef CONTENT_BROWSER_ANDROID_SELECTION_POPUP_CONTROLLER_H_
-#define CONTENT_BROWSER_ANDROID_SELECTION_POPUP_CONTROLLER_H_
+#ifndef CONTENT_BROWSER_ANDROID_SELECTION_SELECTION_POPUP_CONTROLLER_H_
+#define CONTENT_BROWSER_ANDROID_SELECTION_SELECTION_POPUP_CONTROLLER_H_
#include <jni.h>
@@ -27,6 +27,11 @@ class SelectionPopupController : public RenderWidgetHostConnector {
const base::android::JavaParamRef<jobject>& obj,
WebContents* web_contents);
+ void SetTextHandlesTemporarilyHidden(
+ JNIEnv* env,
+ const base::android::JavaParamRef<jobject>& obj,
+ jboolean hidden);
+
// RendetWidgetHostConnector implementation.
void UpdateRenderProcessConnection(
RenderWidgetHostViewAndroid* old_rwhva,
@@ -38,11 +43,10 @@ class SelectionPopupController : public RenderWidgetHostConnector {
void OnDragUpdate(const gfx::PointF& position);
void OnSelectionChanged(const std::string& text);
bool ShowSelectionMenu(const ContextMenuParams& params, int handle_height);
- // |x| and |y| are in physical pixel scale.
- void OnShowUnhandledTapUIIfNeeded(int x_px, int y_px);
void OnSelectWordAroundCaretAck(bool did_select,
int start_adjust,
int end_adjust);
+ void HidePopupsAndPreserveSelection();
std::unique_ptr<ui::TouchHandleDrawable> CreateTouchHandleDrawable();
void MoveRangeSelectionExtent(const gfx::PointF& extent);
@@ -52,10 +56,11 @@ class SelectionPopupController : public RenderWidgetHostConnector {
private:
~SelectionPopupController() override {}
base::android::ScopedJavaLocalRef<jobject> GetContext() const;
+ RenderWidgetHostViewAndroid* rwhva_ = nullptr;
JavaObjectWeakGlobalRef java_obj_;
};
} // namespace content
-#endif // CONTENT_BROWSER_ANDROID_SELECTION_POPUP_CONTROLLER_H_
+#endif // CONTENT_BROWSER_ANDROID_SELECTION_SELECTION_POPUP_CONTROLLER_H_
diff --git a/chromium/content/browser/android/smart_selection_client.cc b/chromium/content/browser/android/selection/smart_selection_client.cc
index ad96d4155e6..9b66c9f7d1f 100644
--- a/chromium/content/browser/android/smart_selection_client.cc
+++ b/chromium/content/browser/android/selection/smart_selection_client.cc
@@ -2,12 +2,11 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "content/browser/android/smart_selection_client.h"
+#include "content/browser/android/selection/smart_selection_client.h"
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/bind.h"
-#include "base/memory/ptr_util.h"
#include "base/supports_user_data.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
diff --git a/chromium/content/browser/android/smart_selection_client.h b/chromium/content/browser/android/selection/smart_selection_client.h
index ca1c32a48f4..93737becbee 100644
--- a/chromium/content/browser/android/smart_selection_client.h
+++ b/chromium/content/browser/android/selection/smart_selection_client.h
@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef CONTENT_BROWSER_ANDROID_SMART_SELECTION_CLIENT_H_
-#define CONTENT_BROWSER_ANDROID_SMART_SELECTION_CLIENT_H_
+#ifndef CONTENT_BROWSER_ANDROID_SELECTION_SMART_SELECTION_CLIENT_H_
+#define CONTENT_BROWSER_ANDROID_SELECTION_SMART_SELECTION_CLIENT_H_
#include <jni.h>
@@ -57,4 +57,4 @@ class SmartSelectionClient {
} // namespace content
-#endif // CONTENT_BROWSER_ANDROID_SMART_SELECTION_CLIENT_H_
+#endif // CONTENT_BROWSER_ANDROID_SELECTION_SMART_SELECTION_CLIENT_H_
diff --git a/chromium/content/browser/android/synchronous_compositor_browser_filter.cc b/chromium/content/browser/android/synchronous_compositor_browser_filter.cc
index 29f01151837..af6f7774137 100644
--- a/chromium/content/browser/android/synchronous_compositor_browser_filter.cc
+++ b/chromium/content/browser/android/synchronous_compositor_browser_filter.cc
@@ -9,7 +9,6 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/lazy_instance.h"
-#include "base/memory/ptr_util.h"
#include "base/optional.h"
#include "base/stl_util.h"
#include "content/browser/android/synchronous_compositor_sync_call_bridge.h"
diff --git a/chromium/content/browser/android/synchronous_compositor_host.cc b/chromium/content/browser/android/synchronous_compositor_host.cc
index 58253929e49..7a2ce5797c4 100644
--- a/chromium/content/browser/android/synchronous_compositor_host.cc
+++ b/chromium/content/browser/android/synchronous_compositor_host.cc
@@ -263,11 +263,9 @@ void SynchronousCompositorHost::InitMojo() {
mojom::SynchronousCompositorAssociatedRequest compositor_request =
mojo::MakeRequest(&sync_compositor_);
- rwhva_->GetRenderWidgetHostImpl()
- ->GetWidgetInputHandler()
- ->AttachSynchronousCompositor(std::move(host_control),
- host.PassInterface(),
- std::move(compositor_request));
+ rwhva_->host()->GetWidgetInputHandler()->AttachSynchronousCompositor(
+ std::move(host_control), host.PassInterface(),
+ std::move(compositor_request));
}
bool SynchronousCompositorHost::IsReadyForSynchronousCall() {
@@ -295,7 +293,8 @@ SynchronousCompositorHost::DemandDrawHwAsync(
const gfx::Rect& viewport_rect_for_tile_priority,
const gfx::Transform& transform_for_tile_priority) {
scoped_refptr<FrameFuture> frame_future = new FrameFuture();
- if (compute_scroll_needs_synchronous_draw_) {
+ if (compute_scroll_needs_synchronous_draw_ || !allow_async_draw_) {
+ allow_async_draw_ = allow_async_draw_ || IsReadyForSynchronousCall();
compute_scroll_needs_synchronous_draw_ = false;
auto frame_ptr = std::make_unique<Frame>();
*frame_ptr = DemandDrawHw(viewport_size, viewport_rect_for_tile_priority,
@@ -575,6 +574,8 @@ void SynchronousCompositorHost::SynchronouslyZoomBy(float zoom_delta,
void SynchronousCompositorHost::OnComputeScroll(
base::TimeTicks animation_time) {
+ on_compute_scroll_called_ = true;
+
if (!need_animate_scroll_)
return;
need_animate_scroll_ = false;
@@ -608,7 +609,7 @@ void SynchronousCompositorHost::SetBeginFramePaused(bool paused) {
}
void SynchronousCompositorHost::SetNeedsBeginFrames(bool needs_begin_frames) {
- rwhva_->GetRenderWidgetHostImpl()->SetNeedsBeginFrame(needs_begin_frames);
+ rwhva_->host()->SetNeedsBeginFrame(needs_begin_frames);
}
void SynchronousCompositorHost::LayerTreeFrameSinkCreated() {
diff --git a/chromium/content/browser/android/synchronous_compositor_host.h b/chromium/content/browser/android/synchronous_compositor_host.h
index 99523dcc63b..74e01ac917d 100644
--- a/chromium/content/browser/android/synchronous_compositor_host.h
+++ b/chromium/content/browser/android/synchronous_compositor_host.h
@@ -51,10 +51,6 @@ class SynchronousCompositorHost : public SynchronousCompositor,
~SynchronousCompositorHost() override;
// SynchronousCompositor overrides.
- SynchronousCompositor::Frame DemandDrawHw(
- const gfx::Size& viewport_size,
- const gfx::Rect& viewport_rect_for_tile_priority,
- const gfx::Transform& transform_for_tile_priority) override;
scoped_refptr<FrameFuture> DemandDrawHwAsync(
const gfx::Size& viewport_size,
const gfx::Rect& viewport_rect_for_tile_priority,
@@ -93,6 +89,8 @@ class SynchronousCompositorHost : public SynchronousCompositor,
void UpdateState(const SyncCompositorCommonRendererParams& params) override;
void SetNeedsBeginFrames(bool needs_begin_frames) override;
+ bool on_compute_scroll_called() { return on_compute_scroll_called_; }
+
private:
class ScopedSendZeroMemory;
struct SharedMemoryWithSize;
@@ -101,6 +99,10 @@ class SynchronousCompositorHost : public SynchronousCompositor,
SynchronousCompositorHost(RenderWidgetHostViewAndroid* rwhva,
bool use_in_proc_software_draw);
+ SynchronousCompositor::Frame DemandDrawHw(
+ const gfx::Size& viewport_size,
+ const gfx::Rect& viewport_rect_for_tile_priority,
+ const gfx::Transform& transform_for_tile_priority);
bool DemandDrawSwInProc(SkCanvas* canvas);
void SetSoftwareDrawSharedMemoryIfNeeded(size_t stride, size_t buffer_size);
void SendZeroMemory();
@@ -124,6 +126,13 @@ class SynchronousCompositorHost : public SynchronousCompositor,
size_t bytes_limit_;
std::unique_ptr<SharedMemoryWithSize> software_draw_shm_;
+ // Make sure to send a synchronous IPC that succeeds first before sending
+ // asynchronous ones. This shouldn't be needed. However we may have come
+ // to rely on sending a synchronous message first on initialization. So
+ // with an abundance of caution, keep that behavior until we are sure this
+ // isn't required.
+ bool allow_async_draw_ = false;
+
// Indicates the next draw needs to be synchronous
bool compute_scroll_needs_synchronous_draw_ = false;
@@ -133,6 +142,11 @@ class SynchronousCompositorHost : public SynchronousCompositor,
// Updated by both renderer and browser.
gfx::ScrollOffset root_scroll_offset_;
+ // Indicates that whether OnComputeScroll is called or overridden. The
+ // fling_controller should advance the fling only when OnComputeScroll is not
+ // overridden.
+ bool on_compute_scroll_called_ = false;
+
// From renderer.
uint32_t renderer_param_version_;
bool need_animate_scroll_;
diff --git a/chromium/content/browser/android/text_suggestion_host_android.h b/chromium/content/browser/android/text_suggestion_host_android.h
index c32b42238de..af220c331ff 100644
--- a/chromium/content/browser/android/text_suggestion_host_android.h
+++ b/chromium/content/browser/android/text_suggestion_host_android.h
@@ -8,8 +8,8 @@
#include "content/browser/android/render_widget_host_connector.h"
#include "content/browser/renderer_host/input/timeout_monitor.h"
#include "services/service_manager/public/cpp/binder_registry.h"
-#include "third_party/WebKit/public/platform/input_host.mojom.h"
-#include "third_party/WebKit/public/platform/input_messages.mojom.h"
+#include "third_party/blink/public/platform/input_host.mojom.h"
+#include "third_party/blink/public/platform/input_messages.mojom.h"
namespace content {
diff --git a/chromium/content/browser/android/text_suggestion_host_mojo_impl_android.h b/chromium/content/browser/android/text_suggestion_host_mojo_impl_android.h
index 29c66797b7e..075e2735e9d 100644
--- a/chromium/content/browser/android/text_suggestion_host_mojo_impl_android.h
+++ b/chromium/content/browser/android/text_suggestion_host_mojo_impl_android.h
@@ -5,7 +5,7 @@
#ifndef CONTENT_BROWSER_ANDROID_TEXT_SUGGESTION_HOST_MOJO_IMPL_ANDROID_H_
#define CONTENT_BROWSER_ANDROID_TEXT_SUGGESTION_HOST_MOJO_IMPL_ANDROID_H_
-#include "third_party/WebKit/public/platform/input_host.mojom.h"
+#include "third_party/blink/public/platform/input_host.mojom.h"
namespace content {
diff --git a/chromium/content/browser/android/url_request_content_job.cc b/chromium/content/browser/android/url_request_content_job.cc
index baf9483fafe..fb7f3c479a8 100644
--- a/chromium/content/browser/android/url_request_content_job.cc
+++ b/chromium/content/browser/android/url_request_content_job.cc
@@ -9,6 +9,8 @@
#include "base/files/file_util.h"
#include "base/message_loop/message_loop.h"
#include "base/task_runner.h"
+#include "content/public/browser/resource_request_info.h"
+#include "content/public/common/resource_type.h"
#include "net/base/file_stream.h"
#include "net/base/io_buffer.h"
#include "net/http/http_util.h"
@@ -87,6 +89,10 @@ bool URLRequestContentJob::IsRedirectResponse(GURL* location,
bool URLRequestContentJob::GetMimeType(std::string* mime_type) const {
DCHECK(request_);
+ if (!mime_type_from_intent_.empty()) {
+ *mime_type = mime_type_from_intent_;
+ return true;
+ }
if (!meta_info_.mime_type.empty()) {
*mime_type = meta_info_.mime_type;
return true;
@@ -96,6 +102,15 @@ bool URLRequestContentJob::GetMimeType(std::string* mime_type) const {
void URLRequestContentJob::SetExtraRequestHeaders(
const net::HttpRequestHeaders& headers) {
+ const content::ResourceRequestInfo* resource_request_info =
+ content::ResourceRequestInfo::ForRequest(request());
+ if (resource_request_info && resource_request_info->GetResourceType() ==
+ content::RESOURCE_TYPE_MAIN_FRAME) {
+ std::string intent_type_header;
+ if (headers.GetHeader("X-Chrome-intent-type", &intent_type_header))
+ mime_type_from_intent_ = intent_type_header;
+ }
+
std::string range_header;
if (!headers.GetHeader(net::HttpRequestHeaders::kRange, &range_header))
return;
diff --git a/chromium/content/browser/android/url_request_content_job.h b/chromium/content/browser/android/url_request_content_job.h
index f36f904cc7e..9f6b379b2c8 100644
--- a/chromium/content/browser/android/url_request_content_job.h
+++ b/chromium/content/browser/android/url_request_content_job.h
@@ -86,6 +86,7 @@ class CONTENT_EXPORT URLRequestContentJob : public net::URLRequestJob {
std::unique_ptr<net::FileStream> stream_;
ContentMetaInfo meta_info_;
+ std::string mime_type_from_intent_;
const scoped_refptr<base::TaskRunner> content_task_runner_;
net::HttpByteRange byte_range_;
diff --git a/chromium/content/browser/android/url_request_content_job_unittest.cc b/chromium/content/browser/android/url_request_content_job_unittest.cc
index 1e96893d229..8815dc8f323 100644
--- a/chromium/content/browser/android/url_request_content_job_unittest.cc
+++ b/chromium/content/browser/android/url_request_content_job_unittest.cc
@@ -15,6 +15,7 @@
#include "base/test/scoped_task_environment.h"
#include "base/test/test_file_util.h"
#include "base/threading/thread_task_runner_handle.h"
+#include "content/public/browser/resource_request_info.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -115,7 +116,7 @@ class URLRequestContentJobTest : public testing::Test {
// contents out of it. If a Range is provided, this function will add the
// appropriate Range http header to the request and verify the bytes
// retrieved.
- void RunRequest(const Range* range);
+ void RunRequest(const Range* range, const char* intent_type);
base::test::ScopedTaskEnvironment scoped_task_environment_;
JobObserverImpl observer_;
@@ -125,7 +126,8 @@ class URLRequestContentJobTest : public testing::Test {
URLRequestContentJobTest::URLRequestContentJobTest() {}
-void URLRequestContentJobTest::RunRequest(const Range* range) {
+void URLRequestContentJobTest::RunRequest(const Range* range,
+ const char* intent_type) {
base::FilePath test_dir;
PathService::Get(base::DIR_SOURCE_ROOT, &test_dir);
test_dir = test_dir.AppendASCII("content");
@@ -148,6 +150,19 @@ void URLRequestContentJobTest::RunRequest(const Range* range) {
std::unique_ptr<net::URLRequest> request(context_.CreateRequest(
GURL(path.value()), net::DEFAULT_PRIORITY, &delegate_));
+
+ ResourceRequestInfo::AllocateForTesting(request.get(),
+ RESOURCE_TYPE_MAIN_FRAME,
+ nullptr, // context
+ 0, // render_process_id
+ 0, // render_view_id
+ 0, // render_frame_id
+ true, // is_main_frame
+ false, // allow_download
+ true, // is_async
+ PREVIEWS_OFF, // previews_state
+ nullptr); // navigation_ui_data
+
int expected_length = file_size;
if (range) {
ASSERT_GE(range->start, 0);
@@ -164,6 +179,12 @@ void URLRequestContentJobTest::RunRequest(const Range* range) {
expected_length = 0;
}
}
+ std::string expected_mime_type("image/png");
+ if (intent_type) {
+ request->SetExtraRequestHeaderByName("X-Chrome-intent-type", intent_type,
+ true /*overwrite*/);
+ expected_mime_type = intent_type;
+ }
request->Start();
base::RunLoop loop;
@@ -172,29 +193,37 @@ void URLRequestContentJobTest::RunRequest(const Range* range) {
EXPECT_FALSE(delegate_.request_failed());
ASSERT_EQ(1, observer_.num_jobs_created());
EXPECT_EQ(expected_length, delegate_.bytes_received());
+
+ std::string mime_type;
+ request->GetMimeType(&mime_type);
+ EXPECT_EQ(expected_mime_type, mime_type);
}
// Disabled: http://crbug.com/807045.
TEST_F(URLRequestContentJobTest, DISABLED_ContentURIWithoutRange) {
- RunRequest(NULL);
+ RunRequest(NULL, NULL);
}
// Disabled: http://crbug.com/807045.
TEST_F(URLRequestContentJobTest, DISABLED_ContentURIWithSmallRange) {
Range range(1, 10);
- RunRequest(&range);
+ RunRequest(&range, NULL);
}
// Disabled: http://crbug.com/807045.
TEST_F(URLRequestContentJobTest, DISABLED_ContentURIWithLargeRange) {
Range range(1, 100000);
- RunRequest(&range);
+ RunRequest(&range, NULL);
}
// Disabled: http://crbug.com/807045.
TEST_F(URLRequestContentJobTest, DISABLED_ContentURIWithZeroRange) {
Range range(0, 0);
- RunRequest(&range);
+ RunRequest(&range, NULL);
+}
+
+TEST_F(URLRequestContentJobTest, ContentURIWithIntentTypeHeader) {
+ RunRequest(NULL, "text/html");
}
} // namespace
diff --git a/chromium/content/browser/appcache/appcache.cc b/chromium/content/browser/appcache/appcache.cc
index 061c95de799..2e1a8046642 100644
--- a/chromium/content/browser/appcache/appcache.cc
+++ b/chromium/content/browser/appcache/appcache.cc
@@ -14,6 +14,7 @@
#include "content/browser/appcache/appcache_host.h"
#include "content/browser/appcache/appcache_storage.h"
#include "content/common/appcache_interfaces.h"
+#include "url/origin.h"
namespace content {
@@ -74,12 +75,11 @@ AppCacheEntry* AppCache::GetEntry(const GURL& url) {
const AppCacheEntry* AppCache::GetEntryAndUrlWithResponseId(
int64_t response_id,
GURL* optional_url_out) {
- for (EntryMap::const_iterator iter = entries_.begin();
- iter != entries_.end(); ++iter) {
- if (iter->second.response_id() == response_id) {
+ for (const auto& pair : entries_) {
+ if (pair.second.response_id() == response_id) {
if (optional_url_out)
- *optional_url_out = iter->first;
- return &iter->second;
+ *optional_url_out = pair.first;
+ return &pair.second;
}
}
return nullptr;
@@ -174,19 +174,18 @@ void AppCache::ToDatabaseRecords(
cache_record->update_time = update_time_;
cache_record->cache_size = 0;
- for (EntryMap::const_iterator iter = entries_.begin();
- iter != entries_.end(); ++iter) {
+ for (const auto& pair : entries_) {
entries->push_back(AppCacheDatabase::EntryRecord());
AppCacheDatabase::EntryRecord& record = entries->back();
- record.url = iter->first;
+ record.url = pair.first;
record.cache_id = cache_id_;
- record.flags = iter->second.types();
- record.response_id = iter->second.response_id();
- record.response_size = iter->second.response_size();
+ record.flags = pair.second.types();
+ record.response_id = pair.second.response_id();
+ record.response_size = pair.second.response_size();
cache_record->cache_size += record.response_size;
}
- GURL origin = group->manifest_url().GetOrigin();
+ const url::Origin origin = url::Origin::Create(group->manifest_url());
for (size_t i = 0; i < intercept_namespaces_.size(); ++i) {
intercepts->push_back(AppCacheDatabase::NamespaceRecord());
@@ -266,19 +265,18 @@ bool AppCache::FindResponseForRequest(const GURL& url,
void AppCache::ToResourceInfoVector(AppCacheResourceInfoVector* infos) const {
DCHECK(infos && infos->empty());
- for (EntryMap::const_iterator iter = entries_.begin();
- iter != entries_.end(); ++iter) {
+ for (const auto& pair : entries_) {
infos->push_back(AppCacheResourceInfo());
AppCacheResourceInfo& info = infos->back();
- info.url = iter->first;
- info.is_master = iter->second.IsMaster();
- info.is_manifest = iter->second.IsManifest();
- info.is_intercept = iter->second.IsIntercept();
- info.is_fallback = iter->second.IsFallback();
- info.is_foreign = iter->second.IsForeign();
- info.is_explicit = iter->second.IsExplicit();
- info.size = iter->second.response_size();
- info.response_id = iter->second.response_id();
+ info.url = pair.first;
+ info.is_master = pair.second.IsMaster();
+ info.is_manifest = pair.second.IsManifest();
+ info.is_intercept = pair.second.IsIntercept();
+ info.is_fallback = pair.second.IsFallback();
+ info.is_foreign = pair.second.IsForeign();
+ info.is_explicit = pair.second.IsExplicit();
+ info.size = pair.second.response_size();
+ info.response_id = pair.second.response_id();
}
}
diff --git a/chromium/content/browser/appcache/appcache.h b/chromium/content/browser/appcache/appcache.h
index f2fdc95566e..f468b5dea18 100644
--- a/chromium/content/browser/appcache/appcache.h
+++ b/chromium/content/browser/appcache/appcache.h
@@ -41,8 +41,8 @@ class AppCacheUpdateJobTest;
class CONTENT_EXPORT AppCache
: public base::RefCounted<AppCache> {
public:
- typedef std::map<GURL, AppCacheEntry> EntryMap;
- typedef std::set<AppCacheHost*> AppCacheHosts;
+ using EntryMap = std::map<GURL, AppCacheEntry>;
+ using AppCacheHosts = std::set<AppCacheHost*>;
AppCache(AppCacheStorage* storage, int64_t cache_id);
diff --git a/chromium/content/browser/appcache/appcache_backend_impl.cc b/chromium/content/browser/appcache/appcache_backend_impl.cc
index e3543ec6933..f0150fb78aa 100644
--- a/chromium/content/browser/appcache/appcache_backend_impl.cc
+++ b/chromium/content/browser/appcache/appcache_backend_impl.cc
@@ -4,7 +4,6 @@
#include "content/browser/appcache/appcache_backend_impl.h"
-#include "base/memory/ptr_util.h"
#include "content/browser/appcache/appcache.h"
#include "content/browser/appcache/appcache_group.h"
#include "content/browser/appcache/appcache_service_impl.h"
diff --git a/chromium/content/browser/appcache/appcache_backend_impl.h b/chromium/content/browser/appcache/appcache_backend_impl.h
index abde0b33910..cf6d4352546 100644
--- a/chromium/content/browser/appcache/appcache_backend_impl.h
+++ b/chromium/content/browser/appcache/appcache_backend_impl.h
@@ -56,7 +56,7 @@ class CONTENT_EXPORT AppCacheBackendImpl {
return (it != hosts_.end()) ? (it->second.get()) : nullptr;
}
- typedef base::hash_map<int, std::unique_ptr<AppCacheHost>> HostMap;
+ using HostMap = base::hash_map<int, std::unique_ptr<AppCacheHost>>;
const HostMap& hosts() { return hosts_; }
// Methods to support cross site navigations. Hosts are transferred
diff --git a/chromium/content/browser/appcache/appcache_database.cc b/chromium/content/browser/appcache/appcache_database.cc
index d0a87ed0707..8e21b82f900 100644
--- a/chromium/content/browser/appcache/appcache_database.cc
+++ b/chromium/content/browser/appcache/appcache_database.cc
@@ -180,6 +180,12 @@ std::string GetActiveExperimentFlags() {
return std::string();
}
+// GetURL().spec() is used instead of Serialize() to ensure
+// backwards compatibility with older data.
+std::string SerializeOrigin(const url::Origin& origin) {
+ return origin.GetURL().spec();
+}
+
} // anon namespace
// AppCacheDatabase ----------------------------------------------------------
@@ -218,32 +224,28 @@ void AppCacheDatabase::Disable() {
ResetConnectionAndTables();
}
-int64_t AppCacheDatabase::GetOriginUsage(const GURL& origin) {
+int64_t AppCacheDatabase::GetOriginUsage(const url::Origin& origin) {
std::vector<CacheRecord> records;
if (!FindCachesForOrigin(origin, &records))
return 0;
int64_t origin_usage = 0;
- std::vector<CacheRecord>::const_iterator iter = records.begin();
- while (iter != records.end()) {
- origin_usage += iter->cache_size;
- ++iter;
- }
+ for (const auto& record : records)
+ origin_usage += record.cache_size;
return origin_usage;
}
-bool AppCacheDatabase::GetAllOriginUsage(std::map<GURL, int64_t>* usage_map) {
- std::set<GURL> origins;
+bool AppCacheDatabase::GetAllOriginUsage(
+ std::map<url::Origin, int64_t>* usage_map) {
+ std::set<url::Origin> origins;
if (!FindOriginsWithGroups(&origins))
return false;
- for (std::set<GURL>::const_iterator origin = origins.begin();
- origin != origins.end(); ++origin) {
- (*usage_map)[*origin] = GetOriginUsage(*origin);
- }
+ for (const auto& origin : origins)
+ (*usage_map)[origin] = GetOriginUsage(origin);
return true;
}
-bool AppCacheDatabase::FindOriginsWithGroups(std::set<GURL>* origins) {
+bool AppCacheDatabase::FindOriginsWithGroups(std::set<url::Origin>* origins) {
DCHECK(origins && origins->empty());
if (!LazyOpen(kDontCreate))
return false;
@@ -254,7 +256,7 @@ bool AppCacheDatabase::FindOriginsWithGroups(std::set<GURL>* origins) {
sql::Statement statement(db_->GetUniqueStatement(kSql));
while (statement.Step())
- origins->insert(GURL(statement.ColumnString(0)));
+ origins->insert(url::Origin::Create(GURL(statement.ColumnString(0))));
return statement.Succeeded();
}
@@ -354,8 +356,8 @@ bool AppCacheDatabase::FindGroupForManifestUrl(
return true;
}
-bool AppCacheDatabase::FindGroupsForOrigin(
- const GURL& origin, std::vector<GroupRecord>* records) {
+bool AppCacheDatabase::FindGroupsForOrigin(const url::Origin& origin,
+ std::vector<GroupRecord>* records) {
DCHECK(records && records->empty());
if (!LazyOpen(kDontCreate))
return false;
@@ -368,7 +370,7 @@ bool AppCacheDatabase::FindGroupsForOrigin(
" FROM Groups WHERE origin = ?";
sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
- statement.BindString(0, origin.spec());
+ statement.BindString(0, SerializeOrigin(origin));
while (statement.Step()) {
records->push_back(GroupRecord());
@@ -414,7 +416,7 @@ bool AppCacheDatabase::InsertGroup(const GroupRecord* record) {
" VALUES(?, ?, ?, ?, ?, ?, ?)";
sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
statement.BindInt64(0, record->group_id);
- statement.BindString(1, record->origin.spec());
+ statement.BindString(1, SerializeOrigin(record->origin));
statement.BindString(2, record->manifest_url.spec());
statement.BindInt64(3, record->creation_time.ToInternalValue());
statement.BindInt64(4, record->last_access_time.ToInternalValue());
@@ -526,19 +528,17 @@ bool AppCacheDatabase::FindCacheForGroup(int64_t group_id,
return true;
}
-bool AppCacheDatabase::FindCachesForOrigin(
- const GURL& origin, std::vector<CacheRecord>* records) {
+bool AppCacheDatabase::FindCachesForOrigin(const url::Origin& origin,
+ std::vector<CacheRecord>* records) {
DCHECK(records);
std::vector<GroupRecord> group_records;
if (!FindGroupsForOrigin(origin, &group_records))
return false;
CacheRecord cache_record;
- std::vector<GroupRecord>::const_iterator iter = group_records.begin();
- while (iter != group_records.end()) {
- if (FindCacheForGroup(iter->group_id, &cache_record))
+ for (const auto& record : group_records) {
+ if (FindCacheForGroup(record.group_id, &cache_record))
records->push_back(cache_record);
- ++iter;
}
return true;
}
@@ -668,11 +668,9 @@ bool AppCacheDatabase::InsertEntryRecords(
sql::Transaction transaction(db_.get());
if (!transaction.Begin())
return false;
- std::vector<EntryRecord>::const_iterator iter = records.begin();
- while (iter != records.end()) {
- if (!InsertEntry(&(*iter)))
+ for (const auto& record : records) {
+ if (!InsertEntry(&record))
return false;
- ++iter;
}
return transaction.Commit();
}
@@ -708,7 +706,7 @@ bool AppCacheDatabase::AddEntryFlags(const GURL& entry_url,
}
bool AppCacheDatabase::FindNamespacesForOrigin(
- const GURL& origin,
+ const url::Origin& origin,
std::vector<NamespaceRecord>* intercepts,
std::vector<NamespaceRecord>* fallbacks) {
DCHECK(intercepts && intercepts->empty());
@@ -721,7 +719,7 @@ bool AppCacheDatabase::FindNamespacesForOrigin(
" FROM Namespaces WHERE origin = ?";
sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
- statement.BindString(0, origin.spec());
+ statement.BindString(0, SerializeOrigin(origin));
ReadNamespaceRecords(&statement, intercepts, fallbacks);
@@ -761,7 +759,7 @@ bool AppCacheDatabase::InsertNamespace(
sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
statement.BindInt64(0, record->cache_id);
- statement.BindString(1, record->origin.spec());
+ statement.BindString(1, SerializeOrigin(record->origin));
statement.BindInt(2, record->namespace_.type);
statement.BindString(3, record->namespace_.namespace_url.spec());
statement.BindString(4, record->namespace_.target_url.spec());
@@ -776,11 +774,9 @@ bool AppCacheDatabase::InsertNamespaceRecords(
sql::Transaction transaction(db_.get());
if (!transaction.Begin())
return false;
- std::vector<NamespaceRecord>::const_iterator iter = records.begin();
- while (iter != records.end()) {
- if (!InsertNamespace(&(*iter)))
+ for (const auto& record : records) {
+ if (!InsertNamespace(&record))
return false;
- ++iter;
}
return transaction.Commit();
}
@@ -844,11 +840,9 @@ bool AppCacheDatabase::InsertOnlineWhiteListRecords(
sql::Transaction transaction(db_.get());
if (!transaction.Begin())
return false;
- std::vector<OnlineWhiteListRecord>::const_iterator iter = records.begin();
- while (iter != records.end()) {
- if (!InsertOnlineWhiteList(&(*iter)))
+ for (const auto& record : records) {
+ if (!InsertOnlineWhiteList(&record))
return false;
- ++iter;
}
return transaction.Commit();
}
@@ -915,13 +909,11 @@ bool AppCacheDatabase::RunCachedStatementWithIds(
sql::Statement statement(db_->GetCachedStatement(statement_id, sql));
- std::vector<int64_t>::const_iterator iter = ids.begin();
- while (iter != ids.end()) {
- statement.BindInt64(0, *iter);
+ for (const auto& id : ids) {
+ statement.BindInt64(0, id);
if (!statement.Run())
return false;
statement.Reset(true);
- ++iter;
}
return transaction.Commit();
@@ -967,7 +959,7 @@ bool AppCacheDatabase::FindResponseIdsForCacheHelper(
void AppCacheDatabase::ReadGroupRecord(
const sql::Statement& statement, GroupRecord* record) {
record->group_id = statement.ColumnInt64(0);
- record->origin = GURL(statement.ColumnString(1));
+ record->origin = url::Origin::Create(GURL(statement.ColumnString(1)));
record->manifest_url = GURL(statement.ColumnString(2));
record->creation_time =
base::Time::FromInternalValue(statement.ColumnInt64(3));
@@ -1022,7 +1014,7 @@ void AppCacheDatabase::ReadNamespaceRecords(
void AppCacheDatabase::ReadNamespaceRecord(
const sql::Statement* statement, NamespaceRecord* record) {
record->cache_id = statement->ColumnInt64(0);
- record->origin = GURL(statement->ColumnString(1));
+ record->origin = url::Origin::Create(GURL(statement->ColumnString(1)));
record->namespace_.type =
static_cast<AppCacheNamespaceType>(statement->ColumnInt(2));
record->namespace_.namespace_url = GURL(statement->ColumnString(3));
diff --git a/chromium/content/browser/appcache/appcache_database.h b/chromium/content/browser/appcache/appcache_database.h
index 47ef0b14484..1150724619e 100644
--- a/chromium/content/browser/appcache/appcache_database.h
+++ b/chromium/content/browser/appcache/appcache_database.h
@@ -19,6 +19,7 @@
#include "content/common/appcache_interfaces.h"
#include "content/common/content_export.h"
#include "url/gurl.h"
+#include "url/origin.h"
namespace sql {
class Connection;
@@ -55,7 +56,7 @@ class CONTENT_EXPORT AppCacheDatabase {
~GroupRecord();
int64_t group_id;
- GURL origin;
+ url::Origin origin;
GURL manifest_url;
base::Time creation_time;
base::Time last_access_time;
@@ -89,11 +90,11 @@ class CONTENT_EXPORT AppCacheDatabase {
~NamespaceRecord();
int64_t cache_id;
- GURL origin;
+ url::Origin origin;
AppCacheNamespace namespace_;
};
- typedef std::vector<NamespaceRecord> NamespaceRecordVector;
+ using NamespaceRecordVector = std::vector<NamespaceRecord>;
struct OnlineWhiteListRecord {
OnlineWhiteListRecord() : cache_id(0), is_pattern(false) {}
@@ -110,10 +111,10 @@ class CONTENT_EXPORT AppCacheDatabase {
bool is_disabled() const { return is_disabled_; }
bool was_corruption_detected() const { return was_corruption_detected_; }
- int64_t GetOriginUsage(const GURL& origin);
- bool GetAllOriginUsage(std::map<GURL, int64_t>* usage_map);
+ int64_t GetOriginUsage(const url::Origin& origin);
+ bool GetAllOriginUsage(std::map<url::Origin, int64_t>* usage_map);
- bool FindOriginsWithGroups(std::set<GURL>* origins);
+ bool FindOriginsWithGroups(std::set<url::Origin>* origins);
bool FindLastStorageIds(int64_t* last_group_id,
int64_t* last_cache_id,
int64_t* last_response_id,
@@ -121,8 +122,8 @@ class CONTENT_EXPORT AppCacheDatabase {
bool FindGroup(int64_t group_id, GroupRecord* record);
bool FindGroupForManifestUrl(const GURL& manifest_url, GroupRecord* record);
- bool FindGroupsForOrigin(
- const GURL& origin, std::vector<GroupRecord>* records);
+ bool FindGroupsForOrigin(const url::Origin& origin,
+ std::vector<GroupRecord>* records);
bool FindGroupForCache(int64_t cache_id, GroupRecord* record);
bool InsertGroup(const GroupRecord* record);
bool DeleteGroup(int64_t group_id);
@@ -139,8 +140,8 @@ class CONTENT_EXPORT AppCacheDatabase {
bool FindCache(int64_t cache_id, CacheRecord* record);
bool FindCacheForGroup(int64_t group_id, CacheRecord* record);
- bool FindCachesForOrigin(
- const GURL& origin, std::vector<CacheRecord>* records);
+ bool FindCachesForOrigin(const url::Origin& origin,
+ std::vector<CacheRecord>* records);
bool InsertCache(const CacheRecord* record);
bool DeleteCache(int64_t cache_id);
@@ -164,10 +165,9 @@ class CONTENT_EXPORT AppCacheDatabase {
return FindResponseIdsForCacheHelper(cache_id, NULL, response_ids);
}
- bool FindNamespacesForOrigin(
- const GURL& origin,
- NamespaceRecordVector* intercepts,
- NamespaceRecordVector* fallbacks);
+ bool FindNamespacesForOrigin(const url::Origin& origin,
+ NamespaceRecordVector* intercepts,
+ NamespaceRecordVector* fallbacks);
bool FindNamespacesForCache(int64_t cache_id,
NamespaceRecordVector* intercepts,
std::vector<NamespaceRecord>* fallbacks);
diff --git a/chromium/content/browser/appcache/appcache_database_unittest.cc b/chromium/content/browser/appcache/appcache_database_unittest.cc
index 36b3ee8e68c..7f72b4fe59c 100644
--- a/chromium/content/browser/appcache/appcache_database_unittest.cc
+++ b/chromium/content/browser/appcache/appcache_database_unittest.cc
@@ -49,7 +49,7 @@ TEST(AppCacheDatabaseTest, LazyOpen) {
EXPECT_EQ(0, response_id);
EXPECT_EQ(0, deleteable_response_rowid);
- std::set<GURL> origins;
+ std::set<url::Origin> origins;
EXPECT_TRUE(db.FindOriginsWithGroups(&origins));
EXPECT_TRUE(origins.empty());
}
@@ -140,7 +140,7 @@ TEST(AppCacheDatabaseTest, WasCorrutionDetected) {
{
sql::test::ScopedErrorExpecter expecter;
expecter.ExpectError(SQLITE_CORRUPT);
- std::map<GURL, int64_t> usage_map;
+ std::map<url::Origin, int64_t> usage_map;
EXPECT_FALSE(db.GetAllOriginUsage(&usage_map));
EXPECT_TRUE(db.was_corruption_detected());
EXPECT_TRUE(base::PathExists(kDbFile));
@@ -320,7 +320,7 @@ TEST(AppCacheDatabaseTest, GroupRecords) {
expecter.ExpectError(SQLITE_CONSTRAINT);
const GURL kManifestUrl("http://blah/manifest");
- const GURL kOrigin(kManifestUrl.GetOrigin());
+ const url::Origin kOrigin(url::Origin::Create(kManifestUrl));
const base::Time kLastAccessTime = base::Time::Now();
const base::Time kCreationTime =
kLastAccessTime - base::TimeDelta::FromDays(7);
@@ -369,16 +369,16 @@ TEST(AppCacheDatabaseTest, GroupRecords) {
record.last_access_time.ToInternalValue());
record.group_id = 2;
- record.manifest_url = kOrigin;
+ record.manifest_url = kOrigin.GetURL();
record.origin = kOrigin;
record.last_access_time = kLastAccessTime;
record.creation_time = kCreationTime;
EXPECT_TRUE(db.InsertGroup(&record));
record = kZeroRecord;
- EXPECT_TRUE(db.FindGroupForManifestUrl(kOrigin, &record));
+ EXPECT_TRUE(db.FindGroupForManifestUrl(kOrigin.GetURL(), &record));
EXPECT_EQ(2, record.group_id);
- EXPECT_EQ(kOrigin, record.manifest_url);
+ EXPECT_EQ(kOrigin.GetURL(), record.manifest_url);
EXPECT_EQ(kOrigin, record.origin);
EXPECT_EQ(kCreationTime.ToInternalValue(),
record.creation_time.ToInternalValue());
@@ -391,7 +391,7 @@ TEST(AppCacheDatabaseTest, GroupRecords) {
EXPECT_EQ(kManifestUrl, records[0].manifest_url);
EXPECT_EQ(kOrigin, records[0].origin);
EXPECT_EQ(2, records[1].group_id);
- EXPECT_EQ(kOrigin, records[1].manifest_url);
+ EXPECT_EQ(kOrigin.GetURL(), records[1].manifest_url);
EXPECT_EQ(kOrigin, records[1].origin);
EXPECT_TRUE(db.DeleteGroup(1));
@@ -400,20 +400,20 @@ TEST(AppCacheDatabaseTest, GroupRecords) {
EXPECT_TRUE(db.FindGroupsForOrigin(kOrigin, &records));
EXPECT_EQ(1U, records.size());
EXPECT_EQ(2, records[0].group_id);
- EXPECT_EQ(kOrigin, records[0].manifest_url);
+ EXPECT_EQ(kOrigin.GetURL(), records[0].manifest_url);
EXPECT_EQ(kOrigin, records[0].origin);
EXPECT_EQ(kCreationTime.ToInternalValue(),
record.creation_time.ToInternalValue());
EXPECT_EQ(kLastAccessTime.ToInternalValue(),
record.last_access_time.ToInternalValue());
- std::set<GURL> origins;
+ std::set<url::Origin> origins;
EXPECT_TRUE(db.FindOriginsWithGroups(&origins));
EXPECT_EQ(1U, origins.size());
EXPECT_EQ(kOrigin, *(origins.begin()));
const GURL kManifest2("http://blah2/manifest");
- const GURL kOrigin2(kManifest2.GetOrigin());
+ const url::Origin kOrigin2(url::Origin::Create(kManifest2));
record.group_id = 1;
record.manifest_url = kManifest2;
record.origin = kOrigin2;
@@ -447,7 +447,7 @@ TEST(AppCacheDatabaseTest, GroupAccessAndEvictionTimes) {
EXPECT_TRUE(db.LazyOpen(true));
const GURL kManifestUrl("http://blah/manifest");
- const GURL kOrigin(kManifestUrl.GetOrigin());
+ const url::Origin kOrigin(url::Origin::Create(kManifestUrl));
const base::Time kDayOne =
base::Time() + base::TimeDelta::FromDays(1);
const base::Time kDayTwo = kDayOne + base::TimeDelta::FromDays(1);
@@ -526,11 +526,11 @@ TEST(AppCacheDatabaseTest, NamespaceRecords) {
const GURL kFooNameSpace1("http://foo/namespace1");
const GURL kFooNameSpace2("http://foo/namespace2");
const GURL kFooFallbackEntry("http://foo/entry");
- const GURL kFooOrigin(kFooNameSpace1.GetOrigin());
+ const url::Origin kFooOrigin(url::Origin::Create(kFooNameSpace1));
const GURL kBarNameSpace1("http://bar/namespace1");
const GURL kBarNameSpace2("http://bar/namespace2");
const GURL kBarFallbackEntry("http://bar/entry");
- const GURL kBarOrigin(kBarNameSpace1.GetOrigin());
+ const url::Origin kBarOrigin(url::Origin::Create(kBarNameSpace1));
const AppCacheDatabase::NamespaceRecord kZeroRecord;
AppCacheDatabase::NamespaceRecord record;
@@ -759,9 +759,9 @@ TEST(AppCacheDatabaseTest, DeletableResponseIds) {
TEST(AppCacheDatabaseTest, OriginUsage) {
const GURL kManifestUrl("http://blah/manifest");
const GURL kManifestUrl2("http://blah/manifest2");
- const GURL kOrigin(kManifestUrl.GetOrigin());
+ const url::Origin kOrigin = url::Origin::Create(kManifestUrl);
const GURL kOtherOriginManifestUrl("http://other/manifest");
- const GURL kOtherOrigin(kOtherOriginManifestUrl.GetOrigin());
+ const url::Origin kOtherOrigin = url::Origin::Create(kOtherOriginManifestUrl);
const base::FilePath kEmptyPath;
AppCacheDatabase db(kEmptyPath);
@@ -819,7 +819,7 @@ TEST(AppCacheDatabaseTest, OriginUsage) {
EXPECT_TRUE(db.FindCachesForOrigin(kOtherOrigin, &cache_records));
EXPECT_EQ(1U, cache_records.size());
- std::map<GURL, int64_t> usage_map;
+ std::map<url::Origin, int64_t> usage_map;
EXPECT_TRUE(db.GetAllOriginUsage(&usage_map));
EXPECT_EQ(2U, usage_map.size());
EXPECT_EQ(1100, usage_map[kOrigin]);
@@ -1043,8 +1043,8 @@ TEST(AppCacheDatabaseTest, UpgradeSchema4to7) {
std::vector<AppCacheDatabase::NamespaceRecord> intercepts;
std::vector<AppCacheDatabase::NamespaceRecord> fallbacks;
- EXPECT_TRUE(db.FindNamespacesForOrigin(kMockOrigin, &intercepts,
- &fallbacks));
+ EXPECT_TRUE(db.FindNamespacesForOrigin(url::Origin::Create(kMockOrigin),
+ &intercepts, &fallbacks));
EXPECT_TRUE(intercepts.empty());
EXPECT_EQ(kNumNamespaces, static_cast<int>(fallbacks.size()));
@@ -1062,7 +1062,7 @@ TEST(AppCacheDatabaseTest, UpgradeSchema4to7) {
EXPECT_EQ(i, fallbacks[i].cache_id);
EXPECT_EQ(APPCACHE_FALLBACK_NAMESPACE, fallbacks[i].namespace_.type);
- EXPECT_EQ(kMockOrigin, fallbacks[i].origin);
+ EXPECT_EQ(url::Origin::Create(kMockOrigin), fallbacks[i].origin);
EXPECT_EQ(expected_namespace_url, fallbacks[i].namespace_.namespace_url);
EXPECT_EQ(expected_target_url, fallbacks[i].namespace_.target_url);
EXPECT_FALSE(fallbacks[i].namespace_.is_pattern);
diff --git a/chromium/content/browser/appcache/appcache_disk_cache.cc b/chromium/content/browser/appcache/appcache_disk_cache.cc
index 1efce0f1438..d718034f704 100644
--- a/chromium/content/browser/appcache/appcache_disk_cache.cc
+++ b/chromium/content/browser/appcache/appcache_disk_cache.cc
@@ -245,9 +245,8 @@ void AppCacheDiskCache::Disable() {
// We need to close open file handles in order to reinitalize the
// appcache system on the fly. File handles held in both entries and in
// the main disk_cache::Backend class need to be released.
- for (OpenEntries::const_iterator iter = open_entries_.begin();
- iter != open_entries_.end(); ++iter) {
- (*iter)->Abandon();
+ for (EntryImpl* entry : open_entries_) {
+ entry->Abandon();
}
open_entries_.clear();
disk_cache_.reset();
@@ -370,25 +369,24 @@ void AppCacheDiskCache::OnCreateBackendComplete(int rv) {
}
// Service pending calls that were queued up while we were initializing.
- for (PendingCalls::const_iterator iter = pending_calls_.begin();
- iter < pending_calls_.end(); ++iter) {
+ for (const auto& call : pending_calls_) {
rv = net::ERR_FAILED;
- switch (iter->call_type) {
+ switch (call.call_type) {
case CREATE:
- rv = CreateEntry(iter->key, iter->entry, iter->callback);
+ rv = CreateEntry(call.key, call.entry, call.callback);
break;
case OPEN:
- rv = OpenEntry(iter->key, iter->entry, iter->callback);
+ rv = OpenEntry(call.key, call.entry, call.callback);
break;
case DOOM:
- rv = DoomEntry(iter->key, iter->callback);
+ rv = DoomEntry(call.key, call.callback);
break;
default:
NOTREACHED();
break;
}
if (rv != net::ERR_IO_PENDING)
- iter->callback.Run(rv);
+ call.callback.Run(rv);
}
pending_calls_.clear();
}
diff --git a/chromium/content/browser/appcache/appcache_disk_cache.h b/chromium/content/browser/appcache/appcache_disk_cache.h
index 876e8ec9db5..5eba6053397 100644
--- a/chromium/content/browser/appcache/appcache_disk_cache.h
+++ b/chromium/content/browser/appcache/appcache_disk_cache.h
@@ -89,11 +89,11 @@ class CONTENT_EXPORT AppCacheDiskCache
~PendingCall();
};
- typedef std::vector<PendingCall> PendingCalls;
+ using PendingCalls = std::vector<PendingCall>;
class ActiveCall;
- typedef std::set<ActiveCall*> ActiveCalls;
- typedef std::set<EntryImpl*> OpenEntries;
+ using ActiveCalls = std::set<ActiveCall*>;
+ using OpenEntries = std::set<EntryImpl*>;
bool is_initializing_or_waiting_to_initialize() const {
return create_backend_callback_.get() != NULL || is_waiting_to_initialize_;
diff --git a/chromium/content/browser/appcache/appcache_disk_cache_unittest.cc b/chromium/content/browser/appcache/appcache_disk_cache_unittest.cc
index 61857e2eb9c..e6e94b70099 100644
--- a/chromium/content/browser/appcache/appcache_disk_cache_unittest.cc
+++ b/chromium/content/browser/appcache/appcache_disk_cache_unittest.cc
@@ -71,9 +71,8 @@ TEST_F(AppCacheDiskCacheTest, DisablePriorToInitCompletion) {
EXPECT_EQ(nullptr, entry);
EXPECT_EQ(4u, completion_results_.size());
- for (std::vector<int>::const_iterator iter = completion_results_.begin();
- iter < completion_results_.end(); ++iter) {
- EXPECT_EQ(net::ERR_ABORTED, *iter);
+ for (const auto& result : completion_results_) {
+ EXPECT_EQ(net::ERR_ABORTED, result);
}
// Ensure the directory can be deleted at this point.
diff --git a/chromium/content/browser/appcache/appcache_group.cc b/chromium/content/browser/appcache/appcache_group.cc
index 06cca4ca884..85e6be0e7e7 100644
--- a/chromium/content/browser/appcache/appcache_group.cc
+++ b/chromium/content/browser/appcache/appcache_group.cc
@@ -98,13 +98,13 @@ void AppCacheGroup::AddCache(AppCache* complete_cache) {
newest_complete_cache_ = complete_cache;
// Update hosts of older caches to add a reference to the newest cache.
- for (Caches::iterator it = old_caches_.begin();
- it != old_caches_.end(); ++it) {
- AppCache::AppCacheHosts& hosts = (*it)->associated_hosts();
- for (AppCache::AppCacheHosts::iterator host_it = hosts.begin();
- host_it != hosts.end(); ++host_it) {
- (*host_it)->SetSwappableCache(this);
- }
+ // (This loop mutates |old_caches_| so a range-based for-loop cannot be
+ // used, because it caches the end iterator.)
+ for (Caches::iterator it = old_caches_.begin(); it != old_caches_.end();
+ ++it) {
+ AppCache* cache = *it;
+ for (AppCacheHost* host : cache->associated_hosts())
+ host->SetSwappableCache(this);
}
} else {
old_caches_.push_back(complete_cache);
@@ -211,9 +211,8 @@ void AppCacheGroup::RunQueuedUpdates() {
queued_updates_.swap(updates_to_run);
DCHECK(queued_updates_.empty());
- for (QueuedUpdates::iterator it = updates_to_run.begin();
- it != updates_to_run.end(); ++it) {
- AppCacheHost* host = it->second.first;
+ for (auto& pair : updates_to_run) {
+ AppCacheHost* host = pair.second.first;
host->RemoveObserver(host_observer_.get());
if (FindObserver(host, queued_observers_)) {
queued_observers_.RemoveObserver(host);
@@ -221,7 +220,7 @@ void AppCacheGroup::RunQueuedUpdates() {
}
if (!is_obsolete() && !is_being_deleted())
- StartUpdateWithNewMasterEntry(host, it->second.second);
+ StartUpdateWithNewMasterEntry(host, pair.second.second);
}
}
diff --git a/chromium/content/browser/appcache/appcache_group.h b/chromium/content/browser/appcache/appcache_group.h
index beb00e3f2a8..c119f59274d 100644
--- a/chromium/content/browser/appcache/appcache_group.h
+++ b/chromium/content/browser/appcache/appcache_group.h
@@ -127,9 +127,9 @@ class CONTENT_EXPORT AppCacheGroup
~AppCacheGroup();
- typedef std::vector<AppCache*> Caches;
- typedef std::map<UpdateObserver*, std::pair<AppCacheHost*, GURL>>
- QueuedUpdates;
+ using Caches = std::vector<AppCache*>;
+ using QueuedUpdates =
+ std::map<UpdateObserver*, std::pair<AppCacheHost*, GURL>>;
static const int kUpdateRestartDelayMs = 1000;
diff --git a/chromium/content/browser/appcache/appcache_histograms.cc b/chromium/content/browser/appcache/appcache_histograms.cc
index 67d94b82f86..6027c8c650a 100644
--- a/chromium/content/browser/appcache/appcache_histograms.cc
+++ b/chromium/content/browser/appcache/appcache_histograms.cc
@@ -5,13 +5,13 @@
#include "content/browser/appcache/appcache_histograms.h"
#include "base/metrics/histogram_macros.h"
-#include "base/metrics/histogram_macros.h"
#include "content/public/common/origin_util.h"
+#include "url/origin.h"
namespace content {
-static std::string OriginToCustomHistogramSuffix(const GURL& origin_url) {
- if (origin_url.host_piece() == "docs.google.com")
+static std::string OriginToCustomHistogramSuffix(const url::Origin& origin) {
+ if (origin.host() == "docs.google.com")
return ".Docs";
return std::string();
}
@@ -32,12 +32,12 @@ void AppCacheHistograms::CountCorruptionDetected() {
void AppCacheHistograms::CountUpdateJobResult(
AppCacheUpdateJob::ResultType result,
- const GURL& origin_url) {
+ const url::Origin& origin) {
UMA_HISTOGRAM_ENUMERATION(
"appcache.UpdateJobResult",
result, AppCacheUpdateJob::NUM_UPDATE_JOB_RESULT_TYPES);
- const std::string suffix = OriginToCustomHistogramSuffix(origin_url);
+ const std::string suffix = OriginToCustomHistogramSuffix(origin);
if (!suffix.empty()) {
base::LinearHistogram::FactoryGet(
"appcache.UpdateJobResult" + suffix,
@@ -55,20 +55,22 @@ void AppCacheHistograms::CountCheckResponseResult(
result, NUM_CHECK_RESPONSE_RESULT_TYPES);
}
-void AppCacheHistograms::CountResponseRetrieval(
- bool success, bool is_main_resource, const GURL& origin_url) {
+void AppCacheHistograms::CountResponseRetrieval(bool success,
+ bool is_main_resource,
+ const url::Origin& origin) {
std::string label;
if (is_main_resource) {
label = "appcache.MainResourceResponseRetrieval";
UMA_HISTOGRAM_BOOLEAN(label, success);
// Also count HTTP vs HTTPS appcache usage.
- UMA_HISTOGRAM_BOOLEAN("appcache.MainPageLoad", IsOriginSecure(origin_url));
+ UMA_HISTOGRAM_BOOLEAN("appcache.MainPageLoad",
+ IsOriginSecure(origin.GetURL()));
} else {
label = "appcache.SubResourceResponseRetrieval";
UMA_HISTOGRAM_BOOLEAN(label, success);
}
- const std::string suffix = OriginToCustomHistogramSuffix(origin_url);
+ const std::string suffix = OriginToCustomHistogramSuffix(origin);
if (!suffix.empty()) {
base::BooleanHistogram::FactoryGet(
label + suffix,
@@ -77,11 +79,11 @@ void AppCacheHistograms::CountResponseRetrieval(
}
void AppCacheHistograms::LogUpdateFailureStats(
- const GURL& origin_url,
- int percent_complete,
- bool was_stalled,
- bool was_off_origin_resource_failure) {
- const std::string suffix = OriginToCustomHistogramSuffix(origin_url);
+ const url::Origin& origin,
+ int percent_complete,
+ bool was_stalled,
+ bool was_off_origin_resource_failure) {
+ const std::string suffix = OriginToCustomHistogramSuffix(origin);
std::string label = "appcache.UpdateProgressAtPointOfFaliure";
UMA_HISTOGRAM_PERCENTAGE(label, percent_complete);
diff --git a/chromium/content/browser/appcache/appcache_histograms.h b/chromium/content/browser/appcache/appcache_histograms.h
index 57ba1f85d02..043d6d9a4fc 100644
--- a/chromium/content/browser/appcache/appcache_histograms.h
+++ b/chromium/content/browser/appcache/appcache_histograms.h
@@ -12,6 +12,10 @@ namespace base {
class TimeDelta;
}
+namespace url {
+class Origin;
+}
+
namespace content {
class AppCacheHistograms {
@@ -24,20 +28,20 @@ class AppCacheHistograms {
static void CountReinitAttempt(bool repeated_attempt);
static void CountCorruptionDetected();
static void CountUpdateJobResult(AppCacheUpdateJob::ResultType result,
- const GURL& origin_url);
+ const url::Origin& origin_url);
enum CheckResponseResultType {
RESPONSE_OK, MANIFEST_OUT_OF_DATE, RESPONSE_OUT_OF_DATE, ENTRY_NOT_FOUND,
READ_HEADERS_ERROR, READ_DATA_ERROR, UNEXPECTED_DATA_SIZE, CHECK_CANCELED,
NUM_CHECK_RESPONSE_RESULT_TYPES
};
static void CountCheckResponseResult(CheckResponseResultType result);
- static void CountResponseRetrieval(
- bool success, bool is_main_resource, const GURL& origin_url);
- static void LogUpdateFailureStats(
- const GURL& origin_url,
- int percent_complete,
- bool was_making_progress,
- bool off_origin_resource_failure);
+ static void CountResponseRetrieval(bool success,
+ bool is_main_resource,
+ const url::Origin& origin_url);
+ static void LogUpdateFailureStats(const url::Origin& origin_url,
+ int percent_complete,
+ bool was_making_progress,
+ bool off_origin_resource_failure);
static void AddTaskQueueTimeSample(const base::TimeDelta& duration);
static void AddTaskRunTimeSample(const base::TimeDelta& duration);
static void AddCompletionQueueTimeSample(const base::TimeDelta& duration);
diff --git a/chromium/content/browser/appcache/appcache_host.cc b/chromium/content/browser/appcache/appcache_host.cc
index f5543c78b69..eb88a3b00d8 100644
--- a/chromium/content/browser/appcache/appcache_host.cc
+++ b/chromium/content/browser/appcache/appcache_host.cc
@@ -19,7 +19,6 @@
#include "services/network/public/cpp/features.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
#include "storage/browser/quota/quota_manager_proxy.h"
-#include "url/origin.h"
namespace content {
@@ -80,9 +79,8 @@ AppCacheHost::~AppCacheHost() {
if (group_being_updated_.get())
group_being_updated_->RemoveUpdateObserver(this);
storage()->CancelDelegateCallbacks(this);
- if (service()->quota_manager_proxy() && !origin_in_use_.is_empty())
- service()->quota_manager_proxy()->NotifyOriginNoLongerInUse(
- url::Origin::Create(origin_in_use_));
+ if (service()->quota_manager_proxy() && !origin_in_use_.unique())
+ service()->quota_manager_proxy()->NotifyOriginNoLongerInUse(origin_in_use_);
}
void AppCacheHost::AddObserver(Observer* observer) {
@@ -110,10 +108,9 @@ bool AppCacheHost::SelectCache(const GURL& document_url,
return true;
}
- origin_in_use_ = document_url.GetOrigin();
- if (service()->quota_manager_proxy() && !origin_in_use_.is_empty())
- service()->quota_manager_proxy()->NotifyOriginInUse(
- url::Origin::Create(origin_in_use_));
+ origin_in_use_ = url::Origin::Create(document_url);
+ if (service()->quota_manager_proxy() && !origin_in_use_.unique())
+ service()->quota_manager_proxy()->NotifyOriginInUse(origin_in_use_);
if (main_resource_blocked_)
frontend_->OnContentBlocked(host_id_,
diff --git a/chromium/content/browser/appcache/appcache_host.h b/chromium/content/browser/appcache/appcache_host.h
index 4941f548e31..7da6f38ede7 100644
--- a/chromium/content/browser/appcache/appcache_host.h
+++ b/chromium/content/browser/appcache/appcache_host.h
@@ -22,6 +22,7 @@
#include "content/common/content_export.h"
#include "content/public/common/resource_type.h"
#include "url/gurl.h"
+#include "url/origin.h"
namespace net {
class URLRequest;
@@ -56,9 +57,9 @@ namespace appcache_update_job_unittest {
class AppCacheUpdateJobTest;
}
-typedef base::OnceCallback<void(AppCacheStatus)> GetStatusCallback;
-typedef base::OnceCallback<void(bool)> StartUpdateCallback;
-typedef base::OnceCallback<void(bool)> SwapCacheCallback;
+using GetStatusCallback = base::OnceCallback<void(AppCacheStatus)>;
+using StartUpdateCallback = base::OnceCallback<void(bool)>;
+using SwapCacheCallback = base::OnceCallback<void(bool)>;
// Server-side representation of an application cache host.
class CONTENT_EXPORT AppCacheHost
@@ -346,7 +347,7 @@ class CONTENT_EXPORT AppCacheHost
base::ObserverList<Observer> observers_;
// Used to inform the QuotaManager of what origins are currently in use.
- GURL origin_in_use_;
+ url::Origin origin_in_use_;
// First party url to be used in policy checks.
GURL first_party_url_;
diff --git a/chromium/content/browser/appcache/appcache_internals_ui.cc b/chromium/content/browser/appcache/appcache_internals_ui.cc
index b5f06abaeb8..3a34269fbc0 100644
--- a/chromium/content/browser/appcache/appcache_internals_ui.cc
+++ b/chromium/content/browser/appcache/appcache_internals_ui.cc
@@ -99,7 +99,8 @@ std::unique_ptr<base::ListValue> GetListValueFromAppCacheInfoCollection(
std::unique_ptr<base::ListValue> list(new base::ListValue());
for (const auto& key_value : appcache_collection->infos_by_origin) {
base::DictionaryValue* dict = new base::DictionaryValue;
- dict->SetString("originURL", key_value.first.spec());
+ // Use GURL::spec() to keep consistency with previous version
+ dict->SetString("originURL", key_value.first.GetURL().spec());
dict->Set("manifests", GetListValueForAppCacheInfoVector(key_value.second));
list->Append(std::unique_ptr<base::Value>(dict));
}
@@ -297,7 +298,7 @@ void AppCacheInternalsUI::Proxy::OnResponseInfoLoaded(
reader->ReadData(response_data.get(), amount_to_read,
base::BindOnce(&Proxy::OnResponseDataReadComplete, this,
response_enquiry, response_info,
- base::Passed(&reader), response_data));
+ std::move(reader), response_data));
} else {
OnResponseDataReadComplete(response_enquiry, nullptr, nullptr, nullptr, -1);
}
@@ -332,19 +333,20 @@ AppCacheInternalsUI::AppCacheInternalsUI(WebUI* web_ui)
: WebUIController(web_ui), weak_ptr_factory_(this) {
web_ui->RegisterMessageCallback(
kRequestGetAllAppCacheInfo,
- base::Bind(&AppCacheInternalsUI::GetAllAppCache, AsWeakPtr()));
+ base::BindRepeating(&AppCacheInternalsUI::GetAllAppCache, AsWeakPtr()));
web_ui->RegisterMessageCallback(
kRequestDeleteAppCache,
- base::Bind(&AppCacheInternalsUI::DeleteAppCache, AsWeakPtr()));
+ base::BindRepeating(&AppCacheInternalsUI::DeleteAppCache, AsWeakPtr()));
web_ui->RegisterMessageCallback(
kRequestGetAppCacheDetails,
- base::Bind(&AppCacheInternalsUI::GetAppCacheDetails, AsWeakPtr()));
+ base::BindRepeating(&AppCacheInternalsUI::GetAppCacheDetails,
+ AsWeakPtr()));
web_ui->RegisterMessageCallback(
kRequestGetFileDetails,
- base::Bind(&AppCacheInternalsUI::GetFileDetails, AsWeakPtr()));
+ base::BindRepeating(&AppCacheInternalsUI::GetFileDetails, AsWeakPtr()));
WebUIDataSource* source =
WebUIDataSource::Create(kChromeUIAppCacheInternalsHost);
diff --git a/chromium/content/browser/appcache/appcache_quota_client.cc b/chromium/content/browser/appcache/appcache_quota_client.cc
index 5c05e97095d..378bb0efe92 100644
--- a/chromium/content/browser/appcache/appcache_quota_client.cc
+++ b/chromium/content/browser/appcache/appcache_quota_client.cc
@@ -11,7 +11,7 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "content/browser/appcache/appcache_service_impl.h"
-#include "third_party/WebKit/public/mojom/quota/quota_types.mojom.h"
+#include "third_party/blink/public/mojom/quota/quota_types.mojom.h"
using blink::mojom::StorageType;
using storage::QuotaClient;
@@ -87,7 +87,7 @@ void AppCacheQuotaClient::GetOriginUsage(const url::Origin& origin,
}
const AppCacheStorage::UsageMap* map = GetUsageMap();
- AppCacheStorage::UsageMap::const_iterator found = map->find(origin.GetURL());
+ auto found = map->find(origin);
if (found == map->end()) {
std::move(callback).Run(0);
return;
@@ -134,7 +134,7 @@ void AppCacheQuotaClient::DeleteOriginData(const url::Origin& origin,
return;
}
- service_->DeleteAppCachesForOrigin(origin.GetURL(),
+ service_->DeleteAppCachesForOrigin(origin,
GetServiceDeleteCallback()->callback());
}
@@ -180,12 +180,10 @@ void AppCacheQuotaClient::GetOriginsHelper(StorageType type,
return;
}
- const AppCacheStorage::UsageMap* map = GetUsageMap();
std::set<url::Origin> origins;
- for (AppCacheStorage::UsageMap::const_iterator iter = map->begin();
- iter != map->end(); ++iter) {
- if (opt_host.empty() || iter->first.host_piece() == opt_host)
- origins.insert(url::Origin::Create(iter->first));
+ for (const auto& pair : *GetUsageMap()) {
+ if (opt_host.empty() || pair.first.host() == opt_host)
+ origins.insert(pair.first);
}
std::move(callback).Run(origins);
}
diff --git a/chromium/content/browser/appcache/appcache_quota_client.h b/chromium/content/browser/appcache/appcache_quota_client.h
index 095c142f05a..d40424dcea3 100644
--- a/chromium/content/browser/appcache/appcache_quota_client.h
+++ b/chromium/content/browser/appcache/appcache_quota_client.h
@@ -17,7 +17,7 @@
#include "net/base/completion_callback.h"
#include "storage/browser/quota/quota_client.h"
#include "storage/browser/quota/quota_task.h"
-#include "third_party/WebKit/public/mojom/quota/quota_types.mojom.h"
+#include "third_party/blink/public/mojom/quota/quota_types.mojom.h"
#include "url/origin.h"
namespace content {
diff --git a/chromium/content/browser/appcache/appcache_quota_client_unittest.cc b/chromium/content/browser/appcache/appcache_quota_client_unittest.cc
index 9168b161c31..7c1f72dd454 100644
--- a/chromium/content/browser/appcache/appcache_quota_client_unittest.cc
+++ b/chromium/content/browser/appcache/appcache_quota_client_unittest.cc
@@ -110,7 +110,7 @@ class AppCacheQuotaClientTest : public testing::Test {
}
void SetUsageMapEntry(const url::Origin& origin, int64_t usage) {
- mock_service_.storage()->usage_map_[origin.GetURL()] = usage;
+ mock_service_.storage()->usage_map_[origin] = usage;
}
AppCacheQuotaClient* CreateClient() {
diff --git a/chromium/content/browser/appcache/appcache_request_handler.cc b/chromium/content/browser/appcache/appcache_request_handler.cc
index 63cc984b427..f7d16136ca7 100644
--- a/chromium/content/browser/appcache/appcache_request_handler.cc
+++ b/chromium/content/browser/appcache/appcache_request_handler.cc
@@ -382,8 +382,8 @@ std::unique_ptr<AppCacheJob> AppCacheRequestHandler::MaybeLoadMainResource(
}
if (storage()->IsInitialized() &&
- service_->storage()->usage_map()->find(request_->GetURL().GetOrigin()) ==
- service_->storage()->usage_map()->end()) {
+ !base::ContainsKey(*service_->storage()->usage_map(),
+ url::Origin::Create(request_->GetURL()))) {
return nullptr;
}
@@ -602,9 +602,9 @@ bool AppCacheRequestHandler::MaybeCreateLoaderForResponse(
network::mojom::URLLoaderClientRequest* client_request,
ThrottlingURLLoader* url_loader) {
// The sync interface of this method is inherited from the
- // URLLoaderRequestHandler class. The LoaderCallback created here is invoked
- // synchronously in fallback cases, and only when there really is a loader
- // to start.
+ // NavigationLoaderInterceptor class. The LoaderCallback created here is
+ // invoked synchronously in fallback cases, and only when there really is
+ // a loader to start.
bool was_called = false;
loader_callback_ = base::BindOnce(
[](network::mojom::URLLoaderPtr* loader,
@@ -639,7 +639,7 @@ AppCacheRequestHandler::MaybeCreateSubresourceLoaderParams() {
SubresourceLoaderParams params;
params.loader_factory_info = factory_ptr.PassInterface();
- return params;
+ return base::Optional<SubresourceLoaderParams>(std::move(params));
}
void AppCacheRequestHandler::MaybeCreateSubresourceLoader(
diff --git a/chromium/content/browser/appcache/appcache_request_handler.h b/chromium/content/browser/appcache/appcache_request_handler.h
index 96ecfa503c9..9f79c30586b 100644
--- a/chromium/content/browser/appcache/appcache_request_handler.h
+++ b/chromium/content/browser/appcache/appcache_request_handler.h
@@ -17,7 +17,7 @@
#include "content/browser/appcache/appcache_host.h"
#include "content/browser/appcache/appcache_request_handler.h"
#include "content/browser/appcache/appcache_service_impl.h"
-#include "content/browser/loader/url_loader_request_handler.h"
+#include "content/browser/loader/navigation_loader_interceptor.h"
#include "content/browser/url_loader_factory_getter.h"
#include "content/common/content_export.h"
#include "content/public/common/resource_type.h"
@@ -50,7 +50,7 @@ class CONTENT_EXPORT AppCacheRequestHandler
public AppCacheHost::Observer,
public AppCacheServiceImpl::Observer,
public AppCacheStorage::Delegate,
- public URLLoaderRequestHandler {
+ public NavigationLoaderInterceptor {
public:
~AppCacheRequestHandler() override;
@@ -80,7 +80,7 @@ class CONTENT_EXPORT AppCacheRequestHandler
// NetworkService loading
- // URLLoaderRequestHandler overrides - main resource loading.
+ // NavigationLoaderInterceptor overrides - main resource loading.
// These methods are used by the NavigationURLLoaderNetworkService.
// Internally they use same methods used by the network library based impl,
// MaybeLoadResource and MaybeLoadFallbackForResponse.
diff --git a/chromium/content/browser/appcache/appcache_request_handler_unittest.cc b/chromium/content/browser/appcache/appcache_request_handler_unittest.cc
index d2bf16206c7..f2391591aaa 100644
--- a/chromium/content/browser/appcache/appcache_request_handler_unittest.cc
+++ b/chromium/content/browser/appcache/appcache_request_handler_unittest.cc
@@ -16,7 +16,6 @@
#include "base/containers/stack.h"
#include "base/location.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/single_thread_task_runner.h"
diff --git a/chromium/content/browser/appcache/appcache_response.h b/chromium/content/browser/appcache/appcache_response.h
index ec28aca2b2a..fb85715d141 100644
--- a/chromium/content/browser/appcache/appcache_response.h
+++ b/chromium/content/browser/appcache/appcache_response.h
@@ -28,7 +28,7 @@ class MockAppCacheStorage;
static const int kUnkownResponseDataSize = -1;
-typedef base::OnceCallback<void(int)> OnceCompletionCallback;
+using OnceCompletionCallback = base::OnceCallback<void(int)>;
// Response info for a particular response id. Instances are tracked in
// the working set.
diff --git a/chromium/content/browser/appcache/appcache_service_impl.cc b/chromium/content/browser/appcache/appcache_service_impl.cc
index 163feb5eb6c..763140468ee 100644
--- a/chromium/content/browser/appcache/appcache_service_impl.cc
+++ b/chromium/content/browser/appcache/appcache_service_impl.cc
@@ -135,12 +135,14 @@ void AppCacheServiceImpl::DeleteHelper::OnGroupMadeObsolete(
class AppCacheServiceImpl::DeleteOriginHelper : public AsyncHelper {
public:
- DeleteOriginHelper(
- AppCacheServiceImpl* service, const GURL& origin,
- const net::CompletionCallback& callback)
- : AsyncHelper(service, callback), origin_(origin),
- num_caches_to_delete_(0), successes_(0), failures_(0) {
- }
+ DeleteOriginHelper(AppCacheServiceImpl* service,
+ const url::Origin& origin,
+ const net::CompletionCallback& callback)
+ : AsyncHelper(service, callback),
+ origin_(origin),
+ num_caches_to_delete_(0),
+ successes_(0),
+ failures_(0) {}
void Start() override {
// We start by listing all caches, continues in OnAllInfo().
@@ -157,7 +159,7 @@ class AppCacheServiceImpl::DeleteOriginHelper : public AsyncHelper {
void CacheCompleted(bool success);
- GURL origin_;
+ url::Origin origin_;
int num_caches_to_delete_;
int successes_;
int failures_;
@@ -174,8 +176,7 @@ void AppCacheServiceImpl::DeleteOriginHelper::OnAllInfo(
return;
}
- std::map<GURL, AppCacheInfoVector>::iterator found =
- collection->infos_by_origin.find(origin_);
+ auto found = collection->infos_by_origin.find(origin_);
if (found == collection->infos_by_origin.end() || found->second.empty()) {
// No caches for this origin.
CallCallback(net::OK);
@@ -188,9 +189,8 @@ void AppCacheServiceImpl::DeleteOriginHelper::OnAllInfo(
successes_ = 0;
failures_ = 0;
num_caches_to_delete_ = static_cast<int>(caches_to_delete.size());
- for (AppCacheInfoVector::const_iterator iter = caches_to_delete.begin();
- iter != caches_to_delete.end(); ++iter) {
- service_->storage()->LoadOrCreateGroup(iter->manifest_url, this);
+ for (const auto& cache : caches_to_delete) {
+ service_->storage()->LoadOrCreateGroup(cache.manifest_url, this);
}
}
@@ -490,7 +490,8 @@ void AppCacheServiceImpl::DeleteAppCacheGroup(
}
void AppCacheServiceImpl::DeleteAppCachesForOrigin(
- const GURL& origin, const net::CompletionCallback& callback) {
+ const url::Origin& origin,
+ const net::CompletionCallback& callback) {
DeleteOriginHelper* helper = new DeleteOriginHelper(this, origin, callback);
helper->Start();
}
diff --git a/chromium/content/browser/appcache/appcache_service_impl.h b/chromium/content/browser/appcache/appcache_service_impl.h
index a4856f4dd7f..a2a41ed9e4f 100644
--- a/chromium/content/browser/appcache/appcache_service_impl.h
+++ b/chromium/content/browser/appcache/appcache_service_impl.h
@@ -110,7 +110,8 @@ class CONTENT_EXPORT AppCacheServiceImpl
// completion. This method always completes asynchronously.
// (virtual for unit testing)
virtual void DeleteAppCachesForOrigin(
- const GURL& origin, const net::CompletionCallback& callback);
+ const url::Origin& origin,
+ const net::CompletionCallback& callback);
// Checks the integrity of 'response_id' by reading the headers and data.
// If it cannot be read, the cache group for 'manifest_url' is deleted.
diff --git a/chromium/content/browser/appcache/appcache_service_unittest.cc b/chromium/content/browser/appcache/appcache_service_unittest.cc
index 38d0dd12ec7..6d0d46cbc5c 100644
--- a/chromium/content/browser/appcache/appcache_service_unittest.cc
+++ b/chromium/content/browser/appcache/appcache_service_unittest.cc
@@ -96,8 +96,9 @@ class MockResponseReader : public AppCacheResponseReader {
class AppCacheServiceImplTest : public testing::Test {
public:
AppCacheServiceImplTest()
- : kOrigin("http://hello/"),
- kManifestUrl(kOrigin.Resolve("manifest")),
+ : kOriginURL("http://hello/"),
+ kOrigin(url::Origin::Create(kOriginURL)),
+ kManifestUrl(kOriginURL.Resolve("manifest")),
service_(new AppCacheServiceImpl(nullptr)),
delete_result_(net::OK),
delete_completion_count_(0),
@@ -182,7 +183,8 @@ class AppCacheServiceImplTest : public testing::Test {
return pickle->size();
}
- const GURL kOrigin;
+ const GURL kOriginURL;
+ const url::Origin kOrigin;
const GURL kManifestUrl;
base::test::ScopedTaskEnvironment scoped_task_environment_;
@@ -216,9 +218,9 @@ TEST_F(AppCacheServiceImplTest, DeleteAppCachesForOrigin) {
AppCacheInfo mock_manifest_1;
AppCacheInfo mock_manifest_2;
AppCacheInfo mock_manifest_3;
- mock_manifest_1.manifest_url = kOrigin.Resolve("manifest1");
- mock_manifest_2.manifest_url = kOrigin.Resolve("manifest2");
- mock_manifest_3.manifest_url = kOrigin.Resolve("manifest3");
+ mock_manifest_1.manifest_url = kOriginURL.Resolve("manifest1");
+ mock_manifest_2.manifest_url = kOriginURL.Resolve("manifest2");
+ mock_manifest_3.manifest_url = kOriginURL.Resolve("manifest3");
AppCacheInfoVector info_vector;
info_vector.push_back(mock_manifest_1);
info_vector.push_back(mock_manifest_2);
diff --git a/chromium/content/browser/appcache/appcache_storage.cc b/chromium/content/browser/appcache/appcache_storage.cc
index 30a61a02c9e..e4394e252df 100644
--- a/chromium/content/browser/appcache/appcache_storage.cc
+++ b/chromium/content/browser/appcache/appcache_storage.cc
@@ -11,7 +11,7 @@
#include "content/browser/appcache/appcache_service_impl.h"
#include "storage/browser/quota/quota_client.h"
#include "storage/browser/quota/quota_manager_proxy.h"
-#include "third_party/WebKit/public/mojom/quota/quota_types.mojom.h"
+#include "third_party/blink/public/mojom/quota/quota_types.mojom.h"
namespace content {
@@ -101,7 +101,7 @@ base::WeakPtr<AppCacheStorage> AppCacheStorage::GetWeakPtr() {
return weak_factory_.GetWeakPtr();
}
-void AppCacheStorage::UpdateUsageMapAndNotify(const GURL& origin,
+void AppCacheStorage::UpdateUsageMapAndNotify(const url::Origin& origin,
int64_t new_usage) {
DCHECK_GE(new_usage, 0);
int64_t old_usage = usage_map_[origin];
@@ -111,28 +111,27 @@ void AppCacheStorage::UpdateUsageMapAndNotify(const GURL& origin,
usage_map_.erase(origin);
if (new_usage != old_usage && service()->quota_manager_proxy()) {
service()->quota_manager_proxy()->NotifyStorageModified(
- storage::QuotaClient::kAppcache, url::Origin::Create(origin),
+ storage::QuotaClient::kAppcache, origin,
blink::mojom::StorageType::kTemporary, new_usage - old_usage);
}
}
void AppCacheStorage::ClearUsageMapAndNotify() {
if (service()->quota_manager_proxy()) {
- for (UsageMap::const_iterator iter = usage_map_.begin();
- iter != usage_map_.end(); ++iter) {
+ for (const auto& pair : usage_map_) {
service()->quota_manager_proxy()->NotifyStorageModified(
- storage::QuotaClient::kAppcache, url::Origin::Create(iter->first),
- blink::mojom::StorageType::kTemporary, -(iter->second));
+ storage::QuotaClient::kAppcache, pair.first,
+ blink::mojom::StorageType::kTemporary, -(pair.second));
}
}
usage_map_.clear();
}
-void AppCacheStorage::NotifyStorageAccessed(const GURL& origin) {
+void AppCacheStorage::NotifyStorageAccessed(const url::Origin& origin) {
if (service()->quota_manager_proxy() &&
usage_map_.find(origin) != usage_map_.end())
service()->quota_manager_proxy()->NotifyStorageAccessed(
- storage::QuotaClient::kAppcache, url::Origin::Create(origin),
+ storage::QuotaClient::kAppcache, origin,
blink::mojom::StorageType::kTemporary);
}
diff --git a/chromium/content/browser/appcache/appcache_storage.h b/chromium/content/browser/appcache/appcache_storage.h
index c73fcb8a20f..2bf62b2c41f 100644
--- a/chromium/content/browser/appcache/appcache_storage.h
+++ b/chromium/content/browser/appcache/appcache_storage.h
@@ -19,6 +19,7 @@
#include "content/browser/appcache/appcache_working_set.h"
#include "content/common/content_export.h"
#include "net/base/completion_callback.h"
+#include "url/origin.h"
class GURL;
@@ -44,7 +45,7 @@ struct HttpResponseInfoIOBuffer;
class CONTENT_EXPORT AppCacheStorage {
public:
- typedef std::map<GURL, int64_t> UsageMap;
+ using UsageMap = std::map<url::Origin, int64_t>;
class CONTENT_EXPORT Delegate {
public:
@@ -224,14 +225,13 @@ class CONTENT_EXPORT AppCacheStorage {
friend class content::appcache_storage_unittest::AppCacheStorageTest;
// Helper to call a collection of delegates.
- #define FOR_EACH_DELEGATE(delegates, func_and_args) \
- do { \
- for (DelegateReferenceVector::iterator it = delegates.begin(); \
- it != delegates.end(); ++it) { \
- if (it->get()->delegate) \
- it->get()->delegate->func_and_args; \
- } \
- } while (0)
+#define FOR_EACH_DELEGATE(delegates, func_and_args) \
+ do { \
+ for (const scoped_refptr<DelegateReference>& ref : delegates) { \
+ if (ref.get()->delegate) \
+ ref.get()->delegate->func_and_args; \
+ } \
+ } while (0)
// Helper used to manage multiple references to a 'delegate' and to
// allow all pending callbacks to that delegate to be easily cancelled.
@@ -253,9 +253,8 @@ class CONTENT_EXPORT AppCacheStorage {
virtual ~DelegateReference();
};
- typedef std::map<Delegate*, DelegateReference*> DelegateReferenceMap;
- typedef std::vector<scoped_refptr<DelegateReference> >
- DelegateReferenceVector;
+ using DelegateReferenceMap = std::map<Delegate*, DelegateReference*>;
+ using DelegateReferenceVector = std::vector<scoped_refptr<DelegateReference>>;
// Helper used to manage an async LoadResponseInfo calls on behalf of
// multiple callers.
@@ -314,9 +313,9 @@ class CONTENT_EXPORT AppCacheStorage {
int64_t NewResponseId() { return ++last_response_id_; }
// Helpers to query and notify the QuotaManager.
- void UpdateUsageMapAndNotify(const GURL& origin, int64_t new_usage);
+ void UpdateUsageMapAndNotify(const url::Origin& origin, int64_t new_usage);
void ClearUsageMapAndNotify();
- void NotifyStorageAccessed(const GURL& origin);
+ void NotifyStorageAccessed(const url::Origin& origin);
// The last storage id used for different object types.
int64_t last_cache_id_;
diff --git a/chromium/content/browser/appcache/appcache_storage_impl.cc b/chromium/content/browser/appcache/appcache_storage_impl.cc
index 407c1a2d5e4..b7003845da0 100644
--- a/chromium/content/browser/appcache/appcache_storage_impl.cc
+++ b/chromium/content/browser/appcache/appcache_storage_impl.cc
@@ -14,11 +14,13 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
+#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
+#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "base/trace_event/trace_event.h"
@@ -30,6 +32,7 @@
#include "content/browser/appcache/appcache_quota_client.h"
#include "content/browser/appcache/appcache_response.h"
#include "content/browser/appcache/appcache_service_impl.h"
+#include "content/public/common/content_switches.h"
#include "net/base/cache_type.h"
#include "net/base/net_errors.h"
#include "sql/connection.h"
@@ -37,15 +40,17 @@
#include "storage/browser/quota/quota_client.h"
#include "storage/browser/quota/quota_manager.h"
#include "storage/browser/quota/quota_manager_proxy.h"
-#include "third_party/WebKit/public/mojom/quota/quota_types.mojom.h"
+#include "third_party/blink/public/mojom/quota/quota_types.mojom.h"
namespace content {
+const int kMB = 1024 * 1024;
+
// Hard coded default when not using quota management.
-static const int kDefaultQuota = 5 * 1024 * 1024;
+static const int kDefaultQuota = 5 * kMB;
-static const int kMaxAppCacheDiskCacheSize = 250 * 1024 * 1024;
-static const int kMaxAppCacheMemDiskCacheSize = 10 * 1024 * 1024;
+static const int kMaxAppCacheDiskCacheSize = 250 * kMB;
+static const int kMaxAppCacheMemDiskCacheSize = 10 * kMB;
static const base::FilePath::CharType kDiskCacheDirectoryName[] =
FILE_PATH_LITERAL("Cache");
@@ -97,7 +102,7 @@ void AppCacheStorageImpl::ClearSessionOnlyOrigins(
if (!has_session_only_appcaches)
return;
- std::set<GURL> origins;
+ std::set<url::Origin> origins;
database->FindOriginsWithGroups(&origins);
if (origins.empty())
return; // nothing to delete
@@ -108,26 +113,22 @@ void AppCacheStorageImpl::ClearSessionOnlyOrigins(
return;
}
- std::set<GURL>::const_iterator origin;
- DCHECK(special_storage_policy.get());
- for (origin = origins.begin(); origin != origins.end(); ++origin) {
- if (!special_storage_policy->IsStorageSessionOnly(*origin))
+ for (const url::Origin& origin : origins) {
+ if (!special_storage_policy->IsStorageSessionOnly(origin.GetURL()))
continue;
- if (special_storage_policy->IsStorageProtected(*origin))
+ if (special_storage_policy->IsStorageProtected(origin.GetURL()))
continue;
std::vector<AppCacheDatabase::GroupRecord> groups;
- database->FindGroupsForOrigin(*origin, &groups);
- std::vector<AppCacheDatabase::GroupRecord>::const_iterator group;
- for (group = groups.begin(); group != groups.end(); ++group) {
+ database->FindGroupsForOrigin(origin, &groups);
+ for (const auto& group : groups) {
sql::Transaction transaction(connection);
if (!transaction.Begin()) {
NOTREACHED() << "Failed to start transaction";
return;
}
std::vector<int64_t> deletable_response_ids;
- bool success = DeleteGroupAndRelatedRecords(database,
- group->group_id,
+ bool success = DeleteGroupAndRelatedRecords(database, group.group_id,
&deletable_response_ids);
success = success && transaction.Commit();
DCHECK(success);
@@ -286,7 +287,7 @@ class AppCacheStorageImpl::InitTask : public DatabaseTask {
int64_t last_cache_id_;
int64_t last_response_id_;
int64_t last_deletable_response_rowid_;
- std::map<GURL, int64_t> usage_map_;
+ std::map<url::Origin, int64_t> usage_map_;
};
void AppCacheStorageImpl::InitTask::Run() {
@@ -363,27 +364,23 @@ class AppCacheStorageImpl::GetAllInfoTask : public DatabaseTask {
};
void AppCacheStorageImpl::GetAllInfoTask::Run() {
- std::set<GURL> origins;
+ std::set<url::Origin> origins;
database_->FindOriginsWithGroups(&origins);
- for (std::set<GURL>::const_iterator origin = origins.begin();
- origin != origins.end(); ++origin) {
- AppCacheInfoVector& infos =
- info_collection_->infos_by_origin[*origin];
+ for (const url::Origin& origin : origins) {
+ AppCacheInfoVector& infos = info_collection_->infos_by_origin[origin];
std::vector<AppCacheDatabase::GroupRecord> groups;
- database_->FindGroupsForOrigin(*origin, &groups);
- for (std::vector<AppCacheDatabase::GroupRecord>::const_iterator
- group = groups.begin();
- group != groups.end(); ++group) {
+ database_->FindGroupsForOrigin(origin, &groups);
+ for (const auto& group : groups) {
AppCacheDatabase::CacheRecord cache_record;
- database_->FindCacheForGroup(group->group_id, &cache_record);
+ database_->FindCacheForGroup(group.group_id, &cache_record);
AppCacheInfo info;
- info.manifest_url = group->manifest_url;
- info.creation_time = group->creation_time;
+ info.manifest_url = group.manifest_url;
+ info.creation_time = group.creation_time;
info.size = cache_record.cache_size;
- info.last_access_time = group->last_access_time;
+ info.last_access_time = group.last_access_time;
info.last_update_time = cache_record.update_time;
info.cache_id = cache_record.cache_id;
- info.group_id = group->group_id;
+ info.group_id = group.group_id;
info.is_complete = true;
infos.push_back(info);
}
@@ -487,12 +484,11 @@ void AppCacheStorageImpl::StoreOrLoadTask::CreateCacheAndGroupFromRecords(
// We have to update foriegn entries if MarkEntryAsForeignTasks
// are in flight.
- std::vector<GURL> urls;
- storage_->GetPendingForeignMarkingsForCache(cache->get()->cache_id(), &urls);
- for (std::vector<GURL>::iterator iter = urls.begin();
- iter != urls.end(); ++iter) {
- DCHECK(cache->get()->GetEntry(*iter));
- cache->get()->GetEntry(*iter)->add_types(AppCacheEntry::FOREIGN);
+ std::vector<GURL> urls =
+ storage_->GetPendingForeignMarkingsForCache(cache->get()->cache_id());
+ for (const auto& url : urls) {
+ DCHECK(cache->get()->GetEntry(url));
+ cache->get()->GetEntry(url)->add_types(AppCacheEntry::FOREIGN);
}
storage_->NotifyStorageAccessed(group_record_.origin);
@@ -621,17 +617,25 @@ class AppCacheStorageImpl::StoreGroupAndCacheTask : public StoreOrLoadTask {
bool would_exceed_quota_;
int64_t space_available_;
int64_t new_origin_usage_;
+ int64_t max_appcache_origin_cache_size_;
std::vector<int64_t> newly_deletable_response_ids_;
};
AppCacheStorageImpl::StoreGroupAndCacheTask::StoreGroupAndCacheTask(
- AppCacheStorageImpl* storage, AppCacheGroup* group, AppCache* newest_cache)
- : StoreOrLoadTask(storage), group_(group), cache_(newest_cache),
- success_(false), would_exceed_quota_(false),
- space_available_(-1), new_origin_usage_(-1) {
+ AppCacheStorageImpl* storage,
+ AppCacheGroup* group,
+ AppCache* newest_cache)
+ : StoreOrLoadTask(storage),
+ group_(group),
+ cache_(newest_cache),
+ success_(false),
+ would_exceed_quota_(false),
+ space_available_(-1),
+ new_origin_usage_(-1),
+ max_appcache_origin_cache_size_(kDefaultQuota) {
group_record_.group_id = group->group_id();
group_record_.manifest_url = group->manifest_url();
- group_record_.origin = group_record_.manifest_url.GetOrigin();
+ group_record_.origin = url::Origin::Create(group_record_.manifest_url);
group_record_.last_full_update_check_time =
group->last_full_update_check_time();
group_record_.first_evictable_error_time =
@@ -642,6 +646,15 @@ AppCacheStorageImpl::StoreGroupAndCacheTask::StoreGroupAndCacheTask(
&intercept_namespace_records_,
&fallback_namespace_records_,
&online_whitelist_records_);
+
+ base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess();
+ if (command_line.HasSwitch(switches::kMaxAppCacheOriginCacheSizeMb)) {
+ if (base::StringToInt64(command_line.GetSwitchValueASCII(
+ switches::kMaxAppCacheOriginCacheSizeMb),
+ &max_appcache_origin_cache_size_)) {
+ max_appcache_origin_cache_size_ *= kMB;
+ }
+ }
}
void AppCacheStorageImpl::StoreGroupAndCacheTask::GetQuotaThenSchedule() {
@@ -654,7 +667,7 @@ void AppCacheStorageImpl::StoreGroupAndCacheTask::GetQuotaThenSchedule() {
if (!quota_manager) {
if (storage_->service()->special_storage_policy() &&
storage_->service()->special_storage_policy()->IsStorageUnlimited(
- group_record_.origin))
+ group_record_.origin.GetURL()))
space_available_ = std::numeric_limits<int64_t>::max();
Schedule();
return;
@@ -668,8 +681,8 @@ void AppCacheStorageImpl::StoreGroupAndCacheTask::GetQuotaThenSchedule() {
// We have to ask the quota manager for the value.
storage_->pending_quota_queries_.insert(this);
quota_manager->GetUsageAndQuota(
- group_record_.origin, blink::mojom::StorageType::kTemporary,
- base::Bind(&StoreGroupAndCacheTask::OnQuotaCallback, this));
+ group_record_.origin.GetURL(), blink::mojom::StorageType::kTemporary,
+ base::BindOnce(&StoreGroupAndCacheTask::OnQuotaCallback, this));
}
void AppCacheStorageImpl::StoreGroupAndCacheTask::OnQuotaCallback(
@@ -725,19 +738,12 @@ void AppCacheStorageImpl::StoreGroupAndCacheTask::Run() {
&existing_response_ids);
// Remove those that remain in the new cache.
- std::vector<AppCacheDatabase::EntryRecord>::const_iterator entry_iter =
- entry_records_.begin();
- while (entry_iter != entry_records_.end()) {
- existing_response_ids.erase(entry_iter->response_id);
- ++entry_iter;
- }
+ for (const auto& entry : entry_records_)
+ existing_response_ids.erase(entry.response_id);
// The rest are deletable.
- std::set<int64_t>::const_iterator id_iter = existing_response_ids.begin();
- while (id_iter != existing_response_ids.end()) {
- newly_deletable_response_ids_.push_back(*id_iter);
- ++id_iter;
- }
+ for (const auto& id : existing_response_ids)
+ newly_deletable_response_ids_.push_back(id);
success_ =
database_->DeleteCache(cache.cache_id) &&
@@ -770,9 +776,10 @@ void AppCacheStorageImpl::StoreGroupAndCacheTask::Run() {
return;
}
- // Use a simple hard-coded value when not using quota management.
+ // Use a user defined value or a simple hard-coded value when not using quota
+ // management.
if (space_available_ == -1) {
- if (new_origin_usage_ > kDefaultQuota) {
+ if (new_origin_usage_ > max_appcache_origin_cache_size_) {
would_exceed_quota_ = true;
success_ = false;
return;
@@ -796,7 +803,7 @@ void AppCacheStorageImpl::StoreGroupAndCacheTask::Run() {
void AppCacheStorageImpl::StoreGroupAndCacheTask::RunCompleted() {
if (success_) {
storage_->UpdateUsageMapAndNotify(
- group_->manifest_url().GetOrigin(), new_origin_usage_);
+ url::Origin::Create(group_->manifest_url()), new_origin_usage_);
if (cache_.get() != group_->newest_complete_cache()) {
cache_->set_complete(true);
group_->AddCache(cache_.get());
@@ -864,8 +871,7 @@ class NetworkNamespaceHelper {
}
bool IsInNetworkNamespace(const GURL& url, int64_t cache_id) {
- typedef std::pair<WhiteListMap::iterator, bool> InsertResult;
- InsertResult result = namespaces_map_.insert(
+ std::pair<WhiteListMap::iterator, bool> result = namespaces_map_.insert(
WhiteListMap::value_type(cache_id, AppCacheNamespaceVector()));
if (result.second)
GetOnlineWhiteListForCache(cache_id, &result.first->second);
@@ -876,22 +882,21 @@ class NetworkNamespaceHelper {
void GetOnlineWhiteListForCache(int64_t cache_id,
AppCacheNamespaceVector* namespaces) {
DCHECK(namespaces && namespaces->empty());
- typedef std::vector<AppCacheDatabase::OnlineWhiteListRecord>
- WhiteListVector;
+ using WhiteListVector =
+ std::vector<AppCacheDatabase::OnlineWhiteListRecord>;
WhiteListVector records;
if (!database_->FindOnlineWhiteListForCache(cache_id, &records))
return;
- WhiteListVector::const_iterator iter = records.begin();
- while (iter != records.end()) {
- namespaces->push_back(
- AppCacheNamespace(APPCACHE_NETWORK_NAMESPACE, iter->namespace_url,
- GURL(), iter->is_pattern));
- ++iter;
+
+ for (const auto& record : records) {
+ namespaces->push_back(AppCacheNamespace(APPCACHE_NETWORK_NAMESPACE,
+ record.namespace_url, GURL(),
+ record.is_pattern));
}
}
// Key is cache id
- typedef std::map<int64_t, AppCacheNamespaceVector> WhiteListMap;
+ using WhiteListMap = std::map<int64_t, AppCacheNamespaceVector>;
WhiteListMap namespaces_map_;
AppCacheDatabase* database_;
};
@@ -908,10 +913,8 @@ class AppCacheStorageImpl::FindMainResponseTask : public DatabaseTask {
preferred_manifest_url_(preferred_manifest_url),
cache_id_(kAppCacheNoCacheId), group_id_(0) {
if (groups_in_use) {
- for (AppCacheWorkingSet::GroupMap::const_iterator it =
- groups_in_use->begin();
- it != groups_in_use->end(); ++it) {
- AppCacheGroup* group = it->second;
+ for (const auto& pair : *groups_in_use) {
+ AppCacheGroup* group = pair.second;
AppCache* cache = group->newest_complete_cache();
if (group->is_obsolete() || !cache)
continue;
@@ -928,8 +931,8 @@ class AppCacheStorageImpl::FindMainResponseTask : public DatabaseTask {
~FindMainResponseTask() override {}
private:
- typedef std::vector<AppCacheDatabase::NamespaceRecord*>
- NamespaceRecordPtrVector;
+ using NamespaceRecordPtrVector =
+ std::vector<AppCacheDatabase::NamespaceRecord*>;
bool FindExactMatch(int64_t preferred_id);
bool FindNamespaceMatch(int64_t preferred_id);
@@ -997,17 +1000,16 @@ bool AppCacheStorageImpl::FindMainResponseTask::FindExactMatch(
SortByCachePreference(preferred_cache_id, cache_ids_in_use_));
// Take the first with a valid, non-foreign entry.
- std::vector<AppCacheDatabase::EntryRecord>::iterator iter;
- for (iter = entries.begin(); iter < entries.end(); ++iter) {
+ for (const auto& entry : entries) {
AppCacheDatabase::GroupRecord group_record;
- if ((iter->flags & AppCacheEntry::FOREIGN) ||
- !database_->FindGroupForCache(iter->cache_id, &group_record)) {
+ if ((entry.flags & AppCacheEntry::FOREIGN) ||
+ !database_->FindGroupForCache(entry.cache_id, &group_record)) {
continue;
}
manifest_url_ = group_record.manifest_url;
group_id_ = group_record.group_id;
- entry_ = AppCacheEntry(iter->flags, iter->response_id);
- cache_id_ = iter->cache_id;
+ entry_ = AppCacheEntry(entry.flags, entry.response_id);
+ cache_id_ = entry.cache_id;
return true; // We found an exact match.
}
}
@@ -1018,9 +1020,9 @@ bool AppCacheStorageImpl::FindMainResponseTask::FindNamespaceMatch(
int64_t preferred_cache_id) {
AppCacheDatabase::NamespaceRecordVector all_intercepts;
AppCacheDatabase::NamespaceRecordVector all_fallbacks;
- if (!database_->FindNamespacesForOrigin(
- url_.GetOrigin(), &all_intercepts, &all_fallbacks)
- || (all_intercepts.empty() && all_fallbacks.empty())) {
+ if (!database_->FindNamespacesForOrigin(url::Origin::Create(url_),
+ &all_intercepts, &all_fallbacks) ||
+ (all_intercepts.empty() && all_fallbacks.empty())) {
return false;
}
@@ -1047,24 +1049,25 @@ bool AppCacheStorageImpl::FindMainResponseTask::FindNamespaceHelper(
NamespaceRecordPtrVector preferred_namespaces;
NamespaceRecordPtrVector inuse_namespaces;
NamespaceRecordPtrVector other_namespaces;
- std::vector<AppCacheDatabase::NamespaceRecord>::iterator iter;
- for (iter = namespaces->begin(); iter < namespaces->end(); ++iter) {
+ for (auto& namespace_record : *namespaces) {
// Skip those that aren't a match.
- if (!iter->namespace_.IsMatch(url_))
+ if (!namespace_record.namespace_.IsMatch(url_))
continue;
// Skip namespaces where the requested url falls into a network
// namespace of its containing appcache.
- if (network_namespace_helper->IsInNetworkNamespace(url_, iter->cache_id))
+ if (network_namespace_helper->IsInNetworkNamespace(
+ url_, namespace_record.cache_id))
continue;
// Bin them into one of our three buckets.
- if (iter->cache_id == preferred_cache_id)
- preferred_namespaces.push_back(&(*iter));
- else if (cache_ids_in_use_.find(iter->cache_id) != cache_ids_in_use_.end())
- inuse_namespaces.push_back(&(*iter));
+ if (namespace_record.cache_id == preferred_cache_id)
+ preferred_namespaces.push_back(&namespace_record);
+ else if (cache_ids_in_use_.find(namespace_record.cache_id) !=
+ cache_ids_in_use_.end())
+ inuse_namespaces.push_back(&namespace_record);
else
- other_namespaces.push_back(&(*iter));
+ other_namespaces.push_back(&namespace_record);
}
if (FindFirstValidNamespace(preferred_namespaces) ||
@@ -1080,10 +1083,10 @@ bool AppCacheStorageImpl::
FindMainResponseTask::FindFirstValidNamespace(
const NamespaceRecordPtrVector& namespaces) {
// Take the first with a valid, non-foreign entry.
- NamespaceRecordPtrVector::const_iterator iter;
- for (iter = namespaces.begin(); iter < namespaces.end(); ++iter) {
+ for (auto* namespace_record : namespaces) {
AppCacheDatabase::EntryRecord entry_record;
- if (database_->FindEntry((*iter)->cache_id, (*iter)->namespace_.target_url,
+ if (database_->FindEntry(namespace_record->cache_id,
+ namespace_record->namespace_.target_url,
&entry_record)) {
AppCacheDatabase::GroupRecord group_record;
if ((entry_record.flags & AppCacheEntry::FOREIGN) ||
@@ -1092,9 +1095,9 @@ FindMainResponseTask::FindFirstValidNamespace(
}
manifest_url_ = group_record.manifest_url;
group_id_ = group_record.group_id;
- cache_id_ = (*iter)->cache_id;
- namespace_entry_url_ = (*iter)->namespace_.target_url;
- if ((*iter)->namespace_.type == APPCACHE_FALLBACK_NAMESPACE)
+ cache_id_ = namespace_record->cache_id;
+ namespace_entry_url_ = namespace_record->namespace_.target_url;
+ if (namespace_record->namespace_.type == APPCACHE_FALLBACK_NAMESPACE)
fallback_entry_ = AppCacheEntry(entry_record.flags,
entry_record.response_id);
else
@@ -1161,7 +1164,7 @@ class AppCacheStorageImpl::MakeGroupObsoleteTask : public DatabaseTask {
private:
scoped_refptr<AppCacheGroup> group_;
int64_t group_id_;
- GURL origin_;
+ url::Origin origin_;
bool success_;
int response_code_;
int64_t new_origin_usage_;
@@ -1175,7 +1178,7 @@ AppCacheStorageImpl::MakeGroupObsoleteTask::MakeGroupObsoleteTask(
: DatabaseTask(storage),
group_(group),
group_id_(group->group_id()),
- origin_(group->manifest_url().GetOrigin()),
+ origin_(url::Origin::Create(group->manifest_url())),
success_(false),
response_code_(response_code),
new_origin_usage_(-1) {}
@@ -1314,7 +1317,7 @@ class AppCacheStorageImpl::LazyUpdateLastAccessTimeTask
AppCacheStorageImpl* storage, AppCacheGroup* group, base::Time time)
: DatabaseTask(storage), group_id_(group->group_id()),
last_access_time_(time) {
- storage->NotifyStorageAccessed(group->manifest_url().GetOrigin());
+ storage->NotifyStorageAccessed(url::Origin::Create(group->manifest_url()));
}
// DatabaseTask:
@@ -1399,9 +1402,9 @@ AppCacheStorageImpl::AppCacheStorageImpl(AppCacheServiceImpl* service)
weak_factory_(this) {}
AppCacheStorageImpl::~AppCacheStorageImpl() {
- for (auto* task : pending_quota_queries_)
+ for (StoreGroupAndCacheTask* task : pending_quota_queries_)
task->CancelCompletion();
- for (auto* task : scheduled_database_tasks_)
+ for (DatabaseTask* task : scheduled_database_tasks_)
task->CancelCompletion();
if (database_ &&
@@ -1505,7 +1508,7 @@ void AppCacheStorageImpl::LoadOrCreateGroup(
return;
}
- if (usage_map_.find(manifest_url.GetOrigin()) == usage_map_.end()) {
+ if (usage_map_.find(url::Origin::Create(manifest_url)) == usage_map_.end()) {
// No need to query the database, return a new group immediately.
scoped_refptr<AppCacheGroup> new_group(
new AppCacheGroup(this, manifest_url, NewGroupId()));
@@ -1553,7 +1556,7 @@ void AppCacheStorageImpl::FindResponseForMainRequest(
url_ptr = &url_no_ref;
}
- const GURL origin = url.GetOrigin();
+ const url::Origin origin(url::Origin::Create(url));
// First look in our working set for a direct hit without having to query
// the database.
@@ -1569,11 +1572,9 @@ void AppCacheStorageImpl::FindResponseForMainRequest(
return;
}
} else {
- for (AppCacheWorkingSet::GroupMap::const_iterator it =
- groups_in_use->begin();
- it != groups_in_use->end(); ++it) {
- if (FindResponseForMainRequestInGroup(
- it->second, *url_ptr, delegate)) {
+ for (const auto& pair : *groups_in_use) {
+ if (FindResponseForMainRequestInGroup(pair.second, *url_ptr,
+ delegate)) {
return;
}
}
@@ -1853,15 +1854,14 @@ AppCacheStorageImpl::GetPendingGroupLoadTask(const GURL& manifest_url) {
return nullptr;
}
-void AppCacheStorageImpl::GetPendingForeignMarkingsForCache(
- int64_t cache_id,
- std::vector<GURL>* urls) {
- PendingForeignMarkings::iterator iter = pending_foreign_markings_.begin();
- while (iter != pending_foreign_markings_.end()) {
- if (iter->second == cache_id)
- urls->push_back(iter->first);
- ++iter;
+std::vector<GURL> AppCacheStorageImpl::GetPendingForeignMarkingsForCache(
+ int64_t cache_id) {
+ std::vector<GURL> urls;
+ for (const auto& pair : pending_foreign_markings_) {
+ if (pair.second == cache_id)
+ urls.push_back(pair.first);
}
+ return urls;
}
void AppCacheStorageImpl::ScheduleSimpleTask(base::OnceClosure task) {
@@ -1892,9 +1892,21 @@ AppCacheDiskCache* AppCacheStorageImpl::disk_cache() {
base::Unretained(this)));
} else {
expecting_cleanup_complete_on_disable_ = true;
+
+ const base::CommandLine& command_line =
+ *base::CommandLine::ForCurrentProcess();
+ unsigned int max_appcache_disk_cache_size = kMaxAppCacheDiskCacheSize;
+ if (command_line.HasSwitch(switches::kMaxAppCacheDiskCacheSizeMb)) {
+ if (base::StringToUint(command_line.GetSwitchValueASCII(
+ switches::kMaxAppCacheDiskCacheSizeMb),
+ &max_appcache_disk_cache_size)) {
+ max_appcache_disk_cache_size *= kMB;
+ }
+ }
+
rv = disk_cache_->InitWithDiskBackend(
cache_directory_.Append(kDiskCacheDirectoryName),
- kMaxAppCacheDiskCacheSize, false,
+ max_appcache_disk_cache_size, false,
base::BindOnce(&AppCacheStorageImpl::OnDiskCacheCleanupComplete,
weak_factory_.GetWeakPtr()),
base::Bind(&AppCacheStorageImpl::OnDiskCacheInitialized,
diff --git a/chromium/content/browser/appcache/appcache_storage_impl.h b/chromium/content/browser/appcache/appcache_storage_impl.h
index 022ae2f4563..51b0bb1c093 100644
--- a/chromium/content/browser/appcache/appcache_storage_impl.h
+++ b/chromium/content/browser/appcache/appcache_storage_impl.h
@@ -109,8 +109,7 @@ class AppCacheStorageImpl : public AppCacheStorage {
CacheLoadTask* GetPendingCacheLoadTask(int64_t cache_id);
GroupLoadTask* GetPendingGroupLoadTask(const GURL& manifest_url);
- void GetPendingForeignMarkingsForCache(int64_t cache_id,
- std::vector<GURL>* urls);
+ std::vector<GURL> GetPendingForeignMarkingsForCache(int64_t cache_id);
void ScheduleSimpleTask(base::OnceClosure task);
void RunOnePendingSimpleTask();
diff --git a/chromium/content/browser/appcache/appcache_storage_impl_unittest.cc b/chromium/content/browser/appcache/appcache_storage_impl_unittest.cc
index 6693b440c64..d8988c284b7 100644
--- a/chromium/content/browser/appcache/appcache_storage_impl_unittest.cc
+++ b/chromium/content/browser/appcache/appcache_storage_impl_unittest.cc
@@ -17,7 +17,6 @@
#include "base/files/scoped_temp_dir.h"
#include "base/location.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/synchronization/waitable_event.h"
@@ -524,7 +523,7 @@ class AppCacheStorageImplTest : public testing::Test {
// Since the origin has groups, storage class will have to
// consult the database and completion will be async.
- storage()->usage_map_[kOrigin.GetURL()] = kDefaultEntrySize;
+ storage()->usage_map_[kOrigin] = kDefaultEntrySize;
storage()->LoadOrCreateGroup(kManifestUrl, delegate());
EXPECT_FALSE(delegate()->loaded_group_.get());
@@ -641,7 +640,7 @@ class AppCacheStorageImplTest : public testing::Test {
EXPECT_TRUE(database()->FindCache(cache_->cache_id(), &cache_record));
// Verify quota bookkeeping
- EXPECT_EQ(kDefaultEntrySize, storage()->usage_map_[kOrigin.GetURL()]);
+ EXPECT_EQ(kDefaultEntrySize, storage()->usage_map_[kOrigin]);
EXPECT_EQ(1, mock_quota_manager_proxy_->notify_storage_modified_count_);
EXPECT_EQ(kOrigin, mock_quota_manager_proxy_->last_origin_);
EXPECT_EQ(kDefaultEntrySize, mock_quota_manager_proxy_->last_delta_);
@@ -660,7 +659,7 @@ class AppCacheStorageImplTest : public testing::Test {
// Setup some preconditions. Create a group and old complete cache
// that appear to be "stored"
MakeCacheAndGroup(kManifestUrl, 1, 1, true);
- EXPECT_EQ(kDefaultEntrySize, storage()->usage_map_[kOrigin.GetURL()]);
+ EXPECT_EQ(kDefaultEntrySize, storage()->usage_map_[kOrigin]);
// And a newest unstored complete cache.
cache2_ = new AppCache(storage(), 2);
@@ -689,7 +688,7 @@ class AppCacheStorageImplTest : public testing::Test {
EXPECT_FALSE(database()->FindCache(1, &cache_record));
// Verify quota bookkeeping
- EXPECT_EQ(kDefaultEntrySize + 100, storage()->usage_map_[kOrigin.GetURL()]);
+ EXPECT_EQ(kDefaultEntrySize + 100, storage()->usage_map_[kOrigin]);
EXPECT_EQ(1, mock_quota_manager_proxy_->notify_storage_modified_count_);
EXPECT_EQ(kOrigin, mock_quota_manager_proxy_->last_origin_);
EXPECT_EQ(100, mock_quota_manager_proxy_->last_delta_);
@@ -707,7 +706,7 @@ class AppCacheStorageImplTest : public testing::Test {
// Setup some preconditions. Create a group and old complete cache
// that appear to be "stored"
MakeCacheAndGroup(kManifestUrl, 1, 1, true);
- EXPECT_EQ(kDefaultEntrySize, storage()->usage_map_[kOrigin.GetURL()]);
+ EXPECT_EQ(kDefaultEntrySize, storage()->usage_map_[kOrigin]);
// Change the cache.
base::Time now = base::Time::Now();
@@ -749,7 +748,7 @@ class AppCacheStorageImplTest : public testing::Test {
EXPECT_EQ(100, entry_records[0].response_size);
// Verify quota bookkeeping
- EXPECT_EQ(100 + kDefaultEntrySize, storage()->usage_map_[kOrigin.GetURL()]);
+ EXPECT_EQ(100 + kDefaultEntrySize, storage()->usage_map_[kOrigin]);
EXPECT_EQ(1, mock_quota_manager_proxy_->notify_storage_modified_count_);
EXPECT_EQ(kOrigin, mock_quota_manager_proxy_->last_origin_);
EXPECT_EQ(100, mock_quota_manager_proxy_->last_delta_);
@@ -807,7 +806,7 @@ class AppCacheStorageImplTest : public testing::Test {
// Setup some preconditions. Create a group and newest cache that
// appears to be "stored" and "currently in use".
MakeCacheAndGroup(kManifestUrl, 1, 1, true);
- EXPECT_EQ(kDefaultEntrySize, storage()->usage_map_[kOrigin.GetURL()]);
+ EXPECT_EQ(kDefaultEntrySize, storage()->usage_map_[kOrigin]);
// Also insert some related records.
AppCacheDatabase::EntryRecord entry_record;
@@ -821,7 +820,7 @@ class AppCacheStorageImplTest : public testing::Test {
fallback_namespace_record.cache_id = 1;
fallback_namespace_record.namespace_.target_url = kEntryUrl;
fallback_namespace_record.namespace_.namespace_url = kFallbackNamespace;
- fallback_namespace_record.origin = kManifestUrl.GetOrigin();
+ fallback_namespace_record.origin = url::Origin::Create(kManifestUrl);
EXPECT_TRUE(database()->InsertNamespace(&fallback_namespace_record));
AppCacheDatabase::OnlineWhiteListRecord online_whitelist_record;
@@ -1062,13 +1061,10 @@ class AppCacheStorageImplTest : public testing::Test {
&fallbacks,
&whitelists);
- std::vector<AppCacheDatabase::EntryRecord>::const_iterator iter =
- entries.begin();
- while (iter != entries.end()) {
+ for (const auto& entry : entries) {
// MakeCacheAndGroup has inserted the default entry record already.
- if (iter->url != kDefaultEntryUrl)
- EXPECT_TRUE(database()->InsertEntry(&(*iter)));
- ++iter;
+ if (entry.url != kDefaultEntryUrl)
+ EXPECT_TRUE(database()->InsertEntry(&entry));
}
EXPECT_TRUE(database()->InsertNamespaceRecords(fallbacks));
@@ -1136,13 +1132,10 @@ class AppCacheStorageImplTest : public testing::Test {
&fallbacks,
&whitelists);
- std::vector<AppCacheDatabase::EntryRecord>::const_iterator iter =
- entries.begin();
- while (iter != entries.end()) {
+ for (const auto& entry : entries) {
// MakeCacheAndGroup has inserted the default entry record already
- if (iter->url != kDefaultEntryUrl)
- EXPECT_TRUE(database()->InsertEntry(&(*iter)));
- ++iter;
+ if (entry.url != kDefaultEntryUrl)
+ EXPECT_TRUE(database()->InsertEntry(&entry));
}
EXPECT_TRUE(database()->InsertNamespaceRecords(intercepts));
@@ -1203,13 +1196,10 @@ class AppCacheStorageImplTest : public testing::Test {
&fallbacks,
&whitelists);
- std::vector<AppCacheDatabase::EntryRecord>::const_iterator iter =
- entries.begin();
- while (iter != entries.end()) {
+ for (const auto& entry : entries) {
// MakeCacheAndGroup has inserted the default entry record already
- if (iter->url != kDefaultEntryUrl)
- EXPECT_TRUE(database()->InsertEntry(&(*iter)));
- ++iter;
+ if (entry.url != kDefaultEntryUrl)
+ EXPECT_TRUE(database()->InsertEntry(&entry));
}
EXPECT_TRUE(database()->InsertNamespaceRecords(intercepts));
@@ -1290,13 +1280,10 @@ class AppCacheStorageImplTest : public testing::Test {
&fallbacks,
&whitelists);
- std::vector<AppCacheDatabase::EntryRecord>::const_iterator iter =
- entries.begin();
- while (iter != entries.end()) {
+ for (const auto& entry : entries) {
// MakeCacheAndGroup has inserted the default entry record already.
- if (iter->url != kDefaultEntryUrl)
- EXPECT_TRUE(database()->InsertEntry(&(*iter)));
- ++iter;
+ if (entry.url != kDefaultEntryUrl)
+ EXPECT_TRUE(database()->InsertEntry(&entry));
}
EXPECT_TRUE(database()->InsertNamespaceRecords(fallbacks));
@@ -1404,7 +1391,7 @@ class AppCacheStorageImplTest : public testing::Test {
fallback_namespace_record.cache_id = id;
fallback_namespace_record.namespace_.target_url = entry_record.url;
fallback_namespace_record.namespace_.namespace_url = kFallbackNamespace;
- fallback_namespace_record.origin = manifest_url.GetOrigin();
+ fallback_namespace_record.origin = url::Origin::Create(manifest_url);
EXPECT_TRUE(database()->InsertNamespace(&fallback_namespace_record));
cache_->fallback_namespaces_.push_back(
AppCacheNamespace(APPCACHE_FALLBACK_NAMESPACE,
@@ -1547,7 +1534,7 @@ class AppCacheStorageImplTest : public testing::Test {
fallback_namespace_record.cache_id = 1;
fallback_namespace_record.namespace_.target_url = kEntryUrl2;
fallback_namespace_record.namespace_.namespace_url = kFallbackNamespace;
- fallback_namespace_record.origin = kManifestUrl.GetOrigin();
+ fallback_namespace_record.origin = url::Origin::Create(kManifestUrl);
EXPECT_TRUE(database()->InsertNamespace(&fallback_namespace_record));
whitelist_record.cache_id = 1;
whitelist_record.namespace_url = kOnlineNamespaceWithinFallback;
@@ -1701,7 +1688,7 @@ class AppCacheStorageImplTest : public testing::Test {
AppCacheDatabase::GroupRecord group_record;
group_record.group_id = 1;
group_record.manifest_url = manifest_url;
- group_record.origin = manifest_url.GetOrigin();
+ group_record.origin = url::Origin::Create(manifest_url);
EXPECT_TRUE(db.InsertGroup(&group_record));
AppCacheDatabase::CacheRecord cache_record;
cache_record.cache_id = 1;
@@ -1851,11 +1838,12 @@ class AppCacheStorageImplTest : public testing::Test {
cache_->AddEntry(kDefaultEntryUrl, default_entry);
cache_->set_complete(true);
group_->AddCache(cache_.get());
+ url::Origin manifest_origin(url::Origin::Create(manifest_url));
if (add_to_database) {
AppCacheDatabase::GroupRecord group_record;
group_record.group_id = group_id;
group_record.manifest_url = manifest_url;
- group_record.origin = manifest_url.GetOrigin();
+ group_record.origin = manifest_origin;
EXPECT_TRUE(database()->InsertGroup(&group_record));
AppCacheDatabase::CacheRecord cache_record;
cache_record.cache_id = cache_id;
@@ -1872,8 +1860,7 @@ class AppCacheStorageImplTest : public testing::Test {
entry_record.response_size = default_entry.response_size();
EXPECT_TRUE(database()->InsertEntry(&entry_record));
- storage()->usage_map_[manifest_url.GetOrigin()] =
- default_entry.response_size();
+ storage()->usage_map_[manifest_origin] = default_entry.response_size();
}
}
diff --git a/chromium/content/browser/appcache/appcache_storage_unittest.cc b/chromium/content/browser/appcache/appcache_storage_unittest.cc
index 8ef6dcbb70a..961299a6eaa 100644
--- a/chromium/content/browser/appcache/appcache_storage_unittest.cc
+++ b/chromium/content/browser/appcache/appcache_storage_unittest.cc
@@ -79,8 +79,8 @@ TEST_F(AppCacheStorageTest, AddRemoveResponseInfo) {
}
TEST_F(AppCacheStorageTest, DelegateReferences) {
- typedef scoped_refptr<AppCacheStorage::DelegateReference>
- ScopedDelegateReference;
+ using ScopedDelegateReference =
+ scoped_refptr<AppCacheStorage::DelegateReference>;
MockAppCacheService service;
MockStorageDelegate delegate;
ScopedDelegateReference delegate_reference1;
@@ -117,8 +117,8 @@ TEST_F(AppCacheStorageTest, DelegateReferences) {
}
TEST_F(AppCacheStorageTest, UsageMap) {
- const GURL kOrigin("http://origin/");
- const GURL kOrigin2("http://origin2/");
+ const url::Origin kOrigin(url::Origin::Create(GURL("http://origin/")));
+ const url::Origin kOrigin2(url::Origin::Create(GURL("http://origin2/")));
MockAppCacheService service;
scoped_refptr<MockQuotaManagerProxy> mock_proxy(
@@ -131,19 +131,19 @@ TEST_F(AppCacheStorageTest, UsageMap) {
service.storage()->UpdateUsageMapAndNotify(kOrigin, 10);
EXPECT_EQ(1, mock_proxy->notify_storage_modified_count());
EXPECT_EQ(10, mock_proxy->last_notified_delta());
- EXPECT_EQ(kOrigin, mock_proxy->last_notified_origin().GetURL());
+ EXPECT_EQ(kOrigin, mock_proxy->last_notified_origin());
EXPECT_EQ(kTemp, mock_proxy->last_notified_type());
service.storage()->UpdateUsageMapAndNotify(kOrigin, 100);
EXPECT_EQ(2, mock_proxy->notify_storage_modified_count());
EXPECT_EQ(90, mock_proxy->last_notified_delta());
- EXPECT_EQ(kOrigin, mock_proxy->last_notified_origin().GetURL());
+ EXPECT_EQ(kOrigin, mock_proxy->last_notified_origin());
EXPECT_EQ(kTemp, mock_proxy->last_notified_type());
service.storage()->UpdateUsageMapAndNotify(kOrigin, 0);
EXPECT_EQ(3, mock_proxy->notify_storage_modified_count());
EXPECT_EQ(-100, mock_proxy->last_notified_delta());
- EXPECT_EQ(kOrigin, mock_proxy->last_notified_origin().GetURL());
+ EXPECT_EQ(kOrigin, mock_proxy->last_notified_origin());
EXPECT_EQ(kTemp, mock_proxy->last_notified_type());
service.storage()->NotifyStorageAccessed(kOrigin2);
@@ -152,7 +152,7 @@ TEST_F(AppCacheStorageTest, UsageMap) {
service.storage()->usage_map_[kOrigin2] = 1;
service.storage()->NotifyStorageAccessed(kOrigin2);
EXPECT_EQ(1, mock_proxy->notify_storage_accessed_count());
- EXPECT_EQ(kOrigin2, mock_proxy->last_notified_origin().GetURL());
+ EXPECT_EQ(kOrigin2, mock_proxy->last_notified_origin());
EXPECT_EQ(kTemp, mock_proxy->last_notified_type());
service.storage()->usage_map_.clear();
@@ -160,7 +160,7 @@ TEST_F(AppCacheStorageTest, UsageMap) {
service.storage()->ClearUsageMapAndNotify();
EXPECT_EQ(4, mock_proxy->notify_storage_modified_count());
EXPECT_EQ(-5000, mock_proxy->last_notified_delta());
- EXPECT_EQ(kOrigin, mock_proxy->last_notified_origin().GetURL());
+ EXPECT_EQ(kOrigin, mock_proxy->last_notified_origin());
EXPECT_EQ(kTemp, mock_proxy->last_notified_type());
EXPECT_TRUE(service.storage()->usage_map_.empty());
}
diff --git a/chromium/content/browser/appcache/appcache_subresource_url_factory.cc b/chromium/content/browser/appcache/appcache_subresource_url_factory.cc
index 83e4def3ba6..a59273f1659 100644
--- a/chromium/content/browser/appcache/appcache_subresource_url_factory.cc
+++ b/chromium/content/browser/appcache/appcache_subresource_url_factory.cc
@@ -12,7 +12,6 @@
#include "content/browser/appcache/appcache_url_loader_request.h"
#include "content/browser/url_loader_factory_getter.h"
#include "content/public/browser/browser_thread.h"
-#include "content/public/common/shared_url_loader_factory.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "mojo/public/cpp/bindings/binding_set.h"
#include "mojo/public/cpp/bindings/interface_ptr.h"
@@ -20,6 +19,7 @@
#include "net/url_request/url_request.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/resource_response.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
namespace content {
@@ -176,11 +176,10 @@ class SubresourceLoader : public network::mojom::URLLoader,
// Called by either the appcache or network loader, whichever is in use.
void OnReceiveResponse(
const network::ResourceResponseHead& response_head,
- const base::Optional<net::SSLInfo>& ssl_info,
network::mojom::DownloadedTempFilePtr downloaded_file) override {
// Don't MaybeFallback for appcache produced responses.
if (appcache_loader_ || !handler_) {
- remote_client_->OnReceiveResponse(response_head, ssl_info,
+ remote_client_->OnReceiveResponse(response_head,
std::move(downloaded_file));
return;
}
@@ -189,19 +188,18 @@ class SubresourceLoader : public network::mojom::URLLoader,
handler_->MaybeFallbackForSubresourceResponse(
response_head,
base::BindOnce(&SubresourceLoader::ContinueOnReceiveResponse,
- weak_factory_.GetWeakPtr(), response_head, ssl_info,
+ weak_factory_.GetWeakPtr(), response_head,
std::move(downloaded_file)));
}
void ContinueOnReceiveResponse(
const network::ResourceResponseHead& response_head,
- const base::Optional<net::SSLInfo>& ssl_info,
network::mojom::DownloadedTempFilePtr downloaded_file,
SingleRequestURLLoaderFactory::RequestHandler handler) {
if (handler) {
CreateAndStartAppCacheLoader(std::move(handler));
} else {
- remote_client_->OnReceiveResponse(response_head, ssl_info,
+ remote_client_->OnReceiveResponse(response_head,
std::move(downloaded_file));
}
}
diff --git a/chromium/content/browser/appcache/appcache_update_job.cc b/chromium/content/browser/appcache/appcache_update_job.cc
index 10630d905e7..a6d641667cb 100644
--- a/chromium/content/browser/appcache/appcache_update_job.cc
+++ b/chromium/content/browser/appcache/appcache_update_job.cc
@@ -97,63 +97,56 @@ void EmptyCompletionCallback(int result) {}
// so that only one notification is sent for all hosts using the same frontend.
class HostNotifier {
public:
- typedef std::vector<int> HostIds;
- typedef std::map<AppCacheFrontend*, HostIds> NotifyHostMap;
+ using HostIds = std::vector<int>;
+ using NotifyHostMap = std::map<AppCacheFrontend*, HostIds>;
// Caller is responsible for ensuring there will be no duplicate hosts.
void AddHost(AppCacheHost* host) {
- std::pair<NotifyHostMap::iterator, bool> ret = hosts_to_notify.insert(
+ std::pair<NotifyHostMap::iterator, bool> ret = hosts_to_notify_.insert(
NotifyHostMap::value_type(host->frontend(), HostIds()));
ret.first->second.push_back(host->host_id());
}
void AddHosts(const std::set<AppCacheHost*>& hosts) {
- for (std::set<AppCacheHost*>::const_iterator it = hosts.begin();
- it != hosts.end(); ++it) {
- AddHost(*it);
- }
+ for (AppCacheHost* host : hosts)
+ AddHost(host);
}
void SendNotifications(AppCacheEventID event_id) {
- for (NotifyHostMap::iterator it = hosts_to_notify.begin();
- it != hosts_to_notify.end(); ++it) {
- AppCacheFrontend* frontend = it->first;
- frontend->OnEventRaised(it->second, event_id);
+ for (auto& pair : hosts_to_notify_) {
+ AppCacheFrontend* frontend = pair.first;
+ frontend->OnEventRaised(pair.second, event_id);
}
}
void SendProgressNotifications(const GURL& url,
int num_total,
int num_complete) {
- for (NotifyHostMap::iterator it = hosts_to_notify.begin();
- it != hosts_to_notify.end(); ++it) {
- AppCacheFrontend* frontend = it->first;
- frontend->OnProgressEventRaised(it->second, url, num_total, num_complete);
+ for (const auto& pair : hosts_to_notify_) {
+ AppCacheFrontend* frontend = pair.first;
+ frontend->OnProgressEventRaised(pair.second, url, num_total,
+ num_complete);
}
}
void SendErrorNotifications(const AppCacheErrorDetails& details) {
DCHECK(!details.message.empty());
- for (NotifyHostMap::iterator it = hosts_to_notify.begin();
- it != hosts_to_notify.end(); ++it) {
- AppCacheFrontend* frontend = it->first;
- frontend->OnErrorEventRaised(it->second, details);
+ for (const auto& pair : hosts_to_notify_) {
+ AppCacheFrontend* frontend = pair.first;
+ frontend->OnErrorEventRaised(pair.second, details);
}
}
void SendLogMessage(const std::string& message) {
- for (NotifyHostMap::iterator it = hosts_to_notify.begin();
- it != hosts_to_notify.end(); ++it) {
- AppCacheFrontend* frontend = it->first;
- for (HostIds::iterator id = it->second.begin(); id != it->second.end();
- ++id) {
- frontend->OnLogMessage(*id, APPCACHE_LOG_WARNING, message);
- }
+ for (const auto& pair : hosts_to_notify_) {
+ AppCacheFrontend* frontend = pair.first;
+ for (const auto& id : pair.second)
+ frontend->OnLogMessage(id, APPCACHE_LOG_WARNING, message);
}
}
private:
- NotifyHostMap hosts_to_notify;
+ NotifyHostMap hosts_to_notify_;
};
AppCacheUpdateJob::UrlToFetch::UrlToFetch(const GURL& url,
bool checked,
@@ -467,13 +460,10 @@ void AppCacheUpdateJob::ContinueHandleManifestFetchCompleted(bool changed) {
inprogress_cache_->InitializeWithManifest(&manifest);
// Associate all pending master hosts with the newly created cache.
- for (PendingMasters::iterator it = pending_master_entries_.begin();
- it != pending_master_entries_.end(); ++it) {
- PendingHosts& hosts = it->second;
- for (PendingHosts::iterator host_it = hosts.begin();
- host_it != hosts.end(); ++host_it) {
- (*host_it)
- ->AssociateIncompleteCache(inprogress_cache_.get(), manifest_url_);
+ for (const auto& pair : pending_master_entries_) {
+ const PendingHosts& hosts = pair.second;
+ for (AppCacheHost* host : hosts) {
+ host->AssociateIncompleteCache(inprogress_cache_.get(), manifest_url_);
}
}
@@ -630,16 +620,12 @@ void AppCacheUpdateJob::HandleMasterEntryFetchCompleted(URLFetcher* fetcher,
if (!inprogress_cache_.get()) {
// TODO(michaeln): defer until the updated cache has been stored
DCHECK(cache == group_->newest_complete_cache());
- for (PendingHosts::iterator host_it = hosts.begin();
- host_it != hosts.end(); ++host_it) {
- (*host_it)->AssociateCompleteCache(cache);
- }
+ for (AppCacheHost* host : hosts)
+ host->AssociateCompleteCache(cache);
}
} else {
HostNotifier host_notifier;
- for (PendingHosts::iterator host_it = hosts.begin();
- host_it != hosts.end(); ++host_it) {
- AppCacheHost* host = *host_it;
+ for (AppCacheHost* host : hosts) {
host_notifier.AddHost(host);
// In downloading case, disassociate host from inprogress cache.
@@ -863,11 +849,8 @@ void AppCacheUpdateJob::AddAllAssociatedHostsToNotifier(
host_notifier->AddHosts(inprogress_cache_->associated_hosts());
}
- AppCacheGroup::Caches old_caches = group_->old_caches();
- for (AppCacheGroup::Caches::const_iterator it = old_caches.begin();
- it != old_caches.end(); ++it) {
- host_notifier->AddHosts((*it)->associated_hosts());
- }
+ for (AppCache* cache : group_->old_caches())
+ host_notifier->AddHosts(cache->associated_hosts());
AppCache* newest_cache = group_->newest_complete_cache();
if (newest_cache)
@@ -942,35 +925,21 @@ void AppCacheUpdateJob::OnManifestDataReadComplete(int result) {
}
void AppCacheUpdateJob::BuildUrlFileList(const AppCacheManifest& manifest) {
- for (base::hash_set<std::string>::const_iterator it =
- manifest.explicit_urls.begin();
- it != manifest.explicit_urls.end(); ++it) {
- AddUrlToFileList(GURL(*it), AppCacheEntry::EXPLICIT);
- }
+ for (const std::string& explicit_url : manifest.explicit_urls)
+ AddUrlToFileList(GURL(explicit_url), AppCacheEntry::EXPLICIT);
- const std::vector<AppCacheNamespace>& intercepts =
- manifest.intercept_namespaces;
- for (std::vector<AppCacheNamespace>::const_iterator it = intercepts.begin();
- it != intercepts.end(); ++it) {
- AddUrlToFileList(it->target_url, AppCacheEntry::INTERCEPT);
- }
+ for (const auto& intercept : manifest.intercept_namespaces)
+ AddUrlToFileList(intercept.target_url, AppCacheEntry::INTERCEPT);
- const std::vector<AppCacheNamespace>& fallbacks =
- manifest.fallback_namespaces;
- for (std::vector<AppCacheNamespace>::const_iterator it = fallbacks.begin();
- it != fallbacks.end(); ++it) {
- AddUrlToFileList(it->target_url, AppCacheEntry::FALLBACK);
- }
+ for (const auto& fallback : manifest.fallback_namespaces)
+ AddUrlToFileList(fallback.target_url, AppCacheEntry::FALLBACK);
// Add all master entries from newest complete cache.
if (update_type_ == UPGRADE_ATTEMPT) {
- const AppCache::EntryMap& entries =
- group_->newest_complete_cache()->entries();
- for (AppCache::EntryMap::const_iterator it = entries.begin();
- it != entries.end(); ++it) {
- const AppCacheEntry& entry = it->second;
+ for (const auto& pair : group_->newest_complete_cache()->entries()) {
+ const AppCacheEntry& entry = pair.second;
if (entry.IsMaster())
- AddUrlToFileList(it->first, AppCacheEntry::MASTER);
+ AddUrlToFileList(pair.first, AppCacheEntry::MASTER);
}
}
}
@@ -1033,10 +1002,8 @@ void AppCacheUpdateJob::FetchUrls() {
void AppCacheUpdateJob::CancelAllUrlFetches() {
// Cancel any pending URL requests.
- for (PendingUrlFetches::iterator it = pending_url_fetches_.begin();
- it != pending_url_fetches_.end(); ++it) {
- delete it->second;
- }
+ for (auto& pair : pending_url_fetches_)
+ delete pair.second;
url_fetches_completed_ +=
pending_url_fetches_.size() + urls_to_fetch_.size();
@@ -1127,10 +1094,8 @@ void AppCacheUpdateJob::FetchMasterEntries() {
PendingMasters::iterator found = pending_master_entries_.find(url);
DCHECK(found != pending_master_entries_.end());
PendingHosts& hosts = found->second;
- for (PendingHosts::iterator host_it = hosts.begin();
- host_it != hosts.end(); ++host_it) {
- (*host_it)->AssociateCompleteCache(cache);
- }
+ for (AppCacheHost* host : hosts)
+ host->AssociateCompleteCache(cache);
}
} else {
URLFetcher* fetcher = new URLFetcher(url, URLFetcher::MASTER_ENTRY_FETCH,
@@ -1151,10 +1116,9 @@ void AppCacheUpdateJob::CancelAllMasterEntryFetches(
// directly.
// Cancel all in-progress fetches.
- for (PendingUrlFetches::iterator it = master_entry_fetches_.begin();
- it != master_entry_fetches_.end(); ++it) {
- delete it->second;
- master_entries_to_fetch_.insert(it->first); // back in unfetched list
+ for (auto& pair : master_entry_fetches_) {
+ delete pair.second;
+ master_entries_to_fetch_.insert(pair.first); // back in unfetched list
}
master_entry_fetches_.clear();
@@ -1169,9 +1133,7 @@ void AppCacheUpdateJob::CancelAllMasterEntryFetches(
PendingMasters::iterator found = pending_master_entries_.find(url);
DCHECK(found != pending_master_entries_.end());
PendingHosts& hosts = found->second;
- for (PendingHosts::iterator host_it = hosts.begin();
- host_it != hosts.end(); ++host_it) {
- AppCacheHost* host = *host_it;
+ for (AppCacheHost* host : hosts) {
host->AssociateNoCache(GURL());
host_notifier.AddHost(host);
host->RemoveObserver(this);
@@ -1340,16 +1302,12 @@ void AppCacheUpdateJob::Cancel() {
manifest_fetcher_ = nullptr;
}
- for (PendingUrlFetches::iterator it = pending_url_fetches_.begin();
- it != pending_url_fetches_.end(); ++it) {
- delete it->second;
- }
+ for (auto& pair : pending_url_fetches_)
+ delete pair.second;
pending_url_fetches_.clear();
- for (PendingUrlFetches::iterator it = master_entry_fetches_.begin();
- it != master_entry_fetches_.end(); ++it) {
- delete it->second;
- }
+ for (auto& pair : master_entry_fetches_)
+ delete pair.second;
master_entry_fetches_.clear();
ClearPendingMasterEntries();
@@ -1363,13 +1321,10 @@ void AppCacheUpdateJob::Cancel() {
}
void AppCacheUpdateJob::ClearPendingMasterEntries() {
- for (PendingMasters::iterator it = pending_master_entries_.begin();
- it != pending_master_entries_.end(); ++it) {
- PendingHosts& hosts = it->second;
- for (PendingHosts::iterator host_it = hosts.begin();
- host_it != hosts.end(); ++host_it) {
- (*host_it)->RemoveObserver(this);
- }
+ for (auto& pair : pending_master_entries_) {
+ PendingHosts& hosts = pair.second;
+ for (AppCacheHost* host : hosts)
+ host->RemoveObserver(this);
}
pending_master_entries_.clear();
@@ -1390,10 +1345,8 @@ void AppCacheUpdateJob::DiscardInprogressCache() {
if (!inprogress_cache_.get()) {
// We have to undo the changes we made, if any, to the existing cache.
if (group_ && group_->newest_complete_cache()) {
- for (std::vector<GURL>::iterator iter = added_master_entries_.begin();
- iter != added_master_entries_.end(); ++iter) {
- group_->newest_complete_cache()->RemoveEntry(*iter);
- }
+ for (auto& url : added_master_entries_)
+ group_->newest_complete_cache()->RemoveEntry(url);
}
added_master_entries_.clear();
return;
@@ -1413,7 +1366,8 @@ void AppCacheUpdateJob::DiscardDuplicateResponses() {
void AppCacheUpdateJob::LogHistogramStats(
ResultType result, const GURL& failed_resource_url) {
- AppCacheHistograms::CountUpdateJobResult(result, manifest_url_.GetOrigin());
+ AppCacheHistograms::CountUpdateJobResult(result,
+ url::Origin::Create(manifest_url_));
if (result == UPDATE_OK)
return;
@@ -1436,9 +1390,7 @@ void AppCacheUpdateJob::LogHistogramStats(
(failed_resource_url.GetOrigin() != manifest_url_.GetOrigin());
AppCacheHistograms::LogUpdateFailureStats(
- manifest_url_.GetOrigin(),
- percent_complete,
- was_making_progress,
+ url::Origin::Create(manifest_url_), percent_complete, was_making_progress,
off_origin_resource_failure);
}
diff --git a/chromium/content/browser/appcache/appcache_update_job.h b/chromium/content/browser/appcache/appcache_update_job.h
index 6b75f215fe7..262da887387 100644
--- a/chromium/content/browser/appcache/appcache_update_job.h
+++ b/chromium/content/browser/appcache/appcache_update_job.h
@@ -72,10 +72,10 @@ class CONTENT_EXPORT AppCacheUpdateJob
// Master entries have multiple hosts, for example, the same page is opened
// in different tabs.
- typedef std::vector<AppCacheHost*> PendingHosts;
- typedef std::map<GURL, PendingHosts> PendingMasters;
- typedef std::map<GURL, URLFetcher*> PendingUrlFetches;
- typedef std::map<int64_t, GURL> LoadingResponses;
+ using PendingHosts = std::vector<AppCacheHost*>;
+ using PendingMasters = std::map<GURL, PendingHosts>;
+ using PendingUrlFetches = std::map<GURL, URLFetcher*>;
+ using LoadingResponses = std::map<int64_t, GURL>;
static const int kRerunDelayMs = 1000;
diff --git a/chromium/content/browser/appcache/appcache_update_job_unittest.cc b/chromium/content/browser/appcache/appcache_update_job_unittest.cc
index c78e912c2aa..c02b0f17956 100644
--- a/chromium/content/browser/appcache/appcache_update_job_unittest.cc
+++ b/chromium/content/browser/appcache/appcache_update_job_unittest.cc
@@ -261,11 +261,9 @@ class MockFrontend : public AppCacheFrontend {
// Trigger additional updates if requested.
if (event_id == start_update_trigger_ && update_) {
- for (std::vector<AppCacheHost*>::iterator it = update_hosts_.begin();
- it != update_hosts_.end(); ++it) {
- AppCacheHost* host = *it;
- update_->StartUpdate(host,
- (host ? host->pending_master_entry_url() : GURL()));
+ for (AppCacheHost* host : update_hosts_) {
+ update_->StartUpdate(
+ host, (host ? host->pending_master_entry_url() : GURL()));
}
update_hosts_.clear(); // only trigger once
}
@@ -349,9 +347,9 @@ class MockFrontend : public AppCacheFrontend {
update_hosts_.push_back(host);
}
- typedef std::vector<int> HostIds;
- typedef std::pair<HostIds, AppCacheEventID> RaisedEvent;
- typedef std::vector<RaisedEvent> RaisedEvents;
+ using HostIds = std::vector<int>;
+ using RaisedEvent = std::pair<HostIds, AppCacheEventID>;
+ using RaisedEvents = std::vector<RaisedEvent>;
RaisedEvents raised_events_;
std::string error_message_;
@@ -626,7 +624,7 @@ class MockURLLoaderFactory : public network::mojom::URLLoaderFactory {
response.headers = info.headers;
response.headers->GetMimeType(&response.mime_type);
- client->OnReceiveResponse(response, base::nullopt, nullptr);
+ client->OnReceiveResponse(response, nullptr);
mojo::DataPipe data_pipe;
@@ -3607,22 +3605,19 @@ class AppCacheUpdateJobTest : public testing::TestWithParam<RequestHandlerType>,
EXPECT_TRUE(storage->IsCacheStored(group_->newest_complete_cache()));
// Check that all entries in the newest cache were stored.
- const AppCache::EntryMap& entries =
- group_->newest_complete_cache()->entries();
- for (AppCache::EntryMap::const_iterator it = entries.begin();
- it != entries.end(); ++it) {
- EXPECT_NE(kAppCacheNoResponseId, it->second.response_id());
+ for (const auto& pair : group_->newest_complete_cache()->entries()) {
+ EXPECT_NE(kAppCacheNoResponseId, pair.second.response_id());
// Check that any copied entries have the expected response id
// and that entries that are not copied have a different response id.
std::map<GURL, int64_t>::iterator found =
- expect_response_ids_.find(it->first);
+ expect_response_ids_.find(pair.first);
if (found != expect_response_ids_.end()) {
- EXPECT_EQ(found->second, it->second.response_id());
+ EXPECT_EQ(found->second, pair.second.response_id());
} else if (expect_old_cache_) {
- AppCacheEntry* old_entry = expect_old_cache_->GetEntry(it->first);
+ AppCacheEntry* old_entry = expect_old_cache_->GetEntry(pair.first);
if (old_entry)
- EXPECT_NE(old_entry->response_id(), it->second.response_id());
+ EXPECT_NE(old_entry->response_id(), pair.second.response_id());
}
}
}
@@ -3712,11 +3707,10 @@ class AppCacheUpdateJobTest : public testing::TestWithParam<RequestHandlerType>,
ASSERT_TRUE(entry);
EXPECT_EQ(AppCacheEntry::FALLBACK, entry->types());
- for (AppCache::EntryMap::iterator i = expect_extra_entries_.begin();
- i != expect_extra_entries_.end(); ++i) {
- entry = cache->GetEntry(i->first);
+ for (const auto& pair : expect_extra_entries_) {
+ entry = cache->GetEntry(pair.first);
ASSERT_TRUE(entry);
- EXPECT_EQ(i->second.types(), entry->types());
+ EXPECT_EQ(pair.second.types(), entry->types());
}
expected = 1;
@@ -3874,7 +3868,7 @@ class AppCacheUpdateJobTest : public testing::TestWithParam<RequestHandlerType>,
// Response infos used by an async test that need to live until update job
// finishes.
- std::vector<scoped_refptr<AppCacheResponseInfo> > response_infos_;
+ std::vector<scoped_refptr<AppCacheResponseInfo>> response_infos_;
// Flag indicating if test cares to verify the update after update finishes.
bool do_checks_after_update_finished_;
diff --git a/chromium/content/browser/appcache/appcache_update_url_loader_request.cc b/chromium/content/browser/appcache/appcache_update_url_loader_request.cc
index 814400fb622..321e4fad8ba 100644
--- a/chromium/content/browser/appcache/appcache_update_url_loader_request.cc
+++ b/chromium/content/browser/appcache/appcache_update_url_loader_request.cc
@@ -21,7 +21,6 @@ void AppCacheUpdateJob::UpdateURLLoaderRequest::Start() {
network::mojom::URLLoaderClientPtr client;
client_binding_.Bind(mojo::MakeRequest(&client));
- DCHECK(loader_factory_getter_->GetNetworkFactory());
loader_factory_getter_->GetNetworkFactory()->CreateLoaderAndStart(
mojo::MakeRequest(&url_loader_), -1, -1,
network::mojom::kURLLoadOptionNone, request_, std::move(client),
@@ -96,7 +95,6 @@ int AppCacheUpdateJob::UpdateURLLoaderRequest::Cancel() {
void AppCacheUpdateJob::UpdateURLLoaderRequest::OnReceiveResponse(
const network::ResourceResponseHead& response_head,
- const base::Optional<net::SSLInfo>& ssl_info,
network::mojom::DownloadedTempFilePtr downloaded_file) {
response_ = response_head;
@@ -105,8 +103,8 @@ void AppCacheUpdateJob::UpdateURLLoaderRequest::OnReceiveResponse(
// have a helper function which populates the HttpResponseInfo structure from
// the ResourceResponseHead structure.
http_response_info_.reset(new net::HttpResponseInfo());
- if (ssl_info.has_value())
- http_response_info_->ssl_info = *ssl_info;
+ if (response_head.ssl_info.has_value())
+ http_response_info_->ssl_info = *response_head.ssl_info;
http_response_info_->headers = response_head.headers;
http_response_info_->was_fetched_via_spdy =
response_head.was_fetched_via_spdy;
@@ -178,7 +176,9 @@ AppCacheUpdateJob::UpdateURLLoaderRequest::UpdateURLLoaderRequest(
loader_factory_getter_(loader_factory_getter),
client_binding_(this),
buffer_size_(buffer_size),
- handle_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL),
+ handle_watcher_(FROM_HERE,
+ mojo::SimpleWatcher::ArmingPolicy::MANUAL,
+ base::SequencedTaskRunnerHandle::Get()),
read_requested_(false) {
request_.url = url;
request_.method = "GET";
diff --git a/chromium/content/browser/appcache/appcache_update_url_loader_request.h b/chromium/content/browser/appcache/appcache_update_url_loader_request.h
index 5f36946b587..e7279f62572 100644
--- a/chromium/content/browser/appcache/appcache_update_url_loader_request.h
+++ b/chromium/content/browser/appcache/appcache_update_url_loader_request.h
@@ -55,7 +55,6 @@ class AppCacheUpdateJob::UpdateURLLoaderRequest
// These methods are called by the network loader.
void OnReceiveResponse(
const network::ResourceResponseHead& response_head,
- const base::Optional<net::SSLInfo>& ssl_info,
network::mojom::DownloadedTempFilePtr downloaded_file) override;
void OnReceiveRedirect(
const net::RedirectInfo& redirect_info,
diff --git a/chromium/content/browser/appcache/appcache_url_loader_job.cc b/chromium/content/browser/appcache/appcache_url_loader_job.cc
index 7add0b05bc5..520195a6ca8 100644
--- a/chromium/content/browser/appcache/appcache_url_loader_job.cc
+++ b/chromium/content/browser/appcache/appcache_url_loader_job.cc
@@ -138,14 +138,15 @@ void AppCacheURLLoaderJob::Start(network::mojom::URLLoaderRequest request,
AppCacheURLLoaderJob::AppCacheURLLoaderJob(
AppCacheURLLoaderRequest* appcache_request,
AppCacheStorage* storage,
- URLLoaderRequestHandler::LoaderCallback loader_callback)
+ NavigationLoaderInterceptor::LoaderCallback loader_callback)
: storage_(storage->GetWeakPtr()),
start_time_tick_(base::TimeTicks::Now()),
cache_id_(kAppCacheNoCacheId),
is_fallback_(false),
binding_(this),
writable_handle_watcher_(FROM_HERE,
- mojo::SimpleWatcher::ArmingPolicy::MANUAL),
+ mojo::SimpleWatcher::ArmingPolicy::MANUAL,
+ base::SequencedTaskRunnerHandle::Get()),
loader_callback_(std::move(loader_callback)),
appcache_request_(appcache_request->GetWeakPtr()),
is_main_resource_load_(IsResourceTypeFrame(static_cast<ResourceType>(
@@ -205,8 +206,8 @@ void AppCacheURLLoaderJob::OnResponseInfoLoaded(
// See http://code.google.com/p/chromium/issues/detail?id=50657
storage_->service()->CheckAppCacheResponse(manifest_url_, cache_id_,
entry_.response_id());
- AppCacheHistograms::CountResponseRetrieval(false, is_main_resource_load_,
- manifest_url_.GetOrigin());
+ AppCacheHistograms::CountResponseRetrieval(
+ false, is_main_resource_load_, url::Origin::Create(manifest_url_));
}
cache_entry_not_found_ = true;
@@ -281,9 +282,11 @@ void AppCacheURLLoaderJob::SendResponseInfo() {
response_head.was_fetched_via_spdy = http_info->was_fetched_via_spdy;
response_head.was_alpn_negotiated = http_info->was_alpn_negotiated;
response_head.alpn_negotiated_protocol = http_info->alpn_negotiated_protocol;
+ if (http_info->ssl_info.cert)
+ response_head.ssl_info = http_info->ssl_info;
response_head.load_timing = load_timing_info_;
- client_->OnReceiveResponse(response_head, http_info->ssl_info,
+ client_->OnReceiveResponse(response_head,
network::mojom::DownloadedTempFilePtr());
client_->OnStartLoadingResponseBody(std::move(data_pipe_.consumer_handle));
}
@@ -341,7 +344,8 @@ void AppCacheURLLoaderJob::NotifyCompleted(int error_code) {
if (delivery_type_ == APPCACHED_DELIVERY) {
AppCacheHistograms::CountResponseRetrieval(
- error_code == 0, is_main_resource_load_, manifest_url_.GetOrigin());
+ error_code == 0, is_main_resource_load_,
+ url::Origin::Create(manifest_url_));
}
}
diff --git a/chromium/content/browser/appcache/appcache_url_loader_job.h b/chromium/content/browser/appcache/appcache_url_loader_job.h
index c7a79ed16c2..f64748dc4a4 100644
--- a/chromium/content/browser/appcache/appcache_url_loader_job.h
+++ b/chromium/content/browser/appcache/appcache_url_loader_job.h
@@ -15,7 +15,7 @@
#include "content/browser/appcache/appcache_request_handler.h"
#include "content/browser/appcache/appcache_response.h"
#include "content/browser/appcache/appcache_storage.h"
-#include "content/browser/loader/url_loader_request_handler.h"
+#include "content/browser/loader/navigation_loader_interceptor.h"
#include "content/common/content_export.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "mojo/public/cpp/system/data_pipe.h"
@@ -68,9 +68,10 @@ class CONTENT_EXPORT AppCacheURLLoaderJob : public AppCacheJob,
// AppCacheRequestHandler::CreateJob() creates this instance.
friend class AppCacheRequestHandler;
- AppCacheURLLoaderJob(AppCacheURLLoaderRequest* appcache_request,
- AppCacheStorage* storage,
- URLLoaderRequestHandler::LoaderCallback loader_callback);
+ AppCacheURLLoaderJob(
+ AppCacheURLLoaderRequest* appcache_request,
+ AppCacheStorage* storage,
+ NavigationLoaderInterceptor::LoaderCallback loader_callback);
// Invokes the loader callback which is expected to setup the mojo binding.
void CallLoaderCallback();
@@ -121,7 +122,7 @@ class CONTENT_EXPORT AppCacheURLLoaderJob : public AppCacheJob,
// The Callback to be invoked in the network service land to indicate if
// the resource request can be serviced via the AppCache.
- URLLoaderRequestHandler::LoaderCallback loader_callback_;
+ NavigationLoaderInterceptor::LoaderCallback loader_callback_;
// The AppCacheRequest instance, used to inform the loader job about range
// request headers. Not owned by this class.
diff --git a/chromium/content/browser/appcache/appcache_url_request_job.cc b/chromium/content/browser/appcache/appcache_url_request_job.cc
index c68a8a68f65..70fd5664338 100644
--- a/chromium/content/browser/appcache/appcache_url_request_job.cc
+++ b/chromium/content/browser/appcache/appcache_url_request_job.cc
@@ -204,7 +204,7 @@ void AppCacheURLRequestJob::OnResponseInfoLoaded(
storage_->service()->CheckAppCacheResponse(manifest_url_, cache_id_,
entry_.response_id());
AppCacheHistograms::CountResponseRetrieval(
- false, is_main_resource_, manifest_url_.GetOrigin());
+ false, is_main_resource_, url::Origin::Create(manifest_url_));
}
cache_entry_not_found_ = true;
@@ -229,14 +229,14 @@ void AppCacheURLRequestJob::OnReadComplete(int result) {
DCHECK(IsDeliveringAppCacheResponse());
if (result == 0) {
AppCacheHistograms::CountResponseRetrieval(
- true, is_main_resource_, manifest_url_.GetOrigin());
+ true, is_main_resource_, url::Origin::Create(manifest_url_));
} else if (result < 0) {
if (storage_->service()->storage() == storage_) {
storage_->service()->CheckAppCacheResponse(manifest_url_, cache_id_,
entry_.response_id());
}
AppCacheHistograms::CountResponseRetrieval(
- false, is_main_resource_, manifest_url_.GetOrigin());
+ false, is_main_resource_, url::Origin::Create(manifest_url_));
}
ReadRawDataComplete(result);
}
diff --git a/chromium/content/browser/appcache/appcache_working_set.cc b/chromium/content/browser/appcache/appcache_working_set.cc
index 646068406d2..9a55fdb0235 100644
--- a/chromium/content/browser/appcache/appcache_working_set.cc
+++ b/chromium/content/browser/appcache/appcache_working_set.cc
@@ -48,19 +48,20 @@ void AppCacheWorkingSet::AddGroup(AppCacheGroup* group) {
const GURL& url = group->manifest_url();
DCHECK(groups_.find(url) == groups_.end());
groups_.insert(GroupMap::value_type(url, group));
- groups_by_origin_[url.GetOrigin()].insert(GroupMap::value_type(url, group));
+ groups_by_origin_[url::Origin::Create(url)].insert(
+ GroupMap::value_type(url, group));
}
void AppCacheWorkingSet::RemoveGroup(AppCacheGroup* group) {
const GURL& url = group->manifest_url();
groups_.erase(url);
- GURL origin_url = url.GetOrigin();
- GroupMap* groups_in_origin = GetMutableGroupsInOrigin(origin_url);
+ const url::Origin origin(url::Origin::Create(url));
+ GroupMap* groups_in_origin = GetMutableGroupsInOrigin(origin);
if (groups_in_origin) {
groups_in_origin->erase(url);
if (groups_in_origin->empty())
- groups_by_origin_.erase(origin_url);
+ groups_by_origin_.erase(origin);
}
}
diff --git a/chromium/content/browser/appcache/appcache_working_set.h b/chromium/content/browser/appcache/appcache_working_set.h
index e9483b6c357..4d8fa0a9856 100644
--- a/chromium/content/browser/appcache/appcache_working_set.h
+++ b/chromium/content/browser/appcache/appcache_working_set.h
@@ -12,6 +12,7 @@
#include "base/containers/hash_tables.h"
#include "content/common/content_export.h"
#include "url/gurl.h"
+#include "url/origin.h"
namespace content {
@@ -23,7 +24,7 @@ class AppCacheResponseInfo;
// currently in memory.
class CONTENT_EXPORT AppCacheWorkingSet {
public:
- typedef std::map<GURL, AppCacheGroup*> GroupMap;
+ using GroupMap = std::map<GURL, AppCacheGroup*>;
AppCacheWorkingSet();
~AppCacheWorkingSet();
@@ -45,8 +46,8 @@ class CONTENT_EXPORT AppCacheWorkingSet {
return (it != groups_.end()) ? it->second : NULL;
}
- const GroupMap* GetGroupsInOrigin(const GURL& origin_url) {
- return GetMutableGroupsInOrigin(origin_url);
+ const GroupMap* GetGroupsInOrigin(const url::Origin& origin) {
+ return GetMutableGroupsInOrigin(origin);
}
void AddResponseInfo(AppCacheResponseInfo* response_info);
@@ -57,12 +58,12 @@ class CONTENT_EXPORT AppCacheWorkingSet {
}
private:
- typedef base::hash_map<int64_t, AppCache*> CacheMap;
- typedef std::map<GURL, GroupMap> GroupsByOriginMap;
- typedef base::hash_map<int64_t, AppCacheResponseInfo*> ResponseInfoMap;
+ using CacheMap = base::hash_map<int64_t, AppCache*>;
+ using GroupsByOriginMap = std::map<url::Origin, GroupMap>;
+ using ResponseInfoMap = base::hash_map<int64_t, AppCacheResponseInfo*>;
- GroupMap* GetMutableGroupsInOrigin(const GURL& origin_url) {
- GroupsByOriginMap::iterator it = groups_by_origin_.find(origin_url);
+ GroupMap* GetMutableGroupsInOrigin(const url::Origin& origin) {
+ GroupsByOriginMap::iterator it = groups_by_origin_.find(origin);
return (it != groups_by_origin_.end()) ? &it->second : NULL;
}
diff --git a/chromium/content/browser/appcache/chrome_appcache_service.cc b/chromium/content/browser/appcache/chrome_appcache_service.cc
index d639909ef0d..89ccb9a8250 100644
--- a/chromium/content/browser/appcache/chrome_appcache_service.cc
+++ b/chromium/content/browser/appcache/chrome_appcache_service.cc
@@ -75,7 +75,7 @@ void ChromeAppCacheService::DeleteOnCorrectThread() const {
delete this;
return;
}
- if (BrowserThread::IsMessageLoopValid(BrowserThread::IO)) {
+ if (BrowserThread::IsThreadInitialized(BrowserThread::IO)) {
BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, this);
return;
}
diff --git a/chromium/content/browser/appcache/chrome_appcache_service_unittest.cc b/chromium/content/browser/appcache/chrome_appcache_service_unittest.cc
index 2db6bb0e092..1e5688dadd6 100644
--- a/chromium/content/browser/appcache/chrome_appcache_service_unittest.cc
+++ b/chromium/content/browser/appcache/chrome_appcache_service_unittest.cc
@@ -130,12 +130,14 @@ void ChromeAppCacheServiceTest::InsertDataIntoAppCache(
appcache_helper.AddGroupAndCache(appcache_service, kSessionOnlyManifestURL);
// Verify that adding the data succeeded
- std::set<GURL> origins;
+ std::set<url::Origin> origins;
appcache_helper.GetOriginsWithCaches(appcache_service, &origins);
ASSERT_EQ(3UL, origins.size());
- ASSERT_TRUE(origins.find(kProtectedManifestURL.GetOrigin()) != origins.end());
- ASSERT_TRUE(origins.find(kNormalManifestURL.GetOrigin()) != origins.end());
- ASSERT_TRUE(origins.find(kSessionOnlyManifestURL.GetOrigin()) !=
+ ASSERT_TRUE(origins.find(url::Origin::Create(kProtectedManifestURL)) !=
+ origins.end());
+ ASSERT_TRUE(origins.find(url::Origin::Create(kNormalManifestURL)) !=
+ origins.end());
+ ASSERT_TRUE(origins.find(url::Origin::Create(kSessionOnlyManifestURL)) !=
origins.end());
}
@@ -163,12 +165,14 @@ TEST_F(ChromeAppCacheServiceTest, KeepOnDestruction) {
// The appcache data is also there, except the session-only origin.
AppCacheTestHelper appcache_helper;
- std::set<GURL> origins;
+ std::set<url::Origin> origins;
appcache_helper.GetOriginsWithCaches(appcache_service.get(), &origins);
EXPECT_EQ(2UL, origins.size());
- EXPECT_TRUE(origins.find(kProtectedManifestURL.GetOrigin()) != origins.end());
- EXPECT_TRUE(origins.find(kNormalManifestURL.GetOrigin()) != origins.end());
- EXPECT_TRUE(origins.find(kSessionOnlyManifestURL.GetOrigin()) ==
+ EXPECT_TRUE(origins.find(url::Origin::Create(kProtectedManifestURL)) !=
+ origins.end());
+ EXPECT_TRUE(origins.find(url::Origin::Create(kNormalManifestURL)) !=
+ origins.end());
+ EXPECT_TRUE(origins.find(url::Origin::Create(kSessionOnlyManifestURL)) ==
origins.end());
// Delete and let cleanup tasks run prior to returning.
@@ -203,12 +207,14 @@ TEST_F(ChromeAppCacheServiceTest, SaveSessionState) {
// No appcache data was deleted.
AppCacheTestHelper appcache_helper;
- std::set<GURL> origins;
+ std::set<url::Origin> origins;
appcache_helper.GetOriginsWithCaches(appcache_service.get(), &origins);
EXPECT_EQ(3UL, origins.size());
- EXPECT_TRUE(origins.find(kProtectedManifestURL.GetOrigin()) != origins.end());
- EXPECT_TRUE(origins.find(kNormalManifestURL.GetOrigin()) != origins.end());
- EXPECT_TRUE(origins.find(kSessionOnlyManifestURL.GetOrigin()) !=
+ EXPECT_TRUE(origins.find(url::Origin::Create(kProtectedManifestURL)) !=
+ origins.end());
+ EXPECT_TRUE(origins.find(url::Origin::Create(kNormalManifestURL)) !=
+ origins.end());
+ EXPECT_TRUE(origins.find(url::Origin::Create(kSessionOnlyManifestURL)) !=
origins.end());
// Delete and let cleanup tasks run prior to returning.
diff --git a/chromium/content/browser/appcache/mock_appcache_service.cc b/chromium/content/browser/appcache/mock_appcache_service.cc
index 20efcfe9261..da773f185db 100644
--- a/chromium/content/browser/appcache/mock_appcache_service.cc
+++ b/chromium/content/browser/appcache/mock_appcache_service.cc
@@ -17,7 +17,8 @@ static void DeferredCallCallback(
}
void MockAppCacheService::DeleteAppCachesForOrigin(
- const GURL& origin, const net::CompletionCallback& callback) {
+ const url::Origin& origin,
+ const net::CompletionCallback& callback) {
++delete_called_count_;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&DeferredCallCallback, callback,
diff --git a/chromium/content/browser/appcache/mock_appcache_service.h b/chromium/content/browser/appcache/mock_appcache_service.h
index 5e384201e4c..51ac9c76591 100644
--- a/chromium/content/browser/appcache/mock_appcache_service.h
+++ b/chromium/content/browser/appcache/mock_appcache_service.h
@@ -25,7 +25,7 @@ class MockAppCacheService : public AppCacheServiceImpl {
// Just returns a canned completion code without actually
// removing groups and caches in our mock storage instance.
void DeleteAppCachesForOrigin(
- const GURL& origin,
+ const url::Origin& origin,
const net::CompletionCallback& callback) override;
void set_quota_manager_proxy(storage::QuotaManagerProxy* proxy) {
diff --git a/chromium/content/browser/appcache/mock_appcache_storage.cc b/chromium/content/browser/appcache/mock_appcache_storage.cc
index b9ff16c792c..79bf39b087e 100644
--- a/chromium/content/browser/appcache/mock_appcache_storage.cc
+++ b/chromium/content/browser/appcache/mock_appcache_storage.cc
@@ -191,11 +191,8 @@ void MockAppCacheStorage::DeleteResponses(
const std::vector<int64_t>& response_ids) {
// We don't bother with actually removing responses from the disk-cache,
// just keep track of which ids have been doomed or deleted
- std::vector<int64_t>::const_iterator it = response_ids.begin();
- while (it != response_ids.end()) {
- doomed_response_ids_.insert(*it);
- ++it;
- }
+ for (const auto& id : response_ids)
+ doomed_response_ids_.insert(id);
}
bool MockAppCacheStorage::IsInitialized() {
@@ -353,9 +350,8 @@ void MockAppCacheStorage::ProcessFindResponseForMainRequest(
FoundCandidate found_fallback_candidate;
GURL found_fallback_candidate_namespace;
- for (StoredGroupMap::const_iterator it = stored_groups_.begin();
- it != stored_groups_.end(); ++it) {
- AppCacheGroup* group = it->second.get();
+ for (const auto& pair : stored_groups_) {
+ AppCacheGroup* group = pair.second.get();
AppCache* cache = group->newest_complete_cache();
if (group->is_obsolete() || !cache ||
(url.GetOrigin() != group->manifest_url().GetOrigin())) {
@@ -501,11 +497,8 @@ void MockAppCacheStorage::RemoveStoredCache(AppCache* cache) {
void MockAppCacheStorage::RemoveStoredCaches(
const AppCacheGroup::Caches& caches) {
- AppCacheGroup::Caches::const_iterator it = caches.begin();
- while (it != caches.end()) {
- RemoveStoredCache(*it);
- ++it;
- }
+ for (AppCache* cache : caches)
+ RemoveStoredCache(cache);
}
void MockAppCacheStorage::AddStoredGroup(AppCacheGroup* group) {
@@ -541,13 +534,10 @@ bool MockAppCacheStorage::ShouldGroupLoadAppearAsync(
// If any of the old caches are "in use", then the group must also
// be memory resident and not require async loading.
- const AppCacheGroup::Caches& old_caches = group->old_caches();
- AppCacheGroup::Caches::const_iterator it = old_caches.begin();
- while (it != old_caches.end()) {
+ for (const AppCache* cache : group->old_caches()) {
// "in use" caches don't require async loading
- if (!ShouldCacheLoadAppearAsync(*it))
+ if (!ShouldCacheLoadAppearAsync(cache))
return false;
- ++it;
}
return true;
diff --git a/chromium/content/browser/appcache/mock_appcache_storage.h b/chromium/content/browser/appcache/mock_appcache_storage.h
index 8605a471fcf..09a1fbd0722 100644
--- a/chromium/content/browser/appcache/mock_appcache_storage.h
+++ b/chromium/content/browser/appcache/mock_appcache_storage.h
@@ -93,11 +93,11 @@ class MockAppCacheStorage : public AppCacheStorage {
friend class appcache_update_job_unittest::AppCacheUpdateJobTest;
friend class MockAppCacheStorageTest;
- typedef base::hash_map<int64_t, scoped_refptr<AppCache>> StoredCacheMap;
- typedef std::map<GURL, scoped_refptr<AppCacheGroup> > StoredGroupMap;
- typedef std::set<int64_t> DoomedResponseIds;
- typedef std::map<int64_t, std::pair<base::Time, base::Time>>
- StoredEvictionTimesMap;
+ using StoredCacheMap = base::hash_map<int64_t, scoped_refptr<AppCache>>;
+ using StoredGroupMap = std::map<GURL, scoped_refptr<AppCacheGroup>>;
+ using DoomedResponseIds = std::set<int64_t>;
+ using StoredEvictionTimesMap =
+ std::map<int64_t, std::pair<base::Time, base::Time>>;
void ProcessGetAllInfo(scoped_refptr<DelegateReference> delegate_ref);
void ProcessLoadCache(int64_t id,
diff --git a/chromium/content/browser/background_fetch/DEPS b/chromium/content/browser/background_fetch/DEPS
index c0c3af0fbea..0cf92f853e8 100644
--- a/chromium/content/browser/background_fetch/DEPS
+++ b/chromium/content/browser/background_fetch/DEPS
@@ -1,3 +1,3 @@
include_rules = [
- "+third_party/WebKit/public/platform/modules/background_fetch/background_fetch.mojom.h",
+ "+third_party/blink/public/platform/modules/background_fetch/background_fetch.mojom.h",
]
diff --git a/chromium/content/browser/background_fetch/OWNERS b/chromium/content/browser/background_fetch/OWNERS
index 317a5576e9a..a7cd217e75b 100644
--- a/chromium/content/browser/background_fetch/OWNERS
+++ b/chromium/content/browser/background_fetch/OWNERS
@@ -1,9 +1,10 @@
# This OWNERS file also covers:
#
+# //chrome/browser/background_fetch/
# //content/common/background_fetch/
+awdf@chromium.org
peter@chromium.org
-johnme@chromium.org
delphick@chromium.org
# TEAM: platform-capabilities@chromium.org
diff --git a/chromium/content/browser/background_fetch/background_fetch.proto b/chromium/content/browser/background_fetch/background_fetch.proto
index 01e7c359d22..b33f8003e4b 100644
--- a/chromium/content/browser/background_fetch/background_fetch.proto
+++ b/chromium/content/browser/background_fetch/background_fetch.proto
@@ -9,8 +9,9 @@ option optimize_for = LITE_RUNTIME;
package content.proto;
// Stores per-registration (as opposed to per-request) data.
+// https://wicg.github.io/background-fetch/#background-fetch-registration
//
-// Next tag: 5
+// Next Tag: 7
message BackgroundFetchRegistration {
// See definition of |unique_id| in BackgroundFetchRegistrationId.
optional string unique_id = 1;
@@ -18,7 +19,58 @@ message BackgroundFetchRegistration {
// See definition of |developer_id| in BackgroundFetchRegistrationId.
optional bytes developer_id = 2;
- optional string origin = 3;
+ optional uint64 upload_total = 3;
+ optional uint64 uploaded = 4;
+ optional uint64 download_total = 5;
+ optional uint64 downloaded = 6;
+}
+
+// Developer provided options.
+// https://wicg.github.io/background-fetch/#background-fetch-manager
+//
+// Next Tag: 4
+message BackgroundFetchOptions {
+ optional string title = 1;
+
+ // https://w3c.github.io/manifest/#icons-member
+ // Note that sizes can have multiple values (e.g. "32x32 64x64").
+ //
+ // Next Tag: 4
+ message IconDefinition {
+ optional string src = 1;
+ optional string sizes = 2;
+ optional string type = 3;
+ }
+
+ // Example value:
+ // icons: {
+ // src: "icon/lowres.webp"
+ // sizes: "48x48"
+ // type: "image/webp"
+ // }
+ // icons: {
+ // src: "icon/hd_hi.ico"
+ // sizes: "72x72 96x96 128x128 256x256"
+ // }
+ repeated IconDefinition icons = 2;
+
+ optional uint64 download_total = 3;
+}
+
+// Stores information about the background fetch that will be persisted
+// in memory. This information should be everything needed to reconstruct
+// the state of an interrupted background fetch.
+//
+// Next Tag: 6
+message BackgroundFetchMetadata {
+ optional int64 creation_microseconds_since_unix_epoch = 1;
+ optional string origin = 2;
+
+ optional BackgroundFetchRegistration registration = 3;
+ optional BackgroundFetchOptions options = 4;
- optional int64 creation_microseconds_since_unix_epoch = 4;
+ // Defaults to BackgroundFetchOptions.title.
+ // Can be updated by calling `BackgroundFetchUpdateEvent.updateUI`.
+ // https://wicg.github.io/background-fetch/#backgroundfetchupdateevent.
+ optional string ui_title = 5;
}
diff --git a/chromium/content/browser/background_fetch/background_fetch_context.cc b/chromium/content/browser/background_fetch/background_fetch_context.cc
index 1b33d19ec60..572933b7540 100644
--- a/chromium/content/browser/background_fetch/background_fetch_context.cc
+++ b/chromium/content/browser/background_fetch/background_fetch_context.cc
@@ -103,19 +103,28 @@ void BackgroundFetchContext::StartFetch(
const BackgroundFetchRegistrationId& registration_id,
const std::vector<ServiceWorkerFetchRequest>& requests,
const BackgroundFetchOptions& options,
+ const SkBitmap& icon,
blink::mojom::BackgroundFetchService::FetchCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
data_manager_.CreateRegistration(
- registration_id, requests, options,
+ registration_id, requests, options, icon,
base::BindOnce(&BackgroundFetchContext::DidCreateRegistration,
- weak_factory_.GetWeakPtr(), registration_id, options,
+ weak_factory_.GetWeakPtr(), registration_id, options, icon,
std::move(callback)));
}
+void BackgroundFetchContext::GetIconDisplaySize(
+ blink::mojom::BackgroundFetchService::GetIconDisplaySizeCallback callback) {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+
+ delegate_proxy_.GetIconDisplaySize(std::move(callback));
+}
+
void BackgroundFetchContext::DidCreateRegistration(
const BackgroundFetchRegistrationId& registration_id,
const BackgroundFetchOptions& options,
+ const SkBitmap& icon,
blink::mojom::BackgroundFetchService::FetchCallback callback,
blink::mojom::BackgroundFetchError error,
std::unique_ptr<BackgroundFetchRegistration> registration) {
@@ -129,7 +138,7 @@ void BackgroundFetchContext::DidCreateRegistration(
DCHECK(registration);
// Create the BackgroundFetchJobController to do the actual fetching.
- CreateController(registration_id, options, *registration.get());
+ CreateController(registration_id, options, icon, *registration.get());
std::move(callback).Run(error, *registration.get());
}
@@ -140,23 +149,23 @@ void BackgroundFetchContext::AddRegistrationObserver(
}
void BackgroundFetchContext::UpdateUI(
- const std::string& unique_id,
+ const BackgroundFetchRegistrationId& registration_id,
const std::string& title,
blink::mojom::BackgroundFetchService::UpdateUICallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
// The registration must a) still be active, or b) have completed/failed (not
// aborted) with the waitUntil promise from that event not yet resolved.
- if (!job_controllers_.count(unique_id)) {
+ if (!job_controllers_.count(registration_id.unique_id())) {
std::move(callback).Run(blink::mojom::BackgroundFetchError::INVALID_ID);
return;
}
data_manager_.UpdateRegistrationUI(
- unique_id, title,
+ registration_id, title,
base::BindOnce(&BackgroundFetchContext::DidUpdateStoredUI,
- weak_factory_.GetWeakPtr(), unique_id, title,
- std::move(callback)));
+ weak_factory_.GetWeakPtr(), registration_id.unique_id(),
+ title, std::move(callback)));
}
void BackgroundFetchContext::DidUpdateStoredUI(
@@ -180,11 +189,12 @@ void BackgroundFetchContext::DidUpdateStoredUI(
void BackgroundFetchContext::CreateController(
const BackgroundFetchRegistrationId& registration_id,
const BackgroundFetchOptions& options,
+ const SkBitmap& icon,
const BackgroundFetchRegistration& registration) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
auto controller = std::make_unique<BackgroundFetchJobController>(
- &delegate_proxy_, registration_id, options, registration,
+ &delegate_proxy_, registration_id, options, icon, registration,
scheduler_.get(),
// Safe because JobControllers are destroyed before RegistrationNotifier.
base::BindRepeating(&BackgroundFetchRegistrationNotifier::Notify,
diff --git a/chromium/content/browser/background_fetch/background_fetch_context.h b/chromium/content/browser/background_fetch/background_fetch_context.h
index 0693caaf1f4..d2a8b980fb0 100644
--- a/chromium/content/browser/background_fetch/background_fetch_context.h
+++ b/chromium/content/browser/background_fetch/background_fetch_context.h
@@ -18,7 +18,7 @@
#include "content/browser/background_fetch/background_fetch_event_dispatcher.h"
#include "content/common/content_export.h"
#include "content/public/browser/browser_thread.h"
-#include "third_party/WebKit/public/platform/modules/background_fetch/background_fetch.mojom.h"
+#include "third_party/blink/public/platform/modules/background_fetch/background_fetch.mojom.h"
namespace storage {
class BlobDataHandle;
@@ -71,8 +71,14 @@ class CONTENT_EXPORT BackgroundFetchContext
void StartFetch(const BackgroundFetchRegistrationId& registration_id,
const std::vector<ServiceWorkerFetchRequest>& requests,
const BackgroundFetchOptions& options,
+ const SkBitmap& icon,
blink::mojom::BackgroundFetchService::FetchCallback callback);
+ // Gets display size for the icon for Background Fetch UI.
+ void GetIconDisplaySize(
+ blink::mojom::BackgroundFetchService::GetIconDisplaySizeCallback
+ callback);
+
// Aborts the Background Fetch for the |registration_id|. The callback will be
// invoked with INVALID_ID if the registration has already completed or
// aborted, STORAGE_ERROR if an I/O error occurs, or NONE for success.
@@ -86,11 +92,11 @@ class CONTENT_EXPORT BackgroundFetchContext
const std::string& unique_id,
blink::mojom::BackgroundFetchRegistrationObserverPtr observer);
- // Updates the title of the Background Fetch identified by |unique_id|. The
- // |callback| will be invoked when the title has been updated, or an error
+ // Updates the title of the Background Fetch identified by |registration_id|.
+ // The |callback| will be invoked when the title has been updated, or an error
// occurred that prevents it from doing so.
void UpdateUI(
- const std::string& unique_id,
+ const BackgroundFetchRegistrationId& registration_id,
const std::string& title,
blink::mojom::BackgroundFetchService::UpdateUICallback callback);
@@ -106,6 +112,7 @@ class CONTENT_EXPORT BackgroundFetchContext
// which will start fetching the files that are part of the registration.
void CreateController(const BackgroundFetchRegistrationId& registration_id,
const BackgroundFetchOptions& options,
+ const SkBitmap& icon,
const BackgroundFetchRegistration& registration);
// Called when an existing registration has been retrieved from the data
@@ -119,6 +126,7 @@ class CONTENT_EXPORT BackgroundFetchContext
void DidCreateRegistration(
const BackgroundFetchRegistrationId& registration_id,
const BackgroundFetchOptions& options,
+ const SkBitmap& icon,
blink::mojom::BackgroundFetchService::FetchCallback callback,
blink::mojom::BackgroundFetchError error,
std::unique_ptr<BackgroundFetchRegistration> registration);
diff --git a/chromium/content/browser/background_fetch/background_fetch_data_manager.cc b/chromium/content/browser/background_fetch/background_fetch_data_manager.cc
index f15fbd5ab71..500993d7b94 100644
--- a/chromium/content/browser/background_fetch/background_fetch_data_manager.cc
+++ b/chromium/content/browser/background_fetch/background_fetch_data_manager.cc
@@ -14,12 +14,13 @@
#include "content/browser/background_fetch/background_fetch_cross_origin_filter.h"
#include "content/browser/background_fetch/background_fetch_request_info.h"
#include "content/browser/background_fetch/storage/cleanup_task.h"
-#include "content/browser/background_fetch/storage/create_registration_task.h"
+#include "content/browser/background_fetch/storage/create_metadata_task.h"
#include "content/browser/background_fetch/storage/database_task.h"
#include "content/browser/background_fetch/storage/delete_registration_task.h"
#include "content/browser/background_fetch/storage/get_developer_ids_task.h"
-#include "content/browser/background_fetch/storage/get_registration_task.h"
+#include "content/browser/background_fetch/storage/get_metadata_task.h"
#include "content/browser/background_fetch/storage/mark_registration_for_deletion_task.h"
+#include "content/browser/background_fetch/storage/update_registration_ui_task.h"
#include "content/browser/blob_storage/chrome_blob_storage_context.h"
#include "content/browser/service_worker/service_worker_context_wrapper.h"
#include "content/public/browser/browser_thread.h"
@@ -28,7 +29,7 @@
#include "storage/browser/blob/blob_data_builder.h"
#include "storage/browser/blob/blob_impl.h"
#include "storage/browser/blob/blob_storage_context.h"
-#include "third_party/WebKit/public/mojom/blob/blob.mojom.h"
+#include "third_party/blink/public/mojom/blob/blob.mojom.h"
namespace content {
@@ -42,6 +43,30 @@ bool IsOK(const BackgroundFetchRequestInfo& request) {
return status >= 200 && status < 300;
}
+// Helper function to convert a BackgroundFetchRegistration proto into a
+// BackgroundFetchRegistration struct, and call the appropriate callback.
+void GetRegistrationFromMetadata(
+ BackgroundFetchDataManager::GetRegistrationCallback callback,
+ blink::mojom::BackgroundFetchError error,
+ std::unique_ptr<proto::BackgroundFetchMetadata> metadata_proto) {
+ if (!metadata_proto) {
+ std::move(callback).Run(error, nullptr);
+ return;
+ }
+
+ const auto& registration_proto = metadata_proto->registration();
+ auto registration = std::make_unique<BackgroundFetchRegistration>();
+ registration->developer_id = registration_proto.developer_id();
+ registration->unique_id = registration_proto.unique_id();
+ // TODO(crbug.com/774054): Uploads are not yet supported.
+ registration->upload_total = registration_proto.upload_total();
+ registration->uploaded = registration_proto.uploaded();
+ registration->download_total = registration_proto.download_total();
+ registration->downloaded = registration_proto.downloaded();
+
+ std::move(callback).Run(error, std::move(registration));
+}
+
} // namespace
// The Registration Data class encapsulates the data stored for a particular
@@ -51,8 +76,9 @@ class BackgroundFetchDataManager::RegistrationData {
public:
RegistrationData(const BackgroundFetchRegistrationId& registration_id,
const std::vector<ServiceWorkerFetchRequest>& requests,
- const BackgroundFetchOptions& options)
- : registration_id_(registration_id), options_(options) {
+ const BackgroundFetchOptions& options,
+ const SkBitmap& icon)
+ : registration_id_(registration_id), options_(options), icon_(icon) {
int request_index = 0;
// Convert the given |requests| to BackgroundFetchRequestInfo objects.
@@ -124,6 +150,7 @@ class BackgroundFetchDataManager::RegistrationData {
private:
BackgroundFetchRegistrationId registration_id_;
BackgroundFetchOptions options_;
+ SkBitmap icon_;
// Number of bytes downloaded as part of completed downloads. (In-progress
// downloads are tracked elsewhere).
uint64_t complete_requests_downloaded_bytes_ = 0;
@@ -178,13 +205,17 @@ void BackgroundFetchDataManager::CreateRegistration(
const BackgroundFetchRegistrationId& registration_id,
const std::vector<ServiceWorkerFetchRequest>& requests,
const BackgroundFetchOptions& options,
+ const SkBitmap& icon,
GetRegistrationCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableBackgroundFetchPersistence)) {
- AddDatabaseTask(std::make_unique<background_fetch::CreateRegistrationTask>(
- this, registration_id, requests, options, std::move(callback)));
+ auto registration_callback =
+ base::BindOnce(&GetRegistrationFromMetadata, std::move(callback));
+ AddDatabaseTask(std::make_unique<background_fetch::CreateMetadataTask>(
+ this, registration_id, requests, options,
+ std::move(registration_callback)));
return;
}
@@ -207,9 +238,9 @@ void BackgroundFetchDataManager::CreateRegistration(
registration_id.unique_id());
// Create the |RegistrationData|, and store it for easy access.
- registrations_.emplace(
- registration_id.unique_id(),
- std::make_unique<RegistrationData>(registration_id, requests, options));
+ registrations_.emplace(registration_id.unique_id(),
+ std::make_unique<RegistrationData>(
+ registration_id, requests, options, icon));
// Re-use GetRegistration to compile the BackgroundFetchRegistration object.
// WARNING: GetRegistration doesn't use the |unique_id| when looking up the
@@ -221,6 +252,21 @@ void BackgroundFetchDataManager::CreateRegistration(
std::move(callback));
}
+void BackgroundFetchDataManager::GetMetadata(
+ int64_t service_worker_registration_id,
+ const url::Origin& origin,
+ const std::string& developer_id,
+ GetMetadataCallback callback) {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+ if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
+ switches::kEnableBackgroundFetchPersistence)) {
+ return;
+ }
+ AddDatabaseTask(std::make_unique<background_fetch::GetMetadataTask>(
+ this, service_worker_registration_id, origin, developer_id,
+ std::move(callback)));
+}
+
void BackgroundFetchDataManager::GetRegistration(
int64_t service_worker_registration_id,
const url::Origin& origin,
@@ -230,9 +276,10 @@ void BackgroundFetchDataManager::GetRegistration(
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableBackgroundFetchPersistence)) {
- AddDatabaseTask(std::make_unique<background_fetch::GetRegistrationTask>(
- this, service_worker_registration_id, origin, developer_id,
- std::move(callback)));
+ auto registration_callback =
+ base::BindOnce(&GetRegistrationFromMetadata, std::move(callback));
+ GetMetadata(service_worker_registration_id, origin, developer_id,
+ std::move(registration_callback));
return;
}
@@ -266,12 +313,20 @@ void BackgroundFetchDataManager::GetRegistration(
}
void BackgroundFetchDataManager::UpdateRegistrationUI(
- const std::string& unique_id,
+ const BackgroundFetchRegistrationId& registration_id,
const std::string& title,
blink::mojom::BackgroundFetchService::UpdateUICallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
- auto registrations_iter = registrations_.find(unique_id);
+ if (base::CommandLine::ForCurrentProcess()->HasSwitch(
+ switches::kEnableBackgroundFetchPersistence)) {
+ AddDatabaseTask(
+ std::make_unique<background_fetch::UpdateRegistrationUITask>(
+ this, registration_id, title, std::move(callback)));
+ return;
+ }
+
+ auto registrations_iter = registrations_.find(registration_id.unique_id());
if (registrations_iter == registrations_.end()) { // Not found.
std::move(callback).Run(blink::mojom::BackgroundFetchError::INVALID_ID);
return;
diff --git a/chromium/content/browser/background_fetch/background_fetch_data_manager.h b/chromium/content/browser/background_fetch/background_fetch_data_manager.h
index 9b3705bd796..3d61469caad 100644
--- a/chromium/content/browser/background_fetch/background_fetch_data_manager.h
+++ b/chromium/content/browser/background_fetch/background_fetch_data_manager.h
@@ -16,11 +16,12 @@
#include "base/containers/queue.h"
#include "base/gtest_prod_util.h"
#include "base/macros.h"
+#include "content/browser/background_fetch/background_fetch.pb.h"
#include "content/browser/background_fetch/background_fetch_registration_id.h"
#include "content/browser/background_fetch/background_fetch_scheduler.h"
#include "content/browser/background_fetch/storage/database_task.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/modules/background_fetch/background_fetch.mojom.h"
+#include "third_party/blink/public/platform/modules/background_fetch/background_fetch.mojom.h"
#include "url/origin.h"
namespace storage {
@@ -54,6 +55,9 @@ class CONTENT_EXPORT BackgroundFetchDataManager
bool /* background_fetch_succeeded */,
std::vector<BackgroundFetchSettledFetch>,
std::vector<std::unique_ptr<storage::BlobDataHandle>>)>;
+ using GetMetadataCallback =
+ base::OnceCallback<void(blink::mojom::BackgroundFetchError,
+ std::unique_ptr<proto::BackgroundFetchMetadata>)>;
using GetRegistrationCallback =
base::OnceCallback<void(blink::mojom::BackgroundFetchError,
std::unique_ptr<BackgroundFetchRegistration>)>;
@@ -73,9 +77,16 @@ class CONTENT_EXPORT BackgroundFetchDataManager
const BackgroundFetchRegistrationId& registration_id,
const std::vector<ServiceWorkerFetchRequest>& requests,
const BackgroundFetchOptions& options,
+ const SkBitmap& icon,
GetRegistrationCallback callback);
- // Get the BackgroundFetchOptions for a registration.
+ // Get the BackgroundFetchMetadata.
+ void GetMetadata(int64_t service_worker_registration_id,
+ const url::Origin& origin,
+ const std::string& developer_id,
+ GetMetadataCallback callback);
+
+ // Get the BackgroundFetchRegistration.
void GetRegistration(int64_t service_worker_registration_id,
const url::Origin& origin,
const std::string& developer_id,
@@ -83,7 +94,7 @@ class CONTENT_EXPORT BackgroundFetchDataManager
// Updates the UI values for a Background Fetch registration.
void UpdateRegistrationUI(
- const std::string& unique_id,
+ const BackgroundFetchRegistrationId& registration_id,
const std::string& title,
blink::mojom::BackgroundFetchService::UpdateUICallback callback);
diff --git a/chromium/content/browser/background_fetch/background_fetch_data_manager_unittest.cc b/chromium/content/browser/background_fetch/background_fetch_data_manager_unittest.cc
index b9b6e3513af..509c5bb5de3 100644
--- a/chromium/content/browser/background_fetch/background_fetch_data_manager_unittest.cc
+++ b/chromium/content/browser/background_fetch/background_fetch_data_manager_unittest.cc
@@ -14,7 +14,6 @@
#include "base/callback_helpers.h"
#include "base/command_line.h"
#include "base/guid.h"
-#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "content/browser/background_fetch/background_fetch_request_info.h"
#include "content/browser/background_fetch/background_fetch_test_base.h"
@@ -39,6 +38,9 @@ const char kAlternativeDeveloperId[] = "my-other-id";
const char kExampleUniqueId[] = "7e57ab1e-c0de-a150-ca75-1e75f005ba11";
const char kAlternativeUniqueId[] = "bb48a9fb-c21f-4c2d-a9ae-58bd48a9fb53";
+const char kInitialTitle[] = "Initial Title";
+const char kUpdatedTitle[] = "Updated Title";
+
// See schema documentation in background_fetch_data_manager.cc.
// A "bgfetch_registration_" per registration (not including keys for requests).
constexpr size_t kUserDataKeysPerInactiveRegistration = 1u;
@@ -52,14 +54,14 @@ void DidCreateRegistration(
blink::mojom::BackgroundFetchError error,
std::unique_ptr<BackgroundFetchRegistration> registration) {
*out_error = error;
- quit_closure.Run();
+ std::move(quit_closure).Run();
}
void DidGetError(base::Closure quit_closure,
blink::mojom::BackgroundFetchError* out_error,
blink::mojom::BackgroundFetchError error) {
*out_error = error;
- quit_closure.Run();
+ std::move(quit_closure).Run();
}
void DidGetRegistrationUserDataByKeyPrefix(base::Closure quit_closure,
@@ -69,7 +71,7 @@ void DidGetRegistrationUserDataByKeyPrefix(base::Closure quit_closure,
DCHECK(out_data);
DCHECK_EQ(SERVICE_WORKER_OK, status);
*out_data = data;
- quit_closure.Run();
+ std::move(quit_closure).Run();
}
} // namespace
@@ -116,7 +118,7 @@ class BackgroundFetchDataManagerTest
base::RunLoop run_loop;
background_fetch_data_manager_->CreateRegistration(
- registration_id, requests, options,
+ registration_id, requests, options, SkBitmap(),
base::BindOnce(&DidCreateRegistration, run_loop.QuitClosure(),
out_error));
run_loop.Run();
@@ -141,6 +143,40 @@ class BackgroundFetchDataManagerTest
return registration;
}
+ std::unique_ptr<proto::BackgroundFetchMetadata> GetMetadata(
+ int64_t service_worker_registration_id,
+ const url::Origin& origin,
+ const std::string developer_id,
+ blink::mojom::BackgroundFetchError* out_error) {
+ DCHECK(out_error);
+
+ std::unique_ptr<proto::BackgroundFetchMetadata> metadata;
+ base::RunLoop run_loop;
+ background_fetch_data_manager_->GetMetadata(
+ service_worker_registration_id, origin, developer_id,
+ base::BindOnce(&BackgroundFetchDataManagerTest::DidGetMetadata,
+ base::Unretained(this), run_loop.QuitClosure(),
+ out_error, &metadata));
+ run_loop.Run();
+
+ return metadata;
+ }
+
+ void UpdateRegistrationUI(
+ const BackgroundFetchRegistrationId& registration_id,
+ const std::string& updated_title,
+ blink::mojom::BackgroundFetchError* out_error) {
+ DCHECK(out_error);
+
+ base::RunLoop run_loop;
+ background_fetch_data_manager_->UpdateRegistrationUI(
+ registration_id, updated_title,
+ base::BindOnce(&BackgroundFetchDataManagerTest::DidUpdateRegistrationUI,
+ base::Unretained(this), run_loop.QuitClosure(),
+ out_error));
+ run_loop.Run();
+ }
+
std::vector<std::string> GetDeveloperIds(
int64_t service_worker_registration_id,
const url::Origin& origin,
@@ -217,7 +253,29 @@ class BackgroundFetchDataManagerTest
*out_error = error;
*out_registration = std::move(registration);
- quit_closure.Run();
+ std::move(quit_closure).Run();
+ }
+
+ void DidGetMetadata(
+ base::OnceClosure quit_closure,
+ blink::mojom::BackgroundFetchError* out_error,
+ std::unique_ptr<proto::BackgroundFetchMetadata>* out_metadata,
+ blink::mojom::BackgroundFetchError error,
+ std::unique_ptr<proto::BackgroundFetchMetadata> metadata) {
+ if (error == blink::mojom::BackgroundFetchError::NONE) {
+ DCHECK(metadata);
+ }
+ *out_error = error;
+ *out_metadata = std::move(metadata);
+
+ std::move(quit_closure).Run();
+ }
+
+ void DidUpdateRegistrationUI(base::OnceClosure quit_closure,
+ blink::mojom::BackgroundFetchError* out_error,
+ blink::mojom::BackgroundFetchError error) {
+ *out_error = error;
+ std::move(quit_closure).Run();
}
void DidGetDeveloperIds(base::Closure quit_closure,
@@ -228,7 +286,7 @@ class BackgroundFetchDataManagerTest
*out_error = error;
*out_ids = ids;
- quit_closure.Run();
+ std::move(quit_closure).Run();
}
BackgroundFetchRegistrationStorage registration_storage_;
@@ -387,6 +445,87 @@ TEST_P(BackgroundFetchDataManagerTest, GetRegistration) {
EXPECT_EQ(kExampleDeveloperId, registration->developer_id);
}
+TEST_P(BackgroundFetchDataManagerTest, GetMetadata) {
+ // This test only applies to persistent storage.
+ if (registration_storage_ ==
+ BackgroundFetchRegistrationStorage::kNonPersistent)
+ return;
+
+ int64_t sw_id = RegisterServiceWorker();
+ ASSERT_NE(blink::mojom::kInvalidServiceWorkerRegistrationId, sw_id);
+
+ BackgroundFetchRegistrationId registration_id(
+ sw_id, origin(), kExampleDeveloperId, kExampleUniqueId);
+
+ std::vector<ServiceWorkerFetchRequest> requests(2u);
+ BackgroundFetchOptions options;
+ blink::mojom::BackgroundFetchError error;
+
+ // Create a single registration.
+ CreateRegistration(registration_id, requests, options, &error);
+ EXPECT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
+
+ // Verify that the metadata can be retrieved.
+ auto metadata = GetMetadata(sw_id, origin(), kExampleDeveloperId, &error);
+ ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
+ ASSERT_TRUE(metadata);
+ EXPECT_EQ(metadata->origin(), origin().Serialize());
+ EXPECT_NE(metadata->creation_microseconds_since_unix_epoch(), 0);
+
+ // Verify that retrieving using the wrong developer id doesn't work.
+ metadata = GetMetadata(sw_id, origin(), kAlternativeDeveloperId, &error);
+ ASSERT_EQ(error, blink::mojom::BackgroundFetchError::INVALID_ID);
+ ASSERT_FALSE(metadata);
+
+ RestartDataManagerFromPersistentStorage();
+
+ // After a restart, GetMetadata should still find the registration.
+ metadata = GetMetadata(sw_id, origin(), kExampleDeveloperId, &error);
+ ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
+ ASSERT_TRUE(metadata);
+ EXPECT_EQ(metadata->origin(), origin().Serialize());
+ EXPECT_NE(metadata->creation_microseconds_since_unix_epoch(), 0);
+}
+
+TEST_P(BackgroundFetchDataManagerTest, UpdateRegistrationUI) {
+ // This test only applies to persistent storage.
+ if (registration_storage_ ==
+ BackgroundFetchRegistrationStorage::kNonPersistent)
+ return;
+
+ int64_t sw_id = RegisterServiceWorker();
+ ASSERT_NE(blink::mojom::kInvalidServiceWorkerRegistrationId, sw_id);
+
+ BackgroundFetchRegistrationId registration_id(
+ sw_id, origin(), kExampleDeveloperId, kExampleUniqueId);
+
+ std::vector<ServiceWorkerFetchRequest> requests(2u);
+ BackgroundFetchOptions options;
+ options.title = kInitialTitle;
+ blink::mojom::BackgroundFetchError error;
+
+ // Create a single registration.
+ CreateRegistration(registration_id, requests, options, &error);
+ EXPECT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
+
+ // Verify that the title can be retrieved.
+ auto metadata = GetMetadata(sw_id, origin(), kExampleDeveloperId, &error);
+ ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
+ ASSERT_TRUE(metadata);
+ EXPECT_EQ(metadata->ui_title(), kInitialTitle);
+
+ // Update the title.
+ UpdateRegistrationUI(registration_id, kUpdatedTitle, &error);
+
+ RestartDataManagerFromPersistentStorage();
+
+ // After a restart, GetMetadata should find the new title.
+ metadata = GetMetadata(sw_id, origin(), kExampleDeveloperId, &error);
+ ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
+ ASSERT_TRUE(metadata);
+ EXPECT_EQ(metadata->ui_title(), kUpdatedTitle);
+}
+
TEST_P(BackgroundFetchDataManagerTest, CreateAndDeleteRegistration) {
int64_t sw_id = RegisterServiceWorker();
ASSERT_NE(blink::mojom::kInvalidServiceWorkerRegistrationId, sw_id);
@@ -545,7 +684,7 @@ TEST_P(BackgroundFetchDataManagerTest, CreateInParallel) {
base::GenerateGUID());
background_fetch_data_manager_->CreateRegistration(
- registration_id, requests, options,
+ registration_id, requests, options, SkBitmap(),
base::BindOnce(&DidCreateRegistration, quit_once_all_finished_closure,
&errors[i]));
}
diff --git a/chromium/content/browser/background_fetch/background_fetch_delegate_proxy.cc b/chromium/content/browser/background_fetch/background_fetch_delegate_proxy.cc
index 6ab13fb9a97..cec58a9ba29 100644
--- a/chromium/content/browser/background_fetch/background_fetch_delegate_proxy.cc
+++ b/chromium/content/browser/background_fetch/background_fetch_delegate_proxy.cc
@@ -6,13 +6,14 @@
#include <utility>
-#include "base/memory/ptr_util.h"
#include "components/download/public/common/download_item.h"
#include "components/download/public/common/download_url_parameters.h"
#include "content/browser/background_fetch/background_fetch_job_controller.h"
-#include "content/public/browser/background_fetch_delegate.h"
#include "content/public/browser/background_fetch_response.h"
#include "content/public/browser/download_manager.h"
+#include "ui/gfx/geometry/size.h"
+
+class SkBitmap;
namespace content {
@@ -39,16 +40,40 @@ class BackgroundFetchDelegateProxy::Core
return weak_ptr_factory_.GetWeakPtr();
}
+ void ForwardGetIconDisplaySizeCallbackToIO(
+ BackgroundFetchDelegate::GetIconDisplaySizeCallback callback,
+ const gfx::Size& display_size) {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
+ base::BindOnce(std::move(callback), display_size));
+ }
+
+ void GetIconDisplaySize(
+ BackgroundFetchDelegate::GetIconDisplaySizeCallback callback) {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+
+ if (delegate_) {
+ delegate_->GetIconDisplaySize(
+ base::BindOnce(&Core::ForwardGetIconDisplaySizeCallbackToIO,
+ weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
+ } else {
+ BrowserThread::PostTask(
+ BrowserThread::IO, FROM_HERE,
+ base::BindOnce(std::move(callback), gfx::Size(0, 0)));
+ }
+ }
+
void CreateDownloadJob(const std::string& job_unique_id,
const std::string& title,
const url::Origin& origin,
+ const SkBitmap& icon,
int completed_parts,
int total_parts,
const std::vector<std::string>& current_guids) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (delegate_) {
- delegate_->CreateDownloadJob(job_unique_id, title, origin,
+ delegate_->CreateDownloadJob(job_unique_id, title, origin, icon,
completed_parts, total_parts, current_guids);
}
}
@@ -227,10 +252,19 @@ BackgroundFetchDelegateProxy::~BackgroundFetchDelegateProxy() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
}
+void BackgroundFetchDelegateProxy::GetIconDisplaySize(
+ BackgroundFetchDelegate::GetIconDisplaySizeCallback callback) {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+ BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
+ base::BindOnce(&Core::GetIconDisplaySize,
+ ui_core_ptr_, std::move(callback)));
+}
+
void BackgroundFetchDelegateProxy::CreateDownloadJob(
const std::string& job_unique_id,
const std::string& title,
const url::Origin& origin,
+ const SkBitmap& icon,
base::WeakPtr<Controller> controller,
int completed_parts,
int total_parts,
@@ -243,7 +277,7 @@ void BackgroundFetchDelegateProxy::CreateDownloadJob(
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::BindOnce(&Core::CreateDownloadJob, ui_core_ptr_, job_unique_id,
- title, origin, completed_parts, total_parts,
+ title, origin, icon, completed_parts, total_parts,
current_guids));
}
diff --git a/chromium/content/browser/background_fetch/background_fetch_delegate_proxy.h b/chromium/content/browser/background_fetch/background_fetch_delegate_proxy.h
index 4bf35b18c97..3b905d3631d 100644
--- a/chromium/content/browser/background_fetch/background_fetch_delegate_proxy.h
+++ b/chromium/content/browser/background_fetch/background_fetch_delegate_proxy.h
@@ -15,12 +15,13 @@
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "content/browser/background_fetch/background_fetch_request_info.h"
+#include "content/public/browser/background_fetch_delegate.h"
#include "content/public/browser/background_fetch_response.h"
#include "content/public/browser/browser_thread.h"
-namespace content {
+class SkBitmap;
-class BackgroundFetchDelegate;
+namespace content {
// Proxy class for passing messages between BackgroundFetchJobControllers on the
// IO thread and BackgroundFetchDelegate on the UI thread.
@@ -54,6 +55,10 @@ class CONTENT_EXPORT BackgroundFetchDelegateProxy {
~BackgroundFetchDelegateProxy();
+ // Gets size of the icon to display with the Background Fetch UI.
+ void GetIconDisplaySize(
+ BackgroundFetchDelegate::GetIconDisplaySizeCallback callback);
+
// Creates a new download grouping identified by |job_unique_id|. Further
// downloads started by StartRequest will also use this |job_unique_id| so
// that a notification can be updated with the current status. If the download
@@ -65,6 +70,7 @@ class CONTENT_EXPORT BackgroundFetchDelegateProxy {
void CreateDownloadJob(const std::string& job_unique_id,
const std::string& title,
const url::Origin& origin,
+ const SkBitmap& icon,
base::WeakPtr<Controller> controller,
int completed_parts,
int total_parts,
diff --git a/chromium/content/browser/background_fetch/background_fetch_delegate_proxy_unittest.cc b/chromium/content/browser/background_fetch/background_fetch_delegate_proxy_unittest.cc
index 1beeeaad401..9091e65d5c5 100644
--- a/chromium/content/browser/background_fetch/background_fetch_delegate_proxy_unittest.cc
+++ b/chromium/content/browser/background_fetch/background_fetch_delegate_proxy_unittest.cc
@@ -12,6 +12,7 @@
#include "content/browser/background_fetch/background_fetch_test_base.h"
#include "content/public/browser/background_fetch_delegate.h"
#include "content/public/browser/background_fetch_response.h"
+#include "content/public/browser/browser_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace content {
@@ -20,16 +21,22 @@ namespace {
const char kExampleUniqueId[] = "7e57ab1e-c0de-a150-ca75-1e75f005ba11";
const char kExampleUniqueId2[] = "17467386-60b4-4c5b-b66c-aabf793fd39b";
+const int kIconDisplaySize = 192;
class FakeBackgroundFetchDelegate : public BackgroundFetchDelegate {
public:
FakeBackgroundFetchDelegate() {}
// BackgroundFetchDelegate implementation:
+ void GetIconDisplaySize(
+ BackgroundFetchDelegate::GetIconDisplaySizeCallback callback) override {
+ std::move(callback).Run(gfx::Size(kIconDisplaySize, kIconDisplaySize));
+ }
void CreateDownloadJob(
const std::string& job_unique_id,
const std::string& title,
const url::Origin& origin,
+ const SkBitmap& icon,
int completed_parts,
int total_parts,
const std::vector<std::string>& current_guids) override {}
@@ -111,6 +118,13 @@ class FakeController : public BackgroundFetchDelegateProxy::Controller {
class BackgroundFetchDelegateProxyTest : public BackgroundFetchTestBase {
public:
BackgroundFetchDelegateProxyTest() : delegate_proxy_(&delegate_) {}
+ void DidGetIconDisplaySize(base::Closure quit_closure,
+ gfx::Size* out_display_size,
+ const gfx::Size& display_size) {
+ DCHECK(out_display_size);
+ *out_display_size = display_size;
+ std::move(quit_closure).Run();
+ }
protected:
FakeBackgroundFetchDelegate delegate_;
@@ -140,9 +154,9 @@ TEST_F(BackgroundFetchDelegateProxyTest, StartRequest) {
EXPECT_FALSE(controller.request_started_);
EXPECT_FALSE(controller.request_completed_);
- delegate_proxy_.CreateDownloadJob(kExampleUniqueId, "Job 1", url::Origin(),
- controller.weak_ptr_factory_.GetWeakPtr(),
- 0, 1, {});
+ delegate_proxy_.CreateDownloadJob(
+ kExampleUniqueId, "Job 1", url::Origin(), SkBitmap(),
+ controller.weak_ptr_factory_.GetWeakPtr(), 0, 1, {});
delegate_proxy_.StartRequest(kExampleUniqueId, url::Origin(), request);
base::RunLoop().RunUntilIdle();
@@ -160,9 +174,9 @@ TEST_F(BackgroundFetchDelegateProxyTest, StartRequest_NotCompleted) {
EXPECT_FALSE(controller.request_completed_);
delegate_.set_complete_downloads(false);
- delegate_proxy_.CreateDownloadJob(kExampleUniqueId, "Job 1", url::Origin(),
- controller.weak_ptr_factory_.GetWeakPtr(),
- 0, 1, {});
+ delegate_proxy_.CreateDownloadJob(
+ kExampleUniqueId, "Job 1", url::Origin(), SkBitmap(),
+ controller.weak_ptr_factory_.GetWeakPtr(), 0, 1, {});
delegate_proxy_.StartRequest(kExampleUniqueId, url::Origin(), request);
base::RunLoop().RunUntilIdle();
@@ -184,13 +198,13 @@ TEST_F(BackgroundFetchDelegateProxyTest, Abort) {
EXPECT_FALSE(controller2.request_started_);
EXPECT_FALSE(controller2.request_completed_);
- delegate_proxy_.CreateDownloadJob(kExampleUniqueId, "Job 1", url::Origin(),
- controller.weak_ptr_factory_.GetWeakPtr(),
- 0, 1, {});
+ delegate_proxy_.CreateDownloadJob(
+ kExampleUniqueId, "Job 1", url::Origin(), SkBitmap(),
+ controller.weak_ptr_factory_.GetWeakPtr(), 0, 1, {});
- delegate_proxy_.CreateDownloadJob(kExampleUniqueId2, "Job 2", url::Origin(),
- controller2.weak_ptr_factory_.GetWeakPtr(),
- 0, 1, {});
+ delegate_proxy_.CreateDownloadJob(
+ kExampleUniqueId2, "Job 2", url::Origin(), SkBitmap(),
+ controller2.weak_ptr_factory_.GetWeakPtr(), 0, 1, {});
delegate_proxy_.StartRequest(kExampleUniqueId, url::Origin(), request);
delegate_proxy_.StartRequest(kExampleUniqueId2, url::Origin(), request2);
@@ -203,4 +217,15 @@ TEST_F(BackgroundFetchDelegateProxyTest, Abort) {
EXPECT_TRUE(controller2.request_completed_) << "Normal job did not complete";
}
+TEST_F(BackgroundFetchDelegateProxyTest, GetIconDisplaySize) {
+ gfx::Size out_display_size;
+ base::RunLoop run_loop;
+ delegate_proxy_.GetIconDisplaySize(base::BindOnce(
+ &BackgroundFetchDelegateProxyTest::DidGetIconDisplaySize,
+ base::Unretained(this), run_loop.QuitClosure(), &out_display_size));
+ run_loop.Run();
+ EXPECT_EQ(out_display_size.width(), kIconDisplaySize);
+ EXPECT_EQ(out_display_size.height(), kIconDisplaySize);
+}
+
} // namespace content
diff --git a/chromium/content/browser/background_fetch/background_fetch_embedded_worker_test_helper.cc b/chromium/content/browser/background_fetch/background_fetch_embedded_worker_test_helper.cc
index f1d5123ef03..dc606892ca4 100644
--- a/chromium/content/browser/background_fetch/background_fetch_embedded_worker_test_helper.cc
+++ b/chromium/content/browser/background_fetch/background_fetch_embedded_worker_test_helper.cc
@@ -8,7 +8,7 @@
#include "base/time/time.h"
#include "content/common/background_fetch/background_fetch_types.h"
#include "content/common/service_worker/service_worker_event_dispatcher.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_event_status.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_event_status.mojom.h"
namespace content {
diff --git a/chromium/content/browser/background_fetch/background_fetch_event_dispatcher.cc b/chromium/content/browser/background_fetch/background_fetch_event_dispatcher.cc
index cebc2bbd095..7a52ccc795b 100644
--- a/chromium/content/browser/background_fetch/background_fetch_event_dispatcher.cc
+++ b/chromium/content/browser/background_fetch/background_fetch_event_dispatcher.cc
@@ -199,9 +199,10 @@ void BackgroundFetchEventDispatcher::StartActiveWorkerForDispatch(
DCHECK(service_worker_version);
service_worker_version->RunAfterStartWorker(
- event, base::BindOnce(&BackgroundFetchEventDispatcher::DispatchEvent,
- event, std::move(finished_closure), loaded_callback,
- base::WrapRefCounted(service_worker_version)));
+ event,
+ base::BindOnce(&BackgroundFetchEventDispatcher::DispatchEvent, event,
+ std::move(finished_closure), std::move(loaded_callback),
+ base::WrapRefCounted(service_worker_version)));
}
void BackgroundFetchEventDispatcher::DispatchEvent(
@@ -221,7 +222,7 @@ void BackgroundFetchEventDispatcher::DispatchEvent(
base::BindOnce(&BackgroundFetchEventDispatcher::DidDispatchEvent, event,
std::move(finished_closure), DispatchPhase::DISPATCHING));
- loaded_callback.Run(std::move(service_worker_version), request_id);
+ std::move(loaded_callback).Run(std::move(service_worker_version), request_id);
}
void BackgroundFetchEventDispatcher::DidDispatchEvent(
diff --git a/chromium/content/browser/background_fetch/background_fetch_job_controller.cc b/chromium/content/browser/background_fetch/background_fetch_job_controller.cc
index f498d24a664..83f1fa69711 100644
--- a/chromium/content/browser/background_fetch/background_fetch_job_controller.cc
+++ b/chromium/content/browser/background_fetch/background_fetch_job_controller.cc
@@ -6,7 +6,6 @@
#include <utility>
-#include "base/memory/ptr_util.h"
#include "content/browser/background_fetch/background_fetch_request_manager.h"
#include "content/public/browser/browser_thread.h"
@@ -16,6 +15,7 @@ BackgroundFetchJobController::BackgroundFetchJobController(
BackgroundFetchDelegateProxy* delegate_proxy,
const BackgroundFetchRegistrationId& registration_id,
const BackgroundFetchOptions& options,
+ const SkBitmap& icon,
const BackgroundFetchRegistration& registration,
BackgroundFetchRequestManager* request_manager,
ProgressCallback progress_callback,
@@ -23,6 +23,7 @@ BackgroundFetchJobController::BackgroundFetchJobController(
: BackgroundFetchScheduler::Controller(registration_id,
std::move(finished_callback)),
options_(options),
+ icon_(icon),
complete_requests_downloaded_bytes_cache_(registration.downloaded),
request_manager_(request_manager),
delegate_proxy_(delegate_proxy),
@@ -44,9 +45,10 @@ void BackgroundFetchJobController::InitializeRequestStatus(
completed_downloads_ = completed_downloads;
total_downloads_ = total_downloads;
- delegate_proxy_->CreateDownloadJob(
- registration_id().unique_id(), options_.title, registration_id().origin(),
- GetWeakPtr(), completed_downloads, total_downloads, outstanding_guids);
+ delegate_proxy_->CreateDownloadJob(registration_id().unique_id(),
+ options_.title, registration_id().origin(),
+ icon_, GetWeakPtr(), completed_downloads,
+ total_downloads, outstanding_guids);
}
BackgroundFetchJobController::~BackgroundFetchJobController() {
diff --git a/chromium/content/browser/background_fetch/background_fetch_job_controller.h b/chromium/content/browser/background_fetch/background_fetch_job_controller.h
index ff942107c1b..02d5378318a 100644
--- a/chromium/content/browser/background_fetch/background_fetch_job_controller.h
+++ b/chromium/content/browser/background_fetch/background_fetch_job_controller.h
@@ -20,6 +20,7 @@
#include "content/common/background_fetch/background_fetch_types.h"
#include "content/common/content_export.h"
#include "content/public/browser/browser_thread.h"
+#include "third_party/skia/include/core/SkBitmap.h"
namespace content {
@@ -49,6 +50,7 @@ class CONTENT_EXPORT BackgroundFetchJobController final
BackgroundFetchDelegateProxy* delegate_proxy,
const BackgroundFetchRegistrationId& registration_id,
const BackgroundFetchOptions& options,
+ const SkBitmap& icon,
const BackgroundFetchRegistration& registration,
BackgroundFetchRequestManager* request_manager,
ProgressCallback progress_callback,
@@ -102,6 +104,9 @@ class CONTENT_EXPORT BackgroundFetchJobController final
// Options for the represented background fetch registration.
BackgroundFetchOptions options_;
+ // Icon for the represented background fetch registration.
+ SkBitmap icon_;
+
// Map from in-progress |download_guid|s to number of bytes downloaded.
base::flat_map<std::string, uint64_t> active_request_download_bytes_;
diff --git a/chromium/content/browser/background_fetch/background_fetch_job_controller_unittest.cc b/chromium/content/browser/background_fetch/background_fetch_job_controller_unittest.cc
index 25ccd195511..f628088aebe 100644
--- a/chromium/content/browser/background_fetch/background_fetch_job_controller_unittest.cc
+++ b/chromium/content/browser/background_fetch/background_fetch_job_controller_unittest.cc
@@ -156,7 +156,7 @@ class BackgroundFetchJobControllerTest : public BackgroundFetchTestBase {
auto controller = std::make_unique<BackgroundFetchJobController>(
delegate_proxy_.get(), registration_id, BackgroundFetchOptions(),
- registration, &request_manager_,
+ SkBitmap(), registration, &request_manager_,
base::BindRepeating(
&BackgroundFetchJobControllerTest::DidUpdateProgress,
base::Unretained(this)),
diff --git a/chromium/content/browser/background_fetch/background_fetch_registration_id.cc b/chromium/content/browser/background_fetch/background_fetch_registration_id.cc
index 7ea6cc7b370..b8d073795bf 100644
--- a/chromium/content/browser/background_fetch/background_fetch_registration_id.cc
+++ b/chromium/content/browser/background_fetch/background_fetch_registration_id.cc
@@ -7,7 +7,7 @@
#include <tuple>
#include "content/common/service_worker/service_worker_types.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
diff --git a/chromium/content/browser/background_fetch/background_fetch_registration_notifier.h b/chromium/content/browser/background_fetch/background_fetch_registration_notifier.h
index 28a8981d88f..80abea1ece9 100644
--- a/chromium/content/browser/background_fetch/background_fetch_registration_notifier.h
+++ b/chromium/content/browser/background_fetch/background_fetch_registration_notifier.h
@@ -13,7 +13,7 @@
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/modules/background_fetch/background_fetch.mojom.h"
+#include "third_party/blink/public/platform/modules/background_fetch/background_fetch.mojom.h"
namespace content {
diff --git a/chromium/content/browser/background_fetch/background_fetch_registration_notifier_unittest.cc b/chromium/content/browser/background_fetch/background_fetch_registration_notifier_unittest.cc
index 2e3f89b593c..9be34593da1 100644
--- a/chromium/content/browser/background_fetch/background_fetch_registration_notifier_unittest.cc
+++ b/chromium/content/browser/background_fetch/background_fetch_registration_notifier_unittest.cc
@@ -14,7 +14,7 @@
#include "mojo/public/cpp/bindings/binding.h"
#include "mojo/public/cpp/bindings/interface_request.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/modules/background_fetch/background_fetch.mojom.h"
+#include "third_party/blink/public/platform/modules/background_fetch/background_fetch.mojom.h"
namespace content {
namespace {
diff --git a/chromium/content/browser/background_fetch/background_fetch_scheduler_unittest.cc b/chromium/content/browser/background_fetch/background_fetch_scheduler_unittest.cc
index 6645140159d..8e917b0345e 100644
--- a/chromium/content/browser/background_fetch/background_fetch_scheduler_unittest.cc
+++ b/chromium/content/browser/background_fetch/background_fetch_scheduler_unittest.cc
@@ -10,6 +10,7 @@
#include "base/strings/string_number_conversions.h"
#include "content/browser/background_fetch/background_fetch_request_info.h"
#include "content/browser/background_fetch/background_fetch_test_base.h"
+#include "content/public/browser/browser_thread.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -80,7 +81,7 @@ class BackgroundFetchSchedulerTest
void PostQuitAfterRepeatingBarriers(base::Closure quit_closure,
int number_of_barriers) {
if (--number_of_barriers == 0) {
- quit_closure.Run();
+ std::move(quit_closure).Run();
return;
}
@@ -88,7 +89,8 @@ class BackgroundFetchSchedulerTest
BrowserThread::IO, FROM_HERE,
base::BindOnce(
&BackgroundFetchSchedulerTest::PostQuitAfterRepeatingBarriers,
- base::Unretained(this), quit_closure, number_of_barriers));
+ base::Unretained(this), std::move(quit_closure),
+ number_of_barriers));
}
void PopNextRequest(
diff --git a/chromium/content/browser/background_fetch/background_fetch_service_impl.cc b/chromium/content/browser/background_fetch/background_fetch_service_impl.cc
index be53f5115d3..c481fb6c041 100644
--- a/chromium/content/browser/background_fetch/background_fetch_service_impl.cc
+++ b/chromium/content/browser/background_fetch/background_fetch_service_impl.cc
@@ -73,6 +73,7 @@ void BackgroundFetchServiceImpl::Fetch(
const std::string& developer_id,
const std::vector<ServiceWorkerFetchRequest>& requests,
const BackgroundFetchOptions& options,
+ const SkBitmap& icon,
FetchCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!ValidateDeveloperId(developer_id)) {
@@ -96,12 +97,21 @@ void BackgroundFetchServiceImpl::Fetch(
base::GenerateGUID());
background_fetch_context_->StartFetch(registration_id, requests, options,
- std::move(callback));
+ icon, std::move(callback));
}
-void BackgroundFetchServiceImpl::UpdateUI(const std::string& unique_id,
- const std::string& title,
- UpdateUICallback callback) {
+void BackgroundFetchServiceImpl::GetIconDisplaySize(
+ blink::mojom::BackgroundFetchService::GetIconDisplaySizeCallback callback) {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+ background_fetch_context_->GetIconDisplaySize(std::move(callback));
+}
+
+void BackgroundFetchServiceImpl::UpdateUI(
+ int64_t service_worker_registration_id,
+ const std::string& developer_id,
+ const std::string& unique_id,
+ const std::string& title,
+ UpdateUICallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!ValidateUniqueId(unique_id) || !ValidateTitle(title)) {
std::move(callback).Run(
@@ -109,7 +119,10 @@ void BackgroundFetchServiceImpl::UpdateUI(const std::string& unique_id,
return;
}
- background_fetch_context_->UpdateUI(unique_id, title, std::move(callback));
+ BackgroundFetchRegistrationId registration_id(
+ service_worker_registration_id, origin_, developer_id, unique_id);
+ background_fetch_context_->UpdateUI(registration_id, title,
+ std::move(callback));
}
void BackgroundFetchServiceImpl::Abort(int64_t service_worker_registration_id,
diff --git a/chromium/content/browser/background_fetch/background_fetch_service_impl.h b/chromium/content/browser/background_fetch/background_fetch_service_impl.h
index f2b79788fe4..984a94c034a 100644
--- a/chromium/content/browser/background_fetch/background_fetch_service_impl.h
+++ b/chromium/content/browser/background_fetch/background_fetch_service_impl.h
@@ -13,7 +13,7 @@
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/modules/background_fetch/background_fetch.mojom.h"
+#include "third_party/blink/public/platform/modules/background_fetch/background_fetch.mojom.h"
#include "url/origin.h"
namespace content {
@@ -40,8 +40,12 @@ class CONTENT_EXPORT BackgroundFetchServiceImpl
const std::string& developer_id,
const std::vector<ServiceWorkerFetchRequest>& requests,
const BackgroundFetchOptions& options,
+ const SkBitmap& icon,
FetchCallback callback) override;
- void UpdateUI(const std::string& unique_id,
+ void GetIconDisplaySize(GetIconDisplaySizeCallback callback) override;
+ void UpdateUI(int64_t service_worker_registration_id,
+ const std::string& developer_id,
+ const std::string& unique_id,
const std::string& title,
UpdateUICallback callback) override;
void Abort(int64_t service_worker_registration_id,
diff --git a/chromium/content/browser/background_fetch/background_fetch_service_unittest.cc b/chromium/content/browser/background_fetch/background_fetch_service_unittest.cc
index f0ffa329be9..6e703f027a3 100644
--- a/chromium/content/browser/background_fetch/background_fetch_service_unittest.cc
+++ b/chromium/content/browser/background_fetch/background_fetch_service_unittest.cc
@@ -8,7 +8,6 @@
#include "base/auto_reset.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/time/time.h"
#include "content/browser/background_fetch/background_fetch_context.h"
@@ -93,6 +92,7 @@ class BackgroundFetchServiceTest : public BackgroundFetchTestBase {
const std::string& developer_id,
const std::vector<ServiceWorkerFetchRequest>& requests,
const BackgroundFetchOptions& options,
+ const SkBitmap& icon,
blink::mojom::BackgroundFetchError* out_error,
BackgroundFetchRegistration* out_registration) {
DCHECK(out_error);
@@ -100,7 +100,7 @@ class BackgroundFetchServiceTest : public BackgroundFetchTestBase {
base::RunLoop run_loop;
service_->Fetch(
- service_worker_registration_id, developer_id, requests, options,
+ service_worker_registration_id, developer_id, requests, options, icon,
base::BindOnce(&BackgroundFetchServiceTest::DidGetRegistration,
base::Unretained(this), run_loop.QuitClosure(),
out_error, out_registration));
@@ -116,13 +116,16 @@ class BackgroundFetchServiceTest : public BackgroundFetchTestBase {
}
// Synchronous wrapper for BackgroundFetchServiceImpl::UpdateUI().
- void UpdateUI(const std::string& unique_id,
+ void UpdateUI(int64_t service_worker_registration_id,
+ const std::string& developer_id,
+ const std::string& unique_id,
const std::string& title,
blink::mojom::BackgroundFetchError* out_error) {
DCHECK(out_error);
base::RunLoop run_loop;
- service_->UpdateUI(unique_id, title,
+ service_->UpdateUI(service_worker_registration_id, unique_id, developer_id,
+ title,
base::BindOnce(&BackgroundFetchServiceTest::DidGetError,
base::Unretained(this),
run_loop.QuitClosure(), out_error));
@@ -214,7 +217,7 @@ class BackgroundFetchServiceTest : public BackgroundFetchTestBase {
*out_registration =
registration ? registration.value() : BackgroundFetchRegistration();
- quit_closure.Run();
+ std::move(quit_closure).Run();
}
void DidGetError(base::Closure quit_closure,
@@ -222,7 +225,7 @@ class BackgroundFetchServiceTest : public BackgroundFetchTestBase {
blink::mojom::BackgroundFetchError error) {
*out_error = error;
- quit_closure.Run();
+ std::move(quit_closure).Run();
}
void DidGetDeveloperIds(base::Closure quit_closure,
@@ -233,7 +236,7 @@ class BackgroundFetchServiceTest : public BackgroundFetchTestBase {
*out_error = error;
*out_developer_ids = developer_ids;
- quit_closure.Run();
+ std::move(quit_closure).Run();
}
scoped_refptr<BackgroundFetchContext> context_;
@@ -258,7 +261,7 @@ TEST_F(BackgroundFetchServiceTest, FetchInvalidArguments) {
BackgroundFetchRegistration registration;
Fetch(42 /* service_worker_registration_id */, "" /* developer_id */,
- requests, options, &error, &registration);
+ requests, options, SkBitmap(), &error, &registration);
ASSERT_EQ(error, blink::mojom::BackgroundFetchError::INVALID_ARGUMENT);
EXPECT_EQ("Invalid developer_id", bad_message_observer.last_error());
}
@@ -273,7 +276,7 @@ TEST_F(BackgroundFetchServiceTest, FetchInvalidArguments) {
BackgroundFetchRegistration registration;
Fetch(42 /* service_worker_registration_id */, kExampleDeveloperId,
- requests, options, &error, &registration);
+ requests, options, SkBitmap(), &error, &registration);
ASSERT_EQ(error, blink::mojom::BackgroundFetchError::INVALID_ARGUMENT);
EXPECT_EQ("Invalid requests", bad_message_observer.last_error());
}
@@ -301,7 +304,7 @@ TEST_F(BackgroundFetchServiceTest, FetchRegistrationProperties) {
BackgroundFetchRegistration registration;
Fetch(service_worker_registration_id, kExampleDeveloperId, requests, options,
- &error, &registration);
+ SkBitmap(), &error, &registration);
ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
// The |registration| should reflect the options given in |options|.
@@ -341,7 +344,7 @@ TEST_F(BackgroundFetchServiceTest, FetchDuplicatedRegistrationFailure) {
// Create the first registration. This must succeed.
Fetch(service_worker_registration_id, kExampleDeveloperId, requests, options,
- &error, &registration);
+ SkBitmap(), &error, &registration);
ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
blink::mojom::BackgroundFetchError second_error;
@@ -349,7 +352,7 @@ TEST_F(BackgroundFetchServiceTest, FetchDuplicatedRegistrationFailure) {
// Create the second registration with the same data. This must fail.
Fetch(service_worker_registration_id, kExampleDeveloperId, requests, options,
- &second_error, &second_registration);
+ SkBitmap(), &second_error, &second_registration);
ASSERT_EQ(second_error,
blink::mojom::BackgroundFetchError::DUPLICATED_DEVELOPER_ID);
}
@@ -409,7 +412,7 @@ TEST_F(BackgroundFetchServiceTest, FetchSuccessEventDispatch) {
// Create the first registration. This must succeed.
Fetch(service_worker_registration_id, kExampleDeveloperId, requests,
- options, &error, &registration);
+ options, SkBitmap(), &error, &registration);
ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
}
@@ -508,7 +511,7 @@ TEST_F(BackgroundFetchServiceTest, FetchFailEventDispatch) {
// Create the first registration. This must succeed.
Fetch(service_worker_registration_id, kExampleDeveloperId, requests,
- options, &error, &registration);
+ options, SkBitmap(), &error, &registration);
ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
}
@@ -579,13 +582,15 @@ TEST_F(BackgroundFetchServiceTest, UpdateUI) {
// Create the registration.
BackgroundFetchRegistrationId registration_id =
Fetch(service_worker_registration_id, kExampleDeveloperId, requests,
- options, &error, &registration);
+ options, SkBitmap(), &error, &registration);
ASSERT_EQ(blink::mojom::BackgroundFetchError::NONE, error);
std::string second_title = "2nd title";
// Immediately update the title. This should succeed.
- UpdateUI(registration_id.unique_id(), second_title, &error);
+ UpdateUI(registration_id.service_worker_registration_id(),
+ registration_id.unique_id(), registration_id.developer_id(),
+ second_title, &error);
EXPECT_EQ(blink::mojom::BackgroundFetchError::NONE, error);
BackgroundFetchRegistration second_registration;
@@ -615,7 +620,7 @@ TEST_F(BackgroundFetchServiceTest, Abort) {
// Create the registration. This must succeed.
BackgroundFetchRegistrationId registration_id =
Fetch(service_worker_registration_id, kExampleDeveloperId, requests,
- options, &error, &registration);
+ options, SkBitmap(), &error, &registration);
ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
blink::mojom::BackgroundFetchError abort_error;
@@ -705,8 +710,9 @@ TEST_F(BackgroundFetchServiceTest, AbortEventDispatch) {
BackgroundFetchRegistration registration;
// Create the registration. This must succeed.
- registration_id = Fetch(service_worker_registration_id, kExampleDeveloperId,
- requests, options, &error, &registration);
+ registration_id =
+ Fetch(service_worker_registration_id, kExampleDeveloperId, requests,
+ options, SkBitmap(), &error, &registration);
ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
}
@@ -751,7 +757,7 @@ TEST_F(BackgroundFetchServiceTest, UniqueId) {
BackgroundFetchRegistration aborted_registration;
BackgroundFetchRegistrationId aborted_registration_id =
Fetch(service_worker_registration_id, kExampleDeveloperId, requests,
- aborted_options, &error, &aborted_registration);
+ aborted_options, SkBitmap(), &error, &aborted_registration);
ASSERT_EQ(blink::mojom::BackgroundFetchError::NONE, error);
// Immediately abort the registration so it is no longer active (everything
@@ -770,7 +776,7 @@ TEST_F(BackgroundFetchServiceTest, UniqueId) {
BackgroundFetchRegistration second_registration;
BackgroundFetchRegistrationId second_registration_id =
Fetch(service_worker_registration_id, kExampleDeveloperId, requests,
- second_options, &error, &second_registration);
+ second_options, SkBitmap(), &error, &second_registration);
EXPECT_EQ(blink::mojom::BackgroundFetchError::NONE, error);
// Now try to get the registration using its |developer_id|. This should
@@ -784,7 +790,9 @@ TEST_F(BackgroundFetchServiceTest, UniqueId) {
// Calling UpdateUI for the second registration should succeed, and update the
// title of the second registration only.
std::string updated_second_registration_title = "Foo";
- UpdateUI(second_registration_id.unique_id(),
+ UpdateUI(second_registration_id.service_worker_registration_id(),
+ second_registration_id.unique_id(),
+ second_registration_id.developer_id(),
updated_second_registration_title, &error);
EXPECT_EQ(blink::mojom::BackgroundFetchError::NONE, error);
@@ -792,7 +800,9 @@ TEST_F(BackgroundFetchServiceTest, UniqueId) {
// calling UpdateUI before resolving the waitUntil promise of a
// backgroundfetched or backgroundfetchfail event, both of which should
// work even though that registration is no longer active).
- UpdateUI(aborted_registration_id.unique_id(), "Bar", &error);
+ UpdateUI(aborted_registration_id.service_worker_registration_id(),
+ aborted_registration_id.unique_id(),
+ aborted_registration_id.developer_id(), "Bar", &error);
EXPECT_EQ(blink::mojom::BackgroundFetchError::INVALID_ID, error);
// Verify that the second registration's title was indeed updated, and that it
@@ -865,7 +875,7 @@ TEST_F(BackgroundFetchServiceTest, GetDeveloperIds) {
BackgroundFetchRegistration registration;
Fetch(service_worker_registration_id, kExampleDeveloperId, requests,
- options, &error, &registration);
+ options, SkBitmap(), &error, &registration);
ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
}
@@ -887,7 +897,7 @@ TEST_F(BackgroundFetchServiceTest, GetDeveloperIds) {
BackgroundFetchRegistration registration;
Fetch(service_worker_registration_id, kAlternativeDeveloperId, requests,
- options, &error, &registration);
+ options, SkBitmap(), &error, &registration);
ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
}
diff --git a/chromium/content/browser/background_fetch/background_fetch_test_base.cc b/chromium/content/browser/background_fetch/background_fetch_test_base.cc
index a455fc5e40c..7c08e174d5b 100644
--- a/chromium/content/browser/background_fetch/background_fetch_test_base.cc
+++ b/chromium/content/browser/background_fetch/background_fetch_test_base.cc
@@ -15,7 +15,6 @@
#include "base/files/scoped_temp_dir.h"
#include "base/guid.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/weak_ptr.h"
#include "base/run_loop.h"
#include "base/time/time.h"
@@ -44,7 +43,7 @@ void DidRegisterServiceWorker(int64_t* out_service_worker_registration_id,
*out_service_worker_registration_id = service_worker_registration_id;
- quit_closure.Run();
+ std::move(quit_closure).Run();
}
void DidFindServiceWorkerRegistration(
@@ -57,7 +56,7 @@ void DidFindServiceWorkerRegistration(
*out_service_worker_registration = service_worker_registration;
- quit_closure.Run();
+ std::move(quit_closure).Run();
}
} // namespace
@@ -95,8 +94,9 @@ int64_t BackgroundFetchTestBase::RegisterServiceWorker() {
base::RunLoop run_loop;
embedded_worker_test_helper_.context()->RegisterServiceWorker(
script_url, options,
- base::Bind(&DidRegisterServiceWorker, &service_worker_registration_id,
- run_loop.QuitClosure()));
+ base::BindOnce(&DidRegisterServiceWorker,
+ &service_worker_registration_id,
+ run_loop.QuitClosure()));
run_loop.Run();
}
diff --git a/chromium/content/browser/background_fetch/mock_background_fetch_delegate.cc b/chromium/content/browser/background_fetch/mock_background_fetch_delegate.cc
index 4ac18a40e3c..ffe514bd9c5 100644
--- a/chromium/content/browser/background_fetch/mock_background_fetch_delegate.cc
+++ b/chromium/content/browser/background_fetch/mock_background_fetch_delegate.cc
@@ -55,10 +55,14 @@ MockBackgroundFetchDelegate::MockBackgroundFetchDelegate() {}
MockBackgroundFetchDelegate::~MockBackgroundFetchDelegate() {}
+void MockBackgroundFetchDelegate::GetIconDisplaySize(
+ GetIconDisplaySizeCallback callback) {}
+
void MockBackgroundFetchDelegate::CreateDownloadJob(
const std::string& job_unique_id,
const std::string& title,
const url::Origin& origin,
+ const SkBitmap& icon,
int completed_parts,
int total_parts,
const std::vector<std::string>& current_guids) {}
diff --git a/chromium/content/browser/background_fetch/mock_background_fetch_delegate.h b/chromium/content/browser/background_fetch/mock_background_fetch_delegate.h
index 953c01e071e..fe63a87b786 100644
--- a/chromium/content/browser/background_fetch/mock_background_fetch_delegate.h
+++ b/chromium/content/browser/background_fetch/mock_background_fetch_delegate.h
@@ -63,10 +63,13 @@ class MockBackgroundFetchDelegate : public BackgroundFetchDelegate {
~MockBackgroundFetchDelegate() override;
// BackgroundFetchDelegate implementation:
+ void GetIconDisplaySize(
+ BackgroundFetchDelegate::GetIconDisplaySizeCallback callback) override;
void CreateDownloadJob(
const std::string& job_unique_id,
const std::string& title,
const url::Origin& origin,
+ const SkBitmap& icon,
int completed_parts,
int total_parts,
const std::vector<std::string>& current_guids) override;
diff --git a/chromium/content/browser/background_fetch/storage/README.md b/chromium/content/browser/background_fetch/storage/README.md
index 7a2ca5dcd93..8292ab494e2 100644
--- a/chromium/content/browser/background_fetch/storage/README.md
+++ b/chromium/content/browser/background_fetch/storage/README.md
@@ -21,7 +21,7 @@ value: "<unique_id>"
```
```
key: "bgfetch_registration_<unique_id>"
-value: "<serialized content::proto::BackgroundFetchRegistration>"
+value: "<serialized content::proto::BackgroundFetchMetadata>"
```
```
key: "bgfetch_request_<unique_id>_<request_index>"
diff --git a/chromium/content/browser/background_fetch/storage/cleanup_task.cc b/chromium/content/browser/background_fetch/storage/cleanup_task.cc
index 5a2e51767f2..047ec4b9015 100644
--- a/chromium/content/browser/background_fetch/storage/cleanup_task.cc
+++ b/chromium/content/browser/background_fetch/storage/cleanup_task.cc
@@ -68,10 +68,11 @@ void CleanupTask::DidGetActiveUniqueIds(
for (const auto& entry : registration_data) {
int64_t service_worker_registration_id = entry.first;
- proto::BackgroundFetchRegistration registration_proto;
- if (registration_proto.ParseFromString(entry.second)) {
- if (registration_proto.has_unique_id()) {
- const std::string& unique_id = registration_proto.unique_id();
+ proto::BackgroundFetchMetadata metadata_proto;
+ if (metadata_proto.ParseFromString(entry.second)) {
+ if (metadata_proto.registration().has_unique_id()) {
+ const std::string& unique_id =
+ metadata_proto.registration().unique_id();
if (!active_unique_ids.count(unique_id) &&
!ref_counted_unique_ids().count(unique_id)) {
// This |unique_id| can be safely cleaned up. Re-use
diff --git a/chromium/content/browser/background_fetch/storage/create_registration_task.cc b/chromium/content/browser/background_fetch/storage/create_metadata_task.cc
index 20bb337da25..18d45c6ec2a 100644
--- a/chromium/content/browser/background_fetch/storage/create_registration_task.cc
+++ b/chromium/content/browser/background_fetch/storage/create_metadata_task.cc
@@ -2,12 +2,11 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "content/browser/background_fetch/storage/create_registration_task.h"
+#include "content/browser/background_fetch/storage/create_metadata_task.h"
#include <utility>
#include "base/strings/string_number_conversions.h"
-#include "content/browser/background_fetch/background_fetch.pb.h"
#include "content/browser/background_fetch/storage/database_helpers.h"
#include "content/browser/service_worker/service_worker_context_wrapper.h"
#include "content/common/service_worker/service_worker_status_code.h"
@@ -21,12 +20,12 @@ std::string RequestKey(const std::string& unique_id, int request_index) {
return RequestKeyPrefix(unique_id) + base::IntToString(request_index);
}
-CreateRegistrationTask::CreateRegistrationTask(
+CreateMetadataTask::CreateMetadataTask(
BackgroundFetchDataManager* data_manager,
const BackgroundFetchRegistrationId& registration_id,
const std::vector<ServiceWorkerFetchRequest>& requests,
const BackgroundFetchOptions& options,
- CreateRegistrationCallback callback)
+ CreateMetadataCallback callback)
: DatabaseTask(data_manager),
registration_id_(registration_id),
requests_(requests),
@@ -34,22 +33,21 @@ CreateRegistrationTask::CreateRegistrationTask(
callback_(std::move(callback)),
weak_factory_(this) {}
-CreateRegistrationTask::~CreateRegistrationTask() = default;
+CreateMetadataTask::~CreateMetadataTask() = default;
-void CreateRegistrationTask::Start() {
+void CreateMetadataTask::Start() {
service_worker_context()->GetRegistrationUserData(
registration_id_.service_worker_registration_id(),
{ActiveRegistrationUniqueIdKey(registration_id_.developer_id())},
- base::BindOnce(&CreateRegistrationTask::DidGetUniqueId,
+ base::BindOnce(&CreateMetadataTask::DidGetUniqueId,
weak_factory_.GetWeakPtr()));
}
-void CreateRegistrationTask::DidGetUniqueId(
- const std::vector<std::string>& data,
- ServiceWorkerStatusCode status) {
+void CreateMetadataTask::DidGetUniqueId(const std::vector<std::string>& data,
+ ServiceWorkerStatusCode status) {
switch (ToDatabaseStatus(status)) {
case DatabaseStatus::kNotFound:
- StoreRegistration();
+ StoreMetadata();
return;
case DatabaseStatus::kOk:
// Can't create a registration since there is already an active
@@ -57,59 +55,64 @@ void CreateRegistrationTask::DidGetUniqueId(
// (completed/failed/aborted) first.
std::move(callback_).Run(
blink::mojom::BackgroundFetchError::DUPLICATED_DEVELOPER_ID,
- nullptr /* registration */);
+ nullptr /* metadata */);
Finished(); // Destroys |this|.
return;
case DatabaseStatus::kFailed:
std::move(callback_).Run(
blink::mojom::BackgroundFetchError::STORAGE_ERROR,
- nullptr /* registration */);
+ nullptr /* metadata */);
Finished(); // Destroys |this|.
return;
}
}
-void CreateRegistrationTask::StoreRegistration() {
- DCHECK(!registration_);
- DCHECK(!registration_id_.origin().unique());
-
- int64_t registration_creation_microseconds_since_unix_epoch =
- (base::Time::Now() - base::Time::UnixEpoch()).InMicroseconds();
+void CreateMetadataTask::InitializeMetadataProto() {
+ metadata_proto_ = std::make_unique<proto::BackgroundFetchMetadata>();
+ // Set BackgroundFetchRegistration fields.
+ // Upload/Download stats default to correct initial values.
+ auto* registration_proto = metadata_proto_->mutable_registration();
+ registration_proto->set_unique_id(registration_id_.unique_id());
+ registration_proto->set_developer_id(registration_id_.developer_id());
+
+ // Set Options fields.
+ auto* options_proto = metadata_proto_->mutable_options();
+ options_proto->set_title(options_.title);
+ options_proto->set_download_total(options_.download_total);
+ for (const auto& icon : options_.icons) {
+ auto* icon_definition_proto = options_proto->add_icons();
+ icon_definition_proto->set_src(icon.src);
+ icon_definition_proto->set_sizes(icon.sizes);
+ icon_definition_proto->set_type(icon.type);
+ }
- registration_ = std::make_unique<BackgroundFetchRegistration>();
- registration_->developer_id = registration_id_.developer_id();
- registration_->unique_id = registration_id_.unique_id();
- // TODO(crbug.com/774054): Uploads are not yet supported.
- registration_->upload_total = 0;
- registration_->uploaded = 0;
- registration_->download_total = options_.download_total;
- registration_->downloaded = 0;
+ // Set other metadata fields.
+ metadata_proto_->set_origin(registration_id_.origin().Serialize());
+ metadata_proto_->set_creation_microseconds_since_unix_epoch(
+ (base::Time::Now() - base::Time::UnixEpoch()).InMicroseconds());
+ metadata_proto_->set_ui_title(options_.title);
+}
+void CreateMetadataTask::StoreMetadata() {
std::vector<std::pair<std::string, std::string>> entries;
entries.reserve(requests_.size() * 2 + 1);
- // First serialize per-registration (as opposed to per-request) data.
- // TODO(crbug.com/757760): Serialize BackgroundFetchOptions as part of this.
- proto::BackgroundFetchRegistration registration_proto;
- registration_proto.set_unique_id(registration_->unique_id);
- registration_proto.set_developer_id(registration_->developer_id);
- registration_proto.set_origin(registration_id_.origin().Serialize());
- registration_proto.set_creation_microseconds_since_unix_epoch(
- registration_creation_microseconds_since_unix_epoch);
- // TODO(delphick): Write options to the proto.
- std::string serialized_registration_proto;
- if (!registration_proto.SerializeToString(&serialized_registration_proto)) {
+ InitializeMetadataProto();
+ std::string serialized_metadata_proto;
+
+ if (!metadata_proto_->SerializeToString(&serialized_metadata_proto)) {
// TODO(crbug.com/780025): Log failures to UMA.
std::move(callback_).Run(blink::mojom::BackgroundFetchError::STORAGE_ERROR,
- nullptr /* registration */);
+ nullptr /* metadata */);
Finished(); // Destroys |this|.
return;
}
+
entries.emplace_back(
ActiveRegistrationUniqueIdKey(registration_id_.developer_id()),
registration_id_.unique_id());
entries.emplace_back(RegistrationKey(registration_id_.unique_id()),
- std::move(serialized_registration_proto));
+ std::move(serialized_metadata_proto));
// Signed integers are used for request indexes to avoid unsigned gotchas.
for (int i = 0; i < base::checked_cast<int>(requests_.size()); i++) {
@@ -117,21 +120,21 @@ void CreateRegistrationTask::StoreRegistration() {
entries.emplace_back(RequestKey(registration_id_.unique_id(), i),
"TODO: Serialize FetchAPIRequest as value");
entries.emplace_back(
- PendingRequestKey(registration_creation_microseconds_since_unix_epoch,
- registration_id_.unique_id(), i),
+ PendingRequestKey(
+ metadata_proto_->creation_microseconds_since_unix_epoch(),
+ registration_id_.unique_id(), i),
std::string());
}
service_worker_context()->StoreRegistrationUserData(
registration_id_.service_worker_registration_id(),
registration_id_.origin().GetURL(), entries,
- base::Bind(&CreateRegistrationTask::DidStoreRegistration,
- weak_factory_.GetWeakPtr()));
+ base::BindRepeating(&CreateMetadataTask::DidStoreMetadata,
+ weak_factory_.GetWeakPtr()));
}
-void CreateRegistrationTask::DidStoreRegistration(
- ServiceWorkerStatusCode status) {
- DCHECK(registration_);
+void CreateMetadataTask::DidStoreMetadata(ServiceWorkerStatusCode status) {
+ DCHECK(metadata_proto_);
switch (ToDatabaseStatus(status)) {
case DatabaseStatus::kOk:
@@ -140,13 +143,13 @@ void CreateRegistrationTask::DidStoreRegistration(
case DatabaseStatus::kNotFound:
std::move(callback_).Run(
blink::mojom::BackgroundFetchError::STORAGE_ERROR,
- nullptr /* registration */);
+ nullptr /* metadata */);
Finished(); // Destroys |this|.
return;
}
std::move(callback_).Run(blink::mojom::BackgroundFetchError::NONE,
- std::move(registration_));
+ std::move(metadata_proto_));
Finished(); // Destroys |this|.
}
} // namespace background_fetch
diff --git a/chromium/content/browser/background_fetch/storage/create_metadata_task.h b/chromium/content/browser/background_fetch/storage/create_metadata_task.h
new file mode 100644
index 00000000000..433c265c38a
--- /dev/null
+++ b/chromium/content/browser/background_fetch/storage/create_metadata_task.h
@@ -0,0 +1,64 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_BROWSER_BACKGROUND_FETCH_STORAGE_CREATE_METADATA_TASK_H_
+#define CONTENT_BROWSER_BACKGROUND_FETCH_STORAGE_CREATE_METADATA_TASK_H_
+
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "content/browser/background_fetch/background_fetch.pb.h"
+#include "content/browser/background_fetch/storage/database_task.h"
+#include "content/common/service_worker/service_worker_status_code.h"
+#include "third_party/blink/public/platform/modules/background_fetch/background_fetch.mojom.h"
+
+namespace content {
+
+namespace background_fetch {
+
+// Creates Background Fetch metadata entries in the database.
+class CreateMetadataTask : public DatabaseTask {
+ public:
+ using CreateMetadataCallback =
+ base::OnceCallback<void(blink::mojom::BackgroundFetchError,
+ std::unique_ptr<proto::BackgroundFetchMetadata>)>;
+
+ CreateMetadataTask(BackgroundFetchDataManager* data_manager,
+ const BackgroundFetchRegistrationId& registration_id,
+ const std::vector<ServiceWorkerFetchRequest>& requests,
+ const BackgroundFetchOptions& options,
+ CreateMetadataCallback callback);
+
+ ~CreateMetadataTask() override;
+
+ void Start() override;
+
+ private:
+ void DidGetUniqueId(const std::vector<std::string>& data,
+ ServiceWorkerStatusCode status);
+
+ void StoreMetadata();
+
+ void DidStoreMetadata(ServiceWorkerStatusCode status);
+
+ void InitializeMetadataProto();
+
+ BackgroundFetchRegistrationId registration_id_;
+ std::vector<ServiceWorkerFetchRequest> requests_;
+ BackgroundFetchOptions options_;
+ CreateMetadataCallback callback_;
+
+ std::unique_ptr<proto::BackgroundFetchMetadata> metadata_proto_;
+
+ base::WeakPtrFactory<CreateMetadataTask> weak_factory_; // Keep as last.
+
+ DISALLOW_COPY_AND_ASSIGN(CreateMetadataTask);
+};
+
+} // namespace background_fetch
+
+} // namespace content
+
+#endif // CONTENT_BROWSER_BACKGROUND_FETCH_STORAGE_CREATE_METADATA_TASK_H_
diff --git a/chromium/content/browser/background_fetch/storage/create_registration_task.h b/chromium/content/browser/background_fetch/storage/create_registration_task.h
deleted file mode 100644
index a045e21a4d9..00000000000
--- a/chromium/content/browser/background_fetch/storage/create_registration_task.h
+++ /dev/null
@@ -1,62 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_BACKGROUND_FETCH_STORAGE_CREATE_REGISTRATION_TASK_H_
-#define CONTENT_BROWSER_BACKGROUND_FETCH_STORAGE_CREATE_REGISTRATION_TASK_H_
-
-#include <memory>
-#include <string>
-#include <vector>
-
-#include "content/browser/background_fetch/storage/database_task.h"
-#include "content/common/service_worker/service_worker_status_code.h"
-#include "content/common/service_worker/service_worker_types.h"
-#include "third_party/WebKit/public/platform/modules/background_fetch/background_fetch.mojom.h"
-
-namespace content {
-
-namespace background_fetch {
-
-// Creates Background Fetch registration entries in the database.
-class CreateRegistrationTask : public DatabaseTask {
- public:
- using CreateRegistrationCallback =
- base::OnceCallback<void(blink::mojom::BackgroundFetchError,
- std::unique_ptr<BackgroundFetchRegistration>)>;
-
- CreateRegistrationTask(BackgroundFetchDataManager* data_manager,
- const BackgroundFetchRegistrationId& registration_id,
- const std::vector<ServiceWorkerFetchRequest>& requests,
- const BackgroundFetchOptions& options,
- CreateRegistrationCallback callback);
-
- ~CreateRegistrationTask() override;
-
- void Start() override;
-
- private:
- void DidGetUniqueId(const std::vector<std::string>& data,
- ServiceWorkerStatusCode status);
-
- void StoreRegistration();
-
- void DidStoreRegistration(ServiceWorkerStatusCode status);
-
- BackgroundFetchRegistrationId registration_id_;
- std::vector<ServiceWorkerFetchRequest> requests_;
- BackgroundFetchOptions options_;
- CreateRegistrationCallback callback_;
-
- std::unique_ptr<BackgroundFetchRegistration> registration_;
-
- base::WeakPtrFactory<CreateRegistrationTask> weak_factory_; // Keep as last.
-
- DISALLOW_COPY_AND_ASSIGN(CreateRegistrationTask);
-};
-
-} // namespace background_fetch
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_BACKGROUND_FETCH_STORAGE_CREATE_REGISTRATION_TASK_H_
diff --git a/chromium/content/browser/background_fetch/storage/database_task.h b/chromium/content/browser/background_fetch/storage/database_task.h
index a29db2d44c5..3d46a0fb358 100644
--- a/chromium/content/browser/background_fetch/storage/database_task.h
+++ b/chromium/content/browser/background_fetch/storage/database_task.h
@@ -12,7 +12,7 @@
#include "base/logging.h"
#include "base/macros.h"
#include "content/browser/background_fetch/background_fetch_registration_id.h"
-#include "third_party/WebKit/public/platform/modules/background_fetch/background_fetch.mojom.h"
+#include "third_party/blink/public/platform/modules/background_fetch/background_fetch.mojom.h"
namespace content {
diff --git a/chromium/content/browser/background_fetch/storage/delete_registration_task.cc b/chromium/content/browser/background_fetch/storage/delete_registration_task.cc
index 0663fc47038..92cb468eac8 100644
--- a/chromium/content/browser/background_fetch/storage/delete_registration_task.cc
+++ b/chromium/content/browser/background_fetch/storage/delete_registration_task.cc
@@ -68,12 +68,13 @@ void DeleteRegistrationTask::DidGetRegistration(
#if DCHECK_IS_ON()
if (ToDatabaseStatus(status) == DatabaseStatus::kOk) {
DCHECK_EQ(1u, data.size());
- proto::BackgroundFetchRegistration registration_proto;
- if (registration_proto.ParseFromString(data[0]) &&
- registration_proto.has_developer_id()) {
+ proto::BackgroundFetchMetadata metadata_proto;
+ if (metadata_proto.ParseFromString(data[0]) &&
+ metadata_proto.registration().has_developer_id()) {
service_worker_context()->GetRegistrationUserData(
service_worker_registration_id_,
- {ActiveRegistrationUniqueIdKey(registration_proto.developer_id())},
+ {ActiveRegistrationUniqueIdKey(
+ metadata_proto.registration().developer_id())},
base::BindOnce(&DCheckRegistrationNotActive, unique_id_));
} else {
NOTREACHED()
@@ -87,8 +88,8 @@ void DeleteRegistrationTask::DidGetRegistration(
service_worker_context()->ClearRegistrationUserDataByKeyPrefixes(
service_worker_registration_id_,
{RegistrationKey(unique_id_), RequestKeyPrefix(unique_id_)},
- base::Bind(&DeleteRegistrationTask::DidDeleteRegistration,
- weak_factory_.GetWeakPtr()));
+ base::BindOnce(&DeleteRegistrationTask::DidDeleteRegistration,
+ weak_factory_.GetWeakPtr()));
}
void DeleteRegistrationTask::DidDeleteRegistration(
diff --git a/chromium/content/browser/background_fetch/storage/get_developer_ids_task.h b/chromium/content/browser/background_fetch/storage/get_developer_ids_task.h
index 207fac55f00..b205c712794 100644
--- a/chromium/content/browser/background_fetch/storage/get_developer_ids_task.h
+++ b/chromium/content/browser/background_fetch/storage/get_developer_ids_task.h
@@ -12,7 +12,7 @@
#include "base/containers/flat_map.h"
#include "content/browser/background_fetch/storage/database_task.h"
#include "content/common/service_worker/service_worker_status_code.h"
-#include "third_party/WebKit/public/platform/modules/background_fetch/background_fetch.mojom.h"
+#include "third_party/blink/public/platform/modules/background_fetch/background_fetch.mojom.h"
#include "url/origin.h"
namespace content {
diff --git a/chromium/content/browser/background_fetch/storage/get_registration_task.cc b/chromium/content/browser/background_fetch/storage/get_metadata_task.cc
index 57c46f9ff20..e80738b9b2e 100644
--- a/chromium/content/browser/background_fetch/storage/get_registration_task.cc
+++ b/chromium/content/browser/background_fetch/storage/get_metadata_task.cc
@@ -2,11 +2,10 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "content/browser/background_fetch/storage/get_registration_task.h"
+#include "content/browser/background_fetch/storage/get_metadata_task.h"
#include <utility>
-#include "content/browser/background_fetch/background_fetch.pb.h"
#include "content/browser/background_fetch/storage/database_helpers.h"
#include "content/browser/service_worker/service_worker_context_wrapper.h"
#include "url/gurl.h"
@@ -15,12 +14,11 @@ namespace content {
namespace background_fetch {
-GetRegistrationTask::GetRegistrationTask(
- BackgroundFetchDataManager* data_manager,
- int64_t service_worker_registration_id,
- const url::Origin& origin,
- const std::string& developer_id,
- GetRegistrationCallback callback)
+GetMetadataTask::GetMetadataTask(BackgroundFetchDataManager* data_manager,
+ int64_t service_worker_registration_id,
+ const url::Origin& origin,
+ const std::string& developer_id,
+ GetMetadataCallback callback)
: DatabaseTask(data_manager),
service_worker_registration_id_(service_worker_registration_id),
origin_(origin),
@@ -28,93 +26,85 @@ GetRegistrationTask::GetRegistrationTask(
callback_(std::move(callback)),
weak_factory_(this) {}
-GetRegistrationTask::~GetRegistrationTask() = default;
+GetMetadataTask::~GetMetadataTask() = default;
-void GetRegistrationTask::Start() {
+void GetMetadataTask::Start() {
service_worker_context()->GetRegistrationUserData(
service_worker_registration_id_,
{ActiveRegistrationUniqueIdKey(developer_id_)},
- base::BindOnce(&GetRegistrationTask::DidGetUniqueId,
+ base::BindOnce(&GetMetadataTask::DidGetUniqueId,
weak_factory_.GetWeakPtr()));
}
-void GetRegistrationTask::DidGetUniqueId(const std::vector<std::string>& data,
- ServiceWorkerStatusCode status) {
+void GetMetadataTask::DidGetUniqueId(const std::vector<std::string>& data,
+ ServiceWorkerStatusCode status) {
switch (ToDatabaseStatus(status)) {
case DatabaseStatus::kNotFound:
std::move(callback_).Run(blink::mojom::BackgroundFetchError::INVALID_ID,
- nullptr /* registration */);
+ nullptr /* metadata */);
Finished(); // Destroys |this|.
return;
case DatabaseStatus::kOk:
DCHECK_EQ(1u, data.size());
service_worker_context()->GetRegistrationUserData(
service_worker_registration_id_, {RegistrationKey(data[0])},
- base::BindOnce(&GetRegistrationTask::DidGetRegistration,
+ base::BindOnce(&GetMetadataTask::DidGetMetadata,
weak_factory_.GetWeakPtr()));
return;
case DatabaseStatus::kFailed:
std::move(callback_).Run(
blink::mojom::BackgroundFetchError::STORAGE_ERROR,
- nullptr /* registration */);
+ nullptr /* metadata */);
Finished(); // Destroys |this|.
return;
}
}
-void GetRegistrationTask::DidGetRegistration(
- const std::vector<std::string>& data,
- ServiceWorkerStatusCode status) {
+void GetMetadataTask::DidGetMetadata(const std::vector<std::string>& data,
+ ServiceWorkerStatusCode status) {
switch (ToDatabaseStatus(status)) {
case DatabaseStatus::kNotFound:
// The database is corrupt as there's no registration data despite there
// being an active developer_id pointing to it.
std::move(callback_).Run(
blink::mojom::BackgroundFetchError::STORAGE_ERROR,
- nullptr /* registration */);
+ nullptr /* metadata */);
Finished(); // Destroys |this|.
return;
case DatabaseStatus::kOk:
DCHECK_EQ(1u, data.size());
- CreateRegistration(data[0]);
+ ProcessMetadata(data[0]);
return;
case DatabaseStatus::kFailed:
std::move(callback_).Run(
blink::mojom::BackgroundFetchError::STORAGE_ERROR,
- nullptr /* registration */);
+ nullptr /* metadata */);
Finished(); // Destroys |this|.
return;
}
}
-void GetRegistrationTask::CreateRegistration(
- const std::string& registration_data) {
- proto::BackgroundFetchRegistration registration_proto;
- if (!registration_proto.ParseFromString(registration_data)) {
+void GetMetadataTask::ProcessMetadata(const std::string& metadata) {
+ metadata_proto_ = std::make_unique<proto::BackgroundFetchMetadata>();
+ if (!metadata_proto_->ParseFromString(metadata)) {
std::move(callback_).Run(blink::mojom::BackgroundFetchError::STORAGE_ERROR,
- nullptr /* registration */);
+ nullptr /* metadata */);
Finished();
return;
}
- auto registration = std::make_unique<BackgroundFetchRegistration>();
+ const auto& registration_proto = metadata_proto_->registration();
if (registration_proto.developer_id() != developer_id_ ||
!origin_.IsSameOriginWith(
- url::Origin::Create(GURL(registration_proto.origin())))) {
+ url::Origin::Create(GURL(metadata_proto_->origin())))) {
std::move(callback_).Run(blink::mojom::BackgroundFetchError::STORAGE_ERROR,
- nullptr /* registration */);
+ nullptr /* metadata */);
Finished();
return;
}
- registration->developer_id = registration_proto.developer_id();
- registration->unique_id = registration_proto.unique_id();
-
- // TODO(delphick): Initialize all the other parts of the registration once
- // they're persisted.
-
std::move(callback_).Run(blink::mojom::BackgroundFetchError::NONE,
- std::move(registration));
+ std::move(metadata_proto_));
Finished();
}
diff --git a/chromium/content/browser/background_fetch/storage/get_metadata_task.h b/chromium/content/browser/background_fetch/storage/get_metadata_task.h
new file mode 100644
index 00000000000..bf51554aa3d
--- /dev/null
+++ b/chromium/content/browser/background_fetch/storage/get_metadata_task.h
@@ -0,0 +1,66 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_BROWSER_BACKGROUND_FETCH_STORAGE_GET_METADATA_TASK_H_
+#define CONTENT_BROWSER_BACKGROUND_FETCH_STORAGE_GET_METADATA_TASK_H_
+
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "base/callback_forward.h"
+#include "content/browser/background_fetch/background_fetch.pb.h"
+#include "content/browser/background_fetch/storage/database_task.h"
+#include "content/common/service_worker/service_worker_status_code.h"
+#include "url/origin.h"
+
+namespace content {
+
+namespace background_fetch {
+
+// Gets an active Background Fetch metadata entry from the database.
+class GetMetadataTask : public DatabaseTask {
+ public:
+ using GetMetadataCallback =
+ base::OnceCallback<void(blink::mojom::BackgroundFetchError,
+ std::unique_ptr<proto::BackgroundFetchMetadata>)>;
+
+ GetMetadataTask(BackgroundFetchDataManager* data_manager,
+ int64_t service_worker_registration_id,
+ const url::Origin& origin,
+ const std::string& developer_id,
+ GetMetadataCallback callback);
+
+ ~GetMetadataTask() override;
+
+ // DatabaseTask implementation:
+ void Start() override;
+
+ private:
+ void DidGetUniqueId(const std::vector<std::string>& data,
+ ServiceWorkerStatusCode status);
+
+ void DidGetMetadata(const std::vector<std::string>& data,
+ ServiceWorkerStatusCode status);
+
+ void ProcessMetadata(const std::string& metadata);
+
+ int64_t service_worker_registration_id_;
+ url::Origin origin_;
+ std::string developer_id_;
+
+ GetMetadataCallback callback_;
+
+ std::unique_ptr<proto::BackgroundFetchMetadata> metadata_proto_;
+
+ base::WeakPtrFactory<GetMetadataTask> weak_factory_; // Keep as last.
+
+ DISALLOW_COPY_AND_ASSIGN(GetMetadataTask);
+};
+
+} // namespace background_fetch
+
+} // namespace content
+
+#endif // CONTENT_BROWSER_BACKGROUND_FETCH_STORAGE_GET_METADATA_TASK_H_
diff --git a/chromium/content/browser/background_fetch/storage/get_registration_task.h b/chromium/content/browser/background_fetch/storage/get_registration_task.h
deleted file mode 100644
index e4498f84904..00000000000
--- a/chromium/content/browser/background_fetch/storage/get_registration_task.h
+++ /dev/null
@@ -1,63 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_BACKGROUND_FETCH_STORAGE_GET_REGISTRATION_TASK_H_
-#define CONTENT_BROWSER_BACKGROUND_FETCH_STORAGE_GET_REGISTRATION_TASK_H_
-
-#include <memory>
-#include <string>
-#include <vector>
-
-#include "base/callback_forward.h"
-#include "content/browser/background_fetch/storage/database_task.h"
-#include "content/common/service_worker/service_worker_status_code.h"
-#include "url/origin.h"
-
-namespace content {
-
-namespace background_fetch {
-
-// Gets an active Background Fetch registration entry from the database.
-class GetRegistrationTask : public DatabaseTask {
- public:
- using GetRegistrationCallback =
- base::OnceCallback<void(blink::mojom::BackgroundFetchError,
- std::unique_ptr<BackgroundFetchRegistration>)>;
-
- GetRegistrationTask(BackgroundFetchDataManager* data_manager,
- int64_t service_worker_registration_id,
- const url::Origin& origin,
- const std::string& developer_id,
- GetRegistrationCallback callback);
-
- ~GetRegistrationTask() override;
-
- // DatabaseTask implementation:
- void Start() override;
-
- private:
- void DidGetUniqueId(const std::vector<std::string>& data,
- ServiceWorkerStatusCode status);
-
- void DidGetRegistration(const std::vector<std::string>& data,
- ServiceWorkerStatusCode status);
-
- void CreateRegistration(const std::string& registration_data);
-
- int64_t service_worker_registration_id_;
- url::Origin origin_;
- std::string developer_id_;
-
- GetRegistrationCallback callback_;
-
- base::WeakPtrFactory<GetRegistrationTask> weak_factory_; // Keep as last.
-
- DISALLOW_COPY_AND_ASSIGN(GetRegistrationTask);
-};
-
-} // namespace background_fetch
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_BACKGROUND_FETCH_STORAGE_GET_REGISTRATION_TASK_H_
diff --git a/chromium/content/browser/background_fetch/storage/mark_registration_for_deletion_task.cc b/chromium/content/browser/background_fetch/storage/mark_registration_for_deletion_task.cc
index c6156f17922..365e6bf7115 100644
--- a/chromium/content/browser/background_fetch/storage/mark_registration_for_deletion_task.cc
+++ b/chromium/content/browser/background_fetch/storage/mark_registration_for_deletion_task.cc
@@ -64,9 +64,9 @@ void MarkRegistrationForDeletionTask::DidGetActiveUniqueId(
return;
}
- proto::BackgroundFetchRegistration registration_proto;
- if (registration_proto.ParseFromString(data[1]) &&
- registration_proto.has_creation_microseconds_since_unix_epoch()) {
+ proto::BackgroundFetchMetadata metadata_proto;
+ if (metadata_proto.ParseFromString(data[1]) &&
+ metadata_proto.has_creation_microseconds_since_unix_epoch()) {
// Mark registration as no longer active. Also deletes pending request
// keys, since those are globally sorted and requests within deactivated
// registrations are no longer eligible to be started. Pending request
@@ -75,10 +75,10 @@ void MarkRegistrationForDeletionTask::DidGetActiveUniqueId(
registration_id_.service_worker_registration_id(),
{ActiveRegistrationUniqueIdKey(registration_id_.developer_id()),
PendingRequestKeyPrefix(
- registration_proto.creation_microseconds_since_unix_epoch(),
+ metadata_proto.creation_microseconds_since_unix_epoch(),
registration_id_.unique_id())},
- base::Bind(&MarkRegistrationForDeletionTask::DidDeactivate,
- weak_factory_.GetWeakPtr()));
+ base::BindOnce(&MarkRegistrationForDeletionTask::DidDeactivate,
+ weak_factory_.GetWeakPtr()));
} else {
NOTREACHED() << "Database is corrupt"; // TODO(crbug.com/780027): Nuke it.
}
diff --git a/chromium/content/browser/background_fetch/storage/update_registration_ui_task.cc b/chromium/content/browser/background_fetch/storage/update_registration_ui_task.cc
new file mode 100644
index 00000000000..0c2bafb7825
--- /dev/null
+++ b/chromium/content/browser/background_fetch/storage/update_registration_ui_task.cc
@@ -0,0 +1,96 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/background_fetch/storage/update_registration_ui_task.h"
+
+#include "content/browser/background_fetch/storage/database_helpers.h"
+#include "content/browser/service_worker/service_worker_context_wrapper.h"
+#include "third_party/blink/public/platform/modules/background_fetch/background_fetch.mojom.h"
+
+namespace content {
+
+namespace background_fetch {
+
+UpdateRegistrationUITask::UpdateRegistrationUITask(
+ BackgroundFetchDataManager* data_manager,
+ const BackgroundFetchRegistrationId& registration_id,
+ const std::string& updated_title,
+ UpdateRegistrationUICallback callback)
+ : DatabaseTask(data_manager),
+ registration_id_(registration_id),
+ updated_title_(updated_title),
+ callback_(std::move(callback)),
+ weak_factory_(this) {}
+
+UpdateRegistrationUITask::~UpdateRegistrationUITask() = default;
+
+void UpdateRegistrationUITask::Start() {
+ service_worker_context()->GetRegistrationUserData(
+ registration_id_.service_worker_registration_id(),
+ {RegistrationKey(registration_id_.unique_id())},
+ base::BindOnce(&UpdateRegistrationUITask::DidGetMetadata,
+ weak_factory_.GetWeakPtr()));
+}
+
+void UpdateRegistrationUITask::DidGetMetadata(
+ const std::vector<std::string>& data,
+ ServiceWorkerStatusCode status) {
+ switch (ToDatabaseStatus(status)) {
+ case DatabaseStatus::kNotFound:
+ case DatabaseStatus::kFailed:
+ std::move(callback_).Run(
+ blink::mojom::BackgroundFetchError::STORAGE_ERROR);
+ Finished(); // Destroys |this|.
+ return;
+ case DatabaseStatus::kOk:
+ if (data.size() != 1u) {
+ std::move(callback_).Run(
+ blink::mojom::BackgroundFetchError::STORAGE_ERROR);
+ Finished(); // Destroys |this|.
+ return;
+ }
+ UpdateUI(data[0]);
+ return;
+ }
+}
+
+void UpdateRegistrationUITask::UpdateUI(
+ const std::string& serialized_metadata_proto) {
+ proto::BackgroundFetchMetadata metadata_proto;
+ if (!metadata_proto.ParseFromString(serialized_metadata_proto)) {
+ std::move(callback_).Run(blink::mojom::BackgroundFetchError::STORAGE_ERROR);
+ Finished(); // Destroys |this|.
+ return;
+ }
+
+ metadata_proto.set_ui_title(updated_title_);
+
+ service_worker_context()->StoreRegistrationUserData(
+ registration_id_.service_worker_registration_id(),
+ registration_id_.origin().GetURL(),
+ {{RegistrationKey(registration_id_.unique_id()),
+ metadata_proto.SerializeAsString()}},
+ base::BindOnce(&UpdateRegistrationUITask::DidUpdateUI,
+ weak_factory_.GetWeakPtr()));
+}
+
+void UpdateRegistrationUITask::DidUpdateUI(ServiceWorkerStatusCode status) {
+ switch (ToDatabaseStatus(status)) {
+ case DatabaseStatus::kOk:
+ break;
+ case DatabaseStatus::kFailed:
+ case DatabaseStatus::kNotFound:
+ std::move(callback_).Run(
+ blink::mojom::BackgroundFetchError::STORAGE_ERROR);
+ Finished(); // Destroys |this|.
+ return;
+ }
+
+ std::move(callback_).Run(blink::mojom::BackgroundFetchError::NONE);
+ Finished(); // Destroys |this|.
+}
+
+} // namespace background_fetch
+
+} // namespace content
diff --git a/chromium/content/browser/background_fetch/storage/update_registration_ui_task.h b/chromium/content/browser/background_fetch/storage/update_registration_ui_task.h
new file mode 100644
index 00000000000..54aebf6ed8d
--- /dev/null
+++ b/chromium/content/browser/background_fetch/storage/update_registration_ui_task.h
@@ -0,0 +1,58 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_BROWSER_BACKGROUND_FETCH_STORAGE_UPDATE_REGISTRATION_UI_TASK_H_
+#define CONTENT_BROWSER_BACKGROUND_FETCH_STORAGE_UPDATE_REGISTRATION_UI_TASK_H_
+
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "content/browser/background_fetch/background_fetch.pb.h"
+#include "content/browser/background_fetch/storage/database_task.h"
+#include "content/common/service_worker/service_worker_status_code.h"
+
+namespace content {
+
+namespace background_fetch {
+
+// Updates Background Fetch UI options. Accepts a new title.
+class UpdateRegistrationUITask : public DatabaseTask {
+ public:
+ using UpdateRegistrationUICallback =
+ base::OnceCallback<void(blink::mojom::BackgroundFetchError)>;
+
+ UpdateRegistrationUITask(BackgroundFetchDataManager* data_manager,
+ const BackgroundFetchRegistrationId& registration_id,
+ const std::string& updated_title,
+ UpdateRegistrationUICallback callback);
+
+ ~UpdateRegistrationUITask() override;
+
+ void Start() override;
+
+ private:
+ void DidGetMetadata(const std::vector<std::string>& data,
+ ServiceWorkerStatusCode status);
+
+ void UpdateUI(const std::string& serialized_metadata_proto);
+
+ void DidUpdateUI(ServiceWorkerStatusCode status);
+
+ BackgroundFetchRegistrationId registration_id_;
+ std::string updated_title_;
+
+ UpdateRegistrationUICallback callback_;
+
+ base::WeakPtrFactory<UpdateRegistrationUITask>
+ weak_factory_; // Keep as last.
+
+ DISALLOW_COPY_AND_ASSIGN(UpdateRegistrationUITask);
+};
+
+} // namespace background_fetch
+
+} // namespace content
+
+#endif // CONTENT_BROWSER_BACKGROUND_FETCH_STORAGE_UPDATE_REGISTRATION_UI_TASK_H_
diff --git a/chromium/content/browser/background_sync/background_sync_browsertest.cc b/chromium/content/browser/background_sync/background_sync_browsertest.cc
index c19fa43514a..e7afc3f8759 100644
--- a/chromium/content/browser/background_sync/background_sync_browsertest.cc
+++ b/chromium/content/browser/background_sync/background_sync_browsertest.cc
@@ -24,6 +24,7 @@
#include "content/browser/service_worker/service_worker_registration.h"
#include "content/browser/storage_partition_impl.h"
#include "content/public/browser/browser_context.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/background_sync_test_util.h"
diff --git a/chromium/content/browser/background_sync/background_sync_context.h b/chromium/content/browser/background_sync/background_sync_context.h
index 6330cd95a61..38d317146c7 100644
--- a/chromium/content/browser/background_sync/background_sync_context.h
+++ b/chromium/content/browser/background_sync/background_sync_context.h
@@ -11,7 +11,7 @@
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/modules/background_sync/background_sync.mojom.h"
+#include "third_party/blink/public/platform/modules/background_sync/background_sync.mojom.h"
namespace content {
diff --git a/chromium/content/browser/background_sync/background_sync_manager.cc b/chromium/content/browser/background_sync/background_sync_manager.cc
index de48afa5b1f..0c6fe683b64 100644
--- a/chromium/content/browser/background_sync/background_sync_manager.cc
+++ b/chromium/content/browser/background_sync/background_sync_manager.cc
@@ -30,7 +30,7 @@
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/permission_manager.h"
#include "content/public/browser/permission_type.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_event_status.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_event_status.mojom.h"
#if defined(OS_ANDROID)
#include "content/browser/android/background_sync_network_observer_android.h"
@@ -790,7 +790,7 @@ void BackgroundSyncManager::DispatchSyncEvent(
active_version->event_dispatcher()->DispatchSyncEvent(
tag, last_chance, parameters_->max_sync_event_duration,
base::BindOnce(&OnSyncEventFinished, std::move(active_version),
- request_id, repeating_callback));
+ request_id, std::move(repeating_callback)));
}
void BackgroundSyncManager::ScheduleDelayedTask(base::OnceClosure callback,
diff --git a/chromium/content/browser/background_sync/background_sync_manager.h b/chromium/content/browser/background_sync/background_sync_manager.h
index b7e6741bdf4..797e632efd5 100644
--- a/chromium/content/browser/background_sync/background_sync_manager.h
+++ b/chromium/content/browser/background_sync/background_sync_manager.h
@@ -29,8 +29,8 @@
#include "content/common/service_worker/service_worker_status_code.h"
#include "content/public/browser/background_sync_parameters.h"
#include "content/public/browser/browser_thread.h"
-#include "third_party/WebKit/public/platform/modules/background_sync/background_sync.mojom.h"
-#include "third_party/WebKit/public/platform/modules/permissions/permission_status.mojom.h"
+#include "third_party/blink/public/platform/modules/background_sync/background_sync.mojom.h"
+#include "third_party/blink/public/platform/modules/permissions/permission_status.mojom.h"
#include "url/gurl.h"
namespace blink {
diff --git a/chromium/content/browser/background_sync/background_sync_manager_unittest.cc b/chromium/content/browser/background_sync/background_sync_manager_unittest.cc
index bf2557d7059..554c5ee9798 100644
--- a/chromium/content/browser/background_sync/background_sync_manager_unittest.cc
+++ b/chromium/content/browser/background_sync/background_sync_manager_unittest.cc
@@ -14,7 +14,6 @@
#include "base/location.h"
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/field_trial.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
@@ -23,7 +22,6 @@
#include "base/threading/thread_task_runner_handle.h"
#include "content/browser/background_sync/background_sync_network_observer.h"
#include "content/browser/background_sync/background_sync_status.h"
-#include "content/browser/browser_thread_impl.h"
#include "content/browser/service_worker/embedded_worker_test_helper.h"
#include "content/browser/service_worker/service_worker_context_core.h"
#include "content/browser/service_worker/service_worker_context_wrapper.h"
@@ -43,8 +41,8 @@
#include "net/base/network_change_notifier.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
-#include "third_party/WebKit/public/platform/modules/permissions/permission_status.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/platform/modules/permissions/permission_status.mojom.h"
namespace content {
diff --git a/chromium/content/browser/background_sync/background_sync_registration.h b/chromium/content/browser/background_sync/background_sync_registration.h
index d15843c9c89..46fbd2f3b27 100644
--- a/chromium/content/browser/background_sync/background_sync_registration.h
+++ b/chromium/content/browser/background_sync/background_sync_registration.h
@@ -15,7 +15,7 @@
#include "content/browser/background_sync/background_sync.pb.h"
#include "content/browser/background_sync/background_sync_registration_options.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/modules/background_sync/background_sync.mojom.h"
+#include "third_party/blink/public/platform/modules/background_sync/background_sync.mojom.h"
namespace content {
diff --git a/chromium/content/browser/background_sync/background_sync_service_impl.h b/chromium/content/browser/background_sync/background_sync_service_impl.h
index 115d92f78f5..e227d51b21f 100644
--- a/chromium/content/browser/background_sync/background_sync_service_impl.h
+++ b/chromium/content/browser/background_sync/background_sync_service_impl.h
@@ -15,7 +15,7 @@
#include "base/memory/ref_counted.h"
#include "content/browser/background_sync/background_sync_manager.h"
#include "mojo/public/cpp/bindings/binding.h"
-#include "third_party/WebKit/public/platform/modules/background_sync/background_sync.mojom.h"
+#include "third_party/blink/public/platform/modules/background_sync/background_sync.mojom.h"
namespace content {
diff --git a/chromium/content/browser/background_sync/background_sync_service_impl_unittest.cc b/chromium/content/browser/background_sync/background_sync_service_impl_unittest.cc
index 53d873c6daa..6cbdfccaf3b 100644
--- a/chromium/content/browser/background_sync/background_sync_service_impl_unittest.cc
+++ b/chromium/content/browser/background_sync/background_sync_service_impl_unittest.cc
@@ -27,7 +27,7 @@
#include "mojo/public/cpp/bindings/interface_ptr.h"
#include "net/base/network_change_notifier.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
diff --git a/chromium/content/browser/bad_message.h b/chromium/content/browser/bad_message.h
index d3603ccd4f2..80ab47d8248 100644
--- a/chromium/content/browser/bad_message.h
+++ b/chromium/content/browser/bad_message.h
@@ -199,9 +199,9 @@ enum BadMessageReason {
RFPH_ILLEGAL_UPLOAD_PARAMS = 172,
OBSOLETE_SWDH_PROVIDER_CREATED_ILLEGAL_TYPE = 173,
SWDH_PROVIDER_CREATED_ILLEGAL_TYPE_NOT_WINDOW = 174,
- SWDH_PROVIDER_CREATED_ILLEGAL_TYPE_CONTROLLER = 175,
+ SWDH_PROVIDER_CREATED_ILLEGAL_TYPE_SERVICE_WORKER = 175,
SWDH_PROVIDER_CREATED_DUPLICATE_ID = 176,
- SWDH_PROVIDER_CREATED_BAD_ID = 177,
+ OBSOLETE_SWDH_PROVIDER_CREATED_BAD_ID = 177,
RFH_KEEP_ALIVE_HANDLE_REQUESTED_INCORRECTLY = 178,
BFSI_INVALID_UNIQUE_ID = 179,
BPE_UNEXPECTED_MESSAGE_BEFORE_BPGM_CREATION = 180,
@@ -224,6 +224,7 @@ enum BadMessageReason {
RWH_COPY_REQUEST_ATTEMPT = 197,
SYNC_COMPOSITOR_NO_FUTURE_FRAME = 198,
SYNC_COMPOSITOR_NO_BEGIN_FRAME = 199,
+ WEBUI_BAD_HOST_ACCESS = 200,
// Please add new elements here. The naming convention is abbreviated class
// name (e.g. RenderFrameHost becomes RFH) plus a unique description of the
diff --git a/chromium/content/browser/blob_storage/blob_dispatcher_host.cc b/chromium/content/browser/blob_storage/blob_dispatcher_host.cc
index 31e36c9f600..9de9c3f1650 100644
--- a/chromium/content/browser/blob_storage/blob_dispatcher_host.cc
+++ b/chromium/content/browser/blob_storage/blob_dispatcher_host.cc
@@ -13,6 +13,7 @@
#include "content/browser/blob_storage/chrome_blob_storage_context.h"
#include "content/browser/child_process_security_policy_impl.h"
#include "content/common/fileapi/webblob_messages.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_features.h"
#include "storage/browser/blob/blob_storage_context.h"
#include "url/gurl.h"
@@ -89,25 +90,6 @@ void BlobDispatcherHost::OnRegisterPublicBlobURL(const GURL& public_url,
public_blob_urls_.insert(public_url);
}
-namespace {
-
-void RevokePublicBlobURLHelperIO(
- scoped_refptr<ChromeBlobStorageContext> context,
- const GURL& public_url) {
- context->context()->RevokePublicBlobURL(public_url);
-}
-
-void RevokePublicBlobURLHelperUI(
- scoped_refptr<ChromeBlobStorageContext> context,
- const GURL& public_url) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
- base::BindOnce(&RevokePublicBlobURLHelperIO,
- std::move(context), public_url));
-}
-
-} // namespace
-
void BlobDispatcherHost::OnRevokePublicBlobURL(const GURL& public_url) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!public_url.is_valid()) {
@@ -122,10 +104,8 @@ void BlobDispatcherHost::OnRevokePublicBlobURL(const GURL& public_url) {
BDH_TRACING_ENUM_LAST);
return;
}
+ context()->RevokePublicBlobURL(public_url);
public_blob_urls_.erase(public_url);
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
- base::BindOnce(&RevokePublicBlobURLHelperUI,
- blob_storage_context_, public_url));
}
storage::BlobStorageContext* BlobDispatcherHost::context() {
diff --git a/chromium/content/browser/blob_storage/blob_internals_url_loader.cc b/chromium/content/browser/blob_storage/blob_internals_url_loader.cc
index 3068afd5e7d..f41b5cdcf39 100644
--- a/chromium/content/browser/blob_storage/blob_internals_url_loader.cc
+++ b/chromium/content/browser/blob_storage/blob_internals_url_loader.cc
@@ -22,7 +22,7 @@ void StartBlobInternalsURLLoader(
network::mojom::URLLoaderClientPtr client;
client.Bind(std::move(client_info));
- client->OnReceiveResponse(resource_response, base::nullopt, nullptr);
+ client->OnReceiveResponse(resource_response, nullptr);
std::string output = storage::ViewBlobInternalsJob::GenerateHTML(
blob_storage_context->context());
diff --git a/chromium/content/browser/blob_storage/blob_registry_wrapper.h b/chromium/content/browser/blob_storage/blob_registry_wrapper.h
index 07bdee939a5..008b5f91962 100644
--- a/chromium/content/browser/blob_storage/blob_registry_wrapper.h
+++ b/chromium/content/browser/blob_storage/blob_registry_wrapper.h
@@ -7,7 +7,7 @@
#include "base/memory/ref_counted.h"
#include "content/public/browser/browser_thread.h"
-#include "third_party/WebKit/public/mojom/blob/blob_registry.mojom.h"
+#include "third_party/blink/public/mojom/blob/blob_registry.mojom.h"
namespace storage {
class BlobRegistryImpl;
diff --git a/chromium/content/browser/blob_storage/blob_url_loader_factory.cc b/chromium/content/browser/blob_storage/blob_url_loader_factory.cc
index e2807e5ed2b..32904bea130 100644
--- a/chromium/content/browser/blob_storage/blob_url_loader_factory.cc
+++ b/chromium/content/browser/blob_storage/blob_url_loader_factory.cc
@@ -9,7 +9,6 @@
#include "base/bind.h"
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "content/public/browser/browser_thread.h"
#include "storage/browser/blob/blob_data_handle.h"
#include "storage/browser/blob/blob_storage_context.h"
@@ -71,6 +70,7 @@ void BlobURLLoaderFactory::CreateLoaderAndStart(
const network::ResourceRequest& request,
network::mojom::URLLoaderClientPtr client,
const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) {
+ DCHECK(!request.download_to_file);
DCHECK_CURRENTLY_ON(BrowserThread::IO);
std::unique_ptr<storage::BlobDataHandle> blob_handle;
if (blob_storage_context_) {
diff --git a/chromium/content/browser/blob_storage/blob_url_unittest.cc b/chromium/content/browser/blob_storage/blob_url_unittest.cc
index bdd260ef97a..82e79a3125b 100644
--- a/chromium/content/browser/blob_storage/blob_url_unittest.cc
+++ b/chromium/content/browser/blob_storage/blob_url_unittest.cc
@@ -12,7 +12,6 @@
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop/message_loop.h"
#include "base/numerics/safe_conversions.h"
@@ -22,7 +21,7 @@
#include "content/browser/blob_storage/blob_url_loader_factory.h"
#include "content/browser/url_loader_factory_getter.h"
#include "content/public/test/test_browser_thread_bundle.h"
-#include "mojo/common/data_pipe_utils.h"
+#include "mojo/public/cpp/system/data_pipe_utils.h"
#include "net/base/net_errors.h"
#include "net/base/request_priority.h"
#include "net/base/test_completion_callback.h"
@@ -307,7 +306,7 @@ class BlobURLRequestJobTest : public testing::TestWithParam<RequestTestType> {
url_loader_client.RunUntilComplete();
if (url_loader_client.response_body().is_valid()) {
- EXPECT_TRUE(mojo::common::BlockingCopyToString(
+ EXPECT_TRUE(mojo::BlockingCopyToString(
url_loader_client.response_body_release(), &response_));
}
response_headers_ = url_loader_client.response_head().headers;
@@ -362,7 +361,7 @@ class BlobURLRequestJobTest : public testing::TestWithParam<RequestTestType> {
url_loader_client.RunUntilComplete();
if (url_loader_client.response_body().is_valid()) {
- EXPECT_TRUE(mojo::common::BlockingCopyToString(
+ EXPECT_TRUE(mojo::BlockingCopyToString(
url_loader_client.response_body_release(), &response_));
}
response_headers_ = url_loader_client.response_head().headers;
@@ -509,7 +508,7 @@ TEST_P(BlobURLRequestJobTest, TestGetChangedFileRequest) {
base::Time old_time =
temp_file_modification_time1_ - base::TimeDelta::FromSeconds(10);
blob_data_->AppendFile(temp_file1_, 0, 3, old_time);
- TestErrorRequest(net::ERR_FILE_NOT_FOUND);
+ TestErrorRequest(net::ERR_UPLOAD_FILE_CHANGED);
}
TEST_P(BlobURLRequestJobTest, TestGetSlicedFileRequest) {
@@ -558,7 +557,7 @@ TEST_P(BlobURLRequestJobTest, TestGetInvalidFileSystemFileRequest) {
blob_data_->AppendFileSystemFile(invalid_file, 0,
std::numeric_limits<uint64_t>::max(),
base::Time(), file_system_context_);
- TestErrorRequest(net::ERR_FAILED);
+ TestErrorRequest(net::ERR_FILE_NOT_FOUND);
}
TEST_P(BlobURLRequestJobTest, TestGetChangedFileSystemFileRequest) {
@@ -567,7 +566,7 @@ TEST_P(BlobURLRequestJobTest, TestGetChangedFileSystemFileRequest) {
base::TimeDelta::FromSeconds(10);
blob_data_->AppendFileSystemFile(temp_file_system_file1_, 0, 3, old_time,
file_system_context_);
- TestErrorRequest(net::ERR_FILE_NOT_FOUND);
+ TestErrorRequest(net::ERR_UPLOAD_FILE_CHANGED);
}
TEST_P(BlobURLRequestJobTest, TestGetSlicedFileSystemFileRequest) {
diff --git a/chromium/content/browser/blob_storage/chrome_blob_storage_context.cc b/chromium/content/browser/blob_storage/chrome_blob_storage_context.cc
index 05e3cc19226..0b5780dfe11 100644
--- a/chromium/content/browser/blob_storage/chrome_blob_storage_context.cc
+++ b/chromium/content/browser/blob_storage/chrome_blob_storage_context.cc
@@ -19,6 +19,7 @@
#include "base/task_runner.h"
#include "base/task_scheduler/post_task.h"
#include "content/browser/resource_context_impl.h"
+#include "content/common/wrapper_shared_url_loader_factory.h"
#include "content/public/browser/blob_handle.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
@@ -28,6 +29,7 @@
#include "storage/browser/blob/blob_impl.h"
#include "storage/browser/blob/blob_memory_controller.h"
#include "storage/browser/blob/blob_storage_context.h"
+#include "storage/browser/blob/blob_url_loader_factory.h"
using base::FilePath;
using base::UserDataAdapter;
@@ -98,7 +100,8 @@ ChromeBlobStorageContext* ChromeBlobStorageContext::GetFor(
blob.get()));
// Check first to avoid memory leak in unittests.
- bool io_thread_valid = BrowserThread::IsMessageLoopValid(BrowserThread::IO);
+ bool io_thread_valid =
+ BrowserThread::IsThreadInitialized(BrowserThread::IO);
// Resolve our storage directories.
FilePath blob_storage_parent =
@@ -192,10 +195,33 @@ std::unique_ptr<BlobHandle> ChromeBlobStorageContext::CreateFileBackedBlob(
return blob_handle;
}
+// static
+scoped_refptr<network::SharedURLLoaderFactory>
+ChromeBlobStorageContext::URLLoaderFactoryForToken(
+ BrowserContext* browser_context,
+ blink::mojom::BlobURLTokenPtr token) {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ network::mojom::URLLoaderFactoryPtr blob_url_loader_factory_ptr;
+ BrowserThread::PostTask(
+ BrowserThread::IO, FROM_HERE,
+ base::BindOnce(
+ [](scoped_refptr<ChromeBlobStorageContext> context,
+ network::mojom::URLLoaderFactoryRequest request,
+ blink::mojom::BlobURLTokenPtrInfo token) {
+ storage::BlobURLLoaderFactory::Create(
+ blink::mojom::BlobURLTokenPtr(std::move(token)),
+ context->context()->AsWeakPtr(), std::move(request));
+ },
+ base::WrapRefCounted(GetFor(browser_context)),
+ MakeRequest(&blob_url_loader_factory_ptr), token.PassInterface()));
+ return base::MakeRefCounted<WrapperSharedURLLoaderFactory>(
+ std::move(blob_url_loader_factory_ptr));
+}
+
ChromeBlobStorageContext::~ChromeBlobStorageContext() {}
void ChromeBlobStorageContext::DeleteOnCorrectThread() const {
- if (BrowserThread::IsMessageLoopValid(BrowserThread::IO) &&
+ if (BrowserThread::IsThreadInitialized(BrowserThread::IO) &&
!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, this);
return;
diff --git a/chromium/content/browser/blob_storage/chrome_blob_storage_context.h b/chromium/content/browser/blob_storage/chrome_blob_storage_context.h
index 8c5b031e1e6..043d968ca6a 100644
--- a/chromium/content/browser/blob_storage/chrome_blob_storage_context.h
+++ b/chromium/content/browser/blob_storage/chrome_blob_storage_context.h
@@ -15,7 +15,9 @@
#include "base/memory/ref_counted.h"
#include "base/sequenced_task_runner_helpers.h"
#include "content/common/content_export.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "storage/browser/blob/blob_data_handle.h"
+#include "third_party/blink/public/mojom/blob/blob_url_store.mojom.h"
namespace base {
class FilePath;
@@ -72,6 +74,11 @@ class CONTENT_EXPORT ChromeBlobStorageContext
int64_t size,
const base::Time& expected_modification_time);
+ // Must be called on the UI thread.
+ static scoped_refptr<network::SharedURLLoaderFactory>
+ URLLoaderFactoryForToken(BrowserContext* browser_context,
+ blink::mojom::BlobURLTokenPtr token);
+
protected:
virtual ~ChromeBlobStorageContext();
diff --git a/chromium/content/browser/bluetooth/README.md b/chromium/content/browser/bluetooth/README.md
index 87c06ffa87f..e39aac5da16 100644
--- a/chromium/content/browser/bluetooth/README.md
+++ b/chromium/content/browser/bluetooth/README.md
@@ -7,7 +7,7 @@ This service is exposed to the web in the [blink bluetooth module].
[Web Bluetooth specification]: https://webbluetoothcg.github.io/web-bluetooth/
[/device/bluetooth]: /device/bluetooth
-[blink bluetooth module]: /third_party/WebKit/Source/modules/bluetooth/
+[blink bluetooth module]: /third_party/blink/renderer/modules/bluetooth/
## Testing
diff --git a/chromium/content/browser/bluetooth/bluetooth_allowed_devices.h b/chromium/content/browser/bluetooth/bluetooth_allowed_devices.h
index 32e871f5ee8..dc5223c254d 100644
--- a/chromium/content/browser/bluetooth/bluetooth_allowed_devices.h
+++ b/chromium/content/browser/bluetooth/bluetooth_allowed_devices.h
@@ -14,7 +14,7 @@
#include "base/optional.h"
#include "content/common/bluetooth/web_bluetooth_device_id.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/modules/bluetooth/web_bluetooth.mojom.h"
+#include "third_party/blink/public/platform/modules/bluetooth/web_bluetooth.mojom.h"
namespace device {
class BluetoothUUID;
diff --git a/chromium/content/browser/bluetooth/bluetooth_blocklist.h b/chromium/content/browser/bluetooth/bluetooth_blocklist.h
index c719b571fae..103e8c2da42 100644
--- a/chromium/content/browser/bluetooth/bluetooth_blocklist.h
+++ b/chromium/content/browser/bluetooth/bluetooth_blocklist.h
@@ -13,7 +13,7 @@
#include "base/strings/string_piece.h"
#include "content/common/content_export.h"
#include "device/bluetooth/bluetooth_uuid.h"
-#include "third_party/WebKit/public/platform/modules/bluetooth/web_bluetooth.mojom.h"
+#include "third_party/blink/public/platform/modules/bluetooth/web_bluetooth.mojom.h"
namespace content {
diff --git a/chromium/content/browser/bluetooth/bluetooth_device_chooser_controller.cc b/chromium/content/browser/bluetooth/bluetooth_device_chooser_controller.cc
index 1b12e6638d5..4d08d443e55 100644
--- a/chromium/content/browser/bluetooth/bluetooth_device_chooser_controller.cc
+++ b/chromium/content/browser/bluetooth/bluetooth_device_chooser_controller.cc
@@ -10,7 +10,6 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
@@ -81,17 +80,14 @@ const int k80thPercentileRSSI = -52;
namespace content {
-bool BluetoothDeviceChooserController::use_test_scan_duration_ = false;
+// Sets the default duration for a Bluetooth scan to 60 seconds.
+int64_t BluetoothDeviceChooserController::scan_duration_ = 60;
namespace {
// Max length of device name in filter. Bluetooth 5.0 3.C.3.2.2.3 states that
// the maximum device name length is 248 bytes (UTF-8 encoded).
constexpr size_t kMaxLengthForDeviceName = 248;
-// The duration of a Bluetooth Scan in seconds.
-constexpr int kScanDuration = 60;
-constexpr int kTestScanDuration = 0;
-
void LogRequestDeviceOptions(
const blink::mojom::WebBluetoothRequestDeviceOptionsPtr& options) {
DVLOG(1) << "requestDevice called with the following filters: ";
@@ -281,10 +277,7 @@ BluetoothDeviceChooserController::BluetoothDeviceChooserController(
web_contents_(WebContents::FromRenderFrameHost(render_frame_host_)),
discovery_session_timer_(
FROM_HERE,
- // TODO(jyasskin): Add a way for tests to control the dialog
- // directly, and change this to a reasonable discovery timeout.
- base::TimeDelta::FromSeconds(
- use_test_scan_duration_ ? kTestScanDuration : kScanDuration),
+ base::TimeDelta::FromSeconds(scan_duration_),
base::Bind(&BluetoothDeviceChooserController::StopDeviceDiscovery,
// base::Timer guarantees it won't call back after its
// destructor starts.
@@ -397,7 +390,7 @@ void BluetoothDeviceChooserController::GetDevice(
if (WebContentsDelegate* delegate = web_contents_->GetDelegate()) {
chooser_ = delegate->RunBluetoothChooser(render_frame_host_,
- chooser_event_handler);
+ std::move(chooser_event_handler));
}
if (!chooser_.get()) {
@@ -490,8 +483,16 @@ int BluetoothDeviceChooserController::CalculateSignalStrengthLevel(
}
}
-void BluetoothDeviceChooserController::SetTestScanDurationForTesting() {
- BluetoothDeviceChooserController::use_test_scan_duration_ = true;
+void BluetoothDeviceChooserController::SetTestScanDurationForTesting(
+ TestScanDurationSetting setting) {
+ switch (setting) {
+ case TestScanDurationSetting::IMMEDIATE_TIMEOUT:
+ scan_duration_ = 0;
+ break;
+ case TestScanDurationSetting::NEVER_TIMEOUT:
+ scan_duration_ = base::TimeDelta::Max().InSeconds();
+ break;
+ }
}
void BluetoothDeviceChooserController::PopulateConnectedDevices() {
diff --git a/chromium/content/browser/bluetooth/bluetooth_device_chooser_controller.h b/chromium/content/browser/bluetooth/bluetooth_device_chooser_controller.h
index a054d6bf705..54eb7a113e2 100644
--- a/chromium/content/browser/bluetooth/bluetooth_device_chooser_controller.h
+++ b/chromium/content/browser/bluetooth/bluetooth_device_chooser_controller.h
@@ -14,7 +14,7 @@
#include "base/timer/timer.h"
#include "content/common/content_export.h"
#include "content/public/browser/bluetooth_chooser.h"
-#include "third_party/WebKit/public/platform/modules/bluetooth/web_bluetooth.mojom.h"
+#include "third_party/blink/public/platform/modules/bluetooth/web_bluetooth.mojom.h"
namespace device {
class BluetoothAdapter;
@@ -39,6 +39,8 @@ class CONTENT_EXPORT BluetoothDeviceChooserController final {
typedef base::Callback<void(blink::mojom::WebBluetoothResult result)>
ErrorCallback;
+ enum class TestScanDurationSetting { IMMEDIATE_TIMEOUT, NEVER_TIMEOUT };
+
// |web_bluetooth_service_| service that owns this class.
// |render_frame_host| should be the RenderFrameHost that owns the
// |web_bluetooth_service_|.
@@ -83,9 +85,14 @@ class CONTENT_EXPORT BluetoothDeviceChooserController final {
// present in a received radio signal.
static int CalculateSignalStrengthLevel(int8_t rssi);
- // After this method is called any new instance of
- // BluetoothDeviceChooserController will have a scan duration of 0.
- static void SetTestScanDurationForTesting();
+ // After this method is called, any new instance of
+ // BluetoothDeviceChooserController will have a scan duration determined by
+ // the |setting| enum. The possible enumerations are described below:
+ // IMMEDIATE_TIMEOUT: Sets the scan duration to 0 seconds.
+ // NEVER_TIMEOUT: Sets the scan duration to INT_MAX seconds.
+ static void SetTestScanDurationForTesting(
+ TestScanDurationSetting setting =
+ TestScanDurationSetting::IMMEDIATE_TIMEOUT);
private:
// Populates the chooser with the GATT connected devices.
@@ -115,8 +122,9 @@ class CONTENT_EXPORT BluetoothDeviceChooserController final {
// Helper function to asynchronously run error_callback_.
void PostErrorCallback(blink::mojom::WebBluetoothResult result);
- // If true all new instances of this class will have a scan duration of 0.
- static bool use_test_scan_duration_;
+ // Stores the scan duration to use for the discovery session timer.
+ // The default value is 60 seconds.
+ static int64_t scan_duration_;
// The adapter used to get existing devices and start a discovery session.
device::BluetoothAdapter* adapter_;
diff --git a/chromium/content/browser/bluetooth/bluetooth_metrics.h b/chromium/content/browser/bluetooth/bluetooth_metrics.h
index 4a7d761c63c..2b7ec33ec91 100644
--- a/chromium/content/browser/bluetooth/bluetooth_metrics.h
+++ b/chromium/content/browser/bluetooth/bluetooth_metrics.h
@@ -8,7 +8,7 @@
#include <string>
#include <vector>
-#include "third_party/WebKit/public/platform/modules/bluetooth/web_bluetooth.mojom.h"
+#include "third_party/blink/public/platform/modules/bluetooth/web_bluetooth.mojom.h"
namespace base {
class TimeDelta;
diff --git a/chromium/content/browser/bluetooth/frame_connected_bluetooth_devices.cc b/chromium/content/browser/bluetooth/frame_connected_bluetooth_devices.cc
index e64676e7745..1b4b07030db 100644
--- a/chromium/content/browser/bluetooth/frame_connected_bluetooth_devices.cc
+++ b/chromium/content/browser/bluetooth/frame_connected_bluetooth_devices.cc
@@ -4,7 +4,6 @@
#include "content/browser/bluetooth/frame_connected_bluetooth_devices.h"
-#include "base/memory/ptr_util.h"
#include "base/optional.h"
#include "base/strings/string_util.h"
#include "content/browser/web_contents/web_contents_impl.h"
diff --git a/chromium/content/browser/bluetooth/frame_connected_bluetooth_devices.h b/chromium/content/browser/bluetooth/frame_connected_bluetooth_devices.h
index 3c4dcf0ce30..d8adcbd5953 100644
--- a/chromium/content/browser/bluetooth/frame_connected_bluetooth_devices.h
+++ b/chromium/content/browser/bluetooth/frame_connected_bluetooth_devices.h
@@ -12,7 +12,7 @@
#include "base/optional.h"
#include "content/common/bluetooth/web_bluetooth_device_id.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/modules/bluetooth/web_bluetooth.mojom.h"
+#include "third_party/blink/public/platform/modules/bluetooth/web_bluetooth.mojom.h"
#include "url/origin.h"
namespace device {
diff --git a/chromium/content/browser/bluetooth/frame_connected_bluetooth_devices_unittest.cc b/chromium/content/browser/bluetooth/frame_connected_bluetooth_devices_unittest.cc
index 1cf49611197..22f2e06d0e8 100644
--- a/chromium/content/browser/bluetooth/frame_connected_bluetooth_devices_unittest.cc
+++ b/chromium/content/browser/bluetooth/frame_connected_bluetooth_devices_unittest.cc
@@ -4,7 +4,6 @@
#include "content/browser/bluetooth/frame_connected_bluetooth_devices.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "content/browser/bluetooth/web_bluetooth_service_impl.h"
#include "content/test/test_render_view_host.h"
diff --git a/chromium/content/browser/bluetooth/web_bluetooth_service_impl.cc b/chromium/content/browser/bluetooth/web_bluetooth_service_impl.cc
index e5c7291dcc8..cda94e43e86 100644
--- a/chromium/content/browser/bluetooth/web_bluetooth_service_impl.cc
+++ b/chromium/content/browser/bluetooth/web_bluetooth_service_impl.cc
@@ -12,7 +12,6 @@
#include <algorithm>
-#include "base/memory/ptr_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/browser/bluetooth/bluetooth_blocklist.h"
@@ -178,8 +177,8 @@ WebBluetoothServiceImpl::~WebBluetoothServiceImpl() {
}
void WebBluetoothServiceImpl::SetClientConnectionErrorHandler(
- base::Closure closure) {
- binding_.set_connection_error_handler(closure);
+ base::OnceClosure closure) {
+ binding_.set_connection_error_handler(std::move(closure));
}
bool WebBluetoothServiceImpl::IsDevicePaired(
@@ -823,11 +822,12 @@ void WebBluetoothServiceImpl::RequestDeviceImpl(
blink::mojom::WebBluetoothRequestDeviceOptionsPtr options,
RequestDeviceCallback callback,
device::BluetoothAdapter* adapter) {
- // requestDevice() can only be called when processing a user-gesture and any
- // user gesture outside of a chooser should close the chooser. This does
- // not happen on all platforms so we don't DCHECK that the old one is closed.
- // We destroy the old chooser before constructing the new one to make sure
- // they can't conflict.
+ // Calls to requestDevice() require user activation (user gestures). We
+ // should close any opened chooser when a duplicate requestDevice call is made
+ // with the same user activation or when any gesture occurs outside of the
+ // opened chooser. This does not happen on all platforms so we don't DCHECK
+ // that the old one is closed. We destroy the old chooser before constructing
+ // the new one to make sure they can't conflict.
device_chooser_controller_.reset();
device_chooser_controller_.reset(
diff --git a/chromium/content/browser/bluetooth/web_bluetooth_service_impl.h b/chromium/content/browser/bluetooth/web_bluetooth_service_impl.h
index 5ecd3e0b7e9..55b409a3525 100644
--- a/chromium/content/browser/bluetooth/web_bluetooth_service_impl.h
+++ b/chromium/content/browser/bluetooth/web_bluetooth_service_impl.h
@@ -21,7 +21,7 @@
#include "device/bluetooth/bluetooth_remote_gatt_characteristic.h"
#include "device/bluetooth/bluetooth_remote_gatt_service.h"
#include "mojo/public/cpp/bindings/binding.h"
-#include "third_party/WebKit/public/platform/modules/bluetooth/web_bluetooth.mojom.h"
+#include "third_party/blink/public/platform/modules/bluetooth/web_bluetooth.mojom.h"
namespace url {
class Origin;
@@ -60,7 +60,7 @@ class CONTENT_EXPORT WebBluetoothServiceImpl
void CrashRendererAndClosePipe(bad_message::BadMessageReason reason);
// Sets the connection error handler for WebBluetoothServiceImpl's Binding.
- void SetClientConnectionErrorHandler(base::Closure closure);
+ void SetClientConnectionErrorHandler(base::OnceClosure closure);
// Returns whether the device is paired with the |render_frame_host_|'s
// GetLastCommittedOrigin().
diff --git a/chromium/content/browser/broadcast_channel/broadcast_channel_provider.h b/chromium/content/browser/broadcast_channel/broadcast_channel_provider.h
index 5394a923f60..7b8dea31f94 100644
--- a/chromium/content/browser/broadcast_channel/broadcast_channel_provider.h
+++ b/chromium/content/browser/broadcast_channel/broadcast_channel_provider.h
@@ -9,7 +9,7 @@
#include "base/memory/ref_counted.h"
#include "mojo/public/cpp/bindings/binding_set.h"
-#include "third_party/WebKit/public/platform/modules/broadcastchannel/broadcast_channel.mojom.h"
+#include "third_party/blink/public/platform/modules/broadcastchannel/broadcast_channel.mojom.h"
#include "url/origin.h"
namespace content {
diff --git a/chromium/content/browser/browser_child_process_host_impl.cc b/chromium/content/browser/browser_child_process_host_impl.cc
index 589568ba3a2..dcf54720afd 100644
--- a/chromium/content/browser/browser_child_process_host_impl.cc
+++ b/chromium/content/browser/browser_child_process_host_impl.cc
@@ -14,7 +14,6 @@
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
@@ -26,8 +25,10 @@
#include "base/synchronization/waitable_event.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
+#include "components/tracing/common/trace_config_file.h"
#include "components/tracing/common/tracing_switches.h"
#include "content/browser/bad_message.h"
+#include "content/browser/browser_main_loop.h"
#include "content/browser/histogram_controller.h"
#include "content/browser/loader/resource_message_filter.h"
#include "content/browser/service_manager/service_manager_context.h"
@@ -209,6 +210,44 @@ void BrowserChildProcessHostImpl::CopyFeatureAndFieldTrialFlags(
switches::kDisableFeatures, cmd_line);
}
+// static
+void BrowserChildProcessHostImpl::CopyTraceStartupFlags(
+ base::CommandLine* cmd_line) {
+ const base::CommandLine& browser_cmd_line =
+ *base::CommandLine::ForCurrentProcess();
+
+ if (browser_cmd_line.HasSwitch(switches::kTraceStartup) &&
+ BrowserMainLoop::GetInstance()->is_tracing_startup_for_duration()) {
+ // Pass kTraceStartup switch to renderer only if startup tracing has not
+ // finished.
+ cmd_line->AppendSwitchASCII(
+ switches::kTraceStartup,
+ browser_cmd_line.GetSwitchValueASCII(switches::kTraceStartup));
+ if (browser_cmd_line.HasSwitch(switches::kTraceStartupRecordMode)) {
+ cmd_line->AppendSwitchASCII(switches::kTraceStartupRecordMode,
+ browser_cmd_line.GetSwitchValueASCII(
+ switches::kTraceStartupRecordMode));
+ }
+ } else if (tracing::TraceConfigFile::GetInstance()->IsEnabled()) {
+ const auto trace_config =
+ tracing::TraceConfigFile::GetInstance()->GetTraceConfig();
+ if (!trace_config.IsArgumentFilterEnabled()) {
+ // The only trace option that we can pass through switches is the record
+ // mode. Other trace options should have the default value.
+ //
+ // TODO(chiniforooshan): Add other trace options to switches if, for
+ // example, they are used in a telemetry test that needs startup trace
+ // events from renderer processes.
+ cmd_line->AppendSwitchASCII(switches::kTraceStartup,
+ trace_config.ToCategoryFilterString());
+ cmd_line->AppendSwitchASCII(
+ switches::kTraceStartupRecordMode,
+ base::trace_event::TraceConfig::TraceRecordModeToStr(
+ trace_config.GetTraceRecordMode()));
+ }
+ }
+}
+
void BrowserChildProcessHostImpl::Launch(
std::unique_ptr<SandboxedProcessLauncherDelegate> delegate,
std::unique_ptr<base::CommandLine> cmd_line,
@@ -222,6 +261,7 @@ void BrowserChildProcessHostImpl::Launch(
*base::CommandLine::ForCurrentProcess();
static const char* const kForwardSwitches[] = {
service_manager::switches::kDisableInProcessStackTraces,
+ switches::kDisableBackgroundTasks,
switches::kDisableLogging,
switches::kEnableLogging,
switches::kIPCConnectionTimeout,
diff --git a/chromium/content/browser/browser_child_process_host_impl.h b/chromium/content/browser/browser_child_process_host_impl.h
index 76923f925b1..5dc64aa2224 100644
--- a/chromium/content/browser/browser_child_process_host_impl.h
+++ b/chromium/content/browser/browser_child_process_host_impl.h
@@ -64,6 +64,10 @@ class CONTENT_EXPORT BrowserChildProcessHostImpl
// from FieldTrials.
static void CopyFeatureAndFieldTrialFlags(base::CommandLine* cmd_line);
+ // Appends kTraceStartup and kTraceRecordMode flags to the command line, if
+ // needed.
+ static void CopyTraceStartupFlags(base::CommandLine* cmd_line);
+
// BrowserChildProcessHost implementation:
bool Send(IPC::Message* message) override;
void Launch(std::unique_ptr<SandboxedProcessLauncherDelegate> delegate,
diff --git a/chromium/content/browser/browser_context.cc b/chromium/content/browser/browser_context.cc
index 0cf6cde723e..15cb62d76bb 100644
--- a/chromium/content/browser/browser_context.cc
+++ b/chromium/content/browser/browser_context.cc
@@ -39,6 +39,7 @@
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/site_instance.h"
+#include "content/public/browser/webrtc_event_logger.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/service_manager_connection.h"
#include "content/public/common/service_names.mojom.h"
@@ -58,9 +59,6 @@
#include "storage/browser/database/database_tracker.h"
#include "storage/browser/fileapi/external_mount_points.h"
-#if BUILDFLAG(ENABLE_WEBRTC)
-#include "content/browser/webrtc/webrtc_event_log_manager.h"
-#endif
using base::UserDataAdapter;
@@ -235,7 +233,7 @@ storage::ExternalMountPoints* BrowserContext::GetMountPoints(
// Ensure that these methods are called on the UI thread, except for
// unittests where a UI thread might not have been created.
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI) ||
- !BrowserThread::IsMessageLoopValid(BrowserThread::UI));
+ !BrowserThread::IsThreadInitialized(BrowserThread::UI));
#if defined(OS_CHROMEOS)
if (!context->GetUserData(kMountPointsKey)) {
@@ -384,6 +382,14 @@ void BrowserContext::DeliverPushMessage(
// static
void BrowserContext::NotifyWillBeDestroyed(BrowserContext* browser_context) {
+ // Make sure NotifyWillBeDestroyed is idempotent. This helps facilitate the
+ // pattern where NotifyWillBeDestroyed is called from *both*
+ // ShellBrowserContext and its derived classes (e.g.
+ // LayoutTestBrowserContext).
+ if (browser_context->was_notify_will_be_destroyed_called_)
+ return;
+ browser_context->was_notify_will_be_destroyed_called_ = true;
+
// Service Workers must shutdown before the browser context is destroyed,
// since they keep render process hosts alive and the codebase assumes that
// render process hosts die before their profile (browser context) dies.
@@ -427,7 +433,7 @@ void BrowserContext::SaveSessionState(BrowserContext* browser_context) {
base::BindOnce(&storage::DatabaseTracker::SetForceKeepSessionState,
base::WrapRefCounted(database_tracker)));
- if (BrowserThread::IsMessageLoopValid(BrowserThread::IO)) {
+ if (BrowserThread::IsThreadInitialized(BrowserThread::IO)) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(
@@ -531,9 +537,9 @@ void BrowserContext::Initialize(
#if BUILDFLAG(ENABLE_WEBRTC)
if (!browser_context->IsOffTheRecord()) {
- auto* webrtc_event_log_manager = WebRtcEventLogManager::GetInstance();
- if (webrtc_event_log_manager) {
- webrtc_event_log_manager->EnableForBrowserContext(browser_context);
+ WebRtcEventLogger* const logger = WebRtcEventLogger::Get();
+ if (logger) {
+ logger->EnableForBrowserContext(browser_context);
}
}
#endif
@@ -587,11 +593,12 @@ BrowserContext::~BrowserContext() {
DCHECK(!GetUserData(kStoragePartitionMapKeyName))
<< "StoragePartitionMap is not shut down properly";
+ DCHECK(was_notify_will_be_destroyed_called_);
+
#if BUILDFLAG(ENABLE_WEBRTC)
- auto* webrtc_event_log_manager = WebRtcEventLogManager::GetInstance();
- if (webrtc_event_log_manager) {
- const auto id = WebRtcEventLogManager::GetBrowserContextId(this);
- webrtc_event_log_manager->DisableForBrowserContext(id);
+ WebRtcEventLogger* const logger = WebRtcEventLogger::Get();
+ if (logger) {
+ logger->DisableForBrowserContext(this);
}
#endif
diff --git a/chromium/content/browser/browser_main_loop.cc b/chromium/content/browser/browser_main_loop.cc
index 427f1acb86f..81c93e51b65 100644
--- a/chromium/content/browser/browser_main_loop.cc
+++ b/chromium/content/browser/browser_main_loop.cc
@@ -15,11 +15,11 @@
#include "base/base_switches.h"
#include "base/bind.h"
#include "base/command_line.h"
+#include "base/debug/alias.h"
#include "base/deferred_sequenced_task_runner.h"
#include "base/feature_list.h"
#include "base/location.h"
#include "base/logging.h"
-#include "base/macros.h"
#include "base/memory/memory_coordinator_proxy.h"
#include "base/memory/memory_pressure_monitor.h"
#include "base/message_loop/message_loop.h"
@@ -37,10 +37,7 @@
#include "base/synchronization/waitable_event.h"
#include "base/system_monitor/system_monitor.h"
#include "base/task_scheduler/initialization_util.h"
-#include "base/task_scheduler/post_task.h"
-#include "base/task_scheduler/single_thread_task_runner_thread_mode.h"
-#include "base/task_scheduler/task_scheduler.h"
-#include "base/task_scheduler/task_traits.h"
+#include "base/threading/thread.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
@@ -54,11 +51,11 @@
#include "components/tracing/common/tracing_switches.h"
#include "components/viz/common/features.h"
#include "components/viz/common/switches.h"
-#include "components/viz/host/forwarding_compositing_mode_reporter_impl.h"
#include "components/viz/host/host_frame_sink_manager.h"
#include "components/viz/service/display_embedder/compositing_mode_reporter_impl.h"
#include "components/viz/service/display_embedder/server_shared_bitmap_manager.h"
#include "components/viz/service/frame_sinks/frame_sink_manager_impl.h"
+#include "content/browser/browser_process_sub_thread.h"
#include "content/browser/browser_thread_impl.h"
#include "content/browser/child_process_security_policy_impl.h"
#include "content/browser/compositor/gpu_process_transport_factory.h"
@@ -77,6 +74,7 @@
#include "content/browser/leveldb_wrapper_impl.h"
#include "content/browser/loader/resource_dispatcher_host_impl.h"
#include "content/browser/loader_delegate_impl.h"
+#include "content/browser/media/capture/audio_mirroring_manager.h"
#include "content/browser/media/media_internals.h"
#include "content/browser/memory/memory_coordinator_impl.h"
#include "content/browser/memory/swap_metrics_delegate_uma.h"
@@ -84,21 +82,22 @@
#include "content/browser/renderer_host/media/media_stream_manager.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/service_manager/service_manager_context.h"
-#include "content/browser/site_isolation_policy.h"
#include "content/browser/speech/speech_recognition_manager_impl.h"
#include "content/browser/startup_task_runner.h"
#include "content/browser/tracing/background_tracing_manager_impl.h"
#include "content/browser/tracing/tracing_controller_impl.h"
-#include "content/browser/utility_process_host_impl.h"
+#include "content/browser/utility_process_host.h"
#include "content/browser/webui/content_web_ui_controller_factory.h"
#include "content/browser/webui/url_data_manager.h"
#include "content/common/content_switches_internal.h"
#include "content/common/service_manager/service_manager_connection_impl.h"
#include "content/common/task_scheduler.h"
#include "content/public/browser/browser_main_parts.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/gpu_data_manager_observer.h"
#include "content/public/browser/render_process_host.h"
+#include "content/public/browser/site_isolation_policy.h"
#include "content/public/browser/swap_metrics_driver.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_features.h"
@@ -106,23 +105,23 @@
#include "content/public/common/main_function_params.h"
#include "content/public/common/result_codes.h"
#include "content/public/common/service_names.mojom.h"
-#include "content/public/common/zygote_features.h"
+#include "content/public/common/zygote_buildflags.h"
#include "device/gamepad/gamepad_service.h"
-#include "gpu/vulkan/features.h"
+#include "gpu/vulkan/buildflags.h"
#include "media/audio/audio_manager.h"
#include "media/audio/audio_system.h"
#include "media/audio/audio_thread_impl.h"
#include "media/base/media.h"
#include "media/base/user_input_monitor.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "media/midi/midi_service.h"
-#include "media/mojo/features.h"
+#include "media/mojo/buildflags.h"
#include "mojo/edk/embedder/embedder.h"
#include "mojo/edk/embedder/scoped_ipc_support.h"
#include "net/base/network_change_notifier.h"
#include "net/socket/client_socket_factory.h"
#include "net/ssl/ssl_config_service.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#include "services/audio/public/cpp/audio_system_factory.h"
#include "services/resource_coordinator/public/cpp/memory_instrumentation/client_process_impl.h"
#include "services/resource_coordinator/public/mojom/memory_instrumentation/memory_instrumentation.mojom.h"
@@ -145,12 +144,6 @@
#include "ui/aura/env.h"
#endif
-#if BUILDFLAG(USE_ZYGOTE_HANDLE)
-#include "content/public/common/common_sandbox_support_linux.h"
-#include "content/public/common/zygote_handle.h"
-#include "media/base/media_switches.h"
-#endif
-
#if defined(OS_ANDROID)
#include "base/android/jni_android.h"
#include "components/tracing/common/graphics_memory_dump_provider_android.h"
@@ -214,13 +207,7 @@
#if defined(OS_POSIX) && !defined(OS_MACOSX)
#include "content/browser/sandbox_host_linux.h"
-#include "content/browser/zygote_host/zygote_host_impl_linux.h"
-
-#if !defined(OS_ANDROID)
-#include "content/browser/zygote_host/zygote_communication_linux.h"
-#endif // !defined(OS_ANDROID)
-#endif // defined(OS_POSIX) && !defined(OS_MACOSX)
-
+#endif
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/browser/plugin_service_impl.h"
@@ -231,7 +218,6 @@
#endif
#if BUILDFLAG(ENABLE_WEBRTC)
-#include "content/browser/webrtc/webrtc_event_log_manager.h"
#include "content/browser/webrtc/webrtc_internals.h"
#endif
@@ -262,64 +248,6 @@
namespace content {
namespace {
-#if BUILDFLAG(USE_ZYGOTE_HANDLE)
-pid_t LaunchZygoteHelper(base::CommandLine* cmd_line,
- base::ScopedFD* control_fd) {
- // Append any switches from the browser process that need to be forwarded on
- // to the zygote/renderers.
- static const char* const kForwardSwitches[] = {
- switches::kAndroidFontsPath, switches::kClearKeyCdmPathForTesting,
- switches::kEnableHeapProfiling,
- switches::kEnableLogging, // Support, e.g., --enable-logging=stderr.
- // Need to tell the zygote that it is headless so that we don't try to use
- // the wrong type of main delegate.
- switches::kHeadless,
- // Zygote process needs to know what resources to have loaded when it
- // becomes a renderer process.
- switches::kForceDeviceScaleFactor, switches::kLoggingLevel,
- switches::kPpapiInProcess, switches::kRegisterPepperPlugins, switches::kV,
- switches::kVModule,
- };
- cmd_line->CopySwitchesFrom(*base::CommandLine::ForCurrentProcess(),
- kForwardSwitches, arraysize(kForwardSwitches));
-
- GetContentClient()->browser()->AppendExtraCommandLineSwitches(cmd_line, -1);
-
- // Start up the sandbox host process and get the file descriptor for the
- // sandboxed processes to talk to it.
- base::FileHandleMappingVector additional_remapped_fds;
- additional_remapped_fds.emplace_back(
- SandboxHostLinux::GetInstance()->GetChildSocket(), GetSandboxFD());
-
- return ZygoteHostImpl::GetInstance()->LaunchZygote(
- cmd_line, control_fd, std::move(additional_remapped_fds));
-}
-
-void SetupSandbox(const base::CommandLine& parsed_command_line) {
- TRACE_EVENT0("startup", "SetupSandbox");
- // SandboxHostLinux needs to be initialized even if the sandbox and
- // zygote are both disabled. It initializes the sandboxed process socket.
- SandboxHostLinux::GetInstance()->Init();
-
- if (parsed_command_line.HasSwitch(switches::kNoZygote) &&
- !parsed_command_line.HasSwitch(switches::kNoSandbox)) {
- LOG(ERROR) << "--no-sandbox should be used together with --no--zygote";
- exit(EXIT_FAILURE);
- }
-
- // Tickle the zygote host so it forks now.
- ZygoteHostImpl::GetInstance()->Init(parsed_command_line);
- ZygoteHandle generic_zygote =
- CreateGenericZygote(base::BindOnce(LaunchZygoteHelper));
-
- // TODO(kerrnel): Investigate doing this without the ZygoteHostImpl as a
- // proxy. It is currently done this way due to concerns about race
- // conditions.
- ZygoteHostImpl::GetInstance()->SetRendererSandboxStatus(
- generic_zygote->GetSandboxStatus());
-}
-#endif // BUILDFLAG(USE_ZYGOTE_HANDLE)
-
#if defined(USE_GLIB)
static void GLibLogHandler(const gchar* log_domain,
GLogLevelFlags log_level,
@@ -375,25 +303,11 @@ void OnStoppedStartupTracing(const base::FilePath& trace_file) {
MSVC_DISABLE_OPTIMIZE()
MSVC_PUSH_DISABLE_WARNING(4748)
-#if defined(OS_ANDROID)
-NOINLINE void ResetThread_PROCESS_LAUNCHER(
- std::unique_ptr<BrowserProcessSubThread> thread) {
- volatile int inhibit_comdat = __LINE__;
- ALLOW_UNUSED_LOCAL(inhibit_comdat);
- thread.reset();
-}
-#else // defined(OS_ANDROID)
-NOINLINE void ResetThread_PROCESS_LAUNCHER() {
- volatile int inhibit_comdat = __LINE__;
- ALLOW_UNUSED_LOCAL(inhibit_comdat);
- BrowserThreadImpl::StopRedirectionOfThreadID(BrowserThread::PROCESS_LAUNCHER);
-}
-#endif // defined(OS_ANDROID)
-
-NOINLINE void ResetThread_IO(std::unique_ptr<BrowserProcessSubThread> thread) {
- volatile int inhibit_comdat = __LINE__;
- ALLOW_UNUSED_LOCAL(inhibit_comdat);
- thread.reset();
+NOINLINE void ResetThread_IO(
+ std::unique_ptr<BrowserProcessSubThread> io_thread) {
+ const int line_number = __LINE__;
+ io_thread.reset();
+ base::debug::Alias(&line_number);
}
MSVC_POP_WARNING()
@@ -629,9 +543,11 @@ int BrowserMainLoop::EarlyInitialization() {
TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
#if BUILDFLAG(USE_ZYGOTE_HANDLE)
- // No thread should be created before this call, as SetupSandbox()
- // will end-up using fork().
- SetupSandbox(parsed_command_line_);
+ // The initialization of the sandbox host ends up with forking the Zygote
+ // process and requires no thread been forked. The initialization has happened
+ // by now since a thread to start the ServiceManager has been created
+ // before the browser main loop starts.
+ DCHECK(SandboxHostLinux::GetInstance()->IsInitialized());
#endif
#if defined(USE_X11)
@@ -940,23 +856,23 @@ void BrowserMainLoop::CreateStartupTasks() {
#endif
StartupTask pre_create_threads =
base::Bind(&BrowserMainLoop::PreCreateThreads, base::Unretained(this));
- startup_task_runner_->AddTask(pre_create_threads);
+ startup_task_runner_->AddTask(std::move(pre_create_threads));
StartupTask create_threads =
base::Bind(&BrowserMainLoop::CreateThreads, base::Unretained(this));
- startup_task_runner_->AddTask(create_threads);
+ startup_task_runner_->AddTask(std::move(create_threads));
StartupTask post_create_threads =
base::Bind(&BrowserMainLoop::PostCreateThreads, base::Unretained(this));
- startup_task_runner_->AddTask(post_create_threads);
+ startup_task_runner_->AddTask(std::move(post_create_threads));
StartupTask browser_thread_started = base::Bind(
&BrowserMainLoop::BrowserThreadsStarted, base::Unretained(this));
- startup_task_runner_->AddTask(browser_thread_started);
+ startup_task_runner_->AddTask(std::move(browser_thread_started));
StartupTask pre_main_message_loop_run = base::Bind(
&BrowserMainLoop::PreMainMessageLoopRun, base::Unretained(this));
- startup_task_runner_->AddTask(pre_main_message_loop_run);
+ startup_task_runner_->AddTask(std::move(pre_main_message_loop_run));
#if defined(OS_ANDROID)
if (parameters_.ui_task) {
@@ -1022,44 +938,14 @@ int BrowserMainLoop::CreateThreads() {
*task_scheduler_init_params.get());
}
- TRACE_EVENT_BEGIN1("startup", "BrowserMainLoop::CreateThreads:start",
- "Thread", "BrowserThread::PROCESS_LAUNCHER");
-
-#if defined(OS_ANDROID)
- // Android specializes Launcher thread so it is accessible in java.
- // Note Android never does clean shutdown, so shutdown use-after-free
- // concerns are not a problem in practice.
- base::MessageLoop* message_loop = android::LauncherThread::GetMessageLoop();
- DCHECK(message_loop);
- // This BrowserThread will use this message loop instead of creating a new
- // thread. Note that means this/ thread will not be joined on shutdown, and
- // may cause use-after-free if anything tries to access objects deleted by
- // AtExitManager, such as non-leaky LazyInstance.
- process_launcher_thread_.reset(new BrowserProcessSubThread(
- BrowserThread::PROCESS_LAUNCHER, message_loop));
-#else // defined(OS_ANDROID)
- // This thread ID will be backed by a SingleThreadTaskRunner using
- // |task_traits|.
- // TODO(gab): WithBaseSyncPrimitives() is likely not required here.
- base::TaskTraits task_traits = {base::MayBlock(),
- base::WithBaseSyncPrimitives(),
- base::TaskPriority::USER_BLOCKING,
- base::TaskShutdownBehavior::BLOCK_SHUTDOWN};
- scoped_refptr<base::SingleThreadTaskRunner> redirection_task_runner =
- base::CreateSingleThreadTaskRunnerWithTraits(
- task_traits, base::SingleThreadTaskRunnerThreadMode::DEDICATED);
- DCHECK(redirection_task_runner);
- BrowserThreadImpl::RedirectThreadIDToTaskRunner(
- BrowserThread::PROCESS_LAUNCHER, std::move(redirection_task_runner));
-#endif // defined(OS_ANDROID)
-
- // |io_thread_| is created by |PostMainMessageLoopStart()|, but its
- // full initialization is deferred until this point because it requires
- // several dependencies we don't want to depend on so early in startup.
+ // The thread used for BrowserThread::IO is created in
+ // |PostMainMessageLoopStart()|, but it's only tagged as BrowserThread::IO
+ // here in order to prevent any code from statically posting to it before
+ // CreateThreads() (as such maintaining the invariant that PreCreateThreads()
+ // et al. "happen-before" BrowserThread::IO is "brought up").
DCHECK(io_thread_);
- io_thread_->InitIOThreadDelegate();
+ io_thread_->RegisterAsBrowserThread();
- TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
created_threads_ = true;
return result_code_;
}
@@ -1179,7 +1065,6 @@ void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
host_frame_sink_manager_.reset();
frame_sink_manager_impl_.reset();
compositing_mode_reporter_impl_.reset();
- forwarding_compositing_mode_reporter_impl_.reset();
#endif
// The device monitors are using |system_monitor_| as dependency, so delete
@@ -1206,39 +1091,9 @@ void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
{
base::ThreadRestrictions::ScopedAllowWait allow_wait_for_join;
-
- // Must be size_t so we can subtract from it.
- for (size_t thread_id = BrowserThread::ID_COUNT - 1;
- thread_id >= (BrowserThread::UI + 1); --thread_id) {
- // Find the thread object we want to stop. Looping over all valid
- // BrowserThread IDs and DCHECKing on a missing case in the switch
- // statement helps avoid a mismatch between this code and the
- // BrowserThread::ID enumeration.
- //
- // The destruction order is the reverse order of occurrence in the
- // BrowserThread::ID list. The rationale for the order is that he
- // PROCESS_LAUNCHER thread must be stopped after IO in case the IO thread
- // posted a task to terminate a process on the process launcher thread.
- switch (thread_id) {
- case BrowserThread::PROCESS_LAUNCHER: {
- TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
-#if defined(OS_ANDROID)
- ResetThread_PROCESS_LAUNCHER(std::move(process_launcher_thread_));
-#else // defined(OS_ANDROID)
- ResetThread_PROCESS_LAUNCHER();
-#endif // defined(OS_ANDROID)
- break;
- }
- case BrowserThread::IO: {
- TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
- ResetThread_IO(std::move(io_thread_));
- break;
- }
- case BrowserThread::UI:
- case BrowserThread::ID_COUNT:
- NOTREACHED();
- break;
- }
+ {
+ TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
+ ResetThread_IO(std::move(io_thread_));
}
{
@@ -1315,10 +1170,7 @@ void BrowserMainLoop::GetCompositingModeReporter(
return;
}
- if (base::FeatureList::IsEnabled(features::kVizDisplayCompositor))
- forwarding_compositing_mode_reporter_impl_->BindRequest(std::move(request));
- else
- compositing_mode_reporter_impl_->BindRequest(std::move(request));
+ compositing_mode_reporter_impl_->BindRequest(std::move(request));
#endif
}
@@ -1330,9 +1182,12 @@ void BrowserMainLoop::InitializeMainThread() {
TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
base::PlatformThread::SetName("CrBrowserMain");
- // Register the main thread by instantiating it, but don't call any methods.
- main_thread_.reset(
- new BrowserThreadImpl(BrowserThread::UI, base::MessageLoop::current()));
+ // Register the main thread. The main thread's task runner should already have
+ // been initialized in MainMessageLoopStart() (or before if
+ // MessageLoop::current() was externally provided).
+ DCHECK(base::ThreadTaskRunnerHandle::IsSet());
+ main_thread_.reset(new BrowserThreadImpl(
+ BrowserThread::UI, base::ThreadTaskRunnerHandle::Get()));
}
int BrowserMainLoop::BrowserThreadsStarted() {
@@ -1392,13 +1247,13 @@ int BrowserMainLoop::BrowserThreadsStarted() {
if (browser_is_viz_host) {
host_frame_sink_manager_ = std::make_unique<viz::HostFrameSinkManager>();
BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
- if (base::FeatureList::IsEnabled(features::kVizDisplayCompositor)) {
- forwarding_compositing_mode_reporter_impl_ =
- std::make_unique<viz::ForwardingCompositingModeReporterImpl>();
+ compositing_mode_reporter_impl_ =
+ std::make_unique<viz::CompositingModeReporterImpl>();
+ if (base::FeatureList::IsEnabled(features::kVizDisplayCompositor)) {
auto transport_factory = std::make_unique<VizProcessTransportFactory>(
BrowserGpuChannelHostFactory::instance(), GetResizeTaskRunner(),
- forwarding_compositing_mode_reporter_impl_.get());
+ compositing_mode_reporter_impl_.get());
transport_factory->ConnectHostFrameSinkManager();
ImageTransportFactory::SetFactory(std::move(transport_factory));
} else {
@@ -1408,8 +1263,6 @@ int BrowserMainLoop::BrowserThreadsStarted() {
surface_utils::ConnectWithLocalFrameSinkManager(
host_frame_sink_manager_.get(), frame_sink_manager_impl_.get());
- compositing_mode_reporter_impl_ =
- std::make_unique<viz::CompositingModeReporterImpl>();
ImageTransportFactory::SetFactory(
std::make_unique<GpuProcessTransportFactory>(
@@ -1455,9 +1308,12 @@ int BrowserMainLoop::BrowserThreadsStarted() {
#endif
#if BUILDFLAG(ENABLE_WEBRTC)
- webrtc_event_log_manager_.reset(
- WebRtcEventLogManager::CreateSingletonInstance());
- webrtc_internals_.reset(WebRTCInternals::CreateSingletonInstance());
+ // Instantiated once using CreateSingletonInstance(), and accessed only using
+ // GetInstance(), which is not allowed to create the object. This allows us
+ // to ensure that it cannot be used before objects it relies on have been
+ // created; namely, WebRtcEventLogManager.
+ // Allowed to leak when the browser exits.
+ WebRTCInternals::CreateSingletonInstance();
#endif
// RDH needs the IO thread to be created
@@ -1503,7 +1359,7 @@ int BrowserMainLoop::BrowserThreadsStarted() {
"startup",
"BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
user_input_monitor_ = media::UserInputMonitor::Create(
- io_thread_->task_runner(), main_thread_->task_runner());
+ io_thread_->task_runner(), base::ThreadTaskRunnerHandle::Get());
}
{
@@ -1523,7 +1379,7 @@ int BrowserMainLoop::BrowserThreadsStarted() {
#endif
ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads);
- if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(nullptr) &&
+ if (GpuDataManagerImpl::GetInstance()->GpuProcessStartAllowed() &&
!established_gpu_channel && always_uses_gpu && browser_is_viz_host) {
TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
TRACE_EVENT_SCOPE_THREAD);
@@ -1534,6 +1390,10 @@ int BrowserMainLoop::BrowserThreadsStarted() {
true /* force_create */));
}
+#if defined(OS_WIN)
+ GpuDataManagerImpl::GetInstance()->RequestGpuSupportedRuntimeVersion();
+#endif
+
#if defined(OS_MACOSX)
ThemeHelperMac::GetInstance();
SystemHotkeyHelperMac::GetInstance()->DeferredLoadSystemHotkeys();
@@ -1653,9 +1513,10 @@ void BrowserMainLoop::InitializeIOThread() {
options.priority = base::ThreadPriority::DISPLAY;
#endif
- io_thread_.reset(new BrowserProcessSubThread(BrowserThread::IO));
+ io_thread_ = std::make_unique<BrowserProcessSubThread>(BrowserThread::IO);
+
if (!io_thread_->StartWithOptions(options))
- LOG(FATAL) << "Failed to start the browser thread: IO";
+ LOG(FATAL) << "Failed to start BrowserThread::IO";
}
void BrowserMainLoop::InitializeMojo() {
@@ -1699,7 +1560,8 @@ void BrowserMainLoop::InitializeMojo() {
if (parsed_command_line_.HasSwitch(switches::kTraceStartup)) {
base::trace_event::TraceConfig trace_config(
parsed_command_line_.GetSwitchValueASCII(switches::kTraceStartup),
- base::trace_event::RECORD_UNTIL_FULL);
+ parsed_command_line_.GetSwitchValueASCII(
+ switches::kTraceStartupRecordMode));
TracingController::GetInstance()->StartTracing(
trace_config, TracingController::StartTracingDoneCallback());
} else if (parsed_command_line_.HasSwitch(switches::kTraceToConsole)) {
@@ -1805,6 +1667,12 @@ void BrowserMainLoop::CreateAudioManager() {
}
CHECK(audio_manager_);
+ AudioMirroringManager* const mirroring_manager =
+ AudioMirroringManager::GetInstance();
+ audio_manager_->SetDiverterCallbacks(
+ mirroring_manager->GetAddDiverterCallback(),
+ mirroring_manager->GetRemoveDiverterCallback());
+
TRACE_EVENT_INSTANT0("startup", "Starting Audio service task runner",
TRACE_EVENT_SCOPE_THREAD);
audio_service_runner_->StartWithTaskRunner(audio_manager_->GetTaskRunner());
diff --git a/chromium/content/browser/browser_main_loop.h b/chromium/content/browser/browser_main_loop.h
index db783e76d2f..20b2ac7b95a 100644
--- a/chromium/content/browser/browser_main_loop.h
+++ b/chromium/content/browser/browser_main_loop.h
@@ -13,9 +13,8 @@
#include "base/memory/ref_counted.h"
#include "base/timer/timer.h"
#include "build/build_config.h"
-#include "content/browser/browser_process_sub_thread.h"
#include "content/public/browser/browser_main_runner.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "mojo/public/cpp/bindings/binding_set.h"
#include "services/viz/public/interfaces/compositing/compositing_mode_watcher.mojom.h"
#include "ui/base/ui_features.h"
@@ -85,7 +84,6 @@ class ImageCursorsSet;
namespace viz {
class CompositingModeReporterImpl;
-class ForwardingCompositingModeReporterImpl;
class FrameSinkManagerImpl;
class HostFrameSinkManager;
}
@@ -93,6 +91,7 @@ class HostFrameSinkManager;
namespace content {
class BrowserMainParts;
class BrowserOnlineStateObserver;
+class BrowserProcessSubThread;
class BrowserThreadImpl;
class LoaderDelegateImpl;
class MediaStreamManager;
@@ -105,11 +104,6 @@ class SwapMetricsDriver;
class TracingControllerImpl;
struct MainFunctionParams;
-#if BUILDFLAG(ENABLE_WEBRTC)
-class WebRTCInternals;
-class WebRtcEventLogManager;
-#endif
-
#if defined(OS_ANDROID)
class ScreenOrientationDelegate;
#endif
@@ -249,7 +243,10 @@ class CONTENT_EXPORT BrowserMainLoop {
void MainMessageLoopRun();
+ // Initializes |io_thread_|. It will not be promoted to BrowserThread::IO
+ // until CreateThreads().
void InitializeIOThread();
+
void InitializeMojo();
base::FilePath GetStartupTraceFileName(
const base::CommandLine& command_line) const;
@@ -291,6 +288,7 @@ class CONTENT_EXPORT BrowserMainLoop {
std::unique_ptr<base::MessageLoop> main_message_loop_;
// Members initialized in |PostMainMessageLoopStart()| -----------------------
+ std::unique_ptr<BrowserProcessSubThread> io_thread_;
std::unique_ptr<base::SystemMonitor> system_monitor_;
std::unique_ptr<base::PowerMonitor> power_monitor_;
std::unique_ptr<base::HighResolutionTimerManager> hi_res_timer_manager_;
@@ -341,23 +339,6 @@ class CONTENT_EXPORT BrowserMainLoop {
gpu_data_manager_visual_proxy_;
#endif
- // Members initialized in |CreateThreads()| ----------------------------------
- // Only the IO thread is a real thread by default, other BrowserThreads are
- // redirected to TaskScheduler under the hood.
- std::unique_ptr<BrowserProcessSubThread> io_thread_;
-#if defined(OS_ANDROID)
- // On Android, the PROCESS_LAUNCHER thread is handled by Java,
- // |process_launcher_thread_| is merely a proxy to the real message loop.
- std::unique_ptr<BrowserProcessSubThread> process_launcher_thread_;
-#elif defined(OS_WIN)
- // TaskScheduler doesn't support async I/O on Windows as CACHE thread is
- // the only user and this use case is going away in
- // https://codereview.chromium.org/2216583003/.
- // TODO(gavinp): Remove this (and thus enable redirection of the CACHE thread
- // on Windows) once that CL lands.
- std::unique_ptr<BrowserProcessSubThread> cache_thread_;
-#endif
-
// Members initialized in |BrowserThreadsStarted()| --------------------------
std::unique_ptr<ServiceManagerContext> service_manager_context_;
std::unique_ptr<mojo::edk::ScopedIPCSupport> mojo_ipc_support_;
@@ -381,11 +362,6 @@ class CONTENT_EXPORT BrowserMainLoop {
std::unique_ptr<media::DeviceMonitorMac> device_monitor_mac_;
#endif
-#if BUILDFLAG(ENABLE_WEBRTC)
- std::unique_ptr<WebRtcEventLogManager> webrtc_event_log_manager_;
- std::unique_ptr<WebRTCInternals> webrtc_internals_;
-#endif
-
std::unique_ptr<LoaderDelegateImpl> loader_delegate_;
std::unique_ptr<ResourceDispatcherHostImpl> resource_dispatcher_host_;
std::unique_ptr<MediaStreamManager> media_stream_manager_;
@@ -402,10 +378,6 @@ class CONTENT_EXPORT BrowserMainLoop {
// http://crbug.com/657959.
std::unique_ptr<viz::FrameSinkManagerImpl> frame_sink_manager_impl_;
- // Forwards requests to watch the compositing mode on to the viz process. This
- // is null if the display compositor in this process.
- std::unique_ptr<viz::ForwardingCompositingModeReporterImpl>
- forwarding_compositing_mode_reporter_impl_;
// Reports on the compositing mode in the system for clients to submit
// resources of the right type. This is null if the display compositor
// is not in this process.
diff --git a/chromium/content/browser/browser_main_loop_unittest.cc b/chromium/content/browser/browser_main_loop_unittest.cc
index 28451f3ec3d..728331bda09 100644
--- a/chromium/content/browser/browser_main_loop_unittest.cc
+++ b/chromium/content/browser/browser_main_loop_unittest.cc
@@ -9,6 +9,8 @@
#include "base/sys_info.h"
#include "base/task_scheduler/task_scheduler.h"
#include "base/test/scoped_command_line.h"
+#include "content/browser/browser_thread_impl.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
#include "testing/gtest/include/gtest/gtest.h"
diff --git a/chromium/content/browser/browser_main_runner.cc b/chromium/content/browser/browser_main_runner.cc
index b9abae7fb54..20d32d31d87 100644
--- a/chromium/content/browser/browser_main_runner.cc
+++ b/chromium/content/browser/browser_main_runner.cc
@@ -16,6 +16,7 @@
#include "base/run_loop.h"
#include "base/sampling_heap_profiler/sampling_heap_profiler.h"
#include "base/strings/string_number_conversions.h"
+#include "base/synchronization/atomic_flag.h"
#include "base/time/time.h"
#include "base/trace_event/heap_profiler_allocation_context_tracker.h"
#include "base/trace_event/trace_event.h"
@@ -26,7 +27,6 @@
#include "content/browser/browser_shutdown_profile_dumper.h"
#include "content/browser/notification_service_impl.h"
#include "content/common/content_switches_internal.h"
-#include "content/public/browser/tracing_controller.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
#include "third_party/skia/include/core/SkGraphics.h"
@@ -74,6 +74,7 @@ class BrowserMainRunnerImpl : public BrowserMainRunner {
const base::TimeTicks start_time_step1 = base::TimeTicks::Now();
+ base::SamplingHeapProfiler::InitTLSSlot();
if (parameters.command_line.HasSwitch(switches::kSamplingHeapProfiler)) {
base::SamplingHeapProfiler* profiler =
base::SamplingHeapProfiler::GetInstance();
@@ -190,8 +191,7 @@ class BrowserMainRunnerImpl : public BrowserMainRunner {
startup_profiler.reset(
new BrowserShutdownProfileDumper(main_loop_->startup_trace_file()));
}
- } else if (tracing::TraceConfigFile::GetInstance()->IsEnabled() &&
- TracingController::GetInstance()->IsTracing()) {
+ } else if (tracing::TraceConfigFile::GetInstance()->IsEnabled()) {
base::FilePath result_file;
#if defined(OS_ANDROID)
TracingControllerAndroid::GenerateTracingFilePath(&result_file);
diff --git a/chromium/content/browser/browser_plugin/browser_plugin_embedder.cc b/chromium/content/browser/browser_plugin/browser_plugin_embedder.cc
index d3bf567e44f..c3e3bbd9b50 100644
--- a/chromium/content/browser/browser_plugin/browser_plugin_embedder.cc
+++ b/chromium/content/browser/browser_plugin/browser_plugin_embedder.cc
@@ -60,7 +60,8 @@ void BrowserPluginEmbedder::CancelGuestDialogs() {
return;
GetBrowserPluginGuestManager()->ForEachGuest(
- web_contents(), base::Bind(&BrowserPluginEmbedder::CancelDialogs));
+ web_contents(),
+ base::BindRepeating(&BrowserPluginEmbedder::CancelDialogs));
}
void BrowserPluginEmbedder::StartDrag(BrowserPluginGuest* guest) {
@@ -101,7 +102,7 @@ void BrowserPluginEmbedder::DidSendScreenRects() {
GetBrowserPluginGuestManager()->ForEachGuest(
web_contents(),
- base::Bind(&BrowserPluginEmbedder::DidSendScreenRectsCallback));
+ base::BindRepeating(&BrowserPluginEmbedder::DidSendScreenRectsCallback));
}
bool BrowserPluginEmbedder::OnMessageReceived(
@@ -179,8 +180,9 @@ bool BrowserPluginEmbedder::HandleKeyboardEvent(
bool event_consumed = false;
GetBrowserPluginGuestManager()->ForEachGuest(
web_contents(),
- base::Bind(&BrowserPluginEmbedder::UnlockMouseIfNecessaryCallback,
- &event_consumed));
+ base::BindRepeating(
+ &BrowserPluginEmbedder::UnlockMouseIfNecessaryCallback,
+ &event_consumed));
return event_consumed;
}
@@ -204,7 +206,8 @@ bool BrowserPluginEmbedder::WereAnyGuestsRecentlyAudible() {
return GetBrowserPluginGuestManager()->ForEachGuest(
web_contents(),
- base::Bind(&BrowserPluginEmbedder::GuestRecentlyAudibleCallback));
+ base::BindRepeating(
+ &BrowserPluginEmbedder::GuestRecentlyAudibleCallback));
}
// static
diff --git a/chromium/content/browser/browser_plugin/browser_plugin_embedder.h b/chromium/content/browser/browser_plugin/browser_plugin_embedder.h
index b73418b463a..e1007f040a7 100644
--- a/chromium/content/browser/browser_plugin/browser_plugin_embedder.h
+++ b/chromium/content/browser/browser_plugin/browser_plugin_embedder.h
@@ -18,7 +18,7 @@
#include "base/memory/weak_ptr.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
-#include "third_party/WebKit/public/platform/WebDragOperation.h"
+#include "third_party/blink/public/platform/web_drag_operation.h"
struct BrowserPluginHostMsg_Attach_Params;
diff --git a/chromium/content/browser/browser_plugin/browser_plugin_guest.cc b/chromium/content/browser/browser_plugin/browser_plugin_guest.cc
index 3e1786aa690..15994d5dada 100644
--- a/chromium/content/browser/browser_plugin/browser_plugin_guest.cc
+++ b/chromium/content/browser/browser_plugin/browser_plugin_guest.cc
@@ -20,7 +20,6 @@
#include "components/viz/common/surfaces/surface_info.h"
#include "components/viz/service/surfaces/surface.h"
#include "content/browser/browser_plugin/browser_plugin_embedder.h"
-#include "content/browser/browser_thread_impl.h"
#include "content/browser/child_process_security_policy_impl.h"
#include "content/browser/frame_host/render_frame_host_impl.h"
#include "content/browser/frame_host/render_frame_proxy_host.h"
@@ -37,6 +36,7 @@
#include "content/common/browser_plugin/browser_plugin_messages.h"
#include "content/common/content_constants_internal.h"
#include "content/common/drag_messages.h"
+#include "content/common/frame_resize_params.h"
#include "content/common/input/ime_text_span_conversions.h"
#include "content/common/input_messages.h"
#include "content/common/text_input_state.h"
@@ -62,24 +62,6 @@
namespace content {
-namespace {
-
-std::vector<ui::ImeTextSpan> ConvertToUiImeTextSpan(
- const std::vector<blink::WebImeTextSpan>& ime_text_spans) {
- std::vector<ui::ImeTextSpan> ui_ime_text_spans;
- for (const auto& ime_text_span : ime_text_spans) {
- ui_ime_text_spans.emplace_back(ui::ImeTextSpan(
- ConvertWebImeTextSpanTypeToUiType(ime_text_span.type),
- ime_text_span.start_offset, ime_text_span.end_offset,
- ime_text_span.underline_color, ime_text_span.thick,
- ime_text_span.background_color,
- ime_text_span.suggestion_highlight_color, ime_text_span.suggestions));
- }
- return ui_ime_text_spans;
-}
-
-}; // namespace
-
class BrowserPluginGuest::EmbedderVisibilityObserver
: public WebContentsObserver {
public:
@@ -183,6 +165,17 @@ int BrowserPluginGuest::LoadURLWithParams(
return GetGuestProxyRoutingID();
}
+void BrowserPluginGuest::EnableAutoResize(const gfx::Size& min_size,
+ const gfx::Size& max_size) {
+ SendMessageToEmbedder(std::make_unique<BrowserPluginMsg_EnableAutoResize>(
+ browser_plugin_instance_id_, min_size, max_size));
+}
+
+void BrowserPluginGuest::DisableAutoResize() {
+ SendMessageToEmbedder(std::make_unique<BrowserPluginMsg_DisableAutoResize>(
+ browser_plugin_instance_id_));
+}
+
void BrowserPluginGuest::ResizeDueToAutoResize(const gfx::Size& new_size,
uint64_t sequence_number) {
SendMessageToEmbedder(
@@ -439,8 +432,8 @@ void BrowserPluginGuest::ResendEventToEmbedder(
if (event.GetType() == blink::WebInputEvent::kGestureScrollUpdate) {
blink::WebGestureEvent resent_gesture_event;
memcpy(&resent_gesture_event, &event, sizeof(blink::WebGestureEvent));
- resent_gesture_event.x += offset_from_embedder.x();
- resent_gesture_event.y += offset_from_embedder.y();
+ resent_gesture_event.SetPositionInWidget(
+ resent_gesture_event.PositionInWidget() + offset_from_embedder);
// Mark the resend source with the browser plugin's instance id, so the
// correct browser_plugin will know to ignore the event.
resent_gesture_event.resending_plugin_id = browser_plugin_instance_id_;
@@ -637,7 +630,7 @@ void BrowserPluginGuest::SendTextInputTypeChangedToView(
if (last_text_input_state_.get()) {
guest_rwhv->TextInputStateChanged(*last_text_input_state_);
- if (auto* rwh = guest_rwhv->GetRenderWidgetHostImpl()) {
+ if (auto* rwh = guest_rwhv->host()) {
// We need composition range information for some IMEs. To get the
// updates, we need to explicitly ask the renderer to monitor and send the
// composition information changes. RenderWidgetHostView of the page will
@@ -913,7 +906,7 @@ void BrowserPluginGuest::OnImeSetComposition(
int browser_plugin_instance_id,
const BrowserPluginHostMsg_SetComposition_Params& params) {
std::vector<ui::ImeTextSpan> ui_ime_text_spans =
- ConvertToUiImeTextSpan(params.ime_text_spans);
+ ConvertBlinkImeTextSpansToUiImeTextSpans(params.ime_text_spans);
GetWebContents()
->GetRenderViewHost()
->GetWidget()
@@ -930,7 +923,7 @@ void BrowserPluginGuest::OnImeCommitText(
const gfx::Range& replacement_range,
int relative_cursor_pos) {
std::vector<ui::ImeTextSpan> ui_ime_text_spans =
- ConvertToUiImeTextSpan(ime_text_spans);
+ ConvertBlinkImeTextSpansToUiImeTextSpans(ime_text_spans);
GetWebContents()
->GetRenderViewHost()
->GetWidget()
@@ -1020,18 +1013,15 @@ void BrowserPluginGuest::OnSetVisibility(int browser_plugin_instance_id,
return;
guest_visible_ = visible;
- // TODO(fdoray): Simplify the logic below. https://crbug.com/668690
- if (!guest_visible_ || embedder_visibility_ == Visibility::HIDDEN) {
+
+ // Do not use WebContents::UpdateWebContentsVisibility() because it ignores
+ // visibility changes that come before the first change to VISIBLE.
+ if (!guest_visible_ || embedder_visibility_ == Visibility::HIDDEN)
GetWebContents()->WasHidden();
- } else if (embedder_visibility_ == Visibility::VISIBLE) {
+ else if (embedder_visibility_ == Visibility::VISIBLE)
GetWebContents()->WasShown();
- if (GetWebContents()->GetVisibility() == Visibility::OCCLUDED)
- GetWebContents()->WasUnOccluded();
- } else {
- if (GetWebContents()->GetVisibility() == Visibility::HIDDEN)
- GetWebContents()->WasShown();
+ else
GetWebContents()->WasOccluded();
- }
}
void BrowserPluginGuest::OnUnlockMouse() {
@@ -1053,13 +1043,11 @@ void BrowserPluginGuest::OnUnlockMouseAck(int browser_plugin_instance_id) {
void BrowserPluginGuest::OnUpdateResizeParams(
int browser_plugin_instance_id,
- const gfx::Rect& frame_rect,
- const ScreenInfo& screen_info,
- uint64_t sequence_number,
- const viz::LocalSurfaceId& local_surface_id) {
+ const viz::LocalSurfaceId& local_surface_id,
+ const FrameResizeParams& resize_params) {
if (local_surface_id_ > local_surface_id ||
- ((frame_rect_.size() != frame_rect.size() ||
- screen_info_ != screen_info) &&
+ ((frame_rect_.size() != resize_params.screen_space_rect.size() ||
+ screen_info_ != resize_params.screen_info) &&
local_surface_id_ == local_surface_id)) {
SiteInstance* owner_site_instance = delegate_->GetOwnerSiteInstance();
bad_message::ReceivedBadMessage(
@@ -1068,8 +1056,8 @@ void BrowserPluginGuest::OnUpdateResizeParams(
return;
}
- screen_info_ = screen_info;
- frame_rect_ = frame_rect;
+ screen_info_ = resize_params.screen_info;
+ frame_rect_ = resize_params.screen_space_rect;
GetWebContents()->SendScreenRects();
local_surface_id_ = local_surface_id;
@@ -1081,8 +1069,13 @@ void BrowserPluginGuest::OnUpdateResizeParams(
RenderWidgetHostImpl::From(view->GetRenderWidgetHost());
DCHECK(render_widget_host);
+ render_widget_host->SetAutoResize(resize_params.auto_resize_enabled,
+ resize_params.min_size_for_auto_resize,
+ resize_params.max_size_for_auto_resize);
+
if (render_widget_host->auto_resize_enabled()) {
- render_widget_host->DidAllocateLocalSurfaceIdForAutoResize(sequence_number);
+ render_widget_host->DidAllocateLocalSurfaceIdForAutoResize(
+ resize_params.auto_resize_sequence_number);
return;
}
diff --git a/chromium/content/browser/browser_plugin/browser_plugin_guest.h b/chromium/content/browser/browser_plugin/browser_plugin_guest.h
index cd64f60b5a9..5c2d39745cc 100644
--- a/chromium/content/browser/browser_plugin/browser_plugin_guest.h
+++ b/chromium/content/browser/browser_plugin/browser_plugin_guest.h
@@ -36,11 +36,11 @@
#include "content/public/browser/web_contents_observer.h"
#include "content/public/common/input_event_ack_state.h"
#include "content/public/common/screen_info.h"
-#include "third_party/WebKit/public/platform/WebDragOperation.h"
-#include "third_party/WebKit/public/platform/WebFocusType.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
-#include "third_party/WebKit/public/web/WebDragStatus.h"
-#include "third_party/WebKit/public/web/WebImeTextSpan.h"
+#include "third_party/blink/public/platform/web_drag_operation.h"
+#include "third_party/blink/public/platform/web_focus_type.h"
+#include "third_party/blink/public/platform/web_input_event.h"
+#include "third_party/blink/public/web/web_drag_status.h"
+#include "third_party/blink/public/web/web_ime_text_span.h"
#include "ui/base/ime/text_input_mode.h"
#include "ui/base/ime/text_input_type.h"
#include "ui/gfx/geometry/rect.h"
@@ -71,6 +71,7 @@ class RenderWidgetHostView;
class RenderWidgetHostViewBase;
class SiteInstance;
struct DropData;
+struct FrameResizeParams;
struct ScreenInfo;
struct TextInputState;
@@ -178,6 +179,8 @@ class CONTENT_EXPORT BrowserPluginGuest : public GuestHost,
BrowserPluginGuestManager* GetBrowserPluginGuestManager() const;
+ void EnableAutoResize(const gfx::Size& min_size, const gfx::Size& max_size);
+ void DisableAutoResize();
void ResizeDueToAutoResize(const gfx::Size& new_size,
uint64_t sequence_number);
@@ -318,7 +321,8 @@ class CONTENT_EXPORT BrowserPluginGuest : public GuestHost,
// fewer GPU and CPU resources.
//
// When every WebContents in a RenderProcessHost is hidden, it will lower
- // the priority of the process (see RenderProcessHostImpl::WidgetHidden).
+ // the priority of the process (see
+ // RenderProcessHostImpl::UpdateClientPriority).
//
// It will also send a message to the guest renderer process to cleanup
// resources such as dropping back buffers and adjusting memory limits (if in
@@ -331,10 +335,8 @@ class CONTENT_EXPORT BrowserPluginGuest : public GuestHost,
void OnUnlockMouse();
void OnUnlockMouseAck(int instance_id);
void OnUpdateResizeParams(int instance_id,
- const gfx::Rect& frame_rect,
- const ScreenInfo& screen_info,
- uint64_t sequence_number,
- const viz::LocalSurfaceId& local_surface_id);
+ const viz::LocalSurfaceId& local_surface_id,
+ const FrameResizeParams& resize_params);
void OnTextInputStateChanged(const TextInputState& params);
void OnImeSetComposition(
diff --git a/chromium/content/browser/browser_plugin/browser_plugin_message_filter.cc b/chromium/content/browser/browser_plugin/browser_plugin_message_filter.cc
index bd5d49b9cc8..fec9859d9b3 100644
--- a/chromium/content/browser/browser_plugin/browser_plugin_message_filter.cc
+++ b/chromium/content/browser/browser_plugin/browser_plugin_message_filter.cc
@@ -13,7 +13,6 @@
#include "content/common/view_messages.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_plugin_guest_manager.h"
-#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_view_host.h"
namespace content {
diff --git a/chromium/content/browser/browser_plugin/browser_plugin_message_filter.h b/chromium/content/browser/browser_plugin/browser_plugin_message_filter.h
index ff17d6f5e69..646f424825e 100644
--- a/chromium/content/browser/browser_plugin/browser_plugin_message_filter.h
+++ b/chromium/content/browser/browser_plugin/browser_plugin_message_filter.h
@@ -7,6 +7,7 @@
#include "base/macros.h"
#include "content/public/browser/browser_message_filter.h"
+#include "content/public/browser/browser_thread.h"
namespace content {
diff --git a/chromium/content/browser/browser_process_sub_thread.cc b/chromium/content/browser/browser_process_sub_thread.cc
index 71f1396dbde..0902fb6bfd0 100644
--- a/chromium/content/browser/browser_process_sub_thread.cc
+++ b/chromium/content/browser/browser_process_sub_thread.cc
@@ -4,57 +4,121 @@
#include "content/browser/browser_process_sub_thread.h"
-#include "base/debug/leak_tracker.h"
+#include "base/compiler_specific.h"
+#include "base/debug/alias.h"
#include "base/threading/thread_restrictions.h"
#include "base/trace_event/memory_dump_manager.h"
-#include "build/build_config.h"
#include "content/browser/browser_child_process_host_impl.h"
+#include "content/browser/browser_thread_impl.h"
#include "content/browser/gpu/browser_gpu_memory_buffer_manager.h"
#include "content/browser/notification_service_impl.h"
+#include "content/public/browser/browser_thread_delegate.h"
#include "net/url_request/url_fetcher.h"
#include "net/url_request/url_request.h"
+#if defined(OS_ANDROID)
+#include "base/android/jni_android.h"
+#endif
+
#if defined(OS_WIN)
#include "base/win/scoped_com_initializer.h"
#endif
namespace content {
-BrowserProcessSubThread::BrowserProcessSubThread(BrowserThread::ID identifier)
- : BrowserThreadImpl(identifier) {}
+namespace {
+BrowserThreadDelegate* g_io_thread_delegate = nullptr;
+} // namespace
-BrowserProcessSubThread::BrowserProcessSubThread(
- BrowserThread::ID identifier,
- base::MessageLoop* message_loop)
- : BrowserThreadImpl(identifier, message_loop) {}
+// static
+void BrowserThread::SetIOThreadDelegate(BrowserThreadDelegate* delegate) {
+ // |delegate| can only be set/unset while BrowserThread::IO isn't up.
+ DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::IO));
+ // and it cannot be set twice.
+ DCHECK(!g_io_thread_delegate || !delegate);
+
+ g_io_thread_delegate = delegate;
+}
+
+BrowserProcessSubThread::BrowserProcessSubThread(BrowserThread::ID identifier)
+ : base::Thread(BrowserThreadImpl::GetThreadName(identifier)),
+ identifier_(identifier) {
+ // Not bound to creation thread.
+ DETACH_FROM_THREAD(browser_thread_checker_);
+}
BrowserProcessSubThread::~BrowserProcessSubThread() {
Stop();
}
+void BrowserProcessSubThread::RegisterAsBrowserThread() {
+ DCHECK(IsRunning());
+
+ DCHECK(!browser_thread_);
+ browser_thread_.reset(new BrowserThreadImpl(identifier_, task_runner()));
+
+ // Unretained(this) is safe as |this| outlives its underlying thread.
+ task_runner()->PostTask(
+ FROM_HERE,
+ base::BindOnce(
+ &BrowserProcessSubThread::CompleteInitializationOnBrowserThread,
+ Unretained(this)));
+}
+
+void BrowserProcessSubThread::AllowBlockingForTesting() {
+ DCHECK(!IsRunning());
+ is_blocking_allowed_for_testing_ = true;
+}
+
void BrowserProcessSubThread::Init() {
+ DCHECK_CALLED_ON_VALID_THREAD(browser_thread_checker_);
+
#if defined(OS_WIN)
- com_initializer_.reset(new base::win::ScopedCOMInitializer());
+ com_initializer_ = std::make_unique<base::win::ScopedCOMInitializer>();
#endif
- notification_service_.reset(new NotificationServiceImpl());
+ if (!is_blocking_allowed_for_testing_) {
+ base::DisallowBlocking();
+ base::DisallowBaseSyncPrimitives();
+ }
+}
- BrowserThreadImpl::Init();
+void BrowserProcessSubThread::Run(base::RunLoop* run_loop) {
+ DCHECK_CALLED_ON_VALID_THREAD(browser_thread_checker_);
- if (BrowserThread::CurrentlyOn(BrowserThread::IO)) {
- // Though this thread is called the "IO" thread, it actually just routes
- // messages around; it shouldn't be allowed to perform any blocking disk
- // I/O.
- base::ThreadRestrictions::SetIOAllowed(false);
- base::ThreadRestrictions::DisallowWaiting();
+#if defined(OS_ANDROID)
+ // Not to reset thread name to "Thread-???" by VM, attach VM with thread name.
+ // Though it may create unnecessary VM thread objects, keeping thread name
+ // gives more benefit in debugging in the platform.
+ if (!thread_name().empty()) {
+ base::android::AttachCurrentThreadWithName(thread_name());
+ }
+#endif
+
+ switch (identifier_) {
+ case BrowserThread::UI:
+ // The main thread is usually promoted as the UI thread and doesn't go
+ // through Run() but some tests do run a separate UI thread.
+ UIThreadRun(run_loop);
+ break;
+ case BrowserThread::IO:
+ IOThreadRun(run_loop);
+ return;
+ case BrowserThread::ID_COUNT:
+ NOTREACHED();
+ break;
}
}
void BrowserProcessSubThread::CleanUp() {
+ DCHECK_CALLED_ON_VALID_THREAD(browser_thread_checker_);
+
+ // Run extra cleanup if this thread represents BrowserThread::IO.
if (BrowserThread::CurrentlyOn(BrowserThread::IO))
- IOThreadPreCleanUp();
+ IOThreadCleanUp();
- BrowserThreadImpl::CleanUp();
+ if (identifier_ == BrowserThread::IO && g_io_thread_delegate)
+ g_io_thread_delegate->CleanUp();
notification_service_.reset();
@@ -63,7 +127,41 @@ void BrowserProcessSubThread::CleanUp() {
#endif
}
-void BrowserProcessSubThread::IOThreadPreCleanUp() {
+void BrowserProcessSubThread::CompleteInitializationOnBrowserThread() {
+ DCHECK_CALLED_ON_VALID_THREAD(browser_thread_checker_);
+
+ notification_service_ = std::make_unique<NotificationServiceImpl>();
+
+ if (identifier_ == BrowserThread::IO && g_io_thread_delegate) {
+ // Allow blocking calls while initializing the IO thread.
+ base::ScopedAllowBlocking allow_blocking_for_init;
+ g_io_thread_delegate->Init();
+ }
+}
+
+// We disable optimizations for Run specifications so the compiler doesn't merge
+// them all together.
+MSVC_DISABLE_OPTIMIZE()
+MSVC_PUSH_DISABLE_WARNING(4748)
+
+NOINLINE void BrowserProcessSubThread::UIThreadRun(base::RunLoop* run_loop) {
+ const int line_number = __LINE__;
+ Thread::Run(run_loop);
+ base::debug::Alias(&line_number);
+}
+
+NOINLINE void BrowserProcessSubThread::IOThreadRun(base::RunLoop* run_loop) {
+ const int line_number = __LINE__;
+ Thread::Run(run_loop);
+ base::debug::Alias(&line_number);
+}
+
+MSVC_POP_WARNING()
+MSVC_ENABLE_OPTIMIZE();
+
+void BrowserProcessSubThread::IOThreadCleanUp() {
+ DCHECK_CALLED_ON_VALID_THREAD(browser_thread_checker_);
+
// Kill all things that might be holding onto
// net::URLRequest/net::URLRequestContexts.
diff --git a/chromium/content/browser/browser_process_sub_thread.h b/chromium/content/browser/browser_process_sub_thread.h
index 5f29b481943..f4b87997e3f 100644
--- a/chromium/content/browser/browser_process_sub_thread.h
+++ b/chromium/content/browser/browser_process_sub_thread.h
@@ -8,9 +8,11 @@
#include <memory>
#include "base/macros.h"
+#include "base/threading/thread.h"
+#include "base/threading/thread_checker.h"
#include "build/build_config.h"
-#include "content/browser/browser_thread_impl.h"
#include "content/common/content_export.h"
+#include "content/public/browser/browser_thread.h"
#if defined(OS_WIN)
namespace base {
@@ -27,29 +29,57 @@ class NotificationService;
namespace content {
// ----------------------------------------------------------------------------
-// BrowserProcessSubThread
-//
-// This simple thread object is used for the specialized threads that the
-// BrowserProcess spins up.
+// A BrowserProcessSubThread is a physical thread backing a BrowserThread.
//
// Applications must initialize the COM library before they can call
// COM library functions other than CoGetMalloc and memory allocation
// functions, so this class initializes COM for those users.
-class CONTENT_EXPORT BrowserProcessSubThread : public BrowserThreadImpl {
+class CONTENT_EXPORT BrowserProcessSubThread : public base::Thread {
public:
+ // Constructs a BrowserProcessSubThread for |identifier|.
explicit BrowserProcessSubThread(BrowserThread::ID identifier);
- BrowserProcessSubThread(BrowserThread::ID identifier,
- base::MessageLoop* message_loop);
~BrowserProcessSubThread() override;
+ // Registers this thread to represent |identifier_| in the browser_thread.h
+ // API. This thread must already be running when this is called. This can only
+ // be called once per BrowserProcessSubThread instance.
+ void RegisterAsBrowserThread();
+
+ // Ideally there wouldn't be a special blanket allowance to block the
+ // BrowserThreads in tests but TestBrowserThreadImpl previously bypassed
+ // BrowserProcessSubThread and hence wasn't subject to ThreadRestrictions...
+ // Flipping that around in favor of explicit scoped allowances would be
+ // preferable but a non-trivial amount of work. Can only be called before
+ // starting this BrowserProcessSubThread.
+ void AllowBlockingForTesting();
+
protected:
void Init() override;
+ void Run(base::RunLoop* run_loop) override;
void CleanUp() override;
private:
- // These methods encapsulate cleanup that needs to happen on the IO thread
- // before we call the embedder's CleanUp function.
- void IOThreadPreCleanUp();
+ // Second Init() phase that must happen on this thread but can only happen
+ // after it's promoted to a BrowserThread in |RegisterAsBrowserThread()|.
+ void CompleteInitializationOnBrowserThread();
+
+ // These methods merely forwards to Thread::Run() but are useful to identify
+ // which BrowserThread this represents in stack traces.
+ void UIThreadRun(base::RunLoop* run_loop);
+ void IOThreadRun(base::RunLoop* run_loop);
+
+ // This method encapsulates cleanup that needs to happen on the IO thread.
+ void IOThreadCleanUp();
+
+ const BrowserThread::ID identifier_;
+
+ // BrowserThreads are not allowed to do file I/O nor wait on synchronization
+ // primivives except when explicitly allowed in tests.
+ bool is_blocking_allowed_for_testing_ = false;
+
+ // The BrowserThread registration for this |identifier_|, initialized in
+ // RegisterAsBrowserThread().
+ std::unique_ptr<BrowserThreadImpl> browser_thread_;
#if defined (OS_WIN)
std::unique_ptr<base::win::ScopedCOMInitializer> com_initializer_;
@@ -58,6 +88,8 @@ class CONTENT_EXPORT BrowserProcessSubThread : public BrowserThreadImpl {
// Each specialized thread has its own notification service.
std::unique_ptr<NotificationService> notification_service_;
+ THREAD_CHECKER(browser_thread_checker_);
+
DISALLOW_COPY_AND_ASSIGN(BrowserProcessSubThread);
};
diff --git a/chromium/content/browser/browser_side_navigation_browsertest.cc b/chromium/content/browser/browser_side_navigation_browsertest.cc
index 4d1a1a9b85a..a2a4b80f88e 100644
--- a/chromium/content/browser/browser_side_navigation_browsertest.cc
+++ b/chromium/content/browser/browser_side_navigation_browsertest.cc
@@ -15,6 +15,7 @@
#include "content/browser/loader/resource_dispatcher_host_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/common/frame_messages.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/resource_dispatcher_host_delegate.h"
@@ -490,13 +491,13 @@ IN_PROC_BROWSER_TEST_F(BrowserSideNavigationBrowserDisableWebSecurityTest,
false /* is_form_submission */, GURL() /* searchable_form_url */,
std::string() /* searchable_form_encoding */,
url::Origin::Create(data_url), GURL() /* client_side_redirect_url */,
- nullptr /* devtools_initiator_info */);
+ base::nullopt /* devtools_initiator_info */);
// Receiving the invalid IPC message should lead to renderer process
// termination.
RenderProcessHostKillWaiter process_kill_waiter(rfh->GetProcess());
rfh->frame_host_binding_for_testing().impl()->BeginNavigation(
- common_params, std::move(begin_params));
+ common_params, std::move(begin_params), nullptr);
EXPECT_EQ(bad_message::RFH_BASE_URL_FOR_DATA_URL_SPECIFIED,
process_kill_waiter.Wait());
@@ -595,13 +596,6 @@ IN_PROC_BROWSER_TEST_F(BrowserSideNavigationBaseBrowserTest,
// properly.
IN_PROC_BROWSER_TEST_F(BrowserSideNavigationBaseBrowserTest,
CancelRequestAfterReadyToCommit) {
-// TODO(https://crbug.com/820959). Test temporarily disabled on Windows with
-// NavigationMojoResponse.
-#if defined(OS_WIN)
- if (IsNavigationMojoResponseEnabled())
- return;
-#endif
-
// This test cancels the request using the ResourceDispatchHost. With the
// NetworkService, it is not used so the request is not canceled.
// TODO(arthursonzogni): Find a way to cancel a request from the browser
diff --git a/chromium/content/browser/browser_thread_impl.cc b/chromium/content/browser/browser_thread_impl.cc
index 566b0f7dafe..4443c7bbc4c 100644
--- a/chromium/content/browser/browser_thread_impl.cc
+++ b/chromium/content/browser/browser_thread_impl.cc
@@ -9,41 +9,21 @@
#include "base/atomicops.h"
#include "base/bind.h"
+#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/macros.h"
-#include "base/message_loop/message_loop.h"
-#include "base/run_loop.h"
-#include "base/synchronization/waitable_event.h"
+#include "base/sequence_checker.h"
#include "base/threading/platform_thread.h"
+#include "base/time/time.h"
#include "build/build_config.h"
-#include "content/public/browser/browser_thread_delegate.h"
#include "content/public/browser/content_browser_client.h"
-#if defined(OS_ANDROID)
-#include "base/android/jni_android.h"
-#endif
-
namespace content {
namespace {
-// Friendly names for the well-known threads.
-static const char* const g_browser_thread_names[BrowserThread::ID_COUNT] = {
- "", // UI (name assembled in browser_main.cc).
- "Chrome_ProcessLauncherThread", // PROCESS_LAUNCHER
- "Chrome_IOThread", // IO
-};
-
-static const char* GetThreadName(BrowserThread::ID thread) {
- if (BrowserThread::UI < thread && thread < BrowserThread::ID_COUNT)
- return g_browser_thread_names[thread];
- if (thread == BrowserThread::UI)
- return "Chrome_UIThread";
- return "Unknown Thread";
-}
-
// An implementation of SingleThreadTaskRunner to be used in conjunction
// with BrowserThread.
// TODO(gab): Consider replacing this with |g_globals->task_runners| -- only
@@ -101,389 +81,149 @@ base::LazyInstance<BrowserThreadTaskRunners>::Leaky g_task_runners =
enum BrowserThreadState {
// BrowserThread::ID isn't associated with anything yet.
UNINITIALIZED = 0,
- // BrowserThread::ID is associated with a BrowserThreadImpl instance but the
- // underlying thread hasn't started yet.
- INITIALIZED,
// BrowserThread::ID is associated to a TaskRunner and is accepting tasks.
RUNNING,
- // BrowserThread::ID no longer accepts tasks.
+ // BrowserThread::ID no longer accepts tasks (it's still associated to a
+ // TaskRunner but that TaskRunner doesn't have to accept tasks).
SHUTDOWN
};
-using BrowserThreadDelegateAtomicPtr = base::subtle::AtomicWord;
-
struct BrowserThreadGlobals {
- // This lock protects |task_runners| and |states|. Do not read or modify those
- // arrays without holding this lock. Do not block while holding this lock.
- base::Lock lock;
-
- // This array is filled either as the underlying threads start and invoke
- // Init() or in RedirectThreadIDToTaskRunner() for threads that are being
- // redirected. It is not emptied during shutdown in order to support
- // RunsTasksInCurrentSequence() until the very end.
- scoped_refptr<base::SingleThreadTaskRunner>
- task_runners[BrowserThread::ID_COUNT];
-
- // Holds the state of each BrowserThread::ID.
- BrowserThreadState states[BrowserThread::ID_COUNT] = {};
+ BrowserThreadGlobals() {
+ // A few unit tests which do not use a TestBrowserThreadBundle still invoke
+ // code that reaches into CurrentlyOn()/IsThreadInitialized(). This can
+ // result in instantiating BrowserThreadGlobals off the main thread.
+ // |main_thread_checker_| being bound incorrectly would then result in a
+ // flake in the next test that instantiates a TestBrowserThreadBundle in the
+ // same process. Detaching here postpones binding |main_thread_checker_| to
+ // the first invocation of BrowserThreadImpl::BrowserThreadImpl() and works
+ // around this issue.
+ DETACH_FROM_THREAD(main_thread_checker_);
+ }
- // Only atomic operations are used on this pointer. The delegate isn't owned
- // by BrowserThreadGlobals, rather by whoever calls
- // BrowserThread::SetIOThreadDelegate.
- BrowserThreadDelegateAtomicPtr io_thread_delegate = 0;
+ // BrowserThreadGlobals must be initialized on main thread before it's used by
+ // any other threads.
+ THREAD_CHECKER(main_thread_checker_);
- // This locks protects |is_io_thread_initialized|. Do not read or modify this
- // variable without holding this lock.
- base::Lock io_thread_lock;
+ // |task_runners[id]| is safe to access on |main_thread_checker_| as
+ // well as on any thread once it's read-only after initialization
+ // (i.e. while |states[id] >= RUNNING|).
+ scoped_refptr<base::SingleThreadTaskRunner>
+ task_runners[BrowserThread::ID_COUNT];
- // A flag indicates whether the BrowserThreadDelegate of the BrowserThread::IO
- // thread has been initialized.
- bool is_io_thread_initialized = false;
+ // Tracks the runtime state of BrowserThreadImpls. Atomic because a few
+ // methods below read this value outside |main_thread_checker_| to
+ // confirm it's >= RUNNING and doing so requires an atomic read as it could be
+ // in the middle of transitioning to SHUTDOWN (which the check is fine with
+ // but reading a non-atomic value as it's written to by another thread can
+ // result in undefined behaviour on some platforms).
+ // Only NoBarrier atomic operations should be used on |states| as it shouldn't
+ // be used to establish happens-after relationships but rather checking the
+ // runtime state of various threads (once again: it's only atomic to support
+ // reading while transitioning from RUNNING=>SHUTDOWN).
+ base::subtle::Atomic32 states[BrowserThread::ID_COUNT] = {};
};
base::LazyInstance<BrowserThreadGlobals>::Leaky
g_globals = LAZY_INSTANCE_INITIALIZER;
-void InitIOThreadDelegateOnIOThread() {
- BrowserThreadDelegateAtomicPtr delegate =
- base::subtle::NoBarrier_Load(&g_globals.Get().io_thread_delegate);
- if (delegate)
- reinterpret_cast<BrowserThreadDelegate*>(delegate)->Init();
-}
-
-bool IsIOThreadInitialized() {
- BrowserThreadGlobals& globals = g_globals.Get();
- base::AutoLock lock(globals.io_thread_lock);
- return globals.is_io_thread_initialized;
-}
-
-void SetIsIOThreadInitialized(bool is_io_thread_initialized) {
- BrowserThreadGlobals& globals = g_globals.Get();
- base::AutoLock lock(globals.io_thread_lock);
- globals.is_io_thread_initialized = is_io_thread_initialized;
-}
-
-} // namespace
-
-BrowserThreadImpl::BrowserThreadImpl(ID identifier)
- : Thread(GetThreadName(identifier)), identifier_(identifier) {
- Initialize();
-}
-
-BrowserThreadImpl::BrowserThreadImpl(ID identifier,
- base::MessageLoop* message_loop)
- : Thread(GetThreadName(identifier)), identifier_(identifier) {
- SetMessageLoop(message_loop);
- Initialize();
+bool PostTaskHelper(BrowserThread::ID identifier,
+ const base::Location& from_here,
+ base::OnceClosure task,
+ base::TimeDelta delay,
+ bool nestable) {
+ DCHECK_GE(identifier, 0);
+ DCHECK_LT(identifier, BrowserThread::ID_COUNT);
- // If constructed with an explicit message loop, this is a fake
- // BrowserThread which runs on the current thread.
BrowserThreadGlobals& globals = g_globals.Get();
- base::AutoLock lock(globals.lock);
-
- DCHECK(!globals.task_runners[identifier_]);
- globals.task_runners[identifier_] = task_runner();
- DCHECK_EQ(globals.states[identifier_], BrowserThreadState::INITIALIZED);
- globals.states[identifier_] = BrowserThreadState::RUNNING;
-}
-
-void BrowserThreadImpl::Init() {
-#if DCHECK_IS_ON()
- {
- BrowserThreadGlobals& globals = g_globals.Get();
- base::AutoLock lock(globals.lock);
- // |globals| should already have been initialized for |identifier_| in
- // BrowserThreadImpl::StartWithOptions(). If this isn't the case it's likely
- // because this BrowserThreadImpl's owner incorrectly used Thread::Start.*()
- // instead of BrowserThreadImpl::Start.*().
- DCHECK_EQ(globals.states[identifier_], BrowserThreadState::RUNNING);
- DCHECK(globals.task_runners[identifier_]);
- DCHECK(globals.task_runners[identifier_]->RunsTasksInCurrentSequence());
- }
-#endif // DCHECK_IS_ON()
-
- if (identifier_ == BrowserThread::PROCESS_LAUNCHER) {
- // Nesting and task observers are not allowed on redirected threads.
- base::RunLoop::DisallowNestingOnCurrentThread();
- message_loop()->DisallowTaskObservers();
- }
-}
-
-// We disable optimizations for this block of functions so the compiler doesn't
-// merge them all together.
-MSVC_DISABLE_OPTIMIZE()
-MSVC_PUSH_DISABLE_WARNING(4748)
-
-NOINLINE void BrowserThreadImpl::UIThreadRun(base::RunLoop* run_loop) {
- volatile int line_number = __LINE__;
- Thread::Run(run_loop);
- CHECK_GT(line_number, 0);
-}
-
-NOINLINE void BrowserThreadImpl::ProcessLauncherThreadRun(
- base::RunLoop* run_loop) {
- volatile int line_number = __LINE__;
- Thread::Run(run_loop);
- CHECK_GT(line_number, 0);
-}
-
-NOINLINE void BrowserThreadImpl::IOThreadRun(base::RunLoop* run_loop) {
- volatile int line_number = __LINE__;
- Thread::Run(run_loop);
- CHECK_GT(line_number, 0);
-}
-
-MSVC_POP_WARNING()
-MSVC_ENABLE_OPTIMIZE();
-
-void BrowserThreadImpl::Run(base::RunLoop* run_loop) {
-#if defined(OS_ANDROID)
- // Not to reset thread name to "Thread-???" by VM, attach VM with thread name.
- // Though it may create unnecessary VM thread objects, keeping thread name
- // gives more benefit in debugging in the platform.
- if (!thread_name().empty()) {
- base::android::AttachCurrentThreadWithName(thread_name());
- }
-#endif
-
- BrowserThread::ID thread_id = ID_COUNT;
- CHECK(GetCurrentThreadIdentifier(&thread_id));
- CHECK_EQ(identifier_, thread_id);
-
- switch (identifier_) {
- case BrowserThread::UI:
- return UIThreadRun(run_loop);
- case BrowserThread::PROCESS_LAUNCHER:
- return ProcessLauncherThreadRun(run_loop);
- case BrowserThread::IO:
- return IOThreadRun(run_loop);
- case BrowserThread::ID_COUNT:
- CHECK(false); // This shouldn't actually be reached!
- break;
- }
-
- // |identifier_| must be set to a valid enum value in the constructor, so it
- // should be impossible to reach here.
- CHECK(false);
-}
-
-void BrowserThreadImpl::CleanUp() {
- BrowserThreadGlobals& globals = g_globals.Get();
+ // Tasks should always be posted while the BrowserThread is in a RUNNING or
+ // SHUTDOWN state (will return false if SHUTDOWN).
+ //
+ // Posting tasks before BrowserThreads are initialized is incorrect as it
+ // would silently no-op. If you need to support posting early, gate it on
+ // BrowserThread::IsThreadInitialized(). If you hit this check in unittests,
+ // you most likely posted a task outside the scope of a
+ // TestBrowserThreadBundle (which also completely resets the state after
+ // shutdown in ~TestBrowserThreadBundle(), ref. ResetGlobalsForTesting(),
+ // making sure TestBrowserThreadBundle is the first member of your test
+ // fixture and thus outlives everything is usually the right solution).
+ DCHECK_GE(base::subtle::NoBarrier_Load(&globals.states[identifier]),
+ BrowserThreadState::RUNNING);
+ DCHECK(globals.task_runners[identifier]);
- if (identifier_ == BrowserThread::IO && IsIOThreadInitialized()) {
- BrowserThreadDelegateAtomicPtr delegate =
- base::subtle::NoBarrier_Load(&globals.io_thread_delegate);
- if (delegate)
- reinterpret_cast<BrowserThreadDelegate*>(delegate)->CleanUp();
- SetIsIOThreadInitialized(false);
+ if (nestable) {
+ return globals.task_runners[identifier]->PostDelayedTask(
+ from_here, std::move(task), delay);
+ } else {
+ return globals.task_runners[identifier]->PostNonNestableDelayedTask(
+ from_here, std::move(task), delay);
}
-
- // Change the state to SHUTDOWN so that PostTaskHelper stops accepting tasks
- // for this thread. Do not clear globals.task_runners[identifier_] so that
- // BrowserThread::CurrentlyOn() works from the MessageLoop's
- // DestructionObservers.
- base::AutoLock lock(globals.lock);
- DCHECK_EQ(globals.states[identifier_], BrowserThreadState::RUNNING);
- globals.states[identifier_] = BrowserThreadState::SHUTDOWN;
}
-void BrowserThreadImpl::Initialize() {
- BrowserThreadGlobals& globals = g_globals.Get();
+} // namespace
- base::AutoLock lock(globals.lock);
+BrowserThreadImpl::BrowserThreadImpl(
+ ID identifier,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner)
+ : identifier_(identifier) {
DCHECK_GE(identifier_, 0);
DCHECK_LT(identifier_, ID_COUNT);
- DCHECK_EQ(globals.states[identifier_], BrowserThreadState::UNINITIALIZED);
- globals.states[identifier_] = BrowserThreadState::INITIALIZED;
-}
+ DCHECK(task_runner);
-// static
-void BrowserThreadImpl::ResetGlobalsForTesting(BrowserThread::ID identifier) {
BrowserThreadGlobals& globals = g_globals.Get();
- base::AutoLock lock(globals.lock);
- DCHECK_EQ(globals.states[identifier], BrowserThreadState::SHUTDOWN);
- globals.states[identifier] = BrowserThreadState::UNINITIALIZED;
- globals.task_runners[identifier] = nullptr;
- if (identifier == BrowserThread::IO)
- SetIOThreadDelegate(nullptr);
-}
+ DCHECK_CALLED_ON_VALID_THREAD(globals.main_thread_checker_);
-void BrowserThreadImpl::InitIOThreadDelegate() {
- DCHECK(!IsIOThreadInitialized());
+ DCHECK_EQ(base::subtle::NoBarrier_Load(&globals.states[identifier_]),
+ BrowserThreadState::UNINITIALIZED);
+ base::subtle::NoBarrier_Store(&globals.states[identifier_],
+ BrowserThreadState::RUNNING);
- SetIsIOThreadInitialized(true);
- BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
- base::BindOnce(&InitIOThreadDelegateOnIOThread));
+ DCHECK(!globals.task_runners[identifier_]);
+ globals.task_runners[identifier_] = std::move(task_runner);
}
BrowserThreadImpl::~BrowserThreadImpl() {
- // All Thread subclasses must call Stop() in the destructor. This is
- // doubly important here as various bits of code check they are on
- // the right BrowserThread.
- Stop();
-
- BrowserThreadGlobals& globals = g_globals.Get();
- base::AutoLock lock(globals.lock);
- // This thread should have gone through Cleanup() as part of Stop() and be in
- // the SHUTDOWN state already (unless it uses an externally provided
- // MessageLoop instead of a real underlying thread and thus doesn't go through
- // Cleanup()).
- if (using_external_message_loop()) {
- DCHECK_EQ(globals.states[identifier_], BrowserThreadState::RUNNING);
- globals.states[identifier_] = BrowserThreadState::SHUTDOWN;
- } else {
- DCHECK_EQ(globals.states[identifier_], BrowserThreadState::SHUTDOWN);
- }
-#if DCHECK_IS_ON()
- // Double check that the threads are ordered correctly in the enumeration.
- for (int i = identifier_ + 1; i < ID_COUNT; ++i) {
- DCHECK(globals.states[i] == BrowserThreadState::SHUTDOWN ||
- globals.states[i] == BrowserThreadState::UNINITIALIZED)
- << "Threads must be listed in the reverse order that they die";
- }
-#endif
-}
-
-bool BrowserThreadImpl::Start() {
- return StartWithOptions(base::Thread::Options());
-}
-
-bool BrowserThreadImpl::StartWithOptions(const Options& options) {
BrowserThreadGlobals& globals = g_globals.Get();
+ DCHECK_CALLED_ON_VALID_THREAD(globals.main_thread_checker_);
- // Holding the lock is necessary when kicking off the thread to ensure
- // |states| and |task_runners| are updated before it gets to query them.
- base::AutoLock lock(globals.lock);
+ DCHECK_EQ(base::subtle::NoBarrier_Load(&globals.states[identifier_]),
+ BrowserThreadState::RUNNING);
+ base::subtle::NoBarrier_Store(&globals.states[identifier_],
+ BrowserThreadState::SHUTDOWN);
- bool result = Thread::StartWithOptions(options);
-
- // Although the thread is starting asynchronously, the MessageLoop is already
- // ready to accept tasks and as such this BrowserThreadImpl is considered as
- // "running".
- DCHECK(!globals.task_runners[identifier_]);
- globals.task_runners[identifier_] = task_runner();
+ // The mapping is kept alive after shutdown to avoid requiring a lock only for
+ // shutdown (the SingleThreadTaskRunner itself may stop accepting tasks at any
+ // point -- usually soon before/after destroying the BrowserThreadImpl).
DCHECK(globals.task_runners[identifier_]);
-
- DCHECK_EQ(globals.states[identifier_], BrowserThreadState::INITIALIZED);
- globals.states[identifier_] = BrowserThreadState::RUNNING;
-
- return result;
-}
-
-bool BrowserThreadImpl::StartAndWaitForTesting() {
- if (!Start())
- return false;
- WaitUntilThreadStarted();
- return true;
-}
-
-// static
-void BrowserThreadImpl::RedirectThreadIDToTaskRunner(
- BrowserThread::ID identifier,
- scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
- DCHECK(task_runner);
-
- BrowserThreadGlobals& globals = g_globals.Get();
- base::AutoLock lock(globals.lock);
-
- DCHECK(!globals.task_runners[identifier]);
- DCHECK_EQ(globals.states[identifier], BrowserThreadState::UNINITIALIZED);
-
- globals.task_runners[identifier] = std::move(task_runner);
- globals.states[identifier] = BrowserThreadState::RUNNING;
}
// static
-void BrowserThreadImpl::StopRedirectionOfThreadID(
- BrowserThread::ID identifier) {
+void BrowserThreadImpl::ResetGlobalsForTesting(BrowserThread::ID identifier) {
BrowserThreadGlobals& globals = g_globals.Get();
- base::AutoLock auto_lock(globals.lock);
-
- DCHECK(globals.task_runners[identifier]);
+ DCHECK_CALLED_ON_VALID_THREAD(globals.main_thread_checker_);
- // Change the state to SHUTDOWN to stop accepting new tasks. Note: this is
- // different from non-redirected threads which continue accepting tasks while
- // being joined and only quit when idle. However, any tasks for which this
- // difference matters was already racy as any thread posting a task after the
- // Signal task below can't be synchronized with the joining thread. Therefore,
- // that task could already come in before or after the join had completed in
- // the non-redirection world. Entering SHUTDOWN early merely skews this race
- // towards making it less likely such a task is accepted by the joined thread
- // which is fine.
- DCHECK_EQ(globals.states[identifier], BrowserThreadState::RUNNING);
- globals.states[identifier] = BrowserThreadState::SHUTDOWN;
-
- // Wait for all pending tasks to complete.
- base::WaitableEvent flushed(base::WaitableEvent::ResetPolicy::MANUAL,
- base::WaitableEvent::InitialState::NOT_SIGNALED);
- globals.task_runners[identifier]->PostTask(
- FROM_HERE,
- base::BindOnce(&base::WaitableEvent::Signal, base::Unretained(&flushed)));
- {
- base::AutoUnlock auto_unlock(globals.lock);
- flushed.Wait();
- }
+ DCHECK_EQ(base::subtle::NoBarrier_Load(&globals.states[identifier]),
+ BrowserThreadState::SHUTDOWN);
+ base::subtle::NoBarrier_Store(&globals.states[identifier],
+ BrowserThreadState::UNINITIALIZED);
- // Only reset the task runner after running pending tasks so that
- // BrowserThread::CurrentlyOn() works in their scope.
globals.task_runners[identifier] = nullptr;
-
- // Note: it's still possible for tasks to be posted to that task runner after
- // this point (e.g. through a previously obtained ThreadTaskRunnerHandle or by
- // one of the last tasks re-posting to its ThreadTaskRunnerHandle) but the
- // BrowserThread API itself won't accept tasks. Such tasks are ultimately
- // guaranteed to run before TaskScheduler::Shutdown() returns but may break
- // the assumption in PostTaskHelper that BrowserThread::ID A > B will always
- // succeed to post to B. This is pretty much the only observable difference
- // between a redirected thread and a real one and is one we're willing to live
- // with for this experiment. TODO(gab): fix this before enabling the
- // experiment by default on trunk, http://crbug.com/653916.
}
// static
-bool BrowserThreadImpl::PostTaskHelper(BrowserThread::ID identifier,
- const base::Location& from_here,
- base::OnceClosure task,
- base::TimeDelta delay,
- bool nestable) {
- DCHECK_GE(identifier, 0);
- DCHECK_LT(identifier, ID_COUNT);
- // Optimization: to avoid unnecessary locks, we listed the ID enumeration in
- // order of lifetime. So no need to lock if we know that the target thread
- // outlives current thread as that implies the current thread only ever sees
- // the target thread in its RUNNING state.
- // Note: since the array is so small, ok to loop instead of creating a map,
- // which would require a lock because std::map isn't thread safe, defeating
- // the whole purpose of this optimization.
- BrowserThread::ID current_thread = ID_COUNT;
- bool target_thread_outlives_current =
- GetCurrentThreadIdentifier(&current_thread) &&
- current_thread >= identifier;
+const char* BrowserThreadImpl::GetThreadName(BrowserThread::ID thread) {
+ static const char* const kBrowserThreadNames[BrowserThread::ID_COUNT] = {
+ "", // UI (name assembled in browser_main_loop.cc).
+ "Chrome_IOThread", // IO
+ };
- BrowserThreadGlobals& globals = g_globals.Get();
- if (!target_thread_outlives_current)
- globals.lock.Acquire();
-
- const bool accepting_tasks =
- globals.states[identifier] == BrowserThreadState::RUNNING;
- if (accepting_tasks) {
- base::SingleThreadTaskRunner* task_runner =
- globals.task_runners[identifier].get();
- DCHECK(task_runner);
- if (nestable) {
- task_runner->PostDelayedTask(from_here, std::move(task), delay);
- } else {
- task_runner->PostNonNestableDelayedTask(from_here, std::move(task),
- delay);
- }
- }
-
- if (!target_thread_outlives_current)
- globals.lock.Release();
-
- return accepting_tasks;
+ if (BrowserThread::UI < thread && thread < BrowserThread::ID_COUNT)
+ return kBrowserThreadNames[thread];
+ if (thread == BrowserThread::UI)
+ return "Chrome_UIThread";
+ return "Unknown Thread";
}
// static
@@ -497,28 +237,25 @@ void BrowserThread::PostAfterStartupTask(
// static
bool BrowserThread::IsThreadInitialized(ID identifier) {
- if (!g_globals.IsCreated())
- return false;
-
- BrowserThreadGlobals& globals = g_globals.Get();
- base::AutoLock lock(globals.lock);
DCHECK_GE(identifier, 0);
DCHECK_LT(identifier, ID_COUNT);
- bool running =
- globals.states[identifier] == BrowserThreadState::INITIALIZED ||
- globals.states[identifier] == BrowserThreadState::RUNNING;
- if (identifier != BrowserThread::IO)
- return running;
- return running && IsIOThreadInitialized();
+ BrowserThreadGlobals& globals = g_globals.Get();
+ return base::subtle::NoBarrier_Load(&globals.states[identifier]) ==
+ BrowserThreadState::RUNNING;
}
// static
bool BrowserThread::CurrentlyOn(ID identifier) {
- BrowserThreadGlobals& globals = g_globals.Get();
- base::AutoLock lock(globals.lock);
DCHECK_GE(identifier, 0);
DCHECK_LT(identifier, ID_COUNT);
+
+ BrowserThreadGlobals& globals = g_globals.Get();
+
+ // Thread-safe since |globals.task_runners| is read-only after being
+ // initialized from main thread (which happens before //content and embedders
+ // are kicked off and enabled to call the BrowserThread API from other
+ // threads).
return globals.task_runners[identifier] &&
globals.task_runners[identifier]->RunsTasksInCurrentSequence();
}
@@ -530,31 +267,18 @@ std::string BrowserThread::GetDCheckCurrentlyOnErrorMessage(ID expected) {
actual_name = "Unknown Thread";
std::string result = "Must be called on ";
- result += GetThreadName(expected);
+ result += BrowserThreadImpl::GetThreadName(expected);
result += "; actually called on ";
result += actual_name;
result += ".";
return result;
}
-// static
-bool BrowserThread::IsMessageLoopValid(ID identifier) {
- if (!g_globals.IsCreated())
- return false;
-
- BrowserThreadGlobals& globals = g_globals.Get();
- base::AutoLock lock(globals.lock);
- DCHECK_GE(identifier, 0);
- DCHECK_LT(identifier, ID_COUNT);
- return globals.states[identifier] == BrowserThreadState::RUNNING;
-}
-
-// static
bool BrowserThread::PostTask(ID identifier,
const base::Location& from_here,
base::OnceClosure task) {
- return BrowserThreadImpl::PostTaskHelper(
- identifier, from_here, std::move(task), base::TimeDelta(), true);
+ return PostTaskHelper(identifier, from_here, std::move(task),
+ base::TimeDelta(), true);
}
// static
@@ -562,16 +286,15 @@ bool BrowserThread::PostDelayedTask(ID identifier,
const base::Location& from_here,
base::OnceClosure task,
base::TimeDelta delay) {
- return BrowserThreadImpl::PostTaskHelper(identifier, from_here,
- std::move(task), delay, true);
+ return PostTaskHelper(identifier, from_here, std::move(task), delay, true);
}
// static
bool BrowserThread::PostNonNestableTask(ID identifier,
const base::Location& from_here,
base::OnceClosure task) {
- return BrowserThreadImpl::PostTaskHelper(
- identifier, from_here, std::move(task), base::TimeDelta(), false);
+ return PostTaskHelper(identifier, from_here, std::move(task),
+ base::TimeDelta(), false);
}
// static
@@ -579,8 +302,7 @@ bool BrowserThread::PostNonNestableDelayedTask(ID identifier,
const base::Location& from_here,
base::OnceClosure task,
base::TimeDelta delay) {
- return BrowserThreadImpl::PostTaskHelper(identifier, from_here,
- std::move(task), delay, false);
+ return PostTaskHelper(identifier, from_here, std::move(task), delay, false);
}
// static
@@ -594,14 +316,12 @@ bool BrowserThread::PostTaskAndReply(ID identifier,
// static
bool BrowserThread::GetCurrentThreadIdentifier(ID* identifier) {
- if (!g_globals.IsCreated())
- return false;
-
BrowserThreadGlobals& globals = g_globals.Get();
- // Profiler to track potential contention on |globals.lock|. This only does
- // real work on canary and local dev builds, so the cost of having this here
- // should be minimal.
- base::AutoLock lock(globals.lock);
+
+ // Thread-safe since |globals.task_runners| is read-only after being
+ // initialized from main thread (which happens before //content and embedders
+ // are kicked off and enabled to call the BrowserThread API from other
+ // threads).
for (int i = 0; i < ID_COUNT; ++i) {
if (globals.task_runners[i] &&
globals.task_runners[i]->RunsTasksInCurrentSequence()) {
@@ -619,16 +339,4 @@ BrowserThread::GetTaskRunnerForThread(ID identifier) {
return g_task_runners.Get().proxies[identifier];
}
-// static
-void BrowserThread::SetIOThreadDelegate(BrowserThreadDelegate* delegate) {
- BrowserThreadGlobals& globals = g_globals.Get();
- BrowserThreadDelegateAtomicPtr old_delegate =
- base::subtle::NoBarrier_AtomicExchange(
- &globals.io_thread_delegate,
- reinterpret_cast<BrowserThreadDelegateAtomicPtr>(delegate));
-
- // This catches registration when previously registered.
- DCHECK(!delegate || !old_delegate);
-}
-
} // namespace content
diff --git a/chromium/content/browser/browser_thread_impl.h b/chromium/content/browser/browser_thread_impl.h
index d8a3a8bc9ee..cd0759c3f58 100644
--- a/chromium/content/browser/browser_thread_impl.h
+++ b/chromium/content/browser/browser_thread_impl.h
@@ -5,58 +5,31 @@
#ifndef CONTENT_BROWSER_BROWSER_THREAD_IMPL_H_
#define CONTENT_BROWSER_BROWSER_THREAD_IMPL_H_
-#include "base/callback.h"
-#include "base/memory/ref_counted.h"
+#include "base/memory/scoped_refptr.h"
#include "base/single_thread_task_runner.h"
-#include "base/threading/thread.h"
-#include "base/time/time.h"
#include "content/common/content_export.h"
#include "content/public/browser/browser_thread.h"
-namespace base {
-class MessageLoop;
-class RunLoop;
-}
-
-namespace base {
-class Location;
-}
-
namespace content {
+class BrowserMainLoop;
+class BrowserProcessSubThread;
+class TestBrowserThread;
+
+// BrowserThreadImpl is a scoped object which maps a SingleThreadTaskRunner to a
+// BrowserThread::ID. On ~BrowserThreadImpl() that ID enters a SHUTDOWN state
+// (in which BrowserThread::IsThreadInitialized() returns false) but the mapping
+// isn't undone to avoid shutdown races (the task runner is free to stop
+// accepting tasks by then however).
+//
// Very few users should use this directly. To mock BrowserThreads, tests should
// use TestBrowserThreadBundle instead.
-class CONTENT_EXPORT BrowserThreadImpl : public BrowserThread,
- public base::Thread {
+class CONTENT_EXPORT BrowserThreadImpl : public BrowserThread {
public:
- // Construct a BrowserThreadImpl with the supplied identifier. It is an error
- // to construct a BrowserThreadImpl that already exists.
- explicit BrowserThreadImpl(BrowserThread::ID identifier);
-
- // Special constructor for the main (UI) thread and unittests. If a
- // |message_loop| is provied, we use a dummy thread here since the main
- // thread already exists.
- BrowserThreadImpl(BrowserThread::ID identifier,
- base::MessageLoop* message_loop);
- ~BrowserThreadImpl() override;
-
- bool Start();
- bool StartWithOptions(const Options& options);
- bool StartAndWaitForTesting();
- // Called only by the BrowserThread::IO thread to initialize its
- // BrowserThreadDelegate after the thread is created. See
- // https://crbug.com/729596.
- void InitIOThreadDelegate();
-
- // Redirects tasks posted to |identifier| to |task_runner|.
- static void RedirectThreadIDToTaskRunner(
- BrowserThread::ID identifier,
- scoped_refptr<base::SingleThreadTaskRunner> task_runner);
+ ~BrowserThreadImpl();
- // Makes this |identifier| no longer accept tasks and synchronously flushes
- // any tasks previously posted to it.
- // Can only be called after a matching RedirectThreadIDToTaskRunner call.
- static void StopRedirectionOfThreadID(BrowserThread::ID identifier);
+ // Returns the thread name for |identifier|.
+ static const char* GetThreadName(BrowserThread::ID identifier);
// Resets globals for |identifier|. Used in tests to clear global state that
// would otherwise leak to the next test. Globals are not otherwise fully
@@ -66,35 +39,21 @@ class CONTENT_EXPORT BrowserThreadImpl : public BrowserThread,
// |identifier|.
static void ResetGlobalsForTesting(BrowserThread::ID identifier);
- protected:
- void Init() override;
- void Run(base::RunLoop* run_loop) override;
- void CleanUp() override;
-
private:
- // We implement all the functionality of the public BrowserThread
- // functions, but state is stored in the BrowserThreadImpl to keep
- // the API cleaner. Therefore make BrowserThread a friend class.
- friend class BrowserThread;
-
- // The following are unique function names that makes it possible to tell
- // the thread id from the callstack alone in crash dumps.
- void UIThreadRun(base::RunLoop* run_loop);
- void ProcessLauncherThreadRun(base::RunLoop* run_loop);
- void IOThreadRun(base::RunLoop* run_loop);
-
- static bool PostTaskHelper(BrowserThread::ID identifier,
- const base::Location& from_here,
- base::OnceClosure task,
- base::TimeDelta delay,
- bool nestable);
-
- // Common initialization code for the constructors.
- void Initialize();
-
- // For testing.
- friend class ContentTestSuiteBaseListener;
- friend class TestBrowserThreadBundle;
+ // Restrict instantiation to BrowserProcessSubThread as it performs important
+ // initialization that shouldn't be bypassed (except by BrowserMainLoop for
+ // the main thread).
+ friend class BrowserProcessSubThread;
+ friend class BrowserMainLoop;
+ // TestBrowserThread is also allowed to construct this when instantiating fake
+ // threads.
+ friend class TestBrowserThread;
+
+ // Binds |identifier| to |task_runner| for the browser_thread.h API. This
+ // needs to happen on the main thread before //content and embedders are
+ // kicked off and enabled to invoke the BrowserThread API from other threads.
+ BrowserThreadImpl(BrowserThread::ID identifier,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner);
// The identifier of this thread. Only one thread can exist with a given
// identifier at a given time.
diff --git a/chromium/content/browser/browser_thread_unittest.cc b/chromium/content/browser/browser_thread_unittest.cc
index 6fc8e70f0c6..703fe3448d4 100644
--- a/chromium/content/browser/browser_thread_unittest.cc
+++ b/chromium/content/browser/browser_thread_unittest.cc
@@ -12,6 +12,7 @@
#include "base/sequenced_task_runner_helpers.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
+#include "content/browser/browser_process_sub_thread.h"
#include "content/browser/browser_thread_impl.h"
#include "content/public/test/test_browser_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -31,17 +32,22 @@ class BrowserThreadTest : public testing::Test {
protected:
void SetUp() override {
- ui_thread_.reset(new BrowserThreadImpl(BrowserThread::UI));
- io_thread_.reset(new BrowserThreadImpl(BrowserThread::IO));
+ ui_thread_ = std::make_unique<BrowserProcessSubThread>(BrowserThread::UI);
ui_thread_->Start();
- io_thread_->Start();
+
+ io_thread_ = std::make_unique<BrowserProcessSubThread>(BrowserThread::IO);
+ base::Thread::Options io_options;
+ io_options.message_loop_type = base::MessageLoop::TYPE_IO;
+ io_thread_->StartWithOptions(io_options);
+
+ ui_thread_->RegisterAsBrowserThread();
+ io_thread_->RegisterAsBrowserThread();
}
void TearDown() override {
- StopUIThread();
- io_thread_->Stop();
- ui_thread_ = nullptr;
- io_thread_ = nullptr;
+ io_thread_.reset();
+ ui_thread_.reset();
+
BrowserThreadImpl::ResetGlobalsForTesting(BrowserThread::UI);
BrowserThreadImpl::ResetGlobalsForTesting(BrowserThread::IO);
}
@@ -73,8 +79,8 @@ class BrowserThreadTest : public testing::Test {
};
private:
- std::unique_ptr<BrowserThreadImpl> ui_thread_;
- std::unique_ptr<BrowserThreadImpl> io_thread_;
+ std::unique_ptr<BrowserProcessSubThread> ui_thread_;
+ std::unique_ptr<BrowserProcessSubThread> io_thread_;
// It's kind of ugly to make this mutable - solely so we can post the Quit
// Task from Release(). This should be fixed.
mutable base::MessageLoop loop_;
diff --git a/chromium/content/browser/browser_url_handler_impl_unittest.cc b/chromium/content/browser/browser_url_handler_impl_unittest.cc
index daceffcee47..769fc670e9a 100644
--- a/chromium/content/browser/browser_url_handler_impl_unittest.cc
+++ b/chromium/content/browser/browser_url_handler_impl_unittest.cc
@@ -4,6 +4,7 @@
#include "content/browser/browser_url_handler_impl.h"
#include "content/public/test/test_browser_context.h"
+#include "content/public/test/test_browser_thread_bundle.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
@@ -31,6 +32,7 @@ static bool BarRewriter(GURL* url, BrowserContext* browser_context) {
}
TEST_F(BrowserURLHandlerImplTest, BasicRewriteAndReverse) {
+ TestBrowserThreadBundle thread_bundle;
TestBrowserContext browser_context;
BrowserURLHandlerImpl handler;
@@ -60,6 +62,7 @@ TEST_F(BrowserURLHandlerImplTest, BasicRewriteAndReverse) {
}
TEST_F(BrowserURLHandlerImplTest, NullHandlerReverse) {
+ TestBrowserThreadBundle thread_bundle;
TestBrowserContext browser_context;
BrowserURLHandlerImpl handler;
@@ -82,6 +85,7 @@ TEST_F(BrowserURLHandlerImplTest, NullHandlerReverse) {
// Verify that the reverse handler for view-source does not duplicate query
// parameters.
TEST_F(BrowserURLHandlerImplTest, ViewSourceReverse) {
+ TestBrowserThreadBundle thread_bundle;
TestBrowserContext browser_context;
BrowserURLHandlerImpl handler;
diff --git a/chromium/content/browser/browsing_data/browsing_data_filter_builder_impl.cc b/chromium/content/browser/browsing_data/browsing_data_filter_builder_impl.cc
index 9058a371bc2..174800f2958 100644
--- a/chromium/content/browser/browsing_data/browsing_data_filter_builder_impl.cc
+++ b/chromium/content/browser/browsing_data/browsing_data_filter_builder_impl.cc
@@ -9,7 +9,6 @@
#include "base/bind.h"
#include "base/callback.h"
-#include "base/memory/ptr_util.h"
#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
#include "net/cookies/canonical_cookie.h"
#include "url/origin.h"
@@ -160,6 +159,20 @@ BrowsingDataFilterBuilderImpl::BuildGeneralFilter() const {
return base::BindRepeating(&MatchesURL, origins_, domains_, mode_);
}
+network::mojom::ClearCacheUrlFilterPtr
+BrowsingDataFilterBuilderImpl::BuildClearCacheUrlFilter() const {
+ network::mojom::ClearCacheUrlFilterPtr filter =
+ network::mojom::ClearCacheUrlFilter::New();
+ filter->type = (mode_ == Mode::WHITELIST)
+ ? network::mojom::ClearCacheUrlFilter::Type::DELETE_MATCHES
+ : network::mojom::ClearCacheUrlFilter::Type::KEEP_MATCHES;
+ filter->origins.insert(filter->origins.begin(), origins_.begin(),
+ origins_.end());
+ filter->domains.insert(filter->domains.begin(), domains_.begin(),
+ domains_.end());
+ return filter;
+}
+
base::RepeatingCallback<bool(const net::CanonicalCookie& cookie)>
BrowsingDataFilterBuilderImpl::BuildCookieFilter() const {
DCHECK(origins_.empty()) <<
diff --git a/chromium/content/browser/browsing_data/browsing_data_filter_builder_impl.h b/chromium/content/browser/browsing_data/browsing_data_filter_builder_impl.h
index fd7e8e61df0..ed3fe8fcd1c 100644
--- a/chromium/content/browser/browsing_data/browsing_data_filter_builder_impl.h
+++ b/chromium/content/browser/browsing_data/browsing_data_filter_builder_impl.h
@@ -24,6 +24,8 @@ class CONTENT_EXPORT BrowsingDataFilterBuilderImpl
bool IsEmptyBlacklist() const override;
base::RepeatingCallback<bool(const GURL&)>
BuildGeneralFilter() const override;
+ network::mojom::ClearCacheUrlFilterPtr BuildClearCacheUrlFilter()
+ const override;
base::RepeatingCallback<bool(const net::CanonicalCookie& pattern)>
BuildCookieFilter() const override;
base::RepeatingCallback<bool(const std::string& server_id)>
diff --git a/chromium/content/browser/browsing_data/browsing_data_remover_impl.cc b/chromium/content/browser/browsing_data/browsing_data_remover_impl.cc
index 1c64aa56a44..bb4e8bd443c 100644
--- a/chromium/content/browser/browsing_data/browsing_data_remover_impl.cc
+++ b/chromium/content/browser/browsing_data/browsing_data_remover_impl.cc
@@ -14,7 +14,6 @@
#include "base/callback.h"
#include "base/callback_helpers.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/metrics/user_metrics.h"
#include "content/browser/browsing_data/storage_partition_http_cache_data_remover.h"
@@ -26,6 +25,7 @@
#include "content/public/browser/download_manager.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/storage_partition.h"
+#include "mojo/public/cpp/bindings/callback_helpers.h"
#include "net/base/net_errors.h"
#include "net/cookies/cookie_store.h"
#include "net/http/http_network_session.h"
@@ -35,7 +35,8 @@
#include "net/ssl/channel_id_store.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
+#include "services/network/public/cpp/features.h"
#include "storage/browser/quota/special_storage_policy.h"
#include "url/origin.h"
@@ -45,6 +46,19 @@ namespace content {
namespace {
+base::OnceClosure RunsOrPostOnCurrentTaskRunner(base::OnceClosure closure) {
+ return base::BindOnce(
+ [](base::OnceClosure closure,
+ scoped_refptr<base::TaskRunner> task_runner) {
+ if (base::ThreadTaskRunnerHandle::Get() == task_runner) {
+ std::move(closure).Run();
+ return;
+ }
+ task_runner->PostTask(FROM_HERE, std::move(closure));
+ },
+ std::move(closure), base::ThreadTaskRunnerHandle::Get());
+}
+
// Returns whether |origin| matches |origin_type_mask| given the special
// storage |policy|; and if |predicate| is not null, then also whether
// it matches |predicate|. If |origin_type_mask| contains embedder-specific
@@ -186,9 +200,9 @@ bool BrowsingDataRemoverImpl::DoesOriginMatchMask(
if (embedder_delegate_)
embedder_matcher = embedder_delegate_->GetOriginTypeMatcher();
- return DoesOriginMatchMaskAndURLs(origin_type_mask,
- base::Callback<bool(const GURL&)>(),
- embedder_matcher, origin, policy);
+ return DoesOriginMatchMaskAndURLs(
+ origin_type_mask, base::Callback<bool(const GURL&)>(),
+ std::move(embedder_matcher), origin, policy);
}
void BrowsingDataRemoverImpl::Remove(const base::Time& delete_begin,
@@ -436,8 +450,8 @@ void BrowsingDataRemoverImpl::RemoveImpl(
storage_partition->ClearData(
storage_partition_remove_mask, quota_storage_remove_mask,
base::BindRepeating(&DoesOriginMatchMaskAndURLs, origin_type_mask_,
- filter, embedder_matcher),
- cookie_matcher, delete_begin_, delete_end_,
+ filter, std::move(embedder_matcher)),
+ std::move(cookie_matcher), delete_begin_, delete_end_,
CreatePendingTaskCompletionClosure());
}
@@ -446,18 +460,32 @@ void BrowsingDataRemoverImpl::RemoveImpl(
if (remove_mask & DATA_TYPE_CACHE) {
base::RecordAction(UserMetricsAction("ClearBrowsingData_Cache"));
+ network::mojom::NetworkContext* network_context =
+ storage_partition->GetNetworkContext();
+
// TODO(msramek): Clear the cache of all renderers.
+ if (base::FeatureList::IsEnabled(network::features::kNetworkService)) {
+ // The clearing of the HTTP cache happens in the network service process
+ // when enabled.
+ network_context->ClearHttpCache(
+ delete_begin, delete_end, filter_builder.BuildClearCacheUrlFilter(),
+ CreatePendingTaskCompletionClosureForMojo());
+ }
+
+ // In the network service case, the call below will only clear the media
+ // cache.
+ // TODO(crbug.com/813882): implement retry on network service.
storage_partition->ClearHttpAndMediaCaches(
delete_begin, delete_end,
filter_builder.IsEmptyBlacklist() ? base::Callback<bool(const GURL&)>()
- : filter,
- CreatePendingTaskCompletionClosure());
+ : std::move(filter),
+ CreatePendingTaskCompletionClosureForMojo());
// When clearing cache, wipe accumulated network related data
// (TransportSecurityState and HttpServerPropertiesManager data).
- storage_partition->GetNetworkContext()->ClearNetworkingHistorySince(
- delete_begin, CreatePendingTaskCompletionClosure());
+ network_context->ClearNetworkingHistorySince(
+ delete_begin, CreatePendingTaskCompletionClosureForMojo());
// Tell the shader disk cache to clear.
base::RecordAction(UserMetricsAction("ClearBrowsingData_ShaderCache"));
@@ -605,6 +633,14 @@ BrowsingDataRemoverImpl::CreatePendingTaskCompletionClosure() {
return base::BindOnce(&BrowsingDataRemoverImpl::OnTaskComplete, GetWeakPtr());
}
+base::OnceClosure
+BrowsingDataRemoverImpl::CreatePendingTaskCompletionClosureForMojo() {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ return RunsOrPostOnCurrentTaskRunner(mojo::WrapCallbackWithDropHandler(
+ CreatePendingTaskCompletionClosure(),
+ base::BindOnce(&BrowsingDataRemoverImpl::OnTaskComplete, GetWeakPtr())));
+}
+
base::WeakPtr<BrowsingDataRemoverImpl> BrowsingDataRemoverImpl::GetWeakPtr() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
base::WeakPtr<BrowsingDataRemoverImpl> weak_ptr =
diff --git a/chromium/content/browser/browsing_data/browsing_data_remover_impl.h b/chromium/content/browser/browsing_data/browsing_data_remover_impl.h
index f71bdc8a9f6..1b02d6fc28e 100644
--- a/chromium/content/browser/browsing_data/browsing_data_remover_impl.h
+++ b/chromium/content/browser/browsing_data/browsing_data_remover_impl.h
@@ -152,6 +152,11 @@ class CONTENT_EXPORT BrowsingDataRemoverImpl
// created by this method have been invoked.
base::OnceClosure CreatePendingTaskCompletionClosure();
+ // Same as CreatePendingTaskCompletionClosure() but guarantees that
+ // OnTaskComplete() is called if the task is dropped. That can typically
+ // happen when the connection is closed while an interface call is made.
+ base::OnceClosure CreatePendingTaskCompletionClosureForMojo();
+
// Like GetWeakPtr(), but returns a weak pointer to BrowsingDataRemoverImpl
// for internal purposes.
base::WeakPtr<BrowsingDataRemoverImpl> GetWeakPtr();
diff --git a/chromium/content/browser/browsing_data/browsing_data_remover_impl_unittest.cc b/chromium/content/browser/browsing_data/browsing_data_remover_impl_unittest.cc
index 1d04bb43c7d..cf4705ac2e8 100644
--- a/chromium/content/browser/browsing_data/browsing_data_remover_impl_unittest.cc
+++ b/chromium/content/browser/browsing_data/browsing_data_remover_impl_unittest.cc
@@ -51,7 +51,7 @@
#include "net/ssl/ssl_client_cert_type.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#include "storage/browser/test/mock_special_storage_policy.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
diff --git a/chromium/content/browser/browsing_data/clear_site_data_throttle_browsertest.cc b/chromium/content/browser/browsing_data/clear_site_data_throttle_browsertest.cc
index 96ac0459659..bd37230b055 100644
--- a/chromium/content/browser/browsing_data/clear_site_data_throttle_browsertest.cc
+++ b/chromium/content/browser/browsing_data/clear_site_data_throttle_browsertest.cc
@@ -19,6 +19,7 @@
#include "content/browser/service_worker/service_worker_context_core_observer.h"
#include "content/browser/service_worker/service_worker_context_wrapper.h"
#include "content/public/browser/browser_context.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/browsing_data_remover.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/storage_partition.h"
@@ -207,7 +208,7 @@ class ClearSiteDataThrottleBrowserTest : public ContentBrowserTest {
base::Closure callback) {
cookie_store_ =
request_context_getter->GetURLRequestContext()->cookie_store();
- callback.Run();
+ std::move(callback).Run();
}
// Adds a cookie for the |url|. Used in the cookie integration tests.
diff --git a/chromium/content/browser/browsing_data/clear_site_data_throttle_unittest.cc b/chromium/content/browser/browsing_data/clear_site_data_throttle_unittest.cc
index 77b4e919b8a..5af116cf2f6 100644
--- a/chromium/content/browser/browsing_data/clear_site_data_throttle_unittest.cc
+++ b/chromium/content/browser/browsing_data/clear_site_data_throttle_unittest.cc
@@ -6,7 +6,6 @@
#include <memory>
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
diff --git a/chromium/content/browser/browsing_data/conditional_cache_deletion_helper_browsertest.cc b/chromium/content/browser/browsing_data/conditional_cache_deletion_helper_browsertest.cc
index 4f6d6122fcb..3d4ecc58671 100644
--- a/chromium/content/browser/browsing_data/conditional_cache_deletion_helper_browsertest.cc
+++ b/chromium/content/browser/browsing_data/conditional_cache_deletion_helper_browsertest.cc
@@ -8,7 +8,6 @@
#include <string>
#include <vector>
-#include "base/memory/ptr_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/synchronization/waitable_event.h"
#include "base/test/test_timeouts.h"
@@ -167,7 +166,7 @@ IN_PROC_BROWSER_TEST_F(ConditionalCacheDeletionHelperBrowserTest,
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&ConditionalCacheDeletionHelperBrowserTest::DeleteEntries,
- base::Unretained(this), base::ConstRef(condition)));
+ base::Unretained(this), std::move(condition)));
WaitForTasksOnIOThread();
// Expect that only "icon2.png" and "icon3.png" were deleted.
diff --git a/chromium/content/browser/browsing_instance.cc b/chromium/content/browser/browsing_instance.cc
index c7ed2164d38..3758184e743 100644
--- a/chromium/content/browser/browsing_instance.cc
+++ b/chromium/content/browser/browsing_instance.cc
@@ -7,9 +7,9 @@
#include "base/command_line.h"
#include "base/logging.h"
#include "content/browser/site_instance_impl.h"
-#include "content/browser/site_isolation_policy.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/content_browser_client.h"
+#include "content/public/browser/site_isolation_policy.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/url_constants.h"
diff --git a/chromium/content/browser/cache_storage/cache_storage.cc b/chromium/content/browser/cache_storage/cache_storage.cc
index ce6a21b2336..241d017ab4c 100644
--- a/chromium/content/browser/cache_storage/cache_storage.cc
+++ b/chromium/content/browser/cache_storage/cache_storage.cc
@@ -40,7 +40,7 @@
#include "net/url_request/url_request_context_getter.h"
#include "storage/browser/blob/blob_storage_context.h"
#include "storage/browser/quota/quota_manager_proxy.h"
-#include "third_party/WebKit/public/mojom/quota/quota_types.mojom.h"
+#include "third_party/blink/public/mojom/quota/quota_types.mojom.h"
using base::LazyInstance;
using blink::mojom::CacheStorageError;
@@ -316,7 +316,7 @@ class CacheStorage::SimpleCacheLoader : public CacheStorage::CacheLoader {
CacheCallback callback,
const std::string& cache_dir) {
if (cache_dir.empty()) {
- std::move(callback).Run(std::unique_ptr<CacheStorageCache>());
+ std::move(callback).Run(nullptr);
return;
}
@@ -635,7 +635,7 @@ void CacheStorage::HasCache(const std::string& cache_name,
}
void CacheStorage::DoomCache(const std::string& cache_name,
- BoolAndErrorCallback callback) {
+ ErrorCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!initialized_)
@@ -828,8 +828,7 @@ void CacheStorage::LazyInitDidLoadIndex(
DCHECK(cache_map_.empty());
for (const auto& cache_metadata : index->ordered_cache_metadata()) {
- cache_map_.insert(std::make_pair(cache_metadata.name,
- std::unique_ptr<CacheStorageCache>()));
+ cache_map_.insert(std::make_pair(cache_metadata.name, nullptr));
}
DCHECK(!cache_index_);
@@ -908,12 +907,12 @@ void CacheStorage::HasCacheImpl(const std::string& cache_name,
}
void CacheStorage::DoomCacheImpl(const std::string& cache_name,
- BoolAndErrorCallback callback) {
+ ErrorCallback callback) {
CacheStorageCacheHandle cache_handle = GetLoadedCache(cache_name);
if (!cache_handle.value()) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
- FROM_HERE, base::BindOnce(std::move(callback), false,
- CacheStorageError::kErrorNotFound));
+ FROM_HERE,
+ base::BindOnce(std::move(callback), CacheStorageError::kErrorNotFound));
return;
}
@@ -928,7 +927,7 @@ void CacheStorage::DoomCacheImpl(const std::string& cache_name,
void CacheStorage::DeleteCacheDidWriteIndex(
CacheStorageCacheHandle cache_handle,
- BoolAndErrorCallback callback,
+ ErrorCallback callback,
bool success) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
@@ -936,7 +935,7 @@ void CacheStorage::DeleteCacheDidWriteIndex(
// Undo any changes if the index couldn't be written to disk.
cache_index_->RestoreDoomedCache();
cache_handle.value()->SetObserver(this);
- std::move(callback).Run(false, CacheStorageError::kErrorStorage);
+ std::move(callback).Run(CacheStorageError::kErrorStorage);
return;
}
@@ -954,7 +953,7 @@ void CacheStorage::DeleteCacheDidWriteIndex(
if (cache_storage_manager_)
cache_storage_manager_->NotifyCacheListChanged(origin_);
- std::move(callback).Run(true, CacheStorageError::kSuccess);
+ std::move(callback).Run(CacheStorageError::kSuccess);
}
// Call this once the last handle to a doomed cache is gone. It's okay if this
@@ -990,8 +989,7 @@ void CacheStorage::MatchCacheImpl(
if (!cache_handle.value()) {
std::move(callback).Run(CacheStorageError::kErrorCacheNameNotFound,
- std::unique_ptr<ServiceWorkerResponse>(),
- std::unique_ptr<storage::BlobDataHandle>());
+ nullptr);
return;
}
@@ -1009,9 +1007,8 @@ void CacheStorage::MatchCacheDidMatch(
CacheStorageCacheHandle cache_handle,
CacheStorageCache::ResponseCallback callback,
CacheStorageError error,
- std::unique_ptr<ServiceWorkerResponse> response,
- std::unique_ptr<storage::BlobDataHandle> handle) {
- std::move(callback).Run(error, std::move(response), std::move(handle));
+ std::unique_ptr<ServiceWorkerResponse> response) {
+ std::move(callback).Run(error, std::move(response));
}
void CacheStorage::MatchAllCachesImpl(
@@ -1047,12 +1044,10 @@ void CacheStorage::MatchAllCachesDidMatch(
CacheMatchResponse* out_match_response,
const base::RepeatingClosure& barrier_closure,
CacheStorageError error,
- std::unique_ptr<ServiceWorkerResponse> service_worker_response,
- std::unique_ptr<storage::BlobDataHandle> handle) {
+ std::unique_ptr<ServiceWorkerResponse> service_worker_response) {
out_match_response->error = error;
out_match_response->service_worker_response =
std::move(service_worker_response);
- out_match_response->blob_data_handle = std::move(handle);
barrier_closure.Run();
}
@@ -1063,13 +1058,10 @@ void CacheStorage::MatchAllCachesDidMatchAll(
if (match_response.error == CacheStorageError::kErrorNotFound)
continue;
std::move(callback).Run(match_response.error,
- std::move(match_response.service_worker_response),
- std::move(match_response.blob_data_handle));
+ std::move(match_response.service_worker_response));
return;
}
- std::move(callback).Run(CacheStorageError::kErrorNotFound,
- std::unique_ptr<ServiceWorkerResponse>(),
- std::unique_ptr<storage::BlobDataHandle>());
+ std::move(callback).Run(CacheStorageError::kErrorNotFound, nullptr);
}
void CacheStorage::AddCacheHandleRef(CacheStorageCache* cache) {
diff --git a/chromium/content/browser/cache_storage/cache_storage.h b/chromium/content/browser/cache_storage/cache_storage.h
index 7a03796ecfe..acfbcd77ec0 100644
--- a/chromium/content/browser/cache_storage/cache_storage.h
+++ b/chromium/content/browser/cache_storage/cache_storage.h
@@ -20,7 +20,7 @@
#include "base/memory/weak_ptr.h"
#include "content/browser/cache_storage/cache_storage_cache.h"
#include "content/browser/cache_storage/cache_storage_cache_observer.h"
-#include "third_party/WebKit/public/platform/modules/cache_storage/cache_storage.mojom.h"
+#include "third_party/blink/public/platform/modules/cache_storage/cache_storage.mojom.h"
#include "url/origin.h"
namespace base {
@@ -58,6 +58,8 @@ class CONTENT_EXPORT CacheStorage : public CacheStorageCacheObserver {
using BoolAndErrorCallback =
base::OnceCallback<void(bool, blink::mojom::CacheStorageError)>;
+ using ErrorCallback =
+ base::OnceCallback<void(blink::mojom::CacheStorageError)>;
using CacheAndErrorCallback =
base::OnceCallback<void(CacheStorageCacheHandle,
blink::mojom::CacheStorageError)>;
@@ -95,7 +97,7 @@ class CONTENT_EXPORT CacheStorage : public CacheStorageCacheObserver {
// existing CacheStorageCacheHandle(s) to the cache will remain valid but
// future CacheStorage operations won't be able to access the cache. The cache
// isn't actually erased from disk until the last handle is dropped.
- void DoomCache(const std::string& cache_name, BoolAndErrorCallback callback);
+ void DoomCache(const std::string& cache_name, ErrorCallback callback);
// Calls the callback with the cache index.
void EnumerateCaches(IndexCallback callback);
@@ -184,10 +186,9 @@ class CONTENT_EXPORT CacheStorage : public CacheStorageCacheObserver {
BoolAndErrorCallback callback);
// The DeleteCache callbacks are below.
- void DoomCacheImpl(const std::string& cache_name,
- BoolAndErrorCallback callback);
+ void DoomCacheImpl(const std::string& cache_name, ErrorCallback callback);
void DeleteCacheDidWriteIndex(CacheStorageCacheHandle cache_handle,
- BoolAndErrorCallback callback,
+ ErrorCallback callback,
bool success);
void DeleteCacheFinalize(CacheStorageCache* doomed_cache);
void DeleteCacheDidGetSize(CacheStorageCache* doomed_cache,
@@ -205,8 +206,7 @@ class CONTENT_EXPORT CacheStorage : public CacheStorageCacheObserver {
void MatchCacheDidMatch(CacheStorageCacheHandle cache_handle,
CacheStorageCache::ResponseCallback callback,
blink::mojom::CacheStorageError error,
- std::unique_ptr<ServiceWorkerResponse> response,
- std::unique_ptr<storage::BlobDataHandle> handle);
+ std::unique_ptr<ServiceWorkerResponse> response);
// The MatchAllCaches callbacks are below.
void MatchAllCachesImpl(std::unique_ptr<ServiceWorkerFetchRequest> request,
@@ -217,8 +217,7 @@ class CONTENT_EXPORT CacheStorage : public CacheStorageCacheObserver {
CacheMatchResponse* out_match_response,
const base::RepeatingClosure& barrier_closure,
blink::mojom::CacheStorageError error,
- std::unique_ptr<ServiceWorkerResponse> service_worker_response,
- std::unique_ptr<storage::BlobDataHandle> handle);
+ std::unique_ptr<ServiceWorkerResponse> service_worker_response);
void MatchAllCachesDidMatchAll(
std::unique_ptr<std::vector<CacheMatchResponse>> match_responses,
CacheStorageCache::ResponseCallback callback);
diff --git a/chromium/content/browser/cache_storage/cache_storage_blob_to_disk_cache.cc b/chromium/content/browser/cache_storage/cache_storage_blob_to_disk_cache.cc
index ef4abff98fd..ad208e12186 100644
--- a/chromium/content/browser/cache_storage/cache_storage_blob_to_disk_cache.cc
+++ b/chromium/content/browser/cache_storage/cache_storage_blob_to_disk_cache.cc
@@ -19,7 +19,9 @@ namespace content {
const int CacheStorageBlobToDiskCache::kBufferSize = 1024 * 512;
CacheStorageBlobToDiskCache::CacheStorageBlobToDiskCache()
- : handle_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL),
+ : handle_watcher_(FROM_HERE,
+ mojo::SimpleWatcher::ArmingPolicy::MANUAL,
+ base::SequencedTaskRunnerHandle::Get()),
client_binding_(this),
weak_ptr_factory_(this) {}
@@ -145,7 +147,7 @@ void CacheStorageBlobToDiskCache::OnDataPipeReadable(MojoResult unused) {
buffer.get(), bytes_to_read, cache_write_callback,
true /* truncate */);
if (rv != net::ERR_IO_PENDING)
- cache_write_callback.Run(rv);
+ std::move(cache_write_callback).Run(rv);
}
} // namespace content
diff --git a/chromium/content/browser/cache_storage/cache_storage_blob_to_disk_cache.h b/chromium/content/browser/cache_storage/cache_storage_blob_to_disk_cache.h
index 381bf03a2ac..dbaf77d581a 100644
--- a/chromium/content/browser/cache_storage/cache_storage_blob_to_disk_cache.h
+++ b/chromium/content/browser/cache_storage/cache_storage_blob_to_disk_cache.h
@@ -15,7 +15,7 @@
#include "mojo/public/cpp/bindings/binding.h"
#include "net/disk_cache/disk_cache.h"
#include "services/network/public/cpp/net_adapters.h"
-#include "third_party/WebKit/public/mojom/blob/blob.mojom.h"
+#include "third_party/blink/public/mojom/blob/blob.mojom.h"
namespace content {
diff --git a/chromium/content/browser/cache_storage/cache_storage_blob_to_disk_cache_unittest.cc b/chromium/content/browser/cache_storage/cache_storage_blob_to_disk_cache_unittest.cc
index 109ee44bc27..71a6e088876 100644
--- a/chromium/content/browser/cache_storage/cache_storage_blob_to_disk_cache_unittest.cc
+++ b/chromium/content/browser/cache_storage/cache_storage_blob_to_disk_cache_unittest.cc
@@ -9,7 +9,6 @@
#include "base/files/file_path.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/test/null_task_runner.h"
diff --git a/chromium/content/browser/cache_storage/cache_storage_cache.cc b/chromium/content/browser/cache_storage/cache_storage_cache.cc
index 321039f3dc2..90956c40767 100644
--- a/chromium/content/browser/cache_storage/cache_storage_cache.cc
+++ b/chromium/content/browser/cache_storage/cache_storage_cache.cc
@@ -47,7 +47,7 @@
#include "storage/browser/quota/quota_manager_proxy.h"
#include "storage/common/blob_storage/blob_handle.h"
#include "storage/common/storage_histograms.h"
-#include "third_party/WebKit/public/mojom/quota/quota_types.mojom.h"
+#include "third_party/blink/public/mojom/quota/quota_types.mojom.h"
using blink::mojom::CacheStorageError;
@@ -199,7 +199,7 @@ void ReadMetadata(disk_cache::Entry* entry, MetadataCallback callback) {
buffer->size(), read_header_callback);
if (read_rv != net::ERR_IO_PENDING)
- read_header_callback.Run(read_rv);
+ std::move(read_header_callback).Run(read_rv);
}
void ReadMetadataDidReadMetadata(disk_cache::Entry* entry,
@@ -207,7 +207,7 @@ void ReadMetadataDidReadMetadata(disk_cache::Entry* entry,
scoped_refptr<net::IOBufferWithSize> buffer,
int rv) {
if (rv != buffer->size()) {
- std::move(callback).Run(std::unique_ptr<proto::CacheMetadata>());
+ std::move(callback).Run(nullptr);
return;
}
@@ -217,7 +217,7 @@ void ReadMetadataDidReadMetadata(disk_cache::Entry* entry,
std::unique_ptr<proto::CacheMetadata> metadata(new proto::CacheMetadata());
if (!metadata->ParseFromArray(buffer->data(), buffer->size())) {
- std::move(callback).Run(std::unique_ptr<proto::CacheMetadata>());
+ std::move(callback).Run(nullptr);
return;
}
@@ -373,7 +373,6 @@ struct CacheStorageCache::QueryCacheResult {
std::unique_ptr<ServiceWorkerFetchRequest> request;
std::unique_ptr<ServiceWorkerResponse> response;
- std::unique_ptr<storage::BlobDataHandle> blob_handle;
disk_cache::ScopedEntryPtr entry;
base::Time entry_time;
};
@@ -466,9 +465,7 @@ void CacheStorageCache::Match(
const CacheStorageCacheQueryParams& match_params,
ResponseCallback callback) {
if (backend_state_ == BACKEND_CLOSED) {
- std::move(callback).Run(CacheStorageError::kErrorStorage,
- std::unique_ptr<ServiceWorkerResponse>(),
- std::unique_ptr<storage::BlobDataHandle>());
+ std::move(callback).Run(CacheStorageError::kErrorStorage, nullptr);
return;
}
@@ -484,8 +481,7 @@ void CacheStorageCache::MatchAll(
ResponsesCallback callback) {
if (backend_state_ == BACKEND_CLOSED) {
std::move(callback).Run(CacheStorageError::kErrorStorage,
- std::vector<ServiceWorkerResponse>(),
- std::unique_ptr<BlobDataHandles>());
+ std::vector<ServiceWorkerResponse>());
return;
}
@@ -541,8 +537,7 @@ void CacheStorageCache::BatchOperation(
}
if (!safe_space_required.IsValid() || !safe_side_data_size.IsValid()) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
- FROM_HERE, base::BindOnce(std::move(bad_message_callback),
- bad_message::CSDH_UNEXPECTED_OPERATION));
+ FROM_HERE, std::move(bad_message_callback));
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(std::move(callback), CacheStorageError::kErrorStorage));
@@ -588,8 +583,7 @@ void CacheStorageCache::BatchDidGetUsageAndQuota(
if (!safe_space_required.IsValid() ||
!safe_space_required_with_side_data.IsValid()) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
- FROM_HERE, base::BindOnce(std::move(bad_message_callback),
- bad_message::CSDH_UNEXPECTED_OPERATION));
+ FROM_HERE, std::move(bad_message_callback));
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(std::move(callback), CacheStorageError::kErrorStorage));
@@ -615,7 +609,7 @@ void CacheStorageCache::BatchDidGetUsageAndQuota(
weak_ptr_factory_.GetWeakPtr(), callback_copy));
auto completion_callback = base::BindRepeating(
&CacheStorageCache::BatchDidOneOperation, weak_ptr_factory_.GetWeakPtr(),
- barrier_closure, callback_copy);
+ std::move(barrier_closure), std::move(callback_copy));
// Operations may synchronously invoke |callback| which could release the
// last reference to this instance. Hold a handle for the duration of this
@@ -673,8 +667,7 @@ void CacheStorageCache::Keys(std::unique_ptr<ServiceWorkerFetchRequest> request,
const CacheStorageCacheQueryParams& options,
RequestsCallback callback) {
if (backend_state_ == BACKEND_CLOSED) {
- std::move(callback).Run(CacheStorageError::kErrorStorage,
- std::unique_ptr<Requests>());
+ std::move(callback).Run(CacheStorageError::kErrorStorage, nullptr);
return;
}
@@ -778,8 +771,7 @@ void CacheStorageCache::QueryCache(
QUERY_CACHE_ENTRIES | QUERY_CACHE_RESPONSES_WITH_BODIES,
query_types & (QUERY_CACHE_ENTRIES | QUERY_CACHE_RESPONSES_WITH_BODIES));
if (backend_state_ == BACKEND_CLOSED) {
- std::move(callback).Run(CacheStorageError::kErrorStorage,
- std::unique_ptr<QueryCacheResults>());
+ std::move(callback).Run(CacheStorageError::kErrorStorage, nullptr);
return;
}
@@ -806,7 +798,7 @@ void CacheStorageCache::QueryCache(
int rv = backend_->OpenEntry(request_ptr->url.spec(), entry_ptr,
open_entry_callback);
if (rv != net::ERR_IO_PENDING)
- open_entry_callback.Run(rv);
+ std::move(open_entry_callback).Run(rv);
return;
}
@@ -853,7 +845,7 @@ void CacheStorageCache::QueryCacheOpenNextEntry(
int rv = iterator.OpenNextEntry(enumerated_entry, open_entry_callback);
if (rv != net::ERR_IO_PENDING)
- open_entry_callback.Run(rv);
+ std::move(open_entry_callback).Run(rv);
}
void CacheStorageCache::QueryCacheFilterEntry(
@@ -946,8 +938,7 @@ void CacheStorageCache::QueryCacheDidReadMetadata(
match->request->EstimatedStructSize();
if (query_cache_context->estimated_out_bytes > max_query_size_bytes_) {
std::move(query_cache_context->callback)
- .Run(CacheStorageError::kErrorQueryTooLarge,
- std::unique_ptr<QueryCacheResults>());
+ .Run(CacheStorageError::kErrorQueryTooLarge, nullptr);
return;
}
} else {
@@ -959,8 +950,7 @@ void CacheStorageCache::QueryCacheDidReadMetadata(
match->response->EstimatedStructSize();
if (query_cache_context->estimated_out_bytes > max_query_size_bytes_) {
std::move(query_cache_context->callback)
- .Run(CacheStorageError::kErrorQueryTooLarge,
- std::unique_ptr<QueryCacheResults>());
+ .Run(CacheStorageError::kErrorQueryTooLarge, nullptr);
return;
}
if (entry->GetDataSize(INDEX_RESPONSE_BODY) == 0) {
@@ -970,13 +960,11 @@ void CacheStorageCache::QueryCacheDidReadMetadata(
if (!blob_storage_context_) {
std::move(query_cache_context->callback)
- .Run(CacheStorageError::kErrorStorage,
- std::unique_ptr<QueryCacheResults>());
+ .Run(CacheStorageError::kErrorStorage, nullptr);
return;
}
- match->blob_handle =
- PopulateResponseBody(std::move(entry), match->response.get());
+ PopulateResponseBody(std::move(entry), match->response.get());
} else if (!(query_cache_context->query_types &
QUERY_CACHE_RESPONSES_NO_BODIES)) {
match->response.reset();
@@ -1020,27 +1008,21 @@ void CacheStorageCache::MatchImpl(
void CacheStorageCache::MatchDidMatchAll(
ResponseCallback callback,
CacheStorageError match_all_error,
- std::vector<ServiceWorkerResponse> match_all_responses,
- std::unique_ptr<BlobDataHandles> match_all_handles) {
+ std::vector<ServiceWorkerResponse> match_all_responses) {
if (match_all_error != CacheStorageError::kSuccess) {
- std::move(callback).Run(match_all_error,
- std::unique_ptr<ServiceWorkerResponse>(),
- std::unique_ptr<storage::BlobDataHandle>());
+ std::move(callback).Run(match_all_error, nullptr);
return;
}
if (match_all_responses.empty()) {
- std::move(callback).Run(CacheStorageError::kErrorNotFound,
- std::unique_ptr<ServiceWorkerResponse>(),
- std::unique_ptr<storage::BlobDataHandle>());
+ std::move(callback).Run(CacheStorageError::kErrorNotFound, nullptr);
return;
}
std::unique_ptr<ServiceWorkerResponse> response =
std::make_unique<ServiceWorkerResponse>(match_all_responses[0]);
- std::move(callback).Run(CacheStorageError::kSuccess, std::move(response),
- std::move(match_all_handles->at(0)));
+ std::move(callback).Run(CacheStorageError::kSuccess, std::move(response));
}
void CacheStorageCache::MatchAllImpl(
@@ -1050,8 +1032,7 @@ void CacheStorageCache::MatchAllImpl(
DCHECK_NE(BACKEND_UNINITIALIZED, backend_state_);
if (backend_state_ != BACKEND_OPEN) {
std::move(callback).Run(CacheStorageError::kErrorStorage,
- std::vector<ServiceWorkerResponse>(),
- std::unique_ptr<BlobDataHandles>());
+ std::vector<ServiceWorkerResponse>());
return;
}
@@ -1067,24 +1048,19 @@ void CacheStorageCache::MatchAllDidQueryCache(
CacheStorageError error,
std::unique_ptr<QueryCacheResults> query_cache_results) {
if (error != CacheStorageError::kSuccess) {
- std::move(callback).Run(error, std::vector<ServiceWorkerResponse>(),
- std::unique_ptr<BlobDataHandles>());
+ std::move(callback).Run(error, std::vector<ServiceWorkerResponse>());
return;
}
std::vector<ServiceWorkerResponse> out_responses;
- std::unique_ptr<BlobDataHandles> out_handles =
- std::make_unique<BlobDataHandles>();
out_responses.reserve(query_cache_results->size());
- out_handles->reserve(query_cache_results->size());
for (auto& result : *query_cache_results) {
out_responses.push_back(*result.response);
- out_handles->push_back(std::move(result.blob_handle));
}
- std::move(callback).Run(CacheStorageError::kSuccess, std::move(out_responses),
- std::move(out_handles));
+ std::move(callback).Run(CacheStorageError::kSuccess,
+ std::move(out_responses));
}
void CacheStorageCache::WriteSideDataDidGetQuota(
@@ -1132,7 +1108,7 @@ void CacheStorageCache::WriteSideDataImpl(ErrorCallback callback,
int rv = backend_->OpenEntry(url.spec(), entry_ptr, open_entry_callback);
if (rv != net::ERR_IO_PENDING)
- open_entry_callback.Run(rv);
+ std::move(open_entry_callback).Run(rv);
}
void CacheStorageCache::WriteSideDataDidOpenEntry(
@@ -1189,7 +1165,7 @@ void CacheStorageCache::WriteSideDataDidReadMetaData(
write_side_data_callback, true /* truncate */);
if (rv != net::ERR_IO_PENDING)
- write_side_data_callback.Run(rv);
+ std::move(write_side_data_callback).Run(rv);
}
void CacheStorageCache::WriteSideDataDidWrite(
@@ -1242,10 +1218,8 @@ void CacheStorageCache::Put(const CacheStorageBatchOperation& operation,
if (response->side_data_blob)
side_data_blob = response->side_data_blob->Clone();
- UMA_HISTOGRAM_ENUMERATION(
- "ServiceWorkerCache.Cache.AllWritesResponseType",
- operation.response.response_type,
- static_cast<int>(network::mojom::FetchResponseType::kLast) + 1);
+ UMA_HISTOGRAM_ENUMERATION("ServiceWorkerCache.Cache.AllWritesResponseType",
+ operation.response.response_type);
auto put_context = std::make_unique<PutContext>(
std::move(request), std::move(response), std::move(blob),
@@ -1311,7 +1285,7 @@ void CacheStorageCache::PutDidDeleteEntry(
create_entry_callback);
if (rv != net::ERR_IO_PENDING)
- create_entry_callback.Run(rv);
+ std::move(create_entry_callback).Run(rv);
}
void CacheStorageCache::PutDidCreateEntry(
@@ -1383,7 +1357,7 @@ void CacheStorageCache::PutDidCreateEntry(
true /* truncate */);
if (rv != net::ERR_IO_PENDING)
- write_headers_callback.Run(rv);
+ std::move(write_headers_callback).Run(rv);
}
void CacheStorageCache::PutDidWriteHeaders(
@@ -1474,7 +1448,7 @@ void CacheStorageCache::CalculateCacheSizePadding(
int rv = backend_->CalculateSizeOfAllEntries(got_size_callback);
if (rv != net::ERR_IO_PENDING)
- got_size_callback.Run(rv);
+ std::move(got_size_callback).Run(rv);
}
void CacheStorageCache::CalculateCacheSizePaddingGotSize(
@@ -1623,8 +1597,7 @@ void CacheStorageCache::KeysImpl(
RequestsCallback callback) {
DCHECK_NE(BACKEND_UNINITIALIZED, backend_state_);
if (backend_state_ != BACKEND_OPEN) {
- std::move(callback).Run(CacheStorageError::kErrorStorage,
- std::unique_ptr<Requests>());
+ std::move(callback).Run(CacheStorageError::kErrorStorage, nullptr);
return;
}
@@ -1639,7 +1612,7 @@ void CacheStorageCache::KeysDidQueryCache(
CacheStorageError error,
std::unique_ptr<QueryCacheResults> query_cache_results) {
if (error != CacheStorageError::kSuccess) {
- std::move(callback).Run(error, std::unique_ptr<Requests>());
+ std::move(callback).Run(error, nullptr);
return;
}
@@ -1711,7 +1684,7 @@ void CacheStorageCache::CreateBackend(ErrorCallback callback) {
weak_ptr_factory_.GetWeakPtr()),
create_cache_callback);
if (rv != net::ERR_IO_PENDING)
- create_cache_callback.Run(rv);
+ std::move(create_cache_callback).Run(rv);
}
void CacheStorageCache::CreateBackendDidCreate(
@@ -1756,7 +1729,8 @@ void CacheStorageCache::InitDidCreateBackend(
calculate_size_callback, cache_create_error));
if (rv != net::ERR_IO_PENDING)
- InitGotCacheSize(calculate_size_callback, cache_create_error, rv);
+ InitGotCacheSize(std::move(calculate_size_callback), cache_create_error,
+ rv);
}
void CacheStorageCache::InitGotCacheSize(base::OnceClosure callback,
@@ -1819,8 +1793,7 @@ void CacheStorageCache::InitGotCacheSizeAndPadding(
: BACKEND_CLOSED;
UMA_HISTOGRAM_ENUMERATION("ServiceWorkerCache.InitBackendResult",
- cache_create_error,
- static_cast<int>(CacheStorageError::kLast) + 1);
+ cache_create_error);
if (cache_observer_)
cache_observer_->CacheSizeUpdated(this);
@@ -1828,9 +1801,8 @@ void CacheStorageCache::InitGotCacheSizeAndPadding(
std::move(callback).Run();
}
-std::unique_ptr<storage::BlobDataHandle>
-CacheStorageCache::PopulateResponseBody(disk_cache::ScopedEntryPtr entry,
- ServiceWorkerResponse* response) {
+void CacheStorageCache::PopulateResponseBody(disk_cache::ScopedEntryPtr entry,
+ ServiceWorkerResponse* response) {
DCHECK(blob_storage_context_);
// Create a blob with the response body data.
@@ -1843,15 +1815,13 @@ CacheStorageCache::PopulateResponseBody(disk_cache::ScopedEntryPtr entry,
blob_data->AppendDiskCacheEntryWithSideData(
new CacheStorageCacheDataHandle(CreateCacheHandle(), std::move(entry)),
temp_entry, INDEX_RESPONSE_BODY, INDEX_SIDE_DATA);
- auto result = blob_storage_context_->AddFinishedBlob(std::move(blob_data));
+ auto blob_handle =
+ blob_storage_context_->AddFinishedBlob(std::move(blob_data));
blink::mojom::BlobPtr blob_ptr;
- storage::BlobImpl::Create(std::make_unique<storage::BlobDataHandle>(*result),
- MakeRequest(&blob_ptr));
+ storage::BlobImpl::Create(std::move(blob_handle), MakeRequest(&blob_ptr));
response->blob =
base::MakeRefCounted<storage::BlobHandle>(std::move(blob_ptr));
-
- return result;
}
CacheStorageCacheHandle CacheStorageCache::CreateCacheHandle() {
diff --git a/chromium/content/browser/cache_storage/cache_storage_cache.h b/chromium/content/browser/cache_storage/cache_storage_cache.h
index a64b9c344ea..75d0bc95ac9 100644
--- a/chromium/content/browser/cache_storage/cache_storage_cache.h
+++ b/chromium/content/browser/cache_storage/cache_storage_cache.h
@@ -16,13 +16,12 @@
#include "base/files/file_path.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
-#include "content/browser/bad_message.h"
#include "content/common/cache_storage/cache_storage_types.h"
#include "content/common/service_worker/service_worker_types.h"
#include "net/base/io_buffer.h"
#include "net/disk_cache/disk_cache.h"
-#include "third_party/WebKit/public/mojom/quota/quota_types.mojom.h"
-#include "third_party/WebKit/public/platform/modules/cache_storage/cache_storage.mojom.h"
+#include "third_party/blink/public/mojom/quota/quota_types.mojom.h"
+#include "third_party/blink/public/platform/modules/cache_storage/cache_storage.mojom.h"
#include "url/origin.h"
namespace crypto {
@@ -34,7 +33,6 @@ class URLRequestContextGetter;
}
namespace storage {
-class BlobDataHandle;
class BlobStorageContext;
class QuotaManagerProxy;
}
@@ -65,17 +63,13 @@ class CONTENT_EXPORT CacheStorageCache {
public:
using ErrorCallback =
base::OnceCallback<void(blink::mojom::CacheStorageError)>;
- using BadMessageCallback =
- base::OnceCallback<void(bad_message::BadMessageReason)>;
+ using BadMessageCallback = base::OnceCallback<void()>;
using ResponseCallback =
base::OnceCallback<void(blink::mojom::CacheStorageError,
- std::unique_ptr<ServiceWorkerResponse>,
- std::unique_ptr<storage::BlobDataHandle>)>;
- using BlobDataHandles = std::vector<std::unique_ptr<storage::BlobDataHandle>>;
+ std::unique_ptr<ServiceWorkerResponse>)>;
using ResponsesCallback =
base::OnceCallback<void(blink::mojom::CacheStorageError,
- std::vector<ServiceWorkerResponse>,
- std::unique_ptr<BlobDataHandles>)>;
+ std::vector<ServiceWorkerResponse>)>;
using Requests = std::vector<ServiceWorkerFetchRequest>;
using RequestsCallback =
base::OnceCallback<void(blink::mojom::CacheStorageError,
@@ -290,8 +284,7 @@ class CONTENT_EXPORT CacheStorageCache {
ResponseCallback callback);
void MatchDidMatchAll(ResponseCallback callback,
blink::mojom::CacheStorageError match_all_error,
- std::vector<ServiceWorkerResponse> match_all_responses,
- std::unique_ptr<BlobDataHandles> match_all_handles);
+ std::vector<ServiceWorkerResponse> match_all_responses);
// MatchAll callbacks
void MatchAllImpl(std::unique_ptr<ServiceWorkerFetchRequest> request,
@@ -438,9 +431,8 @@ class CONTENT_EXPORT CacheStorageCache {
int64_t cache_padding);
void DeleteBackendCompletedIO();
- std::unique_ptr<storage::BlobDataHandle> PopulateResponseBody(
- disk_cache::ScopedEntryPtr entry,
- ServiceWorkerResponse* response);
+ void PopulateResponseBody(disk_cache::ScopedEntryPtr entry,
+ ServiceWorkerResponse* response);
// Virtual for testing.
virtual CacheStorageCacheHandle CreateCacheHandle();
diff --git a/chromium/content/browser/cache_storage/cache_storage_cache_unittest.cc b/chromium/content/browser/cache_storage/cache_storage_cache_unittest.cc
index 8b70bc1646c..3243379ec93 100644
--- a/chromium/content/browser/cache_storage/cache_storage_cache_unittest.cc
+++ b/chromium/content/browser/cache_storage/cache_storage_cache_unittest.cc
@@ -19,6 +19,7 @@
#include "base/memory/ref_counted.h"
#include "base/run_loop.h"
#include "base/strings/string_split.h"
+#include "base/test/bind_test_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/browser/blob_storage/chrome_blob_storage_context.h"
#include "content/browser/cache_storage/cache_storage_cache_handle.h"
@@ -32,6 +33,7 @@
#include "content/public/test/test_browser_thread_bundle.h"
#include "content/public/test/test_utils.h"
#include "crypto/symmetric_key.h"
+#include "mojo/public/cpp/system/data_pipe_drainer.h"
#include "net/base/test_completion_callback.h"
#include "net/disk_cache/disk_cache.h"
#include "net/url_request/url_request_context.h"
@@ -157,61 +159,42 @@ class DelayableBackend : public disk_cache::Backend {
base::OnceClosure open_entry_callback_;
};
-void CopyBody(const storage::BlobDataHandle& blob_handle, std::string* output) {
- *output = std::string();
- std::unique_ptr<storage::BlobDataSnapshot> data =
- blob_handle.CreateSnapshot();
- const auto& items = data->items();
- for (const auto& item : items) {
- switch (item->type()) {
- case BlobDataItem::Type::kBytes: {
- output->append(item->bytes().data(), item->length());
- break;
- }
- case BlobDataItem::Type::kDiskCacheEntry: {
- disk_cache::Entry* entry = item->disk_cache_entry();
- int32_t body_size = entry->GetDataSize(item->disk_cache_stream_index());
-
- scoped_refptr<net::IOBuffer> io_buffer = new net::IOBuffer(body_size);
- net::TestCompletionCallback callback;
- int rv =
- entry->ReadData(item->disk_cache_stream_index(), 0, io_buffer.get(),
- body_size, callback.callback());
- if (rv == net::ERR_IO_PENDING)
- rv = callback.WaitForResult();
- EXPECT_EQ(body_size, rv);
- if (rv > 0)
- output->append(io_buffer->data(), rv);
- break;
- }
- default: { ADD_FAILURE() << "invalid response blob type"; } break;
- }
+class DataPipeDrainerClient : public mojo::DataPipeDrainer::Client {
+ public:
+ DataPipeDrainerClient(std::string* output) : output_(output) {}
+ void Run() { run_loop_.Run(); }
+
+ void OnDataAvailable(const void* data, size_t num_bytes) override {
+ output_->append(reinterpret_cast<const char*>(data), num_bytes);
}
-}
+ void OnDataComplete() override { run_loop_.Quit(); }
-void CopySideData(const storage::BlobDataHandle& blob_handle,
- std::string* output) {
- *output = std::string();
- std::unique_ptr<storage::BlobDataSnapshot> data =
- blob_handle.CreateSnapshot();
- const auto& items = data->items();
- ASSERT_EQ(1u, items.size());
- const auto& item = items[0];
- ASSERT_EQ(BlobDataItem::Type::kDiskCacheEntry, item->type());
- ASSERT_EQ(CacheStorageCache::INDEX_SIDE_DATA,
- item->disk_cache_side_stream_index());
-
- disk_cache::Entry* entry = item->disk_cache_entry();
- int32_t body_size = entry->GetDataSize(item->disk_cache_side_stream_index());
- scoped_refptr<net::IOBuffer> io_buffer = new net::IOBuffer(body_size);
- net::TestCompletionCallback callback;
- int rv = entry->ReadData(item->disk_cache_side_stream_index(), 0,
- io_buffer.get(), body_size, callback.callback());
- if (rv == net::ERR_IO_PENDING)
- rv = callback.WaitForResult();
- EXPECT_EQ(body_size, rv);
- if (rv > 0)
- output->append(io_buffer->data(), rv);
+ private:
+ base::RunLoop run_loop_;
+ std::string* output_;
+};
+
+std::string CopyBody(blink::mojom::Blob* actual_blob) {
+ std::string output;
+ mojo::DataPipe pipe;
+ actual_blob->ReadAll(std::move(pipe.producer_handle), nullptr);
+ DataPipeDrainerClient client(&output);
+ mojo::DataPipeDrainer drainer(&client, std::move(pipe.consumer_handle));
+ client.Run();
+ return output;
+}
+
+std::string CopySideData(blink::mojom::Blob* actual_blob) {
+ std::string output;
+ base::RunLoop loop;
+ actual_blob->ReadSideData(base::BindLambdaForTesting(
+ [&](const base::Optional<std::vector<uint8_t>>& data) {
+ ASSERT_TRUE(data);
+ output.append(data->begin(), data->end());
+ loop.Quit();
+ }));
+ loop.Run();
+ return output;
}
bool ResponseMetadataEqual(const ServiceWorkerResponse& expected,
@@ -261,16 +244,14 @@ bool ResponseMetadataEqual(const ServiceWorkerResponse& expected,
}
bool ResponseBodiesEqual(const std::string& expected_body,
- const storage::BlobDataHandle& actual_body_handle) {
- std::string actual_body;
- CopyBody(actual_body_handle, &actual_body);
+ blink::mojom::Blob* actual_blob) {
+ std::string actual_body = CopyBody(actual_blob);
return expected_body == actual_body;
}
bool ResponseSideDataEqual(const std::string& expected_side_data,
- const storage::BlobDataHandle& actual_body_handle) {
- std::string actual_body;
- CopySideData(actual_body_handle, &actual_body);
+ blink::mojom::Blob* actual_blob) {
+ std::string actual_body = CopySideData(actual_blob);
return expected_side_data == actual_body;
}
@@ -286,9 +267,8 @@ std::unique_ptr<crypto::SymmetricKey> CreateTestPaddingKey() {
"abc123");
}
-void OnBadMessage(base::Optional<bad_message::BadMessageReason>* result,
- bad_message::BadMessageReason reason) {
- *result = reason;
+void OnBadMessage(std::string* result) {
+ *result = "CSDH_UNEXPECTED_OPERATION";
}
// A CacheStorageCache that can optionally delay during backend creation.
@@ -551,26 +531,21 @@ class CacheStorageCacheTest : public testing::Test {
return callback_error_ == CacheStorageError::kSuccess;
}
- bool MatchAll(
- const ServiceWorkerFetchRequest& request,
- const CacheStorageCacheQueryParams& match_params,
- std::vector<ServiceWorkerResponse>* responses,
- std::unique_ptr<CacheStorageCache::BlobDataHandles>* body_handles) {
+ bool MatchAll(const ServiceWorkerFetchRequest& request,
+ const CacheStorageCacheQueryParams& match_params,
+ std::vector<ServiceWorkerResponse>* responses) {
base::RunLoop loop;
cache_->MatchAll(
CopyFetchRequest(request), match_params,
base::BindOnce(&CacheStorageCacheTest::ResponsesAndErrorCallback,
- base::Unretained(this), loop.QuitClosure(), responses,
- body_handles));
+ base::Unretained(this), loop.QuitClosure(), responses));
loop.Run();
return callback_error_ == CacheStorageError::kSuccess;
}
- bool MatchAll(
- std::vector<ServiceWorkerResponse>* responses,
- std::unique_ptr<CacheStorageCache::BlobDataHandles>* body_handles) {
+ bool MatchAll(std::vector<ServiceWorkerResponse>* responses) {
return MatchAll(ServiceWorkerFetchRequest(), CacheStorageCacheQueryParams(),
- responses, body_handles);
+ responses);
}
bool Delete(const ServiceWorkerFetchRequest& request,
@@ -683,14 +658,9 @@ class CacheStorageCacheTest : public testing::Test {
void ResponseAndErrorCallback(
base::RunLoop* run_loop,
CacheStorageError error,
- std::unique_ptr<ServiceWorkerResponse> response,
- std::unique_ptr<storage::BlobDataHandle> body_handle) {
+ std::unique_ptr<ServiceWorkerResponse> response) {
callback_error_ = error;
callback_response_ = std::move(response);
- callback_response_data_.reset();
- if (error == CacheStorageError::kSuccess &&
- !callback_response_->blob_uuid.empty())
- callback_response_data_ = std::move(body_handle);
if (run_loop)
run_loop->Quit();
@@ -699,13 +669,10 @@ class CacheStorageCacheTest : public testing::Test {
void ResponsesAndErrorCallback(
base::OnceClosure quit_closure,
std::vector<ServiceWorkerResponse>* responses_out,
- std::unique_ptr<CacheStorageCache::BlobDataHandles>* body_handles_out,
CacheStorageError error,
- std::vector<ServiceWorkerResponse> responses,
- std::unique_ptr<CacheStorageCache::BlobDataHandles> body_handles) {
+ std::vector<ServiceWorkerResponse> responses) {
callback_error_ = error;
*responses_out = std::move(responses);
- body_handles_out->swap(body_handles);
std::move(quit_closure).Run();
}
@@ -770,9 +737,8 @@ class CacheStorageCacheTest : public testing::Test {
CacheStorageError callback_error_ = CacheStorageError::kSuccess;
std::unique_ptr<ServiceWorkerResponse> callback_response_;
- std::unique_ptr<storage::BlobDataHandle> callback_response_data_;
std::vector<std::string> callback_strings_;
- base::Optional<bad_message::BadMessageReason> bad_message_reason_;
+ std::string bad_message_reason_;
bool callback_closed_ = false;
int64_t callback_size_ = 0;
};
@@ -848,27 +814,25 @@ TEST_P(CacheStorageCacheTestP, MatchAllLimit) {
callback_response_->EstimatedStructSize();
std::vector<ServiceWorkerResponse> responses;
- std::unique_ptr<CacheStorageCache::BlobDataHandles> body_handles;
CacheStorageCacheQueryParams match_params;
// There is enough room for both requests and responses
SetMaxQuerySizeBytes(body_request_size + query_request_size);
- EXPECT_TRUE(MatchAll(body_request_, match_params, &responses, &body_handles));
+ EXPECT_TRUE(MatchAll(body_request_, match_params, &responses));
EXPECT_EQ(1u, responses.size());
match_params.ignore_search = true;
- EXPECT_TRUE(MatchAll(body_request_, match_params, &responses, &body_handles));
+ EXPECT_TRUE(MatchAll(body_request_, match_params, &responses));
EXPECT_EQ(2u, responses.size());
// There is not enough room for both requests and responses
SetMaxQuerySizeBytes(body_request_size);
match_params.ignore_search = false;
- EXPECT_TRUE(MatchAll(body_request_, match_params, &responses, &body_handles));
+ EXPECT_TRUE(MatchAll(body_request_, match_params, &responses));
EXPECT_EQ(1u, responses.size());
match_params.ignore_search = true;
- EXPECT_FALSE(
- MatchAll(body_request_, match_params, &responses, &body_handles));
+ EXPECT_FALSE(MatchAll(body_request_, match_params, &responses));
EXPECT_EQ(CacheStorageError::kErrorQueryTooLarge, callback_error_);
}
@@ -941,7 +905,7 @@ TEST_P(CacheStorageCacheTestP, PutBadMessage) {
std::vector<CacheStorageBatchOperation> operations =
std::vector<CacheStorageBatchOperation>(2, operation);
EXPECT_EQ(CacheStorageError::kErrorStorage, BatchOperation(operations));
- EXPECT_EQ(bad_message::CSDH_UNEXPECTED_OPERATION, *bad_message_reason_);
+ EXPECT_EQ("CSDH_UNEXPECTED_OPERATION", bad_message_reason_);
EXPECT_FALSE(Match(body_request_));
}
@@ -949,15 +913,15 @@ TEST_P(CacheStorageCacheTestP, PutBadMessage) {
TEST_P(CacheStorageCacheTestP, PutReplace) {
EXPECT_TRUE(Put(body_request_, no_body_response_));
EXPECT_TRUE(Match(body_request_));
- EXPECT_FALSE(callback_response_data_);
+ EXPECT_FALSE(callback_response_->blob);
EXPECT_TRUE(Put(body_request_, body_response_));
EXPECT_TRUE(Match(body_request_));
- EXPECT_TRUE(callback_response_data_);
+ EXPECT_TRUE(callback_response_->blob);
EXPECT_TRUE(Put(body_request_, no_body_response_));
EXPECT_TRUE(Match(body_request_));
- EXPECT_FALSE(callback_response_data_);
+ EXPECT_FALSE(callback_response_->blob);
}
TEST_P(CacheStorageCacheTestP, PutReplaceInBatch) {
@@ -979,7 +943,7 @@ TEST_P(CacheStorageCacheTestP, PutReplaceInBatch) {
// |operation2| should win.
EXPECT_TRUE(Match(operation2.request));
- EXPECT_TRUE(callback_response_data_);
+ EXPECT_TRUE(callback_response_->blob);
}
TEST_P(CacheStorageCacheTestP, MatchNoBody) {
@@ -987,7 +951,7 @@ TEST_P(CacheStorageCacheTestP, MatchNoBody) {
EXPECT_TRUE(Match(no_body_request_));
EXPECT_TRUE(ResponseMetadataEqual(SetCacheName(no_body_response_),
*callback_response_));
- EXPECT_FALSE(callback_response_data_);
+ EXPECT_FALSE(callback_response_->blob);
}
TEST_P(CacheStorageCacheTestP, MatchBody) {
@@ -995,8 +959,8 @@ TEST_P(CacheStorageCacheTestP, MatchBody) {
EXPECT_TRUE(Match(body_request_));
EXPECT_TRUE(
ResponseMetadataEqual(SetCacheName(body_response_), *callback_response_));
- EXPECT_TRUE(
- ResponseBodiesEqual(expected_blob_data_, *callback_response_data_));
+ EXPECT_TRUE(ResponseBodiesEqual(expected_blob_data_,
+ callback_response_->blob->get()));
}
TEST_P(CacheStorageCacheTestP, MatchBodyHead) {
@@ -1006,37 +970,33 @@ TEST_P(CacheStorageCacheTestP, MatchBodyHead) {
TEST_P(CacheStorageCacheTestP, MatchAll_Empty) {
std::vector<ServiceWorkerResponse> responses;
- std::unique_ptr<CacheStorageCache::BlobDataHandles> body_handles;
- EXPECT_TRUE(MatchAll(&responses, &body_handles));
+ EXPECT_TRUE(MatchAll(&responses));
EXPECT_TRUE(responses.empty());
- EXPECT_TRUE(body_handles->empty());
}
TEST_P(CacheStorageCacheTestP, MatchAll_NoBody) {
EXPECT_TRUE(Put(no_body_request_, no_body_response_));
std::vector<ServiceWorkerResponse> responses;
- std::unique_ptr<CacheStorageCache::BlobDataHandles> body_handles;
- EXPECT_TRUE(MatchAll(&responses, &body_handles));
+ EXPECT_TRUE(MatchAll(&responses));
ASSERT_EQ(1u, responses.size());
EXPECT_TRUE(
ResponseMetadataEqual(SetCacheName(no_body_response_), responses[0]));
- EXPECT_FALSE(body_handles->at(0));
+ EXPECT_FALSE(responses[0].blob);
}
TEST_P(CacheStorageCacheTestP, MatchAll_Body) {
EXPECT_TRUE(Put(body_request_, body_response_));
std::vector<ServiceWorkerResponse> responses;
- std::unique_ptr<CacheStorageCache::BlobDataHandles> body_handles;
- EXPECT_TRUE(MatchAll(&responses, &body_handles));
+ EXPECT_TRUE(MatchAll(&responses));
ASSERT_EQ(1u, responses.size());
- ASSERT_EQ(1u, body_handles->size());
EXPECT_TRUE(
ResponseMetadataEqual(SetCacheName(body_response_), responses[0]));
- EXPECT_TRUE(ResponseBodiesEqual(expected_blob_data_, *body_handles->at(0)));
+ EXPECT_TRUE(
+ ResponseBodiesEqual(expected_blob_data_, responses[0].blob->get()));
}
TEST_P(CacheStorageCacheTestP, MatchAll_TwoResponsesThenOne) {
@@ -1044,28 +1004,27 @@ TEST_P(CacheStorageCacheTestP, MatchAll_TwoResponsesThenOne) {
EXPECT_TRUE(Put(body_request_, body_response_));
std::vector<ServiceWorkerResponse> responses;
- std::unique_ptr<CacheStorageCache::BlobDataHandles> body_handles;
- EXPECT_TRUE(MatchAll(&responses, &body_handles));
- ASSERT_TRUE(body_handles->at(1));
+ EXPECT_TRUE(MatchAll(&responses));
+ ASSERT_EQ(2u, responses.size());
+ EXPECT_TRUE(responses[1].blob);
EXPECT_TRUE(
ResponseMetadataEqual(SetCacheName(no_body_response_), responses[0]));
- EXPECT_FALSE(body_handles->at(0));
+ EXPECT_FALSE(responses[0].blob);
EXPECT_TRUE(
ResponseMetadataEqual(SetCacheName(body_response_), responses[1]));
- EXPECT_TRUE(ResponseBodiesEqual(expected_blob_data_, *body_handles->at(1)));
+ EXPECT_TRUE(
+ ResponseBodiesEqual(expected_blob_data_, responses[1].blob->get()));
responses.clear();
- body_handles->clear();
EXPECT_TRUE(Delete(body_request_));
- EXPECT_TRUE(MatchAll(&responses, &body_handles));
+ EXPECT_TRUE(MatchAll(&responses));
ASSERT_EQ(1u, responses.size());
EXPECT_TRUE(
ResponseMetadataEqual(SetCacheName(no_body_response_), responses[0]));
- ASSERT_EQ(1u, body_handles->size());
- EXPECT_FALSE(body_handles->at(0));
+ EXPECT_FALSE(responses[0].blob);
}
TEST_P(CacheStorageCacheTestP, Match_IgnoreSearch) {
@@ -1186,14 +1145,13 @@ TEST_P(CacheStorageCacheTestP, MatchAll_IgnoreMethod) {
ServiceWorkerFetchRequest post_request = body_request_;
post_request.method = "POST";
std::vector<ServiceWorkerResponse> responses;
- std::unique_ptr<CacheStorageCache::BlobDataHandles> body_handles;
CacheStorageCacheQueryParams match_params;
- EXPECT_TRUE(MatchAll(post_request, match_params, &responses, &body_handles));
+ EXPECT_TRUE(MatchAll(post_request, match_params, &responses));
EXPECT_EQ(0u, responses.size());
match_params.ignore_method = true;
- EXPECT_TRUE(MatchAll(post_request, match_params, &responses, &body_handles));
+ EXPECT_TRUE(MatchAll(post_request, match_params, &responses));
EXPECT_EQ(1u, responses.size());
}
@@ -1202,18 +1160,17 @@ TEST_P(CacheStorageCacheTestP, MatchAll_IgnoreVary) {
body_response_.headers["vary"] = "vary_foo";
EXPECT_TRUE(Put(body_request_, body_response_));
std::vector<ServiceWorkerResponse> responses;
- std::unique_ptr<CacheStorageCache::BlobDataHandles> body_handles;
CacheStorageCacheQueryParams match_params;
- EXPECT_TRUE(MatchAll(body_request_, match_params, &responses, &body_handles));
+ EXPECT_TRUE(MatchAll(body_request_, match_params, &responses));
EXPECT_EQ(1u, responses.size());
body_request_.headers["vary_foo"] = "bar";
- EXPECT_TRUE(MatchAll(body_request_, match_params, &responses, &body_handles));
+ EXPECT_TRUE(MatchAll(body_request_, match_params, &responses));
EXPECT_EQ(0u, responses.size());
match_params.ignore_vary = true;
- EXPECT_TRUE(MatchAll(body_request_, match_params, &responses, &body_handles));
+ EXPECT_TRUE(MatchAll(body_request_, match_params, &responses));
EXPECT_EQ(1u, responses.size());
}
@@ -1223,13 +1180,11 @@ TEST_P(CacheStorageCacheTestP, MatchAll_IgnoreSearch) {
EXPECT_TRUE(Put(no_body_request_, no_body_response_));
std::vector<ServiceWorkerResponse> responses;
- std::unique_ptr<CacheStorageCache::BlobDataHandles> body_handles;
CacheStorageCacheQueryParams match_params;
match_params.ignore_search = true;
- EXPECT_TRUE(MatchAll(body_request_, match_params, &responses, &body_handles));
+ EXPECT_TRUE(MatchAll(body_request_, match_params, &responses));
ASSERT_EQ(2u, responses.size());
- ASSERT_EQ(2u, body_handles->size());
// Order of returned responses is not guaranteed.
std::set<std::string> matched_set;
@@ -1253,22 +1208,18 @@ TEST_P(CacheStorageCacheTestP, MatchAll_Head) {
EXPECT_TRUE(Put(body_request_, body_response_));
std::vector<ServiceWorkerResponse> responses;
- std::unique_ptr<CacheStorageCache::BlobDataHandles> body_handles;
CacheStorageCacheQueryParams match_params;
match_params.ignore_search = true;
- EXPECT_TRUE(
- MatchAll(body_head_request_, match_params, &responses, &body_handles));
+ EXPECT_TRUE(MatchAll(body_head_request_, match_params, &responses));
EXPECT_TRUE(responses.empty());
- EXPECT_TRUE(body_handles->empty());
match_params.ignore_method = true;
- EXPECT_TRUE(
- MatchAll(body_head_request_, match_params, &responses, &body_handles));
+ EXPECT_TRUE(MatchAll(body_head_request_, match_params, &responses));
ASSERT_EQ(1u, responses.size());
- ASSERT_EQ(1u, body_handles->size());
EXPECT_TRUE(
ResponseMetadataEqual(SetCacheName(body_response_), responses[0]));
- EXPECT_TRUE(ResponseBodiesEqual(expected_blob_data_, *body_handles->at(0)));
+ EXPECT_TRUE(
+ ResponseBodiesEqual(expected_blob_data_, responses[0].blob->get()));
}
TEST_P(CacheStorageCacheTestP, Vary) {
@@ -1499,11 +1450,11 @@ TEST_P(CacheStorageCacheTestP, PutWithSideData) {
EXPECT_TRUE(Put(body_request_, response));
EXPECT_TRUE(Match(body_request_));
- EXPECT_TRUE(callback_response_data_);
- EXPECT_TRUE(
- ResponseBodiesEqual(expected_blob_data_, *callback_response_data_));
- EXPECT_TRUE(
- ResponseSideDataEqual(expected_side_data, *callback_response_data_));
+ ASSERT_TRUE(callback_response_->blob);
+ EXPECT_TRUE(ResponseBodiesEqual(expected_blob_data_,
+ callback_response_->blob->get()));
+ EXPECT_TRUE(ResponseSideDataEqual(expected_side_data,
+ callback_response_->blob->get()));
}
TEST_P(CacheStorageCacheTestP, PutWithSideData_QuotaExceeded) {
@@ -1537,11 +1488,11 @@ TEST_P(CacheStorageCacheTestP, PutWithSideData_QuotaExceededSkipSideData) {
EXPECT_TRUE(Put(body_request_, response));
EXPECT_TRUE(Match(body_request_));
- EXPECT_TRUE(callback_response_data_);
- EXPECT_TRUE(
- ResponseBodiesEqual(expected_blob_data_, *callback_response_data_));
+ ASSERT_TRUE(callback_response_->blob);
+ EXPECT_TRUE(ResponseBodiesEqual(expected_blob_data_,
+ callback_response_->blob->get()));
// The side data should not be written.
- EXPECT_TRUE(ResponseSideDataEqual("", *callback_response_data_));
+ EXPECT_TRUE(ResponseSideDataEqual("", callback_response_->blob->get()));
}
TEST_P(CacheStorageCacheTestP, PutWithSideData_BadMessage) {
@@ -1562,7 +1513,7 @@ TEST_P(CacheStorageCacheTestP, PutWithSideData_BadMessage) {
std::vector<CacheStorageBatchOperation> operations =
std::vector<CacheStorageBatchOperation>(1, operation);
EXPECT_EQ(CacheStorageError::kErrorStorage, BatchOperation(operations));
- EXPECT_EQ(bad_message::CSDH_UNEXPECTED_OPERATION, *bad_message_reason_);
+ EXPECT_EQ("CSDH_UNEXPECTED_OPERATION", bad_message_reason_);
EXPECT_FALSE(Match(body_request_));
}
@@ -1580,11 +1531,11 @@ TEST_P(CacheStorageCacheTestP, WriteSideData) {
expected_side_data1.length()));
EXPECT_TRUE(Match(body_request_));
- EXPECT_TRUE(callback_response_data_);
- EXPECT_TRUE(
- ResponseBodiesEqual(expected_blob_data_, *callback_response_data_));
- EXPECT_TRUE(
- ResponseSideDataEqual(expected_side_data1, *callback_response_data_));
+ ASSERT_TRUE(callback_response_->blob);
+ EXPECT_TRUE(ResponseBodiesEqual(expected_blob_data_,
+ callback_response_->blob->get()));
+ EXPECT_TRUE(ResponseSideDataEqual(expected_side_data1,
+ callback_response_->blob->get()));
const std::string expected_side_data2 = "New data";
scoped_refptr<net::IOBuffer> buffer2(
@@ -1592,11 +1543,11 @@ TEST_P(CacheStorageCacheTestP, WriteSideData) {
EXPECT_TRUE(WriteSideData(body_request_.url, response_time, buffer2,
expected_side_data2.length()));
EXPECT_TRUE(Match(body_request_));
- EXPECT_TRUE(callback_response_data_);
- EXPECT_TRUE(
- ResponseBodiesEqual(expected_blob_data_, *callback_response_data_));
- EXPECT_TRUE(
- ResponseSideDataEqual(expected_side_data2, *callback_response_data_));
+ ASSERT_TRUE(callback_response_->blob);
+ EXPECT_TRUE(ResponseBodiesEqual(expected_blob_data_,
+ callback_response_->blob->get()));
+ EXPECT_TRUE(ResponseSideDataEqual(expected_side_data2,
+ callback_response_->blob->get()));
ASSERT_TRUE(Delete(body_request_));
}
diff --git a/chromium/content/browser/cache_storage/cache_storage_dispatcher_host.cc b/chromium/content/browser/cache_storage/cache_storage_dispatcher_host.cc
index 6a2bf56fac8..9680429f601 100644
--- a/chromium/content/browser/cache_storage/cache_storage_dispatcher_host.cc
+++ b/chromium/content/browser/cache_storage/cache_storage_dispatcher_host.cc
@@ -15,28 +15,28 @@
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "base/trace_event/trace_event.h"
-#include "content/browser/bad_message.h"
#include "content/browser/cache_storage/cache_storage_cache.h"
#include "content/browser/cache_storage/cache_storage_cache_handle.h"
#include "content/browser/cache_storage/cache_storage_context_impl.h"
#include "content/browser/cache_storage/cache_storage_manager.h"
-#include "content/common/cache_storage/cache_storage_messages.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/common/origin_util.h"
-#include "storage/browser/blob/blob_data_handle.h"
-#include "third_party/WebKit/public/platform/modules/cache_storage/cache_storage.mojom.h"
+#include "mojo/public/cpp/bindings/message.h"
+#include "third_party/blink/public/platform/modules/cache_storage/cache_storage.mojom.h"
#include "url/gurl.h"
#include "url/origin.h"
-using blink::mojom::CacheStorageError;
namespace content {
namespace {
-const uint32_t kCacheFilteredMessageClasses[] = {CacheStorageMsgStart};
+using blink::mojom::CacheStorageError;
+
const int32_t kCachePreservationSeconds = 5;
+// TODO(lucmult): Check this before binding.
bool OriginCanAccessCacheStorage(const url::Origin& origin) {
return !origin.unique() && IsOriginSecure(origin.GetURL());
}
@@ -45,50 +45,198 @@ void StopPreservingCache(CacheStorageCacheHandle cache_handle) {}
} // namespace
-CacheStorageDispatcherHost::CacheStorageDispatcherHost()
- : BrowserMessageFilter(kCacheFilteredMessageClasses,
- arraysize(kCacheFilteredMessageClasses)) {}
+// Implements the mojom interface CacheStorageCache. It's owned by
+// CacheStorageDispatcherHost and it's destroyed when client drops the mojo ptr
+// which in turn removes from StrongBindingSet in CacheStorageDispatcherHost.
+class CacheStorageDispatcherHost::CacheImpl
+ : public blink::mojom::CacheStorageCache {
+ public:
+ CacheImpl(CacheStorageCacheHandle cache_handle,
+ CacheStorageDispatcherHost* dispatcher_host)
+ : cache_handle_(std::move(cache_handle)),
+ owner_(dispatcher_host),
+ weak_factory_(this) {}
+
+ ~CacheImpl() override = default;
+
+ // blink::mojom::CacheStorageCache implementation:
+ void Match(const ServiceWorkerFetchRequest& request,
+ const CacheStorageCacheQueryParams& match_params,
+ MatchCallback callback) override {
+ content::CacheStorageCache* cache = cache_handle_.value();
+ if (!cache) {
+ std::move(callback).Run(blink::mojom::MatchResult::NewStatus(
+ CacheStorageError::kErrorNotFound));
+ return;
+ }
+
+ auto scoped_request = std::make_unique<ServiceWorkerFetchRequest>(
+ request.url, request.method, request.headers, request.referrer,
+ request.is_reload);
+ cache->Match(std::move(scoped_request), match_params,
+ base::BindOnce(&CacheImpl::OnCacheMatchCallback,
+ weak_factory_.GetWeakPtr(), std::move(callback),
+ cache_handle_.Clone()));
+ }
+
+ void OnCacheMatchCallback(
+ blink::mojom::CacheStorageCache::MatchCallback callback,
+ CacheStorageCacheHandle cache_handle,
+ blink::mojom::CacheStorageError error,
+ std::unique_ptr<ServiceWorkerResponse> response) {
+ if (error != CacheStorageError::kSuccess) {
+ std::move(callback).Run(blink::mojom::MatchResult::NewStatus(error));
+ return;
+ }
+
+ std::move(callback).Run(blink::mojom::MatchResult::NewResponse(*response));
+ }
-CacheStorageDispatcherHost::~CacheStorageDispatcherHost() {
-}
+ void MatchAll(const ServiceWorkerFetchRequest& request,
+ const CacheStorageCacheQueryParams& match_params,
+ MatchAllCallback callback) override {
+ content::CacheStorageCache* cache = cache_handle_.value();
+ if (!cache) {
+ std::move(callback).Run(blink::mojom::MatchAllResult::NewStatus(
+ CacheStorageError::kErrorNotFound));
+ return;
+ }
+
+ if (request.url.is_empty()) {
+ cache->MatchAll(
+ nullptr, match_params,
+ base::BindOnce(&CacheImpl::OnCacheMatchAllCallback,
+ weak_factory_.GetWeakPtr(), std::move(callback),
+ cache_handle_.Clone()));
+ return;
+ }
+
+ auto scoped_request = std::make_unique<ServiceWorkerFetchRequest>(
+ request.url, request.method, request.headers, request.referrer,
+ request.is_reload);
+ if (match_params.ignore_search) {
+ cache->MatchAll(
+ std::move(scoped_request), match_params,
+ base::BindOnce(&CacheImpl::OnCacheMatchAllCallback,
+ weak_factory_.GetWeakPtr(), std::move(callback),
+ cache_handle_.Clone()));
+ return;
+ }
+
+ cache->Match(std::move(scoped_request), match_params,
+ base::BindOnce(&CacheImpl::OnCacheMatchAllCallbackAdapter,
+ weak_factory_.GetWeakPtr(), std::move(callback),
+ cache_handle_.Clone()));
+ }
+
+ void OnCacheMatchAllCallback(
+ blink::mojom::CacheStorageCache::MatchAllCallback callback,
+ CacheStorageCacheHandle cache_handle,
+ blink::mojom::CacheStorageError error,
+ std::vector<ServiceWorkerResponse> responses) {
+ if (error != CacheStorageError::kSuccess &&
+ error != CacheStorageError::kErrorNotFound) {
+ std::move(callback).Run(blink::mojom::MatchAllResult::NewStatus(error));
+ return;
+ }
+
+ std::move(callback).Run(
+ blink::mojom::MatchAllResult::NewResponses(std::move(responses)));
+ }
+
+ void OnCacheMatchAllCallbackAdapter(
+ blink::mojom::CacheStorageCache::MatchAllCallback callback,
+ CacheStorageCacheHandle cache_handle,
+ blink::mojom::CacheStorageError error,
+ std::unique_ptr<ServiceWorkerResponse> response) {
+ std::vector<ServiceWorkerResponse> responses;
+ if (error == CacheStorageError::kSuccess) {
+ DCHECK(response);
+ responses.push_back(std::move(*response.release()));
+ }
+ OnCacheMatchAllCallback(std::move(callback), std::move(cache_handle), error,
+ std::move(responses));
+ }
+
+ void Keys(const ServiceWorkerFetchRequest& request,
+ const CacheStorageCacheQueryParams& match_params,
+ KeysCallback callback) override {
+ content::CacheStorageCache* cache = cache_handle_.value();
+ if (!cache) {
+ std::move(callback).Run(blink::mojom::CacheKeysResult::NewStatus(
+ CacheStorageError::kErrorNotFound));
+ return;
+ }
+
+ auto request_ptr = std::make_unique<ServiceWorkerFetchRequest>(
+ request.url, request.method, request.headers, request.referrer,
+ request.is_reload);
+ cache->Keys(std::move(request_ptr), match_params,
+ base::BindOnce(&CacheImpl::OnCacheKeysCallback,
+ weak_factory_.GetWeakPtr(), std::move(callback),
+ cache_handle_.Clone()));
+ }
+
+ void OnCacheKeysCallback(
+ blink::mojom::CacheStorageCache::KeysCallback callback,
+ CacheStorageCacheHandle cache_handle,
+ blink::mojom::CacheStorageError error,
+ std::unique_ptr<content::CacheStorageCache::Requests> requests) {
+ if (error != CacheStorageError::kSuccess) {
+ std::move(callback).Run(blink::mojom::CacheKeysResult::NewStatus(error));
+ return;
+ }
+
+ std::move(callback).Run(blink::mojom::CacheKeysResult::NewKeys(*requests));
+ }
+
+ void Batch(const std::vector<CacheStorageBatchOperation>& batch_operations,
+ BatchCallback callback) override {
+ content::CacheStorageCache* cache = cache_handle_.value();
+ if (!cache) {
+ std::move(callback).Run(CacheStorageError::kErrorNotFound);
+ return;
+ }
+ cache->BatchOperation(
+ batch_operations,
+ base::BindOnce(&CacheImpl::OnCacheBatchCallback,
+ weak_factory_.GetWeakPtr(), std::move(callback),
+ cache_handle_.Clone()),
+ base::BindOnce(&CacheImpl::OnBadMessage, weak_factory_.GetWeakPtr(),
+ mojo::GetBadMessageCallback()));
+ }
+
+ void OnCacheBatchCallback(
+ blink::mojom::CacheStorageCache::BatchCallback callback,
+ CacheStorageCacheHandle cache_handle,
+ blink::mojom::CacheStorageError error) {
+ std::move(callback).Run(error);
+ }
+
+ void OnBadMessage(mojo::ReportBadMessageCallback bad_message_callback) {
+ std::move(bad_message_callback).Run("CSDH_UNEXPECTED_OPERATION");
+ }
+
+ CacheStorageCacheHandle cache_handle_;
+
+ // Owns this.
+ CacheStorageDispatcherHost* const owner_;
+
+ base::WeakPtrFactory<CacheImpl> weak_factory_;
+
+ DISALLOW_COPY_AND_ASSIGN(CacheImpl);
+};
+
+CacheStorageDispatcherHost::CacheStorageDispatcherHost() = default;
+
+CacheStorageDispatcherHost::~CacheStorageDispatcherHost() = default;
void CacheStorageDispatcherHost::Init(CacheStorageContextImpl* context) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
- base::BindOnce(&CacheStorageDispatcherHost::CreateCacheListener, this,
- base::RetainedRef(context)));
-}
-
-void CacheStorageDispatcherHost::OnDestruct() const {
- BrowserThread::DeleteOnIOThread::Destruct(this);
-}
-
-bool CacheStorageDispatcherHost::OnMessageReceived(
- const IPC::Message& message) {
- DCHECK_CURRENTLY_ON(BrowserThread::IO);
-
- bool handled = true;
- IPC_BEGIN_MESSAGE_MAP(CacheStorageDispatcherHost, message)
- IPC_MESSAGE_HANDLER(CacheStorageHostMsg_CacheStorageHas, OnCacheStorageHas)
- IPC_MESSAGE_HANDLER(CacheStorageHostMsg_CacheStorageOpen, OnCacheStorageOpen)
- IPC_MESSAGE_HANDLER(CacheStorageHostMsg_CacheStorageDelete,
- OnCacheStorageDelete)
- IPC_MESSAGE_HANDLER(CacheStorageHostMsg_CacheStorageKeys, OnCacheStorageKeys)
- IPC_MESSAGE_HANDLER(CacheStorageHostMsg_CacheStorageMatch,
- OnCacheStorageMatch)
- IPC_MESSAGE_HANDLER(CacheStorageHostMsg_CacheMatch, OnCacheMatch)
- IPC_MESSAGE_HANDLER(CacheStorageHostMsg_CacheMatchAll, OnCacheMatchAll)
- IPC_MESSAGE_HANDLER(CacheStorageHostMsg_CacheKeys, OnCacheKeys)
- IPC_MESSAGE_HANDLER(CacheStorageHostMsg_CacheBatch, OnCacheBatch)
- IPC_MESSAGE_HANDLER(CacheStorageHostMsg_CacheClosed, OnCacheClosed)
- IPC_MESSAGE_HANDLER(CacheStorageHostMsg_BlobDataHandled, OnBlobDataHandled)
- IPC_MESSAGE_UNHANDLED(handled = false)
- IPC_END_MESSAGE_MAP()
-
- if (!handled)
- bad_message::ReceivedBadMessage(this, bad_message::CSDH_NOT_RECOGNIZED);
- return handled;
+ base::BindOnce(&CacheStorageDispatcherHost::CreateCacheListener,
+ base::RetainedRef(this), base::RetainedRef(context)));
}
void CacheStorageDispatcherHost::CreateCacheListener(
@@ -97,241 +245,121 @@ void CacheStorageDispatcherHost::CreateCacheListener(
context_ = context;
}
-void CacheStorageDispatcherHost::OnCacheStorageHas(
- int thread_id,
- int request_id,
- const url::Origin& origin,
- const base::string16& cache_name) {
+void CacheStorageDispatcherHost::Has(
+ const base::string16& cache_name,
+ blink::mojom::CacheStorage::HasCallback callback) {
TRACE_EVENT0("CacheStorage", "CacheStorageDispatcherHost::OnCacheStorageHas");
+ url::Origin origin = bindings_.dispatch_context();
if (!OriginCanAccessCacheStorage(origin)) {
- bad_message::ReceivedBadMessage(this, bad_message::CSDH_INVALID_ORIGIN);
+ bindings_.ReportBadMessage("CSDH_INVALID_ORIGIN");
return;
}
+ if (!ValidState())
+ return;
context_->cache_manager()->HasCache(
origin, base::UTF16ToUTF8(cache_name),
- base::BindOnce(&CacheStorageDispatcherHost::OnCacheStorageHasCallback,
- this, thread_id, request_id));
+ base::BindOnce(&CacheStorageDispatcherHost::OnHasCallback, this,
+ std::move(callback)));
}
-void CacheStorageDispatcherHost::OnCacheStorageOpen(
- int thread_id,
- int request_id,
- const url::Origin& origin,
- const base::string16& cache_name) {
+void CacheStorageDispatcherHost::Open(
+ const base::string16& cache_name,
+ blink::mojom::CacheStorage::OpenCallback callback) {
TRACE_EVENT0("CacheStorage",
"CacheStorageDispatcherHost::OnCacheStorageOpen");
+ url::Origin origin = bindings_.dispatch_context();
if (!OriginCanAccessCacheStorage(origin)) {
- bad_message::ReceivedBadMessage(this, bad_message::CSDH_INVALID_ORIGIN);
+ bindings_.ReportBadMessage("CSDH_INVALID_ORIGIN");
return;
}
+ if (!ValidState())
+ return;
context_->cache_manager()->OpenCache(
origin, base::UTF16ToUTF8(cache_name),
- base::BindOnce(&CacheStorageDispatcherHost::OnCacheStorageOpenCallback,
- this, thread_id, request_id));
+ base::BindOnce(&CacheStorageDispatcherHost::OnOpenCallback, this, origin,
+ std::move(callback)));
}
-void CacheStorageDispatcherHost::OnCacheStorageDelete(
- int thread_id,
- int request_id,
- const url::Origin& origin,
- const base::string16& cache_name) {
+void CacheStorageDispatcherHost::Delete(
+ const base::string16& cache_name,
+ blink::mojom::CacheStorage::DeleteCallback callback) {
TRACE_EVENT0("CacheStorage",
"CacheStorageDispatcherHost::OnCacheStorageDelete");
+ url::Origin origin = bindings_.dispatch_context();
if (!OriginCanAccessCacheStorage(origin)) {
- bad_message::ReceivedBadMessage(this, bad_message::CSDH_INVALID_ORIGIN);
+ bindings_.ReportBadMessage("CSDH_INVALID_ORIGIN");
return;
}
- context_->cache_manager()->DeleteCache(
- origin, base::UTF16ToUTF8(cache_name),
- base::BindOnce(&CacheStorageDispatcherHost::OnCacheStorageDeleteCallback,
- this, thread_id, request_id));
+ if (!ValidState())
+ return;
+ context_->cache_manager()->DeleteCache(origin, base::UTF16ToUTF8(cache_name),
+ std::move(callback));
}
-void CacheStorageDispatcherHost::OnCacheStorageKeys(int thread_id,
- int request_id,
- const url::Origin& origin) {
+void CacheStorageDispatcherHost::Keys(
+ blink::mojom::CacheStorage::KeysCallback callback) {
TRACE_EVENT0("CacheStorage",
"CacheStorageDispatcherHost::OnCacheStorageKeys");
+ url::Origin origin = bindings_.dispatch_context();
+
if (!OriginCanAccessCacheStorage(origin)) {
- bad_message::ReceivedBadMessage(this, bad_message::CSDH_INVALID_ORIGIN);
+ bindings_.ReportBadMessage("CSDH_INVALID_ORIGIN");
return;
}
+ if (!ValidState())
+ return;
context_->cache_manager()->EnumerateCaches(
- origin,
- base::BindOnce(&CacheStorageDispatcherHost::OnCacheStorageKeysCallback,
- this, thread_id, request_id));
+ origin, base::BindOnce(&CacheStorageDispatcherHost::OnKeysCallback, this,
+ std::move(callback)));
}
-void CacheStorageDispatcherHost::OnCacheStorageMatch(
- int thread_id,
- int request_id,
- const url::Origin& origin,
- const ServiceWorkerFetchRequest& request,
- const CacheStorageCacheQueryParams& match_params) {
+void CacheStorageDispatcherHost::Match(
+ const content::ServiceWorkerFetchRequest& request,
+ const content::CacheStorageCacheQueryParams& match_params,
+ blink::mojom::CacheStorage::MatchCallback callback) {
TRACE_EVENT0("CacheStorage",
"CacheStorageDispatcherHost::OnCacheStorageMatch");
+ url::Origin origin = bindings_.dispatch_context();
if (!OriginCanAccessCacheStorage(origin)) {
- bad_message::ReceivedBadMessage(this, bad_message::CSDH_INVALID_ORIGIN);
+ bindings_.ReportBadMessage("CSDH_INVALID_ORIGIN");
return;
}
- std::unique_ptr<ServiceWorkerFetchRequest> scoped_request(
- new ServiceWorkerFetchRequest(request.url, request.method,
- request.headers, request.referrer,
- request.is_reload));
+ if (!ValidState())
+ return;
+ auto scoped_request = std::make_unique<ServiceWorkerFetchRequest>(
+ request.url, request.method, request.headers, request.referrer,
+ request.is_reload);
if (match_params.cache_name.is_null()) {
context_->cache_manager()->MatchAllCaches(
- origin, std::move(scoped_request), match_params,
- base::BindOnce(&CacheStorageDispatcherHost::OnCacheStorageMatchCallback,
- this, thread_id, request_id));
+ origin, std::move(scoped_request), std::move(match_params),
+ base::BindOnce(&CacheStorageDispatcherHost::OnMatchCallback, this,
+ std::move(callback)));
return;
}
context_->cache_manager()->MatchCache(
origin, base::UTF16ToUTF8(match_params.cache_name.string()),
- std::move(scoped_request), match_params,
- base::BindOnce(&CacheStorageDispatcherHost::OnCacheStorageMatchCallback,
- this, thread_id, request_id));
-}
-
-void CacheStorageDispatcherHost::OnCacheMatch(
- int thread_id,
- int request_id,
- int cache_id,
- const ServiceWorkerFetchRequest& request,
- const CacheStorageCacheQueryParams& match_params) {
- IDToCacheMap::iterator it = id_to_cache_map_.find(cache_id);
- if (it == id_to_cache_map_.end() || !it->second.value()) {
- Send(new CacheStorageMsg_CacheMatchError(
- thread_id, request_id, CacheStorageError::kErrorNotFound));
- return;
- }
-
- CacheStorageCache* cache = it->second.value();
- std::unique_ptr<ServiceWorkerFetchRequest> scoped_request(
- new ServiceWorkerFetchRequest(request.url, request.method,
- request.headers, request.referrer,
- request.is_reload));
- cache->Match(std::move(scoped_request), match_params,
- base::BindOnce(&CacheStorageDispatcherHost::OnCacheMatchCallback,
- this, thread_id, request_id, it->second.Clone()));
-}
-
-void CacheStorageDispatcherHost::OnCacheMatchAll(
- int thread_id,
- int request_id,
- int cache_id,
- const ServiceWorkerFetchRequest& request,
- const CacheStorageCacheQueryParams& match_params) {
- IDToCacheMap::iterator it = id_to_cache_map_.find(cache_id);
- if (it == id_to_cache_map_.end() || !it->second.value()) {
- Send(new CacheStorageMsg_CacheMatchError(
- thread_id, request_id, CacheStorageError::kErrorNotFound));
- return;
- }
-
- CacheStorageCache* cache = it->second.value();
- if (request.url.is_empty()) {
- cache->MatchAll(
- std::unique_ptr<ServiceWorkerFetchRequest>(), match_params,
- base::BindOnce(&CacheStorageDispatcherHost::OnCacheMatchAllCallback,
- this, thread_id, request_id, it->second.Clone()));
- return;
- }
-
- std::unique_ptr<ServiceWorkerFetchRequest> scoped_request(
- new ServiceWorkerFetchRequest(request.url, request.method,
- request.headers, request.referrer,
- request.is_reload));
- if (match_params.ignore_search) {
- cache->MatchAll(
- std::move(scoped_request), match_params,
- base::BindOnce(&CacheStorageDispatcherHost::OnCacheMatchAllCallback,
- this, thread_id, request_id, it->second.Clone()));
- return;
- }
- cache->Match(std::move(scoped_request), match_params,
- base::BindOnce(
- &CacheStorageDispatcherHost::OnCacheMatchAllCallbackAdapter,
- this, thread_id, request_id, it->second.Clone()));
-}
-
-void CacheStorageDispatcherHost::OnCacheKeys(
- int thread_id,
- int request_id,
- int cache_id,
- const ServiceWorkerFetchRequest& request,
- const CacheStorageCacheQueryParams& match_params) {
- IDToCacheMap::iterator it = id_to_cache_map_.find(cache_id);
- if (it == id_to_cache_map_.end() || !it->second.value()) {
- Send(new CacheStorageMsg_CacheKeysError(thread_id, request_id,
- CacheStorageError::kErrorNotFound));
- return;
- }
-
- CacheStorageCache* cache = it->second.value();
- std::unique_ptr<ServiceWorkerFetchRequest> request_ptr(
- new ServiceWorkerFetchRequest(request.url, request.method,
- request.headers, request.referrer,
- request.is_reload));
- cache->Keys(std::move(request_ptr), match_params,
- base::BindOnce(&CacheStorageDispatcherHost::OnCacheKeysCallback,
- this, thread_id, request_id, it->second.Clone()));
-}
-
-void CacheStorageDispatcherHost::OnCacheBatch(
- int thread_id,
- int request_id,
- int cache_id,
- const std::vector<CacheStorageBatchOperation>& operations) {
- IDToCacheMap::iterator it = id_to_cache_map_.find(cache_id);
- if (it == id_to_cache_map_.end() || !it->second.value()) {
- Send(new CacheStorageMsg_CacheBatchError(
- thread_id, request_id, CacheStorageError::kErrorNotFound));
- return;
- }
-
- CacheStorageCache* cache = it->second.value();
- cache->BatchOperation(
- operations,
- base::BindOnce(&CacheStorageDispatcherHost::OnCacheBatchCallback, this,
- thread_id, request_id, it->second.Clone()),
- base::BindOnce(&CacheStorageDispatcherHost::OnBadMessage, this));
-}
-
-void CacheStorageDispatcherHost::OnCacheClosed(int cache_id) {
- DropCacheReference(cache_id);
-}
-
-void CacheStorageDispatcherHost::OnBlobDataHandled(const std::string& uuid) {
- DropBlobDataHandle(uuid);
+ std::move(scoped_request), std::move(match_params),
+ base::BindOnce(&CacheStorageDispatcherHost::OnMatchCallback, this,
+ std::move(callback)));
}
-void CacheStorageDispatcherHost::OnCacheStorageHasCallback(
- int thread_id,
- int request_id,
+void CacheStorageDispatcherHost::OnHasCallback(
+ blink::mojom::CacheStorage::HasCallback callback,
bool has_cache,
CacheStorageError error) {
- if (error != CacheStorageError::kSuccess) {
- Send(
- new CacheStorageMsg_CacheStorageHasError(thread_id, request_id, error));
- return;
- }
- if (!has_cache) {
- Send(new CacheStorageMsg_CacheStorageHasError(
- thread_id, request_id, CacheStorageError::kErrorNotFound));
- return;
- }
- Send(new CacheStorageMsg_CacheStorageHasSuccess(thread_id, request_id));
+ if (!has_cache)
+ error = CacheStorageError::kErrorNotFound;
+ std::move(callback).Run(error);
}
-void CacheStorageDispatcherHost::OnCacheStorageOpenCallback(
- int thread_id,
- int request_id,
+void CacheStorageDispatcherHost::OnOpenCallback(
+ url::Origin origin,
+ blink::mojom::CacheStorage::OpenCallback callback,
CacheStorageCacheHandle cache_handle,
CacheStorageError error) {
if (error != CacheStorageError::kSuccess) {
- Send(new CacheStorageMsg_CacheStorageOpenError(thread_id, request_id,
- error));
+ std::move(callback).Run(blink::mojom::OpenResult::NewStatus(error));
return;
}
@@ -341,174 +369,53 @@ void CacheStorageDispatcherHost::OnCacheStorageOpenCallback(
FROM_HERE, base::BindOnce(&StopPreservingCache, cache_handle.Clone()),
base::TimeDelta::FromSeconds(kCachePreservationSeconds));
- CacheID cache_id = StoreCacheReference(std::move(cache_handle));
- Send(new CacheStorageMsg_CacheStorageOpenSuccess(thread_id, request_id,
- cache_id));
-}
+ blink::mojom::CacheStorageCacheAssociatedPtrInfo ptr_info;
+ auto request = mojo::MakeRequest(&ptr_info);
+ auto cache_impl = std::make_unique<CacheImpl>(std::move(cache_handle), this);
+ cache_bindings_.AddBinding(std::move(cache_impl), std::move(request));
-void CacheStorageDispatcherHost::OnCacheStorageDeleteCallback(
- int thread_id,
- int request_id,
- bool deleted,
- CacheStorageError error) {
- if (!deleted || error != CacheStorageError::kSuccess) {
- Send(new CacheStorageMsg_CacheStorageDeleteError(thread_id, request_id,
- error));
- return;
- }
- Send(new CacheStorageMsg_CacheStorageDeleteSuccess(thread_id, request_id));
+ std::move(callback).Run(
+ blink::mojom::OpenResult::NewCache(std::move(ptr_info)));
}
-void CacheStorageDispatcherHost::OnCacheStorageKeysCallback(
- int thread_id,
- int request_id,
+void CacheStorageDispatcherHost::OnKeysCallback(
+ blink::mojom::CacheStorage::KeysCallback callback,
const CacheStorageIndex& cache_index) {
std::vector<base::string16> string16s;
- for (const auto& metadata : cache_index.ordered_cache_metadata())
+ for (const auto& metadata : cache_index.ordered_cache_metadata()) {
string16s.push_back(base::UTF8ToUTF16(metadata.name));
- Send(new CacheStorageMsg_CacheStorageKeysSuccess(thread_id, request_id,
- string16s));
-}
-
-void CacheStorageDispatcherHost::OnCacheStorageMatchCallback(
- int thread_id,
- int request_id,
- CacheStorageError error,
- std::unique_ptr<ServiceWorkerResponse> response,
- std::unique_ptr<storage::BlobDataHandle> blob_data_handle) {
- if (error != CacheStorageError::kSuccess) {
- Send(new CacheStorageMsg_CacheStorageMatchError(thread_id, request_id,
- error));
- return;
}
- if (blob_data_handle)
- StoreBlobDataHandle(*blob_data_handle);
-
- Send(new CacheStorageMsg_CacheStorageMatchSuccess(thread_id, request_id,
- *response));
+ std::move(callback).Run(string16s);
}
-void CacheStorageDispatcherHost::OnCacheMatchCallback(
- int thread_id,
- int request_id,
- CacheStorageCacheHandle cache_handle,
+void CacheStorageDispatcherHost::OnMatchCallback(
+ blink::mojom::CacheStorage::MatchCallback callback,
CacheStorageError error,
- std::unique_ptr<ServiceWorkerResponse> response,
- std::unique_ptr<storage::BlobDataHandle> blob_data_handle) {
+ std::unique_ptr<ServiceWorkerResponse> response) {
if (error != CacheStorageError::kSuccess) {
- Send(new CacheStorageMsg_CacheMatchError(thread_id, request_id, error));
- return;
- }
-
- if (blob_data_handle)
- StoreBlobDataHandle(*blob_data_handle);
-
- Send(new CacheStorageMsg_CacheMatchSuccess(thread_id, request_id, *response));
-}
-
-void CacheStorageDispatcherHost::OnCacheMatchAllCallbackAdapter(
- int thread_id,
- int request_id,
- CacheStorageCacheHandle cache_handle,
- CacheStorageError error,
- std::unique_ptr<ServiceWorkerResponse> response,
- std::unique_ptr<storage::BlobDataHandle> blob_data_handle) {
- std::vector<ServiceWorkerResponse> responses;
- std::unique_ptr<CacheStorageCache::BlobDataHandles> blob_data_handles(
- new CacheStorageCache::BlobDataHandles);
- if (error == CacheStorageError::kSuccess) {
- DCHECK(response);
- responses.push_back(*response);
- if (blob_data_handle)
- blob_data_handles->push_back(std::move(blob_data_handle));
- }
- OnCacheMatchAllCallback(thread_id, request_id, std::move(cache_handle), error,
- std::move(responses), std::move(blob_data_handles));
-}
-
-void CacheStorageDispatcherHost::OnCacheMatchAllCallback(
- int thread_id,
- int request_id,
- CacheStorageCacheHandle cache_handle,
- CacheStorageError error,
- std::vector<ServiceWorkerResponse> responses,
- std::unique_ptr<CacheStorageCache::BlobDataHandles> blob_data_handles) {
- if (error != CacheStorageError::kSuccess &&
- error != CacheStorageError::kErrorNotFound) {
- Send(new CacheStorageMsg_CacheMatchAllError(thread_id, request_id, error));
+ std::move(callback).Run(blink::mojom::MatchResult::NewStatus(error));
return;
}
- for (const auto& handle : *blob_data_handles) {
- if (handle)
- StoreBlobDataHandle(*handle);
- }
-
- Send(new CacheStorageMsg_CacheMatchAllSuccess(thread_id, request_id,
- responses));
+ std::move(callback).Run(
+ blink::mojom::MatchResult::NewResponse(std::move(*response)));
}
-void CacheStorageDispatcherHost::OnCacheKeysCallback(
- int thread_id,
- int request_id,
- CacheStorageCacheHandle cache_handle,
- CacheStorageError error,
- std::unique_ptr<CacheStorageCache::Requests> requests) {
- if (error != CacheStorageError::kSuccess) {
- Send(new CacheStorageMsg_CacheKeysError(thread_id, request_id, error));
- return;
- }
-
- Send(new CacheStorageMsg_CacheKeysSuccess(thread_id, request_id, *requests));
+void CacheStorageDispatcherHost::AddBinding(
+ blink::mojom::CacheStorageRequest request,
+ const url::Origin& origin) {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+ bindings_.AddBinding(this, std::move(request), origin);
}
-void CacheStorageDispatcherHost::OnCacheBatchCallback(
- int thread_id,
- int request_id,
- CacheStorageCacheHandle cache_handle,
- CacheStorageError error) {
- if (error != CacheStorageError::kSuccess) {
- Send(new CacheStorageMsg_CacheBatchError(thread_id, request_id, error));
- return;
+bool CacheStorageDispatcherHost::ValidState() {
+ // cache_manager() can return nullptr when process is shutting down.
+ if (!(context_ && context_->cache_manager())) {
+ bindings_.CloseAllBindings();
+ return false;
}
-
- Send(new CacheStorageMsg_CacheBatchSuccess(thread_id, request_id));
-}
-
-void CacheStorageDispatcherHost::OnBadMessage(
- bad_message::BadMessageReason reason) {
- bad_message::ReceivedBadMessage(this, reason);
-}
-
-CacheStorageDispatcherHost::CacheID
-CacheStorageDispatcherHost::StoreCacheReference(
- CacheStorageCacheHandle cache_handle) {
- int cache_id = next_cache_id_++;
- id_to_cache_map_[cache_id] = std::move(cache_handle);
- return cache_id;
-}
-
-void CacheStorageDispatcherHost::DropCacheReference(CacheID cache_id) {
- id_to_cache_map_.erase(cache_id);
-}
-
-void CacheStorageDispatcherHost::StoreBlobDataHandle(
- const storage::BlobDataHandle& blob_data_handle) {
- std::pair<UUIDToBlobDataHandleList::iterator, bool> rv =
- blob_handle_store_.insert(std::make_pair(
- blob_data_handle.uuid(), std::list<storage::BlobDataHandle>()));
- rv.first->second.push_front(storage::BlobDataHandle(blob_data_handle));
-}
-
-void CacheStorageDispatcherHost::DropBlobDataHandle(const std::string& uuid) {
- UUIDToBlobDataHandleList::iterator it = blob_handle_store_.find(uuid);
- if (it == blob_handle_store_.end())
- return;
- DCHECK(!it->second.empty());
- it->second.pop_front();
- if (it->second.empty())
- blob_handle_store_.erase(it);
+ return true;
}
} // namespace content
diff --git a/chromium/content/browser/cache_storage/cache_storage_dispatcher_host.h b/chromium/content/browser/cache_storage/cache_storage_dispatcher_host.h
index 459a6ee7d5f..3dde6c6d6a6 100644
--- a/chromium/content/browser/cache_storage/cache_storage_dispatcher_host.h
+++ b/chromium/content/browser/cache_storage/cache_storage_dispatcher_host.h
@@ -14,10 +14,12 @@
#include <vector>
#include "base/macros.h"
-#include "content/browser/bad_message.h"
#include "content/browser/cache_storage/cache_storage.h"
#include "content/browser/cache_storage/cache_storage_index.h"
-#include "content/public/browser/browser_message_filter.h"
+#include "content/public/browser/browser_thread.h"
+#include "mojo/public/cpp/bindings/associated_binding_set.h"
+#include "mojo/public/cpp/bindings/strong_associated_binding_set.h"
+#include "mojo/public/cpp/bindings/strong_binding_set.h"
namespace url {
class Origin;
@@ -30,153 +32,74 @@ class CacheStorageContextImpl;
// Handles Cache Storage related messages sent to the browser process from
// child processes. One host instance exists per child process. All
// messages are processed on the IO thread.
-class CONTENT_EXPORT CacheStorageDispatcherHost : public BrowserMessageFilter {
+class CONTENT_EXPORT CacheStorageDispatcherHost
+ : public base::RefCountedThreadSafe<CacheStorageDispatcherHost,
+ BrowserThread::DeleteOnIOThread>,
+ public blink::mojom::CacheStorage {
public:
CacheStorageDispatcherHost();
// Runs on UI thread.
void Init(CacheStorageContextImpl* context);
- // BrowserMessageFilter implementation
- void OnDestruct() const override;
- bool OnMessageReceived(const IPC::Message& message) override;
+ // Binds Mojo request to this instance, must be called on IO thread.
+ // NOTE: The same CacheStorageDispatcherHost instance may be bound to
+ // different clients on different origins. Each context is kept on
+ // BindingSet's context. This guarantees that the browser process uses the
+ // origin of the client known at the binding time, instead of relying on the
+ // client to provide its origin at every method call.
+ void AddBinding(blink::mojom::CacheStorageRequest request,
+ const url::Origin& origin);
private:
- // Friends to allow OnDestruct() delegation
- friend class BrowserThread;
+ // Friends to allow BrowserThread::DeleteOnIOThread delegation.
+ friend struct BrowserThread::DeleteOnThread<BrowserThread::IO>;
friend class base::DeleteHelper<CacheStorageDispatcherHost>;
- typedef int32_t CacheID; // TODO(jkarlin): Bump to 64 bit.
- typedef std::map<CacheID, CacheStorageCacheHandle> IDToCacheMap;
- typedef std::map<std::string, std::list<storage::BlobDataHandle>>
- UUIDToBlobDataHandleList;
+ class CacheImpl;
~CacheStorageDispatcherHost() override;
// Called by Init() on IO thread.
void CreateCacheListener(CacheStorageContextImpl* context);
- // The message receiver functions for the CacheStorage API:
- void OnCacheStorageHas(int thread_id,
- int request_id,
- const url::Origin& origin,
- const base::string16& cache_name);
- void OnCacheStorageOpen(int thread_id,
- int request_id,
- const url::Origin& origin,
- const base::string16& cache_name);
- void OnCacheStorageDelete(int thread_id,
- int request_id,
- const url::Origin& origin,
- const base::string16& cache_name);
- void OnCacheStorageKeys(int thread_id,
- int request_id,
- const url::Origin& origin);
- void OnCacheStorageMatch(int thread_id,
- int request_id,
- const url::Origin& origin,
- const ServiceWorkerFetchRequest& request,
- const CacheStorageCacheQueryParams& match_params);
-
- // The message receiver functions for the Cache API:
- void OnCacheMatch(int thread_id,
- int request_id,
- int cache_id,
- const ServiceWorkerFetchRequest& request,
- const CacheStorageCacheQueryParams& match_params);
- void OnCacheKeys(int thread_id,
- int request_id,
- int cache_id,
- const ServiceWorkerFetchRequest& request,
- const CacheStorageCacheQueryParams& match_params);
- void OnCacheBatch(int thread_id,
- int request_id,
- int cache_id,
- const std::vector<CacheStorageBatchOperation>& operations);
- void OnCacheClosed(int cache_id);
- void OnBlobDataHandled(const std::string& uuid);
-
- // CacheStorageManager callbacks
- void OnCacheStorageHasCallback(int thread_id,
- int request_id,
- bool has_cache,
- blink::mojom::CacheStorageError error);
- void OnCacheStorageOpenCallback(int thread_id,
- int request_id,
- CacheStorageCacheHandle cache_handle,
- blink::mojom::CacheStorageError error);
- void OnCacheStorageDeleteCallback(int thread_id,
- int request_id,
- bool deleted,
- blink::mojom::CacheStorageError error);
- void OnCacheStorageKeysCallback(int thread_id,
- int request_id,
- const CacheStorageIndex& cache_index);
- void OnCacheStorageMatchCallback(
- int thread_id,
- int request_id,
- blink::mojom::CacheStorageError error,
- std::unique_ptr<ServiceWorkerResponse> response,
- std::unique_ptr<storage::BlobDataHandle> blob_data_handle);
-
- // Cache callbacks.
- void OnCacheMatchCallback(
- int thread_id,
- int request_id,
- CacheStorageCacheHandle cache_handle,
- blink::mojom::CacheStorageError error,
- std::unique_ptr<ServiceWorkerResponse> response,
- std::unique_ptr<storage::BlobDataHandle> blob_data_handle);
- void OnCacheMatchAllCallbackAdapter(
- int thread_id,
- int request_id,
- CacheStorageCacheHandle cache_handle,
- blink::mojom::CacheStorageError error,
- std::unique_ptr<ServiceWorkerResponse> response,
- std::unique_ptr<storage::BlobDataHandle> blob_data_handle);
- void OnCacheMatchAllCallback(
- int thread_id,
- int request_id,
- CacheStorageCacheHandle cache_handle,
- blink::mojom::CacheStorageError error,
- std::vector<ServiceWorkerResponse> responses,
- std::unique_ptr<CacheStorageCache::BlobDataHandles> blob_data_handles);
- void OnCacheMatchAll(int thread_id,
- int request_id,
- int cache_id,
- const ServiceWorkerFetchRequest& request,
- const CacheStorageCacheQueryParams& match_params);
- void OnCacheKeysCallback(
- int thread_id,
- int request_id,
- CacheStorageCacheHandle cache_handle,
- blink::mojom::CacheStorageError error,
- std::unique_ptr<CacheStorageCache::Requests> requests);
- void OnCacheBatchCallback(int thread_id,
- int request_id,
- CacheStorageCacheHandle cache_handle,
- blink::mojom::CacheStorageError error);
-
- // Called when a bad message is detected while executing operations.
- void OnBadMessage(bad_message::BadMessageReason reason);
-
- // Hangs onto a cache handle. Returns a unique cache_id. Call
- // DropCacheReference when the reference is no longer needed.
- CacheID StoreCacheReference(CacheStorageCacheHandle cache_handle);
- void DropCacheReference(CacheID cache_id);
-
- // Stores blob handles while waiting for acknowledgement of receipt from the
- // renderer.
- void StoreBlobDataHandle(const storage::BlobDataHandle& blob_data_handle);
- void DropBlobDataHandle(const std::string& uuid);
-
- IDToCacheMap id_to_cache_map_;
- CacheID next_cache_id_ = 0;
-
- UUIDToBlobDataHandleList blob_handle_store_;
+ // Mojo CacheStorage Interface implementation:
+ void Keys(blink::mojom::CacheStorage::KeysCallback callback) override;
+ void Delete(const base::string16& cache_name,
+ blink::mojom::CacheStorage::DeleteCallback callback) override;
+ void Has(const base::string16& cache_name,
+ blink::mojom::CacheStorage::HasCallback callback) override;
+ void Match(const content::ServiceWorkerFetchRequest& request,
+ const content::CacheStorageCacheQueryParams& match_params,
+ blink::mojom::CacheStorage::MatchCallback callback) override;
+ void Open(const base::string16& cache_name,
+ blink::mojom::CacheStorage::OpenCallback callback) override;
+
+ // Callbacks used by Mojo implementation:
+ void OnKeysCallback(KeysCallback callback,
+ const CacheStorageIndex& cache_index);
+ void OnHasCallback(blink::mojom::CacheStorage::HasCallback callback,
+ bool has_cache,
+ blink::mojom::CacheStorageError error);
+ void OnMatchCallback(blink::mojom::CacheStorage::MatchCallback callback,
+ blink::mojom::CacheStorageError error,
+ std::unique_ptr<ServiceWorkerResponse> response);
+ void OnOpenCallback(url::Origin origin,
+ blink::mojom::CacheStorage::OpenCallback callback,
+ CacheStorageCacheHandle cache_handle,
+ blink::mojom::CacheStorageError error);
+
+ // Validate the current state of required members, returns false if they
+ // aren't valid and also close |bindings_|, so it's safe to not run
+ // mojo callbacks.
+ bool ValidState();
scoped_refptr<CacheStorageContextImpl> context_;
+ mojo::BindingSet<blink::mojom::CacheStorage, url::Origin> bindings_;
+ mojo::StrongAssociatedBindingSet<blink::mojom::CacheStorageCache>
+ cache_bindings_;
+
DISALLOW_COPY_AND_ASSIGN(CacheStorageDispatcherHost);
};
diff --git a/chromium/content/browser/cache_storage/cache_storage_manager.cc b/chromium/content/browser/cache_storage/cache_storage_manager.cc
index 7b21aa82a69..d87786e203f 100644
--- a/chromium/content/browser/cache_storage/cache_storage_manager.cc
+++ b/chromium/content/browser/cache_storage/cache_storage_manager.cc
@@ -31,7 +31,7 @@
#include "net/base/url_util.h"
#include "storage/browser/quota/quota_manager_proxy.h"
#include "storage/common/database/database_identifier.h"
-#include "third_party/WebKit/public/mojom/quota/quota_types.mojom.h"
+#include "third_party/blink/public/mojom/quota/quota_types.mojom.h"
#include "url/gurl.h"
#include "url/origin.h"
@@ -196,10 +196,9 @@ void CacheStorageManager::HasCache(
cache_storage->HasCache(cache_name, std::move(callback));
}
-void CacheStorageManager::DeleteCache(
- const url::Origin& origin,
- const std::string& cache_name,
- CacheStorage::BoolAndErrorCallback callback) {
+void CacheStorageManager::DeleteCache(const url::Origin& origin,
+ const std::string& cache_name,
+ CacheStorage::ErrorCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
CacheStorage* cache_storage = FindOrCreateCacheStorage(origin);
diff --git a/chromium/content/browser/cache_storage/cache_storage_manager.h b/chromium/content/browser/cache_storage/cache_storage_manager.h
index 265c60785a4..f053d4c1dbd 100644
--- a/chromium/content/browser/cache_storage/cache_storage_manager.h
+++ b/chromium/content/browser/cache_storage/cache_storage_manager.h
@@ -69,7 +69,7 @@ class CONTENT_EXPORT CacheStorageManager {
CacheStorage::BoolAndErrorCallback callback);
void DeleteCache(const url::Origin& origin,
const std::string& cache_name,
- CacheStorage::BoolAndErrorCallback callback);
+ CacheStorage::ErrorCallback callback);
void EnumerateCaches(const url::Origin& origin,
CacheStorage::IndexCallback callback);
void MatchCache(const url::Origin& origin,
diff --git a/chromium/content/browser/cache_storage/cache_storage_manager_unittest.cc b/chromium/content/browser/cache_storage/cache_storage_manager_unittest.cc
index b1d0b769fc4..2ccc79e2a13 100644
--- a/chromium/content/browser/cache_storage/cache_storage_manager_unittest.cc
+++ b/chromium/content/browser/cache_storage/cache_storage_manager_unittest.cc
@@ -52,7 +52,7 @@
#include "storage/browser/test/mock_special_storage_policy.h"
#include "storage/common/blob_storage/blob_handle.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/modules/cache_storage/cache_storage.mojom.h"
+#include "third_party/blink/public/platform/modules/cache_storage/cache_storage.mojom.h"
#include "url/origin.h"
using blink::mojom::CacheStorageError;
@@ -145,6 +145,12 @@ class CacheStorageManagerTest : public testing::Test {
run_loop->Quit();
}
+ void ErrorCallback(base::RunLoop* run_loop, CacheStorageError error) {
+ callback_error_ = error;
+ callback_bool_ = error == CacheStorageError::kSuccess;
+ run_loop->Quit();
+ }
+
void BoolAndErrorCallback(base::RunLoop* run_loop,
bool value,
CacheStorageError error) {
@@ -189,14 +195,11 @@ class CacheStorageManagerTest : public testing::Test {
run_loop->Quit();
}
- void CacheMatchCallback(
- base::RunLoop* run_loop,
- CacheStorageError error,
- std::unique_ptr<ServiceWorkerResponse> response,
- std::unique_ptr<storage::BlobDataHandle> blob_data_handle) {
+ void CacheMatchCallback(base::RunLoop* run_loop,
+ CacheStorageError error,
+ std::unique_ptr<ServiceWorkerResponse> response) {
callback_error_ = error;
callback_cache_handle_response_ = std::move(response);
- callback_data_handle_ = std::move(blob_data_handle);
run_loop->Quit();
}
@@ -263,7 +266,6 @@ class CacheStorageManagerTest : public testing::Test {
callback_cache_handle_ = CacheStorageCacheHandle();
callback_bool_ = false;
callback_cache_handle_response_ = nullptr;
- callback_data_handle_ = nullptr;
callback_cache_index_ = CacheStorageIndex();
callback_all_origins_usage_.clear();
@@ -310,7 +312,7 @@ class CacheStorageManagerTest : public testing::Test {
base::RunLoop loop;
cache_manager_->DeleteCache(
origin, cache_name,
- base::BindOnce(&CacheStorageManagerTest::BoolAndErrorCallback,
+ base::BindOnce(&CacheStorageManagerTest::ErrorCallback,
base::Unretained(this), base::Unretained(&loop)));
loop.Run();
@@ -544,8 +546,9 @@ class CacheStorageManagerTest : public testing::Test {
quota_manager_proxy_->GetUsageAndQuota(
base::ThreadTaskRunnerHandle::Get().get(), origin,
StorageType::kTemporary,
- base::Bind(&CacheStorageManagerTest::DidGetQuotaOriginUsage,
- base::Unretained(this), base::Unretained(&usage), &loop));
+ base::BindOnce(&CacheStorageManagerTest::DidGetQuotaOriginUsage,
+ base::Unretained(this), base::Unretained(&usage),
+ &loop));
loop.Run();
return usage;
}
diff --git a/chromium/content/browser/cache_storage/cache_storage_operation_unittest.cc b/chromium/content/browser/cache_storage/cache_storage_operation_unittest.cc
index 792f324ba1a..b1bd4a25961 100644
--- a/chromium/content/browser/cache_storage/cache_storage_operation_unittest.cc
+++ b/chromium/content/browser/cache_storage/cache_storage_operation_unittest.cc
@@ -6,7 +6,6 @@
#include "base/bind.h"
#include "base/callback.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/run_loop.h"
#include "base/test/histogram_tester.h"
diff --git a/chromium/content/browser/cache_storage/cache_storage_quota_client.cc b/chromium/content/browser/cache_storage/cache_storage_quota_client.cc
index 1217fc5e588..1eea5a76e35 100644
--- a/chromium/content/browser/cache_storage/cache_storage_quota_client.cc
+++ b/chromium/content/browser/cache_storage/cache_storage_quota_client.cc
@@ -6,7 +6,7 @@
#include "content/browser/cache_storage/cache_storage_manager.h"
#include "content/public/browser/browser_thread.h"
-#include "third_party/WebKit/public/mojom/quota/quota_types.mojom.h"
+#include "third_party/blink/public/mojom/quota/quota_types.mojom.h"
#include "url/origin.h"
namespace content {
diff --git a/chromium/content/browser/cache_storage/cache_storage_quota_client.h b/chromium/content/browser/cache_storage/cache_storage_quota_client.h
index 1089395791d..6eab4ce0324 100644
--- a/chromium/content/browser/cache_storage/cache_storage_quota_client.h
+++ b/chromium/content/browser/cache_storage/cache_storage_quota_client.h
@@ -9,7 +9,7 @@
#include "base/memory/weak_ptr.h"
#include "content/common/content_export.h"
#include "storage/browser/quota/quota_client.h"
-#include "third_party/WebKit/public/mojom/quota/quota_types.mojom.h"
+#include "third_party/blink/public/mojom/quota/quota_types.mojom.h"
#include "url/origin.h"
namespace content {
diff --git a/chromium/content/browser/cache_storage/cache_storage_scheduler.cc b/chromium/content/browser/cache_storage/cache_storage_scheduler.cc
index 759fd61c92b..d28492ff53d 100644
--- a/chromium/content/browser/cache_storage/cache_storage_scheduler.cc
+++ b/chromium/content/browser/cache_storage/cache_storage_scheduler.cc
@@ -9,7 +9,6 @@
#include "base/bind.h"
#include "base/location.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
diff --git a/chromium/content/browser/child_process_launcher.cc b/chromium/content/browser/child_process_launcher.cc
index c924922e9eb..fcc37f21745 100644
--- a/chromium/content/browser/child_process_launcher.cc
+++ b/chromium/content/browser/child_process_launcher.cc
@@ -11,6 +11,7 @@
#include "base/logging.h"
#include "base/process/launch.h"
#include "build/build_config.h"
+#include "content/public/browser/child_process_launcher_utils.h"
#include "content/public/common/result_codes.h"
#include "content/public/common/sandboxed_process_launcher_delegate.h"
@@ -62,8 +63,8 @@ void ChildProcessLauncher::SetProcessPriority(
const ChildProcessLauncherPriority& priority) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
base::Process to_pass = process_.process.Duplicate();
- BrowserThread::PostTask(
- BrowserThread::PROCESS_LAUNCHER, FROM_HERE,
+ GetProcessLauncherTaskRunner()->PostTask(
+ FROM_HERE,
base::BindOnce(
&ChildProcessLauncherHelper::SetProcessPriorityOnLauncherThread,
helper_, std::move(to_pass), priority));
@@ -102,8 +103,14 @@ base::TerminationStatus ChildProcessLauncher::GetChildTerminationStatus(
bool known_dead,
int* exit_code) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
+
if (!process_.process.IsValid()) {
- // Process is already gone, so return the cached termination status.
+ // Make sure to avoid using the default termination status if the process
+ // hasn't even started yet.
+ if (IsStarting())
+ termination_status_ = base::TERMINATION_STATUS_STILL_RUNNING;
+
+ // Process doesn't exist, so return the cached termination status.
if (exit_code)
*exit_code = exit_code_;
return termination_status_;
@@ -128,17 +135,16 @@ base::TerminationStatus ChildProcessLauncher::GetChildTerminationStatus(
return termination_status_;
}
-bool ChildProcessLauncher::Terminate(int exit_code, bool wait) {
+bool ChildProcessLauncher::Terminate(int exit_code) {
return IsStarting() ? false
: ChildProcessLauncherHelper::TerminateProcess(
- GetProcess(), exit_code, wait);
+ GetProcess(), exit_code);
}
// static
bool ChildProcessLauncher::TerminateProcess(const base::Process& process,
- int exit_code,
- bool wait) {
- return ChildProcessLauncherHelper::TerminateProcess(process, exit_code, wait);
+ int exit_code) {
+ return ChildProcessLauncherHelper::TerminateProcess(process, exit_code);
}
// static
@@ -170,7 +176,7 @@ ChildProcessLauncher::Client* ChildProcessLauncher::ReplaceClientForTest(
bool ChildProcessLauncherPriority::operator==(
const ChildProcessLauncherPriority& other) const {
- return background == other.background &&
+ return background == other.background && frame_depth == other.frame_depth &&
boost_for_pending_views == other.boost_for_pending_views
#if defined(OS_ANDROID)
&& importance == other.importance
diff --git a/chromium/content/browser/child_process_launcher.h b/chromium/content/browser/child_process_launcher.h
index 7763d0c2860..c9d243c37ea 100644
--- a/chromium/content/browser/child_process_launcher.h
+++ b/chromium/content/browser/child_process_launcher.h
@@ -55,6 +55,7 @@ static_assert(static_cast<int>(LAUNCH_RESULT_START) >
struct ChildProcessLauncherPriority {
bool background;
+ unsigned int frame_depth;
bool boost_for_pending_views;
#if defined(OS_ANDROID)
ChildProcessImportance importance;
@@ -130,15 +131,13 @@ class CONTENT_EXPORT ChildProcessLauncher {
// Terminates the process associated with this ChildProcessLauncher.
// Returns true if the process was stopped, false if the process had not been
// started yet or could not be stopped.
- // Note that |exit_code| and |wait| are not used on Android.
- bool Terminate(int exit_code, bool wait);
+ // Note that |exit_code| is not used on Android.
+ bool Terminate(int exit_code);
// Similar to Terminate() but takes in a |process|.
// On Android |process| must have been started by ChildProcessLauncher for
// this method to work.
- static bool TerminateProcess(const base::Process& process,
- int exit_code,
- bool wait);
+ static bool TerminateProcess(const base::Process& process, int exit_code);
// Replaces the ChildProcessLauncher::Client for testing purposes. Returns the
// previous client.
diff --git a/chromium/content/browser/child_process_launcher_helper.cc b/chromium/content/browser/child_process_launcher_helper.cc
index 7ee3df4cfd6..b9ad8d7ed5e 100644
--- a/chromium/content/browser/child_process_launcher_helper.cc
+++ b/chromium/content/browser/child_process_launcher_helper.cc
@@ -6,18 +6,29 @@
#include "base/command_line.h"
#include "base/metrics/histogram_macros.h"
+#include "base/no_destructor.h"
+#include "base/single_thread_task_runner.h"
+#include "base/task_scheduler/lazy_task_runner.h"
+#include "base/task_scheduler/post_task.h"
+#include "base/task_scheduler/single_thread_task_runner_thread_mode.h"
+#include "base/task_scheduler/task_traits.h"
#include "content/browser/child_process_launcher.h"
+#include "content/public/browser/child_process_launcher_utils.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/sandboxed_process_launcher_delegate.h"
#include "mojo/edk/embedder/platform_channel_pair.h"
+#if defined(OS_ANDROID)
+#include "content/browser/android/launcher_thread.h"
+#endif
+
namespace content {
namespace internal {
namespace {
void RecordHistogramsOnLauncherThread(base::TimeDelta launch_time) {
- DCHECK_CURRENTLY_ON(BrowserThread::PROCESS_LAUNCHER);
+ DCHECK(CurrentlyOnProcessLauncherTaskRunner());
// Log the launch time, separating out the first one (which will likely be
// slower due to the rest of the browser initializing at the same time).
static bool done_first_launch = false;
@@ -85,14 +96,14 @@ void ChildProcessLauncherHelper::StartLaunchOnClientThread() {
mojo_client_handle_ = channel_pair.PassClientHandle();
}
- BrowserThread::PostTask(
- BrowserThread::PROCESS_LAUNCHER, FROM_HERE,
+ GetProcessLauncherTaskRunner()->PostTask(
+ FROM_HERE,
base::BindOnce(&ChildProcessLauncherHelper::LaunchOnLauncherThread,
this));
}
void ChildProcessLauncherHelper::LaunchOnLauncherThread() {
- DCHECK_CURRENTLY_ON(BrowserThread::PROCESS_LAUNCHER);
+ DCHECK(CurrentlyOnProcessLauncherTaskRunner());
begin_launch_time_ = base::TimeTicks::Now();
@@ -167,18 +178,51 @@ std::string ChildProcessLauncherHelper::GetProcessType() {
// static
void ChildProcessLauncherHelper::ForceNormalProcessTerminationAsync(
ChildProcessLauncherHelper::Process process) {
- if (BrowserThread::CurrentlyOn(BrowserThread::PROCESS_LAUNCHER)) {
+ if (CurrentlyOnProcessLauncherTaskRunner()) {
ForceNormalProcessTerminationSync(std::move(process));
return;
}
// On Posix, EnsureProcessTerminated can lead to 2 seconds of sleep!
// So don't do this on the UI/IO threads.
- BrowserThread::PostTask(
- BrowserThread::PROCESS_LAUNCHER, FROM_HERE,
+ GetProcessLauncherTaskRunner()->PostTask(
+ FROM_HERE,
base::BindOnce(
&ChildProcessLauncherHelper::ForceNormalProcessTerminationSync,
std::move(process)));
}
} // namespace internal
+
+// static
+base::SingleThreadTaskRunner* GetProcessLauncherTaskRunner() {
+#if defined(OS_ANDROID)
+ // Android specializes Launcher thread so it is accessible in java.
+ // Note Android never does clean shutdown, so shutdown use-after-free
+ // concerns are not a problem in practice.
+ // This process launcher thread will use the Java-side process-launching
+ // thread, instead of creating its own separate thread on C++ side. Note
+ // that means this thread will not be joined on shutdown, and may cause
+ // use-after-free if anything tries to access objects deleted by
+ // AtExitManager, such as non-leaky LazyInstance.
+ static base::NoDestructor<scoped_refptr<base::SingleThreadTaskRunner>>
+ launcher_task_runner(
+ android::LauncherThread::GetMessageLoop()->task_runner());
+ return (*launcher_task_runner).get();
+#else // defined(OS_ANDROID)
+ // TODO(http://crbug.com/820200): Investigate whether we could use
+ // SequencedTaskRunner on platforms other than Windows.
+ static base::LazySingleThreadTaskRunner launcher_task_runner =
+ LAZY_SINGLE_THREAD_TASK_RUNNER_INITIALIZER(
+ base::TaskTraits({base::MayBlock(), base::TaskPriority::USER_BLOCKING,
+ base::TaskShutdownBehavior::BLOCK_SHUTDOWN}),
+ base::SingleThreadTaskRunnerThreadMode::DEDICATED);
+ return launcher_task_runner.Get().get();
+#endif // defined(OS_ANDROID)
+}
+
+// static
+bool CurrentlyOnProcessLauncherTaskRunner() {
+ return GetProcessLauncherTaskRunner()->RunsTasksInCurrentSequence();
+}
+
} // namespace content
diff --git a/chromium/content/browser/child_process_launcher_helper.h b/chromium/content/browser/child_process_launcher_helper.h
index 2dac50fc450..b9b7a82652b 100644
--- a/chromium/content/browser/child_process_launcher_helper.h
+++ b/chromium/content/browser/child_process_launcher_helper.h
@@ -14,7 +14,7 @@
#include "build/build_config.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/result_codes.h"
-#include "content/public/common/zygote_features.h"
+#include "content/public/common/zygote_buildflags.h"
#include "mojo/edk/embedder/embedder.h"
#include "mojo/edk/embedder/outgoing_broker_client_invitation.h"
#include "mojo/edk/embedder/scoped_platform_handle.h"
@@ -156,10 +156,8 @@ class ChildProcessLauncherHelper :
// Terminates |process|.
// Returns true if the process was stopped, false if the process had not been
// started yet or could not be stopped.
- // Note that |exit_code| and |wait| are not used on Android.
- static bool TerminateProcess(const base::Process& process,
- int exit_code,
- bool wait);
+ // Note that |exit_code| is not used on Android.
+ static bool TerminateProcess(const base::Process& process, int exit_code);
// Terminates the process with the normal exit code and ensures it has been
// stopped. By returning a normal exit code this ensures UMA won't treat this
diff --git a/chromium/content/browser/child_process_launcher_helper_android.cc b/chromium/content/browser/child_process_launcher_helper_android.cc
index 989018e9917..1954e362d8c 100644
--- a/chromium/content/browser/child_process_launcher_helper_android.cc
+++ b/chromium/content/browser/child_process_launcher_helper_android.cc
@@ -15,6 +15,7 @@
#include "content/browser/posix_file_descriptor_info_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/browser/browser_thread.h"
+#include "content/public/browser/child_process_launcher_utils.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_descriptors.h"
#include "content/public/common/content_switches.h"
@@ -32,7 +33,7 @@ namespace {
// Stops a child process based on the handle returned from StartChildProcess.
void StopChildProcess(base::ProcessHandle handle) {
- DCHECK_CURRENTLY_ON(BrowserThread::PROCESS_LAUNCHER);
+ DCHECK(CurrentlyOnProcessLauncherTaskRunner());
JNIEnv* env = AttachCurrentThread();
DCHECK(env);
Java_ChildProcessLauncherHelper_stop(env, static_cast<jint>(handle));
@@ -64,7 +65,7 @@ ChildProcessLauncherHelper::PrepareMojoPipeHandlesOnClientThread() {
std::unique_ptr<PosixFileDescriptorInfo>
ChildProcessLauncherHelper::GetFilesToMap() {
- DCHECK_CURRENTLY_ON(BrowserThread::PROCESS_LAUNCHER);
+ DCHECK(CurrentlyOnProcessLauncherTaskRunner());
// Android WebView runs in single process, ensure that we never get here when
// running in single process mode.
@@ -156,21 +157,23 @@ base::TerminationStatus ChildProcessLauncherHelper::GetTerminationStatus(
java_peer_)) {
return base::TERMINATION_STATUS_OOM_PROTECTED;
}
- return base::GetTerminationStatus(process.process.Handle(), exit_code);
+ // Note waitpid does not work on Android since these are not actually child
+ // processes. So there is no need for base::GetTerminationStatus.
+ return base::TERMINATION_STATUS_NORMAL_TERMINATION;
}
// static
-bool ChildProcessLauncherHelper::TerminateProcess(
- const base::Process& process, int exit_code, bool wait) {
- BrowserThread::PostTask(BrowserThread::PROCESS_LAUNCHER, FROM_HERE,
- base::Bind(&StopChildProcess, process.Handle()));
+bool ChildProcessLauncherHelper::TerminateProcess(const base::Process& process,
+ int exit_code) {
+ GetProcessLauncherTaskRunner()->PostTask(
+ FROM_HERE, base::BindOnce(&StopChildProcess, process.Handle()));
return true;
}
// static
void ChildProcessLauncherHelper::ForceNormalProcessTerminationSync(
ChildProcessLauncherHelper::Process process) {
- DCHECK_CURRENTLY_ON(BrowserThread::PROCESS_LAUNCHER);
+ DCHECK(CurrentlyOnProcessLauncherTaskRunner());
VLOG(1) << "ChromeProcess: Stopping process with handle "
<< process.process.Handle();
StopChildProcess(process.process.Handle());
@@ -183,7 +186,8 @@ void ChildProcessLauncherHelper::SetProcessPriorityOnLauncherThread(
DCHECK(env);
return Java_ChildProcessLauncherHelper_setPriority(
env, java_peer_, process.Handle(), !priority.background,
- priority.boost_for_pending_views, static_cast<jint>(priority.importance));
+ priority.frame_depth, priority.boost_for_pending_views,
+ static_cast<jint>(priority.importance));
}
// static
@@ -211,7 +215,7 @@ void ChildProcessLauncherHelper::OnChildProcessStarted(
JNIEnv*,
const base::android::JavaParamRef<jobject>& obj,
jint handle) {
- DCHECK_CURRENTLY_ON(BrowserThread::PROCESS_LAUNCHER);
+ DCHECK(CurrentlyOnProcessLauncherTaskRunner());
scoped_refptr<ChildProcessLauncherHelper> ref(this);
Release(); // Balances with LaunchProcessOnLauncherThread.
diff --git a/chromium/content/browser/child_process_launcher_helper_fuchsia.cc b/chromium/content/browser/child_process_launcher_helper_fuchsia.cc
index 6d5e6cacb3e..281f4609d10 100644
--- a/chromium/content/browser/child_process_launcher_helper_fuchsia.cc
+++ b/chromium/content/browser/child_process_launcher_helper_fuchsia.cc
@@ -8,6 +8,7 @@
#include "base/process/launch.h"
#include "content/browser/child_process_launcher.h"
#include "content/common/sandbox_policy_fuchsia.h"
+#include "content/public/browser/child_process_launcher_utils.h"
#include "content/public/common/sandboxed_process_launcher_delegate.h"
#include "mojo/edk/embedder/platform_channel_pair.h"
@@ -17,7 +18,7 @@ namespace internal {
void ChildProcessLauncherHelper::SetProcessPriorityOnLauncherThread(
base::Process process,
const ChildProcessLauncherPriority& priority) {
- DCHECK_CURRENTLY_ON(BrowserThread::PROCESS_LAUNCHER);
+ DCHECK(CurrentlyOnProcessLauncherTaskRunner());
// TODO(fuchsia): Implement this. (crbug.com/707031)
NOTIMPLEMENTED();
}
@@ -31,9 +32,8 @@ base::TerminationStatus ChildProcessLauncherHelper::GetTerminationStatus(
// static
bool ChildProcessLauncherHelper::TerminateProcess(const base::Process& process,
- int exit_code,
- bool wait) {
- return process.Terminate(exit_code, wait);
+ int exit_code) {
+ return process.Terminate(exit_code, false);
}
// static
@@ -65,14 +65,14 @@ ChildProcessLauncherHelper::PrepareMojoPipeHandlesOnClientThread() {
std::unique_ptr<FileMappedForLaunch>
ChildProcessLauncherHelper::GetFilesToMap() {
- DCHECK_CURRENTLY_ON(BrowserThread::PROCESS_LAUNCHER);
+ DCHECK(CurrentlyOnProcessLauncherTaskRunner());
return std::unique_ptr<FileMappedForLaunch>();
}
bool ChildProcessLauncherHelper::BeforeLaunchOnLauncherThread(
const PosixFileDescriptorInfo& files_to_register,
base::LaunchOptions* options) {
- DCHECK_CURRENTLY_ON(BrowserThread::PROCESS_LAUNCHER);
+ DCHECK(CurrentlyOnProcessLauncherTaskRunner());
mojo::edk::PlatformChannelPair::PrepareToPassHandleToChildProcess(
mojo_client_handle(), command_line(), &options->handles_to_transfer);
@@ -88,7 +88,7 @@ ChildProcessLauncherHelper::LaunchProcessOnLauncherThread(
std::unique_ptr<FileMappedForLaunch> files_to_register,
bool* is_synchronous_launch,
int* launch_result) {
- DCHECK_CURRENTLY_ON(BrowserThread::PROCESS_LAUNCHER);
+ DCHECK(CurrentlyOnProcessLauncherTaskRunner());
DCHECK(mojo_client_handle().is_valid());
// TODO(750938): Implement sandboxed/isolated subprocess launching.
@@ -100,7 +100,7 @@ ChildProcessLauncherHelper::LaunchProcessOnLauncherThread(
void ChildProcessLauncherHelper::AfterLaunchOnLauncherThread(
const ChildProcessLauncherHelper::Process& process,
const base::LaunchOptions& options) {
- DCHECK_CURRENTLY_ON(BrowserThread::PROCESS_LAUNCHER);
+ DCHECK(CurrentlyOnProcessLauncherTaskRunner());
if (process.process.IsValid()) {
// |mojo_client_handle_| has already been transferred to the child process
@@ -113,7 +113,7 @@ void ChildProcessLauncherHelper::AfterLaunchOnLauncherThread(
// static
void ChildProcessLauncherHelper::ForceNormalProcessTerminationSync(
ChildProcessLauncherHelper::Process process) {
- DCHECK_CURRENTLY_ON(BrowserThread::PROCESS_LAUNCHER);
+ DCHECK(CurrentlyOnProcessLauncherTaskRunner());
process.process.Terminate(RESULT_CODE_NORMAL_EXIT, true);
}
diff --git a/chromium/content/browser/child_process_launcher_helper_linux.cc b/chromium/content/browser/child_process_launcher_helper_linux.cc
index 1b8601de2c1..732970c0e83 100644
--- a/chromium/content/browser/child_process_launcher_helper_linux.cc
+++ b/chromium/content/browser/child_process_launcher_helper_linux.cc
@@ -11,6 +11,7 @@
#include "content/browser/sandbox_host_linux.h"
#include "content/browser/zygote_host/zygote_communication_linux.h"
#include "content/browser/zygote_host/zygote_host_impl_linux.h"
+#include "content/public/browser/child_process_launcher_utils.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/common/common_sandbox_support_linux.h"
#include "content/public/common/content_client.h"
@@ -36,7 +37,7 @@ void ChildProcessLauncherHelper::BeforeLaunchOnClientThread() {
std::unique_ptr<FileMappedForLaunch>
ChildProcessLauncherHelper::GetFilesToMap() {
- DCHECK_CURRENTLY_ON(BrowserThread::PROCESS_LAUNCHER);
+ DCHECK(CurrentlyOnProcessLauncherTaskRunner());
return CreateDefaultPosixFilesToMap(child_process_id(), mojo_client_handle(),
true /* include_service_required_files */,
GetProcessType(), command_line());
@@ -130,14 +131,17 @@ base::TerminationStatus ChildProcessLauncherHelper::GetTerminationStatus(
}
// static
-bool ChildProcessLauncherHelper::TerminateProcess(
- const base::Process& process, int exit_code, bool wait) {
- return process.Terminate(exit_code, wait);
+bool ChildProcessLauncherHelper::TerminateProcess(const base::Process& process,
+ int exit_code) {
+ // TODO(https://crbug.com/818244): Determine whether we should also call
+ // EnsureProcessTerminated() to make sure of process-exit, and reap it.
+ return process.Terminate(exit_code, false);
}
// static
void ChildProcessLauncherHelper::ForceNormalProcessTerminationSync(
ChildProcessLauncherHelper::Process process) {
+ DCHECK(CurrentlyOnProcessLauncherTaskRunner());
process.process.Terminate(RESULT_CODE_NORMAL_EXIT, false);
// On POSIX, we must additionally reap the child.
if (process.zygote) {
@@ -152,7 +156,7 @@ void ChildProcessLauncherHelper::ForceNormalProcessTerminationSync(
void ChildProcessLauncherHelper::SetProcessPriorityOnLauncherThread(
base::Process process,
const ChildProcessLauncherPriority& priority) {
- DCHECK_CURRENTLY_ON(BrowserThread::PROCESS_LAUNCHER);
+ DCHECK(CurrentlyOnProcessLauncherTaskRunner());
if (process.CanBackgroundProcesses())
process.SetProcessBackgrounded(priority.background);
}
diff --git a/chromium/content/browser/child_process_launcher_helper_mac.cc b/chromium/content/browser/child_process_launcher_helper_mac.cc
index 87278e21698..61f9aa4ec40 100644
--- a/chromium/content/browser/child_process_launcher_helper_mac.cc
+++ b/chromium/content/browser/child_process_launcher_helper_mac.cc
@@ -4,7 +4,6 @@
#include "base/command_line.h"
#include "base/feature_list.h"
-#include "base/memory/ptr_util.h"
#include "base/path_service.h"
#include "base/posix/global_descriptors.h"
#include "content/browser/child_process_launcher.h"
@@ -13,6 +12,7 @@
#include "content/browser/mach_broker_mac.h"
#include "content/browser/sandbox_parameters_mac.h"
#include "content/grit/content_resources.h"
+#include "content/public/browser/child_process_launcher_utils.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_paths.h"
@@ -47,7 +47,7 @@ void ChildProcessLauncherHelper::BeforeLaunchOnClientThread() {
std::unique_ptr<PosixFileDescriptorInfo>
ChildProcessLauncherHelper::GetFilesToMap() {
- DCHECK_CURRENTLY_ON(BrowserThread::PROCESS_LAUNCHER);
+ DCHECK(CurrentlyOnProcessLauncherTaskRunner());
return CreateDefaultPosixFilesToMap(
child_process_id(), mojo_client_handle(),
false /* include_service_required_files */, GetProcessType(),
@@ -231,15 +231,17 @@ base::TerminationStatus ChildProcessLauncherHelper::GetTerminationStatus(
}
// static
-bool ChildProcessLauncherHelper::TerminateProcess(
- const base::Process& process, int exit_code, bool wait) {
- return process.Terminate(exit_code, wait);
+bool ChildProcessLauncherHelper::TerminateProcess(const base::Process& process,
+ int exit_code) {
+ // TODO(https://crbug.com/818244): Determine whether we should also call
+ // EnsureProcessTerminated() to make sure of process-exit, and reap it.
+ return process.Terminate(exit_code, false);
}
// static
void ChildProcessLauncherHelper::ForceNormalProcessTerminationSync(
ChildProcessLauncherHelper::Process process) {
- DCHECK_CURRENTLY_ON(BrowserThread::PROCESS_LAUNCHER);
+ DCHECK(CurrentlyOnProcessLauncherTaskRunner());
// Client has gone away, so just kill the process. Using exit code 0 means
// that UMA won't treat this as a crash.
process.process.Terminate(RESULT_CODE_NORMAL_EXIT, false);
diff --git a/chromium/content/browser/child_process_launcher_helper_win.cc b/chromium/content/browser/child_process_launcher_helper_win.cc
index b9183469740..ca73f6006dc 100644
--- a/chromium/content/browser/child_process_launcher_helper_win.cc
+++ b/chromium/content/browser/child_process_launcher_helper_win.cc
@@ -10,6 +10,7 @@
#include "base/win/win_util.h"
#include "content/browser/child_process_launcher.h"
#include "content/browser/child_process_launcher_helper.h"
+#include "content/public/browser/child_process_launcher_utils.h"
#include "content/public/common/result_codes.h"
#include "content/public/common/sandbox_init.h"
#include "content/public/common/sandboxed_process_launcher_delegate.h"
@@ -46,7 +47,7 @@ ChildProcessLauncherHelper::GetFilesToMap() {
bool ChildProcessLauncherHelper::BeforeLaunchOnLauncherThread(
const FileMappedForLaunch& files_to_register,
base::LaunchOptions* options) {
- DCHECK_CURRENTLY_ON(BrowserThread::PROCESS_LAUNCHER);
+ DCHECK(CurrentlyOnProcessLauncherTaskRunner());
return true;
}
@@ -56,7 +57,7 @@ ChildProcessLauncherHelper::LaunchProcessOnLauncherThread(
std::unique_ptr<FileMappedForLaunch> files_to_register,
bool* is_synchronous_launch,
int* launch_result) {
- DCHECK_CURRENTLY_ON(BrowserThread::PROCESS_LAUNCHER);
+ DCHECK(CurrentlyOnProcessLauncherTaskRunner());
*is_synchronous_launch = true;
if (delegate_->ShouldLaunchElevated()) {
// When establishing a Mojo connection, the pipe path has already been added
@@ -85,7 +86,7 @@ ChildProcessLauncherHelper::LaunchProcessOnLauncherThread(
void ChildProcessLauncherHelper::AfterLaunchOnLauncherThread(
const ChildProcessLauncherHelper::Process& process,
const base::LaunchOptions& options) {
- DCHECK_CURRENTLY_ON(BrowserThread::PROCESS_LAUNCHER);
+ DCHECK(CurrentlyOnProcessLauncherTaskRunner());
}
base::TerminationStatus ChildProcessLauncherHelper::GetTerminationStatus(
@@ -96,14 +97,14 @@ base::TerminationStatus ChildProcessLauncherHelper::GetTerminationStatus(
}
// static
-bool ChildProcessLauncherHelper::TerminateProcess(
- const base::Process& process, int exit_code, bool wait) {
- return process.Terminate(exit_code, wait);
+bool ChildProcessLauncherHelper::TerminateProcess(const base::Process& process,
+ int exit_code) {
+ return process.Terminate(exit_code, false);
}
void ChildProcessLauncherHelper::ForceNormalProcessTerminationSync(
ChildProcessLauncherHelper::Process process) {
- DCHECK_CURRENTLY_ON(BrowserThread::PROCESS_LAUNCHER);
+ DCHECK(CurrentlyOnProcessLauncherTaskRunner());
// Client has gone away, so just kill the process. Using exit code 0 means
// that UMA won't treat this as a crash.
process.process.Terminate(RESULT_CODE_NORMAL_EXIT, false);
@@ -112,7 +113,7 @@ void ChildProcessLauncherHelper::ForceNormalProcessTerminationSync(
void ChildProcessLauncherHelper::SetProcessPriorityOnLauncherThread(
base::Process process,
const ChildProcessLauncherPriority& priority) {
- DCHECK_CURRENTLY_ON(BrowserThread::PROCESS_LAUNCHER);
+ DCHECK(CurrentlyOnProcessLauncherTaskRunner());
if (process.CanBackgroundProcesses())
process.SetProcessBackgrounded(priority.background);
}
diff --git a/chromium/content/browser/child_process_security_policy_browsertest.cc b/chromium/content/browser/child_process_security_policy_browsertest.cc
index 942d5d23b17..a308f42cdee 100644
--- a/chromium/content/browser/child_process_security_policy_browsertest.cc
+++ b/chromium/content/browser/child_process_security_policy_browsertest.cc
@@ -7,10 +7,12 @@
#include "base/files/file_path.h"
#include "build/build_config.h"
#include "content/browser/child_process_security_policy_impl.h"
+#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/result_codes.h"
+#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/shell/browser/shell.h"
@@ -45,16 +47,19 @@ IN_PROC_BROWSER_TEST_F(ChildProcessSecurityPolicyInProcessBrowserTest, NoLeak) {
NavigateToURL(shell(), url);
EXPECT_EQ(
- ChildProcessSecurityPolicyImpl::GetInstance()->security_state_.size(),
- 1U);
+ RenderProcessHostImpl::IsSpareProcessKeptAtAllTimes() ? 2u : 1u,
+ ChildProcessSecurityPolicyImpl::GetInstance()->security_state_.size());
WebContents* web_contents = shell()->web_contents();
- web_contents->GetMainFrame()->GetProcess()->Shutdown(RESULT_CODE_KILLED,
- true);
+ content::RenderProcessHostWatcher exit_observer(
+ web_contents->GetMainFrame()->GetProcess(),
+ content::RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
+ web_contents->GetMainFrame()->GetProcess()->Shutdown(RESULT_CODE_KILLED);
+ exit_observer.Wait();
web_contents->GetController().Reload(ReloadType::NORMAL, true);
EXPECT_EQ(
- 1U,
+ RenderProcessHostImpl::IsSpareProcessKeptAtAllTimes() ? 2u : 1u,
ChildProcessSecurityPolicyImpl::GetInstance()->security_state_.size());
}
diff --git a/chromium/content/browser/child_process_security_policy_impl.cc b/chromium/content/browser/child_process_security_policy_impl.cc
index 51e217a963a..09d1adb47f3 100644
--- a/chromium/content/browser/child_process_security_policy_impl.cc
+++ b/chromium/content/browser/child_process_security_policy_impl.cc
@@ -13,7 +13,6 @@
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
@@ -21,12 +20,12 @@
#include "content/browser/bad_message.h"
#include "content/browser/isolated_origin_util.h"
#include "content/browser/site_instance_impl.h"
-#include "content/browser/site_isolation_policy.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/child_process_data.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/render_process_host.h"
+#include "content/public/browser/site_isolation_policy.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/common/bindings_policy.h"
#include "content/public/common/url_constants.h"
@@ -807,6 +806,10 @@ bool ChildProcessSecurityPolicyImpl::CanReadRequestBody(
// sufficient defense against access from an unrelated renderer.
break;
+ case network::DataElement::TYPE_DATA_PIPE:
+ // Data is self-contained within |body| - no need to check access.
+ break;
+
case network::DataElement::TYPE_UNKNOWN:
default:
// Fail safe - deny access.
diff --git a/chromium/content/browser/compositor/browser_compositor_output_surface.cc b/chromium/content/browser/compositor/browser_compositor_output_surface.cc
index e2cd453651f..f7e37d38bfb 100644
--- a/chromium/content/browser/compositor/browser_compositor_output_surface.cc
+++ b/chromium/content/browser/compositor/browser_compositor_output_surface.cc
@@ -9,7 +9,6 @@
#include "base/bind.h"
#include "base/command_line.h"
#include "base/location.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/string_number_conversions.h"
#include "components/viz/common/frame_sinks/begin_frame_source.h"
#include "components/viz/service/display/output_surface_client.h"
diff --git a/chromium/content/browser/compositor/gpu_browser_compositor_output_surface.h b/chromium/content/browser/compositor/gpu_browser_compositor_output_surface.h
index ef06c3e8e34..95aa6d1983e 100644
--- a/chromium/content/browser/compositor/gpu_browser_compositor_output_surface.h
+++ b/chromium/content/browser/compositor/gpu_browser_compositor_output_surface.h
@@ -11,7 +11,7 @@
#include "build/build_config.h"
#include "content/browser/compositor/browser_compositor_output_surface.h"
#include "content/browser/compositor/gpu_vsync_begin_frame_source.h"
-#include "gpu/vulkan/features.h"
+#include "gpu/vulkan/buildflags.h"
#include "ui/gfx/swap_result.h"
namespace viz {
diff --git a/chromium/content/browser/compositor/gpu_process_transport_factory.cc b/chromium/content/browser/compositor/gpu_process_transport_factory.cc
index b40de2a2910..7b9fc4114c5 100644
--- a/chromium/content/browser/compositor/gpu_process_transport_factory.cc
+++ b/chromium/content/browser/compositor/gpu_process_transport_factory.cc
@@ -50,6 +50,7 @@
#include "content/browser/gpu/gpu_data_manager_impl.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/common/gpu_stream_constants.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "gpu/GLES2/gl2extchromium.h"
#include "gpu/command_buffer/client/gles2_interface.h"
@@ -60,7 +61,7 @@
#include "gpu/config/gpu_feature_info.h"
#include "gpu/ipc/client/gpu_channel_host.h"
#include "gpu/ipc/host/gpu_memory_buffer_support.h"
-#include "gpu/vulkan/features.h"
+#include "gpu/vulkan/buildflags.h"
#include "services/service_manager/runner/common/client_util.h"
#include "services/ui/public/cpp/gpu/context_provider_command_buffer.h"
#include "third_party/khronos/GLES2/gl2.h"
@@ -393,10 +394,11 @@ void GpuProcessTransportFactory::EstablishedGpuChannel(
bool support_locking = true;
bool support_gles2_interface = false;
bool support_raster_interface = true;
+ bool support_grcontext = false;
shared_worker_context_provider_ = CreateContextCommon(
gpu_channel_host, gpu::kNullSurfaceHandle, need_alpha_channel,
false /* support_stencil */, support_locking, support_gles2_interface,
- support_raster_interface,
+ support_raster_interface, support_grcontext,
ui::command_buffer_metrics::BROWSER_WORKER_CONTEXT);
auto result = shared_worker_context_provider_->BindToCurrentThread();
if (result != gpu::ContextResult::kSuccess) {
@@ -419,10 +421,11 @@ void GpuProcessTransportFactory::EstablishedGpuChannel(
bool support_locking = false;
bool support_gles2_interface = true;
bool support_raster_interface = false;
+ bool support_grcontext = true;
context_provider = CreateContextCommon(
std::move(gpu_channel_host), surface_handle, need_alpha_channel,
support_stencil, support_locking, support_gles2_interface,
- support_raster_interface,
+ support_raster_interface, support_grcontext,
ui::command_buffer_metrics::DISPLAY_COMPOSITOR_ONSCREEN_CONTEXT);
// On Mac, GpuCommandBufferMsg_SwapBuffersCompleted must be handled in
// a nested run loop during resize.
@@ -494,15 +497,15 @@ void GpuProcessTransportFactory::EstablishedGpuChannel(
}
display_output_surface =
std::make_unique<SoftwareBrowserCompositorOutputSurface>(
- CreateSoftwareOutputDevice(compositor->widget()), vsync_callback,
- compositor->task_runner());
+ CreateSoftwareOutputDevice(compositor->widget()),
+ std::move(vsync_callback), compositor->task_runner());
} else {
DCHECK(context_provider);
const auto& capabilities = context_provider->ContextCapabilities();
if (data->surface_handle == gpu::kNullSurfaceHandle) {
display_output_surface =
std::make_unique<OffscreenBrowserCompositorOutputSurface>(
- context_provider, vsync_callback,
+ context_provider, std::move(vsync_callback),
std::unique_ptr<viz::CompositorOverlayCandidateValidator>());
} else if (capabilities.surfaceless) {
#if defined(OS_MACOSX)
@@ -516,11 +519,13 @@ void GpuProcessTransportFactory::EstablishedGpuChannel(
disable_overlay_ca_layers),
GetGpuMemoryBufferManager());
#else
+ DCHECK(capabilities.texture_format_bgra8888);
auto gpu_output_surface =
std::make_unique<GpuSurfacelessBrowserCompositorOutputSurface>(
- context_provider, data->surface_handle, vsync_callback,
+ context_provider, data->surface_handle,
+ std::move(vsync_callback),
CreateOverlayCandidateValidator(compositor->widget()),
- GL_TEXTURE_2D, GL_RGB,
+ GL_TEXTURE_2D, GL_BGRA_EXT,
display::DisplaySnapshot::PrimaryFormat(),
GetGpuMemoryBufferManager());
gpu_vsync_control = gpu_output_surface.get();
@@ -537,7 +542,8 @@ void GpuProcessTransportFactory::EstablishedGpuChannel(
#endif
auto gpu_output_surface =
std::make_unique<GpuBrowserCompositorOutputSurface>(
- context_provider, vsync_callback, std::move(validator));
+ context_provider, std::move(vsync_callback),
+ std::move(validator));
gpu_vsync_control = gpu_output_surface.get();
display_output_surface = std::move(gpu_output_surface);
}
@@ -690,6 +696,8 @@ void GpuProcessTransportFactory::DisableGpuCompositing(
if (visible)
compositor->SetVisible(true);
}
+
+ GpuDataManagerImpl::GetInstance()->NotifyGpuInfoUpdate();
}
std::unique_ptr<ui::Reflector> GpuProcessTransportFactory::CreateReflector(
@@ -965,9 +973,11 @@ GpuProcessTransportFactory::SharedMainThreadContextProvider() {
bool support_locking = false;
bool support_gles2_interface = true;
bool support_raster_interface = false;
+ bool support_grcontext = true;
shared_main_thread_contexts_ = CreateContextCommon(
std::move(gpu_channel_host), gpu::kNullSurfaceHandle, need_alpha_channel,
false, support_locking, support_gles2_interface, support_raster_interface,
+ support_grcontext,
ui::command_buffer_metrics::BROWSER_OFFSCREEN_MAINTHREAD_CONTEXT);
shared_main_thread_contexts_->AddObserver(this);
auto result = shared_main_thread_contexts_->BindToCurrentThread();
@@ -1056,6 +1066,7 @@ GpuProcessTransportFactory::CreateContextCommon(
bool support_locking,
bool support_gles2_interface,
bool support_raster_interface,
+ bool support_grcontext,
ui::command_buffer_metrics::ContextType type) {
DCHECK(gpu_channel_host);
DCHECK(!is_gpu_compositing_disabled_);
@@ -1096,7 +1107,8 @@ GpuProcessTransportFactory::CreateContextCommon(
return base::MakeRefCounted<ui::ContextProviderCommandBuffer>(
std::move(gpu_channel_host), GetGpuMemoryBufferManager(), stream_id,
stream_priority, surface_handle, url, automatic_flushes, support_locking,
- gpu::SharedMemoryLimits(), attributes, nullptr /* share_context */, type);
+ support_grcontext, gpu::SharedMemoryLimits(), attributes,
+ nullptr /* share_context */, type);
}
} // namespace content
diff --git a/chromium/content/browser/compositor/gpu_process_transport_factory.h b/chromium/content/browser/compositor/gpu_process_transport_factory.h
index 0e6713cef3b..bc7e7750003 100644
--- a/chromium/content/browser/compositor/gpu_process_transport_factory.h
+++ b/chromium/content/browser/compositor/gpu_process_transport_factory.h
@@ -139,6 +139,7 @@ class GpuProcessTransportFactory : public ui::ContextFactory,
bool support_locking,
bool support_gles2_interface,
bool support_raster_interface,
+ bool support_grcontext,
ui::command_buffer_metrics::ContextType type);
viz::FrameSinkIdAllocator frame_sink_id_allocator_;
diff --git a/chromium/content/browser/compositor/offscreen_browser_compositor_output_surface.h b/chromium/content/browser/compositor/offscreen_browser_compositor_output_surface.h
index abbcd19e70e..a1f4e6df47f 100644
--- a/chromium/content/browser/compositor/offscreen_browser_compositor_output_surface.h
+++ b/chromium/content/browser/compositor/offscreen_browser_compositor_output_surface.h
@@ -14,7 +14,7 @@
#include "base/memory/weak_ptr.h"
#include "build/build_config.h"
#include "content/browser/compositor/browser_compositor_output_surface.h"
-#include "gpu/vulkan/features.h"
+#include "gpu/vulkan/buildflags.h"
#include "ui/latency/latency_info.h"
namespace ui {
diff --git a/chromium/content/browser/compositor/reflector_impl.cc b/chromium/content/browser/compositor/reflector_impl.cc
index 76300248bc4..a0a54c0d450 100644
--- a/chromium/content/browser/compositor/reflector_impl.cc
+++ b/chromium/content/browser/compositor/reflector_impl.cc
@@ -6,7 +6,6 @@
#include "base/bind.h"
#include "base/location.h"
-#include "base/memory/ptr_util.h"
#include "components/viz/common/resources/transferable_resource.h"
#include "content/browser/compositor/browser_compositor_output_surface.h"
#include "content/browser/compositor/owned_mailbox.h"
diff --git a/chromium/content/browser/compositor/reflector_impl_unittest.cc b/chromium/content/browser/compositor/reflector_impl_unittest.cc
index 303535abdfe..3d36fdbb7be 100644
--- a/chromium/content/browser/compositor/reflector_impl_unittest.cc
+++ b/chromium/content/browser/compositor/reflector_impl_unittest.cc
@@ -5,7 +5,6 @@
#include "content/browser/compositor/reflector_impl.h"
#include "base/callback.h"
-#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
@@ -181,7 +180,8 @@ class ReflectorImplTest : public testing::Test {
reflector_->RemoveMirroringLayer(mirroring_layer_.get());
viz::TransferableResource resource;
std::unique_ptr<viz::SingleReleaseCallback> release;
- if (mirroring_layer_->PrepareTransferableResource(&resource, &release)) {
+ if (mirroring_layer_->PrepareTransferableResource(nullptr, &resource,
+ &release)) {
release->Run(gpu::SyncToken(), false);
}
compositor_.reset();
diff --git a/chromium/content/browser/compositor/software_browser_compositor_output_surface.h b/chromium/content/browser/compositor/software_browser_compositor_output_surface.h
index 4036e691a6b..79bc9f5f6b8 100644
--- a/chromium/content/browser/compositor/software_browser_compositor_output_surface.h
+++ b/chromium/content/browser/compositor/software_browser_compositor_output_surface.h
@@ -11,7 +11,7 @@
#include "build/build_config.h"
#include "content/browser/compositor/browser_compositor_output_surface.h"
#include "content/common/content_export.h"
-#include "gpu/vulkan/features.h"
+#include "gpu/vulkan/buildflags.h"
namespace cc {
class SoftwareOutputDevice;
diff --git a/chromium/content/browser/compositor/software_browser_compositor_output_surface_unittest.cc b/chromium/content/browser/compositor/software_browser_compositor_output_surface_unittest.cc
index f9d7405c4d7..103c816895e 100644
--- a/chromium/content/browser/compositor/software_browser_compositor_output_surface_unittest.cc
+++ b/chromium/content/browser/compositor/software_browser_compositor_output_surface_unittest.cc
@@ -7,7 +7,6 @@
#include <utility>
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/test/test_message_loop.h"
#include "base/threading/thread_task_runner_handle.h"
#include "cc/test/fake_output_surface_client.h"
diff --git a/chromium/content/browser/compositor/viz_process_transport_factory.cc b/chromium/content/browser/compositor/viz_process_transport_factory.cc
index d92cac2cbdd..a2b4b4095c4 100644
--- a/chromium/content/browser/compositor/viz_process_transport_factory.cc
+++ b/chromium/content/browser/compositor/viz_process_transport_factory.cc
@@ -7,22 +7,25 @@
#include <utility>
#include "base/command_line.h"
+#include "base/debug/dump_without_crashing.h"
#include "base/single_thread_task_runner.h"
#include "cc/raster/single_thread_task_graph_runner.h"
#include "components/viz/client/client_layer_tree_frame_sink.h"
+#include "components/viz/client/hit_test_data_provider_draw_quad.h"
#include "components/viz/client/local_surface_id_provider.h"
#include "components/viz/common/gpu/context_provider.h"
#include "components/viz/common/gpu/raster_context_provider.h"
-#include "components/viz/host/forwarding_compositing_mode_reporter_impl.h"
#include "components/viz/host/host_frame_sink_manager.h"
#include "components/viz/host/renderer_settings_creation.h"
+#include "components/viz/service/display_embedder/compositing_mode_reporter_impl.h"
#include "components/viz/service/display_embedder/server_shared_bitmap_manager.h"
#include "content/browser/browser_main_loop.h"
-#include "content/browser/browser_thread_impl.h"
#include "content/browser/compositor/external_begin_frame_controller_client_impl.h"
#include "content/browser/gpu/compositor_util.h"
+#include "content/browser/gpu/gpu_data_manager_impl.h"
#include "content/browser/gpu/gpu_process_host.h"
#include "content/common/gpu_stream_constants.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_switches.h"
#include "gpu/command_buffer/client/gles2_interface.h"
@@ -49,6 +52,7 @@ scoped_refptr<ui::ContextProviderCommandBuffer> CreateContextProviderImpl(
bool support_locking,
bool support_gles2_interface,
bool support_raster_interface,
+ bool support_grcontext,
ui::command_buffer_metrics::ContextType type) {
constexpr bool kAutomaticFlushes = false;
@@ -68,7 +72,7 @@ scoped_refptr<ui::ContextProviderCommandBuffer> CreateContextProviderImpl(
return base::MakeRefCounted<ui::ContextProviderCommandBuffer>(
std::move(gpu_channel_host), gpu_memory_buffer_manager,
kGpuStreamIdDefault, kGpuStreamPriorityUI, gpu::kNullSurfaceHandle,
- std::move(url), kAutomaticFlushes, support_locking,
+ std::move(url), kAutomaticFlushes, support_locking, support_grcontext,
gpu::SharedMemoryLimits(), attributes, nullptr /* share_context */, type);
}
@@ -82,19 +86,35 @@ bool IsWorkerContextLost(viz::RasterContextProvider* context_provider) {
return lock.RasterInterface()->GetGraphicsResetStatusKHR() != GL_NO_ERROR;
}
+// Provided as a callback to crash the GPU process.
+void ReceivedBadMessageFromGpuProcess() {
+ GpuProcessHost::CallOnIO(
+ GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED, false /* force_create */,
+ base::BindRepeating([](GpuProcessHost* host) {
+ // There should always be a GpuProcessHost instance, and GPU process,
+ // for running the compositor thread. The exception is during shutdown
+ // the GPU process won't be restarted and GpuProcessHost::Get() can
+ // return null.
+ if (host)
+ host->ForceShutdown();
+
+ LOG(ERROR) << "Bad message received, terminating gpu process.";
+ base::debug::DumpWithoutCrashing();
+ }));
+}
+
} // namespace
VizProcessTransportFactory::VizProcessTransportFactory(
gpu::GpuChannelEstablishFactory* gpu_channel_establish_factory,
scoped_refptr<base::SingleThreadTaskRunner> resize_task_runner,
- viz::ForwardingCompositingModeReporterImpl* forwarding_mode_reporter)
+ viz::CompositingModeReporterImpl* compositing_mode_reporter)
: gpu_channel_establish_factory_(gpu_channel_establish_factory),
resize_task_runner_(std::move(resize_task_runner)),
- forwarding_mode_reporter_(forwarding_mode_reporter),
+ compositing_mode_reporter_(compositing_mode_reporter),
frame_sink_id_allocator_(kBrowserClientId),
task_graph_runner_(std::make_unique<cc::SingleThreadTaskGraphRunner>()),
renderer_settings_(viz::CreateRendererSettings()),
- compositing_mode_watcher_binding_(this),
weak_ptr_factory_(this) {
DCHECK(gpu_channel_establish_factory_);
task_graph_runner_->Start("CompositorTileWorker1",
@@ -102,17 +122,13 @@ VizProcessTransportFactory::VizProcessTransportFactory(
GetHostFrameSinkManager()->SetConnectionLostCallback(
base::BindRepeating(&VizProcessTransportFactory::OnGpuProcessLost,
weak_ptr_factory_.GetWeakPtr()));
+ GetHostFrameSinkManager()->SetBadMessageReceivedFromGpuCallback(
+ base::BindRepeating(&ReceivedBadMessageFromGpuProcess));
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kDisableGpu) ||
command_line->HasSwitch(switches::kDisableGpuCompositing)) {
CompositingModeFallbackToSoftware();
- } else {
- // Make |this| a CompositingModeWatcher for the |forwarding_mode_reporter_|.
- viz::mojom::CompositingModeWatcherPtr watcher_ptr;
- compositing_mode_watcher_binding_.Bind(mojo::MakeRequest(&watcher_ptr));
- forwarding_mode_reporter_->AddCompositingModeWatcher(
- std::move(watcher_ptr));
}
}
@@ -136,34 +152,25 @@ void VizProcessTransportFactory::ConnectHostFrameSinkManager() {
std::move(frame_sink_manager_client_request), resize_task_runner_,
std::move(frame_sink_manager));
- // The ForwardingCompositingModeReporterImpl wants to watch the reporter in
- // the viz process. We give a mojo pointer to it over to that process and have
- // the viz process connect it to the reporter there directly, instead of
- // requesting a pointer to that reporter from this process.
- viz::mojom::CompositingModeWatcherPtr mode_watch_ptr =
- forwarding_mode_reporter_->BindAsWatcher();
-
// Hop to the IO thread, then send the other side of interface to viz process.
auto connect_on_io_thread =
[](viz::mojom::FrameSinkManagerRequest request,
- viz::mojom::FrameSinkManagerClientPtrInfo client,
- viz::mojom::CompositingModeWatcherPtrInfo mode_watcher) {
+ viz::mojom::FrameSinkManagerClientPtrInfo client) {
// There should always be a GpuProcessHost instance, and GPU process,
// for running the compositor thread. The exception is during shutdown
// the GPU process won't be restarted and GpuProcessHost::Get() can
// return null.
auto* gpu_process_host = GpuProcessHost::Get();
if (gpu_process_host) {
- gpu_process_host->ConnectFrameSinkManager(
- std::move(request), std::move(client), std::move(mode_watcher));
+ gpu_process_host->ConnectFrameSinkManager(std::move(request),
+ std::move(client));
}
};
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(connect_on_io_thread,
std::move(frame_sink_manager_request),
- frame_sink_manager_client.PassInterface(),
- mode_watch_ptr.PassInterface()));
+ frame_sink_manager_client.PassInterface()));
}
void VizProcessTransportFactory::CreateLayerTreeFrameSink(
@@ -369,6 +376,8 @@ void VizProcessTransportFactory::CompositingModeFallbackToSoftware() {
// Change the result of IsGpuCompositingDisabled() before notifying anything.
is_gpu_compositing_disabled_ = true;
+ compositing_mode_reporter_->SetUsingSoftwareCompositing();
+
// Consumers of the shared main thread context aren't CompositingModeWatchers,
// so inform them about the compositing mode switch by acting like the context
// was lost. This also destroys the contexts since they aren't created when
@@ -404,6 +413,8 @@ void VizProcessTransportFactory::CompositingModeFallbackToSoftware() {
if (visible)
compositor->SetVisible(true);
}
+
+ GpuDataManagerImpl::GetInstance()->NotifyGpuInfoUpdate();
}
void VizProcessTransportFactory::OnContextLost() {
@@ -430,6 +441,8 @@ void VizProcessTransportFactory::OnEstablishedGpuChannel(
// Only try to make contexts for gpu compositing.
if (gpu_compositing) {
+ // TODO(kylechar): Check GPU compositing status from GpuFeatureInfo.
+
if (!gpu_channel_host ||
!CreateContextProviders(std::move(gpu_channel_host))) {
// Retry on failure. If this isn't possible we should hear that we're
@@ -485,8 +498,7 @@ void VizProcessTransportFactory::OnEstablishedGpuChannel(
root_params->frame_sink_id = compositor->frame_sink_id();
root_params->widget = surface_handle;
- root_params->force_software_compositing =
- compositor->force_software_compositor();
+ root_params->gpu_compositing = gpu_compositing;
root_params->renderer_settings = renderer_settings_;
// Connects the viz process end of CompositorFrameSink message pipes. The
@@ -509,6 +521,9 @@ void VizProcessTransportFactory::OnEstablishedGpuChannel(
params.local_surface_id_provider =
std::make_unique<viz::DefaultLocalSurfaceIdProvider>();
params.enable_surface_synchronization = true;
+ params.hit_test_data_provider =
+ std::make_unique<viz::HitTestDataProviderDrawQuad>(
+ /*should_ask_for_child_region=*/false);
scoped_refptr<viz::ContextProvider> compositor_context;
scoped_refptr<viz::RasterContextProvider> worker_context;
@@ -532,9 +547,11 @@ bool VizProcessTransportFactory::CreateContextProviders(
constexpr bool kSharedWorkerContextSupportsLocking = true;
constexpr bool kSharedWorkerContextSupportsGLES2 = false;
constexpr bool kSharedWorkerContextSupportsRaster = true;
+ constexpr bool kSharedWorkerContextSupportsGrContext = false;
constexpr bool kCompositorContextSupportsLocking = false;
constexpr bool kCompositorContextSupportsGLES2 = true;
constexpr bool kCompositorContextSupportsRaster = false;
+ constexpr bool kCompositorContextSupportsGrContext = true;
if (main_context_provider_ && IsContextLost(main_context_provider_.get())) {
main_context_provider_->RemoveObserver(this);
@@ -550,6 +567,7 @@ bool VizProcessTransportFactory::CreateContextProviders(
gpu_channel_host, GetGpuMemoryBufferManager(),
kSharedWorkerContextSupportsLocking, kSharedWorkerContextSupportsGLES2,
kSharedWorkerContextSupportsRaster,
+ kSharedWorkerContextSupportsGrContext,
ui::command_buffer_metrics::BROWSER_WORKER_CONTEXT);
// Don't observer context loss on |worker_context_provider_| here, that is
@@ -566,7 +584,7 @@ bool VizProcessTransportFactory::CreateContextProviders(
main_context_provider_ = CreateContextProviderImpl(
std::move(gpu_channel_host), GetGpuMemoryBufferManager(),
kCompositorContextSupportsLocking, kCompositorContextSupportsGLES2,
- kCompositorContextSupportsRaster,
+ kCompositorContextSupportsRaster, kCompositorContextSupportsGrContext,
ui::command_buffer_metrics::UI_COMPOSITOR_CONTEXT);
main_context_provider_->SetDefaultTaskRunner(resize_task_runner_);
main_context_provider_->AddObserver(this);
diff --git a/chromium/content/browser/compositor/viz_process_transport_factory.h b/chromium/content/browser/compositor/viz_process_transport_factory.h
index 69643cd4a0f..44c00cbc446 100644
--- a/chromium/content/browser/compositor/viz_process_transport_factory.h
+++ b/chromium/content/browser/compositor/viz_process_transport_factory.h
@@ -38,7 +38,7 @@ class ContextProviderCommandBuffer;
}
namespace viz {
-class ForwardingCompositingModeReporterImpl;
+class CompositingModeReporterImpl;
class RasterContextProvider;
}
@@ -59,7 +59,7 @@ class VizProcessTransportFactory : public ui::ContextFactory,
VizProcessTransportFactory(
gpu::GpuChannelEstablishFactory* gpu_channel_establish_factory,
scoped_refptr<base::SingleThreadTaskRunner> resize_task_runner,
- viz::ForwardingCompositingModeReporterImpl* forwarding_mode_reporter);
+ viz::CompositingModeReporterImpl* compositing_mode_reporter);
~VizProcessTransportFactory() override;
// Connects HostFrameSinkManager to FrameSinkManagerImpl in viz process.
@@ -157,12 +157,10 @@ class VizProcessTransportFactory : public ui::ContextFactory,
gpu::GpuChannelEstablishFactory* const gpu_channel_establish_factory_;
scoped_refptr<base::SingleThreadTaskRunner> const resize_task_runner_;
- // Acts as a proxy from the mojo connection to the authoritive
- // |compositing_mode_reporter_|. This will forward the state on to clients of
- // the browser process (eg the renderers). Since the browser process is not
- // restartable, it prevents these clients from having to reconnect to their
- // CompositingModeReporter.
- viz::ForwardingCompositingModeReporterImpl* const forwarding_mode_reporter_;
+
+ // Controls the compositing mode based on what mode the display compositors
+ // are using.
+ viz::CompositingModeReporterImpl* const compositing_mode_reporter_;
base::flat_map<ui::Compositor*, CompositorData> compositor_data_map_;
bool is_gpu_compositing_disabled_ = false;
@@ -180,11 +178,6 @@ class VizProcessTransportFactory : public ui::ContextFactory,
std::unique_ptr<cc::SingleThreadTaskGraphRunner> task_graph_runner_;
const viz::RendererSettings renderer_settings_;
- // The class is a CompositingModeWatcher, which is bound to mojo through
- // this member.
- mojo::Binding<viz::mojom::CompositingModeWatcher>
- compositing_mode_watcher_binding_;
-
base::WeakPtrFactory<VizProcessTransportFactory> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(VizProcessTransportFactory);
diff --git a/chromium/content/browser/cross_site_transfer_browsertest.cc b/chromium/content/browser/cross_site_transfer_browsertest.cc
index 5f1c338daa3..bc1b974fb45 100644
--- a/chromium/content/browser/cross_site_transfer_browsertest.cc
+++ b/chromium/content/browser/cross_site_transfer_browsertest.cc
@@ -9,7 +9,6 @@
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "content/browser/child_process_security_policy_impl.h"
@@ -33,6 +32,7 @@
#include "content/public/test/test_navigation_observer.h"
#include "content/shell/browser/shell.h"
#include "content/shell/browser/shell_content_browser_client.h"
+#include "content/shell/common/shell_switches.h"
#include "content/test/content_browser_test_utils_internal.h"
#include "net/base/escape.h"
#include "net/dns/mock_host_resolver.h"
@@ -472,4 +472,24 @@ IN_PROC_BROWSER_TEST_F(CrossSiteTransferTest, NoDeliveryToDetachedFrame) {
<< "Request should have been cancelled before reaching the renderer.";
}
+// Ensure that we don't send a referrer if a site tries to trigger the forking
+// heuristic, even if we would have forked anyways.
+IN_PROC_BROWSER_TEST_F(CrossSiteTransferTest, NoReferrerOnFork) {
+ base::CommandLine::ForCurrentProcess()->AppendSwitch(
+ switches::kContentShellAlwaysFork);
+
+ GURL start_url(embedded_test_server()->GetURL("a.com", "/fork-popup.html"));
+ EXPECT_TRUE(NavigateToURL(shell(), start_url));
+ EXPECT_EQ(2u, shell()->windows().size());
+ Shell* popup = shell()->windows().back();
+ EXPECT_NE(popup, shell());
+
+ base::string16 expected_title = base::ASCIIToUTF16("Referrer = ''");
+ base::string16 failed_title = base::ASCIIToUTF16(
+ base::StringPrintf("Referrer = '%s'", start_url.spec().c_str()));
+ TitleWatcher watcher(popup->web_contents(), expected_title);
+ watcher.AlsoWaitForTitle(failed_title);
+ EXPECT_EQ(expected_title, watcher.WaitAndGetTitle());
+}
+
} // namespace content
diff --git a/chromium/content/browser/dedicated_worker/dedicated_worker_host.h b/chromium/content/browser/dedicated_worker/dedicated_worker_host.h
index 514a483e8f1..60bbdd54536 100644
--- a/chromium/content/browser/dedicated_worker/dedicated_worker_host.h
+++ b/chromium/content/browser/dedicated_worker/dedicated_worker_host.h
@@ -5,7 +5,7 @@
#ifndef CONTENT_BROWSER_DEDICATED_WORKER_DEDICATED_WORKER_HOST_H_
#define CONTENT_BROWSER_DEDICATED_WORKER_DEDICATED_WORKER_HOST_H_
-#include "third_party/WebKit/public/platform/dedicated_worker_factory.mojom.h"
+#include "third_party/blink/public/platform/dedicated_worker_factory.mojom.h"
namespace url {
class Origin;
diff --git a/chromium/content/browser/device_sensors/DEPS b/chromium/content/browser/device_sensors/DEPS
deleted file mode 100644
index 860720f2f77..00000000000
--- a/chromium/content/browser/device_sensors/DEPS
+++ /dev/null
@@ -1,3 +0,0 @@
-include_rules = [
- "+device/sensors/public/cpp",
-]
diff --git a/chromium/content/browser/device_sensors/device_sensor_browsertest.cc b/chromium/content/browser/device_sensors/device_sensor_browsertest.cc
index 9fe346b50d8..b2b99a142b5 100644
--- a/chromium/content/browser/device_sensors/device_sensor_browsertest.cc
+++ b/chromium/content/browser/device_sensors/device_sensor_browsertest.cc
@@ -8,7 +8,6 @@
#include "base/command_line.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/synchronization/waitable_event.h"
@@ -32,6 +31,7 @@
#include "net/dns/mock_host_resolver.h"
#include "services/device/public/cpp/generic_sensor/platform_sensor_configuration.h"
#include "services/device/public/cpp/generic_sensor/sensor_reading.h"
+#include "services/device/public/cpp/test/fake_sensor_and_provider.h"
#include "services/device/public/mojom/constants.mojom.h"
#include "services/device/public/mojom/sensor.mojom.h"
#include "services/device/public/mojom/sensor_provider.mojom.h"
@@ -41,232 +41,7 @@ namespace content {
namespace {
-class FakeSensor : public device::mojom::Sensor {
- public:
- FakeSensor(device::mojom::SensorType sensor_type)
- : sensor_type_(sensor_type) {
- shared_buffer_handle_ = mojo::SharedBufferHandle::Create(
- sizeof(device::SensorReadingSharedBuffer) *
- static_cast<uint64_t>(device::mojom::SensorType::LAST));
-
- if (!shared_buffer_handle_.is_valid())
- return;
-
- // Create read/write mapping now, to ensure it is kept writable
- // after the region is sealed read-only on Android.
- shared_buffer_mapping_ = shared_buffer_handle_->MapAtOffset(
- device::mojom::SensorInitParams::kReadBufferSizeForTests,
- GetBufferOffset());
- }
-
- ~FakeSensor() override = default;
-
- // device::mojom::Sensor:
- void AddConfiguration(
- const device::PlatformSensorConfiguration& configuration,
- AddConfigurationCallback callback) override {
- std::move(callback).Run(true);
- SensorReadingChanged();
- }
-
- // device::mojom::Sensor:
- void GetDefaultConfiguration(
- GetDefaultConfigurationCallback callback) override {
- std::move(callback).Run(GetDefaultConfiguration());
- }
-
- // device::mojom::Sensor:
- void RemoveConfiguration(
- const device::PlatformSensorConfiguration& configuration) override {}
-
- // device::mojom::Sensor:
- void Suspend() override {}
- void Resume() override {}
- void ConfigureReadingChangeNotifications(bool enabled) override {
- reading_notification_enabled_ = enabled;
- }
-
- device::PlatformSensorConfiguration GetDefaultConfiguration() {
- return device::PlatformSensorConfiguration(60 /* frequency */);
- }
-
- device::mojom::ReportingMode GetReportingMode() {
- return device::mojom::ReportingMode::ON_CHANGE;
- }
-
- double GetMaximumSupportedFrequency() { return 60.0; }
- double GetMinimumSupportedFrequency() { return 1.0; }
-
- device::mojom::SensorClientRequest GetClient() {
- return mojo::MakeRequest(&client_);
- }
-
- mojo::ScopedSharedBufferHandle GetSharedBufferHandle() {
- return shared_buffer_handle_->Clone(
- mojo::SharedBufferHandle::AccessMode::READ_ONLY);
- }
-
- uint64_t GetBufferOffset() {
- return device::SensorReadingSharedBuffer::GetOffset(sensor_type_);
- }
-
- void set_reading(device::SensorReading reading) { reading_ = reading; }
-
- void SensorReadingChanged() {
- if (!shared_buffer_mapping_.get())
- return;
-
- device::SensorReadingSharedBuffer* buffer =
- static_cast<device::SensorReadingSharedBuffer*>(
- shared_buffer_mapping_.get());
-
- auto& seqlock = buffer->seqlock.value();
- seqlock.WriteBegin();
- buffer->reading = reading_;
- seqlock.WriteEnd();
-
- if (client_ && reading_notification_enabled_)
- client_->SensorReadingChanged();
- }
-
- private:
- device::mojom::SensorType sensor_type_;
- bool reading_notification_enabled_ = true;
- mojo::ScopedSharedBufferHandle shared_buffer_handle_;
- mojo::ScopedSharedBufferMapping shared_buffer_mapping_;
- device::mojom::SensorClientPtr client_;
- device::SensorReading reading_;
-
- DISALLOW_COPY_AND_ASSIGN(FakeSensor);
-};
-
-class FakeSensorProvider : public device::mojom::SensorProvider {
- public:
- FakeSensorProvider() : binding_(this) {}
- ~FakeSensorProvider() override = default;
-
- void Bind(const std::string& interface_name,
- mojo::ScopedMessagePipeHandle handle,
- const service_manager::BindSourceInfo& source_info) {
- DCHECK(!binding_.is_bound());
- binding_.Bind(device::mojom::SensorProviderRequest(std::move(handle)));
- }
-
- void set_accelerometer_is_available(bool accelerometer_is_available) {
- accelerometer_is_available_ = accelerometer_is_available;
- }
-
- void set_linear_acceleration_sensor_is_available(
- bool linear_acceleration_sensor_is_available) {
- linear_acceleration_sensor_is_available_ =
- linear_acceleration_sensor_is_available;
- }
-
- void set_gyroscope_is_available(bool gyroscope_is_available) {
- gyroscope_is_available_ = gyroscope_is_available;
- }
-
- void set_relative_orientation_sensor_is_available(
- bool relative_orientation_sensor_is_available) {
- relative_orientation_sensor_is_available_ =
- relative_orientation_sensor_is_available;
- }
-
- void set_absolute_orientation_sensor_is_available(
- bool absolute_orientation_sensor_is_available) {
- absolute_orientation_sensor_is_available_ =
- absolute_orientation_sensor_is_available;
- }
-
- // device::mojom::sensorProvider:
- void GetSensor(device::mojom::SensorType type,
- GetSensorCallback callback) override {
- std::unique_ptr<FakeSensor> sensor;
- device::SensorReading reading;
- reading.raw.timestamp =
- (base::TimeTicks::Now() - base::TimeTicks()).InSecondsF();
-
- switch (type) {
- case device::mojom::SensorType::ACCELEROMETER:
- if (accelerometer_is_available_) {
- sensor = std::make_unique<FakeSensor>(
- device::mojom::SensorType::ACCELEROMETER);
- reading.accel.x = 4;
- reading.accel.y = 5;
- reading.accel.z = 6;
- }
- break;
- case device::mojom::SensorType::LINEAR_ACCELERATION:
- if (linear_acceleration_sensor_is_available_) {
- sensor = std::make_unique<FakeSensor>(
- device::mojom::SensorType::LINEAR_ACCELERATION);
- reading.accel.x = 1;
- reading.accel.y = 2;
- reading.accel.z = 3;
- }
- break;
- case device::mojom::SensorType::GYROSCOPE:
- if (gyroscope_is_available_) {
- sensor = std::make_unique<FakeSensor>(
- device::mojom::SensorType::GYROSCOPE);
- reading.gyro.x = 7;
- reading.gyro.y = 8;
- reading.gyro.z = 9;
- }
- break;
- case device::mojom::SensorType::RELATIVE_ORIENTATION_EULER_ANGLES:
- if (relative_orientation_sensor_is_available_) {
- sensor = std::make_unique<FakeSensor>(
- device::mojom::SensorType::RELATIVE_ORIENTATION_EULER_ANGLES);
- reading.orientation_euler.x = 2; // beta
- reading.orientation_euler.y = 3; // gamma
- reading.orientation_euler.z = 1; // alpha
- }
- break;
- case device::mojom::SensorType::ABSOLUTE_ORIENTATION_EULER_ANGLES:
- if (absolute_orientation_sensor_is_available_) {
- sensor = std::make_unique<FakeSensor>(
- device::mojom::SensorType::ABSOLUTE_ORIENTATION_EULER_ANGLES);
- reading.orientation_euler.x = 5; // beta
- reading.orientation_euler.y = 6; // gamma
- reading.orientation_euler.z = 4; // alpha
- }
- break;
- default:
- NOTIMPLEMENTED();
- }
-
- if (sensor) {
- sensor->set_reading(reading);
-
- auto init_params = device::mojom::SensorInitParams::New();
- init_params->client_request = sensor->GetClient();
- init_params->memory = sensor->GetSharedBufferHandle();
- init_params->buffer_offset = sensor->GetBufferOffset();
- init_params->default_configuration = sensor->GetDefaultConfiguration();
- init_params->maximum_frequency = sensor->GetMaximumSupportedFrequency();
- init_params->minimum_frequency = sensor->GetMinimumSupportedFrequency();
-
- mojo::MakeStrongBinding(std::move(sensor),
- mojo::MakeRequest(&init_params->sensor));
- std::move(callback).Run(device::mojom::SensorCreationResult::SUCCESS,
- std::move(init_params));
- } else {
- std::move(callback).Run(
- device::mojom::SensorCreationResult::ERROR_NOT_AVAILABLE, nullptr);
- }
- }
-
- private:
- mojo::Binding<device::mojom::SensorProvider> binding_;
- bool accelerometer_is_available_ = true;
- bool linear_acceleration_sensor_is_available_ = true;
- bool gyroscope_is_available_ = true;
- bool relative_orientation_sensor_is_available_ = true;
- bool absolute_orientation_sensor_is_available_ = true;
-
- DISALLOW_COPY_AND_ASSIGN(FakeSensorProvider);
-};
+using device::FakeSensorProvider;
class DeviceSensorBrowserTest : public ContentBrowserTest {
public:
@@ -287,6 +62,11 @@ class DeviceSensorBrowserTest : public ContentBrowserTest {
https_embedded_test_server_->StartAcceptingConnections();
sensor_provider_ = std::make_unique<FakeSensorProvider>();
+ sensor_provider_->SetAccelerometerData(4, 5, 6);
+ sensor_provider_->SetLinearAccelerationSensorData(1, 2, 3);
+ sensor_provider_->SetGyroscopeData(7, 8, 9);
+ sensor_provider_->SetRelativeOrientationSensorData(1, 2, 3);
+ sensor_provider_->SetAbsoluteOrientationSensorData(4, 5, 6);
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&DeviceSensorBrowserTest::SetUpOnIOThread,
@@ -306,8 +86,7 @@ class DeviceSensorBrowserTest : public ContentBrowserTest {
// it.
service_manager::ServiceContext::SetGlobalBinderForTesting(
device::mojom::kServiceName, device::mojom::SensorProvider::Name_,
- base::Bind(&FakeSensorProvider::Bind,
- base::Unretained(sensor_provider_.get())));
+ base::Bind(&DeviceSensorBrowserTest::Bind, base::Unretained(this)));
io_loop_finished_event_.Signal();
}
@@ -333,6 +112,13 @@ class DeviceSensorBrowserTest : public ContentBrowserTest {
std::unique_ptr<net::EmbeddedTestServer> https_embedded_test_server_;
private:
+ void Bind(const std::string& interface_name,
+ mojo::ScopedMessagePipeHandle handle,
+ const service_manager::BindSourceInfo& source_info) {
+ sensor_provider_->Bind(
+ device::mojom::SensorProviderRequest(std::move(handle)));
+ }
+
base::WaitableEvent io_loop_finished_event_;
};
diff --git a/chromium/content/browser/devtools/BUILD.gn b/chromium/content/browser/devtools/BUILD.gn
index 611d0281158..2e5ef6a415e 100644
--- a/chromium/content/browser/devtools/BUILD.gn
+++ b/chromium/content/browser/devtools/BUILD.gn
@@ -15,13 +15,14 @@ group("resources") {
}
compressed_protocol_file =
- "$root_gen_dir/blink/core/inspector/protocol.json.bro"
+ "$root_gen_dir/third_party/blink/renderer/core/inspector/protocol.json.bro"
compress_file_brotli("compressed_protocol_json") {
- input_file = "$root_gen_dir/blink/core/inspector/protocol.json"
+ input_file =
+ "$root_gen_dir/third_party/blink/renderer/core/inspector/protocol.json"
output_file = compressed_protocol_file
deps = [
- "//third_party/WebKit/Source/core/inspector:protocol_version",
+ "//third_party/blink/renderer/core/inspector:protocol_version",
]
}
@@ -49,18 +50,18 @@ grit("devtools_resources") {
":compressed_protocol_json",
# This is the action that generates out .grd input file.
- "//third_party/WebKit/public:blink_generate_devtools_grd",
+ "//third_party/blink/public:blink_generate_devtools_grd",
]
}
inspector_protocol_generate("protocol_sources") {
visibility = [ "//content/browser" ]
deps = [
- "//third_party/WebKit/Source/core/inspector:protocol_version",
+ "//third_party/blink/renderer/core/inspector:protocol_version",
]
- _blink_protocol_path =
- rebase_path("$root_gen_dir/blink/core/inspector/protocol.json",
- root_build_dir)
+ _blink_protocol_path = rebase_path(
+ "$root_gen_dir/third_party/blink/renderer/core/inspector/protocol.json",
+ root_build_dir)
inspector_protocol_dir = "//third_party/inspector_protocol"
out_dir = target_gen_dir
@@ -68,7 +69,7 @@ inspector_protocol_generate("protocol_sources") {
config_values = [ "protocol.path=$_blink_protocol_path" ]
inputs = [
- "$root_gen_dir/blink/core/inspector/protocol.json",
+ "$root_gen_dir/third_party/blink/renderer/core/inspector/protocol.json",
config_file,
]
diff --git a/chromium/content/browser/devtools/browser_devtools_agent_host.cc b/chromium/content/browser/devtools/browser_devtools_agent_host.cc
index 6475584ed6b..bd0c4705380 100644
--- a/chromium/content/browser/devtools/browser_devtools_agent_host.cc
+++ b/chromium/content/browser/devtools/browser_devtools_agent_host.cc
@@ -31,7 +31,7 @@ scoped_refptr<DevToolsAgentHost> DevToolsAgentHost::CreateForBrowser(
scoped_refptr<DevToolsAgentHost> DevToolsAgentHost::CreateForDiscovery() {
CreateServerSocketCallback null_callback;
- return new BrowserDevToolsAgentHost(nullptr, null_callback, true);
+ return new BrowserDevToolsAgentHost(nullptr, std::move(null_callback), true);
}
BrowserDevToolsAgentHost::BrowserDevToolsAgentHost(
@@ -48,12 +48,15 @@ BrowserDevToolsAgentHost::BrowserDevToolsAgentHost(
BrowserDevToolsAgentHost::~BrowserDevToolsAgentHost() {
}
-void BrowserDevToolsAgentHost::AttachSession(DevToolsSession* session) {
+bool BrowserDevToolsAgentHost::AttachSession(DevToolsSession* session) {
+ if (session->restricted())
+ return false;
+
session->SetBrowserOnly(true);
session->AddHandler(
base::WrapUnique(new protocol::TargetHandler(true /* browser_only */)));
if (only_discovery_)
- return;
+ return true;
session->AddHandler(base::WrapUnique(new protocol::BrowserHandler()));
session->AddHandler(base::WrapUnique(new protocol::IOHandler(
@@ -63,10 +66,9 @@ void BrowserDevToolsAgentHost::AttachSession(DevToolsSession* session) {
session->AddHandler(base::WrapUnique(new protocol::SystemInfoHandler()));
session->AddHandler(base::WrapUnique(new protocol::TetheringHandler(
socket_callback_, tethering_task_runner_)));
- session->AddHandler(base::WrapUnique(new protocol::TracingHandler(
- protocol::TracingHandler::Browser,
- FrameTreeNode::kFrameTreeNodeInvalidId,
- GetIOContext())));
+ session->AddHandler(
+ base::WrapUnique(new protocol::TracingHandler(nullptr, GetIOContext())));
+ return true;
}
void BrowserDevToolsAgentHost::DetachSession(DevToolsSession* session) {}
diff --git a/chromium/content/browser/devtools/browser_devtools_agent_host.h b/chromium/content/browser/devtools/browser_devtools_agent_host.h
index b7576135a7c..7022e2d167c 100644
--- a/chromium/content/browser/devtools/browser_devtools_agent_host.h
+++ b/chromium/content/browser/devtools/browser_devtools_agent_host.h
@@ -19,7 +19,7 @@ class BrowserDevToolsAgentHost : public DevToolsAgentHostImpl {
~BrowserDevToolsAgentHost() override;
// DevToolsAgentHostImpl implementation.
- void AttachSession(DevToolsSession* session) override;
+ bool AttachSession(DevToolsSession* session) override;
void DetachSession(DevToolsSession* session) override;
void DispatchProtocolMessage(DevToolsSession* session,
const std::string& message) override;
diff --git a/chromium/content/browser/devtools/devtools_agent_host_impl.cc b/chromium/content/browser/devtools/devtools_agent_host_impl.cc
index 775bec85a36..7c9b58aa5e1 100644
--- a/chromium/content/browser/devtools/devtools_agent_host_impl.cc
+++ b/chromium/content/browser/devtools/devtools_agent_host_impl.cc
@@ -176,23 +176,37 @@ DevToolsSession* DevToolsAgentHostImpl::SessionByClient(
return it == session_by_client_.end() ? nullptr : it->second.get();
}
-void DevToolsAgentHostImpl::InnerAttachClient(DevToolsAgentHostClient* client) {
+bool DevToolsAgentHostImpl::InnerAttachClient(DevToolsAgentHostClient* client,
+ bool restricted) {
scoped_refptr<DevToolsAgentHostImpl> protect(this);
- DevToolsSession* session = new DevToolsSession(this, client);
+ DevToolsSession* session = new DevToolsSession(this, client, restricted);
sessions_.insert(session);
session_by_client_[client].reset(session);
- AttachSession(session);
+ if (!AttachSession(session)) {
+ sessions_.erase(session);
+ session_by_client_.erase(client);
+ return false;
+ }
+
if (sessions_.size() == 1)
NotifyAttached();
DevToolsManager* manager = DevToolsManager::GetInstance();
if (manager->delegate())
manager->delegate()->ClientAttached(this, client);
+ return true;
}
void DevToolsAgentHostImpl::AttachClient(DevToolsAgentHostClient* client) {
if (SessionByClient(client))
return;
- InnerAttachClient(client);
+ InnerAttachClient(client, false /* restricted */);
+}
+
+bool DevToolsAgentHostImpl::AttachRestrictedClient(
+ DevToolsAgentHostClient* client) {
+ if (SessionByClient(client))
+ return false;
+ return InnerAttachClient(client, true /* restricted */);
}
void DevToolsAgentHostImpl::ForceAttachClient(DevToolsAgentHostClient* client) {
@@ -200,9 +214,9 @@ void DevToolsAgentHostImpl::ForceAttachClient(DevToolsAgentHostClient* client) {
return;
scoped_refptr<DevToolsAgentHostImpl> protect(this);
if (!sessions_.empty())
- ForceDetachAllClients();
+ ForceDetachAllSessions();
DCHECK(sessions_.empty());
- InnerAttachClient(client);
+ InnerAttachClient(client, false /* restricted */);
}
bool DevToolsAgentHostImpl::DetachClient(DevToolsAgentHostClient* client) {
@@ -298,16 +312,34 @@ bool DevToolsAgentHostImpl::Inspect() {
return false;
}
-void DevToolsAgentHostImpl::ForceDetachAllClients() {
+void DevToolsAgentHostImpl::ForceDetachAllSessions() {
scoped_refptr<DevToolsAgentHostImpl> protect(this);
- while (!session_by_client_.empty()) {
- DevToolsAgentHostClient* client = session_by_client_.begin()->first;
- InnerDetachClient(client);
+ while (!sessions_.empty()) {
+ DevToolsAgentHostClient* client = (*sessions_.begin())->client();
+ DetachClient(client);
client->AgentHostClosed(this);
}
}
-void DevToolsAgentHostImpl::AttachSession(DevToolsSession* session) {}
+void DevToolsAgentHostImpl::ForceDetachRestrictedSessions() {
+ if (sessions_.empty())
+ return;
+ scoped_refptr<DevToolsAgentHostImpl> protect(this);
+ std::vector<DevToolsSession*> restricted;
+ for (DevToolsSession* session : sessions_) {
+ if (session->restricted())
+ restricted.push_back(session);
+ }
+ for (DevToolsSession* session : restricted) {
+ DevToolsAgentHostClient* client = session->client();
+ DetachClient(client);
+ client->AgentHostClosed(this);
+ }
+}
+
+bool DevToolsAgentHostImpl::AttachSession(DevToolsSession* session) {
+ return false;
+}
void DevToolsAgentHostImpl::DetachSession(DevToolsSession* session) {}
@@ -325,7 +357,7 @@ void DevToolsAgentHost::DetachAllClients() {
DevToolsMap copy = g_devtools_instances.Get();
for (DevToolsMap::iterator it(copy.begin()); it != copy.end(); ++it) {
DevToolsAgentHostImpl* agent_host = it->second;
- agent_host->ForceDetachAllClients();
+ agent_host->ForceDetachAllSessions();
}
}
diff --git a/chromium/content/browser/devtools/devtools_agent_host_impl.h b/chromium/content/browser/devtools/devtools_agent_host_impl.h
index 20178938a01..c69bf5a70f2 100644
--- a/chromium/content/browser/devtools/devtools_agent_host_impl.h
+++ b/chromium/content/browser/devtools/devtools_agent_host_impl.h
@@ -16,7 +16,7 @@
#include "content/common/content_export.h"
#include "content/public/browser/certificate_request_result_type.h"
#include "content/public/browser/devtools_agent_host.h"
-#include "third_party/WebKit/public/web/devtools_agent.mojom.h"
+#include "third_party/blink/public/web/devtools_agent.mojom.h"
namespace content {
@@ -37,6 +37,7 @@ class CONTENT_EXPORT DevToolsAgentHostImpl : public DevToolsAgentHost {
// DevToolsAgentHost implementation.
void AttachClient(DevToolsAgentHostClient* client) override;
+ bool AttachRestrictedClient(DevToolsAgentHostClient* client) override;
void ForceAttachClient(DevToolsAgentHostClient* client) override;
bool DetachClient(DevToolsAgentHostClient* client) override;
bool DispatchProtocolMessage(DevToolsAgentHostClient* client,
@@ -63,14 +64,16 @@ class CONTENT_EXPORT DevToolsAgentHostImpl : public DevToolsAgentHost {
static bool ShouldForceCreation();
- virtual void AttachSession(DevToolsSession* session);
+ // Returning |false| will block the attach.
+ virtual bool AttachSession(DevToolsSession* session);
virtual void DetachSession(DevToolsSession* session);
virtual void DispatchProtocolMessage(DevToolsSession* session,
const std::string& message);
void NotifyCreated();
void NotifyNavigated();
- void ForceDetachAllClients();
+ void ForceDetachAllSessions();
+ void ForceDetachRestrictedSessions();
DevToolsIOContext* GetIOContext() { return &io_context_; }
base::flat_set<DevToolsSession*>& sessions() { return sessions_; }
@@ -78,7 +81,7 @@ class CONTENT_EXPORT DevToolsAgentHostImpl : public DevToolsAgentHost {
private:
friend class DevToolsAgentHost; // for static methods
friend class DevToolsSession;
- void InnerAttachClient(DevToolsAgentHostClient* client);
+ bool InnerAttachClient(DevToolsAgentHostClient* client, bool restricted);
void InnerDetachClient(DevToolsAgentHostClient* client);
void NotifyAttached();
void NotifyDetached();
diff --git a/chromium/content/browser/devtools/devtools_frame_trace_recorder_for_viz.cc b/chromium/content/browser/devtools/devtools_frame_trace_recorder_for_viz.cc
deleted file mode 100644
index ab433746a7e..00000000000
--- a/chromium/content/browser/devtools/devtools_frame_trace_recorder_for_viz.cc
+++ /dev/null
@@ -1,118 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/devtools/devtools_frame_trace_recorder_for_viz.h"
-
-#include "cc/paint/skia_paint_canvas.h"
-#include "components/viz/host/host_frame_sink_manager.h"
-#include "content/browser/compositor/surface_utils.h"
-#include "content/browser/devtools/devtools_frame_trace_recorder.h"
-#include "content/browser/devtools/devtools_traceable_screenshot.h"
-#include "media/renderers/paint_canvas_video_renderer.h"
-
-namespace content {
-
-namespace {
-
-static constexpr gfx::Size kMaxFrameSize = gfx::Size(500, 500);
-
-} // namespace
-
-DevToolsFrameTraceRecorderForViz::DevToolsFrameTraceRecorderForViz()
- : binding_(this) {}
-
-DevToolsFrameTraceRecorderForViz::~DevToolsFrameTraceRecorderForViz() = default;
-
-void DevToolsFrameTraceRecorderForViz::StartCapture() {
- // Early out if we're already capturing,
- if (video_capturer_)
- return;
- GetHostFrameSinkManager()->CreateVideoCapturer(
- mojo::MakeRequest(&video_capturer_));
- video_capturer_->SetResolutionConstraints(gfx::Size(1, 1), kMaxFrameSize,
- false);
- video_capturer_->SetMinCapturePeriod(base::TimeDelta::FromMilliseconds(10));
- viz::mojom::FrameSinkVideoConsumerPtr consumer;
- binding_.Bind(mojo::MakeRequest(&consumer));
- video_capturer_->ChangeTarget(frame_sink_id_);
- video_capturer_->Start(std::move(consumer));
- number_of_screenshots_ = 0;
-}
-
-void DevToolsFrameTraceRecorderForViz::StopCapture() {
- if (!video_capturer_)
- return;
- binding_.Close();
- video_capturer_->Stop();
- video_capturer_.reset();
-}
-
-void DevToolsFrameTraceRecorderForViz::SetFrameSinkId(
- const viz::FrameSinkId& frame_sink_id) {
- frame_sink_id_ = frame_sink_id;
- if (video_capturer_)
- video_capturer_->ChangeTarget(frame_sink_id_);
-}
-
-void DevToolsFrameTraceRecorderForViz::OnFrameCaptured(
- mojo::ScopedSharedBufferHandle buffer,
- uint32_t buffer_size,
- ::media::mojom::VideoFrameInfoPtr info,
- const gfx::Rect& update_rect,
- const gfx::Rect& content_rect,
- viz::mojom::FrameSinkVideoConsumerFrameCallbacksPtr callbacks) {
- if (!buffer.is_valid()) {
- callbacks->Done();
- return;
- }
-
- mojo::ScopedSharedBufferMapping mapping = buffer->Map(buffer_size);
- if (!mapping) {
- DLOG(ERROR) << "Shared memory mapping failed.";
- return;
- }
-
- scoped_refptr<media::VideoFrame> frame;
- frame = media::VideoFrame::WrapExternalData(
- info->pixel_format, info->coded_size, info->visible_rect,
- info->visible_rect.size(), static_cast<uint8_t*>(mapping.get()),
- buffer_size, info->timestamp);
- if (!frame)
- return;
- frame->AddDestructionObserver(base::BindOnce(
- [](mojo::ScopedSharedBufferMapping mapping) {}, std::move(mapping)));
-
- media::PaintCanvasVideoRenderer renderer;
- SkBitmap skbitmap;
- skbitmap.allocN32Pixels(info->visible_rect.width(),
- info->visible_rect.height());
- cc::SkiaPaintCanvas canvas(skbitmap);
- renderer.Copy(frame, &canvas, media::Context3D());
- callbacks->Done();
-
- DCHECK(info->metadata);
- frame->metadata()->MergeInternalValuesFrom(*info->metadata);
- base::TimeTicks reference_time;
- const bool had_reference_time = frame->metadata()->GetTimeTicks(
- media::VideoFrameMetadata::REFERENCE_TIME, &reference_time);
- DCHECK(had_reference_time);
-
- TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID_AND_TIMESTAMP(
- TRACE_DISABLED_BY_DEFAULT("devtools.screenshot"), "Screenshot", 1,
- reference_time,
- std::unique_ptr<base::trace_event::ConvertableToTraceFormat>(
- new DevToolsTraceableScreenshot(skbitmap)));
-
- ++number_of_screenshots_;
- if (number_of_screenshots_ >=
- DevToolsFrameTraceRecorder::kMaximumNumberOfScreenshots)
- StopCapture();
-}
-
-void DevToolsFrameTraceRecorderForViz::OnTargetLost(
- const viz::FrameSinkId& frame_sink_id) {}
-
-void DevToolsFrameTraceRecorderForViz::OnStopped() {}
-
-} // namespace content
diff --git a/chromium/content/browser/devtools/devtools_frame_trace_recorder_for_viz.h b/chromium/content/browser/devtools/devtools_frame_trace_recorder_for_viz.h
deleted file mode 100644
index d459e1c139d..00000000000
--- a/chromium/content/browser/devtools/devtools_frame_trace_recorder_for_viz.h
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_DEVTOOLS_DEVTOOLS_FRAME_TRACE_RECORDER_FOR_VIZ_H_
-#define CONTENT_BROWSER_DEVTOOLS_DEVTOOLS_FRAME_TRACE_RECORDER_FOR_VIZ_H_
-
-#include "mojo/public/cpp/bindings/binding.h"
-#include "services/viz/privileged/interfaces/compositing/frame_sink_video_capture.mojom.h"
-
-namespace content {
-
-// Captures snapshots of the page being traced. Used when the
-// VizDisplayCompositor feature is enabled.
-// TODO(https://crbug.com/813929): Use this class everywhere even if viz is not
-// enabled and remove DevToolsFrameTraceRecorder.
-class DevToolsFrameTraceRecorderForViz
- : public viz::mojom::FrameSinkVideoConsumer {
- public:
- DevToolsFrameTraceRecorderForViz();
- ~DevToolsFrameTraceRecorderForViz() override;
-
- void StartCapture();
- void StopCapture();
- void SetFrameSinkId(const viz::FrameSinkId& frame_sink_id);
-
- // viz::mojom::FrameSinkVideoConsumer implementation.
- void OnFrameCaptured(
- mojo::ScopedSharedBufferHandle buffer,
- uint32_t buffer_size,
- ::media::mojom::VideoFrameInfoPtr info,
- const gfx::Rect& update_rect,
- const gfx::Rect& content_rect,
- viz::mojom::FrameSinkVideoConsumerFrameCallbacksPtr callbacks) override;
- void OnTargetLost(const viz::FrameSinkId& frame_sink_id) override;
- void OnStopped() override;
-
- private:
- viz::mojom::FrameSinkVideoCapturerPtr video_capturer_;
- mojo::Binding<viz::mojom::FrameSinkVideoConsumer> binding_;
- viz::FrameSinkId frame_sink_id_;
- int number_of_screenshots_ = 0;
-
- DISALLOW_COPY_AND_ASSIGN(DevToolsFrameTraceRecorderForViz);
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_DEVTOOLS_DEVTOOLS_FRAME_TRACE_RECORDER_FOR_VIZ_H_
diff --git a/chromium/content/browser/devtools/devtools_frontend_host_impl.cc b/chromium/content/browser/devtools/devtools_frontend_host_impl.cc
index eacded0190a..8fe9445564e 100644
--- a/chromium/content/browser/devtools/devtools_frontend_host_impl.cc
+++ b/chromium/content/browser/devtools/devtools_frontend_host_impl.cc
@@ -12,7 +12,7 @@
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_client.h"
-#include "third_party/WebKit/public/common/associated_interfaces/associated_interface_provider.h"
+#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
namespace content {
diff --git a/chromium/content/browser/devtools/devtools_frontend_host_impl.h b/chromium/content/browser/devtools/devtools_frontend_host_impl.h
index 0b4275e577e..43f03d2dfb3 100644
--- a/chromium/content/browser/devtools/devtools_frontend_host_impl.h
+++ b/chromium/content/browser/devtools/devtools_frontend_host_impl.h
@@ -8,7 +8,7 @@
#include "base/macros.h"
#include "content/public/browser/devtools_frontend_host.h"
#include "mojo/public/cpp/bindings/associated_binding.h"
-#include "third_party/WebKit/public/web/devtools_frontend.mojom.h"
+#include "third_party/blink/public/web/devtools_frontend.mojom.h"
namespace content {
diff --git a/chromium/content/browser/devtools/devtools_http_handler.cc b/chromium/content/browser/devtools/devtools_http_handler.cc
index 26c4f50fad5..cae7c566146 100644
--- a/chromium/content/browser/devtools/devtools_http_handler.cc
+++ b/chromium/content/browser/devtools/devtools_http_handler.cc
@@ -369,6 +369,10 @@ static bool TimeComparator(scoped_refptr<DevToolsAgentHost> host1,
// DevToolsHttpHandler -------------------------------------------------------
DevToolsHttpHandler::~DevToolsHttpHandler() {
+ // Disconnecting sessions might lead to the last minute messages generated
+ // by the targets. It is essential that this happens before we issue delete
+ // soon for the server wrapper.
+ connection_to_client_.clear();
TerminateOnUI(std::move(thread_), std::move(server_wrapper_),
std::move(socket_factory_));
}
@@ -568,8 +572,9 @@ void DevToolsHttpHandler::OnJsonRequest(
kTargetWebSocketDebuggerUrlField,
base::StringPrintf("ws://%s%s", host.c_str(), browser_guid_.c_str()));
#if defined(OS_ANDROID)
- version.SetString("Android-Package",
- base::android::BuildInfo::GetInstance()->package_name());
+ version.SetString(
+ "Android-Package",
+ base::android::BuildInfo::GetInstance()->host_package_name());
#endif
SendJson(connection_id, net::HTTP_OK, &version, std::string());
return;
diff --git a/chromium/content/browser/devtools/devtools_interceptor_controller.cc b/chromium/content/browser/devtools/devtools_interceptor_controller.cc
index 77de8fe584f..a2c27cba5df 100644
--- a/chromium/content/browser/devtools/devtools_interceptor_controller.cc
+++ b/chromium/content/browser/devtools/devtools_interceptor_controller.cc
@@ -4,11 +4,11 @@
#include "content/browser/devtools/devtools_interceptor_controller.h"
-#include "base/memory/ptr_util.h"
#include "base/supports_user_data.h"
#include "content/browser/frame_host/frame_tree_node.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/browser/browser_context.h"
+#include "content/public/browser/browser_thread.h"
namespace content {
diff --git a/chromium/content/browser/devtools/devtools_io_context.cc b/chromium/content/browser/devtools/devtools_io_context.cc
index 24a756c05ad..1e0ae3d9eee 100644
--- a/chromium/content/browser/devtools/devtools_io_context.cc
+++ b/chromium/content/browser/devtools/devtools_io_context.cc
@@ -8,7 +8,6 @@
#include "base/containers/queue.h"
#include "base/files/file.h"
#include "base/files/file_util.h"
-#include "base/memory/ptr_util.h"
#include "base/sequenced_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
diff --git a/chromium/content/browser/devtools/devtools_manager.cc b/chromium/content/browser/devtools/devtools_manager.cc
index 6336ea21da7..241e5039fa9 100644
--- a/chromium/content/browser/devtools/devtools_manager.cc
+++ b/chromium/content/browser/devtools/devtools_manager.cc
@@ -5,7 +5,6 @@
#include "content/browser/devtools/devtools_manager.h"
#include "base/bind.h"
-#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "content/browser/devtools/devtools_agent_host_impl.h"
#include "content/browser/devtools/devtools_http_handler.h"
diff --git a/chromium/content/browser/devtools/devtools_network_interceptor.cc b/chromium/content/browser/devtools/devtools_network_interceptor.cc
index 812f543da2a..8213acf5d97 100644
--- a/chromium/content/browser/devtools/devtools_network_interceptor.cc
+++ b/chromium/content/browser/devtools/devtools_network_interceptor.cc
@@ -3,6 +3,9 @@
// found in the LICENSE file.
#include "content/browser/devtools/devtools_network_interceptor.h"
+#include "base/strings/pattern.h"
+#include "content/browser/devtools/protocol/network_handler.h"
+#include "url/gurl.h"
namespace content {
@@ -22,4 +25,50 @@ DevToolsNetworkInterceptor::FilterEntry::FilterEntry(
DevToolsNetworkInterceptor::FilterEntry::FilterEntry(FilterEntry&&) {}
DevToolsNetworkInterceptor::FilterEntry::~FilterEntry() {}
+DevToolsNetworkInterceptor::Modifications::Modifications()
+ : mark_as_canceled(false) {}
+
+DevToolsNetworkInterceptor::Modifications::Modifications(
+ base::Optional<net::Error> error_reason,
+ base::Optional<std::string> raw_response,
+ protocol::Maybe<std::string> modified_url,
+ protocol::Maybe<std::string> modified_method,
+ protocol::Maybe<std::string> modified_post_data,
+ protocol::Maybe<protocol::Network::Headers> modified_headers,
+ protocol::Maybe<protocol::Network::AuthChallengeResponse>
+ auth_challenge_response,
+ bool mark_as_canceled)
+ : error_reason(std::move(error_reason)),
+ raw_response(std::move(raw_response)),
+ modified_url(std::move(modified_url)),
+ modified_method(std::move(modified_method)),
+ modified_post_data(std::move(modified_post_data)),
+ modified_headers(std::move(modified_headers)),
+ auth_challenge_response(std::move(auth_challenge_response)),
+ mark_as_canceled(mark_as_canceled) {}
+
+DevToolsNetworkInterceptor::Modifications::~Modifications() {}
+
+DevToolsNetworkInterceptor::Pattern::~Pattern() = default;
+
+DevToolsNetworkInterceptor::Pattern::Pattern(const Pattern& other) = default;
+
+DevToolsNetworkInterceptor::Pattern::Pattern(
+ const std::string& url_pattern,
+ base::flat_set<ResourceType> resource_types,
+ InterceptionStage interception_stage)
+ : url_pattern(url_pattern),
+ resource_types(std::move(resource_types)),
+ interception_stage(interception_stage) {}
+
+bool DevToolsNetworkInterceptor::Pattern::Matches(
+ const std::string& url,
+ ResourceType resource_type) const {
+ if (!resource_types.empty() &&
+ resource_types.find(resource_type) == resource_types.end()) {
+ return false;
+ }
+ return base::MatchPattern(url, url_pattern);
+}
+
} // namespace content
diff --git a/chromium/content/browser/devtools/devtools_network_interceptor.h b/chromium/content/browser/devtools/devtools_network_interceptor.h
index 59769bf7e01..97c64bc6257 100644
--- a/chromium/content/browser/devtools/devtools_network_interceptor.h
+++ b/chromium/content/browser/devtools/devtools_network_interceptor.h
@@ -35,6 +35,8 @@ struct InterceptedRequestInfo {
class DevToolsNetworkInterceptor {
public:
+ virtual ~DevToolsNetworkInterceptor() = default;
+
using RequestInterceptedCallback =
base::RepeatingCallback<void(std::unique_ptr<InterceptedRequestInfo>)>;
using ContinueInterceptedRequestCallback =
@@ -43,6 +45,7 @@ class DevToolsNetworkInterceptor {
protocol::Network::Backend::GetResponseBodyForInterceptionCallback;
struct Modifications {
+ Modifications();
Modifications(base::Optional<net::Error> error_reason,
base::Optional<std::string> raw_response,
protocol::Maybe<std::string> modified_url,
@@ -73,25 +76,27 @@ class DevToolsNetworkInterceptor {
};
enum InterceptionStage {
- REQUEST,
- RESPONSE,
+ DONT_INTERCEPT = 0,
+ REQUEST = (1 << 0),
+ RESPONSE = (1 << 1),
// Note: Both is not sent from front-end. It is used if both Request
// and HeadersReceived was found it upgrades it to Both.
- BOTH,
- DONT_INTERCEPT
+ BOTH = (REQUEST | RESPONSE),
};
struct Pattern {
public:
- Pattern();
~Pattern();
Pattern(const Pattern& other);
Pattern(const std::string& url_pattern,
base::flat_set<ResourceType> resource_types,
InterceptionStage interception_stage);
+
+ bool Matches(const std::string& url, ResourceType resource_type) const;
+
const std::string url_pattern;
const base::flat_set<ResourceType> resource_types;
- InterceptionStage interception_stage;
+ const InterceptionStage interception_stage;
};
struct FilterEntry {
@@ -121,6 +126,13 @@ class DevToolsNetworkInterceptor {
std::unique_ptr<ContinueInterceptedRequestCallback> callback) = 0;
};
+inline DevToolsNetworkInterceptor::InterceptionStage& operator|=(
+ DevToolsNetworkInterceptor::InterceptionStage& a,
+ const DevToolsNetworkInterceptor::InterceptionStage& b) {
+ a = static_cast<DevToolsNetworkInterceptor::InterceptionStage>(a | b);
+ return a;
+}
+
} // namespace content
#endif // CONTENT_BROWSER_DEVTOOLS_DEVTOOLS_NETWORK_INTERCEPTOR_H_
diff --git a/chromium/content/browser/devtools/devtools_pipe_handler.cc b/chromium/content/browser/devtools/devtools_pipe_handler.cc
index dce8d284663..4fbea246102 100644
--- a/chromium/content/browser/devtools/devtools_pipe_handler.cc
+++ b/chromium/content/browser/devtools/devtools_pipe_handler.cc
@@ -16,7 +16,6 @@
#include <string>
#include "base/bind.h"
#include "base/files/file_util.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted_memory.h"
#include "base/message_loop/message_loop.h"
#include "base/sequenced_task_runner.h"
diff --git a/chromium/content/browser/devtools/devtools_session.cc b/chromium/content/browser/devtools/devtools_session.cc
index 61d9b790cbc..b31ca0ada8b 100644
--- a/chromium/content/browser/devtools/devtools_session.cc
+++ b/chromium/content/browser/devtools/devtools_session.cc
@@ -24,16 +24,20 @@ bool ShouldSendOnIO(const std::string& method) {
method == "Debugger.setBreakpointByUrl" ||
method == "Debugger.removeBreakpoint" ||
method == "Debugger.setBreakpointsActive" ||
- method == "Performance.getMetrics" || method == "Page.crash";
+ method == "Performance.getMetrics" || method == "Page.crash" ||
+ method == "Runtime.terminateExecution" ||
+ method == "Emulation.setScriptExecutionDisabled";
}
} // namespace
DevToolsSession::DevToolsSession(DevToolsAgentHostImpl* agent_host,
- DevToolsAgentHostClient* client)
+ DevToolsAgentHostClient* client,
+ bool restricted)
: binding_(this),
agent_host_(agent_host),
client_(client),
+ restricted_(restricted),
process_host_id_(ChildProcessHost::kInvalidUniqueID),
host_(nullptr),
dispatcher_(new protocol::UberDispatcher(this)),
@@ -123,12 +127,6 @@ void DevToolsSession::DispatchProtocolMessage(const std::string& message) {
if (delegate->HandleCommand(agent_host_, client_, dict_value))
return;
-
- if (delegate->HandleAsyncCommand(agent_host_, client_, dict_value,
- base::Bind(&DevToolsSession::SendResponse,
- weak_factory_.GetWeakPtr()))) {
- return;
- }
}
int call_id;
diff --git a/chromium/content/browser/devtools/devtools_session.h b/chromium/content/browser/devtools/devtools_session.h
index d7dd60140c4..ea900e26bb3 100644
--- a/chromium/content/browser/devtools/devtools_session.h
+++ b/chromium/content/browser/devtools/devtools_session.h
@@ -14,7 +14,7 @@
#include "content/browser/devtools/devtools_agent_host_impl.h"
#include "content/browser/devtools/protocol/devtools_domain_handler.h"
#include "mojo/public/cpp/bindings/associated_binding.h"
-#include "third_party/WebKit/public/web/devtools_agent.mojom.h"
+#include "third_party/blink/public/web/devtools_agent.mojom.h"
namespace content {
@@ -25,9 +25,13 @@ class DevToolsSession : public protocol::FrontendChannel,
public blink::mojom::DevToolsSessionHost {
public:
DevToolsSession(DevToolsAgentHostImpl* agent_host,
- DevToolsAgentHostClient* client);
+ DevToolsAgentHostClient* client,
+ bool restricted);
~DevToolsSession() override;
+ bool restricted() { return restricted_; }
+ DevToolsAgentHostClient* client() { return client_; };
+
// Browser-only sessions do not talk to mojom::DevToolsAgent, but instead
// handle all protocol messages locally in the browser process.
void SetBrowserOnly(bool browser_only);
@@ -83,6 +87,7 @@ class DevToolsSession : public protocol::FrontendChannel,
blink::mojom::DevToolsSessionPtr io_session_ptr_;
DevToolsAgentHostImpl* agent_host_;
DevToolsAgentHostClient* client_;
+ bool restricted_;
bool browser_only_ = false;
base::flat_map<std::string, std::unique_ptr<protocol::DevToolsDomainHandler>>
handlers_;
diff --git a/chromium/content/browser/devtools/devtools_target_registry.cc b/chromium/content/browser/devtools/devtools_target_registry.cc
index eefc74d8d0a..a426d9e1924 100644
--- a/chromium/content/browser/devtools/devtools_target_registry.cc
+++ b/chromium/content/browser/devtools/devtools_target_registry.cc
@@ -9,6 +9,7 @@
#include "content/browser/frame_host/frame_tree_node.h"
#include "content/browser/frame_host/render_frame_host_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents_observer.h"
namespace content {
diff --git a/chromium/content/browser/devtools/devtools_traceable_screenshot.h b/chromium/content/browser/devtools/devtools_traceable_screenshot.h
index b9f9605379c..bd6afd2271b 100644
--- a/chromium/content/browser/devtools/devtools_traceable_screenshot.h
+++ b/chromium/content/browser/devtools/devtools_traceable_screenshot.h
@@ -19,14 +19,14 @@ class DevToolsTraceableScreenshot
DevToolsTraceableScreenshot(const SkBitmap& bitmap);
+ ~DevToolsTraceableScreenshot() override;
+
// base::trace_event::ConvertableToTraceFormat implementation.
void AppendAsTraceFormat(std::string* out) const override;
private:
static base::subtle::Atomic32 number_of_instances_;
- ~DevToolsTraceableScreenshot() override;
-
SkBitmap frame_;
DISALLOW_COPY_AND_ASSIGN(DevToolsTraceableScreenshot);
diff --git a/chromium/content/browser/devtools/devtools_url_interceptor_request_job.cc b/chromium/content/browser/devtools/devtools_url_interceptor_request_job.cc
index 91a151c75ea..3c9d31b784b 100644
--- a/chromium/content/browser/devtools/devtools_url_interceptor_request_job.cc
+++ b/chromium/content/browser/devtools/devtools_url_interceptor_request_job.cc
@@ -5,7 +5,6 @@
#include "content/browser/devtools/devtools_url_interceptor_request_job.h"
#include "base/base64.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "content/browser/devtools/protocol/network_handler.h"
@@ -448,6 +447,8 @@ int DevToolsURLInterceptorRequestJob::MockResponseDetails::ReadRawData(
namespace {
+using DevToolsStatus = ResourceRequestInfoImpl::DevToolsStatus;
+
void SendPendingBodyRequestsOnUiThread(
std::vector<std::unique_ptr<
protocol::Network::Backend::GetResponseBodyForInterceptionCallback>>
@@ -522,6 +523,14 @@ std::unique_ptr<net::UploadDataStream> GetUploadData(net::URLRequest* request) {
std::move(proxy_readers), 0);
}
+void SetDevToolsStatus(net::URLRequest* request,
+ DevToolsStatus devtools_status) {
+ ResourceRequestInfoImpl* resource_request_info =
+ ResourceRequestInfoImpl::ForRequest(request);
+ DCHECK(resource_request_info);
+ resource_request_info->set_devtools_status(devtools_status);
+}
+
} // namespace
DevToolsURLInterceptorRequestJob::DevToolsURLInterceptorRequestJob(
@@ -660,10 +669,14 @@ DevToolsURLInterceptorRequestJob::GetHttpResponseHeaders() const {
bool DevToolsURLInterceptorRequestJob::GetMimeType(
std::string* mime_type) const {
+ if (sub_request_) {
+ sub_request_->request()->GetMimeType(mime_type);
+ return true;
+ }
const net::HttpResponseHeaders* response_headers = GetHttpResponseHeaders();
- if (!response_headers)
- return false;
- return response_headers->GetMimeType(mime_type);
+ if (response_headers)
+ return response_headers->GetMimeType(mime_type);
+ return false;
}
bool DevToolsURLInterceptorRequestJob::GetCharset(std::string* charset) {
@@ -711,7 +724,7 @@ void DevToolsURLInterceptorRequestJob::OnSubRequestAuthRequired(
if (stage_to_intercept_ == InterceptionStage::DONT_INTERCEPT) {
// This should trigger default auth behavior.
- // See comment in ProcessAuthRespose.
+ // See comment in ProcessAuthResponse.
NotifyHeadersComplete();
return;
}
@@ -756,6 +769,8 @@ void DevToolsURLInterceptorRequestJob::OnSubRequestRedirectReceived(
bool* defer_redirect) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DCHECK(sub_request_);
+ SetDevToolsStatus(sub_request_->request(),
+ DevToolsStatus::kCanceledAsRedirect);
// If we're not intercepting results or are a response then cancel this
// redirect and tell the parent request it was redirected through |redirect_|.
@@ -799,8 +814,10 @@ void DevToolsURLInterceptorRequestJob::OnInterceptedRequestResponseStarted(
const net::Error& net_error) {
DCHECK_NE(waiting_for_user_response_,
WaitingForUserResponse::WAITING_FOR_RESPONSE_ACK);
- if (stage_to_intercept_ == InterceptionStage::DONT_INTERCEPT)
+ if (stage_to_intercept_ == InterceptionStage::DONT_INTERCEPT) {
+ static_cast<InterceptedRequest*>(sub_request_.get())->FetchResponseBody();
return;
+ }
waiting_for_user_response_ = WaitingForUserResponse::WAITING_FOR_RESPONSE_ACK;
std::unique_ptr<InterceptedRequestInfo> request_info = BuildRequestInfo();
@@ -873,7 +890,7 @@ void DevToolsURLInterceptorRequestJob::StopIntercepting() {
case WaitingForUserResponse::WAITING_FOR_RESPONSE_ACK:
// Fallthough.
case WaitingForUserResponse::WAITING_FOR_REQUEST_ACK:
- ProcessInterceptionRespose(
+ ProcessInterceptionResponse(
std::make_unique<DevToolsNetworkInterceptor::Modifications>(
base::nullopt, base::nullopt, protocol::Maybe<std::string>(),
protocol::Maybe<std::string>(), protocol::Maybe<std::string>(),
@@ -887,7 +904,7 @@ void DevToolsURLInterceptorRequestJob::StopIntercepting() {
.SetResponse(protocol::Network::AuthChallengeResponse::
ResponseEnum::Default)
.Build();
- ProcessAuthRespose(
+ ProcessAuthResponse(
std::make_unique<DevToolsNetworkInterceptor::Modifications>(
base::nullopt, base::nullopt, protocol::Maybe<std::string>(),
protocol::Maybe<std::string>(), protocol::Maybe<std::string>(),
@@ -928,7 +945,7 @@ void DevToolsURLInterceptorRequestJob::ContinueInterceptedRequest(
"authChallengeResponse not expected.")));
break;
}
- ProcessInterceptionRespose(std::move(modifications));
+ ProcessInterceptionResponse(std::move(modifications));
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::BindOnce(&ContinueInterceptedRequestCallback::sendSuccess,
@@ -945,7 +962,7 @@ void DevToolsURLInterceptorRequestJob::ContinueInterceptedRequest(
"authChallengeResponse required.")));
break;
}
- if (ProcessAuthRespose(std::move(modifications))) {
+ if (ProcessAuthResponse(std::move(modifications))) {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::BindOnce(&ContinueInterceptedRequestCallback::sendSuccess,
@@ -1025,18 +1042,14 @@ DevToolsURLInterceptorRequestJob::BuildRequestInfo() {
return result;
}
-void DevToolsURLInterceptorRequestJob::ProcessInterceptionRespose(
+void DevToolsURLInterceptorRequestJob::ProcessInterceptionResponse(
std::unique_ptr<DevToolsNetworkInterceptor::Modifications> modifications) {
bool is_response_ack = waiting_for_user_response_ ==
WaitingForUserResponse::WAITING_FOR_RESPONSE_ACK;
waiting_for_user_response_ = WaitingForUserResponse::NOT_WAITING;
- if (modifications->mark_as_canceled) {
- ResourceRequestInfoImpl* resource_request_info =
- ResourceRequestInfoImpl::ForRequest(request());
- DCHECK(resource_request_info);
- resource_request_info->set_canceled_by_devtools(true);
- }
+ if (modifications->mark_as_canceled)
+ SetDevToolsStatus(request(), DevToolsStatus::kCanceled);
if (modifications->error_reason) {
if (sub_request_) {
@@ -1061,6 +1074,10 @@ void DevToolsURLInterceptorRequestJob::ProcessInterceptionRespose(
sub_request_->Cancel();
sub_request_.reset();
}
+ if (response_headers_callback_) {
+ response_headers_callback_.Run(
+ mock_response_details_->response_headers());
+ }
NotifyHeadersComplete();
return;
}
@@ -1118,11 +1135,17 @@ void DevToolsURLInterceptorRequestJob::ProcessInterceptionRespose(
// The reason we start a sub request is because we are in full control of it
// and can choose to ignore it if, for example, the fetch encounters a
// redirect that the user chooses to replace with a mock response.
- sub_request_.reset(new SubRequest(request_details_, this, interceptor_));
+ DCHECK(stage_to_intercept_ != InterceptionStage::RESPONSE);
+ if (stage_to_intercept_ == InterceptionStage::BOTH) {
+ sub_request_.reset(
+ new InterceptedRequest(request_details_, this, interceptor_));
+ } else {
+ sub_request_.reset(new SubRequest(request_details_, this, interceptor_));
+ }
}
}
-bool DevToolsURLInterceptorRequestJob::ProcessAuthRespose(
+bool DevToolsURLInterceptorRequestJob::ProcessAuthResponse(
std::unique_ptr<DevToolsNetworkInterceptor::Modifications> modifications) {
waiting_for_user_response_ = WaitingForUserResponse::NOT_WAITING;
@@ -1150,8 +1173,8 @@ bool DevToolsURLInterceptorRequestJob::ProcessAuthRespose(
protocol::Network::AuthChallengeResponse::ResponseEnum::
ProvideCredentials) {
SetAuth(net::AuthCredentials(
- base::UTF8ToUTF16(auth_challenge_response->GetUsername("").c_str()),
- base::UTF8ToUTF16(auth_challenge_response->GetPassword("").c_str())));
+ base::UTF8ToUTF16(auth_challenge_response->GetUsername("")),
+ base::UTF8ToUTF16(auth_challenge_response->GetPassword(""))));
return true;
}
@@ -1160,12 +1183,12 @@ bool DevToolsURLInterceptorRequestJob::ProcessAuthRespose(
void DevToolsURLInterceptorRequestJob::SetRequestHeadersCallback(
net::RequestHeadersCallback callback) {
- request_headers_callback_ = callback;
+ request_headers_callback_ = std::move(callback);
}
void DevToolsURLInterceptorRequestJob::SetResponseHeadersCallback(
net::ResponseHeadersCallback callback) {
- response_headers_callback_ = callback;
+ response_headers_callback_ = std::move(callback);
}
DevToolsURLInterceptorRequestJob::RequestDetails::RequestDetails(
diff --git a/chromium/content/browser/devtools/devtools_url_interceptor_request_job.h b/chromium/content/browser/devtools/devtools_url_interceptor_request_job.h
index 961cf901c6b..48e7a7bde39 100644
--- a/chromium/content/browser/devtools/devtools_url_interceptor_request_job.h
+++ b/chromium/content/browser/devtools/devtools_url_interceptor_request_job.h
@@ -128,10 +128,10 @@ class DevToolsURLInterceptorRequestJob : public net::URLRequestJob {
const net::HttpResponseHeaders* GetHttpResponseHeaders() const;
void ProcessRedirect(int status_code, const std::string& new_url);
- void ProcessInterceptionRespose(
+ void ProcessInterceptionResponse(
std::unique_ptr<DevToolsNetworkInterceptor::Modifications> modification);
- bool ProcessAuthRespose(
+ bool ProcessAuthResponse(
std::unique_ptr<DevToolsNetworkInterceptor::Modifications> modification);
enum class WaitingForUserResponse {
diff --git a/chromium/content/browser/devtools/devtools_url_loader_interceptor.cc b/chromium/content/browser/devtools/devtools_url_loader_interceptor.cc
new file mode 100644
index 00000000000..ced25eb9169
--- /dev/null
+++ b/chromium/content/browser/devtools/devtools_url_loader_interceptor.cc
@@ -0,0 +1,1170 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/devtools/devtools_url_loader_interceptor.h"
+#include "base/base64.h"
+#include "base/no_destructor.h"
+#include "base/strings/stringprintf.h"
+#include "base/time/time.h"
+#include "base/unguessable_token.h"
+#include "content/browser/devtools/protocol/network_handler.h"
+#include "content/browser/frame_host/frame_tree_node.h"
+#include "content/public/browser/browser_thread.h"
+#include "mojo/public/cpp/bindings/binding_set.h"
+#include "mojo/public/cpp/system/data_pipe_drainer.h"
+#include "net/base/mime_sniffer.h"
+#include "net/http/http_util.h"
+#include "net/url_request/url_request.h"
+#include "services/network/public/cpp/resource_request_body.h"
+
+namespace content {
+
+namespace {
+
+using RequestInterceptedCallback =
+ DevToolsNetworkInterceptor::RequestInterceptedCallback;
+using ContinueInterceptedRequestCallback =
+ DevToolsNetworkInterceptor::ContinueInterceptedRequestCallback;
+using GetResponseBodyForInterceptionCallback =
+ DevToolsNetworkInterceptor::GetResponseBodyForInterceptionCallback;
+using Modifications = DevToolsNetworkInterceptor::Modifications;
+using InterceptionStage = DevToolsNetworkInterceptor::InterceptionStage;
+using protocol::Response;
+using protocol::Network::AuthChallengeResponse;
+using GlobalRequestId = std::tuple<int32_t, int32_t, int32_t>;
+
+struct CreateLoaderParameters {
+ CreateLoaderParameters(
+ int32_t routing_id,
+ int32_t request_id,
+ uint32_t options,
+ network::ResourceRequest request,
+ net::MutableNetworkTrafficAnnotationTag traffic_annotation)
+ : routing_id(routing_id),
+ request_id(request_id),
+ options(options),
+ request(request),
+ traffic_annotation(traffic_annotation) {}
+
+ const int32_t routing_id;
+ const int32_t request_id;
+ const uint32_t options;
+ network::ResourceRequest request;
+ const net::MutableNetworkTrafficAnnotationTag traffic_annotation;
+};
+
+class BodyReader : public mojo::DataPipeDrainer::Client {
+ public:
+ explicit BodyReader(base::OnceClosure download_complete_callback)
+ : download_complete_callback_(std::move(download_complete_callback)) {}
+
+ void StartReading(mojo::ScopedDataPipeConsumerHandle body);
+
+ void AddCallback(
+ std::unique_ptr<GetResponseBodyForInterceptionCallback> callback) {
+ callbacks_.push_back(std::move(callback));
+ if (data_complete_) {
+ DCHECK_EQ(1UL, callbacks_.size());
+ BrowserThread::PostTask(
+ BrowserThread::UI, FROM_HERE,
+ base::BindOnce(&BodyReader::DispatchBodyOnUI, std::move(callbacks_),
+ encoded_body_));
+ }
+ }
+
+ bool data_complete() const { return data_complete_; }
+ const std::string& body() const { return body_; }
+
+ void CancelWithError(std::string error) {
+ BrowserThread::PostTask(
+ BrowserThread::UI, FROM_HERE,
+ base::BindOnce(&BodyReader::DispatchErrorOnUI, std::move(callbacks_),
+ std::move(error)));
+ }
+
+ private:
+ using CallbackVector =
+ std::vector<std::unique_ptr<GetResponseBodyForInterceptionCallback>>;
+ static void DispatchBodyOnUI(const CallbackVector& callbacks,
+ const std::string& body);
+ static void DispatchErrorOnUI(const CallbackVector& callbacks,
+ const std::string& error);
+
+ void OnDataAvailable(const void* data, size_t num_bytes) override {
+ DCHECK(!data_complete_);
+ body_.append(std::string(static_cast<const char*>(data), num_bytes));
+ }
+
+ void OnDataComplete() override;
+
+ std::unique_ptr<mojo::DataPipeDrainer> body_pipe_drainer_;
+ CallbackVector callbacks_;
+ base::OnceClosure download_complete_callback_;
+ std::string body_;
+ std::string encoded_body_;
+ bool data_complete_ = false;
+};
+
+void BodyReader::StartReading(mojo::ScopedDataPipeConsumerHandle body) {
+ DCHECK(!callbacks_.empty());
+ DCHECK(!body_pipe_drainer_);
+ DCHECK(!data_complete_);
+
+ body_pipe_drainer_.reset(new mojo::DataPipeDrainer(this, std::move(body)));
+}
+
+void BodyReader::OnDataComplete() {
+ DCHECK(!data_complete_);
+ data_complete_ = true;
+ body_pipe_drainer_.reset();
+ // TODO(caseq): only encode if necessary.
+ base::Base64Encode(body_, &encoded_body_);
+ BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
+ base::BindOnce(&BodyReader::DispatchBodyOnUI,
+ std::move(callbacks_), encoded_body_));
+ std::move(download_complete_callback_).Run();
+}
+
+// static
+void BodyReader::DispatchBodyOnUI(const CallbackVector& callbacks,
+ const std::string& encoded_body) {
+ for (const auto& cb : callbacks)
+ cb->sendSuccess(encoded_body, true);
+}
+
+// static
+void BodyReader::DispatchErrorOnUI(const CallbackVector& callbacks,
+ const std::string& error) {
+ for (const auto& cb : callbacks)
+ cb->sendFailure(Response::Error(error));
+}
+
+struct ResponseMetadata {
+ ResponseMetadata() = default;
+ explicit ResponseMetadata(const network::ResourceResponseHead& head)
+ : head(head) {}
+
+ network::ResourceResponseHead head;
+ std::unique_ptr<net::RedirectInfo> redirect_info;
+ network::mojom::DownloadedTempFilePtr downloaded_file;
+ std::vector<uint8_t> cached_metadata;
+ size_t encoded_length = 0;
+ size_t transfer_size = 0;
+ network::URLLoaderCompletionStatus status;
+};
+
+class InterceptionJob : public network::mojom::URLLoaderClient,
+ public network::mojom::URLLoader {
+ public:
+ static InterceptionJob* FindByRequestId(
+ const GlobalRequestId& global_req_id) {
+ const auto& map = GetInterceptionJobMap();
+ auto it = map.find(global_req_id);
+ return it == map.end() ? nullptr : it->second;
+ }
+
+ InterceptionJob(DevToolsURLLoaderInterceptor::Impl* interceptor,
+ const std::string& id,
+ const base::UnguessableToken& frame_token,
+ int32_t process_id,
+ std::unique_ptr<CreateLoaderParameters> create_loader_params,
+ network::mojom::URLLoaderRequest loader_request,
+ network::mojom::URLLoaderClientPtr client,
+ network::mojom::URLLoaderFactoryPtr target_factory);
+
+ void GetResponseBody(
+ std::unique_ptr<GetResponseBodyForInterceptionCallback> callback);
+ void ContinueInterceptedRequest(
+ std::unique_ptr<Modifications> modifications,
+ std::unique_ptr<ContinueInterceptedRequestCallback> callback);
+ void Detach();
+
+ void OnAuthRequest(
+ const scoped_refptr<net::AuthChallengeInfo>& auth_info,
+ DevToolsURLLoaderInterceptor::HandleAuthRequestCallback callback);
+
+ private:
+ static std::map<GlobalRequestId, InterceptionJob*>& GetInterceptionJobMap() {
+ DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
+ static base::NoDestructor<std::map<GlobalRequestId, InterceptionJob*>> inst;
+ return *inst;
+ }
+
+ ~InterceptionJob() override {
+ size_t erased = GetInterceptionJobMap().erase(global_req_id_);
+ DCHECK_EQ(1lu, erased);
+ }
+
+ Response InnerContinueRequest(std::unique_ptr<Modifications> modifications);
+ Response ProcessAuthResponse(AuthChallengeResponse* auth_challenge_response);
+ Response ProcessResponseOverride(const std::string& response);
+ Response ProcessRedirectByClient(const std::string& location);
+ void SendResponse(const base::StringPiece& body);
+ void ApplyModificationsToRequest(
+ std::unique_ptr<Modifications> modifications);
+
+ void StartRequest();
+ void CancelRequest();
+ void Shutdown();
+
+ std::unique_ptr<InterceptedRequestInfo> BuildRequestInfo(
+ const network::ResourceResponseHead* head);
+ void NotifyClient(std::unique_ptr<InterceptedRequestInfo> request_info);
+
+ void ResponseBodyComplete();
+
+ bool ShouldBypassForResponse() const {
+ DCHECK_EQ(!!response_metadata_, !!body_reader_);
+ DCHECK_EQ(state_, State::kResponseReceived);
+ return !response_metadata_;
+ }
+
+ // network::mojom::URLLoader methods
+ void FollowRedirect() override;
+ void ProceedWithResponse() override;
+ void SetPriority(net::RequestPriority priority,
+ int32_t intra_priority_value) override;
+ void PauseReadingBodyFromNet() override;
+ void ResumeReadingBodyFromNet() override;
+
+ // network::mojom::URLLoaderClient methods
+ void OnReceiveResponse(
+ const network::ResourceResponseHead& head,
+ network::mojom::DownloadedTempFilePtr downloaded_file) override;
+ void OnReceiveRedirect(const net::RedirectInfo& redirect_info,
+ const network::ResourceResponseHead& head) override;
+ void OnDataDownloaded(int64_t data_length, int64_t encoded_length) override;
+ void OnUploadProgress(int64_t current_position,
+ int64_t total_size,
+ OnUploadProgressCallback callback) override;
+ void OnReceiveCachedMetadata(const std::vector<uint8_t>& data) override;
+ void OnTransferSizeUpdated(int32_t transfer_size_diff) override;
+ void OnStartLoadingResponseBody(
+ mojo::ScopedDataPipeConsumerHandle body) override;
+ void OnComplete(const network::URLLoaderCompletionStatus& status) override;
+
+ const std::string id_;
+ const GlobalRequestId global_req_id_;
+ const base::UnguessableToken frame_token_;
+ const base::TimeTicks start_ticks_;
+ const base::Time start_time_;
+ const bool report_upload_;
+
+ DevToolsURLLoaderInterceptor::Impl* interceptor_;
+ InterceptionStage stage_;
+
+ std::unique_ptr<CreateLoaderParameters> create_loader_params_;
+
+ mojo::Binding<network::mojom::URLLoaderClient> client_binding_;
+ mojo::Binding<network::mojom::URLLoader> loader_binding_;
+
+ network::mojom::URLLoaderClientPtr client_;
+ network::mojom::URLLoaderPtr loader_;
+ network::mojom::URLLoaderFactoryPtr target_factory_;
+
+ enum State {
+ kNotStarted,
+ kRequestSent,
+ kRedirectReceived,
+ kAuthRequired,
+ kResponseReceived,
+ };
+
+ State state_;
+ bool waiting_for_resolution_;
+
+ std::unique_ptr<BodyReader> body_reader_;
+ std::unique_ptr<ResponseMetadata> response_metadata_;
+
+ base::Optional<std::pair<net::RequestPriority, int32_t>> priority_;
+ DevToolsURLLoaderInterceptor::HandleAuthRequestCallback
+ pending_auth_callback_;
+
+ DISALLOW_COPY_AND_ASSIGN(InterceptionJob);
+};
+
+} // namespace
+
+class DevToolsURLLoaderInterceptor::Impl
+ : public base::SupportsWeakPtr<DevToolsURLLoaderInterceptor::Impl> {
+ public:
+ explicit Impl(RequestInterceptedCallback callback)
+ : request_intercepted_callback_(callback) {}
+ ~Impl() {
+ for (auto const& entry : jobs_)
+ entry.second->Detach();
+ }
+
+ void CreateJob(const base::UnguessableToken& frame_token,
+ int32_t process_id,
+ std::unique_ptr<CreateLoaderParameters> create_params,
+ network::mojom::URLLoaderRequest loader_request,
+ network::mojom::URLLoaderClientPtr client,
+ network::mojom::URLLoaderFactoryPtr target_factory) {
+ DCHECK(!frame_token.is_empty());
+
+ static int last_id = 0;
+
+ std::string id = base::StringPrintf("interception-job-%d", ++last_id);
+ InterceptionJob* job =
+ new InterceptionJob(this, id, frame_token, process_id,
+ std::move(create_params), std::move(loader_request),
+ std::move(client), std::move(target_factory));
+ jobs_.emplace(std::move(id), job);
+ }
+
+ void SetPatterns(std::vector<DevToolsNetworkInterceptor::Pattern> patterns) {
+ patterns_ = std::move(patterns);
+ }
+
+ InterceptionStage GetInterceptionStage(const GURL& url,
+ ResourceType resource_type) const {
+ InterceptionStage stage = InterceptionStage::DONT_INTERCEPT;
+ std::string url_str = protocol::NetworkHandler::ClearUrlRef(url).spec();
+ for (const auto& pattern : patterns_) {
+ if (pattern.Matches(url_str, resource_type))
+ stage |= pattern.interception_stage;
+ }
+ return stage;
+ }
+
+ void GetResponseBody(
+ const std::string& interception_id,
+ std::unique_ptr<GetResponseBodyForInterceptionCallback> callback) {
+ if (InterceptionJob* job = FindJob(interception_id, &callback))
+ job->GetResponseBody(std::move(callback));
+ }
+
+ void ContinueInterceptedRequest(
+ const std::string& interception_id,
+ std::unique_ptr<Modifications> modifications,
+ std::unique_ptr<ContinueInterceptedRequestCallback> callback) {
+ if (InterceptionJob* job = FindJob(interception_id, &callback)) {
+ job->ContinueInterceptedRequest(std::move(modifications),
+ std::move(callback));
+ }
+ }
+
+ private:
+ friend class content::InterceptionJob;
+
+ template <typename Callback>
+ InterceptionJob* FindJob(const std::string& id,
+ std::unique_ptr<Callback>* callback) {
+ auto it = jobs_.find(id);
+ if (it != jobs_.end())
+ return it->second;
+ BrowserThread::PostTask(
+ BrowserThread::UI, FROM_HERE,
+ base::BindOnce(
+ &Callback::sendFailure, std::move(*callback),
+ protocol::Response::InvalidParams("Invalid InterceptionId.")));
+ return nullptr;
+ }
+
+ void RemoveJob(const std::string& id) { jobs_.erase(id); }
+
+ std::map<std::string, InterceptionJob*> jobs_;
+ RequestInterceptedCallback request_intercepted_callback_;
+ std::vector<DevToolsNetworkInterceptor::Pattern> patterns_;
+
+ DISALLOW_COPY_AND_ASSIGN(Impl);
+};
+
+class DevToolsURLLoaderFactoryProxy : public network::mojom::URLLoaderFactory {
+ public:
+ DevToolsURLLoaderFactoryProxy(
+ const base::UnguessableToken& frame_token,
+ int32_t process_id,
+ network::mojom::URLLoaderFactoryRequest loader_request,
+ network::mojom::URLLoaderFactoryPtrInfo target_factory_info,
+ base::WeakPtr<DevToolsURLLoaderInterceptor::Impl> interceptor);
+ ~DevToolsURLLoaderFactoryProxy() override;
+
+ private:
+ // network::mojom::URLLoaderFactory implementation
+ void CreateLoaderAndStart(network::mojom::URLLoaderRequest loader,
+ int32_t routing_id,
+ int32_t request_id,
+ uint32_t options,
+ const network::ResourceRequest& request,
+ network::mojom::URLLoaderClientPtr client,
+ const net::MutableNetworkTrafficAnnotationTag&
+ traffic_annotation) override;
+ void Clone(network::mojom::URLLoaderFactoryRequest request) override;
+
+ void StartOnIO(network::mojom::URLLoaderFactoryRequest loader_request,
+ network::mojom::URLLoaderFactoryPtrInfo target_factory_info);
+ void OnProxyBindingError();
+ void OnTargetFactoryError();
+
+ const base::UnguessableToken frame_token_;
+ const int32_t process_id_;
+
+ network::mojom::URLLoaderFactoryPtr target_factory_;
+ base::WeakPtr<DevToolsURLLoaderInterceptor::Impl> interceptor_;
+ mojo::BindingSet<network::mojom::URLLoaderFactory> bindings_;
+
+ SEQUENCE_CHECKER(sequence_checker_);
+};
+
+DevToolsURLLoaderFactoryProxy::DevToolsURLLoaderFactoryProxy(
+ const base::UnguessableToken& frame_token,
+ int32_t process_id,
+ network::mojom::URLLoaderFactoryRequest loader_request,
+ network::mojom::URLLoaderFactoryPtrInfo target_factory_info,
+ base::WeakPtr<DevToolsURLLoaderInterceptor::Impl> interceptor)
+ : frame_token_(frame_token),
+ process_id_(process_id),
+ interceptor_(std::move(interceptor)) {
+ DETACH_FROM_SEQUENCE(sequence_checker_);
+ BrowserThread::PostTask(
+ BrowserThread::IO, FROM_HERE,
+ base::BindOnce(&DevToolsURLLoaderFactoryProxy::StartOnIO,
+ base::Unretained(this), std::move(loader_request),
+ std::move(target_factory_info)));
+}
+
+DevToolsURLLoaderFactoryProxy::~DevToolsURLLoaderFactoryProxy() {}
+
+void DevToolsURLLoaderFactoryProxy::CreateLoaderAndStart(
+ network::mojom::URLLoaderRequest loader,
+ int32_t routing_id,
+ int32_t request_id,
+ uint32_t options,
+ const network::ResourceRequest& request,
+ network::mojom::URLLoaderClientPtr client,
+ const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) {
+ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
+
+ DevToolsURLLoaderInterceptor::Impl* interceptor = interceptor_.get();
+ if (!interceptor_) {
+ target_factory_->CreateLoaderAndStart(
+ std::move(loader), routing_id, request_id, options, request,
+ std::move(client), traffic_annotation);
+ return;
+ }
+ auto creation_params = std::make_unique<CreateLoaderParameters>(
+ routing_id, request_id, options, request, traffic_annotation);
+ network::mojom::URLLoaderFactoryPtr factory_clone;
+ target_factory_->Clone(MakeRequest(&factory_clone));
+ interceptor->CreateJob(frame_token_, process_id_, std::move(creation_params),
+ std::move(loader), std::move(client),
+ std::move(factory_clone));
+}
+
+void DevToolsURLLoaderFactoryProxy::StartOnIO(
+ network::mojom::URLLoaderFactoryRequest loader_request,
+ network::mojom::URLLoaderFactoryPtrInfo target_factory_info) {
+ target_factory_.Bind(std::move(target_factory_info));
+ target_factory_.set_connection_error_handler(
+ base::BindOnce(&DevToolsURLLoaderFactoryProxy::OnTargetFactoryError,
+ base::Unretained(this)));
+
+ bindings_.AddBinding(this, std::move(loader_request));
+ bindings_.set_connection_error_handler(
+ base::BindRepeating(&DevToolsURLLoaderFactoryProxy::OnProxyBindingError,
+ base::Unretained(this)));
+}
+
+void DevToolsURLLoaderFactoryProxy::Clone(
+ network::mojom::URLLoaderFactoryRequest request) {
+ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
+ bindings_.AddBinding(this, std::move(request));
+}
+
+void DevToolsURLLoaderFactoryProxy::OnTargetFactoryError() {
+ DCHECK(!target_factory_.is_bound());
+ delete this;
+}
+
+void DevToolsURLLoaderFactoryProxy::OnProxyBindingError() {
+ if (bindings_.empty())
+ delete this;
+}
+
+// static
+void DevToolsURLLoaderInterceptor::HandleAuthRequest(
+ int32_t process_id,
+ int32_t routing_id,
+ int32_t request_id,
+ const scoped_refptr<net::AuthChallengeInfo>& auth_info,
+ HandleAuthRequestCallback callback) {
+ GlobalRequestId req_id = std::make_tuple(process_id, routing_id, request_id);
+ if (auto* job = InterceptionJob::FindByRequestId(req_id))
+ job->OnAuthRequest(auth_info, std::move(callback));
+ else
+ std::move(callback).Run(true, base::nullopt);
+}
+
+DevToolsURLLoaderInterceptor::DevToolsURLLoaderInterceptor(
+ FrameTreeNode* const local_root,
+ RequestInterceptedCallback callback)
+ : local_root_(local_root),
+ enabled_(false),
+ impl_(new DevToolsURLLoaderInterceptor::Impl(std::move(callback)),
+ base::OnTaskRunnerDeleter(
+ BrowserThread::GetTaskRunnerForThread(BrowserThread::IO))),
+ weak_impl_(impl_->AsWeakPtr()) {}
+
+DevToolsURLLoaderInterceptor::~DevToolsURLLoaderInterceptor() {
+ UpdateSubresourceLoaderFactories();
+};
+
+void DevToolsURLLoaderInterceptor::UpdateSubresourceLoaderFactories() {
+ base::queue<FrameTreeNode*> queue;
+ queue.push(local_root_);
+ while (!queue.empty()) {
+ FrameTreeNode* node = queue.front();
+ queue.pop();
+ RenderFrameHostImpl* host = node->current_frame_host();
+ if (node != local_root_ && host->IsCrossProcessSubframe())
+ continue;
+ host->UpdateSubresourceLoaderFactories();
+ for (size_t i = 0; i < node->child_count(); ++i)
+ queue.push(node->child_at(i));
+ }
+}
+
+void DevToolsURLLoaderInterceptor::SetPatterns(
+ std::vector<DevToolsNetworkInterceptor::Pattern> patterns) {
+ if (enabled_ != !!patterns.size()) {
+ enabled_ = !!patterns.size();
+ UpdateSubresourceLoaderFactories();
+ }
+ BrowserThread::PostTask(
+ BrowserThread::IO, FROM_HERE,
+ base::BindOnce(&Impl::SetPatterns, base::Unretained(impl_.get()),
+ std::move(patterns)));
+}
+
+void DevToolsURLLoaderInterceptor::GetResponseBody(
+ const std::string& interception_id,
+ std::unique_ptr<GetResponseBodyForInterceptionCallback> callback) {
+ BrowserThread::PostTask(
+ BrowserThread::IO, FROM_HERE,
+ base::BindOnce(&Impl::GetResponseBody, base::Unretained(impl_.get()),
+ interception_id, std::move(callback)));
+}
+
+void DevToolsURLLoaderInterceptor::ContinueInterceptedRequest(
+ const std::string& interception_id,
+ std::unique_ptr<Modifications> modifications,
+ std::unique_ptr<ContinueInterceptedRequestCallback> callback) {
+ BrowserThread::PostTask(
+ BrowserThread::IO, FROM_HERE,
+ base::BindOnce(&Impl::ContinueInterceptedRequest,
+ base::Unretained(impl_.get()), interception_id,
+ std::move(modifications), std::move(callback)));
+}
+
+bool DevToolsURLLoaderInterceptor::CreateProxyForInterception(
+ const base::UnguessableToken frame_token,
+ int process_id,
+ network::mojom::URLLoaderFactoryRequest* request) const {
+ if (!enabled_)
+ return false;
+ network::mojom::URLLoaderFactoryRequest original_request =
+ std::move(*request);
+ network::mojom::URLLoaderFactoryPtrInfo target_ptr_info;
+ *request = MakeRequest(&target_ptr_info);
+
+ new DevToolsURLLoaderFactoryProxy(frame_token, process_id,
+ std::move(original_request),
+ std::move(target_ptr_info), weak_impl_);
+ return true;
+}
+
+InterceptionJob::InterceptionJob(
+ DevToolsURLLoaderInterceptor::Impl* interceptor,
+ const std::string& id,
+ const base::UnguessableToken& frame_token,
+ int process_id,
+ std::unique_ptr<CreateLoaderParameters> create_loader_params,
+ network::mojom::URLLoaderRequest loader_request,
+ network::mojom::URLLoaderClientPtr client,
+ network::mojom::URLLoaderFactoryPtr target_factory)
+ : id_(std::move(id)),
+ global_req_id_(
+ std::make_tuple(process_id,
+ create_loader_params->request.render_frame_id,
+ create_loader_params->request_id)),
+ frame_token_(frame_token),
+ start_ticks_(base::TimeTicks::Now()),
+ start_time_(base::Time::Now()),
+ report_upload_(!!create_loader_params->request.request_body),
+ interceptor_(interceptor),
+ create_loader_params_(std::move(create_loader_params)),
+ client_binding_(this),
+ loader_binding_(this),
+ client_(std::move(client)),
+ target_factory_(std::move(target_factory)),
+ state_(kNotStarted),
+ waiting_for_resolution_(false) {
+ const network::ResourceRequest& request = create_loader_params_->request;
+ stage_ = interceptor_->GetInterceptionStage(
+ request.url, static_cast<ResourceType>(request.resource_type));
+
+ loader_binding_.Bind(std::move(loader_request));
+ loader_binding_.set_connection_error_handler(
+ base::BindOnce(&InterceptionJob::Shutdown, base::Unretained(this)));
+
+ auto& job_map = GetInterceptionJobMap();
+ bool inserted = job_map.emplace(global_req_id_, this).second;
+ DCHECK(inserted);
+
+ if (stage_ & InterceptionStage::REQUEST) {
+ NotifyClient(BuildRequestInfo(nullptr));
+ return;
+ }
+
+ StartRequest();
+}
+
+void InterceptionJob::GetResponseBody(
+ std::unique_ptr<GetResponseBodyForInterceptionCallback> callback) {
+ std::string error_reason;
+
+ if (!(stage_ & InterceptionStage::RESPONSE)) {
+ error_reason =
+ "Can only get response body on HeadersReceived pattern matched "
+ "requests.";
+ } else if (state_ != kResponseReceived) {
+ DCHECK(waiting_for_resolution_);
+ error_reason =
+ "Can only get response body on requests captured after headers "
+ "received.";
+ }
+ if (!error_reason.empty()) {
+ BrowserThread::PostTask(
+ BrowserThread::UI, FROM_HERE,
+ base::BindOnce(&GetResponseBodyForInterceptionCallback::sendFailure,
+ std::move(callback),
+ Response::Error(std::move(error_reason))));
+ return;
+ }
+
+ if (!body_reader_) {
+ body_reader_ = std::make_unique<BodyReader>(base::BindOnce(
+ &InterceptionJob::ResponseBodyComplete, base::Unretained(this)));
+ client_binding_.ResumeIncomingMethodCallProcessing();
+ loader_->ResumeReadingBodyFromNet();
+ }
+ body_reader_->AddCallback(std::move(callback));
+}
+
+void InterceptionJob::ContinueInterceptedRequest(
+ std::unique_ptr<Modifications> modifications,
+ std::unique_ptr<ContinueInterceptedRequestCallback> callback) {
+ Response response = InnerContinueRequest(std::move(modifications));
+ // |this| may be destroyed at this pont.
+ bool success = response.isSuccess();
+ base::OnceClosure task =
+ success ? base::BindOnce(&ContinueInterceptedRequestCallback::sendSuccess,
+ std::move(callback))
+ : base::BindOnce(&ContinueInterceptedRequestCallback::sendFailure,
+ std::move(callback), std::move(response));
+ BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, std::move(task));
+}
+
+void InterceptionJob::Detach() {
+ stage_ = InterceptionStage::DONT_INTERCEPT;
+ interceptor_ = nullptr;
+ if (!waiting_for_resolution_)
+ return;
+ if (state_ == State::kAuthRequired) {
+ state_ = State::kRequestSent;
+ waiting_for_resolution_ = false;
+ std::move(pending_auth_callback_).Run(true, base::nullopt);
+ return;
+ }
+ InnerContinueRequest(std::make_unique<Modifications>());
+}
+
+Response InterceptionJob::InnerContinueRequest(
+ std::unique_ptr<Modifications> modifications) {
+ if (!waiting_for_resolution_)
+ return Response::Error("Invalid state for continueInterceptedRequest");
+ waiting_for_resolution_ = false;
+
+ if (state_ == State::kAuthRequired) {
+ if (!modifications->auth_challenge_response.isJust())
+ return Response::InvalidParams("authChallengeResponse required.");
+ return ProcessAuthResponse(
+ modifications->auth_challenge_response.fromJust());
+ } else if (modifications->auth_challenge_response.isJust()) {
+ return Response::InvalidParams("authChallengeResponse not expected.");
+ }
+
+ if (modifications->mark_as_canceled || modifications->error_reason) {
+ int error = modifications->error_reason
+ ? *modifications->error_reason
+ : (modifications->mark_as_canceled ? net::ERR_ABORTED
+ : net::ERR_FAILED);
+ network::URLLoaderCompletionStatus status(error);
+ status.completion_time = base::TimeTicks::Now();
+ client_->OnComplete(status);
+ Shutdown();
+ return Response::OK();
+ }
+
+ if (modifications->raw_response)
+ return ProcessResponseOverride(*modifications->raw_response);
+
+ if (state_ == State::kRedirectReceived) {
+ // TODO(caseq): report error if other modifications are present.
+ if (modifications->modified_url.isJust()) {
+ std::string location = modifications->modified_url.fromJust();
+ CancelRequest();
+ auto* headers = response_metadata_->head.headers.get();
+ headers->RemoveHeader("location");
+ headers->AddHeader("location: " + location);
+ return ProcessRedirectByClient(location);
+ }
+ client_->OnReceiveRedirect(*response_metadata_->redirect_info,
+ response_metadata_->head);
+ return Response::OK();
+ }
+
+ if (body_reader_) {
+ if (body_reader_->data_complete())
+ SendResponse(body_reader_->body());
+
+ // There are read callbacks pending, so let the reader do its job and come
+ // back when it's done.
+ return Response::OK();
+ }
+
+ if (response_metadata_) {
+ // TODO(caseq): report error if other modifications are present.
+ DCHECK_EQ(State::kResponseReceived, state_);
+ DCHECK(!body_reader_);
+ client_->OnReceiveResponse(response_metadata_->head,
+ std::move(response_metadata_->downloaded_file));
+ response_metadata_.reset();
+ loader_->ResumeReadingBodyFromNet();
+ client_binding_.ResumeIncomingMethodCallProcessing();
+ return Response::OK();
+ }
+
+ DCHECK_EQ(State::kNotStarted, state_);
+ ApplyModificationsToRequest(std::move(modifications));
+ StartRequest();
+ return Response::OK();
+}
+
+void InterceptionJob::ApplyModificationsToRequest(
+ std::unique_ptr<Modifications> modifications) {
+ network::ResourceRequest* request = &create_loader_params_->request;
+
+ // Note this redirect is not visible to the page by design. If they want a
+ // visible redirect they can mock a response with a 302.
+ if (modifications->modified_url.isJust())
+ request->url = GURL(modifications->modified_url.fromJust());
+
+ if (modifications->modified_method.isJust())
+ request->method = modifications->modified_method.fromJust();
+
+ if (modifications->modified_post_data.isJust()) {
+ const std::string& post_data = modifications->modified_post_data.fromJust();
+ request->request_body = network::ResourceRequestBody::CreateFromBytes(
+ post_data.data(), post_data.size());
+ }
+
+ if (modifications->modified_headers.isJust()) {
+ request->headers.Clear();
+ std::unique_ptr<protocol::DictionaryValue> headers =
+ modifications->modified_headers.fromJust()->toValue();
+ for (size_t i = 0; i < headers->size(); i++) {
+ protocol::DictionaryValue::Entry entry = headers->at(i);
+ std::string value;
+ if (!entry.second->asString(&value))
+ continue;
+ if (base::EqualsCaseInsensitiveASCII(entry.first,
+ net::HttpRequestHeaders::kReferer)) {
+ request->referrer = GURL(value);
+ request->referrer_policy = net::URLRequest::NEVER_CLEAR_REFERRER;
+ } else {
+ request->headers.SetHeader(entry.first, value);
+ }
+ }
+ }
+}
+
+Response InterceptionJob::ProcessAuthResponse(
+ AuthChallengeResponse* auth_challenge_response) {
+ std::string response = auth_challenge_response->GetResponse();
+ state_ = State::kRequestSent;
+ if (response == AuthChallengeResponse::ResponseEnum::Default) {
+ std::move(pending_auth_callback_).Run(true, base::nullopt);
+ } else if (response == AuthChallengeResponse::ResponseEnum::CancelAuth) {
+ std::move(pending_auth_callback_).Run(false, base::nullopt);
+ } else if (response ==
+ AuthChallengeResponse::ResponseEnum::ProvideCredentials) {
+ net::AuthCredentials credentials(
+ base::UTF8ToUTF16(auth_challenge_response->GetUsername("")),
+ base::UTF8ToUTF16(auth_challenge_response->GetPassword("")));
+ std::move(pending_auth_callback_).Run(false, std::move(credentials));
+ } else {
+ return Response::InvalidParams("Unrecognized authChallengeResponse.");
+ }
+
+ return Response::OK();
+}
+
+Response InterceptionJob::ProcessResponseOverride(const std::string& response) {
+ CancelRequest();
+
+ std::string raw_headers;
+ int header_size =
+ net::HttpUtil::LocateEndOfHeaders(response.c_str(), response.size());
+ if (header_size == -1) {
+ LOG(WARNING) << "Can't find headers in result";
+ header_size = 0;
+ } else {
+ raw_headers =
+ net::HttpUtil::AssembleRawHeaders(response.c_str(), header_size);
+ }
+ CHECK_LE(static_cast<size_t>(header_size), response.size());
+ size_t body_size = response.size() - header_size;
+
+ response_metadata_ = std::make_unique<ResponseMetadata>();
+ network::ResourceResponseHead* head = &response_metadata_->head;
+
+ head->request_time = start_time_;
+ head->response_time = base::Time::Now();
+ head->headers = new net::HttpResponseHeaders(std::move(raw_headers));
+ head->headers->GetMimeTypeAndCharset(&head->mime_type, &head->charset);
+ if (head->mime_type.empty()) {
+ net::SniffMimeType(response.data() + header_size, body_size,
+ create_loader_params_->request.url, "",
+ net::ForceSniffFileUrlsForHtml::kDisabled,
+ &head->mime_type);
+ }
+ head->content_length = body_size;
+ head->encoded_data_length = header_size;
+ head->encoded_body_length = 0;
+ head->request_start = start_ticks_;
+ head->response_start = base::TimeTicks::Now();
+
+ std::string location_url;
+ if (head->headers->IsRedirect(&location_url))
+ return ProcessRedirectByClient(location_url);
+
+ response_metadata_->transfer_size = body_size;
+
+ response_metadata_->status.completion_time = base::TimeTicks::Now();
+ response_metadata_->status.encoded_data_length = response.size();
+ response_metadata_->status.encoded_body_length = body_size;
+ response_metadata_->status.decoded_body_length = body_size;
+
+ SendResponse(base::StringPiece(response.data() + header_size, body_size));
+ return Response::OK();
+}
+
+Response InterceptionJob::ProcessRedirectByClient(const std::string& location) {
+ GURL redirect_url = create_loader_params_->request.url.Resolve(location);
+
+ if (!redirect_url.is_valid())
+ return Response::Error("Invalid redirect URL in overriden headers");
+
+ const net::HttpResponseHeaders& headers = *response_metadata_->head.headers;
+ const network::ResourceRequest& request = create_loader_params_->request;
+
+ auto first_party_url_policy =
+ request.update_first_party_url_on_redirect
+ ? net::URLRequest::FirstPartyURLPolicy::
+ UPDATE_FIRST_PARTY_URL_ON_REDIRECT
+ : net::URLRequest::FirstPartyURLPolicy::NEVER_CHANGE_FIRST_PARTY_URL;
+
+ response_metadata_->redirect_info = std::make_unique<net::RedirectInfo>(
+ net::RedirectInfo::ComputeRedirectInfo(
+ request.method, request.url, request.site_for_cookies,
+ first_party_url_policy, request.referrer_policy,
+ request.referrer.spec(), &headers, headers.response_code(),
+ redirect_url, false /* token_binding_negotiated */,
+ false /* copy_fragment */));
+
+ client_->OnReceiveRedirect(*response_metadata_->redirect_info,
+ response_metadata_->head);
+ return Response::OK();
+}
+
+void InterceptionJob::SendResponse(const base::StringPiece& body) {
+ client_->OnReceiveResponse(response_metadata_->head,
+ std::move(response_metadata_->downloaded_file));
+
+ // We shouldn't be able to transfer a string that big over the protocol,
+ // but just in case...
+ DCHECK_LE(body.size(), UINT32_MAX)
+ << "Response bodies larger than " << UINT32_MAX << " are not supported";
+ mojo::DataPipe pipe(body.size());
+ uint32_t num_bytes = body.size();
+ MojoResult res = pipe.producer_handle->WriteData(body.data(), &num_bytes,
+ MOJO_WRITE_DATA_FLAG_NONE);
+ DCHECK_EQ(0u, res);
+ DCHECK_EQ(num_bytes, body.size());
+
+ if (!response_metadata_->cached_metadata.empty())
+ client_->OnReceiveCachedMetadata(response_metadata_->cached_metadata);
+ client_->OnStartLoadingResponseBody(std::move(pipe.consumer_handle));
+ if (response_metadata_->transfer_size)
+ client_->OnTransferSizeUpdated(response_metadata_->transfer_size);
+
+ client_->OnComplete(response_metadata_->status);
+ Shutdown();
+}
+
+void InterceptionJob::ResponseBodyComplete() {
+ if (waiting_for_resolution_)
+ return;
+ // We're here only if client has already told us to proceed with unmodified
+ // response.
+ SendResponse(body_reader_->body());
+}
+
+void InterceptionJob::StartRequest() {
+ DCHECK_EQ(State::kNotStarted, state_);
+ DCHECK(!response_metadata_);
+
+ state_ = State::kRequestSent;
+
+ network::mojom::URLLoaderClientPtr loader_client;
+ client_binding_.Bind(MakeRequest(&loader_client));
+ client_binding_.set_connection_error_handler(
+ base::BindOnce(&InterceptionJob::Shutdown, base::Unretained(this)));
+
+ target_factory_->CreateLoaderAndStart(
+ MakeRequest(&loader_), create_loader_params_->routing_id,
+ create_loader_params_->request_id, create_loader_params_->options,
+ create_loader_params_->request, std::move(loader_client),
+ create_loader_params_->traffic_annotation);
+
+ if (priority_)
+ loader_->SetPriority(priority_->first, priority_->second);
+}
+
+void InterceptionJob::CancelRequest() {
+ if (state_ == State::kNotStarted)
+ return;
+ client_binding_.Close();
+ loader_.reset();
+ if (body_reader_) {
+ body_reader_->CancelWithError(
+ "Another command has cancelled the fetch request");
+ body_reader_.reset();
+ }
+ state_ = State::kNotStarted;
+}
+
+std::unique_ptr<InterceptedRequestInfo> InterceptionJob::BuildRequestInfo(
+ const network::ResourceResponseHead* head) {
+ auto result = std::make_unique<InterceptedRequestInfo>();
+ result->interception_id = id_;
+ result->network_request =
+ protocol::NetworkHandler::CreateRequestFromResourceRequest(
+ create_loader_params_->request);
+ result->frame_id = frame_token_;
+ ResourceType resource_type =
+ static_cast<ResourceType>(create_loader_params_->request.resource_type);
+ result->resource_type = resource_type;
+ result->is_navigation = resource_type == RESOURCE_TYPE_MAIN_FRAME ||
+ resource_type == RESOURCE_TYPE_SUB_FRAME;
+
+ // TODO(caseq): merge with NetworkHandler::BuildResponse()
+ if (head && head->headers) {
+ result->http_response_status_code = head->headers->response_code();
+ auto headers_dict = protocol::DictionaryValue::create();
+ size_t iter = 0;
+ std::string name;
+ std::string value;
+ while (head->headers->EnumerateHeaderLines(&iter, &name, &value)) {
+ std::string old_value;
+ bool merge_with_another = headers_dict->getString(name, &old_value);
+ headers_dict->setString(
+ name, merge_with_another ? old_value + '\n' + value : value);
+ }
+ result->response_headers =
+ protocol::Object::fromValue(headers_dict.get(), nullptr);
+ }
+ return result;
+}
+
+void InterceptionJob::NotifyClient(
+ std::unique_ptr<InterceptedRequestInfo> request_info) {
+ waiting_for_resolution_ = true;
+ BrowserThread::PostTask(
+ BrowserThread::UI, FROM_HERE,
+ base::BindOnce(interceptor_->request_intercepted_callback_,
+ std::move(request_info)));
+}
+
+void InterceptionJob::Shutdown() {
+ if (interceptor_)
+ interceptor_->RemoveJob(id_);
+ delete this;
+}
+
+// URLLoader methods
+void InterceptionJob::FollowRedirect() {
+ DCHECK(!waiting_for_resolution_);
+
+ network::ResourceRequest* request = &create_loader_params_->request;
+ const net::RedirectInfo& info = *response_metadata_->redirect_info;
+ request->method = info.new_method;
+ request->url = info.new_url;
+ request->site_for_cookies = info.new_site_for_cookies;
+ request->referrer_policy = info.new_referrer_policy;
+ request->referrer = GURL(info.new_referrer);
+ response_metadata_.reset();
+ if (interceptor_) {
+ stage_ = interceptor_->GetInterceptionStage(
+ request->url, static_cast<ResourceType>(request->resource_type));
+ }
+ if (state_ == State::kRedirectReceived) {
+ state_ = State::kRequestSent;
+ loader_->FollowRedirect();
+ return;
+ }
+
+ DCHECK_EQ(State::kNotStarted, state_);
+ StartRequest();
+}
+
+void InterceptionJob::ProceedWithResponse() {
+ NOTREACHED();
+}
+
+void InterceptionJob::SetPriority(net::RequestPriority priority,
+ int32_t intra_priority_value) {
+ priority_ = std::make_pair(priority, intra_priority_value);
+
+ if (state_ != State::kNotStarted)
+ loader_->SetPriority(priority, intra_priority_value);
+}
+
+void InterceptionJob::PauseReadingBodyFromNet() {
+ if (state_ != State::kNotStarted && !body_reader_)
+ loader_->PauseReadingBodyFromNet();
+}
+
+void InterceptionJob::ResumeReadingBodyFromNet() {
+ if (state_ != State::kNotStarted && !body_reader_)
+ loader_->ResumeReadingBodyFromNet();
+}
+
+// URLLoaderClient methods
+void InterceptionJob::OnReceiveResponse(
+ const network::ResourceResponseHead& head,
+ network::mojom::DownloadedTempFilePtr downloaded_file) {
+ state_ = State::kResponseReceived;
+ DCHECK(!response_metadata_);
+ if (!(stage_ & InterceptionStage::RESPONSE)) {
+ client_->OnReceiveResponse(head, std::move(downloaded_file));
+ return;
+ }
+ loader_->PauseReadingBodyFromNet();
+ client_binding_.PauseIncomingMethodCallProcessing();
+
+ response_metadata_ = std::make_unique<ResponseMetadata>(head);
+ response_metadata_->downloaded_file = std::move(downloaded_file);
+
+ NotifyClient(BuildRequestInfo(&head));
+}
+
+void InterceptionJob::OnReceiveRedirect(
+ const net::RedirectInfo& redirect_info,
+ const network::ResourceResponseHead& head) {
+ DCHECK_EQ(State::kRequestSent, state_);
+ state_ = State::kRedirectReceived;
+ response_metadata_ = std::make_unique<ResponseMetadata>(head);
+ response_metadata_->redirect_info =
+ std::make_unique<net::RedirectInfo>(redirect_info);
+
+ if (!(stage_ & InterceptionStage::REQUEST)) {
+ client_->OnReceiveRedirect(redirect_info, head);
+ return;
+ }
+
+ std::unique_ptr<InterceptedRequestInfo> request_info =
+ BuildRequestInfo(&head);
+ request_info->http_response_status_code = redirect_info.status_code;
+ request_info->redirect_url = redirect_info.new_url.spec();
+ NotifyClient(std::move(request_info));
+}
+
+void InterceptionJob::OnDataDownloaded(int64_t data_length,
+ int64_t encoded_length) {
+ if (ShouldBypassForResponse())
+ client_->OnDataDownloaded(data_length, encoded_length);
+}
+
+void InterceptionJob::OnUploadProgress(int64_t current_position,
+ int64_t total_size,
+ OnUploadProgressCallback callback) {
+ if (!report_upload_)
+ return;
+ client_->OnUploadProgress(current_position, total_size, std::move(callback));
+}
+
+void InterceptionJob::OnReceiveCachedMetadata(
+ const std::vector<uint8_t>& data) {
+ if (ShouldBypassForResponse())
+ client_->OnReceiveCachedMetadata(data);
+ else
+ response_metadata_->cached_metadata = data;
+}
+
+void InterceptionJob::OnTransferSizeUpdated(int32_t transfer_size_diff) {
+ if (ShouldBypassForResponse())
+ client_->OnTransferSizeUpdated(transfer_size_diff);
+ else
+ response_metadata_->transfer_size += transfer_size_diff;
+}
+
+void InterceptionJob::OnStartLoadingResponseBody(
+ mojo::ScopedDataPipeConsumerHandle body) {
+ if (ShouldBypassForResponse())
+ client_->OnStartLoadingResponseBody(std::move(body));
+ else
+ body_reader_->StartReading(std::move(body));
+}
+
+void InterceptionJob::OnComplete(
+ const network::URLLoaderCompletionStatus& status) {
+ if (ShouldBypassForResponse()) {
+ client_->OnComplete(status);
+ Shutdown();
+ return;
+ }
+ response_metadata_->status = status;
+}
+
+void InterceptionJob::OnAuthRequest(
+ const scoped_refptr<net::AuthChallengeInfo>& auth_info,
+ DevToolsURLLoaderInterceptor::HandleAuthRequestCallback callback) {
+ DCHECK_EQ(kRequestSent, state_);
+ DCHECK(pending_auth_callback_.is_null());
+ DCHECK(!waiting_for_resolution_);
+
+ if (!(stage_ & InterceptionStage::REQUEST)) {
+ std::move(callback).Run(true, base::nullopt);
+ return;
+ }
+ state_ = State::kAuthRequired;
+ auto request_info = BuildRequestInfo(nullptr);
+ request_info->auth_challenge =
+ protocol::Network::AuthChallenge::Create()
+ .SetSource(auth_info->is_proxy
+ ? protocol::Network::AuthChallenge::SourceEnum::Proxy
+ : protocol::Network::AuthChallenge::SourceEnum::Server)
+ .SetOrigin(auth_info->challenger.Serialize())
+ .SetScheme(auth_info->scheme)
+ .SetRealm(auth_info->realm)
+ .Build();
+ pending_auth_callback_ = std::move(callback);
+ NotifyClient(std::move(request_info));
+}
+
+} // namespace content
diff --git a/chromium/content/browser/devtools/devtools_url_loader_interceptor.h b/chromium/content/browser/devtools/devtools_url_loader_interceptor.h
new file mode 100644
index 00000000000..a05c8bc1f56
--- /dev/null
+++ b/chromium/content/browser/devtools/devtools_url_loader_interceptor.h
@@ -0,0 +1,68 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_BROWSER_DEVTOOLS_DEVTOOLS_URL_LOADER_INTERCEPTOR_H_
+#define CONTENT_BROWSER_DEVTOOLS_DEVTOOLS_URL_LOADER_INTERCEPTOR_H_
+
+#include "base/memory/weak_ptr.h"
+#include "content/browser/devtools/devtools_network_interceptor.h"
+#include "services/network/public/mojom/url_loader_factory.mojom.h"
+
+namespace content {
+
+class FrameTreeNode;
+
+class DevToolsURLLoaderInterceptor {
+ public:
+ class Impl;
+
+ using HandleAuthRequestCallback =
+ base::OnceCallback<void(bool use_fallback,
+ const base::Optional<net::AuthCredentials>&)>;
+ // Can only be called on the IO thread.
+ static void HandleAuthRequest(
+ int32_t process_id,
+ int32_t routing_id,
+ int32_t request_id,
+ const scoped_refptr<net::AuthChallengeInfo>& auth_info,
+ HandleAuthRequestCallback callback);
+
+ DevToolsURLLoaderInterceptor(
+ FrameTreeNode* local_root,
+ DevToolsNetworkInterceptor::RequestInterceptedCallback callback);
+ ~DevToolsURLLoaderInterceptor();
+
+ void SetPatterns(std::vector<DevToolsNetworkInterceptor::Pattern> patterns);
+
+ void GetResponseBody(
+ const std::string& interception_id,
+ std::unique_ptr<
+ DevToolsNetworkInterceptor::GetResponseBodyForInterceptionCallback>
+ callback);
+ void ContinueInterceptedRequest(
+ const std::string& interception_id,
+ std::unique_ptr<DevToolsNetworkInterceptor::Modifications> modifications,
+ std::unique_ptr<
+ DevToolsNetworkInterceptor::ContinueInterceptedRequestCallback>
+ callback);
+
+ bool CreateProxyForInterception(
+ const base::UnguessableToken frame_token,
+ int process_id, // 0 for navigation
+ network::mojom::URLLoaderFactoryRequest* request) const;
+
+ private:
+ void UpdateSubresourceLoaderFactories();
+
+ FrameTreeNode* const local_root_;
+ bool enabled_;
+ std::unique_ptr<Impl, base::OnTaskRunnerDeleter> impl_;
+ base::WeakPtr<Impl> weak_impl_;
+
+ DISALLOW_COPY_AND_ASSIGN(DevToolsURLLoaderInterceptor);
+};
+
+} // namespace content
+
+#endif // CONTENT_BROWSER_DEVTOOLS_DEVTOOLS_URL_LOADER_INTERCEPTOR_H_
diff --git a/chromium/content/browser/devtools/devtools_url_request_interceptor.cc b/chromium/content/browser/devtools/devtools_url_request_interceptor.cc
index 3f361e8e0c5..260a5206a1f 100644
--- a/chromium/content/browser/devtools/devtools_url_request_interceptor.cc
+++ b/chromium/content/browser/devtools/devtools_url_request_interceptor.cc
@@ -4,7 +4,6 @@
#include "content/browser/devtools/devtools_url_request_interceptor.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/pattern.h"
#include "base/strings/stringprintf.h"
#include "content/browser/devtools/devtools_interceptor_controller.h"
@@ -42,20 +41,6 @@ DevToolsURLRequestInterceptor::~DevToolsURLRequestInterceptor() {
// DevToolsURLRequestInterceptorUserData explicitly.
}
-DevToolsURLRequestInterceptor::Pattern::Pattern() = default;
-
-DevToolsURLRequestInterceptor::Pattern::~Pattern() = default;
-
-DevToolsURLRequestInterceptor::Pattern::Pattern(const Pattern& other) = default;
-
-DevToolsURLRequestInterceptor::Pattern::Pattern(
- const std::string& url_pattern,
- base::flat_set<ResourceType> resource_types,
- InterceptionStage interception_stage)
- : url_pattern(url_pattern),
- resource_types(std::move(resource_types)),
- interception_stage(interception_stage) {}
-
const DevToolsTargetRegistry::TargetInfo*
DevToolsURLRequestInterceptor::TargetInfoForRequestInfo(
const ResourceRequestInfo* request_info) const {
@@ -318,25 +303,4 @@ void DevToolsURLRequestInterceptor::JobFinished(
controller_, interception_id));
}
-DevToolsURLRequestInterceptor::Modifications::Modifications(
- base::Optional<net::Error> error_reason,
- base::Optional<std::string> raw_response,
- protocol::Maybe<std::string> modified_url,
- protocol::Maybe<std::string> modified_method,
- protocol::Maybe<std::string> modified_post_data,
- protocol::Maybe<protocol::Network::Headers> modified_headers,
- protocol::Maybe<protocol::Network::AuthChallengeResponse>
- auth_challenge_response,
- bool mark_as_canceled)
- : error_reason(std::move(error_reason)),
- raw_response(std::move(raw_response)),
- modified_url(std::move(modified_url)),
- modified_method(std::move(modified_method)),
- modified_post_data(std::move(modified_post_data)),
- modified_headers(std::move(modified_headers)),
- auth_challenge_response(std::move(auth_challenge_response)),
- mark_as_canceled(mark_as_canceled) {}
-
-DevToolsURLRequestInterceptor::Modifications::~Modifications() {}
-
} // namespace content
diff --git a/chromium/content/browser/devtools/devtools_video_consumer.cc b/chromium/content/browser/devtools/devtools_video_consumer.cc
new file mode 100644
index 00000000000..8c9bdd44ade
--- /dev/null
+++ b/chromium/content/browser/devtools/devtools_video_consumer.cc
@@ -0,0 +1,169 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/devtools/devtools_video_consumer.h"
+
+#include "cc/paint/skia_paint_canvas.h"
+#include "components/viz/host/host_frame_sink_manager.h"
+#include "components/viz/service/frame_sinks/video_capture/frame_sink_video_capturer_impl.h"
+#include "content/browser/compositor/surface_utils.h"
+#include "media/base/limits.h"
+#include "media/renderers/paint_canvas_video_renderer.h"
+
+namespace content {
+
+namespace {
+
+// Frame capture period is 10 frames per second by default.
+constexpr base::TimeDelta kDefaultMinCapturePeriod =
+ base::TimeDelta::FromMilliseconds(100);
+
+// Frame size can change every frame.
+constexpr base::TimeDelta kDefaultMinPeriod = base::TimeDelta();
+
+// Allow variable aspect ratio.
+const bool kDefaultUseFixedAspectRatio = false;
+
+} // namespace
+
+// static
+constexpr gfx::Size DevToolsVideoConsumer::kDefaultMinFrameSize;
+
+// static
+constexpr gfx::Size DevToolsVideoConsumer::kDefaultMaxFrameSize;
+
+DevToolsVideoConsumer::DevToolsVideoConsumer(OnFrameCapturedCallback callback)
+ : callback_(std::move(callback)),
+ min_capture_period_(kDefaultMinCapturePeriod),
+ min_frame_size_(kDefaultMinFrameSize),
+ max_frame_size_(kDefaultMaxFrameSize),
+ binding_(this) {}
+
+DevToolsVideoConsumer::~DevToolsVideoConsumer() = default;
+
+// static
+SkBitmap DevToolsVideoConsumer::GetSkBitmapFromFrame(
+ scoped_refptr<media::VideoFrame> frame) {
+ media::PaintCanvasVideoRenderer renderer;
+ SkBitmap skbitmap;
+ skbitmap.allocN32Pixels(frame->visible_rect().width(),
+ frame->visible_rect().height());
+ cc::SkiaPaintCanvas canvas(skbitmap);
+ renderer.Copy(frame, &canvas, media::Context3D());
+ return skbitmap;
+}
+
+void DevToolsVideoConsumer::StartCapture() {
+ if (capturer_)
+ return;
+ InnerStartCapture(CreateCapturer());
+}
+
+void DevToolsVideoConsumer::StopCapture() {
+ if (!capturer_)
+ return;
+ binding_.Close();
+ capturer_->Stop();
+ capturer_.reset();
+}
+
+void DevToolsVideoConsumer::SetFrameSinkId(
+ const viz::FrameSinkId& frame_sink_id) {
+ frame_sink_id_ = frame_sink_id;
+ if (capturer_)
+ capturer_->ChangeTarget(frame_sink_id_);
+}
+
+void DevToolsVideoConsumer::SetMinCapturePeriod(
+ base::TimeDelta min_capture_period) {
+ min_capture_period_ = min_capture_period;
+ if (capturer_)
+ capturer_->SetMinCapturePeriod(min_capture_period_);
+}
+
+void DevToolsVideoConsumer::SetMinAndMaxFrameSize(gfx::Size min_frame_size,
+ gfx::Size max_frame_size) {
+ DCHECK(IsValidMinAndMaxFrameSize(min_frame_size, max_frame_size));
+ min_frame_size_ = min_frame_size;
+ max_frame_size_ = max_frame_size;
+ if (capturer_) {
+ capturer_->SetResolutionConstraints(min_frame_size_, max_frame_size_,
+ kDefaultUseFixedAspectRatio);
+ }
+}
+
+viz::mojom::FrameSinkVideoCapturerPtrInfo
+DevToolsVideoConsumer::CreateCapturer() {
+ viz::HostFrameSinkManager* const manager = GetHostFrameSinkManager();
+ viz::mojom::FrameSinkVideoCapturerPtr capturer;
+ manager->CreateVideoCapturer(mojo::MakeRequest(&capturer));
+ return capturer.PassInterface();
+}
+
+void DevToolsVideoConsumer::InnerStartCapture(
+ viz::mojom::FrameSinkVideoCapturerPtrInfo capturer_info) {
+ capturer_.Bind(std::move(capturer_info));
+
+ // Give |capturer_| the capture parameters.
+ capturer_->SetMinCapturePeriod(min_capture_period_);
+ capturer_->SetMinSizeChangePeriod(kDefaultMinPeriod);
+ capturer_->SetResolutionConstraints(min_frame_size_, max_frame_size_,
+ kDefaultUseFixedAspectRatio);
+ capturer_->ChangeTarget(frame_sink_id_);
+
+ viz::mojom::FrameSinkVideoConsumerPtr consumer;
+ binding_.Bind(mojo::MakeRequest(&consumer));
+ capturer_->Start(std::move(consumer));
+}
+
+bool DevToolsVideoConsumer::IsValidMinAndMaxFrameSize(
+ gfx::Size min_frame_size,
+ gfx::Size max_frame_size) {
+ // Returns true if
+ // 0 < |min_frame_size| <= |max_frame_size| <= media::limits::kMaxDimension.
+ return 0 < min_frame_size.width() && 0 < min_frame_size.height() &&
+ min_frame_size.width() <= max_frame_size.width() &&
+ min_frame_size.height() <= max_frame_size.height() &&
+ max_frame_size.width() <= media::limits::kMaxDimension &&
+ max_frame_size.height() <= media::limits::kMaxDimension;
+}
+
+void DevToolsVideoConsumer::OnFrameCaptured(
+ mojo::ScopedSharedBufferHandle buffer,
+ uint32_t buffer_size,
+ ::media::mojom::VideoFrameInfoPtr info,
+ const gfx::Rect& update_rect,
+ const gfx::Rect& content_rect,
+ viz::mojom::FrameSinkVideoConsumerFrameCallbacksPtr callbacks) {
+ if (!buffer.is_valid())
+ return;
+
+ mojo::ScopedSharedBufferMapping mapping = buffer->Map(buffer_size);
+ if (!mapping) {
+ DLOG(ERROR) << "Shared memory mapping failed.";
+ return;
+ }
+
+ scoped_refptr<media::VideoFrame> frame;
+ // Setting |frame|'s visible rect equal to |content_rect| so that only the
+ // portion of the frame that contain content are used.
+ frame = media::VideoFrame::WrapExternalData(
+ info->pixel_format, info->coded_size, info->visible_rect,
+ info->visible_rect.size(), static_cast<uint8_t*>(mapping.get()),
+ buffer_size, info->timestamp);
+ if (!frame)
+ return;
+ frame->AddDestructionObserver(base::BindOnce(
+ [](mojo::ScopedSharedBufferMapping mapping) {}, std::move(mapping)));
+ frame->metadata()->MergeInternalValuesFrom(info->metadata);
+
+ callback_.Run(std::move(frame));
+}
+
+void DevToolsVideoConsumer::OnTargetLost(
+ const viz::FrameSinkId& frame_sink_id) {}
+
+void DevToolsVideoConsumer::OnStopped() {}
+
+} // namespace content
diff --git a/chromium/content/browser/devtools/devtools_video_consumer.h b/chromium/content/browser/devtools/devtools_video_consumer.h
new file mode 100644
index 00000000000..fc9bbdba359
--- /dev/null
+++ b/chromium/content/browser/devtools/devtools_video_consumer.h
@@ -0,0 +1,104 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_BROWSER_DEVTOOLS_DEVTOOLS_VIDEO_CONSUMER_H_
+#define CONTENT_BROWSER_DEVTOOLS_DEVTOOLS_VIDEO_CONSUMER_H_
+
+#include "base/time/time.h"
+#include "content/common/content_export.h"
+#include "mojo/public/cpp/bindings/binding.h"
+#include "services/viz/privileged/interfaces/compositing/frame_sink_video_capture.mojom.h"
+#include "ui/gfx/geometry/size.h"
+
+class SkBitmap;
+
+namespace content {
+
+// This class is the video consumer to FrameSinkVideoCapturerImpl. This class,
+// in turn sends video frames to its host via the OnFrameCapturedCallback. Used
+// when the VizDisplayCompositor feature is enabled.
+// TODO(https://crbug.com/813929): Use this class everywhere even if viz is not
+// enabled.
+class CONTENT_EXPORT DevToolsVideoConsumer
+ : public viz::mojom::FrameSinkVideoConsumer {
+ public:
+ using OnFrameCapturedCallback =
+ base::RepeatingCallback<void(scoped_refptr<media::VideoFrame> frame)>;
+
+ explicit DevToolsVideoConsumer(OnFrameCapturedCallback callback);
+ ~DevToolsVideoConsumer() override;
+
+ // Copies |frame| onto a SkBitmap and returns it.
+ static SkBitmap GetSkBitmapFromFrame(scoped_refptr<media::VideoFrame> frame);
+
+ // If not currently capturing, this creates the capturer and starts capturing.
+ void StartCapture();
+
+ // Closes |binding_|. Stops capturing and resets |capturer_|.
+ void StopCapture();
+
+ // These functions cache the values passed to them and if we're currently
+ // capturing, they call the corresponding |capturer_| functions.
+ // TODO(samans): Add a SetFormat function here so that ARGB pixel format can
+ // be used.
+ void SetFrameSinkId(const viz::FrameSinkId& frame_sink_id);
+ void SetMinCapturePeriod(base::TimeDelta min_capture_period);
+ void SetMinAndMaxFrameSize(gfx::Size min_frame_size,
+ gfx::Size max_frame_size);
+
+ private:
+ friend class DevToolsVideoConsumerTest;
+ // Sets up a mojo message pipe and requests the HostFrameSinkManager create a
+ // new capturer instance bound to it. Returns the client-side interface.
+ viz::mojom::FrameSinkVideoCapturerPtrInfo CreateCapturer();
+
+ // Binds |capturer_info| to the |capturer_|, sets capture parameters, and
+ // starts capture. Normally, CreateCapturer produces the |capturer_info|, but
+ // unittests can provide a mock.
+ void InnerStartCapture(
+ viz::mojom::FrameSinkVideoCapturerPtrInfo capturer_info);
+
+ // Checks that |min_frame_size| and |max_frame_size| are in the expected
+ // range. Limits are specified in media::limits.
+ bool IsValidMinAndMaxFrameSize(gfx::Size min_frame_size,
+ gfx::Size max_frame_size);
+
+ // viz::mojom::FrameSinkVideoConsumer:
+ void OnFrameCaptured(
+ mojo::ScopedSharedBufferHandle buffer,
+ uint32_t buffer_size,
+ ::media::mojom::VideoFrameInfoPtr info,
+ const gfx::Rect& update_rect,
+ const gfx::Rect& content_rect,
+ viz::mojom::FrameSinkVideoConsumerFrameCallbacksPtr callbacks) override;
+ void OnTargetLost(const viz::FrameSinkId& frame_sink_id) override;
+ void OnStopped() override;
+
+ // Default min frame size is 1x1, as otherwise, nothing would be captured.
+ static constexpr gfx::Size kDefaultMinFrameSize = gfx::Size(1, 1);
+
+ // Using an arbitrary default max frame size of 500x500.
+ static constexpr gfx::Size kDefaultMaxFrameSize = gfx::Size(500, 500);
+
+ // Callback that is run when a frame is received.
+ const OnFrameCapturedCallback callback_;
+
+ // Capture parameters.
+ base::TimeDelta min_capture_period_;
+ gfx::Size min_frame_size_;
+ gfx::Size max_frame_size_;
+ viz::FrameSinkId frame_sink_id_;
+
+ // Mojo pointer to the viz::FrameSinkVideoCapturer instance. If |capturer_|
+ // is alive, then we are currently capturing.
+ viz::mojom::FrameSinkVideoCapturerPtr capturer_;
+
+ mojo::Binding<viz::mojom::FrameSinkVideoConsumer> binding_;
+
+ DISALLOW_COPY_AND_ASSIGN(DevToolsVideoConsumer);
+};
+
+} // namespace content
+
+#endif // CONTENT_BROWSER_DEVTOOLS_DEVTOOLS_VIDEO_CONSUMER_H_
diff --git a/chromium/content/browser/devtools/devtools_video_consumer_browsertest.cc b/chromium/content/browser/devtools/devtools_video_consumer_browsertest.cc
new file mode 100644
index 00000000000..789594ed607
--- /dev/null
+++ b/chromium/content/browser/devtools/devtools_video_consumer_browsertest.cc
@@ -0,0 +1,128 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include <memory>
+
+#include "content/browser/devtools/devtools_video_consumer.h"
+#include "content/browser/web_contents/web_contents_impl.h"
+#include "content/public/test/browser_test_utils.h"
+#include "content/public/test/content_browser_test.h"
+#include "content/public/test/content_browser_test_utils.h"
+#include "content/public/test/test_utils.h"
+#include "content/shell/browser/shell.h"
+#include "net/test/embedded_test_server/controllable_http_response.h"
+
+namespace {
+
+// Helper to verify that |frame| dimensions are in the expected ranges.
+bool VerifyFrameSize(scoped_refptr<media::VideoFrame> frame,
+ gfx::Size min_frame_size,
+ gfx::Size max_frame_size) {
+ // Returns true if |min_frame_size| <= |frame| <= |max_frame_size|.
+ return min_frame_size.width() <= frame->visible_rect().width() &&
+ min_frame_size.height() <= frame->visible_rect().height() &&
+ frame->visible_rect().width() <= max_frame_size.width() &&
+ frame->visible_rect().height() <= max_frame_size.height();
+}
+
+// The default video pixel format.
+// TODO(sundarrajs): Add |FrameSinkVideoCapturerImpl::kDefaultPixelFormat| to
+// frame_sink_video_capture.mojom and use that instead of
+// |kVideoCapturerDefaultPixelFormat|.
+constexpr media::VideoPixelFormat kVideoCapturerDefaultPixelFormat =
+ media::PIXEL_FORMAT_I420;
+
+} // namespace
+
+namespace content {
+
+class DevToolsVideoConsumerTest : public ContentBrowserTest {
+ public:
+ DevToolsVideoConsumerTest() {}
+
+ void SetUpOnMainThread() override {
+ consumer_ = std::make_unique<DevToolsVideoConsumer>(base::BindRepeating(
+ &DevToolsVideoConsumerTest::OnFrameFromVideoConsumer,
+ base::Unretained(this)));
+ consumer_->SetFrameSinkId(
+ static_cast<content::WebContentsImpl*>(shell()->web_contents())
+ ->GetRenderViewHost()
+ ->GetWidget()
+ ->GetFrameSinkId());
+ }
+
+ scoped_refptr<media::VideoFrame> GetFrame(int i) { return frames_[i]; }
+
+ size_t NumberOfFramesReceived() { return frames_.size(); }
+
+ void OnFrameFromVideoConsumer(scoped_refptr<media::VideoFrame> frame) {
+ run_loop_->Quit();
+ frames_.push_back(std::move(frame));
+ }
+
+ void WaitUntilFrameReceived() {
+ run_loop_.reset(new base::RunLoop);
+ run_loop_->Run();
+ }
+
+ static gfx::Size GetVideoConsumerDefaultMinFrameSize() {
+ return DevToolsVideoConsumer::kDefaultMinFrameSize;
+ }
+
+ static gfx::Size GetVideoConsumerDefaultMaxFrameSize() {
+ return DevToolsVideoConsumer::kDefaultMaxFrameSize;
+ }
+
+ protected:
+ std::unique_ptr<DevToolsVideoConsumer> consumer_;
+
+ private:
+ std::vector<scoped_refptr<media::VideoFrame>> frames_;
+ std::unique_ptr<base::RunLoop> run_loop_;
+};
+
+// Tests that setting new frame dimensions via SetMinAndMaxFrameSizes
+// produces frames of the new dimensions.
+IN_PROC_BROWSER_TEST_F(DevToolsVideoConsumerTest,
+ SetMinAndMaxFramesChangesDimensions) {
+ ASSERT_TRUE(embedded_test_server()->Start());
+
+ // Complete navigation to a page and then start capture. Since navigation is
+ // complete before capturing, we only expect the refresh frame from the
+ // StartCapture call. Wait for this refresh frame and verify its info.
+ NavigateToURLBlockUntilNavigationsComplete(
+ shell(), embedded_test_server()->GetURL("/devtools/navigation.html"), 1);
+ consumer_->StartCapture();
+ WaitUntilFrameReceived();
+ size_t cur_frame_index = 0;
+ size_t num_frames_received = 1;
+ EXPECT_EQ(num_frames_received, NumberOfFramesReceived());
+ scoped_refptr<media::VideoFrame> frame = GetFrame(cur_frame_index);
+ EXPECT_EQ(frame->format(), kVideoCapturerDefaultPixelFormat);
+ EXPECT_TRUE(VerifyFrameSize(frame, GetVideoConsumerDefaultMinFrameSize(),
+ GetVideoConsumerDefaultMaxFrameSize()));
+
+ // Setting |kNewMinFrameSize| > |kDefaultMaxFrameSize| to disambiguate
+ // frames with older vs. newer dimensions.
+ const gfx::Size kNewMinFrameSize =
+ gfx::Size(GetVideoConsumerDefaultMaxFrameSize().width() + 1,
+ GetVideoConsumerDefaultMaxFrameSize().height() + 1);
+ // |kNewMaxFrameSize| only needs to be >= |kNewMinFrameSize|.
+ const gfx::Size kNewMaxFrameSize = gfx::Size(kNewMinFrameSize.width() + 500,
+ kNewMinFrameSize.height() + 500);
+ // Set the min and max frame sizes. This will call
+ // FrameSinkVideoCapturer::SetResolutionConstraints which triggers sending a
+ // refresh frame. Wait for this refresh frame and verify it's info.
+ consumer_->SetMinAndMaxFrameSize(kNewMinFrameSize, kNewMaxFrameSize);
+ WaitUntilFrameReceived();
+ EXPECT_EQ(++num_frames_received, NumberOfFramesReceived());
+ frame = GetFrame(++cur_frame_index);
+ EXPECT_EQ(frame->format(), kVideoCapturerDefaultPixelFormat);
+ EXPECT_TRUE(VerifyFrameSize(frame, kNewMinFrameSize, kNewMaxFrameSize));
+
+ // Stop capturing.
+ consumer_->StopCapture();
+}
+
+} // namespace content
diff --git a/chromium/content/browser/devtools/devtools_video_consumer_unittest.cc b/chromium/content/browser/devtools/devtools_video_consumer_unittest.cc
new file mode 100644
index 00000000000..adb95d4bbab
--- /dev/null
+++ b/chromium/content/browser/devtools/devtools_video_consumer_unittest.cc
@@ -0,0 +1,394 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include <memory>
+
+#include "base/message_loop/message_loop.h"
+#include "content/browser/devtools/devtools_video_consumer.h"
+#include "content/public/test/test_utils.h"
+#include "media/base/limits.h"
+#include "testing/gmock/include/gmock/gmock.h"
+
+using testing::_;
+
+namespace content {
+namespace {
+
+// Capture parameters.
+constexpr gfx::Size kResolution = gfx::Size(320, 180); // Arbitrarily chosen.
+constexpr media::VideoPixelFormat kFormat = media::PIXEL_FORMAT_I420;
+constexpr media::VideoPixelStorage kStorage = media::VideoPixelStorage::CPU;
+
+// A non-zero FrameSinkId to prevent validation errors when
+// DevToolsVideoConsumer::ChangeTarget(viz::FrameSinkId) is called
+// (which eventually fails in FrameSinkVideoCapturerStubDispatch::Accept).
+constexpr viz::FrameSinkId kInitialFrameSinkId = viz::FrameSinkId(1, 1);
+
+} // namespace
+
+// Mock for the FrameSinkVideoCapturer running in the VIZ process.
+class MockFrameSinkVideoCapturer : public viz::mojom::FrameSinkVideoCapturer {
+ public:
+ MockFrameSinkVideoCapturer() : binding_(this) {}
+
+ bool is_bound() const { return binding_.is_bound(); }
+
+ void Bind(viz::mojom::FrameSinkVideoCapturerRequest request) {
+ DCHECK(!binding_.is_bound());
+ binding_.Bind(std::move(request));
+ }
+
+ // This is never called.
+ MOCK_METHOD2(SetFormat,
+ void(media::VideoPixelFormat format,
+ media::ColorSpace color_space));
+ void SetMinCapturePeriod(base::TimeDelta min_capture_period) final {
+ min_capture_period_ = min_capture_period;
+ MockSetMinCapturePeriod(min_capture_period_);
+ }
+ MOCK_METHOD1(MockSetMinCapturePeriod,
+ void(base::TimeDelta min_capture_period));
+ void SetMinSizeChangePeriod(base::TimeDelta min_period) final {
+ min_period_ = min_period;
+ MockSetMinSizeChangePeriod(min_period_);
+ }
+ MOCK_METHOD1(MockSetMinSizeChangePeriod, void(base::TimeDelta min_period));
+ void SetResolutionConstraints(const gfx::Size& min_frame_size,
+ const gfx::Size& max_frame_size,
+ bool use_fixed_aspect_ratio) final {
+ min_frame_size_ = min_frame_size;
+ max_frame_size_ = max_frame_size;
+ MockSetResolutionConstraints(min_frame_size_, max_frame_size_, true);
+ }
+ MOCK_METHOD3(MockSetResolutionConstraints,
+ void(const gfx::Size& min_frame_size,
+ const gfx::Size& max_frame_size,
+ bool use_fixed_aspect_ratio));
+ // This is never called.
+ MOCK_METHOD1(SetAutoThrottlingEnabled, void(bool));
+ void ChangeTarget(const viz::FrameSinkId& frame_sink_id) final {
+ frame_sink_id_ = frame_sink_id;
+ MockChangeTarget(frame_sink_id_);
+ }
+ MOCK_METHOD1(MockChangeTarget, void(const viz::FrameSinkId& frame_sink_id));
+ void Start(viz::mojom::FrameSinkVideoConsumerPtr consumer) final {
+ DCHECK(!consumer_);
+ consumer_ = std::move(consumer);
+ MockStart(consumer_.get());
+ }
+ MOCK_METHOD1(MockStart, void(viz::mojom::FrameSinkVideoConsumer* consumer));
+ void Stop() final {
+ binding_.Close();
+ consumer_.reset();
+ MockStop();
+ }
+ MOCK_METHOD0(MockStop, void());
+ MOCK_METHOD0(RequestRefreshFrame, void());
+
+ // Const accessors to get the cached variables.
+ base::TimeDelta min_capture_period() const { return min_capture_period_; }
+ base::TimeDelta min_period() const { return min_period_; }
+ gfx::Size min_frame_size() const { return min_frame_size_; }
+ gfx::Size max_frame_size() const { return max_frame_size_; }
+ viz::FrameSinkId frame_sink_id() const { return frame_sink_id_; }
+
+ private:
+ // These variables are cached when they are received from
+ // DevToolsVideoConsumer.
+ base::TimeDelta min_capture_period_;
+ base::TimeDelta min_period_;
+ gfx::Size min_frame_size_;
+ gfx::Size max_frame_size_;
+ viz::FrameSinkId frame_sink_id_;
+ viz::mojom::FrameSinkVideoConsumerPtr consumer_;
+
+ mojo::Binding<viz::mojom::FrameSinkVideoCapturer> binding_;
+};
+
+// Represents the FrameSinkVideoConsumerFrameCallbacks instance in the VIZ
+// process.
+class MockFrameSinkVideoConsumerFrameCallbacks
+ : public viz::mojom::FrameSinkVideoConsumerFrameCallbacks {
+ public:
+ MockFrameSinkVideoConsumerFrameCallbacks() : binding_(this) {}
+
+ void Bind(viz::mojom::FrameSinkVideoConsumerFrameCallbacksRequest request) {
+ binding_.Bind(std::move(request));
+ }
+
+ MOCK_METHOD0(Done, void());
+ MOCK_METHOD1(ProvideFeedback, void(double utilization));
+
+ private:
+ mojo::Binding<viz::mojom::FrameSinkVideoConsumerFrameCallbacks> binding_;
+};
+
+// Mock for the classes like TracingHandler that receive frames from
+// DevToolsVideoConsumer via the OnFrameCapturedCallback.
+class MockDevToolsVideoFrameReceiver {
+ public:
+ MOCK_METHOD1(OnFrameFromVideoConsumerMock,
+ void(scoped_refptr<media::VideoFrame> frame));
+
+ MockDevToolsVideoFrameReceiver() : weak_factory_(this) {}
+
+ scoped_refptr<media::VideoFrame> TakeFrameAt(int i) {
+ return std::move(frames_[i]);
+ }
+
+ void OnFrameFromVideoConsumer(scoped_refptr<media::VideoFrame> frame) {
+ OnFrameFromVideoConsumerMock(frame);
+ frames_.push_back(std::move(frame));
+ }
+
+ std::unique_ptr<DevToolsVideoConsumer> CreateDevToolsVideoConsumer() {
+ return std::make_unique<DevToolsVideoConsumer>(base::BindRepeating(
+ &MockDevToolsVideoFrameReceiver::OnFrameFromVideoConsumer,
+ weak_factory_.GetWeakPtr()));
+ }
+
+ private:
+ std::vector<scoped_refptr<media::VideoFrame>> frames_;
+ base::WeakPtrFactory<MockDevToolsVideoFrameReceiver> weak_factory_;
+};
+
+class DevToolsVideoConsumerTest : public testing::Test {
+ public:
+ DevToolsVideoConsumerTest() : weak_factory_(this) {}
+
+ void SetUp() override {
+ consumer_ = receiver_.CreateDevToolsVideoConsumer();
+
+ consumer_->SetFrameSinkId(kInitialFrameSinkId);
+ }
+
+ void SimulateFrameCapture(mojo::ScopedSharedBufferHandle buffer,
+ uint32_t buffer_size) {
+ viz::mojom::FrameSinkVideoConsumerFrameCallbacksPtr callbacks_ptr;
+ callbacks.Bind(mojo::MakeRequest(&callbacks_ptr));
+
+ media::mojom::VideoFrameInfoPtr info = media::mojom::VideoFrameInfo::New(
+ base::TimeDelta(), base::Value(base::Value::Type::DICTIONARY), kFormat,
+ kStorage, kResolution, gfx::Rect(kResolution));
+
+ consumer_->OnFrameCaptured(std::move(buffer), buffer_size, std::move(info),
+ gfx::Rect(kResolution), gfx::Rect(kResolution),
+ std::move(callbacks_ptr));
+ }
+
+ void StartCaptureWithMockCapturer() {
+ consumer_->InnerStartCapture(BindMockCapturer());
+ }
+
+ bool IsValidMinAndMaxFrameSize(gfx::Size min_frame_size,
+ gfx::Size max_frame_size) {
+ return consumer_->IsValidMinAndMaxFrameSize(min_frame_size, max_frame_size);
+ }
+
+ static gfx::Size GetVideoConsumerDefaultMinFrameSize() {
+ return DevToolsVideoConsumer::kDefaultMinFrameSize;
+ }
+
+ static gfx::Size GetVideoConsumerDefaultMaxFrameSize() {
+ return DevToolsVideoConsumer::kDefaultMaxFrameSize;
+ }
+
+ // Getters for |consumer_|'s private variables.
+ base::TimeDelta GetMinCapturePeriod() const {
+ return consumer_->min_capture_period_;
+ }
+ gfx::Size GetMinFrameSize() const { return consumer_->min_frame_size_; }
+ gfx::Size GetMaxFrameSize() const { return consumer_->max_frame_size_; }
+ viz::FrameSinkId GetFrameSinkId() const { return consumer_->frame_sink_id_; }
+
+ protected:
+ MockFrameSinkVideoCapturer capturer_;
+ MockFrameSinkVideoConsumerFrameCallbacks callbacks;
+ MockDevToolsVideoFrameReceiver receiver_;
+ std::unique_ptr<DevToolsVideoConsumer> consumer_;
+
+ private:
+ viz::mojom::FrameSinkVideoCapturerPtrInfo BindMockCapturer() {
+ viz::mojom::FrameSinkVideoCapturerPtr capturer_ptr;
+ capturer_.Bind(mojo::MakeRequest(&capturer_ptr));
+ return capturer_ptr.PassInterface();
+ }
+
+ base::MessageLoop message_loop_;
+ base::WeakPtrFactory<DevToolsVideoConsumerTest> weak_factory_;
+};
+
+// Tests that the OnFrameFromVideoConsumer callbacks is called when
+// OnFrameCaptured is passed a valid buffer with valid mapping.
+TEST_F(DevToolsVideoConsumerTest, CallbacksAreCalledWhenBufferValid) {
+ // Create a valid buffer.
+ const size_t buffer_size =
+ media::VideoFrame::AllocationSize(kFormat, kResolution);
+ mojo::ScopedSharedBufferHandle buffer =
+ mojo::SharedBufferHandle::Create(buffer_size);
+
+ // On valid buffer the |receiver_| gets a frame via OnFrameFromVideoConsumer.
+ EXPECT_CALL(receiver_, OnFrameFromVideoConsumerMock(_)).Times(1);
+
+ SimulateFrameCapture(std::move(buffer), buffer_size);
+ base::RunLoop().RunUntilIdle();
+}
+
+// Tests that only the OnFrameFromVideoConsumer callback is not called when
+// OnFrameCaptured is passed an invalid buffer.
+TEST_F(DevToolsVideoConsumerTest, OnFrameCapturedExitEarlyOnInvalidBuffer) {
+ // Create an invalid buffer.
+ const size_t buffer_size = 0;
+ mojo::ScopedSharedBufferHandle buffer =
+ mojo::SharedBufferHandle::Create(buffer_size);
+
+ // On invalid buffer, the |receiver_| doesn't get a frame.
+ EXPECT_CALL(receiver_, OnFrameFromVideoConsumerMock(_)).Times(0);
+
+ SimulateFrameCapture(std::move(buffer), buffer_size);
+ base::RunLoop().RunUntilIdle();
+}
+
+// Tests that the OnFrameFromVideoConsumer callback is not called when
+// OnFrameCaptured is passed a buffer with invalid mapping.
+TEST_F(DevToolsVideoConsumerTest, OnFrameCapturedExitsOnInvalidMapping) {
+ // Create a valid buffer, but change buffer_size to simulate an invalid
+ // mapping.
+ size_t buffer_size = media::VideoFrame::AllocationSize(kFormat, kResolution);
+ mojo::ScopedSharedBufferHandle buffer =
+ mojo::SharedBufferHandle::Create(buffer_size);
+ buffer_size = 0;
+
+ // On invalid mapping, the |receiver_| doesn't get a frame.
+ EXPECT_CALL(receiver_, OnFrameFromVideoConsumerMock(_)).Times(0);
+
+ SimulateFrameCapture(std::move(buffer), buffer_size);
+ base::RunLoop().RunUntilIdle();
+}
+
+// Tests that starting capture calls |capturer_| functions, and capture can be
+// restarted. This test is important as it ensures that when restarting capture,
+// a FrameSinkVideoCapturerPtrInfo is bound to |capturer_| and it verifies that
+// resources used in the previous StartCapture aren't reused.
+TEST_F(DevToolsVideoConsumerTest, StartCaptureCallsSetFunctions) {
+ // Starting capture should call these |capturer_| functions once.
+ EXPECT_CALL(capturer_, MockSetMinCapturePeriod(_));
+ EXPECT_CALL(capturer_, MockSetMinSizeChangePeriod(_));
+ EXPECT_CALL(capturer_, MockSetResolutionConstraints(_, _, _));
+ EXPECT_CALL(capturer_, MockChangeTarget(_));
+ EXPECT_CALL(capturer_, MockStart(_));
+ StartCaptureWithMockCapturer();
+ base::RunLoop().RunUntilIdle();
+
+ // Stop capturing.
+ EXPECT_CALL(capturer_, MockStop());
+ consumer_->StopCapture();
+ base::RunLoop().RunUntilIdle();
+
+ // Start capturing again, and expect that these |capturer_| functions are
+ // called once. This will re-bind the |capturer_| and ensures that destroyed
+ // resources aren't being reused.
+ EXPECT_CALL(capturer_, MockSetMinCapturePeriod(_));
+ EXPECT_CALL(capturer_, MockSetMinSizeChangePeriod(_));
+ EXPECT_CALL(capturer_, MockSetResolutionConstraints(_, _, _));
+ EXPECT_CALL(capturer_, MockChangeTarget(_));
+ EXPECT_CALL(capturer_, MockStart(_));
+ StartCaptureWithMockCapturer();
+ base::RunLoop().RunUntilIdle();
+}
+
+// Tests that calling 'Set' functions in DevToolsVideoConsumer before
+// |capturer_| is initialized results in the passed values being cached.
+// When capture is later started (and |capturer_| initialized), these cached
+// values should be used and sent to the |capturer_|.
+TEST_F(DevToolsVideoConsumerTest, CapturerIsPassedCachedValues) {
+ // These values are chosen so that they are valid, and different from
+ // the default values in DevToolsVideoConsumer.
+ constexpr base::TimeDelta kNewMinCapturePeriod = base::TimeDelta();
+ const gfx::Size kNewMinFrameSize =
+ gfx::Size(GetVideoConsumerDefaultMinFrameSize().width() + 1,
+ GetVideoConsumerDefaultMinFrameSize().height() + 1);
+ const gfx::Size kNewMaxFrameSize =
+ gfx::Size(GetVideoConsumerDefaultMaxFrameSize().width() + 1,
+ GetVideoConsumerDefaultMaxFrameSize().width() + 1);
+ constexpr viz::FrameSinkId kNewFrameSinkId = viz::FrameSinkId(2, 2);
+
+ // Right now, |capturer_| has not been created via StartCapture, so
+ // calling these functions should not call the |capturer_|, but the
+ // values that are passed in should be cached.
+ EXPECT_CALL(capturer_, MockSetMinCapturePeriod(_)).Times(0);
+ EXPECT_CALL(capturer_, MockSetMinSizeChangePeriod(_)).Times(0);
+ EXPECT_CALL(capturer_, MockSetResolutionConstraints(_, _, _)).Times(0);
+ EXPECT_CALL(capturer_, MockChangeTarget(_)).Times(0);
+ EXPECT_CALL(capturer_, MockStart(_)).Times(0);
+ consumer_->SetMinCapturePeriod(kNewMinCapturePeriod);
+ consumer_->SetMinAndMaxFrameSize(kNewMinFrameSize, kNewMaxFrameSize);
+ consumer_->SetFrameSinkId(kNewFrameSinkId);
+ base::RunLoop().RunUntilIdle();
+ // Verify that new values are cached.
+ EXPECT_EQ(GetMinCapturePeriod(), kNewMinCapturePeriod);
+ EXPECT_EQ(GetMinFrameSize(), kNewMinFrameSize);
+ EXPECT_EQ(GetMaxFrameSize(), kNewMaxFrameSize);
+ EXPECT_EQ(GetFrameSinkId(), kNewFrameSinkId);
+
+ // Starting capture now, will result in the cached values being sent to
+ // |capturer_|. So, expect that these calls are made and verify the values.
+ EXPECT_CALL(capturer_, MockSetMinCapturePeriod(_));
+ EXPECT_CALL(capturer_, MockSetMinSizeChangePeriod(_));
+ EXPECT_CALL(capturer_, MockSetResolutionConstraints(_, _, _));
+ EXPECT_CALL(capturer_, MockChangeTarget(_));
+ EXPECT_CALL(capturer_, MockStart(_));
+ StartCaptureWithMockCapturer();
+ base::RunLoop().RunUntilIdle();
+ // Verify that the previously cached values are sent to |capturer_|.
+ EXPECT_EQ(capturer_.min_capture_period(), kNewMinCapturePeriod);
+ EXPECT_EQ(capturer_.min_frame_size(), kNewMinFrameSize);
+ EXPECT_EQ(capturer_.max_frame_size(), kNewMaxFrameSize);
+ EXPECT_EQ(capturer_.frame_sink_id(), kNewFrameSinkId);
+}
+
+// Tests that DevToolsVideoConsumer::IsValidMinAndMaxFrameSize adheres to the
+// limits set by media::limits::kMaxDimension
+TEST_F(DevToolsVideoConsumerTest, IsValidMinAndMaxFrameSize) {
+ // Choosing valid frame sizes with
+ // kNormalMinSize.height() > kNormalMaxSize.width() so that width
+ // and height are not interchanged in this test.
+ constexpr gfx::Size kNormalMinSize = gfx::Size(50, 150);
+ constexpr gfx::Size kNormalMaxSize = gfx::Size(100, 200);
+
+ // Testing success cases.
+ EXPECT_TRUE(IsValidMinAndMaxFrameSize(kNormalMinSize, kNormalMaxSize));
+ // Non-zero frames that are equal should pass.
+ EXPECT_TRUE(IsValidMinAndMaxFrameSize(kNormalMinSize, kNormalMaxSize));
+ // Swapping width and height of frames should pass.
+ EXPECT_TRUE(IsValidMinAndMaxFrameSize(
+ gfx::Size(kNormalMinSize.height(), kNormalMinSize.width()),
+ gfx::Size(kNormalMaxSize.height(), kNormalMaxSize.width())));
+
+ // Testing failure cases.
+ // |min_frame_size|.width() should be > 0
+ EXPECT_FALSE(IsValidMinAndMaxFrameSize(gfx::Size(0, kNormalMinSize.height()),
+ kNormalMaxSize));
+ // |min_frame_size|.height() should be > 0
+ EXPECT_FALSE(IsValidMinAndMaxFrameSize(gfx::Size(kNormalMinSize.width(), 0),
+ kNormalMaxSize));
+ // |min_frame_size|.width() should be <= |max_frame_size|.width()
+ EXPECT_FALSE(IsValidMinAndMaxFrameSize(
+ gfx::Size(kNormalMaxSize.width() + 1, kNormalMinSize.height()),
+ kNormalMaxSize));
+ // |max_frame_size|.height() should be <= |max_frame_size|.height()
+ EXPECT_FALSE(IsValidMinAndMaxFrameSize(
+ gfx::Size(kNormalMinSize.width(), kNormalMaxSize.height() + 1),
+ kNormalMaxSize));
+ // |max_frame_size|.height() should be <= media::limits::kMaxDimension
+ EXPECT_FALSE(IsValidMinAndMaxFrameSize(
+ kNormalMinSize,
+ gfx::Size(kNormalMaxSize.width(), media::limits::kMaxDimension + 1)));
+ // |max_frame_size|.width() should be <= media::limits::kMaxDimension
+ EXPECT_FALSE(IsValidMinAndMaxFrameSize(
+ kNormalMinSize,
+ gfx::Size(media::limits::kMaxDimension + 1, kNormalMaxSize.height())));
+}
+
+} // namespace content
diff --git a/chromium/content/browser/devtools/protocol/browser_handler.cc b/chromium/content/browser/devtools/protocol/browser_handler.cc
index aed9964e47b..7e03482fde2 100644
--- a/chromium/content/browser/devtools/protocol/browser_handler.cc
+++ b/chromium/content/browser/devtools/protocol/browser_handler.cc
@@ -112,7 +112,7 @@ Response BrowserHandler::GetHistogram(
return Response::OK();
}
-Response BrowserHandler::GetCommandLine(
+Response BrowserHandler::GetBrowserCommandLine(
std::unique_ptr<protocol::Array<String>>* arguments) {
*arguments = protocol::Array<String>::create();
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
diff --git a/chromium/content/browser/devtools/protocol/browser_handler.h b/chromium/content/browser/devtools/protocol/browser_handler.h
index 8af1d28e08a..b4f3e05eccc 100644
--- a/chromium/content/browser/devtools/protocol/browser_handler.h
+++ b/chromium/content/browser/devtools/protocol/browser_handler.h
@@ -34,7 +34,7 @@ class BrowserHandler : public DevToolsDomainHandler, public Browser::Backend {
const std::string& in_name,
std::unique_ptr<Browser::Histogram>* out_histogram) override;
- Response GetCommandLine(
+ Response GetBrowserCommandLine(
std::unique_ptr<protocol::Array<String>>* arguments) override;
private:
diff --git a/chromium/content/browser/devtools/protocol/devtools_download_manager_delegate.cc b/chromium/content/browser/devtools/protocol/devtools_download_manager_delegate.cc
index 687a744304b..f71a5bf4ab3 100644
--- a/chromium/content/browser/devtools/protocol/devtools_download_manager_delegate.cc
+++ b/chromium/content/browser/devtools/protocol/devtools_download_manager_delegate.cc
@@ -121,7 +121,7 @@ bool DevToolsDownloadManagerDelegate::DetermineDownloadTarget(
base::BindOnce(&DevToolsDownloadManagerDelegate::GenerateFilename,
item->GetURL(), item->GetContentDisposition(),
item->GetSuggestedFilename(), item->GetMimeType(),
- download_path, filename_determined_callback));
+ download_path, std::move(filename_determined_callback)));
return true;
}
diff --git a/chromium/content/browser/devtools/protocol/devtools_protocol_browsertest.cc b/chromium/content/browser/devtools/protocol/devtools_protocol_browsertest.cc
index d8eba18ceb5..5a364cef4ed 100644
--- a/chromium/content/browser/devtools/protocol/devtools_protocol_browsertest.cc
+++ b/chromium/content/browser/devtools/protocol/devtools_protocol_browsertest.cc
@@ -21,15 +21,16 @@
#include "base/sys_info.h"
#include "base/values.h"
#include "build/build_config.h"
+#include "components/download/public/common/download_file_factory.h"
+#include "components/download/public/common/download_file_impl.h"
#include "components/download/public/common/download_task_runner.h"
#include "content/browser/devtools/protocol/devtools_download_manager_delegate.h"
-#include "content/browser/download/download_file_factory.h"
-#include "content/browser/download/download_file_impl.h"
#include "content/browser/download/download_manager_impl.h"
#include "content/browser/frame_host/interstitial_page_impl.h"
#include "content/browser/frame_host/navigator.h"
#include "content/browser/renderer_host/render_widget_host_view_base.h"
#include "content/browser/web_contents/web_contents_impl.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/interstitial_page_delegate.h"
@@ -49,6 +50,7 @@
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/public/test/download_test_observer.h"
+#include "content/public/test/slow_download_http_response.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/shell/browser/shell.h"
#include "content/shell/browser/shell_browser_context.h"
@@ -58,9 +60,7 @@
#include "net/dns/mock_host_resolver.h"
#include "net/test/cert_test_util.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
-#include "net/test/test_data_directory.h"
-#include "net/test/url_request/url_request_mock_http_job.h"
-#include "net/test/url_request/url_request_slow_download_job.h"
+#include "services/network/public/cpp/features.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkColor.h"
@@ -2243,6 +2243,24 @@ IN_PROC_BROWSER_TEST_F(DevToolsProtocolDeviceEmulationTest, MAYBE_DeviceSize) {
EXPECT_EQ(original_size, GetViewSize());
}
+// Setting frame size (through RWHV) is not supported on Android.
+#if defined(OS_ANDROID)
+#define MAYBE_RenderKillDoesNotCrashBrowser \
+ DISABLED_RenderKillDoesNotCrashBrowser
+#else
+#define MAYBE_RenderKillDoesNotCrashBrowser RenderKillDoesNotCrashBrowser
+#endif
+IN_PROC_BROWSER_TEST_F(DevToolsProtocolDeviceEmulationTest,
+ MAYBE_RenderKillDoesNotCrashBrowser) {
+ NavigateToURLBlockUntilNavigationsComplete(shell(), GURL("about:blank"), 1);
+ Attach();
+ EmulateDeviceSize(gfx::Size(200, 200));
+ NavigateToURLBlockUntilNavigationsComplete(
+ shell(), GURL(content::kChromeUICrashURL), 1);
+ SendCommand("Emulation.clearDeviceMetricsOverride", nullptr);
+ // Should not crash at this point.
+}
+
class DevToolsProtocolTouchTest : public DevToolsProtocolTest {
public:
~DevToolsProtocolTouchTest() override {}
@@ -2385,32 +2403,34 @@ static void RemoveShellDelegate(Shell* shell) {
DownloadManagerForShell(shell)->SetDelegate(nullptr);
}
-class CountingDownloadFile : public DownloadFileImpl {
+class CountingDownloadFile : public download::DownloadFileImpl {
public:
- CountingDownloadFile(std::unique_ptr<download::DownloadSaveInfo> save_info,
- const base::FilePath& default_downloads_directory,
- std::unique_ptr<DownloadManager::InputStream> stream,
- uint32_t download_id,
- base::WeakPtr<DownloadDestinationObserver> observer)
- : DownloadFileImpl(std::move(save_info),
- default_downloads_directory,
- std::move(stream),
- download_id,
- observer) {}
+ CountingDownloadFile(
+ std::unique_ptr<download::DownloadSaveInfo> save_info,
+ const base::FilePath& default_downloads_directory,
+ std::unique_ptr<download::InputStream> stream,
+ uint32_t download_id,
+ base::WeakPtr<download::DownloadDestinationObserver> observer)
+ : download::DownloadFileImpl(std::move(save_info),
+ default_downloads_directory,
+ std::move(stream),
+ download_id,
+ observer) {}
~CountingDownloadFile() override {
DCHECK(download::GetDownloadTaskRunner()->RunsTasksInCurrentSequence());
active_files_--;
}
- void Initialize(const InitializeCallback& callback,
+ void Initialize(InitializeCallback callback,
const CancelRequestCallback& cancel_request_callback,
const download::DownloadItem::ReceivedSlices& received_slices,
bool is_parallelizable) override {
DCHECK(download::GetDownloadTaskRunner()->RunsTasksInCurrentSequence());
active_files_++;
- DownloadFileImpl::Initialize(callback, cancel_request_callback,
- received_slices, is_parallelizable);
+ download::DownloadFileImpl::Initialize(std::move(callback),
+ cancel_request_callback,
+ received_slices, is_parallelizable);
}
static void GetNumberActiveFiles(int* result) {
@@ -2437,18 +2457,18 @@ class CountingDownloadFile : public DownloadFileImpl {
int CountingDownloadFile::active_files_ = 0;
-class CountingDownloadFileFactory : public DownloadFileFactory {
+class CountingDownloadFileFactory : public download::DownloadFileFactory {
public:
CountingDownloadFileFactory() {}
~CountingDownloadFileFactory() override {}
// DownloadFileFactory interface.
- DownloadFile* CreateFile(
+ download::DownloadFile* CreateFile(
std::unique_ptr<download::DownloadSaveInfo> save_info,
const base::FilePath& default_downloads_directory,
- std::unique_ptr<DownloadManager::InputStream> stream,
+ std::unique_ptr<download::InputStream> stream,
uint32_t download_id,
- base::WeakPtr<DownloadDestinationObserver> observer) override {
+ base::WeakPtr<download::DownloadDestinationObserver> observer) override {
return new CountingDownloadFile(std::move(save_info),
default_downloads_directory,
std::move(stream), download_id, observer);
@@ -2488,7 +2508,7 @@ class TestShellDownloadManagerDelegate : public ShellDownloadManagerDelegate {
class DownloadCreateObserver : DownloadManager::Observer {
public:
explicit DownloadCreateObserver(DownloadManager* manager)
- : manager_(manager), item_(nullptr) {
+ : manager_(manager), item_(nullptr), received_item_response_(false) {
manager_->AddObserver(this);
}
@@ -2506,16 +2526,26 @@ class DownloadCreateObserver : DownloadManager::Observer {
void OnDownloadCreated(DownloadManager* manager,
download::DownloadItem* download) override {
+ received_item_response_ = true;
+
if (!item_)
item_ = download;
- if (!completion_closure_.is_null())
- base::ResetAndReturn(&completion_closure_).Run();
+ if (completion_closure_)
+ std::move(completion_closure_).Run();
+ }
+
+ void OnDownloadDropped(DownloadManager* manager) override {
+ received_item_response_ = true;
+
+ item_ = nullptr;
+ if (completion_closure_)
+ std::move(completion_closure_).Run();
}
download::DownloadItem* WaitForFinished() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
- if (!item_) {
+ if (!received_item_response_) {
base::RunLoop run_loop;
completion_closure_ = run_loop.QuitClosure();
run_loop.Run();
@@ -2526,6 +2556,7 @@ class DownloadCreateObserver : DownloadManager::Observer {
private:
DownloadManager* manager_;
download::DownloadItem* item_;
+ bool received_item_response_;
base::Closure completion_closure_;
};
@@ -2549,14 +2580,8 @@ class DevToolsDownloadContentTest : public DevToolsProtocolTest {
manager->SetDelegate(test_delegate_.get());
test_delegate_->SetDownloadManager(manager);
- BrowserThread::PostTask(
- BrowserThread::IO, FROM_HERE,
- base::BindOnce(&net::URLRequestSlowDownloadJob::AddUrlHandler));
- base::FilePath mock_base(GetTestFilePath("download", ""));
-
- BrowserThread::PostTask(
- BrowserThread::IO, FROM_HERE,
- base::BindOnce(&net::URLRequestMockHTTPJob::AddUrlHandlers, mock_base));
+ embedded_test_server()->RegisterRequestHandler(base::BindRepeating(
+ &content::SlowDownloadHttpResponse::HandleSlowDownloadRequest));
ASSERT_TRUE(embedded_test_server()->Start());
}
@@ -2590,7 +2615,7 @@ class DevToolsDownloadContentTest : public DevToolsProtocolTest {
// Note: Cannot be used with other alternative DownloadFileFactorys
void SetupEnsureNoPendingDownloads() {
DownloadManagerForShell(shell())->SetDownloadFileFactoryForTesting(
- std::unique_ptr<DownloadFileFactory>(
+ std::unique_ptr<download::DownloadFileFactory>(
new CountingDownloadFileFactory()));
}
@@ -2602,13 +2627,7 @@ class DevToolsDownloadContentTest : public DevToolsProtocolTest {
}
bool EnsureNoPendingDownloads() {
- bool result = true;
- BrowserThread::PostTask(
- BrowserThread::IO, FROM_HERE,
- base::BindOnce(&EnsureNoPendingDownloadJobsOnIO, &result));
- base::RunLoop().Run();
- return result &&
- (CountingDownloadFile::GetNumberActiveFilesFromFileThread() == 0);
+ return CountingDownloadFile::GetNumberActiveFilesFromFileThread() == 0;
}
// Checks that |path| is has |file_size| bytes, and matches the |value|
@@ -2652,14 +2671,6 @@ class DevToolsDownloadContentTest : public DevToolsProtocolTest {
}
private:
- static void EnsureNoPendingDownloadJobsOnIO(bool* result) {
- if (net::URLRequestSlowDownloadJob::NumberOutstandingRequests())
- *result = false;
- BrowserThread::PostTask(
- BrowserThread::UI, FROM_HERE,
- base::MessageLoop::current()->QuitWhenIdleClosure());
- }
-
// Location of the downloads directory for these tests
base::ScopedTempDir downloads_directory_;
std::unique_ptr<TestShellDownloadManagerDelegate> test_delegate_;
@@ -2678,8 +2689,7 @@ IN_PROC_BROWSER_TEST_F(DevToolsDownloadContentTest, SingleDownload) {
// Create a download, wait until it's started, and confirm
// we're in the expected state.
download::DownloadItem* download = StartDownloadAndReturnItem(
- shell(),
- GURL(net::URLRequestMockHTTPJob::GetMockUrl("download-test.lib")));
+ shell(), embedded_test_server()->GetURL("/download/download-test.lib"));
ASSERT_EQ(download::DownloadItem::IN_PROGRESS, download->GetState());
WaitForCompletion(download);
@@ -2697,7 +2707,8 @@ IN_PROC_BROWSER_TEST_F(DevToolsDownloadContentTest, DownloadCancelled) {
// Create a download, wait until it's started, and confirm
// we're in the expected state.
download::DownloadItem* download = StartDownloadAndReturnItem(
- shell(), GURL(net::URLRequestSlowDownloadJob::kUnknownSizeUrl));
+ shell(), embedded_test_server()->GetURL(
+ content::SlowDownloadHttpResponse::kUnknownSizeUrl));
ASSERT_EQ(download::DownloadItem::IN_PROGRESS, download->GetState());
// Cancel the download and wait for download system quiesce.
@@ -2719,9 +2730,10 @@ IN_PROC_BROWSER_TEST_F(DevToolsDownloadContentTest, DeniedDownload) {
SetDownloadBehavior("deny");
// Create a download, wait and confirm it was cancelled.
download::DownloadItem* download = StartDownloadAndReturnItem(
- shell(),
- GURL(net::URLRequestMockHTTPJob::GetMockUrl("download-test.lib")));
- EnsureNoPendingDownloads();
+ shell(), embedded_test_server()->GetURL("/download/download-test.lib"));
+ DownloadTestFlushObserver flush_observer(DownloadManagerForShell(shell()));
+ flush_observer.WaitForFlush();
+ EXPECT_TRUE(EnsureNoPendingDownloads());
ASSERT_EQ(download::DownloadItem::CANCELLED, download->GetState());
}
@@ -2736,7 +2748,8 @@ IN_PROC_BROWSER_TEST_F(DevToolsDownloadContentTest, DefaultDownload) {
// Create a download, wait until it's started, and confirm
// we're in the expected state.
download::DownloadItem* download = StartDownloadAndReturnItem(
- shell(), GURL(net::URLRequestSlowDownloadJob::kUnknownSizeUrl));
+ shell(), embedded_test_server()->GetURL(
+ content::SlowDownloadHttpResponse::kUnknownSizeUrl));
ASSERT_EQ(download::DownloadItem::IN_PROGRESS, download->GetState());
// Cancel the download and wait for download system quiesce.
@@ -2760,10 +2773,17 @@ IN_PROC_BROWSER_TEST_F(DevToolsDownloadContentTest, DefaultDownloadHeadless) {
SetDownloadBehavior("default");
// Create a download, wait and confirm it was cancelled.
download::DownloadItem* download = StartDownloadAndReturnItem(
- shell(),
- GURL(net::URLRequestMockHTTPJob::GetMockUrl("download-test.lib")));
- EnsureNoPendingDownloads();
- ASSERT_EQ(download::DownloadItem::CANCELLED, download->GetState());
+ shell(), embedded_test_server()->GetURL("/download/download-test.lib"));
+ DownloadTestFlushObserver flush_observer(DownloadManagerForShell(shell()));
+ flush_observer.WaitForFlush();
+ EXPECT_TRUE(EnsureNoPendingDownloads());
+ if (base::FeatureList::IsEnabled(network::features::kNetworkService)) {
+ // The download manager will intercept the download navigation and drop it
+ // since we have set the delegate to null.
+ EXPECT_EQ(nullptr, download);
+ } else {
+ EXPECT_EQ(download::DownloadItem::CANCELLED, download->GetState());
+ }
}
// Check that download logic is reset when creating a new target.
@@ -2780,7 +2800,7 @@ IN_PROC_BROWSER_TEST_F(DevToolsDownloadContentTest, ResetDownloadState) {
// Create a download, wait and confirm it wasn't cancelled.
download::DownloadItem* download = StartDownloadAndReturnItem(
new_window,
- GURL(net::URLRequestMockHTTPJob::GetMockUrl("download-test.lib")));
+ embedded_test_server()->GetURL("/download/download-test.lib"));
WaitForCompletion(download);
ASSERT_EQ(download::DownloadItem::COMPLETE, download->GetState());
}
@@ -2797,13 +2817,14 @@ IN_PROC_BROWSER_TEST_F(DevToolsDownloadContentTest, MultiDownload) {
// Create a download, wait until it's started, and confirm
// we're in the expected state.
download::DownloadItem* download1 = StartDownloadAndReturnItem(
- shell(), GURL(net::URLRequestSlowDownloadJob::kUnknownSizeUrl));
+ shell(), embedded_test_server()->GetURL(
+ content::SlowDownloadHttpResponse::kUnknownSizeUrl));
ASSERT_EQ(download::DownloadItem::IN_PROGRESS, download1->GetState());
NavigateToURLBlockUntilNavigationsComplete(shell(), GURL("about:blank"), 1);
SetDownloadBehavior("allow", "download2");
// Start the second download and wait until it's done.
- GURL url(net::URLRequestMockHTTPJob::GetMockUrl("download-test.lib"));
+ GURL url(embedded_test_server()->GetURL("/download/download-test.lib"));
download::DownloadItem* download2 = StartDownloadAndReturnItem(shell(), url);
WaitForCompletion(download2);
@@ -2813,7 +2834,8 @@ IN_PROC_BROWSER_TEST_F(DevToolsDownloadContentTest, MultiDownload) {
// Allow the first request to finish.
std::unique_ptr<DownloadTestObserver> observer2(CreateWaiter(shell(), 1));
NavigateToURL(shell(),
- GURL(net::URLRequestSlowDownloadJob::kFinishDownloadUrl));
+ embedded_test_server()->GetURL(
+ content::SlowDownloadHttpResponse::kFinishDownloadUrl));
observer2->WaitForFinished(); // Wait for the third request.
EXPECT_EQ(
1u, observer2->NumDownloadsSeenInState(download::DownloadItem::COMPLETE));
@@ -2827,8 +2849,8 @@ IN_PROC_BROWSER_TEST_F(DevToolsDownloadContentTest, MultiDownload) {
// source file.
base::FilePath file1(download1->GetTargetFilePath());
ASSERT_EQ(file1.DirName().MaybeAsASCII(), "download1");
- size_t file_size1 = net::URLRequestSlowDownloadJob::kFirstDownloadSize +
- net::URLRequestSlowDownloadJob::kSecondDownloadSize;
+ size_t file_size1 = content::SlowDownloadHttpResponse::kFirstDownloadSize +
+ content::SlowDownloadHttpResponse::kSecondDownloadSize;
std::string expected_contents(file_size1, '*');
ASSERT_TRUE(VerifyFile(file1, expected_contents, file_size1));
diff --git a/chromium/content/browser/devtools/protocol/emulation_handler.cc b/chromium/content/browser/devtools/protocol/emulation_handler.cc
index 25ffa90042d..f61f93491cc 100644
--- a/chromium/content/browser/devtools/protocol/emulation_handler.cc
+++ b/chromium/content/browser/devtools/protocol/emulation_handler.cc
@@ -265,8 +265,12 @@ Response EmulationHandler::SetDeviceMetricsOverride(
device_emulation_enabled_ = true;
device_emulation_params_ = params;
UpdateDeviceEmulationState();
+
// Renderer should answer after emulation params were updated, so that the
// response is only sent to the client once updates were applied.
+ // Unless the renderer has crashed.
+ if (GetWebContents() && GetWebContents()->IsCrashed())
+ return Response::OK();
return Response::FallThrough();
}
@@ -282,6 +286,9 @@ Response EmulationHandler::ClearDeviceMetricsOverride() {
UpdateDeviceEmulationState();
// Renderer should answer after emulation was disabled, so that the response
// is only sent to the client once updates were applied.
+ // Unless the renderer has crashed.
+ if (GetWebContents() && GetWebContents()->IsCrashed())
+ return Response::OK();
return Response::FallThrough();
}
@@ -316,16 +323,16 @@ WebContentsImpl* EmulationHandler::GetWebContents() {
}
void EmulationHandler::UpdateTouchEventEmulationState() {
- RenderWidgetHostImpl* widget_host =
- host_ ? host_->GetRenderWidgetHost() : nullptr;
- if (!widget_host)
+ if (!host_ || !host_->GetRenderWidgetHost())
+ return;
+ if (host_->GetParent() && !host_->IsCrossProcessSubframe())
return;
if (touch_emulation_enabled_) {
- widget_host->GetTouchEmulator()->Enable(
+ host_->GetRenderWidgetHost()->GetTouchEmulator()->Enable(
TouchEmulator::Mode::kEmulatingTouchFromMouse,
TouchEmulationConfigurationToType(touch_emulation_configuration_));
} else {
- widget_host->GetTouchEmulator()->Disable();
+ host_->GetRenderWidgetHost()->GetTouchEmulator()->Disable();
}
if (GetWebContents()) {
GetWebContents()->SetForceDisableOverscrollContent(
@@ -334,9 +341,9 @@ void EmulationHandler::UpdateTouchEventEmulationState() {
}
void EmulationHandler::UpdateDeviceEmulationState() {
- RenderWidgetHostImpl* widget_host =
- host_ ? host_->GetRenderWidgetHost() : nullptr;
- if (!widget_host)
+ if (!host_ || !host_->GetRenderWidgetHost())
+ return;
+ if (host_->GetParent() && !host_->IsCrossProcessSubframe())
return;
// TODO(eseckler): Once we change this to mojo, we should wait for an ack to
// these messages from the renderer. The renderer should send the ack once the
@@ -346,11 +353,12 @@ void EmulationHandler::UpdateDeviceEmulationState() {
// ViewMsg and acknowledgment, as well as plump the acknowledgment back to the
// EmulationHandler somehow. Mojo callbacks should make this much simpler.
if (device_emulation_enabled_) {
- widget_host->Send(new ViewMsg_EnableDeviceEmulation(
- widget_host->GetRoutingID(), device_emulation_params_));
+ host_->GetRenderWidgetHost()->Send(new ViewMsg_EnableDeviceEmulation(
+ host_->GetRenderWidgetHost()->GetRoutingID(),
+ device_emulation_params_));
} else {
- widget_host->Send(new ViewMsg_DisableDeviceEmulation(
- widget_host->GetRoutingID()));
+ host_->GetRenderWidgetHost()->Send(new ViewMsg_DisableDeviceEmulation(
+ host_->GetRenderWidgetHost()->GetRoutingID()));
}
}
diff --git a/chromium/content/browser/devtools/protocol/emulation_handler.h b/chromium/content/browser/devtools/protocol/emulation_handler.h
index f322802b648..1503b2e70da 100644
--- a/chromium/content/browser/devtools/protocol/emulation_handler.h
+++ b/chromium/content/browser/devtools/protocol/emulation_handler.h
@@ -8,7 +8,7 @@
#include "base/macros.h"
#include "content/browser/devtools/protocol/devtools_domain_handler.h"
#include "content/browser/devtools/protocol/emulation.h"
-#include "third_party/WebKit/public/web/WebDeviceEmulationParams.h"
+#include "third_party/blink/public/web/web_device_emulation_params.h"
namespace content {
diff --git a/chromium/content/browser/devtools/protocol/input_handler.cc b/chromium/content/browser/devtools/protocol/input_handler.cc
index 689dc38a92d..3556f33c0fb 100644
--- a/chromium/content/browser/devtools/protocol/input_handler.cc
+++ b/chromium/content/browser/devtools/protocol/input_handler.cc
@@ -10,7 +10,6 @@
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/trace_event/trace_event.h"
-#include "components/viz/common/quads/compositor_frame_metadata.h"
#include "content/browser/devtools/devtools_session.h"
#include "content/browser/devtools/protocol/native_input_event_builder.h"
#include "content/browser/frame_host/render_frame_host_impl.h"
@@ -441,9 +440,8 @@ void InputHandler::Wire(UberDispatcher* dispatcher) {
Input::Dispatcher::wire(dispatcher, this);
}
-void InputHandler::OnSwapCompositorFrame(
- const viz::CompositorFrameMetadata& frame_metadata) {
- page_scale_factor_ = frame_metadata.page_scale_factor;
+void InputHandler::OnPageScaleFactorChanged(float page_scale_factor) {
+ page_scale_factor_ = page_scale_factor;
}
Response InputHandler::Disable() {
diff --git a/chromium/content/browser/devtools/protocol/input_handler.h b/chromium/content/browser/devtools/protocol/input_handler.h
index 9dce4844708..ae8fd55904c 100644
--- a/chromium/content/browser/devtools/protocol/input_handler.h
+++ b/chromium/content/browser/devtools/protocol/input_handler.h
@@ -16,11 +16,7 @@
#include "content/browser/renderer_host/input/synthetic_gesture.h"
#include "content/common/input/synthetic_smooth_scroll_gesture_params.h"
#include "content/public/browser/render_widget_host.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
-
-namespace viz {
-class CompositorFrameMetadata;
-}
+#include "third_party/blink/public/platform/web_input_event.h"
namespace content {
class DevToolsAgentHostImpl;
@@ -40,8 +36,7 @@ class InputHandler : public DevToolsDomainHandler, public Input::Backend {
void SetRenderer(int process_host_id,
RenderFrameHostImpl* frame_host) override;
- void OnSwapCompositorFrame(
- const viz::CompositorFrameMetadata& frame_metadata);
+ void OnPageScaleFactorChanged(float page_scale_factor);
Response Disable() override;
void DispatchKeyEvent(
diff --git a/chromium/content/browser/devtools/protocol/native_input_event_builder_mac.mm b/chromium/content/browser/devtools/protocol/native_input_event_builder_mac.mm
index 601ec197b5b..3faae032e20 100644
--- a/chromium/content/browser/devtools/protocol/native_input_event_builder_mac.mm
+++ b/chromium/content/browser/devtools/protocol/native_input_event_builder_mac.mm
@@ -5,7 +5,7 @@
#include <Cocoa/Cocoa.h>
#include "base/strings/sys_string_conversions.h"
#include "content/browser/devtools/protocol/native_input_event_builder.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
namespace content {
namespace protocol {
diff --git a/chromium/content/browser/devtools/protocol/network_handler.cc b/chromium/content/browser/devtools/protocol/network_handler.cc
index 06c84ec3703..6d62f72deae 100644
--- a/chromium/content/browser/devtools/protocol/network_handler.cc
+++ b/chromium/content/browser/devtools/protocol/network_handler.cc
@@ -19,6 +19,7 @@
#include "base/time/time.h"
#include "content/browser/devtools/devtools_interceptor_controller.h"
#include "content/browser/devtools/devtools_session.h"
+#include "content/browser/devtools/devtools_url_loader_interceptor.h"
#include "content/browser/devtools/protocol/page.h"
#include "content/browser/devtools/protocol/security.h"
#include "content/browser/frame_host/frame_tree_node.h"
@@ -38,10 +39,12 @@
#include "content/public/browser/site_instance.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
+#include "content/public/common/browser_side_navigation_policy.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_switches.h"
#include "net/base/net_errors.h"
#include "net/base/upload_bytes_element_reader.h"
+#include "net/cert/ct_policy_status.h"
#include "net/cert/ct_sct_to_string.h"
#include "net/cookies/canonical_cookie.h"
#include "net/cookies/cookie_store.h"
@@ -53,6 +56,7 @@
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "services/network/public/cpp/data_element.h"
+#include "services/network/public/cpp/features.h"
#include "services/network/public/cpp/http_raw_request_response_info.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/resource_response.h"
@@ -76,125 +80,203 @@ using ClearBrowserCookiesCallback =
const char kDevToolsEmulateNetworkConditionsClientId[] =
"X-DevTools-Emulate-Network-Conditions-Client-Id";
+Network::CertificateTransparencyCompliance SerializeCTPolicyCompliance(
+ net::ct::CTPolicyCompliance ct_compliance) {
+ switch (ct_compliance) {
+ case net::ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS:
+ return Network::CertificateTransparencyComplianceEnum::Compliant;
+ case net::ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS:
+ case net::ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS:
+ return Network::CertificateTransparencyComplianceEnum::NotCompliant;
+ case net::ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY:
+ case net::ct::CTPolicyCompliance::
+ CT_POLICY_COMPLIANCE_DETAILS_NOT_AVAILABLE:
+ return Network::CertificateTransparencyComplianceEnum::Unknown;
+ case net::ct::CTPolicyCompliance::CT_POLICY_MAX:
+ NOTREACHED();
+ return Network::CertificateTransparencyComplianceEnum::Unknown;
+ }
+ NOTREACHED();
+ return Network::CertificateTransparencyComplianceEnum::Unknown;
+}
+
+std::unique_ptr<Network::Cookie> BuildCookie(
+ const net::CanonicalCookie& cookie) {
+ std::unique_ptr<Network::Cookie> devtools_cookie =
+ Network::Cookie::Create()
+ .SetName(cookie.Name())
+ .SetValue(cookie.Value())
+ .SetDomain(cookie.Domain())
+ .SetPath(cookie.Path())
+ .SetExpires(cookie.ExpiryDate().is_null()
+ ? -1
+ : cookie.ExpiryDate().ToDoubleT())
+ .SetSize(cookie.Name().length() + cookie.Value().length())
+ .SetHttpOnly(cookie.IsHttpOnly())
+ .SetSecure(cookie.IsSecure())
+ .SetSession(!cookie.IsPersistent())
+ .Build();
+
+ switch (cookie.SameSite()) {
+ case net::CookieSameSite::STRICT_MODE:
+ devtools_cookie->SetSameSite(Network::CookieSameSiteEnum::Strict);
+ break;
+ case net::CookieSameSite::LAX_MODE:
+ devtools_cookie->SetSameSite(Network::CookieSameSiteEnum::Lax);
+ break;
+ case net::CookieSameSite::NO_RESTRICTION:
+ break;
+ }
+ return devtools_cookie;
+}
+
+std::unique_ptr<ProtocolCookieArray> BuildCookieArray(
+ const std::vector<net::CanonicalCookie>& cookie_list) {
+ auto cookies = std::make_unique<ProtocolCookieArray>();
+
+ for (const net::CanonicalCookie& cookie : cookie_list)
+ cookies->addItem(BuildCookie(cookie));
+
+ return cookies;
+}
+
class CookieRetriever : public base::RefCountedThreadSafe<CookieRetriever> {
- public:
- CookieRetriever(std::unique_ptr<GetCookiesCallback> callback)
- : callback_(std::move(callback)),
- all_callback_(nullptr) {}
-
- CookieRetriever(std::unique_ptr<GetAllCookiesCallback> callback)
- : callback_(nullptr),
- all_callback_(std::move(callback)) {}
-
- void RetrieveCookiesOnIO(
- net::URLRequestContextGetter* context_getter,
- const std::vector<GURL>& urls) {
- DCHECK_CURRENTLY_ON(BrowserThread::IO);
- callback_count_ = urls.size();
-
- if (callback_count_ == 0) {
- GotAllCookies();
- return;
- }
+ public:
+ CookieRetriever(std::unique_ptr<GetCookiesCallback> callback)
+ : callback_(std::move(callback)), all_callback_(nullptr) {
+ DCHECK(!base::FeatureList::IsEnabled(network::features::kNetworkService));
+ }
- for (const GURL& url : urls) {
- net::URLRequestContext* request_context =
- context_getter->GetURLRequestContext();
- request_context->cookie_store()->GetAllCookiesForURLAsync(
- url, base::BindOnce(&CookieRetriever::GotCookies, this));
- }
- }
+ CookieRetriever(std::unique_ptr<GetAllCookiesCallback> callback)
+ : callback_(nullptr), all_callback_(std::move(callback)) {}
- void RetrieveAllCookiesOnIO(
- net::URLRequestContextGetter* context_getter) {
- DCHECK_CURRENTLY_ON(BrowserThread::IO);
- callback_count_ = 1;
+ void RetrieveCookiesOnIO(net::URLRequestContextGetter* context_getter,
+ const std::vector<GURL>& urls) {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+ callback_count_ = urls.size();
+ if (callback_count_ == 0) {
+ GotAllCookies();
+ return;
+ }
+
+ for (const GURL& url : urls) {
net::URLRequestContext* request_context =
context_getter->GetURLRequestContext();
- request_context->cookie_store()->GetAllCookiesAsync(
- base::BindOnce(&CookieRetriever::GotCookies, this));
+ request_context->cookie_store()->GetAllCookiesForURLAsync(
+ url, base::BindOnce(&CookieRetriever::GotCookies, this));
+ }
+ }
+
+ void RetrieveAllCookiesOnIO(net::URLRequestContextGetter* context_getter) {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+ callback_count_ = 1;
+
+ net::URLRequestContext* request_context =
+ context_getter->GetURLRequestContext();
+ request_context->cookie_store()->GetAllCookiesAsync(
+ base::BindOnce(&CookieRetriever::GotCookies, this));
+ }
+
+ protected:
+ virtual ~CookieRetriever() {}
+
+ void GotCookies(const net::CookieList& cookie_list) {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+ for (const net::CanonicalCookie& cookie : cookie_list) {
+ std::string key = base::StringPrintf(
+ "%s::%s::%s::%d", cookie.Name().c_str(), cookie.Domain().c_str(),
+ cookie.Path().c_str(), cookie.IsSecure());
+ cookies_[key] = cookie;
}
- protected:
- virtual ~CookieRetriever() {}
-
- void GotCookies(const net::CookieList& cookie_list) {
- DCHECK_CURRENTLY_ON(BrowserThread::IO);
- for (const net::CanonicalCookie& cookie : cookie_list) {
- std::string key = base::StringPrintf(
- "%s::%s::%s::%d", cookie.Name().c_str(), cookie.Domain().c_str(),
- cookie.Path().c_str(), cookie.IsSecure());
- cookies_[key] = cookie;
- }
- --callback_count_;
- if (callback_count_ == 0)
- GotAllCookies();
+ --callback_count_;
+ if (callback_count_ == 0)
+ GotAllCookies();
+ }
+
+ void GotAllCookies() {
+ net::CookieList master_cookie_list;
+ for (const auto& pair : cookies_)
+ master_cookie_list.push_back(pair.second);
+
+ BrowserThread::PostTask(
+ BrowserThread::UI, FROM_HERE,
+ base::BindOnce(&CookieRetriever::SendCookiesResponseOnUI, this,
+ master_cookie_list));
+ }
+
+ void SendCookiesResponseOnUI(const net::CookieList& cookie_list) {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ std::unique_ptr<ProtocolCookieArray> cookies =
+ BuildCookieArray(cookie_list);
+
+ if (callback_) {
+ callback_->sendSuccess(std::move(cookies));
+ } else {
+ DCHECK(all_callback_);
+ all_callback_->sendSuccess(std::move(cookies));
}
+ }
+
+ std::unique_ptr<GetCookiesCallback> callback_;
+ std::unique_ptr<GetAllCookiesCallback> all_callback_;
+ int callback_count_ = 0;
+ std::unordered_map<std::string, net::CanonicalCookie> cookies_;
- void GotAllCookies() {
- net::CookieList master_cookie_list;
- for (const auto& pair : cookies_)
- master_cookie_list.push_back(pair.second);
+ private:
+ friend class base::RefCountedThreadSafe<CookieRetriever>;
+};
- BrowserThread::PostTask(
- BrowserThread::UI, FROM_HERE,
- base::BindOnce(&CookieRetriever::SendCookiesResponseOnUI, this,
- master_cookie_list));
+class CookieRetrieverNetworkService
+ : public base::RefCounted<CookieRetrieverNetworkService> {
+ public:
+ static void Retrieve(network::mojom::CookieManager* cookie_manager,
+ const std::vector<GURL> urls,
+ std::unique_ptr<GetCookiesCallback> callback) {
+ scoped_refptr<CookieRetrieverNetworkService> self =
+ new CookieRetrieverNetworkService(std::move(callback));
+ net::CookieOptions cookie_options;
+ cookie_options.set_include_httponly();
+ cookie_options.set_same_site_cookie_mode(
+ net::CookieOptions::SameSiteCookieMode::INCLUDE_STRICT_AND_LAX);
+ cookie_options.set_do_not_update_access_time();
+ for (const auto& url : urls) {
+ cookie_manager->GetCookieList(
+ url, cookie_options,
+ base::BindOnce(&CookieRetrieverNetworkService::GotCookies, self));
}
+ }
- void SendCookiesResponseOnUI(const net::CookieList& cookie_list) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- std::unique_ptr<ProtocolCookieArray> cookies =
- ProtocolCookieArray::create();
-
- for (const net::CanonicalCookie& cookie : cookie_list) {
- std::unique_ptr<Network::Cookie> devtools_cookie =
- Network::Cookie::Create()
- .SetName(cookie.Name())
- .SetValue(cookie.Value())
- .SetDomain(cookie.Domain())
- .SetPath(cookie.Path())
- .SetExpires(cookie.ExpiryDate().is_null() ? -1 : cookie.ExpiryDate().ToDoubleT())
- .SetSize(cookie.Name().length() + cookie.Value().length())
- .SetHttpOnly(cookie.IsHttpOnly())
- .SetSecure(cookie.IsSecure())
- .SetSession(!cookie.IsPersistent())
- .Build();
+ private:
+ friend class base::RefCounted<CookieRetrieverNetworkService>;
- switch (cookie.SameSite()) {
- case net::CookieSameSite::STRICT_MODE:
- devtools_cookie->SetSameSite(Network::CookieSameSiteEnum::Strict);
- break;
- case net::CookieSameSite::LAX_MODE:
- devtools_cookie->SetSameSite(Network::CookieSameSiteEnum::Lax);
- break;
- case net::CookieSameSite::NO_RESTRICTION:
- break;
- }
-
- cookies->addItem(std::move(devtools_cookie));
- }
+ CookieRetrieverNetworkService(std::unique_ptr<GetCookiesCallback> callback)
+ : callback_(std::move(callback)) {}
- if (callback_) {
- callback_->sendSuccess(std::move(cookies));
- } else {
- DCHECK(all_callback_);
- all_callback_->sendSuccess(std::move(cookies));
- }
+ void GotCookies(const std::vector<net::CanonicalCookie>& cookies) {
+ for (const auto& cookie : cookies) {
+ std::string key = base::StringPrintf(
+ "%s::%s::%s::%d", cookie.Name().c_str(), cookie.Domain().c_str(),
+ cookie.Path().c_str(), cookie.IsSecure());
+ all_cookies_.emplace(std::move(key), cookie);
}
+ }
- std::unique_ptr<GetCookiesCallback> callback_;
- std::unique_ptr<GetAllCookiesCallback> all_callback_;
- int callback_count_ = 0;
- std::unordered_map<std::string, net::CanonicalCookie> cookies_;
+ ~CookieRetrieverNetworkService() {
+ auto cookies = std::make_unique<ProtocolCookieArray>();
+ for (const auto& entry : all_cookies_)
+ cookies->addItem(BuildCookie(entry.second));
+ callback_->sendSuccess(std::move(cookies));
+ }
- private:
- friend class base::RefCountedThreadSafe<CookieRetriever>;
+ std::unique_ptr<GetCookiesCallback> callback_;
+ std::unordered_map<std::string, net::CanonicalCookie> all_cookies_;
};
void ClearedCookiesOnIO(std::unique_ptr<ClearBrowserCookiesCallback> callback,
uint32_t num_deleted) {
+ DCHECK(!base::FeatureList::IsEnabled(network::features::kNetworkService));
DCHECK_CURRENTLY_ON(BrowserThread::IO);
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
@@ -204,6 +286,7 @@ void ClearedCookiesOnIO(std::unique_ptr<ClearBrowserCookiesCallback> callback,
void ClearCookiesOnIO(net::URLRequestContextGetter* context_getter,
std::unique_ptr<ClearBrowserCookiesCallback> callback) {
+ DCHECK(!base::FeatureList::IsEnabled(network::features::kNetworkService));
DCHECK_CURRENTLY_ON(BrowserThread::IO);
net::URLRequestContext* request_context =
context_getter->GetURLRequestContext();
@@ -216,36 +299,38 @@ void DeletedCookiesOnIO(base::OnceClosure callback, uint32_t num_deleted) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, std::move(callback));
}
-void DeleteSelectedCookiesOnIO(net::URLRequestContextGetter* context_getter,
- const std::string& name,
- const std::string& url_spec,
- const std::string& domain,
- const std::string& path,
- base::OnceClosure callback,
- const net::CookieList& cookie_list) {
- net::URLRequestContext* request_context =
- context_getter->GetURLRequestContext();
- std::string normalized_domain = domain;
- if (normalized_domain.empty()) {
- GURL url(url_spec);
- if (!url.SchemeIsHTTPOrHTTPS()) {
- std::move(callback).Run();
- return;
- }
- normalized_domain = url.host();
- }
+std::vector<net::CanonicalCookie> FilterCookies(
+ const std::vector<net::CanonicalCookie>& cookies,
+ const std::string& name,
+ const std::string& normalized_domain,
+ const std::string& path) {
+ std::vector<net::CanonicalCookie> result;
- net::CookieList filtered_list;
- for (const auto& cookie : cookie_list) {
+ for (const auto& cookie : cookies) {
if (cookie.Name() != name)
continue;
if (cookie.Domain() != normalized_domain)
continue;
if (!path.empty() && cookie.Path() != path)
continue;
- filtered_list.push_back(cookie);
+ result.push_back(cookie);
}
+ return result;
+}
+
+void DeleteSelectedCookiesOnIO(net::URLRequestContextGetter* context_getter,
+ const std::string& name,
+ const std::string& normalized_domain,
+ const std::string& path,
+ base::OnceClosure callback,
+ const net::CookieList& cookie_list) {
+ DCHECK(!base::FeatureList::IsEnabled(network::features::kNetworkService));
+
+ net::URLRequestContext* request_context =
+ context_getter->GetURLRequestContext();
+ net::CookieList filtered_list =
+ FilterCookies(cookie_list, name, normalized_domain, path);
for (size_t i = 0; i < filtered_list.size(); ++i) {
const auto& cookie = filtered_list[i];
base::OnceCallback<void(uint32_t)> once_callback;
@@ -255,22 +340,22 @@ void DeleteSelectedCookiesOnIO(net::URLRequestContextGetter* context_getter,
cookie, std::move(once_callback));
}
if (!filtered_list.size())
- std::move(callback).Run();
+ DeletedCookiesOnIO(std::move(callback), 0);
}
void DeleteCookiesOnIO(net::URLRequestContextGetter* context_getter,
const std::string& name,
- const std::string& url,
- const std::string& domain,
+ const std::string& normalized_domain,
const std::string& path,
base::OnceClosure callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
+ DCHECK(!base::FeatureList::IsEnabled(network::features::kNetworkService));
net::URLRequestContext* request_context =
context_getter->GetURLRequestContext();
request_context->cookie_store()->GetAllCookiesAsync(base::BindOnce(
- &DeleteSelectedCookiesOnIO, base::Unretained(context_getter), name, url,
- domain, path, std::move(callback)));
+ &DeleteSelectedCookiesOnIO, base::Unretained(context_getter), name,
+ normalized_domain, path, std::move(callback)));
}
void CookieSetOnIO(std::unique_ptr<SetCookieCallback> callback, bool success) {
@@ -280,33 +365,55 @@ void CookieSetOnIO(std::unique_ptr<SetCookieCallback> callback, bool success) {
std::move(callback), success));
}
-void SetCookieOnIO(net::URLRequestContextGetter* context_getter,
- const std::string& name,
- const std::string& value,
- const std::string& url_spec,
- const std::string& domain,
- const std::string& path,
- bool secure,
- bool http_only,
- const std::string& same_site,
- double expires,
- base::OnceCallback<void(bool)> callback) {
- DCHECK_CURRENTLY_ON(BrowserThread::IO);
- net::URLRequestContext* request_context =
- context_getter->GetURLRequestContext();
+void DeleteFilteredCookies(network::mojom::CookieManager* cookie_manager,
+ const std::string& name,
+ const std::string& normalized_domain,
+ const std::string& path,
+ std::unique_ptr<DeleteCookiesCallback> callback,
+ const std::vector<net::CanonicalCookie>& cookies) {
+ base::Time yesterday(base::Time::Now() - base::TimeDelta::FromDays(1));
- if (url_spec.empty() && domain.empty()) {
- std::move(callback).Run(false);
- return;
+ std::vector<net::CanonicalCookie> filtered_list =
+ FilterCookies(cookies, name, normalized_domain, path);
+
+ base::RepeatingClosure barrier_closure = base::BarrierClosure(
+ filtered_list.size(),
+ base::BindOnce(&DeleteCookiesCallback::sendSuccess, std::move(callback)));
+
+ for (auto& cookie : filtered_list) {
+ // Delete a single cookie by setting its expiration time into the past.
+ cookie_manager->SetCanonicalCookie(
+ net::CanonicalCookie(cookie.Name(), cookie.Value(), cookie.Domain(),
+ cookie.Path(), cookie.CreationDate(), yesterday,
+ cookie.LastAccessDate(), cookie.IsSecure(),
+ cookie.IsHttpOnly(), cookie.SameSite(),
+ cookie.Priority()),
+ true /* secure_source */, true /* modify_http_only */,
+ base::BindOnce(
+ [](base::RepeatingClosure callback, bool) { callback.Run(); },
+ barrier_closure));
}
+}
+std::unique_ptr<net::CanonicalCookie> MakeCookieFromProtocolValues(
+ const std::string& name,
+ const std::string& value,
+ const std::string& url_spec,
+ const std::string& domain,
+ const std::string& path,
+ bool secure,
+ bool http_only,
+ const std::string& same_site,
+ double expires) {
std::string normalized_domain = domain;
+
+ if (url_spec.empty() && domain.empty())
+ return nullptr;
+
if (!url_spec.empty()) {
GURL source_url = GURL(url_spec);
- if (!source_url.SchemeIsHTTPOrHTTPS()) {
- std::move(callback).Run(false);
- return;
- }
+ if (!source_url.SchemeIsHTTPOrHTTPS())
+ return nullptr;
secure = secure || source_url.SchemeIsCryptographic();
if (normalized_domain.empty())
@@ -329,45 +436,44 @@ void SetCookieOnIO(net::URLRequestContextGetter* context_getter,
if (same_site == Network::CookieSameSiteEnum::Strict)
css = net::CookieSameSite::STRICT_MODE;
- std::unique_ptr<net::CanonicalCookie> cc(
- net::CanonicalCookie::CreateSanitizedCookie(
- url, name, value, normalized_domain, path, base::Time(),
- expiration_date, base::Time(), secure, http_only, css,
- net::COOKIE_PRIORITY_DEFAULT));
- if (!cc) {
- std::move(callback).Run(false);
- return;
- }
+ return net::CanonicalCookie::CreateSanitizedCookie(
+ url, name, value, normalized_domain, path, base::Time(), expiration_date,
+ base::Time(), secure, http_only, css, net::COOKIE_PRIORITY_DEFAULT);
+}
+
+void SetCookieOnIO(net::URLRequestContextGetter* context_getter,
+ std::unique_ptr<net::CanonicalCookie> cookie,
+ base::OnceCallback<void(bool)> callback) {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+ DCHECK(!base::FeatureList::IsEnabled(network::features::kNetworkService));
+ net::URLRequestContext* request_context =
+ context_getter->GetURLRequestContext();
+
request_context->cookie_store()->SetCanonicalCookieAsync(
- std::move(cc), secure, true /*modify_http_only*/, std::move(callback));
+ std::move(cookie), true /* secure_source */, true /*modify_http_only*/,
+ std::move(callback));
}
-void CookiesSetOnIO(std::unique_ptr<SetCookiesCallback> callback,
- bool success) {
+void CookiesSetOnIO(std::unique_ptr<SetCookiesCallback> callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::BindOnce(&SetCookiesCallback::sendSuccess, std::move(callback)));
}
-void SetCookiesOnIO(
- net::URLRequestContextGetter* context_getter,
- std::unique_ptr<protocol::Array<Network::CookieParam>> cookies,
- base::OnceCallback<void(bool)> callback) {
+void SetCookiesOnIO(net::URLRequestContextGetter* context_getter,
+ std::vector<std::unique_ptr<net::CanonicalCookie>> cookies,
+ base::OnceClosure callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
+ DCHECK(!base::FeatureList::IsEnabled(network::features::kNetworkService));
- for (size_t i = 0; i < cookies->length(); i++) {
- Network::CookieParam* cookie = cookies->get(i);
-
- base::OnceCallback<void(bool)> once_callback;
- if (i == cookies->length() - 1)
- once_callback = std::move(callback);
-
- SetCookieOnIO(context_getter, cookie->GetName(), cookie->GetValue(),
- cookie->GetUrl(""), cookie->GetDomain(""),
- cookie->GetPath(""), cookie->GetSecure(false),
- cookie->GetHttpOnly(false), cookie->GetSameSite(""),
- cookie->GetExpires(-1), std::move(once_callback));
+ base::RepeatingClosure barrier_closure =
+ base::BarrierClosure(cookies.size(), std::move(callback));
+ for (auto& cookie : cookies) {
+ SetCookieOnIO(context_getter, std::move(cookie),
+ base::BindOnce([](base::RepeatingClosure callback,
+ bool) { callback.Run(); },
+ barrier_closure));
}
}
@@ -809,6 +915,7 @@ Response NetworkHandler::Disable() {
enabled_ = false;
user_agent_ = std::string();
interception_handle_.reset();
+ url_loader_interceptor_.reset();
SetNetworkConditions(nullptr);
extra_headers_.clear();
return Response::FallThrough();
@@ -863,30 +970,47 @@ void NetworkHandler::ClearBrowserCookies(
return;
}
- BrowserThread::PostTask(
- BrowserThread::IO, FROM_HERE,
- base::BindOnce(
- &ClearCookiesOnIO,
- base::Unretained(storage_partition_->GetURLRequestContext()),
- std::move(callback)));
+ if (!base::FeatureList::IsEnabled(network::features::kNetworkService)) {
+ BrowserThread::PostTask(
+ BrowserThread::IO, FROM_HERE,
+ base::BindOnce(
+ &ClearCookiesOnIO,
+ base::Unretained(storage_partition_->GetURLRequestContext()),
+ std::move(callback)));
+ return;
+ }
+
+ storage_partition_->GetCookieManagerForBrowserProcess()->DeleteCookies(
+ network::mojom::CookieDeletionFilter::New(),
+ base::BindOnce([](std::unique_ptr<ClearBrowserCookiesCallback> callback,
+ uint32_t) { callback->sendSuccess(); },
+ std::move(callback)));
}
void NetworkHandler::GetCookies(Maybe<Array<String>> protocol_urls,
std::unique_ptr<GetCookiesCallback> callback) {
- if (!host_) {
+ if (!host_ || !storage_partition_) {
callback->sendFailure(Response::InternalError());
return;
}
-
std::vector<GURL> urls = ComputeCookieURLs(host_, protocol_urls);
- scoped_refptr<CookieRetriever> retriever =
- new CookieRetriever(std::move(callback));
- BrowserThread::PostTask(
- BrowserThread::IO, FROM_HERE,
- base::BindOnce(
- &CookieRetriever::RetrieveCookiesOnIO, retriever,
- base::Unretained(storage_partition_->GetURLRequestContext()), urls));
+ if (!base::FeatureList::IsEnabled(network::features::kNetworkService)) {
+ scoped_refptr<CookieRetriever> retriever =
+ new CookieRetriever(std::move(callback));
+
+ BrowserThread::PostTask(
+ BrowserThread::IO, FROM_HERE,
+ base::BindOnce(
+ &CookieRetriever::RetrieveCookiesOnIO, retriever,
+ base::Unretained(storage_partition_->GetURLRequestContext()),
+ urls));
+ return;
+ }
+
+ CookieRetrieverNetworkService::Retrieve(
+ storage_partition_->GetCookieManagerForBrowserProcess(), urls,
+ std::move(callback));
}
void NetworkHandler::GetAllCookies(
@@ -895,15 +1019,25 @@ void NetworkHandler::GetAllCookies(
callback->sendFailure(Response::InternalError());
return;
}
+ if (!base::FeatureList::IsEnabled(network::features::kNetworkService)) {
+ scoped_refptr<CookieRetriever> retriever =
+ new CookieRetriever(std::move(callback));
- scoped_refptr<CookieRetriever> retriever =
- new CookieRetriever(std::move(callback));
+ BrowserThread::PostTask(
+ BrowserThread::IO, FROM_HERE,
+ base::BindOnce(
+ &CookieRetriever::RetrieveAllCookiesOnIO, retriever,
+ base::Unretained(storage_partition_->GetURLRequestContext())));
+ return;
+ }
- BrowserThread::PostTask(
- BrowserThread::IO, FROM_HERE,
+ storage_partition_->GetCookieManagerForBrowserProcess()->GetAllCookies(
base::BindOnce(
- &CookieRetriever::RetrieveAllCookiesOnIO, retriever,
- base::Unretained(storage_partition_->GetURLRequestContext())));
+ [](std::unique_ptr<GetAllCookiesCallback> callback,
+ const std::vector<net::CanonicalCookie>& cookies) {
+ callback->sendSuccess(BuildCookieArray(cookies));
+ },
+ std::move(callback)));
}
void NetworkHandler::SetCookie(const std::string& name,
@@ -926,15 +1060,32 @@ void NetworkHandler::SetCookie(const std::string& name,
"At least one of the url and domain needs to be specified"));
}
- BrowserThread::PostTask(
- BrowserThread::IO, FROM_HERE,
- base::BindOnce(
- &SetCookieOnIO,
- base::Unretained(storage_partition_->GetURLRequestContext()), name,
- value, url.fromMaybe(""), domain.fromMaybe(""), path.fromMaybe(""),
- secure.fromMaybe(false), http_only.fromMaybe(false),
- same_site.fromMaybe(""), expires.fromMaybe(-1),
- base::BindOnce(&CookieSetOnIO, std::move(callback))));
+ std::unique_ptr<net::CanonicalCookie> cookie = MakeCookieFromProtocolValues(
+ name, value, url.fromMaybe(""), domain.fromMaybe(""), path.fromMaybe(""),
+ secure.fromMaybe(false), http_only.fromMaybe(false),
+ same_site.fromMaybe(""), expires.fromMaybe(-1));
+
+ if (!cookie) {
+ // TODO(caseq): Current logic is for compatability only.
+ // Consider returning protocol error here.
+ callback->sendSuccess(false);
+ return;
+ }
+
+ if (!base::FeatureList::IsEnabled(network::features::kNetworkService)) {
+ BrowserThread::PostTask(
+ BrowserThread::IO, FROM_HERE,
+ base::BindOnce(
+ &SetCookieOnIO,
+ base::Unretained(storage_partition_->GetURLRequestContext()),
+ std::move(cookie),
+ base::BindOnce(&CookieSetOnIO, std::move(callback))));
+ return;
+ }
+
+ storage_partition_->GetCookieManagerForBrowserProcess()->SetCanonicalCookie(
+ *cookie, true /* secure_source */, true /* modify_http_only */,
+ base::BindOnce(&SetCookieCallback::sendSuccess, std::move(callback)));
}
void NetworkHandler::SetCookies(
@@ -945,18 +1096,51 @@ void NetworkHandler::SetCookies(
return;
}
- BrowserThread::PostTask(
- BrowserThread::IO, FROM_HERE,
- base::BindOnce(
- &SetCookiesOnIO,
- base::Unretained(storage_partition_->GetURLRequestContext()),
- std::move(cookies),
- base::BindOnce(&CookiesSetOnIO, std::move(callback))));
+ std::vector<std::unique_ptr<net::CanonicalCookie>> net_cookies;
+ for (size_t i = 0; i < cookies->length(); i++) {
+ Network::CookieParam* cookie = cookies->get(i);
+ std::unique_ptr<net::CanonicalCookie> net_cookie =
+ MakeCookieFromProtocolValues(
+ cookie->GetName(), cookie->GetValue(), cookie->GetUrl(""),
+ cookie->GetDomain(""), cookie->GetPath(""),
+ cookie->GetSecure(false), cookie->GetHttpOnly(false),
+ cookie->GetSameSite(""), cookie->GetExpires(-1));
+ if (!cookie) {
+ callback->sendFailure(Response::InvalidParams("Invalid cookie fields"));
+ return;
+ }
+ net_cookies.push_back(std::move(net_cookie));
+ }
+
+ if (!base::FeatureList::IsEnabled(network::features::kNetworkService)) {
+ BrowserThread::PostTask(
+ BrowserThread::IO, FROM_HERE,
+ base::BindOnce(
+ &SetCookiesOnIO,
+ base::Unretained(storage_partition_->GetURLRequestContext()),
+ std::move(net_cookies),
+ base::BindOnce(&CookiesSetOnIO, std::move(callback))));
+ return;
+ }
+
+ base::RepeatingClosure barrier_closure = base::BarrierClosure(
+ net_cookies.size(),
+ base::BindOnce(&SetCookiesCallback::sendSuccess, std::move(callback)));
+
+ auto* cookie_manager =
+ storage_partition_->GetCookieManagerForBrowserProcess();
+ for (const auto& cookie : net_cookies) {
+ cookie_manager->SetCanonicalCookie(
+ *cookie, true, true,
+ base::BindOnce(
+ [](base::RepeatingClosure callback, bool) { callback.Run(); },
+ barrier_closure));
+ }
}
void NetworkHandler::DeleteCookies(
const std::string& name,
- Maybe<std::string> url,
+ Maybe<std::string> url_spec,
Maybe<std::string> domain,
Maybe<std::string> path,
std::unique_ptr<DeleteCookiesCallback> callback) {
@@ -964,19 +1148,40 @@ void NetworkHandler::DeleteCookies(
callback->sendFailure(Response::InternalError());
return;
}
-
- if (!url.isJust() && !domain.isJust()) {
+ if (!url_spec.isJust() && !domain.isJust()) {
callback->sendFailure(Response::InvalidParams(
"At least one of the url and domain needs to be specified"));
}
- BrowserThread::PostTask(
- BrowserThread::IO, FROM_HERE,
- base::BindOnce(
- &DeleteCookiesOnIO,
- base::Unretained(storage_partition_->GetURLRequestContext()), name,
- url.fromMaybe(""), domain.fromMaybe(""), path.fromMaybe(""),
- base::BindOnce(&DeleteCookiesCallback::sendSuccess,
- std::move(callback))));
+
+ std::string normalized_domain = domain.fromMaybe("");
+ if (normalized_domain.empty()) {
+ GURL url(url_spec.fromMaybe(""));
+ if (!url.SchemeIsHTTPOrHTTPS()) {
+ callback->sendFailure(Response::InvalidParams(
+ "An http or https url URL must be specified"));
+ return;
+ }
+ normalized_domain = url.host();
+ }
+
+ if (!base::FeatureList::IsEnabled(network::features::kNetworkService)) {
+ BrowserThread::PostTask(
+ BrowserThread::IO, FROM_HERE,
+ base::BindOnce(
+ &DeleteCookiesOnIO,
+ base::Unretained(storage_partition_->GetURLRequestContext()), name,
+ normalized_domain, path.fromMaybe(""),
+ base::BindOnce(&DeleteCookiesCallback::sendSuccess,
+ std::move(callback))));
+ return;
+ }
+
+ auto* cookie_manager =
+ storage_partition_->GetCookieManagerForBrowserProcess();
+
+ cookie_manager->GetAllCookies(base::BindOnce(
+ &DeleteFilteredCookies, base::Unretained(cookie_manager), name,
+ normalized_domain, path.fromMaybe(""), std::move(callback)));
}
Response NetworkHandler::SetUserAgentOverride(const std::string& user_agent) {
@@ -1041,20 +1246,14 @@ Response NetworkHandler::SetBypassServiceWorker(bool bypass) {
namespace {
std::unique_ptr<protocol::Network::SecurityDetails> BuildSecurityDetails(
- const network::ResourceResponseInfo& info) {
- if (info.certificate.empty())
+ const net::SSLInfo& ssl_info) {
+ if (!ssl_info.cert)
return nullptr;
- scoped_refptr<net::X509Certificate> cert(
- net::X509Certificate::CreateFromBytes(info.certificate[0].data(),
- info.certificate[0].size()));
- if (!cert)
- return nullptr;
-
std::unique_ptr<
protocol::Array<protocol::Network::SignedCertificateTimestamp>>
signed_certificate_timestamp_list =
protocol::Array<Network::SignedCertificateTimestamp>::create();
- for (auto const& sct : info.signed_certificate_timestamps) {
+ for (auto const& sct : ssl_info.signed_certificate_timestamps) {
std::unique_ptr<protocol::Network::SignedCertificateTimestamp>
signed_certificate_timestamp =
Network::SignedCertificateTimestamp::Create()
@@ -1063,8 +1262,8 @@ std::unique_ptr<protocol::Network::SecurityDetails> BuildSecurityDetails(
.SetLogDescription(sct.sct->log_description)
.SetLogId(base::HexEncode(sct.sct->log_id.c_str(),
sct.sct->log_id.length()))
- .SetTimestamp(
- (sct.sct->timestamp - base::Time()).InMillisecondsF())
+ .SetTimestamp((sct.sct->timestamp - base::Time::UnixEpoch())
+ .InMillisecondsF())
.SetHashAlgorithm(net::ct::HashAlgorithmToString(
sct.sct->signature.hash_algorithm))
.SetSignatureAlgorithm(net::ct::SignatureAlgorithmToString(
@@ -1078,7 +1277,7 @@ std::unique_ptr<protocol::Network::SecurityDetails> BuildSecurityDetails(
}
std::vector<std::string> san_dns;
std::vector<std::string> san_ip;
- cert->GetSubjectAltName(&san_dns, &san_ip);
+ ssl_info.cert->GetSubjectAltName(&san_dns, &san_ip);
std::unique_ptr<Array<String>> san_list = Array<String>::create();
for (const std::string& san : san_dns)
san_list->addItem(san);
@@ -1088,23 +1287,27 @@ std::unique_ptr<protocol::Network::SecurityDetails> BuildSecurityDetails(
.ToString());
}
+ const char* protocol = "";
+ const char* key_exchange = "";
+ const char* cipher = "";
+ const char* mac = nullptr;
+
int ssl_version =
- net::SSLConnectionStatusToVersion(info.ssl_connection_status);
- const char* protocol;
- net::SSLVersionToString(&protocol, ssl_version);
-
- const char* key_exchange;
- const char* cipher;
- const char* mac;
- bool is_aead;
- bool is_tls13;
- uint16_t cipher_suite =
- net::SSLConnectionStatusToCipherSuite(info.ssl_connection_status);
- net::SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, &is_aead,
- &is_tls13, cipher_suite);
- if (key_exchange == nullptr) {
- DCHECK(is_tls13);
- key_exchange = "";
+ net::SSLConnectionStatusToVersion(ssl_info.connection_status);
+
+ if (ssl_info.connection_status) {
+ net::SSLVersionToString(&protocol, ssl_version);
+
+ bool is_aead;
+ bool is_tls13;
+ uint16_t cipher_suite =
+ net::SSLConnectionStatusToCipherSuite(ssl_info.connection_status);
+ net::SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, &is_aead,
+ &is_tls13, cipher_suite);
+ if (key_exchange == nullptr) {
+ DCHECK(is_tls13);
+ key_exchange = "";
+ }
}
std::unique_ptr<protocol::Network::SecurityDetails> security_details =
@@ -1112,19 +1315,21 @@ std::unique_ptr<protocol::Network::SecurityDetails> BuildSecurityDetails(
.SetProtocol(protocol)
.SetKeyExchange(key_exchange)
.SetCipher(cipher)
- .SetSubjectName(cert->subject().common_name)
+ .SetSubjectName(ssl_info.cert->subject().common_name)
.SetSanList(std::move(san_list))
- .SetIssuer(cert->issuer().common_name)
- .SetValidFrom(cert->valid_start().ToDoubleT())
- .SetValidTo(cert->valid_expiry().ToDoubleT())
+ .SetIssuer(ssl_info.cert->issuer().common_name)
+ .SetValidFrom(ssl_info.cert->valid_start().ToDoubleT())
+ .SetValidTo(ssl_info.cert->valid_expiry().ToDoubleT())
.SetCertificateId(0) // Keep this in protocol for compatability.
.SetSignedCertificateTimestampList(
std::move(signed_certificate_timestamp_list))
+ .SetCertificateTransparencyCompliance(
+ SerializeCTPolicyCompliance(ssl_info.ct_policy_compliance))
.Build();
- if (info.ssl_key_exchange_group != 0) {
+ if (ssl_info.key_exchange_group != 0) {
const char* key_exchange_group =
- SSL_get_curve_name(info.ssl_key_exchange_group);
+ SSL_get_curve_name(ssl_info.key_exchange_group);
if (key_exchange_group)
security_details->SetKeyExchangeGroup(key_exchange_group);
}
@@ -1195,7 +1400,8 @@ std::unique_ptr<Network::Response> BuildResponse(
response->SetProtocol(GetProtocol(url, info));
response->SetRemoteIPAddress(info.socket_address.HostForURL());
response->SetRemotePort(info.socket_address.port());
- response->SetSecurityDetails(BuildSecurityDetails(info));
+ if (info.ssl_info.has_value())
+ response->SetSecurityDetails(BuildSecurityDetails(*info.ssl_info));
return response;
}
@@ -1242,12 +1448,13 @@ void NetworkHandler::NavigationRequestWillBeSent(
request->SetMixedContentType(Security::MixedContentTypeEnum::None);
std::unique_ptr<Network::Initiator> initiator;
- base::DictionaryValue* initiator_value =
- nav_request.begin_params()->devtools_initiator.get();
- if (initiator_value) {
+ const base::Optional<base::Value>& initiator_optional =
+ nav_request.begin_params()->devtools_initiator;
+ if (initiator_optional.has_value()) {
ErrorSupport ignored_errors;
initiator = Network::Initiator::fromValue(
- toProtocolValue(initiator_value, 1000).get(), &ignored_errors);
+ toProtocolValue(&initiator_optional.value(), 1000).get(),
+ &ignored_errors);
}
if (!initiator) {
initiator = Network::Initiator::Create()
@@ -1264,7 +1471,8 @@ void NetworkHandler::NavigationRequestWillBeSent(
id, id, StripFragment(common_params.url), std::move(request),
current_ticks, current_wall_time, std::move(initiator),
std::move(redirect_response),
- std::string(Page::ResourceTypeEnum::Document), std::move(frame_token));
+ std::string(Page::ResourceTypeEnum::Document), std::move(frame_token),
+ common_params.has_user_gesture);
}
void NetworkHandler::RequestSent(const std::string& request_id,
@@ -1290,7 +1498,8 @@ void NetworkHandler::RequestSent(const std::string& request_id,
base::Time::Now().ToDoubleT(),
Network::Initiator::Create().SetType(initiator_type).Build(),
std::unique_ptr<Network::Response>(),
- std::string(Page::ResourceTypeEnum::Other));
+ std::string(Page::ResourceTypeEnum::Other),
+ Maybe<std::string>() /* frame_id */, request.has_user_gesture);
}
void NetworkHandler::ResponseReceived(const std::string& request_id,
@@ -1369,7 +1578,9 @@ void NetworkHandler::NavigationFailed(NavigationRequest* navigation_request) {
.SetType(Network::Initiator::TypeEnum::Parser)
.Build(),
std::unique_ptr<Network::Response>(),
- std::string(Page::ResourceTypeEnum::Document));
+ std::string(Page::ResourceTypeEnum::Document),
+ Maybe<std::string>() /* frame_id */,
+ navigation_request->common_params().has_user_gesture);
frontend_->LoadingFailed(
request_id,
@@ -1381,18 +1592,9 @@ void NetworkHandler::NavigationFailed(NavigationRequest* navigation_request) {
DispatchResponse NetworkHandler::SetRequestInterception(
std::unique_ptr<protocol::Array<protocol::Network::RequestPattern>>
patterns) {
- WebContents* web_contents = WebContents::FromRenderFrameHost(host_);
- if (!web_contents)
- return Response::InternalError();
-
- DevToolsInterceptorController* interceptor =
- DevToolsInterceptorController::FromBrowserContext(
- web_contents->GetBrowserContext());
- if (!interceptor)
- return Response::Error("Interception not supported");
-
if (!patterns->length()) {
interception_handle_.reset();
+ url_loader_interceptor_.reset();
return Response::OK();
}
@@ -1412,13 +1614,37 @@ DispatchResponse NetworkHandler::SetRequestInterception(
protocol::Network::InterceptionStageEnum::Request))));
}
+ if (!host_)
+ return Response::InternalError();
+
+ if (base::FeatureList::IsEnabled(network::features::kNetworkService)) {
+ if (!url_loader_interceptor_) {
+ url_loader_interceptor_ = std::make_unique<DevToolsURLLoaderInterceptor>(
+ host_->frame_tree_node(),
+ base::BindRepeating(&NetworkHandler::RequestIntercepted,
+ weak_factory_.GetWeakPtr()));
+ }
+ url_loader_interceptor_->SetPatterns(interceptor_patterns);
+ return Response::OK();
+ }
+
+ WebContents* web_contents = WebContents::FromRenderFrameHost(host_);
+ if (!web_contents)
+ return Response::InternalError();
+
+ DevToolsInterceptorController* interceptor =
+ DevToolsInterceptorController::FromBrowserContext(
+ web_contents->GetBrowserContext());
+ if (!interceptor)
+ return Response::Error("Interception not supported");
+
if (interception_handle_) {
- interception_handle_->UpdatePatterns(std::move(interceptor_patterns));
+ interception_handle_->UpdatePatterns(interceptor_patterns);
} else {
interception_handle_ = interceptor->StartInterceptingRequests(
- host_->frame_tree_node(), std::move(interceptor_patterns),
- base::Bind(&NetworkHandler::RequestIntercepted,
- weak_factory_.GetWeakPtr()));
+ host_->frame_tree_node(), interceptor_patterns,
+ base::BindRepeating(&NetworkHandler::RequestIntercepted,
+ weak_factory_.GetWeakPtr()));
}
return Response::OK();
@@ -1434,13 +1660,6 @@ void NetworkHandler::ContinueInterceptedRequest(
Maybe<protocol::Network::Headers> headers,
Maybe<protocol::Network::AuthChallengeResponse> auth_challenge_response,
std::unique_ptr<ContinueInterceptedRequestCallback> callback) {
- DevToolsInterceptorController* interceptor =
- DevToolsInterceptorController::FromBrowserContext(browser_context_);
- if (!interceptor) {
- callback->sendFailure(Response::InternalError());
- return;
- }
-
base::Optional<std::string> raw_response;
if (base64_raw_response.isJust()) {
std::string decoded;
@@ -1464,18 +1683,37 @@ void NetworkHandler::ContinueInterceptedRequest(
mark_as_canceled = true;
}
- interceptor->ContinueInterceptedRequest(
- interception_id,
+ auto modifications =
std::make_unique<DevToolsNetworkInterceptor::Modifications>(
std::move(error), std::move(raw_response), std::move(url),
std::move(method), std::move(post_data), std::move(headers),
- std::move(auth_challenge_response), mark_as_canceled),
- std::move(callback));
+ std::move(auth_challenge_response), mark_as_canceled);
+
+ if (url_loader_interceptor_) {
+ url_loader_interceptor_->ContinueInterceptedRequest(
+ interception_id, std::move(modifications), std::move(callback));
+ return;
+ }
+
+ DevToolsInterceptorController* interceptor =
+ DevToolsInterceptorController::FromBrowserContext(browser_context_);
+ if (!interceptor) {
+ callback->sendFailure(Response::InternalError());
+ return;
+ }
+ interceptor->ContinueInterceptedRequest(
+ interception_id, std::move(modifications), std::move(callback));
}
void NetworkHandler::GetResponseBodyForInterception(
const String& interception_id,
std::unique_ptr<GetResponseBodyForInterceptionCallback> callback) {
+ if (url_loader_interceptor_) {
+ url_loader_interceptor_->GetResponseBody(interception_id,
+ std::move(callback));
+ return;
+ }
+
DevToolsInterceptorController* interceptor =
DevToolsInterceptorController::FromBrowserContext(browser_context_);
if (!interceptor) {
@@ -1495,6 +1733,31 @@ GURL NetworkHandler::ClearUrlRef(const GURL& url) {
}
// static
+std::unique_ptr<Network::Request>
+NetworkHandler::CreateRequestFromResourceRequest(
+ const network::ResourceRequest& request) {
+ std::unique_ptr<DictionaryValue> headers_dict(DictionaryValue::create());
+ for (net::HttpRequestHeaders::Iterator it(request.headers); it.GetNext();)
+ headers_dict->setString(it.name(), it.value());
+ if (request.referrer.is_valid()) {
+ headers_dict->setString(net::HttpRequestHeaders::kReferer,
+ request.referrer.spec());
+ }
+ std::unique_ptr<protocol::Network::Request> request_object =
+ Network::Request::Create()
+ .SetUrl(ClearUrlRef(request.url).spec())
+ .SetMethod(request.method)
+ .SetHeaders(Object::fromValue(headers_dict.get(), nullptr))
+ .SetInitialPriority(resourcePriority(request.priority))
+ .SetReferrerPolicy(referrerPolicy(request.referrer_policy))
+ .Build();
+ std::string post_data;
+ if (request.request_body && GetPostData(*request.request_body, &post_data))
+ request_object->SetPostData(std::move(post_data));
+ return request_object;
+}
+
+// static
std::unique_ptr<Network::Request> NetworkHandler::CreateRequestFromURLRequest(
const net::URLRequest* request) {
std::unique_ptr<DictionaryValue> headers_dict(DictionaryValue::create());
@@ -1540,6 +1803,15 @@ bool NetworkHandler::ShouldCancelNavigation(
return interceptor && interceptor->ShouldCancelNavigation(global_request_id);
}
+bool NetworkHandler::MaybeCreateProxyForInterception(
+ const base::UnguessableToken& frame_token,
+ int process_id,
+ network::mojom::URLLoaderFactoryRequest* target_factory_request) {
+ return url_loader_interceptor_ &&
+ url_loader_interceptor_->CreateProxyForInterception(
+ frame_token, process_id, target_factory_request);
+}
+
void NetworkHandler::ApplyOverrides(net::HttpRequestHeaders* headers,
bool* skip_service_worker,
bool* disable_cache) {
diff --git a/chromium/content/browser/devtools/protocol/network_handler.h b/chromium/content/browser/devtools/protocol/network_handler.h
index f28d42d4601..6bf4e7e976a 100644
--- a/chromium/content/browser/devtools/protocol/network_handler.h
+++ b/chromium/content/browser/devtools/protocol/network_handler.h
@@ -11,12 +11,17 @@
#include "base/containers/flat_set.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
+#include "content/browser/devtools/devtools_url_loader_interceptor.h"
#include "content/browser/devtools/protocol/devtools_domain_handler.h"
#include "content/browser/devtools/protocol/network.h"
#include "net/base/net_errors.h"
#include "net/cookies/canonical_cookie.h"
#include "services/network/public/mojom/network_service.mojom.h"
+namespace base {
+class UnguessableToken;
+};
+
namespace net {
class HttpRequestHeaders;
class URLRequest;
@@ -120,6 +125,11 @@ class NetworkHandler : public DevToolsDomainHandler,
std::unique_ptr<GetResponseBodyForInterceptionCallback> callback)
override;
+ bool MaybeCreateProxyForInterception(
+ const base::UnguessableToken& frame_token,
+ int process_id,
+ network::mojom::URLLoaderFactoryRequest* target_factory_request);
+
void ApplyOverrides(net::HttpRequestHeaders* headers,
bool* skip_service_worker,
bool* disable_cache);
@@ -146,6 +156,8 @@ class NetworkHandler : public DevToolsDomainHandler,
Network::Frontend* frontend() const { return frontend_.get(); }
static GURL ClearUrlRef(const GURL& url);
+ static std::unique_ptr<Network::Request> CreateRequestFromResourceRequest(
+ const network::ResourceRequest& request);
static std::unique_ptr<Network::Request> CreateRequestFromURLRequest(
const net::URLRequest* request);
@@ -169,6 +181,7 @@ class NetworkHandler : public DevToolsDomainHandler,
std::vector<std::pair<std::string, std::string>> extra_headers_;
std::string host_id_;
std::unique_ptr<InterceptionHandle> interception_handle_;
+ std::unique_ptr<DevToolsURLLoaderInterceptor> url_loader_interceptor_;
bool bypass_service_worker_;
bool cache_disabled_;
base::WeakPtrFactory<NetworkHandler> weak_factory_;
diff --git a/chromium/content/browser/devtools/protocol/page_handler.cc b/chromium/content/browser/devtools/protocol/page_handler.cc
index a76eb43b702..8dc4689a515 100644
--- a/chromium/content/browser/devtools/protocol/page_handler.cc
+++ b/chromium/content/browser/devtools/protocol/page_handler.cc
@@ -230,6 +230,7 @@ void PageHandler::DidRunJavaScriptDialog(const GURL& url,
const base::string16& message,
const base::string16& default_prompt,
JavaScriptDialogType dialog_type,
+ bool has_non_devtools_handlers,
JavaScriptDialogCallback callback) {
if (!enabled_)
return;
@@ -241,10 +242,12 @@ void PageHandler::DidRunJavaScriptDialog(const GURL& url,
if (dialog_type == JAVASCRIPT_DIALOG_TYPE_PROMPT)
type = Page::DialogTypeEnum::Prompt;
frontend_->JavascriptDialogOpening(url.spec(), base::UTF16ToUTF8(message),
- type, base::UTF16ToUTF8(default_prompt));
+ type, has_non_devtools_handlers,
+ base::UTF16ToUTF8(default_prompt));
}
void PageHandler::DidRunBeforeUnloadConfirm(const GURL& url,
+ bool has_non_devtools_handlers,
JavaScriptDialogCallback callback) {
if (!enabled_)
return;
@@ -252,7 +255,7 @@ void PageHandler::DidRunBeforeUnloadConfirm(const GURL& url,
pending_dialog_ = std::move(callback);
frontend_->JavascriptDialogOpening(url.spec(), std::string(),
Page::DialogTypeEnum::Beforeunload,
- std::string());
+ has_non_devtools_handlers, std::string());
}
void PageHandler::DidCloseJavaScriptDialog(bool success,
diff --git a/chromium/content/browser/devtools/protocol/page_handler.h b/chromium/content/browser/devtools/protocol/page_handler.h
index 9c1b84e68d9..8e45be2d993 100644
--- a/chromium/content/browser/devtools/protocol/page_handler.h
+++ b/chromium/content/browser/devtools/protocol/page_handler.h
@@ -24,7 +24,7 @@
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
#include "content/public/common/javascript_dialog_type.h"
-#include "third_party/WebKit/public/platform/modules/manifest/manifest_manager.mojom.h"
+#include "third_party/blink/public/platform/modules/manifest/manifest_manager.mojom.h"
#include "url/gurl.h"
class SkBitmap;
@@ -78,8 +78,10 @@ class PageHandler : public DevToolsDomainHandler,
const base::string16& message,
const base::string16& default_prompt,
JavaScriptDialogType dialog_type,
+ bool has_non_devtools_handlers,
JavaScriptDialogCallback callback);
void DidRunBeforeUnloadConfirm(const GURL& url,
+ bool has_non_devtools_handlers,
JavaScriptDialogCallback callback);
void DidCloseJavaScriptDialog(bool success, const base::string16& user_input);
void NavigationReset(NavigationRequest* navigation_request);
diff --git a/chromium/content/browser/devtools/protocol/security_handler.cc b/chromium/content/browser/devtools/protocol/security_handler.cc
index bd4a401fdca..bdc3c63acb8 100644
--- a/chromium/content/browser/devtools/protocol/security_handler.cc
+++ b/chromium/content/browser/devtools/protocol/security_handler.cc
@@ -20,7 +20,7 @@
#include "content/public/browser/web_contents_delegate.h"
#include "net/cert/x509_certificate.h"
#include "net/cert/x509_util.h"
-#include "third_party/WebKit/public/platform/WebMixedContentContextType.h"
+#include "third_party/blink/public/platform/web_mixed_content_context_type.h"
namespace content {
namespace protocol {
@@ -141,6 +141,8 @@ void SecurityHandler::SetRenderer(int process_host_id,
void SecurityHandler::DidChangeVisibleSecurityState() {
DCHECK(enabled_);
+ if (!web_contents()->GetDelegate())
+ return;
SecurityStyleExplanations security_style_explanations;
blink::WebSecurityStyle security_style =
@@ -206,7 +208,7 @@ bool SecurityHandler::NotifyCertificateError(int cert_error,
CertErrorCallback handler) {
if (cert_error_override_mode_ == CertErrorOverrideMode::kIgnoreAll) {
if (handler)
- handler.Run(content::CERTIFICATE_REQUEST_RESULT_TYPE_CONTINUE);
+ std::move(handler).Run(content::CERTIFICATE_REQUEST_RESULT_TYPE_CONTINUE);
return true;
}
@@ -222,7 +224,7 @@ bool SecurityHandler::NotifyCertificateError(int cert_error,
return false;
}
- cert_error_callbacks_[last_cert_error_id_] = handler;
+ cert_error_callbacks_[last_cert_error_id_] = std::move(handler);
return true;
}
diff --git a/chromium/content/browser/devtools/protocol/service_worker_handler.cc b/chromium/content/browser/devtools/protocol/service_worker_handler.cc
index 5501f6ad645..5449b409717 100644
--- a/chromium/content/browser/devtools/protocol/service_worker_handler.cc
+++ b/chromium/content/browser/devtools/protocol/service_worker_handler.cc
@@ -29,8 +29,8 @@
#include "content/public/browser/web_contents.h"
#include "content/public/common/push_event_payload.h"
#include "content/public/common/push_messaging_status.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_provider_type.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_provider_type.mojom.h"
#include "url/gurl.h"
namespace content {
@@ -213,8 +213,7 @@ Response ServiceWorkerHandler::Unregister(const std::string& scope_url) {
return CreateDomainNotEnabledErrorResponse();
if (!context_)
return CreateContextErrorResponse();
- context_->UnregisterServiceWorker(GURL(scope_url),
- base::DoNothing::Repeatedly<bool>());
+ context_->UnregisterServiceWorker(GURL(scope_url), base::DoNothing());
return Response::OK();
}
@@ -223,8 +222,7 @@ Response ServiceWorkerHandler::StartWorker(const std::string& scope_url) {
return CreateDomainNotEnabledErrorResponse();
if (!context_)
return CreateContextErrorResponse();
- context_->StartServiceWorker(
- GURL(scope_url), base::DoNothing::Repeatedly<ServiceWorkerStatusCode>());
+ context_->StartServiceWorker(GURL(scope_url), base::DoNothing());
return Response::OK();
}
diff --git a/chromium/content/browser/devtools/protocol/storage_handler.cc b/chromium/content/browser/devtools/protocol/storage_handler.cc
index 2c621aa87f0..ad5bb6d37ed 100644
--- a/chromium/content/browser/devtools/protocol/storage_handler.cc
+++ b/chromium/content/browser/devtools/protocol/storage_handler.cc
@@ -12,11 +12,12 @@
#include "base/strings/string_split.h"
#include "content/browser/cache_storage/cache_storage_context_impl.h"
#include "content/browser/indexed_db/indexed_db_context_impl.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/storage_partition.h"
#include "storage/browser/quota/quota_client.h"
#include "storage/browser/quota/quota_manager.h"
-#include "third_party/WebKit/public/mojom/quota/quota_types.mojom.h"
+#include "third_party/blink/public/mojom/quota/quota_types.mojom.h"
#include "url/gurl.h"
#include "url/origin.h"
@@ -88,8 +89,7 @@ void GetUsageAndQuotaOnIOThread(
DCHECK_CURRENTLY_ON(BrowserThread::IO);
manager->GetUsageAndQuotaWithBreakdown(
url, blink::mojom::StorageType::kTemporary,
- base::Bind(&GotUsageAndQuotaDataCallback,
- base::Passed(std::move(callback))));
+ base::BindOnce(&GotUsageAndQuotaDataCallback, std::move(callback)));
}
} // namespace
diff --git a/chromium/content/browser/devtools/protocol/system_info_handler.cc b/chromium/content/browser/devtools/protocol/system_info_handler.cc
index 5372bd781ab..3a90a35db77 100644
--- a/chromium/content/browser/devtools/protocol/system_info_handler.cc
+++ b/chromium/content/browser/devtools/protocol/system_info_handler.cc
@@ -10,7 +10,6 @@
#include "base/bind.h"
#include "base/command_line.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "content/browser/gpu/compositor_util.h"
diff --git a/chromium/content/browser/devtools/protocol/target_auto_attacher.cc b/chromium/content/browser/devtools/protocol/target_auto_attacher.cc
index b460c7fa321..3d4b128b294 100644
--- a/chromium/content/browser/devtools/protocol/target_auto_attacher.cc
+++ b/chromium/content/browser/devtools/protocol/target_auto_attacher.cc
@@ -170,7 +170,10 @@ DevToolsAgentHost* TargetAutoAttacher::AutoAttachToFrame(
DCHECK(old_cross_process);
auto it = auto_attached_hosts_.find(agent_host);
- DCHECK(it != auto_attached_hosts_.end());
+ // This should not happen in theory, but error pages are sometimes not
+ // picked up. See https://crbug.com/836511 and https://crbug.com/817881.
+ if (it == auto_attached_hosts_.end())
+ return nullptr;
auto_attached_hosts_.erase(it);
detach_callback_.Run(agent_host.get());
return nullptr;
diff --git a/chromium/content/browser/devtools/protocol/tethering_handler.cc b/chromium/content/browser/devtools/protocol/tethering_handler.cc
index 494aea4d93b..ce6738651b2 100644
--- a/chromium/content/browser/devtools/protocol/tethering_handler.cc
+++ b/chromium/content/browser/devtools/protocol/tethering_handler.cc
@@ -6,7 +6,6 @@
#include <map>
-#include "base/memory/ptr_util.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/io_buffer.h"
#include "net/base/ip_address.h"
@@ -295,7 +294,7 @@ void TetheringHandler::TetheringImpl::Bind(
BoundSocket::AcceptedCallback accepted = base::Bind(
&TetheringHandler::TetheringImpl::Accepted, base::Unretained(this));
std::unique_ptr<BoundSocket> bound_socket =
- std::make_unique<BoundSocket>(accepted, socket_callback_);
+ std::make_unique<BoundSocket>(std::move(accepted), socket_callback_);
if (!bound_socket->Listen(port)) {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
diff --git a/chromium/content/browser/devtools/protocol/tracing_handler.cc b/chromium/content/browser/devtools/protocol/tracing_handler.cc
index e94eb77facf..ea314dff3c0 100644
--- a/chromium/content/browser/devtools/protocol/tracing_handler.cc
+++ b/chromium/content/browser/devtools/protocol/tracing_handler.cc
@@ -25,13 +25,19 @@
#include "base/trace_event/tracing_agent.h"
#include "components/tracing/common/trace_config_file.h"
#include "components/viz/common/features.h"
-#include "content/browser/devtools/devtools_frame_trace_recorder_for_viz.h"
+#include "content/browser/devtools/devtools_frame_trace_recorder.h"
#include "content/browser/devtools/devtools_io_context.h"
#include "content/browser/devtools/devtools_session.h"
+#include "content/browser/devtools/devtools_traceable_screenshot.h"
+#include "content/browser/devtools/devtools_video_consumer.h"
+#include "content/browser/frame_host/frame_tree.h"
+#include "content/browser/frame_host/frame_tree_node.h"
+#include "content/browser/frame_host/navigation_handle_impl.h"
#include "content/browser/frame_host/render_frame_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/browser/tracing/tracing_controller_impl.h"
#include "content/public/browser/browser_thread.h"
+#include "content/public/common/content_features.h"
#include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h"
#include "services/tracing/public/mojom/constants.mojom.h"
@@ -44,6 +50,17 @@ const double kMinimumReportingInterval = 250.0;
const char kRecordModeParam[] = "record_mode";
+// Settings for |video_consumer_|.
+// Tracing requires a 10ms minimum capture period.
+constexpr base::TimeDelta kMinCapturePeriod =
+ base::TimeDelta::FromMilliseconds(10);
+
+// Frames need to be at least 1x1, otherwise nothing would be captured.
+constexpr gfx::Size kMinFrameSize = gfx::Size(1, 1);
+
+// Frames do not need to be greater than 500x500 for tracing.
+constexpr gfx::Size kMaxFrameSize = gfx::Size(500, 500);
+
// Convert from camel case to separator + lowercase.
std::string ConvertFromCamelCase(const std::string& in_str, char separator) {
std::string out_str;
@@ -143,22 +160,66 @@ class DevToolsStreamEndpoint : public TracingController::TraceDataEndpoint {
base::WeakPtr<TracingHandler> tracing_handler_;
};
+std::string GetProcessHostHex(RenderProcessHost* host) {
+ return base::StringPrintf("0x%" PRIxPTR, reinterpret_cast<uintptr_t>(host));
+}
+
+void SendProcessReadyInBrowserEvent(const base::UnguessableToken& frame_token,
+ RenderProcessHost* host) {
+ auto data = std::make_unique<base::trace_event::TracedValue>();
+ data->SetString("frame", frame_token.ToString());
+ data->SetString("processPseudoId", GetProcessHostHex(host));
+ data->SetInteger("processId",
+ static_cast<int>(base::GetProcId(host->GetHandle())));
+ TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"),
+ "ProcessReadyInBrowser", TRACE_EVENT_SCOPE_THREAD,
+ "data", std::move(data));
+}
+
+void FillFrameData(base::trace_event::TracedValue* data,
+ FrameTreeNode* node,
+ RenderFrameHostImpl* frame_host,
+ const GURL& url) {
+ url::Replacements<char> strip_fragment;
+ strip_fragment.ClearRef();
+ data->SetString("frame", node->devtools_frame_token().ToString());
+ data->SetString("url", url.ReplaceComponents(strip_fragment).spec());
+ data->SetString("name", node->frame_name());
+ if (node->parent())
+ data->SetString("parent",
+ node->parent()->devtools_frame_token().ToString());
+ if (frame_host) {
+ RenderProcessHost* process_host = frame_host->GetProcess();
+ base::ProcessId process_id = base::GetProcId(process_host->GetHandle());
+ if (process_id == base::kNullProcessId) {
+ data->SetString("processPseudoId", GetProcessHostHex(process_host));
+ frame_host->GetProcess()->PostTaskWhenProcessIsReady(
+ base::BindOnce(&SendProcessReadyInBrowserEvent,
+ node->devtools_frame_token(), process_host));
+ } else {
+ // Cast process id to int to be compatible with tracing.
+ data->SetInteger("processId", static_cast<int>(process_id));
+ }
+ }
+}
+
} // namespace
-TracingHandler::TracingHandler(TracingHandler::Target target,
- int frame_tree_node_id,
+TracingHandler::TracingHandler(FrameTreeNode* frame_tree_node_,
DevToolsIOContext* io_context)
: DevToolsDomainHandler(Tracing::Metainfo::domainName),
- target_(target),
io_context_(io_context),
- frame_tree_node_id_(frame_tree_node_id),
+ frame_tree_node_(frame_tree_node_),
did_initiate_recording_(false),
return_as_stream_(false),
gzip_compression_(false),
weak_factory_(this) {
- if (base::FeatureList::IsEnabled(features::kVizDisplayCompositor)) {
- frame_trace_recorder_ =
- std::make_unique<DevToolsFrameTraceRecorderForViz>();
+ if (base::FeatureList::IsEnabled(features::kVizDisplayCompositor) ||
+ base::FeatureList::IsEnabled(
+ features::kUseVideoCaptureApiForDevToolsSnapshots)) {
+ video_consumer_ =
+ std::make_unique<DevToolsVideoConsumer>(base::BindRepeating(
+ &TracingHandler::OnFrameFromVideoConsumer, base::Unretained(this)));
}
}
@@ -174,9 +235,9 @@ std::vector<TracingHandler*> TracingHandler::ForAgentHost(
void TracingHandler::SetRenderer(int process_host_id,
RenderFrameHostImpl* frame_host) {
- if (!frame_trace_recorder_ || !frame_host)
+ if (!video_consumer_ || !frame_host)
return;
- frame_trace_recorder_->SetFrameSinkId(
+ video_consumer_->SetFrameSinkId(
frame_host->GetRenderWidgetHost()->GetFrameSinkId());
}
@@ -340,7 +401,7 @@ void TracingHandler::Start(Maybe<std::string> categories,
// If inspected target is a render process Tracing.start will be handled by
// tracing agent in the renderer.
- if (target_ == Renderer)
+ if (frame_tree_node_)
callback->fallThrough();
TracingController::GetInstance()->StartTracing(
@@ -377,7 +438,7 @@ void TracingHandler::End(std::unique_ptr<EndCallback> callback) {
}
// If inspected target is a render process Tracing.end will be handled by
// tracing agent in the renderer.
- if (target_ == Renderer)
+ if (frame_tree_node_)
callback->fallThrough();
else
callback->sendSuccess();
@@ -393,17 +454,21 @@ void TracingHandler::GetCategories(
void TracingHandler::OnRecordingEnabled(
std::unique_ptr<StartCallback> callback) {
- TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"),
- "TracingStartedInBrowser", TRACE_EVENT_SCOPE_THREAD,
- "frameTreeNodeId", frame_tree_node_id_);
- if (target_ != Renderer)
+ EmitFrameTree();
+
+ if (!frame_tree_node_)
callback->sendSuccess();
bool screenshot_enabled;
TRACE_EVENT_CATEGORY_GROUP_ENABLED(
TRACE_DISABLED_BY_DEFAULT("devtools.screenshot"), &screenshot_enabled);
- if (frame_trace_recorder_ && screenshot_enabled)
- frame_trace_recorder_->StartCapture();
+ if (video_consumer_ && screenshot_enabled) {
+ // Reset number of screenshots received, each time tracing begins.
+ number_of_screenshots_from_video_consumer_ = 0;
+ video_consumer_->SetMinCapturePeriod(kMinCapturePeriod);
+ video_consumer_->SetMinAndMaxFrameSize(kMinFrameSize, kMaxFrameSize);
+ video_consumer_->StartCapture();
+ }
}
void TracingHandler::OnBufferUsage(float percent_full,
@@ -437,7 +502,7 @@ void TracingHandler::RequestMemoryDump(
->RequestGlobalDumpAndAppendToTrace(
base::trace_event::MemoryDumpType::EXPLICITLY_TRIGGERED,
base::trace_event::MemoryDumpLevelOfDetail::DETAILED,
- on_memory_dump_finished);
+ std::move(on_memory_dump_finished));
}
void TracingHandler::OnMemoryDumpFinished(
@@ -447,6 +512,27 @@ void TracingHandler::OnMemoryDumpFinished(
callback->sendSuccess(base::StringPrintf("0x%" PRIx64, dump_id), success);
}
+void TracingHandler::OnFrameFromVideoConsumer(
+ scoped_refptr<media::VideoFrame> frame) {
+ const SkBitmap skbitmap = DevToolsVideoConsumer::GetSkBitmapFromFrame(frame);
+
+ base::TimeTicks reference_time;
+ const bool had_reference_time = frame->metadata()->GetTimeTicks(
+ media::VideoFrameMetadata::REFERENCE_TIME, &reference_time);
+ DCHECK(had_reference_time);
+
+ TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID_AND_TIMESTAMP(
+ TRACE_DISABLED_BY_DEFAULT("devtools.screenshot"), "Screenshot", 1,
+ reference_time, std::make_unique<DevToolsTraceableScreenshot>(skbitmap));
+
+ ++number_of_screenshots_from_video_consumer_;
+ DCHECK(video_consumer_);
+ if (number_of_screenshots_from_video_consumer_ >=
+ DevToolsFrameTraceRecorder::kMaximumNumberOfScreenshots) {
+ video_consumer_->StopCapture();
+ }
+}
+
Response TracingHandler::RecordClockSyncMarker(const std::string& sync_id) {
if (!IsTracing())
return Response::Error("Tracing is not started");
@@ -478,17 +564,63 @@ void TracingHandler::StopTracing(
buffer_usage_poll_timer_.reset();
TracingController::GetInstance()->StopTracing(endpoint, agent_label);
did_initiate_recording_ = false;
- if (frame_trace_recorder_)
- frame_trace_recorder_->StopCapture();
+ if (video_consumer_)
+ video_consumer_->StopCapture();
}
bool TracingHandler::IsTracing() const {
return TracingController::GetInstance()->IsTracing();
}
+void TracingHandler::EmitFrameTree() {
+ auto data = std::make_unique<base::trace_event::TracedValue>();
+ if (frame_tree_node_) {
+ data->SetInteger("frameTreeNodeId", frame_tree_node_->frame_tree_node_id());
+ data->SetBoolean("persistentIds", true);
+ data->BeginArray("frames");
+ FrameTree::NodeRange subtree =
+ frame_tree_node_->frame_tree()->SubtreeNodes(frame_tree_node_);
+ for (FrameTreeNode* node : subtree) {
+ data->BeginDictionary();
+ FillFrameData(data.get(), node, node->current_frame_host(),
+ node->current_url());
+ data->EndDictionary();
+ }
+ data->EndArray();
+ }
+ TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"),
+ "TracingStartedInBrowser", TRACE_EVENT_SCOPE_THREAD,
+ "data", std::move(data));
+}
+
+void TracingHandler::ReadyToCommitNavigation(
+ NavigationHandleImpl* navigation_handle) {
+ if (!did_initiate_recording_)
+ return;
+ auto data = std::make_unique<base::trace_event::TracedValue>();
+ FillFrameData(data.get(), navigation_handle->frame_tree_node(),
+ navigation_handle->GetRenderFrameHost(),
+ navigation_handle->GetURL());
+ TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"),
+ "FrameCommittedInBrowser", TRACE_EVENT_SCOPE_THREAD,
+ "data", std::move(data));
+}
+
+void TracingHandler::FrameDeleted(RenderFrameHostImpl* frame_host) {
+ if (!did_initiate_recording_)
+ return;
+ auto data = std::make_unique<base::trace_event::TracedValue>();
+ data->SetString(
+ "frame",
+ frame_host->frame_tree_node()->devtools_frame_token().ToString());
+ TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"),
+ "FrameDeletedInBrowser", TRACE_EVENT_SCOPE_THREAD,
+ "data", std::move(data));
+}
+
+// static
bool TracingHandler::IsStartupTracingActive() {
- return ::tracing::TraceConfigFile::GetInstance()->IsEnabled() &&
- TracingController::GetInstance()->IsTracing();
+ return ::tracing::TraceConfigFile::GetInstance()->IsEnabled();
}
// static
diff --git a/chromium/content/browser/devtools/protocol/tracing_handler.h b/chromium/content/browser/devtools/protocol/tracing_handler.h
index 8515e3a3dfa..7f21754cc10 100644
--- a/chromium/content/browser/devtools/protocol/tracing_handler.h
+++ b/chromium/content/browser/devtools/protocol/tracing_handler.h
@@ -26,19 +26,23 @@ namespace base {
class Timer;
}
+namespace media {
+class VideoFrame;
+}
+
namespace content {
class DevToolsAgentHostImpl;
-class DevToolsFrameTraceRecorderForViz;
+class DevToolsVideoConsumer;
class DevToolsIOContext;
+class FrameTreeNode;
+class NavigationHandleImpl;
namespace protocol {
class TracingHandler : public DevToolsDomainHandler, public Tracing::Backend {
public:
- enum Target { Browser, Renderer };
- CONTENT_EXPORT TracingHandler(Target target,
- int frame_tree_node_id,
+ CONTENT_EXPORT TracingHandler(FrameTreeNode* frame_tree_node,
DevToolsIOContext* io_context);
CONTENT_EXPORT ~TracingHandler() override;
@@ -69,6 +73,8 @@ class TracingHandler : public DevToolsDomainHandler, public Tracing::Backend {
Response RecordClockSyncMarker(const std::string& sync_id) override;
bool did_initiate_recording() { return did_initiate_recording_; }
+ void ReadyToCommitNavigation(NavigationHandleImpl* navigation_handle);
+ void FrameDeleted(RenderFrameHostImpl* frame_host);
private:
friend class TracingHandlerTest;
@@ -90,7 +96,7 @@ class TracingHandler : public DevToolsDomainHandler, public Tracing::Backend {
void OnMemoryDumpFinished(std::unique_ptr<RequestMemoryDumpCallback> callback,
bool success,
uint64_t dump_id);
-
+ void OnFrameFromVideoConsumer(scoped_refptr<media::VideoFrame> frame);
// Assuming that the input is a potentially incomplete string representation
// of a comma separated list of JSON objects, return the longest prefix that
// is a valid list and store the rest to be used in subsequent calls.
@@ -102,22 +108,23 @@ class TracingHandler : public DevToolsDomainHandler, public Tracing::Backend {
const scoped_refptr<TracingController::TraceDataEndpoint>& endpoint,
const std::string& agent_label);
bool IsTracing() const;
+ void EmitFrameTree();
static bool IsStartupTracingActive();
CONTENT_EXPORT static base::trace_event::TraceConfig
GetTraceConfigFromDevToolsConfig(
const base::DictionaryValue& devtools_config);
std::unique_ptr<base::Timer> buffer_usage_poll_timer_;
- Target target_;
std::unique_ptr<Tracing::Frontend> frontend_;
DevToolsIOContext* io_context_;
- int frame_tree_node_id_;
+ FrameTreeNode* frame_tree_node_;
bool did_initiate_recording_;
bool return_as_stream_;
bool gzip_compression_;
TraceDataBufferState trace_data_buffer_state_;
- std::unique_ptr<DevToolsFrameTraceRecorderForViz> frame_trace_recorder_;
+ std::unique_ptr<DevToolsVideoConsumer> video_consumer_;
+ int number_of_screenshots_from_video_consumer_ = 0;
base::WeakPtrFactory<TracingHandler> weak_factory_;
FRIEND_TEST_ALL_PREFIXES(TracingHandlerTest,
diff --git a/chromium/content/browser/devtools/protocol/tracing_handler_unittest.cc b/chromium/content/browser/devtools/protocol/tracing_handler_unittest.cc
index 5af1a8d65d4..a392742902a 100644
--- a/chromium/content/browser/devtools/protocol/tracing_handler_unittest.cc
+++ b/chromium/content/browser/devtools/protocol/tracing_handler_unittest.cc
@@ -72,8 +72,7 @@ const char kCustomTraceConfigStringDevToolsStyle[] =
class TracingHandlerTest : public testing::Test {
public:
void SetUp() override {
- tracing_handler_.reset(
- new TracingHandler(TracingHandler::Browser, 0, nullptr));
+ tracing_handler_.reset(new TracingHandler(nullptr, nullptr));
}
void TearDown() override { tracing_handler_.reset(); }
diff --git a/chromium/content/browser/devtools/protocol_config.json b/chromium/content/browser/devtools/protocol_config.json
index 4e9d341cc03..f40789fe6f4 100644
--- a/chromium/content/browser/devtools/protocol_config.json
+++ b/chromium/content/browser/devtools/protocol_config.json
@@ -11,7 +11,7 @@
"options": [
{
"domain": "Browser",
- "include": ["getVersion", "getHistograms", "getHistogram", "getCommandLine"]
+ "include": ["getVersion", "getHistograms", "getHistogram", "getBrowserCommandLine"]
},
{
"domain": "DOM",
diff --git a/chromium/content/browser/devtools/render_frame_devtools_agent_host.cc b/chromium/content/browser/devtools/render_frame_devtools_agent_host.cc
index cdeca684d4f..f6977596a09 100644
--- a/chromium/content/browser/devtools/render_frame_devtools_agent_host.cc
+++ b/chromium/content/browser/devtools/render_frame_devtools_agent_host.cc
@@ -12,6 +12,7 @@
#include "base/memory/ptr_util.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
+#include "components/viz/common/features.h"
#include "content/browser/bad_message.h"
#include "content/browser/child_process_security_policy_impl.h"
#include "content/browser/devtools/devtools_frame_trace_recorder.h"
@@ -42,17 +43,19 @@
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/common/view_messages.h"
#include "content/public/browser/browser_context.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/browser/render_widget_host_iterator.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/common/browser_side_navigation_policy.h"
+#include "content/public/common/content_features.h"
#include "mojo/public/cpp/bindings/associated_binding.h"
#include "net/base/load_flags.h"
#include "net/http/http_request_headers.h"
#include "services/network/public/cpp/features.h"
-#include "third_party/WebKit/public/common/associated_interfaces/associated_interface_provider.h"
+#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#if defined(OS_ANDROID)
#include "content/public/browser/render_widget_host_view.h"
@@ -272,6 +275,7 @@ void RenderFrameDevToolsAgentHost::ApplyOverrides(
net::HttpRequestHeaders headers;
headers.AddHeadersFromString(begin_params->headers);
for (auto* network : protocol::NetworkHandler::ForAgentHost(agent_host)) {
+ // TODO(caseq): consider chaining intercepting proxies from multiple agents.
if (!network->enabled())
continue;
*report_raw_headers = true;
@@ -289,6 +293,27 @@ void RenderFrameDevToolsAgentHost::ApplyOverrides(
}
// static
+bool RenderFrameDevToolsAgentHost::WillCreateURLLoaderFactory(
+ RenderFrameHostImpl* rfh,
+ bool is_navigation,
+ network::mojom::URLLoaderFactoryRequest* target_factory_request) {
+ FrameTreeNode* frame_tree_node = rfh->frame_tree_node();
+ base::UnguessableToken frame_token = frame_tree_node->devtools_frame_token();
+ frame_tree_node = GetFrameTreeNodeAncestor(frame_tree_node);
+ RenderFrameDevToolsAgentHost* agent_host = FindAgentHost(frame_tree_node);
+ if (!agent_host)
+ return false;
+ int process_id = is_navigation ? 0 : rfh->GetProcess()->GetID();
+ for (auto* network : protocol::NetworkHandler::ForAgentHost(agent_host)) {
+ if (network->MaybeCreateProxyForInterception(frame_token, process_id,
+ target_factory_request)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+// static
void RenderFrameDevToolsAgentHost::OnNavigationRequestWillBeSent(
const NavigationRequest& navigation_request) {
DispatchToAgents(navigation_request.frame_tree_node(),
@@ -342,7 +367,9 @@ WebContents* RenderFrameDevToolsAgentHost::GetWebContents() {
return web_contents();
}
-void RenderFrameDevToolsAgentHost::AttachSession(DevToolsSession* session) {
+bool RenderFrameDevToolsAgentHost::AttachSession(DevToolsSession* session) {
+ if (session->restricted() && !IsFrameHostAllowedForRestrictedSessions())
+ return false;
session->SetRenderer(frame_host_ ? frame_host_->GetProcess()->GetID()
: ChildProcessHost::kInvalidUniqueID,
frame_host_);
@@ -361,26 +388,34 @@ void RenderFrameDevToolsAgentHost::AttachSession(DevToolsSession* session) {
session->AddHandler(base::WrapUnique(new protocol::SchemaHandler()));
session->AddHandler(base::WrapUnique(new protocol::ServiceWorkerHandler()));
session->AddHandler(base::WrapUnique(new protocol::StorageHandler()));
- session->AddHandler(
- base::WrapUnique(new protocol::TargetHandler(false /* browser_only */)));
- session->AddHandler(base::WrapUnique(new protocol::TracingHandler(
- protocol::TracingHandler::Renderer,
- frame_tree_node_ ? frame_tree_node_->frame_tree_node_id() : 0,
- GetIOContext())));
+ if (!session->restricted()) {
+ session->AddHandler(base::WrapUnique(
+ new protocol::TargetHandler(false /* browser_only */)));
+ }
session->AddHandler(
base::WrapUnique(new protocol::PageHandler(emulation_handler)));
session->AddHandler(base::WrapUnique(new protocol::SecurityHandler()));
+ if (!frame_tree_node_ || !frame_tree_node_->parent()) {
+ session->AddHandler(base::WrapUnique(
+ new protocol::TracingHandler(frame_tree_node_, GetIOContext())));
+ }
if (EnsureAgent())
session->AttachToAgent(agent_ptr_);
if (sessions().size() == 1) {
- frame_trace_recorder_.reset(new DevToolsFrameTraceRecorder());
+ // Taking screenshots using the video capture API is done in TracingHandler.
+ if (!base::FeatureList::IsEnabled(features::kVizDisplayCompositor) &&
+ !base::FeatureList::IsEnabled(
+ features::kUseVideoCaptureApiForDevToolsSnapshots)) {
+ frame_trace_recorder_.reset(new DevToolsFrameTraceRecorder());
+ }
GrantPolicy();
#if defined(OS_ANDROID)
GetWakeLock()->RequestWakeLock();
#endif
}
+ return true;
}
void RenderFrameDevToolsAgentHost::DetachSession(DevToolsSession* session) {
@@ -431,6 +466,9 @@ void RenderFrameDevToolsAgentHost::ReadyToCommitNavigation(
NavigationHandle* navigation_handle) {
NavigationHandleImpl* handle =
static_cast<NavigationHandleImpl*>(navigation_handle);
+ for (auto* tracing : protocol::TracingHandler::ForAgentHost(this))
+ tracing->ReadyToCommitNavigation(handle);
+
if (handle->frame_tree_node() != frame_tree_node_) {
if (ShouldForceCreation() && handle->GetRenderFrameHost() &&
handle->GetRenderFrameHost()->IsCrossProcessSubframe()) {
@@ -487,13 +525,19 @@ void RenderFrameDevToolsAgentHost::UpdateFrameHost(
if (IsAttached())
RevokePolicy();
+
frame_host_ = frame_host;
agent_ptr_.reset();
+
+ if (!IsFrameHostAllowedForRestrictedSessions())
+ ForceDetachRestrictedSessions();
+
if (!render_frame_alive_) {
render_frame_alive_ = true;
for (auto* inspector : protocol::InspectorHandler::ForAgentHost(this))
inspector->TargetReloadedAfterCrash();
}
+
if (IsAttached()) {
GrantPolicy();
for (DevToolsSession* session : sessions()) {
@@ -570,9 +614,12 @@ void RenderFrameDevToolsAgentHost::RenderFrameHostChanged(
}
void RenderFrameDevToolsAgentHost::FrameDeleted(RenderFrameHost* rfh) {
- if (static_cast<RenderFrameHostImpl*>(rfh)->frame_tree_node() ==
- frame_tree_node_) {
- DestroyOnRenderFrameGone(); // |this| may be deleted at this point.
+ RenderFrameHostImpl* host = static_cast<RenderFrameHostImpl*>(rfh);
+ for (auto* tracing : protocol::TracingHandler::ForAgentHost(this))
+ tracing->FrameDeleted(host);
+ if (host->frame_tree_node() == frame_tree_node_) {
+ DestroyOnRenderFrameGone();
+ // |this| may be deleted at this point.
}
}
@@ -587,7 +634,7 @@ void RenderFrameDevToolsAgentHost::DestroyOnRenderFrameGone() {
scoped_refptr<RenderFrameDevToolsAgentHost> protect(this);
if (IsAttached())
RevokePolicy();
- ForceDetachAllClients();
+ ForceDetachAllSessions();
frame_host_ = nullptr;
agent_ptr_.reset();
SetFrameTreeNode(nullptr);
@@ -662,8 +709,6 @@ void RenderFrameDevToolsAgentHost::DidReceiveCompositorFrame() {
->last_frame_metadata();
for (auto* page : protocol::PageHandler::ForAgentHost(this))
page->OnSwapCompositorFrame(metadata.Clone());
- for (auto* input : protocol::InputHandler::ForAgentHost(this))
- input->OnSwapCompositorFrame(metadata);
if (!frame_trace_recorder_)
return;
@@ -674,6 +719,12 @@ void RenderFrameDevToolsAgentHost::DidReceiveCompositorFrame() {
frame_trace_recorder_->OnSwapCompositorFrame(frame_host_, metadata);
}
+void RenderFrameDevToolsAgentHost::OnPageScaleFactorChanged(
+ float page_scale_factor) {
+ for (auto* input : protocol::InputHandler::ForAgentHost(this))
+ input->OnPageScaleFactorChanged(page_scale_factor);
+}
+
void RenderFrameDevToolsAgentHost::DisconnectWebContents() {
navigation_handles_.clear();
SetFrameTreeNode(nullptr);
@@ -822,8 +873,6 @@ void RenderFrameDevToolsAgentHost::SynchronousSwapCompositorFrame(
viz::CompositorFrameMetadata frame_metadata) {
for (auto* page : protocol::PageHandler::ForAgentHost(this))
page->OnSynchronousSwapCompositorFrame(frame_metadata.Clone());
- for (auto* input : protocol::InputHandler::ForAgentHost(this))
- input->OnSwapCompositorFrame(frame_metadata);
if (!frame_trace_recorder_)
return;
@@ -848,4 +897,9 @@ bool RenderFrameDevToolsAgentHost::IsChildFrame() {
return frame_tree_node_ && frame_tree_node_->parent();
}
+bool RenderFrameDevToolsAgentHost::IsFrameHostAllowedForRestrictedSessions() {
+ return !frame_host_ ||
+ (!frame_host_->web_ui() && !frame_host_->pending_web_ui());
+}
+
} // namespace content
diff --git a/chromium/content/browser/devtools/render_frame_devtools_agent_host.h b/chromium/content/browser/devtools/render_frame_devtools_agent_host.h
index 8877e6c3f18..afd61919b40 100644
--- a/chromium/content/browser/devtools/render_frame_devtools_agent_host.h
+++ b/chromium/content/browser/devtools/render_frame_devtools_agent_host.h
@@ -18,7 +18,8 @@
#include "content/common/navigation_params.mojom.h"
#include "content/public/browser/web_contents_observer.h"
#include "net/base/net_errors.h"
-#include "third_party/WebKit/public/web/devtools_agent.mojom.h"
+#include "services/network/public/mojom/url_loader_factory.mojom.h"
+#include "third_party/blink/public/web/devtools_agent.mojom.h"
#if defined(OS_ANDROID)
#include "services/device/public/mojom/wake_lock.mojom.h"
@@ -69,6 +70,11 @@ class CONTENT_EXPORT RenderFrameDevToolsAgentHost
static void ApplyOverrides(FrameTreeNode* frame_tree_node,
mojom::BeginNavigationParams* begin_params,
bool* report_raw_headers);
+ static bool WillCreateURLLoaderFactory(
+ RenderFrameHostImpl* rfh,
+ bool is_navigation,
+ network::mojom::URLLoaderFactoryRequest* loader_factory_request);
+
static void OnNavigationRequestWillBeSent(
const NavigationRequest& navigation_request);
static void OnNavigationResponseReceived(
@@ -114,7 +120,7 @@ class CONTENT_EXPORT RenderFrameDevToolsAgentHost
~RenderFrameDevToolsAgentHost() override;
// DevToolsAgentHostImpl overrides.
- void AttachSession(DevToolsSession* session) override;
+ bool AttachSession(DevToolsSession* session) override;
void DetachSession(DevToolsSession* session) override;
void InspectElement(RenderFrameHost* frame_host, int x, int y) override;
void DispatchProtocolMessage(DevToolsSession* session,
@@ -133,8 +139,10 @@ class CONTENT_EXPORT RenderFrameDevToolsAgentHost
void DidDetachInterstitialPage() override;
void OnVisibilityChanged(content::Visibility visibility) override;
void DidReceiveCompositorFrame() override;
+ void OnPageScaleFactorChanged(float page_scale_factor) override;
bool IsChildFrame();
+ bool IsFrameHostAllowedForRestrictedSessions();
void OnSwapCompositorFrame(const IPC::Message& message);
void DestroyOnRenderFrameGone();
diff --git a/chromium/content/browser/devtools/service_worker_devtools_agent_host.cc b/chromium/content/browser/devtools/service_worker_devtools_agent_host.cc
index 71ea6f0d4e7..b4886cc9754 100644
--- a/chromium/content/browser/devtools/service_worker_devtools_agent_host.cc
+++ b/chromium/content/browser/devtools/service_worker_devtools_agent_host.cc
@@ -115,7 +115,7 @@ ServiceWorkerDevToolsAgentHost::~ServiceWorkerDevToolsAgentHost() {
ServiceWorkerDevToolsManager::GetInstance()->AgentHostDestroyed(this);
}
-void ServiceWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) {
+bool ServiceWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) {
if (state_ == WORKER_READY) {
if (sessions().size() == 1) {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
@@ -128,6 +128,7 @@ void ServiceWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) {
session->AddHandler(base::WrapUnique(new protocol::InspectorHandler()));
session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(GetId())));
session->AddHandler(base::WrapUnique(new protocol::SchemaHandler()));
+ return true;
}
void ServiceWorkerDevToolsAgentHost::DetachSession(DevToolsSession* session) {
diff --git a/chromium/content/browser/devtools/service_worker_devtools_agent_host.h b/chromium/content/browser/devtools/service_worker_devtools_agent_host.h
index 59af14400fa..456e9938e8e 100644
--- a/chromium/content/browser/devtools/service_worker_devtools_agent_host.h
+++ b/chromium/content/browser/devtools/service_worker_devtools_agent_host.h
@@ -14,7 +14,7 @@
#include "base/unguessable_token.h"
#include "content/browser/devtools/devtools_agent_host_impl.h"
#include "content/browser/devtools/service_worker_devtools_manager.h"
-#include "third_party/WebKit/public/web/devtools_agent.mojom.h"
+#include "third_party/blink/public/web/devtools_agent.mojom.h"
namespace content {
@@ -47,7 +47,7 @@ class ServiceWorkerDevToolsAgentHost : public DevToolsAgentHostImpl {
bool Close() override;
// DevToolsAgentHostImpl overrides.
- void AttachSession(DevToolsSession* session) override;
+ bool AttachSession(DevToolsSession* session) override;
void DetachSession(DevToolsSession* session) override;
void DispatchProtocolMessage(DevToolsSession* session,
const std::string& message) override;
diff --git a/chromium/content/browser/devtools/service_worker_devtools_manager.h b/chromium/content/browser/devtools/service_worker_devtools_manager.h
index a660f6a1410..1018d40705a 100644
--- a/chromium/content/browser/devtools/service_worker_devtools_manager.h
+++ b/chromium/content/browser/devtools/service_worker_devtools_manager.h
@@ -16,7 +16,7 @@
#include "base/observer_list.h"
#include "base/unguessable_token.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/web/devtools_agent.mojom.h"
+#include "third_party/blink/public/web/devtools_agent.mojom.h"
#include "url/gurl.h"
namespace network {
diff --git a/chromium/content/browser/devtools/shared_worker_devtools_agent_host.cc b/chromium/content/browser/devtools/shared_worker_devtools_agent_host.cc
index e4e0d316406..485edd42a67 100644
--- a/chromium/content/browser/devtools/shared_worker_devtools_agent_host.cc
+++ b/chromium/content/browser/devtools/shared_worker_devtools_agent_host.cc
@@ -66,13 +66,14 @@ bool SharedWorkerDevToolsAgentHost::Close() {
return true;
}
-void SharedWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) {
+bool SharedWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) {
session->AddHandler(std::make_unique<protocol::InspectorHandler>());
session->AddHandler(std::make_unique<protocol::NetworkHandler>(GetId()));
session->AddHandler(std::make_unique<protocol::SchemaHandler>());
session->SetRenderer(worker_host_ ? worker_host_->process_id() : -1, nullptr);
if (state_ == WORKER_READY)
session->AttachToAgent(EnsureAgent());
+ return true;
}
void SharedWorkerDevToolsAgentHost::DetachSession(DevToolsSession* session) {
diff --git a/chromium/content/browser/devtools/shared_worker_devtools_agent_host.h b/chromium/content/browser/devtools/shared_worker_devtools_agent_host.h
index 15c5de57b59..6a1d800795b 100644
--- a/chromium/content/browser/devtools/shared_worker_devtools_agent_host.h
+++ b/chromium/content/browser/devtools/shared_worker_devtools_agent_host.h
@@ -8,7 +8,7 @@
#include "base/macros.h"
#include "base/unguessable_token.h"
#include "content/browser/devtools/devtools_agent_host_impl.h"
-#include "third_party/WebKit/public/web/devtools_agent.mojom.h"
+#include "third_party/blink/public/web/devtools_agent.mojom.h"
namespace content {
@@ -33,7 +33,7 @@ class SharedWorkerDevToolsAgentHost : public DevToolsAgentHostImpl {
bool Close() override;
// DevToolsAgentHostImpl overrides.
- void AttachSession(DevToolsSession* session) override;
+ bool AttachSession(DevToolsSession* session) override;
void DetachSession(DevToolsSession* session) override;
void DispatchProtocolMessage(DevToolsSession* session,
const std::string& message) override;
diff --git a/chromium/content/browser/do_not_track_browsertest.cc b/chromium/content/browser/do_not_track_browsertest.cc
new file mode 100644
index 00000000000..c09c64f7a5b
--- /dev/null
+++ b/chromium/content/browser/do_not_track_browsertest.cc
@@ -0,0 +1,89 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/public/browser/web_contents.h"
+#include "content/public/common/renderer_preferences.h"
+#include "content/public/test/browser_test_utils.h"
+#include "content/public/test/content_browser_test.h"
+#include "content/public/test/content_browser_test_utils.h"
+#include "content/shell/browser/shell.h"
+#include "net/test/embedded_test_server/embedded_test_server.h"
+
+namespace content {
+
+namespace {
+
+class DoNotTrackTest : public ContentBrowserTest {
+ protected:
+ void EnableDoNotTrack() {
+ RendererPreferences* prefs =
+ shell()->web_contents()->GetMutableRendererPrefs();
+ EXPECT_FALSE(prefs->enable_do_not_track);
+ prefs->enable_do_not_track = true;
+ }
+
+ void ExpectPageTextEq(const std::string& expected_content) {
+ std::string text;
+ ASSERT_TRUE(ExecuteScriptAndExtractString(
+ shell(),
+ "window.domAutomationController.send(document.body.innerText);",
+ &text));
+ EXPECT_EQ(expected_content, text);
+ }
+
+ std::string GetDOMDoNotTrackProperty() {
+ std::string value;
+ EXPECT_TRUE(ExecuteScriptAndExtractString(
+ shell(),
+ "window.domAutomationController.send("
+ " navigator.doNotTrack === null ? '' : navigator.doNotTrack)",
+ &value));
+ return value;
+ }
+};
+
+// Checks that the DNT header is not sent by default.
+IN_PROC_BROWSER_TEST_F(DoNotTrackTest, NotEnabled) {
+ ASSERT_TRUE(embedded_test_server()->Start());
+ GURL url = embedded_test_server()->GetURL("/echoheader?DNT");
+ EXPECT_TRUE(NavigateToURL(shell(), url));
+ ExpectPageTextEq("None");
+ // And the DOM property is not set.
+ EXPECT_EQ("", GetDOMDoNotTrackProperty());
+}
+
+// Checks that the DNT header is sent when the corresponding preference is set.
+IN_PROC_BROWSER_TEST_F(DoNotTrackTest, Simple) {
+ ASSERT_TRUE(embedded_test_server()->Start());
+ EnableDoNotTrack();
+ GURL url = embedded_test_server()->GetURL("/echoheader?DNT");
+ EXPECT_TRUE(NavigateToURL(shell(), url));
+ ExpectPageTextEq("1");
+}
+
+// Checks that the DNT header is preserved during redirects.
+IN_PROC_BROWSER_TEST_F(DoNotTrackTest, Redirect) {
+ ASSERT_TRUE(embedded_test_server()->Start());
+ GURL final_url = embedded_test_server()->GetURL("/echoheader?DNT");
+ GURL url = embedded_test_server()->GetURL(std::string("/server-redirect?") +
+ final_url.spec());
+ EnableDoNotTrack();
+ // We don't check the result NavigateToURL as it returns true only if the
+ // final URL is equal to the passed URL.
+ NavigateToURL(shell(), url);
+ ExpectPageTextEq("1");
+}
+
+// Checks that the DOM property is set when the corresponding preference is set.
+IN_PROC_BROWSER_TEST_F(DoNotTrackTest, DOMProperty) {
+ ASSERT_TRUE(embedded_test_server()->Start());
+ GURL url = embedded_test_server()->GetURL("/echo");
+ EnableDoNotTrack();
+ EXPECT_TRUE(NavigateToURL(shell(), url));
+ EXPECT_EQ("1", GetDOMDoNotTrackProperty());
+}
+
+} // namespace
+
+} // namespace content \ No newline at end of file
diff --git a/chromium/content/browser/dom_storage/dom_storage_browsertest.cc b/chromium/content/browser/dom_storage/dom_storage_browsertest.cc
index 849804be4ff..61f3ebdb64a 100644
--- a/chromium/content/browser/dom_storage/dom_storage_browsertest.cc
+++ b/chromium/content/browser/dom_storage/dom_storage_browsertest.cc
@@ -14,6 +14,7 @@
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/common/dom_storage/dom_storage_types.h"
#include "content/public/browser/browser_context.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/local_storage_usage_info.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/common/content_paths.h"
diff --git a/chromium/content/browser/dom_storage/dom_storage_context_impl.cc b/chromium/content/browser/dom_storage/dom_storage_context_impl.cc
index e47e04b9d9d..f8e1b0ec7ad 100644
--- a/chromium/content/browser/dom_storage/dom_storage_context_impl.cc
+++ b/chromium/content/browser/dom_storage/dom_storage_context_impl.cc
@@ -414,7 +414,7 @@ bool DOMStorageContextImpl::OnMemoryDump(
DOMStorageNamespace::UsageStatistics total_stats =
GetTotalNamespaceStatistics(namespaces_);
auto* mad = pmd->CreateAllocatorDump(base::StringPrintf(
- "site_storage/session_storage_0x%" PRIXPTR "/cache_size",
+ "site_storage/session_storage/0x%" PRIXPTR "/cache_size",
reinterpret_cast<uintptr_t>(this)));
mad->AddScalar(base::trace_event::MemoryAllocatorDump::kNameSize,
base::trace_event::MemoryAllocatorDump::kUnitsBytes,
diff --git a/chromium/content/browser/dom_storage/dom_storage_context_wrapper.cc b/chromium/content/browser/dom_storage/dom_storage_context_wrapper.cc
index 247cb69030e..8089997ca7b 100644
--- a/chromium/content/browser/dom_storage/dom_storage_context_wrapper.cc
+++ b/chromium/content/browser/dom_storage/dom_storage_context_wrapper.cc
@@ -15,7 +15,6 @@
#include "base/files/file_path.h"
#include "base/location.h"
#include "base/memory/memory_coordinator_client_registry.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/weak_ptr.h"
#include "base/sequenced_task_runner.h"
#include "base/single_thread_task_runner.h"
@@ -28,6 +27,7 @@
#include "content/browser/dom_storage/local_storage_context_mojo.h"
#include "content/browser/dom_storage/session_storage_context_mojo.h"
#include "content/browser/dom_storage/session_storage_namespace_impl.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/local_storage_usage_info.h"
#include "content/public/browser/session_storage_usage_info.h"
@@ -85,7 +85,7 @@ void CollectLocalStorageUsage(
base::Closure done_callback,
const std::vector<LocalStorageUsageInfo>& in_info) {
out_info->insert(out_info->end(), in_info.begin(), in_info.end());
- done_callback.Run();
+ std::move(done_callback).Run();
}
void GotMojoDeletionCallback(
@@ -180,7 +180,7 @@ void DOMStorageContextWrapper::GetLocalStorageUsage(
2, base::BindOnce(&InvokeLocalStorageUsageCallbackHelper, callback,
std::move(infos)));
auto collect_callback = base::BindRepeating(
- CollectLocalStorageUsage, infos_ptr, got_local_storage_usage);
+ CollectLocalStorageUsage, infos_ptr, std::move(got_local_storage_usage));
// base::Unretained is safe here, because the mojo_state_ won't be deleted
// until a ShutdownAndDelete task has been ran on the mojo_task_runner_, and
// as soon as that task is posted, mojo_state_ is set to null, preventing
@@ -195,7 +195,8 @@ void DOMStorageContextWrapper::GetLocalStorageUsage(
context_->task_runner()->PostShutdownBlockingTask(
FROM_HERE, DOMStorageTaskRunner::PRIMARY_SEQUENCE,
base::BindOnce(&GetLegacyLocalStorageUsage, legacy_localstorage_path_,
- base::ThreadTaskRunnerHandle::Get(), collect_callback));
+ base::ThreadTaskRunnerHandle::Get(),
+ std::move(collect_callback)));
}
void DOMStorageContextWrapper::GetSessionStorageUsage(
@@ -259,7 +260,8 @@ void DOMStorageContextWrapper::DeleteSessionStorage(
mojo_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&SessionStorageContextMojo::DeleteStorage,
base::Unretained(mojo_session_state_),
- usage_info.origin, usage_info.namespace_id));
+ url::Origin::Create(usage_info.origin),
+ usage_info.namespace_id));
return;
}
DCHECK(context_.get());
@@ -303,6 +305,12 @@ void DOMStorageContextWrapper::SetForceKeepSessionState() {
FROM_HERE,
base::BindOnce(&LocalStorageContextMojo::SetForceKeepSessionState,
base::Unretained(mojo_state_)));
+ if (mojo_session_state_) {
+ mojo_task_runner_->PostTask(
+ FROM_HERE,
+ base::BindOnce(&SessionStorageContextMojo::SetForceKeepSessionState,
+ base::Unretained(mojo_session_state_)));
+ }
}
void DOMStorageContextWrapper::Shutdown() {
diff --git a/chromium/content/browser/dom_storage/dom_storage_context_wrapper.h b/chromium/content/browser/dom_storage/dom_storage_context_wrapper.h
index 5188c48c81f..0f2e85e9224 100644
--- a/chromium/content/browser/dom_storage/dom_storage_context_wrapper.h
+++ b/chromium/content/browser/dom_storage/dom_storage_context_wrapper.h
@@ -86,18 +86,18 @@ class CONTENT_EXPORT DOMStorageContextWrapper
void SetLocalStorageDatabaseForTesting(
leveldb::mojom::LevelDBDatabaseAssociatedPtr database);
+ SessionStorageContextMojo* mojo_session_state() {
+ return mojo_session_state_;
+ }
+
private:
friend class DOMStorageMessageFilter; // for access to context()
friend class SessionStorageNamespaceImpl; // ditto
- friend class DOMStorageSession; // ditto
friend class base::RefCountedThreadSafe<DOMStorageContextWrapper>;
friend class DOMStorageBrowserTest;
~DOMStorageContextWrapper() override;
DOMStorageContextImpl* context() const { return context_.get(); }
- SessionStorageContextMojo* mojo_session_state() {
- return mojo_session_state_;
- }
base::SequencedTaskRunner* mojo_task_runner() {
return mojo_task_runner_.get();
diff --git a/chromium/content/browser/dom_storage/dom_storage_message_filter.cc b/chromium/content/browser/dom_storage/dom_storage_message_filter.cc
index dbadd773489..33c9163f090 100644
--- a/chromium/content/browser/dom_storage/dom_storage_message_filter.cc
+++ b/chromium/content/browser/dom_storage/dom_storage_message_filter.cc
@@ -15,6 +15,7 @@
#include "content/browser/dom_storage/dom_storage_namespace.h"
#include "content/browser/dom_storage/dom_storage_task_runner.h"
#include "content/common/dom_storage/dom_storage_messages.h"
+#include "content/public/browser/browser_thread.h"
#include "url/gurl.h"
namespace content {
diff --git a/chromium/content/browser/dom_storage/dom_storage_session.cc b/chromium/content/browser/dom_storage/dom_storage_session.cc
deleted file mode 100644
index af607879567..00000000000
--- a/chromium/content/browser/dom_storage/dom_storage_session.cc
+++ /dev/null
@@ -1,164 +0,0 @@
-// Copyright 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/dom_storage/dom_storage_session.h"
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/logging.h"
-#include "base/memory/ptr_util.h"
-#include "base/single_thread_task_runner.h"
-#include "content/browser/dom_storage/dom_storage_context_impl.h"
-#include "content/browser/dom_storage/dom_storage_context_wrapper.h"
-#include "content/browser/dom_storage/dom_storage_task_runner.h"
-#include "content/browser/dom_storage/session_storage_context_mojo.h"
-#include "content/common/dom_storage/dom_storage_namespace_ids.h"
-#include "content/public/common/content_features.h"
-
-namespace content {
-
-// Constructed on thread that constructs DOMStorageSession. Used & destroyed on
-// the mojo task runner that the |mojo_context_| runs on.
-class DOMStorageSession::SequenceHelper {
- public:
- SequenceHelper(SessionStorageContextMojo* context_wrapper)
- : context_wrapper_(context_wrapper) {}
- ~SequenceHelper() = default;
-
- void CreateSessionNamespace(const std::string& namespace_id) {
- context_wrapper_->CreateSessionNamespace(namespace_id);
- }
-
- void CloneSessionNamespace(const std::string& namespace_id_to_clone,
- const std::string& clone_namespace_id) {
- context_wrapper_->CloneSessionNamespace(namespace_id_to_clone,
- clone_namespace_id);
- }
-
- void DeleteSessionNamespace(const std::string& namespace_id,
- bool should_persist) {
- context_wrapper_->DeleteSessionNamespace(namespace_id, should_persist);
- }
-
- private:
- SessionStorageContextMojo* context_wrapper_;
-};
-
-// static
-std::unique_ptr<DOMStorageSession> DOMStorageSession::Create(
- scoped_refptr<DOMStorageContextWrapper> context) {
- return DOMStorageSession::CreateWithNamespace(
- std::move(context), AllocateSessionStorageNamespaceId());
-}
-
-// static
-std::unique_ptr<DOMStorageSession> DOMStorageSession::CreateWithNamespace(
- scoped_refptr<DOMStorageContextWrapper> context,
- const std::string& namespace_id) {
- if (context->mojo_session_state()) {
- DCHECK(base::FeatureList::IsEnabled(features::kMojoSessionStorage));
- std::unique_ptr<DOMStorageSession> result = base::WrapUnique(
- new DOMStorageSession(std::move(context), namespace_id));
- result->mojo_task_runner_->PostTask(
- FROM_HERE,
- base::BindOnce(&SequenceHelper::CreateSessionNamespace,
- base::Unretained(result->sequence_helper_.get()),
- result->namespace_id_));
- return result;
- }
- scoped_refptr<DOMStorageContextImpl> context_impl = context->context();
- context_impl->task_runner()->PostTask(
- FROM_HERE, base::BindOnce(&DOMStorageContextImpl::CreateSessionNamespace,
- context_impl, namespace_id));
- return std::unique_ptr<DOMStorageSession>(new DOMStorageSession(
- std::move(context), std::move(context_impl), namespace_id));
-}
-
-// static
-std::unique_ptr<DOMStorageSession> DOMStorageSession::CloneFrom(
- scoped_refptr<DOMStorageContextWrapper> context,
- std::string namepace_id,
- const std::string& namespace_id_to_clone) {
- if (context->mojo_session_state()) {
- DCHECK(base::FeatureList::IsEnabled(features::kMojoSessionStorage));
- std::unique_ptr<DOMStorageSession> result = base::WrapUnique(
- new DOMStorageSession(std::move(context), std::move(namepace_id)));
-
- result->mojo_task_runner_->PostTask(
- FROM_HERE,
- base::BindOnce(&SequenceHelper::CloneSessionNamespace,
- base::Unretained(result->sequence_helper_.get()),
- namespace_id_to_clone, result->namespace_id_));
- return result;
- }
- scoped_refptr<DOMStorageContextImpl> context_impl = context->context();
- context_impl->task_runner()->PostTask(
- FROM_HERE,
- base::BindOnce(&DOMStorageContextImpl::CloneSessionNamespace,
- context_impl, namespace_id_to_clone, namepace_id));
- return std::unique_ptr<DOMStorageSession>(new DOMStorageSession(
- std::move(context), std::move(context_impl), std::move(namepace_id)));
-}
-
-void DOMStorageSession::SetShouldPersist(bool should_persist) {
- should_persist_ = should_persist;
-}
-
-bool DOMStorageSession::should_persist() const {
- return should_persist_;
-}
-
-bool DOMStorageSession::IsFromContext(DOMStorageContextWrapper* context) {
- return context_wrapper_.get() == context;
-}
-
-std::unique_ptr<DOMStorageSession> DOMStorageSession::Clone() {
- return CloneFrom(context_wrapper_, AllocateSessionStorageNamespaceId(),
- namespace_id_);
-}
-
-DOMStorageSession::DOMStorageSession(
- scoped_refptr<DOMStorageContextWrapper> context_wrapper,
- scoped_refptr<DOMStorageContextImpl> context,
- std::string namespace_id)
- : context_(std::move(context)),
- context_wrapper_(std::move(context_wrapper)),
- namespace_id_(std::move(namespace_id)),
- should_persist_(false) {
- DCHECK(!base::FeatureList::IsEnabled(features::kMojoSessionStorage));
-}
-
-DOMStorageSession::DOMStorageSession(
- scoped_refptr<DOMStorageContextWrapper> context,
- std::string namespace_id)
- : context_wrapper_(std::move(context)),
- mojo_task_runner_(context_wrapper_->mojo_task_runner()),
- namespace_id_(std::move(namespace_id)),
- should_persist_(false),
- sequence_helper_(std::make_unique<SequenceHelper>(
- context_wrapper_->mojo_session_state())) {
- DCHECK(base::FeatureList::IsEnabled(features::kMojoSessionStorage));
-}
-
-DOMStorageSession::~DOMStorageSession() {
- DCHECK(!!context_ || !!sequence_helper_);
- if (context_) {
- context_->task_runner()->PostTask(
- FROM_HERE,
- base::BindOnce(&DOMStorageContextImpl::DeleteSessionNamespace, context_,
- namespace_id_, should_persist_));
- }
- if (sequence_helper_) {
- mojo_task_runner_->PostTask(
- FROM_HERE, base::BindOnce(&SequenceHelper::DeleteSessionNamespace,
- base::Unretained(sequence_helper_.get()),
- namespace_id_, should_persist_));
- mojo_task_runner_->DeleteSoon(FROM_HERE, std::move(sequence_helper_));
- context_wrapper_->AddRef();
- if (!mojo_task_runner_->ReleaseSoon(FROM_HERE, context_wrapper_.get()))
- context_wrapper_->Release();
- }
-}
-
-} // namespace content
diff --git a/chromium/content/browser/dom_storage/dom_storage_session.h b/chromium/content/browser/dom_storage/dom_storage_session.h
deleted file mode 100644
index 83bda92989e..00000000000
--- a/chromium/content/browser/dom_storage/dom_storage_session.h
+++ /dev/null
@@ -1,86 +0,0 @@
-// Copyright 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_DOM_STORAGE_DOM_STORAGE_SESSION_H_
-#define CONTENT_BROWSER_DOM_STORAGE_DOM_STORAGE_SESSION_H_
-
-#include <stdint.h>
-
-#include <memory>
-#include <string>
-
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/memory/weak_ptr.h"
-#include "content/common/content_export.h"
-
-namespace base {
-class SequencedTaskRunner;
-}
-
-namespace content {
-
-class DOMStorageContextImpl;
-class DOMStorageContextWrapper;
-
-// This class determines the lifetime of a session storage namespace and
-// provides an interface to Clone() an existing session storage namespace. It
-// may be used on any thread. See class comments for DOMStorageContextImpl for a
-// larger overview.
-class CONTENT_EXPORT DOMStorageSession {
- public:
- // Constructs a |DOMStorageSession| and allocates a new ID for it.
- static std::unique_ptr<DOMStorageSession> Create(
- scoped_refptr<DOMStorageContextWrapper> context);
-
- // Constructs a |DOMStorageSession| and assigns |namespace_id|
- // to it.
- static std::unique_ptr<DOMStorageSession> CreateWithNamespace(
- scoped_refptr<DOMStorageContextWrapper> context,
- const std::string& namespace_id);
-
- // Constructs a |DOMStorageSession| with id |namespace_id| by cloning
- // |namespace_id_to_clone|.
- static std::unique_ptr<DOMStorageSession> CloneFrom(
- scoped_refptr<DOMStorageContextWrapper> context,
- std::string namepace_id,
- const std::string& namepace_id_to_clone);
-
- ~DOMStorageSession();
-
- const std::string& namespace_id() const { return namespace_id_; }
- void SetShouldPersist(bool should_persist);
- bool should_persist() const;
- DOMStorageContextWrapper* context() const { return context_wrapper_.get(); }
- bool IsFromContext(DOMStorageContextWrapper* context);
-
- std::unique_ptr<DOMStorageSession> Clone();
-
- private:
- class SequenceHelper;
-
- // Creates the non-mojo version.
- DOMStorageSession(scoped_refptr<DOMStorageContextWrapper> context_wrapper,
- scoped_refptr<DOMStorageContextImpl> context_impl,
- std::string namespace_id);
- // Creates a mojo version.
- DOMStorageSession(scoped_refptr<DOMStorageContextWrapper> context,
- std::string namespace_id);
-
- scoped_refptr<DOMStorageContextImpl> context_;
- scoped_refptr<DOMStorageContextWrapper> context_wrapper_;
- scoped_refptr<base::SequencedTaskRunner> mojo_task_runner_;
- std::string namespace_id_;
- bool should_persist_;
-
- // Contructed on constructing thread of DOMStorageSession, used and destroyed
- // on |mojo_task_runner_|.
- std::unique_ptr<SequenceHelper> sequence_helper_;
-
- DISALLOW_IMPLICIT_CONSTRUCTORS(DOMStorageSession);
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_DOM_STORAGE_DOM_STORAGE_SESSION_H_
diff --git a/chromium/content/browser/dom_storage/local_storage_context_mojo.cc b/chromium/content/browser/dom_storage/local_storage_context_mojo.cc
index 7193a33dfb9..c6975829bbe 100644
--- a/chromium/content/browser/dom_storage/local_storage_context_mojo.cc
+++ b/chromium/content/browser/dom_storage/local_storage_context_mojo.cc
@@ -5,9 +5,14 @@
#include "content/browser/dom_storage/local_storage_context_mojo.h"
#include <inttypes.h>
+
+#include <algorithm>
#include <cctype> // for std::isalnum
+#include <set>
+#include <string>
+#include <utility>
+
#include "base/barrier_closure.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/single_thread_task_runner.h"
@@ -16,8 +21,8 @@
#include "base/sys_info.h"
#include "base/trace_event/memory_dump_manager.h"
#include "build/build_config.h"
-#include "components/leveldb/public/cpp/util.h"
-#include "components/leveldb/public/interfaces/leveldb.mojom.h"
+#include "components/services/leveldb/public/cpp/util.h"
+#include "components/services/leveldb/public/interfaces/leveldb.mojom.h"
#include "content/browser/dom_storage/dom_storage_area.h"
#include "content/browser/dom_storage/dom_storage_database.h"
#include "content/browser/dom_storage/dom_storage_task_runner.h"
@@ -103,8 +108,8 @@ void MigrateStorageHelper(
(*values)[LocalStorageContextMojo::MigrateString(it.first)] =
LocalStorageContextMojo::MigrateString(it.second.string());
}
- reply_task_runner->PostTask(FROM_HERE,
- base::BindOnce(callback, std::move(values)));
+ reply_task_runner->PostTask(
+ FROM_HERE, base::BindOnce(std::move(callback), std::move(values)));
}
// Helper to convert from OnceCallback to Callback.
@@ -564,7 +569,7 @@ bool LocalStorageContextMojo::OnMemoryDump(
return true;
std::string context_name =
- base::StringPrintf("site_storage/localstorage_0x%" PRIXPTR,
+ base::StringPrintf("site_storage/localstorage/0x%" PRIXPTR,
reinterpret_cast<uintptr_t>(this));
// Account for leveldb memory usage, which actually lives in the file service.
@@ -680,13 +685,11 @@ void LocalStorageContextMojo::InitiateConnection(bool in_memory_only) {
}
}
-void LocalStorageContextMojo::OnDirectoryOpened(
- filesystem::mojom::FileError err) {
- if (err != filesystem::mojom::FileError::OK) {
+void LocalStorageContextMojo::OnDirectoryOpened(base::File::Error err) {
+ if (err != base::File::Error::FILE_OK) {
// We failed to open the directory; continue with startup so that we create
// the |level_db_wrappers_|.
- UMA_HISTOGRAM_ENUMERATION("LocalStorageContext.DirectoryOpenError",
- -static_cast<base::File::Error>(err),
+ UMA_HISTOGRAM_ENUMERATION("LocalStorageContext.DirectoryOpenError", -err,
-base::File::FILE_ERROR_MAX);
LogDatabaseOpenResult(OpenResult::DIRECTORY_OPEN_FAILED);
OnDatabaseOpened(false, leveldb::mojom::DatabaseError::OK);
diff --git a/chromium/content/browser/dom_storage/local_storage_context_mojo.h b/chromium/content/browser/dom_storage/local_storage_context_mojo.h
index b7df333fbd7..2d7799a7920 100644
--- a/chromium/content/browser/dom_storage/local_storage_context_mojo.h
+++ b/chromium/content/browser/dom_storage/local_storage_context_mojo.h
@@ -107,7 +107,7 @@ class CONTENT_EXPORT LocalStorageContextMojo
// Part of our asynchronous directory opening called from RunWhenConnected().
void InitiateConnection(bool in_memory_only = false);
- void OnDirectoryOpened(filesystem::mojom::FileError err);
+ void OnDirectoryOpened(base::File::Error err);
void OnDatabaseOpened(bool in_memory, leveldb::mojom::DatabaseError status);
void OnGotDatabaseVersion(leveldb::mojom::DatabaseError status,
const std::vector<uint8_t>& value);
diff --git a/chromium/content/browser/dom_storage/local_storage_context_mojo_unittest.cc b/chromium/content/browser/dom_storage/local_storage_context_mojo_unittest.cc
index 4687ad5d478..1603bdb3282 100644
--- a/chromium/content/browser/dom_storage/local_storage_context_mojo_unittest.cc
+++ b/chromium/content/browser/dom_storage/local_storage_context_mojo_unittest.cc
@@ -11,8 +11,8 @@
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
-#include "components/filesystem/public/interfaces/file_system.mojom.h"
-#include "components/leveldb/public/cpp/util.h"
+#include "components/services/filesystem/public/interfaces/file_system.mojom.h"
+#include "components/services/leveldb/public/cpp/util.h"
#include "content/browser/dom_storage/dom_storage_area.h"
#include "content/browser/dom_storage/dom_storage_context_impl.h"
#include "content/browser/dom_storage/dom_storage_database.h"
diff --git a/chromium/content/browser/dom_storage/session_storage_context_mojo.cc b/chromium/content/browser/dom_storage/session_storage_context_mojo.cc
index c31359878c1..1297a78569c 100644
--- a/chromium/content/browser/dom_storage/session_storage_context_mojo.cc
+++ b/chromium/content/browser/dom_storage/session_storage_context_mojo.cc
@@ -63,7 +63,7 @@ void SessionStorageContextMojo::GetStorageUsage(
NOTREACHED();
}
void SessionStorageContextMojo::DeleteStorage(
- const GURL& origin,
+ const url::Origin& origin,
const std::string& persistent_namespace_id) {
NOTREACHED();
}
diff --git a/chromium/content/browser/dom_storage/session_storage_context_mojo.h b/chromium/content/browser/dom_storage/session_storage_context_mojo.h
index 078bcdde09e..919c1356d22 100644
--- a/chromium/content/browser/dom_storage/session_storage_context_mojo.h
+++ b/chromium/content/browser/dom_storage/session_storage_context_mojo.h
@@ -54,8 +54,14 @@ class CONTENT_EXPORT SessionStorageContextMojo {
bool should_persist);
void Flush();
+ // Used by content settings to alter the behavior around
+ // what data to keep and what data to discard at shutdown.
+ // The policy is not so straight forward to describe, see
+ // the implementation for details.
+ void SetForceKeepSessionState() { force_keep_session_state_ = true; }
+
void GetStorageUsage(GetStorageUsageCallback callback);
- void DeleteStorage(const GURL& origin,
+ void DeleteStorage(const url::Origin& origin,
const std::string& persistent_namespace_id);
// Called when the owning BrowserContext is ending.
@@ -80,6 +86,8 @@ class CONTENT_EXPORT SessionStorageContextMojo {
const base::Optional<base::FilePath> partition_directory_path_;
std::string leveldb_name_;
+ bool force_keep_session_state_ = false;
+
base::WeakPtrFactory<SessionStorageContextMojo> weak_ptr_factory_;
};
diff --git a/chromium/content/browser/dom_storage/session_storage_database.cc b/chromium/content/browser/dom_storage/session_storage_database.cc
index 2717a141024..ef35996152a 100644
--- a/chromium/content/browser/dom_storage/session_storage_database.cc
+++ b/chromium/content/browser/dom_storage/session_storage_database.cc
@@ -390,7 +390,7 @@ void SessionStorageDatabase::OnMemoryDump(
return;
auto* mad = pmd->CreateAllocatorDump(
- base::StringPrintf("site_storage/session_storage_0x%" PRIXPTR,
+ base::StringPrintf("site_storage/session_storage/0x%" PRIXPTR,
reinterpret_cast<uintptr_t>(this)));
pmd->AddOwnershipEdge(mad->guid(), tracker_dump->guid());
mad->AddScalar(base::trace_event::MemoryAllocatorDump::kNameSize,
diff --git a/chromium/content/browser/dom_storage/session_storage_namespace_impl.cc b/chromium/content/browser/dom_storage/session_storage_namespace_impl.cc
index d159c20c69d..484118b1826 100644
--- a/chromium/content/browser/dom_storage/session_storage_namespace_impl.cc
+++ b/chromium/content/browser/dom_storage/session_storage_namespace_impl.cc
@@ -6,73 +6,164 @@
#include <utility>
+#include "base/bind.h"
+#include "base/callback_helpers.h"
+#include "base/logging.h"
+#include "base/memory/ptr_util.h"
+#include "base/sequenced_task_runner.h"
+#include "content/browser/dom_storage/dom_storage_context_impl.h"
#include "content/browser/dom_storage/dom_storage_context_wrapper.h"
-#include "content/browser/dom_storage/dom_storage_session.h"
+#include "content/browser/dom_storage/dom_storage_task_runner.h"
#include "content/browser/dom_storage/session_storage_context_mojo.h"
+#include "content/common/dom_storage/dom_storage_namespace_ids.h"
+#include "content/public/browser/browser_thread.h"
+#include "content/public/common/content_features.h"
namespace content {
// static
scoped_refptr<SessionStorageNamespaceImpl> SessionStorageNamespaceImpl::Create(
scoped_refptr<DOMStorageContextWrapper> context) {
- return base::WrapRefCounted(new SessionStorageNamespaceImpl(
- DOMStorageSession::Create(std::move(context))));
+ return SessionStorageNamespaceImpl::Create(
+ std::move(context), AllocateSessionStorageNamespaceId());
}
// static
scoped_refptr<SessionStorageNamespaceImpl> SessionStorageNamespaceImpl::Create(
scoped_refptr<DOMStorageContextWrapper> context,
- const std::string& namepace_id) {
+ std::string namespace_id) {
scoped_refptr<SessionStorageNamespaceImpl> existing =
- context->MaybeGetExistingNamespace(namepace_id);
- if (!existing) {
- existing = base::WrapRefCounted(
- new SessionStorageNamespaceImpl(DOMStorageSession::CreateWithNamespace(
- std::move(context), namepace_id)));
+ context->MaybeGetExistingNamespace(namespace_id);
+ if (existing)
+ return existing;
+ if (context->mojo_session_state()) {
+ DCHECK(base::FeatureList::IsEnabled(features::kMojoSessionStorage));
+ auto result = base::WrapRefCounted(
+ new SessionStorageNamespaceImpl(context, std::move(namespace_id)));
+ result->mojo_task_runner_->PostTask(
+ FROM_HERE,
+ base::BindOnce(&SessionStorageContextMojo::CreateSessionNamespace,
+ base::Unretained(context->mojo_session_state()),
+ result->namespace_id_));
+ return result;
}
- return existing;
+ scoped_refptr<DOMStorageContextImpl> context_impl = context->context();
+ context_impl->task_runner()->PostTask(
+ FROM_HERE, base::BindOnce(&DOMStorageContextImpl::CreateSessionNamespace,
+ context_impl, namespace_id));
+ return base::WrapRefCounted(new SessionStorageNamespaceImpl(
+ std::move(context), std::move(context_impl), std::move(namespace_id)));
}
// static
scoped_refptr<SessionStorageNamespaceImpl>
SessionStorageNamespaceImpl::CloneFrom(
scoped_refptr<DOMStorageContextWrapper> context,
- std::string namepace_id,
- const std::string& namepace_id_to_clone) {
- return base::WrapRefCounted(
- new SessionStorageNamespaceImpl(DOMStorageSession::CloneFrom(
- std::move(context), std::move(namepace_id), namepace_id_to_clone)));
+ std::string namespace_id,
+ const std::string& namespace_id_to_clone) {
+ if (context->mojo_session_state()) {
+ DCHECK(base::FeatureList::IsEnabled(features::kMojoSessionStorage));
+ auto result = base::WrapRefCounted(
+ new SessionStorageNamespaceImpl(context, std::move(namespace_id)));
+ result->mojo_task_runner_->PostTask(
+ FROM_HERE,
+ base::BindOnce(&SessionStorageContextMojo::CloneSessionNamespace,
+ base::Unretained(context->mojo_session_state()),
+ namespace_id_to_clone, result->namespace_id_));
+ return result;
+ }
+ scoped_refptr<DOMStorageContextImpl> context_impl = context->context();
+ context_impl->task_runner()->PostTask(
+ FROM_HERE,
+ base::BindOnce(&DOMStorageContextImpl::CloneSessionNamespace,
+ context_impl, namespace_id_to_clone, namespace_id));
+ return base::WrapRefCounted(new SessionStorageNamespaceImpl(
+ std::move(context), std::move(context_impl), std::move(namespace_id)));
}
const std::string& SessionStorageNamespaceImpl::id() const {
- return session_->namespace_id();
+ return namespace_id_;
}
void SessionStorageNamespaceImpl::SetShouldPersist(bool should_persist) {
- session_->SetShouldPersist(should_persist);
+ should_persist_ = should_persist;
}
bool SessionStorageNamespaceImpl::should_persist() const {
- return session_->should_persist();
+ return should_persist_;
}
-SessionStorageNamespaceImpl* SessionStorageNamespaceImpl::Clone() {
- return new SessionStorageNamespaceImpl(session_->Clone());
+scoped_refptr<SessionStorageNamespaceImpl>
+SessionStorageNamespaceImpl::Clone() {
+ return CloneFrom(context_wrapper_, AllocateSessionStorageNamespaceId(),
+ namespace_id_);
}
bool SessionStorageNamespaceImpl::IsFromContext(
DOMStorageContextWrapper* context) {
- return session_->IsFromContext(context);
+ return context_wrapper_.get() == context;
}
SessionStorageNamespaceImpl::SessionStorageNamespaceImpl(
- std::unique_ptr<DOMStorageSession> session)
- : session_(std::move(session)) {
- session_->context()->AddNamespace(session_->namespace_id(), this);
+ scoped_refptr<DOMStorageContextWrapper> context_wrapper,
+ scoped_refptr<DOMStorageContextImpl> context,
+ std::string namespace_id)
+ : context_(std::move(context)),
+ context_wrapper_(std::move(context_wrapper)),
+ namespace_id_(std::move(namespace_id)),
+ should_persist_(false) {
+ context_wrapper_->AddNamespace(namespace_id_, this);
+ DCHECK(!base::FeatureList::IsEnabled(features::kMojoSessionStorage));
+}
+
+SessionStorageNamespaceImpl::SessionStorageNamespaceImpl(
+ scoped_refptr<DOMStorageContextWrapper> context,
+ std::string namespace_id)
+ : context_wrapper_(std::move(context)),
+ mojo_task_runner_(context_wrapper_->mojo_task_runner()),
+ namespace_id_(std::move(namespace_id)),
+ should_persist_(false) {
+ context_wrapper_->AddNamespace(namespace_id_, this);
+ DCHECK(base::FeatureList::IsEnabled(features::kMojoSessionStorage));
}
SessionStorageNamespaceImpl::~SessionStorageNamespaceImpl() {
- session_->context()->RemoveNamespace(session_->namespace_id());
+ DCHECK(context_ || mojo_task_runner_);
+ context_wrapper_->RemoveNamespace(namespace_id_);
+ if (context_) {
+ context_->task_runner()->PostTask(
+ FROM_HERE,
+ base::BindOnce(&DOMStorageContextImpl::DeleteSessionNamespace, context_,
+ namespace_id_, should_persist_));
+ }
+ if (IsMojoSessionStorage()) {
+ base::ScopedClosureRunner deleteNamespaceRunner =
+ base::ScopedClosureRunner(base::BindOnce(
+ &SessionStorageNamespaceImpl::DeleteSessionNamespaceFromUIThread,
+ std::move(mojo_task_runner_), std::move(context_wrapper_),
+ std::move(namespace_id_), should_persist_));
+ if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
+ // If this fails to post then that's fine, as the mojo state should
+ // already be destructed.
+ BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
+ deleteNamespaceRunner.Release());
+ }
+ }
+}
+
+// static
+void SessionStorageNamespaceImpl::DeleteSessionNamespaceFromUIThread(
+ scoped_refptr<base::SequencedTaskRunner> mojo_task_runner,
+ scoped_refptr<DOMStorageContextWrapper> context_wrapper,
+ std::string namespace_id,
+ bool should_persist) {
+ if (context_wrapper->mojo_session_state()) {
+ mojo_task_runner->PostTask(
+ FROM_HERE,
+ base::BindOnce(&SessionStorageContextMojo::DeleteSessionNamespace,
+ base::Unretained(context_wrapper->mojo_session_state()),
+ namespace_id, should_persist));
+ }
}
} // namespace content
diff --git a/chromium/content/browser/dom_storage/session_storage_namespace_impl.h b/chromium/content/browser/dom_storage/session_storage_namespace_impl.h
index 2b6a7c4420d..8278286e086 100644
--- a/chromium/content/browser/dom_storage/session_storage_namespace_impl.h
+++ b/chromium/content/browser/dom_storage/session_storage_namespace_impl.h
@@ -7,15 +7,21 @@
#include <stdint.h>
+#include <memory>
+#include <string>
+
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "content/common/content_export.h"
#include "content/public/browser/session_storage_namespace.h"
-namespace content {
+namespace base {
+class SequencedTaskRunner;
+}
+namespace content {
+class DOMStorageContextImpl;
class DOMStorageContextWrapper;
-class DOMStorageSession;
class SessionStorageNamespaceImpl : public SessionStorageNamespace {
public:
@@ -27,32 +33,53 @@ class SessionStorageNamespaceImpl : public SessionStorageNamespace {
// If there is an existing SessionStorageNamespaceImpl with the given id in
// the DOMStorageContextWrapper, this will return that object. Otherwise this
- // constructs a SessionStorageNamespaceImpl and assigns |namepace_id| to it.
+ // constructs a SessionStorageNamespaceImpl and assigns |namespace_id| to it.
static scoped_refptr<SessionStorageNamespaceImpl> Create(
scoped_refptr<DOMStorageContextWrapper> context,
- const std::string& namepace_id);
+ std::string namespace_id);
// Constructs a |SessionStorageNamespaceImpl| with id |namespace_id| by
- // cloning |namespace_to_clone|.
+ // cloning |namespace_to_clone|. Allocates it a new ID.
static scoped_refptr<SessionStorageNamespaceImpl> CloneFrom(
scoped_refptr<DOMStorageContextWrapper> context,
- std::string namepace_id,
- const std::string& namepace_id_to_clone);
+ std::string namespace_id,
+ const std::string& namespace_id_to_clone);
+
+ DOMStorageContextWrapper* context() const { return context_wrapper_.get(); }
// SessionStorageNamespace implementation.
const std::string& id() const override;
void SetShouldPersist(bool should_persist) override;
bool should_persist() const override;
- SessionStorageNamespaceImpl* Clone();
+ bool IsMojoSessionStorage() { return context_.get(); }
+
+ scoped_refptr<SessionStorageNamespaceImpl> Clone();
bool IsFromContext(DOMStorageContextWrapper* context);
private:
- explicit SessionStorageNamespaceImpl(
- std::unique_ptr<DOMStorageSession> session);
+ // Creates the non-mojo version.
+ SessionStorageNamespaceImpl(
+ scoped_refptr<DOMStorageContextWrapper> context_wrapper,
+ scoped_refptr<DOMStorageContextImpl> context_impl,
+ std::string namespace_id);
+ // Creates a mojo version.
+ SessionStorageNamespaceImpl(scoped_refptr<DOMStorageContextWrapper> context,
+ std::string namespace_id);
+
~SessionStorageNamespaceImpl() override;
- std::unique_ptr<DOMStorageSession> session_;
+ static void DeleteSessionNamespaceFromUIThread(
+ scoped_refptr<base::SequencedTaskRunner> mojo_task_runner,
+ scoped_refptr<DOMStorageContextWrapper> context_wrapper,
+ std::string namespace_id,
+ bool should_persist);
+
+ scoped_refptr<DOMStorageContextImpl> context_;
+ scoped_refptr<DOMStorageContextWrapper> context_wrapper_;
+ scoped_refptr<base::SequencedTaskRunner> mojo_task_runner_;
+ std::string namespace_id_;
+ bool should_persist_;
DISALLOW_COPY_AND_ASSIGN(SessionStorageNamespaceImpl);
};
diff --git a/chromium/content/browser/download/base_file.cc b/chromium/content/browser/download/base_file.cc
deleted file mode 100644
index cbbd4c34837..00000000000
--- a/chromium/content/browser/download/base_file.cc
+++ /dev/null
@@ -1,535 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/download/base_file.h"
-
-#include <memory>
-#include <utility>
-
-#include "base/bind.h"
-#include "base/files/file.h"
-#include "base/files/file_util.h"
-#include "base/format_macros.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/pickle.h"
-#include "base/strings/stringprintf.h"
-#include "base/threading/thread_restrictions.h"
-#include "base/trace_event/trace_event.h"
-#include "build/build_config.h"
-#include "components/download/public/common/download_item.h"
-#include "components/download/public/common/download_stats.h"
-#include "components/download/quarantine/quarantine.h"
-#include "content/browser/download/download_interrupt_reasons_utils.h"
-#include "crypto/secure_hash.h"
-#include "net/base/net_errors.h"
-
-#define CONDITIONAL_TRACE(trace) \
- do { \
- if (download_id_ != download::DownloadItem::kInvalidId) \
- TRACE_EVENT_##trace; \
- } while (0)
-
-namespace content {
-
-namespace {
-class FileErrorData : public base::trace_event::ConvertableToTraceFormat {
- public:
- FileErrorData(const char* operation,
- int os_error,
- download::DownloadInterruptReason interrupt_reason)
- : operation_(operation),
- os_error_(os_error),
- interrupt_reason_(interrupt_reason) {}
-
- ~FileErrorData() override = default;
-
- void AppendAsTraceFormat(std::string* out) const override {
- out->append("{");
- out->append(
- base::StringPrintf("\"operation\":\"%s\",", operation_.c_str()));
- out->append(base::StringPrintf("\"os_error\":\"%d\",", os_error_));
- out->append(base::StringPrintf(
- "\"interrupt_reason\":\"%s\",",
- DownloadInterruptReasonToString(interrupt_reason_).c_str()));
- out->append("}");
- }
-
- private:
- std::string operation_;
- int os_error_;
- download::DownloadInterruptReason interrupt_reason_;
- DISALLOW_COPY_AND_ASSIGN(FileErrorData);
-};
-} // namespace
-
-BaseFile::BaseFile(uint32_t download_id) : download_id_(download_id) {
- DETACH_FROM_SEQUENCE(sequence_checker_);
-}
-
-BaseFile::~BaseFile() {
- DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
- if (detached_)
- Close();
- else
- Cancel(); // Will delete the file.
-}
-
-download::DownloadInterruptReason BaseFile::Initialize(
- const base::FilePath& full_path,
- const base::FilePath& default_directory,
- base::File file,
- int64_t bytes_so_far,
- const std::string& hash_so_far,
- std::unique_ptr<crypto::SecureHash> hash_state,
- bool is_sparse_file) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
- DCHECK(!detached_);
-
- if (full_path.empty()) {
- base::FilePath temp_file;
- if ((default_directory.empty() ||
- !base::CreateTemporaryFileInDir(default_directory, &temp_file)) &&
- !base::CreateTemporaryFile(&temp_file)) {
- return LogInterruptReason(
- "Unable to create", 0,
- download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED);
- }
- full_path_ = temp_file;
- } else {
- full_path_ = full_path;
- }
-
- bytes_so_far_ = bytes_so_far;
- secure_hash_ = std::move(hash_state);
- is_sparse_file_ = is_sparse_file;
- // Sparse file doesn't validate hash.
- if (is_sparse_file_)
- secure_hash_.reset();
- file_ = std::move(file);
-
- return Open(hash_so_far);
-}
-
-download::DownloadInterruptReason BaseFile::AppendDataToFile(const char* data,
- size_t data_len) {
- DCHECK(!is_sparse_file_);
- return WriteDataToFile(bytes_so_far_, data, data_len);
-}
-
-download::DownloadInterruptReason BaseFile::WriteDataToFile(int64_t offset,
- const char* data,
- size_t data_len) {
- // NOTE(benwells): The above DCHECK won't be present in release builds,
- // so we log any occurences to see how common this error is in the wild.
- if (detached_)
- download::RecordDownloadCount(download::APPEND_TO_DETACHED_FILE_COUNT);
-
- if (!file_.IsValid())
- return LogInterruptReason("No file stream on append", 0,
- download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED);
-
- // TODO(phajdan.jr): get rid of this check.
- if (data_len == 0)
- return download::DOWNLOAD_INTERRUPT_REASON_NONE;
-
- // Use nestable async event instead of sync event so that all the writes
- // belong to the same download will be grouped together.
- CONDITIONAL_TRACE(
- NESTABLE_ASYNC_BEGIN0("download", "DownloadFileWrite", download_id_));
- int write_result = file_.Write(offset, data, data_len);
- DCHECK_NE(0, write_result);
-
- // Report errors on file writes.
- if (write_result < 0)
- return LogSystemError("Write", logging::GetLastSystemErrorCode());
-
- DCHECK_EQ(static_cast<size_t>(write_result), data_len);
-
- if (bytes_so_far_ != offset) {
- // A hole is created in the file.
- is_sparse_file_ = true;
- secure_hash_.reset();
- }
-
- bytes_so_far_ += data_len;
- CONDITIONAL_TRACE(NESTABLE_ASYNC_END1("download", "DownloadFileWrite",
- download_id_, "bytes", data_len));
-
- if (secure_hash_)
- secure_hash_->Update(data, data_len);
-
- return download::DOWNLOAD_INTERRUPT_REASON_NONE;
-}
-
-download::DownloadInterruptReason BaseFile::Rename(
- const base::FilePath& new_path) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
- download::DownloadInterruptReason rename_result =
- download::DOWNLOAD_INTERRUPT_REASON_NONE;
-
- // If the new path is same as the old one, there is no need to perform the
- // following renaming logic.
- if (new_path == full_path_)
- return download::DOWNLOAD_INTERRUPT_REASON_NONE;
-
- // Save the information whether the download is in progress because
- // it will be overwritten by closing the file.
- bool was_in_progress = in_progress();
-
- Close();
-
- CONDITIONAL_TRACE(BEGIN2("download", "DownloadFileRename", "old_filename",
- full_path_.AsUTF8Unsafe(), "new_filename",
- new_path.AsUTF8Unsafe()));
-
- base::CreateDirectory(new_path.DirName());
-
- // A simple rename wouldn't work here since we want the file to have
- // permissions / security descriptors that makes sense in the new directory.
- rename_result = MoveFileAndAdjustPermissions(new_path);
-
- CONDITIONAL_TRACE(END0("download", "DownloadFileRename"));
-
- if (rename_result == download::DOWNLOAD_INTERRUPT_REASON_NONE)
- full_path_ = new_path;
-
- // Re-open the file if we were still using it regardless of the interrupt
- // reason.
- download::DownloadInterruptReason open_result =
- download::DOWNLOAD_INTERRUPT_REASON_NONE;
- if (was_in_progress)
- open_result = Open(std::string());
-
- return rename_result == download::DOWNLOAD_INTERRUPT_REASON_NONE
- ? open_result
- : rename_result;
-}
-
-void BaseFile::Detach() {
- detached_ = true;
- CONDITIONAL_TRACE(
- INSTANT0("download", "DownloadFileDetached", TRACE_EVENT_SCOPE_THREAD));
-}
-
-void BaseFile::Cancel() {
- DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
- DCHECK(!detached_);
-
- CONDITIONAL_TRACE(
- INSTANT0("download", "DownloadCancelled", TRACE_EVENT_SCOPE_THREAD));
-
- Close();
-
- if (!full_path_.empty()) {
- CONDITIONAL_TRACE(
- INSTANT0("download", "DownloadFileDeleted", TRACE_EVENT_SCOPE_THREAD));
- base::DeleteFile(full_path_, false);
- }
-
- Detach();
-}
-
-std::unique_ptr<crypto::SecureHash> BaseFile::Finish() {
- DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
-
- // TODO(qinmin): verify that all the holes have been filled.
- if (is_sparse_file_)
- CalculatePartialHash(std::string());
- Close();
- return std::move(secure_hash_);
-}
-
-std::string BaseFile::DebugString() const {
- return base::StringPrintf(
- "{ "
- " full_path_ = \"%" PRFilePath
- "\""
- " bytes_so_far_ = %" PRId64 " detached_ = %c }",
- full_path_.value().c_str(),
- bytes_so_far_,
- detached_ ? 'T' : 'F');
-}
-
-download::DownloadInterruptReason BaseFile::CalculatePartialHash(
- const std::string& hash_to_expect) {
- secure_hash_ = crypto::SecureHash::Create(crypto::SecureHash::SHA256);
-
- if (bytes_so_far_ == 0)
- return download::DOWNLOAD_INTERRUPT_REASON_NONE;
-
- if (file_.Seek(base::File::FROM_BEGIN, 0) != 0)
- return LogSystemError("Seek partial file",
- logging::GetLastSystemErrorCode());
-
- const size_t kMinBufferSize = secure_hash_->GetHashLength();
- const size_t kMaxBufferSize = 1024 * 512;
- static_assert(kMaxBufferSize <= std::numeric_limits<int>::max(),
- "kMaxBufferSize must fit on an int");
-
- // The size of the buffer is:
- // - at least kMinBufferSize so that we can use it to hold the hash as well.
- // - at most kMaxBufferSize so that there's a reasonable bound.
- // - not larger than |bytes_so_far_| unless bytes_so_far_ is less than the
- // hash size.
- std::vector<char> buffer(std::max<int64_t>(
- kMinBufferSize, std::min<int64_t>(kMaxBufferSize, bytes_so_far_)));
-
- int64_t current_position = 0;
- while (current_position < bytes_so_far_) {
- // While std::min needs to work with int64_t, the result is always at most
- // kMaxBufferSize, which fits on an int.
- int bytes_to_read =
- std::min<int64_t>(buffer.size(), bytes_so_far_ - current_position);
- int length = file_.ReadAtCurrentPos(&buffer.front(), bytes_to_read);
- if (length == -1) {
- return LogInterruptReason(
- "Reading partial file", logging::GetLastSystemErrorCode(),
- download::DOWNLOAD_INTERRUPT_REASON_FILE_TOO_SHORT);
- }
-
- if (length == 0)
- break;
-
- secure_hash_->Update(&buffer.front(), length);
- current_position += length;
- }
-
- if (current_position != bytes_so_far_) {
- return LogInterruptReason(
- "Verifying prefix hash", 0,
- download::DOWNLOAD_INTERRUPT_REASON_FILE_TOO_SHORT);
- }
-
- if (!hash_to_expect.empty()) {
- DCHECK_EQ(secure_hash_->GetHashLength(), hash_to_expect.size());
- DCHECK(buffer.size() >= secure_hash_->GetHashLength());
- std::unique_ptr<crypto::SecureHash> partial_hash(secure_hash_->Clone());
- partial_hash->Finish(&buffer.front(), buffer.size());
-
- if (memcmp(&buffer.front(),
- hash_to_expect.c_str(),
- partial_hash->GetHashLength())) {
- return LogInterruptReason(
- "Verifying prefix hash", 0,
- download::DOWNLOAD_INTERRUPT_REASON_FILE_HASH_MISMATCH);
- }
- }
-
- return download::DOWNLOAD_INTERRUPT_REASON_NONE;
-}
-
-download::DownloadInterruptReason BaseFile::Open(
- const std::string& hash_so_far) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
- DCHECK(!detached_);
- DCHECK(!full_path_.empty());
-
- // Create a new file if it is not provided.
- if (!file_.IsValid()) {
- file_.Initialize(full_path_,
- base::File::FLAG_OPEN_ALWAYS | base::File::FLAG_WRITE |
- base::File::FLAG_READ);
- if (!file_.IsValid()) {
- return LogNetError("Open/Initialize File",
- net::FileErrorToNetError(file_.error_details()));
- }
- }
-
- CONDITIONAL_TRACE(NESTABLE_ASYNC_BEGIN2(
- "download", "DownloadFileOpen", download_id_, "file_name",
- full_path_.AsUTF8Unsafe(), "bytes_so_far", bytes_so_far_));
-
- // For sparse file, skip hash validation.
- if (is_sparse_file_) {
- if (file_.GetLength() < bytes_so_far_) {
- ClearFile();
- return LogInterruptReason(
- "File has fewer written bytes than expected", 0,
- download::DOWNLOAD_INTERRUPT_REASON_FILE_TOO_SHORT);
- }
- return download::DOWNLOAD_INTERRUPT_REASON_NONE;
- }
-
- if (!secure_hash_) {
- download::DownloadInterruptReason reason =
- CalculatePartialHash(hash_so_far);
- if (reason != download::DOWNLOAD_INTERRUPT_REASON_NONE) {
- ClearFile();
- return reason;
- }
- }
-
- int64_t file_size = file_.Seek(base::File::FROM_END, 0);
- if (file_size < 0) {
- logging::SystemErrorCode error = logging::GetLastSystemErrorCode();
- ClearFile();
- return LogSystemError("Seeking to end", error);
- } else if (file_size > bytes_so_far_) {
- // The file is larger than we expected.
- // This is OK, as long as we don't use the extra.
- // Truncate the file.
- if (!file_.SetLength(bytes_so_far_) ||
- file_.Seek(base::File::FROM_BEGIN, bytes_so_far_) != bytes_so_far_) {
- logging::SystemErrorCode error = logging::GetLastSystemErrorCode();
- ClearFile();
- return LogSystemError("Truncating to last known offset", error);
- }
- } else if (file_size < bytes_so_far_) {
- // The file is shorter than we expected. Our hashes won't be valid.
- ClearFile();
- return LogInterruptReason(
- "Unable to seek to last written point", 0,
- download::DOWNLOAD_INTERRUPT_REASON_FILE_TOO_SHORT);
- }
-
- return download::DOWNLOAD_INTERRUPT_REASON_NONE;
-}
-
-void BaseFile::Close() {
- DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
-
- if (file_.IsValid()) {
- // Currently we don't really care about the return value, since if it fails
- // theres not much we can do. But we might in the future.
- file_.Flush();
- ClearFile();
- }
-}
-
-void BaseFile::ClearFile() {
- // This should only be called when we have a stream.
- DCHECK(file_.IsValid());
- file_.Close();
- CONDITIONAL_TRACE(
- NESTABLE_ASYNC_END0("download", "DownloadFileOpen", download_id_));
-}
-
-download::DownloadInterruptReason BaseFile::LogNetError(const char* operation,
- net::Error error) {
- CONDITIONAL_TRACE(INSTANT2("download", "DownloadFileError",
- TRACE_EVENT_SCOPE_THREAD, "operation", operation,
- "net_error", error));
- return ConvertNetErrorToInterruptReason(error, DOWNLOAD_INTERRUPT_FROM_DISK);
-}
-
-download::DownloadInterruptReason BaseFile::LogSystemError(
- const char* operation,
- logging::SystemErrorCode os_error) {
- // There's no direct conversion from a system error to an interrupt reason.
- base::File::Error file_error = base::File::OSErrorToFileError(os_error);
- return LogInterruptReason(
- operation, os_error,
- ConvertFileErrorToInterruptReason(file_error));
-}
-
-download::DownloadInterruptReason BaseFile::LogInterruptReason(
- const char* operation,
- int os_error,
- download::DownloadInterruptReason reason) {
- DVLOG(1) << __func__ << "() operation:" << operation
- << " os_error:" << os_error
- << " reason:" << DownloadInterruptReasonToString(reason);
- auto error_data =
- std::make_unique<FileErrorData>(operation, os_error, reason);
- CONDITIONAL_TRACE(INSTANT1("download", "DownloadFileError",
- TRACE_EVENT_SCOPE_THREAD, "file_error",
- std::move(error_data)));
- return reason;
-}
-
-#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX)
-
-namespace {
-
-// Given a source and a referrer, determines the "safest" URL that can be used
-// to determine the authority of the download source. Returns an empty URL if no
-// HTTP/S URL can be determined for the <|source_url|, |referrer_url|> pair.
-GURL GetEffectiveAuthorityURL(const GURL& source_url,
- const GURL& referrer_url) {
- if (source_url.is_valid()) {
- // http{,s} has an authority and are supported.
- if (source_url.SchemeIsHTTPOrHTTPS())
- return source_url;
-
- // If the download source is file:// ideally we should copy the MOTW from
- // the original file, but given that Chrome/Chromium places strict
- // restrictions on which schemes can reference file:// URLs, this code is
- // going to assume that at this point it's okay to treat this download as
- // being from the local system.
- if (source_url.SchemeIsFile())
- return source_url;
-
- // ftp:// has an authority.
- if (source_url.SchemeIs(url::kFtpScheme))
- return source_url;
- }
-
- if (referrer_url.is_valid() && referrer_url.SchemeIsHTTPOrHTTPS())
- return referrer_url;
-
- return GURL();
-}
-
-} // namespace
-
-download::DownloadInterruptReason BaseFile::AnnotateWithSourceInformation(
- const std::string& client_guid,
- const GURL& source_url,
- const GURL& referrer_url) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
- DCHECK(!detached_);
- DCHECK(!full_path_.empty());
-
- CONDITIONAL_TRACE(BEGIN0("download", "DownloadFileAnnotate"));
- download::QuarantineFileResult result = download::QuarantineFile(
- full_path_, GetEffectiveAuthorityURL(source_url, referrer_url),
- referrer_url, client_guid);
- CONDITIONAL_TRACE(END0("download", "DownloadFileAnnotate"));
-
- switch (result) {
- case download::QuarantineFileResult::OK:
- return download::DOWNLOAD_INTERRUPT_REASON_NONE;
- case download::QuarantineFileResult::VIRUS_INFECTED:
- return download::DOWNLOAD_INTERRUPT_REASON_FILE_VIRUS_INFECTED;
- case download::QuarantineFileResult::SECURITY_CHECK_FAILED:
- return download::DOWNLOAD_INTERRUPT_REASON_FILE_SECURITY_CHECK_FAILED;
- case download::QuarantineFileResult::BLOCKED_BY_POLICY:
- return download::DOWNLOAD_INTERRUPT_REASON_FILE_BLOCKED;
- case download::QuarantineFileResult::ACCESS_DENIED:
- return download::DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED;
-
- case download::QuarantineFileResult::FILE_MISSING:
- // Don't have a good interrupt reason here. This return code means that
- // the file at |full_path_| went missing before QuarantineFile got to look
- // at it. Not expected to happen, but we've seen instances where a file
- // goes missing immediately after BaseFile closes the handle.
- //
- // Intentionally using a different error message than
- // SECURITY_CHECK_FAILED in order to distinguish the two.
- return download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED;
-
- case download::QuarantineFileResult::ANNOTATION_FAILED:
- // This means that the mark-of-the-web couldn't be applied. The file is
- // already on the file system under its final target name.
- //
- // Causes of failed annotations typically aren't transient. E.g. the
- // target file system may not support extended attributes or alternate
- // streams. We are going to allow these downloads to progress on the
- // assumption that failures to apply MOTW can't reliably be introduced
- // remotely.
- return download::DOWNLOAD_INTERRUPT_REASON_NONE;
- }
- return download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED;
-}
-#else // !OS_WIN && !OS_MACOSX && !OS_LINUX
-download::DownloadInterruptReason BaseFile::AnnotateWithSourceInformation(
- const std::string& client_guid,
- const GURL& source_url,
- const GURL& referrer_url) {
- return download::DOWNLOAD_INTERRUPT_REASON_NONE;
-}
-#endif
-
-} // namespace content
diff --git a/chromium/content/browser/download/base_file.h b/chromium/content/browser/download/base_file.h
deleted file mode 100644
index 671c6e4d95a..00000000000
--- a/chromium/content/browser/download/base_file.h
+++ /dev/null
@@ -1,267 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_DOWNLOAD_BASE_FILE_H_
-#define CONTENT_BROWSER_DOWNLOAD_BASE_FILE_H_
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include <memory>
-#include <string>
-
-#include "base/files/file.h"
-#include "base/files/file_path.h"
-#include "base/gtest_prod_util.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/sequence_checker.h"
-#include "base/time/time.h"
-#include "components/download/public/common/download_interrupt_reasons.h"
-#include "content/common/content_export.h"
-#include "crypto/secure_hash.h"
-#include "net/base/net_errors.h"
-#include "url/gurl.h"
-
-namespace content {
-
-// File being downloaded and saved to disk. This is a base class
-// for DownloadFile and SaveFile, which keep more state information. BaseFile
-// considers itself the owner of the physical file and will delete it when the
-// BaseFile object is destroyed unless the ownership is revoked via a call to
-// Detach().
-class CONTENT_EXPORT BaseFile {
- public:
- // May be constructed on any thread. All other routines (including
- // destruction) must occur on the same sequence.
- BaseFile(uint32_t download_id);
- ~BaseFile();
-
- // Returns DOWNLOAD_INTERRUPT_REASON_NONE on success, or a
- // DownloadInterruptReason on failure. Upon success, the file at |full_path()|
- // is assumed to be owned by the BaseFile. It will be deleted when the
- // BaseFile object is destroyed unless Detach() is called before destroying
- // the BaseFile instance.
- //
- // |full_path|: Full path to the download file. Can be empty, in which case
- // the rules described in |default_directory| will be used to generate a
- // temporary filename.
- //
- // |default_directory|: specifies the directory to create the temporary file
- // in if |full_path| is empty. If |default_directory| and |full_path| are
- // empty, then a temporary file will be created in the default download
- // location as determined by ContentBrowserClient.
- //
- // |file|: The base::File handle to use. If specified, BaseFile will not open
- // a file and will use this handle. The file should be opened for both
- // read and write. Only makes sense if |full_path| is non-empty since it
- // implies that the caller already knows the path to the file. There's no
- // perfect way to come up with a canonical path for a file. So BaseFile
- // will not attempt to determine the |full_path|.
- //
- // |bytes_so_far|: If a file is provided (via |full_path| or |file|), then
- // this argument specifies the amount of data that has been written to
- // the file. If |is_sparse_file| is false, this value should be the size
- // of the file to expect. It is legal for the file to be larger, in which
- // case the file will be truncated down to this size if |is_sparse_file|
- // is false. However, if the file is shorter, then the operation will
- // fail with DOWNLOAD_INTERRUPT_REASON_FILE_TOO_SHORT.
-
- //
- // |hash_so_far|: If |bytes_so_far| is non-zero and |is_sparse_file| is
- // false, this specifies the SHA-256 hash of the first |bytes_so_far|
- // bytes of the target file. If specified, BaseFile will read the first
- // |bytes_so_far| of the target file in order to calculate the hash and
- // verify that the file matches. If there's a mismatch, then the operation
- // fails with DOWNLOAD_INTERRUPT_REASON_FILE_HASH_MISMATCH. Not used if
- // |hash_state| is also specified.
- //
- // |hash_state|: The partial hash object to use. Only meaningful if there's a
- // preexisting target file and it is non-empty (i.e. bytes_so_far is
- // non-zero). If specified, BaseFile will assume that the bytes up to
- // |bytes_so_far| has been accurately hashed into |hash_state| and will
- // ignore |hash_so_far|. Not used if |is_sparse_file| is true.
- //
- // |is_sparse_file|: Specifies whether the file is a sparse file. If so, it is
- // possible that a write can happen at an offset that is larger than the
- // file size, thus creating holes in it.
- download::DownloadInterruptReason Initialize(
- const base::FilePath& full_path,
- const base::FilePath& default_directory,
- base::File file,
- int64_t bytes_so_far,
- const std::string& hash_so_far,
- std::unique_ptr<crypto::SecureHash> hash_state,
- bool is_sparse_file);
-
- // Write a new chunk of data to the file. Returns a DownloadInterruptReason
- // indicating the result of the operation. Works only if |is_sparse_file| is
- // false.
- download::DownloadInterruptReason AppendDataToFile(const char* data,
- size_t data_len);
-
- // Write a new chunk of data to the file. Returns a DownloadInterruptReason
- // indicating the result of the operation.
- download::DownloadInterruptReason WriteDataToFile(int64_t offset,
- const char* data,
- size_t data_len);
-
- // Rename the download file. Returns a DownloadInterruptReason indicating the
- // result of the operation. A return code of NONE indicates that the rename
- // was successful. After a failure, the full_path() and in_progress() can be
- // used to determine the last known filename and whether the file is available
- // for writing or retrying the rename. Call Finish() to obtain the last known
- // hash state.
- download::DownloadInterruptReason Rename(const base::FilePath& full_path);
-
- // Mark the file as detached. Up until this method is called, BaseFile assumes
- // ownership of the file and hence will delete the file if the BaseFile object
- // is destroyed. Calling Detach() causes BaseFile to assume that it no longer
- // owns the file. Detach() can be called at any time. Close() must still be
- // called to close the file if it is open.
- void Detach();
-
- // Abort the download and automatically close and delete the file.
- void Cancel();
-
- // Indicate that the download has finished. No new data will be received.
- // Returns the SecureHash object representing the state of the hash function
- // at the end of the operation. If |is_sparse_file_| is true, calling this
- // will cause |secure_hash_| to get calculated.
- std::unique_ptr<crypto::SecureHash> Finish();
-
- // Informs the OS that this file came from the internet. Returns a
- // DownloadInterruptReason indicating the result of the operation.
- //
- // |client_guid|: The client GUID which will be used to identify the caller to
- // the system AV scanning function.
- //
- // |source_url| / |referrer_url|: Source and referrer for the network request
- // that originated this download. Will be used to annotate source
- // information and also to determine the relative danger level of the
- // file.
- download::DownloadInterruptReason AnnotateWithSourceInformation(
- const std::string& client_guid,
- const GURL& source_url,
- const GURL& referrer_url);
-
- // Returns the last known path to the download file. Can be empty if there's
- // no file.
- const base::FilePath& full_path() const { return full_path_; }
-
- // Returns true if the file is open. If true, the file can be written to or
- // renamed.
- bool in_progress() const { return file_.IsValid(); }
-
- // Returns the number of bytes that has been written so far. If
- // |is_sparse_file_| is false, this should always be equal to the file size.
- // If |is_sparse_file_| is true, this should not be larger than the file size
- // as the file may contain holes in it.
- int64_t bytes_so_far() const { return bytes_so_far_; }
-
- std::string DebugString() const;
-
- private:
- friend class BaseFileTest;
- FRIEND_TEST_ALL_PREFIXES(BaseFileTest, IsEmptyHash);
-
- // Creates and opens the file_ if it is invalid.
- //
- // If |is_sparse_file_| is false and |hash_so_far| is not empty, then it must
- // match the SHA-256 hash of the first |bytes_so_far_| bytes of |file_|. If
- // there's a hash mismatch, Open() fails with
- // DOWNLOAD_INTERRUPT_REASON_FILE_HASH_MISMATCH.
- //
- // If the opened file is shorter than |bytes_so_far_| bytes, then Open() fails
- // with DOWNLOAD_INTERRUPT_REASON_FILE_TOO_SHORT. If the opened file is longer
- // and |is_sparse_file_| is false, then the file is truncated to
- // |bytes_so_far_|.
- //
- // Open() can fail for other reasons as well. In that case, it returns a
- // relevant interrupt reason. Unless Open() return
- // DOWNLOAD_INTERRUPT_REASON_NONE, it should be assumed that |file_| is not
- // valid.
- download::DownloadInterruptReason Open(const std::string& hash_so_far);
-
- // Closes and resets file_.
- void Close();
-
- // Resets file_.
- void ClearFile();
-
- // Platform specific method that moves a file to a new path and adjusts the
- // security descriptor / permissions on the file to match the defaults for the
- // new directory.
- download::DownloadInterruptReason MoveFileAndAdjustPermissions(
- const base::FilePath& new_path);
-
- // Split out from CurrentSpeed to enable testing.
- int64_t CurrentSpeedAtTime(base::TimeTicks current_time) const;
-
- // Verifies that:
- // * Size of the file represented by |file_| is at least |bytes_so_far_|.
- //
- // * If |hash_to_expect| is not empty, then the result of hashing the first
- // |bytes_so_far_| bytes of |file_| matches |hash_to_expect|.
- //
- // If the result is REASON_NONE, then on return |secure_hash_| is valid and
- // is ready to hash bytes from offset |bytes_so_far_| + 1.
- // If |is_sparse_file_| is true, this function is only called when Finish()
- // is called.
- download::DownloadInterruptReason CalculatePartialHash(
- const std::string& hash_to_expect);
-
- // Log a TYPE_DOWNLOAD_FILE_ERROR NetLog event with |error| and passes error
- // on through, converting to a |DownloadInterruptReason|.
- download::DownloadInterruptReason LogNetError(const char* operation,
- net::Error error);
-
- // Log the system error in |os_error| and converts it into a
- // |DownloadInterruptReason|.
- download::DownloadInterruptReason LogSystemError(
- const char* operation,
- logging::SystemErrorCode os_error);
-
- // Log a TYPE_DOWNLOAD_FILE_ERROR NetLog event with |os_error| and |reason|.
- // Returns |reason|.
- download::DownloadInterruptReason LogInterruptReason(
- const char* operation,
- int os_error,
- download::DownloadInterruptReason reason);
-
- // Full path to the file including the file name.
- base::FilePath full_path_;
-
- // OS file for writing
- base::File file_;
-
- // Amount of data received up so far, in bytes.
- int64_t bytes_so_far_ = 0;
-
- // Used to calculate hash for the file when calculate_hash_ is set.
- std::unique_ptr<crypto::SecureHash> secure_hash_;
-
- // Start time for calculating speed.
- base::TimeTicks start_tick_;
-
- // Indicates that this class no longer owns the associated file, and so
- // won't delete it on destruction.
- bool detached_ = false;
-
- // Whether the file is sparse.
- // TODO(qinmin): pass the slice information to this class so that we can
- // verify that writes are not overlapping.
- bool is_sparse_file_ = false;
-
- // ID of the download, used for trace events.
- uint32_t download_id_;
-
- SEQUENCE_CHECKER(sequence_checker_);
-
- DISALLOW_COPY_AND_ASSIGN(BaseFile);
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_DOWNLOAD_BASE_FILE_H_
diff --git a/chromium/content/browser/download/base_file_posix.cc b/chromium/content/browser/download/base_file_posix.cc
deleted file mode 100644
index 5870c0c9e8a..00000000000
--- a/chromium/content/browser/download/base_file_posix.cc
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/download/base_file.h"
-
-#include <errno.h>
-
-#include "base/files/file_util.h"
-#include "components/download/public/common/download_interrupt_reasons.h"
-
-namespace content {
-
-download::DownloadInterruptReason BaseFile::MoveFileAndAdjustPermissions(
- const base::FilePath& new_path) {
- // Similarly, on Unix, we're moving a temp file created with permissions 600
- // to |new_path|. Here, we try to fix up the destination file with appropriate
- // permissions.
- struct stat st;
- // First check the file existence and create an empty file if it doesn't
- // exist.
- if (!base::PathExists(new_path)) {
- int write_error = base::WriteFile(new_path, "", 0);
- if (write_error < 0)
- return LogSystemError("WriteFile", errno);
- }
- int stat_error = stat(new_path.value().c_str(), &st);
- bool stat_succeeded = (stat_error == 0);
- if (!stat_succeeded)
- LogSystemError("stat", errno);
-
- if (!base::Move(full_path_, new_path))
- return LogSystemError("Move", errno);
-
- if (stat_succeeded) {
- // On Windows file systems (FAT, NTFS), chmod fails. This is OK.
- int chmod_error = chmod(new_path.value().c_str(), st.st_mode);
- if (chmod_error < 0)
- LogSystemError("chmod", errno);
- }
- return download::DOWNLOAD_INTERRUPT_REASON_NONE;
-}
-
-} // namespace content
diff --git a/chromium/content/browser/download/base_file_unittest.cc b/chromium/content/browser/download/base_file_unittest.cc
deleted file mode 100644
index 2402de281b6..00000000000
--- a/chromium/content/browser/download/base_file_unittest.cc
+++ /dev/null
@@ -1,759 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/download/base_file.h"
-
-#include <stddef.h>
-#include <stdint.h>
-#include <utility>
-
-#include "base/files/file.h"
-#include "base/files/file_util.h"
-#include "base/files/scoped_temp_dir.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/test/test_file_util.h"
-#include "build/build_config.h"
-#include "components/download/public/common/download_interrupt_reasons.h"
-#include "components/download/public/common/download_item.h"
-#include "content/public/test/test_browser_thread_bundle.h"
-#include "crypto/secure_hash.h"
-#include "crypto/sha2.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace content {
-namespace {
-
-const char kTestData1[] = "Let's write some data to the file!\n";
-const char kTestData2[] = "Writing more data.\n";
-const char kTestData3[] = "Final line.";
-const char kTestData4[] = "supercalifragilisticexpialidocious";
-const int kTestDataLength1 = arraysize(kTestData1) - 1;
-const int kTestDataLength2 = arraysize(kTestData2) - 1;
-const int kTestDataLength3 = arraysize(kTestData3) - 1;
-const int kTestDataLength4 = arraysize(kTestData4) - 1;
-
-// SHA-256 hash of kTestData1 (excluding terminating NUL).
-const uint8_t kHashOfTestData1[] = {
- 0x0b, 0x2d, 0x3f, 0x3f, 0x79, 0x43, 0xad, 0x64, 0xb8, 0x60, 0xdf,
- 0x94, 0xd0, 0x5c, 0xb5, 0x6a, 0x8a, 0x97, 0xc6, 0xec, 0x57, 0x68,
- 0xb5, 0xb7, 0x0b, 0x93, 0x0c, 0x5a, 0xa7, 0xfa, 0x9a, 0xde};
-
-// SHA-256 hash of kTestData1 ++ kTestData2 ++ kTestData3 (excluding terminating
-// NUL).
-const uint8_t kHashOfTestData1To3[] = {
- 0xcb, 0xf6, 0x8b, 0xf1, 0x0f, 0x80, 0x03, 0xdb, 0x86, 0xb3, 0x13,
- 0x43, 0xaf, 0xac, 0x8c, 0x71, 0x75, 0xbd, 0x03, 0xfb, 0x5f, 0xc9,
- 0x05, 0x65, 0x0f, 0x8c, 0x80, 0xaf, 0x08, 0x74, 0x43, 0xa8};
-
-} // namespace
-
-class BaseFileTest : public testing::Test {
- public:
- static const unsigned char kEmptySha256Hash[crypto::kSHA256Length];
-
- BaseFileTest()
- : expect_file_survives_(false),
- expect_in_progress_(true),
- expected_error_(download::DOWNLOAD_INTERRUPT_REASON_NONE) {}
-
- void SetUp() override {
- ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
- base_file_.reset(new BaseFile(download::DownloadItem::kInvalidId));
- }
-
- void TearDown() override {
- EXPECT_FALSE(base_file_->in_progress());
- if (!expected_error_) {
- EXPECT_EQ(static_cast<int64_t>(expected_data_.size()),
- base_file_->bytes_so_far());
- }
-
- base::FilePath full_path = base_file_->full_path();
-
- if (!expected_data_.empty() && !expected_error_) {
- // Make sure the data has been properly written to disk.
- std::string disk_data;
- EXPECT_TRUE(base::ReadFileToString(full_path, &disk_data));
- EXPECT_EQ(expected_data_, disk_data);
- }
-
- // Make sure the mock BrowserThread outlives the BaseFile to satisfy
- // thread checks inside it.
- base_file_.reset();
-
- EXPECT_EQ(expect_file_survives_, base::PathExists(full_path));
- }
-
- bool InitializeFile() {
- download::DownloadInterruptReason result = base_file_->Initialize(
- base::FilePath(), temp_dir_.GetPath(), base::File(), 0, std::string(),
- std::unique_ptr<crypto::SecureHash>(), false);
- EXPECT_EQ(expected_error_, result);
- return result == download::DOWNLOAD_INTERRUPT_REASON_NONE;
- }
-
- bool AppendDataToFile(const std::string& data) {
- EXPECT_EQ(expect_in_progress_, base_file_->in_progress());
- download::DownloadInterruptReason result =
- base_file_->AppendDataToFile(data.data(), data.size());
- if (result == download::DOWNLOAD_INTERRUPT_REASON_NONE)
- EXPECT_TRUE(expect_in_progress_) << " result = " << result;
-
- EXPECT_EQ(expected_error_, result);
- if (base_file_->in_progress()) {
- expected_data_ += data;
- if (expected_error_ == download::DOWNLOAD_INTERRUPT_REASON_NONE) {
- EXPECT_EQ(static_cast<int64_t>(expected_data_.size()),
- base_file_->bytes_so_far());
- }
- }
- return result == download::DOWNLOAD_INTERRUPT_REASON_NONE;
- }
-
- void set_expected_data(const std::string& data) { expected_data_ = data; }
-
- // Helper functions.
- // Create a file. Returns the complete file path.
- base::FilePath CreateTestFile() {
- base::FilePath file_name;
- BaseFile file(download::DownloadItem::kInvalidId);
-
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE,
- file.Initialize(base::FilePath(), temp_dir_.GetPath(),
- base::File(), 0, std::string(),
- std::unique_ptr<crypto::SecureHash>(), false));
- file_name = file.full_path();
- EXPECT_NE(base::FilePath::StringType(), file_name.value());
-
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE,
- file.AppendDataToFile(kTestData4, kTestDataLength4));
-
- // Keep the file from getting deleted when existing_file_name is deleted.
- file.Detach();
-
- return file_name;
- }
-
- // Create a file with the specified file name.
- void CreateFileWithName(const base::FilePath& file_name) {
- EXPECT_NE(base::FilePath::StringType(), file_name.value());
- BaseFile duplicate_file(download::DownloadItem::kInvalidId);
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE,
- duplicate_file.Initialize(
- file_name, temp_dir_.GetPath(), base::File(), 0,
- std::string(), std::unique_ptr<crypto::SecureHash>(), false));
- // Write something into it.
- duplicate_file.AppendDataToFile(kTestData4, kTestDataLength4);
- // Detach the file so it isn't deleted on destruction of |duplicate_file|.
- duplicate_file.Detach();
- }
-
- int64_t CurrentSpeedAtTime(base::TimeTicks current_time) {
- EXPECT_TRUE(base_file_.get());
- return base_file_->CurrentSpeedAtTime(current_time);
- }
-
- base::TimeTicks StartTick() {
- EXPECT_TRUE(base_file_.get());
- return base_file_->start_tick_;
- }
-
- void set_expected_error(download::DownloadInterruptReason err) {
- expected_error_ = err;
- }
-
- void ExpectPermissionError(download::DownloadInterruptReason err) {
- EXPECT_TRUE(err ==
- download::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR ||
- err == download::DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED)
- << "Interrupt reason = " << err;
- }
-
- template <size_t SZ>
- static void ExpectHashValue(const uint8_t (&expected_hash)[SZ],
- std::unique_ptr<crypto::SecureHash> hash_state) {
- std::vector<uint8_t> hash_value(hash_state->GetHashLength());
- hash_state->Finish(&hash_value.front(), hash_value.size());
- ASSERT_EQ(SZ, hash_value.size());
- EXPECT_EQ(0, memcmp(expected_hash, &hash_value.front(), hash_value.size()));
- }
-
- protected:
- // BaseClass instance we are testing.
- std::unique_ptr<BaseFile> base_file_;
-
- // Temporary directory for renamed downloads.
- base::ScopedTempDir temp_dir_;
-
- // Expect the file to survive deletion of the BaseFile instance.
- bool expect_file_survives_;
-
- // Expect the file to be in progress.
- bool expect_in_progress_;
-
- private:
- // Keep track of what data should be saved to the disk file.
- std::string expected_data_;
- download::DownloadInterruptReason expected_error_;
-
- TestBrowserThreadBundle thread_bundle_;
-};
-
-// This will initialize the entire array to zero.
-const unsigned char BaseFileTest::kEmptySha256Hash[] = { 0 };
-
-// Test the most basic scenario: just create the object and do a sanity check
-// on all its accessors. This is actually a case that rarely happens
-// in production, where we would at least Initialize it.
-TEST_F(BaseFileTest, CreateDestroy) {
- EXPECT_EQ(base::FilePath().value(), base_file_->full_path().value());
-}
-
-// Cancel the download explicitly.
-TEST_F(BaseFileTest, Cancel) {
- ASSERT_TRUE(InitializeFile());
- EXPECT_TRUE(base::PathExists(base_file_->full_path()));
- base_file_->Cancel();
- EXPECT_FALSE(base::PathExists(base_file_->full_path()));
- EXPECT_NE(base::FilePath().value(), base_file_->full_path().value());
-}
-
-// Write data to the file and detach it, so it doesn't get deleted
-// automatically when base_file_ is destructed.
-TEST_F(BaseFileTest, WriteAndDetach) {
- ASSERT_TRUE(InitializeFile());
- ASSERT_TRUE(AppendDataToFile(kTestData1));
- base_file_->Finish();
- base_file_->Detach();
- expect_file_survives_ = true;
-}
-
-// Write data to the file and detach it, and calculate its sha256 hash.
-TEST_F(BaseFileTest, WriteWithHashAndDetach) {
- ASSERT_TRUE(InitializeFile());
- ASSERT_TRUE(AppendDataToFile(kTestData1));
- ExpectHashValue(kHashOfTestData1, base_file_->Finish());
- base_file_->Detach();
- expect_file_survives_ = true;
-}
-
-// Rename the file after writing to it, then detach.
-TEST_F(BaseFileTest, WriteThenRenameAndDetach) {
- ASSERT_TRUE(InitializeFile());
-
- base::FilePath initial_path(base_file_->full_path());
- EXPECT_TRUE(base::PathExists(initial_path));
- base::FilePath new_path(temp_dir_.GetPath().AppendASCII("NewFile"));
- EXPECT_FALSE(base::PathExists(new_path));
-
- ASSERT_TRUE(AppendDataToFile(kTestData1));
-
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE,
- base_file_->Rename(new_path));
- EXPECT_FALSE(base::PathExists(initial_path));
- EXPECT_TRUE(base::PathExists(new_path));
-
- ExpectHashValue(kHashOfTestData1, base_file_->Finish());
- base_file_->Detach();
- expect_file_survives_ = true;
-}
-
-// Write data to the file once.
-TEST_F(BaseFileTest, SingleWrite) {
- ASSERT_TRUE(InitializeFile());
- ASSERT_TRUE(AppendDataToFile(kTestData1));
- ExpectHashValue(kHashOfTestData1, base_file_->Finish());
-}
-
-// Write data to the file multiple times.
-TEST_F(BaseFileTest, MultipleWrites) {
- ASSERT_TRUE(InitializeFile());
- ASSERT_TRUE(AppendDataToFile(kTestData1));
- ASSERT_TRUE(AppendDataToFile(kTestData2));
- ASSERT_TRUE(AppendDataToFile(kTestData3));
- ExpectHashValue(kHashOfTestData1To3, base_file_->Finish());
-}
-
-// Write data to the file multiple times, interrupt it, and continue using
-// another file. Calculate the resulting combined sha256 hash.
-TEST_F(BaseFileTest, MultipleWritesInterruptedWithHash) {
- ASSERT_TRUE(InitializeFile());
- // Write some data
- ASSERT_TRUE(AppendDataToFile(kTestData1));
- ASSERT_TRUE(AppendDataToFile(kTestData2));
- // Get the hash state and file name.
- std::unique_ptr<crypto::SecureHash> hash_state = base_file_->Finish();
-
- base::FilePath new_file_path(temp_dir_.GetPath().Append(
- base::FilePath(FILE_PATH_LITERAL("second_file"))));
-
- ASSERT_TRUE(base::CopyFile(base_file_->full_path(), new_file_path));
-
- // Create another file
- BaseFile second_file(download::DownloadItem::kInvalidId);
- ASSERT_EQ(
- download::DOWNLOAD_INTERRUPT_REASON_NONE,
- second_file.Initialize(new_file_path, base::FilePath(), base::File(),
- base_file_->bytes_so_far(), std::string(),
- std::move(hash_state), false));
- std::string data(kTestData3);
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE,
- second_file.AppendDataToFile(data.data(), data.size()));
- ExpectHashValue(kHashOfTestData1To3, second_file.Finish());
-}
-
-// Rename the file after all writes to it.
-TEST_F(BaseFileTest, WriteThenRename) {
- ASSERT_TRUE(InitializeFile());
-
- base::FilePath initial_path(base_file_->full_path());
- EXPECT_TRUE(base::PathExists(initial_path));
- base::FilePath new_path(temp_dir_.GetPath().AppendASCII("NewFile"));
- EXPECT_FALSE(base::PathExists(new_path));
-
- ASSERT_TRUE(AppendDataToFile(kTestData1));
-
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE,
- base_file_->Rename(new_path));
- EXPECT_FALSE(base::PathExists(initial_path));
- EXPECT_TRUE(base::PathExists(new_path));
-
- ExpectHashValue(kHashOfTestData1, base_file_->Finish());
-}
-
-// Rename the file while the download is still in progress.
-TEST_F(BaseFileTest, RenameWhileInProgress) {
- ASSERT_TRUE(InitializeFile());
-
- base::FilePath initial_path(base_file_->full_path());
- EXPECT_TRUE(base::PathExists(initial_path));
- base::FilePath new_path(temp_dir_.GetPath().AppendASCII("NewFile"));
- EXPECT_FALSE(base::PathExists(new_path));
-
- ASSERT_TRUE(AppendDataToFile(kTestData1));
-
- EXPECT_TRUE(base_file_->in_progress());
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE,
- base_file_->Rename(new_path));
- EXPECT_FALSE(base::PathExists(initial_path));
- EXPECT_TRUE(base::PathExists(new_path));
-
- ASSERT_TRUE(AppendDataToFile(kTestData2));
- ASSERT_TRUE(AppendDataToFile(kTestData3));
-
- ExpectHashValue(kHashOfTestData1To3, base_file_->Finish());
-}
-
-// Test that a failed rename reports the correct error.
-TEST_F(BaseFileTest, RenameWithError) {
- ASSERT_TRUE(InitializeFile());
-
- // TestDir is a subdirectory in |temp_dir_| that we will make read-only so
- // that the rename will fail.
- base::FilePath test_dir(temp_dir_.GetPath().AppendASCII("TestDir"));
- ASSERT_TRUE(base::CreateDirectory(test_dir));
-
- base::FilePath new_path(test_dir.AppendASCII("TestFile"));
- EXPECT_FALSE(base::PathExists(new_path));
-
- {
- base::FilePermissionRestorer restore_permissions_for(test_dir);
- ASSERT_TRUE(base::MakeFileUnwritable(test_dir));
- ExpectPermissionError(base_file_->Rename(new_path));
- }
-
- base_file_->Finish();
-}
-
-// Test that if a rename fails for an in-progress BaseFile, it remains writeable
-// and renameable.
-TEST_F(BaseFileTest, RenameWithErrorInProgress) {
- ASSERT_TRUE(InitializeFile());
-
- base::FilePath test_dir(temp_dir_.GetPath().AppendASCII("TestDir"));
- ASSERT_TRUE(base::CreateDirectory(test_dir));
-
- base::FilePath new_path(test_dir.AppendASCII("TestFile"));
- EXPECT_FALSE(base::PathExists(new_path));
-
- // Write some data to start with.
- ASSERT_TRUE(AppendDataToFile(kTestData1));
- ASSERT_TRUE(base_file_->in_progress());
-
- base::FilePath old_path = base_file_->full_path();
-
- {
- base::FilePermissionRestorer restore_permissions_for(test_dir);
- ASSERT_TRUE(base::MakeFileUnwritable(test_dir));
- ExpectPermissionError(base_file_->Rename(new_path));
-
- // The file should still be open and we should be able to continue writing
- // to it.
- ASSERT_TRUE(base_file_->in_progress());
- ASSERT_TRUE(AppendDataToFile(kTestData2));
- ASSERT_EQ(old_path.value(), base_file_->full_path().value());
-
- // Try to rename again, just for kicks. It should still fail.
- ExpectPermissionError(base_file_->Rename(new_path));
- }
-
- // Now that TestDir is writeable again, we should be able to successfully
- // rename the file.
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE,
- base_file_->Rename(new_path));
- ASSERT_EQ(new_path.value(), base_file_->full_path().value());
- ASSERT_TRUE(AppendDataToFile(kTestData3));
-
- ExpectHashValue(kHashOfTestData1To3, base_file_->Finish());
-}
-
-// Test that a failed write reports an error.
-TEST_F(BaseFileTest, WriteWithError) {
- base::FilePath path;
- ASSERT_TRUE(base::CreateTemporaryFile(&path));
-
- // Pass a file handle which was opened without the WRITE flag.
- // This should result in an error when writing.
- base::File file(path, base::File::FLAG_OPEN_ALWAYS | base::File::FLAG_READ);
- base_file_.reset(new BaseFile(download::DownloadItem::kInvalidId));
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE,
- base_file_->Initialize(
- path, base::FilePath(), std::move(file), 0, std::string(),
- std::unique_ptr<crypto::SecureHash>(), false));
-#if defined(OS_WIN)
- set_expected_error(download::DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED);
-#elif defined (OS_POSIX)
- set_expected_error(download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED);
-#endif
- ASSERT_FALSE(AppendDataToFile(kTestData1));
- base_file_->Finish();
-}
-
-// Try to write to uninitialized file.
-TEST_F(BaseFileTest, UninitializedFile) {
- expect_in_progress_ = false;
- set_expected_error(download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED);
- EXPECT_FALSE(AppendDataToFile(kTestData1));
-}
-
-// Create two |BaseFile|s with the same file, and attempt to write to both.
-// Overwrite base_file_ with another file with the same name and
-// non-zero contents, and make sure the last file to close 'wins'.
-TEST_F(BaseFileTest, DuplicateBaseFile) {
- ASSERT_TRUE(InitializeFile());
-
- // Create another |BaseFile| referring to the file that |base_file_| owns.
- CreateFileWithName(base_file_->full_path());
-
- ASSERT_TRUE(AppendDataToFile(kTestData1));
- base_file_->Finish();
-}
-
-// Create a file and append to it.
-TEST_F(BaseFileTest, AppendToBaseFile) {
- // Create a new file.
- base::FilePath existing_file_name = CreateTestFile();
- set_expected_data(kTestData4);
-
- // Use the file we've just created.
- base_file_.reset(new BaseFile(download::DownloadItem::kInvalidId));
- ASSERT_EQ(
- download::DOWNLOAD_INTERRUPT_REASON_NONE,
- base_file_->Initialize(existing_file_name, base::FilePath(), base::File(),
- kTestDataLength4, std::string(),
- std::unique_ptr<crypto::SecureHash>(), false));
-
- const base::FilePath file_name = base_file_->full_path();
- EXPECT_NE(base::FilePath::StringType(), file_name.value());
-
- // Write into the file.
- EXPECT_TRUE(AppendDataToFile(kTestData1));
-
- base_file_->Finish();
- base_file_->Detach();
- expect_file_survives_ = true;
-}
-
-// Create a read-only file and attempt to write to it.
-TEST_F(BaseFileTest, ReadonlyBaseFile) {
- // Create a new file.
- base::FilePath readonly_file_name = CreateTestFile();
-
- // Restore permissions to the file when we are done with this test.
- base::FilePermissionRestorer restore_permissions(readonly_file_name);
-
- // Make it read-only.
- EXPECT_TRUE(base::MakeFileUnwritable(readonly_file_name));
-
- // Try to overwrite it.
- base_file_.reset(new BaseFile(download::DownloadItem::kInvalidId));
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED,
- base_file_->Initialize(
- readonly_file_name, base::FilePath(), base::File(), 0,
- std::string(), std::unique_ptr<crypto::SecureHash>(), false));
-
- expect_in_progress_ = false;
-
- const base::FilePath file_name = base_file_->full_path();
- EXPECT_NE(base::FilePath::StringType(), file_name.value());
-
- // Write into the file.
- set_expected_error(download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED);
- EXPECT_FALSE(AppendDataToFile(kTestData1));
-
- base_file_->Finish();
- base_file_->Detach();
- expect_file_survives_ = true;
-}
-
-// Open an existing file and continue writing to it. The hash of the partial
-// file is known and matches the existing contents.
-TEST_F(BaseFileTest, ExistingBaseFileKnownHash) {
- base::FilePath file_path = temp_dir_.GetPath().AppendASCII("existing");
- ASSERT_EQ(kTestDataLength1,
- base::WriteFile(file_path, kTestData1, kTestDataLength1));
-
- std::string hash_so_far(std::begin(kHashOfTestData1),
- std::end(kHashOfTestData1));
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE,
- base_file_->Initialize(
- file_path, base::FilePath(), base::File(), kTestDataLength1,
- hash_so_far, std::unique_ptr<crypto::SecureHash>(), false));
- set_expected_data(kTestData1);
- ASSERT_TRUE(AppendDataToFile(kTestData2));
- ASSERT_TRUE(AppendDataToFile(kTestData3));
- ExpectHashValue(kHashOfTestData1To3, base_file_->Finish());
-}
-
-// Open an existing file and continue writing to it. The hash of the partial
-// file is unknown.
-TEST_F(BaseFileTest, ExistingBaseFileUnknownHash) {
- base::FilePath file_path = temp_dir_.GetPath().AppendASCII("existing");
- ASSERT_EQ(kTestDataLength1,
- base::WriteFile(file_path, kTestData1, kTestDataLength1));
-
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE,
- base_file_->Initialize(
- file_path, base::FilePath(), base::File(), kTestDataLength1,
- std::string(), std::unique_ptr<crypto::SecureHash>(), false));
- set_expected_data(kTestData1);
- ASSERT_TRUE(AppendDataToFile(kTestData2));
- ASSERT_TRUE(AppendDataToFile(kTestData3));
- ExpectHashValue(kHashOfTestData1To3, base_file_->Finish());
-}
-
-// Open an existing file. The contentsof the file doesn't match the known hash.
-TEST_F(BaseFileTest, ExistingBaseFileIncorrectHash) {
- base::FilePath file_path = temp_dir_.GetPath().AppendASCII("existing");
- ASSERT_EQ(kTestDataLength2,
- base::WriteFile(file_path, kTestData2, kTestDataLength2));
-
- std::string hash_so_far(std::begin(kHashOfTestData1),
- std::end(kHashOfTestData1));
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_FILE_HASH_MISMATCH,
- base_file_->Initialize(
- file_path, base::FilePath(), base::File(), kTestDataLength2,
- hash_so_far, std::unique_ptr<crypto::SecureHash>(), false));
- set_expected_error(download::DOWNLOAD_INTERRUPT_REASON_FILE_HASH_MISMATCH);
-}
-
-// Open a large existing file with a known hash and continue writing to it.
-TEST_F(BaseFileTest, ExistingBaseFileLargeSizeKnownHash) {
- base::FilePath file_path = temp_dir_.GetPath().AppendASCII("existing");
- std::string big_buffer(1024 * 200, 'a');
- ASSERT_EQ(static_cast<int>(big_buffer.size()),
- base::WriteFile(file_path, big_buffer.data(), big_buffer.size()));
-
- // Hash of partial file (1024*200 * 'a')
- const uint8_t kExpectedPartialHash[] = {
- 0x4b, 0x4f, 0x0f, 0x46, 0xac, 0x02, 0xd1, 0x77, 0xde, 0xa0, 0xab,
- 0x36, 0xa6, 0x6a, 0x65, 0x78, 0x40, 0xe2, 0xfb, 0x98, 0xb2, 0x0b,
- 0xb2, 0x7a, 0x68, 0x8d, 0xb4, 0xd8, 0xea, 0x9c, 0xd2, 0x2c};
-
- // Hash of entire file (1024*400 * 'a')
- const uint8_t kExpectedFullHash[] = {
- 0x0c, 0xe9, 0xf6, 0x78, 0x6b, 0x0f, 0x58, 0x49, 0x36, 0xe8, 0x83,
- 0xc5, 0x09, 0x16, 0xbc, 0x5e, 0x2d, 0x07, 0x95, 0xb9, 0x42, 0x20,
- 0x41, 0x7c, 0xb3, 0x38, 0xd3, 0xf4, 0xe0, 0x78, 0x89, 0x46};
-
- ASSERT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE,
- base_file_->Initialize(
- file_path, base::FilePath(), base::File(), big_buffer.size(),
- std::string(std::begin(kExpectedPartialHash),
- std::end(kExpectedPartialHash)),
- std::unique_ptr<crypto::SecureHash>(), false));
- set_expected_data(big_buffer); // Contents of the file on Open.
- ASSERT_TRUE(AppendDataToFile(big_buffer));
- ExpectHashValue(kExpectedFullHash, base_file_->Finish());
-}
-
-// Open a large existing file. The contents doesn't match the known hash.
-TEST_F(BaseFileTest, ExistingBaseFileLargeSizeIncorrectHash) {
- base::FilePath file_path = temp_dir_.GetPath().AppendASCII("existing");
- std::string big_buffer(1024 * 200, 'a');
- ASSERT_EQ(static_cast<int>(big_buffer.size()),
- base::WriteFile(file_path, big_buffer.data(), big_buffer.size()));
-
- // Incorrect hash of partial file (1024*200 * 'a')
- const uint8_t kExpectedPartialHash[] = {
- 0xc2, 0xa9, 0x08, 0xd9, 0x8f, 0x5d, 0xf9, 0x87, 0xad, 0xe4, 0x1b,
- 0x5f, 0xce, 0x21, 0x30, 0x67, 0xef, 0x6c, 0xc2, 0x1e, 0xf2, 0x24,
- 0x02, 0x12, 0xa4, 0x1e, 0x54, 0xb5, 0xe7, 0xc2, 0x8a, 0xe5};
-
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_FILE_HASH_MISMATCH,
- base_file_->Initialize(
- file_path, base::FilePath(), base::File(), big_buffer.size(),
- std::string(std::begin(kExpectedPartialHash),
- std::end(kExpectedPartialHash)),
- std::unique_ptr<crypto::SecureHash>(), false));
- set_expected_error(download::DOWNLOAD_INTERRUPT_REASON_FILE_HASH_MISMATCH);
-}
-
-// Open an existing file. The size of the file is too short.
-TEST_F(BaseFileTest, ExistingBaseFileTooShort) {
- base::FilePath file_path = temp_dir_.GetPath().AppendASCII("existing");
- ASSERT_EQ(kTestDataLength1,
- base::WriteFile(file_path, kTestData1, kTestDataLength1));
-
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_FILE_TOO_SHORT,
- base_file_->Initialize(
- file_path, base::FilePath(), base::File(), kTestDataLength1 + 1,
- std::string(), std::unique_ptr<crypto::SecureHash>(), false));
- set_expected_error(download::DOWNLOAD_INTERRUPT_REASON_FILE_TOO_SHORT);
-}
-
-// Open an existing file. The size is larger than expected.
-TEST_F(BaseFileTest, ExistingBaseFileKnownHashTooLong) {
- base::FilePath file_path = temp_dir_.GetPath().AppendASCII("existing");
- std::string contents;
- contents.append(kTestData1);
- contents.append("Something extra");
- ASSERT_EQ(static_cast<int>(contents.size()),
- base::WriteFile(file_path, contents.data(), contents.size()));
-
- std::string hash_so_far(std::begin(kHashOfTestData1),
- std::end(kHashOfTestData1));
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE,
- base_file_->Initialize(
- file_path, base::FilePath(), base::File(), kTestDataLength1,
- hash_so_far, std::unique_ptr<crypto::SecureHash>(), false));
- set_expected_data(kTestData1); // Our starting position.
- ASSERT_TRUE(AppendDataToFile(kTestData2));
- ASSERT_TRUE(AppendDataToFile(kTestData3));
- ExpectHashValue(kHashOfTestData1To3, base_file_->Finish());
-}
-
-// Open an existing file. The size is large than expected and the hash is
-// unknown.
-TEST_F(BaseFileTest, ExistingBaseFileUnknownHashTooLong) {
- base::FilePath file_path = temp_dir_.GetPath().AppendASCII("existing");
- std::string contents;
- contents.append(kTestData1);
- contents.append("Something extra");
- ASSERT_EQ(static_cast<int>(contents.size()),
- base::WriteFile(file_path, contents.data(), contents.size()));
-
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE,
- base_file_->Initialize(
- file_path, base::FilePath(), base::File(), kTestDataLength1,
- std::string(), std::unique_ptr<crypto::SecureHash>(), false));
- set_expected_data(kTestData1);
- ASSERT_TRUE(AppendDataToFile(kTestData2));
- ASSERT_TRUE(AppendDataToFile(kTestData3));
- ExpectHashValue(kHashOfTestData1To3, base_file_->Finish());
-}
-
-// Similar to ExistingBaseFileKnownHashTooLong test, but with a file large
-// enough to requre multiple Read()s to complete. This provides additional code
-// coverage for the CalculatePartialHash() logic.
-TEST_F(BaseFileTest, ExistingBaseFileUnknownHashTooLongForLargeFile) {
- base::FilePath file_path = temp_dir_.GetPath().AppendASCII("existing");
- const size_t kFileSize = 1024 * 1024;
- const size_t kIntermediateSize = kFileSize / 2 + 111;
- // |contents| is 100 bytes longer than kIntermediateSize. The latter is the
- // expected size.
- std::string contents(kIntermediateSize + 100, 'a');
- ASSERT_EQ(static_cast<int>(contents.size()),
- base::WriteFile(file_path, contents.data(), contents.size()));
-
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE,
- base_file_->Initialize(
- file_path, base::FilePath(), base::File(), kIntermediateSize,
- std::string(), std::unique_ptr<crypto::SecureHash>(), false));
- // The extra bytes should be stripped during Initialize().
- contents.resize(kIntermediateSize, 'a');
- set_expected_data(contents);
- std::string new_data(kFileSize - kIntermediateSize, 'a');
- ASSERT_TRUE(AppendDataToFile(new_data));
- const uint8_t kExpectedHash[] = {
- 0x9b, 0xc1, 0xb2, 0xa2, 0x88, 0xb2, 0x6a, 0xf7, 0x25, 0x7a, 0x36,
- 0x27, 0x7a, 0xe3, 0x81, 0x6a, 0x7d, 0x4f, 0x16, 0xe8, 0x9c, 0x1e,
- 0x7e, 0x77, 0xd0, 0xa5, 0xc4, 0x8b, 0xad, 0x62, 0xb3, 0x60,
- };
- ExpectHashValue(kExpectedHash, base_file_->Finish());
-}
-
-// Test that a temporary file is created in the default download directory.
-TEST_F(BaseFileTest, CreatedInDefaultDirectory) {
- ASSERT_TRUE(base_file_->full_path().empty());
- ASSERT_TRUE(InitializeFile());
- EXPECT_FALSE(base_file_->full_path().empty());
-
- // On Windows, CreateTemporaryFileInDir() will cause a path with short names
- // to be expanded into a path with long names. Thus temp_dir.GetPath() might
- // not
- // be a string-wise match to base_file_->full_path().DirName() even though
- // they are in the same directory.
- base::FilePath temp_file;
- ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir_.GetPath(), &temp_file));
- ASSERT_FALSE(temp_file.empty());
- EXPECT_STREQ(temp_file.DirName().value().c_str(),
- base_file_->full_path().DirName().value().c_str());
- base_file_->Finish();
-}
-
-TEST_F(BaseFileTest, NoDoubleDeleteAfterCancel) {
- ASSERT_TRUE(InitializeFile());
- base::FilePath full_path = base_file_->full_path();
- ASSERT_FALSE(full_path.empty());
- ASSERT_TRUE(base::PathExists(full_path));
-
- base_file_->Cancel();
- ASSERT_FALSE(base::PathExists(full_path));
-
- const char kData[] = "hello";
- const int kDataLength = static_cast<int>(arraysize(kData) - 1);
- ASSERT_EQ(kDataLength, base::WriteFile(full_path, kData, kDataLength));
- // The file that we created here should stick around when the BaseFile is
- // destroyed during TearDown.
- expect_file_survives_ = true;
-}
-
-// Test that writing data to a sparse file works.
-TEST_F(BaseFileTest, WriteDataToSparseFile) {
- base::FilePath file_path = temp_dir_.GetPath().AppendASCII("existing");
- std::string contents = kTestData1;
- ASSERT_EQ(static_cast<int>(contents.size()),
- base::WriteFile(file_path, contents.data(), contents.size()));
-
- base_file_->Initialize(file_path, base::FilePath(), base::File(),
- kTestDataLength1,
- std::string(),
- std::unique_ptr<crypto::SecureHash>(),
- true);
- // This will create a hole in the file.
- base_file_->WriteDataToFile(kTestDataLength1 + kTestDataLength2,
- kTestData3,
- kTestDataLength3);
- // This should fill the hole.
- base_file_->WriteDataToFile(kTestDataLength1,
- kTestData2,
- kTestDataLength2);
- set_expected_data(contents + kTestData2 + kTestData3);
- ExpectHashValue(kHashOfTestData1To3, base_file_->Finish());
-}
-
-} // namespace content
diff --git a/chromium/content/browser/download/base_file_win.cc b/chromium/content/browser/download/base_file_win.cc
deleted file mode 100644
index 3a2a027b671..00000000000
--- a/chromium/content/browser/download/base_file_win.cc
+++ /dev/null
@@ -1,328 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/download/base_file.h"
-
-#include <windows.h>
-#include <cguid.h>
-#include <objbase.h>
-#include <shellapi.h>
-
-#include "base/files/file.h"
-#include "base/files/file_util.h"
-#include "base/guid.h"
-#include "base/macros.h"
-#include "base/metrics/histogram_macros.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/threading/thread_restrictions.h"
-#include "components/download/public/common/download_stats.h"
-#include "content/browser/download/download_interrupt_reasons_utils.h"
-#include "content/public/browser/browser_thread.h"
-#include "net/log/net_log_event_type.h"
-
-namespace content {
-namespace {
-
-const int kAllSpecialShFileOperationCodes[] = {
- // Should be kept in sync with the case statement below.
- ERROR_ACCESS_DENIED,
- ERROR_SHARING_VIOLATION,
- ERROR_INVALID_PARAMETER,
- 0x71,
- 0x72,
- 0x73,
- 0x74,
- 0x75,
- 0x76,
- 0x78,
- 0x79,
- 0x7A,
- 0x7C,
- 0x7D,
- 0x7E,
- 0x80,
- 0x81,
- 0x82,
- 0x83,
- 0x84,
- 0x85,
- 0x86,
- 0x87,
- 0x88,
- 0xB7,
- 0x402,
- 0x10000,
- 0x10074,
-};
-
-// Maps the result of a call to |SHFileOperation()| onto a
-// |DownloadInterruptReason|.
-//
-// These return codes are *old* (as in, DOS era), and specific to
-// |SHFileOperation()|.
-// They do not appear in any windows header.
-//
-// See http://msdn.microsoft.com/en-us/library/bb762164(VS.85).aspx.
-download::DownloadInterruptReason MapShFileOperationCodes(int code) {
- download::DownloadInterruptReason result =
- download::DOWNLOAD_INTERRUPT_REASON_NONE;
-
- // Check these pre-Win32 error codes first, then check for matches
- // in Winerror.h.
- // This switch statement should be kept in sync with the list of codes
- // above.
- switch (code) {
- // Not a pre-Win32 error code; here so that this particular case shows up in
- // our histograms. Unfortunately, it is used not just to signal actual
- // ACCESS_DENIED errors, but many other errors as well. So we treat it as a
- // transient error.
- case ERROR_ACCESS_DENIED: // Access is denied.
- result = download::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR;
- break;
-
- // This isn't documented but returned from SHFileOperation. Sharing
- // violations indicate that another process had the file open while we were
- // trying to rename. Anti-virus is believed to be the cause of this error in
- // the wild. Treated as a transient error on the assumption that the file
- // will be made available for renaming at a later time.
- case ERROR_SHARING_VIOLATION:
- result = download::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR;
- break;
-
- // This is also not a documented return value of SHFileOperation, but has
- // been observed in the wild. We are treating it as a transient error based
- // on the cases we have seen so far. See http://crbug.com/368455.
- case ERROR_INVALID_PARAMETER:
- result = download::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR;
- break;
-
- // The source and destination files are the same file.
- // DE_SAMEFILE == 0x71
- case 0x71:
- result = download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED;
- break;
-
- // The operation was canceled by the user, or silently canceled if the
- // appropriate flags were supplied to SHFileOperation.
- // DE_OPCANCELLED == 0x75
- case 0x75:
- result = download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED;
- break;
-
- // Security settings denied access to the source.
- // DE_ACCESSDENIEDSRC == 0x78
- case 0x78:
- result = download::DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED;
- break;
-
- // The source or destination path exceeded or would exceed MAX_PATH.
- // DE_PATHTOODEEP == 0x79
- case 0x79:
- result = download::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG;
- break;
-
- // The path in the source or destination or both was invalid.
- // DE_INVALIDFILES == 0x7C
- case 0x7C:
- result = download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED;
- break;
-
- // The destination path is an existing file.
- // DE_FLDDESTISFILE == 0x7E
- case 0x7E:
- result = download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED;
- break;
-
- // The destination path is an existing folder.
- // DE_FILEDESTISFLD == 0x80
- case 0x80:
- result = download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED;
- break;
-
- // The name of the file exceeds MAX_PATH.
- // DE_FILENAMETOOLONG == 0x81
- case 0x81:
- result = download::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG;
- break;
-
- // The destination is a read-only CD-ROM, possibly unformatted.
- // DE_DEST_IS_CDROM == 0x82
- case 0x82:
- result = download::DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED;
- break;
-
- // The destination is a read-only DVD, possibly unformatted.
- // DE_DEST_IS_DVD == 0x83
- case 0x83:
- result = download::DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED;
- break;
-
- // The destination is a writable CD-ROM, possibly unformatted.
- // DE_DEST_IS_CDRECORD == 0x84
- case 0x84:
- result = download::DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED;
- break;
-
- // The file involved in the operation is too large for the destination
- // media or file system.
- // DE_FILE_TOO_LARGE == 0x85
- case 0x85:
- result = download::DOWNLOAD_INTERRUPT_REASON_FILE_TOO_LARGE;
- break;
-
- // The source is a read-only CD-ROM, possibly unformatted.
- // DE_SRC_IS_CDROM == 0x86
- case 0x86:
- result = download::DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED;
- break;
-
- // The source is a read-only DVD, possibly unformatted.
- // DE_SRC_IS_DVD == 0x87
- case 0x87:
- result = download::DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED;
- break;
-
- // The source is a writable CD-ROM, possibly unformatted.
- // DE_SRC_IS_CDRECORD == 0x88
- case 0x88:
- result = download::DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED;
- break;
-
- // MAX_PATH was exceeded during the operation.
- // DE_ERROR_MAX == 0xB7
- case 0xB7:
- result = download::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG;
- break;
-
- // An unspecified error occurred on the destination.
- // XE_ERRORONDEST == 0x10000
- case 0x10000:
- result = download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED;
- break;
-
- // Multiple file paths were specified in the source buffer, but only one
- // destination file path.
- // DE_MANYSRC1DEST == 0x72
- case 0x72:
- result = download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED;
- break;
-
- // Rename operation was specified but the destination path is
- // a different directory. Use the move operation instead.
- // DE_DIFFDIR == 0x73
- case 0x73:
- result = download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED;
- break;
-
- // The source is a root directory, which cannot be moved or renamed.
- // DE_ROOTDIR == 0x74
- case 0x74:
- result = download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED;
- break;
-
- // The destination is a subtree of the source.
- // DE_DESTSUBTREE == 0x76
- case 0x76:
- result = download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED;
- break;
-
- // The operation involved multiple destination paths,
- // which can fail in the case of a move operation.
- // DE_MANYDEST == 0x7A
- case 0x7A:
- result = download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED;
- break;
-
- // The source and destination have the same parent folder.
- // DE_DESTSAMETREE == 0x7D
- case 0x7D:
- result = download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED;
- break;
-
- // An unknown error occurred. This is typically due to an invalid path in
- // the source or destination. This error does not occur on Windows Vista
- // and later.
- // DE_UNKNOWN_ERROR == 0x402
- case 0x402:
- result = download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED;
- break;
-
- // Destination is a root directory and cannot be renamed.
- // DE_ROOTDIR | ERRORONDEST == 0x10074
- case 0x10074:
- result = download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED;
- break;
- }
-
- // Narrow down on the reason we're getting some catch-all interrupt reasons.
- if (result == download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED) {
- UMA_HISTOGRAM_CUSTOM_ENUMERATION(
- "Download.MapWinShErrorFileFailed", code,
- base::CustomHistogram::ArrayToCustomRanges(
- kAllSpecialShFileOperationCodes,
- arraysize(kAllSpecialShFileOperationCodes)));
- }
-
- if (result == download::DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED) {
- UMA_HISTOGRAM_CUSTOM_ENUMERATION(
- "Download.MapWinShErrorAccessDenied", code,
- base::CustomHistogram::ArrayToCustomRanges(
- kAllSpecialShFileOperationCodes,
- arraysize(kAllSpecialShFileOperationCodes)));
- }
-
- if (result == download::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR) {
- UMA_HISTOGRAM_CUSTOM_ENUMERATION(
- "Download.MapWinShErrorTransientError", code,
- base::CustomHistogram::ArrayToCustomRanges(
- kAllSpecialShFileOperationCodes,
- arraysize(kAllSpecialShFileOperationCodes)));
- }
-
- if (result != download::DOWNLOAD_INTERRUPT_REASON_NONE)
- return result;
-
- // If not one of the above codes, it should be a standard Windows error code.
- return ConvertFileErrorToInterruptReason(
- base::File::OSErrorToFileError(code));
-}
-
-} // namespace
-
-// Renames a file using the SHFileOperation API to ensure that the target file
-// gets the correct default security descriptor in the new path.
-// Returns a network error, or net::OK for success.
-download::DownloadInterruptReason BaseFile::MoveFileAndAdjustPermissions(
- const base::FilePath& new_path) {
- base::AssertBlockingAllowed();
-
- // The parameters to SHFileOperation must be terminated with 2 NULL chars.
- base::FilePath::StringType source = full_path_.value();
- base::FilePath::StringType target = new_path.value();
-
- source.append(1, L'\0');
- target.append(1, L'\0');
-
- SHFILEOPSTRUCT move_info = {0};
- move_info.wFunc = FO_MOVE;
- move_info.pFrom = source.c_str();
- move_info.pTo = target.c_str();
- move_info.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI |
- FOF_NOCONFIRMMKDIR | FOF_NOCOPYSECURITYATTRIBS;
-
- int result = SHFileOperation(&move_info);
- download::DownloadInterruptReason interrupt_reason =
- download::DOWNLOAD_INTERRUPT_REASON_NONE;
-
- if (result == 0 && move_info.fAnyOperationsAborted)
- interrupt_reason = download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED;
- else if (result != 0)
- interrupt_reason = MapShFileOperationCodes(result);
-
- if (interrupt_reason != download::DOWNLOAD_INTERRUPT_REASON_NONE)
- return LogInterruptReason("SHFileOperation", result, interrupt_reason);
- return interrupt_reason;
-}
-
-} // namespace content
diff --git a/chromium/content/browser/download/base_file_win_unittest.cc b/chromium/content/browser/download/base_file_win_unittest.cc
deleted file mode 100644
index 6aa523ac2b7..00000000000
--- a/chromium/content/browser/download/base_file_win_unittest.cc
+++ /dev/null
@@ -1,116 +0,0 @@
-// Copyright 2016 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/download/base_file.h"
-
-#include "base/files/file_util.h"
-#include "base/files/scoped_temp_dir.h"
-#include "components/download/public/common/download_interrupt_reasons.h"
-#include "components/download/public/common/download_item.h"
-#include "content/public/test/test_browser_thread_bundle.h"
-#include "net/base/filename_util.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace content {
-
-TEST(BaseFileWin, AnnotateWithSourceInformation) {
- const base::FilePath::CharType kZoneIdentifierStreamName[] =
- FILE_PATH_LITERAL(":Zone.Identifier");
- const char kInternetZoneIdentifierString[] = "[ZoneTransfer]\r\nZoneId=3\r\n";
-
- struct {
- const char* const url;
- const char* const referrer;
- bool expected_internet_zone;
- } kTestCases[] = {
- // Test cases where we expect a MOTW.
- {"http://example.com", "http://example.com", true},
- {"", "http://example.com", true},
- {"", "", true},
- {"http://example.com", "", true},
- {"data:text/plain,Foo", "http://example.com", true},
- {"data:text/plain,Foo", "", true},
- {"data:text/plain,Foo", "data:text/plain,Bar", true},
- {"data:text/plain,Foo", "ftp://localhost/foo", true},
- {"http://example.com", "http://localhost/foo", true},
- {"ftp://example.com/foo", "", true},
-
- // Test cases where we don't expect a MOTW. These test cases result in
- // different behavior across Windows versions.
- {"ftp://localhost/foo", "", false},
- {"http://localhost/foo", "", false},
- {"", "http://localhost/foo", false},
- {"file:///exists.txt", "", false},
- {"file:///exists.txt", "http://example.com", false},
- {"file:///does-not-exist.txt", "", false},
- };
-
- content::TestBrowserThreadBundle threads;
- base::ScopedTempDir target_directory;
- ASSERT_TRUE(target_directory.CreateUniqueTempDir());
-
- ASSERT_EQ(
- 6, base::WriteFile(target_directory.GetPath().AppendASCII("exists.txt"),
- "Exists", 6));
-
- for (const auto& test_case : kTestCases) {
- GURL url(test_case.url);
- GURL referrer(test_case.referrer);
-
- // Resolve file:// URLs relative to our temp directory.
- if (url.SchemeIsFile()) {
- base::FilePath relative_path =
- base::FilePath().AppendASCII(url.path().substr(1));
- url = net::FilePathToFileURL(
- target_directory.GetPath().Append(relative_path));
- }
-
- SCOPED_TRACE(::testing::Message() << "Source URL: " << url.spec()
- << " Referrer: " << test_case.referrer);
-
- BaseFile base_file(download::DownloadItem::kInvalidId);
- ASSERT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE,
- base_file.Initialize(
- base::FilePath(), target_directory.GetPath(), base::File(), 0,
- std::string(), std::unique_ptr<crypto::SecureHash>(), false));
- ASSERT_FALSE(base_file.full_path().empty());
- ASSERT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE,
- base_file.Rename(
- target_directory.GetPath().AppendASCII("test_file.doc")));
- ASSERT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE,
- base_file.AnnotateWithSourceInformation(
- "7B2CEE7C-DC81-4160-86F1-9C968597118F", url, referrer));
- base_file.Detach();
- base_file.Finish();
-
- base::FilePath path = base_file.full_path();
- base::FilePath zone_identifier_stream(path.value() +
- kZoneIdentifierStreamName);
-
- ASSERT_TRUE(base::PathExists(path));
-
- std::string zone_identifier;
- base::ReadFileToString(zone_identifier_stream, &zone_identifier);
-
- if (test_case.expected_internet_zone) {
- EXPECT_STREQ(kInternetZoneIdentifierString, zone_identifier.c_str());
- } else {
- // Seeing an unexpected zone identifier is not an error, but we log a
- // warning just the same so that such cases can be identified during
- // manual testing.
- if (zone_identifier == kInternetZoneIdentifierString) {
- LOG(WARNING) << "Unexpected internet zone annotation for Source:"
- << url.spec() << " Referrer:" << test_case.referrer;
- } else if (!zone_identifier.empty()) {
- LOG(WARNING) << "Unexpected zone annotation for Source:" << url.spec()
- << " Referrer:" << test_case.referrer
- << " Annotation:" << std::endl
- << zone_identifier;
- }
- }
- base::DeleteFile(path, false);
- }
-}
-
-} // namespace content
diff --git a/chromium/content/browser/download/blob_download_url_loader_factory_getter.cc b/chromium/content/browser/download/blob_download_url_loader_factory_getter.cc
new file mode 100644
index 00000000000..93027498724
--- /dev/null
+++ b/chromium/content/browser/download/blob_download_url_loader_factory_getter.cc
@@ -0,0 +1,38 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/download/blob_download_url_loader_factory_getter.h"
+
+#include "components/download/public/common/download_task_runner.h"
+#include "content/browser/url_loader_factory_getter.h"
+#include "content/common/wrapper_shared_url_loader_factory.h"
+#include "services/network/public/mojom/url_loader_factory.mojom.h"
+#include "storage/browser/blob/blob_data_handle.h"
+#include "storage/browser/blob/blob_url_loader_factory.h"
+
+namespace content {
+
+BlobDownloadURLLoaderFactoryGetter::BlobDownloadURLLoaderFactoryGetter(
+ const GURL& url,
+ std::unique_ptr<storage::BlobDataHandle> blob_data_handle)
+ : url_(url), blob_data_handle_(std::move(blob_data_handle)) {
+ DCHECK(url.SchemeIs(url::kBlobScheme));
+}
+
+BlobDownloadURLLoaderFactoryGetter::~BlobDownloadURLLoaderFactoryGetter() =
+ default;
+
+scoped_refptr<network::SharedURLLoaderFactory>
+BlobDownloadURLLoaderFactoryGetter::GetURLLoaderFactory() {
+ DCHECK(download::GetIOTaskRunner());
+ DCHECK(download::GetIOTaskRunner()->BelongsToCurrentThread());
+ network::mojom::URLLoaderFactoryPtrInfo url_loader_factory_ptr_info;
+ storage::BlobURLLoaderFactory::Create(
+ std::move(blob_data_handle_), url_,
+ mojo::MakeRequest(&url_loader_factory_ptr_info));
+ return base::MakeRefCounted<WrapperSharedURLLoaderFactory>(
+ std::move(url_loader_factory_ptr_info));
+}
+
+} // namespace content
diff --git a/chromium/content/browser/download/blob_download_url_loader_factory_getter.h b/chromium/content/browser/download/blob_download_url_loader_factory_getter.h
new file mode 100644
index 00000000000..10938f46c42
--- /dev/null
+++ b/chromium/content/browser/download/blob_download_url_loader_factory_getter.h
@@ -0,0 +1,40 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_BROWSER_DOWNLOAD_BLOB_DOWNLOAD_URL_LOADER_FACTORY_GETTER_H_
+#define CONTENT_BROWSER_DOWNLOAD_BLOB_DOWNLOAD_URL_LOADER_FACTORY_GETTER_H_
+
+#include "components/download/public/common/download_url_loader_factory_getter.h"
+#include "url/gurl.h"
+
+namespace storage {
+class BlobDataHandle;
+}
+
+namespace content {
+
+// Class for retrieving the URLLoaderFactory for a blob URL.
+class BlobDownloadURLLoaderFactoryGetter
+ : public download::DownloadURLLoaderFactoryGetter {
+ public:
+ BlobDownloadURLLoaderFactoryGetter(
+ const GURL& url,
+ std::unique_ptr<storage::BlobDataHandle> blob_data_handle);
+
+ // download::DownloadURLLoaderFactoryGetter implementation.
+ scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory() override;
+
+ protected:
+ ~BlobDownloadURLLoaderFactoryGetter() override;
+
+ private:
+ GURL url_;
+ std::unique_ptr<storage::BlobDataHandle> blob_data_handle_;
+
+ DISALLOW_COPY_AND_ASSIGN(BlobDownloadURLLoaderFactoryGetter);
+};
+
+} // namespace content
+
+#endif // CONTENT_BROWSER_DOWNLOAD_BLOB_DOWNLOAD_URL_LOADER_FACTORY_GETTER_H_
diff --git a/chromium/content/browser/download/byte_stream_input_stream.cc b/chromium/content/browser/download/byte_stream_input_stream.cc
new file mode 100644
index 00000000000..24782195796
--- /dev/null
+++ b/chromium/content/browser/download/byte_stream_input_stream.cc
@@ -0,0 +1,59 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/download/byte_stream_input_stream.h"
+
+#include "content/browser/byte_stream.h"
+
+namespace content {
+
+ByteStreamInputStream::ByteStreamInputStream(
+ std::unique_ptr<ByteStreamReader> stream_reader)
+ : stream_reader_(std::move(stream_reader)),
+ completion_status_(download::DOWNLOAD_INTERRUPT_REASON_NONE) {}
+
+ByteStreamInputStream::~ByteStreamInputStream() = default;
+
+bool ByteStreamInputStream::IsEmpty() {
+ return !stream_reader_;
+}
+
+void ByteStreamInputStream::RegisterDataReadyCallback(
+ const mojo::SimpleWatcher::ReadyCallback& callback) {
+ if (stream_reader_) {
+ stream_reader_->RegisterCallback(
+ base::BindRepeating(callback, MOJO_RESULT_OK));
+ }
+}
+
+void ByteStreamInputStream::ClearDataReadyCallback() {
+ if (stream_reader_)
+ stream_reader_->RegisterCallback(base::RepeatingClosure());
+}
+
+download::InputStream::StreamState ByteStreamInputStream::Read(
+ scoped_refptr<net::IOBuffer>* data,
+ size_t* length) {
+ if (!stream_reader_)
+ return download::InputStream::EMPTY;
+
+ ByteStreamReader::StreamState state = stream_reader_->Read(data, length);
+ switch (state) {
+ case ByteStreamReader::STREAM_EMPTY:
+ return download::InputStream::EMPTY;
+ case ByteStreamReader::STREAM_HAS_DATA:
+ return download::InputStream::HAS_DATA;
+ case ByteStreamReader::STREAM_COMPLETE:
+ completion_status_ = static_cast<download::DownloadInterruptReason>(
+ stream_reader_->GetStatus());
+ return download::InputStream::COMPLETE;
+ }
+ return download::InputStream::EMPTY;
+}
+
+download::DownloadInterruptReason ByteStreamInputStream::GetCompletionStatus() {
+ return completion_status_;
+}
+
+} // namespace content
diff --git a/chromium/content/browser/download/byte_stream_input_stream.h b/chromium/content/browser/download/byte_stream_input_stream.h
new file mode 100644
index 00000000000..1deaeb4b5a7
--- /dev/null
+++ b/chromium/content/browser/download/byte_stream_input_stream.h
@@ -0,0 +1,43 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_BROWSER_DOWNLOAD_BYTE_STREAM_INPUT_STREAM_H_
+#define CONTENT_BROWSER_DOWNLOAD_BYTE_STREAM_INPUT_STREAM_H_
+
+#include "components/download/public/common/input_stream.h"
+#include "content/common/content_export.h"
+
+namespace content {
+
+class ByteStreamReader;
+
+// Download input stream backed by a ByteStreamReader.
+class CONTENT_EXPORT ByteStreamInputStream : public download::InputStream {
+ public:
+ explicit ByteStreamInputStream(
+ std::unique_ptr<ByteStreamReader> stream_reader);
+ ~ByteStreamInputStream() override;
+
+ // download::InputStream
+ bool IsEmpty() override;
+ void RegisterDataReadyCallback(
+ const mojo::SimpleWatcher::ReadyCallback& callback) override;
+ void ClearDataReadyCallback() override;
+ download::InputStream::StreamState Read(scoped_refptr<net::IOBuffer>* data,
+ size_t* length) override;
+ download::DownloadInterruptReason GetCompletionStatus() override;
+
+ private:
+ // ByteStreamReader to read from.
+ std::unique_ptr<ByteStreamReader> stream_reader_;
+
+ // Status when the response completes.
+ download::DownloadInterruptReason completion_status_;
+
+ DISALLOW_COPY_AND_ASSIGN(ByteStreamInputStream);
+};
+
+} // namespace content
+
+#endif // CONTENT_BROWSER_DOWNLOAD_BYTE_STREAM_INPUT_STREAM_H_
diff --git a/chromium/content/browser/download/docs/save-page-as.md b/chromium/content/browser/download/docs/save-page-as.md
index cb6f38a5cee..4493bd6b9ba 100644
--- a/chromium/content/browser/download/docs/save-page-as.md
+++ b/chromium/content/browser/download/docs/save-page-as.md
@@ -130,11 +130,11 @@ Pointers to related code outside of `//content/browser/download`:
* `//content/renderer/savable_resources...`
* Blink:
- * `//third_party/WebKit/public/web/WebFrameSerializer...`
- * `//third_party/WebKit/Source/web/WebFrameSerializerImpl...`
+ * `//third_party/blink/public/web/web_frame_serializer...`
+ * `//third_party/blink/renderere/core/frame/web_frame_serializer_impl...`
(used for Complete HTML today; should use `FrameSerializer` instead in
the long-term - see https://crbug.com/328354).
- * `//third_party/WebKit/Source/core/frame/FrameSerializer...`
+ * `//third_party/blink/renderer/core/frame/frame_serializer...`
(used for MHTML today)
- * `//third_party/WebKit/Source/platform/mhtml/MHTMLArchive...`
+ * `//third_party/blink/renderer/platform/mhtml/mhtml_archive...`
diff --git a/chromium/content/browser/download/download_browsertest.cc b/chromium/content/browser/download/download_browsertest.cc
index 7a71a1628d8..e642ee09851 100644
--- a/chromium/content/browser/download/download_browsertest.cc
+++ b/chromium/content/browser/download/download_browsertest.cc
@@ -32,17 +32,17 @@
#include "base/time/time.h"
#include "build/build_config.h"
#include "components/download/public/common/download_danger_type.h"
+#include "components/download/public/common/download_features.h"
+#include "components/download/public/common/download_file_factory.h"
+#include "components/download/public/common/download_file_impl.h"
#include "components/download/public/common/download_task_runner.h"
-#include "content/browser/download/download_file_factory.h"
-#include "content/browser/download/download_file_impl.h"
-#include "content/browser/download/download_item_impl.h"
+#include "components/download/public/common/parallel_download_configs.h"
#include "content/browser/download/download_manager_impl.h"
#include "content/browser/download/download_resource_handler.h"
-#include "content/browser/download/parallel_download_utils.h"
#include "content/browser/web_contents/web_contents_impl.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/download_request_utils.h"
#include "content/public/browser/resource_throttle.h"
-#include "content/public/common/content_features.h"
#include "content/public/common/content_paths.h"
#include "content/public/common/webplugininfo.h"
#include "content/public/test/browser_test_utils.h"
@@ -59,12 +59,13 @@
#include "content/shell/browser/shell_download_manager_delegate.h"
#include "content/shell/browser/shell_network_delegate.h"
#include "content/test/content_browser_test_utils_internal.h"
+#include "content/test/test_content_browser_client.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 "net/traffic_annotation/network_traffic_annotation_test_helper.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
@@ -99,7 +100,7 @@ const char k404Response[] = "HTTP/1.1 404 Not found\r\n\r\n";
// Implementation of TestContentBrowserClient that overrides
// AllowRenderingMhtmlOverHttp() and allows consumers to set a value.
-class DownloadTestContentBrowserClient : public ContentBrowserClient {
+class DownloadTestContentBrowserClient : public TestContentBrowserClient {
public:
DownloadTestContentBrowserClient() = default;
@@ -111,6 +112,10 @@ class DownloadTestContentBrowserClient : public ContentBrowserClient {
allowed_rendering_mhtml_over_http_ = allowed;
}
+ base::FilePath GetDefaultDownloadDirectory() override {
+ return base::FilePath();
+ }
+
private:
bool allowed_rendering_mhtml_over_http_ = false;
@@ -165,14 +170,15 @@ static DownloadManagerImpl* DownloadManagerForShell(Shell* shell) {
shell->web_contents()->GetBrowserContext()));
}
-class DownloadFileWithDelay : public DownloadFileImpl {
+class DownloadFileWithDelay : public download::DownloadFileImpl {
public:
- DownloadFileWithDelay(std::unique_ptr<download::DownloadSaveInfo> save_info,
- const base::FilePath& default_download_directory,
- std::unique_ptr<DownloadManager::InputStream> stream,
- uint32_t download_id,
- base::WeakPtr<DownloadDestinationObserver> observer,
- base::WeakPtr<DownloadFileWithDelayFactory> owner);
+ DownloadFileWithDelay(
+ std::unique_ptr<download::DownloadSaveInfo> save_info,
+ const base::FilePath& default_download_directory,
+ std::unique_ptr<download::InputStream> stream,
+ uint32_t download_id,
+ base::WeakPtr<download::DownloadDestinationObserver> observer,
+ base::WeakPtr<DownloadFileWithDelayFactory> owner);
~DownloadFileWithDelay() override;
@@ -205,18 +211,18 @@ class DownloadFileWithDelay : public DownloadFileImpl {
};
// All routines on this class must be called on the UI thread.
-class DownloadFileWithDelayFactory : public DownloadFileFactory {
+class DownloadFileWithDelayFactory : public download::DownloadFileFactory {
public:
DownloadFileWithDelayFactory();
~DownloadFileWithDelayFactory() override;
// DownloadFileFactory interface.
- DownloadFile* CreateFile(
+ download::DownloadFile* CreateFile(
std::unique_ptr<download::DownloadSaveInfo> save_info,
const base::FilePath& default_download_directory,
- std::unique_ptr<DownloadManager::InputStream> stream,
+ std::unique_ptr<download::InputStream> stream,
uint32_t download_id,
- base::WeakPtr<DownloadDestinationObserver> observer) override;
+ base::WeakPtr<download::DownloadDestinationObserver> observer) override;
void AddRenameCallback(base::Closure callback);
void GetAllRenameCallbacks(std::vector<base::Closure>* results);
@@ -235,15 +241,15 @@ class DownloadFileWithDelayFactory : public DownloadFileFactory {
DownloadFileWithDelay::DownloadFileWithDelay(
std::unique_ptr<download::DownloadSaveInfo> save_info,
const base::FilePath& default_download_directory,
- std::unique_ptr<DownloadManager::InputStream> stream,
+ std::unique_ptr<download::InputStream> stream,
uint32_t download_id,
- base::WeakPtr<DownloadDestinationObserver> observer,
+ base::WeakPtr<download::DownloadDestinationObserver> observer,
base::WeakPtr<DownloadFileWithDelayFactory> owner)
- : DownloadFileImpl(std::move(save_info),
- default_download_directory,
- std::move(stream),
- download_id,
- observer),
+ : download::DownloadFileImpl(std::move(save_info),
+ default_download_directory,
+ std::move(stream),
+ download_id,
+ observer),
owner_(owner) {}
DownloadFileWithDelay::~DownloadFileWithDelay() {}
@@ -252,7 +258,7 @@ void DownloadFileWithDelay::RenameAndUniquify(
const base::FilePath& full_path,
const RenameCompletionCallback& callback) {
DCHECK(download::GetDownloadTaskRunner()->RunsTasksInCurrentSequence());
- DownloadFileImpl::RenameAndUniquify(
+ download::DownloadFileImpl::RenameAndUniquify(
full_path, base::Bind(DownloadFileWithDelay::RenameCallbackWrapper,
owner_, callback));
}
@@ -264,13 +270,10 @@ void DownloadFileWithDelay::RenameAndAnnotate(
const GURL& referrer_url,
const RenameCompletionCallback& callback) {
DCHECK(download::GetDownloadTaskRunner()->RunsTasksInCurrentSequence());
- DownloadFileImpl::RenameAndAnnotate(
- full_path,
- client_guid,
- source_url,
- referrer_url,
- base::Bind(
- DownloadFileWithDelay::RenameCallbackWrapper, owner_, callback));
+ download::DownloadFileImpl::RenameAndAnnotate(
+ full_path, client_guid, source_url, referrer_url,
+ base::Bind(DownloadFileWithDelay::RenameCallbackWrapper, owner_,
+ callback));
}
// static
@@ -291,12 +294,12 @@ DownloadFileWithDelayFactory::DownloadFileWithDelayFactory()
DownloadFileWithDelayFactory::~DownloadFileWithDelayFactory() {}
-DownloadFile* DownloadFileWithDelayFactory::CreateFile(
+download::DownloadFile* DownloadFileWithDelayFactory::CreateFile(
std::unique_ptr<download::DownloadSaveInfo> save_info,
const base::FilePath& default_download_directory,
- std::unique_ptr<DownloadManager::InputStream> stream,
+ std::unique_ptr<download::InputStream> stream,
uint32_t download_id,
- base::WeakPtr<DownloadDestinationObserver> observer) {
+ base::WeakPtr<download::DownloadDestinationObserver> observer) {
return new DownloadFileWithDelay(
std::move(save_info), default_download_directory, std::move(stream),
download_id, observer, weak_ptr_factory_.GetWeakPtr());
@@ -304,7 +307,7 @@ DownloadFile* DownloadFileWithDelayFactory::CreateFile(
void DownloadFileWithDelayFactory::AddRenameCallback(base::Closure callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
- rename_callbacks_.push_back(callback);
+ rename_callbacks_.push_back(std::move(callback));
if (waiting_)
base::RunLoop::QuitCurrentWhenIdleDeprecated();
}
@@ -325,32 +328,34 @@ void DownloadFileWithDelayFactory::WaitForSomeCallback() {
}
}
-class CountingDownloadFile : public DownloadFileImpl {
+class CountingDownloadFile : public download::DownloadFileImpl {
public:
- CountingDownloadFile(std::unique_ptr<download::DownloadSaveInfo> save_info,
- const base::FilePath& default_downloads_directory,
- std::unique_ptr<DownloadManager::InputStream> stream,
- uint32_t download_id,
- base::WeakPtr<DownloadDestinationObserver> observer)
- : DownloadFileImpl(std::move(save_info),
- default_downloads_directory,
- std::move(stream),
- download_id,
- observer) {}
+ CountingDownloadFile(
+ std::unique_ptr<download::DownloadSaveInfo> save_info,
+ const base::FilePath& default_downloads_directory,
+ std::unique_ptr<download::InputStream> stream,
+ uint32_t download_id,
+ base::WeakPtr<download::DownloadDestinationObserver> observer)
+ : download::DownloadFileImpl(std::move(save_info),
+ default_downloads_directory,
+ std::move(stream),
+ download_id,
+ observer) {}
~CountingDownloadFile() override {
DCHECK(download::GetDownloadTaskRunner()->RunsTasksInCurrentSequence());
active_files_--;
}
- void Initialize(const InitializeCallback& callback,
+ void Initialize(InitializeCallback callback,
const CancelRequestCallback& cancel_request_callback,
const download::DownloadItem::ReceivedSlices& received_slices,
bool is_parallelizable) override {
DCHECK(download::GetDownloadTaskRunner()->RunsTasksInCurrentSequence());
active_files_++;
- DownloadFileImpl::Initialize(callback, cancel_request_callback,
- received_slices, is_parallelizable);
+ download::DownloadFileImpl::Initialize(std::move(callback),
+ cancel_request_callback,
+ received_slices, is_parallelizable);
}
static void GetNumberActiveFiles(int* result) {
@@ -377,39 +382,39 @@ class CountingDownloadFile : public DownloadFileImpl {
int CountingDownloadFile::active_files_ = 0;
-class CountingDownloadFileFactory : public DownloadFileFactory {
+class CountingDownloadFileFactory : public download::DownloadFileFactory {
public:
CountingDownloadFileFactory() {}
~CountingDownloadFileFactory() override {}
// DownloadFileFactory interface.
- DownloadFile* CreateFile(
+ download::DownloadFile* CreateFile(
std::unique_ptr<download::DownloadSaveInfo> save_info,
const base::FilePath& default_downloads_directory,
- std::unique_ptr<DownloadManager::InputStream> stream,
+ std::unique_ptr<download::InputStream> stream,
uint32_t download_id,
- base::WeakPtr<DownloadDestinationObserver> observer) override {
+ base::WeakPtr<download::DownloadDestinationObserver> observer) override {
return new CountingDownloadFile(std::move(save_info),
default_downloads_directory,
std::move(stream), download_id, observer);
}
};
-class ErrorInjectionDownloadFile : public DownloadFileImpl {
+class ErrorInjectionDownloadFile : public download::DownloadFileImpl {
public:
ErrorInjectionDownloadFile(
std::unique_ptr<download::DownloadSaveInfo> save_info,
const base::FilePath& default_downloads_directory,
- std::unique_ptr<DownloadManager::InputStream> stream,
+ std::unique_ptr<download::InputStream> stream,
uint32_t download_id,
- base::WeakPtr<DownloadDestinationObserver> observer,
+ base::WeakPtr<download::DownloadDestinationObserver> observer,
int64_t error_stream_offset,
int64_t error_stream_length)
- : DownloadFileImpl(std::move(save_info),
- default_downloads_directory,
- std::move(stream),
- download_id,
- observer),
+ : download::DownloadFileImpl(std::move(save_info),
+ default_downloads_directory,
+ std::move(stream),
+ download_id,
+ observer),
error_stream_offset_(error_stream_offset),
error_stream_length_(error_stream_length) {}
@@ -427,7 +432,8 @@ class ErrorInjectionDownloadFile : public DownloadFileImpl {
source_stream->bytes_written() >= error_stream_length_) {
return download::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED;
}
- return DownloadFileImpl::HandleStreamCompletionStatus(source_stream);
+ return download::DownloadFileImpl::HandleStreamCompletionStatus(
+ source_stream);
}
private:
@@ -437,19 +443,19 @@ class ErrorInjectionDownloadFile : public DownloadFileImpl {
// Factory for creating download files that allow error injection. All routines
// on this class must be called on the UI thread.
-class ErrorInjectionDownloadFileFactory : public DownloadFileFactory {
+class ErrorInjectionDownloadFileFactory : public download::DownloadFileFactory {
public:
ErrorInjectionDownloadFileFactory()
: download_file_(nullptr), weak_ptr_factory_(this) {}
~ErrorInjectionDownloadFileFactory() override = default;
// DownloadFileFactory interface.
- DownloadFile* CreateFile(
+ download::DownloadFile* CreateFile(
std::unique_ptr<download::DownloadSaveInfo> save_info,
const base::FilePath& default_download_directory,
- std::unique_ptr<DownloadManager::InputStream> stream,
+ std::unique_ptr<download::InputStream> stream,
uint32_t download_id,
- base::WeakPtr<DownloadDestinationObserver> observer) override {
+ base::WeakPtr<download::DownloadDestinationObserver> observer) override {
ErrorInjectionDownloadFile* download_file = new ErrorInjectionDownloadFile(
std::move(save_info), default_download_directory, std::move(stream),
download_id, observer, injected_error_offset_, injected_error_length_);
@@ -786,7 +792,7 @@ class DownloadContentTest : public ContentBrowserTest {
// Note: Cannot be used with other alternative DownloadFileFactorys
void SetupEnsureNoPendingDownloads() {
DownloadManagerForShell(shell())->SetDownloadFileFactoryForTesting(
- std::unique_ptr<DownloadFileFactory>(
+ std::unique_ptr<download::DownloadFileFactory>(
new CountingDownloadFileFactory()));
}
@@ -907,13 +913,13 @@ class ParallelDownloadTest : public DownloadContentTest {
protected:
ParallelDownloadTest() {
std::map<std::string, std::string> params = {
- {content::kMinSliceSizeFinchKey, "1"},
- {content::kParallelRequestCountFinchKey,
+ {download::kMinSliceSizeFinchKey, "1"},
+ {download::kParallelRequestCountFinchKey,
base::IntToString(kTestRequestCount)},
- {content::kParallelRequestDelayFinchKey, "0"},
- {content::kParallelRequestRemainingTimeFinchKey, "0"}};
+ {download::kParallelRequestDelayFinchKey, "0"},
+ {download::kParallelRequestRemainingTimeFinchKey, "0"}};
scoped_feature_list_.InitAndEnableFeatureWithParameters(
- features::kParallelDownloading, params);
+ download::features::kParallelDownloading, params);
}
~ParallelDownloadTest() override {}
@@ -927,18 +933,23 @@ class ParallelDownloadTest : public DownloadContentTest {
TestDownloadHttpResponse::Parameters& parameters) {
std::string output;
int64_t total_bytes = 0u;
+ const int64_t kBufferSize = 64 * 1024;
{
base::ScopedAllowBlockingForTesting allow_io_for_test_setup;
base::File file(path, base::File::FLAG_CREATE | base::File::FLAG_WRITE);
for (const auto& slice : slices) {
- total_bytes += slice.received_bytes;
-
EXPECT_TRUE(file.IsValid());
- output = TestDownloadHttpResponse::GetPatternBytes(
- parameters.pattern_generator_seed, slice.offset,
- slice.received_bytes);
- EXPECT_EQ(slice.received_bytes, file.Write(slice.offset, output.data(),
- slice.received_bytes));
+ int64_t length = slice.offset + slice.received_bytes;
+ for (int64_t offset = slice.offset; offset < length;) {
+ int64_t bytes_to_write =
+ length - offset > kBufferSize ? kBufferSize : length - offset;
+ output = TestDownloadHttpResponse::GetPatternBytes(
+ parameters.pattern_generator_seed, offset, bytes_to_write);
+ EXPECT_EQ(bytes_to_write,
+ file.Write(offset, output.data(), bytes_to_write));
+ total_bytes += bytes_to_write;
+ offset += bytes_to_write;
+ }
}
file.Close();
}
@@ -964,7 +975,8 @@ class ParallelDownloadTest : public DownloadContentTest {
const download::DownloadItem::ReceivedSlices& received_slices,
int64_t total_length,
size_t expected_request_count) {
- EXPECT_TRUE(base::FeatureList::IsEnabled(features::kParallelDownloading));
+ EXPECT_TRUE(
+ base::FeatureList::IsEnabled(download::features::kParallelDownloading));
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::Parameters parameters;
@@ -987,6 +999,7 @@ class ParallelDownloadTest : public DownloadContentTest {
// Resume the parallel download with sparse file and received slices data.
download->Resume();
WaitForCompletion(download);
+ test_response_handler()->WaitUntilCompletion(expected_request_count);
// Verify number of requests sent to the server.
const TestDownloadResponseHandler::CompletedRequests& completed_requests =
@@ -1000,7 +1013,8 @@ class ParallelDownloadTest : public DownloadContentTest {
// Verifies parallel download completion.
void RunCompletionTest(TestDownloadHttpResponse::Parameters& parameters) {
- EXPECT_TRUE(base::FeatureList::IsEnabled(features::kParallelDownloading));
+ EXPECT_TRUE(
+ base::FeatureList::IsEnabled(download::features::kParallelDownloading));
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
@@ -1024,7 +1038,7 @@ class ParallelDownloadTest : public DownloadContentTest {
// Now resume the first request.
request_pause_handler.Resume();
WaitForCompletion(download);
-
+ test_response_handler()->WaitUntilCompletion(3u);
const TestDownloadResponseHandler::CompletedRequests& completed_requests =
test_response_handler()->completed_requests();
EXPECT_EQ(kTestRequestCount, static_cast<int>(completed_requests.size()));
@@ -1140,7 +1154,7 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, CancelAtFinalRename) {
new DownloadFileWithDelayFactory();
DownloadManagerImpl* download_manager(DownloadManagerForShell(shell()));
download_manager->SetDownloadFileFactoryForTesting(
- std::unique_ptr<DownloadFileFactory>(file_factory));
+ std::unique_ptr<download::DownloadFileFactory>(file_factory));
// Create a download
NavigateToURL(shell(),
@@ -1189,7 +1203,7 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, CancelAtRelease) {
DownloadFileWithDelayFactory* file_factory =
new DownloadFileWithDelayFactory();
download_manager->SetDownloadFileFactoryForTesting(
- std::unique_ptr<DownloadFileFactory>(file_factory));
+ std::unique_ptr<download::DownloadFileFactory>(file_factory));
// Create a download
NavigateToURL(shell(),
@@ -1233,16 +1247,9 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, CancelAtRelease) {
EXPECT_EQ(download::DownloadItem::COMPLETE, items[0]->GetState());
}
-#if defined(OS_ANDROID)
-// Flaky on android: https://crbug.com/324525
-#define MAYBE_ShutdownInProgress DISABLED_ShutdownInProgress
-#else
-#define MAYBE_ShutdownInProgress ShutdownInProgress
-#endif
-
// Try to shutdown with a download in progress to make sure shutdown path
// works properly.
-IN_PROC_BROWSER_TEST_F(DownloadContentTest, MAYBE_ShutdownInProgress) {
+IN_PROC_BROWSER_TEST_F(DownloadContentTest, ShutdownInProgress) {
// Create a download that won't complete.
download::DownloadItem* download = StartDownloadAndReturnItem(
shell(), embedded_test_server()->GetURL(
@@ -1304,7 +1311,7 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, ShutdownAtRelease) {
DownloadFileWithDelayFactory* file_factory =
new DownloadFileWithDelayFactory();
download_manager->SetDownloadFileFactoryForTesting(
- std::unique_ptr<DownloadFileFactory>(file_factory));
+ std::unique_ptr<download::DownloadFileFactory>(file_factory));
// Create a download
NavigateToURL(shell(),
@@ -1366,6 +1373,9 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, StrongValidators) {
ASSERT_EQ(interruption_offset, download->GetReceivedBytes());
ASSERT_EQ(parameters.size, download->GetTotalBytes());
+ parameters.ClearInjectedErrors();
+ TestDownloadHttpResponse::StartServing(parameters, server_url);
+
download->Resume();
WaitForCompletion(download);
@@ -1456,6 +1466,9 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, RedirectBeforeResume) {
second_url);
TestDownloadHttpResponse::StartServingStaticResponse(k404Response, third_url);
+ parameters.ClearInjectedErrors();
+ TestDownloadHttpResponse::StartServing(parameters, download_url);
+
download->Resume();
WaitForCompletion(download);
@@ -1500,6 +1513,7 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, RedirectWhileResume) {
// Back to the original request handler. Resumption should now succeed, and
// use the partial data it had prior to the first interruption.
+ parameters.ClearInjectedErrors();
TestDownloadHttpResponse::StartServing(parameters, first_url);
download->Resume();
WaitForCompletion(download);
@@ -1579,6 +1593,7 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, BadRangeHeader) {
// Back to the original request handler. Resumption should now succeed, and
// use the partial data it had prior to the first interruption.
+ parameters.ClearInjectedErrors();
TestDownloadHttpResponse::StartServing(parameters, server_url);
download->Resume();
WaitForCompletion(download);
@@ -1640,6 +1655,7 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, RestartIfNotPartialResponse) {
download->Resume();
WaitForCompletion(download);
+ ASSERT_EQ(interruption_offset, download->GetBytesWasted());
ASSERT_EQ(parameters.size, download->GetReceivedBytes());
ASSERT_EQ(parameters.size, download->GetTotalBytes());
ASSERT_NO_FATAL_FAILURE(
@@ -1731,6 +1747,7 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, RestartIfNoPartialFile) {
TestDownloadHttpResponse::Parameters parameters =
TestDownloadHttpResponse::Parameters::WithSingleInterruption(
inject_error_callback());
+ int64_t interruption_offset = parameters.injected_errors.front();
TestDownloadHttpResponse::StartServing(parameters, server_url);
download::DownloadItem* download =
@@ -1750,6 +1767,7 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, RestartIfNoPartialFile) {
download->Resume();
WaitForCompletion(download);
+ ASSERT_EQ(interruption_offset, download->GetBytesWasted());
ASSERT_EQ(parameters.size, download->GetReceivedBytes());
ASSERT_EQ(parameters.size, download->GetTotalBytes());
ASSERT_NO_FATAL_FAILURE(ReadAndVerifyFileContents(
@@ -1914,18 +1932,28 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, Resume_Hash) {
StartDownloadAndReturnItem(shell(), server_url2));
WaitForInterrupt(download);
+ parameters.injected_errors.pop();
+ TestDownloadHttpResponse::StartServing(parameters, server_url2);
download->Resume();
WaitForInterrupt(download);
+ parameters.injected_errors.pop();
+ TestDownloadHttpResponse::StartServing(parameters, server_url2);
download->Resume();
WaitForInterrupt(download);
+ parameters.injected_errors.pop();
+ TestDownloadHttpResponse::StartServing(parameters, server_url2);
download->Resume();
WaitForInterrupt(download);
+ parameters.injected_errors.pop();
+ TestDownloadHttpResponse::StartServing(parameters, server_url2);
download->Resume();
WaitForInterrupt(download);
+ parameters.injected_errors.pop();
+ TestDownloadHttpResponse::StartServing(parameters, server_url2);
download->Resume();
WaitForCompletion(download);
@@ -2083,6 +2111,7 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, CancelResumingDownload) {
TestRequestPauseHandler request_pause_handler;
parameters.on_pause_handler = request_pause_handler.GetOnPauseHandler();
parameters.pause_offset = -1;
+ parameters.ClearInjectedErrors();
TestDownloadHttpResponse::StartServing(parameters, server_url);
download->Resume();
@@ -2135,6 +2164,9 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, RemoveResumedDownload) {
MockDownloadManagerObserver dm_observer(DownloadManagerForShell(shell()));
EXPECT_CALL(dm_observer, OnDownloadCreated(_, _)).Times(0);
+ parameters.ClearInjectedErrors();
+ TestDownloadHttpResponse::StartServing(parameters, server_url);
+
download->Resume();
WaitForInProgress(download);
@@ -2171,6 +2203,9 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, CancelResumedDownload) {
MockDownloadManagerObserver dm_observer(DownloadManagerForShell(shell()));
EXPECT_CALL(dm_observer, OnDownloadCreated(_, _)).Times(0);
+ parameters.ClearInjectedErrors();
+ TestDownloadHttpResponse::StartServing(parameters, server_url);
+
download->Resume();
WaitForInProgress(download);
@@ -2332,6 +2367,7 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest,
download->Resume();
WaitForCompletion(download);
+ EXPECT_EQ(kIntermediateSize, download->GetBytesWasted());
EXPECT_FALSE(PathExists(intermediate_file_path));
ReadAndVerifyFileContents(parameters.pattern_generator_seed,
parameters.size,
@@ -2605,6 +2641,8 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, ResumeRestoredDownload_LongFile) {
download->Resume();
WaitForCompletion(download);
+ // The amount "extra" that was added to the file.
+ EXPECT_EQ(100, download->GetBytesWasted());
EXPECT_FALSE(PathExists(intermediate_file_path));
ReadAndVerifyFileContents(parameters.pattern_generator_seed,
parameters.size,
@@ -2642,6 +2680,9 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, ReferrerForPartialResumption) {
StartDownloadAndReturnItem(shell(), document_url);
WaitForInterrupt(download);
+ parameters.ClearInjectedErrors();
+ TestDownloadHttpResponse::StartServing(parameters, server_url);
+
download->Resume();
WaitForCompletion(download);
@@ -3099,8 +3140,7 @@ IN_PROC_BROWSER_TEST_F(ParallelDownloadTest, LastRequestRejected) {
parameters.etag = "ABC";
parameters.size = 5097152;
// The 3rd request will always fail. Other requests should take over.
- parameters.SetResponseForRangeRequest(3398000, -1, k404Response,
- std::string());
+ parameters.SetResponseForRangeRequest(3398000, -1, k404Response);
RunCompletionTest(parameters);
}
@@ -3112,8 +3152,7 @@ IN_PROC_BROWSER_TEST_F(ParallelDownloadTest, SecondRequestRejected) {
parameters.etag = "ABC";
parameters.size = 5097152;
// The 2nd request will always fail. Other requests should take over.
- parameters.SetResponseForRangeRequest(1699000, 2000000, k404Response,
- std::string());
+ parameters.SetResponseForRangeRequest(1699000, 2000000, k404Response);
RunCompletionTest(parameters);
}
@@ -3126,7 +3165,7 @@ IN_PROC_BROWSER_TEST_F(ParallelDownloadTest, OnlyFirstRequestValid) {
// 2nd and 3rd request will fail, the original request should complete the
// download.
- parameters.SetResponseForRangeRequest(1000, -1, k404Response, std::string());
+ parameters.SetResponseForRangeRequest(1000, -1, k404Response);
RunCompletionTest(parameters);
}
@@ -3161,16 +3200,7 @@ IN_PROC_BROWSER_TEST_F(ParallelDownloadTest, ResumptionLastSliceFinished) {
// Verifies that if the last slice is finished, but the database record is not
// finished, which may happen in database migration.
// When the server sends HTTP range not satisfied, the download can complete.
-#if defined(OS_WIN) || defined(OS_ANDROID)
-// Failing on Windows: https://crbug.com/814310
-// Failing on Android: https://crbug.com/817801
-#define MAYBE_ResumptionLastSliceUnfinished \
- DISABLED_ResumptionLastSliceUnfinished
-#else
-#define MAYBE_ResumptionLastSliceUnfinished ResumptionLastSliceUnfinished
-#endif
-IN_PROC_BROWSER_TEST_F(ParallelDownloadTest,
- MAYBE_ResumptionLastSliceUnfinished) {
+IN_PROC_BROWSER_TEST_F(ParallelDownloadTest, ResumptionLastSliceUnfinished) {
// Create the received slices data, last slice is actually finished.
std::vector<download::DownloadItem::ReceivedSlice> received_slices = {
download::DownloadItem::ReceivedSlice(0, 1000),
@@ -3288,6 +3318,7 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, UploadBytes) {
// Verify the case that the first response is HTTP 200, and then interrupted,
// and the second response is HTTP 404, the response body of 404 should be
// fetched.
+// Also verify the request header is correctly piped to download item.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, FetchErrorResponseBodyResumption) {
SetupErrorInjectionDownloads();
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
@@ -3302,6 +3333,8 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, FetchErrorResponseBodyResumption) {
DownloadRequestUtils::CreateDownloadForWebContentsMainFrame(
shell()->web_contents(), server_url, TRAFFIC_ANNOTATION_FOR_TESTS));
download_parameters->set_fetch_error_body(true);
+ download_parameters->add_request_header("header_key", "header_value");
+
DownloadManager* download_manager = DownloadManagerForShell(shell());
std::unique_ptr<DownloadTestObserver> observer;
@@ -3332,6 +3365,14 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, FetchErrorResponseBodyResumption) {
base::ReadFileToString(items[0]->GetTargetFilePath(), &file_content));
EXPECT_EQ(std::string(), file_content);
}
+
+ // Additional request header should be sent.
+ test_response_handler()->WaitUntilCompletion(2u);
+ const auto& request = test_response_handler()->completed_requests().back();
+ auto it = request->http_request.headers.find("header_key");
+ EXPECT_TRUE(it != request->http_request.headers.end());
+ EXPECT_EQ(request->http_request.headers["header_key"],
+ std::string("header_value"));
}
IN_PROC_BROWSER_TEST_F(DownloadContentTest, ForceDownloadMultipartRelatedPage) {
diff --git a/chromium/content/browser/download/download_destination_observer.h b/chromium/content/browser/download/download_destination_observer.h
deleted file mode 100644
index 224adc111cf..00000000000
--- a/chromium/content/browser/download/download_destination_observer.h
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_DESTINATION_OBSERVER_H_
-#define CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_DESTINATION_OBSERVER_H_
-
-#include <stdint.h>
-
-#include <memory>
-#include <string>
-
-#include "components/download/public/common/download_interrupt_reasons.h"
-#include "components/download/public/common/download_item.h"
-#include "crypto/secure_hash.h"
-
-namespace content {
-
-// Class that receives asynchronous events from a DownloadDestination about
-// downloading progress and completion. These should report status when the
-// data arrives at its final location; i.e. DestinationUpdate should be
-// called after the destination is finished with whatever operation it
-// is doing on the data described by |bytes_so_far| and DestinationCompleted
-// should only be called once that is true for all data.
-//
-// All methods are invoked on the UI thread.
-//
-// Note that this interface does not deal with cross-thread lifetime issues.
-class DownloadDestinationObserver {
- public:
- virtual void DestinationUpdate(
- int64_t bytes_so_far,
- int64_t bytes_per_sec,
- const std::vector<download::DownloadItem::ReceivedSlice>&
- received_slices) = 0;
-
- virtual void DestinationError(
- download::DownloadInterruptReason reason,
- int64_t bytes_so_far,
- std::unique_ptr<crypto::SecureHash> hash_state) = 0;
-
- virtual void DestinationCompleted(
- int64_t total_bytes,
- std::unique_ptr<crypto::SecureHash> hash_state) = 0;
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_DESTINATION_OBSERVER_H_
diff --git a/chromium/content/browser/download/download_file.h b/chromium/content/browser/download/download_file.h
deleted file mode 100644
index f531890fd81..00000000000
--- a/chromium/content/browser/download/download_file.h
+++ /dev/null
@@ -1,110 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_FILE_H_
-#define CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_FILE_H_
-
-#include <stdint.h>
-
-#include <memory>
-#include <string>
-
-#include "base/callback_forward.h"
-#include "base/files/file_path.h"
-#include "components/download/public/common/download_interrupt_reasons.h"
-#include "components/download/public/common/download_item.h"
-#include "content/common/content_export.h"
-#include "content/public/browser/download_manager.h"
-#include "mojo/public/cpp/system/data_pipe.h"
-
-class GURL;
-
-namespace content {
-
-// These objects live exclusively on the download sequence and handle the
-// writing operations for one download. These objects live only for the duration
-// that the download is 'in progress': once the download has been completed or
-// cancelled, the DownloadFile is destroyed.
-class CONTENT_EXPORT DownloadFile {
- public:
- // Callback used with Initialize. On a successful initialize, |reason| will
- // be DOWNLOAD_INTERRUPT_REASON_NONE; on a failed initialize, it will be
- // set to the reason for the failure.
- typedef base::Callback<void(download::DownloadInterruptReason reason)>
- InitializeCallback;
-
- // Callback used with Rename*(). On a successful rename |reason| will be
- // DOWNLOAD_INTERRUPT_REASON_NONE and |path| the path the rename
- // was done to. On a failed rename, |reason| will contain the
- // error.
- typedef base::Callback<void(download::DownloadInterruptReason reason,
- const base::FilePath& path)>
- RenameCompletionCallback;
-
- // Used to drop the request, when the byte stream reader should be closed on
- // download sequence.
- typedef base::Callback<void(int64_t offset)> CancelRequestCallback;
-
- virtual ~DownloadFile() {}
-
- // Upon completion, |initialize_callback| will be called on the UI
- // thread as per the comment above, passing DOWNLOAD_INTERRUPT_REASON_NONE
- // on success, or a network download interrupt reason on failure.
- virtual void Initialize(
- const InitializeCallback& initialize_callback,
- const CancelRequestCallback& cancel_request_callback,
- const download::DownloadItem::ReceivedSlices& received_slices,
- bool is_parallelizable) = 0;
-
- // Add an input stream to write into a slice of the file, used for
- // parallel download.
- virtual void AddInputStream(
- std::unique_ptr<DownloadManager::InputStream> stream,
- int64_t offset,
- int64_t length) = 0;
-
- // Called when the response for the stream starting at |offset| is completed,
- virtual void OnResponseCompleted(
- int64_t offset,
- download::DownloadInterruptReason status) = 0;
-
- // Rename the download file to |full_path|. If that file exists
- // |full_path| will be uniquified by suffixing " (<number>)" to the
- // file name before the extension.
- virtual void RenameAndUniquify(const base::FilePath& full_path,
- const RenameCompletionCallback& callback) = 0;
-
- // Rename the download file to |full_path| and annotate it with
- // "Mark of the Web" information about its source. No uniquification
- // will be performed.
- virtual void RenameAndAnnotate(const base::FilePath& full_path,
- const std::string& client_guid,
- const GURL& source_url,
- const GURL& referrer_url,
- const RenameCompletionCallback& callback) = 0;
-
- // Detach the file so it is not deleted on destruction.
- virtual void Detach() = 0;
-
- // Abort the download and automatically close the file.
- virtual void Cancel() = 0;
-
- // Sets the potential file length. This is called when a half-open range
- // request fails or completes successfully. If the range request fails, the
- // file length should not be larger than the request's offset. If the range
- // request completes successfully, the file length can be determined by
- // the request offset and the bytes received. So |length| may not be the
- // actual file length, but it should not be smaller than it.
- virtual void SetPotentialFileLength(int64_t length) = 0;
-
- virtual const base::FilePath& FullPath() const = 0;
- virtual bool InProgress() const = 0;
-
- virtual void Pause() = 0;
- virtual void Resume() = 0;
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_FILE_H_
diff --git a/chromium/content/browser/download/download_file_factory.cc b/chromium/content/browser/download/download_file_factory.cc
deleted file mode 100644
index 1b457ea9804..00000000000
--- a/chromium/content/browser/download/download_file_factory.cc
+++ /dev/null
@@ -1,25 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/download/download_file_factory.h"
-
-#include <utility>
-
-#include "content/browser/download/download_file_impl.h"
-
-namespace content {
-
-DownloadFileFactory::~DownloadFileFactory() {}
-
-DownloadFile* DownloadFileFactory::CreateFile(
- std::unique_ptr<download::DownloadSaveInfo> save_info,
- const base::FilePath& default_downloads_directory,
- std::unique_ptr<DownloadManager::InputStream> stream,
- uint32_t download_id,
- base::WeakPtr<DownloadDestinationObserver> observer) {
- return new DownloadFileImpl(std::move(save_info), default_downloads_directory,
- std::move(stream), download_id, observer);
-}
-
-} // namespace content
diff --git a/chromium/content/browser/download/download_file_factory.h b/chromium/content/browser/download/download_file_factory.h
deleted file mode 100644
index 6dcf3c5bce4..00000000000
--- a/chromium/content/browser/download/download_file_factory.h
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-//
-#ifndef CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_FILE_FACTORY_H_
-#define CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_FILE_FACTORY_H_
-
-#include <memory>
-#include <vector>
-
-#include "base/files/file.h"
-#include "base/files/file_path.h"
-#include "base/memory/ref_counted.h"
-#include "base/memory/weak_ptr.h"
-#include "content/browser/download/url_download_handler.h"
-#include "content/common/content_export.h"
-#include "url/gurl.h"
-
-namespace download {
-struct DownloadSaveInfo;
-}
-
-namespace content {
-
-class DownloadDestinationObserver;
-class DownloadFile;
-
-class CONTENT_EXPORT DownloadFileFactory {
- public:
- virtual ~DownloadFileFactory();
-
- virtual DownloadFile* CreateFile(
- std::unique_ptr<download::DownloadSaveInfo> save_info,
- const base::FilePath& default_downloads_directory,
- std::unique_ptr<DownloadManager::InputStream> stream,
- uint32_t download_id,
- base::WeakPtr<DownloadDestinationObserver> observer);
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_FILE_FACTORY_H_
diff --git a/chromium/content/browser/download/download_file_impl.cc b/chromium/content/browser/download/download_file_impl.cc
deleted file mode 100644
index a5fa050c256..00000000000
--- a/chromium/content/browser/download/download_file_impl.cc
+++ /dev/null
@@ -1,908 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/download/download_file_impl.h"
-
-#include <string>
-#include <utility>
-
-#include "base/bind.h"
-#include "base/files/file_util.h"
-#include "base/memory/ptr_util.h"
-#include "base/strings/stringprintf.h"
-#include "base/threading/sequenced_task_runner_handle.h"
-#include "base/time/time.h"
-#include "base/values.h"
-#include "components/download/public/common/download_create_info.h"
-#include "components/download/public/common/download_stats.h"
-#include "content/browser/byte_stream.h"
-#include "content/browser/download/download_destination_observer.h"
-#include "content/browser/download/download_interrupt_reasons_utils.h"
-#include "content/browser/download/download_utils.h"
-#include "content/browser/download/parallel_download_utils.h"
-#include "content/public/browser/browser_thread.h"
-#include "content/public/common/content_features.h"
-#include "crypto/secure_hash.h"
-#include "crypto/sha2.h"
-#include "mojo/public/c/system/types.h"
-#include "net/base/io_buffer.h"
-#include "services/network/public/cpp/features.h"
-
-namespace content {
-
-namespace {
-
-const int kUpdatePeriodMs = 500;
-const int kMaxTimeBlockingFileThreadMs = 1000;
-
-// These constants control the default retry behavior for failing renames. Each
-// retry is performed after a delay that is twice the previous delay. The
-// initial delay is specified by kInitialRenameRetryDelayMs.
-const int kInitialRenameRetryDelayMs = 200;
-
-// Number of times a failing rename is retried before giving up.
-const int kMaxRenameRetries = 3;
-
-// Because DownloadSaveInfo::kLengthFullContent is 0, we should avoid using
-// 0 for length if we found that a stream can no longer write any data.
-const int kNoBytesToWrite = -1;
-
-// Default content length when the potential file size is not yet determined.
-const int kUnknownContentLength = -1;
-
-// Data length to read from data pipe.
-const int kBytesToRead = 4096;
-
-} // namespace
-
-DownloadFileImpl::SourceStream::SourceStream(
- int64_t offset,
- int64_t length,
- std::unique_ptr<DownloadManager::InputStream> stream)
- : offset_(offset),
- length_(length),
- bytes_written_(0),
- finished_(false),
- index_(0u),
- stream_reader_(std::move(stream->stream_reader_)),
- completion_status_(download::DOWNLOAD_INTERRUPT_REASON_NONE),
- is_response_completed_(false),
- stream_handle_(std::move(stream->stream_handle_)) {}
-
-DownloadFileImpl::SourceStream::~SourceStream() = default;
-
-void DownloadFileImpl::SourceStream::Initialize() {
- if (stream_handle_.is_null())
- return;
- binding_ =
- std::make_unique<mojo::Binding<download::mojom::DownloadStreamClient>>(
- this, std::move(stream_handle_->client_request));
- binding_->set_connection_error_handler(
- base::BindOnce(&DownloadFileImpl::SourceStream::OnStreamCompleted,
- base::Unretained(this),
- download::mojom::NetworkRequestStatus::USER_CANCELED));
- handle_watcher_ = std::make_unique<mojo::SimpleWatcher>(
- FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::AUTOMATIC);
-}
-
-void DownloadFileImpl::SourceStream::OnStreamCompleted(
- download::mojom::NetworkRequestStatus status) {
- // This can be called before or after data pipe is completely drained. So we
- // need to pass the |completion_status_| to DownloadFileImpl if the data pipe
- // is already drained.
- OnResponseCompleted(ConvertMojoNetworkRequestStatusToInterruptReason(status));
-}
-
-void DownloadFileImpl::SourceStream::OnResponseCompleted(
- download::DownloadInterruptReason reason) {
- is_response_completed_ = true;
- completion_status_ = reason;
- if (completion_callback_)
- std::move(completion_callback_).Run(this);
-}
-
-void DownloadFileImpl::SourceStream::OnWriteBytesToDisk(int64_t bytes_write) {
- bytes_written_ += bytes_write;
-}
-
-void DownloadFileImpl::SourceStream::TruncateLengthWithWrittenDataBlock(
- int64_t offset,
- int64_t bytes_written) {
- DCHECK_GT(bytes_written, 0);
- if (length_ == kNoBytesToWrite)
- return;
-
- if (offset <= offset_) {
- if (offset + bytes_written > offset_) {
- length_ = kNoBytesToWrite;
- finished_ = true;
- }
- return;
- }
-
- if (length_ == download::DownloadSaveInfo::kLengthFullContent ||
- length_ > offset - offset_) {
- length_ = offset - offset_;
- }
-}
-
-void DownloadFileImpl::SourceStream::RegisterDataReadyCallback(
- const mojo::SimpleWatcher::ReadyCallback& callback) {
- if (handle_watcher_) {
- handle_watcher_->Watch(stream_handle_->stream.get(),
- MOJO_HANDLE_SIGNAL_READABLE, callback);
- } else if (stream_reader_) {
- stream_reader_->RegisterCallback(base::Bind(callback, MOJO_RESULT_OK));
- }
-}
-
-void DownloadFileImpl::SourceStream::ClearDataReadyCallback() {
- if (handle_watcher_)
- handle_watcher_->Cancel();
- else if (stream_reader_)
- stream_reader_->RegisterCallback(base::Closure());
-}
-
-download::DownloadInterruptReason
-DownloadFileImpl::SourceStream::GetCompletionStatus() const {
- return completion_status_;
-}
-
-void DownloadFileImpl::SourceStream::RegisterCompletionCallback(
- DownloadFileImpl::SourceStream::CompletionCallback callback) {
- completion_callback_ = std::move(callback);
-}
-
-DownloadFileImpl::SourceStream::StreamState
-DownloadFileImpl::SourceStream::Read(scoped_refptr<net::IOBuffer>* data,
- size_t* length) {
- if (handle_watcher_) {
- *length = kBytesToRead;
- *data = new net::IOBuffer(kBytesToRead);
- MojoResult mojo_result = stream_handle_->stream->ReadData(
- (*data)->data(), (uint32_t*)length, MOJO_READ_DATA_FLAG_NONE);
- // TODO(qinmin): figure out when COMPLETE should be returned.
- switch (mojo_result) {
- case MOJO_RESULT_OK:
- return HAS_DATA;
- case MOJO_RESULT_SHOULD_WAIT:
- return EMPTY;
- case MOJO_RESULT_FAILED_PRECONDITION:
- if (is_response_completed_)
- return COMPLETE;
- stream_handle_->stream.reset();
- ClearDataReadyCallback();
- return WAIT_FOR_COMPLETION;
- case MOJO_RESULT_INVALID_ARGUMENT:
- case MOJO_RESULT_OUT_OF_RANGE:
- case MOJO_RESULT_BUSY:
- NOTREACHED();
- return COMPLETE;
- }
- } else if (stream_reader_) {
- ByteStreamReader::StreamState state = stream_reader_->Read(data, length);
- switch (state) {
- case ByteStreamReader::STREAM_EMPTY:
- return EMPTY;
- case ByteStreamReader::STREAM_HAS_DATA:
- return HAS_DATA;
- case ByteStreamReader::STREAM_COMPLETE:
- download::DownloadInterruptReason reason =
- static_cast<download::DownloadInterruptReason>(
- stream_reader_->GetStatus());
- OnResponseCompleted(reason);
- return COMPLETE;
- }
- }
- return COMPLETE;
-}
-
-DownloadFileImpl::DownloadFileImpl(
- std::unique_ptr<download::DownloadSaveInfo> save_info,
- const base::FilePath& default_download_directory,
- std::unique_ptr<DownloadManager::InputStream> stream,
- uint32_t download_id,
- base::WeakPtr<DownloadDestinationObserver> observer)
- : DownloadFileImpl(std::move(save_info),
- default_download_directory,
- download_id,
- observer) {
- source_streams_[save_info_->offset] = std::make_unique<SourceStream>(
- save_info_->offset, save_info_->length, std::move(stream));
-}
-
-DownloadFileImpl::DownloadFileImpl(
- std::unique_ptr<download::DownloadSaveInfo> save_info,
- const base::FilePath& default_download_directory,
- uint32_t download_id,
- base::WeakPtr<DownloadDestinationObserver> observer)
- : file_(download_id),
- save_info_(std::move(save_info)),
- default_download_directory_(default_download_directory),
- potential_file_length_(kUnknownContentLength),
- bytes_seen_(0),
- num_active_streams_(0),
- record_stream_bandwidth_(false),
- bytes_seen_with_parallel_streams_(0),
- bytes_seen_without_parallel_streams_(0),
- is_paused_(false),
- download_id_(download_id),
- observer_(observer),
- weak_factory_(this) {
- TRACE_EVENT_INSTANT0("download", "DownloadFileCreated",
- TRACE_EVENT_SCOPE_THREAD);
- TRACE_EVENT_NESTABLE_ASYNC_BEGIN0("download", "DownloadFileActive",
- download_id);
-
- DETACH_FROM_SEQUENCE(sequence_checker_);
-}
-
-DownloadFileImpl::~DownloadFileImpl() {
- DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
-
- TRACE_EVENT_NESTABLE_ASYNC_END0("download", "DownloadFileActive",
- download_id_);
-}
-
-void DownloadFileImpl::Initialize(
- const InitializeCallback& initialize_callback,
- const CancelRequestCallback& cancel_request_callback,
- const download::DownloadItem::ReceivedSlices& received_slices,
- bool is_parallelizable) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
-
- update_timer_.reset(new base::RepeatingTimer());
- int64_t bytes_so_far = 0;
- cancel_request_callback_ = cancel_request_callback;
- received_slices_ = received_slices;
-
- // If the last slice is finished, then we know the actual content size.
- if (!received_slices_.empty() && received_slices_.back().finished) {
- SetPotentialFileLength(received_slices_.back().offset +
- received_slices_.back().received_bytes);
- }
-
- if (IsSparseFile()) {
- for (const auto& received_slice : received_slices_) {
- bytes_so_far += received_slice.received_bytes;
- }
- } else {
- bytes_so_far = save_info_->offset;
- }
- download::DownloadInterruptReason result =
- file_.Initialize(save_info_->file_path, default_download_directory_,
- std::move(save_info_->file), bytes_so_far,
- save_info_->hash_of_partial_file,
- std::move(save_info_->hash_state), IsSparseFile());
- if (result != download::DOWNLOAD_INTERRUPT_REASON_NONE) {
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
- base::BindOnce(initialize_callback, result));
- return;
- }
- download_start_ = base::TimeTicks::Now();
- last_update_time_ = download_start_;
- record_stream_bandwidth_ = is_parallelizable;
-
- // Primarily to make reset to zero in restart visible to owner.
- SendUpdate();
-
- BrowserThread::PostTask(
- BrowserThread::UI, FROM_HERE,
- base::BindOnce(initialize_callback,
- download::DOWNLOAD_INTERRUPT_REASON_NONE));
-
- // Initial pull from the straw from all source streams.
- for (auto& source_stream : source_streams_)
- RegisterAndActivateStream(source_stream.second.get());
-}
-
-void DownloadFileImpl::AddInputStream(
- std::unique_ptr<DownloadManager::InputStream> stream,
- int64_t offset,
- int64_t length) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
-
- // UI thread may not be notified about completion and detach download file,
- // clear up the network request.
- if (IsDownloadCompleted()) {
- CancelRequest(offset);
- return;
- }
-
- source_streams_[offset] =
- std::make_unique<SourceStream>(offset, length, std::move(stream));
- OnSourceStreamAdded(source_streams_[offset].get());
-}
-
-void DownloadFileImpl::OnResponseCompleted(
- int64_t offset,
- download::DownloadInterruptReason status) {
- auto iter = source_streams_.find(offset);
- if (iter != source_streams_.end())
- iter->second->OnResponseCompleted(status);
-}
-
-void DownloadFileImpl::OnSourceStreamAdded(SourceStream* source_stream) {
- // There are writers at different offsets now, create the received slices
- // vector if necessary.
- if (received_slices_.empty() && TotalBytesReceived() > 0) {
- size_t index = AddOrMergeReceivedSliceIntoSortedArray(
- download::DownloadItem::ReceivedSlice(0, TotalBytesReceived()),
- received_slices_);
- DCHECK_EQ(index, 0u);
- }
- // If the file is initialized, start to write data, or wait until file opened.
- if (file_.in_progress())
- RegisterAndActivateStream(source_stream);
-}
-
-download::DownloadInterruptReason DownloadFileImpl::WriteDataToFile(
- int64_t offset,
- const char* data,
- size_t data_len) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
-
- WillWriteToDisk(data_len);
- return file_.WriteDataToFile(offset, data, data_len);
-}
-
-bool DownloadFileImpl::CalculateBytesToWrite(SourceStream* source_stream,
- size_t bytes_available_to_write,
- size_t* bytes_to_write) {
- if (source_stream->length() == kNoBytesToWrite) {
- *bytes_to_write = 0;
- return true;
- }
-
- // If a new slice finds that its target position has already been written,
- // terminate the stream.
- if (source_stream->bytes_written() == 0) {
- for (const auto& received_slice : received_slices_) {
- if (received_slice.offset <= source_stream->offset() &&
- received_slice.offset + received_slice.received_bytes >
- source_stream->offset()) {
- *bytes_to_write = 0;
- return true;
- }
- }
- }
-
- if (source_stream->length() !=
- download::DownloadSaveInfo::kLengthFullContent &&
- source_stream->bytes_written() +
- static_cast<int64_t>(bytes_available_to_write) >
- source_stream->length()) {
- // Write a partial buffer as the incoming data exceeds the length limit.
- *bytes_to_write = source_stream->length() - source_stream->bytes_written();
- return true;
- }
-
- *bytes_to_write = bytes_available_to_write;
- return false;
-}
-
-void DownloadFileImpl::RenameAndUniquify(
- const base::FilePath& full_path,
- const RenameCompletionCallback& callback) {
- std::unique_ptr<RenameParameters> parameters(
- new RenameParameters(UNIQUIFY, full_path, callback));
- RenameWithRetryInternal(std::move(parameters));
-}
-
-void DownloadFileImpl::RenameAndAnnotate(
- const base::FilePath& full_path,
- const std::string& client_guid,
- const GURL& source_url,
- const GURL& referrer_url,
- const RenameCompletionCallback& callback) {
- std::unique_ptr<RenameParameters> parameters(new RenameParameters(
- ANNOTATE_WITH_SOURCE_INFORMATION, full_path, callback));
- parameters->client_guid = client_guid;
- parameters->source_url = source_url;
- parameters->referrer_url = referrer_url;
- RenameWithRetryInternal(std::move(parameters));
-}
-
-base::TimeDelta DownloadFileImpl::GetRetryDelayForFailedRename(
- int attempt_number) {
- DCHECK_GE(attempt_number, 0);
- // |delay| starts at kInitialRenameRetryDelayMs and increases by a factor of
- // 2 at each subsequent retry. Assumes that |retries_left| starts at
- // kMaxRenameRetries. Also assumes that kMaxRenameRetries is less than the
- // number of bits in an int.
- return base::TimeDelta::FromMilliseconds(kInitialRenameRetryDelayMs) *
- (1 << attempt_number);
-}
-
-bool DownloadFileImpl::ShouldRetryFailedRename(
- download::DownloadInterruptReason reason) {
- return reason == download::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR;
-}
-
-download::DownloadInterruptReason
-DownloadFileImpl::HandleStreamCompletionStatus(SourceStream* source_stream) {
- download::DownloadInterruptReason reason =
- source_stream->GetCompletionStatus();
- if (source_stream->length() ==
- download::DownloadSaveInfo::kLengthFullContent &&
- !received_slices_.empty() &&
- (source_stream->offset() == received_slices_.back().offset +
- received_slices_.back().received_bytes) &&
- reason == download::DOWNLOAD_INTERRUPT_REASON_SERVER_NO_RANGE) {
- // We are probably reaching the end of the stream, don't treat this
- // as an error.
- return download::DOWNLOAD_INTERRUPT_REASON_NONE;
- }
- return reason;
-}
-
-void DownloadFileImpl::RenameWithRetryInternal(
- std::unique_ptr<RenameParameters> parameters) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
-
- base::FilePath new_path = parameters->new_path;
-
- if ((parameters->option & UNIQUIFY) && new_path != file_.full_path()) {
- int uniquifier =
- base::GetUniquePathNumber(new_path, base::FilePath::StringType());
- if (uniquifier > 0)
- new_path = new_path.InsertBeforeExtensionASCII(
- base::StringPrintf(" (%d)", uniquifier));
- }
-
- download::DownloadInterruptReason reason = file_.Rename(new_path);
-
- // Attempt to retry the rename if possible. If the rename failed and the
- // subsequent open also failed, then in_progress() would be false. We don't
- // try to retry renames if the in_progress() was false to begin with since we
- // have less assurance that the file at file_.full_path() was the one we were
- // working with.
- if (ShouldRetryFailedRename(reason) && file_.in_progress() &&
- parameters->retries_left > 0) {
- int attempt_number = kMaxRenameRetries - parameters->retries_left;
- --parameters->retries_left;
- if (parameters->time_of_first_failure.is_null())
- parameters->time_of_first_failure = base::TimeTicks::Now();
- base::SequencedTaskRunnerHandle::Get()->PostDelayedTask(
- FROM_HERE,
- base::BindOnce(&DownloadFileImpl::RenameWithRetryInternal,
- weak_factory_.GetWeakPtr(), std::move(parameters)),
- GetRetryDelayForFailedRename(attempt_number));
- return;
- }
-
- if (!parameters->time_of_first_failure.is_null()) {
- download::RecordDownloadFileRenameResultAfterRetry(
- base::TimeTicks::Now() - parameters->time_of_first_failure, reason);
- }
-
- if (reason == download::DOWNLOAD_INTERRUPT_REASON_NONE &&
- (parameters->option & ANNOTATE_WITH_SOURCE_INFORMATION)) {
- // Doing the annotation after the rename rather than before leaves
- // a very small window during which the file has the final name but
- // hasn't been marked with the Mark Of The Web. However, it allows
- // anti-virus scanners on Windows to actually see the data
- // (http://crbug.com/127999) under the correct name (which is information
- // it uses).
- reason = file_.AnnotateWithSourceInformation(parameters->client_guid,
- parameters->source_url,
- parameters->referrer_url);
- }
-
- if (reason != download::DOWNLOAD_INTERRUPT_REASON_NONE) {
- // Make sure our information is updated, since we're about to
- // error out.
- SendUpdate();
-
- // Null out callback so that we don't do any more stream processing.
- // The request that writes to the pipe should be canceled after
- // the download being interrupted.
- for (auto& stream : source_streams_)
- stream.second->ClearDataReadyCallback();
-
- new_path.clear();
- }
-
- BrowserThread::PostTask(
- BrowserThread::UI, FROM_HERE,
- base::BindOnce(parameters->completion_callback, reason, new_path));
-}
-
-void DownloadFileImpl::Detach() {
- file_.Detach();
-}
-
-void DownloadFileImpl::Cancel() {
- file_.Cancel();
-}
-
-void DownloadFileImpl::SetPotentialFileLength(int64_t length) {
- DCHECK(potential_file_length_ == length ||
- potential_file_length_ == kUnknownContentLength)
- << "Potential file length changed, the download might have updated.";
-
- if (length < potential_file_length_ ||
- potential_file_length_ == kUnknownContentLength) {
- potential_file_length_ = length;
- }
-
- // TODO(qinmin): interrupt the download if the received bytes are larger
- // than content length limit.
- LOG_IF(ERROR, TotalBytesReceived() > potential_file_length_)
- << "Received data is larger than the content length limit.";
-}
-
-const base::FilePath& DownloadFileImpl::FullPath() const {
- return file_.full_path();
-}
-
-bool DownloadFileImpl::InProgress() const {
- return file_.in_progress();
-}
-
-void DownloadFileImpl::Pause() {
- DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
- is_paused_ = true;
- record_stream_bandwidth_ = false;
-}
-
-void DownloadFileImpl::Resume() {
- DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
- DCHECK(is_paused_);
- is_paused_ = false;
-
- if (!base::FeatureList::IsEnabled(network::features::kNetworkService))
- return;
-
- for (auto& stream : source_streams_) {
- SourceStream* source_stream = stream.second.get();
- if (!source_stream->is_finished()) {
- StreamActive(source_stream, MOJO_RESULT_OK);
- }
- }
-}
-
-void DownloadFileImpl::StreamActive(SourceStream* source_stream,
- MojoResult result) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
- if (base::FeatureList::IsEnabled(network::features::kNetworkService) &&
- is_paused_)
- return;
-
- base::TimeTicks start(base::TimeTicks::Now());
- base::TimeTicks now;
- scoped_refptr<net::IOBuffer> incoming_data;
- size_t incoming_data_size = 0;
- size_t total_incoming_data_size = 0;
- size_t num_buffers = 0;
- size_t bytes_to_write = 0;
- bool should_terminate = false;
- SourceStream::StreamState state(SourceStream::EMPTY);
- download::DownloadInterruptReason reason =
- download::DOWNLOAD_INTERRUPT_REASON_NONE;
- base::TimeDelta delta(
- base::TimeDelta::FromMilliseconds(kMaxTimeBlockingFileThreadMs));
-
- // Take care of any file local activity required.
- do {
- state = source_stream->Read(&incoming_data, &incoming_data_size);
- switch (state) {
- case SourceStream::EMPTY:
- should_terminate = (source_stream->length() == kNoBytesToWrite);
- break;
- case SourceStream::HAS_DATA: {
- ++num_buffers;
- base::TimeTicks write_start(base::TimeTicks::Now());
- should_terminate = CalculateBytesToWrite(
- source_stream, incoming_data_size, &bytes_to_write);
- DCHECK_GE(incoming_data_size, bytes_to_write);
- reason = WriteDataToFile(
- source_stream->offset() + source_stream->bytes_written(),
- incoming_data.get()->data(), bytes_to_write);
- disk_writes_time_ += (base::TimeTicks::Now() - write_start);
- bytes_seen_ += bytes_to_write;
- total_incoming_data_size += bytes_to_write;
- if (reason == download::DOWNLOAD_INTERRUPT_REASON_NONE) {
- int64_t prev_bytes_written = source_stream->bytes_written();
- source_stream->OnWriteBytesToDisk(bytes_to_write);
- if (!IsSparseFile())
- break;
- // If the write operation creates a new slice, add it to the
- // |received_slices_| and update all the entries in
- // |source_streams_|.
- if (bytes_to_write > 0 && prev_bytes_written == 0) {
- AddNewSlice(source_stream->offset(), bytes_to_write);
- } else {
- received_slices_[source_stream->index()].received_bytes +=
- bytes_to_write;
- }
- }
- } break;
- case SourceStream::WAIT_FOR_COMPLETION:
- source_stream->RegisterCompletionCallback(base::BindOnce(
- &DownloadFileImpl::OnStreamCompleted, weak_factory_.GetWeakPtr()));
- break;
- case SourceStream::COMPLETE:
- break;
- default:
- NOTREACHED();
- break;
- }
- now = base::TimeTicks::Now();
- } while (state == SourceStream::HAS_DATA &&
- reason == download::DOWNLOAD_INTERRUPT_REASON_NONE &&
- now - start <= delta && !should_terminate);
-
- // If we're stopping to yield the thread, post a task so we come back.
- if (state == SourceStream::HAS_DATA && now - start > delta &&
- !should_terminate) {
- base::SequencedTaskRunnerHandle::Get()->PostTask(
- FROM_HERE, base::BindOnce(&DownloadFileImpl::StreamActive,
- weak_factory_.GetWeakPtr(), source_stream,
- MOJO_RESULT_OK));
- }
-
- if (total_incoming_data_size)
- download::RecordFileThreadReceiveBuffers(num_buffers);
-
- download::RecordContiguousWriteTime(now - start);
-
- if (state == SourceStream::COMPLETE)
- OnStreamCompleted(source_stream);
- else
- NotifyObserver(source_stream, reason, state, should_terminate);
-
- TRACE_EVENT_INSTANT2("download", "DownloadStreamDrained",
- TRACE_EVENT_SCOPE_THREAD, "stream_size",
- total_incoming_data_size, "num_buffers", num_buffers);
-}
-
-void DownloadFileImpl::OnStreamCompleted(SourceStream* source_stream) {
- download::DownloadInterruptReason reason =
- HandleStreamCompletionStatus(source_stream);
-
- SendUpdate();
-
- NotifyObserver(source_stream, reason, SourceStream::COMPLETE, false);
-}
-
-void DownloadFileImpl::NotifyObserver(SourceStream* source_stream,
- download::DownloadInterruptReason reason,
- SourceStream::StreamState stream_state,
- bool should_terminate) {
- if (reason != download::DOWNLOAD_INTERRUPT_REASON_NONE) {
- HandleStreamError(source_stream, reason);
- } else if (stream_state == SourceStream::COMPLETE || should_terminate) {
- // Signal successful completion or termination of the current stream.
- source_stream->ClearDataReadyCallback();
- source_stream->set_finished(true);
-
- if (should_terminate)
- CancelRequest(source_stream->offset());
- if (source_stream->length() ==
- download::DownloadSaveInfo::kLengthFullContent) {
- // Mark received slice as finished.
- if (IsSparseFile() && source_stream->bytes_written() > 0) {
- DCHECK_GT(received_slices_.size(), source_stream->index())
- << "Received slice index out of bound!";
- received_slices_[source_stream->index()].finished = true;
- }
-
- SetPotentialFileLength(source_stream->offset() +
- source_stream->bytes_written());
- }
- num_active_streams_--;
-
- // Inform observers.
- SendUpdate();
-
- // All the stream reader are completed, shut down file IO processing.
- if (IsDownloadCompleted()) {
- download::RecordFileBandwidth(bytes_seen_, disk_writes_time_,
- base::TimeTicks::Now() - download_start_);
- if (record_stream_bandwidth_) {
- download::RecordParallelizableDownloadStats(
- bytes_seen_with_parallel_streams_,
- download_time_with_parallel_streams_,
- bytes_seen_without_parallel_streams_,
- download_time_without_parallel_streams_, IsSparseFile());
- }
- weak_factory_.InvalidateWeakPtrs();
- std::unique_ptr<crypto::SecureHash> hash_state = file_.Finish();
- update_timer_.reset();
- BrowserThread::PostTask(
- BrowserThread::UI, FROM_HERE,
- base::BindOnce(&DownloadDestinationObserver::DestinationCompleted,
- observer_, TotalBytesReceived(),
- std::move(hash_state)));
- }
- }
-}
-
-void DownloadFileImpl::RegisterAndActivateStream(SourceStream* source_stream) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
-
- source_stream->Initialize();
- source_stream->RegisterDataReadyCallback(
- base::Bind(&DownloadFileImpl::StreamActive, weak_factory_.GetWeakPtr(),
- source_stream));
- // Truncate |source_stream|'s length if necessary.
- for (const auto& received_slice : received_slices_) {
- source_stream->TruncateLengthWithWrittenDataBlock(
- received_slice.offset, received_slice.received_bytes);
- }
- num_active_streams_++;
- StreamActive(source_stream, MOJO_RESULT_OK);
-}
-
-int64_t DownloadFileImpl::TotalBytesReceived() const {
- return file_.bytes_so_far();
-}
-
-void DownloadFileImpl::SendUpdate() {
- // TODO(qinmin): For each active stream, add the slice it has written so
- // far along with received_slices_.
- BrowserThread::PostTask(
- BrowserThread::UI, FROM_HERE,
- base::BindOnce(&DownloadDestinationObserver::DestinationUpdate, observer_,
- TotalBytesReceived(), rate_estimator_.GetCountPerSecond(),
- received_slices_));
-}
-
-void DownloadFileImpl::WillWriteToDisk(size_t data_len) {
- if (!update_timer_->IsRunning()) {
- update_timer_->Start(FROM_HERE,
- base::TimeDelta::FromMilliseconds(kUpdatePeriodMs),
- this, &DownloadFileImpl::SendUpdate);
- }
- rate_estimator_.Increment(data_len);
- base::TimeTicks now = base::TimeTicks::Now();
- base::TimeDelta time_elapsed = (now - last_update_time_);
- last_update_time_ = now;
- if (num_active_streams_ > 1) {
- download_time_with_parallel_streams_ += time_elapsed;
- bytes_seen_with_parallel_streams_ += data_len;
- } else {
- download_time_without_parallel_streams_ += time_elapsed;
- bytes_seen_without_parallel_streams_ += data_len;
- }
-}
-
-void DownloadFileImpl::AddNewSlice(int64_t offset, int64_t length) {
- size_t index = AddOrMergeReceivedSliceIntoSortedArray(
- download::DownloadItem::ReceivedSlice(offset, length), received_slices_);
- // Check if the slice is added as a new slice, or merged with an existing one.
- bool slice_added = (offset == received_slices_[index].offset);
- // Update the index of exising SourceStreams.
- for (auto& stream : source_streams_) {
- SourceStream* source_stream = stream.second.get();
- if (source_stream->offset() > offset) {
- if (slice_added && source_stream->bytes_written() > 0)
- source_stream->set_index(source_stream->index() + 1);
- } else if (source_stream->offset() == offset) {
- source_stream->set_index(index);
- } else {
- source_stream->TruncateLengthWithWrittenDataBlock(offset, length);
- }
- }
-}
-
-bool DownloadFileImpl::IsDownloadCompleted() {
- for (auto& stream : source_streams_) {
- if (!stream.second->is_finished())
- return false;
- }
-
- if (!IsSparseFile())
- return true;
-
- // Verify that all the file slices have been downloaded.
- std::vector<download::DownloadItem::ReceivedSlice> slices_to_download =
- FindSlicesToDownload(received_slices_);
- if (slices_to_download.size() > 1) {
- // If there are 1 or more holes in the file, download is not finished.
- // Some streams might not have been added to |source_streams_| yet.
- return false;
- }
- return TotalBytesReceived() == potential_file_length_;
-}
-
-void DownloadFileImpl::HandleStreamError(
- SourceStream* source_stream,
- download::DownloadInterruptReason reason) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
- source_stream->ClearDataReadyCallback();
- source_stream->set_finished(true);
- num_active_streams_--;
-
- // If previous stream has already written data at the starting offset of
- // the error stream. The download can complete.
- bool can_recover_from_error = (source_stream->length() == kNoBytesToWrite);
-
- // See if the previous stream can download the full content.
- // If the current stream has written some data, length of all preceding
- // streams will be truncated.
- if (IsSparseFile() && !can_recover_from_error) {
- SourceStream* preceding_neighbor = FindPrecedingNeighbor(source_stream);
- while (preceding_neighbor) {
- if (CanRecoverFromError(source_stream, preceding_neighbor)) {
- can_recover_from_error = true;
- break;
- }
-
- // If the neighbor cannot recover the error and it has already created
- // a slice, just interrupt the download.
- if (preceding_neighbor->bytes_written() > 0)
- break;
- preceding_neighbor = FindPrecedingNeighbor(preceding_neighbor);
- }
- }
-
- SendUpdate(); // Make info up to date before error.
-
- if (!can_recover_from_error) {
- // Error case for both upstream source and file write.
- // Shut down processing and signal an error to our observer.
- // Our observer will clean us up.
- weak_factory_.InvalidateWeakPtrs();
- std::unique_ptr<crypto::SecureHash> hash_state = file_.Finish();
- BrowserThread::PostTask(
- BrowserThread::UI, FROM_HERE,
- base::BindOnce(&DownloadDestinationObserver::DestinationError,
- observer_, reason, TotalBytesReceived(),
- std::move(hash_state)));
- }
-}
-
-bool DownloadFileImpl::IsSparseFile() const {
- return source_streams_.size() > 1 || !received_slices_.empty();
-}
-
-DownloadFileImpl::SourceStream* DownloadFileImpl::FindPrecedingNeighbor(
- SourceStream* source_stream) {
- int64_t max_preceding_offset = 0;
- SourceStream* ret = nullptr;
- for (auto& stream : source_streams_) {
- int64_t offset = stream.second->offset();
- if (offset < source_stream->offset() && offset >= max_preceding_offset) {
- ret = stream.second.get();
- max_preceding_offset = offset;
- }
- }
- return ret;
-}
-
-void DownloadFileImpl::CancelRequest(int64_t offset) {
- if (!cancel_request_callback_.is_null()) {
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
- base::BindOnce(cancel_request_callback_, offset));
- }
-}
-
-void DownloadFileImpl::DebugStates() const {
- DVLOG(1) << "### Debugging DownloadFile states:";
- DVLOG(1) << "Total source stream count = " << source_streams_.size();
- for (const auto& stream : source_streams_) {
- DVLOG(1) << "Source stream, offset = " << stream.second->offset()
- << " , bytes_written = " << stream.second->bytes_written()
- << " , is_finished = " << stream.second->is_finished()
- << " , length = " << stream.second->length()
- << ", index = " << stream.second->index();
- }
-
- DebugSlicesInfo(received_slices_);
-}
-
-DownloadFileImpl::RenameParameters::RenameParameters(
- RenameOption option,
- const base::FilePath& new_path,
- const RenameCompletionCallback& completion_callback)
- : option(option),
- new_path(new_path),
- retries_left(kMaxRenameRetries),
- completion_callback(completion_callback) {}
-
-DownloadFileImpl::RenameParameters::~RenameParameters() {}
-
-} // namespace content
diff --git a/chromium/content/browser/download/download_file_impl.h b/chromium/content/browser/download/download_file_impl.h
deleted file mode 100644
index 6369df09c55..00000000000
--- a/chromium/content/browser/download/download_file_impl.h
+++ /dev/null
@@ -1,373 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_FILE_IMPL_H_
-#define CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_FILE_IMPL_H_
-
-#include "content/browser/download/download_file.h"
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include <memory>
-#include <string>
-#include <unordered_map>
-#include <vector>
-
-#include "base/files/file.h"
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/memory/weak_ptr.h"
-#include "base/sequence_checker.h"
-#include "base/time/time.h"
-#include "base/timer/timer.h"
-#include "components/download/public/common/download_item.h"
-#include "components/download/public/common/download_save_info.h"
-#include "components/download/public/common/download_stream.mojom.h"
-#include "components/download/public/common/rate_estimator.h"
-#include "content/browser/byte_stream.h"
-#include "content/browser/download/base_file.h"
-#include "mojo/public/cpp/bindings/binding.h"
-#include "mojo/public/cpp/system/simple_watcher.h"
-
-namespace content {
-class ByteStreamReader;
-class DownloadDestinationObserver;
-
-class CONTENT_EXPORT DownloadFileImpl : public DownloadFile {
- public:
- // Takes ownership of the object pointed to by |save_info|.
- // |net_log| will be used for logging the download file's events.
- // May be constructed on any thread. All methods besides the constructor
- // (including destruction) must occur in the same sequence.
- //
- // Note that the DownloadFileImpl automatically reads from the passed in
- // |stream|, and sends updates and status of those reads to the
- // DownloadDestinationObserver.
- DownloadFileImpl(std::unique_ptr<download::DownloadSaveInfo> save_info,
- const base::FilePath& default_downloads_directory,
- std::unique_ptr<DownloadManager::InputStream> stream,
- uint32_t download_id,
- base::WeakPtr<DownloadDestinationObserver> observer);
-
- ~DownloadFileImpl() override;
-
- // DownloadFile functions.
- void Initialize(const InitializeCallback& initialize_callback,
- const CancelRequestCallback& cancel_request_callback,
- const download::DownloadItem::ReceivedSlices& received_slices,
- bool is_parallelizable) override;
- void AddInputStream(std::unique_ptr<DownloadManager::InputStream> stream,
- int64_t offset,
- int64_t length) override;
- void OnResponseCompleted(int64_t offset,
- download::DownloadInterruptReason status) override;
- void RenameAndUniquify(const base::FilePath& full_path,
- const RenameCompletionCallback& callback) override;
- void RenameAndAnnotate(const base::FilePath& full_path,
- const std::string& client_guid,
- const GURL& source_url,
- const GURL& referrer_url,
- const RenameCompletionCallback& callback) override;
- void Detach() override;
- void Cancel() override;
- void SetPotentialFileLength(int64_t length) override;
- const base::FilePath& FullPath() const override;
- bool InProgress() const override;
- void Pause() override;
- void Resume() override;
-
- // Wrapper of a ByteStreamReader or ScopedDataPipeConsumerHandle, and the meta
- // data needed to write to a slice of the target file.
- //
- // Does not require the stream reader or the consumer handle to be ready when
- // constructor is called. They can be added later when the network response
- // is handled.
- //
- // Multiple SourceStreams can concurrently write to the same file sink.
- class CONTENT_EXPORT SourceStream
- : public download::mojom::DownloadStreamClient {
- public:
- SourceStream(int64_t offset,
- int64_t length,
- std::unique_ptr<DownloadManager::InputStream> stream);
- ~SourceStream() override;
-
- void Initialize();
-
- // download::mojom::DownloadStreamClient
- void OnStreamCompleted(
- download::mojom::NetworkRequestStatus status) override;
-
- // Called when response is completed.
- void OnResponseCompleted(download::DownloadInterruptReason reason);
-
- // Called after successfully writing a buffer to disk.
- void OnWriteBytesToDisk(int64_t bytes_write);
-
- // Given a data block that is already written, truncate the length of this
- // object to avoid overwriting that block.
- void TruncateLengthWithWrittenDataBlock(int64_t offset,
- int64_t bytes_written);
-
- // Registers the callback that will be called when data is ready.
- void RegisterDataReadyCallback(
- const mojo::SimpleWatcher::ReadyCallback& callback);
- // Clears the callback that is registed when data is ready.
- void ClearDataReadyCallback();
-
- // Gets the status of the input stream when the stream completes.
- // TODO(qinmin): for data pipe, it currently doesn't support sending an
- // abort status at the end. The best way to do this is to add a separate
- // mojo interface for control messages when creating this object. See
- // http://crbug.com/748240. An alternative strategy is to let the
- // DownloadManager pass the status code to download::DownloadItem or
- // DownloadFile. However, a DownloadFile can have multiple SourceStreams, so
- // we have to maintain a map between data pipe and
- // download::DownloadItem/DownloadFile somewhere.
- download::DownloadInterruptReason GetCompletionStatus() const;
-
- using CompletionCallback = base::OnceCallback<void(SourceStream*)>;
- // Register an callback to be called when download completes.
- void RegisterCompletionCallback(CompletionCallback callback);
-
- // Results for reading the SourceStream.
- enum StreamState {
- EMPTY = 0,
- HAS_DATA,
- WAIT_FOR_COMPLETION,
- COMPLETE,
- };
- StreamState Read(scoped_refptr<net::IOBuffer>* data, size_t* length);
-
- int64_t offset() const { return offset_; }
- int64_t length() const { return length_; }
- int64_t bytes_written() const { return bytes_written_; }
- bool is_finished() const { return finished_; }
- void set_finished(bool finish) { finished_ = finish; }
- size_t index() { return index_; }
- void set_index(size_t index) { index_ = index; }
-
- private:
- // Starting position for the stream to write to disk.
- int64_t offset_;
-
- // The maximum length to write to the disk. If set to 0, keep writing until
- // the stream depletes.
- int64_t length_;
-
- // Number of bytes written to disk from the stream.
- // Next write position is (|offset_| + |bytes_written_|).
- int64_t bytes_written_;
-
- // If all the data read from the stream has been successfully written to
- // disk.
- bool finished_;
-
- // The slice index in the |received_slices_| vector. A slice was created
- // once the stream started writing data to the target file.
- size_t index_;
-
- // The stream through which data comes.
- std::unique_ptr<ByteStreamReader> stream_reader_;
-
- // Status when the response completes, used by data pipe.
- download::DownloadInterruptReason completion_status_;
-
- // Whether the producer has completed handling the response.
- bool is_response_completed_;
-
- CompletionCallback completion_callback_;
-
- // Objects for consuming a mojo data pipe.
- download::mojom::DownloadStreamHandlePtr stream_handle_;
- std::unique_ptr<mojo::SimpleWatcher> handle_watcher_;
- std::unique_ptr<mojo::Binding<download::mojom::DownloadStreamClient>>
- binding_;
-
- DISALLOW_COPY_AND_ASSIGN(SourceStream);
- };
-
- protected:
- // For test class overrides.
- // Write data from the offset to the file.
- // On OS level, it will seek to the |offset| and write from there.
- virtual download::DownloadInterruptReason WriteDataToFile(int64_t offset,
- const char* data,
- size_t data_len);
-
- virtual base::TimeDelta GetRetryDelayForFailedRename(int attempt_number);
-
- virtual bool ShouldRetryFailedRename(
- download::DownloadInterruptReason reason);
-
- virtual download::DownloadInterruptReason HandleStreamCompletionStatus(
- SourceStream* source_stream);
-
- private:
- friend class DownloadFileTest;
-
- DownloadFileImpl(std::unique_ptr<download::DownloadSaveInfo> save_info,
- const base::FilePath& default_downloads_directory,
- uint32_t download_id,
- base::WeakPtr<DownloadDestinationObserver> observer);
-
- // Options for RenameWithRetryInternal.
- enum RenameOption {
- UNIQUIFY = 1 << 0, // If there's already a file on disk that conflicts with
- // |new_path|, try to create a unique file by appending
- // a uniquifier.
- ANNOTATE_WITH_SOURCE_INFORMATION = 1 << 1
- };
-
- struct RenameParameters {
- RenameParameters(RenameOption option,
- const base::FilePath& new_path,
- const RenameCompletionCallback& completion_callback);
- ~RenameParameters();
-
- RenameOption option;
- base::FilePath new_path;
- std::string client_guid; // See BaseFile::AnnotateWithSourceInformation()
- GURL source_url; // See BaseFile::AnnotateWithSourceInformation()
- GURL referrer_url; // See BaseFile::AnnotateWithSourceInformation()
- int retries_left; // RenameWithRetryInternal() will
- // automatically retry until this
- // count reaches 0. Each attempt
- // decrements this counter.
- base::TimeTicks time_of_first_failure; // Set to empty at first, but is set
- // when a failure is first
- // encountered. Used for UMA.
- RenameCompletionCallback completion_callback;
- };
-
- // Rename file_ based on |parameters|.
- void RenameWithRetryInternal(std::unique_ptr<RenameParameters> parameters);
-
- // Send an update on our progress.
- void SendUpdate();
-
- // Called before the data is written to disk.
- void WillWriteToDisk(size_t data_len);
-
- // For a given SourceStream object and the bytes available to write, determine
- // the actual number of bytes it can write to the disk. For parallel
- // downloading, if the first disk IO writes to a location that is already
- // written by another stream, the current stream should stop writing. Returns
- // true if the stream can write no more data and should be finished, returns
- // false otherwise.
- bool CalculateBytesToWrite(SourceStream* source_stream,
- size_t bytes_available_to_write,
- size_t* bytes_to_write);
-
- // Called when a new SourceStream object is added.
- void OnSourceStreamAdded(SourceStream* source_stream);
-
- // Called when there's some activity on the input data that needs to be
- // handled.
- void StreamActive(SourceStream* source_stream, MojoResult result);
-
- // Register callback and start to read data from the stream.
- void RegisterAndActivateStream(SourceStream* source_stream);
-
- // Called when a stream completes.
- void OnStreamCompleted(SourceStream* source_stream);
-
- // Notify |observer_| about the download status.
- void NotifyObserver(SourceStream* source_stream,
- download::DownloadInterruptReason reason,
- SourceStream::StreamState stream_state,
- bool should_terminate);
-
- // Adds a new slice to |received_slices_| and update the existing entries in
- // |source_streams_| as their lengths will change.
- // TODO(qinmin): add a test for this function.
- void AddNewSlice(int64_t offset, int64_t length);
-
- // Check if download is completed.
- bool IsDownloadCompleted();
-
- // Return the total valid bytes received in the target file.
- // If the file is a sparse file, return the total number of valid bytes.
- // Otherwise, return the current file size.
- int64_t TotalBytesReceived() const;
-
- // Helper method to handle stream error
- void HandleStreamError(SourceStream* source_stream,
- download::DownloadInterruptReason reason);
-
- // Check whether this file is potentially sparse.
- bool IsSparseFile() const;
-
- // Given a SourceStream object, returns its neighbor that precedes it if
- // SourceStreams are ordered by their offsets.
- SourceStream* FindPrecedingNeighbor(SourceStream* source_stream);
-
- // See |cancel_request_callback_|.
- void CancelRequest(int64_t offset);
-
- // Print the internal states for debugging.
- void DebugStates() const;
-
- // The base file instance.
- BaseFile file_;
-
- // DownloadSaveInfo provided during construction. Since the DownloadFileImpl
- // can be created on any thread, this holds the save_info_ until it can be
- // used to initialize file_ on the download sequence.
- std::unique_ptr<download::DownloadSaveInfo> save_info_;
-
- // The default directory for creating the download file.
- base::FilePath default_download_directory_;
-
- // Map of the offset and the source stream that represents the slice
- // starting from offset.
- typedef std::unordered_map<int64_t, std::unique_ptr<SourceStream>>
- SourceStreams;
- SourceStreams source_streams_;
-
- // Used to cancel the request on UI thread, since the ByteStreamReader can't
- // close the underlying resource writing to the pipe.
- CancelRequestCallback cancel_request_callback_;
-
- // Used to trigger progress updates.
- std::unique_ptr<base::RepeatingTimer> update_timer_;
-
- // Potential file length. A range request with an offset larger than this
- // value will fail. So the actual file length cannot be larger than this.
- int64_t potential_file_length_;
-
- // Statistics
- size_t bytes_seen_;
- base::TimeDelta disk_writes_time_;
- base::TimeTicks download_start_;
- download::RateEstimator rate_estimator_;
- int num_active_streams_;
- bool record_stream_bandwidth_;
- base::TimeTicks last_update_time_;
- size_t bytes_seen_with_parallel_streams_;
- size_t bytes_seen_without_parallel_streams_;
- base::TimeDelta download_time_with_parallel_streams_;
- base::TimeDelta download_time_without_parallel_streams_;
-
- std::vector<download::DownloadItem::ReceivedSlice> received_slices_;
-
- // Used to track whether the download is paused or not. This value is ignored
- // when network service is disabled as download pause/resumption is handled
- // by DownloadRequestCore in that case.
- bool is_paused_;
-
- uint32_t download_id_;
-
- SEQUENCE_CHECKER(sequence_checker_);
-
- base::WeakPtr<DownloadDestinationObserver> observer_;
- base::WeakPtrFactory<DownloadFileImpl> weak_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(DownloadFileImpl);
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_FILE_IMPL_H_
diff --git a/chromium/content/browser/download/download_file_unittest.cc b/chromium/content/browser/download/download_file_unittest.cc
deleted file mode 100644
index 93d17338567..00000000000
--- a/chromium/content/browser/download/download_file_unittest.cc
+++ /dev/null
@@ -1,1093 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include <utility>
-#include <vector>
-
-#include "base/files/file.h"
-#include "base/files/file_util.h"
-#include "base/files/scoped_temp_dir.h"
-#include "base/location.h"
-#include "base/memory/ptr_util.h"
-#include "base/run_loop.h"
-#include "base/single_thread_task_runner.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/test/test_file_util.h"
-#include "base/threading/thread_task_runner_handle.h"
-#include "build/build_config.h"
-#include "components/download/public/common/download_create_info.h"
-#include "components/download/public/common/download_interrupt_reasons.h"
-#include "content/browser/byte_stream.h"
-#include "content/browser/download/download_destination_observer.h"
-#include "content/browser/download/download_file_impl.h"
-#include "content/browser/download/download_request_handle.h"
-#include "content/public/browser/download_manager.h"
-#include "content/public/test/mock_download_manager.h"
-#include "content/public/test/test_browser_thread_bundle.h"
-#include "net/base/file_stream.h"
-#include "net/base/mock_file_stream.h"
-#include "net/base/net_errors.h"
-#include "testing/gmock/include/gmock/gmock.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-using ::testing::_;
-using ::testing::AnyNumber;
-using ::testing::DoAll;
-using ::testing::InSequence;
-using ::testing::Return;
-using ::testing::Sequence;
-using ::testing::SetArgPointee;
-using ::testing::StrictMock;
-
-namespace content {
-namespace {
-
-// Struct for SourceStream states verification.
-struct SourceStreamTestData {
- SourceStreamTestData(int64_t offset, int64_t bytes_written, bool finished)
- : offset(offset), bytes_written(bytes_written), finished(finished) {}
- int64_t offset;
- int64_t bytes_written;
- bool finished;
-};
-
-int64_t GetBuffersLength(const char** buffers, size_t num_buffer) {
- int64_t result = 0;
- for (size_t i = 0; i < num_buffer; ++i)
- result += static_cast<int64_t>(strlen(buffers[i]));
- return result;
-}
-
-std::string GetHexEncodedHashValue(crypto::SecureHash* hash_state) {
- if (!hash_state)
- return std::string();
- std::vector<char> hash_value(hash_state->GetHashLength());
- hash_state->Finish(&hash_value.front(), hash_value.size());
- return base::HexEncode(&hash_value.front(), hash_value.size());
-}
-
-class MockByteStreamReader : public ByteStreamReader {
- public:
- MockByteStreamReader() {}
- ~MockByteStreamReader() {}
-
- // ByteStream functions
- MOCK_METHOD2(Read, ByteStreamReader::StreamState(
- scoped_refptr<net::IOBuffer>*, size_t*));
- MOCK_CONST_METHOD0(GetStatus, int());
- MOCK_METHOD1(RegisterCallback, void(const base::Closure&));
-};
-
-class MockDownloadDestinationObserver : public DownloadDestinationObserver {
- public:
- MOCK_METHOD3(DestinationUpdate,
- void(int64_t,
- int64_t,
- const std::vector<download::DownloadItem::ReceivedSlice>&));
- void DestinationError(
- download::DownloadInterruptReason reason,
- int64_t bytes_so_far,
- std::unique_ptr<crypto::SecureHash> hash_state) override {
- MockDestinationError(
- reason, bytes_so_far, GetHexEncodedHashValue(hash_state.get()));
- }
- void DestinationCompleted(
- int64_t total_bytes,
- std::unique_ptr<crypto::SecureHash> hash_state) override {
- MockDestinationCompleted(total_bytes,
- GetHexEncodedHashValue(hash_state.get()));
- }
-
- MOCK_METHOD3(MockDestinationError,
- void(download::DownloadInterruptReason,
- int64_t,
- const std::string&));
- MOCK_METHOD2(MockDestinationCompleted, void(int64_t, const std::string&));
-
- // Doesn't override any methods in the base class. Used to make sure
- // that the last DestinationUpdate before a Destination{Completed,Error}
- // had the right values.
- MOCK_METHOD2(CurrentUpdateStatus, void(int64_t, int64_t));
-};
-
-MATCHER(IsNullCallback, "") { return (arg.is_null()); }
-
-enum DownloadFileRenameMethodType { RENAME_AND_UNIQUIFY, RENAME_AND_ANNOTATE };
-
-// This is a test DownloadFileImpl that has no retry delay and, on Posix,
-// retries renames failed due to ACCESS_DENIED.
-class TestDownloadFileImpl : public DownloadFileImpl {
- public:
- TestDownloadFileImpl(std::unique_ptr<download::DownloadSaveInfo> save_info,
- const base::FilePath& default_downloads_directory,
- std::unique_ptr<DownloadManager::InputStream> stream,
- uint32_t download_id,
- base::WeakPtr<DownloadDestinationObserver> observer)
- : DownloadFileImpl(std::move(save_info),
- default_downloads_directory,
- std::move(stream),
- download_id,
- observer) {}
-
- protected:
- base::TimeDelta GetRetryDelayForFailedRename(int attempt_count) override {
- return base::TimeDelta::FromMilliseconds(0);
- }
-
-#if !defined(OS_WIN)
- // On Posix, we don't encounter transient errors during renames, except
- // possibly EAGAIN, which is difficult to replicate reliably. So we resort to
- // simulating a transient error using ACCESS_DENIED instead.
- bool ShouldRetryFailedRename(
- download::DownloadInterruptReason reason) override {
- return reason == download::DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED;
- }
-#endif
-};
-
-} // namespace
-
-class DownloadFileTest : public testing::Test {
- public:
- static const char kTestData1[];
- static const char kTestData2[];
- static const char kTestData3[];
- static const char kTestData4[];
- static const char kTestData5[];
- static const char* kTestData6[];
- static const char* kTestData7[];
- static const char* kTestData8[];
- static const char kDataHash[];
- static const char kEmptyHash[];
- static const uint32_t kDummyDownloadId;
- static const int kDummyChildId;
- static const int kDummyRequestId;
-
- DownloadFileTest()
- : observer_(new StrictMock<MockDownloadDestinationObserver>),
- observer_factory_(observer_.get()),
- input_stream_(nullptr),
- additional_streams_(
- std::vector<StrictMock<MockByteStreamReader>*>{nullptr, nullptr}),
- bytes_(-1),
- bytes_per_sec_(-1) {}
-
- ~DownloadFileTest() override {}
-
- void SetUpdateDownloadInfo(
- int64_t bytes,
- int64_t bytes_per_sec,
- const std::vector<download::DownloadItem::ReceivedSlice>&
- received_slices) {
- bytes_ = bytes;
- bytes_per_sec_ = bytes_per_sec;
- }
-
- void ConfirmUpdateDownloadInfo() {
- observer_->CurrentUpdateStatus(bytes_, bytes_per_sec_);
- }
-
- void SetUp() override {
- EXPECT_CALL(*(observer_.get()), DestinationUpdate(_, _, _))
- .Times(AnyNumber())
- .WillRepeatedly(Invoke(this, &DownloadFileTest::SetUpdateDownloadInfo));
- bool result = download_dir_.CreateUniqueTempDir();
- CHECK(result);
- }
-
- // Mock calls to this function are forwarded here.
- void RegisterCallback(const base::Closure& sink_callback) {
- sink_callback_ = sink_callback;
- }
-
- void SetInterruptReasonCallback(const base::Closure& closure,
- download::DownloadInterruptReason* reason_p,
- download::DownloadInterruptReason reason) {
- *reason_p = reason;
- closure.Run();
- }
-
- bool CreateDownloadFile(int offset, bool calculate_hash) {
- return CreateDownloadFile(offset, 0, calculate_hash,
- download::DownloadItem::ReceivedSlices());
- }
-
- bool CreateDownloadFile(
- int offset,
- int length,
- bool calculate_hash,
- const download::DownloadItem::ReceivedSlices& received_slices) {
- // There can be only one.
- DCHECK(!download_file_.get());
-
- input_stream_ = new StrictMock<MockByteStreamReader>();
-
- // TODO: Need to actually create a function that'll set the variables
- // based on the inputs from the callback.
- EXPECT_CALL(*input_stream_, RegisterCallback(_))
- .WillOnce(Invoke(this, &DownloadFileTest::RegisterCallback))
- .RetiresOnSaturation();
-
- std::unique_ptr<download::DownloadSaveInfo> save_info(
- new download::DownloadSaveInfo());
- save_info->offset = offset;
- save_info->length = length;
-
- download_file_.reset(new TestDownloadFileImpl(
- std::move(save_info), download_dir_.GetPath(),
- std::make_unique<DownloadManager::InputStream>(
- std::unique_ptr<ByteStreamReader>(input_stream_)),
- download::DownloadItem::kInvalidId, observer_factory_.GetWeakPtr()));
-
- EXPECT_CALL(*input_stream_, Read(_, _))
- .WillOnce(Return(ByteStreamReader::STREAM_EMPTY))
- .RetiresOnSaturation();
-
- base::WeakPtrFactory<DownloadFileTest> weak_ptr_factory(this);
- download::DownloadInterruptReason result =
- download::DOWNLOAD_INTERRUPT_REASON_NONE;
- base::RunLoop loop_runner;
- download_file_->Initialize(
- base::Bind(&DownloadFileTest::SetInterruptReasonCallback,
- weak_ptr_factory.GetWeakPtr(), loop_runner.QuitClosure(),
- &result),
- DownloadFile::CancelRequestCallback(), received_slices, true);
- loop_runner.Run();
-
- ::testing::Mock::VerifyAndClearExpectations(input_stream_);
- return result == download::DOWNLOAD_INTERRUPT_REASON_NONE;
- }
-
- void DestroyDownloadFile(int offset, bool compare_disk_data = true) {
- EXPECT_FALSE(download_file_->InProgress());
-
- // Make sure the data has been properly written to disk.
- if (compare_disk_data) {
- std::string disk_data;
- EXPECT_TRUE(
- base::ReadFileToString(download_file_->FullPath(), &disk_data));
- EXPECT_EQ(expected_data_, disk_data);
- }
-
- // Make sure the Browser and File threads outlive the DownloadFile
- // to satisfy thread checks inside it.
- download_file_.reset();
- }
-
- // Setup the stream to append data or write from |offset| to the file.
- // Don't actually trigger the callback or do verifications.
- void SetupDataAppend(const char** data_chunks,
- size_t num_chunks,
- MockByteStreamReader* stream_reader,
- ::testing::Sequence s,
- int64_t offset = -1) {
- DCHECK(stream_reader);
- size_t current_pos = static_cast<size_t>(offset);
- for (size_t i = 0; i < num_chunks; i++) {
- const char *source_data = data_chunks[i];
- size_t length = strlen(source_data);
- scoped_refptr<net::IOBuffer> data = new net::IOBuffer(length);
- memcpy(data->data(), source_data, length);
- EXPECT_CALL(*stream_reader, Read(_, _))
- .InSequence(s)
- .WillOnce(DoAll(SetArgPointee<0>(data), SetArgPointee<1>(length),
- Return(ByteStreamReader::STREAM_HAS_DATA)))
- .RetiresOnSaturation();
-
- if (offset < 0) {
- // Append data.
- expected_data_ += source_data;
- continue;
- }
-
- // Write from offset. May fill holes with '\0'.
- size_t new_len = current_pos + length;
- if (new_len > expected_data_.size())
- expected_data_.append(new_len - expected_data_.size(), '\0');
- expected_data_.replace(current_pos, length, source_data);
- current_pos += length;
- }
- }
-
- void VerifyStreamAndSize() {
- ::testing::Mock::VerifyAndClearExpectations(input_stream_);
- int64_t size;
- EXPECT_TRUE(base::GetFileSize(download_file_->FullPath(), &size));
- EXPECT_EQ(expected_data_.size(), static_cast<size_t>(size));
- }
-
- // TODO(rdsmith): Manage full percentage issues properly.
- void AppendDataToFile(const char **data_chunks, size_t num_chunks) {
- ::testing::Sequence s1;
- SetupDataAppend(data_chunks, num_chunks, input_stream_, s1);
- EXPECT_CALL(*input_stream_, Read(_, _))
- .InSequence(s1)
- .WillOnce(Return(ByteStreamReader::STREAM_EMPTY))
- .RetiresOnSaturation();
- sink_callback_.Run();
- VerifyStreamAndSize();
- }
-
- void SetupFinishStream(download::DownloadInterruptReason interrupt_reason,
- MockByteStreamReader* stream_reader,
- ::testing::Sequence s) {
- EXPECT_CALL(*stream_reader, Read(_, _))
- .InSequence(s)
- .WillOnce(Return(ByteStreamReader::STREAM_COMPLETE))
- .RetiresOnSaturation();
- EXPECT_CALL(*stream_reader, GetStatus())
- .InSequence(s)
- .WillOnce(Return(interrupt_reason))
- .RetiresOnSaturation();
- EXPECT_CALL(*stream_reader, RegisterCallback(_)).RetiresOnSaturation();
- }
-
- void FinishStream(download::DownloadInterruptReason interrupt_reason,
- bool check_observer,
- const std::string& expected_hash) {
- ::testing::Sequence s1;
- SetupFinishStream(interrupt_reason, input_stream_, s1);
- sink_callback_.Run();
- VerifyStreamAndSize();
- if (check_observer) {
- EXPECT_CALL(*(observer_.get()),
- MockDestinationCompleted(_, expected_hash));
- base::RunLoop().RunUntilIdle();
- ::testing::Mock::VerifyAndClearExpectations(observer_.get());
- EXPECT_CALL(*(observer_.get()), DestinationUpdate(_, _, _))
- .Times(AnyNumber())
- .WillRepeatedly(
- Invoke(this, &DownloadFileTest::SetUpdateDownloadInfo));
- }
- }
-
- download::DownloadInterruptReason RenameAndUniquify(
- const base::FilePath& full_path,
- base::FilePath* result_path_p) {
- return InvokeRenameMethodAndWaitForCallback(
- RENAME_AND_UNIQUIFY, full_path, result_path_p);
- }
-
- download::DownloadInterruptReason RenameAndAnnotate(
- const base::FilePath& full_path,
- base::FilePath* result_path_p) {
- return InvokeRenameMethodAndWaitForCallback(
- RENAME_AND_ANNOTATE, full_path, result_path_p);
- }
-
- void ExpectPermissionError(download::DownloadInterruptReason err) {
- EXPECT_TRUE(err ==
- download::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR ||
- err == download::DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED)
- << "Interrupt reason = " << err;
- }
-
- protected:
- void InvokeRenameMethod(
- DownloadFileRenameMethodType method,
- const base::FilePath& full_path,
- const DownloadFile::RenameCompletionCallback& completion_callback) {
- switch (method) {
- case RENAME_AND_UNIQUIFY:
- download_file_->RenameAndUniquify(full_path, completion_callback);
- break;
-
- case RENAME_AND_ANNOTATE:
- download_file_->RenameAndAnnotate(
- full_path,
- "12345678-ABCD-1234-DCBA-123456789ABC",
- GURL(),
- GURL(),
- completion_callback);
- break;
- }
- }
-
- download::DownloadInterruptReason InvokeRenameMethodAndWaitForCallback(
- DownloadFileRenameMethodType method,
- const base::FilePath& full_path,
- base::FilePath* result_path_p) {
- download::DownloadInterruptReason result_reason(
- download::DOWNLOAD_INTERRUPT_REASON_NONE);
- base::FilePath result_path;
- base::RunLoop loop_runner;
- DownloadFile::RenameCompletionCallback completion_callback =
- base::Bind(&DownloadFileTest::SetRenameResult,
- base::Unretained(this),
- loop_runner.QuitClosure(),
- &result_reason,
- result_path_p);
- InvokeRenameMethod(method, full_path, completion_callback);
- loop_runner.Run();
- return result_reason;
- }
-
- // Prepare a byte stream to write to the file sink.
- void PrepareStream(StrictMock<MockByteStreamReader>** stream,
- int64_t offset,
- bool create_stream,
- bool will_finish,
- const char** buffers,
- size_t num_buffer) {
- if (create_stream)
- *stream = new StrictMock<MockByteStreamReader>();
-
- // Expectation on MockByteStreamReader for MultipleStreams tests:
- // 1. RegisterCallback: Must called twice. One to set the callback, the
- // other to release the stream.
- // 2. Read: If filled with N buffer, called (N+1) times, where the last Read
- // call doesn't read any data but returns STRAM_COMPLETE.
- // The stream may terminate in the middle and less Read calls are expected.
- // 3. GetStatus: Only called if the stream is completed and last Read call
- // returns STREAM_COMPLETE.
- Sequence seq;
- SetupDataAppend(buffers, num_buffer, *stream, seq, offset);
- if (will_finish)
- SetupFinishStream(download::DOWNLOAD_INTERRUPT_REASON_NONE, *stream, seq);
- }
-
- void VerifySourceStreamsStates(const SourceStreamTestData& data) {
- DCHECK(download_file_->source_streams_.find(data.offset) !=
- download_file_->source_streams_.end())
- << "Can't find stream at offset : " << data.offset;
- DownloadFileImpl::SourceStream* stream =
- download_file_->source_streams_[data.offset].get();
- DCHECK(stream);
- EXPECT_EQ(data.offset, stream->offset());
- EXPECT_EQ(data.bytes_written, stream->bytes_written());
- EXPECT_EQ(data.finished, stream->is_finished());
- }
-
- size_t source_streams_count() const {
- DCHECK(download_file_);
- return download_file_->source_streams_.size();
- }
-
- int64_t TotalBytesReceived() const {
- DCHECK(download_file_);
- return download_file_->TotalBytesReceived();
- }
-
- std::unique_ptr<StrictMock<MockDownloadDestinationObserver>> observer_;
- base::WeakPtrFactory<DownloadDestinationObserver> observer_factory_;
-
- // DownloadFile instance we are testing.
- std::unique_ptr<DownloadFileImpl> download_file_;
-
- // Stream for sending data into the download file.
- // Owned by download_file_; will be alive for lifetime of download_file_.
- StrictMock<MockByteStreamReader>* input_stream_;
-
- // Additional streams to test multiple stream write.
- std::vector<StrictMock<MockByteStreamReader>*> additional_streams_;
-
- // Sink callback data for stream.
- base::Closure sink_callback_;
-
- base::ScopedTempDir download_dir_;
-
- // Latest update sent to the observer.
- int64_t bytes_;
- int64_t bytes_per_sec_;
-
- private:
- void SetRenameResult(const base::Closure& closure,
- download::DownloadInterruptReason* reason_p,
- base::FilePath* result_path_p,
- download::DownloadInterruptReason reason,
- const base::FilePath& result_path) {
- if (reason_p)
- *reason_p = reason;
- if (result_path_p)
- *result_path_p = result_path;
- closure.Run();
- }
-
- TestBrowserThreadBundle thread_bundle_;
-
- // Keep track of what data should be saved to the disk file.
- std::string expected_data_;
-};
-
-// DownloadFile::RenameAndAnnotate and DownloadFile::RenameAndUniquify have a
-// considerable amount of functional overlap. In order to re-use test logic, we
-// are going to introduce this value parameterized test fixture. It will take a
-// DownloadFileRenameMethodType value which can be either of the two rename
-// methods.
-class DownloadFileTestWithRename
- : public DownloadFileTest,
- public ::testing::WithParamInterface<DownloadFileRenameMethodType> {
- protected:
- download::DownloadInterruptReason InvokeSelectedRenameMethod(
- const base::FilePath& full_path,
- base::FilePath* result_path_p) {
- return InvokeRenameMethodAndWaitForCallback(
- GetParam(), full_path, result_path_p);
- }
-};
-
-// And now instantiate all DownloadFileTestWithRename tests using both
-// DownloadFile rename methods. Each test of the form
-// DownloadFileTestWithRename.<FooTest> will be instantiated once with
-// RenameAndAnnotate as the value parameter and once with RenameAndUniquify as
-// the value parameter.
-INSTANTIATE_TEST_CASE_P(DownloadFile,
- DownloadFileTestWithRename,
- ::testing::Values(RENAME_AND_ANNOTATE,
- RENAME_AND_UNIQUIFY));
-
-const char DownloadFileTest::kTestData1[] =
- "Let's write some data to the file!\n";
-const char DownloadFileTest::kTestData2[] = "Writing more data.\n";
-const char DownloadFileTest::kTestData3[] = "Final line.";
-const char DownloadFileTest::kTestData4[] = "abcdefg";
-const char DownloadFileTest::kTestData5[] = "01234";
-const char* DownloadFileTest::kTestData6[] = {kTestData1, kTestData2};
-const char* DownloadFileTest::kTestData7[] = {kTestData4, kTestData5};
-const char* DownloadFileTest::kTestData8[] = {kTestData1, kTestData2,
- kTestData4, kTestData5};
-
-const char DownloadFileTest::kDataHash[] =
- "CBF68BF10F8003DB86B31343AFAC8C7175BD03FB5FC905650F8C80AF087443A8";
-const char DownloadFileTest::kEmptyHash[] =
- "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855";
-
-const uint32_t DownloadFileTest::kDummyDownloadId = 23;
-const int DownloadFileTest::kDummyChildId = 3;
-const int DownloadFileTest::kDummyRequestId = 67;
-
-// Rename the file before any data is downloaded, after some has, after it all
-// has, and after it's closed.
-TEST_P(DownloadFileTestWithRename, RenameFileFinal) {
- ASSERT_TRUE(CreateDownloadFile(0, true));
- base::FilePath initial_path(download_file_->FullPath());
- EXPECT_TRUE(base::PathExists(initial_path));
- base::FilePath path_1(initial_path.InsertBeforeExtensionASCII("_1"));
- base::FilePath path_2(initial_path.InsertBeforeExtensionASCII("_2"));
- base::FilePath path_3(initial_path.InsertBeforeExtensionASCII("_3"));
- base::FilePath path_4(initial_path.InsertBeforeExtensionASCII("_4"));
- base::FilePath output_path;
-
- // Rename the file before downloading any data.
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE,
- InvokeSelectedRenameMethod(path_1, &output_path));
- base::FilePath renamed_path = download_file_->FullPath();
- EXPECT_EQ(path_1, renamed_path);
- EXPECT_EQ(path_1, output_path);
-
- // Check the files.
- EXPECT_FALSE(base::PathExists(initial_path));
- EXPECT_TRUE(base::PathExists(path_1));
-
- // Download the data.
- const char* chunks1[] = { kTestData1, kTestData2 };
- AppendDataToFile(chunks1, 2);
-
- // Rename the file after downloading some data.
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE,
- InvokeSelectedRenameMethod(path_2, &output_path));
- renamed_path = download_file_->FullPath();
- EXPECT_EQ(path_2, renamed_path);
- EXPECT_EQ(path_2, output_path);
-
- // Check the files.
- EXPECT_FALSE(base::PathExists(path_1));
- EXPECT_TRUE(base::PathExists(path_2));
-
- const char* chunks2[] = { kTestData3 };
- AppendDataToFile(chunks2, 1);
-
- // Rename the file after downloading all the data.
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE,
- InvokeSelectedRenameMethod(path_3, &output_path));
- renamed_path = download_file_->FullPath();
- EXPECT_EQ(path_3, renamed_path);
- EXPECT_EQ(path_3, output_path);
-
- // Check the files.
- EXPECT_FALSE(base::PathExists(path_2));
- EXPECT_TRUE(base::PathExists(path_3));
-
- FinishStream(download::DOWNLOAD_INTERRUPT_REASON_NONE, true, kDataHash);
- base::RunLoop().RunUntilIdle();
-
- // Rename the file after downloading all the data and closing the file.
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE,
- InvokeSelectedRenameMethod(path_4, &output_path));
- renamed_path = download_file_->FullPath();
- EXPECT_EQ(path_4, renamed_path);
- EXPECT_EQ(path_4, output_path);
-
- // Check the files.
- EXPECT_FALSE(base::PathExists(path_3));
- EXPECT_TRUE(base::PathExists(path_4));
-
- DestroyDownloadFile(0);
-}
-
-// Test to make sure the rename overwrites when requested. This is separate from
-// the above test because it only applies to RenameAndAnnotate().
-// RenameAndUniquify() doesn't overwrite by design.
-TEST_F(DownloadFileTest, RenameOverwrites) {
- ASSERT_TRUE(CreateDownloadFile(0, true));
- base::FilePath initial_path(download_file_->FullPath());
- EXPECT_TRUE(base::PathExists(initial_path));
- base::FilePath path_1(initial_path.InsertBeforeExtensionASCII("_1"));
-
- ASSERT_FALSE(base::PathExists(path_1));
- static const char file_data[] = "xyzzy";
- ASSERT_EQ(static_cast<int>(sizeof(file_data)),
- base::WriteFile(path_1, file_data, sizeof(file_data)));
- ASSERT_TRUE(base::PathExists(path_1));
-
- base::FilePath new_path;
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE,
- RenameAndAnnotate(path_1, &new_path));
- EXPECT_EQ(path_1.value(), new_path.value());
-
- std::string file_contents;
- ASSERT_TRUE(base::ReadFileToString(new_path, &file_contents));
- EXPECT_NE(std::string(file_data), file_contents);
-
- FinishStream(download::DOWNLOAD_INTERRUPT_REASON_NONE, true, kEmptyHash);
- base::RunLoop().RunUntilIdle();
- DestroyDownloadFile(0);
-}
-
-// Test to make sure the rename uniquifies if we aren't overwriting
-// and there's a file where we're aiming. As above, not a
-// DownloadFileTestWithRename test because this only applies to
-// RenameAndUniquify().
-TEST_F(DownloadFileTest, RenameUniquifies) {
- ASSERT_TRUE(CreateDownloadFile(0, true));
- base::FilePath initial_path(download_file_->FullPath());
- EXPECT_TRUE(base::PathExists(initial_path));
- base::FilePath path_1(initial_path.InsertBeforeExtensionASCII("_1"));
- base::FilePath path_1_suffixed(path_1.InsertBeforeExtensionASCII(" (1)"));
-
- ASSERT_FALSE(base::PathExists(path_1));
- static const char file_data[] = "xyzzy";
- ASSERT_EQ(static_cast<int>(sizeof(file_data)),
- base::WriteFile(path_1, file_data, sizeof(file_data)));
- ASSERT_TRUE(base::PathExists(path_1));
-
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE,
- RenameAndUniquify(path_1, nullptr));
- EXPECT_TRUE(base::PathExists(path_1_suffixed));
-
- FinishStream(download::DOWNLOAD_INTERRUPT_REASON_NONE, true, kEmptyHash);
- base::RunLoop().RunUntilIdle();
- DestroyDownloadFile(0);
-}
-
-// Test that RenameAndUniquify doesn't try to uniquify in the case where the
-// target filename is the same as the current filename.
-TEST_F(DownloadFileTest, RenameRecognizesSelfConflict) {
- ASSERT_TRUE(CreateDownloadFile(0, true));
- base::FilePath initial_path(download_file_->FullPath());
- EXPECT_TRUE(base::PathExists(initial_path));
-
- base::FilePath new_path;
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE,
- RenameAndUniquify(initial_path, &new_path));
- EXPECT_TRUE(base::PathExists(initial_path));
-
- FinishStream(download::DOWNLOAD_INTERRUPT_REASON_NONE, true, kEmptyHash);
- base::RunLoop().RunUntilIdle();
- DestroyDownloadFile(0);
- EXPECT_EQ(initial_path.value(), new_path.value());
-}
-
-// Test to make sure we get the proper error on failure.
-TEST_P(DownloadFileTestWithRename, RenameError) {
- ASSERT_TRUE(CreateDownloadFile(0, true));
- base::FilePath initial_path(download_file_->FullPath());
-
- // Create a subdirectory.
- base::FilePath target_dir(
- initial_path.DirName().Append(FILE_PATH_LITERAL("TargetDir")));
- ASSERT_FALSE(base::DirectoryExists(target_dir));
- ASSERT_TRUE(base::CreateDirectory(target_dir));
- base::FilePath target_path(target_dir.Append(initial_path.BaseName()));
-
- // Targets
- base::FilePath target_path_suffixed(
- target_path.InsertBeforeExtensionASCII(" (1)"));
- ASSERT_FALSE(base::PathExists(target_path));
- ASSERT_FALSE(base::PathExists(target_path_suffixed));
-
- // Make the directory unwritable and try to rename within it.
- {
- base::FilePermissionRestorer restorer(target_dir);
- ASSERT_TRUE(base::MakeFileUnwritable(target_dir));
-
- // Expect nulling out of further processing.
- EXPECT_CALL(*input_stream_, RegisterCallback(IsNullCallback()));
- ExpectPermissionError(InvokeSelectedRenameMethod(target_path, nullptr));
- EXPECT_FALSE(base::PathExists(target_path_suffixed));
- }
-
- FinishStream(download::DOWNLOAD_INTERRUPT_REASON_NONE, true, kEmptyHash);
- base::RunLoop().RunUntilIdle();
- DestroyDownloadFile(0);
-}
-
-namespace {
-
-void TestRenameCompletionCallback(
- const base::Closure& closure,
- bool* did_run_callback,
- download::DownloadInterruptReason interrupt_reason,
- const base::FilePath& new_path) {
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE, interrupt_reason);
- *did_run_callback = true;
- closure.Run();
-}
-
-} // namespace
-
-// Test that the retry logic works. This test assumes that DownloadFileImpl will
-// post tasks to the current message loop (acting as the download sequence)
-// asynchronously to retry the renames. We will stuff RunLoop::QuitClosures()
-// in between the retry tasks to stagger them and then allow the rename to
-// succeed.
-//
-// Note that there is only one queue of tasks to run, and that is in the tests'
-// base::MessageLoop::current(). Each RunLoop processes that queue until it sees
-// a QuitClosure() targeted at itself, at which point it stops processing.
-TEST_P(DownloadFileTestWithRename, RenameWithErrorRetry) {
- ASSERT_TRUE(CreateDownloadFile(0, true));
- base::FilePath initial_path(download_file_->FullPath());
-
- // Create a subdirectory.
- base::FilePath target_dir(
- initial_path.DirName().Append(FILE_PATH_LITERAL("TargetDir")));
- ASSERT_FALSE(base::DirectoryExists(target_dir));
- ASSERT_TRUE(base::CreateDirectory(target_dir));
- base::FilePath target_path(target_dir.Append(initial_path.BaseName()));
-
- bool did_run_callback = false;
-
- // Each RunLoop can be used the run the MessageLoop until the corresponding
- // QuitClosure() is run. This one is used to produce the QuitClosure() that
- // will be run when the entire rename operation is complete.
- base::RunLoop succeeding_run;
- {
- // (Scope for the base::File or base::FilePermissionRestorer below.)
-#if defined(OS_WIN)
- // On Windows we test with an actual transient error, a sharing violation.
- // The rename will fail because we are holding the file open for READ. On
- // Posix this doesn't cause a failure.
- base::File locked_file(initial_path,
- base::File::FLAG_OPEN | base::File::FLAG_READ);
- ASSERT_TRUE(locked_file.IsValid());
-#else
- // Simulate a transient failure by revoking write permission for target_dir.
- // The TestDownloadFileImpl class treats this error as transient even though
- // DownloadFileImpl itself doesn't.
- base::FilePermissionRestorer restore_permissions_for(target_dir);
- ASSERT_TRUE(base::MakeFileUnwritable(target_dir));
-#endif
-
- // The Rename() should fail here and enqueue a retry task without invoking
- // the completion callback.
- InvokeRenameMethod(GetParam(),
- target_path,
- base::Bind(&TestRenameCompletionCallback,
- succeeding_run.QuitClosure(),
- &did_run_callback));
- EXPECT_FALSE(did_run_callback);
-
- base::RunLoop first_failing_run;
- // Queue the QuitClosure() on the MessageLoop now. Any tasks queued by the
- // Rename() will be in front of the QuitClosure(). Running the message loop
- // now causes the just the first retry task to be run. The rename still
- // fails, so another retry task would get queued behind the QuitClosure().
- base::ThreadTaskRunnerHandle::Get()->PostTask(
- FROM_HERE, first_failing_run.QuitClosure());
- first_failing_run.Run();
- EXPECT_FALSE(did_run_callback);
-
- // Running another loop should have the same effect as the above as long as
- // kMaxRenameRetries is greater than 2.
- base::RunLoop second_failing_run;
- base::ThreadTaskRunnerHandle::Get()->PostTask(
- FROM_HERE, second_failing_run.QuitClosure());
- second_failing_run.Run();
- EXPECT_FALSE(did_run_callback);
- }
-
- // This time the QuitClosure from succeeding_run should get executed.
- succeeding_run.Run();
- EXPECT_TRUE(did_run_callback);
-
- FinishStream(download::DOWNLOAD_INTERRUPT_REASON_NONE, true, kEmptyHash);
- base::RunLoop().RunUntilIdle();
- DestroyDownloadFile(0);
-}
-
-// Various tests of the StreamActive method.
-TEST_F(DownloadFileTest, StreamEmptySuccess) {
- ASSERT_TRUE(CreateDownloadFile(0, true));
- base::FilePath initial_path(download_file_->FullPath());
- EXPECT_TRUE(base::PathExists(initial_path));
-
- // Test that calling the sink_callback_ on an empty stream shouldn't
- // do anything.
- AppendDataToFile(nullptr, 0);
-
- // Finish the download this way and make sure we see it on the observer.
- FinishStream(download::DOWNLOAD_INTERRUPT_REASON_NONE, true, kEmptyHash);
- base::RunLoop().RunUntilIdle();
-
- DestroyDownloadFile(0);
-}
-
-TEST_F(DownloadFileTest, StreamEmptyError) {
- ASSERT_TRUE(CreateDownloadFile(0, true));
- base::FilePath initial_path(download_file_->FullPath());
- EXPECT_TRUE(base::PathExists(initial_path));
-
- // Finish the download in error and make sure we see it on the
- // observer.
- EXPECT_CALL(*(observer_.get()),
- MockDestinationError(
- download::DOWNLOAD_INTERRUPT_REASON_NETWORK_DISCONNECTED, 0,
- kEmptyHash))
- .WillOnce(InvokeWithoutArgs(
- this, &DownloadFileTest::ConfirmUpdateDownloadInfo));
-
- // If this next EXPECT_CALL fails flakily, it's probably a real failure.
- // We'll be getting a stream of UpdateDownload calls from the timer, and
- // the last one may have the correct information even if the failure
- // doesn't produce an update, as the timer update may have triggered at the
- // same time.
- EXPECT_CALL(*(observer_.get()), CurrentUpdateStatus(0, _));
-
- FinishStream(download::DOWNLOAD_INTERRUPT_REASON_NETWORK_DISCONNECTED, false,
- kEmptyHash);
-
- base::RunLoop().RunUntilIdle();
-
- DestroyDownloadFile(0);
-}
-
-TEST_F(DownloadFileTest, StreamNonEmptySuccess) {
- ASSERT_TRUE(CreateDownloadFile(0, true));
- base::FilePath initial_path(download_file_->FullPath());
- EXPECT_TRUE(base::PathExists(initial_path));
-
- const char* chunks1[] = { kTestData1, kTestData2 };
- ::testing::Sequence s1;
- SetupDataAppend(chunks1, 2, input_stream_, s1);
- SetupFinishStream(download::DOWNLOAD_INTERRUPT_REASON_NONE, input_stream_,
- s1);
- EXPECT_CALL(*(observer_.get()), MockDestinationCompleted(_, _));
- sink_callback_.Run();
- VerifyStreamAndSize();
- base::RunLoop().RunUntilIdle();
- DestroyDownloadFile(0);
-}
-
-TEST_F(DownloadFileTest, StreamNonEmptyError) {
- ASSERT_TRUE(CreateDownloadFile(0, true));
- base::FilePath initial_path(download_file_->FullPath());
- EXPECT_TRUE(base::PathExists(initial_path));
-
- const char* chunks1[] = { kTestData1, kTestData2 };
- ::testing::Sequence s1;
- SetupDataAppend(chunks1, 2, input_stream_, s1);
- SetupFinishStream(download::DOWNLOAD_INTERRUPT_REASON_NETWORK_DISCONNECTED,
- input_stream_, s1);
-
- EXPECT_CALL(
- *(observer_.get()),
- MockDestinationError(
- download::DOWNLOAD_INTERRUPT_REASON_NETWORK_DISCONNECTED, _, _))
- .WillOnce(InvokeWithoutArgs(
- this, &DownloadFileTest::ConfirmUpdateDownloadInfo));
-
- // If this next EXPECT_CALL fails flakily, it's probably a real failure.
- // We'll be getting a stream of UpdateDownload calls from the timer, and
- // the last one may have the correct information even if the failure
- // doesn't produce an update, as the timer update may have triggered at the
- // same time.
- EXPECT_CALL(*(observer_.get()),
- CurrentUpdateStatus(strlen(kTestData1) + strlen(kTestData2), _));
-
- sink_callback_.Run();
- base::RunLoop().RunUntilIdle();
- VerifyStreamAndSize();
- DestroyDownloadFile(0);
-}
-
-// Tests for concurrent streams handling, used for parallel download.
-//
-// Activate both streams at the same time.
-TEST_F(DownloadFileTest, MultipleStreamsWrite) {
- int64_t stream_0_length = GetBuffersLength(kTestData6, 2);
- int64_t stream_1_length = GetBuffersLength(kTestData7, 2);
-
- ASSERT_TRUE(CreateDownloadFile(0, stream_0_length, true,
- download::DownloadItem::ReceivedSlices()));
-
- PrepareStream(&input_stream_, 0, false, true, kTestData6, 2);
- PrepareStream(&additional_streams_[0], stream_0_length, true, true,
- kTestData7, 2);
-
- EXPECT_CALL(*additional_streams_[0], RegisterCallback(_))
- .RetiresOnSaturation();
- EXPECT_CALL(*(observer_.get()), MockDestinationCompleted(_, _));
-
- // Activate the streams.
- download_file_->AddInputStream(
- std::make_unique<DownloadManager::InputStream>(
- std::unique_ptr<ByteStreamReader>(additional_streams_[0])),
- stream_0_length, download::DownloadSaveInfo::kLengthFullContent);
- sink_callback_.Run();
- base::RunLoop().RunUntilIdle();
-
- SourceStreamTestData stream_data_0(0, stream_0_length, true);
- SourceStreamTestData stream_data_1(stream_0_length, stream_1_length, true);
- VerifySourceStreamsStates(stream_data_0);
- VerifySourceStreamsStates(stream_data_1);
- EXPECT_EQ(stream_0_length + stream_1_length, TotalBytesReceived());
-
- DestroyDownloadFile(0);
-}
-
-// 3 streams write to one sink, the second stream has a limited length.
-TEST_F(DownloadFileTest, MutipleStreamsLimitedLength) {
- int64_t stream_0_length = GetBuffersLength(kTestData6, 2);
-
- // The second stream has a limited length and should be partially written
- // to disk. When we prepare the stream, we fill the stream with 2 full buffer.
- int64_t stream_1_length = GetBuffersLength(kTestData7, 2) - 1;
-
- // The last stream can't have length limit, it's a half open request, e.g
- // "Range:50-".
- int64_t stream_2_length = GetBuffersLength(kTestData6, 2);
-
- ASSERT_TRUE(CreateDownloadFile(0, stream_0_length, true,
- download::DownloadItem::ReceivedSlices()));
-
- PrepareStream(&input_stream_, 0, false, true, kTestData6, 2);
- PrepareStream(&additional_streams_[0], stream_0_length, true, false,
- kTestData7, 2);
- PrepareStream(&additional_streams_[1], stream_0_length + stream_1_length,
- true, true, kTestData6, 2);
-
- EXPECT_CALL(*additional_streams_[0], RegisterCallback(_))
- .Times(2)
- .RetiresOnSaturation();
-
- EXPECT_CALL(*additional_streams_[1], RegisterCallback(_))
- .RetiresOnSaturation();
-
- EXPECT_CALL(*(observer_.get()), MockDestinationCompleted(_, _));
-
- // Activate all the streams.
- download_file_->AddInputStream(
- std::make_unique<DownloadManager::InputStream>(
- std::unique_ptr<ByteStreamReader>(additional_streams_[0])),
- stream_0_length, stream_1_length);
- download_file_->AddInputStream(
- std::make_unique<DownloadManager::InputStream>(
- std::unique_ptr<ByteStreamReader>(additional_streams_[1])),
- stream_0_length + stream_1_length,
- download::DownloadSaveInfo::kLengthFullContent);
- sink_callback_.Run();
- base::RunLoop().RunUntilIdle();
-
- SourceStreamTestData stream_data_0(0, stream_0_length, true);
- SourceStreamTestData stream_data_1(stream_0_length, stream_1_length, true);
- SourceStreamTestData stream_data_2(stream_0_length + stream_1_length,
- stream_2_length, true);
-
- VerifySourceStreamsStates(stream_data_0);
- VerifySourceStreamsStates(stream_data_1);
- VerifySourceStreamsStates(stream_data_2);
-
- EXPECT_EQ(stream_0_length + stream_1_length + stream_2_length,
- TotalBytesReceived());
-
- download_file_->Cancel();
- DestroyDownloadFile(0, false);
-}
-
-// Activate and deplete one stream, later add the second stream.
-TEST_F(DownloadFileTest, MultipleStreamsFirstStreamWriteAllData) {
- int64_t stream_0_length = GetBuffersLength(kTestData8, 4);
-
- ASSERT_TRUE(
- CreateDownloadFile(0, download::DownloadSaveInfo::kLengthFullContent,
- true, download::DownloadItem::ReceivedSlices()));
-
- PrepareStream(&input_stream_, 0, false, true, kTestData8, 4);
-
- EXPECT_CALL(*(observer_.get()), MockDestinationCompleted(_, _));
-
- sink_callback_.Run();
- base::RunLoop().RunUntilIdle();
-
- // Add another stream, the file is already closed, so nothing should be
- // called.
- EXPECT_FALSE(download_file_->InProgress());
-
- additional_streams_[0] = new StrictMock<MockByteStreamReader>();
- download_file_->AddInputStream(
- std::make_unique<DownloadManager::InputStream>(
- std::unique_ptr<ByteStreamReader>(additional_streams_[0])),
- stream_0_length - 1, download::DownloadSaveInfo::kLengthFullContent);
- base::RunLoop().RunUntilIdle();
-
- SourceStreamTestData stream_data_0(0, stream_0_length, true);
- VerifySourceStreamsStates(stream_data_0);
- EXPECT_EQ(stream_0_length, TotalBytesReceived());
- EXPECT_EQ(1u, source_streams_count());
-
- DestroyDownloadFile(0);
-}
-
-// While one stream is writing, kick off another stream with an offset that has
-// been written by the first one.
-TEST_F(DownloadFileTest, SecondStreamStartingOffsetAlreadyWritten) {
- int64_t stream_0_length = GetBuffersLength(kTestData6, 2);
-
- ASSERT_TRUE(CreateDownloadFile(0, stream_0_length, true,
- download::DownloadItem::ReceivedSlices()));
-
- Sequence seq;
- SetupDataAppend(kTestData6, 2, input_stream_, seq, 0);
-
- EXPECT_CALL(*input_stream_, Read(_, _))
- .InSequence(seq)
- .WillOnce(Return(ByteStreamReader::STREAM_EMPTY))
- .RetiresOnSaturation();
- sink_callback_.Run();
- base::RunLoop().RunUntilIdle();
-
- additional_streams_[0] = new StrictMock<MockByteStreamReader>();
- EXPECT_CALL(*additional_streams_[0], RegisterCallback(_))
- .WillRepeatedly(Invoke(this, &DownloadFileTest::RegisterCallback))
- .RetiresOnSaturation();
- EXPECT_CALL(*additional_streams_[0], Read(_, _))
- .WillOnce(Return(ByteStreamReader::STREAM_EMPTY))
- .RetiresOnSaturation();
-
- download_file_->AddInputStream(
- std::make_unique<DownloadManager::InputStream>(
- std::unique_ptr<ByteStreamReader>(additional_streams_[0])),
- 0, download::DownloadSaveInfo::kLengthFullContent);
-
- // The stream should get terminated and reset the callback.
- EXPECT_TRUE(sink_callback_.is_null());
- download_file_->Cancel();
- DestroyDownloadFile(0, false);
-}
-
-} // namespace content
diff --git a/chromium/content/browser/download/download_interrupt_reasons_utils.cc b/chromium/content/browser/download/download_interrupt_reasons_utils.cc
deleted file mode 100644
index d8743b19a3a..00000000000
--- a/chromium/content/browser/download/download_interrupt_reasons_utils.cc
+++ /dev/null
@@ -1,157 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/download/download_interrupt_reasons_utils.h"
-
-#include "base/logging.h"
-
-namespace content {
-
-download::DownloadInterruptReason ConvertFileErrorToInterruptReason(
- base::File::Error file_error) {
- switch (file_error) {
- case base::File::FILE_OK:
- return download::DOWNLOAD_INTERRUPT_REASON_NONE;
-
- case base::File::FILE_ERROR_IN_USE:
- return download::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR;
-
- case base::File::FILE_ERROR_ACCESS_DENIED:
- return download::DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED;
-
- case base::File::FILE_ERROR_TOO_MANY_OPENED:
- return download::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR;
-
- case base::File::FILE_ERROR_NO_MEMORY:
- return download::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR;
-
- case base::File::FILE_ERROR_NO_SPACE:
- return download::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE;
-
- case base::File::FILE_ERROR_SECURITY:
- return download::DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED;
-
- default:
- return download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED;
- }
-}
-
-download::DownloadInterruptReason ConvertNetErrorToInterruptReason(
- net::Error net_error,
- DownloadInterruptSource source) {
- switch (net_error) {
- case net::OK:
- return download::DOWNLOAD_INTERRUPT_REASON_NONE;
-
- // File errors.
-
- // The file is too large.
- case net::ERR_FILE_TOO_BIG:
- return download::DOWNLOAD_INTERRUPT_REASON_FILE_TOO_LARGE;
-
- // Permission to access a resource, other than the network, was denied.
- case net::ERR_ACCESS_DENIED:
- return download::DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED;
-
- // There were not enough resources to complete the operation.
- case net::ERR_INSUFFICIENT_RESOURCES:
- return download::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR;
-
- // Memory allocation failed.
- case net::ERR_OUT_OF_MEMORY:
- return download::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR;
-
- // The path or file name is too long.
- case net::ERR_FILE_PATH_TOO_LONG:
- return download::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG;
-
- // Not enough room left on the disk.
- case net::ERR_FILE_NO_SPACE:
- return download::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE;
-
- // The file has a virus.
- case net::ERR_FILE_VIRUS_INFECTED:
- return download::DOWNLOAD_INTERRUPT_REASON_FILE_VIRUS_INFECTED;
-
- // The file was blocked by local policy.
- case net::ERR_BLOCKED_BY_CLIENT:
- return download::DOWNLOAD_INTERRUPT_REASON_FILE_BLOCKED;
-
- // Network errors.
-
- // The network operation timed out.
- case net::ERR_TIMED_OUT:
- return download::DOWNLOAD_INTERRUPT_REASON_NETWORK_TIMEOUT;
-
- // The network connection was lost or changed.
- case net::ERR_NETWORK_CHANGED:
- case net::ERR_INTERNET_DISCONNECTED:
- return download::DOWNLOAD_INTERRUPT_REASON_NETWORK_DISCONNECTED;
-
- // The server has gone down.
- case net::ERR_CONNECTION_FAILED:
- return download::DOWNLOAD_INTERRUPT_REASON_NETWORK_SERVER_DOWN;
-
- // Server responses.
-
- // The server does not support range requests.
- case net::ERR_REQUEST_RANGE_NOT_SATISFIABLE:
- return download::DOWNLOAD_INTERRUPT_REASON_SERVER_NO_RANGE;
-
- case net::ERR_CONTENT_LENGTH_MISMATCH:
- return download::DOWNLOAD_INTERRUPT_REASON_SERVER_CONTENT_LENGTH_MISMATCH;
-
- default:
- break;
- }
-
- // Handle errors that don't have mappings, depending on the source.
- switch (source) {
- case DOWNLOAD_INTERRUPT_FROM_DISK:
- return download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED;
- case DOWNLOAD_INTERRUPT_FROM_NETWORK:
- return download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED;
- case DOWNLOAD_INTERRUPT_FROM_SERVER:
- return download::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED;
- default:
- break;
- }
-
- NOTREACHED();
-
- return download::DOWNLOAD_INTERRUPT_REASON_NONE;
-}
-
-download::DownloadInterruptReason
-ConvertMojoNetworkRequestStatusToInterruptReason(
- download::mojom::NetworkRequestStatus status) {
- switch (status) {
- case download::mojom::NetworkRequestStatus::OK:
- return download::DOWNLOAD_INTERRUPT_REASON_NONE;
- case download::mojom::NetworkRequestStatus::NETWORK_TIMEOUT:
- return download::DOWNLOAD_INTERRUPT_REASON_NETWORK_TIMEOUT;
- case download::mojom::NetworkRequestStatus::NETWORK_DISCONNECTED:
- return download::DOWNLOAD_INTERRUPT_REASON_NETWORK_DISCONNECTED;
- case download::mojom::NetworkRequestStatus::NETWORK_SERVER_DOWN:
- return download::DOWNLOAD_INTERRUPT_REASON_NETWORK_SERVER_DOWN;
- case download::mojom::NetworkRequestStatus::SERVER_NO_RANGE:
- return download::DOWNLOAD_INTERRUPT_REASON_SERVER_NO_RANGE;
- case download::mojom::NetworkRequestStatus::SERVER_CONTENT_LENGTH_MISMATCH:
- return download::DOWNLOAD_INTERRUPT_REASON_SERVER_CONTENT_LENGTH_MISMATCH;
- case download::mojom::NetworkRequestStatus::SERVER_UNREACHABLE:
- return download::DOWNLOAD_INTERRUPT_REASON_SERVER_UNREACHABLE;
- case download::mojom::NetworkRequestStatus::SERVER_CERT_PROBLEM:
- return download::DOWNLOAD_INTERRUPT_REASON_SERVER_CERT_PROBLEM;
- case download::mojom::NetworkRequestStatus::USER_CANCELED:
- return download::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED;
- case download::mojom::NetworkRequestStatus::NETWORK_FAILED:
- return download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED;
- default:
- NOTREACHED();
- break;
- }
- return download::DOWNLOAD_INTERRUPT_REASON_NONE;
-}
-
-} // namespace content
diff --git a/chromium/content/browser/download/download_interrupt_reasons_utils.h b/chromium/content/browser/download/download_interrupt_reasons_utils.h
deleted file mode 100644
index 553ed8e6324..00000000000
--- a/chromium/content/browser/download/download_interrupt_reasons_utils.h
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_INTERRUPT_REASONS_UTILS_H_
-#define CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_INTERRUPT_REASONS_UTILS_H_
-
-#include "base/files/file.h"
-#include "components/download/public/common/download_interrupt_reasons.h"
-#include "components/download/public/common/download_stream.mojom.h"
-#include "content/common/content_export.h"
-#include "net/base/net_errors.h"
-
-namespace content {
-
-enum DownloadInterruptSource {
- DOWNLOAD_INTERRUPT_FROM_DISK,
- DOWNLOAD_INTERRUPT_FROM_NETWORK,
- DOWNLOAD_INTERRUPT_FROM_SERVER,
- DOWNLOAD_INTERRUPT_FROM_USER,
- DOWNLOAD_INTERRUPT_FROM_CRASH
-};
-
-// Safe to call from any thread.
-download::DownloadInterruptReason CONTENT_EXPORT
-ConvertNetErrorToInterruptReason(net::Error file_error,
- DownloadInterruptSource source);
-
-// Safe to call from any thread.
-download::DownloadInterruptReason CONTENT_EXPORT
-ConvertFileErrorToInterruptReason(base::File::Error file_error);
-
-// Safe to call from any thread.
-download::DownloadInterruptReason CONTENT_EXPORT
-ConvertMojoNetworkRequestStatusToInterruptReason(
- download::mojom::NetworkRequestStatus status);
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_INTERRUPT_REASONS_UTILS_H_
diff --git a/chromium/content/browser/download/download_item_factory.h b/chromium/content/browser/download/download_item_factory.h
deleted file mode 100644
index 7d6ef5ee66c..00000000000
--- a/chromium/content/browser/download/download_item_factory.h
+++ /dev/null
@@ -1,86 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-//
-// The DownloadItemFactory is used to produce different download::DownloadItems.
-// It is separate from the DownloadManager to allow download manager
-// unit tests to control the items produced.
-
-#ifndef CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_ITEM_FACTORY_H_
-#define CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_ITEM_FACTORY_H_
-
-#include <stdint.h>
-
-#include <memory>
-#include <string>
-#include <vector>
-
-#include "components/download/public/common/download_item.h"
-
-class GURL;
-
-namespace base {
-class FilePath;
-} // namespace base
-
-namespace download {
-struct DownloadCreateInfo;
-class DownloadRequestHandleInterface;
-} // namespace download
-
-namespace content {
-
-class DownloadItemImpl;
-class DownloadItemImplDelegate;
-
-class DownloadItemFactory {
-public:
- virtual ~DownloadItemFactory() {}
-
- virtual DownloadItemImpl* CreatePersistedItem(
- DownloadItemImplDelegate* delegate,
- const std::string& guid,
- uint32_t download_id,
- const base::FilePath& current_path,
- const base::FilePath& target_path,
- const std::vector<GURL>& url_chain,
- const GURL& referrer_url,
- const GURL& site_url,
- const GURL& tab_url,
- const GURL& tab_refererr_url,
- const std::string& mime_type,
- const std::string& original_mime_type,
- base::Time start_time,
- base::Time end_time,
- const std::string& etag,
- const std::string& last_modified,
- int64_t received_bytes,
- int64_t total_bytes,
- const std::string& hash,
- download::DownloadItem::DownloadState state,
- download::DownloadDangerType danger_type,
- download::DownloadInterruptReason interrupt_reason,
- bool opened,
- base::Time last_access_time,
- bool transient,
- const std::vector<download::DownloadItem::ReceivedSlice>&
- received_slices) = 0;
-
- virtual DownloadItemImpl* CreateActiveItem(
- DownloadItemImplDelegate* delegate,
- uint32_t download_id,
- const download::DownloadCreateInfo& info) = 0;
-
- virtual DownloadItemImpl* CreateSavePageItem(
- DownloadItemImplDelegate* delegate,
- uint32_t download_id,
- const base::FilePath& path,
- const GURL& url,
- const std::string& mime_type,
- std::unique_ptr<download::DownloadRequestHandleInterface>
- request_handle) = 0;
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_ITEM_FACTORY_H_
diff --git a/chromium/content/browser/download/download_item_impl.cc b/chromium/content/browser/download/download_item_impl.cc
deleted file mode 100644
index 31e5e6bfb74..00000000000
--- a/chromium/content/browser/download/download_item_impl.cc
+++ /dev/null
@@ -1,2571 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// File method ordering: Methods in this file are in the same order as
-// in download_item_impl.h, with the following exception: The public
-// interface Start is placed in chronological order with the other
-// (private) routines that together define a download::DownloadItem's state
-// transitions as the download progresses. See "Download progression
-// cascade" later in this file.
-
-// A regular download::DownloadItem (created for a download in this session of
-// the browser) normally goes through the following states:
-// * Created (when download starts)
-// * Destination filename determined
-// * Entered into the history database.
-// * Made visible in the download shelf.
-// * All the data is saved. Note that the actual data download occurs
-// in parallel with the above steps, but until those steps are
-// complete, the state of the data save will be ignored.
-// * Download file is renamed to its final name, and possibly
-// auto-opened.
-
-#include "content/browser/download/download_item_impl.h"
-
-#include <memory>
-#include <utility>
-#include <vector>
-
-#include "base/bind.h"
-#include "base/files/file_util.h"
-#include "base/format_macros.h"
-#include "base/guid.h"
-#include "base/logging.h"
-#include "base/metrics/histogram_macros.h"
-#include "base/optional.h"
-#include "base/stl_util.h"
-#include "base/strings/string_util.h"
-#include "base/strings/stringprintf.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/task_runner_util.h"
-#include "components/download/downloader/in_progress/in_progress_cache.h"
-#include "components/download/public/common/download_danger_type.h"
-#include "components/download/public/common/download_interrupt_reasons.h"
-#include "components/download/public/common/download_stats.h"
-#include "components/download/public/common/download_task_runner.h"
-#include "components/download/public/common/download_ukm_helper.h"
-#include "components/download/public/common/download_url_parameters.h"
-#include "content/browser/download/download_file.h"
-#include "content/browser/download/download_interrupt_reasons_utils.h"
-#include "content/browser/download/download_item_impl_delegate.h"
-#include "content/browser/download/download_job_factory.h"
-#include "content/browser/download/download_job_impl.h"
-#include "content/browser/download/download_request_handle.h"
-#include "content/browser/download/download_utils.h"
-#include "content/browser/download/parallel_download_utils.h"
-#include "content/browser/renderer_host/render_view_host_impl.h"
-#include "content/browser/web_contents/web_contents_impl.h"
-#include "content/public/browser/browser_context.h"
-#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/content_browser_client.h"
-#include "content/public/browser/download_item_utils.h"
-#include "content/public/browser/storage_partition.h"
-#include "content/public/common/content_features.h"
-#include "content/public/common/referrer.h"
-#include "net/http/http_response_headers.h"
-#include "net/http/http_status_code.h"
-#include "net/traffic_annotation/network_traffic_annotation.h"
-
-namespace content {
-
-namespace {
-
-bool DeleteDownloadedFile(const base::FilePath& path) {
- DCHECK(download::GetDownloadTaskRunner()->RunsTasksInCurrentSequence());
-
- // Make sure we only delete files.
- if (base::DirectoryExists(path))
- return true;
- return base::DeleteFile(path, false);
-}
-
-void DeleteDownloadedFileDone(
- base::WeakPtr<DownloadItemImpl> item,
- const base::Callback<void(bool)>& callback,
- bool success) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- if (success && item.get())
- item->OnDownloadedFileRemoved();
- callback.Run(success);
-}
-
-// Wrapper around DownloadFile::Detach and DownloadFile::Cancel that
-// takes ownership of the DownloadFile and hence implicitly destroys it
-// at the end of the function.
-base::FilePath DownloadFileDetach(std::unique_ptr<DownloadFile> download_file) {
- DCHECK(download::GetDownloadTaskRunner()->RunsTasksInCurrentSequence());
- base::FilePath full_path = download_file->FullPath();
- download_file->Detach();
- return full_path;
-}
-
-base::FilePath MakeCopyOfDownloadFile(DownloadFile* download_file) {
- DCHECK(download::GetDownloadTaskRunner()->RunsTasksInCurrentSequence());
- base::FilePath temp_file_path;
- if (!base::CreateTemporaryFile(&temp_file_path))
- return base::FilePath();
-
- if (!base::CopyFile(download_file->FullPath(), temp_file_path)) {
- DeleteDownloadedFile(temp_file_path);
- return base::FilePath();
- }
-
- return temp_file_path;
-}
-
-void DownloadFileCancel(std::unique_ptr<DownloadFile> download_file) {
- DCHECK(download::GetDownloadTaskRunner()->RunsTasksInCurrentSequence());
- download_file->Cancel();
-}
-
-// Most of the cancellation pathways behave the same whether the cancellation
-// was initiated by ther user (CANCELED) or initiated due to browser context
-// shutdown (SHUTDOWN).
-bool IsCancellation(download::DownloadInterruptReason reason) {
- return reason == download::DOWNLOAD_INTERRUPT_REASON_USER_SHUTDOWN ||
- reason == download::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED;
-}
-
-std::string GetDownloadTypeNames(download::DownloadItem::DownloadType type) {
- switch (type) {
- case download::DownloadItem::TYPE_ACTIVE_DOWNLOAD:
- return "NEW_DOWNLOAD";
- case download::DownloadItem::TYPE_HISTORY_IMPORT:
- return "HISTORY_IMPORT";
- case download::DownloadItem::TYPE_SAVE_PAGE_AS:
- return "SAVE_PAGE_AS";
- default:
- NOTREACHED();
- return "INVALID_TYPE";
- }
-}
-
-std::string GetDownloadDangerNames(download::DownloadDangerType type) {
- switch (type) {
- case download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS:
- return "NOT_DANGEROUS";
- case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE:
- return "DANGEROUS_FILE";
- case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL:
- return "DANGEROUS_URL";
- case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT:
- return "DANGEROUS_CONTENT";
- case download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT:
- return "MAYBE_DANGEROUS_CONTENT";
- case download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT:
- return "UNCOMMON_CONTENT";
- case download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED:
- return "USER_VALIDATED";
- case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST:
- return "DANGEROUS_HOST";
- case download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED:
- return "POTENTIALLY_UNWANTED";
- default:
- NOTREACHED();
- return "UNKNOWN_DANGER_TYPE";
- }
-}
-
-class DownloadItemActivatedData
- : public base::trace_event::ConvertableToTraceFormat {
- public:
- DownloadItemActivatedData(download::DownloadItem::DownloadType download_type,
- uint32_t download_id,
- std::string original_url,
- std::string final_url,
- std::string file_name,
- download::DownloadDangerType danger_type,
- int64_t start_offset,
- bool has_user_gesture)
- : download_type_(download_type),
- download_id_(download_id),
- original_url_(original_url),
- final_url_(final_url),
- file_name_(file_name),
- danger_type_(danger_type),
- start_offset_(start_offset),
- has_user_gesture_(has_user_gesture) {}
-
- ~DownloadItemActivatedData() override = default;
-
- void AppendAsTraceFormat(std::string* out) const override {
- out->append("{");
- out->append(base::StringPrintf(
- "\"type\":\"%s\",", GetDownloadTypeNames(download_type_).c_str()));
- out->append(base::StringPrintf("\"id\":\"%d\",", download_id_));
- out->append(
- base::StringPrintf("\"original_url\":\"%s\",", original_url_.c_str()));
- out->append(
- base::StringPrintf("\"final_url\":\"%s\",", final_url_.c_str()));
- out->append(
- base::StringPrintf("\"file_name\":\"%s\",", file_name_.c_str()));
- out->append(
- base::StringPrintf("\"danger_type\":\"%s\",",
- GetDownloadDangerNames(danger_type_).c_str()));
- out->append(
- base::StringPrintf("\"start_offset\":\"%" PRId64 "\",", start_offset_));
- out->append(base::StringPrintf("\"has_user_gesture\":\"%s\"",
- has_user_gesture_ ? "true" : "false"));
- out->append("}");
- }
-
- private:
- download::DownloadItem::DownloadType download_type_;
- uint32_t download_id_;
- std::string original_url_;
- std::string final_url_;
- std::string file_name_;
- download::DownloadDangerType danger_type_;
- int64_t start_offset_;
- bool has_user_gesture_;
- DISALLOW_COPY_AND_ASSIGN(DownloadItemActivatedData);
-};
-
-} // namespace
-
-// The maximum number of attempts we will make to resume automatically.
-const int DownloadItemImpl::kMaxAutoResumeAttempts = 5;
-
-DownloadItemImpl::RequestInfo::RequestInfo(
- const std::vector<GURL>& url_chain,
- const GURL& referrer_url,
- const GURL& site_url,
- const GURL& tab_url,
- const GURL& tab_referrer_url,
- const std::string& suggested_filename,
- const base::FilePath& forced_file_path,
- ui::PageTransition transition_type,
- bool has_user_gesture,
- const std::string& remote_address,
- base::Time start_time)
- : url_chain(url_chain),
- referrer_url(referrer_url),
- site_url(site_url),
- tab_url(tab_url),
- tab_referrer_url(tab_referrer_url),
- suggested_filename(suggested_filename),
- forced_file_path(forced_file_path),
- transition_type(transition_type),
- has_user_gesture(has_user_gesture),
- remote_address(remote_address),
- start_time(start_time) {}
-
-DownloadItemImpl::RequestInfo::RequestInfo(const GURL& url)
- : url_chain(std::vector<GURL>(1, url)), start_time(base::Time::Now()) {}
-
-DownloadItemImpl::RequestInfo::RequestInfo() = default;
-
-DownloadItemImpl::RequestInfo::RequestInfo(
- const DownloadItemImpl::RequestInfo& other) = default;
-
-DownloadItemImpl::RequestInfo::~RequestInfo() = default;
-
-DownloadItemImpl::DestinationInfo::DestinationInfo(
- const base::FilePath& target_path,
- const base::FilePath& current_path,
- int64_t received_bytes,
- bool all_data_saved,
- const std::string& hash,
- base::Time end_time)
- : target_path(target_path),
- current_path(current_path),
- received_bytes(received_bytes),
- all_data_saved(all_data_saved),
- hash(hash),
- end_time(end_time) {}
-
-DownloadItemImpl::DestinationInfo::DestinationInfo(
- TargetDisposition target_disposition)
- : target_disposition(target_disposition) {}
-
-DownloadItemImpl::DestinationInfo::DestinationInfo() = default;
-
-DownloadItemImpl::DestinationInfo::DestinationInfo(
- const DownloadItemImpl::DestinationInfo& other) = default;
-
-DownloadItemImpl::DestinationInfo::~DestinationInfo() = default;
-
-// Constructor for reading from the history service.
-DownloadItemImpl::DownloadItemImpl(
- DownloadItemImplDelegate* delegate,
- const std::string& guid,
- uint32_t download_id,
- const base::FilePath& current_path,
- const base::FilePath& target_path,
- const std::vector<GURL>& url_chain,
- const GURL& referrer_url,
- const GURL& site_url,
- const GURL& tab_url,
- const GURL& tab_refererr_url,
- const std::string& mime_type,
- const std::string& original_mime_type,
- base::Time start_time,
- base::Time end_time,
- const std::string& etag,
- const std::string& last_modified,
- int64_t received_bytes,
- int64_t total_bytes,
- const std::string& hash,
- download::DownloadItem::DownloadState state,
- download::DownloadDangerType danger_type,
- download::DownloadInterruptReason interrupt_reason,
- bool opened,
- base::Time last_access_time,
- bool transient,
- const std::vector<download::DownloadItem::ReceivedSlice>& received_slices)
- : request_info_(url_chain,
- referrer_url,
- site_url,
- tab_url,
- tab_refererr_url,
- std::string(),
- base::FilePath(),
- ui::PAGE_TRANSITION_LINK,
- false,
- std::string(),
- start_time),
- guid_(guid),
- download_id_(download_id),
- mime_type_(mime_type),
- original_mime_type_(original_mime_type),
- total_bytes_(total_bytes),
- last_reason_(interrupt_reason),
- start_tick_(base::TimeTicks()),
- state_(ExternalToInternalState(state)),
- danger_type_(danger_type),
- delegate_(delegate),
- opened_(opened),
- last_access_time_(last_access_time),
- transient_(transient),
- destination_info_(target_path,
- current_path,
- received_bytes,
- state == COMPLETE,
- hash,
- end_time),
- last_modified_time_(last_modified),
- etag_(etag),
- received_slices_(received_slices),
- is_updating_observers_(false),
- weak_ptr_factory_(this) {
- delegate_->Attach();
- DCHECK(state_ == COMPLETE_INTERNAL || state_ == INTERRUPTED_INTERNAL ||
- state_ == CANCELLED_INTERNAL);
- DCHECK(base::IsValidGUID(guid_));
- Init(false /* not actively downloading */, TYPE_HISTORY_IMPORT);
-}
-
-// Constructing for a regular download:
-DownloadItemImpl::DownloadItemImpl(DownloadItemImplDelegate* delegate,
- uint32_t download_id,
- const download::DownloadCreateInfo& info)
- : request_info_(info.url_chain,
- info.referrer_url,
- info.site_url,
- info.tab_url,
- info.tab_referrer_url,
- base::UTF16ToUTF8(info.save_info->suggested_name),
- info.save_info->file_path,
- info.transition_type ? info.transition_type.value()
- : ui::PAGE_TRANSITION_LINK,
- info.has_user_gesture,
- info.remote_address,
- info.start_time),
- guid_(info.guid.empty() ? base::GenerateGUID() : info.guid),
- download_id_(download_id),
- response_headers_(info.response_headers),
- content_disposition_(info.content_disposition),
- mime_type_(info.mime_type),
- original_mime_type_(info.original_mime_type),
- total_bytes_(info.total_bytes),
- last_reason_(info.result),
- start_tick_(base::TimeTicks::Now()),
- state_(INITIAL_INTERNAL),
- delegate_(delegate),
- is_temporary_(!info.transient && !info.save_info->file_path.empty()),
- transient_(info.transient),
- destination_info_(info.save_info->prompt_for_save_location
- ? TARGET_DISPOSITION_PROMPT
- : TARGET_DISPOSITION_OVERWRITE),
- last_modified_time_(info.last_modified),
- etag_(info.etag),
- is_updating_observers_(false),
- fetch_error_body_(info.fetch_error_body),
- download_source_(info.download_source),
- weak_ptr_factory_(this) {
- delegate_->Attach();
- Init(true /* actively downloading */, TYPE_ACTIVE_DOWNLOAD);
-
- TRACE_EVENT_INSTANT0("download", "DownloadStarted", TRACE_EVENT_SCOPE_THREAD);
-}
-
-// Constructing for the "Save Page As..." feature:
-DownloadItemImpl::DownloadItemImpl(
- DownloadItemImplDelegate* delegate,
- uint32_t download_id,
- const base::FilePath& path,
- const GURL& url,
- const std::string& mime_type,
- std::unique_ptr<download::DownloadRequestHandleInterface> request_handle)
- : request_info_(url),
- guid_(base::GenerateGUID()),
- download_id_(download_id),
- mime_type_(mime_type),
- original_mime_type_(mime_type),
- start_tick_(base::TimeTicks::Now()),
- state_(IN_PROGRESS_INTERNAL),
- delegate_(delegate),
- destination_info_(path, path, 0, false, std::string(), base::Time()),
- is_updating_observers_(false),
- weak_ptr_factory_(this) {
- job_ = DownloadJobFactory::CreateJob(this, std::move(request_handle),
- download::DownloadCreateInfo(), true);
- delegate_->Attach();
- Init(true /* actively downloading */, TYPE_SAVE_PAGE_AS);
-}
-
-DownloadItemImpl::~DownloadItemImpl() {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- // Should always have been nuked before now, at worst in
- // DownloadManager shutdown.
- DCHECK(!download_file_.get());
- CHECK(!is_updating_observers_);
-
- for (auto& observer : observers_)
- observer.OnDownloadDestroyed(this);
- delegate_->AssertStateConsistent(this);
- delegate_->Detach();
-}
-
-void DownloadItemImpl::AddObserver(Observer* observer) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- observers_.AddObserver(observer);
-}
-
-void DownloadItemImpl::RemoveObserver(Observer* observer) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- observers_.RemoveObserver(observer);
-}
-
-void DownloadItemImpl::UpdateObservers() {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DVLOG(20) << __func__ << "()";
-
- // Nested updates should not be allowed.
- DCHECK(!is_updating_observers_);
-
- is_updating_observers_ = true;
- for (auto& observer : observers_)
- observer.OnDownloadUpdated(this);
- is_updating_observers_ = false;
-}
-
-void DownloadItemImpl::ValidateDangerousDownload() {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DCHECK(!IsDone());
- DCHECK(IsDangerous());
-
- DVLOG(20) << __func__ << "() download=" << DebugString(true);
-
- if (IsDone() || !IsDangerous())
- return;
-
- download::RecordDangerousDownloadAccept(GetDangerType(), GetTargetFilePath());
-
- danger_type_ = download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED;
-
- TRACE_EVENT_INSTANT1("download", "DownloadItemSaftyStateUpdated",
- TRACE_EVENT_SCOPE_THREAD, "danger_type",
- GetDownloadDangerNames(danger_type_).c_str());
-
- UpdateObservers(); // TODO(asanka): This is potentially unsafe. The download
- // may not be in a consistent state or around at all after
- // invoking observers. http://crbug.com/586610
-
- MaybeCompleteDownload();
-}
-
-void DownloadItemImpl::StealDangerousDownload(
- bool delete_file_afterward,
- const AcquireFileCallback& callback) {
- DVLOG(20) << __func__ << "() download = " << DebugString(true);
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DCHECK(IsDangerous());
- DCHECK(AllDataSaved());
-
- if (delete_file_afterward) {
- if (download_file_) {
- base::PostTaskAndReplyWithResult(
- download::GetDownloadTaskRunner().get(), FROM_HERE,
- base::Bind(&DownloadFileDetach, base::Passed(&download_file_)),
- callback);
- } else {
- callback.Run(GetFullPath());
- }
- destination_info_.current_path.clear();
- Remove();
- // Download item has now been deleted.
- } else if (download_file_) {
- base::PostTaskAndReplyWithResult(
- download::GetDownloadTaskRunner().get(), FROM_HERE,
- base::Bind(&MakeCopyOfDownloadFile, download_file_.get()), callback);
- } else {
- callback.Run(GetFullPath());
- }
-}
-
-void DownloadItemImpl::Pause() {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- // Ignore irrelevant states.
- if (IsPaused())
- return;
-
- switch (state_) {
- case CANCELLED_INTERNAL:
- case COMPLETE_INTERNAL:
- case COMPLETING_INTERNAL:
- case INITIAL_INTERNAL:
- case INTERRUPTED_INTERNAL:
- case INTERRUPTED_TARGET_PENDING_INTERNAL:
- case RESUMING_INTERNAL:
- // No active request.
- // TODO(asanka): In the case of RESUMING_INTERNAL, consider setting
- // |DownloadJob::is_paused_| even if there's no request currently
- // associated with this DII. When a request is assigned (due to a
- // resumption, for example) we can honor the |DownloadJob::is_paused_|
- // setting.
- return;
-
- case IN_PROGRESS_INTERNAL:
- case TARGET_PENDING_INTERNAL:
- job_->Pause();
- UpdateObservers();
- return;
-
- case MAX_DOWNLOAD_INTERNAL_STATE:
- case TARGET_RESOLVED_INTERNAL:
- NOTREACHED();
- }
-}
-
-void DownloadItemImpl::Resume() {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DVLOG(20) << __func__ << "() download = " << DebugString(true);
- switch (state_) {
- case CANCELLED_INTERNAL: // Nothing to resume.
- case COMPLETE_INTERNAL:
- case COMPLETING_INTERNAL:
- case INITIAL_INTERNAL:
- case INTERRUPTED_TARGET_PENDING_INTERNAL:
- case RESUMING_INTERNAL: // Resumption in progress.
- return;
-
- case TARGET_PENDING_INTERNAL:
- case IN_PROGRESS_INTERNAL:
- if (!IsPaused())
- return;
- if (job_)
- job_->Resume(true);
- UpdateObservers();
- return;
-
- case INTERRUPTED_INTERNAL:
- auto_resume_count_ = 0; // User input resets the counter.
- ResumeInterruptedDownload(ResumptionRequestSource::USER);
- UpdateObservers();
- return;
-
- case MAX_DOWNLOAD_INTERNAL_STATE:
- case TARGET_RESOLVED_INTERNAL:
- NOTREACHED();
- }
-}
-
-void DownloadItemImpl::Cancel(bool user_cancel) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DVLOG(20) << __func__ << "() download = " << DebugString(true);
- InterruptAndDiscardPartialState(
- user_cancel ? download::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED
- : download::DOWNLOAD_INTERRUPT_REASON_USER_SHUTDOWN);
- UpdateObservers();
-}
-
-void DownloadItemImpl::Remove() {
- DVLOG(20) << __func__ << "() download = " << DebugString(true);
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- delegate_->AssertStateConsistent(this);
- InterruptAndDiscardPartialState(
- download::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED);
- UpdateObservers();
- delegate_->AssertStateConsistent(this);
-
- NotifyRemoved();
- delegate_->DownloadRemoved(this);
- // We have now been deleted.
-}
-
-void DownloadItemImpl::OpenDownload() {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- if (!IsDone()) {
- // We don't honor the open_when_complete_ flag for temporary
- // downloads. Don't set it because it shows up in the UI.
- if (!IsTemporary())
- open_when_complete_ = !open_when_complete_;
- return;
- }
-
- if (state_ != COMPLETE_INTERNAL || file_externally_removed_)
- return;
-
- // Ideally, we want to detect errors in opening and report them, but we
- // don't generally have the proper interface for that to the external
- // program that opens the file. So instead we spawn a check to update
- // the UI if the file has been deleted in parallel with the open.
- delegate_->CheckForFileRemoval(this);
- download::RecordOpen(GetEndTime(), !GetOpened());
- opened_ = true;
- last_access_time_ = base::Time::Now();
- for (auto& observer : observers_)
- observer.OnDownloadOpened(this);
- delegate_->OpenDownload(this);
-}
-
-void DownloadItemImpl::ShowDownloadInShell() {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- delegate_->ShowDownloadInShell(this);
-}
-
-uint32_t DownloadItemImpl::GetId() const {
- return download_id_;
-}
-
-const std::string& DownloadItemImpl::GetGuid() const {
- return guid_;
-}
-
-download::DownloadItem::DownloadState DownloadItemImpl::GetState() const {
- return InternalToExternalState(state_);
-}
-
-download::DownloadInterruptReason DownloadItemImpl::GetLastReason() const {
- return last_reason_;
-}
-
-bool DownloadItemImpl::IsPaused() const {
- return job_ ? job_->is_paused() : false;
-}
-
-bool DownloadItemImpl::IsTemporary() const {
- return is_temporary_;
-}
-
-bool DownloadItemImpl::CanResume() const {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- switch (state_) {
- case INITIAL_INTERNAL:
- case COMPLETING_INTERNAL:
- case COMPLETE_INTERNAL:
- case CANCELLED_INTERNAL:
- case RESUMING_INTERNAL:
- case INTERRUPTED_TARGET_PENDING_INTERNAL:
- return false;
-
- case TARGET_PENDING_INTERNAL:
- case TARGET_RESOLVED_INTERNAL:
- case IN_PROGRESS_INTERNAL:
- return IsPaused();
-
- case INTERRUPTED_INTERNAL: {
- download::ResumeMode resume_mode = GetResumeMode();
- // Only allow Resume() calls if the resumption mode requires a user
- // action.
- return resume_mode == download::ResumeMode::USER_RESTART ||
- resume_mode == download::ResumeMode::USER_CONTINUE;
- }
-
- case MAX_DOWNLOAD_INTERNAL_STATE:
- NOTREACHED();
- }
- return false;
-}
-
-bool DownloadItemImpl::IsDone() const {
- switch (state_) {
- case INITIAL_INTERNAL:
- case COMPLETING_INTERNAL:
- case RESUMING_INTERNAL:
- case TARGET_PENDING_INTERNAL:
- case INTERRUPTED_TARGET_PENDING_INTERNAL:
- case TARGET_RESOLVED_INTERNAL:
- case IN_PROGRESS_INTERNAL:
- return false;
-
- case COMPLETE_INTERNAL:
- case CANCELLED_INTERNAL:
- return true;
-
- case INTERRUPTED_INTERNAL:
- return !CanResume();
-
- case MAX_DOWNLOAD_INTERNAL_STATE:
- NOTREACHED();
- }
- return false;
-}
-
-const GURL& DownloadItemImpl::GetURL() const {
- return request_info_.url_chain.empty() ? GURL::EmptyGURL()
- : request_info_.url_chain.back();
-}
-
-const std::vector<GURL>& DownloadItemImpl::GetUrlChain() const {
- return request_info_.url_chain;
-}
-
-const GURL& DownloadItemImpl::GetOriginalUrl() const {
- // Be careful about taking the front() of possibly-empty vectors!
- // http://crbug.com/190096
- return request_info_.url_chain.empty() ? GURL::EmptyGURL()
- : request_info_.url_chain.front();
-}
-
-const GURL& DownloadItemImpl::GetReferrerUrl() const {
- return request_info_.referrer_url;
-}
-
-const GURL& DownloadItemImpl::GetSiteUrl() const {
- return request_info_.site_url;
-}
-
-const GURL& DownloadItemImpl::GetTabUrl() const {
- return request_info_.tab_url;
-}
-
-const GURL& DownloadItemImpl::GetTabReferrerUrl() const {
- return request_info_.tab_referrer_url;
-}
-
-std::string DownloadItemImpl::GetSuggestedFilename() const {
- return request_info_.suggested_filename;
-}
-
-const scoped_refptr<const net::HttpResponseHeaders>&
-DownloadItemImpl::GetResponseHeaders() const {
- return response_headers_;
-}
-
-std::string DownloadItemImpl::GetContentDisposition() const {
- return content_disposition_;
-}
-
-std::string DownloadItemImpl::GetMimeType() const {
- return mime_type_;
-}
-
-std::string DownloadItemImpl::GetOriginalMimeType() const {
- return original_mime_type_;
-}
-
-std::string DownloadItemImpl::GetRemoteAddress() const {
- return request_info_.remote_address;
-}
-
-bool DownloadItemImpl::HasUserGesture() const {
- return request_info_.has_user_gesture;
-}
-
-ui::PageTransition DownloadItemImpl::GetTransitionType() const {
- return request_info_.transition_type;
-}
-
-const std::string& DownloadItemImpl::GetLastModifiedTime() const {
- return last_modified_time_;
-}
-
-const std::string& DownloadItemImpl::GetETag() const {
- return etag_;
-}
-
-bool DownloadItemImpl::IsSavePackageDownload() const {
- return job_ && job_->IsSavePackageDownload();
-}
-
-const base::FilePath& DownloadItemImpl::GetFullPath() const {
- return destination_info_.current_path;
-}
-
-const base::FilePath& DownloadItemImpl::GetTargetFilePath() const {
- return destination_info_.target_path;
-}
-
-const base::FilePath& DownloadItemImpl::GetForcedFilePath() const {
- // TODO(asanka): Get rid of GetForcedFilePath(). We should instead just
- // require that clients respect GetTargetFilePath() if it is already set.
- return request_info_.forced_file_path;
-}
-
-base::FilePath DownloadItemImpl::GetFileNameToReportUser() const {
- if (!display_name_.empty())
- return display_name_;
- return GetTargetFilePath().BaseName();
-}
-
-download::DownloadItem::TargetDisposition
-DownloadItemImpl::GetTargetDisposition() const {
- return destination_info_.target_disposition;
-}
-
-const std::string& DownloadItemImpl::GetHash() const {
- return destination_info_.hash;
-}
-
-bool DownloadItemImpl::GetFileExternallyRemoved() const {
- return file_externally_removed_;
-}
-
-void DownloadItemImpl::DeleteFile(const base::Callback<void(bool)>& callback) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- if (GetState() != download::DownloadItem::COMPLETE) {
- // Pass a null WeakPtr so it doesn't call OnDownloadedFileRemoved.
- BrowserThread::PostTask(
- BrowserThread::UI, FROM_HERE,
- base::BindOnce(&DeleteDownloadedFileDone,
- base::WeakPtr<DownloadItemImpl>(), callback, false));
- return;
- }
- if (GetFullPath().empty() || file_externally_removed_) {
- // Pass a null WeakPtr so it doesn't call OnDownloadedFileRemoved.
- BrowserThread::PostTask(
- BrowserThread::UI, FROM_HERE,
- base::BindOnce(&DeleteDownloadedFileDone,
- base::WeakPtr<DownloadItemImpl>(), callback, true));
- return;
- }
- base::PostTaskAndReplyWithResult(
- download::GetDownloadTaskRunner().get(), FROM_HERE,
- base::Bind(&DeleteDownloadedFile, GetFullPath()),
- base::Bind(&DeleteDownloadedFileDone, weak_ptr_factory_.GetWeakPtr(),
- callback));
-}
-
-bool DownloadItemImpl::IsDangerous() const {
- return (danger_type_ == download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE ||
- danger_type_ == download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL ||
- danger_type_ == download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT ||
- danger_type_ == download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT ||
- danger_type_ == download::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST ||
- danger_type_ == download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED);
-}
-
-download::DownloadDangerType DownloadItemImpl::GetDangerType() const {
- return danger_type_;
-}
-
-bool DownloadItemImpl::TimeRemaining(base::TimeDelta* remaining) const {
- if (total_bytes_ <= 0)
- return false; // We never received the content_length for this download.
-
- int64_t speed = CurrentSpeed();
- if (speed == 0)
- return false;
-
- *remaining =
- base::TimeDelta::FromSeconds((total_bytes_ - GetReceivedBytes()) / speed);
- return true;
-}
-
-int64_t DownloadItemImpl::CurrentSpeed() const {
- if (IsPaused())
- return 0;
- return bytes_per_sec_;
-}
-
-int DownloadItemImpl::PercentComplete() const {
- // If the delegate is delaying completion of the download, then we have no
- // idea how long it will take.
- if (delegate_delayed_complete_ || total_bytes_ <= 0)
- return -1;
-
- return static_cast<int>(GetReceivedBytes() * 100.0 / total_bytes_);
-}
-
-bool DownloadItemImpl::AllDataSaved() const {
- return destination_info_.all_data_saved;
-}
-
-int64_t DownloadItemImpl::GetTotalBytes() const {
- return total_bytes_;
-}
-
-int64_t DownloadItemImpl::GetReceivedBytes() const {
- return destination_info_.received_bytes;
-}
-
-const std::vector<download::DownloadItem::ReceivedSlice>&
-DownloadItemImpl::GetReceivedSlices() const {
- return received_slices_;
-}
-
-base::Time DownloadItemImpl::GetStartTime() const {
- return request_info_.start_time;
-}
-
-base::Time DownloadItemImpl::GetEndTime() const {
- return destination_info_.end_time;
-}
-
-bool DownloadItemImpl::CanShowInFolder() {
- // A download can be shown in the folder if the downloaded file is in a known
- // location.
- return CanOpenDownload() && !GetFullPath().empty();
-}
-
-bool DownloadItemImpl::CanOpenDownload() {
- // We can open the file or mark it for opening on completion if the download
- // is expected to complete successfully. Exclude temporary downloads, since
- // they aren't owned by the download system.
- const bool is_complete = GetState() == download::DownloadItem::COMPLETE;
- return (!IsDone() || is_complete) && !IsTemporary() &&
- !file_externally_removed_ &&
- delegate_->IsMostRecentDownloadItemAtFilePath(this);
-}
-
-bool DownloadItemImpl::ShouldOpenFileBasedOnExtension() {
- return delegate_->ShouldOpenFileBasedOnExtension(GetTargetFilePath());
-}
-
-bool DownloadItemImpl::GetOpenWhenComplete() const {
- return open_when_complete_;
-}
-
-bool DownloadItemImpl::GetAutoOpened() {
- return auto_opened_;
-}
-
-bool DownloadItemImpl::GetOpened() const {
- return opened_;
-}
-
-base::Time DownloadItemImpl::GetLastAccessTime() const {
- return last_access_time_;
-}
-
-bool DownloadItemImpl::IsTransient() const {
- return transient_;
-}
-
-void DownloadItemImpl::OnContentCheckCompleted(
- download::DownloadDangerType danger_type,
- download::DownloadInterruptReason reason) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DCHECK(AllDataSaved());
-
- // Danger type is only allowed to be set on an active download after all data
- // has been saved. This excludes all other states. In particular,
- // OnContentCheckCompleted() isn't allowed on an INTERRUPTED download since
- // such an interruption would need to happen between OnAllDataSaved() and
- // OnContentCheckCompleted() during which no disk or network activity
- // should've taken place.
- DCHECK_EQ(state_, IN_PROGRESS_INTERNAL);
- DVLOG(20) << __func__ << "() danger_type=" << danger_type
- << " download=" << DebugString(true);
- SetDangerType(danger_type);
- if (reason != download::DOWNLOAD_INTERRUPT_REASON_NONE) {
- InterruptAndDiscardPartialState(reason);
- DCHECK_EQ(download::ResumeMode::INVALID, GetResumeMode());
- }
- UpdateObservers();
-}
-
-void DownloadItemImpl::SetOpenWhenComplete(bool open) {
- open_when_complete_ = open;
-}
-
-void DownloadItemImpl::SetOpened(bool opened) {
- opened_ = opened;
-}
-
-void DownloadItemImpl::SetLastAccessTime(base::Time last_access_time) {
- last_access_time_ = last_access_time;
- UpdateObservers();
-}
-
-void DownloadItemImpl::SetDisplayName(const base::FilePath& name) {
- display_name_ = name;
-}
-
-std::string DownloadItemImpl::DebugString(bool verbose) const {
- std::string description =
- base::StringPrintf("{ id = %d"
- " state = %s",
- download_id_,
- DebugDownloadStateString(state_));
-
- // Construct a string of the URL chain.
- std::string url_list("<none>");
- if (!request_info_.url_chain.empty()) {
- std::vector<GURL>::const_iterator iter = request_info_.url_chain.begin();
- std::vector<GURL>::const_iterator last = request_info_.url_chain.end();
- url_list = (*iter).is_valid() ? (*iter).spec() : "<invalid>";
- ++iter;
- for ( ; verbose && (iter != last); ++iter) {
- url_list += " ->\n\t";
- const GURL& next_url = *iter;
- url_list += next_url.is_valid() ? next_url.spec() : "<invalid>";
- }
- }
-
- if (verbose) {
- description += base::StringPrintf(
- " total = %" PRId64 " received = %" PRId64
- " reason = %s"
- " paused = %c"
- " resume_mode = %s"
- " auto_resume_count = %d"
- " danger = %d"
- " all_data_saved = %c"
- " last_modified = '%s'"
- " etag = '%s'"
- " has_download_file = %s"
- " url_chain = \n\t\"%s\"\n\t"
- " current_path = \"%" PRFilePath
- "\"\n\t"
- " target_path = \"%" PRFilePath
- "\""
- " referrer = \"%s\""
- " site_url = \"%s\"",
- GetTotalBytes(), GetReceivedBytes(),
- DownloadInterruptReasonToString(last_reason_).c_str(),
- IsPaused() ? 'T' : 'F', DebugResumeModeString(GetResumeMode()),
- auto_resume_count_, GetDangerType(), AllDataSaved() ? 'T' : 'F',
- GetLastModifiedTime().c_str(), GetETag().c_str(),
- download_file_.get() ? "true" : "false", url_list.c_str(),
- GetFullPath().value().c_str(), GetTargetFilePath().value().c_str(),
- GetReferrerUrl().spec().c_str(), GetSiteUrl().spec().c_str());
- } else {
- description += base::StringPrintf(" url = \"%s\"", url_list.c_str());
- }
-
- description += " }";
-
- return description;
-}
-
-void DownloadItemImpl::SimulateErrorForTesting(
- download::DownloadInterruptReason reason) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- InterruptWithPartialState(GetReceivedBytes(), nullptr, reason);
- UpdateObservers();
-}
-
-download::ResumeMode DownloadItemImpl::GetResumeMode() const {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- // Only support resumption for HTTP(S).
- if (!GetURL().SchemeIsHTTPOrHTTPS())
- return download::ResumeMode::INVALID;
-
- // We can't continue without a handle on the intermediate file.
- // We also can't continue if we don't have some verifier to make sure
- // we're getting the same file.
- bool restart_required =
- (GetFullPath().empty() || (etag_.empty() && last_modified_time_.empty()));
-
- // We won't auto-restart if we've used up our attempts or the
- // download has been paused by user action.
- bool user_action_required =
- (auto_resume_count_ >= kMaxAutoResumeAttempts || IsPaused());
-
- switch (last_reason_) {
- case download::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR:
- case download::DOWNLOAD_INTERRUPT_REASON_NETWORK_TIMEOUT:
- case download::DOWNLOAD_INTERRUPT_REASON_SERVER_CONTENT_LENGTH_MISMATCH:
- break;
-
- case download::DOWNLOAD_INTERRUPT_REASON_SERVER_NO_RANGE:
- // The server disagreed with the file offset that we sent.
-
- case download::DOWNLOAD_INTERRUPT_REASON_FILE_HASH_MISMATCH:
- // The file on disk was found to not match the expected hash. Discard and
- // start from beginning.
-
- case download::DOWNLOAD_INTERRUPT_REASON_FILE_TOO_SHORT:
- // The [possibly persisted] file offset disagreed with the file on disk.
-
- // The intermediate stub is not usable and the server is responding. Hence
- // retrying the request from the beginning is likely to work.
- restart_required = true;
- break;
-
- case download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED:
- case download::DOWNLOAD_INTERRUPT_REASON_NETWORK_DISCONNECTED:
- case download::DOWNLOAD_INTERRUPT_REASON_NETWORK_SERVER_DOWN:
- case download::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED:
- case download::DOWNLOAD_INTERRUPT_REASON_SERVER_UNREACHABLE:
- case download::DOWNLOAD_INTERRUPT_REASON_USER_SHUTDOWN:
- case download::DOWNLOAD_INTERRUPT_REASON_CRASH:
- // It is not clear whether attempting a resumption is acceptable at this
- // time or whether it would work at all. Hence allow the user to retry the
- // download manually.
- user_action_required = true;
- break;
-
- case download::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE:
- // There was no space. Require user interaction so that the user may, for
- // example, choose a different location to store the file. Or they may
- // free up some space on the targret device and retry. But try to reuse
- // the partial stub.
- user_action_required = true;
- break;
-
- case download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED:
- case download::DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED:
- case download::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG:
- case download::DOWNLOAD_INTERRUPT_REASON_FILE_TOO_LARGE:
- // Assume the partial stub is unusable. Also it may not be possible to
- // restart immediately.
- user_action_required = true;
- restart_required = true;
- break;
-
- case download::DOWNLOAD_INTERRUPT_REASON_NONE:
- case download::DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST:
- case download::DOWNLOAD_INTERRUPT_REASON_FILE_VIRUS_INFECTED:
- case download::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT:
- case download::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED:
- case download::DOWNLOAD_INTERRUPT_REASON_FILE_BLOCKED:
- case download::DOWNLOAD_INTERRUPT_REASON_FILE_SECURITY_CHECK_FAILED:
- case download::DOWNLOAD_INTERRUPT_REASON_SERVER_UNAUTHORIZED:
- case download::DOWNLOAD_INTERRUPT_REASON_SERVER_CERT_PROBLEM:
- case download::DOWNLOAD_INTERRUPT_REASON_SERVER_FORBIDDEN:
- case download::DOWNLOAD_INTERRUPT_REASON_FILE_SAME_AS_SOURCE:
- return download::ResumeMode::INVALID;
- }
-
- if (user_action_required && restart_required)
- return download::ResumeMode::USER_RESTART;
-
- if (restart_required)
- return download::ResumeMode::IMMEDIATE_RESTART;
-
- if (user_action_required)
- return download::ResumeMode::USER_CONTINUE;
-
- return download::ResumeMode::IMMEDIATE_CONTINUE;
-}
-
-BrowserContext* DownloadItemImpl::GetBrowserContext() const {
- return delegate_->GetBrowserContext();
-}
-
-WebContents* DownloadItemImpl::GetWebContents() const {
- // TODO(rdsmith): Remove null check after removing GetWebContents() from
- // paths that might be used by download::DownloadItems created from history
- // import. Currently such items have null request_handle_s, where other items
- // (regular and SavePackage downloads) have actual objects off the pointer.
- return DownloadItemUtils::GetWebContents(this);
-}
-
-void DownloadItemImpl::UpdateValidatorsOnResumption(
- const download::DownloadCreateInfo& new_create_info) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DCHECK_EQ(RESUMING_INTERNAL, state_);
- DCHECK(!new_create_info.url_chain.empty());
-
- // We are going to tack on any new redirects to our list of redirects.
- // When a download is resumed, the URL used for the resumption request is the
- // one at the end of the previous redirect chain. Tacking additional redirects
- // to the end of this chain ensures that:
- // - If the download needs to be resumed again, the ETag/Last-Modified headers
- // will be used with the last server that sent them to us.
- // - The redirect chain contains all the servers that were involved in this
- // download since the initial request, in order.
- std::vector<GURL>::const_iterator chain_iter =
- new_create_info.url_chain.begin();
- if (*chain_iter == request_info_.url_chain.back())
- ++chain_iter;
-
- // Record some stats. If the precondition failed (the server returned
- // HTTP_PRECONDITION_FAILED), then the download will automatically retried as
- // a full request rather than a partial. Full restarts clobber validators.
- int origin_state = 0;
- bool is_partial = GetReceivedBytes() > 0;
- if (chain_iter != new_create_info.url_chain.end())
- origin_state |= download::ORIGIN_STATE_ON_RESUMPTION_ADDITIONAL_REDIRECTS;
- if (etag_ != new_create_info.etag ||
- last_modified_time_ != new_create_info.last_modified) {
- received_slices_.clear();
- destination_info_.received_bytes = 0;
- origin_state |= download::ORIGIN_STATE_ON_RESUMPTION_VALIDATORS_CHANGED;
- }
- if (content_disposition_ != new_create_info.content_disposition)
- origin_state |=
- download::ORIGIN_STATE_ON_RESUMPTION_CONTENT_DISPOSITION_CHANGED;
- download::RecordOriginStateOnResumption(
- is_partial, static_cast<download::OriginStateOnResumption>(origin_state));
-
- request_info_.url_chain.insert(request_info_.url_chain.end(), chain_iter,
- new_create_info.url_chain.end());
- etag_ = new_create_info.etag;
- last_modified_time_ = new_create_info.last_modified;
- response_headers_ = new_create_info.response_headers;
- content_disposition_ = new_create_info.content_disposition;
- // It is possible that the previous download attempt failed right before the
- // response is received. Need to reset the MIME type.
- mime_type_ = new_create_info.mime_type;
-
- // Don't update observers. This method is expected to be called just before a
- // DownloadFile is created and Start() is called. The observers will be
- // notified when the download transitions to the IN_PROGRESS state.
-}
-
-void DownloadItemImpl::NotifyRemoved() {
- for (auto& observer : observers_)
- observer.OnDownloadRemoved(this);
-}
-
-void DownloadItemImpl::OnDownloadedFileRemoved() {
- file_externally_removed_ = true;
- DVLOG(20) << __func__ << "() download=" << DebugString(true);
- UpdateObservers();
-}
-
-base::WeakPtr<DownloadDestinationObserver>
-DownloadItemImpl::DestinationObserverAsWeakPtr() {
- return weak_ptr_factory_.GetWeakPtr();
-}
-
-void DownloadItemImpl::SetTotalBytes(int64_t total_bytes) {
- total_bytes_ = total_bytes;
-}
-
-void DownloadItemImpl::OnAllDataSaved(
- int64_t total_bytes,
- std::unique_ptr<crypto::SecureHash> hash_state) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DCHECK(!AllDataSaved());
- destination_info_.all_data_saved = true;
- SetTotalBytes(total_bytes);
- UpdateProgress(total_bytes, 0);
- received_slices_.clear();
- SetHashState(std::move(hash_state));
- hash_state_.reset(); // No need to retain hash_state_ since we are done with
- // the download and don't expect to receive any more
- // data.
-
- if (received_bytes_at_length_mismatch_ > 0) {
- if (total_bytes > received_bytes_at_length_mismatch_) {
- download::RecordDownloadCountWithSource(
- download::MORE_BYTES_RECEIVED_AFTER_CONTENT_LENGTH_MISMATCH_COUNT,
- download_source_);
- } else if (total_bytes == received_bytes_at_length_mismatch_) {
- download::RecordDownloadCountWithSource(
- download::NO_BYTES_RECEIVED_AFTER_CONTENT_LENGTH_MISMATCH_COUNT,
- download_source_);
- } else {
- // This could happen if the content changes on the server.
- }
- }
- DVLOG(20) << __func__ << "() download=" << DebugString(true);
- UpdateObservers();
-}
-
-void DownloadItemImpl::MarkAsComplete() {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- DCHECK(AllDataSaved());
- destination_info_.end_time = base::Time::Now();
- TransitionTo(COMPLETE_INTERNAL);
- UpdateObservers();
-}
-
-void DownloadItemImpl::DestinationUpdate(
- int64_t bytes_so_far,
- int64_t bytes_per_sec,
- const std::vector<download::DownloadItem::ReceivedSlice>& received_slices) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- // If the download is in any other state we don't expect any
- // DownloadDestinationObserver callbacks. An interruption or a cancellation
- // results in a call to ReleaseDownloadFile which invalidates the weak
- // reference held by the DownloadFile and hence cuts off any pending
- // callbacks.
- DCHECK(state_ == TARGET_PENDING_INTERNAL || state_ == IN_PROGRESS_INTERNAL ||
- state_ == INTERRUPTED_TARGET_PENDING_INTERNAL);
-
- // There must be no pending deferred_interrupt_reason_.
- DCHECK(deferred_interrupt_reason_ ==
- download::DOWNLOAD_INTERRUPT_REASON_NONE ||
- state_ == INTERRUPTED_TARGET_PENDING_INTERNAL);
-
- DVLOG(20) << __func__ << "() so_far=" << bytes_so_far
- << " per_sec=" << bytes_per_sec
- << " download=" << DebugString(true);
-
- UpdateProgress(bytes_so_far, bytes_per_sec);
- received_slices_ = received_slices;
- TRACE_EVENT_INSTANT1("download", "DownloadItemUpdated",
- TRACE_EVENT_SCOPE_THREAD, "bytes_so_far",
- GetReceivedBytes());
-
- UpdateObservers();
-}
-
-void DownloadItemImpl::DestinationError(
- download::DownloadInterruptReason reason,
- int64_t bytes_so_far,
- std::unique_ptr<crypto::SecureHash> secure_hash) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- // If the download is in any other state we don't expect any
- // DownloadDestinationObserver callbacks. An interruption or a cancellation
- // results in a call to ReleaseDownloadFile which invalidates the weak
- // reference held by the DownloadFile and hence cuts off any pending
- // callbacks.
- DCHECK(state_ == TARGET_PENDING_INTERNAL || state_ == IN_PROGRESS_INTERNAL);
- DVLOG(20) << __func__
- << "() reason:" << DownloadInterruptReasonToString(reason)
- << " this:" << DebugString(true);
-
- InterruptWithPartialState(bytes_so_far, std::move(secure_hash), reason);
- UpdateObservers();
-}
-
-void DownloadItemImpl::DestinationCompleted(
- int64_t total_bytes,
- std::unique_ptr<crypto::SecureHash> secure_hash) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- // If the download is in any other state we don't expect any
- // DownloadDestinationObserver callbacks. An interruption or a cancellation
- // results in a call to ReleaseDownloadFile which invalidates the weak
- // reference held by the DownloadFile and hence cuts off any pending
- // callbacks.
- DCHECK(state_ == TARGET_PENDING_INTERNAL || state_ == IN_PROGRESS_INTERNAL ||
- state_ == INTERRUPTED_TARGET_PENDING_INTERNAL);
- DVLOG(20) << __func__ << "() download=" << DebugString(true);
-
- OnAllDataSaved(total_bytes, std::move(secure_hash));
- MaybeCompleteDownload();
-}
-
-// **** Download progression cascade
-
-void DownloadItemImpl::Init(
- bool active,
- download::DownloadItem::DownloadType download_type) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- std::string file_name;
- if (download_type == TYPE_HISTORY_IMPORT) {
- // target_path_ works for History and Save As versions.
- file_name = GetTargetFilePath().AsUTF8Unsafe();
- } else {
- // See if it's set programmatically.
- file_name = GetForcedFilePath().AsUTF8Unsafe();
- // Possibly has a 'download' attribute for the anchor.
- if (file_name.empty())
- file_name = GetSuggestedFilename();
- // From the URL file name.
- if (file_name.empty())
- file_name = GetURL().ExtractFileName();
- }
-
- auto active_data = std::make_unique<DownloadItemActivatedData>(
- download_type, GetId(), GetOriginalUrl().spec(), GetURL().spec(),
- file_name, GetDangerType(), GetReceivedBytes(), HasUserGesture());
-
- if (active) {
- TRACE_EVENT_ASYNC_BEGIN1("download", "DownloadItemActive", download_id_,
- "download_item", std::move(active_data));
- } else {
- TRACE_EVENT_INSTANT1("download", "DownloadItemActive",
- TRACE_EVENT_SCOPE_THREAD, "download_item",
- std::move(active_data));
-
- // Read data from in-progress cache.
- auto in_progress_entry = GetInProgressEntry(guid_, GetBrowserContext());
- if (in_progress_entry)
- download_source_ = in_progress_entry->download_source;
- }
-
- DVLOG(20) << __func__ << "() " << DebugString(true);
-}
-
-// We're starting the download.
-void DownloadItemImpl::Start(
- std::unique_ptr<DownloadFile> file,
- std::unique_ptr<download::DownloadRequestHandleInterface> req_handle,
- const download::DownloadCreateInfo& new_create_info) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DCHECK(!download_file_.get());
- DVLOG(20) << __func__ << "() this=" << DebugString(true);
- download::RecordDownloadCountWithSource(download::START_COUNT,
- download_source_);
-
- download_file_ = std::move(file);
- job_ = DownloadJobFactory::CreateJob(this, std::move(req_handle),
- new_create_info, false);
- if (job_->IsParallelizable()) {
- download::RecordParallelizableDownloadCount(download::START_COUNT,
- IsParallelDownloadEnabled());
- }
-
- deferred_interrupt_reason_ = download::DOWNLOAD_INTERRUPT_REASON_NONE;
-
- if (state_ == CANCELLED_INTERNAL) {
- // The download was in the process of resuming when it was cancelled. Don't
- // proceed.
- ReleaseDownloadFile(true);
- job_->Cancel(true);
- return;
- }
-
- // The state could be one of the following:
- //
- // INITIAL_INTERNAL: A normal download attempt.
- //
- // RESUMING_INTERNAL: A resumption attempt. May or may not have been
- // successful.
- DCHECK(state_ == INITIAL_INTERNAL || state_ == RESUMING_INTERNAL);
-
- // If the state_ is INITIAL_INTERNAL, then the target path must be empty.
- DCHECK(state_ != INITIAL_INTERNAL || GetTargetFilePath().empty());
-
- // If a resumption attempted failed, or if the download was DOA, then the
- // download should go back to being interrupted.
- if (new_create_info.result != download::DOWNLOAD_INTERRUPT_REASON_NONE) {
- DCHECK(!download_file_.get());
-
- // Download requests that are interrupted by Start() should result in a
- // DownloadCreateInfo with an intact DownloadSaveInfo.
- DCHECK(new_create_info.save_info);
-
- int64_t offset = new_create_info.save_info->offset;
- std::unique_ptr<crypto::SecureHash> hash_state =
- new_create_info.save_info->hash_state
- ? new_create_info.save_info->hash_state->Clone()
- : nullptr;
-
- destination_info_.received_bytes = offset;
- hash_state_ = std::move(hash_state);
- destination_info_.hash.clear();
- deferred_interrupt_reason_ = new_create_info.result;
- received_slices_.clear();
- TransitionTo(INTERRUPTED_TARGET_PENDING_INTERNAL);
- DetermineDownloadTarget();
- return;
- }
-
- if (state_ == INITIAL_INTERNAL) {
- download::RecordDownloadCountWithSource(download::NEW_DOWNLOAD_COUNT,
- download_source_);
- if (job_->IsParallelizable()) {
- download::RecordParallelizableDownloadCount(download::NEW_DOWNLOAD_COUNT,
- IsParallelDownloadEnabled());
- }
- download::RecordDownloadMimeType(mime_type_);
- download::DownloadContent file_type =
- download::DownloadContentFromMimeType(mime_type_, false);
- auto in_progress_entry = GetInProgressEntry(guid_, GetBrowserContext());
- if (in_progress_entry) {
- download::DownloadUkmHelper::RecordDownloadStarted(
- in_progress_entry->ukm_download_id, new_create_info.ukm_source_id,
- file_type, download_source_);
- }
-
- if (!GetBrowserContext()->IsOffTheRecord()) {
- download::RecordDownloadCountWithSource(
- download::NEW_DOWNLOAD_COUNT_NORMAL_PROFILE, download_source_);
- download::RecordDownloadMimeTypeForNormalProfile(mime_type_);
- }
- }
-
- // Successful download start.
- DCHECK(download_file_);
- DCHECK(job_);
-
- if (state_ == RESUMING_INTERNAL)
- UpdateValidatorsOnResumption(new_create_info);
-
- // If the download is not parallel download during resumption, clear the
- // |received_slices_|.
- if (!job_->IsParallelizable() && !received_slices_.empty()) {
- destination_info_.received_bytes =
- GetMaxContiguousDataBlockSizeFromBeginning(received_slices_);
- received_slices_.clear();
- }
-
- TransitionTo(TARGET_PENDING_INTERNAL);
-
- job_->Start(download_file_.get(),
- base::Bind(&DownloadItemImpl::OnDownloadFileInitialized,
- weak_ptr_factory_.GetWeakPtr()),
- GetReceivedSlices());
-}
-
-void DownloadItemImpl::OnDownloadFileInitialized(
- download::DownloadInterruptReason result) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DCHECK(state_ == TARGET_PENDING_INTERNAL ||
- state_ == INTERRUPTED_TARGET_PENDING_INTERNAL)
- << "Unexpected state: " << DebugDownloadStateString(state_);
-
- DVLOG(20) << __func__
- << "() result:" << DownloadInterruptReasonToString(result);
- if (result != download::DOWNLOAD_INTERRUPT_REASON_NONE) {
- ReleaseDownloadFile(true);
- InterruptAndDiscardPartialState(result);
- }
-
- DetermineDownloadTarget();
-}
-
-void DownloadItemImpl::DetermineDownloadTarget() {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DVLOG(20) << __func__ << "() " << DebugString(true);
-
- download::RecordDownloadCountWithSource(
- download::DETERMINE_DOWNLOAD_TARGET_COUNT, download_source_);
- delegate_->DetermineDownloadTarget(
- this, base::Bind(&DownloadItemImpl::OnDownloadTargetDetermined,
- weak_ptr_factory_.GetWeakPtr()));
-}
-
-// Called by delegate_ when the download target path has been determined.
-void DownloadItemImpl::OnDownloadTargetDetermined(
- const base::FilePath& target_path,
- TargetDisposition disposition,
- download::DownloadDangerType danger_type,
- const base::FilePath& intermediate_path,
- download::DownloadInterruptReason interrupt_reason) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- if (state_ == CANCELLED_INTERNAL)
- return;
-
- DCHECK(state_ == TARGET_PENDING_INTERNAL ||
- state_ == INTERRUPTED_TARGET_PENDING_INTERNAL);
- DVLOG(20) << __func__ << "() target_path:" << target_path.value()
- << " intermediate_path:" << intermediate_path.value()
- << " disposition:" << disposition << " danger_type:" << danger_type
- << " interrupt_reason:"
- << DownloadInterruptReasonToString(interrupt_reason)
- << " this:" << DebugString(true);
-
- download::RecordDownloadCountWithSource(
- download::DOWNLOAD_TARGET_DETERMINED_COUNT, download_source_);
-
- if (IsCancellation(interrupt_reason) || target_path.empty()) {
- Cancel(true);
- return;
- }
-
- // There were no other pending errors, and we just failed to determined the
- // download target. The target path, if it is non-empty, should be considered
- // suspect. The safe option here is to interrupt the download without doing an
- // intermediate rename. In the case of a new download, we'll lose the partial
- // data that may have been downloaded, but that should be a small loss.
- if (state_ == TARGET_PENDING_INTERNAL &&
- interrupt_reason != download::DOWNLOAD_INTERRUPT_REASON_NONE) {
- deferred_interrupt_reason_ = interrupt_reason;
- TransitionTo(INTERRUPTED_TARGET_PENDING_INTERNAL);
- OnTargetResolved();
- return;
- }
-
- destination_info_.target_path = target_path;
- destination_info_.target_disposition = disposition;
- SetDangerType(danger_type);
-
- // This was an interrupted download that was looking for a filename. Resolve
- // early without performing the intermediate rename. If there is a
- // DownloadFile, then that should be renamed to the intermediate name before
- // we can interrupt the download. Otherwise we may lose intermediate state.
- if (state_ == INTERRUPTED_TARGET_PENDING_INTERNAL && !download_file_) {
- OnTargetResolved();
- return;
- }
-
- // We want the intermediate and target paths to refer to the same directory so
- // that they are both on the same device and subject to same
- // space/permission/availability constraints.
- DCHECK(intermediate_path.DirName() == target_path.DirName());
-
- // During resumption, we may choose to proceed with the same intermediate
- // file. No rename is necessary if our intermediate file already has the
- // correct name.
- //
- // The intermediate name may change from its original value during filename
- // determination on resumption, for example if the reason for the interruption
- // was the download target running out space, resulting in a user prompt.
- if (intermediate_path == GetFullPath()) {
- OnDownloadRenamedToIntermediateName(
- download::DOWNLOAD_INTERRUPT_REASON_NONE, intermediate_path);
- return;
- }
-
- // Rename to intermediate name.
- // TODO(asanka): Skip this rename if AllDataSaved() is true. This avoids a
- // spurious rename when we can just rename to the final
- // filename. Unnecessary renames may cause bugs like
- // http://crbug.com/74187.
- DCHECK(!IsSavePackageDownload());
- DownloadFile::RenameCompletionCallback callback =
- base::Bind(&DownloadItemImpl::OnDownloadRenamedToIntermediateName,
- weak_ptr_factory_.GetWeakPtr());
- download::GetDownloadTaskRunner()->PostTask(
- FROM_HERE,
- base::BindOnce(&DownloadFile::RenameAndUniquify,
- // Safe because we control download file lifetime.
- base::Unretained(download_file_.get()), intermediate_path,
- callback));
-}
-
-void DownloadItemImpl::OnDownloadRenamedToIntermediateName(
- download::DownloadInterruptReason reason,
- const base::FilePath& full_path) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DCHECK(state_ == TARGET_PENDING_INTERNAL ||
- state_ == INTERRUPTED_TARGET_PENDING_INTERNAL);
- DCHECK(download_file_);
- DVLOG(20) << __func__ << "() download=" << DebugString(true);
-
- if (download::DOWNLOAD_INTERRUPT_REASON_NONE == reason) {
- SetFullPath(full_path);
- } else {
- // TODO(asanka): Even though the rename failed, it may still be possible to
- // recover the partial state from the 'before' name.
- deferred_interrupt_reason_ = reason;
- TransitionTo(INTERRUPTED_TARGET_PENDING_INTERNAL);
- }
- OnTargetResolved();
-}
-
-void DownloadItemImpl::OnTargetResolved() {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DVLOG(20) << __func__ << "() download=" << DebugString(true);
- DCHECK(
- (state_ == TARGET_PENDING_INTERNAL &&
- deferred_interrupt_reason_ ==
- download::DOWNLOAD_INTERRUPT_REASON_NONE) ||
- (state_ == INTERRUPTED_TARGET_PENDING_INTERNAL &&
- deferred_interrupt_reason_ != download::DOWNLOAD_INTERRUPT_REASON_NONE))
- << " deferred_interrupt_reason_:"
- << DownloadInterruptReasonToString(deferred_interrupt_reason_)
- << " this:" << DebugString(true);
-
- // This transition is here to ensure that the DownloadItemImpl state machine
- // doesn't transition to INTERRUPTED or IN_PROGRESS from
- // TARGET_PENDING_INTERNAL directly. Doing so without passing through
- // OnTargetResolved() can result in an externally visible state where the
- // download is interrupted but doesn't have a target path associated with it.
- //
- // While not terrible, this complicates the download::DownloadItem<->Observer
- // relationship since an observer that needs a target path in order to respond
- // properly to an interruption will need to wait for another OnDownloadUpdated
- // notification. This requirement currently affects all of our UIs.
- TransitionTo(TARGET_RESOLVED_INTERNAL);
-
- if (download::DOWNLOAD_INTERRUPT_REASON_NONE != deferred_interrupt_reason_) {
- InterruptWithPartialState(GetReceivedBytes(), std::move(hash_state_),
- deferred_interrupt_reason_);
- deferred_interrupt_reason_ = download::DOWNLOAD_INTERRUPT_REASON_NONE;
- UpdateObservers();
- return;
- }
-
- TransitionTo(IN_PROGRESS_INTERNAL);
- // TODO(asanka): Calling UpdateObservers() prior to MaybeCompleteDownload() is
- // not safe. The download could be in an underminate state after invoking
- // observers. http://crbug.com/586610
- UpdateObservers();
- MaybeCompleteDownload();
-}
-
-// When SavePackage downloads MHTML to GData (see
-// SavePackageFilePickerChromeOS), GData calls MaybeCompleteDownload() like it
-// does for non-SavePackage downloads, but SavePackage downloads never satisfy
-// IsDownloadReadyForCompletion(). GDataDownloadObserver manually calls
-// download::DownloadItem::UpdateObservers() when the upload completes so that
-// SavePackage notices that the upload has completed and runs its normal
-// Finish() pathway. MaybeCompleteDownload() is never the mechanism by which
-// SavePackage completes downloads. SavePackage always uses its own Finish() to
-// mark downloads complete.
-void DownloadItemImpl::MaybeCompleteDownload() {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DCHECK(!IsSavePackageDownload());
-
- if (!IsDownloadReadyForCompletion(
- base::Bind(&DownloadItemImpl::MaybeCompleteDownload,
- weak_ptr_factory_.GetWeakPtr())))
- return;
- // Confirm we're in the proper set of states to be here; have all data, have a
- // history handle, (validated or safe).
- DCHECK_EQ(IN_PROGRESS_INTERNAL, state_);
- DCHECK(!IsDangerous());
- DCHECK(AllDataSaved());
-
- OnDownloadCompleting();
-}
-
-// Called by MaybeCompleteDownload() when it has determined that the download
-// is ready for completion.
-void DownloadItemImpl::OnDownloadCompleting() {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- if (state_ != IN_PROGRESS_INTERNAL)
- return;
-
- DVLOG(20) << __func__ << "() " << DebugString(true);
- DCHECK(!GetTargetFilePath().empty());
- DCHECK(!IsDangerous());
-
- DCHECK(download_file_.get());
- // Unilaterally rename; even if it already has the right name,
- // we need theannotation.
- DownloadFile::RenameCompletionCallback callback =
- base::Bind(&DownloadItemImpl::OnDownloadRenamedToFinalName,
- weak_ptr_factory_.GetWeakPtr());
- download::GetDownloadTaskRunner()->PostTask(
- FROM_HERE,
- base::BindOnce(&DownloadFile::RenameAndAnnotate,
- base::Unretained(download_file_.get()),
- GetTargetFilePath(),
- delegate_->GetApplicationClientIdForFileScanning(),
- GetURL(), GetReferrerUrl(), callback));
-}
-
-void DownloadItemImpl::OnDownloadRenamedToFinalName(
- download::DownloadInterruptReason reason,
- const base::FilePath& full_path) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DCHECK(!IsSavePackageDownload());
-
- // If a cancel or interrupt hit, we'll cancel the DownloadFile, which
- // will result in deleting the file on the file thread. So we don't
- // care about the name having been changed.
- if (state_ != IN_PROGRESS_INTERNAL)
- return;
-
- DVLOG(20) << __func__ << "() full_path = \"" << full_path.value() << "\" "
- << DebugString(false);
-
- if (download::DOWNLOAD_INTERRUPT_REASON_NONE != reason) {
- // Failure to perform the final rename is considered fatal. TODO(asanka): It
- // may not be, in which case we should figure out whether we can recover the
- // state.
- InterruptAndDiscardPartialState(reason);
- UpdateObservers();
- return;
- }
-
- DCHECK(GetTargetFilePath() == full_path);
-
- if (full_path != GetFullPath()) {
- // full_path is now the current and target file path.
- DCHECK(!full_path.empty());
- SetFullPath(full_path);
- }
-
- // Complete the download and release the DownloadFile.
- DCHECK(download_file_);
- ReleaseDownloadFile(false);
-
- // We're not completely done with the download item yet, but at this
- // point we're committed to complete the download. Cancels (or Interrupts,
- // though it's not clear how they could happen) after this point will be
- // ignored.
- TransitionTo(COMPLETING_INTERNAL);
-
- if (delegate_->ShouldOpenDownload(
- this, base::Bind(&DownloadItemImpl::DelayedDownloadOpened,
- weak_ptr_factory_.GetWeakPtr()))) {
- Completed();
- } else {
- delegate_delayed_complete_ = true;
- UpdateObservers();
- }
-}
-
-void DownloadItemImpl::DelayedDownloadOpened(bool auto_opened) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- auto_opened_ = auto_opened;
- Completed();
-}
-
-void DownloadItemImpl::Completed() {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- DVLOG(20) << __func__ << "() " << DebugString(false);
-
- DCHECK(AllDataSaved());
- destination_info_.end_time = base::Time::Now();
- TransitionTo(COMPLETE_INTERNAL);
-
- bool is_parallelizable = job_ && job_->IsParallelizable();
- download::RecordDownloadCompleted(start_tick_, GetReceivedBytes(),
- is_parallelizable, download_source_);
- if (!GetBrowserContext()->IsOffTheRecord()) {
- download::RecordDownloadCountWithSource(
- download::COMPLETED_COUNT_NORMAL_PROFILE, download_source_);
- }
- if (is_parallelizable) {
- download::RecordParallelizableDownloadCount(download::COMPLETED_COUNT,
- IsParallelDownloadEnabled());
- int64_t content_length = -1;
- if (response_headers_->response_code() != net::HTTP_PARTIAL_CONTENT) {
- content_length = response_headers_->GetContentLength();
- } else {
- int64_t first_byte = -1;
- int64_t last_byte = -1;
- response_headers_->GetContentRangeFor206(&first_byte, &last_byte,
- &content_length);
- }
- if (content_length > 0)
- download::RecordParallelizableContentLength(content_length);
- }
-
- if (auto_opened_) {
- // If it was already handled by the delegate, do nothing.
- } else if (GetOpenWhenComplete() ||
- ShouldOpenFileBasedOnExtension() ||
- IsTemporary()) {
- // If the download is temporary, like in drag-and-drop, do not open it but
- // we still need to set it auto-opened so that it can be removed from the
- // download shelf.
- if (!IsTemporary())
- OpenDownload();
-
- auto_opened_ = true;
- }
- UpdateObservers();
-
- base::TimeDelta time_since_start = GetEndTime() - GetStartTime();
-
- // If all data is saved, the number of received bytes is resulting file size.
- int resulting_file_size = GetReceivedBytes();
-
- auto in_progress_entry = GetInProgressEntry(guid_, GetBrowserContext());
- if (in_progress_entry) {
- download::DownloadUkmHelper::RecordDownloadCompleted(
- in_progress_entry->ukm_download_id, resulting_file_size,
- time_since_start);
- }
-}
-
-// **** End of Download progression cascade
-
-void DownloadItemImpl::InterruptAndDiscardPartialState(
- download::DownloadInterruptReason reason) {
- InterruptWithPartialState(0, std::unique_ptr<crypto::SecureHash>(), reason);
-}
-
-void DownloadItemImpl::InterruptWithPartialState(
- int64_t bytes_so_far,
- std::unique_ptr<crypto::SecureHash> hash_state,
- download::DownloadInterruptReason reason) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DCHECK_NE(download::DOWNLOAD_INTERRUPT_REASON_NONE, reason);
- DVLOG(20) << __func__
- << "() reason:" << DownloadInterruptReasonToString(reason)
- << " bytes_so_far:" << bytes_so_far
- << " hash_state:" << (hash_state ? "Valid" : "Invalid")
- << " this=" << DebugString(true);
-
- // Somewhat counter-intuitively, it is possible for us to receive an
- // interrupt after we've already been interrupted. The generation of
- // interrupts from the file thread Renames and the generation of
- // interrupts from disk writes go through two different mechanisms (driven
- // by rename requests from UI thread and by write requests from IO thread,
- // respectively), and since we choose not to keep state on the File thread,
- // this is the place where the races collide. It's also possible for
- // interrupts to race with cancels.
- switch (state_) {
- case CANCELLED_INTERNAL:
- // If the download is already cancelled, then there's no point in
- // transitioning out to interrupted.
- case COMPLETING_INTERNAL:
- case COMPLETE_INTERNAL:
- // Already complete.
- return;
-
- case INITIAL_INTERNAL:
- case MAX_DOWNLOAD_INTERNAL_STATE:
- NOTREACHED();
- return;
-
- case TARGET_PENDING_INTERNAL:
- case INTERRUPTED_TARGET_PENDING_INTERNAL:
- // Postpone recognition of this error until after file name determination
- // has completed and the intermediate file has been renamed to simplify
- // resumption conditions. The target determination logic is much simpler
- // if the state of the download remains constant until that stage
- // completes.
- //
- // current_path_ may be empty because it is possible for
- // download::DownloadItem to receive a DestinationError prior to the
- // download file initialization complete callback.
- if (!IsCancellation(reason)) {
- UpdateProgress(bytes_so_far, 0);
- SetHashState(std::move(hash_state));
- deferred_interrupt_reason_ = reason;
- TransitionTo(INTERRUPTED_TARGET_PENDING_INTERNAL);
- return;
- }
- // else - Fallthrough for cancellation handling which is equivalent to the
- // IN_PROGRESS state.
- FALLTHROUGH;
-
- case IN_PROGRESS_INTERNAL:
- case TARGET_RESOLVED_INTERNAL:
- // last_reason_ needs to be set for GetResumeMode() to work.
- last_reason_ = reason;
-
- if (download_file_) {
- download::ResumeMode resume_mode = GetResumeMode();
- ReleaseDownloadFile(resume_mode !=
- download::ResumeMode::IMMEDIATE_CONTINUE &&
- resume_mode != download::ResumeMode::USER_CONTINUE);
- }
- break;
-
- case RESUMING_INTERNAL:
- case INTERRUPTED_INTERNAL:
- DCHECK(!download_file_);
- // The first non-cancel interrupt reason wins in cases where multiple
- // things go wrong.
- if (!IsCancellation(reason))
- return;
-
- last_reason_ = reason;
- if (!GetFullPath().empty()) {
- // There is no download file and this is transitioning from INTERRUPTED
- // to CANCELLED. The intermediate file is no longer usable, and should
- // be deleted.
- download::GetDownloadTaskRunner()->PostTask(
- FROM_HERE, base::BindOnce(base::IgnoreResult(&DeleteDownloadedFile),
- GetFullPath()));
- destination_info_.current_path.clear();
- }
- break;
- }
-
- // Reset all data saved, as even if we did save all the data we're going to go
- // through another round of downloading when we resume. There's a potential
- // problem here in the abstract, as if we did download all the data and then
- // run into a continuable error, on resumption we won't download any more
- // data. However, a) there are currently no continuable errors that can occur
- // after we download all the data, and b) if there were, that would probably
- // simply result in a null range request, which would generate a
- // DestinationCompleted() notification from the DownloadFile, which would
- // behave properly with setting all_data_saved_ to false here.
- destination_info_.all_data_saved = false;
-
- if (GetFullPath().empty()) {
- hash_state_.reset();
- destination_info_.hash.clear();
- destination_info_.received_bytes = 0;
- received_slices_.clear();
- } else {
- UpdateProgress(bytes_so_far, 0);
- SetHashState(std::move(hash_state));
- }
-
- if (job_)
- job_->Cancel(false);
-
- if (IsCancellation(reason)) {
- if (IsDangerous()) {
- download::RecordDangerousDownloadDiscard(
- reason == download::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED
- ? download::DOWNLOAD_DISCARD_DUE_TO_USER_ACTION
- : download::DOWNLOAD_DISCARD_DUE_TO_SHUTDOWN,
- GetDangerType(), GetTargetFilePath());
- }
-
- download::RecordDownloadCountWithSource(download::CANCELLED_COUNT,
- download_source_);
- if (job_ && job_->IsParallelizable()) {
- download::RecordParallelizableDownloadCount(download::CANCELLED_COUNT,
- IsParallelDownloadEnabled());
- }
- DCHECK_EQ(last_reason_, reason);
- TransitionTo(CANCELLED_INTERNAL);
- return;
- }
-
- download::RecordDownloadInterrupted(reason, GetReceivedBytes(), total_bytes_,
- job_ && job_->IsParallelizable(),
- IsParallelDownloadEnabled(),
- download_source_);
-
- base::TimeDelta time_since_start = base::Time::Now() - GetStartTime();
- int resulting_file_size = GetReceivedBytes();
- auto in_progress_entry = GetInProgressEntry(guid_, GetBrowserContext());
- base::Optional<int> change_in_file_size;
- if (in_progress_entry) {
- if (total_bytes_ >= 0) {
- change_in_file_size = total_bytes_ - resulting_file_size;
- }
-
- download::DownloadUkmHelper::RecordDownloadInterrupted(
- in_progress_entry->ukm_download_id, change_in_file_size, reason,
- resulting_file_size, time_since_start);
- }
- if (reason ==
- download::DOWNLOAD_INTERRUPT_REASON_SERVER_CONTENT_LENGTH_MISMATCH) {
- received_bytes_at_length_mismatch_ = GetReceivedBytes();
- }
-
- if (!GetWebContents())
- download::RecordDownloadCountWithSource(
- download::INTERRUPTED_WITHOUT_WEBCONTENTS, download_source_);
-
- // TODO(asanka): This is not good. We can transition to interrupted from
- // target-pending, which is something we don't want to do. Perhaps we should
- // explicitly transition to target-resolved prior to switching to interrupted.
- DCHECK_EQ(last_reason_, reason);
- TransitionTo(INTERRUPTED_INTERNAL);
- AutoResumeIfValid();
-}
-
-void DownloadItemImpl::UpdateProgress(
- int64_t bytes_so_far,
- int64_t bytes_per_sec) {
- destination_info_.received_bytes = bytes_so_far;
- bytes_per_sec_ = bytes_per_sec;
-
- // If we've received more data than we were expecting (bad server info?),
- // revert to 'unknown size mode'.
- if (bytes_so_far > total_bytes_)
- total_bytes_ = 0;
-}
-
-void DownloadItemImpl::SetHashState(
- std::unique_ptr<crypto::SecureHash> hash_state) {
- hash_state_ = std::move(hash_state);
- if (!hash_state_) {
- destination_info_.hash.clear();
- return;
- }
-
- std::unique_ptr<crypto::SecureHash> clone_of_hash_state(hash_state_->Clone());
- std::vector<char> hash_value(clone_of_hash_state->GetHashLength());
- clone_of_hash_state->Finish(&hash_value.front(), hash_value.size());
- destination_info_.hash.assign(hash_value.begin(), hash_value.end());
-}
-
-void DownloadItemImpl::ReleaseDownloadFile(bool destroy_file) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DVLOG(20) << __func__ << "() destroy_file:" << destroy_file;
-
- if (destroy_file) {
- download::GetDownloadTaskRunner()->PostTask(
- FROM_HERE,
- // Will be deleted at end of task execution.
- base::BindOnce(&DownloadFileCancel, std::move(download_file_)));
- // Avoid attempting to reuse the intermediate file by clearing out
- // current_path_ and received slices.
- destination_info_.current_path.clear();
- received_slices_.clear();
- } else {
- download::GetDownloadTaskRunner()->PostTask(
- FROM_HERE, base::BindOnce(base::IgnoreResult(&DownloadFileDetach),
- // Will be deleted at end of task execution.
- std::move(download_file_)));
- }
- // Don't accept any more messages from the DownloadFile, and null
- // out any previous "all data received". This also breaks links to
- // other entities we've given out weak pointers to.
- weak_ptr_factory_.InvalidateWeakPtrs();
-}
-
-bool DownloadItemImpl::IsDownloadReadyForCompletion(
- const base::Closure& state_change_notification) {
- // If the download hasn't progressed to the IN_PROGRESS state, then it's not
- // ready for completion.
- if (state_ != IN_PROGRESS_INTERNAL)
- return false;
-
- // If we don't have all the data, the download is not ready for
- // completion.
- if (!AllDataSaved())
- return false;
-
- // If the download is dangerous, but not yet validated, it's not ready for
- // completion.
- if (IsDangerous())
- return false;
-
- // Check for consistency before invoking delegate. Since there are no pending
- // target determination calls and the download is in progress, both the target
- // and current paths should be non-empty and they should point to the same
- // directory.
- DCHECK(!GetTargetFilePath().empty());
- DCHECK(!GetFullPath().empty());
- DCHECK(GetTargetFilePath().DirName() == GetFullPath().DirName());
-
- // Give the delegate a chance to hold up a stop sign. It'll call
- // use back through the passed callback if it does and that state changes.
- if (!delegate_->ShouldCompleteDownload(this, state_change_notification))
- return false;
-
- return true;
-}
-
-void DownloadItemImpl::TransitionTo(DownloadInternalState new_state) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- if (state_ == new_state)
- return;
-
- DownloadInternalState old_state = state_;
- state_ = new_state;
-
- DCHECK(IsSavePackageDownload()
- ? IsValidSavePackageStateTransition(old_state, new_state)
- : IsValidStateTransition(old_state, new_state))
- << "Invalid state transition from:" << DebugDownloadStateString(old_state)
- << " to:" << DebugDownloadStateString(new_state);
-
- switch (state_) {
- case INITIAL_INTERNAL:
- NOTREACHED();
- break;
-
- case TARGET_PENDING_INTERNAL:
- case TARGET_RESOLVED_INTERNAL:
- break;
-
- case INTERRUPTED_TARGET_PENDING_INTERNAL:
- DCHECK_NE(download::DOWNLOAD_INTERRUPT_REASON_NONE,
- deferred_interrupt_reason_)
- << "Interrupt reason must be set prior to transitioning into "
- "TARGET_PENDING";
- break;
-
- case IN_PROGRESS_INTERNAL:
- DCHECK(!GetFullPath().empty()) << "Current output path must be known.";
- DCHECK(!GetTargetFilePath().empty()) << "Target path must be known.";
- DCHECK(GetFullPath().DirName() == GetTargetFilePath().DirName())
- << "Current output directory must match target directory.";
- DCHECK(download_file_) << "Output file must be owned by download item.";
- DCHECK(job_) << "Must have active download job.";
- DCHECK(!job_->is_paused())
- << "At the time a download enters IN_PROGRESS state, "
- "it must not be paused.";
- break;
-
- case COMPLETING_INTERNAL:
- DCHECK(AllDataSaved()) << "All data must be saved prior to completion.";
- DCHECK(!download_file_)
- << "Download file must be released prior to completion.";
- DCHECK(!GetTargetFilePath().empty()) << "Target path must be known.";
- DCHECK(GetFullPath() == GetTargetFilePath())
- << "Current output path must match target path.";
-
- TRACE_EVENT_INSTANT2("download", "DownloadItemCompleting",
- TRACE_EVENT_SCOPE_THREAD, "bytes_so_far",
- GetReceivedBytes(), "final_hash",
- destination_info_.hash);
- break;
-
- case COMPLETE_INTERNAL:
- TRACE_EVENT_INSTANT1("download", "DownloadItemFinished",
- TRACE_EVENT_SCOPE_THREAD, "auto_opened",
- auto_opened_ ? "yes" : "no");
- break;
-
- case INTERRUPTED_INTERNAL:
- DCHECK(!download_file_)
- << "Download file must be released prior to interruption.";
- DCHECK_NE(last_reason_, download::DOWNLOAD_INTERRUPT_REASON_NONE);
- TRACE_EVENT_INSTANT2("download", "DownloadItemInterrupted",
- TRACE_EVENT_SCOPE_THREAD, "interrupt_reason",
- DownloadInterruptReasonToString(last_reason_),
- "bytes_so_far", GetReceivedBytes());
- break;
-
- case RESUMING_INTERNAL:
- TRACE_EVENT_INSTANT2("download", "DownloadItemResumed",
- TRACE_EVENT_SCOPE_THREAD, "interrupt_reason",
- DownloadInterruptReasonToString(last_reason_),
- "bytes_so_far", GetReceivedBytes());
- break;
-
- case CANCELLED_INTERNAL:
- TRACE_EVENT_INSTANT1("download", "DownloadItemCancelled",
- TRACE_EVENT_SCOPE_THREAD, "bytes_so_far",
- GetReceivedBytes());
- break;
-
- case MAX_DOWNLOAD_INTERNAL_STATE:
- NOTREACHED();
- break;
- }
-
- DVLOG(20) << __func__ << "() from:" << DebugDownloadStateString(old_state)
- << " to:" << DebugDownloadStateString(state_)
- << " this = " << DebugString(true);
- bool is_done =
- (state_ == COMPLETE_INTERNAL || state_ == INTERRUPTED_INTERNAL ||
- state_ == RESUMING_INTERNAL || state_ == CANCELLED_INTERNAL);
- bool was_done =
- (old_state == COMPLETE_INTERNAL || old_state == INTERRUPTED_INTERNAL ||
- old_state == RESUMING_INTERNAL || old_state == CANCELLED_INTERNAL);
-
- // Termination
- if (is_done && !was_done)
- TRACE_EVENT_ASYNC_END0("download", "DownloadItemActive", download_id_);
-
- // Resumption
- if (was_done && !is_done) {
- std::string file_name(GetTargetFilePath().BaseName().AsUTF8Unsafe());
- TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(
- "download", "DownloadItemActive", download_id_, "download_item",
- std::make_unique<DownloadItemActivatedData>(
- TYPE_ACTIVE_DOWNLOAD, GetId(), GetOriginalUrl().spec(),
- GetURL().spec(), file_name, GetDangerType(), GetReceivedBytes(),
- HasUserGesture()));
- }
-}
-
-void DownloadItemImpl::SetDangerType(download::DownloadDangerType danger_type) {
- if (danger_type != danger_type_) {
- TRACE_EVENT_INSTANT1("download", "DownloadItemSaftyStateUpdated",
- TRACE_EVENT_SCOPE_THREAD, "danger_type",
- GetDownloadDangerNames(danger_type).c_str());
- }
- // Only record the Malicious UMA stat if it's going from {not malicious} ->
- // {malicious}.
- if ((danger_type_ == download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS ||
- danger_type_ == download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE ||
- danger_type_ == download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT ||
- danger_type_ ==
- download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT) &&
- (danger_type == download::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST ||
- danger_type == download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL ||
- danger_type == download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT ||
- danger_type == download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED)) {
- download::RecordMaliciousDownloadClassified(danger_type);
- }
- danger_type_ = danger_type;
-}
-
-void DownloadItemImpl::SetFullPath(const base::FilePath& new_path) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DVLOG(20) << __func__ << "() new_path = \"" << new_path.value() << "\" "
- << DebugString(true);
- DCHECK(!new_path.empty());
-
- TRACE_EVENT_INSTANT2("download", "DownloadItemRenamed",
- TRACE_EVENT_SCOPE_THREAD, "old_filename",
- destination_info_.current_path.AsUTF8Unsafe(),
- "new_filename", new_path.AsUTF8Unsafe());
-
- destination_info_.current_path = new_path;
-}
-
-void DownloadItemImpl::AutoResumeIfValid() {
- DVLOG(20) << __func__ << "() " << DebugString(true);
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- download::ResumeMode mode = GetResumeMode();
-
- if (mode != download::ResumeMode::IMMEDIATE_RESTART &&
- mode != download::ResumeMode::IMMEDIATE_CONTINUE) {
- return;
- }
-
- auto_resume_count_++;
-
- ResumeInterruptedDownload(ResumptionRequestSource::AUTOMATIC);
-}
-
-void DownloadItemImpl::ResumeInterruptedDownload(
- ResumptionRequestSource source) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- // If we're not interrupted, ignore the request; our caller is drunk.
- if (state_ != INTERRUPTED_INTERNAL)
- return;
-
- // We are starting a new request. Shake off all pending operations.
- DCHECK(!download_file_);
- weak_ptr_factory_.InvalidateWeakPtrs();
-
- // Reset the appropriate state if restarting.
- download::ResumeMode mode = GetResumeMode();
- if (mode == download::ResumeMode::IMMEDIATE_RESTART ||
- mode == download::ResumeMode::USER_RESTART) {
- DCHECK(GetFullPath().empty());
- destination_info_.received_bytes = 0;
- last_modified_time_.clear();
- etag_.clear();
- destination_info_.hash.clear();
- hash_state_.reset();
- received_slices_.clear();
- }
-
- StoragePartition* storage_partition =
- BrowserContext::GetStoragePartitionForSite(GetBrowserContext(),
- request_info_.site_url);
-
- net::NetworkTrafficAnnotationTag traffic_annotation =
- net::DefineNetworkTrafficAnnotation("download_manager_resume", R"(
- semantics {
- sender: "Download Manager"
- description:
- "When user resumes downloading a file, a network request is made "
- "to fetch it."
- trigger:
- "User resumes a download."
- data: "None."
- destination: WEBSITE
- }
- policy {
- cookies_allowed: YES
- cookies_store: "user"
- setting:
- "This feature cannot be disabled in settings, but it is activated "
- "by direct user action."
- chrome_policy {
- DownloadRestrictions {
- DownloadRestrictions: 3
- }
- }
- })");
- // Avoid using the WebContents even if it's still around. Resumption requests
- // are consistently routed through the no-renderer code paths so that the
- // request will not be dropped if the WebContents (and by extension, the
- // associated renderer) goes away before a response is received.
- std::unique_ptr<download::DownloadUrlParameters> download_params(
- new download::DownloadUrlParameters(
- GetURL(), storage_partition->GetURLRequestContext(),
- traffic_annotation));
- download_params->set_file_path(GetFullPath());
- if (received_slices_.size() > 0) {
- std::vector<download::DownloadItem::ReceivedSlice> slices_to_download =
- FindSlicesToDownload(received_slices_);
- download_params->set_offset(slices_to_download[0].offset);
- } else {
- download_params->set_offset(GetReceivedBytes());
- }
- download_params->set_last_modified(GetLastModifiedTime());
- download_params->set_etag(GetETag());
- download_params->set_hash_of_partial_file(GetHash());
- download_params->set_hash_state(std::move(hash_state_));
- download_params->set_fetch_error_body(fetch_error_body_);
-
- auto entry = GetInProgressEntry(GetGuid(), GetBrowserContext());
- if (entry)
- download_params->set_request_origin(entry.value().request_origin);
-
- // Note that resumed downloads disallow redirects. Hence the referrer URL
- // (which is the contents of the Referer header for the last download request)
- // will only be sent to the URL returned by GetURL().
- download_params->set_referrer(GetReferrerUrl());
- download_params->set_referrer_policy(net::URLRequest::NEVER_CLEAR_REFERRER);
-
- TransitionTo(RESUMING_INTERNAL);
- download::RecordDownloadCountWithSource(
- source == ResumptionRequestSource::USER
- ? download::MANUAL_RESUMPTION_COUNT
- : download::AUTO_RESUMPTION_COUNT,
- download_source_);
-
- base::TimeDelta time_since_start = base::Time::Now() - GetStartTime();
- auto in_progress_entry = GetInProgressEntry(guid_, GetBrowserContext());
- if (in_progress_entry) {
- download::DownloadUkmHelper::RecordDownloadResumed(
- in_progress_entry->ukm_download_id, GetResumeMode(), time_since_start);
- }
-
- delegate_->ResumeInterruptedDownload(std::move(download_params), GetId());
-
- if (job_)
- job_->Resume(false);
-}
-
-// static
-download::DownloadItem::DownloadState DownloadItemImpl::InternalToExternalState(
- DownloadInternalState internal_state) {
- switch (internal_state) {
- case INITIAL_INTERNAL:
- case TARGET_PENDING_INTERNAL:
- case TARGET_RESOLVED_INTERNAL:
- case INTERRUPTED_TARGET_PENDING_INTERNAL:
- // TODO(asanka): Introduce an externally visible state to distinguish
- // between the above states and IN_PROGRESS_INTERNAL. The latter (the
- // state where the download is active and has a known target) is the state
- // that most external users are interested in.
- case IN_PROGRESS_INTERNAL:
- return IN_PROGRESS;
- case COMPLETING_INTERNAL:
- return IN_PROGRESS;
- case COMPLETE_INTERNAL:
- return COMPLETE;
- case CANCELLED_INTERNAL:
- return CANCELLED;
- case INTERRUPTED_INTERNAL:
- return INTERRUPTED;
- case RESUMING_INTERNAL:
- return IN_PROGRESS;
- case MAX_DOWNLOAD_INTERNAL_STATE:
- break;
- }
- NOTREACHED();
- return MAX_DOWNLOAD_STATE;
-}
-
-// static
-DownloadItemImpl::DownloadInternalState
-DownloadItemImpl::ExternalToInternalState(
- DownloadState external_state) {
- switch (external_state) {
- case IN_PROGRESS:
- return IN_PROGRESS_INTERNAL;
- case COMPLETE:
- return COMPLETE_INTERNAL;
- case CANCELLED:
- return CANCELLED_INTERNAL;
- case INTERRUPTED:
- return INTERRUPTED_INTERNAL;
- default:
- NOTREACHED();
- }
- return MAX_DOWNLOAD_INTERNAL_STATE;
-}
-
-// static
-bool DownloadItemImpl::IsValidSavePackageStateTransition(
- DownloadInternalState from,
- DownloadInternalState to) {
-#if DCHECK_IS_ON()
- switch (from) {
- case INITIAL_INTERNAL:
- case TARGET_PENDING_INTERNAL:
- case INTERRUPTED_TARGET_PENDING_INTERNAL:
- case TARGET_RESOLVED_INTERNAL:
- case COMPLETING_INTERNAL:
- case COMPLETE_INTERNAL:
- case INTERRUPTED_INTERNAL:
- case RESUMING_INTERNAL:
- case CANCELLED_INTERNAL:
- return false;
-
- case IN_PROGRESS_INTERNAL:
- return to == CANCELLED_INTERNAL || to == COMPLETE_INTERNAL;
-
- case MAX_DOWNLOAD_INTERNAL_STATE:
- NOTREACHED();
- }
- return false;
-#else
- return true;
-#endif
-}
-
-// static
-bool DownloadItemImpl::IsValidStateTransition(DownloadInternalState from,
- DownloadInternalState to) {
-#if DCHECK_IS_ON()
- switch (from) {
- case INITIAL_INTERNAL:
- return to == TARGET_PENDING_INTERNAL ||
- to == INTERRUPTED_TARGET_PENDING_INTERNAL;
-
- case TARGET_PENDING_INTERNAL:
- return to == INTERRUPTED_TARGET_PENDING_INTERNAL ||
- to == TARGET_RESOLVED_INTERNAL || to == CANCELLED_INTERNAL;
-
- case INTERRUPTED_TARGET_PENDING_INTERNAL:
- return to == TARGET_RESOLVED_INTERNAL || to == CANCELLED_INTERNAL;
-
- case TARGET_RESOLVED_INTERNAL:
- return to == IN_PROGRESS_INTERNAL || to == INTERRUPTED_INTERNAL ||
- to == CANCELLED_INTERNAL;
-
- case IN_PROGRESS_INTERNAL:
- return to == COMPLETING_INTERNAL || to == CANCELLED_INTERNAL ||
- to == INTERRUPTED_INTERNAL;
-
- case COMPLETING_INTERNAL:
- return to == COMPLETE_INTERNAL;
-
- case COMPLETE_INTERNAL:
- return false;
-
- case INTERRUPTED_INTERNAL:
- return to == RESUMING_INTERNAL || to == CANCELLED_INTERNAL;
-
- case RESUMING_INTERNAL:
- return to == TARGET_PENDING_INTERNAL ||
- to == INTERRUPTED_TARGET_PENDING_INTERNAL ||
- to == TARGET_RESOLVED_INTERNAL || to == CANCELLED_INTERNAL;
-
- case CANCELLED_INTERNAL:
- return false;
-
- case MAX_DOWNLOAD_INTERNAL_STATE:
- NOTREACHED();
- }
- return false;
-#else
- return true;
-#endif // DCHECK_IS_ON()
-}
-
-const char* DownloadItemImpl::DebugDownloadStateString(
- DownloadInternalState state) {
- switch (state) {
- case INITIAL_INTERNAL:
- return "INITIAL";
- case TARGET_PENDING_INTERNAL:
- return "TARGET_PENDING";
- case INTERRUPTED_TARGET_PENDING_INTERNAL:
- return "INTERRUPTED_TARGET_PENDING";
- case TARGET_RESOLVED_INTERNAL:
- return "TARGET_RESOLVED";
- case IN_PROGRESS_INTERNAL:
- return "IN_PROGRESS";
- case COMPLETING_INTERNAL:
- return "COMPLETING";
- case COMPLETE_INTERNAL:
- return "COMPLETE";
- case CANCELLED_INTERNAL:
- return "CANCELLED";
- case INTERRUPTED_INTERNAL:
- return "INTERRUPTED";
- case RESUMING_INTERNAL:
- return "RESUMING";
- case MAX_DOWNLOAD_INTERNAL_STATE:
- break;
- }
- NOTREACHED() << "Unknown download state " << state;
- return "unknown";
-}
-
-const char* DownloadItemImpl::DebugResumeModeString(download::ResumeMode mode) {
- switch (mode) {
- case download::ResumeMode::INVALID:
- return "INVALID";
- case download::ResumeMode::IMMEDIATE_CONTINUE:
- return "IMMEDIATE_CONTINUE";
- case download::ResumeMode::IMMEDIATE_RESTART:
- return "IMMEDIATE_RESTART";
- case download::ResumeMode::USER_CONTINUE:
- return "USER_CONTINUE";
- case download::ResumeMode::USER_RESTART:
- return "USER_RESTART";
- }
- NOTREACHED() << "Unknown resume mode " << static_cast<int>(mode);
- return "unknown";
-}
-
-} // namespace content
diff --git a/chromium/content/browser/download/download_item_impl.h b/chromium/content/browser/download/download_item_impl.h
deleted file mode 100644
index 002727cd43f..00000000000
--- a/chromium/content/browser/download/download_item_impl.h
+++ /dev/null
@@ -1,772 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_ITEM_IMPL_H_
-#define CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_ITEM_IMPL_H_
-
-#include <stdint.h>
-
-#include <memory>
-#include <string>
-#include <vector>
-
-#include "base/callback_forward.h"
-#include "base/files/file_path.h"
-#include "base/macros.h"
-#include "base/memory/weak_ptr.h"
-#include "base/observer_list.h"
-#include "base/time/time.h"
-#include "components/download/public/common/download_create_info.h"
-#include "components/download/public/common/download_interrupt_reasons.h"
-#include "components/download/public/common/download_item.h"
-#include "components/download/public/common/download_request_handle_interface.h"
-#include "components/download/public/common/resume_mode.h"
-#include "content/browser/download/download_destination_observer.h"
-#include "content/common/content_export.h"
-#include "url/gurl.h"
-
-namespace content {
-class BrowserContext;
-class DownloadFile;
-class DownloadItemImplDelegate;
-class DownloadJob;
-class WebContents;
-
-// See download_item.h for usage.
-class CONTENT_EXPORT DownloadItemImpl : public download::DownloadItem,
- public DownloadDestinationObserver {
- public:
- // Information about the initial request that triggers the download. Most of
- // the fields are immutable after the download::DownloadItem is successfully
- // created. However, it is possible that the url chain is changed when
- // resuming an interrupted download. In that case, the download will restart
- // from the beginning.
- struct CONTENT_EXPORT RequestInfo {
- RequestInfo(const std::vector<GURL>& url_chain,
- const GURL& referrer_url,
- const GURL& site_url,
- const GURL& tab_url,
- const GURL& tab_referrer_url,
- const std::string& suggested_filename,
- const base::FilePath& forced_file_path,
- ui::PageTransition transition_type,
- bool has_user_gesture,
- const std::string& remote_address,
- base::Time start_time);
- RequestInfo();
- explicit RequestInfo(const RequestInfo& other);
- explicit RequestInfo(const GURL& url);
- ~RequestInfo();
-
- // The chain of redirects that leading up to and including the final URL.
- std::vector<GURL> url_chain;
-
- // The URL of the page that initiated the download.
- GURL referrer_url;
-
- // Site URL for the site instance that initiated this download.
- GURL site_url;
-
- // The URL of the tab that initiated the download.
- GURL tab_url;
-
- // The URL of the referrer of the tab that initiated the download.
- GURL tab_referrer_url;
-
- // Filename suggestion from DownloadSaveInfo. It could, among others, be the
- // suggested filename in 'download' attribute of an anchor. Details:
- // http://www.whatwg.org/specs/web-apps/current-work/#downloading-hyperlinks
- std::string suggested_filename;
-
- // If non-empty, contains an externally supplied path that should be used as
- // the target path.
- base::FilePath forced_file_path;
-
- // Page transition that triggerred the download.
- ui::PageTransition transition_type = ui::PAGE_TRANSITION_LINK;
-
- // Whether the download was triggered with a user gesture.
- bool has_user_gesture = false;
-
- // The remote IP address where the download was fetched from.
- std::string remote_address;
-
- // Time the download was started.
- base::Time start_time;
- };
-
- // Information about the current state of the download destination.
- struct CONTENT_EXPORT DestinationInfo {
- DestinationInfo(const base::FilePath& target_path,
- const base::FilePath& current_path,
- int64_t received_bytes,
- bool all_data_saved,
- const std::string& hash,
- base::Time end_time);
- DestinationInfo();
- explicit DestinationInfo(TargetDisposition target_disposition);
- explicit DestinationInfo(const DestinationInfo& other);
- ~DestinationInfo();
-
- // Whether the target should be overwritten, uniquified or prompted for.
- TargetDisposition target_disposition = TARGET_DISPOSITION_OVERWRITE;
-
- // Target path of an in-progress download. We may be downloading to a
- // temporary or intermediate file (specified by |current_path|). Once the
- // download completes, we will rename the file to |target_path|.
- base::FilePath target_path;
-
- // Full path to the downloaded or downloading file. This is the path to the
- // physical file, if one exists. The final target path is specified by
- // |target_path|. |current_path| can be empty if the in-progress path
- // hasn't been determined.
- base::FilePath current_path;
-
- // Current received bytes.
- int64_t received_bytes = 0;
-
- // True if we've saved all the data for the download. If true, then the file
- // at |current_path| contains |received_bytes|, which constitute the
- // entirety of what we expect to save there. A digest of its contents can be
- // found at |hash|.
- bool all_data_saved = false;
-
- // SHA256 hash of the possibly partial content. The hash is updated each
- // time the download is interrupted, and when the all the data has been
- // transferred. |hash| contains the raw binary hash and is not hex encoded.
- //
- // While the download is in progress, and while resuming, |hash| will be
- // empty.
- std::string hash;
-
- // Time last update was written to target file.
- base::Time end_time;
- };
-
- // The maximum number of attempts we will make to resume automatically.
- static const int kMaxAutoResumeAttempts;
-
- // Note that it is the responsibility of the caller to ensure that a
- // DownloadItemImplDelegate passed to a DownloadItemImpl constructor
- // outlives the DownloadItemImpl.
-
- // Constructing from persistent store:
- // |net_log| is constructed externally for our use.
- DownloadItemImpl(DownloadItemImplDelegate* delegate,
- const std::string& guid,
- uint32_t id,
- const base::FilePath& current_path,
- const base::FilePath& target_path,
- const std::vector<GURL>& url_chain,
- const GURL& referrer_url,
- const GURL& site_url,
- const GURL& tab_url,
- const GURL& tab_referrer_url,
- const std::string& mime_type,
- const std::string& original_mime_type,
- base::Time start_time,
- base::Time end_time,
- const std::string& etag,
- const std::string& last_modified,
- int64_t received_bytes,
- int64_t total_bytes,
- const std::string& hash,
- download::DownloadItem::DownloadState state,
- download::DownloadDangerType danger_type,
- download::DownloadInterruptReason interrupt_reason,
- bool opened,
- base::Time last_access_time,
- bool transient,
- const std::vector<download::DownloadItem::ReceivedSlice>&
- received_slices);
-
- // Constructing for a regular download.
- // |net_log| is constructed externally for our use.
- DownloadItemImpl(DownloadItemImplDelegate* delegate,
- uint32_t id,
- const download::DownloadCreateInfo& info);
-
- // Constructing for the "Save Page As..." feature:
- // |net_log| is constructed externally for our use.
- DownloadItemImpl(
- DownloadItemImplDelegate* delegate,
- uint32_t id,
- const base::FilePath& path,
- const GURL& url,
- const std::string& mime_type,
- std::unique_ptr<download::DownloadRequestHandleInterface> request_handle);
-
- ~DownloadItemImpl() override;
-
- // download::DownloadItem
- void AddObserver(download::DownloadItem::Observer* observer) override;
- void RemoveObserver(download::DownloadItem::Observer* observer) override;
- void UpdateObservers() override;
- void ValidateDangerousDownload() override;
- void StealDangerousDownload(bool need_removal,
- const AcquireFileCallback& callback) override;
- void Pause() override;
- void Resume() override;
- void Cancel(bool user_cancel) override;
- void Remove() override;
- void OpenDownload() override;
- void ShowDownloadInShell() override;
- uint32_t GetId() const override;
- const std::string& GetGuid() const override;
- DownloadState GetState() const override;
- download::DownloadInterruptReason GetLastReason() const override;
- bool IsPaused() const override;
- bool IsTemporary() const override;
- bool CanResume() const override;
- bool IsDone() const override;
- const GURL& GetURL() const override;
- const std::vector<GURL>& GetUrlChain() const override;
- const GURL& GetOriginalUrl() const override;
- const GURL& GetReferrerUrl() const override;
- const GURL& GetSiteUrl() const override;
- const GURL& GetTabUrl() const override;
- const GURL& GetTabReferrerUrl() const override;
- std::string GetSuggestedFilename() const override;
- const scoped_refptr<const net::HttpResponseHeaders>& GetResponseHeaders()
- const override;
- std::string GetContentDisposition() const override;
- std::string GetMimeType() const override;
- std::string GetOriginalMimeType() const override;
- std::string GetRemoteAddress() const override;
- bool HasUserGesture() const override;
- ui::PageTransition GetTransitionType() const override;
- const std::string& GetLastModifiedTime() const override;
- const std::string& GetETag() const override;
- bool IsSavePackageDownload() const override;
- const base::FilePath& GetFullPath() const override;
- const base::FilePath& GetTargetFilePath() const override;
- const base::FilePath& GetForcedFilePath() const override;
- base::FilePath GetFileNameToReportUser() const override;
- TargetDisposition GetTargetDisposition() const override;
- const std::string& GetHash() const override;
- bool GetFileExternallyRemoved() const override;
- void DeleteFile(const base::Callback<void(bool)>& callback) override;
- bool IsDangerous() const override;
- download::DownloadDangerType GetDangerType() const override;
- bool TimeRemaining(base::TimeDelta* remaining) const override;
- int64_t CurrentSpeed() const override;
- int PercentComplete() const override;
- bool AllDataSaved() const override;
- int64_t GetTotalBytes() const override;
- int64_t GetReceivedBytes() const override;
- const std::vector<download::DownloadItem::ReceivedSlice>& GetReceivedSlices()
- const override;
- base::Time GetStartTime() const override;
- base::Time GetEndTime() const override;
- bool CanShowInFolder() override;
- bool CanOpenDownload() override;
- bool ShouldOpenFileBasedOnExtension() override;
- bool GetOpenWhenComplete() const override;
- bool GetAutoOpened() override;
- bool GetOpened() const override;
- base::Time GetLastAccessTime() const override;
- bool IsTransient() const override;
- void OnContentCheckCompleted(
- download::DownloadDangerType danger_type,
- download::DownloadInterruptReason reason) override;
- void SetOpenWhenComplete(bool open) override;
- void SetOpened(bool opened) override;
- void SetLastAccessTime(base::Time last_access_time) override;
- void SetDisplayName(const base::FilePath& name) override;
- std::string DebugString(bool verbose) const override;
- void SimulateErrorForTesting(
- download::DownloadInterruptReason reason) override;
-
- // All remaining public interfaces virtual to allow for DownloadItemImpl
- // mocks.
-
- // State transition operations on regular downloads --------------------------
-
- // Start the download.
- // |download_file| is the associated file on the storage medium.
- // |req_handle| is the new request handle associated with the download.
- // |new_create_info| is a DownloadCreateInfo containing the new response
- // parameters. It may be different from the DownloadCreateInfo used to create
- // the download::DownloadItem if Start() is being called in response for a
- // download resumption request.
- virtual void Start(
- std::unique_ptr<DownloadFile> download_file,
- std::unique_ptr<download::DownloadRequestHandleInterface> req_handle,
- const download::DownloadCreateInfo& new_create_info);
-
- // Needed because of intertwining with DownloadManagerImpl -------------------
-
- // TODO(rdsmith): Unwind DownloadManagerImpl and DownloadItemImpl,
- // removing these from the public interface.
-
- virtual void OnDownloadedFileRemoved();
-
- // Provide a weak pointer reference to a DownloadDestinationObserver
- // for use by download destinations.
- virtual base::WeakPtr<DownloadDestinationObserver>
- DestinationObserverAsWeakPtr();
-
- // DownloadItemImpl routines only needed by SavePackage ----------------------
-
- // Called by SavePackage to set the total number of bytes on the item.
- virtual void SetTotalBytes(int64_t total_bytes);
-
- virtual void OnAllDataSaved(int64_t total_bytes,
- std::unique_ptr<crypto::SecureHash> hash_state);
-
- // Called by SavePackage to display progress when the download::DownloadItem
- // should be considered complete.
- virtual void MarkAsComplete();
-
- download::DownloadSource download_source() const { return download_source_; }
-
- // DownloadDestinationObserver
- void DestinationUpdate(
- int64_t bytes_so_far,
- int64_t bytes_per_sec,
- const std::vector<download::DownloadItem::ReceivedSlice>& received_slices)
- override;
- void DestinationError(
- download::DownloadInterruptReason reason,
- int64_t bytes_so_far,
- std::unique_ptr<crypto::SecureHash> hash_state) override;
- void DestinationCompleted(
- int64_t total_bytes,
- std::unique_ptr<crypto::SecureHash> hash_state) override;
-
- private:
- friend class DownloadJob;
-
- // Fine grained states of a download.
- //
- // New downloads can be created in the following states:
- //
- // INITIAL_INTERNAL: All active new downloads.
- //
- // COMPLETE_INTERNAL: Downloads restored from persisted state.
- // CANCELLED_INTERNAL: - do -
- // INTERRUPTED_INTERNAL: - do -
- //
- // IN_PROGRESS_INTERNAL: SavePackage downloads.
- //
- // On debug builds, state transitions can be verified via
- // IsValidStateTransition() and IsValidSavePackageStateTransition(). Allowed
- // state transitions are described below, both for normal downloads and
- // SavePackage downloads.
- enum DownloadInternalState {
- // Initial state. Regular downloads are created in this state until the
- // Start() call is received.
- //
- // Transitions to (regular):
- // TARGET_PENDING_INTERNAL: After a successful Start() call.
- // INTERRUPTED_TARGET_PENDING_INTERNAL: After a failed Start() call.
- //
- // Transitions to (SavePackage):
- // <n/a> SavePackage downloads never reach this state.
- INITIAL_INTERNAL,
-
- // Embedder is in the process of determining the target of the download.
- // Since the embedder is sensitive to state transitions during this time,
- // any DestinationError/DestinationCompleted events are deferred until
- // TARGET_RESOLVED_INTERNAL.
- //
- // Transitions to (regular):
- // TARGET_RESOLVED_INTERNAL: Once the embedder invokes the callback.
- // INTERRUPTED_TARGET_PENDING_INTERNAL: An error occurred prior to target
- // determination.
- // CANCELLED_INTERNAL: Cancelled.
- //
- // Transitions to (SavePackage):
- // <n/a> SavePackage downloads never reach this state.
- TARGET_PENDING_INTERNAL,
-
- // Embedder is in the process of determining the target of the download, and
- // the download is in an interrupted state. The interrupted state is not
- // exposed to the emedder until target determination is complete.
- //
- // Transitions to (regular):
- // INTERRUPTED_INTERNAL: Once the target is determined, the download
- // is marked as interrupted.
- // CANCELLED_INTERNAL: Cancelled.
- //
- // Transitions to (SavePackage):
- // <n/a> SavePackage downloads never reach this state.
- INTERRUPTED_TARGET_PENDING_INTERNAL,
-
- // Embedder has completed target determination. It is now safe to resolve
- // the download target as well as process deferred DestinationError events.
- // This state is differs from TARGET_PENDING_INTERNAL due to it being
- // allowed to transition to INTERRUPTED_INTERNAL, and it's different from
- // IN_PROGRESS_INTERNAL in that entering this state doesn't require having
- // a valid target. This state is transient (i.e. DownloadItemImpl will
- // transition out of it before yielding execution). It's only purpose in
- // life is to ensure the integrity of state transitions.
- //
- // Transitions to (regular):
- // IN_PROGRESS_INTERNAL: Target successfully determined. The incoming
- // data stream can now be written to the target.
- // INTERRUPTED_INTERNAL: Either the target determination or one of the
- // deferred signals indicated that the download
- // should be interrupted.
- // CANCELLED_INTERNAL: User cancelled the download or there was a
- // deferred Cancel() call.
- //
- // Transitions to (SavePackage):
- // <n/a> SavePackage downloads never reach this state.
- TARGET_RESOLVED_INTERNAL,
-
- // Download target is known and the data can be transferred from our source
- // to our sink.
- //
- // Transitions to (regular):
- // COMPLETING_INTERNAL: On final rename completion.
- // CANCELLED_INTERNAL: On cancel.
- // INTERRUPTED_INTERNAL: On interrupt.
- //
- // Transitions to (SavePackage):
- // COMPLETE_INTERNAL: On completion.
- // CANCELLED_INTERNAL: On cancel.
- IN_PROGRESS_INTERNAL,
-
- // Between commit point (dispatch of download file release) and completed.
- // Embedder may be opening the file in this state.
- //
- // Transitions to (regular):
- // COMPLETE_INTERNAL: On successful completion.
- //
- // Transitions to (SavePackage):
- // <n/a> SavePackage downloads never reach this state.
- COMPLETING_INTERNAL,
-
- // After embedder has had a chance to auto-open. User may now open
- // or auto-open based on extension.
- //
- // Transitions to (regular):
- // <none> Terminal state.
- //
- // Transitions to (SavePackage):
- // <none> Terminal state.
- COMPLETE_INTERNAL,
-
- // An error has interrupted the download.
- //
- // Transitions to (regular):
- // RESUMING_INTERNAL: On resumption.
- // CANCELLED_INTERNAL: On cancel.
- //
- // Transitions to (SavePackage):
- // <n/a> SavePackage downloads never reach this state.
- INTERRUPTED_INTERNAL,
-
- // A request to resume this interrupted download is in progress.
- //
- // Transitions to (regular):
- // TARGET_PENDING_INTERNAL: Once a server response is received from a
- // resumption.
- // INTERRUPTED_TARGET_PENDING_INTERNAL: A server response was received,
- // but it indicated an error, and the download
- // needs to go through target determination.
- // TARGET_RESOLVED_INTERNAL: A resumption attempt received an error
- // but it was not necessary to go through target
- // determination.
- // CANCELLED_INTERNAL: On cancel.
- //
- // Transitions to (SavePackage):
- // <n/a> SavePackage downloads never reach this state.
- RESUMING_INTERNAL,
-
- // User has cancelled the download.
- // TODO(asanka): Merge interrupted and cancelled states.
- //
- // Transitions to (regular):
- // <none> Terminal state.
- //
- // Transitions to (SavePackage):
- // <none> Terminal state.
- CANCELLED_INTERNAL,
-
- MAX_DOWNLOAD_INTERNAL_STATE,
- };
-
- // Normal progression of a download ------------------------------------------
-
- // These are listed in approximately chronological order. There are also
- // public methods involved in normal download progression; see
- // the implementation ordering in download_item_impl.cc.
-
- // Construction common to all constructors. |active| should be true for new
- // downloads and false for downloads from the history.
- // |download_type| indicates to the trace event what kind of download this is.
- void Init(bool active, download::DownloadItem::DownloadType download_type);
-
- // Callback from file thread when we initialize the DownloadFile.
- void OnDownloadFileInitialized(download::DownloadInterruptReason result);
-
- // Called to determine the target path. Will cause OnDownloadTargetDetermined
- // to be called when the target information is available.
- void DetermineDownloadTarget();
-
- // Called when the target path has been determined. |target_path| is the
- // suggested target path. |disposition| indicates how the target path should
- // be used (see TargetDisposition). |danger_type| is the danger level of
- // |target_path| as determined by the caller. |intermediate_path| is the path
- // to use to store the download until OnDownloadCompleting() is called.
- virtual void OnDownloadTargetDetermined(
- const base::FilePath& target_path,
- TargetDisposition disposition,
- download::DownloadDangerType danger_type,
- const base::FilePath& intermediate_path,
- download::DownloadInterruptReason interrupt_reason);
-
- void OnDownloadRenamedToIntermediateName(
- download::DownloadInterruptReason reason,
- const base::FilePath& full_path);
-
- void OnTargetResolved();
-
- // If all pre-requisites have been met, complete download processing, i.e. do
- // internal cleanup, file rename, and potentially auto-open. (Dangerous
- // downloads still may block on user acceptance after this point.)
- void MaybeCompleteDownload();
-
- // Called when the download is ready to complete.
- // This may perform final rename if necessary and will eventually call
- // download::DownloadItem::Completed().
- void OnDownloadCompleting();
-
- void OnDownloadRenamedToFinalName(download::DownloadInterruptReason reason,
- const base::FilePath& full_path);
-
- // Called if the embedder took over opening a download, to indicate that
- // the download has been opened.
- void DelayedDownloadOpened(bool auto_opened);
-
- // Called when the entire download operation (including renaming etc.)
- // is completed.
- void Completed();
-
- // Helper routines -----------------------------------------------------------
-
- // Indicate that an error has occurred on the download. Discards partial
- // state. The interrupted download will not be considered continuable, but may
- // be restarted.
- void InterruptAndDiscardPartialState(
- download::DownloadInterruptReason reason);
-
- // Indiates that an error has occurred on the download. The |bytes_so_far| and
- // |hash_state| should correspond to the state of the DownloadFile. If the
- // interrupt reason allows, this partial state may be allowed to continue the
- // interrupted download upon resumption.
- void InterruptWithPartialState(int64_t bytes_so_far,
- std::unique_ptr<crypto::SecureHash> hash_state,
- download::DownloadInterruptReason reason);
-
- void UpdateProgress(int64_t bytes_so_far, int64_t bytes_per_sec);
-
- // Set |hash_| and |hash_state_| based on |hash_state|.
- void SetHashState(std::unique_ptr<crypto::SecureHash> hash_state);
-
- // Destroy the DownloadFile object. If |destroy_file| is true, the file is
- // destroyed with it. Otherwise, DownloadFile::Detach() is called before
- // object destruction to prevent file destruction. Destroying the file also
- // resets |current_path_|.
- void ReleaseDownloadFile(bool destroy_file);
-
- // Check if a download is ready for completion. The callback provided
- // may be called at some point in the future if an external entity
- // state has change s.t. this routine should be checked again.
- bool IsDownloadReadyForCompletion(const base::Closure& state_change_notify);
-
- // Call to transition state; all state transitions should go through this.
- // |notify_action| specifies whether or not to call UpdateObservers() after
- // the state transition.
- void TransitionTo(DownloadInternalState new_state);
-
- // Set the |danger_type_| and invoke observers if necessary.
- void SetDangerType(download::DownloadDangerType danger_type);
-
- void SetFullPath(const base::FilePath& new_path);
-
- void AutoResumeIfValid();
-
- enum class ResumptionRequestSource { AUTOMATIC, USER };
- void ResumeInterruptedDownload(ResumptionRequestSource source);
-
- // Update origin information based on the response to a download resumption
- // request. Should only be called if the resumption request was successful.
- virtual void UpdateValidatorsOnResumption(
- const download::DownloadCreateInfo& new_create_info);
-
- // Notify observers that this item is being removed by the user.
- void NotifyRemoved();
-
- // Determines the resume mode for an interrupted download. Requires
- // last_reason_ to be set, but doesn't require the download to be in
- // INTERRUPTED state.
- download::ResumeMode GetResumeMode() const;
-
- // Helper method to get WebContents and BrowserContext of the DownloadItem.
- WebContents* GetWebContents() const;
- BrowserContext* GetBrowserContext() const;
-
- static DownloadState InternalToExternalState(
- DownloadInternalState internal_state);
- static DownloadInternalState ExternalToInternalState(
- DownloadState external_state);
-
- // Debugging routines --------------------------------------------------------
- static const char* DebugDownloadStateString(DownloadInternalState state);
- static const char* DebugResumeModeString(download::ResumeMode mode);
- static bool IsValidSavePackageStateTransition(DownloadInternalState from,
- DownloadInternalState to);
- static bool IsValidStateTransition(DownloadInternalState from,
- DownloadInternalState to);
-
- RequestInfo request_info_;
-
- // GUID to identify the download, generated by |base::GenerateGUID| in
- // download item, or provided by |download::DownloadUrlParameters|.
- // The format should follow UUID version 4 in RFC 4122.
- // The string representation is case sensitive. Legacy download GUID hex
- // digits may be upper case ASCII characters, and new GUID will be in lower
- // case.
- std::string guid_;
-
- uint32_t download_id_ = kInvalidId;
-
- // Display name for the download. If this is empty, then the display name is
- // considered to be |GetTargetFilePath().BaseName()|.
- base::FilePath display_name_;
-
- // Information from the response.
-
- // The HTTP response headers. This contains a nullptr when the response has
- // not yet been received. Only for consuming headers.
- scoped_refptr<const net::HttpResponseHeaders> response_headers_;
-
- // Content-disposition field from the header.
- std::string content_disposition_;
-
- // Mime-type from the header. Subject to change.
- std::string mime_type_;
-
- // The value of the content type header sent with the downloaded item. It
- // may be different from |mime_type_|, which may be set based on heuristics
- // which may look at the file extension and first few bytes of the file.
- std::string original_mime_type_;
-
- // Total bytes expected.
- int64_t total_bytes_ = 0;
-
- // Last reason.
- download::DownloadInterruptReason last_reason_ =
- download::DOWNLOAD_INTERRUPT_REASON_NONE;
-
- // Start time for recording statistics.
- base::TimeTicks start_tick_;
-
- // The current state of this download.
- DownloadInternalState state_ = INITIAL_INTERNAL;
-
- // Current danger type for the download.
- download::DownloadDangerType danger_type_ =
- download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS;
-
- // The views of this item in the download shelf and download contents.
- base::ObserverList<Observer> observers_;
-
- // Our delegate.
- DownloadItemImplDelegate* delegate_ = nullptr;
-
- // A flag for indicating if the download should be opened at completion.
- bool open_when_complete_ = false;
-
- // A flag for indicating if the downloaded file is externally removed.
- bool file_externally_removed_ = false;
-
- // True if the download was auto-opened. We set this rather than using
- // an observer as it's frequently possible for the download to be auto opened
- // before the observer is added.
- bool auto_opened_ = false;
-
- // True if the item was downloaded temporarily.
- bool is_temporary_ = false;
-
- // Did the user open the item either directly or indirectly (such as by
- // setting always open files of this type)? The shelf also sets this field
- // when the user closes the shelf before the item has been opened but should
- // be treated as though the user opened it.
- bool opened_ = false;
-
- // Time when the download was last accessed.
- base::Time last_access_time_;
-
- // Whether the download item should be transient and not shown in the UI.
- bool transient_ = false;
-
- // Did the delegate delay calling Complete on this download?
- bool delegate_delayed_complete_ = false;
-
- // Error return from DestinationError or received at Start(). Stored
- // separately from last_reason_ so that we can avoid handling destination
- // errors until after file name determination has occurred.
- download::DownloadInterruptReason deferred_interrupt_reason_ =
- download::DOWNLOAD_INTERRUPT_REASON_NONE;
-
- // The following fields describe the current state of the download file.
-
- // DownloadFile associated with this download. Note that this
- // pointer may only be used or destroyed on the download sequence.
- // This pointer will be non-null only while the download::DownloadItem is in
- // the IN_PROGRESS state.
- std::unique_ptr<DownloadFile> download_file_;
-
- // Information about |download_file_|.
- DestinationInfo destination_info_;
-
- // Current speed. Calculated by the DownloadFile.
- int64_t bytes_per_sec_ = 0;
-
- // The number of times this download has been resumed automatically. Will be
- // reset to 0 if a resumption is performed in response to a Resume() call.
- int auto_resume_count_ = 0;
-
- // In the event of an interruption, the DownloadDestinationObserver interface
- // exposes the partial hash state. This state can be held by the download item
- // in case it's needed for resumption.
- std::unique_ptr<crypto::SecureHash> hash_state_;
-
- // Contents of the Last-Modified header for the most recent server response.
- std::string last_modified_time_;
-
- // Server's ETAG for the file.
- std::string etag_;
-
- // The data slices that have been received so far.
- std::vector<download::DownloadItem::ReceivedSlice> received_slices_;
-
- std::unique_ptr<DownloadJob> job_;
-
- // Value of |received_bytes_| at the time the download was interrupted with
- // CONTENT_LENGTH_MISMATCH.
- int64_t received_bytes_at_length_mismatch_ = -1;
-
- // Check whether the download item is updating its observers.
- bool is_updating_observers_;
-
- // Whether the download should fetch the response body for non successful HTTP
- // response.
- bool fetch_error_body_ = false;
-
- // Source of the download, used in metrics.
- download::DownloadSource download_source_ = download::DownloadSource::UNKNOWN;
-
- base::WeakPtrFactory<DownloadItemImpl> weak_ptr_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(DownloadItemImpl);
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_ITEM_IMPL_H_
diff --git a/chromium/content/browser/download/download_item_impl_delegate.cc b/chromium/content/browser/download/download_item_impl_delegate.cc
deleted file mode 100644
index 0c03780e129..00000000000
--- a/chromium/content/browser/download/download_item_impl_delegate.cc
+++ /dev/null
@@ -1,90 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/download/download_item_impl_delegate.h"
-
-#include "base/logging.h"
-#include "components/download/public/common/download_danger_type.h"
-#include "content/browser/download/download_item_impl.h"
-
-namespace content {
-
-// Infrastructure in DownloadItemImplDelegate to assert invariant that
-// delegate always outlives all attached DownloadItemImpls.
-DownloadItemImplDelegate::DownloadItemImplDelegate()
- : count_(0) {}
-
-DownloadItemImplDelegate::~DownloadItemImplDelegate() {
- DCHECK_EQ(0, count_);
-}
-
-void DownloadItemImplDelegate::Attach() {
- ++count_;
-}
-
-void DownloadItemImplDelegate::Detach() {
- DCHECK_LT(0, count_);
- --count_;
-}
-
-void DownloadItemImplDelegate::DetermineDownloadTarget(
- DownloadItemImpl* download, const DownloadTargetCallback& callback) {
- // TODO(rdsmith/asanka): Do something useful if forced file path is null.
- base::FilePath target_path(download->GetForcedFilePath());
- callback.Run(target_path,
- download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
- download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, target_path,
- download::DOWNLOAD_INTERRUPT_REASON_NONE);
-}
-
-bool DownloadItemImplDelegate::ShouldCompleteDownload(
- DownloadItemImpl* download,
- const base::Closure& complete_callback) {
- return true;
-}
-
-bool DownloadItemImplDelegate::ShouldOpenDownload(
- DownloadItemImpl* download, const ShouldOpenDownloadCallback& callback) {
- return false;
-}
-
-bool DownloadItemImplDelegate::ShouldOpenFileBasedOnExtension(
- const base::FilePath& path) {
- return false;
-}
-
-void DownloadItemImplDelegate::CheckForFileRemoval(
- DownloadItemImpl* download_item) {}
-
-std::string DownloadItemImplDelegate::GetApplicationClientIdForFileScanning()
- const {
- return std::string();
-}
-
-void DownloadItemImplDelegate::ResumeInterruptedDownload(
- std::unique_ptr<download::DownloadUrlParameters> params,
- uint32_t id) {}
-
-BrowserContext* DownloadItemImplDelegate::GetBrowserContext() const {
- return nullptr;
-}
-
-void DownloadItemImplDelegate::UpdatePersistence(DownloadItemImpl* download) {}
-
-void DownloadItemImplDelegate::OpenDownload(DownloadItemImpl* download) {}
-
-bool DownloadItemImplDelegate::IsMostRecentDownloadItemAtFilePath(
- DownloadItemImpl* download) {
- return true;
-}
-
-void DownloadItemImplDelegate::ShowDownloadInShell(DownloadItemImpl* download) {
-}
-
-void DownloadItemImplDelegate::DownloadRemoved(DownloadItemImpl* download) {}
-
-void DownloadItemImplDelegate::AssertStateConsistent(
- DownloadItemImpl* download) const {}
-
-} // namespace content
diff --git a/chromium/content/browser/download/download_item_impl_delegate.h b/chromium/content/browser/download/download_item_impl_delegate.h
deleted file mode 100644
index f919d5dc18b..00000000000
--- a/chromium/content/browser/download/download_item_impl_delegate.h
+++ /dev/null
@@ -1,110 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_ITEM_IMPL_DELEGATE_H_
-#define CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_ITEM_IMPL_DELEGATE_H_
-
-#include <stdint.h>
-
-#include "base/callback.h"
-#include "base/files/file_path.h"
-#include "base/macros.h"
-#include "components/download/public/common/download_item.h"
-#include "components/download/public/common/download_url_parameters.h"
-#include "content/common/content_export.h"
-#include "content/public/browser/download_manager_delegate.h"
-
-namespace content {
-class DownloadItemImpl;
-class BrowserContext;
-
-// Delegate for operations that a DownloadItemImpl can't do for itself.
-// The base implementation of this class does nothing (returning false
-// on predicates) so interfaces not of interest to a derived class may
-// be left unimplemented.
-class CONTENT_EXPORT DownloadItemImplDelegate {
- public:
- // The boolean argument indicates whether or not the download was
- // actually opened.
- typedef base::Callback<void(bool)> ShouldOpenDownloadCallback;
-
- DownloadItemImplDelegate();
- virtual ~DownloadItemImplDelegate();
-
- // Used for catching use-after-free errors.
- void Attach();
- void Detach();
-
- // Request determination of the download target from the delegate.
- virtual void DetermineDownloadTarget(
- DownloadItemImpl* download, const DownloadTargetCallback& callback);
-
- // Allows the delegate to delay completion of the download. This function
- // will either return true (if the download may complete now) or will return
- // false and call the provided callback at some future point. This function
- // may be called repeatedly.
- virtual bool ShouldCompleteDownload(
- DownloadItemImpl* download,
- const base::Closure& complete_callback);
-
- // Allows the delegate to override the opening of a download. If it returns
- // true then it's reponsible for opening the item.
- virtual bool ShouldOpenDownload(
- DownloadItemImpl* download, const ShouldOpenDownloadCallback& callback);
-
- // Tests if a file type should be opened automatically.
- virtual bool ShouldOpenFileBasedOnExtension(const base::FilePath& path);
-
- // Checks whether a downloaded file still exists and updates the
- // file's state if the file is already removed.
- // The check may or may not result in a later asynchronous call
- // to OnDownloadedFileRemoved().
- virtual void CheckForFileRemoval(DownloadItemImpl* download_item);
-
- // Return a GUID string used for identifying the application to the system AV
- // function for scanning downloaded files. If no GUID is provided or if the
- // provided GUID is invalid, then the appropriate quarantining will be
- // performed manually without passing the download to the system AV function.
- //
- // This GUID is only used on Windows.
- virtual std::string GetApplicationClientIdForFileScanning() const;
-
- // Called when an interrupted download is resumed.
- virtual void ResumeInterruptedDownload(
- std::unique_ptr<download::DownloadUrlParameters> params,
- uint32_t id);
-
- // For contextual issues like language and prefs.
- virtual BrowserContext* GetBrowserContext() const;
-
- // Update the persistent store with our information.
- virtual void UpdatePersistence(DownloadItemImpl* download);
-
- // Opens the file associated with this download.
- virtual void OpenDownload(DownloadItemImpl* download);
-
- // Returns whether this is the most recent download in the rare event where
- // multiple downloads are associated with the same file path.
- virtual bool IsMostRecentDownloadItemAtFilePath(DownloadItemImpl* download);
-
- // Shows the download via the OS shell.
- virtual void ShowDownloadInShell(DownloadItemImpl* download);
-
- // Handle any delegate portions of a state change operation on the
- // download::DownloadItem.
- virtual void DownloadRemoved(DownloadItemImpl* download);
-
- // Assert consistent state for delgate object at various transitions.
- virtual void AssertStateConsistent(DownloadItemImpl* download) const;
-
- private:
- // For "Outlives attached DownloadItemImpl" invariant assertion.
- int count_;
-
- DISALLOW_COPY_AND_ASSIGN(DownloadItemImplDelegate);
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_ITEM_IMPL_DELEGATE_H_
diff --git a/chromium/content/browser/download/download_item_impl_unittest.cc b/chromium/content/browser/download/download_item_impl_unittest.cc
deleted file mode 100644
index d3ea641c4f4..00000000000
--- a/chromium/content/browser/download/download_item_impl_unittest.cc
+++ /dev/null
@@ -1,2468 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/download/download_item_impl.h"
-
-#include <stdint.h>
-
-#include <iterator>
-#include <map>
-#include <memory>
-#include <utility>
-#include <vector>
-
-#include "base/callback.h"
-#include "base/callback_helpers.h"
-#include "base/containers/circular_deque.h"
-#include "base/containers/queue.h"
-#include "base/feature_list.h"
-#include "base/files/file_util.h"
-#include "base/memory/ptr_util.h"
-#include "base/test/histogram_tester.h"
-#include "base/test/scoped_task_environment.h"
-#include "base/threading/thread.h"
-#include "components/download/public/common/download_create_info.h"
-#include "components/download/public/common/download_interrupt_reasons.h"
-#include "components/download/public/common/download_request_handle_interface.h"
-#include "components/download/public/common/download_url_parameters.h"
-#include "content/browser/byte_stream.h"
-#include "content/browser/download/download_destination_observer.h"
-#include "content/browser/download/download_file_factory.h"
-#include "content/browser/download/download_item_impl_delegate.h"
-#include "content/browser/download/mock_download_file.h"
-#include "content/public/browser/browser_thread.h"
-#include "content/public/common/content_features.h"
-#include "content/public/test/mock_download_item.h"
-#include "content/public/test/test_browser_context.h"
-#include "content/public/test/test_browser_thread_bundle.h"
-#include "content/public/test/test_utils.h"
-#include "content/public/test/web_contents_tester.h"
-#include "crypto/secure_hash.h"
-#include "net/http/http_response_headers.h"
-#include "testing/gmock/include/gmock/gmock.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-using ::testing::DoAll;
-using ::testing::Invoke;
-using ::testing::InvokeWithoutArgs;
-using ::testing::NiceMock;
-using ::testing::Property;
-using ::testing::Return;
-using ::testing::ReturnRefOfCopy;
-using ::testing::SaveArg;
-using ::testing::StrictMock;
-using ::testing::WithArg;
-using ::testing::_;
-
-const int kDownloadChunkSize = 1000;
-const int kDownloadSpeed = 1000;
-const base::FilePath::CharType kDummyTargetPath[] =
- FILE_PATH_LITERAL("/testpath");
-const base::FilePath::CharType kDummyIntermediatePath[] =
- FILE_PATH_LITERAL("/testpathx");
-
-namespace content {
-
-namespace {
-
-template <typename T>
-base::HistogramBase::Sample ToHistogramSample(T t) {
- return static_cast<base::HistogramBase::Sample>(t);
-}
-
-class MockDelegate : public DownloadItemImplDelegate {
- public:
- MockDelegate() : DownloadItemImplDelegate() {
- browser_context_.reset(new TestBrowserContext);
- SetDefaultExpectations();
- }
-
- MOCK_METHOD2(DetermineDownloadTarget, void(
- DownloadItemImpl*, const DownloadTargetCallback&));
- MOCK_METHOD2(ShouldCompleteDownload,
- bool(DownloadItemImpl*, const base::Closure&));
- MOCK_METHOD2(ShouldOpenDownload,
- bool(DownloadItemImpl*, const ShouldOpenDownloadCallback&));
- MOCK_METHOD1(ShouldOpenFileBasedOnExtension, bool(const base::FilePath&));
- MOCK_METHOD1(CheckForFileRemoval, void(DownloadItemImpl*));
-
- void ResumeInterruptedDownload(
- std::unique_ptr<download::DownloadUrlParameters> params,
- uint32_t id) override {
- MockResumeInterruptedDownload(params.get(), id);
- }
- MOCK_METHOD2(MockResumeInterruptedDownload,
- void(download::DownloadUrlParameters* params, uint32_t id));
-
- BrowserContext* GetBrowserContext() const override {
- return browser_context_.get();
- }
-
- MOCK_METHOD1(DownloadOpened, void(DownloadItemImpl*));
- MOCK_METHOD1(DownloadRemoved, void(DownloadItemImpl*));
- MOCK_CONST_METHOD1(AssertStateConsistent, void(DownloadItemImpl*));
-
- void VerifyAndClearExpectations() {
- ::testing::Mock::VerifyAndClearExpectations(this);
- SetDefaultExpectations();
- }
-
- private:
- void SetDefaultExpectations() {
- EXPECT_CALL(*this, AssertStateConsistent(_))
- .WillRepeatedly(Return());
- EXPECT_CALL(*this, ShouldOpenFileBasedOnExtension(_))
- .WillRepeatedly(Return(false));
- EXPECT_CALL(*this, ShouldOpenDownload(_, _))
- .WillRepeatedly(Return(true));
- }
-
- std::unique_ptr<TestBrowserContext> browser_context_;
-};
-
-class MockRequestHandle : public download::DownloadRequestHandleInterface {
- public:
- MOCK_METHOD0(PauseRequest, void());
- MOCK_METHOD0(ResumeRequest, void());
- MOCK_METHOD1(CancelRequest, void(bool));
-};
-
-class TestDownloadItemObserver : public download::DownloadItem::Observer {
- public:
- explicit TestDownloadItemObserver(download::DownloadItem* item)
- : item_(item),
- last_state_(item->GetState()),
- removed_(false),
- destroyed_(false),
- updated_(false),
- interrupt_count_(0),
- resume_count_(0) {
- item_->AddObserver(this);
- }
-
- ~TestDownloadItemObserver() override {
- if (item_)
- item_->RemoveObserver(this);
- }
-
- bool download_removed() const { return removed_; }
- bool download_destroyed() const { return destroyed_; }
- int interrupt_count() const { return interrupt_count_; }
- int resume_count() const { return resume_count_; }
-
- bool CheckAndResetDownloadUpdated() {
- bool was_updated = updated_;
- updated_ = false;
- return was_updated;
- }
-
- private:
- void OnDownloadRemoved(download::DownloadItem* download) override {
- SCOPED_TRACE(::testing::Message() << " " << __FUNCTION__ << " download = "
- << download->DebugString(false));
- removed_ = true;
- }
-
- void OnDownloadUpdated(download::DownloadItem* download) override {
- DVLOG(20) << " " << __FUNCTION__
- << " download = " << download->DebugString(false);
- updated_ = true;
- download::DownloadItem::DownloadState new_state = download->GetState();
- if (last_state_ == download::DownloadItem::IN_PROGRESS &&
- new_state == download::DownloadItem::INTERRUPTED) {
- interrupt_count_++;
- }
- if (last_state_ == download::DownloadItem::INTERRUPTED &&
- new_state == download::DownloadItem::IN_PROGRESS) {
- resume_count_++;
- }
- last_state_ = new_state;
- }
-
- void OnDownloadOpened(download::DownloadItem* download) override {
- DVLOG(20) << " " << __FUNCTION__
- << " download = " << download->DebugString(false);
- }
-
- void OnDownloadDestroyed(download::DownloadItem* download) override {
- DVLOG(20) << " " << __FUNCTION__
- << " download = " << download->DebugString(false);
- destroyed_ = true;
- item_->RemoveObserver(this);
- item_ = nullptr;
- }
-
- download::DownloadItem* item_;
- download::DownloadItem::DownloadState last_state_;
- bool removed_;
- bool destroyed_;
- bool updated_;
- int interrupt_count_;
- int resume_count_;
-};
-
-// Schedules a task to invoke the RenameCompletionCallback with |new_path| on
-// the UI thread. Should only be used as the action for
-// MockDownloadFile::RenameAndUniquify as follows:
-// EXPECT_CALL(download_file, RenameAndUniquify(_,_))
-// .WillOnce(ScheduleRenameAndUniquifyCallback(
-// download::DOWNLOAD_INTERRUPT_REASON_NONE, new_path));
-ACTION_P2(ScheduleRenameAndUniquifyCallback, interrupt_reason, new_path) {
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
- base::BindOnce(arg1, interrupt_reason, new_path));
-}
-
-// Schedules a task to invoke the RenameCompletionCallback with |new_path| on
-// the UI thread. Should only be used as the action for
-// MockDownloadFile::RenameAndAnnotate as follows:
-// EXPECT_CALL(download_file, RenameAndAnnotate(_,_,_,_,_))
-// .WillOnce(ScheduleRenameAndAnnotateCallback(
-// download::DOWNLOAD_INTERRUPT_REASON_NONE, new_path));
-ACTION_P2(ScheduleRenameAndAnnotateCallback, interrupt_reason, new_path) {
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
- base::BindOnce(arg4, interrupt_reason, new_path));
-}
-
-// Schedules a task to invoke a callback that's bound to the specified
-// parameter.
-// E.g.:
-//
-// EXPECT_CALL(foo, Bar(1, _))
-// .WithArg<1>(ScheduleCallbackWithParam(0));
-//
-// .. will invoke the second argument to Bar with 0 as the parameter.
-ACTION_P(ScheduleCallbackWithParam, param) {
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
- base::BindOnce(arg0, param));
-}
-
-// Schedules a task to invoke a closure.
-// E.g.:
-//
-// EXPECT_CALL(foo, Bar(1, _))
-// .WillOnce(ScheduleClosure(some_closure));
-ACTION_P(ScheduleClosure, closure) {
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, closure);
-}
-
-const char kTestData1[] = {'M', 'a', 'r', 'y', ' ', 'h', 'a', 'd',
- ' ', 'a', ' ', 'l', 'i', 't', 't', 'l',
- 'e', ' ', 'l', 'a', 'm', 'b', '.'};
-
-// SHA256 hash of TestData1
-const uint8_t kHashOfTestData1[] = {
- 0xd2, 0xfc, 0x16, 0xa1, 0xf5, 0x1a, 0x65, 0x3a, 0xa0, 0x19, 0x64,
- 0xef, 0x9c, 0x92, 0x33, 0x36, 0xe1, 0x06, 0x53, 0xfe, 0xc1, 0x95,
- 0xf4, 0x93, 0x45, 0x8b, 0x3b, 0x21, 0x89, 0x0e, 0x1b, 0x97};
-
-} // namespace
-
-class DownloadItemTest : public testing::Test {
- public:
- DownloadItemTest()
- : task_environment_(
- base::test::ScopedTaskEnvironment::MainThreadType::UI,
- base::test::ScopedTaskEnvironment::ExecutionMode::QUEUED),
- next_download_id_(download::DownloadItem::kInvalidId + 1) {
- create_info_.reset(new download::DownloadCreateInfo());
- create_info_->save_info = std::unique_ptr<download::DownloadSaveInfo>(
- new download::DownloadSaveInfo());
- create_info_->save_info->prompt_for_save_location = false;
- create_info_->url_chain.push_back(GURL("http://example.com/download"));
- create_info_->etag = "SomethingToSatisfyResumption";
- }
-
- DownloadItemImpl* CreateDownloadItemWithCreateInfo(
- std::unique_ptr<download::DownloadCreateInfo> info) {
- DownloadItemImpl* download = new DownloadItemImpl(
- mock_delegate(), next_download_id_++, *(info.get()));
- allocated_downloads_[download] = base::WrapUnique(download);
- return download;
- }
-
- // Creates a new net::HttpResponseHeaders object for the |response_code|.
- scoped_refptr<const net::HttpResponseHeaders> CreateResponseHeaders(
- int response_code) {
- return base::MakeRefCounted<net::HttpResponseHeaders>(
- "HTTP/1.1 " + std::to_string(response_code));
- }
-
- // This class keeps ownership of the created download item; it will
- // be torn down at the end of the test unless DestroyDownloadItem is
- // called.
- DownloadItemImpl* CreateDownloadItem() {
- create_info_->download_id = ++next_download_id_;
- DownloadItemImpl* download = new DownloadItemImpl(
- mock_delegate(), create_info_->download_id, *create_info_);
- allocated_downloads_[download] = base::WrapUnique(download);
- return download;
- }
-
- // Add DownloadFile to download::DownloadItem.
- MockDownloadFile* CallDownloadItemStart(DownloadItemImpl* item,
- DownloadTargetCallback* callback) {
- MockDownloadFile* mock_download_file = nullptr;
- std::unique_ptr<DownloadFile> download_file;
- EXPECT_CALL(*mock_delegate(), DetermineDownloadTarget(item, _))
- .WillOnce(SaveArg<1>(callback));
-
- // Only create a DownloadFile if the request was successful.
- if (create_info_->result == download::DOWNLOAD_INTERRUPT_REASON_NONE) {
- mock_download_file = new StrictMock<MockDownloadFile>;
- download_file.reset(mock_download_file);
- EXPECT_CALL(*mock_download_file, Initialize(_, _, _, _))
- .WillOnce(ScheduleCallbackWithParam(
- download::DOWNLOAD_INTERRUPT_REASON_NONE));
- EXPECT_CALL(*mock_download_file, FullPath())
- .WillRepeatedly(ReturnRefOfCopy(base::FilePath()));
- }
-
- std::unique_ptr<MockRequestHandle> request_handle =
- std::make_unique<NiceMock<MockRequestHandle>>();
- item->Start(std::move(download_file), std::move(request_handle),
- *create_info_);
- task_environment_.RunUntilIdle();
-
- // So that we don't have a function writing to a stack variable
- // lying around if the above failed.
- mock_delegate()->VerifyAndClearExpectations();
- EXPECT_CALL(*mock_delegate(), AssertStateConsistent(_))
- .WillRepeatedly(Return());
- EXPECT_CALL(*mock_delegate(), ShouldOpenFileBasedOnExtension(_))
- .WillRepeatedly(Return(false));
- EXPECT_CALL(*mock_delegate(), ShouldOpenDownload(_, _))
- .WillRepeatedly(Return(true));
-
- return mock_download_file;
- }
-
- // Perform the intermediate rename for |item|. The target path for the
- // download will be set to kDummyTargetPath. Returns the MockDownloadFile*
- // that was added to the download::DownloadItem.
- MockDownloadFile* DoIntermediateRename(
- DownloadItemImpl* item,
- download::DownloadDangerType danger_type) {
- EXPECT_EQ(download::DownloadItem::IN_PROGRESS, item->GetState());
- EXPECT_TRUE(item->GetTargetFilePath().empty());
- DownloadTargetCallback callback;
- MockDownloadFile* download_file = CallDownloadItemStart(item, &callback);
- base::FilePath target_path(kDummyTargetPath);
- base::FilePath intermediate_path(kDummyIntermediatePath);
- EXPECT_CALL(*download_file, RenameAndUniquify(intermediate_path, _))
- .WillOnce(ScheduleRenameAndUniquifyCallback(
- download::DOWNLOAD_INTERRUPT_REASON_NONE, intermediate_path));
- callback.Run(target_path,
- download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
- danger_type, intermediate_path,
- download::DOWNLOAD_INTERRUPT_REASON_NONE);
- task_environment_.RunUntilIdle();
- return download_file;
- }
-
- void DoDestinationComplete(DownloadItemImpl* item,
- MockDownloadFile* download_file) {
- EXPECT_CALL(*mock_delegate(), ShouldCompleteDownload(_, _))
- .WillOnce(Return(true));
- base::FilePath final_path(kDummyTargetPath);
- EXPECT_CALL(*download_file, RenameAndAnnotate(_, _, _, _, _))
- .WillOnce(ScheduleRenameAndAnnotateCallback(
- download::DOWNLOAD_INTERRUPT_REASON_NONE, final_path));
- EXPECT_CALL(*download_file, FullPath())
- .WillRepeatedly(ReturnRefOfCopy(base::FilePath(kDummyTargetPath)));
- EXPECT_CALL(*download_file, Detach());
-
- item->DestinationObserverAsWeakPtr()->DestinationCompleted(
- 0, std::unique_ptr<crypto::SecureHash>());
- task_environment_.RunUntilIdle();
- }
-
- // Cleanup a download item (specifically get rid of the DownloadFile on it).
- // The item must be in the expected state.
- void CleanupItem(DownloadItemImpl* item,
- MockDownloadFile* download_file,
- download::DownloadItem::DownloadState expected_state) {
- EXPECT_EQ(expected_state, item->GetState());
-
- if (expected_state == download::DownloadItem::IN_PROGRESS) {
- if (download_file)
- EXPECT_CALL(*download_file, Cancel());
- item->Cancel(true);
- task_environment_.RunUntilIdle();
- }
- }
-
- // Destroy a previously created download item.
- void DestroyDownloadItem(download::DownloadItem* item) {
- allocated_downloads_.erase(item);
- }
-
- MockDelegate* mock_delegate() { return &mock_delegate_; }
-
- void OnDownloadFileAcquired(base::FilePath* return_path,
- const base::FilePath& path) {
- *return_path = path;
- }
-
- download::DownloadCreateInfo* create_info() { return create_info_.get(); }
-
- BrowserContext* browser_context() { return &browser_context_; }
-
- base::test::ScopedTaskEnvironment task_environment_;
-
- private:
- TestBrowserThreadBundle thread_bundle_;
- StrictMock<MockDelegate> mock_delegate_;
- std::map<download::DownloadItem*, std::unique_ptr<download::DownloadItem>>
- allocated_downloads_;
- std::unique_ptr<download::DownloadCreateInfo> create_info_;
- uint32_t next_download_id_ = download::DownloadItem::kInvalidId + 1;
- TestBrowserContext browser_context_;
-};
-
-// Tests to ensure calls that change a download::DownloadItem generate an update
-// to observers. State changing functions not tested:
-// void OpenDownload();
-// void ShowDownloadInShell();
-// void CompleteDelayedDownload();
-// set_* mutators
-
-TEST_F(DownloadItemTest, NotificationAfterUpdate) {
- DownloadItemImpl* item = CreateDownloadItem();
- MockDownloadFile* file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
- ASSERT_EQ(download::DownloadItem::IN_PROGRESS, item->GetState());
- TestDownloadItemObserver observer(item);
-
- item->DestinationUpdate(kDownloadChunkSize, kDownloadSpeed,
- std::vector<download::DownloadItem::ReceivedSlice>());
- ASSERT_TRUE(observer.CheckAndResetDownloadUpdated());
- EXPECT_EQ(kDownloadSpeed, item->CurrentSpeed());
- CleanupItem(item, file, download::DownloadItem::IN_PROGRESS);
-}
-
-TEST_F(DownloadItemTest, NotificationAfterCancel) {
- DownloadItemImpl* user_cancel = CreateDownloadItem();
- DownloadTargetCallback target_callback;
- MockDownloadFile* download_file =
- CallDownloadItemStart(user_cancel, &target_callback);
- EXPECT_CALL(*download_file, Cancel());
-
- TestDownloadItemObserver observer1(user_cancel);
- user_cancel->Cancel(true);
- ASSERT_TRUE(observer1.CheckAndResetDownloadUpdated());
-
- DownloadItemImpl* system_cancel = CreateDownloadItem();
- download_file = CallDownloadItemStart(system_cancel, &target_callback);
- EXPECT_CALL(*download_file, Cancel());
-
- TestDownloadItemObserver observer2(system_cancel);
- system_cancel->Cancel(false);
- ASSERT_TRUE(observer2.CheckAndResetDownloadUpdated());
-}
-
-TEST_F(DownloadItemTest, NotificationAfterComplete) {
- DownloadItemImpl* item = CreateDownloadItem();
- TestDownloadItemObserver observer(item);
- MockDownloadFile* download_file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
- ASSERT_TRUE(observer.CheckAndResetDownloadUpdated());
- DoDestinationComplete(item, download_file);
- ASSERT_TRUE(observer.CheckAndResetDownloadUpdated());
-}
-
-TEST_F(DownloadItemTest, NotificationAfterDownloadedFileRemoved) {
- DownloadItemImpl* item = CreateDownloadItem();
- TestDownloadItemObserver observer(item);
-
- item->OnDownloadedFileRemoved();
- ASSERT_TRUE(observer.CheckAndResetDownloadUpdated());
-}
-
-TEST_F(DownloadItemTest, NotificationAfterInterrupted) {
- DownloadItemImpl* item = CreateDownloadItem();
- MockDownloadFile* download_file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
- EXPECT_CALL(*download_file, Cancel());
- TestDownloadItemObserver observer(item);
-
- EXPECT_CALL(*mock_delegate(), MockResumeInterruptedDownload(_, _)).Times(0);
-
- item->DestinationObserverAsWeakPtr()->DestinationError(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED, 0,
- std::unique_ptr<crypto::SecureHash>());
- ASSERT_TRUE(observer.CheckAndResetDownloadUpdated());
-}
-
-TEST_F(DownloadItemTest, NotificationAfterDestroyed) {
- DownloadItemImpl* item = CreateDownloadItem();
- TestDownloadItemObserver observer(item);
-
- DestroyDownloadItem(item);
- ASSERT_TRUE(observer.download_destroyed());
-}
-
-TEST_F(DownloadItemTest, NotificationAfterRemove) {
- DownloadItemImpl* item = CreateDownloadItem();
- DownloadTargetCallback target_callback;
- MockDownloadFile* download_file =
- CallDownloadItemStart(item, &target_callback);
- EXPECT_CALL(*download_file, Cancel());
- EXPECT_CALL(*mock_delegate(), DownloadRemoved(_));
- TestDownloadItemObserver observer(item);
-
- item->Remove();
- ASSERT_TRUE(observer.CheckAndResetDownloadUpdated());
- ASSERT_TRUE(observer.download_removed());
-}
-
-TEST_F(DownloadItemTest, NotificationAfterOnContentCheckCompleted) {
- // Setting to NOT_DANGEROUS does not trigger a notification.
- DownloadItemImpl* safe_item = CreateDownloadItem();
- MockDownloadFile* download_file = DoIntermediateRename(
- safe_item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
- TestDownloadItemObserver safe_observer(safe_item);
-
- safe_item->OnAllDataSaved(0, std::unique_ptr<crypto::SecureHash>());
- EXPECT_TRUE(safe_observer.CheckAndResetDownloadUpdated());
- safe_item->OnContentCheckCompleted(
- download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
- download::DOWNLOAD_INTERRUPT_REASON_NONE);
- EXPECT_TRUE(safe_observer.CheckAndResetDownloadUpdated());
- CleanupItem(safe_item, download_file, download::DownloadItem::IN_PROGRESS);
-
- // Setting to unsafe url or unsafe file should trigger a notification.
- DownloadItemImpl* unsafeurl_item = CreateDownloadItem();
- download_file = DoIntermediateRename(
- unsafeurl_item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
- TestDownloadItemObserver unsafeurl_observer(unsafeurl_item);
-
- unsafeurl_item->OnAllDataSaved(0, std::unique_ptr<crypto::SecureHash>());
- EXPECT_TRUE(unsafeurl_observer.CheckAndResetDownloadUpdated());
- unsafeurl_item->OnContentCheckCompleted(
- download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL,
- download::DOWNLOAD_INTERRUPT_REASON_NONE);
- EXPECT_TRUE(unsafeurl_observer.CheckAndResetDownloadUpdated());
-
- EXPECT_CALL(*mock_delegate(), ShouldCompleteDownload(_, _))
- .WillOnce(Return(true));
- EXPECT_CALL(*download_file, RenameAndAnnotate(_, _, _, _, _));
- unsafeurl_item->ValidateDangerousDownload();
- EXPECT_TRUE(unsafeurl_observer.CheckAndResetDownloadUpdated());
- CleanupItem(unsafeurl_item, download_file,
- download::DownloadItem::IN_PROGRESS);
-
- DownloadItemImpl* unsafefile_item = CreateDownloadItem();
- download_file = DoIntermediateRename(
- unsafefile_item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
- TestDownloadItemObserver unsafefile_observer(unsafefile_item);
-
- unsafefile_item->OnAllDataSaved(0, std::unique_ptr<crypto::SecureHash>());
- EXPECT_TRUE(unsafefile_observer.CheckAndResetDownloadUpdated());
- unsafefile_item->OnContentCheckCompleted(
- download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE,
- download::DOWNLOAD_INTERRUPT_REASON_NONE);
- EXPECT_TRUE(unsafefile_observer.CheckAndResetDownloadUpdated());
-
- EXPECT_CALL(*mock_delegate(), ShouldCompleteDownload(_, _))
- .WillOnce(Return(true));
- EXPECT_CALL(*download_file, RenameAndAnnotate(_, _, _, _, _));
- unsafefile_item->ValidateDangerousDownload();
- EXPECT_TRUE(unsafefile_observer.CheckAndResetDownloadUpdated());
- CleanupItem(unsafefile_item, download_file,
- download::DownloadItem::IN_PROGRESS);
-}
-
-// DownloadItemImpl::OnDownloadTargetDetermined will schedule a task to run
-// DownloadFile::Rename(). Once the rename
-// completes, DownloadItemImpl receives a notification with the new file
-// name. Check that observers are updated when the new filename is available and
-// not before.
-TEST_F(DownloadItemTest, NotificationAfterOnDownloadTargetDetermined) {
- DownloadItemImpl* item = CreateDownloadItem();
- DownloadTargetCallback callback;
- MockDownloadFile* download_file = CallDownloadItemStart(item, &callback);
- TestDownloadItemObserver observer(item);
- base::FilePath target_path(kDummyTargetPath);
- base::FilePath intermediate_path(target_path.InsertBeforeExtensionASCII("x"));
- base::FilePath new_intermediate_path(
- target_path.InsertBeforeExtensionASCII("y"));
- EXPECT_CALL(*download_file, RenameAndUniquify(intermediate_path, _))
- .WillOnce(ScheduleRenameAndUniquifyCallback(
- download::DOWNLOAD_INTERRUPT_REASON_NONE, new_intermediate_path));
-
- // Currently, a notification would be generated if the danger type is anything
- // other than NOT_DANGEROUS.
- callback.Run(target_path,
- download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
- download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, intermediate_path,
- download::DOWNLOAD_INTERRUPT_REASON_NONE);
- EXPECT_FALSE(observer.CheckAndResetDownloadUpdated());
- task_environment_.RunUntilIdle();
- EXPECT_TRUE(observer.CheckAndResetDownloadUpdated());
- EXPECT_EQ(new_intermediate_path, item->GetFullPath());
-
- CleanupItem(item, download_file, download::DownloadItem::IN_PROGRESS);
-}
-
-TEST_F(DownloadItemTest, NotificationAfterTogglePause) {
- DownloadItemImpl* item = CreateDownloadItem();
- TestDownloadItemObserver observer(item);
- MockDownloadFile* mock_download_file(new MockDownloadFile);
- std::unique_ptr<DownloadFile> download_file(mock_download_file);
- std::unique_ptr<download::DownloadRequestHandleInterface> request_handle(
- new NiceMock<MockRequestHandle>);
-
- EXPECT_CALL(*mock_download_file, Initialize(_, _, _, _));
- EXPECT_CALL(*mock_delegate(), DetermineDownloadTarget(_, _));
- item->Start(std::move(download_file), std::move(request_handle),
- *create_info());
-
- item->Pause();
- ASSERT_TRUE(observer.CheckAndResetDownloadUpdated());
-
- ASSERT_TRUE(item->IsPaused());
-
- item->Resume();
- ASSERT_TRUE(observer.CheckAndResetDownloadUpdated());
-
- task_environment_.RunUntilIdle();
-
- CleanupItem(item, mock_download_file, download::DownloadItem::IN_PROGRESS);
-}
-
-// Test that a download is resumed automatically after a continuable interrupt.
-TEST_F(DownloadItemTest, AutomaticResumption_Continue) {
- DownloadItemImpl* item = CreateDownloadItem();
- TestDownloadItemObserver observer(item);
- MockDownloadFile* download_file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
-
- // Interrupt the download using a continuable interrupt after writing a single
- // byte. An intermediate file with data shouldn't be discarding after a
- // continuable interrupt.
-
- // The DownloadFile should be detached without discarding.
- EXPECT_CALL(*download_file, FullPath())
- .WillOnce(ReturnRefOfCopy(base::FilePath()));
- EXPECT_CALL(*download_file, Detach());
-
- // Resumption attempt should pass the intermediate file along.
- EXPECT_CALL(*mock_delegate(),
- MockResumeInterruptedDownload(
- AllOf(Property(&download::DownloadUrlParameters::file_path,
- Property(&base::FilePath::value,
- kDummyIntermediatePath)),
- Property(&download::DownloadUrlParameters::offset, 1)),
- _));
-
- base::HistogramTester histogram_tester;
- item->DestinationObserverAsWeakPtr()->DestinationError(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR, 1,
- std::unique_ptr<crypto::SecureHash>());
- ASSERT_TRUE(observer.CheckAndResetDownloadUpdated());
- // Since the download is resumed automatically, the interrupt count doesn't
- // increase.
- ASSERT_EQ(0, observer.interrupt_count());
-
- // Test expectations verify that ResumeInterruptedDownload() is called (by way
- // of MockResumeInterruptedDownload) after the download is interrupted. But
- // the mock doesn't follow through with the resumption.
- // ResumeInterruptedDownload() being called is sufficient for verifying that
- // the automatic resumption was triggered.
- task_environment_.RunUntilIdle();
-
- // Interrupt reason is recorded in auto resumption even when download is not
- // finally interrupted.
- histogram_tester.ExpectBucketCount(
- "Download.InterruptedReason",
- ToHistogramSample<download::DownloadInterruptReason>(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR),
- 1);
-
- // The download item is currently in RESUMING_INTERNAL state, which maps to
- // IN_PROGRESS.
- CleanupItem(item, nullptr, download::DownloadItem::IN_PROGRESS);
-}
-
-// Automatic resumption should restart and discard the intermediate file if the
-// interrupt reason requires it.
-TEST_F(DownloadItemTest, AutomaticResumption_Restart) {
- DownloadItemImpl* item = CreateDownloadItem();
- TestDownloadItemObserver observer(item);
- MockDownloadFile* download_file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
-
- // Interrupt the download, using a restartable interrupt.
- EXPECT_CALL(*download_file, Cancel());
- EXPECT_EQ(kDummyIntermediatePath, item->GetFullPath().value());
-
- // Resumption attempt should have discarded intermediate file.
- EXPECT_CALL(*mock_delegate(),
- MockResumeInterruptedDownload(
- Property(&download::DownloadUrlParameters::file_path,
- Property(&base::FilePath::empty, true)),
- _));
-
- base::HistogramTester histogram_tester;
- item->DestinationObserverAsWeakPtr()->DestinationError(
- download::DOWNLOAD_INTERRUPT_REASON_SERVER_NO_RANGE, 1,
- std::unique_ptr<crypto::SecureHash>());
- ASSERT_TRUE(observer.CheckAndResetDownloadUpdated());
-
- // Since the download is resumed automatically, the interrupt count doesn't
- // increase.
- ASSERT_EQ(0, observer.interrupt_count());
-
- task_environment_.RunUntilIdle();
- // Auto resumption will record interrupt reason even if download is not
- // finally interrupted.
- histogram_tester.ExpectBucketCount(
- "Download.InterruptedReason",
- ToHistogramSample<download::DownloadInterruptReason>(
- download::DOWNLOAD_INTERRUPT_REASON_SERVER_NO_RANGE),
- 1);
- CleanupItem(item, nullptr, download::DownloadItem::IN_PROGRESS);
-}
-
-// Test that automatic resumption doesn't happen after an interrupt that
-// requires user action to resolve.
-TEST_F(DownloadItemTest, AutomaticResumption_NeedsUserAction) {
- DownloadItemImpl* item = CreateDownloadItem();
- TestDownloadItemObserver observer(item);
- MockDownloadFile* download_file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
-
- // Interrupt the download, using a restartable interrupt.
- EXPECT_CALL(*download_file, Cancel());
- base::HistogramTester histogram_tester;
- item->DestinationObserverAsWeakPtr()->DestinationError(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED, 1,
- std::unique_ptr<crypto::SecureHash>());
- ASSERT_TRUE(observer.CheckAndResetDownloadUpdated());
- // Should not try to auto-resume.
- ASSERT_EQ(1, observer.interrupt_count());
- ASSERT_EQ(0, observer.resume_count());
-
- task_environment_.RunUntilIdle();
- histogram_tester.ExpectBucketCount(
- "Download.InterruptedReason",
- ToHistogramSample<download::DownloadInterruptReason>(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED),
- 1);
- CleanupItem(item, nullptr, download::DownloadItem::INTERRUPTED);
-}
-
-// Test that a download is resumed automatically after a content length mismatch
-// error.
-TEST_F(DownloadItemTest, AutomaticResumption_ContentLengthMismatch) {
- DownloadItemImpl* item = CreateDownloadItem();
- TestDownloadItemObserver observer(item);
- MockDownloadFile* download_file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
-
- // Interrupt the download with content length mismatch error. The intermediate
- // file with data shouldn't be discarded.
-
- // The DownloadFile should be detached without discarding.
- EXPECT_CALL(*download_file, FullPath())
- .WillOnce(ReturnRefOfCopy(base::FilePath()));
- EXPECT_CALL(*download_file, Detach());
-
- // Resumption attempt should pass the intermediate file along.
- EXPECT_CALL(*mock_delegate(),
- MockResumeInterruptedDownload(
- AllOf(Property(&download::DownloadUrlParameters::file_path,
- Property(&base::FilePath::value,
- kDummyIntermediatePath)),
- Property(&download::DownloadUrlParameters::offset, 1)),
- _));
-
- base::HistogramTester histogram_tester;
- item->DestinationObserverAsWeakPtr()->DestinationError(
- download::DOWNLOAD_INTERRUPT_REASON_SERVER_CONTENT_LENGTH_MISMATCH, 1,
- std::unique_ptr<crypto::SecureHash>());
- ASSERT_TRUE(observer.CheckAndResetDownloadUpdated());
- // Since the download is resumed automatically, the observer shouldn't notice
- // the interruption.
- ASSERT_EQ(0, observer.interrupt_count());
- ASSERT_EQ(0, observer.resume_count());
-
- task_environment_.RunUntilIdle();
- histogram_tester.ExpectBucketCount(
- "Download.InterruptedReason",
- ToHistogramSample<download::DownloadInterruptReason>(
- download::DOWNLOAD_INTERRUPT_REASON_SERVER_CONTENT_LENGTH_MISMATCH),
- 1);
- CleanupItem(item, nullptr, download::DownloadItem::IN_PROGRESS);
-}
-
-// Check we do correct cleanup for RESUME_MODE_INVALID interrupts.
-TEST_F(DownloadItemTest, UnresumableInterrupt) {
- DownloadItemImpl* item = CreateDownloadItem();
- TestDownloadItemObserver observer(item);
- MockDownloadFile* download_file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
-
- // Fail final rename with unresumable reason.
- EXPECT_CALL(*mock_delegate(), ShouldCompleteDownload(item, _))
- .WillOnce(Return(true));
- EXPECT_CALL(*download_file,
- RenameAndAnnotate(base::FilePath(kDummyTargetPath), _, _, _, _))
- .WillOnce(ScheduleRenameAndAnnotateCallback(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_BLOCKED, base::FilePath()));
- EXPECT_CALL(*download_file, Cancel());
-
- // Complete download to trigger final rename.
- base::HistogramTester histogram_tester;
- item->DestinationObserverAsWeakPtr()->DestinationCompleted(
- 0, std::unique_ptr<crypto::SecureHash>());
-
- task_environment_.RunUntilIdle();
- histogram_tester.ExpectBucketCount(
- "Download.InterruptedReason",
- ToHistogramSample<download::DownloadInterruptReason>(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_BLOCKED),
- 1);
- ASSERT_TRUE(observer.CheckAndResetDownloadUpdated());
- // Should not try to auto-resume.
- ASSERT_EQ(1, observer.interrupt_count());
- ASSERT_EQ(0, observer.resume_count());
-
- CleanupItem(item, nullptr, download::DownloadItem::INTERRUPTED);
-}
-
-TEST_F(DownloadItemTest, AutomaticResumption_AttemptLimit) {
- base::HistogramTester histogram_tester;
- DownloadItemImpl* item = CreateDownloadItem();
- base::WeakPtr<DownloadDestinationObserver> as_observer(
- item->DestinationObserverAsWeakPtr());
- TestDownloadItemObserver observer(item);
- MockDownloadFile* mock_download_file_ref = nullptr;
- std::unique_ptr<MockDownloadFile> mock_download_file;
- std::unique_ptr<MockRequestHandle> mock_request_handle;
- DownloadTargetCallback callback;
-
- EXPECT_CALL(*mock_delegate(), DetermineDownloadTarget(item, _))
- .WillRepeatedly(SaveArg<1>(&callback));
-
- // All attempts at resumption should pass along the intermediate file.
- EXPECT_CALL(*mock_delegate(),
- MockResumeInterruptedDownload(
- AllOf(Property(&download::DownloadUrlParameters::file_path,
- Property(&base::FilePath::value,
- kDummyIntermediatePath)),
- Property(&download::DownloadUrlParameters::offset, 1)),
- _))
- .Times(DownloadItemImpl::kMaxAutoResumeAttempts);
- for (int i = 0; i < (DownloadItemImpl::kMaxAutoResumeAttempts + 1); ++i) {
- SCOPED_TRACE(::testing::Message() << "Iteration " << i);
-
- mock_download_file = std::make_unique<NiceMock<MockDownloadFile>>();
- mock_download_file_ref = mock_download_file.get();
- mock_request_handle = std::make_unique<NiceMock<MockRequestHandle>>();
-
- ON_CALL(*mock_download_file_ref, FullPath())
- .WillByDefault(ReturnRefOfCopy(base::FilePath()));
-
- // Copied key parts of DoIntermediateRename & CallDownloadItemStart
- // to allow for holding onto the request handle.
- item->Start(std::move(mock_download_file), std::move(mock_request_handle),
- *create_info());
- task_environment_.RunUntilIdle();
-
- base::FilePath target_path(kDummyTargetPath);
- base::FilePath intermediate_path(kDummyIntermediatePath);
-
- // Target of RenameAndUniquify is always the intermediate path.
- ON_CALL(*mock_download_file_ref, RenameAndUniquify(_, _))
- .WillByDefault(ScheduleRenameAndUniquifyCallback(
- download::DOWNLOAD_INTERRUPT_REASON_NONE, intermediate_path));
-
- // RenameAndUniquify is only called the first time. In all the subsequent
- // iterations, the intermediate file already has the correct name, hence no
- // rename is necessary.
- EXPECT_CALL(*mock_download_file_ref, RenameAndUniquify(_, _)).Times(i == 0);
-
- ASSERT_FALSE(callback.is_null());
- base::ResetAndReturn(&callback).Run(
- target_path, download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
- download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, intermediate_path,
- download::DOWNLOAD_INTERRUPT_REASON_NONE);
- task_environment_.RunUntilIdle();
-
- // Use a continuable interrupt.
- EXPECT_CALL(*mock_download_file_ref, Cancel()).Times(0);
- item->DestinationObserverAsWeakPtr()->DestinationError(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR, 1,
- std::unique_ptr<crypto::SecureHash>());
-
- task_environment_.RunUntilIdle();
- ::testing::Mock::VerifyAndClearExpectations(mock_download_file_ref);
- }
-
- histogram_tester.ExpectBucketCount(
- "Download.InterruptedReason",
- ToHistogramSample<download::DownloadInterruptReason>(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR),
- DownloadItemImpl::kMaxAutoResumeAttempts + 1);
- EXPECT_EQ(download::DownloadItem::INTERRUPTED, item->GetState());
- EXPECT_EQ(1, observer.interrupt_count());
- CleanupItem(item, nullptr, download::DownloadItem::INTERRUPTED);
-}
-
-// If the download attempts to resume and the resumption request fails, the
-// subsequent Start() call shouldn't update the origin state (URL redirect
-// chains, Content-Disposition, download URL, etc..)
-TEST_F(DownloadItemTest, FailedResumptionDoesntUpdateOriginState) {
- constexpr int kFirstResponseCode = 200;
- const char kContentDisposition[] = "attachment; filename=foo";
- const char kFirstETag[] = "ABC";
- const char kFirstLastModified[] = "Yesterday";
- const char kFirstURL[] = "http://www.example.com/download";
- const char kMimeType[] = "text/css";
- create_info()->response_headers = CreateResponseHeaders(kFirstResponseCode);
- create_info()->content_disposition = kContentDisposition;
- create_info()->etag = kFirstETag;
- create_info()->last_modified = kFirstLastModified;
- create_info()->url_chain.push_back(GURL(kFirstURL));
- create_info()->mime_type = kMimeType;
-
- DownloadItemImpl* item = CreateDownloadItem();
- MockDownloadFile* download_file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
- ASSERT_TRUE(item->GetResponseHeaders());
- EXPECT_EQ(kFirstResponseCode, item->GetResponseHeaders()->response_code());
- EXPECT_EQ(kContentDisposition, item->GetContentDisposition());
- EXPECT_EQ(kFirstETag, item->GetETag());
- EXPECT_EQ(kFirstLastModified, item->GetLastModifiedTime());
- EXPECT_EQ(kFirstURL, item->GetURL().spec());
- EXPECT_EQ(kMimeType, item->GetMimeType());
-
- EXPECT_CALL(*mock_delegate(),
- MockResumeInterruptedDownload(
- AllOf(Property(&download::DownloadUrlParameters::file_path,
- Property(&base::FilePath::value,
- kDummyIntermediatePath)),
- Property(&download::DownloadUrlParameters::offset, 1)),
- _));
- EXPECT_CALL(*download_file, Detach());
- item->DestinationObserverAsWeakPtr()->DestinationError(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR, 1,
- std::unique_ptr<crypto::SecureHash>());
- task_environment_.RunUntilIdle();
- EXPECT_EQ(download::DownloadItem::IN_PROGRESS, item->GetState());
-
- // Now change the create info. The changes should not cause the
- // download::DownloadItem to be updated.
- constexpr int kSecondResponseCode = 418;
- const char kSecondContentDisposition[] = "attachment; filename=bar";
- const char kSecondETag[] = "123";
- const char kSecondLastModified[] = "Today";
- const char kSecondURL[] = "http://example.com/another-download";
- const char kSecondMimeType[] = "text/html";
- create_info()->response_headers = CreateResponseHeaders(kSecondResponseCode);
- create_info()->content_disposition = kSecondContentDisposition;
- create_info()->etag = kSecondETag;
- create_info()->last_modified = kSecondLastModified;
- create_info()->url_chain.clear();
- create_info()->url_chain.push_back(GURL(kSecondURL));
- create_info()->mime_type = kSecondMimeType;
- create_info()->result = download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED;
- create_info()->save_info->file_path = base::FilePath(kDummyIntermediatePath);
- create_info()->save_info->offset = 1;
-
- // Calling Start() with a response indicating failure shouldn't cause a target
- // update, nor should it result in discarding the intermediate file.
- DownloadTargetCallback target_callback;
- download_file = CallDownloadItemStart(item, &target_callback);
- ASSERT_FALSE(target_callback.is_null());
- target_callback.Run(base::FilePath(kDummyTargetPath),
- download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
- download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
- base::FilePath(kDummyIntermediatePath),
- download::DOWNLOAD_INTERRUPT_REASON_NONE);
- task_environment_.RunUntilIdle();
-
- ASSERT_TRUE(item->GetResponseHeaders());
- EXPECT_EQ(kFirstResponseCode, item->GetResponseHeaders()->response_code());
- EXPECT_EQ(kContentDisposition, item->GetContentDisposition());
- EXPECT_EQ(kFirstETag, item->GetETag());
- EXPECT_EQ(kFirstLastModified, item->GetLastModifiedTime());
- EXPECT_EQ(kFirstURL, item->GetURL().spec());
- EXPECT_EQ(kMimeType, item->GetMimeType());
- EXPECT_EQ(download::DownloadItem::INTERRUPTED, item->GetState());
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED,
- item->GetLastReason());
- EXPECT_EQ(kDummyIntermediatePath, item->GetFullPath().value());
- EXPECT_EQ(1, item->GetReceivedBytes());
-}
-
-// If the download resumption request succeeds, the origin state should be
-// updated.
-TEST_F(DownloadItemTest, SucceededResumptionUpdatesOriginState) {
- constexpr int kFirstResponseCode = 200;
- const char kContentDisposition[] = "attachment; filename=foo";
- const char kFirstETag[] = "ABC";
- const char kFirstLastModified[] = "Yesterday";
- const char kFirstURL[] = "http://www.example.com/download";
- const char kMimeType[] = "text/css";
- create_info()->response_headers = CreateResponseHeaders(kFirstResponseCode);
- create_info()->content_disposition = kContentDisposition;
- create_info()->etag = kFirstETag;
- create_info()->last_modified = kFirstLastModified;
- create_info()->url_chain.push_back(GURL(kFirstURL));
- create_info()->mime_type = kMimeType;
-
- DownloadItemImpl* item = CreateDownloadItem();
- MockDownloadFile* download_file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
- EXPECT_CALL(*mock_delegate(), MockResumeInterruptedDownload(_, _));
- EXPECT_CALL(*download_file, Detach());
- item->DestinationObserverAsWeakPtr()->DestinationError(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR, 0,
- std::unique_ptr<crypto::SecureHash>());
- task_environment_.RunUntilIdle();
- EXPECT_EQ(download::DownloadItem::IN_PROGRESS, item->GetState());
-
- // Now change the create info. The changes should not cause the
- // download::DownloadItem to be updated.
- constexpr int kSecondResponseCode = 201;
- const char kSecondContentDisposition[] = "attachment; filename=bar";
- const char kSecondETag[] = "123";
- const char kSecondLastModified[] = "Today";
- const char kSecondURL[] = "http://example.com/another-download";
- const char kSecondMimeType[] = "text/html";
- create_info()->response_headers = CreateResponseHeaders(kSecondResponseCode);
- create_info()->content_disposition = kSecondContentDisposition;
- create_info()->etag = kSecondETag;
- create_info()->last_modified = kSecondLastModified;
- create_info()->url_chain.clear();
- create_info()->url_chain.push_back(GURL(kSecondURL));
- create_info()->mime_type = kSecondMimeType;
-
- DownloadTargetCallback target_callback;
- download_file = CallDownloadItemStart(item, &target_callback);
-
- ASSERT_TRUE(item->GetResponseHeaders());
- EXPECT_EQ(kSecondResponseCode, item->GetResponseHeaders()->response_code());
- EXPECT_EQ(kSecondContentDisposition, item->GetContentDisposition());
- EXPECT_EQ(kSecondETag, item->GetETag());
- EXPECT_EQ(kSecondLastModified, item->GetLastModifiedTime());
- EXPECT_EQ(kSecondURL, item->GetURL().spec());
- EXPECT_EQ(kSecondMimeType, item->GetMimeType());
-
- CleanupItem(item, download_file, download::DownloadItem::IN_PROGRESS);
-}
-
-// Ensure when strong validators changed on resumption, the received
-// slices should be cleared.
-TEST_F(DownloadItemTest, ClearReceivedSliceIfEtagChanged) {
- const char kFirstETag[] = "ABC";
- const char kSecondETag[] = "123";
- const download::DownloadItem::ReceivedSlices kReceivedSlice = {
- download::DownloadItem::ReceivedSlice(0, 10)};
- create_info()->etag = kFirstETag;
-
- DownloadItemImpl* item = CreateDownloadItem();
- MockDownloadFile* download_file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
-
- EXPECT_CALL(*mock_delegate(), MockResumeInterruptedDownload(_, _));
- EXPECT_CALL(*download_file, Detach());
-
- item->DestinationObserverAsWeakPtr()->DestinationUpdate(10, 100,
- kReceivedSlice);
- EXPECT_EQ(kReceivedSlice, item->GetReceivedSlices());
- EXPECT_EQ(10, item->GetReceivedBytes());
-
- item->DestinationObserverAsWeakPtr()->DestinationError(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR, 0,
- std::unique_ptr<crypto::SecureHash>());
- EXPECT_EQ(kReceivedSlice, item->GetReceivedSlices());
-
- task_environment_.RunUntilIdle();
-
- // Change the strong validator and resume the download, the received slices
- // should be cleared.
- create_info()->etag = kSecondETag;
- DownloadTargetCallback target_callback;
- download_file = CallDownloadItemStart(item, &target_callback);
- EXPECT_TRUE(item->GetReceivedSlices().empty());
- EXPECT_EQ(0, item->GetReceivedBytes());
-
- CleanupItem(item, download_file, download::DownloadItem::IN_PROGRESS);
-}
-
-// Test that resumption uses the final URL in a URL chain when resuming.
-TEST_F(DownloadItemTest, ResumeUsesFinalURL) {
- create_info()->save_info->prompt_for_save_location = false;
- create_info()->url_chain.clear();
- create_info()->url_chain.push_back(GURL("http://example.com/a"));
- create_info()->url_chain.push_back(GURL("http://example.com/b"));
- create_info()->url_chain.push_back(GURL("http://example.com/c"));
-
- DownloadItemImpl* item = CreateDownloadItem();
- TestDownloadItemObserver observer(item);
- MockDownloadFile* download_file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
-
- // Interrupt the download, using a continuable interrupt.
- EXPECT_CALL(*download_file, FullPath())
- .WillOnce(ReturnRefOfCopy(base::FilePath()));
- EXPECT_CALL(*download_file, Detach());
- EXPECT_CALL(*mock_delegate(),
- MockResumeInterruptedDownload(
- Property(&download::DownloadUrlParameters::url,
- GURL("http://example.com/c")),
- _))
- .Times(1);
- item->DestinationObserverAsWeakPtr()->DestinationError(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR, 1,
- std::unique_ptr<crypto::SecureHash>());
-
- // Test expectations verify that ResumeInterruptedDownload() is called (by way
- // of MockResumeInterruptedDownload) after the download is interrupted. But
- // the mock doesn't follow through with the resumption.
- // ResumeInterruptedDownload() being called is sufficient for verifying that
- // the resumption was triggered.
- task_environment_.RunUntilIdle();
-
- // The download is currently in RESUMING_INTERNAL, which maps to IN_PROGRESS.
- CleanupItem(item, nullptr, download::DownloadItem::IN_PROGRESS);
-}
-
-TEST_F(DownloadItemTest, DisplayName) {
- DownloadItemImpl* item = CreateDownloadItem();
- DownloadTargetCallback callback;
- MockDownloadFile* download_file = CallDownloadItemStart(item, &callback);
- base::FilePath target_path(
- base::FilePath(kDummyTargetPath).AppendASCII("foo.bar"));
- base::FilePath intermediate_path(target_path.InsertBeforeExtensionASCII("x"));
- EXPECT_EQ(FILE_PATH_LITERAL(""),
- item->GetFileNameToReportUser().value());
- EXPECT_CALL(*download_file, RenameAndUniquify(_, _))
- .WillOnce(ScheduleRenameAndUniquifyCallback(
- download::DOWNLOAD_INTERRUPT_REASON_NONE, intermediate_path));
- callback.Run(target_path,
- download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
- download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, intermediate_path,
- download::DOWNLOAD_INTERRUPT_REASON_NONE);
- task_environment_.RunUntilIdle();
- EXPECT_EQ(FILE_PATH_LITERAL("foo.bar"),
- item->GetFileNameToReportUser().value());
- item->SetDisplayName(base::FilePath(FILE_PATH_LITERAL("new.name")));
- EXPECT_EQ(FILE_PATH_LITERAL("new.name"),
- item->GetFileNameToReportUser().value());
- CleanupItem(item, download_file, download::DownloadItem::IN_PROGRESS);
-}
-
-// Test to make sure that Start method calls DF initialize properly.
-TEST_F(DownloadItemTest, Start) {
- MockDownloadFile* mock_download_file(new MockDownloadFile);
- std::unique_ptr<DownloadFile> download_file(mock_download_file);
- DownloadItemImpl* item = CreateDownloadItem();
- EXPECT_CALL(*mock_download_file, Initialize(_, _, _, _));
- std::unique_ptr<download::DownloadRequestHandleInterface> request_handle(
- new NiceMock<MockRequestHandle>);
- EXPECT_CALL(*mock_delegate(), DetermineDownloadTarget(item, _));
- item->Start(std::move(download_file), std::move(request_handle),
- *create_info());
- task_environment_.RunUntilIdle();
-
- CleanupItem(item, mock_download_file, download::DownloadItem::IN_PROGRESS);
-}
-
-// Download file and the request should be cancelled as a result of download
-// file initialization failing.
-TEST_F(DownloadItemTest, InitDownloadFileFails) {
- DownloadItemImpl* item = CreateDownloadItem();
- std::unique_ptr<MockDownloadFile> file = std::make_unique<MockDownloadFile>();
- std::unique_ptr<MockRequestHandle> request_handle =
- std::make_unique<MockRequestHandle>();
-
- base::HistogramTester histogram_tester;
- EXPECT_CALL(*file, Cancel());
- EXPECT_CALL(*request_handle, CancelRequest(_));
- EXPECT_CALL(*file, Initialize(_, _, _, _))
- .WillOnce(ScheduleCallbackWithParam(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED));
-
- DownloadTargetCallback download_target_callback;
- EXPECT_CALL(*mock_delegate(), DetermineDownloadTarget(item, _))
- .WillOnce(SaveArg<1>(&download_target_callback));
-
- item->Start(std::move(file), std::move(request_handle), *create_info());
- task_environment_.RunUntilIdle();
-
- download_target_callback.Run(
- base::FilePath(kDummyTargetPath),
- download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
- download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
- base::FilePath(kDummyIntermediatePath),
- download::DOWNLOAD_INTERRUPT_REASON_NONE);
- task_environment_.RunUntilIdle();
-
- EXPECT_EQ(download::DownloadItem::INTERRUPTED, item->GetState());
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED,
- item->GetLastReason());
- EXPECT_FALSE(item->GetTargetFilePath().empty());
- EXPECT_TRUE(item->GetFullPath().empty());
- histogram_tester.ExpectBucketCount(
- "Download.InterruptedReason",
- ToHistogramSample<download::DownloadInterruptReason>(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED),
- 1);
-}
-
-// Handling of downloads initiated via a failed request. In this case, Start()
-// will get called with a DownloadCreateInfo with a non-zero interrupt_reason.
-TEST_F(DownloadItemTest, StartFailedDownload) {
- base::HistogramTester histogram_tester;
- create_info()->result = download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED;
- DownloadItemImpl* item = CreateDownloadItem();
-
- // DownloadFile and DownloadRequestHandleInterface objects aren't created for
- // failed downloads.
- std::unique_ptr<DownloadFile> null_download_file;
- std::unique_ptr<download::DownloadRequestHandleInterface> null_request_handle;
- DownloadTargetCallback download_target_callback;
- EXPECT_CALL(*mock_delegate(), DetermineDownloadTarget(item, _))
- .WillOnce(SaveArg<1>(&download_target_callback));
- item->Start(std::move(null_download_file), std::move(null_request_handle),
- *create_info());
- EXPECT_EQ(download::DownloadItem::IN_PROGRESS, item->GetState());
- task_environment_.RunUntilIdle();
-
- // The DownloadItemImpl should attempt to determine a target path even if the
- // download was interrupted.
- ASSERT_FALSE(download_target_callback.is_null());
- ASSERT_EQ(download::DownloadItem::IN_PROGRESS, item->GetState());
- base::FilePath target_path(FILE_PATH_LITERAL("foo"));
- download_target_callback.Run(
- target_path, download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
- download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, target_path,
- download::DOWNLOAD_INTERRUPT_REASON_NONE);
- task_environment_.RunUntilIdle();
-
- // Interrupt reason carried in create info should be recorded.
- histogram_tester.ExpectBucketCount(
- "Download.InterruptedReason",
- ToHistogramSample<download::DownloadInterruptReason>(
- download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED),
- 1);
- EXPECT_EQ(target_path, item->GetTargetFilePath());
- CleanupItem(item, nullptr, download::DownloadItem::INTERRUPTED);
-}
-
-// Test that the delegate is invoked after the download file is renamed.
-TEST_F(DownloadItemTest, CallbackAfterRename) {
- DownloadItemImpl* item = CreateDownloadItem();
- DownloadTargetCallback callback;
- MockDownloadFile* download_file = CallDownloadItemStart(item, &callback);
- base::FilePath final_path(
- base::FilePath(kDummyTargetPath).AppendASCII("foo.bar"));
- base::FilePath intermediate_path(final_path.InsertBeforeExtensionASCII("x"));
- base::FilePath new_intermediate_path(
- final_path.InsertBeforeExtensionASCII("y"));
- EXPECT_CALL(*download_file, RenameAndUniquify(intermediate_path, _))
- .WillOnce(ScheduleRenameAndUniquifyCallback(
- download::DOWNLOAD_INTERRUPT_REASON_NONE, new_intermediate_path));
-
- callback.Run(final_path, download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
- download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, intermediate_path,
- download::DOWNLOAD_INTERRUPT_REASON_NONE);
- task_environment_.RunUntilIdle();
- // All the callbacks should have happened by now.
- ::testing::Mock::VerifyAndClearExpectations(download_file);
- mock_delegate()->VerifyAndClearExpectations();
-
- EXPECT_CALL(*mock_delegate(), ShouldCompleteDownload(item, _))
- .WillOnce(Return(true));
- EXPECT_CALL(*download_file, RenameAndAnnotate(final_path, _, _, _, _))
- .WillOnce(ScheduleRenameAndAnnotateCallback(
- download::DOWNLOAD_INTERRUPT_REASON_NONE, final_path));
- EXPECT_CALL(*download_file, FullPath())
- .WillOnce(ReturnRefOfCopy(base::FilePath()));
- EXPECT_CALL(*download_file, Detach());
- item->DestinationObserverAsWeakPtr()->DestinationCompleted(
- 0, std::unique_ptr<crypto::SecureHash>());
- task_environment_.RunUntilIdle();
- ::testing::Mock::VerifyAndClearExpectations(download_file);
- mock_delegate()->VerifyAndClearExpectations();
-}
-
-// Test that the delegate is invoked after the download file is renamed and the
-// download item is in an interrupted state.
-TEST_F(DownloadItemTest, CallbackAfterInterruptedRename) {
- DownloadItemImpl* item = CreateDownloadItem();
- DownloadTargetCallback callback;
- base::HistogramTester histogram_tester;
- MockDownloadFile* download_file = CallDownloadItemStart(item, &callback);
- base::FilePath final_path(
- base::FilePath(kDummyTargetPath).AppendASCII("foo.bar"));
- base::FilePath intermediate_path(final_path.InsertBeforeExtensionASCII("x"));
- base::FilePath new_intermediate_path(
- final_path.InsertBeforeExtensionASCII("y"));
- EXPECT_CALL(*download_file, RenameAndUniquify(intermediate_path, _))
- .WillOnce(ScheduleRenameAndUniquifyCallback(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
- new_intermediate_path));
- EXPECT_CALL(*download_file, Cancel())
- .Times(1);
-
- callback.Run(final_path, download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
- download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, intermediate_path,
- download::DOWNLOAD_INTERRUPT_REASON_NONE);
- task_environment_.RunUntilIdle();
- // All the callbacks should have happened by now.
- ::testing::Mock::VerifyAndClearExpectations(download_file);
- mock_delegate()->VerifyAndClearExpectations();
- histogram_tester.ExpectBucketCount(
- "Download.InterruptedReason",
- ToHistogramSample<download::DownloadInterruptReason>(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED),
- 1);
-}
-
-TEST_F(DownloadItemTest, Interrupted) {
- base::HistogramTester histogram_tester;
- DownloadItemImpl* item = CreateDownloadItem();
- MockDownloadFile* download_file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
-
- const download::DownloadInterruptReason reason(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED);
-
- // Confirm interrupt sets state properly.
- EXPECT_CALL(*download_file, Cancel());
- item->DestinationObserverAsWeakPtr()->DestinationError(
- reason, 0, std::unique_ptr<crypto::SecureHash>());
- task_environment_.RunUntilIdle();
- EXPECT_EQ(download::DownloadItem::INTERRUPTED, item->GetState());
- EXPECT_EQ(reason, item->GetLastReason());
-
- // Cancel should kill it.
- item->Cancel(true);
- EXPECT_EQ(download::DownloadItem::CANCELLED, item->GetState());
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED,
- item->GetLastReason());
-
- histogram_tester.ExpectBucketCount(
- "Download.InterruptedReason",
- ToHistogramSample<download::DownloadInterruptReason>(reason), 1);
-}
-
-// Destination errors that occur before the intermediate rename shouldn't cause
-// the download to be marked as interrupted until after the intermediate rename.
-TEST_F(DownloadItemTest, InterruptedBeforeIntermediateRename_Restart) {
- base::HistogramTester histogram_tester;
- DownloadItemImpl* item = CreateDownloadItem();
- DownloadTargetCallback callback;
- MockDownloadFile* download_file = CallDownloadItemStart(item, &callback);
- item->DestinationObserverAsWeakPtr()->DestinationError(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED, 0,
- std::unique_ptr<crypto::SecureHash>());
- ASSERT_EQ(download::DownloadItem::IN_PROGRESS, item->GetState());
-
- base::FilePath final_path(
- base::FilePath(kDummyTargetPath).AppendASCII("foo.bar"));
- base::FilePath intermediate_path(final_path.InsertBeforeExtensionASCII("x"));
- base::FilePath new_intermediate_path(
- final_path.InsertBeforeExtensionASCII("y"));
- EXPECT_CALL(*download_file, RenameAndUniquify(intermediate_path, _))
- .WillOnce(ScheduleRenameAndUniquifyCallback(
- download::DOWNLOAD_INTERRUPT_REASON_NONE, new_intermediate_path));
- EXPECT_CALL(*download_file, Cancel())
- .Times(1);
-
- callback.Run(final_path, download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
- download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, intermediate_path,
- download::DOWNLOAD_INTERRUPT_REASON_NONE);
- task_environment_.RunUntilIdle();
- // All the callbacks should have happened by now.
- ::testing::Mock::VerifyAndClearExpectations(download_file);
- mock_delegate()->VerifyAndClearExpectations();
- EXPECT_EQ(download::DownloadItem::INTERRUPTED, item->GetState());
- EXPECT_TRUE(item->GetFullPath().empty());
- EXPECT_EQ(final_path, item->GetTargetFilePath());
- histogram_tester.ExpectBucketCount(
- "Download.InterruptedReason",
- ToHistogramSample<download::DownloadInterruptReason>(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED),
- 1);
-}
-
-// As above. But if the download can be resumed by continuing, then the
-// intermediate path should be retained when the download is interrupted after
-// the intermediate rename succeeds.
-TEST_F(DownloadItemTest, InterruptedBeforeIntermediateRename_Continue) {
- base::HistogramTester histogram_tester;
- DownloadItemImpl* item = CreateDownloadItem();
- DownloadTargetCallback callback;
- MockDownloadFile* download_file = CallDownloadItemStart(item, &callback);
-
- // Write some data and interrupt with NETWORK_FAILED. The download shouldn't
- // transition to INTERRUPTED until the destination callback has been invoked.
- item->DestinationObserverAsWeakPtr()->DestinationError(
- download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED, 1,
- std::unique_ptr<crypto::SecureHash>());
- ASSERT_EQ(download::DownloadItem::IN_PROGRESS, item->GetState());
-
- base::FilePath final_path(
- base::FilePath(kDummyTargetPath).AppendASCII("foo.bar"));
- base::FilePath intermediate_path(final_path.InsertBeforeExtensionASCII("x"));
- base::FilePath new_intermediate_path(
- final_path.InsertBeforeExtensionASCII("y"));
- EXPECT_CALL(*download_file, RenameAndUniquify(intermediate_path, _))
- .WillOnce(ScheduleRenameAndUniquifyCallback(
- download::DOWNLOAD_INTERRUPT_REASON_NONE, new_intermediate_path));
- EXPECT_CALL(*download_file, FullPath())
- .WillOnce(ReturnRefOfCopy(base::FilePath(new_intermediate_path)));
- EXPECT_CALL(*download_file, Detach());
-
- callback.Run(final_path, download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
- download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, intermediate_path,
- download::DOWNLOAD_INTERRUPT_REASON_NONE);
- task_environment_.RunUntilIdle();
- // All the callbacks should have happened by now.
- ::testing::Mock::VerifyAndClearExpectations(download_file);
- mock_delegate()->VerifyAndClearExpectations();
- EXPECT_EQ(download::DownloadItem::INTERRUPTED, item->GetState());
- EXPECT_EQ(new_intermediate_path, item->GetFullPath());
- EXPECT_EQ(final_path, item->GetTargetFilePath());
- histogram_tester.ExpectBucketCount(
- "Download.InterruptedReason",
- ToHistogramSample<download::DownloadInterruptReason>(
- download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED),
- 1);
-}
-
-// As above. If the intermediate rename fails, then the interrupt reason should
-// be set to the file error and the intermediate path should be empty.
-TEST_F(DownloadItemTest, InterruptedBeforeIntermediateRename_Failed) {
- base::HistogramTester histogram_tester;
- DownloadItemImpl* item = CreateDownloadItem();
- DownloadTargetCallback callback;
- MockDownloadFile* download_file = CallDownloadItemStart(item, &callback);
- item->DestinationObserverAsWeakPtr()->DestinationError(
- download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED, 0,
- std::unique_ptr<crypto::SecureHash>());
- ASSERT_EQ(download::DownloadItem::IN_PROGRESS, item->GetState());
-
- base::FilePath final_path(
- base::FilePath(kDummyTargetPath).AppendASCII("foo.bar"));
- base::FilePath intermediate_path(final_path.InsertBeforeExtensionASCII("x"));
- base::FilePath new_intermediate_path(
- final_path.InsertBeforeExtensionASCII("y"));
- EXPECT_CALL(*download_file, RenameAndUniquify(intermediate_path, _))
- .WillOnce(ScheduleRenameAndUniquifyCallback(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
- new_intermediate_path));
- EXPECT_CALL(*download_file, Cancel())
- .Times(1);
-
- callback.Run(final_path, download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
- download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, intermediate_path,
- download::DOWNLOAD_INTERRUPT_REASON_NONE);
- task_environment_.RunUntilIdle();
- // All the callbacks should have happened by now.
- ::testing::Mock::VerifyAndClearExpectations(download_file);
- mock_delegate()->VerifyAndClearExpectations();
- EXPECT_EQ(download::DownloadItem::INTERRUPTED, item->GetState());
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
- item->GetLastReason());
- EXPECT_TRUE(item->GetFullPath().empty());
- EXPECT_EQ(final_path, item->GetTargetFilePath());
-
- // Rename error will overwrite the previous network interrupt reason.
- // TODO(xingliu): See if we should report both interrupted reasons or the
- // first one, see https://crbug.com/769040.
- histogram_tester.ExpectBucketCount(
- "Download.InterruptedReason",
- ToHistogramSample<download::DownloadInterruptReason>(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED),
- 1);
- histogram_tester.ExpectTotalCount("Download.InterruptedReason", 1);
-}
-
-TEST_F(DownloadItemTest, Canceled) {
- DownloadItemImpl* item = CreateDownloadItem();
- DownloadTargetCallback target_callback;
- MockDownloadFile* download_file =
- CallDownloadItemStart(item, &target_callback);
-
- // Confirm cancel sets state properly.
- EXPECT_CALL(*download_file, Cancel());
- item->Cancel(true);
- EXPECT_EQ(download::DownloadItem::CANCELLED, item->GetState());
-}
-
-TEST_F(DownloadItemTest, DownloadTargetDetermined_Cancel) {
- DownloadItemImpl* item = CreateDownloadItem();
- DownloadTargetCallback callback;
- MockDownloadFile* download_file = CallDownloadItemStart(item, &callback);
-
- EXPECT_CALL(*download_file, Cancel());
- callback.Run(base::FilePath(FILE_PATH_LITERAL("foo")),
- download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
- download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
- base::FilePath(FILE_PATH_LITERAL("bar")),
- download::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED);
- EXPECT_EQ(download::DownloadItem::CANCELLED, item->GetState());
-}
-
-TEST_F(DownloadItemTest, DownloadTargetDetermined_CancelWithEmptyName) {
- DownloadItemImpl* item = CreateDownloadItem();
- DownloadTargetCallback callback;
- MockDownloadFile* download_file = CallDownloadItemStart(item, &callback);
-
- EXPECT_CALL(*download_file, Cancel());
- callback.Run(base::FilePath(),
- download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
- download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, base::FilePath(),
- download::DOWNLOAD_INTERRUPT_REASON_NONE);
- EXPECT_EQ(download::DownloadItem::CANCELLED, item->GetState());
-}
-
-TEST_F(DownloadItemTest, DownloadTargetDetermined_Conflict) {
- DownloadItemImpl* item = CreateDownloadItem();
- DownloadTargetCallback callback;
- MockDownloadFile* download_file = CallDownloadItemStart(item, &callback);
- base::FilePath target_path(FILE_PATH_LITERAL("/foo/bar"));
-
- EXPECT_CALL(*download_file, Cancel());
- callback.Run(target_path,
- download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
- download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, target_path,
- download::DOWNLOAD_INTERRUPT_REASON_FILE_SAME_AS_SOURCE);
- EXPECT_EQ(download::DownloadItem::INTERRUPTED, item->GetState());
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_FILE_SAME_AS_SOURCE,
- item->GetLastReason());
-}
-
-TEST_F(DownloadItemTest, FileRemoved) {
- DownloadItemImpl* item = CreateDownloadItem();
-
- EXPECT_FALSE(item->GetFileExternallyRemoved());
- item->OnDownloadedFileRemoved();
- EXPECT_TRUE(item->GetFileExternallyRemoved());
-}
-
-TEST_F(DownloadItemTest, DestinationUpdate) {
- DownloadItemImpl* item = CreateDownloadItem();
- MockDownloadFile* file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
- base::WeakPtr<DownloadDestinationObserver> as_observer(
- item->DestinationObserverAsWeakPtr());
- TestDownloadItemObserver observer(item);
-
- EXPECT_EQ(0l, item->CurrentSpeed());
- EXPECT_EQ(0l, item->GetReceivedBytes());
- EXPECT_EQ(0l, item->GetTotalBytes());
- EXPECT_FALSE(observer.CheckAndResetDownloadUpdated());
- item->SetTotalBytes(100l);
- EXPECT_EQ(100l, item->GetTotalBytes());
-
- std::vector<download::DownloadItem::ReceivedSlice> received_slices;
- received_slices.emplace_back(0, 10);
- as_observer->DestinationUpdate(10, 20, received_slices);
- EXPECT_EQ(20l, item->CurrentSpeed());
- EXPECT_EQ(10l, item->GetReceivedBytes());
- EXPECT_EQ(100l, item->GetTotalBytes());
- EXPECT_EQ(received_slices, item->GetReceivedSlices());
- EXPECT_TRUE(observer.CheckAndResetDownloadUpdated());
-
- received_slices.emplace_back(200, 100);
- as_observer->DestinationUpdate(200, 20, received_slices);
- EXPECT_EQ(20l, item->CurrentSpeed());
- EXPECT_EQ(200l, item->GetReceivedBytes());
- EXPECT_EQ(0l, item->GetTotalBytes());
- EXPECT_EQ(received_slices, item->GetReceivedSlices());
- EXPECT_TRUE(observer.CheckAndResetDownloadUpdated());
-
- CleanupItem(item, file, download::DownloadItem::IN_PROGRESS);
-}
-
-TEST_F(DownloadItemTest, DestinationError_NoRestartRequired) {
- base::HistogramTester histogram_tester;
- DownloadItemImpl* item = CreateDownloadItem();
- MockDownloadFile* download_file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
- base::WeakPtr<DownloadDestinationObserver> as_observer(
- item->DestinationObserverAsWeakPtr());
- TestDownloadItemObserver observer(item);
-
- EXPECT_EQ(download::DownloadItem::IN_PROGRESS, item->GetState());
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE, item->GetLastReason());
- EXPECT_FALSE(observer.CheckAndResetDownloadUpdated());
-
- std::unique_ptr<crypto::SecureHash> hash(
- crypto::SecureHash::Create(crypto::SecureHash::SHA256));
- hash->Update(kTestData1, sizeof(kTestData1));
-
- EXPECT_CALL(*download_file, Detach());
- as_observer->DestinationError(
- download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED, 1, std::move(hash));
- mock_delegate()->VerifyAndClearExpectations();
- EXPECT_TRUE(observer.CheckAndResetDownloadUpdated());
- EXPECT_EQ(download::DownloadItem::INTERRUPTED, item->GetState());
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED,
- item->GetLastReason());
- EXPECT_EQ(
- std::string(std::begin(kHashOfTestData1), std::end(kHashOfTestData1)),
- item->GetHash());
- histogram_tester.ExpectBucketCount(
- "Download.InterruptedReason",
- ToHistogramSample<download::DownloadInterruptReason>(
- download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED),
- 1);
-}
-
-TEST_F(DownloadItemTest, DestinationError_RestartRequired) {
- base::HistogramTester histogram_tester;
- DownloadItemImpl* item = CreateDownloadItem();
- MockDownloadFile* download_file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
- base::WeakPtr<DownloadDestinationObserver> as_observer(
- item->DestinationObserverAsWeakPtr());
- TestDownloadItemObserver observer(item);
-
- EXPECT_EQ(download::DownloadItem::IN_PROGRESS, item->GetState());
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE, item->GetLastReason());
- EXPECT_FALSE(observer.CheckAndResetDownloadUpdated());
-
- std::unique_ptr<crypto::SecureHash> hash(
- crypto::SecureHash::Create(crypto::SecureHash::SHA256));
- hash->Update(kTestData1, sizeof(kTestData1));
-
- EXPECT_CALL(*download_file, Cancel());
- as_observer->DestinationError(download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
- 1, std::move(hash));
- mock_delegate()->VerifyAndClearExpectations();
- EXPECT_TRUE(observer.CheckAndResetDownloadUpdated());
- EXPECT_EQ(download::DownloadItem::INTERRUPTED, item->GetState());
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
- item->GetLastReason());
- EXPECT_EQ(std::string(), item->GetHash());
- histogram_tester.ExpectBucketCount(
- "Download.InterruptedReason",
- ToHistogramSample<download::DownloadInterruptReason>(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED),
- 1);
-}
-
-TEST_F(DownloadItemTest, DestinationCompleted) {
- base::HistogramTester histogram_tester;
- DownloadItemImpl* item = CreateDownloadItem();
- MockDownloadFile* download_file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
- base::WeakPtr<DownloadDestinationObserver> as_observer(
- item->DestinationObserverAsWeakPtr());
- TestDownloadItemObserver observer(item);
-
- EXPECT_EQ(download::DownloadItem::IN_PROGRESS, item->GetState());
- EXPECT_EQ("", item->GetHash());
- EXPECT_FALSE(item->AllDataSaved());
- EXPECT_FALSE(observer.CheckAndResetDownloadUpdated());
-
- as_observer->DestinationUpdate(
- 10, 20, std::vector<download::DownloadItem::ReceivedSlice>());
- EXPECT_TRUE(observer.CheckAndResetDownloadUpdated());
- EXPECT_FALSE(observer.CheckAndResetDownloadUpdated()); // Confirm reset.
- EXPECT_EQ(download::DownloadItem::IN_PROGRESS, item->GetState());
- EXPECT_EQ("", item->GetHash());
- EXPECT_FALSE(item->AllDataSaved());
-
- std::unique_ptr<crypto::SecureHash> hash(
- crypto::SecureHash::Create(crypto::SecureHash::SHA256));
- hash->Update(kTestData1, sizeof(kTestData1));
-
- EXPECT_CALL(*mock_delegate(), ShouldCompleteDownload(_, _));
- as_observer->DestinationCompleted(10, std::move(hash));
- mock_delegate()->VerifyAndClearExpectations();
- EXPECT_EQ(download::DownloadItem::IN_PROGRESS, item->GetState());
- EXPECT_TRUE(observer.CheckAndResetDownloadUpdated());
- EXPECT_EQ(
- std::string(std::begin(kHashOfTestData1), std::end(kHashOfTestData1)),
- item->GetHash());
- EXPECT_TRUE(item->AllDataSaved());
-
- // Even though the download::DownloadItem receives a DestinationCompleted()
- // event, target determination hasn't completed, hence the download item is
- // stuck in TARGET_PENDING.
- CleanupItem(item, download_file, download::DownloadItem::IN_PROGRESS);
-
- histogram_tester.ExpectTotalCount("Download.InterruptedReason", 0);
-}
-
-TEST_F(DownloadItemTest, EnabledActionsForNormalDownload) {
- DownloadItemImpl* item = CreateDownloadItem();
- MockDownloadFile* download_file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
-
- // InProgress
- ASSERT_EQ(download::DownloadItem::IN_PROGRESS, item->GetState());
- ASSERT_FALSE(item->GetTargetFilePath().empty());
- EXPECT_TRUE(item->CanShowInFolder());
- EXPECT_TRUE(item->CanOpenDownload());
-
- // Complete
- EXPECT_CALL(*download_file, RenameAndAnnotate(_, _, _, _, _))
- .WillOnce(ScheduleRenameAndAnnotateCallback(
- download::DOWNLOAD_INTERRUPT_REASON_NONE,
- base::FilePath(kDummyTargetPath)));
- EXPECT_CALL(*mock_delegate(), ShouldCompleteDownload(item, _))
- .WillOnce(Return(true));
- EXPECT_CALL(*download_file, FullPath())
- .WillOnce(ReturnRefOfCopy(base::FilePath()));
- EXPECT_CALL(*download_file, Detach());
- item->DestinationObserverAsWeakPtr()->DestinationCompleted(
- 0, std::unique_ptr<crypto::SecureHash>());
- task_environment_.RunUntilIdle();
-
- ASSERT_EQ(download::DownloadItem::COMPLETE, item->GetState());
- EXPECT_TRUE(item->CanShowInFolder());
- EXPECT_TRUE(item->CanOpenDownload());
-}
-
-TEST_F(DownloadItemTest, EnabledActionsForTemporaryDownload) {
- // A download created with a non-empty FilePath is considered a temporary
- // download.
- create_info()->save_info->file_path = base::FilePath(kDummyTargetPath);
- DownloadItemImpl* item = CreateDownloadItem();
- MockDownloadFile* download_file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
-
- // InProgress Temporary
- ASSERT_EQ(download::DownloadItem::IN_PROGRESS, item->GetState());
- ASSERT_FALSE(item->GetTargetFilePath().empty());
- ASSERT_TRUE(item->IsTemporary());
- EXPECT_FALSE(item->CanShowInFolder());
- EXPECT_FALSE(item->CanOpenDownload());
-
- // Complete Temporary
- EXPECT_CALL(*mock_delegate(), ShouldCompleteDownload(item, _))
- .WillOnce(Return(true));
- EXPECT_CALL(*download_file, RenameAndAnnotate(_, _, _, _, _))
- .WillOnce(ScheduleRenameAndAnnotateCallback(
- download::DOWNLOAD_INTERRUPT_REASON_NONE,
- base::FilePath(kDummyTargetPath)));
- EXPECT_CALL(*download_file, FullPath())
- .WillOnce(ReturnRefOfCopy(base::FilePath()));
- EXPECT_CALL(*download_file, Detach());
- item->DestinationObserverAsWeakPtr()->DestinationCompleted(
- 0, std::unique_ptr<crypto::SecureHash>());
- task_environment_.RunUntilIdle();
-
- ASSERT_EQ(download::DownloadItem::COMPLETE, item->GetState());
- EXPECT_FALSE(item->CanShowInFolder());
- EXPECT_FALSE(item->CanOpenDownload());
-}
-
-TEST_F(DownloadItemTest, EnabledActionsForInterruptedDownload) {
- DownloadItemImpl* item = CreateDownloadItem();
- MockDownloadFile* download_file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
-
- EXPECT_CALL(*download_file, Cancel());
- item->DestinationObserverAsWeakPtr()->DestinationError(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED, 0,
- std::unique_ptr<crypto::SecureHash>());
- task_environment_.RunUntilIdle();
-
- ASSERT_EQ(download::DownloadItem::INTERRUPTED, item->GetState());
- ASSERT_FALSE(item->GetTargetFilePath().empty());
- EXPECT_FALSE(item->CanShowInFolder());
- EXPECT_TRUE(item->CanOpenDownload());
-}
-
-TEST_F(DownloadItemTest, EnabledActionsForCancelledDownload) {
- DownloadItemImpl* item = CreateDownloadItem();
- MockDownloadFile* download_file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
-
- EXPECT_CALL(*download_file, Cancel());
- item->Cancel(true);
- task_environment_.RunUntilIdle();
-
- ASSERT_EQ(download::DownloadItem::CANCELLED, item->GetState());
- EXPECT_FALSE(item->CanShowInFolder());
- EXPECT_FALSE(item->CanOpenDownload());
-}
-
-// Test various aspects of the delegate completion blocker.
-
-// Just allowing completion.
-TEST_F(DownloadItemTest, CompleteDelegate_ReturnTrue) {
- // Test to confirm that if we have a callback that returns true,
- // we complete immediately.
- DownloadItemImpl* item = CreateDownloadItem();
- MockDownloadFile* download_file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
-
- // Drive the delegate interaction.
- EXPECT_CALL(*mock_delegate(), ShouldCompleteDownload(item, _))
- .WillOnce(Return(true));
- item->DestinationObserverAsWeakPtr()->DestinationCompleted(
- 0, std::unique_ptr<crypto::SecureHash>());
- EXPECT_EQ(download::DownloadItem::IN_PROGRESS, item->GetState());
- EXPECT_FALSE(item->IsDangerous());
-
- // Make sure the download can complete.
- EXPECT_CALL(*download_file,
- RenameAndAnnotate(base::FilePath(kDummyTargetPath), _, _, _, _))
- .WillOnce(ScheduleRenameAndAnnotateCallback(
- download::DOWNLOAD_INTERRUPT_REASON_NONE,
- base::FilePath(kDummyTargetPath)));
- EXPECT_CALL(*mock_delegate(), ShouldOpenDownload(item, _))
- .WillOnce(Return(true));
- EXPECT_CALL(*download_file, FullPath())
- .WillOnce(ReturnRefOfCopy(base::FilePath()));
- EXPECT_CALL(*download_file, Detach());
- task_environment_.RunUntilIdle();
- EXPECT_EQ(download::DownloadItem::COMPLETE, item->GetState());
-}
-
-// Just delaying completion.
-TEST_F(DownloadItemTest, CompleteDelegate_BlockOnce) {
- // Test to confirm that if we have a callback that returns true,
- // we complete immediately.
-
- DownloadItemImpl* item = CreateDownloadItem();
- MockDownloadFile* download_file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
-
- base::Closure delegate_callback;
- base::Closure copy_delegate_callback;
- EXPECT_CALL(*mock_delegate(), ShouldCompleteDownload(item, _))
- .WillOnce(DoAll(SaveArg<1>(&delegate_callback),
- Return(false)))
- .WillOnce(Return(true));
- item->DestinationObserverAsWeakPtr()->DestinationCompleted(
- 0, std::unique_ptr<crypto::SecureHash>());
- ASSERT_FALSE(delegate_callback.is_null());
- copy_delegate_callback = delegate_callback;
- delegate_callback.Reset();
- EXPECT_EQ(download::DownloadItem::IN_PROGRESS, item->GetState());
- copy_delegate_callback.Run();
- ASSERT_TRUE(delegate_callback.is_null());
- EXPECT_EQ(download::DownloadItem::IN_PROGRESS, item->GetState());
- EXPECT_FALSE(item->IsDangerous());
-
- // Make sure the download can complete.
- EXPECT_CALL(*download_file,
- RenameAndAnnotate(base::FilePath(kDummyTargetPath), _, _, _, _))
- .WillOnce(ScheduleRenameAndAnnotateCallback(
- download::DOWNLOAD_INTERRUPT_REASON_NONE,
- base::FilePath(kDummyTargetPath)));
- EXPECT_CALL(*mock_delegate(), ShouldOpenDownload(item, _))
- .WillOnce(Return(true));
- EXPECT_CALL(*download_file, FullPath())
- .WillOnce(ReturnRefOfCopy(base::FilePath()));
- EXPECT_CALL(*download_file, Detach());
- task_environment_.RunUntilIdle();
- EXPECT_EQ(download::DownloadItem::COMPLETE, item->GetState());
-}
-
-// Delay and set danger.
-TEST_F(DownloadItemTest, CompleteDelegate_SetDanger) {
- // Test to confirm that if we have a callback that returns true,
- // we complete immediately.
- DownloadItemImpl* item = CreateDownloadItem();
- MockDownloadFile* download_file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
-
- // Drive the delegate interaction.
- base::Closure delegate_callback;
- base::Closure copy_delegate_callback;
- EXPECT_CALL(*mock_delegate(), ShouldCompleteDownload(item, _))
- .WillOnce(DoAll(SaveArg<1>(&delegate_callback),
- Return(false)))
- .WillOnce(Return(true));
- item->DestinationObserverAsWeakPtr()->DestinationCompleted(
- 0, std::unique_ptr<crypto::SecureHash>());
- ASSERT_FALSE(delegate_callback.is_null());
- copy_delegate_callback = delegate_callback;
- delegate_callback.Reset();
- EXPECT_FALSE(item->IsDangerous());
- item->OnContentCheckCompleted(download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE,
- download::DOWNLOAD_INTERRUPT_REASON_NONE);
- EXPECT_EQ(download::DownloadItem::IN_PROGRESS, item->GetState());
- copy_delegate_callback.Run();
- ASSERT_TRUE(delegate_callback.is_null());
- EXPECT_EQ(download::DownloadItem::IN_PROGRESS, item->GetState());
- EXPECT_TRUE(item->IsDangerous());
-
- // Make sure the download doesn't complete until we've validated it.
- EXPECT_CALL(*download_file,
- RenameAndAnnotate(base::FilePath(kDummyTargetPath), _, _, _, _))
- .WillOnce(ScheduleRenameAndAnnotateCallback(
- download::DOWNLOAD_INTERRUPT_REASON_NONE,
- base::FilePath(kDummyTargetPath)));
- EXPECT_CALL(*mock_delegate(), ShouldOpenDownload(item, _))
- .WillOnce(Return(true));
- EXPECT_CALL(*download_file, FullPath())
- .WillOnce(ReturnRefOfCopy(base::FilePath()));
- EXPECT_CALL(*download_file, Detach());
- task_environment_.RunUntilIdle();
- EXPECT_EQ(download::DownloadItem::IN_PROGRESS, item->GetState());
- EXPECT_TRUE(item->IsDangerous());
-
- item->ValidateDangerousDownload();
- EXPECT_EQ(download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED,
- item->GetDangerType());
- task_environment_.RunUntilIdle();
- EXPECT_EQ(download::DownloadItem::COMPLETE, item->GetState());
-}
-
-// Just delaying completion twice.
-TEST_F(DownloadItemTest, CompleteDelegate_BlockTwice) {
- // Test to confirm that if we have a callback that returns true,
- // we complete immediately.
- DownloadItemImpl* item = CreateDownloadItem();
- MockDownloadFile* download_file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
-
- // Drive the delegate interaction.
- base::Closure delegate_callback;
- base::Closure copy_delegate_callback;
- EXPECT_CALL(*mock_delegate(), ShouldCompleteDownload(item, _))
- .WillOnce(DoAll(SaveArg<1>(&delegate_callback),
- Return(false)))
- .WillOnce(DoAll(SaveArg<1>(&delegate_callback),
- Return(false)))
- .WillOnce(Return(true));
- item->DestinationObserverAsWeakPtr()->DestinationCompleted(
- 0, std::unique_ptr<crypto::SecureHash>());
- ASSERT_FALSE(delegate_callback.is_null());
- copy_delegate_callback = delegate_callback;
- delegate_callback.Reset();
- EXPECT_EQ(download::DownloadItem::IN_PROGRESS, item->GetState());
- copy_delegate_callback.Run();
- ASSERT_FALSE(delegate_callback.is_null());
- copy_delegate_callback = delegate_callback;
- delegate_callback.Reset();
- EXPECT_EQ(download::DownloadItem::IN_PROGRESS, item->GetState());
- copy_delegate_callback.Run();
- ASSERT_TRUE(delegate_callback.is_null());
- EXPECT_EQ(download::DownloadItem::IN_PROGRESS, item->GetState());
- EXPECT_FALSE(item->IsDangerous());
-
- // Make sure the download can complete.
- EXPECT_CALL(*download_file,
- RenameAndAnnotate(base::FilePath(kDummyTargetPath), _, _, _, _))
- .WillOnce(ScheduleRenameAndAnnotateCallback(
- download::DOWNLOAD_INTERRUPT_REASON_NONE,
- base::FilePath(kDummyTargetPath)));
- EXPECT_CALL(*mock_delegate(), ShouldOpenDownload(item, _))
- .WillOnce(Return(true));
- EXPECT_CALL(*download_file, FullPath())
- .WillOnce(ReturnRefOfCopy(base::FilePath()));
- EXPECT_CALL(*download_file, Detach());
- task_environment_.RunUntilIdle();
- EXPECT_EQ(download::DownloadItem::COMPLETE, item->GetState());
-}
-
-TEST_F(DownloadItemTest, StealDangerousDownloadAndDiscard) {
- DownloadItemImpl* item = CreateDownloadItem();
- MockDownloadFile* download_file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE);
- ASSERT_TRUE(item->IsDangerous());
- base::FilePath full_path(FILE_PATH_LITERAL("foo.txt"));
- base::FilePath returned_path;
-
- EXPECT_CALL(*download_file, FullPath()).WillOnce(ReturnRefOfCopy(full_path));
- EXPECT_CALL(*download_file, Detach());
- EXPECT_CALL(*mock_delegate(), DownloadRemoved(_));
- base::WeakPtrFactory<DownloadItemTest> weak_ptr_factory(this);
- item->OnAllDataSaved(0, std::unique_ptr<crypto::SecureHash>());
- item->StealDangerousDownload(
- true, // delete_file_after_feedback
- base::Bind(&DownloadItemTest::OnDownloadFileAcquired,
- weak_ptr_factory.GetWeakPtr(),
- base::Unretained(&returned_path)));
- task_environment_.RunUntilIdle();
- EXPECT_EQ(full_path, returned_path);
-}
-
-TEST_F(DownloadItemTest, StealDangerousDownloadAndKeep) {
- DownloadItemImpl* item = CreateDownloadItem();
- MockDownloadFile* download_file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE);
- ASSERT_TRUE(item->IsDangerous());
- base::FilePath full_path(FILE_PATH_LITERAL("foo.txt"));
- base::FilePath returned_path;
- EXPECT_CALL(*download_file, FullPath()).WillOnce(ReturnRefOfCopy(full_path));
- base::WeakPtrFactory<DownloadItemTest> weak_ptr_factory(this);
- item->OnAllDataSaved(0, std::unique_ptr<crypto::SecureHash>());
- item->StealDangerousDownload(
- false, // delete_file_after_feedback
- base::Bind(&DownloadItemTest::OnDownloadFileAcquired,
- weak_ptr_factory.GetWeakPtr(),
- base::Unretained(&returned_path)));
- task_environment_.RunUntilIdle();
- EXPECT_NE(full_path, returned_path);
- CleanupItem(item, download_file, download::DownloadItem::IN_PROGRESS);
-}
-
-TEST_F(DownloadItemTest, StealInterruptedContinuableDangerousDownload) {
- base::FilePath returned_path;
- DownloadItemImpl* item = CreateDownloadItem();
- MockDownloadFile* download_file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE);
- base::FilePath full_path = item->GetFullPath();
- EXPECT_FALSE(full_path.empty());
- EXPECT_CALL(*download_file, FullPath()).WillOnce(ReturnRefOfCopy(full_path));
- EXPECT_CALL(*download_file, Detach());
- item->DestinationObserverAsWeakPtr()->DestinationError(
- download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED, 1,
- std::unique_ptr<crypto::SecureHash>());
- ASSERT_TRUE(item->IsDangerous());
-
- EXPECT_CALL(*mock_delegate(), DownloadRemoved(_));
- base::WeakPtrFactory<DownloadItemTest> weak_ptr_factory(this);
- item->OnAllDataSaved(0, std::unique_ptr<crypto::SecureHash>());
- item->StealDangerousDownload(
- true, base::Bind(&DownloadItemTest::OnDownloadFileAcquired,
- weak_ptr_factory.GetWeakPtr(),
- base::Unretained(&returned_path)));
- task_environment_.RunUntilIdle();
- EXPECT_EQ(full_path, returned_path);
-}
-
-TEST_F(DownloadItemTest, StealInterruptedNonContinuableDangerousDownload) {
- base::FilePath returned_path;
- DownloadItemImpl* item = CreateDownloadItem();
- MockDownloadFile* download_file =
- DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE);
- EXPECT_CALL(*download_file, Cancel());
- item->DestinationObserverAsWeakPtr()->DestinationError(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED, 1,
- std::unique_ptr<crypto::SecureHash>());
- ASSERT_TRUE(item->IsDangerous());
-
- EXPECT_CALL(*mock_delegate(), DownloadRemoved(_));
- base::WeakPtrFactory<DownloadItemTest> weak_ptr_factory(this);
- item->OnAllDataSaved(0, std::unique_ptr<crypto::SecureHash>());
- item->StealDangerousDownload(
- true, base::Bind(&DownloadItemTest::OnDownloadFileAcquired,
- weak_ptr_factory.GetWeakPtr(),
- base::Unretained(&returned_path)));
- task_environment_.RunUntilIdle();
- EXPECT_TRUE(returned_path.empty());
-}
-
-namespace {
-
-// The DownloadItemDestinationUpdateRaceTest fixture (defined below) is used to
-// test for race conditions between download destination events received via the
-// DownloadDestinationObserver interface, and the target determination logic.
-//
-// The general control flow for DownloadItemImpl looks like this:
-//
-// * Start() called, which in turn calls DownloadFile::Initialize().
-//
-// Even though OnDownloadFileInitialized hasn't been called, there could now
-// be destination observer calls queued prior to the task that calls
-// OnDownloadFileInitialized. Let's call this point in the workflow "A".
-//
-// * DownloadItemImpl::OnDownloadFileInitialized() called.
-//
-// * Assuming the result is successful, DII now invokes the delegate's
-// DetermineDownloadTarget method.
-//
-// At this point DonwnloadFile acts as the source of
-// DownloadDestinationObserver events, and may invoke callbacks. Let's call
-// this point in the workflow "B".
-//
-// * DII::OnDownloadTargetDetermined() invoked after delegate is done with
-// target determination.
-//
-// * DII attempts to rename the DownloadFile to its intermediate name.
-//
-// More DownloadDestinationObserver events can happen here. Let's call this
-// point in the workflow "C".
-//
-// * DII::OnDownloadRenamedToIntermediateName() invoked. Assuming all went well,
-// DII is now in IN_PROGRESS state.
-//
-// More DownloadDestinationObserver events can happen here. Let's call this
-// point in the workflow "D".
-//
-// The DownloadItemDestinationUpdateRaceTest works by generating various
-// combinations of DownloadDestinationObserver events that might occur at the
-// points "A", "B", "C", and "D" above. Each test in this suite cranks a
-// DownloadItemImpl through the states listed above and invokes the events
-// assigned to each position.
-
-// This type of callback represents a call to a DownloadDestinationObserver
-// method that's missing the DownloadDestinationObserver object. Currying this
-// way allows us to bind a call prior to constructing the object on which the
-// method would be invoked. This is necessary since we are going to construct
-// various permutations of observer calls that will then be applied to a
-// download::DownloadItem in a state as yet undetermined.
-using CurriedObservation =
- base::Callback<void(base::WeakPtr<DownloadDestinationObserver>)>;
-
-// A list of observations that are to be made during some event in the
-// DownloadItemImpl control flow. Ordering of the observations is significant.
-using ObservationList = base::circular_deque<CurriedObservation>;
-
-// An ordered list of events.
-//
-// An "event" in this context refers to some stage in the DownloadItemImpl's
-// workflow described as "A", "B", "C", or "D" above. An EventList is expected
-// to always contains kEventCount events.
-using EventList = base::circular_deque<ObservationList>;
-
-// Number of events in an EventList. This is always 4 for now as described
-// above.
-const int kEventCount = 4;
-
-// The following functions help us with currying the calls to
-// DownloadDestinationObserver. If std::bind was allowed along with
-// std::placeholders, it is possible to avoid these functions, but currently
-// Chromium doesn't allow using std::bind for good reasons.
-void DestinationUpdateInvoker(
- int64_t bytes_so_far,
- int64_t bytes_per_sec,
- base::WeakPtr<DownloadDestinationObserver> observer) {
- DVLOG(20) << "DestinationUpdate(bytes_so_far:" << bytes_so_far
- << ", bytes_per_sec:" << bytes_per_sec
- << ") observer:" << !!observer;
- if (observer) {
- observer->DestinationUpdate(
- bytes_so_far, bytes_per_sec,
- std::vector<download::DownloadItem::ReceivedSlice>());
- }
-}
-
-void DestinationErrorInvoker(
- download::DownloadInterruptReason reason,
- int64_t bytes_so_far,
- base::WeakPtr<DownloadDestinationObserver> observer) {
- DVLOG(20) << "DestinationError(reason:"
- << DownloadInterruptReasonToString(reason)
- << ", bytes_so_far:" << bytes_so_far << ") observer:" << !!observer;
- if (observer)
- observer->DestinationError(reason, bytes_so_far,
- std::unique_ptr<crypto::SecureHash>());
-}
-
-void DestinationCompletedInvoker(
- int64_t total_bytes,
- base::WeakPtr<DownloadDestinationObserver> observer) {
- DVLOG(20) << "DestinationComplete(total_bytes:" << total_bytes
- << ") observer:" << !!observer;
- if (observer)
- observer->DestinationCompleted(total_bytes,
- std::unique_ptr<crypto::SecureHash>());
-}
-
-// Given a set of observations (via the range |begin|..|end|), constructs a list
-// of EventLists such that:
-//
-// * There are exactly |event_count| ObservationSets in each EventList.
-//
-// * Each ObservationList in each EventList contains a subrange (possibly empty)
-// of observations from the input range, in the same order as the input range.
-//
-// * The ordering of the ObservationList in each EventList is such that all
-// observations in one ObservationList occur earlier than all observations in
-// an ObservationList that follows it.
-//
-// * The list of EventLists together describe all the possible ways in which the
-// list of observations can be distributed into |event_count| events.
-std::vector<EventList> DistributeObservationsIntoEvents(
- const std::vector<CurriedObservation>::iterator begin,
- const std::vector<CurriedObservation>::iterator end,
- int event_count) {
- std::vector<EventList> all_event_lists;
- for (auto partition = begin;; ++partition) {
- ObservationList first_group_of_observations(begin, partition);
- if (event_count > 1) {
- std::vector<EventList> list_of_subsequent_events =
- DistributeObservationsIntoEvents(partition, end, event_count - 1);
- for (const auto& subsequent_events : list_of_subsequent_events) {
- EventList event_list;
- event_list = subsequent_events;
- event_list.push_front(first_group_of_observations);
- all_event_lists.push_back(event_list);
- }
- } else {
- EventList event_list;
- event_list.push_front(first_group_of_observations);
- all_event_lists.push_back(event_list);
- }
- if (partition == end)
- break;
- }
- return all_event_lists;
-}
-
-// For the purpose of this tests, we are only concerned with 3 events:
-//
-// 1. Immediately after the DownloadFile is initialized.
-// 2. Immediately after the DownloadTargetCallback is invoked.
-// 3. Immediately after the intermediate file is renamed.
-//
-// We are going to take a couple of sets of DownloadDestinationObserver events
-// and distribute them into the three events described above. And then we are
-// going to invoke the observations while a DownloadItemImpl is carefully
-// stepped through its stages.
-
-std::vector<EventList> GenerateSuccessfulEventLists() {
- std::vector<CurriedObservation> all_observations;
- all_observations.push_back(base::Bind(&DestinationUpdateInvoker, 100, 100));
- all_observations.push_back(base::Bind(&DestinationUpdateInvoker, 200, 100));
- all_observations.push_back(base::Bind(&DestinationCompletedInvoker, 200));
- return DistributeObservationsIntoEvents(all_observations.begin(),
- all_observations.end(), kEventCount);
-}
-
-std::vector<EventList> GenerateFailingEventLists() {
- std::vector<CurriedObservation> all_observations;
- all_observations.push_back(base::Bind(&DestinationUpdateInvoker, 100, 100));
- all_observations.push_back(
- base::Bind(&DestinationErrorInvoker,
- download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED, 100));
- return DistributeObservationsIntoEvents(all_observations.begin(),
- all_observations.end(), kEventCount);
-}
-
-class DownloadItemDestinationUpdateRaceTest
- : public DownloadItemTest,
- public ::testing::WithParamInterface<EventList> {
- public:
- DownloadItemDestinationUpdateRaceTest()
- : DownloadItemTest(),
- item_(CreateDownloadItem()),
- file_(new ::testing::StrictMock<MockDownloadFile>()),
- request_handle_(new ::testing::StrictMock<MockRequestHandle>()) {
- DCHECK_EQ(GetParam().size(), static_cast<unsigned>(kEventCount));
- }
-
- protected:
- const ObservationList& PreInitializeFileObservations() {
- return GetParam().front();
- }
- const ObservationList& PostInitializeFileObservations() {
- return *(GetParam().begin() + 1);
- }
- const ObservationList& PostTargetDeterminationObservations() {
- return *(GetParam().begin() + 2);
- }
- const ObservationList& PostIntermediateRenameObservations() {
- return *(GetParam().begin() + 3);
- }
-
- // Apply all the observations in |observations| to |observer|, but do so
- // asynchronously so that the events are applied in order behind any tasks
- // that are already scheduled.
- void ScheduleObservations(
- const ObservationList& observations,
- base::WeakPtr<DownloadDestinationObserver> observer) {
- for (const auto action : observations)
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
- base::BindOnce(action, observer));
- }
-
- DownloadItemImpl* item_;
- std::unique_ptr<MockDownloadFile> file_;
- std::unique_ptr<MockRequestHandle> request_handle_;
-
- base::queue<base::Closure> successful_update_events_;
- base::queue<base::Closure> failing_update_events_;
-};
-
-INSTANTIATE_TEST_CASE_P(Success,
- DownloadItemDestinationUpdateRaceTest,
- ::testing::ValuesIn(GenerateSuccessfulEventLists()));
-
-INSTANTIATE_TEST_CASE_P(Failure,
- DownloadItemDestinationUpdateRaceTest,
- ::testing::ValuesIn(GenerateFailingEventLists()));
-
-} // namespace
-
-// Run through the DII workflow but the embedder cancels the download at target
-// determination.
-TEST_P(DownloadItemDestinationUpdateRaceTest, DownloadCancelledByUser) {
- // Expect that the download file and the request will be cancelled as a
- // result.
- EXPECT_CALL(*file_, Cancel());
- EXPECT_CALL(*request_handle_, CancelRequest(_));
-
- DownloadFile::InitializeCallback initialize_callback;
- EXPECT_CALL(*file_, Initialize(_, _, _, _))
- .WillOnce(SaveArg<0>(&initialize_callback));
- item_->Start(std::move(file_), std::move(request_handle_), *create_info());
- task_environment_.RunUntilIdle();
-
- base::WeakPtr<DownloadDestinationObserver> destination_observer =
- item_->DestinationObserverAsWeakPtr();
-
- ScheduleObservations(PreInitializeFileObservations(), destination_observer);
- task_environment_.RunUntilIdle();
-
- DownloadTargetCallback target_callback;
- EXPECT_CALL(*mock_delegate(), DetermineDownloadTarget(_, _))
- .WillOnce(SaveArg<1>(&target_callback));
- ScheduleObservations(PostInitializeFileObservations(), destination_observer);
- initialize_callback.Run(download::DOWNLOAD_INTERRUPT_REASON_NONE);
-
- task_environment_.RunUntilIdle();
-
- ASSERT_FALSE(target_callback.is_null());
- ScheduleObservations(PostTargetDeterminationObservations(),
- destination_observer);
- target_callback.Run(
- base::FilePath(), download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
- download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, base::FilePath(),
- download::DOWNLOAD_INTERRUPT_REASON_NONE);
- EXPECT_EQ(download::DownloadItem::CANCELLED, item_->GetState());
- task_environment_.RunUntilIdle();
-}
-
-// Run through the DII workflow, but the intermediate rename fails.
-TEST_P(DownloadItemDestinationUpdateRaceTest, IntermediateRenameFails) {
- // Expect that the download file and the request will be cancelled as a
- // result.
- EXPECT_CALL(*file_, Cancel());
- EXPECT_CALL(*request_handle_, CancelRequest(_));
-
- // Intermediate rename loop is not used immediately, but let's set up the
- // DownloadFile expectations since we are about to transfer its ownership to
- // the download::DownloadItem.
- DownloadFile::RenameCompletionCallback intermediate_rename_callback;
- EXPECT_CALL(*file_, RenameAndUniquify(_, _))
- .WillOnce(SaveArg<1>(&intermediate_rename_callback));
-
- DownloadFile::InitializeCallback initialize_callback;
- EXPECT_CALL(*file_, Initialize(_, _, _, _))
- .WillOnce(SaveArg<0>(&initialize_callback));
-
- item_->Start(std::move(file_), std::move(request_handle_), *create_info());
- task_environment_.RunUntilIdle();
-
- base::WeakPtr<DownloadDestinationObserver> destination_observer =
- item_->DestinationObserverAsWeakPtr();
-
- ScheduleObservations(PreInitializeFileObservations(), destination_observer);
- task_environment_.RunUntilIdle();
-
- DownloadTargetCallback target_callback;
- EXPECT_CALL(*mock_delegate(), DetermineDownloadTarget(_, _))
- .WillOnce(SaveArg<1>(&target_callback));
- ScheduleObservations(PostInitializeFileObservations(), destination_observer);
- initialize_callback.Run(download::DOWNLOAD_INTERRUPT_REASON_NONE);
-
- task_environment_.RunUntilIdle();
- ASSERT_FALSE(target_callback.is_null());
-
- ScheduleObservations(PostTargetDeterminationObservations(),
- destination_observer);
- target_callback.Run(base::FilePath(kDummyTargetPath),
- download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
- download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
- base::FilePath(kDummyIntermediatePath),
- download::DOWNLOAD_INTERRUPT_REASON_NONE);
-
- task_environment_.RunUntilIdle();
- ASSERT_FALSE(intermediate_rename_callback.is_null());
-
- ScheduleObservations(PostIntermediateRenameObservations(),
- destination_observer);
- intermediate_rename_callback.Run(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED, base::FilePath());
- task_environment_.RunUntilIdle();
-
- EXPECT_EQ(download::DownloadItem::INTERRUPTED, item_->GetState());
-}
-
-// Run through the DII workflow. Download file initialization, target
-// determination and intermediate rename all succeed.
-TEST_P(DownloadItemDestinationUpdateRaceTest, IntermediateRenameSucceeds) {
- // We expect either that the download will fail (in which case the request and
- // the download file will be cancelled), or it will succeed (in which case the
- // DownloadFile will Detach()). It depends on the list of observations that
- // are given to us.
- EXPECT_CALL(*file_, Cancel()).Times(::testing::AnyNumber());
- EXPECT_CALL(*request_handle_, CancelRequest(_)).Times(::testing::AnyNumber());
- EXPECT_CALL(*file_, Detach()).Times(::testing::AnyNumber());
-
- EXPECT_CALL(*file_, FullPath())
- .WillRepeatedly(ReturnRefOfCopy(base::FilePath(kDummyIntermediatePath)));
-
- // Intermediate rename loop is not used immediately, but let's set up the
- // DownloadFile expectations since we are about to transfer its ownership to
- // the download::DownloadItem.
- DownloadFile::RenameCompletionCallback intermediate_rename_callback;
- EXPECT_CALL(*file_, RenameAndUniquify(_, _))
- .WillOnce(SaveArg<1>(&intermediate_rename_callback));
-
- DownloadFile::InitializeCallback initialize_callback;
- EXPECT_CALL(*file_, Initialize(_, _, _, _))
- .WillOnce(SaveArg<0>(&initialize_callback));
-
- item_->Start(std::move(file_), std::move(request_handle_), *create_info());
- task_environment_.RunUntilIdle();
-
- base::WeakPtr<DownloadDestinationObserver> destination_observer =
- item_->DestinationObserverAsWeakPtr();
-
- ScheduleObservations(PreInitializeFileObservations(), destination_observer);
- task_environment_.RunUntilIdle();
-
- DownloadTargetCallback target_callback;
- EXPECT_CALL(*mock_delegate(), DetermineDownloadTarget(_, _))
- .WillOnce(SaveArg<1>(&target_callback));
- ScheduleObservations(PostInitializeFileObservations(), destination_observer);
- initialize_callback.Run(download::DOWNLOAD_INTERRUPT_REASON_NONE);
-
- task_environment_.RunUntilIdle();
- ASSERT_FALSE(target_callback.is_null());
-
- ScheduleObservations(PostTargetDeterminationObservations(),
- destination_observer);
- target_callback.Run(base::FilePath(kDummyTargetPath),
- download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
- download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
- base::FilePath(kDummyIntermediatePath),
- download::DOWNLOAD_INTERRUPT_REASON_NONE);
-
- task_environment_.RunUntilIdle();
- ASSERT_FALSE(intermediate_rename_callback.is_null());
-
- // This may or may not be called, depending on whether there are any errors in
- // our action list.
- EXPECT_CALL(*mock_delegate(), ShouldCompleteDownload(_, _))
- .Times(::testing::AnyNumber());
-
- ScheduleObservations(PostIntermediateRenameObservations(),
- destination_observer);
- intermediate_rename_callback.Run(download::DOWNLOAD_INTERRUPT_REASON_NONE,
- base::FilePath(kDummyIntermediatePath));
- task_environment_.RunUntilIdle();
-
- // The state of the download depends on the observer events that were played
- // back to the DownloadItemImpl. Hence we can't establish a single expectation
- // here. On Debug builds, the DCHECKs will verify that the state transitions
- // were correct. On Release builds, tests are expected to run to completion
- // without crashing on success.
- EXPECT_TRUE(item_->GetState() == download::DownloadItem::IN_PROGRESS ||
- item_->GetState() == download::DownloadItem::INTERRUPTED);
- if (item_->GetState() == download::DownloadItem::INTERRUPTED)
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED,
- item_->GetLastReason());
-
- item_->Cancel(true);
- task_environment_.RunUntilIdle();
-}
-
-TEST(MockDownloadItem, Compiles) {
- MockDownloadItem mock_item;
-}
-
-} // namespace content
diff --git a/chromium/content/browser/download/download_job.cc b/chromium/content/browser/download/download_job.cc
deleted file mode 100644
index 1889e71cbcc..00000000000
--- a/chromium/content/browser/download/download_job.cc
+++ /dev/null
@@ -1,117 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/download/download_job.h"
-
-#include "base/bind_helpers.h"
-#include "components/download/public/common/download_task_runner.h"
-#include "content/browser/download/download_item_impl.h"
-#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/web_contents.h"
-
-namespace content {
-
-DownloadJob::DownloadJob(
- DownloadItemImpl* download_item,
- std::unique_ptr<download::DownloadRequestHandleInterface> request_handle)
- : download_item_(download_item),
- request_handle_(std::move(request_handle)),
- is_paused_(false),
- weak_ptr_factory_(this) {}
-
-DownloadJob::~DownloadJob() = default;
-
-void DownloadJob::Cancel(bool user_cancel) {
- if (request_handle_)
- request_handle_->CancelRequest(user_cancel);
-}
-
-void DownloadJob::Pause() {
- is_paused_ = true;
-
- DownloadFile* download_file = download_item_->download_file_.get();
- if (download_file) {
- download::GetDownloadTaskRunner()->PostTask(
- FROM_HERE,
- base::BindOnce(&DownloadFile::Pause,
- // Safe because we control download file lifetime.
- base::Unretained(download_file)));
- }
- if (request_handle_)
- request_handle_->PauseRequest();
-}
-
-void DownloadJob::Resume(bool resume_request) {
- is_paused_ = false;
- if (!resume_request)
- return;
-
- DownloadFile* download_file = download_item_->download_file_.get();
- if (download_file) {
- download::GetDownloadTaskRunner()->PostTask(
- FROM_HERE,
- base::BindOnce(&DownloadFile::Resume,
- // Safe because we control download file lifetime.
- base::Unretained(download_file)));
- }
-
- if (request_handle_)
- request_handle_->ResumeRequest();
-}
-
-void DownloadJob::Start(
- DownloadFile* download_file_,
- const DownloadFile::InitializeCallback& callback,
- const download::DownloadItem::ReceivedSlices& received_slices) {
- download::GetDownloadTaskRunner()->PostTask(
- FROM_HERE,
- base::BindOnce(&DownloadFile::Initialize,
- // Safe because we control download file lifetime.
- base::Unretained(download_file_),
- base::Bind(&DownloadJob::OnDownloadFileInitialized,
- weak_ptr_factory_.GetWeakPtr(), callback),
- base::Bind(&DownloadJob::CancelRequestWithOffset,
- weak_ptr_factory_.GetWeakPtr()),
- received_slices, IsParallelizable()));
-}
-
-void DownloadJob::OnDownloadFileInitialized(
- const DownloadFile::InitializeCallback& callback,
- download::DownloadInterruptReason result) {
- callback.Run(result);
-}
-
-bool DownloadJob::AddInputStream(
- std::unique_ptr<DownloadManager::InputStream> stream,
- int64_t offset,
- int64_t length) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DownloadFile* download_file = download_item_->download_file_.get();
- if (!download_file) {
- CancelRequestWithOffset(offset);
- return false;
- }
-
- // download_file_ is owned by download_item_ on the UI thread and is always
- // deleted on the download task runner after download_file_ is nulled out.
- // So it's safe to use base::Unretained here.
- download::GetDownloadTaskRunner()->PostTask(
- FROM_HERE, base::BindOnce(&DownloadFile::AddInputStream,
- base::Unretained(download_file),
- std::move(stream), offset, length));
- return true;
-}
-
-void DownloadJob::CancelRequestWithOffset(int64_t offset) {
-}
-
-bool DownloadJob::IsParallelizable() const {
- return false;
-}
-
-bool DownloadJob::IsSavePackageDownload() const {
- return false;
-}
-
-} // namespace content
diff --git a/chromium/content/browser/download/download_job.h b/chromium/content/browser/download/download_job.h
deleted file mode 100644
index 8c8c7462a4a..00000000000
--- a/chromium/content/browser/download/download_job.h
+++ /dev/null
@@ -1,84 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_JOB_H_
-#define CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_JOB_H_
-
-#include "base/macros.h"
-#include "base/memory/weak_ptr.h"
-#include "base/time/time.h"
-#include "components/download/public/common/download_interrupt_reasons.h"
-#include "components/download/public/common/download_request_handle_interface.h"
-#include "content/browser/byte_stream.h"
-#include "content/browser/download/download_file.h"
-#include "content/common/content_export.h"
-
-namespace content {
-
-class DownloadItemImpl;
-
-// DownloadJob lives on UI thread and subclasses implement actual download logic
-// and interact with DownloadItemImpl.
-// The base class is a friend class of DownloadItemImpl.
-class CONTENT_EXPORT DownloadJob {
- public:
- DownloadJob(
- DownloadItemImpl* download_item,
- std::unique_ptr<download::DownloadRequestHandleInterface> request_handle);
- virtual ~DownloadJob();
-
- // Download operations.
- // TODO(qinmin): Remove the |callback| and |download_file_| parameter if
- // DownloadJob owns download file.
- void Start(DownloadFile* download_file_,
- const DownloadFile::InitializeCallback& callback,
- const download::DownloadItem::ReceivedSlices& received_slices);
- virtual void Cancel(bool user_cancel);
- virtual void Pause();
- virtual void Resume(bool resume_request);
-
- bool is_paused() const { return is_paused_; }
-
- // Returns whether the download is parallelizable. The download may not send
- // parallel requests as it can be disabled through flags.
- virtual bool IsParallelizable() const;
-
- // Cancel a particular request starts from |offset|, while the download is not
- // canceled. Used in parallel download.
- // TODO(xingliu): Remove this function if download job owns download file.
- virtual void CancelRequestWithOffset(int64_t offset);
-
- // Whether the download is save package.
- virtual bool IsSavePackageDownload() const;
-
- protected:
- // Callback from file thread when we initialize the DownloadFile.
- virtual void OnDownloadFileInitialized(
- const DownloadFile::InitializeCallback& callback,
- download::DownloadInterruptReason result);
-
- // Add an input stream to the download sink. Return false if we start to
- // destroy download file.
- bool AddInputStream(std::unique_ptr<DownloadManager::InputStream> stream,
- int64_t offset,
- int64_t length);
-
- DownloadItemImpl* download_item_;
-
- // Used to perform operations on network request.
- // Can be null on interrupted download.
- std::unique_ptr<download::DownloadRequestHandleInterface> request_handle_;
-
- private:
- // If the download progress is paused by the user.
- bool is_paused_;
-
- base::WeakPtrFactory<DownloadJob> weak_ptr_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(DownloadJob);
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_JOB_H_
diff --git a/chromium/content/browser/download/download_job_factory.cc b/chromium/content/browser/download/download_job_factory.cc
deleted file mode 100644
index 743406152e0..00000000000
--- a/chromium/content/browser/download/download_job_factory.cc
+++ /dev/null
@@ -1,120 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/download/download_job_factory.h"
-
-#include <memory>
-
-#include "base/memory/ptr_util.h"
-#include "components/download/public/common/download_stats.h"
-#include "content/browser/download/download_item_impl.h"
-#include "content/browser/download/download_job.h"
-#include "content/browser/download/download_job_impl.h"
-#include "content/browser/download/parallel_download_job.h"
-#include "content/browser/download/parallel_download_utils.h"
-#include "content/browser/download/save_package_download_job.h"
-#include "content/public/common/content_features.h"
-
-namespace content {
-
-namespace {
-
-// Returns if the download can be parallelized.
-bool IsParallelizableDownload(const download::DownloadCreateInfo& create_info,
- DownloadItemImpl* download_item) {
- // To enable parallel download, following conditions need to be satisfied.
- // 1. Feature |kParallelDownloading| enabled.
- // 2. Strong validators response headers. i.e. ETag and Last-Modified.
- // 3. Accept-Ranges or Content-Range header.
- // 4. Content-Length header.
- // 5. Content-Length is no less than the minimum slice size configuration, or
- // persisted slices alreay exist.
- // 6. HTTP/1.1 protocol, not QUIC nor HTTP/1.0.
- // 7. HTTP or HTTPS scheme with GET method in the initial request.
-
- // Etag and last modified are stored into DownloadCreateInfo in
- // DownloadRequestCore only if the response header complies to the strong
- // validator rule.
- bool has_strong_validator =
- !create_info.etag.empty() || !create_info.last_modified.empty();
- bool has_content_length = create_info.total_bytes > 0;
- bool satisfy_min_file_size =
- !download_item->GetReceivedSlices().empty() ||
- create_info.total_bytes >= GetMinSliceSizeConfig();
- bool satisfy_connection_type = create_info.connection_info ==
- net::HttpResponseInfo::CONNECTION_INFO_HTTP1_1;
- bool http_get_method =
- create_info.method == "GET" && create_info.url().SchemeIsHTTPOrHTTPS();
-
- bool is_parallelizable = has_strong_validator && create_info.accept_range &&
- has_content_length && satisfy_min_file_size &&
- satisfy_connection_type && http_get_method;
-
- if (!IsParallelDownloadEnabled())
- return is_parallelizable;
-
- download::RecordParallelDownloadCreationEvent(
- is_parallelizable
- ? download::ParallelDownloadCreationEvent::STARTED_PARALLEL_DOWNLOAD
- : download::ParallelDownloadCreationEvent::
- FELL_BACK_TO_NORMAL_DOWNLOAD);
-
- if (!has_strong_validator) {
- download::RecordParallelDownloadCreationEvent(
- download::ParallelDownloadCreationEvent::
- FALLBACK_REASON_STRONG_VALIDATORS);
- }
- if (!create_info.accept_range) {
- download::RecordParallelDownloadCreationEvent(
- download::ParallelDownloadCreationEvent::
- FALLBACK_REASON_ACCEPT_RANGE_HEADER);
- }
- if (!has_content_length) {
- download::RecordParallelDownloadCreationEvent(
- download::ParallelDownloadCreationEvent::
- FALLBACK_REASON_CONTENT_LENGTH_HEADER);
- }
- if (!satisfy_min_file_size) {
- download::RecordParallelDownloadCreationEvent(
- download::ParallelDownloadCreationEvent::FALLBACK_REASON_FILE_SIZE);
- }
- if (!satisfy_connection_type) {
- download::RecordParallelDownloadCreationEvent(
- download::ParallelDownloadCreationEvent::
- FALLBACK_REASON_CONNECTION_TYPE);
- }
- if (!http_get_method) {
- download::RecordParallelDownloadCreationEvent(
- download::ParallelDownloadCreationEvent::FALLBACK_REASON_HTTP_METHOD);
- }
-
- return is_parallelizable;
-}
-
-} // namespace
-
-// static
-std::unique_ptr<DownloadJob> DownloadJobFactory::CreateJob(
- DownloadItemImpl* download_item,
- std::unique_ptr<download::DownloadRequestHandleInterface> req_handle,
- const download::DownloadCreateInfo& create_info,
- bool is_save_package_download) {
- if (is_save_package_download) {
- return std::make_unique<SavePackageDownloadJob>(download_item,
- std::move(req_handle));
- }
-
- bool is_parallelizable = IsParallelizableDownload(create_info, download_item);
- // Build parallel download job.
- if (IsParallelDownloadEnabled() && is_parallelizable) {
- return std::make_unique<ParallelDownloadJob>(
- download_item, std::move(req_handle), create_info);
- }
-
- // An ordinary download job.
- return std::make_unique<DownloadJobImpl>(download_item, std::move(req_handle),
- is_parallelizable);
-}
-
-} // namespace
diff --git a/chromium/content/browser/download/download_job_factory.h b/chromium/content/browser/download/download_job_factory.h
deleted file mode 100644
index d1db0dd6629..00000000000
--- a/chromium/content/browser/download/download_job_factory.h
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_JOB_FACTORY_H_
-#define CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_JOB_FACTORY_H_
-
-#include <memory>
-
-#include "base/macros.h"
-#include "components/download/public/common/download_create_info.h"
-
-namespace download {
-class DownloadRequestHandleInterface;
-}
-
-namespace content {
-
-class DownloadItemImpl;
-class DownloadJob;
-
-// Factory class to create different kinds of DownloadJob.
-class DownloadJobFactory {
- public:
- static std::unique_ptr<DownloadJob> CreateJob(
- DownloadItemImpl* download_item,
- std::unique_ptr<download::DownloadRequestHandleInterface> req_handle,
- const download::DownloadCreateInfo& create_info,
- bool is_save_package_download);
-
- private:
- DISALLOW_COPY_AND_ASSIGN(DownloadJobFactory);
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_JOB_FACTORY_H_
diff --git a/chromium/content/browser/download/download_job_impl.cc b/chromium/content/browser/download/download_job_impl.cc
deleted file mode 100644
index e344a854e28..00000000000
--- a/chromium/content/browser/download/download_job_impl.cc
+++ /dev/null
@@ -1,22 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/download/download_job_impl.h"
-
-namespace content {
-
-DownloadJobImpl::DownloadJobImpl(
- DownloadItemImpl* download_item,
- std::unique_ptr<download::DownloadRequestHandleInterface> request_handle,
- bool is_parallizable)
- : DownloadJob(download_item, std::move(request_handle)),
- is_parallizable_(is_parallizable) {}
-
-DownloadJobImpl::~DownloadJobImpl() = default;
-
-bool DownloadJobImpl::IsParallelizable() const {
- return is_parallizable_;
-}
-
-} // namespace content
diff --git a/chromium/content/browser/download/download_job_impl.h b/chromium/content/browser/download/download_job_impl.h
deleted file mode 100644
index d96d0bce326..00000000000
--- a/chromium/content/browser/download/download_job_impl.h
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_JOB_IMPL_H_
-#define CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_JOB_IMPL_H_
-
-#include "base/macros.h"
-#include "content/browser/download/download_item_impl.h"
-#include "content/browser/download/download_job.h"
-#include "content/common/content_export.h"
-
-namespace content {
-
-class CONTENT_EXPORT DownloadJobImpl : public DownloadJob {
- public:
- DownloadJobImpl(
- DownloadItemImpl* download_item,
- std::unique_ptr<download::DownloadRequestHandleInterface> request_handle,
- bool is_parallizable);
- ~DownloadJobImpl() override;
-
- // DownloadJob implementation.
- bool IsParallelizable() const override;
-
- private:
- // Whether the download can be parallized.
- bool is_parallizable_;
-
- DISALLOW_COPY_AND_ASSIGN(DownloadJobImpl);
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_JOB_IMPL_H_
diff --git a/chromium/content/browser/download/download_job_unittest.cc b/chromium/content/browser/download/download_job_unittest.cc
deleted file mode 100644
index 9721059d0b2..00000000000
--- a/chromium/content/browser/download/download_job_unittest.cc
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <memory>
-
-#include "base/memory/ptr_util.h"
-#include "content/browser/download/download_item_impl_delegate.h"
-#include "content/browser/download/download_job.h"
-#include "content/browser/download/mock_download_item_impl.h"
-#include "content/browser/download/mock_download_job.h"
-#include "content/public/test/test_browser_thread_bundle.h"
-#include "testing/gmock/include/gmock/gmock.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-using ::testing::NiceMock;
-
-namespace content {
-
-// Test for DownloadJob base class functionalities.
-class DownloadJobTest : public testing::Test {
- public:
- DownloadJobTest() = default;
- ~DownloadJobTest() override = default;
-
- void SetUp() override {
- item_delegate_ = std::make_unique<DownloadItemImplDelegate>();
- download_item_ =
- std::make_unique<NiceMock<MockDownloadItemImpl>>(item_delegate_.get());
- download_job_ = std::make_unique<MockDownloadJob>(download_item_.get());
- }
-
- content::TestBrowserThreadBundle browser_threads_;
- std::unique_ptr<DownloadItemImplDelegate> item_delegate_;
- std::unique_ptr<MockDownloadItemImpl> download_item_;
- std::unique_ptr<MockDownloadJob> download_job_;
-};
-
-TEST_F(DownloadJobTest, Pause) {
- DCHECK(download_job_->download_item());
-}
-
-} // namespace content
diff --git a/chromium/content/browser/download/download_manager_impl.cc b/chromium/content/browser/download/download_manager_impl.cc
index 02470e87915..316ddd4982c 100644
--- a/chromium/content/browser/download/download_manager_impl.cc
+++ b/chromium/content/browser/download/download_manager_impl.cc
@@ -26,27 +26,35 @@
#include "components/download/downloader/in_progress/download_entry.h"
#include "components/download/downloader/in_progress/in_progress_cache_impl.h"
#include "components/download/public/common/download_create_info.h"
+#include "components/download/public/common/download_file.h"
+#include "components/download/public/common/download_file_factory.h"
#include "components/download/public/common/download_interrupt_reasons.h"
+#include "components/download/public/common/download_item_factory.h"
+#include "components/download/public/common/download_item_impl.h"
#include "components/download/public/common/download_request_handle_interface.h"
#include "components/download/public/common/download_stats.h"
#include "components/download/public/common/download_task_runner.h"
+#include "components/download/public/common/download_url_loader_factory_getter.h"
#include "components/download/public/common/download_url_parameters.h"
+#include "components/download/public/common/download_utils.h"
+#include "components/download/public/common/resource_downloader.h"
+#include "components/download/public/common/url_download_handler_factory.h"
#include "content/browser/byte_stream.h"
#include "content/browser/child_process_security_policy_impl.h"
-#include "content/browser/download/download_file.h"
-#include "content/browser/download/download_file_factory.h"
-#include "content/browser/download/download_item_factory.h"
-#include "content/browser/download/download_item_impl.h"
+#include "content/browser/download/blob_download_url_loader_factory_getter.h"
+#include "content/browser/download/byte_stream_input_stream.h"
#include "content/browser/download/download_resource_handler.h"
#include "content/browser/download/download_utils.h"
-#include "content/browser/download/resource_downloader.h"
+#include "content/browser/download/network_download_url_loader_factory_getter.h"
#include "content/browser/download/url_downloader.h"
+#include "content/browser/download/url_downloader_factory.h"
#include "content/browser/loader/resource_dispatcher_host_impl.h"
#include "content/browser/loader/resource_request_info_impl.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/storage_partition_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/common/throttling_url_loader.h"
+#include "content/common/wrapper_shared_url_loader_factory.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/download_item_utils.h"
@@ -58,6 +66,7 @@
#include "content/public/browser/resource_context.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/common/browser_side_navigation_policy.h"
+#include "content/public/common/origin_util.h"
#include "content/public/common/previews_state.h"
#include "content/public/common/referrer.h"
#include "net/base/elements_upload_data_stream.h"
@@ -119,33 +128,46 @@ void CreateInterruptedDownload(
std::unique_ptr<ByteStreamReader> empty_byte_stream;
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
- base::BindOnce(&DownloadManager::StartDownload, download_manager,
- std::move(failed_created_info),
- std::make_unique<DownloadManager::InputStream>(
- std::move(empty_byte_stream)),
- params->callback()));
+ base::BindOnce(
+ &DownloadManager::StartDownload, download_manager,
+ std::move(failed_created_info),
+ std::make_unique<ByteStreamInputStream>(std::move(empty_byte_stream)),
+ nullptr, params->callback()));
}
-download::DownloadEntry CreateDownloadEntryFromItem(
- const DownloadItemImpl& item) {
+// Helper functions for DownloadItem -> DownloadEntry for InProgressCache.
+
+uint64_t GetUniqueDownloadId() {
// Get a new UKM download_id that is not 0.
uint64_t download_id = 0;
do {
download_id = base::RandUint64();
} while (download_id == 0);
+ return download_id;
+}
- return download::DownloadEntry(item.GetGuid(), item.download_source(),
- download_id);
+download::DownloadEntry CreateDownloadEntryFromItem(
+ const download::DownloadItem& item,
+ const std::string& request_origin,
+ download::DownloadSource download_source,
+ bool fetch_error_body,
+ const download::DownloadUrlParameters::RequestHeadersType&
+ request_headers) {
+ return download::DownloadEntry(item.GetGuid(), request_origin,
+ download_source, fetch_error_body,
+ request_headers, GetUniqueDownloadId());
}
-DownloadManagerImpl::UniqueUrlDownloadHandlerPtr BeginDownload(
- std::unique_ptr<download::DownloadUrlParameters> params,
- std::unique_ptr<storage::BlobDataHandle> blob_data_handle,
- content::ResourceContext* resource_context,
- uint32_t download_id,
- base::WeakPtr<DownloadManagerImpl> download_manager) {
+void BeginDownload(std::unique_ptr<download::DownloadUrlParameters> params,
+ std::unique_ptr<storage::BlobDataHandle> blob_data_handle,
+ content::ResourceContext* resource_context,
+ uint32_t download_id,
+ base::WeakPtr<DownloadManagerImpl> download_manager) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
+ download::UrlDownloadHandler::UniqueUrlDownloadHandlerPtr downloader(
+ nullptr, base::OnTaskRunnerDeleter(base::ThreadTaskRunnerHandle::Get()));
+
params->set_blob_storage_context_getter(
base::BindOnce(&BlobStorageContextGetter, resource_context));
std::unique_ptr<net::URLRequest> url_request =
@@ -166,32 +188,38 @@ DownloadManagerImpl::UniqueUrlDownloadHandlerPtr BeginDownload(
// If the download was accepted, the DownloadResourceHandler is now
// responsible for driving the request to completion.
- if (reason == download::DOWNLOAD_INTERRUPT_REASON_NONE)
- return nullptr;
-
// Otherwise, create an interrupted download.
- CreateInterruptedDownload(params.get(), reason, download_manager);
- return nullptr;
+ if (reason != download::DOWNLOAD_INTERRUPT_REASON_NONE)
+ CreateInterruptedDownload(params.get(), reason, download_manager);
+ } else {
+ downloader.reset(UrlDownloader::BeginDownload(download_manager,
+ std::move(url_request),
+ params.get(), false)
+ .release());
}
-
- return DownloadManagerImpl::UniqueUrlDownloadHandlerPtr(
- UrlDownloader::BeginDownload(download_manager, std::move(url_request),
- params.get(), false)
- .release());
+ BrowserThread::PostTask(
+ BrowserThread::UI, FROM_HERE,
+ base::BindOnce(
+ &download::UrlDownloadHandler::Delegate::OnUrlDownloadHandlerCreated,
+ download_manager, std::move(downloader)));
}
-DownloadManagerImpl::UniqueUrlDownloadHandlerPtr BeginResourceDownload(
+void BeginResourceDownload(
std::unique_ptr<download::DownloadUrlParameters> params,
std::unique_ptr<network::ResourceRequest> request,
- std::unique_ptr<storage::BlobDataHandle> blob_data_handle,
- scoped_refptr<URLLoaderFactoryGetter> url_loader_factory_getter,
+ scoped_refptr<download::DownloadURLLoaderFactoryGetter>
+ url_loader_factory_getter,
uint32_t download_id,
base::WeakPtr<DownloadManagerImpl> download_manager,
const GURL& site_url,
const GURL& tab_url,
- const GURL& tab_referrer_url) {
+ const GURL& tab_referrer_url,
+ const scoped_refptr<base::SingleThreadTaskRunner>& task_runner) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
+ download::UrlDownloadHandler::UniqueUrlDownloadHandlerPtr downloader(
+ nullptr, base::OnTaskRunnerDeleter(base::ThreadTaskRunnerHandle::Get()));
+
// Check if the renderer is permitted to request the requested URL.
if (params->render_process_host_id() >= 0 &&
!CanRequestURLFromRenderer(params->render_process_host_id(),
@@ -200,36 +228,31 @@ DownloadManagerImpl::UniqueUrlDownloadHandlerPtr BeginResourceDownload(
params.get(),
download::DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST,
download_manager);
- return nullptr;
+ } else {
+ // TODO(qinmin): Check the storage permission before creating the URLLoader.
+ // This is already done for context menu download, but it is missing for
+ // download service and download resumption.
+ downloader.reset(
+ download::ResourceDownloader::BeginDownload(
+ download_manager, std::move(params), std::move(request),
+ url_loader_factory_getter->GetURLLoaderFactory(), site_url, tab_url,
+ tab_referrer_url, download_id, false, task_runner)
+ .release());
}
+ task_runner->PostTask(
+ FROM_HERE,
+ base::BindOnce(
+ &download::UrlDownloadHandler::Delegate::OnUrlDownloadHandlerCreated,
+ download_manager, std::move(downloader)));
+}
- network::mojom::URLLoaderFactory* url_loader_factory =
- url_loader_factory_getter->GetNetworkFactory();
- if (params->url().SchemeIs(url::kBlobScheme)) {
- network::mojom::URLLoaderFactoryPtr url_loader_factory_ptr;
- storage::BlobURLLoaderFactory::Create(
- std::move(blob_data_handle), params->url(),
- mojo::MakeRequest(&url_loader_factory_ptr));
- url_loader_factory = url_loader_factory_ptr.get();
- }
- // TODO(qinmin): Check the storage permission before creating the URLLoader.
- // This is already done for context menu download, but it is missing for
- // download service and download resumption.
- return DownloadManagerImpl::UniqueUrlDownloadHandlerPtr(
- ResourceDownloader::BeginDownload(download_manager, std::move(params),
- std::move(request), url_loader_factory,
- site_url, tab_url, tab_referrer_url,
- download_id, false)
- .release());
-}
-
-class DownloadItemFactoryImpl : public DownloadItemFactory {
+class DownloadItemFactoryImpl : public download::DownloadItemFactory {
public:
DownloadItemFactoryImpl() {}
~DownloadItemFactoryImpl() override {}
- DownloadItemImpl* CreatePersistedItem(
- DownloadItemImplDelegate* delegate,
+ download::DownloadItemImpl* CreatePersistedItem(
+ download::DownloadItemImplDelegate* delegate,
const std::string& guid,
uint32_t download_id,
const base::FilePath& current_path,
@@ -256,7 +279,7 @@ class DownloadItemFactoryImpl : public DownloadItemFactory {
bool transient,
const std::vector<download::DownloadItem::ReceivedSlice>& received_slices)
override {
- return new DownloadItemImpl(
+ return new download::DownloadItemImpl(
delegate, guid, download_id, current_path, target_path, url_chain,
referrer_url, site_url, tab_url, tab_refererr_url, mime_type,
original_mime_type, start_time, end_time, etag, last_modified,
@@ -264,23 +287,23 @@ class DownloadItemFactoryImpl : public DownloadItemFactory {
opened, last_access_time, transient, received_slices);
}
- DownloadItemImpl* CreateActiveItem(
- DownloadItemImplDelegate* delegate,
+ download::DownloadItemImpl* CreateActiveItem(
+ download::DownloadItemImplDelegate* delegate,
uint32_t download_id,
const download::DownloadCreateInfo& info) override {
- return new DownloadItemImpl(delegate, download_id, info);
+ return new download::DownloadItemImpl(delegate, download_id, info);
}
- DownloadItemImpl* CreateSavePageItem(
- DownloadItemImplDelegate* delegate,
+ download::DownloadItemImpl* CreateSavePageItem(
+ download::DownloadItemImplDelegate* delegate,
uint32_t download_id,
const base::FilePath& path,
const GURL& url,
const std::string& mime_type,
std::unique_ptr<download::DownloadRequestHandleInterface> request_handle)
override {
- return new DownloadItemImpl(delegate, download_id, path, url, mime_type,
- std::move(request_handle));
+ return new download::DownloadItemImpl(delegate, download_id, path, url,
+ mime_type, std::move(request_handle));
}
};
@@ -327,14 +350,31 @@ void InProgressDownloadObserver::OnDownloadUpdated(
switch (download->GetState()) {
case download::DownloadItem::DownloadState::COMPLETE:
+ // Intentional fallthrough.
case download::DownloadItem::DownloadState::CANCELLED:
if (in_progress_cache_)
in_progress_cache_->RemoveEntry(download->GetGuid());
break;
- case download::DownloadItem::DownloadState::IN_PROGRESS:
- // TODO(crbug.com/778425): After RetrieveEntry has been implemented, do a
- // check to make sure the entry exists in the cache.
+
+ case download::DownloadItem::DownloadState::INTERRUPTED:
+ // Intentional fallthrough.
+ case download::DownloadItem::DownloadState::IN_PROGRESS: {
+ // Make sure the entry exists in the cache.
+ base::Optional<download::DownloadEntry> entry_opt =
+ in_progress_cache_->RetrieveEntry(download->GetGuid());
+ download::DownloadEntry entry;
+ if (!entry_opt.has_value()) {
+ entry = CreateDownloadEntryFromItem(
+ *download, std::string(), /* request_origin */
+ download::DownloadSource::UNKNOWN, false, /* fetch_error_body */
+ download::DownloadUrlParameters::RequestHeadersType());
+ in_progress_cache_->AddOrReplaceEntry(entry);
+ break;
+ }
+ entry = entry_opt.value();
break;
+ }
+
default:
break;
}
@@ -350,7 +390,7 @@ void InProgressDownloadObserver::OnDownloadRemoved(
DownloadManagerImpl::DownloadManagerImpl(BrowserContext* browser_context)
: item_factory_(new DownloadItemFactoryImpl()),
- file_factory_(new DownloadFileFactory()),
+ file_factory_(new download::DownloadFileFactory()),
shutdown_needed_(true),
initialized_(false),
history_db_initialized_(false),
@@ -359,18 +399,24 @@ DownloadManagerImpl::DownloadManagerImpl(BrowserContext* browser_context)
delegate_(nullptr),
weak_factory_(this) {
DCHECK(browser_context);
+ download::SetIOTaskRunner(
+ BrowserThread::GetTaskRunnerForThread(BrowserThread::IO));
+ if (!base::FeatureList::IsEnabled(network::features::kNetworkService))
+ download::UrlDownloadHandlerFactory::Install(new UrlDownloaderFactory());
}
DownloadManagerImpl::~DownloadManagerImpl() {
DCHECK(!shutdown_needed_);
+ download::SetIOTaskRunner(nullptr);
}
-DownloadItemImpl* DownloadManagerImpl::CreateActiveItem(
+download::DownloadItemImpl* DownloadManagerImpl::CreateActiveItem(
uint32_t id,
const download::DownloadCreateInfo& info) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(!base::ContainsKey(downloads_, id));
- DownloadItemImpl* download = item_factory_->CreateActiveItem(this, id, info);
+ download::DownloadItemImpl* download =
+ item_factory_->CreateActiveItem(this, id, info);
downloads_[id] = base::WrapUnique(download);
downloads_by_guid_[download->GetGuid()] = download;
@@ -388,7 +434,8 @@ void DownloadManagerImpl::GetNextId(const DownloadIdCallback& callback) {
}
void DownloadManagerImpl::DetermineDownloadTarget(
- DownloadItemImpl* item, const DownloadTargetCallback& callback) {
+ download::DownloadItemImpl* item,
+ const DownloadTargetCallback& callback) {
// Note that this next call relies on
// DownloadItemImplDelegate::DownloadTargetCallback and
// DownloadManagerDelegate::DownloadTargetCallback having the same
@@ -405,7 +452,8 @@ void DownloadManagerImpl::DetermineDownloadTarget(
}
bool DownloadManagerImpl::ShouldCompleteDownload(
- DownloadItemImpl* item, const base::Closure& complete_callback) {
+ download::DownloadItemImpl* item,
+ const base::Closure& complete_callback) {
if (!delegate_ ||
delegate_->ShouldCompleteDownload(item, complete_callback)) {
return true;
@@ -424,7 +472,8 @@ bool DownloadManagerImpl::ShouldOpenFileBasedOnExtension(
}
bool DownloadManagerImpl::ShouldOpenDownload(
- DownloadItemImpl* item, const ShouldOpenDownloadCallback& callback) {
+ download::DownloadItemImpl* item,
+ const ShouldOpenDownloadCallback& callback) {
if (!delegate_)
return true;
@@ -451,12 +500,13 @@ void DownloadManagerImpl::SetDelegate(DownloadManagerDelegate* delegate) {
download::InProgressCache* in_progress_cache =
delegate_->GetInProgressCache();
if (in_progress_cache) {
- in_progress_cache->Initialize(post_init_callback);
+ in_progress_cache->Initialize(std::move(post_init_callback));
return;
}
}
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, post_init_callback);
+ BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
+ std::move(post_init_callback));
}
DownloadManagerDelegate* DownloadManagerImpl::GetDelegate() const {
@@ -478,7 +528,7 @@ void DownloadManagerImpl::Shutdown() {
// accepted or discarded. Canceling will remove the intermediate download
// file.
for (const auto& it : downloads_) {
- DownloadItemImpl* download = it.second.get();
+ download::DownloadItemImpl* download = it.second.get();
if (download->GetState() == download::DownloadItem::IN_PROGRESS)
download->Cancel(false);
}
@@ -510,7 +560,8 @@ bool DownloadManagerImpl::InterceptDownload(
void DownloadManagerImpl::StartDownload(
std::unique_ptr<download::DownloadCreateInfo> info,
- std::unique_ptr<DownloadManager::InputStream> stream,
+ std::unique_ptr<download::InputStream> stream,
+ scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory,
const download::DownloadUrlParameters::OnStartedCallback& on_started) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(info);
@@ -531,27 +582,33 @@ void DownloadManagerImpl::StartDownload(
stream->IsEmpty()));
DVLOG(20) << __func__ << "() result="
<< download::DownloadInterruptReasonToString(info->result);
- if (new_download)
+ if (new_download) {
download::RecordDownloadConnectionSecurity(info->url(), info->url_chain);
+ download::RecordDownloadContentTypeSecurity(
+ info->url(), info->url_chain, info->mime_type,
+ base::BindRepeating(&IsOriginSecure));
+ }
base::Callback<void(uint32_t)> got_id(base::Bind(
&DownloadManagerImpl::StartDownloadWithId, weak_factory_.GetWeakPtr(),
- base::Passed(&info), base::Passed(&stream), on_started, new_download));
+ base::Passed(&info), base::Passed(&stream),
+ std::move(shared_url_loader_factory), on_started, new_download));
if (new_download) {
- GetNextId(got_id);
+ GetNextId(std::move(got_id));
} else {
- got_id.Run(download_id);
+ std::move(got_id).Run(download_id);
}
}
void DownloadManagerImpl::StartDownloadWithId(
std::unique_ptr<download::DownloadCreateInfo> info,
- std::unique_ptr<DownloadManager::InputStream> stream,
+ std::unique_ptr<download::InputStream> stream,
+ scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory,
const download::DownloadUrlParameters::OnStartedCallback& on_started,
bool new_download,
uint32_t id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK_NE(download::DownloadItem::kInvalidId, id);
- DownloadItemImpl* download = nullptr;
+ download::DownloadItemImpl* download = nullptr;
if (new_download) {
download = CreateActiveItem(id, *info);
} else {
@@ -610,8 +667,9 @@ void DownloadManagerImpl::StartDownloadWithId(
base::Optional<download::DownloadEntry> entry_opt =
in_progress_cache->RetrieveEntry(download->GetGuid());
if (!entry_opt.has_value()) {
- in_progress_cache->AddOrReplaceEntry(
- CreateDownloadEntryFromItem(*download));
+ in_progress_cache->AddOrReplaceEntry(CreateDownloadEntryFromItem(
+ *download, info->request_origin, info->download_source,
+ info->fetch_error_body, info->request_headers));
}
}
@@ -624,7 +682,7 @@ void DownloadManagerImpl::StartDownloadWithId(
download->AddObserver(in_progress_download_observer_.get());
}
- std::unique_ptr<DownloadFile> download_file;
+ std::unique_ptr<download::DownloadFile> download_file;
if (info->result == download::DOWNLOAD_INTERRUPT_REASON_NONE) {
DCHECK(stream.get());
@@ -636,8 +694,13 @@ void DownloadManagerImpl::StartDownloadWithId(
// so that the download::DownloadItem can salvage what it can out of a failed
// resumption attempt.
- download->Start(std::move(download_file), std::move(info->request_handle),
- *info);
+ StoragePartition* storage_partition = GetStoragePartition(
+ browser_context_, info->render_process_id, info->render_frame_id);
+
+ download->Start(
+ std::move(download_file), std::move(info->request_handle), *info,
+ std::move(shared_url_loader_factory),
+ storage_partition ? storage_partition->GetURLRequestContext() : nullptr);
// For interrupted downloads, Start() will transition the state to
// IN_PROGRESS and consumers will be notified via OnDownloadUpdated().
@@ -656,12 +719,13 @@ void DownloadManagerImpl::StartDownloadWithId(
void DownloadManagerImpl::CheckForHistoryFilesRemoval() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
for (const auto& it : downloads_) {
- DownloadItemImpl* item = it.second.get();
+ download::DownloadItemImpl* item = it.second.get();
CheckForFileRemoval(item);
}
}
-void DownloadManagerImpl::CheckForFileRemoval(DownloadItemImpl* download_item) {
+void DownloadManagerImpl::CheckForFileRemoval(
+ download::DownloadItemImpl* download_item) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if ((download_item->GetState() == download::DownloadItem::COMPLETE) &&
!download_item->GetFileExternallyRemoved() && delegate_) {
@@ -721,7 +785,7 @@ void DownloadManagerImpl::CreateSavePackageDownloadItemWithId(
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK_NE(download::DownloadItem::kInvalidId, id);
DCHECK(!base::ContainsKey(downloads_, id));
- DownloadItemImpl* download_item = item_factory_->CreateSavePageItem(
+ download::DownloadItemImpl* download_item = item_factory_->CreateSavePageItem(
this, id, main_file_path, page_url, mime_type, std::move(request_handle));
DownloadItemUtils::AttachInfo(download_item, GetBrowserContext(),
WebContentsImpl::FromRenderFrameHostID(
@@ -743,8 +807,10 @@ void DownloadManagerImpl::CreateSavePackageDownloadItemWithId(
base::Optional<download::DownloadEntry> entry_opt =
in_progress_cache->RetrieveEntry(download_item->GetGuid());
if (!entry_opt.has_value()) {
- in_progress_cache->AddOrReplaceEntry(
- CreateDownloadEntryFromItem(*download_item));
+ in_progress_cache->AddOrReplaceEntry(CreateDownloadEntryFromItem(
+ *download_item, std::string(), /* request_origin */
+ download::DownloadSource::UNKNOWN, false, /* fetch_error_body */
+ download::DownloadUrlParameters::RequestHeadersType()));
}
}
}
@@ -755,26 +821,32 @@ void DownloadManagerImpl::CreateSavePackageDownloadItemWithId(
// download.
void DownloadManagerImpl::ResumeInterruptedDownload(
std::unique_ptr<download::DownloadUrlParameters> params,
- uint32_t id) {
- BeginDownloadInternal(std::move(params), nullptr, id);
+ uint32_t id,
+ const GURL& site_url) {
+ StoragePartitionImpl* storage_partition = static_cast<StoragePartitionImpl*>(
+ BrowserContext::GetStoragePartitionForSite(browser_context_, site_url));
+ params->set_url_request_context_getter(
+ storage_partition->GetURLRequestContext());
+ BeginDownloadInternal(std::move(params), nullptr, id, storage_partition);
}
-
void DownloadManagerImpl::SetDownloadItemFactoryForTesting(
- std::unique_ptr<DownloadItemFactory> item_factory) {
+ std::unique_ptr<download::DownloadItemFactory> item_factory) {
item_factory_ = std::move(item_factory);
}
void DownloadManagerImpl::SetDownloadFileFactoryForTesting(
- std::unique_ptr<DownloadFileFactory> file_factory) {
+ std::unique_ptr<download::DownloadFileFactory> file_factory) {
file_factory_ = std::move(file_factory);
}
-DownloadFileFactory* DownloadManagerImpl::GetDownloadFileFactoryForTesting() {
+download::DownloadFileFactory*
+DownloadManagerImpl::GetDownloadFileFactoryForTesting() {
return file_factory_.get();
}
-void DownloadManagerImpl::DownloadRemoved(DownloadItemImpl* download) {
+void DownloadManagerImpl::DownloadRemoved(
+ download::DownloadItemImpl* download) {
if (!download)
return;
@@ -782,8 +854,47 @@ void DownloadManagerImpl::DownloadRemoved(DownloadItemImpl* download) {
downloads_.erase(download->GetId());
}
-void DownloadManagerImpl::AddUrlDownloadHandler(
- UniqueUrlDownloadHandlerPtr downloader) {
+void DownloadManagerImpl::DownloadInterrupted(
+ download::DownloadItemImpl* download) {
+ WebContents* web_contents = DownloadItemUtils::GetWebContents(download);
+ if (!web_contents) {
+ download::RecordDownloadCountWithSource(
+ download::INTERRUPTED_WITHOUT_WEBCONTENTS, download->download_source());
+ }
+}
+
+base::Optional<download::DownloadEntry> DownloadManagerImpl::GetInProgressEntry(
+ download::DownloadItemImpl* download) {
+ if (!download || !delegate_)
+ return base::Optional<download::DownloadEntry>();
+
+ download::InProgressCache* in_progress_cache =
+ delegate_->GetInProgressCache();
+ if (in_progress_cache)
+ return in_progress_cache->RetrieveEntry(download->GetGuid());
+ return base::Optional<download::DownloadEntry>();
+}
+
+bool DownloadManagerImpl::IsOffTheRecord() const {
+ return browser_context_->IsOffTheRecord();
+}
+
+void DownloadManagerImpl::ReportBytesWasted(
+ download::DownloadItemImpl* download) {
+ if (!delegate_)
+ return;
+ auto entry_opt = GetInProgressEntry(download);
+ if (entry_opt.has_value()) {
+ download::DownloadEntry entry = entry_opt.value();
+ entry.bytes_wasted = download->GetBytesWasted();
+ download::InProgressCache* in_progress_cache =
+ delegate_->GetInProgressCache();
+ in_progress_cache->AddOrReplaceEntry(entry);
+ }
+}
+
+void DownloadManagerImpl::OnUrlDownloadHandlerCreated(
+ download::UrlDownloadHandler::UniqueUrlDownloadHandlerPtr downloader) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (downloader)
url_download_handlers_.push_back(std::move(downloader));
@@ -855,8 +966,11 @@ void DownloadManagerImpl::InterceptNavigation(
net::CertStatus cert_status,
int frame_tree_node_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
- if (!delegate_)
+ if (!delegate_) {
+ for (auto& observer : observers_)
+ observer.OnDownloadDropped(this);
return;
+ }
const GURL& url = resource_request->url;
const std::string& method = resource_request->method;
@@ -872,7 +986,7 @@ void DownloadManagerImpl::InterceptNavigation(
std::move(response), cert_status,
std::move(url_loader_client_endpoints));
- delegate_->CheckDownloadAllowed(web_contents_getter, url, method,
+ delegate_->CheckDownloadAllowed(std::move(web_contents_getter), url, method,
std::move(on_download_checks_done));
}
@@ -883,7 +997,7 @@ int DownloadManagerImpl::RemoveDownloadsByURLAndTime(
int count = 0;
auto it = downloads_.begin();
while (it != downloads_.end()) {
- DownloadItemImpl* download = it->second.get();
+ download::DownloadItemImpl* download = it->second.get();
// Increment done here to protect against invalidation below.
++it;
@@ -916,8 +1030,11 @@ void DownloadManagerImpl::DownloadUrl(
download::RecordDownloadCountWithSource(
download::DownloadCountTypes::DOWNLOAD_TRIGGERED_COUNT,
params->download_source());
+ StoragePartitionImpl* storage_partition =
+ GetStoragePartition(browser_context_, params->render_process_host_id(),
+ params->render_frame_host_routing_id());
BeginDownloadInternal(std::move(params), std::move(blob_data_handle),
- download::DownloadItem::kInvalidId);
+ download::DownloadItem::kInvalidId, storage_partition);
}
void DownloadManagerImpl::AddObserver(Observer* observer) {
@@ -959,7 +1076,7 @@ download::DownloadItem* DownloadManagerImpl::CreateDownloadItem(
return nullptr;
}
DCHECK(!base::ContainsKey(downloads_by_guid_, guid));
- DownloadItemImpl* item = item_factory_->CreatePersistedItem(
+ download::DownloadItemImpl* item = item_factory_->CreatePersistedItem(
this, guid, id, current_path, target_path, url_chain, referrer_url,
site_url, tab_url, tab_refererr_url, mime_type, original_mime_type,
start_time, end_time, etag, last_modified, received_bytes, total_bytes,
@@ -1048,12 +1165,15 @@ download::DownloadItem* DownloadManagerImpl::GetDownloadByGuid(
void DownloadManagerImpl::OnUrlDownloadStarted(
std::unique_ptr<download::DownloadCreateInfo> download_create_info,
- std::unique_ptr<DownloadManager::InputStream> stream,
+ std::unique_ptr<download::InputStream> stream,
+ scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory,
const download::DownloadUrlParameters::OnStartedCallback& callback) {
- StartDownload(std::move(download_create_info), std::move(stream), callback);
+ StartDownload(std::move(download_create_info), std::move(stream),
+ std::move(shared_url_loader_factory), callback);
}
-void DownloadManagerImpl::OnUrlDownloadStopped(UrlDownloadHandler* downloader) {
+void DownloadManagerImpl::OnUrlDownloadStopped(
+ download::UrlDownloadHandler* downloader) {
for (auto ptr = url_download_handlers_.begin();
ptr != url_download_handlers_.end(); ++ptr) {
if (ptr->get() == downloader) {
@@ -1069,10 +1189,10 @@ void DownloadManagerImpl::GetAllDownloads(DownloadVector* downloads) {
}
}
-void DownloadManagerImpl::OpenDownload(DownloadItemImpl* download) {
+void DownloadManagerImpl::OpenDownload(download::DownloadItemImpl* download) {
int num_unopened = 0;
for (const auto& it : downloads_) {
- DownloadItemImpl* item = it.second.get();
+ download::DownloadItemImpl* item = it.second.get();
if ((item->GetState() == download::DownloadItem::COMPLETE) &&
!item->GetOpened())
++num_unopened;
@@ -1084,12 +1204,13 @@ void DownloadManagerImpl::OpenDownload(DownloadItemImpl* download) {
}
bool DownloadManagerImpl::IsMostRecentDownloadItemAtFilePath(
- DownloadItemImpl* download) {
+ download::DownloadItemImpl* download) {
return delegate_ ? delegate_->IsMostRecentDownloadItemAtFilePath(download)
: false;
}
-void DownloadManagerImpl::ShowDownloadInShell(DownloadItemImpl* download) {
+void DownloadManagerImpl::ShowDownloadInShell(
+ download::DownloadItemImpl* download) {
if (delegate_)
delegate_->ShowDownloadInShell(download);
}
@@ -1103,27 +1224,41 @@ void DownloadManagerImpl::InterceptNavigationOnChecksComplete(
net::CertStatus cert_status,
network::mojom::URLLoaderClientEndpointsPtr url_loader_client_endpoints,
bool is_download_allowed) {
- if (!is_download_allowed)
+ if (!is_download_allowed) {
+ for (auto& observer : observers_)
+ observer.OnDownloadDropped(this);
return;
+ }
int render_process_id = -1;
int render_frame_id = -1;
- WebContents* web_contents = web_contents_getter.Run();
+ GURL site_url, tab_url, tab_referrer_url;
+ WebContents* web_contents = std::move(web_contents_getter).Run();
if (web_contents) {
RenderFrameHost* render_frame_host = web_contents->GetMainFrame();
if (render_frame_host) {
render_process_id = render_frame_host->GetProcess()->GetID();
render_frame_id = render_frame_host->GetRoutingID();
+ site_url = render_frame_host->GetSiteInstance()->GetSiteURL();
+ }
+ NavigationEntry* entry = web_contents->GetController().GetVisibleEntry();
+ if (entry) {
+ tab_url = entry->GetURL();
+ tab_referrer_url = entry->GetReferrer().url;
}
}
+ StoragePartitionImpl* storage_partition =
+ GetStoragePartition(browser_context_, render_process_id, render_frame_id);
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&DownloadManagerImpl::CreateDownloadHandlerForNavigation,
weak_factory_.GetWeakPtr(), std::move(resource_request),
- render_process_id, render_frame_id, std::move(url_chain),
- suggested_filename, std::move(response),
- std::move(cert_status),
- std::move(url_loader_client_endpoints)));
+ render_process_id, render_frame_id, site_url, tab_url,
+ tab_referrer_url, std::move(url_chain), suggested_filename,
+ std::move(response), std::move(cert_status),
+ std::move(url_loader_client_endpoints),
+ storage_partition->url_loader_factory_getter(),
+ base::MessageLoop::current()->task_runner()));
}
// static
@@ -1132,39 +1267,42 @@ void DownloadManagerImpl::CreateDownloadHandlerForNavigation(
std::unique_ptr<network::ResourceRequest> resource_request,
int render_process_id,
int render_frame_id,
+ const GURL& site_url,
+ const GURL& tab_url,
+ const GURL& tab_referrer_url,
std::vector<GURL> url_chain,
const base::Optional<std::string>& suggested_filename,
scoped_refptr<network::ResourceResponse> response,
net::CertStatus cert_status,
- network::mojom::URLLoaderClientEndpointsPtr url_loader_client_endpoints) {
+ network::mojom::URLLoaderClientEndpointsPtr url_loader_client_endpoints,
+ scoped_refptr<URLLoaderFactoryGetter> url_loader_factory_getter,
+ const scoped_refptr<base::SingleThreadTaskRunner>& task_runner) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
- std::unique_ptr<ResourceDownloader> resource_downloader =
- ResourceDownloader::InterceptNavigationResponse(
+ download::UrlDownloadHandler::UniqueUrlDownloadHandlerPtr resource_downloader(
+ download::ResourceDownloader::InterceptNavigationResponse(
download_manager, std::move(resource_request), render_process_id,
- render_frame_id, std::move(url_chain), suggested_filename,
- std::move(response), std::move(cert_status),
- std::move(url_loader_client_endpoints));
+ render_frame_id, site_url, tab_url, tab_referrer_url,
+ std::move(url_chain), suggested_filename, std::move(response),
+ std::move(cert_status), std::move(url_loader_client_endpoints),
+ url_loader_factory_getter->GetNetworkFactory(), task_runner)
+ .release(),
+ base::OnTaskRunnerDeleter(base::ThreadTaskRunnerHandle::Get()));
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
- base::BindOnce(&DownloadManagerImpl::AddUrlDownloadHandler,
- download_manager,
- DownloadManagerImpl::UniqueUrlDownloadHandlerPtr(
- resource_downloader.release())));
+ base::BindOnce(&DownloadManagerImpl::OnUrlDownloadHandlerCreated,
+ download_manager, std::move(resource_downloader)));
}
void DownloadManagerImpl::BeginDownloadInternal(
std::unique_ptr<download::DownloadUrlParameters> params,
std::unique_ptr<storage::BlobDataHandle> blob_data_handle,
- uint32_t id) {
+ uint32_t id,
+ StoragePartitionImpl* storage_partition) {
if (base::FeatureList::IsEnabled(network::features::kNetworkService)) {
std::unique_ptr<network::ResourceRequest> request =
- CreateResourceRequest(params.get());
- StoragePartitionImpl* storage_partition =
- GetStoragePartition(browser_context_, params->render_process_host_id(),
- params->render_frame_host_routing_id());
-
+ download::CreateResourceRequest(params.get());
GURL site_url, tab_url, tab_referrer_url;
auto* rfh = RenderFrameHost::FromID(params->render_process_host_id(),
params->render_frame_host_routing_id());
@@ -1178,23 +1316,30 @@ void DownloadManagerImpl::BeginDownloadInternal(
}
}
- BrowserThread::PostTaskAndReplyWithResult(
+ scoped_refptr<download::DownloadURLLoaderFactoryGetter>
+ url_loader_factory_getter;
+ if (params->url().SchemeIs(url::kBlobScheme)) {
+ url_loader_factory_getter =
+ base::MakeRefCounted<BlobDownloadURLLoaderFactoryGetter>(
+ params->url(), std::move(blob_data_handle));
+ } else {
+ url_loader_factory_getter =
+ base::MakeRefCounted<NetworkDownloadURLLoaderFactoryGetter>(
+ storage_partition->url_loader_factory_getter());
+ }
+ BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&BeginResourceDownload, std::move(params),
- std::move(request), std::move(blob_data_handle),
- storage_partition->url_loader_factory_getter(), id,
- weak_factory_.GetWeakPtr(), site_url, tab_url,
- tab_referrer_url),
- base::BindOnce(&DownloadManagerImpl::AddUrlDownloadHandler,
- weak_factory_.GetWeakPtr()));
+ std::move(request), std::move(url_loader_factory_getter),
+ id, weak_factory_.GetWeakPtr(), site_url, tab_url,
+ tab_referrer_url,
+ base::MessageLoop::current()->task_runner()));
} else {
- BrowserThread::PostTaskAndReplyWithResult(
+ BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&BeginDownload, std::move(params),
std::move(blob_data_handle),
browser_context_->GetResourceContext(), id,
- weak_factory_.GetWeakPtr()),
- base::BindOnce(&DownloadManagerImpl::AddUrlDownloadHandler,
weak_factory_.GetWeakPtr()));
}
}
diff --git a/chromium/content/browser/download/download_manager_impl.h b/chromium/content/browser/download/download_manager_impl.h
index f9698955656..13ae60ba113 100644
--- a/chromium/content/browser/download/download_manager_impl.h
+++ b/chromium/content/browser/download/download_manager_impl.h
@@ -20,9 +20,9 @@
#include "base/observer_list.h"
#include "base/sequenced_task_runner_helpers.h"
#include "base/synchronization/lock.h"
+#include "components/download/public/common/download_item_impl_delegate.h"
#include "components/download/public/common/download_url_parameters.h"
-#include "content/browser/download/download_item_impl_delegate.h"
-#include "content/browser/download/url_download_handler.h"
+#include "components/download/public/common/url_download_handler.h"
#include "content/browser/loader/navigation_url_loader.h"
#include "content/common/content_export.h"
#include "content/public/browser/browser_thread.h"
@@ -33,22 +33,24 @@
#include "services/network/public/mojom/url_loader.mojom.h"
namespace download {
+class DownloadFileFactory;
+class DownloadItemFactory;
+class DownloadItemImpl;
class DownloadRequestHandleInterface;
}
namespace content {
-class DownloadFileFactory;
-class DownloadItemFactory;
-class DownloadItemImpl;
class ResourceContext;
+class StoragePartitionImpl;
+class URLLoaderFactoryGetter;
-class CONTENT_EXPORT DownloadManagerImpl : public DownloadManager,
- public UrlDownloadHandler::Delegate,
- private DownloadItemImplDelegate {
+class CONTENT_EXPORT DownloadManagerImpl
+ : public DownloadManager,
+ public download::UrlDownloadHandler::Delegate,
+ private download::DownloadItemImplDelegate {
public:
- using DownloadItemImplCreated = base::Callback<void(DownloadItemImpl*)>;
- using UniqueUrlDownloadHandlerPtr =
- std::unique_ptr<UrlDownloadHandler, BrowserThread::DeleteOnIOThread>;
+ using DownloadItemImplCreated =
+ base::Callback<void(download::DownloadItemImpl*)>;
// Caller guarantees that |net_log| will remain valid
// for the lifetime of DownloadManagerImpl (until Shutdown() is called).
@@ -75,10 +77,12 @@ class CONTENT_EXPORT DownloadManagerImpl : public DownloadManager,
DownloadManagerDelegate* GetDelegate() const override;
void Shutdown() override;
void GetAllDownloads(DownloadVector* result) override;
- void StartDownload(std::unique_ptr<download::DownloadCreateInfo> info,
- std::unique_ptr<DownloadManager::InputStream> stream,
- const download::DownloadUrlParameters::OnStartedCallback&
- on_started) override;
+ void StartDownload(
+ std::unique_ptr<download::DownloadCreateInfo> info,
+ std::unique_ptr<download::InputStream> stream,
+ scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory,
+ const download::DownloadUrlParameters::OnStartedCallback& on_started)
+ override;
int RemoveDownloadsByURLAndTime(
const base::Callback<bool(const GURL&)>& url_filter,
@@ -130,17 +134,21 @@ class CONTENT_EXPORT DownloadManagerImpl : public DownloadManager,
// UrlDownloadHandler::Delegate implementation.
void OnUrlDownloadStarted(
std::unique_ptr<download::DownloadCreateInfo> download_create_info,
- std::unique_ptr<DownloadManager::InputStream> stream,
+ std::unique_ptr<download::InputStream> stream,
+ scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory,
const download::DownloadUrlParameters::OnStartedCallback& callback)
override;
- void OnUrlDownloadStopped(UrlDownloadHandler* downloader) override;
+ void OnUrlDownloadStopped(download::UrlDownloadHandler* downloader) override;
+ void OnUrlDownloadHandlerCreated(
+ download::UrlDownloadHandler::UniqueUrlDownloadHandlerPtr downloader)
+ override;
// For testing; specifically, accessed from TestFileErrorInjector.
void SetDownloadItemFactoryForTesting(
- std::unique_ptr<DownloadItemFactory> item_factory);
+ std::unique_ptr<download::DownloadItemFactory> item_factory);
void SetDownloadFileFactoryForTesting(
- std::unique_ptr<DownloadFileFactory> file_factory);
- virtual DownloadFileFactory* GetDownloadFileFactoryForTesting();
+ std::unique_ptr<download::DownloadFileFactory> file_factory);
+ virtual download::DownloadFileFactory* GetDownloadFileFactoryForTesting();
// Helper function to initiate a download request. This function initiates
// the download using functionality provided by the
@@ -165,8 +173,9 @@ class CONTENT_EXPORT DownloadManagerImpl : public DownloadManager,
private:
using DownloadSet = std::set<download::DownloadItem*>;
- using DownloadGuidMap = std::unordered_map<std::string, DownloadItemImpl*>;
- using DownloadItemImplVector = std::vector<DownloadItemImpl*>;
+ using DownloadGuidMap =
+ std::unordered_map<std::string, download::DownloadItemImpl*>;
+ using DownloadItemImplVector = std::vector<download::DownloadItemImpl*>;
// For testing.
friend class DownloadManagerTest;
@@ -174,7 +183,8 @@ class CONTENT_EXPORT DownloadManagerImpl : public DownloadManager,
void StartDownloadWithId(
std::unique_ptr<download::DownloadCreateInfo> info,
- std::unique_ptr<DownloadManager::InputStream> stream,
+ std::unique_ptr<download::InputStream> stream,
+ scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory,
const download::DownloadUrlParameters::OnStartedCallback& on_started,
bool new_download,
uint32_t id);
@@ -196,8 +206,9 @@ class CONTENT_EXPORT DownloadManagerImpl : public DownloadManager,
// Create a new active item based on the info. Separate from
// StartDownload() for testing.
- DownloadItemImpl* CreateActiveItem(uint32_t id,
- const download::DownloadCreateInfo& info);
+ download::DownloadItemImpl* CreateActiveItem(
+ uint32_t id,
+ const download::DownloadCreateInfo& info);
// Get next download id. |callback| is called on the UI thread and may
// be called synchronously.
@@ -210,30 +221,36 @@ class CONTENT_EXPORT DownloadManagerImpl : public DownloadManager,
// Overridden from DownloadItemImplDelegate
// (Note that |GetBrowserContext| are present in both interfaces.)
- void DetermineDownloadTarget(DownloadItemImpl* item,
+ void DetermineDownloadTarget(download::DownloadItemImpl* item,
const DownloadTargetCallback& callback) override;
- bool ShouldCompleteDownload(DownloadItemImpl* item,
+ bool ShouldCompleteDownload(download::DownloadItemImpl* item,
const base::Closure& complete_callback) override;
bool ShouldOpenFileBasedOnExtension(const base::FilePath& path) override;
- bool ShouldOpenDownload(DownloadItemImpl* item,
+ bool ShouldOpenDownload(download::DownloadItemImpl* item,
const ShouldOpenDownloadCallback& callback) override;
- void CheckForFileRemoval(DownloadItemImpl* download_item) override;
+ void CheckForFileRemoval(download::DownloadItemImpl* download_item) override;
std::string GetApplicationClientIdForFileScanning() const override;
void ResumeInterruptedDownload(
std::unique_ptr<download::DownloadUrlParameters> params,
- uint32_t id) override;
- void OpenDownload(DownloadItemImpl* download) override;
- bool IsMostRecentDownloadItemAtFilePath(DownloadItemImpl* download) override;
- void ShowDownloadInShell(DownloadItemImpl* download) override;
- void DownloadRemoved(DownloadItemImpl* download) override;
-
- void AddUrlDownloadHandler(UniqueUrlDownloadHandlerPtr downloader);
+ uint32_t id,
+ const GURL& site_url) override;
+ void OpenDownload(download::DownloadItemImpl* download) override;
+ bool IsMostRecentDownloadItemAtFilePath(
+ download::DownloadItemImpl* download) override;
+ void ShowDownloadInShell(download::DownloadItemImpl* download) override;
+ void DownloadRemoved(download::DownloadItemImpl* download) override;
+ void DownloadInterrupted(download::DownloadItemImpl* download) override;
+ base::Optional<download::DownloadEntry> GetInProgressEntry(
+ download::DownloadItemImpl* download) override;
+ bool IsOffTheRecord() const override;
+ void ReportBytesWasted(download::DownloadItemImpl* download) override;
// Helper method to start or resume a download.
void BeginDownloadInternal(
std::unique_ptr<download::DownloadUrlParameters> params,
std::unique_ptr<storage::BlobDataHandle> blob_data_handle,
- uint32_t id);
+ uint32_t id,
+ StoragePartitionImpl* storage_partition);
void InterceptNavigationOnChecksComplete(
ResourceRequestInfo::WebContentsGetter web_contents_getter,
@@ -253,17 +270,22 @@ class CONTENT_EXPORT DownloadManagerImpl : public DownloadManager,
std::unique_ptr<network::ResourceRequest> resource_request,
int render_process_id,
int render_frame_id,
+ const GURL& site_url,
+ const GURL& tab_url,
+ const GURL& tab_referrer_url,
std::vector<GURL> url_chain,
const base::Optional<std::string>& suggested_filename,
scoped_refptr<network::ResourceResponse> response,
net::CertStatus cert_status,
- network::mojom::URLLoaderClientEndpointsPtr url_loader_client_endpoints);
+ network::mojom::URLLoaderClientEndpointsPtr url_loader_client_endpoints,
+ scoped_refptr<URLLoaderFactoryGetter> url_loader_factory_getter,
+ const scoped_refptr<base::SingleThreadTaskRunner>& task_runner);
// Factory for creation of downloads items.
- std::unique_ptr<DownloadItemFactory> item_factory_;
+ std::unique_ptr<download::DownloadItemFactory> item_factory_;
// Factory for the creation of download files.
- std::unique_ptr<DownloadFileFactory> file_factory_;
+ std::unique_ptr<download::DownloadFileFactory> file_factory_;
// |downloads_| is the owning set for all downloads known to the
// DownloadManager. This includes downloads started by the user in
@@ -271,7 +293,8 @@ class CONTENT_EXPORT DownloadManagerImpl : public DownloadManager,
// "save page as" downloads.
// TODO(asanka): Remove this container in favor of downloads_by_guid_ as a
// part of http://crbug.com/593020.
- std::unordered_map<uint32_t, std::unique_ptr<DownloadItemImpl>> downloads_;
+ std::unordered_map<uint32_t, std::unique_ptr<download::DownloadItemImpl>>
+ downloads_;
// Same as the above, but maps from GUID to download item. Note that the
// container is case sensitive. Hence the key needs to be normalized to
@@ -302,7 +325,8 @@ class CONTENT_EXPORT DownloadManagerImpl : public DownloadManager,
// Allows an embedder to control behavior. Guaranteed to outlive this object.
DownloadManagerDelegate* delegate_;
- std::vector<UniqueUrlDownloadHandlerPtr> url_download_handlers_;
+ std::vector<download::UrlDownloadHandler::UniqueUrlDownloadHandlerPtr>
+ url_download_handlers_;
base::WeakPtrFactory<DownloadManagerImpl> weak_factory_;
diff --git a/chromium/content/browser/download/download_manager_impl_unittest.cc b/chromium/content/browser/download/download_manager_impl_unittest.cc
index 9e297fe4f75..ccbc17a8954 100644
--- a/chromium/content/browser/download/download_manager_impl_unittest.cc
+++ b/chromium/content/browser/download/download_manager_impl_unittest.cc
@@ -11,6 +11,7 @@
#include <memory>
#include <set>
#include <string>
+#include <tuple>
#include <utility>
#include "base/bind.h"
@@ -25,19 +26,20 @@
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "components/download/public/common/download_create_info.h"
+#include "components/download/public/common/download_file_factory.h"
#include "components/download/public/common/download_interrupt_reasons.h"
#include "components/download/public/common/download_item.h"
+#include "components/download/public/common/download_item_factory.h"
+#include "components/download/public/common/download_item_impl.h"
+#include "components/download/public/common/download_item_impl_delegate.h"
#include "components/download/public/common/download_request_handle_interface.h"
+#include "components/download/public/common/mock_download_file.h"
+#include "components/download/public/common/mock_download_item_impl.h"
#include "content/browser/byte_stream.h"
-#include "content/browser/download/download_file_factory.h"
-#include "content/browser/download/download_item_factory.h"
-#include "content/browser/download/download_item_impl.h"
-#include "content/browser/download/download_item_impl_delegate.h"
-#include "content/browser/download/mock_download_file.h"
-#include "content/browser/download/mock_download_item_impl.h"
+#include "content/browser/download/byte_stream_input_stream.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/download_manager_delegate.h"
-#include "content/public/test/mock_download_item.h"
+#include "content/public/browser/storage_partition.h"
#include "content/public/test/test_browser_context.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "testing/gmock/include/gmock/gmock.h"
@@ -45,10 +47,6 @@
#include "testing/gtest/include/gtest/gtest.h"
#include "url/origin.h"
-#if !defined(OS_ANDROID)
-#include "content/public/browser/zoom_level_delegate.h"
-#endif // !defined(OS_ANDROID)
-
using ::testing::AllOf;
using ::testing::DoAll;
using ::testing::Eq;
@@ -63,7 +61,7 @@ using ::testing::_;
ACTION_TEMPLATE(RunCallback,
HAS_1_TEMPLATE_PARAMS(int, k),
AND_1_VALUE_PARAMS(p0)) {
- return ::std::tr1::get<k>(args).Run(p0);
+ return std::get<k>(args).Run(p0);
}
namespace content {
@@ -100,7 +98,7 @@ MockDownloadManagerDelegate::MockDownloadManagerDelegate() {}
MockDownloadManagerDelegate::~MockDownloadManagerDelegate() {}
class MockDownloadItemFactory
- : public DownloadItemFactory,
+ : public download::DownloadItemFactory,
public base::SupportsWeakPtr<MockDownloadItemFactory> {
public:
MockDownloadItemFactory();
@@ -111,11 +109,11 @@ class MockDownloadItemFactory
// functionality if it's ever needed by consumers.
// Returns NULL if no item of that id is present.
- MockDownloadItemImpl* GetItem(int id);
+ download::MockDownloadItemImpl* GetItem(int id);
// Remove and return an item made by the factory.
// Generally used during teardown.
- MockDownloadItemImpl* PopItem();
+ download::MockDownloadItemImpl* PopItem();
// Should be called when the item of this id is removed so that
// we don't keep dangling pointers.
@@ -126,8 +124,8 @@ class MockDownloadItemFactory
void SetHasObserverCalls(bool observer_calls);
// Overridden methods from DownloadItemFactory.
- DownloadItemImpl* CreatePersistedItem(
- DownloadItemImplDelegate* delegate,
+ download::DownloadItemImpl* CreatePersistedItem(
+ download::DownloadItemImplDelegate* delegate,
const std::string& guid,
uint32_t download_id,
const base::FilePath& current_path,
@@ -154,12 +152,12 @@ class MockDownloadItemFactory
bool transient,
const std::vector<download::DownloadItem::ReceivedSlice>& received_slices)
override;
- DownloadItemImpl* CreateActiveItem(
- DownloadItemImplDelegate* delegate,
+ download::DownloadItemImpl* CreateActiveItem(
+ download::DownloadItemImplDelegate* delegate,
uint32_t download_id,
const download::DownloadCreateInfo& info) override;
- DownloadItemImpl* CreateSavePageItem(
- DownloadItemImplDelegate* delegate,
+ download::DownloadItemImpl* CreateSavePageItem(
+ download::DownloadItemImplDelegate* delegate,
uint32_t download_id,
const base::FilePath& path,
const GURL& url,
@@ -168,8 +166,8 @@ class MockDownloadItemFactory
override;
private:
- std::map<uint32_t, MockDownloadItemImpl*> items_;
- DownloadItemImplDelegate item_delegate_;
+ std::map<uint32_t, download::MockDownloadItemImpl*> items_;
+ download::DownloadItemImplDelegate item_delegate_;
bool has_observer_calls_;
DISALLOW_COPY_AND_ASSIGN(MockDownloadItemFactory);
@@ -180,19 +178,19 @@ MockDownloadItemFactory::MockDownloadItemFactory()
MockDownloadItemFactory::~MockDownloadItemFactory() {}
-MockDownloadItemImpl* MockDownloadItemFactory::GetItem(int id) {
+download::MockDownloadItemImpl* MockDownloadItemFactory::GetItem(int id) {
if (items_.find(id) == items_.end())
return nullptr;
return items_[id];
}
-MockDownloadItemImpl* MockDownloadItemFactory::PopItem() {
+download::MockDownloadItemImpl* MockDownloadItemFactory::PopItem() {
if (items_.empty())
return nullptr;
- std::map<uint32_t, MockDownloadItemImpl*>::iterator first_item =
+ std::map<uint32_t, download::MockDownloadItemImpl*>::iterator first_item =
items_.begin();
- MockDownloadItemImpl* result = first_item->second;
+ download::MockDownloadItemImpl* result = first_item->second;
items_.erase(first_item);
return result;
}
@@ -206,8 +204,8 @@ void MockDownloadItemFactory::SetHasObserverCalls(bool has_observer_calls) {
has_observer_calls_ = has_observer_calls;
}
-DownloadItemImpl* MockDownloadItemFactory::CreatePersistedItem(
- DownloadItemImplDelegate* delegate,
+download::DownloadItemImpl* MockDownloadItemFactory::CreatePersistedItem(
+ download::DownloadItemImplDelegate* delegate,
const std::string& guid,
uint32_t download_id,
const base::FilePath& current_path,
@@ -234,8 +232,8 @@ DownloadItemImpl* MockDownloadItemFactory::CreatePersistedItem(
bool transient,
const std::vector<download::DownloadItem::ReceivedSlice>& received_slices) {
DCHECK(items_.find(download_id) == items_.end());
- MockDownloadItemImpl* result =
- new StrictMock<MockDownloadItemImpl>(&item_delegate_);
+ download::MockDownloadItemImpl* result =
+ new StrictMock<download::MockDownloadItemImpl>(&item_delegate_);
EXPECT_CALL(*result, GetId())
.WillRepeatedly(Return(download_id));
EXPECT_CALL(*result, GetGuid()).WillRepeatedly(ReturnRefOfCopy(guid));
@@ -243,14 +241,14 @@ DownloadItemImpl* MockDownloadItemFactory::CreatePersistedItem(
return result;
}
-DownloadItemImpl* MockDownloadItemFactory::CreateActiveItem(
- DownloadItemImplDelegate* delegate,
+download::DownloadItemImpl* MockDownloadItemFactory::CreateActiveItem(
+ download::DownloadItemImplDelegate* delegate,
uint32_t download_id,
const download::DownloadCreateInfo& info) {
DCHECK(items_.find(download_id) == items_.end());
- MockDownloadItemImpl* result =
- new StrictMock<MockDownloadItemImpl>(&item_delegate_);
+ download::MockDownloadItemImpl* result =
+ new StrictMock<download::MockDownloadItemImpl>(&item_delegate_);
EXPECT_CALL(*result, GetId())
.WillRepeatedly(Return(download_id));
EXPECT_CALL(*result, GetGuid())
@@ -270,8 +268,8 @@ DownloadItemImpl* MockDownloadItemFactory::CreateActiveItem(
return result;
}
-DownloadItemImpl* MockDownloadItemFactory::CreateSavePageItem(
- DownloadItemImplDelegate* delegate,
+download::DownloadItemImpl* MockDownloadItemFactory::CreateSavePageItem(
+ download::DownloadItemImplDelegate* delegate,
uint32_t download_id,
const base::FilePath& path,
const GURL& url,
@@ -279,8 +277,8 @@ DownloadItemImpl* MockDownloadItemFactory::CreateSavePageItem(
std::unique_ptr<download::DownloadRequestHandleInterface> request_handle) {
DCHECK(items_.find(download_id) == items_.end());
- MockDownloadItemImpl* result =
- new StrictMock<MockDownloadItemImpl>(&item_delegate_);
+ download::MockDownloadItemImpl* result =
+ new StrictMock<download::MockDownloadItemImpl>(&item_delegate_);
EXPECT_CALL(*result, GetId())
.WillRepeatedly(Return(download_id));
items_[download_id] = result;
@@ -289,7 +287,7 @@ DownloadItemImpl* MockDownloadItemFactory::CreateSavePageItem(
}
class MockDownloadFileFactory
- : public DownloadFileFactory,
+ : public download::DownloadFileFactory,
public base::SupportsWeakPtr<MockDownloadFileFactory> {
public:
MockDownloadFileFactory() {}
@@ -297,74 +295,19 @@ class MockDownloadFileFactory
// Overridden method from DownloadFileFactory
MOCK_METHOD2(MockCreateFile,
- MockDownloadFile*(const download::DownloadSaveInfo&,
- DownloadManager::InputStream*));
+ download::MockDownloadFile*(const download::DownloadSaveInfo&,
+ download::InputStream*));
- DownloadFile* CreateFile(
+ download::DownloadFile* CreateFile(
std::unique_ptr<download::DownloadSaveInfo> save_info,
const base::FilePath& default_download_directory,
- std::unique_ptr<DownloadManager::InputStream> stream,
+ std::unique_ptr<download::InputStream> stream,
uint32_t download_id,
- base::WeakPtr<DownloadDestinationObserver> observer) override {
+ base::WeakPtr<download::DownloadDestinationObserver> observer) override {
return MockCreateFile(*save_info, stream.get());
}
};
-class MockBrowserContext : public BrowserContext {
- public:
- MockBrowserContext() {
- content::BrowserContext::Initialize(this, base::FilePath());
- }
- ~MockBrowserContext() {}
-
- MOCK_CONST_METHOD0(GetPath, base::FilePath());
-#if !defined(OS_ANDROID)
- MOCK_METHOD1(CreateZoomLevelDelegateMock,
- ZoomLevelDelegate*(const base::FilePath&));
-#endif // !defined(OS_ANDROID)
- MOCK_CONST_METHOD0(IsOffTheRecord, bool());
- MOCK_METHOD0(GetResourceContext, ResourceContext*());
- MOCK_METHOD0(GetDownloadManagerDelegate, DownloadManagerDelegate*());
- MOCK_METHOD0(GetGuestManager, BrowserPluginGuestManager* ());
- MOCK_METHOD0(GetSpecialStoragePolicy, storage::SpecialStoragePolicy*());
- MOCK_METHOD0(GetPushMessagingService, PushMessagingService*());
- MOCK_METHOD0(GetSSLHostStateDelegate, SSLHostStateDelegate*());
- MOCK_METHOD0(GetPermissionManager, PermissionManager*());
- MOCK_METHOD0(GetBackgroundFetchDelegate, BackgroundFetchDelegate*());
- MOCK_METHOD0(GetBackgroundSyncController, BackgroundSyncController*());
- MOCK_METHOD0(GetBrowsingDataRemoverDelegate, BrowsingDataRemoverDelegate*());
- MOCK_METHOD0(CreateMediaRequestContext,
- net::URLRequestContextGetter*());
- MOCK_METHOD2(CreateMediaRequestContextForStoragePartition,
- net::URLRequestContextGetter*(
- const base::FilePath& partition_path, bool in_memory));
-
- // Define these two methods to avoid a
- // 'cannot access private member declared in class
- // URLRequestInterceptorScopedVector'
- // build error if they're put in MOCK_METHOD.
- net::URLRequestContextGetter* CreateRequestContext(
- ProtocolHandlerMap* protocol_handlers,
- URLRequestInterceptorScopedVector request_interceptors) override {
- return nullptr;
- }
-
- net::URLRequestContextGetter* CreateRequestContextForStoragePartition(
- const base::FilePath& partition_path,
- bool in_memory,
- ProtocolHandlerMap* protocol_handlers,
- URLRequestInterceptorScopedVector request_interceptors) override {
- return nullptr;
- }
-#if !defined(OS_ANDROID)
- std::unique_ptr<ZoomLevelDelegate> CreateZoomLevelDelegate(
- const base::FilePath& path) override {
- return std::unique_ptr<ZoomLevelDelegate>(
- CreateZoomLevelDelegateMock(path));
- }
-#endif // !defined(OS_ANDROID)
-};
-
class MockDownloadManagerObserver : public DownloadManager::Observer {
public:
MockDownloadManagerObserver() {}
@@ -413,17 +356,13 @@ class DownloadManagerTest : public testing::Test {
new StrictMock<MockDownloadManagerDelegate>);
EXPECT_CALL(*mock_download_manager_delegate_.get(), Shutdown())
.WillOnce(Return());
- mock_browser_context_.reset(new StrictMock<MockBrowserContext>);
- EXPECT_CALL(*mock_browser_context_.get(), IsOffTheRecord())
- .WillRepeatedly(Return(false));
-
- download_manager_.reset(
- new DownloadManagerImpl(mock_browser_context_.get()));
+ browser_context_ = std::make_unique<TestBrowserContext>();
+ download_manager_.reset(new DownloadManagerImpl(browser_context_.get()));
download_manager_->SetDownloadItemFactoryForTesting(
- std::unique_ptr<DownloadItemFactory>(
+ std::unique_ptr<download::DownloadItemFactory>(
mock_download_item_factory_.get()));
download_manager_->SetDownloadFileFactoryForTesting(
- std::unique_ptr<DownloadFileFactory>(
+ std::unique_ptr<download::DownloadFileFactory>(
mock_download_file_factory_.get()));
observer_.reset(new MockDownloadManagerObserver());
download_manager_->AddObserver(observer_.get());
@@ -435,8 +374,8 @@ class DownloadManagerTest : public testing::Test {
}
void TearDown() override {
- while (MockDownloadItemImpl*
- item = mock_download_item_factory_->PopItem()) {
+ while (download::MockDownloadItemImpl* item =
+ mock_download_item_factory_->PopItem()) {
EXPECT_CALL(*item, GetState())
.WillOnce(Return(download::DownloadItem::CANCELLED));
}
@@ -448,12 +387,11 @@ class DownloadManagerTest : public testing::Test {
base::RunLoop().RunUntilIdle();
ASSERT_FALSE(mock_download_item_factory_);
mock_download_manager_delegate_.reset();
- mock_browser_context_.reset();
download_urls_.clear();
}
// Returns download id.
- MockDownloadItemImpl& AddItemToManager() {
+ download::MockDownloadItemImpl& AddItemToManager() {
download::DownloadCreateInfo info;
// Args are ignored except for download id, so everything else can be
@@ -462,20 +400,23 @@ class DownloadManagerTest : public testing::Test {
++next_download_id_;
download_manager_->CreateActiveItem(id, info);
DCHECK(mock_download_item_factory_->GetItem(id));
- MockDownloadItemImpl& item(*mock_download_item_factory_->GetItem(id));
+ download::MockDownloadItemImpl& item(
+ *mock_download_item_factory_->GetItem(id));
// Satisfy expectation. If the item is created in StartDownload(),
// we call Start on it immediately, so we need to set that expectation
// in the factory.
std::unique_ptr<download::DownloadRequestHandleInterface> req_handle;
- item.Start(std::unique_ptr<DownloadFile>(), std::move(req_handle), info);
+ item.Start(std::unique_ptr<download::DownloadFile>(), std::move(req_handle),
+ info, nullptr, nullptr);
DCHECK(id < download_urls_.size());
EXPECT_CALL(item, GetURL()).WillRepeatedly(ReturnRef(download_urls_[id]));
return item;
}
- MockDownloadItemImpl& GetMockDownloadItem(int id) {
- MockDownloadItemImpl* itemp = mock_download_item_factory_->GetItem(id);
+ download::MockDownloadItemImpl& GetMockDownloadItem(int id) {
+ download::MockDownloadItemImpl* itemp =
+ mock_download_item_factory_->GetItem(id);
DCHECK(itemp);
return *itemp;
@@ -508,7 +449,7 @@ class DownloadManagerTest : public testing::Test {
interrupt_reason_ = interrupt_reason;
}
- void DetermineDownloadTarget(DownloadItemImpl* item) {
+ void DetermineDownloadTarget(download::DownloadItemImpl* item) {
download_manager_->DetermineDownloadTarget(
item, base::Bind(
&DownloadManagerTest::DownloadTargetDeterminedCallback,
@@ -538,8 +479,8 @@ class DownloadManagerTest : public testing::Test {
TestBrowserThreadBundle thread_bundle_;
base::WeakPtr<MockDownloadItemFactory> mock_download_item_factory_;
std::unique_ptr<MockDownloadManagerDelegate> mock_download_manager_delegate_;
- std::unique_ptr<MockBrowserContext> mock_browser_context_;
std::unique_ptr<MockDownloadManagerObserver> observer_;
+ std::unique_ptr<TestBrowserContext> browser_context_;
uint32_t next_download_id_;
DISALLOW_COPY_AND_ASSIGN(DownloadManagerTest);
@@ -569,15 +510,15 @@ TEST_F(DownloadManagerTest, StartDownload) {
EXPECT_CALL(GetMockDownloadManagerDelegate(),
ApplicationClientIdForFileScanning())
.WillRepeatedly(Return("client-id"));
- MockDownloadFile* mock_file = new MockDownloadFile;
+ download::MockDownloadFile* mock_file = new download::MockDownloadFile;
auto input_stream =
- std::make_unique<DownloadManager::InputStream>(std::move(stream));
+ std::make_unique<ByteStreamInputStream>(std::move(stream));
EXPECT_CALL(*mock_download_file_factory_.get(),
MockCreateFile(Ref(*info->save_info.get()), input_stream.get()))
.WillOnce(Return(mock_file));
download_manager_->StartDownload(
- std::move(info), std::move(input_stream),
+ std::move(info), std::move(input_stream), nullptr,
download::DownloadUrlParameters::OnStartedCallback());
EXPECT_TRUE(download_manager_->GetDownload(local_id));
@@ -588,7 +529,7 @@ TEST_F(DownloadManagerTest, StartDownload) {
// blocks starting.
TEST_F(DownloadManagerTest, DetermineDownloadTarget_True) {
// Put a mock we have a handle to on the download manager.
- MockDownloadItemImpl& item(AddItemToManager());
+ download::MockDownloadItemImpl& item(AddItemToManager());
EXPECT_CALL(item, GetState())
.WillRepeatedly(Return(download::DownloadItem::IN_PROGRESS));
@@ -602,7 +543,7 @@ TEST_F(DownloadManagerTest, DetermineDownloadTarget_True) {
// allows starting. This also tests OnDownloadTargetDetermined.
TEST_F(DownloadManagerTest, DetermineDownloadTarget_False) {
// Put a mock we have a handle to on the download manager.
- MockDownloadItemImpl& item(AddItemToManager());
+ download::MockDownloadItemImpl& item(AddItemToManager());
base::FilePath path(FILE_PATH_LITERAL("random_filepath.txt"));
EXPECT_CALL(GetMockDownloadManagerDelegate(),
@@ -626,7 +567,7 @@ TEST_F(DownloadManagerTest, GetDownloadByGuid) {
for (uint32_t i = 0; i < 4; ++i)
AddItemToManager();
- MockDownloadItemImpl& item = GetMockDownloadItem(0);
+ download::MockDownloadItemImpl& item = GetMockDownloadItem(0);
download::DownloadItem* result =
download_manager_->GetDownloadByGuid(item.GetGuid());
ASSERT_TRUE(result);
@@ -665,7 +606,7 @@ base::Callback<bool(const GURL&)> GetSingleURLFilter(const GURL& url) {
TEST_F(DownloadManagerTest, RemoveDownloadsByURL) {
base::Time now(base::Time::Now());
for (uint32_t i = 0; i < 2; ++i) {
- MockDownloadItemImpl& item(AddItemToManager());
+ download::MockDownloadItemImpl& item(AddItemToManager());
EXPECT_CALL(item, GetStartTime()).WillRepeatedly(Return(now));
EXPECT_CALL(item, GetState())
.WillRepeatedly(Return(download::DownloadItem::COMPLETE));
@@ -677,7 +618,7 @@ TEST_F(DownloadManagerTest, RemoveDownloadsByURL) {
base::Callback<bool(const GURL&)> url_filter =
GetSingleURLFilter(download_urls_[0]);
int remove_count = download_manager_->RemoveDownloadsByURLAndTime(
- url_filter, base::Time(), base::Time::Max());
+ std::move(url_filter), base::Time(), base::Time::Max());
EXPECT_EQ(remove_count, 1);
}
diff --git a/chromium/content/browser/download/download_request_core.cc b/chromium/content/browser/download/download_request_core.cc
index 18fb3da94a7..b7eb780ae47 100644
--- a/chromium/content/browser/download/download_request_core.cc
+++ b/chromium/content/browser/download/download_request_core.cc
@@ -11,18 +11,18 @@
#include "base/format_macros.h"
#include "base/location.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_functions.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "components/download/public/common/download_create_info.h"
+#include "components/download/public/common/download_interrupt_reasons_utils.h"
#include "components/download/public/common/download_item.h"
#include "components/download/public/common/download_stats.h"
#include "components/download/public/common/download_task_runner.h"
+#include "components/download/public/common/download_utils.h"
#include "content/browser/byte_stream.h"
-#include "content/browser/download/download_interrupt_reasons_utils.h"
#include "content/browser/download/download_manager_impl.h"
#include "content/browser/download/download_request_handle.h"
#include "content/browser/download/download_utils.h"
@@ -67,6 +67,10 @@ class DownloadRequestData : public base::SupportsUserData::Data {
std::string guid() const { return guid_; }
bool is_transient() const { return transient_; }
bool fetch_error_body() const { return fetch_error_body_; }
+ const download::DownloadUrlParameters::RequestHeadersType& request_headers()
+ const {
+ return request_headers_;
+ }
const download::DownloadUrlParameters::OnStartedCallback& callback() const {
return on_started_callback_;
}
@@ -79,6 +83,7 @@ class DownloadRequestData : public base::SupportsUserData::Data {
uint32_t download_id_ = download::DownloadItem::kInvalidId;
std::string guid_;
bool fetch_error_body_ = false;
+ download::DownloadUrlParameters::RequestHeadersType request_headers_;
bool transient_ = false;
download::DownloadUrlParameters::OnStartedCallback on_started_callback_;
std::string request_origin_;
@@ -97,6 +102,7 @@ void DownloadRequestData::Attach(net::URLRequest* request,
request_data->download_id_ = download_id;
request_data->guid_ = parameters->guid();
request_data->fetch_error_body_ = parameters->fetch_error_body();
+ request_data->request_headers_ = parameters->request_headers();
request_data->transient_ = parameters->is_transient();
request_data->on_started_callback_ = parameters->callback();
request_data->request_origin_ = parameters->request_origin();
@@ -190,6 +196,7 @@ DownloadRequestCore::DownloadRequestCore(
download_id_ = request_data->download_id();
guid_ = request_data->guid();
fetch_error_body_ = request_data->fetch_error_body();
+ request_headers_ = request_data->request_headers();
transient_ = request_data->is_transient();
on_started_callback_ = request_data->callback();
DownloadRequestData::Detach(request_);
@@ -234,6 +241,7 @@ DownloadRequestCore::CreateDownloadCreateInfo(
create_info->response_headers = request()->response_headers();
create_info->offset = create_info->save_info->offset;
create_info->fetch_error_body = fetch_error_body_;
+ create_info->request_headers = request_headers_;
create_info->request_origin = request_origin_;
create_info->download_source = download_source_;
return create_info;
@@ -246,10 +254,10 @@ bool DownloadRequestCore::OnResponseStarted(
download_start_time_ = base::TimeTicks::Now();
download::DownloadInterruptReason result =
- request()->response_headers()
- ? HandleSuccessfulServerResponse(*request()->response_headers(),
- save_info_.get(), fetch_error_body_)
- : download::DOWNLOAD_INTERRUPT_REASON_NONE;
+ request()->response_headers() ? download::HandleSuccessfulServerResponse(
+ *request()->response_headers(),
+ save_info_.get(), fetch_error_body_)
+ : download::DOWNLOAD_INTERRUPT_REASON_NONE;
if (request()->response_headers()) {
download::RecordDownloadHttpResponseCode(
@@ -287,7 +295,7 @@ bool DownloadRequestCore::OnResponseStarted(
// Get the last modified time and etag.
const net::HttpResponseHeaders* headers = request()->response_headers();
- HandleResponseHeaders(headers, create_info.get());
+ download::HandleResponseHeaders(headers, create_info.get());
// If the content-length header is not present (or contains something other
// than numbers), the incoming content_length is -1 (unknown size).
@@ -399,9 +407,10 @@ void DownloadRequestCore::OnResponseCompleted(
if (error_code == net::OK)
error_code = net::ERR_FAILED;
}
- download::DownloadInterruptReason reason = HandleRequestCompletionStatus(
- error_code, has_strong_validators, request()->ssl_info().cert_status,
- abort_reason_);
+ download::DownloadInterruptReason reason =
+ download::HandleRequestCompletionStatus(error_code, has_strong_validators,
+ request()->ssl_info().cert_status,
+ abort_reason_);
std::string accept_ranges;
if (request()->response_headers()) {
diff --git a/chromium/content/browser/download/download_request_core.h b/chromium/content/browser/download/download_request_core.h
index 305754370eb..409e3e3912d 100644
--- a/chromium/content/browser/download/download_request_core.h
+++ b/chromium/content/browser/download/download_request_core.h
@@ -132,6 +132,7 @@ class CONTENT_EXPORT DownloadRequestCore
uint32_t download_id_;
std::string guid_;
bool fetch_error_body_;
+ download::DownloadUrlParameters::RequestHeadersType request_headers_;
bool transient_;
download::DownloadUrlParameters::OnStartedCallback on_started_callback_;
diff --git a/chromium/content/browser/download/download_request_core_unittest.cc b/chromium/content/browser/download/download_request_core_unittest.cc
index 020b4d25701..4d9c0db919d 100644
--- a/chromium/content/browser/download/download_request_core_unittest.cc
+++ b/chromium/content/browser/download/download_request_core_unittest.cc
@@ -4,10 +4,9 @@
#include <memory>
-#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
+#include "components/download/public/common/download_item.h"
#include "components/download/public/common/download_url_parameters.h"
-#include "content/browser/download/download_item_impl.h"
#include "content/browser/download/download_request_core.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/test_browser_thread_bundle.h"
diff --git a/chromium/content/browser/download/download_resource_handler.cc b/chromium/content/browser/download/download_resource_handler.cc
index bef13a0eaa0..d409db6c596 100644
--- a/chromium/content/browser/download/download_resource_handler.cc
+++ b/chromium/content/browser/download/download_resource_handler.cc
@@ -13,10 +13,11 @@
#include "base/strings/stringprintf.h"
#include "components/download/public/common/download_create_info.h"
#include "components/download/public/common/download_interrupt_reasons.h"
+#include "components/download/public/common/download_interrupt_reasons_utils.h"
#include "components/download/public/common/download_task_runner.h"
#include "components/download/public/common/download_ukm_helper.h"
#include "content/browser/byte_stream.h"
-#include "content/browser/download/download_interrupt_reasons_utils.h"
+#include "content/browser/download/byte_stream_input_stream.h"
#include "content/browser/download/download_manager_impl.h"
#include "content/browser/download/download_request_handle.h"
#include "content/browser/frame_host/frame_tree_node.h"
@@ -92,7 +93,7 @@ static void StartOnUIThread(
download_manager->StartDownload(
std::move(info),
- std::make_unique<DownloadManager::InputStream>(std::move(stream)),
+ std::make_unique<ByteStreamInputStream>(std::move(stream)), nullptr,
started_cb);
}
diff --git a/chromium/content/browser/download/download_response_handler.cc b/chromium/content/browser/download/download_response_handler.cc
deleted file mode 100644
index 5ab73c4e1fc..00000000000
--- a/chromium/content/browser/download/download_response_handler.cc
+++ /dev/null
@@ -1,225 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/download/download_response_handler.h"
-
-#include <memory>
-
-#include "components/download/public/common/download_stats.h"
-#include "components/download/public/common/download_url_parameters.h"
-#include "content/browser/download/download_utils.h"
-#include "net/http/http_status_code.h"
-#include "net/log/net_log_with_source.h"
-
-namespace content {
-
-namespace {
-
-download::mojom::NetworkRequestStatus
-ConvertInterruptReasonToMojoNetworkRequestStatus(
- download::DownloadInterruptReason reason) {
- switch (reason) {
- case download::DOWNLOAD_INTERRUPT_REASON_NONE:
- return download::mojom::NetworkRequestStatus::OK;
- case download::DOWNLOAD_INTERRUPT_REASON_NETWORK_TIMEOUT:
- return download::mojom::NetworkRequestStatus::NETWORK_TIMEOUT;
- case download::DOWNLOAD_INTERRUPT_REASON_NETWORK_DISCONNECTED:
- return download::mojom::NetworkRequestStatus::NETWORK_DISCONNECTED;
- case download::DOWNLOAD_INTERRUPT_REASON_NETWORK_SERVER_DOWN:
- return download::mojom::NetworkRequestStatus::NETWORK_SERVER_DOWN;
- case download::DOWNLOAD_INTERRUPT_REASON_SERVER_NO_RANGE:
- return download::mojom::NetworkRequestStatus::SERVER_NO_RANGE;
- case download::DOWNLOAD_INTERRUPT_REASON_SERVER_CONTENT_LENGTH_MISMATCH:
- return download::mojom::NetworkRequestStatus::
- SERVER_CONTENT_LENGTH_MISMATCH;
- case download::DOWNLOAD_INTERRUPT_REASON_SERVER_UNREACHABLE:
- return download::mojom::NetworkRequestStatus::SERVER_UNREACHABLE;
- case download::DOWNLOAD_INTERRUPT_REASON_SERVER_CERT_PROBLEM:
- return download::mojom::NetworkRequestStatus::SERVER_CERT_PROBLEM;
- case download::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED:
- return download::mojom::NetworkRequestStatus::USER_CANCELED;
- case download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED:
- return download::mojom::NetworkRequestStatus::NETWORK_FAILED;
- default:
- NOTREACHED();
- return download::mojom::NetworkRequestStatus::NETWORK_FAILED;
- }
-}
-
-} // namespace
-
-DownloadResponseHandler::DownloadResponseHandler(
- network::ResourceRequest* resource_request,
- Delegate* delegate,
- std::unique_ptr<download::DownloadSaveInfo> save_info,
- bool is_parallel_request,
- bool is_transient,
- bool fetch_error_body,
- const std::string& request_origin,
- download::DownloadSource download_source,
- std::vector<GURL> url_chain)
- : delegate_(delegate),
- started_(false),
- save_info_(std::move(save_info)),
- url_chain_(std::move(url_chain)),
- method_(resource_request->method),
- referrer_(resource_request->referrer),
- is_transient_(is_transient),
- fetch_error_body_(fetch_error_body),
- request_origin_(request_origin),
- download_source_(download_source),
- has_strong_validators_(false),
- is_partial_request_(save_info_->offset > 0),
- abort_reason_(download::DOWNLOAD_INTERRUPT_REASON_NONE) {
- if (!is_parallel_request) {
- download::RecordDownloadCountWithSource(download::UNTHROTTLED_COUNT,
- download_source);
- }
- if (resource_request->request_initiator.has_value())
- origin_ = resource_request->request_initiator.value().GetURL();
-}
-
-DownloadResponseHandler::~DownloadResponseHandler() = default;
-
-void DownloadResponseHandler::OnReceiveResponse(
- const network::ResourceResponseHead& head,
- const base::Optional<net::SSLInfo>& ssl_info,
- network::mojom::DownloadedTempFilePtr downloaded_file) {
- create_info_ = CreateDownloadCreateInfo(head);
-
- if (ssl_info)
- cert_status_ = ssl_info->cert_status;
-
- // TODO(xingliu): Do not use http cache.
- // Sets page transition type correctly and call
- // |RecordDownloadSourcePageTransitionType| here.
- if (head.headers) {
- has_strong_validators_ = head.headers->HasStrongValidators();
- download::RecordDownloadHttpResponseCode(head.headers->response_code());
- download::RecordDownloadContentDisposition(
- create_info_->content_disposition);
- }
-
- // Blink verifies that the requester of this download is allowed to set a
- // suggested name for the security origin of the downlaod URL. However, this
- // assumption doesn't hold if there were cross origin redirects. Therefore,
- // clear the suggested_name for such requests.
- if (origin_.is_valid() && !create_info_->url_chain.back().SchemeIsBlob() &&
- !create_info_->url_chain.back().SchemeIs(url::kAboutScheme) &&
- !create_info_->url_chain.back().SchemeIs(url::kDataScheme) &&
- origin_ != create_info_->url_chain.back().GetOrigin()) {
- create_info_->save_info->suggested_name.clear();
- }
-
- if (create_info_->result != download::DOWNLOAD_INTERRUPT_REASON_NONE)
- OnResponseStarted(download::mojom::DownloadStreamHandlePtr());
-}
-
-std::unique_ptr<download::DownloadCreateInfo>
-DownloadResponseHandler::CreateDownloadCreateInfo(
- const network::ResourceResponseHead& head) {
- // TODO(qinmin): instead of using NetLogWithSource, introduce new logging
- // class for download.
- auto create_info = std::make_unique<download::DownloadCreateInfo>(
- base::Time::Now(), std::move(save_info_));
-
- download::DownloadInterruptReason result =
- head.headers
- ? HandleSuccessfulServerResponse(
- *head.headers, create_info->save_info.get(), fetch_error_body_)
- : download::DOWNLOAD_INTERRUPT_REASON_NONE;
-
- create_info->total_bytes = head.content_length > 0 ? head.content_length : 0;
- create_info->result = result;
- if (result == download::DOWNLOAD_INTERRUPT_REASON_NONE)
- create_info->remote_address = head.socket_address.host();
- create_info->method = method_;
- create_info->connection_info = head.connection_info;
- create_info->url_chain = url_chain_;
- create_info->referrer_url = referrer_;
- create_info->transient = is_transient_;
- create_info->response_headers = head.headers;
- create_info->offset = create_info->save_info->offset;
- create_info->mime_type = head.mime_type;
- create_info->fetch_error_body = fetch_error_body_;
- create_info->request_origin = request_origin_;
- create_info->download_source = download_source_;
-
- HandleResponseHeaders(head.headers.get(), create_info.get());
- return create_info;
-}
-
-void DownloadResponseHandler::OnReceiveRedirect(
- const net::RedirectInfo& redirect_info,
- const network::ResourceResponseHead& head) {
- if (is_partial_request_) {
- // A redirect while attempting a partial resumption indicates a potential
- // middle box. Trigger another interruption so that the
- // download::DownloadItem can retry.
- abort_reason_ = download::DOWNLOAD_INTERRUPT_REASON_SERVER_UNREACHABLE;
- OnComplete(network::URLLoaderCompletionStatus(net::OK));
- return;
- }
- url_chain_.push_back(redirect_info.new_url);
- method_ = redirect_info.new_method;
- referrer_ = GURL(redirect_info.new_referrer);
- delegate_->OnReceiveRedirect();
-}
-
-void DownloadResponseHandler::OnDataDownloaded(int64_t data_length,
- int64_t encoded_length) {}
-
-void DownloadResponseHandler::OnUploadProgress(
- int64_t current_position,
- int64_t total_size,
- OnUploadProgressCallback callback) {}
-
-void DownloadResponseHandler::OnReceiveCachedMetadata(
- const std::vector<uint8_t>& data) {}
-
-void DownloadResponseHandler::OnTransferSizeUpdated(
- int32_t transfer_size_diff) {}
-
-void DownloadResponseHandler::OnStartLoadingResponseBody(
- mojo::ScopedDataPipeConsumerHandle body) {
- if (started_)
- return;
-
- download::mojom::DownloadStreamHandlePtr stream_handle =
- download::mojom::DownloadStreamHandle::New();
- stream_handle->stream = std::move(body);
- stream_handle->client_request = mojo::MakeRequest(&client_ptr_);
- OnResponseStarted(std::move(stream_handle));
-}
-
-void DownloadResponseHandler::OnComplete(
- const network::URLLoaderCompletionStatus& status) {
- download::DownloadInterruptReason reason = HandleRequestCompletionStatus(
- static_cast<net::Error>(status.error_code), has_strong_validators_,
- cert_status_, abort_reason_);
-
- if (client_ptr_) {
- client_ptr_->OnStreamCompleted(
- ConvertInterruptReasonToMojoNetworkRequestStatus(reason));
- }
-
- if (started_)
- return;
-
- // OnComplete() called without OnReceiveResponse(). This should only
- // happen when the request was aborted.
- create_info_ = CreateDownloadCreateInfo(network::ResourceResponseHead());
- create_info_->result = reason;
-
- OnResponseStarted(download::mojom::DownloadStreamHandlePtr());
-}
-
-void DownloadResponseHandler::OnResponseStarted(
- download::mojom::DownloadStreamHandlePtr stream_handle) {
- started_ = true;
- delegate_->OnResponseStarted(std::move(create_info_),
- std::move(stream_handle));
-}
-
-} // namespace content
diff --git a/chromium/content/browser/download/download_response_handler.h b/chromium/content/browser/download/download_response_handler.h
deleted file mode 100644
index 6e2756820c1..00000000000
--- a/chromium/content/browser/download/download_response_handler.h
+++ /dev/null
@@ -1,106 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_DOWNLOAD_RESPONSE_HANDLER_
-#define CONTENT_BROWSER_DOWNLOAD_RESPONSE_HANDLER_
-
-#include <vector>
-
-#include "components/download/public/common/download_create_info.h"
-#include "components/download/public/common/download_source.h"
-#include "components/download/public/common/download_stream.mojom.h"
-#include "content/public/common/referrer.h"
-#include "net/cert/cert_status_flags.h"
-#include "services/network/public/cpp/resource_response.h"
-#include "services/network/public/mojom/url_loader.mojom.h"
-
-namespace download {
-struct DownloadCreateInfo;
-} // namespace download
-
-namespace content {
-
-// This class is responsible for handling the server response for a download.
-// It passes the DataPipeConsumerHandle and completion status to the download
-// sink. The class is common to both navigation triggered downloads and
-// context menu downloads
-class DownloadResponseHandler : public network::mojom::URLLoaderClient {
- public:
- // Class for handling the stream once response starts.
- class Delegate {
- public:
- virtual void OnResponseStarted(
- std::unique_ptr<download::DownloadCreateInfo> download_create_info,
- download::mojom::DownloadStreamHandlePtr stream_handle) = 0;
- virtual void OnReceiveRedirect() = 0;
- };
-
- DownloadResponseHandler(network::ResourceRequest* resource_request,
- Delegate* delegate,
- std::unique_ptr<download::DownloadSaveInfo> save_info,
- bool is_parallel_request,
- bool is_transient,
- bool fetch_error_body,
- const std::string& request_origin,
- download::DownloadSource download_source,
- std::vector<GURL> url_chain);
- ~DownloadResponseHandler() override;
-
- // network::mojom::URLLoaderClient
- void OnReceiveResponse(
- const network::ResourceResponseHead& head,
- const base::Optional<net::SSLInfo>& ssl_info,
- network::mojom::DownloadedTempFilePtr downloaded_file) override;
- void OnReceiveRedirect(const net::RedirectInfo& redirect_info,
- const network::ResourceResponseHead& head) override;
- void OnDataDownloaded(int64_t data_length, int64_t encoded_length) override;
- void OnUploadProgress(int64_t current_position,
- int64_t total_size,
- OnUploadProgressCallback callback) override;
- void OnReceiveCachedMetadata(const std::vector<uint8_t>& data) override;
- void OnTransferSizeUpdated(int32_t transfer_size_diff) override;
- void OnStartLoadingResponseBody(
- mojo::ScopedDataPipeConsumerHandle body) override;
- void OnComplete(const network::URLLoaderCompletionStatus& status) override;
-
- private:
- std::unique_ptr<download::DownloadCreateInfo> CreateDownloadCreateInfo(
- const network::ResourceResponseHead& head);
-
- // Helper method that is called when response is received.
- void OnResponseStarted(
- download::mojom::DownloadStreamHandlePtr stream_handle);
-
- Delegate* const delegate_;
-
- std::unique_ptr<download::DownloadCreateInfo> create_info_;
-
- bool started_;
-
- // Information needed to create DownloadCreateInfo when the time comes.
- std::unique_ptr<download::DownloadSaveInfo> save_info_;
- std::vector<GURL> url_chain_;
- std::string method_;
- GURL referrer_;
- bool is_transient_;
- bool fetch_error_body_;
- std::string request_origin_;
- download::DownloadSource download_source_;
- net::CertStatus cert_status_;
- bool has_strong_validators_;
- GURL origin_;
- bool is_partial_request_;
-
- // The abort reason if this class decides to block the download.
- download::DownloadInterruptReason abort_reason_;
-
- // Mojo interface ptr to send the completion status to the download sink.
- download::mojom::DownloadStreamClientPtr client_ptr_;
-
- DISALLOW_COPY_AND_ASSIGN(DownloadResponseHandler);
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_DOWNLOAD_RESPONSE_HANDLER
diff --git a/chromium/content/browser/download/download_utils.cc b/chromium/content/browser/download/download_utils.cc
index 3ebb4d3b3e9..c9e72c38329 100644
--- a/chromium/content/browser/download/download_utils.cc
+++ b/chromium/content/browser/download/download_utils.cc
@@ -5,18 +5,17 @@
#include "content/browser/download/download_utils.h"
#include "base/format_macros.h"
-#include "base/memory/ptr_util.h"
#include "base/process/process_handle.h"
#include "base/strings/stringprintf.h"
#include "base/task_scheduler/post_task.h"
#include "components/download/downloader/in_progress/download_entry.h"
#include "components/download/downloader/in_progress/in_progress_cache.h"
#include "components/download/public/common/download_create_info.h"
+#include "components/download/public/common/download_interrupt_reasons_utils.h"
#include "components/download/public/common/download_save_info.h"
-#include "components/download/public/common/download_stats.h"
#include "components/download/public/common/download_url_parameters.h"
+#include "components/download/public/common/download_utils.h"
#include "content/browser/blob_storage/chrome_blob_storage_context.h"
-#include "content/browser/download/download_interrupt_reasons_utils.h"
#include "content/browser/loader/upload_data_stream_builder.h"
#include "content/browser/resource_context_impl.h"
#include "content/public/browser/browser_context.h"
@@ -25,104 +24,12 @@
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "net/base/elements_upload_data_stream.h"
-#include "net/base/load_flags.h"
#include "net/base/upload_bytes_element_reader.h"
#include "net/http/http_request_headers.h"
-#include "net/http/http_status_code.h"
#include "net/url_request/url_request_context.h"
-#include "services/network/public/cpp/resource_request.h"
namespace content {
-namespace {
-
-void AppendExtraHeaders(net::HttpRequestHeaders* headers,
- download::DownloadUrlParameters* params) {
- for (const auto& header : params->request_headers())
- headers->SetHeaderIfMissing(header.first, header.second);
-}
-
-int GetLoadFlags(download::DownloadUrlParameters* params,
- bool has_upload_data) {
- int load_flags = 0;
- if (params->prefer_cache()) {
- // If there is upload data attached, only retrieve from cache because there
- // is no current mechanism to prompt the user for their consent for a
- // re-post. For GETs, try to retrieve data from the cache and skip
- // validating the entry if present.
- if (has_upload_data)
- load_flags |= net::LOAD_ONLY_FROM_CACHE | net::LOAD_SKIP_CACHE_VALIDATION;
- else
- load_flags |= net::LOAD_SKIP_CACHE_VALIDATION;
- } else {
- load_flags |= net::LOAD_DISABLE_CACHE;
- }
- return load_flags;
-}
-
-std::unique_ptr<net::HttpRequestHeaders> GetAdditionalRequestHeaders(
- download::DownloadUrlParameters* params) {
- auto headers = std::make_unique<net::HttpRequestHeaders>();
- if (params->offset() == 0 &&
- params->length() == download::DownloadSaveInfo::kLengthFullContent) {
- AppendExtraHeaders(headers.get(), params);
- return headers;
- }
-
- bool has_last_modified = !params->last_modified().empty();
- bool has_etag = !params->etag().empty();
-
- // Strong validator(i.e. etag or last modified) is required in range requests
- // for download resumption and parallel download.
- DCHECK(has_etag || has_last_modified);
- if (!has_etag && !has_last_modified) {
- DVLOG(1) << "Creating partial request without strong validators.";
- AppendExtraHeaders(headers.get(), params);
- return headers;
- }
-
- // Add "Range" header.
- std::string range_header =
- (params->length() == download::DownloadSaveInfo::kLengthFullContent)
- ? base::StringPrintf("bytes=%" PRId64 "-", params->offset())
- : base::StringPrintf("bytes=%" PRId64 "-%" PRId64, params->offset(),
- params->offset() + params->length() - 1);
- headers->SetHeader(net::HttpRequestHeaders::kRange, range_header);
-
- // Add "If-Range" headers.
- if (params->use_if_range()) {
- // In accordance with RFC 7233 Section 3.2, use If-Range to specify that
- // the server return the entire entity if the validator doesn't match.
- // Last-Modified can be used in the absence of ETag as a validator if the
- // response headers satisfied the HttpUtil::HasStrongValidators()
- // predicate.
- //
- // This function assumes that HasStrongValidators() was true and that the
- // ETag and Last-Modified header values supplied are valid.
- headers->SetHeader(net::HttpRequestHeaders::kIfRange,
- has_etag ? params->etag() : params->last_modified());
- AppendExtraHeaders(headers.get(), params);
- return headers;
- }
-
- // Add "If-Match"/"If-Unmodified-Since" headers.
- if (has_etag)
- headers->SetHeader(net::HttpRequestHeaders::kIfMatch, params->etag());
-
- // According to RFC 7232 section 3.4, "If-Unmodified-Since" is mainly for
- // old servers that didn't implement "If-Match" and must be ignored when
- // "If-Match" presents.
- if (has_last_modified) {
- headers->SetHeader(net::HttpRequestHeaders::kIfUnmodifiedSince,
- params->last_modified());
- }
-
- AppendExtraHeaders(headers.get(), params);
- return headers;
-}
-
-} // namespace
-
storage::BlobStorageContext* BlobStorageContextGetter(
ResourceContext* resource_context) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
@@ -131,101 +38,6 @@ storage::BlobStorageContext* BlobStorageContextGetter(
return blob_context->context();
}
-download::DownloadInterruptReason HandleRequestCompletionStatus(
- net::Error error_code,
- bool has_strong_validators,
- net::CertStatus cert_status,
- download::DownloadInterruptReason abort_reason) {
- // ERR_CONTENT_LENGTH_MISMATCH can be caused by 1 of the following reasons:
- // 1. Server or proxy closes the connection too early.
- // 2. The content-length header is wrong.
- // If the download has strong validators, we can interrupt the download
- // and let it resume automatically. Otherwise, resuming the download will
- // cause it to restart and the download may never complete if the error was
- // caused by reason 2. As a result, downloads without strong validators are
- // treated as completed here.
- // TODO(qinmin): check the metrics from downloads with strong validators,
- // and decide whether we should interrupt downloads without strong validators
- // rather than complete them.
- if (error_code == net::ERR_CONTENT_LENGTH_MISMATCH &&
- !has_strong_validators) {
- error_code = net::OK;
- download::RecordDownloadCount(
- download::COMPLETED_WITH_CONTENT_LENGTH_MISMATCH_COUNT);
- }
-
- if (error_code == net::ERR_ABORTED) {
- // ERR_ABORTED == something outside of the network
- // stack cancelled the request. There aren't that many things that
- // could do this to a download request (whose lifetime is separated from
- // the tab from which it came). We map this to USER_CANCELLED as the
- // case we know about (system suspend because of laptop close) corresponds
- // to a user action.
- // TODO(asanka): A lid close or other power event should result in an
- // interruption that doesn't discard the partial state, unlike
- // USER_CANCELLED. (https://crbug.com/166179)
- if (net::IsCertStatusError(cert_status))
- return download::DOWNLOAD_INTERRUPT_REASON_SERVER_CERT_PROBLEM;
- else
- return download::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED;
- } else if (abort_reason != download::DOWNLOAD_INTERRUPT_REASON_NONE) {
- // If a more specific interrupt reason was specified before the request
- // was explicitly cancelled, then use it.
- return abort_reason;
- }
-
- return ConvertNetErrorToInterruptReason(
- error_code, DOWNLOAD_INTERRUPT_FROM_NETWORK);
-}
-
-std::unique_ptr<network::ResourceRequest> CreateResourceRequest(
- download::DownloadUrlParameters* params) {
- DCHECK(params->offset() >= 0);
-
- std::unique_ptr<network::ResourceRequest> request(
- new network::ResourceRequest);
- request->method = params->method();
- request->url = params->url();
- request->request_initiator = params->initiator();
- request->do_not_prompt_for_login = params->do_not_prompt_for_login();
- request->site_for_cookies = params->url();
- request->referrer = params->referrer();
- request->referrer_policy = params->referrer_policy();
- request->download_to_file = true;
- request->allow_download = true;
- request->is_main_frame = true;
-
- if (params->render_process_host_id() >= 0)
- request->render_frame_id = params->render_frame_host_routing_id();
-
- bool has_upload_data = false;
- if (params->post_body()) {
- request->request_body = params->post_body();
- has_upload_data = true;
- }
-
- if (params->post_id() >= 0) {
- // The POST in this case does not have an actual body, and only works
- // when retrieving data from cache. This is done because we don't want
- // to do a re-POST without user consent, and currently don't have a good
- // plan on how to display the UI for that.
- DCHECK(params->prefer_cache());
- DCHECK_EQ("POST", params->method());
- request->request_body = new network::ResourceRequestBody();
- request->request_body->set_identifier(params->post_id());
- has_upload_data = true;
- }
-
- request->load_flags = GetLoadFlags(params, has_upload_data);
-
- // Add additional request headers.
- std::unique_ptr<net::HttpRequestHeaders> headers =
- GetAdditionalRequestHeaders(params);
- request->headers.Swap(headers.get());
-
- return request;
-}
-
std::unique_ptr<net::URLRequest> CreateURLRequestOnIOThread(
download::DownloadUrlParameters* params) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
@@ -267,11 +79,11 @@ std::unique_ptr<net::URLRequest> CreateURLRequestOnIOThread(
std::move(element_readers), params->post_id()));
}
- request->SetLoadFlags(GetLoadFlags(params, request->get_upload()));
+ request->SetLoadFlags(download::GetLoadFlags(params, request->get_upload()));
// Add additional request headers.
std::unique_ptr<net::HttpRequestHeaders> headers =
- GetAdditionalRequestHeaders(params);
+ download::GetAdditionalRequestHeaders(params);
if (!headers->IsEmpty())
request->SetExtraRequestHeaders(*headers);
@@ -286,167 +98,4 @@ std::unique_ptr<net::URLRequest> CreateURLRequestOnIOThread(
return request;
}
-download::DownloadInterruptReason HandleSuccessfulServerResponse(
- const net::HttpResponseHeaders& http_headers,
- download::DownloadSaveInfo* save_info,
- bool fetch_error_body) {
- download::DownloadInterruptReason result =
- download::DOWNLOAD_INTERRUPT_REASON_NONE;
- switch (http_headers.response_code()) {
- case -1: // Non-HTTP request.
- case net::HTTP_OK:
- case net::HTTP_NON_AUTHORITATIVE_INFORMATION:
- case net::HTTP_PARTIAL_CONTENT:
- // Expected successful codes.
- break;
-
- case net::HTTP_CREATED:
- case net::HTTP_ACCEPTED:
- // Per RFC 7231 the entity being transferred is metadata about the
- // resource at the target URL and not the resource at that URL (or the
- // resource that would be at the URL once processing is completed in the
- // case of HTTP_ACCEPTED). However, we currently don't have special
- // handling for these response and they are downloaded the same as a
- // regular response.
- break;
-
- case net::HTTP_NO_CONTENT:
- case net::HTTP_RESET_CONTENT:
- // These two status codes don't have an entity (or rather RFC 7231
- // requires that there be no entity). They are treated the same as the
- // resource not being found since there is no entity to download.
-
- case net::HTTP_NOT_FOUND:
- result = download::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT;
- break;
-
- case net::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE:
- // Retry by downloading from the start automatically:
- // If we haven't received data when we get this error, we won't.
- result = download::DOWNLOAD_INTERRUPT_REASON_SERVER_NO_RANGE;
- break;
- case net::HTTP_UNAUTHORIZED:
- case net::HTTP_PROXY_AUTHENTICATION_REQUIRED:
- // Server didn't authorize this request.
- result = download::DOWNLOAD_INTERRUPT_REASON_SERVER_UNAUTHORIZED;
- break;
- case net::HTTP_FORBIDDEN:
- // Server forbids access to this resource.
- result = download::DOWNLOAD_INTERRUPT_REASON_SERVER_FORBIDDEN;
- break;
- default: // All other errors.
- // Redirection and informational codes should have been handled earlier
- // in the stack.
- // TODO(xingliu): Handle HTTP_PRECONDITION_FAILED and resurrect
- // download::DOWNLOAD_INTERRUPT_REASON_SERVER_PRECONDITION for range
- // requests. This will change extensions::api::download::InterruptReason.
- DCHECK_NE(3, http_headers.response_code() / 100);
- DCHECK_NE(1, http_headers.response_code() / 100);
- result = download::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED;
- }
-
- if (result != download::DOWNLOAD_INTERRUPT_REASON_NONE && !fetch_error_body)
- return result;
-
- // The caller is expecting a partial response.
- if (save_info && (save_info->offset > 0 || save_info->length > 0)) {
- if (http_headers.response_code() != net::HTTP_PARTIAL_CONTENT) {
- // Server should send partial content when "If-Match" or
- // "If-Unmodified-Since" check passes, and the range request header has
- // last byte position. e.g. "Range:bytes=50-99".
- if (save_info->length != download::DownloadSaveInfo::kLengthFullContent &&
- !fetch_error_body)
- return download::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT;
-
- // Requested a partial range, but received the entire response, when
- // the range request header is "Range:bytes={offset}-".
- // The response can be HTTP 200 or other error code when
- // |fetch_error_body| is true.
- save_info->offset = 0;
- save_info->hash_of_partial_file.clear();
- save_info->hash_state.reset();
- return download::DOWNLOAD_INTERRUPT_REASON_NONE;
- }
-
- int64_t first_byte = -1;
- int64_t last_byte = -1;
- int64_t length = -1;
- if (!http_headers.GetContentRangeFor206(&first_byte, &last_byte, &length))
- return download::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT;
- DCHECK_GE(first_byte, 0);
-
- if (first_byte != save_info->offset ||
- (save_info->length > 0 &&
- last_byte != save_info->offset + save_info->length - 1)) {
- // The server returned a different range than the one we requested. Assume
- // the response is bad.
- //
- // In the future we should consider allowing offsets that are less than
- // the offset we've requested, since in theory we can truncate the partial
- // file at the offset and continue.
- return download::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT;
- }
-
- return download::DOWNLOAD_INTERRUPT_REASON_NONE;
- }
-
- if (http_headers.response_code() == net::HTTP_PARTIAL_CONTENT)
- return download::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT;
-
- return download::DOWNLOAD_INTERRUPT_REASON_NONE;
-}
-
-void HandleResponseHeaders(const net::HttpResponseHeaders* headers,
- download::DownloadCreateInfo* create_info) {
- if (!headers)
- return;
-
- if (headers->HasStrongValidators()) {
- // If we don't have strong validators as per RFC 7232 section 2, then
- // we neither store nor use them for range requests.
- if (!headers->EnumerateHeader(nullptr, "Last-Modified",
- &create_info->last_modified))
- create_info->last_modified.clear();
- if (!headers->EnumerateHeader(nullptr, "ETag", &create_info->etag))
- create_info->etag.clear();
- }
-
- // Grab the first content-disposition header. There may be more than one,
- // though as of this writing, the network stack ensures if there are, they
- // are all duplicates.
- headers->EnumerateHeader(nullptr, "Content-Disposition",
- &create_info->content_disposition);
-
- // Parse the original mime type from the header, notice that actual mime type
- // might be different due to mime type sniffing.
- if (!headers->GetMimeType(&create_info->original_mime_type))
- create_info->original_mime_type.clear();
-
- // Content-Range is validated in HandleSuccessfulServerResponse.
- // In RFC 7233, a single part 206 partial response must generate
- // Content-Range. Accept-Range may be sent in 200 response to indicate the
- // server can handle range request, but optional in 206 response.
- create_info->accept_range =
- headers->HasHeaderValue("Accept-Ranges", "bytes") ||
- (headers->HasHeader("Content-Range") &&
- headers->response_code() == net::HTTP_PARTIAL_CONTENT);
-}
-
-base::Optional<download::DownloadEntry> GetInProgressEntry(
- const std::string& guid,
- BrowserContext* browser_context) {
- base::Optional<download::DownloadEntry> entry;
- if (!browser_context || guid.empty())
- return entry;
-
- auto* manager_delegate = browser_context->GetDownloadManagerDelegate();
- if (manager_delegate) {
- download::InProgressCache* in_progress_cache =
- manager_delegate->GetInProgressCache();
- if (in_progress_cache)
- entry = in_progress_cache->RetrieveEntry(guid);
- }
- return entry;
-}
-
} // namespace content
diff --git a/chromium/content/browser/download/download_utils.h b/chromium/content/browser/download/download_utils.h
index 93235adc9a5..df86cad0db7 100644
--- a/chromium/content/browser/download/download_utils.h
+++ b/chromium/content/browser/download/download_utils.h
@@ -5,17 +5,12 @@
#ifndef CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_UTILS_H_
#define CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_UTILS_H_
+#include <memory>
+
#include "base/optional.h"
-#include "components/download/public/common/download_interrupt_reasons.h"
#include "content/common/content_export.h"
-#include "net/base/net_errors.h"
-#include "net/cert/cert_status_flags.h"
-#include "net/http/http_response_headers.h"
namespace download {
-struct DownloadCreateInfo;
-struct DownloadEntry;
-struct DownloadSaveInfo;
class DownloadUrlParameters;
} // namespace download
@@ -23,53 +18,18 @@ namespace net {
class URLRequest;
} // namespace net
-namespace network {
-struct ResourceRequest;
-}
-
namespace storage {
class BlobStorageContext;
}
namespace content {
-class BrowserContext;
class ResourceContext;
-// Handle the url request completion status and return the interrupt reasons.
-// |cert_status| is ignored if error_code is not net::ERR_ABORTED.
-download::DownloadInterruptReason CONTENT_EXPORT
-HandleRequestCompletionStatus(net::Error error_code,
- bool has_strong_validators,
- net::CertStatus cert_status,
- download::DownloadInterruptReason abort_reason);
-
-// Create a ResourceRequest from |params|.
-std::unique_ptr<network::ResourceRequest> CONTENT_EXPORT
-CreateResourceRequest(download::DownloadUrlParameters* params);
-
// Create a URLRequest from |params|.
std::unique_ptr<net::URLRequest> CONTENT_EXPORT
CreateURLRequestOnIOThread(download::DownloadUrlParameters* params);
-// Parse the HTTP server response code.
-// If |fetch_error_body| is true, most of HTTP response codes will be accepted
-// as successful response.
-download::DownloadInterruptReason CONTENT_EXPORT
-HandleSuccessfulServerResponse(const net::HttpResponseHeaders& http_headers,
- download::DownloadSaveInfo* save_info,
- bool fetch_error_body);
-
-// Parse response headers and update |create_info| accordingly.
-CONTENT_EXPORT void HandleResponseHeaders(
- const net::HttpResponseHeaders* headers,
- download::DownloadCreateInfo* create_info);
-
-// Get the entry based on |guid| from in progress cache.
-CONTENT_EXPORT base::Optional<download::DownloadEntry> GetInProgressEntry(
- const std::string& guid,
- BrowserContext* browser_context);
-
storage::BlobStorageContext* BlobStorageContextGetter(
ResourceContext* resource_context);
diff --git a/chromium/content/browser/download/download_worker.cc b/chromium/content/browser/download/download_worker.cc
deleted file mode 100644
index f98b5712a72..00000000000
--- a/chromium/content/browser/download/download_worker.cc
+++ /dev/null
@@ -1,164 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/download/download_worker.h"
-
-#include "components/download/public/common/download_create_info.h"
-#include "components/download/public/common/download_interrupt_reasons.h"
-#include "content/browser/byte_stream.h"
-#include "content/browser/download/download_utils.h"
-#include "content/browser/download/resource_downloader.h"
-#include "content/public/browser/web_contents.h"
-#include "content/public/common/content_features.h"
-#include "services/network/public/cpp/features.h"
-
-namespace content {
-namespace {
-
-const int kWorkerVerboseLevel = 1;
-
-class CompletedByteStreamReader : public ByteStreamReader {
- public:
- CompletedByteStreamReader(int status) : status_(status) {};
- ~CompletedByteStreamReader() override = default;
-
- // ByteStreamReader implementations:
- ByteStreamReader::StreamState Read(scoped_refptr<net::IOBuffer>* data,
- size_t* length) override {
- return ByteStreamReader::STREAM_COMPLETE;
- }
- int GetStatus() const override { return status_; }
- void RegisterCallback(const base::Closure& sink_callback) override {}
-
- private:
- int status_;
-};
-
-std::unique_ptr<UrlDownloadHandler, BrowserThread::DeleteOnIOThread>
-CreateUrlDownloadHandler(
- std::unique_ptr<download::DownloadUrlParameters> params,
- base::WeakPtr<UrlDownloadHandler::Delegate> delegate,
- scoped_refptr<URLLoaderFactoryGetter> url_loader_factory_getter) {
- DCHECK_CURRENTLY_ON(BrowserThread::IO);
-
- if (base::FeatureList::IsEnabled(network::features::kNetworkService)) {
- std::unique_ptr<network::ResourceRequest> request =
- CreateResourceRequest(params.get());
- return std::unique_ptr<ResourceDownloader, BrowserThread::DeleteOnIOThread>(
- ResourceDownloader::BeginDownload(
- delegate, std::move(params), std::move(request),
- url_loader_factory_getter->GetNetworkFactory(), GURL(), GURL(),
- GURL(), download::DownloadItem::kInvalidId, true)
- .release());
- } else {
- // Build the URLRequest, BlobDataHandle is hold in original request for
- // image download.
- std::unique_ptr<net::URLRequest> url_request =
- DownloadRequestCore::CreateRequestOnIOThread(
- download::DownloadItem::kInvalidId, params.get());
-
- return std::unique_ptr<UrlDownloader, BrowserThread::DeleteOnIOThread>(
- UrlDownloader::BeginDownload(delegate, std::move(url_request),
- params.get(), true)
- .release());
- }
-}
-
-} // namespace
-
-DownloadWorker::DownloadWorker(DownloadWorker::Delegate* delegate,
- int64_t offset,
- int64_t length)
- : delegate_(delegate),
- offset_(offset),
- length_(length),
- is_paused_(false),
- is_canceled_(false),
- is_user_cancel_(false),
- weak_factory_(this) {
- DCHECK(delegate_);
-}
-
-DownloadWorker::~DownloadWorker() = default;
-
-void DownloadWorker::SendRequest(
- std::unique_ptr<download::DownloadUrlParameters> params,
- scoped_refptr<URLLoaderFactoryGetter> url_loader_factory_getter) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- BrowserThread::PostTaskAndReplyWithResult(
- BrowserThread::IO, FROM_HERE,
- base::BindOnce(&CreateUrlDownloadHandler, std::move(params),
- weak_factory_.GetWeakPtr(), url_loader_factory_getter),
- base::BindOnce(&DownloadWorker::AddUrlDownloadHandler,
- weak_factory_.GetWeakPtr()));
-}
-
-void DownloadWorker::Pause() {
- is_paused_ = true;
- if (request_handle_)
- request_handle_->PauseRequest();
-}
-
-void DownloadWorker::Resume() {
- is_paused_ = false;
- if (request_handle_)
- request_handle_->ResumeRequest();
-}
-
-void DownloadWorker::Cancel(bool user_cancel) {
- is_canceled_ = true;
- is_user_cancel_ = user_cancel;
- if (request_handle_)
- request_handle_->CancelRequest(user_cancel);
-}
-
-void DownloadWorker::OnUrlDownloadStarted(
- std::unique_ptr<download::DownloadCreateInfo> create_info,
- std::unique_ptr<DownloadManager::InputStream> input_stream,
- const download::DownloadUrlParameters::OnStartedCallback& callback) {
- // |callback| is not used in subsequent requests.
- DCHECK(callback.is_null());
-
- // Destroy the request if user canceled.
- if (is_canceled_) {
- VLOG(kWorkerVerboseLevel)
- << "Byte stream arrived after user cancel the request.";
- create_info->request_handle->CancelRequest(is_user_cancel_);
- return;
- }
-
- // TODO(xingliu): Add metric for error handling.
- if (create_info->result != download::DOWNLOAD_INTERRUPT_REASON_NONE) {
- VLOG(kWorkerVerboseLevel)
- << "Parallel download sub-request failed. reason = "
- << create_info->result;
- input_stream->stream_reader_.reset(
- new CompletedByteStreamReader(create_info->result));
- }
-
- request_handle_ = std::move(create_info->request_handle);
-
- // Pause the stream if user paused, still push the stream reader to the sink.
- if (is_paused_) {
- VLOG(kWorkerVerboseLevel)
- << "Byte stream arrived after user pause the request.";
- Pause();
- }
-
- delegate_->OnInputStreamReady(this, std::move(input_stream));
-}
-
-void DownloadWorker::OnUrlDownloadStopped(UrlDownloadHandler* downloader) {
- // Release the |url_download_handler_|, the object will be deleted on IO
- // thread.
- url_download_handler_.reset();
-}
-
-void DownloadWorker::AddUrlDownloadHandler(
- std::unique_ptr<UrlDownloadHandler, BrowserThread::DeleteOnIOThread>
- downloader) {
- url_download_handler_ = std::move(downloader);
-}
-
-} // namespace content
diff --git a/chromium/content/browser/download/download_worker.h b/chromium/content/browser/download/download_worker.h
deleted file mode 100644
index 9a84008525a..00000000000
--- a/chromium/content/browser/download/download_worker.h
+++ /dev/null
@@ -1,95 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_WORKER_H_
-#define CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_WORKER_H_
-
-#include <memory>
-
-#include "base/macros.h"
-#include "base/memory/weak_ptr.h"
-#include "components/download/public/common/download_request_handle_interface.h"
-#include "components/download/public/common/download_url_parameters.h"
-#include "content/browser/download/url_downloader.h"
-#include "content/browser/url_loader_factory_getter.h"
-#include "content/common/content_export.h"
-#include "content/public/browser/browser_thread.h"
-
-namespace content {
-
-// Helper class used to send subsequent range requests to fetch slices of the
-// file after handling response of the original non-range request.
-// TODO(xingliu): we should consider to reuse this class for single connection
-// download.
-class CONTENT_EXPORT DownloadWorker : public UrlDownloadHandler::Delegate {
- public:
- class Delegate {
- public:
- // Called when the the input stream is established after server response is
- // handled. The stream contains data starts from |offset| of the
- // destination file.
- virtual void OnInputStreamReady(
- DownloadWorker* worker,
- std::unique_ptr<DownloadManager::InputStream> input_stream) = 0;
- };
-
- DownloadWorker(DownloadWorker::Delegate* delegate,
- int64_t offset,
- int64_t length);
- virtual ~DownloadWorker();
-
- int64_t offset() const { return offset_; }
- int64_t length() const { return length_; }
-
- // Send network request to ask for a download.
- void SendRequest(
- std::unique_ptr<download::DownloadUrlParameters> params,
- scoped_refptr<URLLoaderFactoryGetter> url_loader_factory_getter);
-
- // Download operations.
- void Pause();
- void Resume();
- void Cancel(bool user_cancel);
-
- private:
- // UrlDownloader::Delegate implementation.
- void OnUrlDownloadStarted(
- std::unique_ptr<download::DownloadCreateInfo> create_info,
- std::unique_ptr<DownloadManager::InputStream> input_stream,
- const download::DownloadUrlParameters::OnStartedCallback& callback)
- override;
- void OnUrlDownloadStopped(UrlDownloadHandler* downloader) override;
-
- void AddUrlDownloadHandler(
- std::unique_ptr<UrlDownloadHandler, BrowserThread::DeleteOnIOThread>
- downloader);
-
- DownloadWorker::Delegate* const delegate_;
-
- // The starting position of the content for this worker to download.
- int64_t offset_;
-
- // The length of the request. May be 0 to fetch to the end of the file.
- int64_t length_;
-
- // States of the worker.
- bool is_paused_;
- bool is_canceled_;
- bool is_user_cancel_;
-
- // Used to control the network request. Live on UI thread.
- std::unique_ptr<download::DownloadRequestHandleInterface> request_handle_;
-
- // Used to handle the url request. Live and die on IO thread.
- std::unique_ptr<UrlDownloadHandler, BrowserThread::DeleteOnIOThread>
- url_download_handler_;
-
- base::WeakPtrFactory<DownloadWorker> weak_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(DownloadWorker);
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_WORKER_H_
diff --git a/chromium/content/browser/download/drag_download_file.h b/chromium/content/browser/download/drag_download_file.h
index 1eaea49dc48..635a9092c7b 100644
--- a/chromium/content/browser/download/drag_download_file.h
+++ b/chromium/content/browser/download/drag_download_file.h
@@ -16,7 +16,6 @@
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "components/download/public/common/download_item.h"
-#include "content/browser/download/download_file.h"
#include "content/common/content_export.h"
#include "content/public/browser/download_manager.h"
#include "content/public/common/referrer.h"
diff --git a/chromium/content/browser/download/drag_download_file_browsertest.cc b/chromium/content/browser/download/drag_download_file_browsertest.cc
index 8fb11555640..f080504c23c 100644
--- a/chromium/content/browser/download/drag_download_file_browsertest.cc
+++ b/chromium/content/browser/download/drag_download_file_browsertest.cc
@@ -8,13 +8,11 @@
#include "base/memory/ref_counted.h"
#include "base/message_loop/message_loop.h"
#include "base/path_service.h"
-#include "content/browser/download/download_file_factory.h"
-#include "content/browser/download/download_file_impl.h"
-#include "content/browser/download/download_item_impl.h"
#include "content/browser/download/download_manager_impl.h"
#include "content/browser/download/drag_download_file.h"
#include "content/browser/download/drag_download_util.h"
#include "content/browser/web_contents/web_contents_impl.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_paths.h"
diff --git a/chromium/content/browser/download/mhtml_generation_browsertest.cc b/chromium/content/browser/download/mhtml_generation_browsertest.cc
index 6ca932f6fa9..d3e9279628a 100644
--- a/chromium/content/browser/download/mhtml_generation_browsertest.cc
+++ b/chromium/content/browser/download/mhtml_generation_browsertest.cc
@@ -18,6 +18,7 @@
#include "components/download/public/common/download_task_runner.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/common/frame_messages.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/mhtml_extra_parts.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
@@ -33,8 +34,8 @@
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/web/WebFindOptions.h"
-#include "third_party/WebKit/public/web/WebFrameSerializerCacheControlPolicy.h"
+#include "third_party/blink/public/web/web_find_options.h"
+#include "third_party/blink/public/web/web_frame_serializer_cache_control_policy.h"
using testing::ContainsRegex;
using testing::HasSubstr;
@@ -119,9 +120,8 @@ class MHTMLGenerationTest : public ContentBrowserTest {
histogram_tester_.reset(new base::HistogramTester());
shell()->web_contents()->GenerateMHTML(
- params, base::Bind(&MHTMLGenerationTest::MHTMLGenerated,
- base::Unretained(this),
- run_loop.QuitClosure()));
+ params, base::BindOnce(&MHTMLGenerationTest::MHTMLGenerated,
+ base::Unretained(this), run_loop.QuitClosure()));
// Block until the MHTML is generated.
run_loop.Run();
@@ -226,7 +226,7 @@ class MHTMLGenerationTest : public ContentBrowserTest {
void MHTMLGenerated(base::Closure quit_closure, int64_t size) {
has_mhtml_callback_run_ = true;
file_size_ = size;
- quit_closure.Run();
+ std::move(quit_closure).Run();
}
bool has_mhtml_callback_run_;
diff --git a/chromium/content/browser/download/mhtml_generation_manager.cc b/chromium/content/browser/download/mhtml_generation_manager.cc
index b11b891bd34..de16bb4ffc9 100644
--- a/chromium/content/browser/download/mhtml_generation_manager.cc
+++ b/chromium/content/browser/download/mhtml_generation_manager.cc
@@ -51,14 +51,14 @@ class MHTMLGenerationManager::Job : public RenderProcessHostObserver {
Job(int job_id,
WebContents* web_contents,
const MHTMLGenerationParams& params,
- const GenerateMHTMLCallback& callback);
+ GenerateMHTMLCallback callback);
~Job() override;
int id() const { return job_id_; }
void set_browser_file(base::File file) { browser_file_ = std::move(file); }
base::TimeTicks creation_time() const { return creation_time_; }
- const GenerateMHTMLCallback& callback() const { return callback_; }
+ GenerateMHTMLCallback callback() { return std::move(callback_); }
// Indicates whether we expect a message from the |sender| at this time.
// We expect only one message per frame - therefore calling this method
@@ -88,7 +88,7 @@ class MHTMLGenerationManager::Job : public RenderProcessHostObserver {
// back on the UI thread with the updated status and file size (which will be
// negative in case of errors).
void CloseFile(
- base::Callback<void(const std::tuple<MhtmlSaveStatus, int64_t>&)>
+ base::OnceCallback<void(const std::tuple<MhtmlSaveStatus, int64_t>&)>
callback,
MhtmlSaveStatus save_status);
@@ -130,12 +130,6 @@ class MHTMLGenerationManager::Job : public RenderProcessHostObserver {
// false for failure.
static bool CloseFileIfValid(base::File& file, int64_t* file_size);
- // Creates a new map with values (content ids) the same as in
- // |frame_tree_node_to_content_id_| map, but with the keys translated from
- // frame_tree_node_id into a |site_instance|-specific routing_id.
- std::map<int, std::string> CreateFrameRoutingIdToContentId(
- SiteInstance* site_instance);
-
// Id used to map renderer responses to jobs.
// See also MHTMLGenerationManager::id_to_job_ map.
const int job_id_;
@@ -163,10 +157,6 @@ class MHTMLGenerationManager::Job : public RenderProcessHostObserver {
// The handle to the file the MHTML is saved to for the browser process.
base::File browser_file_;
- // Map from frames to content ids (see WebFrameSerializer::generateMHTMLParts
- // for more details about what "content ids" are and how they are used).
- std::map<int, std::string> frame_tree_node_to_content_id_;
-
// MIME multipart boundary to use in the MHTML doc.
const std::string mhtml_boundary_marker_;
@@ -175,7 +165,7 @@ class MHTMLGenerationManager::Job : public RenderProcessHostObserver {
std::string salt_;
// The callback to call once generation is complete.
- const GenerateMHTMLCallback callback_;
+ GenerateMHTMLCallback callback_;
// Whether the job is finished (set to true only for the short duration of
// time between MHTMLGenerationManager::JobFinished is called and the job is
@@ -195,14 +185,14 @@ class MHTMLGenerationManager::Job : public RenderProcessHostObserver {
MHTMLGenerationManager::Job::Job(int job_id,
WebContents* web_contents,
const MHTMLGenerationParams& params,
- const GenerateMHTMLCallback& callback)
+ GenerateMHTMLCallback callback)
: job_id_(job_id),
creation_time_(base::TimeTicks::Now()),
params_(params),
frame_tree_node_id_of_busy_frame_(FrameTreeNode::kFrameTreeNodeInvalidId),
mhtml_boundary_marker_(net::GenerateMimeMultipartBoundary()),
salt_(base::GenerateGUID()),
- callback_(callback),
+ callback_(std::move(callback)),
is_finished_(false),
observed_renderer_process_host_(this) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
@@ -226,28 +216,6 @@ MHTMLGenerationManager::Job::~Job() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
}
-std::map<int, std::string>
-MHTMLGenerationManager::Job::CreateFrameRoutingIdToContentId(
- SiteInstance* site_instance) {
- std::map<int, std::string> result;
- for (const auto& it : frame_tree_node_to_content_id_) {
- int ftn_id = it.first;
- const std::string& content_id = it.second;
-
- FrameTreeNode* ftn = FrameTreeNode::GloballyFindByID(ftn_id);
- if (!ftn)
- continue;
-
- int routing_id =
- ftn->render_manager()->GetRoutingIdForSiteInstance(site_instance);
- if (routing_id == MSG_ROUTING_NONE)
- continue;
-
- result[routing_id] = content_id;
- }
- return result;
-}
-
MhtmlSaveStatus MHTMLGenerationManager::Job::SendToNextRenderFrame() {
DCHECK(browser_file_.IsValid());
DCHECK(!pending_frame_tree_node_ids_.empty());
@@ -278,8 +246,6 @@ MhtmlSaveStatus MHTMLGenerationManager::Job::SendToNextRenderFrame() {
ipc_params.destination_file = IPC::GetPlatformFileForTransit(
browser_file_.GetPlatformFile(), false); // |close_source_handle|.
- ipc_params.frame_routing_id_to_content_id =
- CreateFrameRoutingIdToContentId(rfh->GetSiteInstance());
// Send the IPC asking the renderer to serialize the frame.
DCHECK_EQ(FrameTreeNode::kFrameTreeNodeInvalidId,
@@ -357,11 +323,6 @@ void MHTMLGenerationManager::Job::AddFrame(RenderFrameHost* render_frame_host) {
auto* rfhi = static_cast<RenderFrameHostImpl*>(render_frame_host);
int frame_tree_node_id = rfhi->frame_tree_node()->frame_tree_node_id();
pending_frame_tree_node_ids_.push(frame_tree_node_id);
-
- std::string guid = base::GenerateGUID();
- std::string content_id = base::StringPrintf("<frame-%d-%s@mhtml.blink>",
- frame_tree_node_id, guid.c_str());
- frame_tree_node_to_content_id_[frame_tree_node_id] = content_id;
}
void MHTMLGenerationManager::Job::RenderProcessHostDestroyed(
@@ -371,7 +332,8 @@ void MHTMLGenerationManager::Job::RenderProcessHostDestroyed(
}
void MHTMLGenerationManager::Job::CloseFile(
- base::Callback<void(const std::tuple<MhtmlSaveStatus, int64_t>&)> callback,
+ base::OnceCallback<void(const std::tuple<MhtmlSaveStatus, int64_t>&)>
+ callback,
MhtmlSaveStatus save_status) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(!mhtml_boundary_marker_.empty());
@@ -380,20 +342,20 @@ void MHTMLGenerationManager::Job::CloseFile(
// Only update the status if that won't hide an earlier error.
if (save_status == MhtmlSaveStatus::SUCCESS)
save_status = MhtmlSaveStatus::FILE_WRITTING_ERROR;
- callback.Run(std::make_tuple(save_status, -1));
+ std::move(callback).Run(std::make_tuple(save_status, -1));
return;
}
// If no previous error occurred the boundary should be sent.
base::PostTaskAndReplyWithResult(
download::GetDownloadTaskRunner().get(), FROM_HERE,
- base::Bind(
+ base::BindOnce(
&MHTMLGenerationManager::Job::FinalizeAndCloseFileOnFileThread,
save_status,
(save_status == MhtmlSaveStatus::SUCCESS ? mhtml_boundary_marker_
: std::string()),
- base::Passed(&browser_file_), base::Passed(&extra_data_parts_)),
- callback);
+ std::move(browser_file_), std::move(extra_data_parts_)),
+ std::move(callback));
}
bool MHTMLGenerationManager::Job::IsMessageFromFrameExpected(
@@ -542,10 +504,10 @@ MHTMLGenerationManager::~MHTMLGenerationManager() {
void MHTMLGenerationManager::SaveMHTML(WebContents* web_contents,
const MHTMLGenerationParams& params,
- const GenerateMHTMLCallback& callback) {
+ GenerateMHTMLCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
- Job* job = NewJob(web_contents, params, callback);
+ Job* job = NewJob(web_contents, params, std::move(callback));
TRACE_EVENT_NESTABLE_ASYNC_BEGIN2(
"page-serialization", "SavingMhtmlJob", job, "url",
web_contents->GetLastCommittedURL().possibly_invalid_spec(),
@@ -644,9 +606,9 @@ void MHTMLGenerationManager::JobFinished(Job* job,
DCHECK(job);
job->MarkAsFinished();
job->CloseFile(
- base::Bind(&MHTMLGenerationManager::OnFileClosed,
- base::Unretained(this), // Safe b/c |this| is a singleton.
- job->id()),
+ base::BindOnce(&MHTMLGenerationManager::OnFileClosed,
+ base::Unretained(this), // Safe b/c |this| is a singleton.
+ job->id()),
save_status);
}
@@ -667,17 +629,18 @@ void MHTMLGenerationManager::OnFileClosed(
UMA_HISTOGRAM_ENUMERATION("PageSerialization.MhtmlGeneration.FinalSaveStatus",
static_cast<int>(save_status),
static_cast<int>(MhtmlSaveStatus::LAST));
- job->callback().Run(save_status == MhtmlSaveStatus::SUCCESS ? file_size : -1);
+ std::move(job->callback())
+ .Run(save_status == MhtmlSaveStatus::SUCCESS ? file_size : -1);
id_to_job_.erase(job_id);
}
MHTMLGenerationManager::Job* MHTMLGenerationManager::NewJob(
WebContents* web_contents,
const MHTMLGenerationParams& params,
- const GenerateMHTMLCallback& callback) {
+ GenerateMHTMLCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
- Job* job = new Job(++next_job_id_, web_contents, params, callback);
+ Job* job = new Job(++next_job_id_, web_contents, params, std::move(callback));
id_to_job_[job->id()] = base::WrapUnique(job);
return job;
}
diff --git a/chromium/content/browser/download/mhtml_generation_manager.h b/chromium/content/browser/download/mhtml_generation_manager.h
index e30001535b0..57a1c7e69db 100644
--- a/chromium/content/browser/download/mhtml_generation_manager.h
+++ b/chromium/content/browser/download/mhtml_generation_manager.h
@@ -41,13 +41,13 @@ class MHTMLGenerationManager {
// GenerateMHTMLCallback is called to report completion and status of MHTML
// generation. On success |file_size| indicates the size of the
// generated file. On failure |file_size| is -1.
- typedef base::Callback<void(int64_t file_size)> GenerateMHTMLCallback;
+ using GenerateMHTMLCallback = base::OnceCallback<void(int64_t file_size)>;
// Instructs the RenderFrames in |web_contents| to generate a MHTML
// representation of the current page.
void SaveMHTML(WebContents* web_contents,
const MHTMLGenerationParams& params,
- const GenerateMHTMLCallback& callback);
+ GenerateMHTMLCallback callback);
// Handler for FrameHostMsg_SerializeAsMHTMLResponse (a notification from the
// renderer that the MHTML generation finished for a single frame).
@@ -83,7 +83,7 @@ class MHTMLGenerationManager {
// Creates and registers a new job.
Job* NewJob(WebContents* web_contents,
const MHTMLGenerationParams& params,
- const GenerateMHTMLCallback& callback);
+ GenerateMHTMLCallback callback);
// Finds job by id. Returns nullptr if no job with a given id was found.
Job* FindJob(int job_id);
diff --git a/chromium/content/browser/download/mock_download_file.cc b/chromium/content/browser/download/mock_download_file.cc
deleted file mode 100644
index b46ccb6f736..00000000000
--- a/chromium/content/browser/download/mock_download_file.cc
+++ /dev/null
@@ -1,51 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/download/mock_download_file.h"
-
-#include "base/bind.h"
-#include "content/public/browser/browser_thread.h"
-#include "testing/gmock/include/gmock/gmock.h"
-
-using ::testing::_;
-using ::testing::Return;
-
-namespace content {
-namespace {
-
-void SuccessRun(const DownloadFile::InitializeCallback& initialize_callback) {
- initialize_callback.Run(download::DOWNLOAD_INTERRUPT_REASON_NONE);
-}
-
-void PostSuccessRun(
- const DownloadFile::InitializeCallback& initialize_callback,
- const DownloadFile::CancelRequestCallback& cancel_request_callback,
- const download::DownloadItem::ReceivedSlices& received_slices,
- bool is_parallelizable) {
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
- base::BindOnce(&SuccessRun, initialize_callback));
-}
-
-} // namespace
-
-MockDownloadFile::MockDownloadFile() {
- // This is here because |Initialize()| is normally called right after
- // construction.
- ON_CALL(*this, Initialize(_, _, _, _))
- .WillByDefault(::testing::Invoke(PostSuccessRun));
-}
-
-MockDownloadFile::~MockDownloadFile() {
-}
-
-void MockDownloadFile::AddInputStream(
- std::unique_ptr<DownloadManager::InputStream> input_stream,
- int64_t offset,
- int64_t length) {
- // Gmock currently can't mock method that takes move-only parameters,
- // delegate the EXPECT_CALL count to |DoAddByteStream|.
- DoAddInputStream(input_stream.get(), offset, length);
-}
-
-} // namespace content
diff --git a/chromium/content/browser/download/mock_download_file.h b/chromium/content/browser/download/mock_download_file.h
deleted file mode 100644
index 1fa088c4a2e..00000000000
--- a/chromium/content/browser/download/mock_download_file.h
+++ /dev/null
@@ -1,81 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_DOWNLOAD_MOCK_DOWNLOAD_FILE_H_
-#define CONTENT_BROWSER_DOWNLOAD_MOCK_DOWNLOAD_FILE_H_
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include <map>
-#include <memory>
-#include <string>
-
-#include "base/files/file_path.h"
-#include "base/memory/ref_counted.h"
-#include "content/browser/byte_stream.h"
-#include "content/browser/download/download_file.h"
-#include "content/public/browser/download_manager.h"
-#include "testing/gmock/include/gmock/gmock.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace content {
-
-class MockDownloadFile : public DownloadFile {
- public:
- MockDownloadFile();
- virtual ~MockDownloadFile();
-
- // DownloadFile functions.
- MOCK_METHOD4(
- Initialize,
- void(const InitializeCallback&,
- const CancelRequestCallback&,
- const download::DownloadItem::ReceivedSlices& received_slices,
- bool is_parallelizable));
- void AddInputStream(
- std::unique_ptr<DownloadManager::InputStream> input_stream,
- int64_t offset,
- int64_t length) override;
- MOCK_METHOD3(DoAddInputStream,
- void(DownloadManager::InputStream* input_stream,
- int64_t offset,
- int64_t length));
- MOCK_METHOD2(OnResponseCompleted,
- void(int64_t offset, download::DownloadInterruptReason status));
- MOCK_METHOD2(AppendDataToFile,
- download::DownloadInterruptReason(const char* data,
- size_t data_len));
- MOCK_METHOD1(
- Rename,
- download::DownloadInterruptReason(const base::FilePath& full_path));
- MOCK_METHOD2(RenameAndUniquify,
- void(const base::FilePath& full_path,
- const RenameCompletionCallback& callback));
- MOCK_METHOD5(RenameAndAnnotate,
- void(const base::FilePath& full_path,
- const std::string& client_guid,
- const GURL& source_url,
- const GURL& referrer_url,
- const RenameCompletionCallback& callback));
- MOCK_METHOD0(Detach, void());
- MOCK_METHOD0(Cancel, void());
- MOCK_METHOD1(SetPotentialFileLength, void(int64_t length));
- MOCK_METHOD0(Finish, void());
- MOCK_CONST_METHOD0(FullPath, const base::FilePath&());
- MOCK_CONST_METHOD0(InProgress, bool());
- MOCK_CONST_METHOD0(BytesSoFar, int64_t());
- MOCK_CONST_METHOD0(CurrentSpeed, int64_t());
- MOCK_METHOD1(GetHash, bool(std::string* hash));
- MOCK_METHOD0(SendUpdate, void());
- MOCK_CONST_METHOD0(Id, int());
- MOCK_METHOD0(GetDownloadManager, DownloadManager*());
- MOCK_CONST_METHOD0(DebugString, std::string());
- MOCK_METHOD0(Pause, void());
- MOCK_METHOD0(Resume, void());
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_DOWNLOAD_MOCK_DOWNLOAD_FILE_H_
diff --git a/chromium/content/browser/download/mock_download_item_impl.cc b/chromium/content/browser/download/mock_download_item_impl.cc
deleted file mode 100644
index 674f2521345..00000000000
--- a/chromium/content/browser/download/mock_download_item_impl.cc
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/download/mock_download_item_impl.h"
-
-namespace content {
-
-MockDownloadItemImpl::MockDownloadItemImpl(DownloadItemImplDelegate* delegate)
- : DownloadItemImpl(delegate,
- std::string("7d122682-55b5-4a47-a253-36cadc3e5bee"),
- download::DownloadItem::kInvalidId,
- base::FilePath(),
- base::FilePath(),
- std::vector<GURL>(),
- GURL(),
- GURL(),
- GURL(),
- GURL(),
- "application/octet-stream",
- "application/octet-stream",
- base::Time(),
- base::Time(),
- std::string(),
- std::string(),
- 0,
- 0,
- std::string(),
- download::DownloadItem::COMPLETE,
- download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
- download::DOWNLOAD_INTERRUPT_REASON_NONE,
- false,
- base::Time(),
- true,
- download::DownloadItem::ReceivedSlices()) {}
-
-MockDownloadItemImpl::~MockDownloadItemImpl() = default;
-
-} // namespace content
diff --git a/chromium/content/browser/download/mock_download_item_impl.h b/chromium/content/browser/download/mock_download_item_impl.h
deleted file mode 100644
index 4ac88319b41..00000000000
--- a/chromium/content/browser/download/mock_download_item_impl.h
+++ /dev/null
@@ -1,123 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_DOWNLOAD_MOCK_DOWNLOAD_ITEM_IMPL_H_
-#define CONTENT_BROWSER_DOWNLOAD_MOCK_DOWNLOAD_ITEM_IMPL_H_
-
-#include <memory>
-#include <string>
-#include <vector>
-
-#include "base/macros.h"
-#include "components/download/public/common/download_create_info.h"
-#include "components/download/public/common/download_request_handle_interface.h"
-#include "content/browser/download/download_file.h"
-#include "content/browser/download/download_item_impl.h"
-#include "testing/gmock/include/gmock/gmock.h"
-
-namespace content {
-
-class DownloadManager;
-
-class MockDownloadItemImpl : public DownloadItemImpl {
- public:
- // Use history constructor for minimal base object.
- explicit MockDownloadItemImpl(DownloadItemImplDelegate* delegate);
- ~MockDownloadItemImpl() override;
-
- MOCK_METHOD5(OnDownloadTargetDetermined,
- void(const base::FilePath&,
- TargetDisposition,
- download::DownloadDangerType,
- const base::FilePath&,
- download::DownloadInterruptReason));
- MOCK_METHOD1(AddObserver, void(download::DownloadItem::Observer*));
- MOCK_METHOD1(RemoveObserver, void(download::DownloadItem::Observer*));
- MOCK_METHOD0(UpdateObservers, void());
- MOCK_METHOD0(CanShowInFolder, bool());
- MOCK_METHOD0(CanOpenDownload, bool());
- MOCK_METHOD0(ShouldOpenFileBasedOnExtension, bool());
- MOCK_METHOD0(OpenDownload, void());
- MOCK_METHOD0(ShowDownloadInShell, void());
- MOCK_METHOD0(ValidateDangerousDownload, void());
- MOCK_METHOD2(StealDangerousDownload, void(bool, const AcquireFileCallback&));
- MOCK_METHOD3(UpdateProgress, void(int64_t, int64_t, const std::string&));
- MOCK_METHOD1(Cancel, void(bool));
- MOCK_METHOD0(MarkAsComplete, void());
- void OnAllDataSaved(int64_t, std::unique_ptr<crypto::SecureHash>) override {
- NOTREACHED();
- }
- MOCK_METHOD0(OnDownloadedFileRemoved, void());
- void Start(
- std::unique_ptr<DownloadFile> download_file,
- std::unique_ptr<download::DownloadRequestHandleInterface> req_handle,
- const download::DownloadCreateInfo& create_info) override {
- MockStart(download_file.get(), req_handle.get());
- }
-
- MOCK_METHOD2(MockStart,
- void(DownloadFile*, download::DownloadRequestHandleInterface*));
-
- MOCK_METHOD0(Remove, void());
- MOCK_CONST_METHOD1(TimeRemaining, bool(base::TimeDelta*));
- MOCK_CONST_METHOD0(CurrentSpeed, int64_t());
- MOCK_CONST_METHOD0(PercentComplete, int());
- MOCK_CONST_METHOD0(AllDataSaved, bool());
- MOCK_CONST_METHOD1(MatchesQuery, bool(const base::string16& query));
- MOCK_CONST_METHOD0(IsDone, bool());
- MOCK_CONST_METHOD0(GetFullPath, const base::FilePath&());
- MOCK_CONST_METHOD0(GetTargetFilePath, const base::FilePath&());
- MOCK_CONST_METHOD0(GetTargetDisposition, TargetDisposition());
- MOCK_METHOD2(OnContentCheckCompleted,
- void(download::DownloadDangerType,
- download::DownloadInterruptReason));
- MOCK_CONST_METHOD0(GetState, DownloadState());
- MOCK_CONST_METHOD0(GetUrlChain, const std::vector<GURL>&());
- MOCK_METHOD1(SetTotalBytes, void(int64_t));
- MOCK_CONST_METHOD0(GetURL, const GURL&());
- MOCK_CONST_METHOD0(GetOriginalUrl, const GURL&());
- MOCK_CONST_METHOD0(GetReferrerUrl, const GURL&());
- MOCK_CONST_METHOD0(GetTabUrl, const GURL&());
- MOCK_CONST_METHOD0(GetTabReferrerUrl, const GURL&());
- MOCK_CONST_METHOD0(GetSuggestedFilename, std::string());
- MOCK_CONST_METHOD0(GetContentDisposition, std::string());
- MOCK_CONST_METHOD0(GetMimeType, std::string());
- MOCK_CONST_METHOD0(GetOriginalMimeType, std::string());
- MOCK_CONST_METHOD0(GetReferrerCharset, std::string());
- MOCK_CONST_METHOD0(GetRemoteAddress, std::string());
- MOCK_CONST_METHOD0(GetTotalBytes, int64_t());
- MOCK_CONST_METHOD0(GetReceivedBytes, int64_t());
- MOCK_CONST_METHOD0(GetReceivedSlices, const std::vector<ReceivedSlice>&());
- MOCK_CONST_METHOD0(GetHashState, const std::string&());
- MOCK_CONST_METHOD0(GetHash, const std::string&());
- MOCK_CONST_METHOD0(GetId, uint32_t());
- MOCK_CONST_METHOD0(GetGuid, const std::string&());
- MOCK_CONST_METHOD0(GetStartTime, base::Time());
- MOCK_CONST_METHOD0(GetEndTime, base::Time());
- MOCK_METHOD0(GetDownloadManager, DownloadManager*());
- MOCK_CONST_METHOD0(IsPaused, bool());
- MOCK_CONST_METHOD0(GetOpenWhenComplete, bool());
- MOCK_METHOD1(SetOpenWhenComplete, void(bool));
- MOCK_CONST_METHOD0(GetFileExternallyRemoved, bool());
- MOCK_CONST_METHOD0(GetDangerType, download::DownloadDangerType());
- MOCK_CONST_METHOD0(IsDangerous, bool());
- MOCK_METHOD0(GetAutoOpened, bool());
- MOCK_CONST_METHOD0(GetForcedFilePath, const base::FilePath&());
- MOCK_CONST_METHOD0(HasUserGesture, bool());
- MOCK_CONST_METHOD0(GetTransitionType, ui::PageTransition());
- MOCK_CONST_METHOD0(IsTemporary, bool());
- MOCK_METHOD1(SetOpened, void(bool));
- MOCK_CONST_METHOD0(GetOpened, bool());
- MOCK_CONST_METHOD0(GetLastAccessTime, base::Time());
- MOCK_CONST_METHOD0(GetLastModifiedTime, const std::string&());
- MOCK_CONST_METHOD0(GetETag, const std::string&());
- MOCK_CONST_METHOD0(GetLastReason, download::DownloadInterruptReason());
- MOCK_CONST_METHOD0(GetFileNameToReportUser, base::FilePath());
- MOCK_METHOD1(SetDisplayName, void(const base::FilePath&));
- // May be called when vlog is on.
- std::string DebugString(bool verbose) const override { return std::string(); }
-};
-} // namespace content
-
-#endif // CONTENT_BROWSER_DOWNLOAD_MOCK_DOWNLOAD_ITEM_IMPL_H_
diff --git a/chromium/content/browser/download/mock_download_job.cc b/chromium/content/browser/download/mock_download_job.cc
deleted file mode 100644
index 02f927df6cc..00000000000
--- a/chromium/content/browser/download/mock_download_job.cc
+++ /dev/null
@@ -1,14 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/download/mock_download_job.h"
-
-namespace content {
-
-MockDownloadJob::MockDownloadJob(DownloadItemImpl* download_item)
- : DownloadJob(download_item, nullptr) {}
-
-MockDownloadJob::~MockDownloadJob() = default;
-
-} // namespace content
diff --git a/chromium/content/browser/download/mock_download_job.h b/chromium/content/browser/download/mock_download_job.h
deleted file mode 100644
index ac9c7b7b313..00000000000
--- a/chromium/content/browser/download/mock_download_job.h
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_DOWNLOAD_MOCK_DOWNLOAD_JOB_H_
-#define CONTENT_BROWSER_DOWNLOAD_MOCK_DOWNLOAD_JOB_H_
-
-#include <string>
-
-#include "base/macros.h"
-#include "content/browser/download/download_job.h"
-#include "testing/gmock/include/gmock/gmock.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace content {
-
-class DownloadItemImpl;
-
-class MockDownloadJob : public DownloadJob {
- public:
- explicit MockDownloadJob(DownloadItemImpl* download_item);
- ~MockDownloadJob() override;
-
- DownloadItemImpl* download_item() { return download_item_; }
-
- // DownloadJob implementation.
- MOCK_METHOD2(Start,
- void(const DownloadFile::InitializeCallback&,
- const download::DownloadItem::ReceivedSlices&));
- MOCK_METHOD1(Cancel, void(bool));
- MOCK_METHOD0(Pause, void());
- MOCK_METHOD1(Resume, void(bool));
- MOCK_CONST_METHOD0(CanOpen, bool());
- MOCK_CONST_METHOD0(CanResume, bool());
- MOCK_CONST_METHOD0(CanShowInFolder, bool());
- MOCK_CONST_METHOD0(IsActive, bool());
- MOCK_CONST_METHOD0(IsPaused, bool());
- MOCK_CONST_METHOD0(PercentComplete, int());
- MOCK_CONST_METHOD0(CurrentSpeed, int64_t());
- MOCK_CONST_METHOD1(TimeRemaining, bool(base::TimeDelta* remaining));
- MOCK_CONST_METHOD1(DebugString, std::string(bool));
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_DOWNLOAD_MOCK_DOWNLOAD_JOB_H_
diff --git a/chromium/content/browser/download/network_download_url_loader_factory_getter.cc b/chromium/content/browser/download/network_download_url_loader_factory_getter.cc
new file mode 100644
index 00000000000..df96621f93b
--- /dev/null
+++ b/chromium/content/browser/download/network_download_url_loader_factory_getter.cc
@@ -0,0 +1,27 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/download/network_download_url_loader_factory_getter.h"
+
+#include "components/download/public/common/download_task_runner.h"
+#include "content/browser/url_loader_factory_getter.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
+
+namespace content {
+
+NetworkDownloadURLLoaderFactoryGetter::NetworkDownloadURLLoaderFactoryGetter(
+ scoped_refptr<URLLoaderFactoryGetter> url_loader_factory_getter)
+ : url_loader_factory_getter_(url_loader_factory_getter) {}
+
+NetworkDownloadURLLoaderFactoryGetter::
+ ~NetworkDownloadURLLoaderFactoryGetter() = default;
+
+scoped_refptr<network::SharedURLLoaderFactory>
+NetworkDownloadURLLoaderFactoryGetter::GetURLLoaderFactory() {
+ DCHECK(download::GetIOTaskRunner());
+ DCHECK(download::GetIOTaskRunner()->BelongsToCurrentThread());
+ return url_loader_factory_getter_->GetNetworkFactory();
+}
+
+} // namespace content
diff --git a/chromium/content/browser/download/network_download_url_loader_factory_getter.h b/chromium/content/browser/download/network_download_url_loader_factory_getter.h
new file mode 100644
index 00000000000..cf6eaa10182
--- /dev/null
+++ b/chromium/content/browser/download/network_download_url_loader_factory_getter.h
@@ -0,0 +1,35 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_BROWSER_DOWNLOAD_NETWORK_DOWNLOAD_URL_LOADER_FACTORY_GETTER_H_
+#define CONTENT_BROWSER_DOWNLOAD_NETWORK_DOWNLOAD_URL_LOADER_FACTORY_GETTER_H_
+
+#include "components/download/public/common/download_url_loader_factory_getter.h"
+
+namespace content {
+
+class URLLoaderFactoryGetter;
+
+// Wrapper of URLLoaderFactoryGetter to retrieve URLLoaderFactory.
+class NetworkDownloadURLLoaderFactoryGetter
+ : public download::DownloadURLLoaderFactoryGetter {
+ public:
+ explicit NetworkDownloadURLLoaderFactoryGetter(
+ scoped_refptr<URLLoaderFactoryGetter> url_loader_factory_getter);
+
+ // download::DownloadURLLoaderFactoryGetter implementation.
+ scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory() override;
+
+ protected:
+ ~NetworkDownloadURLLoaderFactoryGetter() override;
+
+ private:
+ scoped_refptr<URLLoaderFactoryGetter> url_loader_factory_getter_;
+
+ DISALLOW_COPY_AND_ASSIGN(NetworkDownloadURLLoaderFactoryGetter);
+};
+
+} // namespace content
+
+#endif // CONTENT_BROWSER_DOWNLOAD_NETWORK_DOWNLOAD_URL_LOADER_FACTORY_GETTER_H_
diff --git a/chromium/content/browser/download/parallel_download_job.cc b/chromium/content/browser/download/parallel_download_job.cc
deleted file mode 100644
index de25ae93f74..00000000000
--- a/chromium/content/browser/download/parallel_download_job.cc
+++ /dev/null
@@ -1,313 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/download/parallel_download_job.h"
-
-#include <algorithm>
-
-#include "base/bind.h"
-#include "base/memory/ptr_util.h"
-#include "base/metrics/histogram_macros.h"
-#include "base/time/time.h"
-#include "components/download/public/common/download_create_info.h"
-#include "components/download/public/common/download_stats.h"
-#include "content/browser/download/download_utils.h"
-#include "content/browser/download/parallel_download_utils.h"
-#include "content/browser/storage_partition_impl.h"
-#include "content/public/browser/browser_context.h"
-#include "content/public/browser/download_item_utils.h"
-#include "content/public/browser/storage_partition.h"
-#include "net/traffic_annotation/network_traffic_annotation.h"
-
-namespace content {
-namespace {
-
-const int kDownloadJobVerboseLevel = 1;
-
-} // namespace
-
-ParallelDownloadJob::ParallelDownloadJob(
- DownloadItemImpl* download_item,
- std::unique_ptr<download::DownloadRequestHandleInterface> request_handle,
- const download::DownloadCreateInfo& create_info)
- : DownloadJobImpl(download_item, std::move(request_handle), true),
- initial_request_offset_(create_info.offset),
- initial_received_slices_(download_item->GetReceivedSlices()),
- content_length_(create_info.total_bytes),
- requests_sent_(false),
- is_canceled_(false) {}
-
-ParallelDownloadJob::~ParallelDownloadJob() = default;
-
-void ParallelDownloadJob::OnDownloadFileInitialized(
- const DownloadFile::InitializeCallback& callback,
- download::DownloadInterruptReason result) {
- DownloadJobImpl::OnDownloadFileInitialized(callback, result);
- if (result == download::DOWNLOAD_INTERRUPT_REASON_NONE)
- BuildParallelRequestAfterDelay();
-}
-
-void ParallelDownloadJob::Cancel(bool user_cancel) {
- is_canceled_ = true;
- DownloadJobImpl::Cancel(user_cancel);
-
- if (!requests_sent_) {
- timer_.Stop();
- return;
- }
-
- for (auto& worker : workers_)
- worker.second->Cancel(user_cancel);
-}
-
-void ParallelDownloadJob::Pause() {
- DownloadJobImpl::Pause();
-
- if (!requests_sent_) {
- timer_.Stop();
- return;
- }
-
- for (auto& worker : workers_)
- worker.second->Pause();
-}
-
-void ParallelDownloadJob::Resume(bool resume_request) {
- DownloadJobImpl::Resume(resume_request);
- if (!resume_request)
- return;
-
- // Send parallel requests if the download is paused previously.
- if (!requests_sent_) {
- if (!timer_.IsRunning())
- BuildParallelRequestAfterDelay();
- return;
- }
-
- for (auto& worker : workers_)
- worker.second->Resume();
-}
-
-int ParallelDownloadJob::GetParallelRequestCount() const {
- return GetParallelRequestCountConfig();
-}
-
-int64_t ParallelDownloadJob::GetMinSliceSize() const {
- return GetMinSliceSizeConfig();
-}
-
-int ParallelDownloadJob::GetMinRemainingTimeInSeconds() const {
- return GetParallelRequestRemainingTimeConfig().InSeconds();
-}
-
-void ParallelDownloadJob::CancelRequestWithOffset(int64_t offset) {
- if (initial_request_offset_ == offset) {
- DownloadJobImpl::Cancel(false);
- return;
- }
-
- auto it = workers_.find(offset);
- DCHECK(it != workers_.end());
- it->second->Cancel(false);
-}
-
-void ParallelDownloadJob::BuildParallelRequestAfterDelay() {
- DCHECK(workers_.empty());
- DCHECK(!requests_sent_);
- DCHECK(!timer_.IsRunning());
-
- timer_.Start(FROM_HERE, GetParallelRequestDelayConfig(), this,
- &ParallelDownloadJob::BuildParallelRequests);
-}
-
-void ParallelDownloadJob::OnInputStreamReady(
- DownloadWorker* worker,
- std::unique_ptr<DownloadManager::InputStream> input_stream) {
- bool success = DownloadJob::AddInputStream(
- std::move(input_stream), worker->offset(), worker->length());
- download::RecordParallelDownloadAddStreamSuccess(success);
-
- // Destroy the request if the sink is gone.
- if (!success) {
- VLOG(kDownloadJobVerboseLevel)
- << "Byte stream arrived after download file is released.";
- worker->Cancel(false);
- }
-}
-
-void ParallelDownloadJob::BuildParallelRequests() {
- DCHECK(!requests_sent_);
- DCHECK(!is_paused());
- if (is_canceled_ || download_item_->GetState() !=
- download::DownloadItem::DownloadState::IN_PROGRESS) {
- return;
- }
-
- // TODO(qinmin): The size of |slices_to_download| should be no larger than
- // |kParallelRequestCount| unless |kParallelRequestCount| is changed after
- // a download is interrupted. This could happen if we use finch to config
- // the number of parallel requests.
- // Get the next |kParallelRequestCount - 1| slices and fork
- // new requests. For the remaining slices, they will be handled once some
- // of the workers finish their job.
- const download::DownloadItem::ReceivedSlices& received_slices =
- download_item_->GetReceivedSlices();
- download::DownloadItem::ReceivedSlices slices_to_download =
- FindSlicesToDownload(received_slices);
-
- DCHECK(!slices_to_download.empty());
- int64_t first_slice_offset = slices_to_download[0].offset;
-
- // We may build parallel job without slices. The slices can be cleared or
- // previous session only has one stream writing to disk. In these cases, fall
- // back to non parallel download.
- if (initial_request_offset_ > first_slice_offset) {
- VLOG(kDownloadJobVerboseLevel)
- << "Received slices data mismatch initial request offset.";
- return;
- }
-
- // Create more slices for a new download. The initial request may generate
- // a received slice.
- if (slices_to_download.size() <= 1 && download_item_->GetTotalBytes() > 0) {
- int64_t current_bytes_per_second =
- std::max(static_cast<int64_t>(1), download_item_->CurrentSpeed());
- int64_t remaining_bytes =
- download_item_->GetTotalBytes() - download_item_->GetReceivedBytes();
-
- int64_t remaining_time = remaining_bytes / current_bytes_per_second;
- UMA_HISTOGRAM_CUSTOM_COUNTS(
- "Download.ParallelDownload.RemainingTimeWhenBuildingRequests",
- remaining_time, 0, base::TimeDelta::FromDays(1).InSeconds(), 50);
- if (remaining_bytes / current_bytes_per_second >
- GetMinRemainingTimeInSeconds()) {
- // Fork more requests to accelerate, only if one slice is left to download
- // and remaining time seems to be long enough.
- slices_to_download = FindSlicesForRemainingContent(
- first_slice_offset,
- content_length_ - first_slice_offset + initial_request_offset_,
- GetParallelRequestCount(), GetMinSliceSize());
- } else {
- download::RecordParallelDownloadCreationEvent(
- download::ParallelDownloadCreationEvent::
- FALLBACK_REASON_REMAINING_TIME);
- }
- }
-
- DCHECK(!slices_to_download.empty());
-
- // If the last received slice is finished, remove the last request which can
- // be out of the range of the file. E.g, the file is 100 bytes, and the last
- // request's range header will be "Range:100-".
- if (!received_slices.empty() && received_slices.back().finished)
- slices_to_download.pop_back();
-
- ForkSubRequests(slices_to_download);
- download::RecordParallelDownloadRequestCount(
- static_cast<int>(slices_to_download.size()));
- requests_sent_ = true;
-}
-
-void ParallelDownloadJob::ForkSubRequests(
- const download::DownloadItem::ReceivedSlices& slices_to_download) {
- if (slices_to_download.size() < 2)
- return;
-
- // If the initial request is working on the first hole, don't create parallel
- // request for this hole.
- bool skip_first_slice = true;
- download::DownloadItem::ReceivedSlices initial_slices_to_download =
- FindSlicesToDownload(initial_received_slices_);
- if (initial_slices_to_download.size() > 1) {
- DCHECK_EQ(initial_request_offset_, initial_slices_to_download[0].offset);
- int64_t first_hole_max = initial_slices_to_download[0].offset +
- initial_slices_to_download[0].received_bytes;
- skip_first_slice = slices_to_download[0].offset <= first_hole_max;
- }
-
- for (auto it = slices_to_download.begin(); it != slices_to_download.end();
- ++it) {
- if (skip_first_slice) {
- skip_first_slice = false;
- continue;
- }
-
- DCHECK_GE(it->offset, initial_request_offset_);
- // All parallel requests are half open, which sends request headers like
- // "Range:50-".
- // If server rejects a certain request, others should take over.
- CreateRequest(it->offset, download::DownloadSaveInfo::kLengthFullContent);
- }
-}
-
-void ParallelDownloadJob::CreateRequest(int64_t offset, int64_t length) {
- DCHECK(download_item_);
- DCHECK_EQ(download::DownloadSaveInfo::kLengthFullContent, length);
-
- std::unique_ptr<DownloadWorker> worker =
- std::make_unique<DownloadWorker>(this, offset, length);
-
- StoragePartition* storage_partition =
- BrowserContext::GetStoragePartitionForSite(
- DownloadItemUtils::GetBrowserContext(download_item_),
- download_item_->GetSiteUrl());
-
- net::NetworkTrafficAnnotationTag traffic_annotation =
- net::DefineNetworkTrafficAnnotation("parallel_download_job", R"(
- semantics {
- sender: "Parallel Download"
- description:
- "Chrome makes parallel request to speed up download of a file."
- trigger:
- "When user starts a download request, if it would be technically "
- "possible, Chrome starts parallel downloading."
- data: "None."
- destination: WEBSITE
- }
- policy {
- cookies_allowed: YES
- cookies_store: "user"
- setting: "This feature cannot be disabled in settings."
- chrome_policy {
- DownloadRestrictions {
- DownloadRestrictions: 3
- }
- }
- })");
- // The parallel requests only use GET method.
- std::unique_ptr<download::DownloadUrlParameters> download_params(
- new download::DownloadUrlParameters(
- download_item_->GetURL(), storage_partition->GetURLRequestContext(),
- traffic_annotation));
- download_params->set_file_path(download_item_->GetFullPath());
- download_params->set_last_modified(download_item_->GetLastModifiedTime());
- download_params->set_etag(download_item_->GetETag());
- download_params->set_offset(offset);
-
- // Setting the length will result in range request to fetch a slice of the
- // file.
- download_params->set_length(length);
-
- // Subsequent range requests don't need the "If-Range" header.
- download_params->set_use_if_range(false);
-
- // Subsequent range requests have the same referrer URL as the original
- // download request.
- download_params->set_referrer(download_item_->GetReferrerUrl());
- download_params->set_referrer_policy(net::URLRequest::NEVER_CLEAR_REFERRER);
-
- download_params->set_blob_storage_context_getter(
- base::BindOnce(&BlobStorageContextGetter,
- DownloadItemUtils::GetBrowserContext(download_item_)
- ->GetResourceContext()));
-
- // Send the request.
- worker->SendRequest(std::move(download_params),
- static_cast<StoragePartitionImpl*>(storage_partition)
- ->url_loader_factory_getter());
- DCHECK(workers_.find(offset) == workers_.end());
- workers_[offset] = std::move(worker);
-}
-
-} // namespace content
diff --git a/chromium/content/browser/download/parallel_download_job.h b/chromium/content/browser/download/parallel_download_job.h
deleted file mode 100644
index 14d16beba7e..00000000000
--- a/chromium/content/browser/download/parallel_download_job.h
+++ /dev/null
@@ -1,110 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_DOWNLOAD_PARALLEL_DOWNLOAD_JOB_H_
-#define CONTENT_BROWSER_DOWNLOAD_PARALLEL_DOWNLOAD_JOB_H_
-
-#include <memory>
-#include <unordered_map>
-#include <vector>
-
-#include "base/macros.h"
-#include "base/timer/timer.h"
-#include "content/browser/download/download_job_impl.h"
-#include "content/browser/download/download_worker.h"
-#include "content/common/content_export.h"
-
-namespace content {
-
-// DownloadJob that can create concurrent range requests to fetch different
-// parts of the file.
-// The original request is hold in base class.
-class CONTENT_EXPORT ParallelDownloadJob : public DownloadJobImpl,
- public DownloadWorker::Delegate {
- public:
- ParallelDownloadJob(
- DownloadItemImpl* download_item,
- std::unique_ptr<download::DownloadRequestHandleInterface> request_handle,
- const download::DownloadCreateInfo& create_info);
- ~ParallelDownloadJob() override;
-
- // DownloadJobImpl implementation.
- void Cancel(bool user_cancel) override;
- void Pause() override;
- void Resume(bool resume_request) override;
- void CancelRequestWithOffset(int64_t offset) override;
-
- protected:
- // DownloadJobImpl implementation.
- void OnDownloadFileInitialized(
- const DownloadFile::InitializeCallback& callback,
- download::DownloadInterruptReason result) override;
-
- // Virtual for testing.
- virtual int GetParallelRequestCount() const;
- virtual int64_t GetMinSliceSize() const;
- virtual int GetMinRemainingTimeInSeconds() const;
-
- using WorkerMap =
- std::unordered_map<int64_t, std::unique_ptr<DownloadWorker>>;
-
- // Map from the offset position of the slice to the worker that downloads the
- // slice.
- WorkerMap workers_;
-
- private:
- friend class ParallelDownloadJobTest;
-
- // DownloadWorker::Delegate implementation.
- void OnInputStreamReady(
- DownloadWorker* worker,
- std::unique_ptr<DownloadManager::InputStream> input_stream) override;
-
- // Build parallel requests after a delay, to effectively measure the single
- // stream bandwidth.
- void BuildParallelRequestAfterDelay();
-
- // Build parallel requests to download. This function is the entry point for
- // all parallel downloads.
- void BuildParallelRequests();
-
- // Build one http request for each slice from the second slice.
- // The first slice represents the original request.
- void ForkSubRequests(
- const download::DownloadItem::ReceivedSlices& slices_to_download);
-
- // Create one range request, virtual for testing. Range request will start
- // from |offset| to |length|. Range request will be half open, e.g.
- // "Range:50-" if |length| is 0.
- virtual void CreateRequest(int64_t offset, int64_t length);
-
- // Information about the initial request when download is started.
- int64_t initial_request_offset_;
-
- // A snapshot of received slices when creating the parallel download job.
- // Download item's received slices may be different from this snapshot when
- // |BuildParallelRequests| is called.
- download::DownloadItem::ReceivedSlices initial_received_slices_;
-
- // The length of the response body of the original request.
- // Used to estimate the remaining size of the content when the initial
- // request is half open, i.e, |initial_request_length_| is
- // DownloadSaveInfo::kLengthFullContent.
- int64_t content_length_;
-
- // Used to send parallel requests after a delay based on Finch config.
- base::OneShotTimer timer_;
-
- // If we have sent parallel requests.
- bool requests_sent_;
-
- // If the download progress is canceled.
- bool is_canceled_;
-
- DISALLOW_COPY_AND_ASSIGN(ParallelDownloadJob);
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_DOWNLOAD_PARALLEL_DOWNLOAD_JOB_H_
diff --git a/chromium/content/browser/download/parallel_download_job_unittest.cc b/chromium/content/browser/download/parallel_download_job_unittest.cc
deleted file mode 100644
index 00aff74305b..00000000000
--- a/chromium/content/browser/download/parallel_download_job_unittest.cc
+++ /dev/null
@@ -1,543 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/download/parallel_download_job.h"
-
-#include <utility>
-#include <vector>
-
-#include "base/memory/ptr_util.h"
-#include "base/run_loop.h"
-#include "base/test/mock_callback.h"
-#include "base/test/scoped_task_environment.h"
-#include "components/download/public/common/download_task_runner.h"
-#include "content/browser/download/download_destination_observer.h"
-#include "content/browser/download/download_file_impl.h"
-#include "content/browser/download/download_item_impl_delegate.h"
-#include "content/browser/download/mock_download_item_impl.h"
-#include "content/browser/download/parallel_download_utils.h"
-#include "content/public/test/test_browser_thread_bundle.h"
-#include "testing/gmock/include/gmock/gmock.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-using ::testing::_;
-using ::testing::NiceMock;
-using ::testing::Return;
-using ::testing::ReturnRef;
-using ::testing::StrictMock;
-
-namespace content {
-
-namespace {
-
-class MockDownloadRequestHandle
- : public download::DownloadRequestHandleInterface {
- public:
- MOCK_METHOD0(PauseRequest, void());
- MOCK_METHOD0(ResumeRequest, void());
- MOCK_METHOD1(CancelRequest, void(bool));
-};
-
-class MockDownloadDestinationObserver : public DownloadDestinationObserver {
- public:
- MOCK_METHOD3(DestinationUpdate,
- void(int64_t,
- int64_t,
- const std::vector<download::DownloadItem::ReceivedSlice>&));
- void DestinationError(
- download::DownloadInterruptReason reason,
- int64_t bytes_so_far,
- std::unique_ptr<crypto::SecureHash> hash_state) override {}
- void DestinationCompleted(
- int64_t total_bytes,
- std::unique_ptr<crypto::SecureHash> hash_state) override {}
- MOCK_METHOD2(CurrentUpdateStatus, void(int64_t, int64_t));
-};
-
-class MockByteStreamReader : public ByteStreamReader {
- public:
- MOCK_METHOD2(Read,
- ByteStreamReader::StreamState(scoped_refptr<net::IOBuffer>*,
- size_t*));
- MOCK_CONST_METHOD0(GetStatus, int());
- MOCK_METHOD1(RegisterCallback, void(const base::Closure&));
-};
-
-} // namespace
-
-class ParallelDownloadJobForTest : public ParallelDownloadJob {
- public:
- ParallelDownloadJobForTest(
- DownloadItemImpl* download_item,
- std::unique_ptr<download::DownloadRequestHandleInterface> request_handle,
- const download::DownloadCreateInfo& create_info,
- int request_count,
- int64_t min_slice_size,
- int min_remaining_time)
- : ParallelDownloadJob(download_item,
- std::move(request_handle),
- create_info),
- request_count_(request_count),
- min_slice_size_(min_slice_size),
- min_remaining_time_(min_remaining_time) {}
-
- void CreateRequest(int64_t offset, int64_t length) override {
- std::unique_ptr<DownloadWorker> worker =
- std::make_unique<DownloadWorker>(this, offset, length);
-
- DCHECK(workers_.find(offset) == workers_.end());
- workers_[offset] = std::move(worker);
- }
-
- ParallelDownloadJob::WorkerMap& workers() { return workers_; }
-
- void MakeFileInitialized(const DownloadFile::InitializeCallback& callback,
- download::DownloadInterruptReason result) {
- ParallelDownloadJob::OnDownloadFileInitialized(callback, result);
- }
-
- int GetParallelRequestCount() const override { return request_count_; }
- int64_t GetMinSliceSize() const override { return min_slice_size_; }
- int GetMinRemainingTimeInSeconds() const override {
- return min_remaining_time_;
- }
-
- void OnInputStreamReady(
- DownloadWorker* worker,
- std::unique_ptr<DownloadManager::InputStream> input_stream) override {
- CountOnInputStreamReady();
- }
-
- MOCK_METHOD0(CountOnInputStreamReady, void());
-
- private:
- int request_count_;
- int min_slice_size_;
- int min_remaining_time_;
- DISALLOW_COPY_AND_ASSIGN(ParallelDownloadJobForTest);
-};
-
-class ParallelDownloadJobTest : public testing::Test {
- public:
- ParallelDownloadJobTest()
- : task_environment_(
- base::test::ScopedTaskEnvironment::MainThreadType::UI,
- base::test::ScopedTaskEnvironment::ExecutionMode::QUEUED) {}
-
- void CreateParallelJob(int64_t initial_request_offset,
- int64_t content_length,
- const download::DownloadItem::ReceivedSlices& slices,
- int request_count,
- int64_t min_slice_size,
- int min_remaining_time) {
- item_delegate_ = std::make_unique<DownloadItemImplDelegate>();
- received_slices_ = slices;
- download_item_ =
- std::make_unique<NiceMock<MockDownloadItemImpl>>(item_delegate_.get());
- EXPECT_CALL(*download_item_, GetTotalBytes())
- .WillRepeatedly(Return(initial_request_offset + content_length));
- EXPECT_CALL(*download_item_, GetReceivedBytes())
- .WillRepeatedly(Return(initial_request_offset));
- EXPECT_CALL(*download_item_, GetReceivedSlices())
- .WillRepeatedly(ReturnRef(received_slices_));
-
- download::DownloadCreateInfo info;
- info.offset = initial_request_offset;
- info.total_bytes = content_length;
- std::unique_ptr<MockDownloadRequestHandle> request_handle =
- std::make_unique<MockDownloadRequestHandle>();
- mock_request_handle_ = request_handle.get();
- job_ = std::make_unique<ParallelDownloadJobForTest>(
- download_item_.get(), std::move(request_handle), info, request_count,
- min_slice_size, min_remaining_time);
- file_initialized_ = false;
- }
-
- void DestroyParallelJob() {
- job_.reset();
- download_item_.reset();
- item_delegate_.reset();
- mock_request_handle_ = nullptr;
- }
-
- void BuildParallelRequests() { job_->BuildParallelRequests(); }
-
- void set_received_slices(
- const download::DownloadItem::ReceivedSlices& slices) {
- received_slices_ = slices;
- }
-
- bool IsJobCanceled() const { return job_->is_canceled_; };
-
- void MakeWorkerReady(
- DownloadWorker* worker,
- std::unique_ptr<MockDownloadRequestHandle> request_handle) {
- UrlDownloadHandler::Delegate* delegate =
- static_cast<UrlDownloadHandler::Delegate*>(worker);
- std::unique_ptr<download::DownloadCreateInfo> create_info =
- std::make_unique<download::DownloadCreateInfo>();
- create_info->request_handle = std::move(request_handle);
- delegate->OnUrlDownloadStarted(
- std::move(create_info),
- std::make_unique<DownloadManager::InputStream>(
- std::make_unique<MockByteStreamReader>()),
- download::DownloadUrlParameters::OnStartedCallback());
- }
-
- void VerifyWorker(int64_t offset, int64_t length) const {
- EXPECT_TRUE(job_->workers_.find(offset) != job_->workers_.end());
- EXPECT_EQ(offset, job_->workers_[offset]->offset());
- EXPECT_EQ(length, job_->workers_[offset]->length());
- }
-
- void OnFileInitialized(download::DownloadInterruptReason result) {
- file_initialized_ = true;
- }
-
- base::test::ScopedTaskEnvironment task_environment_;
- content::TestBrowserThreadBundle browser_threads_;
- std::unique_ptr<DownloadItemImplDelegate> item_delegate_;
- std::unique_ptr<MockDownloadItemImpl> download_item_;
- std::unique_ptr<ParallelDownloadJobForTest> job_;
- bool file_initialized_;
- // Request handle for the original request.
- MockDownloadRequestHandle* mock_request_handle_;
-
- // The received slices used to return in
- // |MockDownloadItemImpl::GetReceivedSlices| mock function.
- download::DownloadItem::ReceivedSlices received_slices_;
-};
-
-// Test if parallel requests can be built correctly for a new download without
-// existing slices.
-TEST_F(ParallelDownloadJobTest, CreateNewDownloadRequestsWithoutSlices) {
- // Totally 2 requests for 100 bytes.
- // Original request: Range:0-, for 50 bytes.
- // Task 1: Range:50-, for 50 bytes.
- CreateParallelJob(0, 100, download::DownloadItem::ReceivedSlices(), 2, 1, 10);
- BuildParallelRequests();
- EXPECT_EQ(1u, job_->workers().size());
- VerifyWorker(50, 0);
- DestroyParallelJob();
-
- // Totally 3 requests for 100 bytes.
- // Original request: Range:0-, for 33 bytes.
- // Task 1: Range:33-, for 33 bytes.
- // Task 2: Range:66-, for 34 bytes.
- CreateParallelJob(0, 100, download::DownloadItem::ReceivedSlices(), 3, 1, 10);
- BuildParallelRequests();
- EXPECT_EQ(2u, job_->workers().size());
- VerifyWorker(33, 0);
- VerifyWorker(66, 0);
- DestroyParallelJob();
-
- // Less than 2 requests, do nothing.
- CreateParallelJob(0, 100, download::DownloadItem::ReceivedSlices(), 1, 1, 10);
- BuildParallelRequests();
- EXPECT_TRUE(job_->workers().empty());
- DestroyParallelJob();
-
- CreateParallelJob(0, 100, download::DownloadItem::ReceivedSlices(), 0, 1, 10);
- BuildParallelRequests();
- EXPECT_TRUE(job_->workers().empty());
- DestroyParallelJob();
-
- // Content-length is 0, do nothing.
- CreateParallelJob(0, 0, download::DownloadItem::ReceivedSlices(), 3, 1, 10);
- BuildParallelRequests();
- EXPECT_TRUE(job_->workers().empty());
- DestroyParallelJob();
-}
-
-TEST_F(ParallelDownloadJobTest, CreateNewDownloadRequestsWithSlices) {
- // File size: 100 bytes.
- // Received slices: [0, 17]
- // Original request: Range:12-. Content-length: 88.
- // Totally 3 requests for 83 bytes.
- // Original request: Range:12-43.
- // Task 1: Range:44-70, for 27 bytes.
- // Task 2: Range:71-, for 29 bytes.
- download::DownloadItem::ReceivedSlices slices = {
- download::DownloadItem::ReceivedSlice(0, 17)};
- CreateParallelJob(12, 88, slices, 3, 1, 10);
- BuildParallelRequests();
- EXPECT_EQ(2u, job_->workers().size());
- VerifyWorker(44, 0);
- VerifyWorker(71, 0);
- DestroyParallelJob();
-
- // File size: 100 bytes.
- // Received slices: [0, 60], Range:0-59.
- // Original request: Range:60-. Content-length: 40.
- // 40 bytes left for 4 requests. Only 1 additional request.
- // Original request: Range:60-79, for 20 bytes.
- // Task 1: Range:80-, for 20 bytes.
- slices = {download::DownloadItem::ReceivedSlice(0, 60)};
- CreateParallelJob(60, 40, slices, 4, 20, 10);
- BuildParallelRequests();
- EXPECT_EQ(1u, job_->workers().size());
- VerifyWorker(80, 0);
- DestroyParallelJob();
-
- // Content-Length is 0, no additional requests.
- slices = {download::DownloadItem::ReceivedSlice(0, 100)};
- CreateParallelJob(100, 0, slices, 3, 1, 10);
- BuildParallelRequests();
- EXPECT_TRUE(job_->workers().empty());
- DestroyParallelJob();
-
- // File size: 100 bytes.
- // Original request: Range:0-. Content-length: 12(Incorrect server header).
- // The request count is 2, however the file contains 3 holes, and we don't
- // know if the last slice is completed, so there should be 3 requests in
- // parallel and the last request is an out-of-range request.
- slices = {download::DownloadItem::ReceivedSlice(10, 10),
- download::DownloadItem::ReceivedSlice(20, 10),
- download::DownloadItem::ReceivedSlice(40, 10),
- download::DownloadItem::ReceivedSlice(90, 10)};
- CreateParallelJob(0, 12, slices, 2, 1, 10);
- BuildParallelRequests();
- EXPECT_EQ(3u, job_->workers().size());
- VerifyWorker(30, 0);
- VerifyWorker(50, 0);
- VerifyWorker(100, 0);
- DestroyParallelJob();
-}
-
-// Ensure that in download resumption, if the first hole is filled before
-// sending multiple requests, the new requests can be correctly calculated.
-TEST_F(ParallelDownloadJobTest, CreateResumptionRequestsFirstSliceFilled) {
- download::DownloadItem::ReceivedSlices slices = {
- download::DownloadItem::ReceivedSlice(0, 10),
- download::DownloadItem::ReceivedSlice(40, 10),
- download::DownloadItem::ReceivedSlice(80, 10)};
-
- // The updated slices that has filled the first hole.
- download::DownloadItem::ReceivedSlices updated_slices = slices;
- updated_slices[0].received_bytes = 40;
-
- CreateParallelJob(10, 90, slices, 3, 1, 10);
- // Now let download item to return an updated received slice, that the first
- // hole in the file has been filled.
- set_received_slices(updated_slices);
- BuildParallelRequests();
-
- // Since the first hole is filled, parallel requests are created to fill other
- // two holes.
- EXPECT_EQ(2u, job_->workers().size());
- VerifyWorker(50, 0);
- VerifyWorker(90, 0);
- DestroyParallelJob();
-}
-
-// Simulate an edge case that we have one received slice in the middle. The
-// parallel request should be created correctly.
-// This may not happen under current implementation, but should be also handled
-// correctly.
-TEST_F(ParallelDownloadJobTest, CreateResumptionRequestsTwoSlicesToFill) {
- download::DownloadItem::ReceivedSlices slices = {
- download::DownloadItem::ReceivedSlice(40, 10)};
-
- CreateParallelJob(0, 100, slices, 3, 1, 10);
- BuildParallelRequests();
-
- EXPECT_EQ(1u, job_->workers().size());
- VerifyWorker(50, 0);
- DestroyParallelJob();
-
- download::DownloadItem::ReceivedSlices updated_slices = {
- download::DownloadItem::ReceivedSlice(0, 10),
- download::DownloadItem::ReceivedSlice(40, 10)};
-
- CreateParallelJob(0, 100, slices, 3, 1, 10);
- // Now let download item to return an updated received slice, that the first
- // hole in the file is not fully filled.
- set_received_slices(updated_slices);
- BuildParallelRequests();
-
- // Because the initial request is working on the first hole, there should be
- // only one parallel request to fill the second hole.
- EXPECT_EQ(1u, job_->workers().size());
- VerifyWorker(50, 0);
- DestroyParallelJob();
-}
-
-// Verifies that if the last received slice is finished, we don't send an out
-// of range request that starts from the last byte position.
-TEST_F(ParallelDownloadJobTest, LastReceivedSliceFinished) {
- // One finished slice, no parallel requests should be created. Content length
- // should be 0.
- download::DownloadItem::ReceivedSlices slices = {
- download::DownloadItem::ReceivedSlice(0, 100, true)};
- CreateParallelJob(100, 0, slices, 3, 1, 10);
- BuildParallelRequests();
- EXPECT_EQ(0u, job_->workers().size());
- DestroyParallelJob();
-
- // Two received slices with one hole in the middle. Since the second slice is
- // finished, and the hole will be filled by original request, no parallel
- // requests will be created.
- slices = {download::DownloadItem::ReceivedSlice(0, 25),
- download::DownloadItem::ReceivedSlice(75, 25, true)};
- CreateParallelJob(25, 100, slices, 3, 1, 10);
- BuildParallelRequests();
- EXPECT_EQ(0u, job_->workers().size());
- DestroyParallelJob();
-
- // Three received slices with two hole in the middle and the last slice is
- // finished. The original request will work on the first hole and one parallel
- // request is created to fill the second hole.
- slices = {download::DownloadItem::ReceivedSlice(0, 25),
- download::DownloadItem::ReceivedSlice(50, 25),
- download::DownloadItem::ReceivedSlice(100, 25, true)};
- CreateParallelJob(25, 125, slices, 3, 1, 10);
- BuildParallelRequests();
- EXPECT_EQ(1u, job_->workers().size());
- VerifyWorker(75, 0);
- DestroyParallelJob();
-}
-
-// Pause, cancel, resume can be called before or after the worker establish
-// the byte stream.
-// These tests ensure the states consistency between the job and workers.
-
-// Ensure cancel before building the requests will result in no requests are
-// built.
-TEST_F(ParallelDownloadJobTest, EarlyCancelBeforeBuildRequests) {
- CreateParallelJob(0, 100, download::DownloadItem::ReceivedSlices(), 2, 1, 10);
- EXPECT_CALL(*mock_request_handle_, CancelRequest(_));
-
- // Job is canceled before building parallel requests.
- job_->Cancel(true);
- EXPECT_TRUE(IsJobCanceled());
-
- BuildParallelRequests();
- EXPECT_TRUE(job_->workers().empty());
-
- DestroyParallelJob();
-}
-
-// Ensure cancel before adding the byte stream will result in workers being
-// canceled.
-TEST_F(ParallelDownloadJobTest, EarlyCancelBeforeByteStreamReady) {
- CreateParallelJob(0, 100, download::DownloadItem::ReceivedSlices(), 2, 1, 10);
- EXPECT_CALL(*mock_request_handle_, CancelRequest(_));
-
- BuildParallelRequests();
- VerifyWorker(50, 0);
-
- // Job is canceled after building parallel requests and before byte streams
- // are added to the file sink.
- job_->Cancel(true);
- EXPECT_TRUE(IsJobCanceled());
-
- for (auto& worker : job_->workers()) {
- std::unique_ptr<MockDownloadRequestHandle> mock_handle =
- std::make_unique<MockDownloadRequestHandle>();
- EXPECT_CALL(*mock_handle.get(), CancelRequest(_));
- MakeWorkerReady(worker.second.get(), std::move(mock_handle));
- }
-
- DestroyParallelJob();
-}
-
-// Ensure pause before adding the byte stream will result in workers being
-// paused.
-TEST_F(ParallelDownloadJobTest, EarlyPauseBeforeByteStreamReady) {
- CreateParallelJob(0, 100, download::DownloadItem::ReceivedSlices(), 2, 1, 10);
- EXPECT_CALL(*mock_request_handle_, PauseRequest());
-
- BuildParallelRequests();
- VerifyWorker(50, 0);
-
- // Job is paused after building parallel requests and before adding the byte
- // stream to the file sink.
- job_->Pause();
- EXPECT_TRUE(job_->is_paused());
-
- for (auto& worker : job_->workers()) {
- EXPECT_CALL(*job_.get(), CountOnInputStreamReady());
- std::unique_ptr<MockDownloadRequestHandle> mock_handle =
- std::make_unique<MockDownloadRequestHandle>();
- EXPECT_CALL(*mock_handle.get(), PauseRequest());
- MakeWorkerReady(worker.second.get(), std::move(mock_handle));
- }
-
- DestroyParallelJob();
-}
-
-// Test that parallel request is not created if the remaining content can be
-// finish downloading soon.
-TEST_F(ParallelDownloadJobTest, RemainingContentWillFinishSoon) {
- download::DownloadItem::ReceivedSlices slices = {
- download::DownloadItem::ReceivedSlice(0, 99)};
- CreateParallelJob(99, 1, slices, 3, 1, 10);
- BuildParallelRequests();
- EXPECT_EQ(0u, job_->workers().size());
-
- DestroyParallelJob();
-}
-
-// Test that parallel request is not created until download file is initialized.
-TEST_F(ParallelDownloadJobTest, ParallelRequestNotCreatedUntilFileInitialized) {
- auto save_info = std::make_unique<download::DownloadSaveInfo>();
- StrictMock<MockByteStreamReader>* input_stream =
- new StrictMock<MockByteStreamReader>();
- auto observer =
- std::make_unique<StrictMock<MockDownloadDestinationObserver>>();
- base::WeakPtrFactory<DownloadDestinationObserver> observer_factory(
- observer.get());
- auto download_file = std::make_unique<DownloadFileImpl>(
- std::move(save_info), base::FilePath(),
- std::make_unique<DownloadManager::InputStream>(
- std::unique_ptr<ByteStreamReader>(input_stream)),
- download::DownloadItem::kInvalidId, observer_factory.GetWeakPtr());
- CreateParallelJob(0, 100, download::DownloadItem::ReceivedSlices(), 2, 0, 0);
- job_->Start(download_file.get(),
- base::Bind(&ParallelDownloadJobTest::OnFileInitialized,
- base::Unretained(this)),
- download::DownloadItem::ReceivedSlices());
- EXPECT_FALSE(file_initialized_);
- EXPECT_EQ(0u, job_->workers().size());
- EXPECT_CALL(*input_stream, RegisterCallback(_));
- EXPECT_CALL(*input_stream, Read(_, _));
- EXPECT_CALL(*(observer.get()), DestinationUpdate(_, _, _));
- task_environment_.RunUntilIdle();
- EXPECT_TRUE(file_initialized_);
- EXPECT_EQ(1u, job_->workers().size());
- DestroyParallelJob();
-
- // The download file lives on the download sequence, and must
- // be deleted there.
- download::GetDownloadTaskRunner()->DeleteSoon(FROM_HERE,
- std::move(download_file));
- task_environment_.RunUntilIdle();
-}
-
-// Interruption from IO thread after the file initialized and before building
-// the parallel requests, should correctly stop the download.
-TEST_F(ParallelDownloadJobTest, InterruptOnStartup) {
- download::DownloadItem::ReceivedSlices slices = {
- download::DownloadItem::ReceivedSlice(0, 99)};
- CreateParallelJob(99, 1, slices, 3, 1, 10);
-
- // Start to build the requests without any error.
- base::MockCallback<DownloadFile::InitializeCallback> callback;
- EXPECT_CALL(callback, Run(_)).Times(1);
- job_->MakeFileInitialized(callback.Get(),
- download::DOWNLOAD_INTERRUPT_REASON_NONE);
-
- // Simulate and inject an error from IO thread after file initialized.
- EXPECT_CALL(*download_item_.get(), GetState())
- .WillRepeatedly(
- Return(download::DownloadItem::DownloadState::INTERRUPTED));
-
- // Because of the error, no parallel requests are built.
- task_environment_.RunUntilIdle();
- EXPECT_EQ(0u, job_->workers().size());
-
- DestroyParallelJob();
-}
-
-} // namespace content
diff --git a/chromium/content/browser/download/parallel_download_utils.cc b/chromium/content/browser/download/parallel_download_utils.cc
deleted file mode 100644
index 1204be29196..00000000000
--- a/chromium/content/browser/download/parallel_download_utils.cc
+++ /dev/null
@@ -1,225 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/download/parallel_download_utils.h"
-
-#include "base/metrics/field_trial_params.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/time/time.h"
-#include "components/download/public/common/download_save_info.h"
-#include "content/public/common/content_features.h"
-
-namespace content {
-
-namespace {
-
-// Default value for |kMinSliceSizeFinchKey|, when no parameter is specified.
-const int64_t kMinSliceSizeParallelDownload = 1365333;
-
-// Default value for |kParallelRequestCountFinchKey|, when no parameter is
-// specified.
-const int kParallelRequestCount = 3;
-
-// The default remaining download time in seconds required for parallel request
-// creation.
-const int kDefaultRemainingTimeInSeconds = 2;
-
-// TODO(qinmin): replace this with a comparator operator in
-// download::DownloadItem::ReceivedSlice.
-bool compareReceivedSlices(const download::DownloadItem::ReceivedSlice& lhs,
- const download::DownloadItem::ReceivedSlice& rhs) {
- return lhs.offset < rhs.offset;
-}
-
-} // namespace
-
-std::vector<download::DownloadItem::ReceivedSlice>
-FindSlicesForRemainingContent(int64_t current_offset,
- int64_t total_length,
- int request_count,
- int64_t min_slice_size) {
- std::vector<download::DownloadItem::ReceivedSlice> new_slices;
-
- if (request_count > 0) {
- int64_t slice_size =
- std::max<int64_t>(total_length / request_count, min_slice_size);
- slice_size = slice_size > 0 ? slice_size : 1;
- for (int i = 0, num_requests = total_length / slice_size;
- i < num_requests - 1; ++i) {
- new_slices.emplace_back(current_offset, slice_size);
- current_offset += slice_size;
- }
- }
-
- // No strong assumption that content length header is correct. So the last
- // slice is always half open, which sends range request like "Range:50-".
- new_slices.emplace_back(current_offset,
- download::DownloadSaveInfo::kLengthFullContent);
- return new_slices;
-}
-
-std::vector<download::DownloadItem::ReceivedSlice> FindSlicesToDownload(
- const std::vector<download::DownloadItem::ReceivedSlice>& received_slices) {
- std::vector<download::DownloadItem::ReceivedSlice> result;
- if (received_slices.empty()) {
- result.emplace_back(0, download::DownloadSaveInfo::kLengthFullContent);
- return result;
- }
-
- std::vector<download::DownloadItem::ReceivedSlice>::const_iterator iter =
- received_slices.begin();
- DCHECK_GE(iter->offset, 0);
- if (iter->offset != 0)
- result.emplace_back(0, iter->offset);
-
- while (true) {
- int64_t offset = iter->offset + iter->received_bytes;
- std::vector<download::DownloadItem::ReceivedSlice>::const_iterator next =
- std::next(iter);
- if (next == received_slices.end()) {
- result.emplace_back(offset,
- download::DownloadSaveInfo::kLengthFullContent);
- break;
- }
-
- DCHECK_GE(next->offset, offset);
- if (next->offset > offset)
- result.emplace_back(offset, next->offset - offset);
- iter = next;
- }
- return result;
-}
-
-size_t AddOrMergeReceivedSliceIntoSortedArray(
- const download::DownloadItem::ReceivedSlice& new_slice,
- std::vector<download::DownloadItem::ReceivedSlice>& received_slices) {
- std::vector<download::DownloadItem::ReceivedSlice>::iterator it =
- std::upper_bound(received_slices.begin(), received_slices.end(),
- new_slice, compareReceivedSlices);
- if (it != received_slices.begin()) {
- std::vector<download::DownloadItem::ReceivedSlice>::iterator prev =
- std::prev(it);
- if (prev->offset + prev->received_bytes == new_slice.offset) {
- prev->received_bytes += new_slice.received_bytes;
- return static_cast<size_t>(std::distance(received_slices.begin(), prev));
- }
- }
-
- it = received_slices.emplace(it, new_slice);
- return static_cast<size_t>(std::distance(received_slices.begin(), it));
-}
-
-bool CanRecoverFromError(
- const DownloadFileImpl::SourceStream* error_stream,
- const DownloadFileImpl::SourceStream* preceding_neighbor) {
- DCHECK(error_stream->offset() >= preceding_neighbor->offset())
- << "Preceding"
- "stream's offset should be smaller than the error stream.";
- DCHECK_GE(error_stream->length(), 0);
-
- if (preceding_neighbor->is_finished()) {
- // Check if the preceding stream fetched to the end of the file without
- // error. The error stream doesn't need to download anything.
- if (preceding_neighbor->length() ==
- download::DownloadSaveInfo::kLengthFullContent &&
- preceding_neighbor->GetCompletionStatus() ==
- download::DOWNLOAD_INTERRUPT_REASON_NONE) {
- return true;
- }
-
- // Check if finished preceding stream has already downloaded all data for
- // the error stream.
- if (error_stream->length() > 0) {
- return error_stream->offset() + error_stream->length() <=
- preceding_neighbor->offset() + preceding_neighbor->bytes_written();
- }
-
- return false;
- }
-
- // If preceding stream is half open, and still working, we can recover.
- if (preceding_neighbor->length() ==
- download::DownloadSaveInfo::kLengthFullContent) {
- return true;
- }
-
- // Check if unfinished preceding stream is able to download data for error
- // stream in the future only when preceding neighbor and error stream both
- // have an upper bound.
- if (error_stream->length() > 0 && preceding_neighbor->length() > 0) {
- return error_stream->offset() + error_stream->length() <=
- preceding_neighbor->offset() + preceding_neighbor->length();
- }
-
- return false;
-}
-
-int64_t GetMinSliceSizeConfig() {
- std::string finch_value = base::GetFieldTrialParamValueByFeature(
- features::kParallelDownloading, kMinSliceSizeFinchKey);
- int64_t result;
- return base::StringToInt64(finch_value, &result)
- ? result
- : kMinSliceSizeParallelDownload;
-}
-
-int GetParallelRequestCountConfig() {
- std::string finch_value = base::GetFieldTrialParamValueByFeature(
- features::kParallelDownloading, kParallelRequestCountFinchKey);
- int result;
- return base::StringToInt(finch_value, &result) ? result
- : kParallelRequestCount;
-}
-
-base::TimeDelta GetParallelRequestDelayConfig() {
- std::string finch_value = base::GetFieldTrialParamValueByFeature(
- features::kParallelDownloading, kParallelRequestDelayFinchKey);
- int64_t time_ms = 0;
- return base::StringToInt64(finch_value, &time_ms)
- ? base::TimeDelta::FromMilliseconds(time_ms)
- : base::TimeDelta::FromMilliseconds(0);
-}
-
-base::TimeDelta GetParallelRequestRemainingTimeConfig() {
- std::string finch_value = base::GetFieldTrialParamValueByFeature(
- features::kParallelDownloading, kParallelRequestRemainingTimeFinchKey);
- int time_in_seconds = 0;
- return base::StringToInt(finch_value, &time_in_seconds)
- ? base::TimeDelta::FromSeconds(time_in_seconds)
- : base::TimeDelta::FromSeconds(kDefaultRemainingTimeInSeconds);
-}
-
-void DebugSlicesInfo(const download::DownloadItem::ReceivedSlices& slices) {
- DVLOG(1) << "Received slices size : " << slices.size();
- for (const auto& it : slices) {
- DVLOG(1) << "Slice offset = " << it.offset
- << " , received_bytes = " << it.received_bytes
- << " , finished = " << it.finished;
- }
-}
-
-int64_t GetMaxContiguousDataBlockSizeFromBeginning(
- const download::DownloadItem::ReceivedSlices& slices) {
- std::vector<download::DownloadItem::ReceivedSlice>::const_iterator iter =
- slices.begin();
-
- int64_t size = 0;
- while (iter != slices.end() && iter->offset == size) {
- size += iter->received_bytes;
- iter++;
- }
- return size;
-}
-
-bool IsParallelDownloadEnabled() {
- bool feature_enabled =
- base::FeatureList::IsEnabled(features::kParallelDownloading);
- // Disabled when |kEnableParallelDownloadFinchKey| Finch config is set to
- // false.
- bool enabled_parameter = GetFieldTrialParamByFeatureAsBool(
- features::kParallelDownloading, kEnableParallelDownloadFinchKey, true);
- return feature_enabled && enabled_parameter;
-}
-
-} // namespace content
diff --git a/chromium/content/browser/download/parallel_download_utils.h b/chromium/content/browser/download/parallel_download_utils.h
deleted file mode 100644
index 63b36a27cde..00000000000
--- a/chromium/content/browser/download/parallel_download_utils.h
+++ /dev/null
@@ -1,102 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_DOWNLOAD_PARALLEL_DOWNLOAD_UTILS_H_
-#define CONTENT_BROWSER_DOWNLOAD_PARALLEL_DOWNLOAD_UTILS_H_
-
-#include <vector>
-
-#include "components/download/public/common/download_create_info.h"
-#include "components/download/public/common/download_item.h"
-#include "content/browser/download/download_file_impl.h"
-#include "content/common/content_export.h"
-
-namespace content {
-
-// Finch parameter key value to enable parallel download. Used in enabled
-// experiment group that needs other parameters, such as min_slice_size, but
-// don't want to actually do parallel download.
-constexpr char kEnableParallelDownloadFinchKey[] = "enable_parallel_download";
-
-// Finch parameter key value for minimum slice size in bytes to use parallel
-// download.
-constexpr char kMinSliceSizeFinchKey[] = "min_slice_size";
-
-// Finch parameter key value for number of parallel requests in a parallel
-// download, including the original request.
-constexpr char kParallelRequestCountFinchKey[] = "request_count";
-
-// Finch parameter key value for the delay time in milliseconds to send
-// parallel requests after response of the original request is handled.
-constexpr char kParallelRequestDelayFinchKey[] = "parallel_request_delay";
-
-// Finch parameter key value for the remaining time in seconds that is required
-// to send parallel requests.
-constexpr char kParallelRequestRemainingTimeFinchKey[] =
- "parallel_request_remaining_time";
-
-// Chunks the content that starts from |current_offset|, into at most
-// std::max(|request_count|, 1) smaller slices.
-// Each slice contains at least |min_slice_size| bytes unless |total_length|
-// is less than |min_slice_size|.
-// The last slice is half opened.
-CONTENT_EXPORT std::vector<download::DownloadItem::ReceivedSlice>
-FindSlicesForRemainingContent(int64_t current_offset,
- int64_t total_length,
- int request_count,
- int64_t min_slice_size);
-
-// Given an array of slices that are received, returns an array of slices to
-// download. |received_slices| must be ordered by offsets.
-CONTENT_EXPORT std::vector<download::DownloadItem::ReceivedSlice>
-FindSlicesToDownload(
- const std::vector<download::DownloadItem::ReceivedSlice>& received_slices);
-
-// Adds or merges a new received slice into a vector of sorted slices. If the
-// slice can be merged with the slice preceding it, merge the 2 slices.
-// Otherwise, insert the slice and keep the vector sorted. Returns the index
-// of the newly updated slice.
-CONTENT_EXPORT size_t AddOrMergeReceivedSliceIntoSortedArray(
- const download::DownloadItem::ReceivedSlice& new_slice,
- std::vector<download::DownloadItem::ReceivedSlice>& received_slices);
-
-// Returns if a preceding stream can still download the part of content that
-// was arranged to |error_stream|.
-CONTENT_EXPORT bool CanRecoverFromError(
- const DownloadFileImpl::SourceStream* error_stream,
- const DownloadFileImpl::SourceStream* preceding_neighbor);
-
-// Finch configuration utilities.
-//
-// Get the minimum slice size to use parallel download from finch configuration.
-// A slice won't be further chunked into smaller slices if the size is less
-// than the minimum size.
-CONTENT_EXPORT int64_t GetMinSliceSizeConfig();
-
-// Get the request count for parallel download from finch configuration.
-CONTENT_EXPORT int GetParallelRequestCountConfig();
-
-// Get the time delay to send parallel requests after the response of original
-// request is handled.
-CONTENT_EXPORT base::TimeDelta GetParallelRequestDelayConfig();
-
-// Get the required remaining time before creating parallel requests.
-CONTENT_EXPORT base::TimeDelta GetParallelRequestRemainingTimeConfig();
-
-// Print the states of received slices for debugging.
-CONTENT_EXPORT void DebugSlicesInfo(
- const download::DownloadItem::ReceivedSlices& slices);
-
-// Given an ordered array of slices, get the maximum size of a contiguous data
-// block that starts from offset 0. If the first slice doesn't start from offset
-// 0, return 0.
-CONTENT_EXPORT int64_t GetMaxContiguousDataBlockSizeFromBeginning(
- const download::DownloadItem::ReceivedSlices& slices);
-
-// Returns whether parallel download is enabled.
-CONTENT_EXPORT bool IsParallelDownloadEnabled();
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_DOWNLOAD_PARALLEL_DOWNLOAD_UTILS_H_
diff --git a/chromium/content/browser/download/parallel_download_utils_unittest.cc b/chromium/content/browser/download/parallel_download_utils_unittest.cc
deleted file mode 100644
index 834468764a7..00000000000
--- a/chromium/content/browser/download/parallel_download_utils_unittest.cc
+++ /dev/null
@@ -1,400 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/download/parallel_download_utils.h"
-
-#include <map>
-#include <memory>
-
-#include "base/strings/string_number_conversions.h"
-#include "base/test/scoped_feature_list.h"
-#include "components/download/public/common/download_save_info.h"
-#include "content/browser/byte_stream.h"
-#include "content/public/browser/download_manager.h"
-#include "content/public/common/content_features.h"
-#include "testing/gmock/include/gmock/gmock.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace content {
-
-namespace {
-
-const int kErrorStreamOffset = 100;
-
-class MockByteStreamReader : public ByteStreamReader {
- public:
- MockByteStreamReader() {}
- ~MockByteStreamReader() override {}
-
- // ByteStream functions
- MOCK_METHOD2(Read,
- ByteStreamReader::StreamState(scoped_refptr<net::IOBuffer>*,
- size_t*));
- MOCK_CONST_METHOD0(GetStatus, int());
- MOCK_METHOD1(RegisterCallback, void(const base::Closure&));
-};
-
-// Creates a source stream to test.
-std::unique_ptr<DownloadFileImpl::SourceStream> CreateSourceStream(
- int64_t offset,
- int64_t length) {
- auto input_stream = std::make_unique<DownloadManager::InputStream>(
- std::make_unique<MockByteStreamReader>());
- return std::make_unique<DownloadFileImpl::SourceStream>(
- offset, length, std::move(input_stream));
-}
-
-} // namespace
-
-class ParallelDownloadUtilsTest : public testing::Test {};
-
-class ParallelDownloadUtilsRecoverErrorTest
- : public ::testing::TestWithParam<int64_t> {};
-
-TEST_F(ParallelDownloadUtilsTest, FindSlicesToDownload) {
- std::vector<download::DownloadItem::ReceivedSlice> downloaded_slices;
- std::vector<download::DownloadItem::ReceivedSlice> slices_to_download =
- FindSlicesToDownload(downloaded_slices);
- EXPECT_EQ(1u, slices_to_download.size());
- EXPECT_EQ(0, slices_to_download[0].offset);
- EXPECT_EQ(download::DownloadSaveInfo::kLengthFullContent,
- slices_to_download[0].received_bytes);
-
- downloaded_slices.emplace_back(0, 500);
- slices_to_download = FindSlicesToDownload(downloaded_slices);
- EXPECT_EQ(1u, slices_to_download.size());
- EXPECT_EQ(500, slices_to_download[0].offset);
- EXPECT_EQ(download::DownloadSaveInfo::kLengthFullContent,
- slices_to_download[0].received_bytes);
-
- // Create a gap between slices.
- downloaded_slices.emplace_back(1000, 500);
- slices_to_download = FindSlicesToDownload(downloaded_slices);
- EXPECT_EQ(2u, slices_to_download.size());
- EXPECT_EQ(500, slices_to_download[0].offset);
- EXPECT_EQ(500, slices_to_download[0].received_bytes);
- EXPECT_EQ(1500, slices_to_download[1].offset);
- EXPECT_EQ(download::DownloadSaveInfo::kLengthFullContent,
- slices_to_download[1].received_bytes);
-
- // Fill the gap.
- downloaded_slices.emplace(
- downloaded_slices.begin() + 1, slices_to_download[0]);
- slices_to_download = FindSlicesToDownload(downloaded_slices);
- EXPECT_EQ(1u, slices_to_download.size());
- EXPECT_EQ(1500, slices_to_download[0].offset);
- EXPECT_EQ(download::DownloadSaveInfo::kLengthFullContent,
- slices_to_download[0].received_bytes);
-
- // Create a new gap at the beginning.
- downloaded_slices.erase(downloaded_slices.begin());
- slices_to_download = FindSlicesToDownload(downloaded_slices);
- EXPECT_EQ(2u, slices_to_download.size());
- EXPECT_EQ(0, slices_to_download[0].offset);
- EXPECT_EQ(500, slices_to_download[0].received_bytes);
- EXPECT_EQ(1500, slices_to_download[1].offset);
- EXPECT_EQ(download::DownloadSaveInfo::kLengthFullContent,
- slices_to_download[1].received_bytes);
-}
-
-TEST_F(ParallelDownloadUtilsTest, AddOrMergeReceivedSliceIntoSortedArray) {
- std::vector<download::DownloadItem::ReceivedSlice> slices;
- download::DownloadItem::ReceivedSlice slice1(500, 500);
- EXPECT_EQ(0u, AddOrMergeReceivedSliceIntoSortedArray(slice1, slices));
- EXPECT_EQ(1u, slices.size());
- EXPECT_EQ(slice1, slices[0]);
-
- // Adding a slice that can be merged with existing slice.
- download::DownloadItem::ReceivedSlice slice2(1000, 400);
- EXPECT_EQ(0u, AddOrMergeReceivedSliceIntoSortedArray(slice2, slices));
- EXPECT_EQ(1u, slices.size());
- EXPECT_EQ(500, slices[0].offset);
- EXPECT_EQ(900, slices[0].received_bytes);
-
- download::DownloadItem::ReceivedSlice slice3(0, 50);
- EXPECT_EQ(0u, AddOrMergeReceivedSliceIntoSortedArray(slice3, slices));
- EXPECT_EQ(2u, slices.size());
- EXPECT_EQ(slice3, slices[0]);
-
- download::DownloadItem::ReceivedSlice slice4(100, 50);
- EXPECT_EQ(1u, AddOrMergeReceivedSliceIntoSortedArray(slice4, slices));
- EXPECT_EQ(3u, slices.size());
- EXPECT_EQ(slice3, slices[0]);
- EXPECT_EQ(slice4, slices[1]);
-
- // A new slice can only merge with an existing slice earlier in the file, not
- // later in the file.
- download::DownloadItem::ReceivedSlice slice5(50, 50);
- EXPECT_EQ(0u, AddOrMergeReceivedSliceIntoSortedArray(slice5, slices));
- EXPECT_EQ(3u, slices.size());
- EXPECT_EQ(0, slices[0].offset);
- EXPECT_EQ(100, slices[0].received_bytes);
- EXPECT_EQ(slice4, slices[1]);
-}
-
-// Ensure the minimum slice size is correctly applied.
-TEST_F(ParallelDownloadUtilsTest, FindSlicesForRemainingContentMinSliceSize) {
- // Minimum slice size is smaller than total length, only one slice returned.
- download::DownloadItem::ReceivedSlices slices =
- FindSlicesForRemainingContent(0, 100, 3, 150);
- EXPECT_EQ(1u, slices.size());
- EXPECT_EQ(0, slices[0].offset);
- EXPECT_EQ(0, slices[0].received_bytes);
-
- // Request count is large, the minimum slice size should limit the number of
- // slices returned.
- slices = FindSlicesForRemainingContent(0, 100, 33, 50);
- EXPECT_EQ(2u, slices.size());
- EXPECT_EQ(0, slices[0].offset);
- EXPECT_EQ(50, slices[0].received_bytes);
- EXPECT_EQ(50, slices[1].offset);
- EXPECT_EQ(0, slices[1].received_bytes);
-
- // Can chunk 2 slices under minimum slice size, but request count is only 1,
- // request count should win.
- slices = FindSlicesForRemainingContent(0, 100, 1, 50);
- EXPECT_EQ(1u, slices.size());
- EXPECT_EQ(0, slices[0].offset);
- EXPECT_EQ(0, slices[0].received_bytes);
-
- // A total 100 bytes data and a 51 bytes minimum slice size, only one slice is
- // returned.
- slices = FindSlicesForRemainingContent(0, 100, 3, 51);
- EXPECT_EQ(1u, slices.size());
- EXPECT_EQ(0, slices[0].offset);
- EXPECT_EQ(0, slices[0].received_bytes);
-
- // Extreme case where size is smaller than request number.
- slices = FindSlicesForRemainingContent(0, 1, 3, 1);
- EXPECT_EQ(1u, slices.size());
- EXPECT_EQ(download::DownloadItem::ReceivedSlice(0, 0), slices[0]);
-
- // Normal case.
- slices = FindSlicesForRemainingContent(0, 100, 3, 5);
- EXPECT_EQ(3u, slices.size());
- EXPECT_EQ(download::DownloadItem::ReceivedSlice(0, 33), slices[0]);
- EXPECT_EQ(download::DownloadItem::ReceivedSlice(33, 33), slices[1]);
- EXPECT_EQ(download::DownloadItem::ReceivedSlice(66, 0), slices[2]);
-}
-
-TEST_F(ParallelDownloadUtilsTest, GetMaxContiguousDataBlockSizeFromBeginning) {
- std::vector<download::DownloadItem::ReceivedSlice> slices;
- slices.emplace_back(500, 500);
- EXPECT_EQ(0, GetMaxContiguousDataBlockSizeFromBeginning(slices));
-
- download::DownloadItem::ReceivedSlice slice1(0, 200);
- AddOrMergeReceivedSliceIntoSortedArray(slice1, slices);
- EXPECT_EQ(200, GetMaxContiguousDataBlockSizeFromBeginning(slices));
-
- download::DownloadItem::ReceivedSlice slice2(200, 300);
- AddOrMergeReceivedSliceIntoSortedArray(slice2, slices);
- EXPECT_EQ(1000, GetMaxContiguousDataBlockSizeFromBeginning(slices));
-}
-
-// Test to verify Finch parameters for enabled experiment group is read
-// correctly.
-TEST_F(ParallelDownloadUtilsTest, FinchConfigEnabled) {
- base::test::ScopedFeatureList feature_list;
- std::map<std::string, std::string> params = {
- {content::kMinSliceSizeFinchKey, "1234"},
- {content::kParallelRequestCountFinchKey, "6"},
- {content::kParallelRequestDelayFinchKey, "2000"},
- {content::kParallelRequestRemainingTimeFinchKey, "3"}};
- feature_list.InitAndEnableFeatureWithParameters(
- features::kParallelDownloading, params);
- EXPECT_TRUE(IsParallelDownloadEnabled());
- EXPECT_EQ(GetMinSliceSizeConfig(), 1234);
- EXPECT_EQ(GetParallelRequestCountConfig(), 6);
- EXPECT_EQ(GetParallelRequestDelayConfig(), base::TimeDelta::FromSeconds(2));
- EXPECT_EQ(GetParallelRequestRemainingTimeConfig(),
- base::TimeDelta::FromSeconds(3));
-}
-
-// Test to verify the disable experiment group will actually disable the
-// feature.
-TEST_F(ParallelDownloadUtilsTest, FinchConfigDisabled) {
- base::test::ScopedFeatureList feature_list;
- feature_list.InitAndDisableFeature(features::kParallelDownloading);
- EXPECT_FALSE(IsParallelDownloadEnabled());
-}
-
-// Test to verify that the Finch parameter |enable_parallel_download| works
-// correctly.
-TEST_F(ParallelDownloadUtilsTest, FinchConfigDisabledWithParameter) {
- {
- base::test::ScopedFeatureList feature_list;
- std::map<std::string, std::string> params = {
- {content::kMinSliceSizeFinchKey, "4321"},
- {content::kEnableParallelDownloadFinchKey, "false"}};
- feature_list.InitAndEnableFeatureWithParameters(
- features::kParallelDownloading, params);
- // Use |enable_parallel_download| to disable parallel download in enabled
- // experiment group.
- EXPECT_FALSE(IsParallelDownloadEnabled());
- EXPECT_EQ(GetMinSliceSizeConfig(), 4321);
- }
- {
- base::test::ScopedFeatureList feature_list;
- std::map<std::string, std::string> params = {
- {content::kMinSliceSizeFinchKey, "4321"},
- {content::kEnableParallelDownloadFinchKey, "true"}};
- feature_list.InitAndEnableFeatureWithParameters(
- features::kParallelDownloading, params);
- // Disable only if |enable_parallel_download| sets to false.
- EXPECT_TRUE(IsParallelDownloadEnabled());
- EXPECT_EQ(GetMinSliceSizeConfig(), 4321);
- }
- {
- base::test::ScopedFeatureList feature_list;
- std::map<std::string, std::string> params = {
- {content::kMinSliceSizeFinchKey, "4321"}};
- feature_list.InitAndEnableFeatureWithParameters(
- features::kParallelDownloading, params);
- // Empty |enable_parallel_download| in an enabled experiment group will have
- // no impact.
- EXPECT_TRUE(IsParallelDownloadEnabled());
- EXPECT_EQ(GetMinSliceSizeConfig(), 4321);
- }
-}
-
-// Verify if a preceding stream can recover the download for half open error
-// stream(the current last stream).
-TEST_P(ParallelDownloadUtilsRecoverErrorTest,
- RecoverErrorForHalfOpenErrorStream) {
- // Create a stream that will work on byte range "100-".
- const int kErrorStreamOffset = 100;
- auto error_stream = CreateSourceStream(
- kErrorStreamOffset, download::DownloadSaveInfo::kLengthFullContent);
- error_stream->set_finished(true);
-
- // Get starting offset of preceding stream.
- int64_t preceding_offset = GetParam();
- EXPECT_LT(preceding_offset, kErrorStreamOffset);
- auto preceding_stream = CreateSourceStream(
- preceding_offset, download::DownloadSaveInfo::kLengthFullContent);
- EXPECT_FALSE(preceding_stream->is_finished());
- EXPECT_EQ(0u, preceding_stream->bytes_written());
- EXPECT_TRUE(CanRecoverFromError(error_stream.get(), preceding_stream.get()));
-
- // Half open finished preceding stream with 0 bytes written, if there is no
- // error, the download should be finished.
- preceding_stream->set_finished(true);
- EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE,
- preceding_stream->GetCompletionStatus());
- EXPECT_TRUE(CanRecoverFromError(error_stream.get(), preceding_stream.get()));
-
- // Half open finished preceding stream with error, should be treated as
- // failed.
- preceding_stream->OnResponseCompleted(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE);
- EXPECT_FALSE(CanRecoverFromError(error_stream.get(), preceding_stream.get()));
-
- // Even if it has written some data.
- preceding_stream->OnWriteBytesToDisk(1000u);
- EXPECT_FALSE(CanRecoverFromError(error_stream.get(), preceding_stream.get()));
-
- // Now capped the length of preceding stream with different values.
- preceding_stream = CreateSourceStream(preceding_offset,
- kErrorStreamOffset - preceding_offset);
- // Since preceding stream can't reach the first byte of the error stream, it
- // will fail.
- preceding_stream->set_finished(false);
- EXPECT_FALSE(CanRecoverFromError(error_stream.get(), preceding_stream.get()));
- preceding_stream->set_finished(true);
- preceding_stream->OnWriteBytesToDisk(kErrorStreamOffset - preceding_offset);
- EXPECT_FALSE(CanRecoverFromError(error_stream.get(), preceding_stream.get()));
-
- // Inject an error results in failure, even if data written exceeds the first
- // byte of error stream.
- preceding_stream->OnResponseCompleted(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE);
- preceding_stream->OnWriteBytesToDisk(1000u);
- EXPECT_FALSE(CanRecoverFromError(error_stream.get(), preceding_stream.get()));
-
- // Make preceding stream can reach the first byte of error stream.
- preceding_stream = CreateSourceStream(
- preceding_offset, kErrorStreamOffset - preceding_offset + 1);
- // Since the error stream is half opened, no matter what it should fail.
- preceding_stream->set_finished(false);
- EXPECT_FALSE(CanRecoverFromError(error_stream.get(), preceding_stream.get()));
- preceding_stream->set_finished(true);
- preceding_stream->OnWriteBytesToDisk(kErrorStreamOffset - preceding_offset);
- EXPECT_FALSE(CanRecoverFromError(error_stream.get(), preceding_stream.get()));
- preceding_stream->OnWriteBytesToDisk(1);
- EXPECT_FALSE(CanRecoverFromError(error_stream.get(), preceding_stream.get()));
-
- // Preceding stream that never download data won't recover the error stream.
- preceding_stream = CreateSourceStream(preceding_offset, -1);
- EXPECT_FALSE(CanRecoverFromError(error_stream.get(), preceding_stream.get()));
-}
-
-// Verify recovery for length capped error stream.
-// Since the error stream length is capped, assume the previous stream length
-// is also capped or the previous stream is finished due to error like http
-// 404.
-TEST_P(ParallelDownloadUtilsRecoverErrorTest,
- RecoverErrorForLengthCappedErrorStream) {
- // Create a stream that will work on byte range "100-150".
- const int kErrorStreamLength = 50;
- auto error_stream =
- CreateSourceStream(kErrorStreamOffset, kErrorStreamLength);
- error_stream->set_finished(true);
-
- // Get starting offset of preceding stream.
- const int64_t preceding_offset = GetParam();
- EXPECT_LT(preceding_offset, kErrorStreamOffset);
-
- // Create preceding stream capped before starting offset of error stream.
- auto preceding_stream = CreateSourceStream(
- preceding_offset, kErrorStreamOffset - preceding_offset);
- EXPECT_FALSE(preceding_stream->is_finished());
- EXPECT_EQ(0u, preceding_stream->bytes_written());
-
- // Since the preceding stream can never reach the starting offset, for an
- // unfinished stream, we rely on length instead of bytes written.
- EXPECT_FALSE(CanRecoverFromError(error_stream.get(), preceding_stream.get()));
- preceding_stream->OnWriteBytesToDisk(kErrorStreamOffset - preceding_offset);
- EXPECT_FALSE(CanRecoverFromError(error_stream.get(), preceding_stream.get()));
- preceding_stream->OnWriteBytesToDisk(kErrorStreamLength - 1);
- EXPECT_FALSE(CanRecoverFromError(error_stream.get(), preceding_stream.get()));
- preceding_stream->OnWriteBytesToDisk(1);
-
- // Create preceding stream that can reach the upper bound of error stream.
- // Since it's unfinished, it potentially can take over error stream's work
- // even if no data is written.
- preceding_stream = CreateSourceStream(
- preceding_offset,
- kErrorStreamOffset - preceding_offset + kErrorStreamLength);
- EXPECT_FALSE(preceding_stream->is_finished());
- EXPECT_EQ(0u, preceding_stream->bytes_written());
- EXPECT_TRUE(CanRecoverFromError(error_stream.get(), preceding_stream.get()));
-
- // Finished preceding stream only checks data written.
- preceding_stream = CreateSourceStream(preceding_offset, 1);
- preceding_stream->set_finished(true);
- preceding_stream->OnWriteBytesToDisk(kErrorStreamOffset - preceding_offset);
- EXPECT_FALSE(CanRecoverFromError(error_stream.get(), preceding_stream.get()));
- preceding_stream->OnWriteBytesToDisk(kErrorStreamLength - 1);
- EXPECT_FALSE(CanRecoverFromError(error_stream.get(), preceding_stream.get()));
- preceding_stream->OnWriteBytesToDisk(1);
- EXPECT_TRUE(CanRecoverFromError(error_stream.get(), preceding_stream.get()));
-
- // Even if inject an error, since data written has cover the upper bound of
- // the error stream, it should succeed.
- preceding_stream->OnResponseCompleted(
- download::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE);
- EXPECT_TRUE(CanRecoverFromError(error_stream.get(), preceding_stream.get()));
-
- // Preceding stream that never download data won't recover the error stream.
- preceding_stream = CreateSourceStream(preceding_offset, -1);
- EXPECT_FALSE(CanRecoverFromError(error_stream.get(), preceding_stream.get()));
-}
-
-// The testing value specified offset for preceding stream. The error stream
-// offset is fixed value.
-INSTANTIATE_TEST_CASE_P(ParallelDownloadUtilsTestSuite,
- ParallelDownloadUtilsRecoverErrorTest,
- ::testing::Values(0, 20, 80));
-
-} // namespace content
diff --git a/chromium/content/browser/download/resource_downloader.cc b/chromium/content/browser/download/resource_downloader.cc
deleted file mode 100644
index e3a3c28ac1d..00000000000
--- a/chromium/content/browser/download/resource_downloader.cc
+++ /dev/null
@@ -1,215 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/download/resource_downloader.h"
-
-#include <memory>
-
-#include "base/strings/utf_string_conversions.h"
-#include "content/browser/blob_storage/blob_url_loader_factory.h"
-#include "content/browser/download/download_utils.h"
-
-#include "content/public/browser/web_contents.h"
-
-namespace network {
-struct ResourceResponseHead;
-}
-
-namespace content {
-
-// This object monitors the URLLoaderCompletionStatus change when
-// ResourceDownloader is asking |delegate_| whether download can proceed.
-class URLLoaderStatusMonitor : public network::mojom::URLLoaderClient {
- public:
- using URLLoaderStatusChangeCallback =
- base::OnceCallback<void(const network::URLLoaderCompletionStatus&)>;
- explicit URLLoaderStatusMonitor(URLLoaderStatusChangeCallback callback);
- ~URLLoaderStatusMonitor() override = default;
-
- // network::mojom::URLLoaderClient
- void OnReceiveResponse(
- const network::ResourceResponseHead& head,
- const base::Optional<net::SSLInfo>& ssl_info,
- network::mojom::DownloadedTempFilePtr downloaded_file) override {}
- void OnReceiveRedirect(const net::RedirectInfo& redirect_info,
- const network::ResourceResponseHead& head) override {}
- void OnDataDownloaded(int64_t data_length, int64_t encoded_length) override {}
- void OnUploadProgress(int64_t current_position,
- int64_t total_size,
- OnUploadProgressCallback callback) override {}
- void OnReceiveCachedMetadata(const std::vector<uint8_t>& data) override {}
- void OnTransferSizeUpdated(int32_t transfer_size_diff) override {}
- void OnStartLoadingResponseBody(
- mojo::ScopedDataPipeConsumerHandle body) override {}
- void OnComplete(const network::URLLoaderCompletionStatus& status) override;
-
- private:
- URLLoaderStatusChangeCallback callback_;
- DISALLOW_COPY_AND_ASSIGN(URLLoaderStatusMonitor);
-};
-
-URLLoaderStatusMonitor::URLLoaderStatusMonitor(
- URLLoaderStatusChangeCallback callback)
- : callback_(std::move(callback)) {}
-
-void URLLoaderStatusMonitor::OnComplete(
- const network::URLLoaderCompletionStatus& status) {
- std::move(callback_).Run(status);
-}
-
-// static
-std::unique_ptr<ResourceDownloader> ResourceDownloader::BeginDownload(
- base::WeakPtr<UrlDownloadHandler::Delegate> delegate,
- std::unique_ptr<download::DownloadUrlParameters> params,
- std::unique_ptr<network::ResourceRequest> request,
- network::mojom::URLLoaderFactory* url_loader_factory,
- const GURL& site_url,
- const GURL& tab_url,
- const GURL& tab_referrer_url,
- uint32_t download_id,
- bool is_parallel_request) {
- auto downloader = std::make_unique<ResourceDownloader>(
- delegate, std::move(request), params->render_process_host_id(),
- params->render_frame_host_routing_id(), site_url, tab_url,
- tab_referrer_url, download_id);
-
- downloader->Start(url_loader_factory, std::move(params), is_parallel_request);
- return downloader;
-}
-
-// static
-std::unique_ptr<ResourceDownloader>
-ResourceDownloader::InterceptNavigationResponse(
- base::WeakPtr<UrlDownloadHandler::Delegate> delegate,
- std::unique_ptr<network::ResourceRequest> resource_request,
- int render_process_id,
- int render_frame_id,
- std::vector<GURL> url_chain,
- const base::Optional<std::string>& suggested_filename,
- const scoped_refptr<network::ResourceResponse>& response,
- net::CertStatus cert_status,
- network::mojom::URLLoaderClientEndpointsPtr url_loader_client_endpoints) {
- auto downloader = std::make_unique<ResourceDownloader>(
- delegate, std::move(resource_request), render_process_id, render_frame_id,
- GURL(), GURL(), GURL(), download::DownloadItem::kInvalidId);
- downloader->InterceptResponse(std::move(response), std::move(url_chain),
- suggested_filename, cert_status,
- std::move(url_loader_client_endpoints));
- return downloader;
-}
-
-ResourceDownloader::ResourceDownloader(
- base::WeakPtr<UrlDownloadHandler::Delegate> delegate,
- std::unique_ptr<network::ResourceRequest> resource_request,
- int render_process_id,
- int render_frame_id,
- const GURL& site_url,
- const GURL& tab_url,
- const GURL& tab_referrer_url,
- uint32_t download_id)
- : delegate_(delegate),
- resource_request_(std::move(resource_request)),
- download_id_(download_id),
- render_process_id_(render_process_id),
- render_frame_id_(render_frame_id),
- site_url_(site_url),
- tab_url_(tab_url),
- tab_referrer_url_(tab_referrer_url),
- weak_ptr_factory_(this) {}
-
-ResourceDownloader::~ResourceDownloader() = default;
-
-void ResourceDownloader::Start(
- network::mojom::URLLoaderFactory* url_loader_factory,
- std::unique_ptr<download::DownloadUrlParameters> download_url_parameters,
- bool is_parallel_request) {
- callback_ = download_url_parameters->callback();
- guid_ = download_url_parameters->guid();
-
- // Set up the URLLoaderClient.
- url_loader_client_ = std::make_unique<DownloadResponseHandler>(
- resource_request_.get(), this,
- std::make_unique<download::DownloadSaveInfo>(
- download_url_parameters->GetSaveInfo()),
- is_parallel_request, download_url_parameters->is_transient(),
- download_url_parameters->fetch_error_body(),
- download_url_parameters->request_origin(),
- download_url_parameters->download_source(),
- std::vector<GURL>(1, resource_request_->url));
- network::mojom::URLLoaderClientPtr url_loader_client_ptr;
- url_loader_client_binding_ =
- std::make_unique<mojo::Binding<network::mojom::URLLoaderClient>>(
- url_loader_client_.get(), mojo::MakeRequest(&url_loader_client_ptr));
-
- // Set up the URLLoader
- network::mojom::URLLoaderRequest url_loader_request =
- mojo::MakeRequest(&url_loader_);
- url_loader_factory->CreateLoaderAndStart(
- std::move(url_loader_request),
- 0, // routing_id
- 0, // request_id
- network::mojom::kURLLoadOptionSendSSLInfoWithResponse,
- *(resource_request_.get()), std::move(url_loader_client_ptr),
- net::MutableNetworkTrafficAnnotationTag(
- download_url_parameters->GetNetworkTrafficAnnotation()));
- url_loader_->SetPriority(net::RequestPriority::IDLE,
- 0 /* intra_priority_value */);
-}
-
-void ResourceDownloader::InterceptResponse(
- const scoped_refptr<network::ResourceResponse>& response,
- std::vector<GURL> url_chain,
- const base::Optional<std::string>& suggested_filename,
- net::CertStatus cert_status,
- network::mojom::URLLoaderClientEndpointsPtr endpoints) {
- // Set the URLLoader.
- url_loader_.Bind(std::move(endpoints->url_loader));
-
- // Create the new URLLoaderClient that will intercept the navigation.
- auto save_info = std::make_unique<download::DownloadSaveInfo>();
- if (suggested_filename.has_value())
- save_info->suggested_name = base::UTF8ToUTF16(suggested_filename.value());
- url_loader_client_ = std::make_unique<DownloadResponseHandler>(
- resource_request_.get(), this, std::move(save_info), false, false, false,
- std::string(), download::DownloadSource::NAVIGATION,
- std::move(url_chain));
-
- // Simulate on the new URLLoaderClient calls that happened on the old client.
- net::SSLInfo info;
- info.cert_status = cert_status;
- url_loader_client_->OnReceiveResponse(
- response->head, base::Optional<net::SSLInfo>(info),
- network::mojom::DownloadedTempFilePtr());
-
- // Bind the new client.
- url_loader_client_binding_ =
- std::make_unique<mojo::Binding<network::mojom::URLLoaderClient>>(
- url_loader_client_.get(), std::move(endpoints->url_loader_client));
-}
-
-void ResourceDownloader::OnResponseStarted(
- std::unique_ptr<download::DownloadCreateInfo> download_create_info,
- download::mojom::DownloadStreamHandlePtr stream_handle) {
- download_create_info->download_id = download_id_;
- download_create_info->guid = guid_;
- download_create_info->site_url = site_url_;
- download_create_info->tab_url = tab_url_;
- download_create_info->tab_referrer_url = tab_referrer_url_;
- download_create_info->render_process_id = render_process_id_;
- download_create_info->render_frame_id = render_frame_id_;
-
- BrowserThread::PostTask(
- BrowserThread::UI, FROM_HERE,
- base::BindOnce(&UrlDownloadHandler::Delegate::OnUrlDownloadStarted,
- delegate_, std::move(download_create_info),
- std::make_unique<DownloadManager::InputStream>(
- std::move(stream_handle)),
- callback_));
-}
-
-void ResourceDownloader::OnReceiveRedirect() {
- url_loader_->FollowRedirect();
-}
-
-} // namespace content
diff --git a/chromium/content/browser/download/resource_downloader.h b/chromium/content/browser/download/resource_downloader.h
deleted file mode 100644
index bd20c4979fa..00000000000
--- a/chromium/content/browser/download/resource_downloader.h
+++ /dev/null
@@ -1,127 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_DOWNLOAD_RESOURCE_DOWNLOADER_
-#define CONTENT_BROWSER_DOWNLOAD_RESOURCE_DOWNLOADER_
-
-#include "content/browser/download/download_response_handler.h"
-#include "content/browser/download/url_download_handler.h"
-#include "content/public/browser/ssl_status.h"
-#include "mojo/public/cpp/bindings/binding.h"
-#include "services/network/public/cpp/resource_request.h"
-#include "services/network/public/mojom/url_loader.mojom.h"
-#include "services/network/public/mojom/url_loader_factory.mojom.h"
-
-namespace content {
-
-// Class for handing the download of a url.
-class ResourceDownloader : public UrlDownloadHandler,
- public DownloadResponseHandler::Delegate {
- public:
- // Called to start a download, must be called on IO thread.
- static std::unique_ptr<ResourceDownloader> BeginDownload(
- base::WeakPtr<UrlDownloadHandler::Delegate> delegate,
- std::unique_ptr<download::DownloadUrlParameters> download_url_parameters,
- std::unique_ptr<network::ResourceRequest> request,
- network::mojom::URLLoaderFactory* url_loader_factory,
- const GURL& site_url,
- const GURL& tab_url,
- const GURL& tab_referrer_url,
- uint32_t download_id,
- bool is_parallel_request);
-
- // Create a ResourceDownloader from a navigation that turns to be a download.
- // No URLLoader is created, but the URLLoaderClient implementation is
- // transferred.
- static std::unique_ptr<ResourceDownloader> InterceptNavigationResponse(
- base::WeakPtr<UrlDownloadHandler::Delegate> delegate,
- std::unique_ptr<network::ResourceRequest> resource_request,
- int render_process_id,
- int render_frame_id,
- std::vector<GURL> url_chain,
- const base::Optional<std::string>& suggested_filename,
- const scoped_refptr<network::ResourceResponse>& response,
- net::CertStatus cert_status,
- network::mojom::URLLoaderClientEndpointsPtr url_loader_client_endpoints);
-
- ResourceDownloader(base::WeakPtr<UrlDownloadHandler::Delegate> delegate,
- std::unique_ptr<network::ResourceRequest> resource_request,
- int render_process_id,
- int render_frame_id,
- const GURL& site_url,
- const GURL& tab_url,
- const GURL& tab_referrer_url,
- uint32_t download_id);
- ~ResourceDownloader() override;
-
- // DownloadResponseHandler::Delegate
- void OnResponseStarted(
- std::unique_ptr<download::DownloadCreateInfo> download_create_info,
- download::mojom::DownloadStreamHandlePtr stream_handle) override;
- void OnReceiveRedirect() override;
-
- private:
- // Helper method to start the network request.
- void Start(
- network::mojom::URLLoaderFactory* url_loader_factory,
- std::unique_ptr<download::DownloadUrlParameters> download_url_parameters,
- bool is_parallel_request);
-
- // Intercepts the navigation response.
- void InterceptResponse(
- const scoped_refptr<network::ResourceResponse>& response,
- std::vector<GURL> url_chain,
- const base::Optional<std::string>& suggested_filename,
- net::CertStatus cert_status,
- network::mojom::URLLoaderClientEndpointsPtr url_loader_client_endpoints);
-
- base::WeakPtr<UrlDownloadHandler::Delegate> delegate_;
-
- // The ResourceRequest for this object.
- std::unique_ptr<network::ResourceRequest> resource_request_;
-
- // Object that will handle the response.
- std::unique_ptr<network::mojom::URLLoaderClient> url_loader_client_;
-
- // URLLoaderClient binding. It sends any requests to the |url_loader_client_|.
- std::unique_ptr<mojo::Binding<network::mojom::URLLoaderClient>>
- url_loader_client_binding_;
-
- // URLLoader for sending out the request.
- network::mojom::URLLoaderPtr url_loader_;
-
- // ID of the download, or download::DownloadItem::kInvalidId if this is a new
- // download.
- uint32_t download_id_;
-
- // GUID of the download, or empty if this is a new download.
- std::string guid_;
-
- // Callback to run after download starts.
- download::DownloadUrlParameters::OnStartedCallback callback_;
-
- // Frame and process id associated with the request.
- int render_process_id_;
- int render_frame_id_;
-
- // Site URL for the site instance that initiated the download.
- GURL site_url_;
-
- // The URL of the tab that started us.
- GURL tab_url_;
-
- // The referrer URL of the tab that started us.
- GURL tab_referrer_url_;
-
- // URLLoader status when intercepting the navigation request.
- base::Optional<network::URLLoaderCompletionStatus> url_loader_status_;
-
- base::WeakPtrFactory<ResourceDownloader> weak_ptr_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(ResourceDownloader);
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_DOWNLOAD_RESOURCE_DOWNLOADER_
diff --git a/chromium/content/browser/download/save_file.cc b/chromium/content/browser/download/save_file.cc
index 1d4140a88af..cbb514a48e9 100644
--- a/chromium/content/browser/download/save_file.cc
+++ b/chromium/content/browser/download/save_file.cc
@@ -4,7 +4,9 @@
#include "content/browser/download/save_file.h"
+#include "base/bind.h"
#include "base/logging.h"
+#include "base/optional.h"
#include "components/download/public/common/download_item.h"
#include "components/download/public/common/download_task_runner.h"
@@ -28,10 +30,12 @@ SaveFile::~SaveFile() {
}
download::DownloadInterruptReason SaveFile::Initialize() {
+ int64_t bytes_wasted = 0;
download::DownloadInterruptReason reason = file_.Initialize(
/*full_path=*/base::FilePath(), /*default_directory=*/base::FilePath(),
/*file=*/base::File(), /*bytes_so_far=*/0, /*hash_so_far=*/std::string(),
- /*hash_state=*/nullptr, /*is_sparse_file=*/false);
+ /*hash_state=*/nullptr, /*is_sparse_file=*/false,
+ /*bytes_wasted*/ &bytes_wasted);
info_->path = FullPath();
return reason;
}
diff --git a/chromium/content/browser/download/save_file.h b/chromium/content/browser/download/save_file.h
index d820c48e2fb..688574b07f9 100644
--- a/chromium/content/browser/download/save_file.h
+++ b/chromium/content/browser/download/save_file.h
@@ -10,7 +10,7 @@
#include "base/files/file_path.h"
#include "base/macros.h"
-#include "content/browser/download/base_file.h"
+#include "components/download/public/common/base_file.h"
#include "content/browser/download/save_types.h"
namespace content {
@@ -43,14 +43,13 @@ class SaveFile {
// Accessors.
SaveItemId save_item_id() const { return info_->save_item_id; }
int render_process_id() const { return info_->render_process_id; }
- int request_id() const { return info_->request_id; }
SaveFileCreateInfo::SaveFileSource save_source() const {
return info_->save_source;
}
const SaveFileCreateInfo& create_info() const { return *info_; }
private:
- BaseFile file_;
+ download::BaseFile file_;
std::unique_ptr<SaveFileCreateInfo> info_;
DISALLOW_COPY_AND_ASSIGN(SaveFile);
diff --git a/chromium/content/browser/download/save_file_manager.cc b/chromium/content/browser/download/save_file_manager.cc
index 770f5d266e7..96c463e4471 100644
--- a/chromium/content/browser/download/save_file_manager.cc
+++ b/chromium/content/browser/download/save_file_manager.cc
@@ -9,20 +9,17 @@
#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/string_util.h"
-#include "base/threading/thread.h"
#include "components/download/public/common/download_task_runner.h"
#include "content/browser/child_process_security_policy_impl.h"
#include "content/browser/download/save_file.h"
-#include "content/browser/download/save_file_resource_handler.h"
#include "content/browser/download/save_package.h"
-#include "content/browser/loader/resource_dispatcher_host_impl.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/resource_context.h"
+#include "content/public/browser/storage_partition.h"
#include "content/public/common/previews_state.h"
#include "net/base/io_buffer.h"
#include "net/base/load_flags.h"
@@ -30,6 +27,9 @@
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_job_factory.h"
+#include "services/network/public/cpp/simple_url_loader.h"
+#include "services/network/public/cpp/simple_url_loader_stream_consumer.h"
+#include "services/network/public/mojom/url_loader_factory.mojom.h"
#include "url/gurl.h"
namespace content {
@@ -41,6 +41,101 @@ static SaveFileManager* g_save_file_manager = nullptr;
} // namespace
+class SaveFileManager::SimpleURLLoaderHelper
+ : public network::SimpleURLLoaderStreamConsumer {
+ public:
+ static std::unique_ptr<SimpleURLLoaderHelper> CreateAndStartDownload(
+ std::unique_ptr<network::ResourceRequest> resource_request,
+ SaveItemId save_item_id,
+ SavePackageId save_package_id,
+ int render_process_id,
+ int render_frame_routing_id,
+ const net::NetworkTrafficAnnotationTag& annotation_tag,
+ network::mojom::URLLoaderFactory* url_loader_factory,
+ SaveFileManager* save_file_manager) {
+ return std::unique_ptr<SimpleURLLoaderHelper>(new SimpleURLLoaderHelper(
+ std::move(resource_request), save_item_id, save_package_id,
+ render_process_id, render_frame_routing_id, annotation_tag,
+ url_loader_factory, save_file_manager));
+ }
+
+ ~SimpleURLLoaderHelper() override = default;
+
+ private:
+ SimpleURLLoaderHelper(
+ std::unique_ptr<network::ResourceRequest> resource_request,
+ SaveItemId save_item_id,
+ SavePackageId save_package_id,
+ int render_process_id,
+ int render_frame_routing_id,
+ const net::NetworkTrafficAnnotationTag& annotation_tag,
+ network::mojom::URLLoaderFactory* url_loader_factory,
+ SaveFileManager* save_file_manager)
+ : save_file_manager_(save_file_manager),
+ save_item_id_(save_item_id),
+ save_package_id_(save_package_id) {
+ GURL url = resource_request->url;
+ url_loader_ = network::SimpleURLLoader::Create(std::move(resource_request),
+ annotation_tag);
+ // We can use Unretained below as |url_loader_| is owned by |this|, so the
+ // callback won't be invoked if |this| gets deleted.
+ url_loader_->SetOnResponseStartedCallback(base::BindOnce(
+ &SimpleURLLoaderHelper::OnResponseStarted, base::Unretained(this), url,
+ render_process_id, render_frame_routing_id));
+ url_loader_->DownloadAsStream(url_loader_factory, this);
+ }
+
+ void OnResponseStarted(GURL url,
+ int render_process_id,
+ int render_frame_routing_id,
+ const GURL& final_url,
+ const network::ResourceResponseHead& response_head) {
+ std::string content_disposition;
+ if (response_head.headers) {
+ response_head.headers->GetNormalizedHeader("Content-Disposition",
+ &content_disposition);
+ }
+
+ auto info = std::make_unique<SaveFileCreateInfo>(
+ url, final_url, save_item_id_, save_package_id_, render_process_id,
+ render_frame_routing_id, content_disposition);
+ download::GetDownloadTaskRunner()->PostTask(
+ FROM_HERE, base::BindOnce(&SaveFileManager::StartSave,
+ save_file_manager_, std::move(info)));
+ }
+
+ // network::SimpleURLLoaderStreamConsumer implementation:
+ void OnDataReceived(base::StringPiece string_piece,
+ base::OnceClosure resume) override {
+ // TODO(jcivelli): we should make threading sane and avoid copying
+ // |string_piece| bytes.
+ download::GetDownloadTaskRunner()->PostTask(
+ FROM_HERE,
+ base::BindOnce(&SaveFileManager::UpdateSaveProgress, save_file_manager_,
+ save_item_id_, string_piece.as_string()));
+ std::move(resume).Run();
+ }
+
+ void OnComplete(bool success) override {
+ download::GetDownloadTaskRunner()->PostTask(
+ FROM_HERE,
+ base::BindOnce(&SaveFileManager::SaveFinished, save_file_manager_,
+ save_item_id_, save_package_id_, success));
+ }
+
+ void OnRetry(base::OnceClosure start_retry) override {
+ // Retries are not enabled.
+ NOTREACHED();
+ }
+
+ SaveFileManager* save_file_manager_;
+ SaveItemId save_item_id_;
+ SavePackageId save_package_id_;
+ std::unique_ptr<network::SimpleURLLoader> url_loader_;
+
+ DISALLOW_COPY_AND_ASSIGN(SimpleURLLoaderHelper);
+};
+
SaveFileManager::SaveFileManager() {
DCHECK(g_save_file_manager == nullptr);
g_save_file_manager = this;
@@ -96,6 +191,7 @@ void SaveFileManager::SaveURL(SaveItemId save_item_id,
SaveFileCreateInfo::SaveFileSource save_source,
const base::FilePath& file_full_path,
ResourceContext* context,
+ StoragePartition* storage_partition,
SavePackage* save_package) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
@@ -106,13 +202,48 @@ void SaveFileManager::SaveURL(SaveItemId save_item_id,
// Register a saving job.
if (save_source == SaveFileCreateInfo::SAVE_FILE_FROM_NET) {
DCHECK(url.is_valid());
+ // Starts the actual download.
+ if (!ChildProcessSecurityPolicyImpl::GetInstance()->CanRequestURL(
+ render_process_host_id, url)) {
+ download::GetDownloadTaskRunner()->PostTask(
+ FROM_HERE,
+ base::BindOnce(&SaveFileManager::SaveFinished, this, save_item_id,
+ save_package->id(), /*success=*/false));
+ return;
+ }
- BrowserThread::PostTask(
- BrowserThread::IO, FROM_HERE,
- base::BindOnce(&SaveFileManager::OnSaveURL, this, url, referrer,
- save_item_id, save_package->id(), render_process_host_id,
- render_view_routing_id, render_frame_routing_id,
- context));
+ net::NetworkTrafficAnnotationTag traffic_annotation =
+ net::DefineNetworkTrafficAnnotation("save_file_manager", R"(
+ semantics {
+ sender: "Save File"
+ description: "Saving url to local file."
+ trigger:
+ "User clicks on 'Save link as...' context menu command to save a "
+ "link."
+ data: "None."
+ destination: WEBSITE
+ }
+ policy {
+ cookies_allowed: YES
+ cookies_store: "user"
+ setting:
+ "This feature cannot be disable by settings. The request is made "
+ "only if user chooses 'Save link as...' in context menu."
+ policy_exception_justification: "Not implemented."
+ })");
+
+ auto request = std::make_unique<network::ResourceRequest>();
+ request->url = url;
+ request->referrer = referrer.url;
+ request->priority = net::DEFAULT_PRIORITY;
+ request->load_flags = net::LOAD_SKIP_CACHE_VALIDATION;
+
+ url_loader_helpers_[save_item_id] =
+ SimpleURLLoaderHelper::CreateAndStartDownload(
+ std::move(request), save_item_id, save_package->id(),
+ render_process_host_id, render_frame_routing_id, traffic_annotation,
+ storage_partition->GetURLLoaderFactoryForBrowserProcess().get(),
+ this);
} else {
// We manually start the save job.
auto info = std::make_unique<SaveFileCreateInfo>(
@@ -204,15 +335,14 @@ void SaveFileManager::StartSave(std::unique_ptr<SaveFileCreateInfo> info) {
// thread). We may receive a few more updates before the IO thread gets the
// cancel message. We just delete the data since the SaveFile has been deleted.
void SaveFileManager::UpdateSaveProgress(SaveItemId save_item_id,
- net::IOBuffer* data,
- int data_len) {
+ const std::string& data) {
DCHECK(download::GetDownloadTaskRunner()->RunsTasksInCurrentSequence());
SaveFile* save_file = LookupSaveFile(save_item_id);
if (save_file) {
DCHECK(save_file->InProgress());
download::DownloadInterruptReason reason =
- save_file->AppendDataToFile(data->data(), data_len);
+ save_file->AppendDataToFile(data.data(), data.size());
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::BindOnce(&SaveFileManager::OnUpdateSaveProgress, this,
@@ -233,17 +363,15 @@ void SaveFileManager::SaveFinished(SaveItemId save_item_id,
int64_t bytes_so_far = 0;
SaveFile* save_file = LookupSaveFile(save_item_id);
- if (save_file != nullptr) {
+ // Note that we might not have a save_file: canceling starts on the download
+ // thread but the load is canceled on the UI thread. The request might finish
+ // while thread hoping.
+ if (save_file) {
DCHECK(save_file->InProgress());
DVLOG(20) << __func__ << "() save_file = " << save_file->DebugString();
bytes_so_far = save_file->BytesSoFar();
save_file->Finish();
save_file->Detach();
- } else {
- // We got called before StartSave - this should only happen if
- // ResourceHandler failed before it got a chance to parse headers
- // and metadata.
- DCHECK(!is_success);
}
BrowserThread::PostTask(
@@ -283,98 +411,12 @@ void SaveFileManager::OnSaveFinished(SaveItemId save_item_id,
int64_t bytes_so_far,
bool is_success) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ ClearURLLoader(save_item_id);
SavePackage* package = LookupPackage(save_item_id);
if (package)
package->SaveFinished(save_item_id, bytes_so_far, is_success);
}
-// Notifications sent from the UI thread and run on the IO thread.
-
-void SaveFileManager::OnSaveURL(const GURL& url,
- const Referrer& referrer,
- SaveItemId save_item_id,
- SavePackageId save_package_id,
- int render_process_host_id,
- int render_view_routing_id,
- int render_frame_routing_id,
- ResourceContext* context) {
- DCHECK_CURRENTLY_ON(BrowserThread::IO);
-
- const net::URLRequestContext* request_context = context->GetRequestContext();
- if (!request_context->job_factory()->IsHandledProtocol(url.scheme())) {
- // Since any URLs which have non-standard scheme have been filtered
- // by save manager(see GURL::SchemeIsStandard). This situation
- // should not happen.
- NOTREACHED();
- return;
- }
-
- net::NetworkTrafficAnnotationTag traffic_annotation =
- net::DefineNetworkTrafficAnnotation("save_file_manager", R"(
- semantics {
- sender: "Save File"
- description: "Saving url to local file."
- trigger:
- "User clicks on 'Save link as...' context menu command to save a "
- "link."
- data: "None."
- destination: WEBSITE
- }
- policy {
- cookies_allowed: YES
- cookies_store: "user"
- setting:
- "This feature cannot be disable by settings. The request is made "
- "only if user chooses 'Save link as...' in context menu."
- policy_exception_justification: "Not implemented."
- })");
- std::unique_ptr<net::URLRequest> request(request_context->CreateRequest(
- url, net::DEFAULT_PRIORITY, nullptr, traffic_annotation));
- request->set_method("GET");
-
- // The URLRequest needs to be initialized with the referrer and other
- // information prior to issuing it.
- ResourceDispatcherHostImpl::Get()->InitializeURLRequest(
- request.get(), referrer,
- false, // download.
- render_process_host_id, render_view_routing_id, render_frame_routing_id,
- PREVIEWS_OFF, context);
-
- // So far, for saving page, we need fetch content from cache, in the
- // future, maybe we can use a configuration to configure this behavior.
- request->SetLoadFlags(net::LOAD_SKIP_CACHE_VALIDATION);
-
- // Check if the renderer is permitted to request the requested URL.
- using AuthorizationState = SaveFileResourceHandler::AuthorizationState;
- AuthorizationState authorization_state = AuthorizationState::AUTHORIZED;
- if (!ChildProcessSecurityPolicyImpl::GetInstance()->CanRequestURL(
- render_process_host_id, url)) {
- DVLOG(1) << "Denying unauthorized save of " << url.possibly_invalid_spec();
- authorization_state = AuthorizationState::NOT_AUTHORIZED;
- // No need to return here (i.e. okay to begin processing the request below),
- // because NOT_AUTHORIZED will cause the request to be cancelled. See also
- // doc comments for AuthorizationState enum.
- }
-
- std::unique_ptr<SaveFileResourceHandler> handler(new SaveFileResourceHandler(
- request.get(), save_item_id, save_package_id, render_process_host_id,
- render_frame_routing_id, url, authorization_state));
-
- ResourceDispatcherHostImpl::Get()->BeginURLRequest(
- std::move(request), std::move(handler),
- false, // download
- false, // content_initiated (download specific)
- false, // do_not_prompt_for_login (download specific)
- context);
-}
-
-void SaveFileManager::ExecuteCancelSaveRequest(int render_process_id,
- int request_id) {
- DCHECK_CURRENTLY_ON(BrowserThread::IO);
- ResourceDispatcherHostImpl::Get()->CancelRequest(
- render_process_id, request_id);
-}
-
// Notifications sent from the UI thread and run on the file thread.
// This method will be sent via a user action, or shutdown on the UI thread,
@@ -395,15 +437,9 @@ void SaveFileManager::CancelSave(SaveItemId save_item_id) {
base::DeleteFile(save_file->FullPath(), false);
} else if (save_file->save_source() ==
SaveFileCreateInfo::SAVE_FILE_FROM_NET) {
- // If the data comes from the net IO thread and hasn't completed
- // yet, then forward the cancel message to IO thread & cancel the
- // save locally. If the data doesn't come from the IO thread,
- // we can ignore the message.
BrowserThread::PostTask(
- BrowserThread::IO, FROM_HERE,
- base::BindOnce(&SaveFileManager::ExecuteCancelSaveRequest, this,
- save_file->render_process_id(),
- save_file->request_id()));
+ BrowserThread::UI, FROM_HERE,
+ base::BindOnce(&SaveFileManager::ClearURLLoader, this, save_item_id));
}
// Whatever the save file is complete or not, just delete it. This
@@ -412,6 +448,13 @@ void SaveFileManager::CancelSave(SaveItemId save_item_id) {
}
}
+void SaveFileManager::ClearURLLoader(SaveItemId save_item_id) {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ auto url_loader_iter = url_loader_helpers_.find(save_item_id);
+ if (url_loader_iter != url_loader_helpers_.end())
+ url_loader_helpers_.erase(url_loader_iter);
+}
+
void SaveFileManager::OnDeleteDirectoryOrFile(const base::FilePath& full_path,
bool is_dir) {
DCHECK(download::GetDownloadTaskRunner()->RunsTasksInCurrentSequence());
diff --git a/chromium/content/browser/download/save_file_manager.h b/chromium/content/browser/download/save_file_manager.h
index b8f0eb7986c..d6e539cfbd9 100644
--- a/chromium/content/browser/download/save_file_manager.h
+++ b/chromium/content/browser/download/save_file_manager.h
@@ -10,27 +10,22 @@
// thread or the UI thread. It coordinates the notifications from the network
// and UI.
//
-// The SaveFileManager itself is a singleton object owned by the
-// ResourceDispatcherHostImpl.
+// The SaveFileManager itself is a singleton object created and owned by the
+// BrowserMainLoop.
//
-// The data sent to SaveFileManager have 2 sources, one is from
-// ResourceDispatcherHostImpl, run in network IO thread, the all sub-resources
-// and save-only-HTML pages will be got from network IO. The second is from
-// render process, those html pages which are serialized from DOM will be
-// composed in render process and encoded to its original encoding, then sent
-// to UI loop in browser process, then UI loop will dispatch the data to
-// SaveFileManager on the file thread. SaveFileManager will directly
-// call SaveFile's method to persist data.
+// The data sent to SaveFileManager have 2 sources:
+// - SimpleURLLoaders which are used to download sub-resources and
+// save-only-HTML pages
+// - render processese, for HTML pages which are serialized from the DOM in
+// their original encoding. The data is received on the UI thread and
+// dispatched directly to the SaveFileManager on the file thread.
//
// A typical saving job operation involves multiple threads and sequences:
//
-// Updating an in progress save file
-// io_thread
-// |----> data from net ---->|
-// |
-// |
+// Updating an in progress save file:
// |----> data from ---->| |
// | render process | |
+// | SimpleURLLoaders | |
// ui_thread | |
// download_task_runner (writes to disk)
// |----> stats ---->|
@@ -62,6 +57,7 @@
#include <memory>
#include <string>
#include <unordered_map>
+#include <vector>
#include "base/macros.h"
#include "base/memory/ref_counted.h"
@@ -74,14 +70,11 @@ namespace base {
class FilePath;
}
-namespace net {
-class IOBuffer;
-}
-
namespace content {
class ResourceContext;
class SaveFile;
class SavePackage;
+class StoragePartition;
struct Referrer;
class CONTENT_EXPORT SaveFileManager
@@ -95,10 +88,8 @@ class CONTENT_EXPORT SaveFileManager
// Lifetime management.
void Shutdown();
- // Save the specified URL. Caller has to guarantee that |save_package| will
- // be alive until the call to RemoveSaveFile. Called on the UI thread (and in
- // case of network downloads forwarded to the ResourceDispatcherHostImpl on
- // the IO thread).
+ // Saves the specified URL |url|. |save_package| must not be deleted before
+ // the call to RemoveSaveFile. Should be called on the UI thread,
void SaveURL(SaveItemId save_item_id,
const GURL& url,
const Referrer& referrer,
@@ -108,13 +99,12 @@ class CONTENT_EXPORT SaveFileManager
SaveFileCreateInfo::SaveFileSource save_source,
const base::FilePath& file_full_path,
ResourceContext* context,
+ StoragePartition* storage_partition,
SavePackage* save_package);
// Notifications sent from the IO thread and run on the file thread:
void StartSave(std::unique_ptr<SaveFileCreateInfo> info);
- void UpdateSaveProgress(SaveItemId save_item_id,
- net::IOBuffer* data,
- int size);
+ void UpdateSaveProgress(SaveItemId save_item_id, const std::string& data);
void SaveFinished(SaveItemId save_item_id,
SavePackageId save_package_id,
bool is_success);
@@ -150,6 +140,8 @@ class CONTENT_EXPORT SaveFileManager
private:
friend class base::RefCountedThreadSafe<SaveFileManager>;
+ class SimpleURLLoaderHelper;
+
~SaveFileManager();
// A cleanup helper that runs on the file thread.
@@ -205,10 +197,12 @@ class CONTENT_EXPORT SaveFileManager
int render_process_host_id,
int render_view_routing_id,
int render_frame_routing_id,
- ResourceContext* context);
- // Call ResourceDispatcherHostImpl's CancelRequest method to execute cancel
- // action in the IO thread.
- void ExecuteCancelSaveRequest(int render_process_id, int request_id);
+ StoragePartition* storage_partition);
+
+ // Called on the UI thread to remove the SimpleURLLoader in
+ // |url_loader_helpers_| associated with |save_item_id|. This stops the load
+ // if it is not complete.
+ void ClearURLLoader(SaveItemId save_item_id);
// A map from save_item_id into SaveFiles.
std::unordered_map<SaveItemId, std::unique_ptr<SaveFile>, SaveItemId::Hasher>
@@ -218,6 +212,13 @@ class CONTENT_EXPORT SaveFileManager
// SavePackageMap maps save item ids to their SavePackage.
std::unordered_map<SaveItemId, SavePackage*, SaveItemId::Hasher> packages_;
+ // The helper object doing the actual download. Should be accessed on the UI
+ // thread.
+ std::unordered_map<SaveItemId,
+ std::unique_ptr<SimpleURLLoaderHelper>,
+ SaveItemId::Hasher>
+ url_loader_helpers_;
+
DISALLOW_COPY_AND_ASSIGN(SaveFileManager);
};
diff --git a/chromium/content/browser/download/save_file_resource_handler.cc b/chromium/content/browser/download/save_file_resource_handler.cc
deleted file mode 100644
index fee5c7a98ce..00000000000
--- a/chromium/content/browser/download/save_file_resource_handler.cc
+++ /dev/null
@@ -1,128 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/download/save_file_resource_handler.h"
-
-#include <string>
-
-#include "base/bind.h"
-#include "base/logging.h"
-#include "base/message_loop/message_loop.h"
-#include "base/strings/string_number_conversions.h"
-#include "components/download/public/common/download_task_runner.h"
-#include "content/browser/download/save_file_manager.h"
-#include "content/browser/loader/resource_controller.h"
-#include "net/base/io_buffer.h"
-#include "net/http/http_response_headers.h"
-#include "net/url_request/redirect_info.h"
-#include "net/url_request/url_request_status.h"
-#include "services/network/public/cpp/resource_response.h"
-
-namespace content {
-
-SaveFileResourceHandler::SaveFileResourceHandler(
- net::URLRequest* request,
- SaveItemId save_item_id,
- SavePackageId save_package_id,
- int render_process_host_id,
- int render_frame_routing_id,
- const GURL& url,
- AuthorizationState authorization_state)
- : ResourceHandler(request),
- save_item_id_(save_item_id),
- save_package_id_(save_package_id),
- render_process_id_(render_process_host_id),
- render_frame_routing_id_(render_frame_routing_id),
- url_(url),
- save_manager_(SaveFileManager::Get()),
- authorization_state_(authorization_state) {}
-
-SaveFileResourceHandler::~SaveFileResourceHandler() {
-}
-
-void SaveFileResourceHandler::OnRequestRedirected(
- const net::RedirectInfo& redirect_info,
- network::ResourceResponse* response,
- std::unique_ptr<ResourceController> controller) {
- final_url_ = redirect_info.new_url;
- controller->Resume();
-}
-
-void SaveFileResourceHandler::OnResponseStarted(
- network::ResourceResponse* response,
- std::unique_ptr<ResourceController> controller) {
- std::string content_disposition;
- if (response->head.headers) {
- response->head.headers->GetNormalizedHeader("Content-Disposition",
- &content_disposition);
- }
-
- auto info = std::make_unique<SaveFileCreateInfo>(
- url_, final_url_, save_item_id_, save_package_id_, render_process_id_,
- render_frame_routing_id_, GetRequestID(), content_disposition);
- download::GetDownloadTaskRunner()->PostTask(
- FROM_HERE, base::BindOnce(&SaveFileManager::StartSave, save_manager_,
- std::move(info)));
- controller->Resume();
-}
-
-void SaveFileResourceHandler::OnWillStart(
- const GURL& url,
- std::unique_ptr<ResourceController> controller) {
- if (authorization_state_ == AuthorizationState::AUTHORIZED) {
- controller->Resume();
- } else {
- controller->Cancel();
- }
-}
-
-void SaveFileResourceHandler::OnWillRead(
- scoped_refptr<net::IOBuffer>* buf,
- int* buf_size,
- std::unique_ptr<ResourceController> controller) {
- DCHECK_EQ(AuthorizationState::AUTHORIZED, authorization_state_);
- DCHECK(buf && buf_size);
- if (!read_buffer_.get()) {
- *buf_size = kReadBufSize;
- read_buffer_ = new net::IOBuffer(*buf_size);
- }
- *buf = read_buffer_.get();
- controller->Resume();
-}
-
-void SaveFileResourceHandler::OnReadCompleted(
- int bytes_read,
- std::unique_ptr<ResourceController> controller) {
- DCHECK_EQ(AuthorizationState::AUTHORIZED, authorization_state_);
- DCHECK(read_buffer_.get());
- // We are passing ownership of this buffer to the save file manager.
- scoped_refptr<net::IOBuffer> buffer;
- read_buffer_.swap(buffer);
- download::GetDownloadTaskRunner()->PostTask(
- FROM_HERE,
- base::BindOnce(&SaveFileManager::UpdateSaveProgress, save_manager_,
- save_item_id_, base::RetainedRef(buffer), bytes_read));
- controller->Resume();
-}
-
-void SaveFileResourceHandler::OnResponseCompleted(
- const net::URLRequestStatus& status,
- std::unique_ptr<ResourceController> controller) {
- if (authorization_state_ != AuthorizationState::AUTHORIZED)
- DCHECK(!status.is_success());
-
- download::GetDownloadTaskRunner()->PostTask(
- FROM_HERE,
- base::BindOnce(&SaveFileManager::SaveFinished, save_manager_,
- save_item_id_, save_package_id_,
- status.is_success() && !status.is_io_pending()));
- read_buffer_ = nullptr;
- controller->Resume();
-}
-
-void SaveFileResourceHandler::OnDataDownloaded(int bytes_downloaded) {
- NOTREACHED();
-}
-
-} // namespace content
diff --git a/chromium/content/browser/download/save_file_resource_handler.h b/chromium/content/browser/download/save_file_resource_handler.h
deleted file mode 100644
index e371cbe150d..00000000000
--- a/chromium/content/browser/download/save_file_resource_handler.h
+++ /dev/null
@@ -1,100 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_DOWNLOAD_SAVE_FILE_RESOURCE_HANDLER_H_
-#define CONTENT_BROWSER_DOWNLOAD_SAVE_FILE_RESOURCE_HANDLER_H_
-
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "content/browser/download/save_types.h"
-#include "content/browser/loader/resource_handler.h"
-#include "url/gurl.h"
-
-namespace net {
-class URLRequest;
-}
-
-namespace content {
-class ResourceController;
-class SaveFileManager;
-
-// Forwards data to the save thread.
-class SaveFileResourceHandler : public ResourceHandler {
- public:
- // Unauthorized requests are cancelled from OnWillStart callback.
- //
- // This way of handling unauthorized requests allows unified handling of all
- // SaveFile requests - communicating the failure to OnResponseCompleted
- // happens in a generic, typical way, reusing common infrastructure code
- // (rather than forcing an ad-hoc, Save-File-specific call to
- // OnResponseCompleted from ResourceDispatcherHostImpl::BeginSaveFile).
- enum class AuthorizationState {
- AUTHORIZED,
- NOT_AUTHORIZED,
- };
-
- SaveFileResourceHandler(net::URLRequest* request,
- SaveItemId save_item_id,
- SavePackageId save_package_id,
- int render_process_host_id,
- int render_frame_routing_id,
- const GURL& url,
- AuthorizationState authorization_state);
- ~SaveFileResourceHandler() override;
-
- // ResourceHandler Implementation:
-
- // Saves the redirected URL to final_url_, we need to use the original
- // URL to match original request.
- void OnRequestRedirected(
- const net::RedirectInfo& redirect_info,
- network::ResourceResponse* response,
- std::unique_ptr<ResourceController> controller) override;
-
- // Sends the download creation information to the download thread.
- void OnResponseStarted(
- network::ResourceResponse* response,
- std::unique_ptr<ResourceController> controller) override;
-
- // Pass-through implementation.
- void OnWillStart(const GURL& url,
- std::unique_ptr<ResourceController> controller) override;
-
- // Creates a new buffer, which will be handed to the download thread for file
- // writing and deletion.
- void OnWillRead(scoped_refptr<net::IOBuffer>* buf,
- int* buf_size,
- std::unique_ptr<ResourceController> controller) override;
-
- // Passes the buffer to the download file writer.
- void OnReadCompleted(int bytes_read,
- std::unique_ptr<ResourceController> controller) override;
-
- void OnResponseCompleted(
- const net::URLRequestStatus& status,
- std::unique_ptr<ResourceController> controller) override;
-
- // N/A to this flavor of SaveFileResourceHandler.
- void OnDataDownloaded(int bytes_downloaded) override;
-
- private:
- SaveItemId save_item_id_;
- SavePackageId save_package_id_;
- int render_process_id_;
- int render_frame_routing_id_;
- scoped_refptr<net::IOBuffer> read_buffer_;
- GURL url_;
- GURL final_url_;
- SaveFileManager* save_manager_;
-
- AuthorizationState authorization_state_;
-
- static const int kReadBufSize = 32768; // bytes
-
- DISALLOW_COPY_AND_ASSIGN(SaveFileResourceHandler);
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_DOWNLOAD_SAVE_FILE_RESOURCE_HANDLER_H_
diff --git a/chromium/content/browser/download/save_package.cc b/chromium/content/browser/download/save_package.cc
index 977eda13ec9..ce081e96056 100644
--- a/chromium/content/browser/download/save_package.cc
+++ b/chromium/content/browser/download/save_package.cc
@@ -24,6 +24,7 @@
#include "base/threading/thread.h"
#include "base/threading/thread_restrictions.h"
#include "build/build_config.h"
+#include "components/download/public/common/download_item_impl.h"
#include "components/download/public/common/download_request_handle_interface.h"
#include "components/download/public/common/download_stats.h"
#include "components/download/public/common/download_task_runner.h"
@@ -31,7 +32,6 @@
#include "components/filename_generation/filename_generation.h"
#include "components/url_formatter/url_formatter.h"
#include "content/browser/bad_message.h"
-#include "content/browser/download/download_item_impl.h"
#include "content/browser/download/download_manager_impl.h"
#include "content/browser/download/save_file.h"
#include "content/browser/download/save_file_manager.h"
@@ -297,7 +297,7 @@ bool SavePackage::Init(
void SavePackage::InitWithDownloadItem(
const SavePackageDownloadCreatedCallback& download_created_callback,
- DownloadItemImpl* item) {
+ download::DownloadItemImpl* item) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(item);
download_ = item;
@@ -314,7 +314,7 @@ void SavePackage::InitWithDownloadItem(
MHTMLGenerationParams mhtml_generation_params(saved_main_file_path_);
web_contents()->GenerateMHTML(
mhtml_generation_params,
- base::Bind(&SavePackage::OnMHTMLGenerated, this));
+ base::BindOnce(&SavePackage::OnMHTMLGenerated, this));
} else {
DCHECK_EQ(SAVE_PAGE_TYPE_AS_ONLY_HTML, save_type_);
wait_state_ = NET_FILES;
@@ -820,7 +820,13 @@ void SavePackage::SaveNextFile(bool process_all_remaining_items) {
requester_frame->render_view_host()->GetRoutingID(),
requester_frame->routing_id(), save_item_ptr->save_source(),
save_item_ptr->full_path(),
- web_contents()->GetBrowserContext()->GetResourceContext(), this);
+ web_contents()->GetBrowserContext()->GetResourceContext(),
+ web_contents()
+ ->GetRenderViewHost()
+ ->GetProcess()
+ ->GetStoragePartition(),
+ this);
+
} while (process_all_remaining_items && !waiting_item_queue_.empty());
}
@@ -1046,16 +1052,10 @@ void SavePackage::OnSerializedHtmlWithLocalLinksResponse(
}
if (!data.empty()) {
- // Prepare buffer for saving HTML data.
- scoped_refptr<net::IOBuffer> new_data(new net::IOBuffer(data.size()));
- memcpy(new_data->data(), data.data(), data.size());
-
// Call write file functionality in download sequence.
download::GetDownloadTaskRunner()->PostTask(
- FROM_HERE,
- base::BindOnce(&SaveFileManager::UpdateSaveProgress, file_manager_,
- save_item->id(), base::RetainedRef(new_data),
- static_cast<int>(data.size())));
+ FROM_HERE, base::BindOnce(&SaveFileManager::UpdateSaveProgress,
+ file_manager_, save_item->id(), data));
}
// Current frame is completed saving, call finish in download sequence.
diff --git a/chromium/content/browser/download/save_package.h b/chromium/content/browser/download/save_package.h
index 425d6dabd92..d4ad79aec82 100644
--- a/chromium/content/browser/download/save_package.h
+++ b/chromium/content/browser/download/save_package.h
@@ -34,8 +34,11 @@
class GURL;
-namespace content {
+namespace download {
class DownloadItemImpl;
+}
+
+namespace content {
class DownloadManagerImpl;
class FrameTreeNode;
class RenderFrameHostImpl;
@@ -45,15 +48,15 @@ class SaveItem;
class SavePackage;
class WebContents;
-// The SavePackage object manages the process of saving a page as only-html or
-// complete-html or MHTML and providing the information for displaying saving
-// status. Saving page as only-html means means that we save web page to a
-// single HTML file regardless internal sub resources and sub frames. Saving
-// page as complete-html page means we save not only the main html file the user
-// told it to save but also a directory for the auxiliary files such as all
-// sub-frame html files, image files, css files and js files. Saving page as
-// MHTML means the same thing as complete-html, but it uses the MHTML format to
-// contain the html and all auxiliary files in a single text file.
+// SavePackage manages the process of saving a page as only-HTML, complete-HTML
+// or MHTML and provides status information about the job.
+// - only-html: the web page is saved to a single HTML file excluding
+// sub-resources and sub-frames
+// - complete-html: the web page's main frame HTML is saved to the user selected
+// file and a directory for the auxiliary files such as all sub-frame html
+// files, image files, css files and js files is created
+// - MHTML: the main frame and all auxiliary files are stored a single text
+// file using the MHTML format.
//
// Each page saving job may include one or multiple files which need to be
// saved. Each file is represented by a SaveItem, and all SaveItems are owned
@@ -156,7 +159,7 @@ class CONTENT_EXPORT SavePackage
void InitWithDownloadItem(
const SavePackageDownloadCreatedCallback& download_created_callback,
- DownloadItemImpl* item);
+ download::DownloadItemImpl* item);
// Callback for WebContents::GenerateMHTML().
void OnMHTMLGenerated(int64_t size);
@@ -369,7 +372,7 @@ class CONTENT_EXPORT SavePackage
// DownloadManager owns the download::DownloadItem and handles history and UI.
DownloadManagerImpl* download_manager_ = nullptr;
- DownloadItemImpl* download_ = nullptr;
+ download::DownloadItemImpl* download_ = nullptr;
// The URL of the page the user wants to save.
const GURL page_url_;
diff --git a/chromium/content/browser/download/save_package_download_job.cc b/chromium/content/browser/download/save_package_download_job.cc
deleted file mode 100644
index 0b15a2ff851..00000000000
--- a/chromium/content/browser/download/save_package_download_job.cc
+++ /dev/null
@@ -1,20 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/download/save_package_download_job.h"
-
-namespace content {
-
-SavePackageDownloadJob::SavePackageDownloadJob(
- DownloadItemImpl* download_item,
- std::unique_ptr<download::DownloadRequestHandleInterface> request_handle)
- : DownloadJob(download_item, std::move(request_handle)) {}
-
-SavePackageDownloadJob::~SavePackageDownloadJob() = default;
-
-bool SavePackageDownloadJob::IsSavePackageDownload() const {
- return true;
-}
-
-} // namespace content
diff --git a/chromium/content/browser/download/save_package_download_job.h b/chromium/content/browser/download/save_package_download_job.h
deleted file mode 100644
index b624d0c0d18..00000000000
--- a/chromium/content/browser/download/save_package_download_job.h
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_DOWNLOAD_SAVE_PACKAGE_DOWNLOAD_JOB_H_
-#define CONTENT_BROWSER_DOWNLOAD_SAVE_PACKAGE_DOWNLOAD_JOB_H_
-
-#include "base/macros.h"
-#include "components/download/public/common/download_request_handle_interface.h"
-#include "content/browser/download/download_item_impl.h"
-#include "content/browser/download/download_job.h"
-#include "content/common/content_export.h"
-
-namespace content {
-
-class CONTENT_EXPORT SavePackageDownloadJob : public DownloadJob {
- public:
- SavePackageDownloadJob(
- DownloadItemImpl* download_item,
- std::unique_ptr<download::DownloadRequestHandleInterface> request_handle);
- ~SavePackageDownloadJob() override;
-
- // DownloadJob implementation.
- bool IsSavePackageDownload() const override;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(SavePackageDownloadJob);
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_DOWNLOAD_SAVE_PACKAGE_DOWNLOAD_JOB_H_
diff --git a/chromium/content/browser/download/save_types.cc b/chromium/content/browser/download/save_types.cc
index 81e5925c506..80d714bf02c 100644
--- a/chromium/content/browser/download/save_types.cc
+++ b/chromium/content/browser/download/save_types.cc
@@ -21,7 +21,6 @@ SaveFileCreateInfo::SaveFileCreateInfo(const base::FilePath& path,
save_package_id(save_package_id),
render_process_id(render_process_id),
render_frame_routing_id(render_frame_routing_id),
- request_id(-1),
save_source(save_source) {}
SaveFileCreateInfo::SaveFileCreateInfo(const GURL& url,
@@ -30,7 +29,6 @@ SaveFileCreateInfo::SaveFileCreateInfo(const GURL& url,
SavePackageId save_package_id,
int render_process_id,
int render_frame_routing_id,
- int request_id,
const std::string& content_disposition)
: url(url),
final_url(final_url),
@@ -38,7 +36,6 @@ SaveFileCreateInfo::SaveFileCreateInfo(const GURL& url,
save_package_id(save_package_id),
render_process_id(render_process_id),
render_frame_routing_id(render_frame_routing_id),
- request_id(request_id),
content_disposition(content_disposition),
save_source(SaveFileCreateInfo::SAVE_FILE_FROM_NET) {}
diff --git a/chromium/content/browser/download/save_types.h b/chromium/content/browser/download/save_types.h
index 027daec0d4b..20c8089d4a5 100644
--- a/chromium/content/browser/download/save_types.h
+++ b/chromium/content/browser/download/save_types.h
@@ -57,7 +57,6 @@ struct SaveFileCreateInfo {
SavePackageId save_package_id,
int render_process_id,
int render_frame_routing_id,
- int request_id,
const std::string& content_disposition);
SaveFileCreateInfo(const SaveFileCreateInfo& other);
@@ -78,8 +77,6 @@ struct SaveFileCreateInfo {
// IDs for looking up the contents we are associated with.
int render_process_id;
int render_frame_routing_id;
- // Handle for informing the ResourceDispatcherHost of a UI based cancel.
- int request_id;
// Disposition info from HTTP response.
std::string content_disposition;
// Source type of saved file.
diff --git a/chromium/content/browser/download/url_download_handler.h b/chromium/content/browser/download/url_download_handler.h
deleted file mode 100644
index c73d685cf09..00000000000
--- a/chromium/content/browser/download/url_download_handler.h
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_DOWNLOAD_URL_DOWNLOAD_HANDLER
-#define CONTENT_BROWSER_DOWNLOAD_URL_DOWNLOAD_HANDLER
-
-#include "components/download/public/common/download_url_parameters.h"
-#include "content/public/browser/download_manager.h"
-
-namespace download {
-struct DownloadCreateInfo;
-} // namespace download
-
-namespace content {
-
-// Class for handling the download of a url. Implemented by child classes.
-class CONTENT_EXPORT UrlDownloadHandler {
- public:
- // Class to be notified when download starts/stops.
- class CONTENT_EXPORT Delegate {
- public:
- virtual void OnUrlDownloadStarted(
- std::unique_ptr<download::DownloadCreateInfo> download_create_info,
- std::unique_ptr<DownloadManager::InputStream> input_stream,
- const download::DownloadUrlParameters::OnStartedCallback& callback) = 0;
- // Called after the connection is cancelled or finished.
- virtual void OnUrlDownloadStopped(UrlDownloadHandler* downloader) = 0;
- };
-
- UrlDownloadHandler() = default;
- virtual ~UrlDownloadHandler() = default;
-
- DISALLOW_COPY_AND_ASSIGN(UrlDownloadHandler);
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_DOWNLOAD_URL_DOWNLOAD_HANDLER
diff --git a/chromium/content/browser/download/url_downloader.cc b/chromium/content/browser/download/url_downloader.cc
index e6d93a0af9f..034fadddce8 100644
--- a/chromium/content/browser/download/url_downloader.cc
+++ b/chromium/content/browser/download/url_downloader.cc
@@ -14,6 +14,7 @@
#include "components/download/public/common/download_request_handle_interface.h"
#include "components/download/public/common/download_url_parameters.h"
#include "content/browser/byte_stream.h"
+#include "content/browser/download/byte_stream_input_stream.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/io_buffer.h"
#include "net/base/load_flags.h"
@@ -63,7 +64,7 @@ class UrlDownloader::RequestHandle
// static
std::unique_ptr<UrlDownloader> UrlDownloader::BeginDownload(
- base::WeakPtr<UrlDownloadHandler::Delegate> delegate,
+ base::WeakPtr<download::UrlDownloadHandler::Delegate> delegate,
std::unique_ptr<net::URLRequest> request,
download::DownloadUrlParameters* params,
bool is_parallel_request) {
@@ -89,7 +90,7 @@ std::unique_ptr<UrlDownloader> UrlDownloader::BeginDownload(
UrlDownloader::UrlDownloader(
std::unique_ptr<net::URLRequest> request,
- base::WeakPtr<UrlDownloadHandler::Delegate> delegate,
+ base::WeakPtr<download::UrlDownloadHandler::Delegate> delegate,
bool is_parallel_request,
const std::string& request_origin,
download::DownloadSource download_source)
@@ -225,11 +226,11 @@ void UrlDownloader::OnStart(
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
- base::BindOnce(&UrlDownloadHandler::Delegate::OnUrlDownloadStarted,
- delegate_, std::move(create_info),
- std::make_unique<DownloadManager::InputStream>(
- std::move(stream_reader)),
- callback));
+ base::BindOnce(
+ &download::UrlDownloadHandler::Delegate::OnUrlDownloadStarted,
+ delegate_, std::move(create_info),
+ std::make_unique<ByteStreamInputStream>(std::move(stream_reader)),
+ nullptr, callback));
}
void UrlDownloader::OnReadyToRead() {
@@ -251,8 +252,9 @@ void UrlDownloader::CancelRequest() {
void UrlDownloader::Destroy() {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
- base::BindOnce(&UrlDownloadHandler::Delegate::OnUrlDownloadStopped,
- delegate_, this));
+ base::BindOnce(
+ &download::UrlDownloadHandler::Delegate::OnUrlDownloadStopped,
+ delegate_, this));
}
} // namespace content
diff --git a/chromium/content/browser/download/url_downloader.h b/chromium/content/browser/download/url_downloader.h
index c058081f1dc..0ee10feddf7 100644
--- a/chromium/content/browser/download/url_downloader.h
+++ b/chromium/content/browser/download/url_downloader.h
@@ -11,8 +11,8 @@
#include "base/memory/weak_ptr.h"
#include "components/download/public/common/download_url_parameters.h"
+#include "components/download/public/common/url_download_handler.h"
#include "content/browser/download/download_request_core.h"
-#include "content/browser/download/url_download_handler.h"
#include "content/public/common/referrer.h"
#include "net/url_request/redirect_info.h"
#include "net/url_request/url_request.h"
@@ -26,7 +26,7 @@ class ByteStreamReader;
class UrlDownloader : public net::URLRequest::Delegate,
public DownloadRequestCore::Delegate,
- public UrlDownloadHandler {
+ public download::UrlDownloadHandler {
public:
UrlDownloader(std::unique_ptr<net::URLRequest> request,
base::WeakPtr<UrlDownloadHandler::Delegate> delegate,
@@ -36,7 +36,7 @@ class UrlDownloader : public net::URLRequest::Delegate,
~UrlDownloader() override;
static std::unique_ptr<UrlDownloader> BeginDownload(
- base::WeakPtr<UrlDownloadHandler::Delegate> delegate,
+ base::WeakPtr<download::UrlDownloadHandler::Delegate> delegate,
std::unique_ptr<net::URLRequest> request,
download::DownloadUrlParameters* params,
bool is_parallel_request);
@@ -76,7 +76,7 @@ class UrlDownloader : public net::URLRequest::Delegate,
std::unique_ptr<net::URLRequest> request_;
// Live on UI thread, post task to call |delegate_| functions.
- base::WeakPtr<UrlDownloadHandler::Delegate> delegate_;
+ base::WeakPtr<download::UrlDownloadHandler::Delegate> delegate_;
DownloadRequestCore core_;
base::WeakPtrFactory<UrlDownloader> weak_ptr_factory_;
diff --git a/chromium/content/browser/download/url_downloader_factory.cc b/chromium/content/browser/download/url_downloader_factory.cc
new file mode 100644
index 00000000000..342a24ab99d
--- /dev/null
+++ b/chromium/content/browser/download/url_downloader_factory.cc
@@ -0,0 +1,34 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/download/url_downloader_factory.h"
+
+#include "components/download/public/common/download_item.h"
+#include "content/browser/download/download_request_core.h"
+#include "content/browser/download/url_downloader.h"
+
+namespace content {
+
+UrlDownloaderFactory::UrlDownloaderFactory() = default;
+
+UrlDownloaderFactory::~UrlDownloaderFactory() = default;
+
+download::UrlDownloadHandler::UniqueUrlDownloadHandlerPtr
+UrlDownloaderFactory::CreateUrlDownloadHandler(
+ std::unique_ptr<download::DownloadUrlParameters> params,
+ base::WeakPtr<download::UrlDownloadHandler::Delegate> delegate,
+ scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory,
+ const scoped_refptr<base::SingleThreadTaskRunner>& task_runner) {
+ std::unique_ptr<net::URLRequest> url_request =
+ DownloadRequestCore::CreateRequestOnIOThread(
+ download::DownloadItem::kInvalidId, params.get());
+
+ return download::UrlDownloadHandler::UniqueUrlDownloadHandlerPtr(
+ UrlDownloader::BeginDownload(delegate, std::move(url_request),
+ params.get(), true)
+ .release(),
+ base::OnTaskRunnerDeleter(base::ThreadTaskRunnerHandle::Get()));
+}
+
+} // namespace content
diff --git a/chromium/content/browser/download/url_downloader_factory.h b/chromium/content/browser/download/url_downloader_factory.h
new file mode 100644
index 00000000000..cd187b55971
--- /dev/null
+++ b/chromium/content/browser/download/url_downloader_factory.h
@@ -0,0 +1,30 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_BROWSER_DOWNLOAD_URL_DOWNLOADER_FACTORY_H_
+#define CONTENT_BROWSER_DOWNLOAD_URL_DOWNLOADER_FACTORY_H_
+
+#include "components/download/public/common/url_download_handler_factory.h"
+
+namespace content {
+
+// Class for creating UrlDownloader object.
+// TODO(qinmin): remove this once network service is fully enabled.
+class UrlDownloaderFactory : public download::UrlDownloadHandlerFactory {
+ public:
+ UrlDownloaderFactory();
+ ~UrlDownloaderFactory() override;
+
+ // download::UrlDownloadHandlerFactory
+ download::UrlDownloadHandler::UniqueUrlDownloadHandlerPtr
+ CreateUrlDownloadHandler(
+ std::unique_ptr<download::DownloadUrlParameters> params,
+ base::WeakPtr<download::UrlDownloadHandler::Delegate> delegate,
+ scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory,
+ const scoped_refptr<base::SingleThreadTaskRunner>& task_runner) override;
+};
+
+} // namespace content
+
+#endif // CONTENT_BROWSER_DOWNLOAD_URL_DOWNLOADER_FACTORY_H_
diff --git a/chromium/content/browser/field_trial_recorder.cc b/chromium/content/browser/field_trial_recorder.cc
index ed847e7fe89..51540dcd050 100644
--- a/chromium/content/browser/field_trial_recorder.cc
+++ b/chromium/content/browser/field_trial_recorder.cc
@@ -4,7 +4,6 @@
#include "content/browser/field_trial_recorder.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/field_trial.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
diff --git a/chromium/content/browser/file_url_loader_factory.cc b/chromium/content/browser/file_url_loader_factory.cc
index 1bbeafd3e79..8bf1bcedd08 100644
--- a/chromium/content/browser/file_url_loader_factory.cc
+++ b/chromium/content/browser/file_url_loader_factory.cc
@@ -159,7 +159,7 @@ class FileURLDirectoryLoader
network::ResourceResponseHead head;
head.mime_type = "text/html";
head.charset = "utf-8";
- client->OnReceiveResponse(head, base::nullopt, nullptr);
+ client->OnReceiveResponse(head, nullptr);
client->OnStartLoadingResponseBody(std::move(pipe.consumer_handle));
client_ = std::move(client);
@@ -554,7 +554,7 @@ class FileURLLoader : public network::mojom::URLLoader {
base::StringPrintf("%s: %s", net::HttpRequestHeaders::kContentType,
head.mime_type.c_str()));
}
- client->OnReceiveResponse(head, base::nullopt, nullptr);
+ client->OnReceiveResponse(head, nullptr);
client->OnStartLoadingResponseBody(std::move(pipe.consumer_handle));
client_ = std::move(client);
@@ -630,6 +630,7 @@ void FileURLLoaderFactory::CreateLoaderAndStart(
const network::ResourceRequest& request,
network::mojom::URLLoaderClientPtr client,
const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) {
+ DCHECK(!request.download_to_file);
base::FilePath file_path;
const bool is_file = net::FileURLToFilePath(request.url, &file_path);
if (is_file && file_path.EndsWithSeparator() && file_path.IsAbsolute()) {
diff --git a/chromium/content/browser/fileapi/DEPS b/chromium/content/browser/fileapi/DEPS
index 87b83c0917d..743a2f3baec 100644
--- a/chromium/content/browser/fileapi/DEPS
+++ b/chromium/content/browser/fileapi/DEPS
@@ -1,3 +1,3 @@
include_rules = [
- "+third_party/leveldatabase/src/include/leveldb",
+ "+third_party/leveldatabase",
]
diff --git a/chromium/content/browser/fileapi/browser_file_system_helper.cc b/chromium/content/browser/fileapi/browser_file_system_helper.cc
index fb3533d5bca..4d8ecc2bab9 100644
--- a/chromium/content/browser/fileapi/browser_file_system_helper.cc
+++ b/chromium/content/browser/fileapi/browser_file_system_helper.cc
@@ -33,6 +33,7 @@
#include "storage/browser/fileapi/file_system_url.h"
#include "storage/browser/fileapi/isolated_context.h"
#include "storage/browser/quota/quota_manager.h"
+#include "third_party/leveldatabase/leveldb_chrome.h"
#include "url/gurl.h"
#include "url/url_constants.h"
@@ -61,7 +62,11 @@ FileSystemOptions CreateBrowserFileSystemOptions(bool is_incognito) {
switches::kAllowFileAccessFromFiles)) {
additional_allowed_schemes.push_back(url::kFileScheme);
}
- return FileSystemOptions(profile_mode, additional_allowed_schemes, nullptr);
+ leveldb::Env* env_override = nullptr;
+ if (is_incognito)
+ env_override = leveldb_chrome::NewMemEnv(leveldb::Env::Default());
+ return FileSystemOptions(profile_mode, additional_allowed_schemes,
+ env_override);
}
} // namespace
diff --git a/chromium/content/browser/fileapi/fileapi_message_filter.cc b/chromium/content/browser/fileapi/fileapi_message_filter.cc
index 3eb75cf5cf8..1e427681d69 100644
--- a/chromium/content/browser/fileapi/fileapi_message_filter.cc
+++ b/chromium/content/browser/fileapi/fileapi_message_filter.cc
@@ -19,12 +19,14 @@
#include "base/threading/thread.h"
#include "base/time/time.h"
#include "build/build_config.h"
+#include "components/services/filesystem/public/interfaces/types.mojom.h"
#include "content/browser/bad_message.h"
#include "content/browser/blob_storage/chrome_blob_storage_context.h"
#include "content/browser/child_process_security_policy_impl.h"
#include "content/browser/fileapi/browser_file_system_helper.h"
#include "content/common/fileapi/file_system_messages.h"
#include "content/common/fileapi/webblob_messages.h"
+#include "content/public/browser/browser_thread.h"
#include "ipc/ipc_platform_file.h"
#include "net/base/mime_util.h"
#include "net/url_request/url_request_context.h"
@@ -36,7 +38,6 @@
#include "storage/browser/fileapi/file_permission_policy.h"
#include "storage/browser/fileapi/file_system_context.h"
#include "storage/browser/fileapi/isolated_context.h"
-#include "storage/common/fileapi/directory_entry.h"
#include "storage/common/fileapi/file_system_info.h"
#include "storage/common/fileapi/file_system_types.h"
#include "storage/common/fileapi/file_system_util.h"
@@ -501,7 +502,7 @@ void FileAPIMessageFilter::DidGetMetadataForStreaming(
void FileAPIMessageFilter::DidReadDirectory(
int request_id,
base::File::Error result,
- std::vector<storage::DirectoryEntry> entries,
+ std::vector<filesystem::mojom::DirectoryEntry> entries,
bool has_more) {
if (result == base::File::FILE_OK) {
if (!entries.empty() || !has_more)
diff --git a/chromium/content/browser/fileapi/fileapi_message_filter.h b/chromium/content/browser/fileapi/fileapi_message_filter.h
index c43d3cc4eb1..f699cc7b53d 100644
--- a/chromium/content/browser/fileapi/fileapi_message_filter.h
+++ b/chromium/content/browser/fileapi/fileapi_message_filter.h
@@ -9,8 +9,10 @@
#include <stdint.h>
#include <map>
+#include <memory>
#include <set>
#include <string>
+#include <vector>
#include "base/callback.h"
#include "base/containers/hash_tables.h"
@@ -18,6 +20,7 @@
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/memory/shared_memory.h"
+#include "components/services/filesystem/public/interfaces/types.mojom.h"
#include "content/browser/streams/stream.h"
#include "content/browser/streams/stream_context.h"
#include "content/common/content_export.h"
@@ -36,7 +39,6 @@ class Time;
namespace storage {
class FileSystemURL;
class FileSystemOperationRunner;
-struct DirectoryEntry;
struct FileSystemInfo;
}
@@ -127,7 +129,7 @@ class CONTENT_EXPORT FileAPIMessageFilter : public BrowserMessageFilter {
const base::File::Info& info);
void DidReadDirectory(int request_id,
base::File::Error result,
- std::vector<storage::DirectoryEntry> entries,
+ std::vector<filesystem::mojom::DirectoryEntry> entries,
bool has_more);
void DidWrite(int request_id,
base::File::Error result,
diff --git a/chromium/content/browser/find_request_manager.h b/chromium/content/browser/find_request_manager.h
index 5a3fbd3f8ef..1939bc57742 100644
--- a/chromium/content/browser/find_request_manager.h
+++ b/chromium/content/browser/find_request_manager.h
@@ -14,7 +14,7 @@
#include "content/common/content_export.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/common/stop_find_action.h"
-#include "third_party/WebKit/public/web/WebFindOptions.h"
+#include "third_party/blink/public/web/web_find_options.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/rect_f.h"
diff --git a/chromium/content/browser/find_request_manager_browsertest.cc b/chromium/content/browser/find_request_manager_browsertest.cc
index 5e89155728f..c639245949f 100644
--- a/chromium/content/browser/find_request_manager_browsertest.cc
+++ b/chromium/content/browser/find_request_manager_browsertest.cc
@@ -17,7 +17,7 @@
#include "content/shell/browser/shell.h"
#include "content/test/content_browser_test_utils_internal.h"
#include "net/dns/mock_host_resolver.h"
-#include "third_party/WebKit/public/web/WebFindOptions.h"
+#include "third_party/blink/public/web/web_find_options.h"
namespace content {
@@ -229,13 +229,16 @@ bool ExecuteScriptAndExtractRect(FrameTreeNode* frame,
// Basic test that a search result is actually brought into view.
IN_PROC_BROWSER_TEST_P(FindRequestManagerTest, ScrollAndZoomIntoView) {
+ WebContentsImpl* web_contents =
+ static_cast<WebContentsImpl*>(shell()->web_contents());
+ WebPreferences prefs =
+ web_contents->GetRenderViewHost()->GetWebkitPreferences();
+ prefs.smooth_scroll_for_find_enabled = false;
+ web_contents->GetRenderViewHost()->UpdateWebkitPreferences(prefs);
+
LoadAndWait("/find_in_page_desktop.html");
- if (GetParam()) {
- // TODO(bokan): The OOPIF version of this test is currently broken due to
- // bug https://crbug.com/810291.
- // MakeChildFrameCrossProcess();
- return;
- }
+ if (GetParam())
+ MakeChildFrameCrossProcess();
FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
->GetFrameTree()
diff --git a/chromium/content/browser/frame_host/cross_process_frame_connector.cc b/chromium/content/browser/frame_host/cross_process_frame_connector.cc
index b9d26dfaf51..5a706cd6e3f 100644
--- a/chromium/content/browser/frame_host/cross_process_frame_connector.cc
+++ b/chromium/content/browser/frame_host/cross_process_frame_connector.cc
@@ -24,7 +24,7 @@
#include "content/public/common/screen_info.h"
#include "content/public/common/use_zoom_for_dsf_policy.h"
#include "gpu/ipc/common/gpu_messages.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/base/ui_base_features.h"
#include "ui/base/ui_base_switches_util.h"
#include "ui/gfx/geometry/dip_util.h"
@@ -76,11 +76,9 @@ void CrossProcessFrameConnector::SetView(RenderWidgetHostViewChildFrame* view) {
// be called during nested WebContents destruction. See
// https://crbug.com/644306.
if (is_scroll_bubbling_ && GetParentRenderWidgetHostView() &&
- GetParentRenderWidgetHostView()
- ->GetRenderWidgetHostImpl()
- ->delegate()) {
+ GetParentRenderWidgetHostView()->host()->delegate()) {
GetParentRenderWidgetHostView()
- ->GetRenderWidgetHostImpl()
+ ->host()
->delegate()
->GetInputEventRouter()
->CancelScrollBubbling(view_);
@@ -211,18 +209,16 @@ void CrossProcessFrameConnector::BubbleScrollEvent(
if (!parent_view)
return;
- auto* event_router =
- parent_view->GetRenderWidgetHostImpl()->delegate()->GetInputEventRouter();
+ auto* event_router = parent_view->host()->delegate()->GetInputEventRouter();
// We will only convert the coordinates back to the root here. The
// RenderWidgetHostInputEventRouter will determine which ancestor view will
// receive a resent gesture event, so it will be responsible for converting to
// the coordinates of the target view.
blink::WebGestureEvent resent_gesture_event(event);
- const gfx::Point root_point =
- view_->TransformPointToRootCoordSpace(gfx::Point(event.x, event.y));
- resent_gesture_event.x = root_point.x();
- resent_gesture_event.y = root_point.y();
+ const gfx::PointF root_point =
+ view_->TransformPointToRootCoordSpaceF(event.PositionInWidget());
+ resent_gesture_event.SetPositionInWidget(root_point);
if (view_->wheel_scroll_latching_enabled()) {
if (event.GetType() == blink::WebInputEvent::kGestureScrollBegin) {
@@ -275,15 +271,12 @@ void CrossProcessFrameConnector::UnlockMouse() {
}
void CrossProcessFrameConnector::OnUpdateResizeParams(
- const gfx::Rect& screen_space_rect,
- const gfx::Size& local_frame_size,
- const ScreenInfo& screen_info,
- uint64_t sequence_number,
- const viz::SurfaceId& surface_id) {
+ const viz::SurfaceId& surface_id,
+ const FrameResizeParams& resize_params) {
// If the |screen_space_rect| or |screen_info| of the frame has changed, then
// the viz::LocalSurfaceId must also change.
- if ((last_received_local_frame_size_ != local_frame_size ||
- screen_info_ != screen_info) &&
+ if ((last_received_local_frame_size_ != resize_params.local_frame_size ||
+ screen_info_ != resize_params.screen_info) &&
local_surface_id_ == surface_id.local_surface_id()) {
bad_message::ReceivedBadMessage(
frame_proxy_in_parent_renderer_->GetProcess(),
@@ -291,16 +284,18 @@ void CrossProcessFrameConnector::OnUpdateResizeParams(
return;
}
- last_received_local_frame_size_ = local_frame_size;
- UpdateResizeParams(screen_space_rect, local_frame_size, screen_info,
- sequence_number, surface_id);
+ last_received_local_frame_size_ = resize_params.local_frame_size;
+ UpdateResizeParams(surface_id, resize_params);
}
void CrossProcessFrameConnector::OnUpdateViewportIntersection(
- const gfx::Rect& viewport_intersection) {
+ const gfx::Rect& viewport_intersection,
+ const gfx::Rect& compositor_visible_rect) {
viewport_intersection_rect_ = viewport_intersection;
+ compositor_visible_rect_ = compositor_visible_rect;
if (view_)
- view_->UpdateViewportIntersection(viewport_intersection);
+ view_->UpdateViewportIntersection(viewport_intersection,
+ compositor_visible_rect);
}
void CrossProcessFrameConnector::OnVisibilityChanged(bool visible) {
@@ -315,13 +310,11 @@ void CrossProcessFrameConnector::OnVisibilityChanged(bool visible) {
if (frame_proxy_in_parent_renderer_->frame_tree_node()
->render_manager()
->ForInnerDelegate()) {
- view_->GetRenderWidgetHostImpl()
- ->delegate()
- ->OnRenderFrameProxyVisibilityChanged(visible);
+ view_->host()->delegate()->OnRenderFrameProxyVisibilityChanged(visible);
return;
}
- if (visible && !view_->GetRenderWidgetHostImpl()->delegate()->IsHidden()) {
+ if (visible && !view_->host()->delegate()->IsHidden()) {
view_->Show();
} else if (!visible) {
view_->Hide();
@@ -376,6 +369,17 @@ CrossProcessFrameConnector::GetParentRenderWidgetHostView() {
return nullptr;
}
+void CrossProcessFrameConnector::EnableAutoResize(const gfx::Size& min_size,
+ const gfx::Size& max_size) {
+ frame_proxy_in_parent_renderer_->Send(new FrameMsg_EnableAutoResize(
+ frame_proxy_in_parent_renderer_->GetRoutingID(), min_size, max_size));
+}
+
+void CrossProcessFrameConnector::DisableAutoResize() {
+ frame_proxy_in_parent_renderer_->Send(new FrameMsg_DisableAutoResize(
+ frame_proxy_in_parent_renderer_->GetRoutingID()));
+}
+
bool CrossProcessFrameConnector::IsInert() const {
return is_inert_;
}
diff --git a/chromium/content/browser/frame_host/cross_process_frame_connector.h b/chromium/content/browser/frame_host/cross_process_frame_connector.h
index 92486c63e00..95e72d659cb 100644
--- a/chromium/content/browser/frame_host/cross_process_frame_connector.h
+++ b/chromium/content/browser/frame_host/cross_process_frame_connector.h
@@ -12,6 +12,7 @@
#include "components/viz/common/surfaces/surface_id.h"
#include "content/browser/renderer_host/frame_connector_delegate.h"
#include "content/common/content_export.h"
+#include "content/common/frame_resize_params.h"
namespace IPC {
class Message;
@@ -19,7 +20,6 @@ class Message;
namespace content {
class RenderFrameProxyHost;
-struct ScreenInfo;
// CrossProcessFrameConnector provides the platform view abstraction for
// RenderWidgetHostViewChildFrame allowing RWHVChildFrame to remain ignorant
@@ -100,6 +100,9 @@ class CONTENT_EXPORT CrossProcessFrameConnector
void FocusRootView() override;
bool LockMouse() override;
void UnlockMouse() override;
+ void EnableAutoResize(const gfx::Size& min_size,
+ const gfx::Size& max_size) override;
+ void DisableAutoResize() override;
bool IsInert() const override;
bool IsHidden() const override;
bool IsThrottled() const override;
@@ -130,12 +133,10 @@ class CONTENT_EXPORT CrossProcessFrameConnector
void ResetScreenSpaceRect();
// Handlers for messages received from the parent frame.
- void OnUpdateResizeParams(const gfx::Rect& screen_space_rect,
- const gfx::Size& local_frame_size,
- const ScreenInfo& screen_info,
- uint64_t sequence_number,
- const viz::SurfaceId& surface_id);
- void OnUpdateViewportIntersection(const gfx::Rect& viewport_intersection);
+ void OnUpdateResizeParams(const viz::SurfaceId& surface_id,
+ const FrameResizeParams& frame_resize_params);
+ void OnUpdateViewportIntersection(const gfx::Rect& viewport_intersection,
+ const gfx::Rect& compositor_visible_rect);
void OnVisibilityChanged(bool visible);
void OnSetIsInert(bool);
void OnUpdateRenderThrottlingStatus(bool is_throttled,
diff --git a/chromium/content/browser/frame_host/data_url_navigation_browsertest.cc b/chromium/content/browser/frame_host/data_url_navigation_browsertest.cc
index 87c9b51c7a7..02d8c983202 100644
--- a/chromium/content/browser/frame_host/data_url_navigation_browsertest.cc
+++ b/chromium/content/browser/frame_host/data_url_navigation_browsertest.cc
@@ -31,7 +31,7 @@
#include "net/base/escape.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/public/browser/plugin_service.h"
diff --git a/chromium/content/browser/frame_host/data_url_navigation_throttle.cc b/chromium/content/browser/frame_host/data_url_navigation_throttle.cc
index 4e1e7112990..2835bda8b7d 100644
--- a/chromium/content/browser/frame_host/data_url_navigation_throttle.cc
+++ b/chromium/content/browser/frame_host/data_url_navigation_throttle.cc
@@ -5,7 +5,6 @@
#include "content/browser/frame_host/data_url_navigation_throttle.h"
#include "base/feature_list.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/stringprintf.h"
#include "build/build_config.h"
#include "content/browser/frame_host/frame_tree.h"
@@ -33,18 +32,6 @@ DataUrlNavigationThrottle::~DataUrlNavigationThrottle() {}
NavigationThrottle::ThrottleCheckResult
DataUrlNavigationThrottle::WillProcessResponse() {
-#if defined(OS_ANDROID)
- // This should ideally be done in CreateThrottleForNavigation(), but
- // NavigationHandleImpl::GetRenderFrameHost() expects to not be run before
- // WillProcessResponse().
- // TODO(meacer): Remove this special case when PlzNavigate is enabled.
- if (!IsBrowserSideNavigationEnabled() &&
- navigation_handle()
- ->GetRenderFrameHost()
- ->IsDataUrlNavigationAllowedForAndroidWebView()) {
- return PROCEED;
- }
-#endif
NavigationHandleImpl* handle =
static_cast<NavigationHandleImpl*>(navigation_handle());
if (handle->IsDownload())
diff --git a/chromium/content/browser/frame_host/debug_urls.cc b/chromium/content/browser/frame_host/debug_urls.cc
index 46954327b9c..f66e16a2ebc 100644
--- a/chromium/content/browser/frame_host/debug_urls.cc
+++ b/chromium/content/browser/frame_host/debug_urls.cc
@@ -4,10 +4,6 @@
#include "content/browser/frame_host/debug_urls.h"
-#if defined(SYZYASAN)
-#include <windows.h>
-#endif
-
#include <vector>
#include "base/command_line.h"
@@ -16,12 +12,13 @@
#include "base/strings/utf_string_conversions.h"
#include "base/synchronization/waitable_event.h"
#include "base/threading/thread_restrictions.h"
+#include "build/build_config.h"
#include "cc/base/switches.h"
#include "content/browser/gpu/gpu_process_host.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/url_constants.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#include "url/gurl.h"
#if BUILDFLAG(ENABLE_PLUGINS)
@@ -43,7 +40,8 @@ const char kAsanCrashDomain[] = "crash";
const char kAsanHeapOverflow[] = "/browser-heap-overflow";
const char kAsanHeapUnderflow[] = "/browser-heap-underflow";
const char kAsanUseAfterFree[] = "/browser-use-after-free";
-#if defined(SYZYASAN)
+
+#if defined(OS_WIN)
const char kAsanCorruptHeapBlock[] = "/browser-corrupt-heap-block";
const char kAsanCorruptHeap[] = "/browser-corrupt-heap";
#endif
@@ -66,11 +64,6 @@ void HandlePpapiFlashDebugURL(const GURL& url) {
}
bool IsAsanDebugURL(const GURL& url) {
-#if defined(SYZYASAN)
- if (!base::debug::IsBinaryInstrumented())
- return false;
-#endif
-
if (!(url.is_valid() && url.SchemeIs(kChromeUIScheme) &&
url.DomainIs(kAsanCrashDomain) &&
url.has_path())) {
@@ -83,7 +76,7 @@ bool IsAsanDebugURL(const GURL& url) {
return true;
}
-#if defined(SYZYASAN)
+#if defined(OS_WIN)
if (url.path_piece() == kAsanCorruptHeapBlock ||
url.path_piece() == kAsanCorruptHeap) {
return true;
@@ -94,10 +87,8 @@ bool IsAsanDebugURL(const GURL& url) {
}
bool HandleAsanDebugURL(const GURL& url) {
-#if defined(SYZYASAN)
- if (!base::debug::IsBinaryInstrumented())
- return false;
-
+#if defined(ADDRESS_SANITIZER)
+#if defined(OS_WIN)
if (url.path_piece() == kAsanCorruptHeapBlock) {
base::debug::AsanCorruptHeapBlock();
return true;
@@ -105,9 +96,8 @@ bool HandleAsanDebugURL(const GURL& url) {
base::debug::AsanCorruptHeap();
return true;
}
-#endif
+#endif // OS_WIN
-#if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
if (url.path_piece() == kAsanHeapOverflow) {
base::debug::AsanHeapOverflow();
} else if (url.path_piece() == kAsanHeapUnderflow) {
diff --git a/chromium/content/browser/frame_host/frame_tree.cc b/chromium/content/browser/frame_host/frame_tree.cc
index ed4980321ab..5f7134c4f2b 100644
--- a/chromium/content/browser/frame_host/frame_tree.cc
+++ b/chromium/content/browser/frame_host/frame_tree.cc
@@ -28,7 +28,7 @@
#include "content/common/content_switches_internal.h"
#include "content/common/frame_owner_properties.h"
#include "content/common/input_messages.h"
-#include "third_party/WebKit/public/common/frame/frame_policy.h"
+#include "third_party/blink/public/common/frame/frame_policy.h"
namespace content {
@@ -183,7 +183,8 @@ bool FrameTree::AddFrame(
bool is_created_by_script,
const base::UnguessableToken& devtools_frame_token,
const blink::FramePolicy& frame_policy,
- const FrameOwnerProperties& frame_owner_properties) {
+ const FrameOwnerProperties& frame_owner_properties,
+ bool was_discarded) {
CHECK_NE(new_routing_id, MSG_ROUTING_NONE);
// A child frame always starts with an initial empty document, which means
@@ -207,6 +208,9 @@ bool FrameTree::AddFrame(
new_node->SetPendingFramePolicy(frame_policy);
new_node->CommitPendingFramePolicy();
+ if (was_discarded)
+ new_node->set_was_discarded();
+
// Add the new node to the FrameTree, creating the RenderFrameHost.
FrameTreeNode* added_node =
parent->AddChild(std::move(new_node), process_id, new_routing_id);
diff --git a/chromium/content/browser/frame_host/frame_tree.h b/chromium/content/browser/frame_host/frame_tree.h
index 37aede4aa03..3b24e06febd 100644
--- a/chromium/content/browser/frame_host/frame_tree.h
+++ b/chromium/content/browser/frame_host/frame_tree.h
@@ -141,7 +141,8 @@ class CONTENT_EXPORT FrameTree {
bool is_created_by_script,
const base::UnguessableToken& devtools_frame_token,
const blink::FramePolicy& frame_policy,
- const FrameOwnerProperties& frame_owner_properties);
+ const FrameOwnerProperties& frame_owner_properties,
+ bool was_discarded);
// Removes a frame from the frame tree. |child|, its children, and objects
// owned by their RenderFrameHostManagers are immediately deleted. The root
diff --git a/chromium/content/browser/frame_host/frame_tree_browsertest.cc b/chromium/content/browser/frame_host/frame_tree_browsertest.cc
index 13a8faefcd2..13d191c9ebd 100644
--- a/chromium/content/browser/frame_host/frame_tree_browsertest.cc
+++ b/chromium/content/browser/frame_host/frame_tree_browsertest.cc
@@ -24,7 +24,7 @@
#include "content/test/content_browser_test_utils_internal.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
-#include "third_party/WebKit/public/common/frame/sandbox_flags.h"
+#include "third_party/blink/public/common/frame/sandbox_flags.h"
#include "url/url_constants.h"
namespace content {
@@ -131,8 +131,8 @@ IN_PROC_BROWSER_TEST_F(FrameTreeBrowserTest, FrameTreeAfterCrash) {
RenderProcessHostWatcher crash_observer(
shell()->web_contents(),
RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
- ASSERT_TRUE(shell()->web_contents()->GetMainFrame()->GetProcess()->Shutdown(
- 0, false));
+ ASSERT_TRUE(
+ shell()->web_contents()->GetMainFrame()->GetProcess()->Shutdown(0));
crash_observer.Wait();
// The frame tree should be cleared.
diff --git a/chromium/content/browser/frame_host/frame_tree_node.cc b/chromium/content/browser/frame_host/frame_tree_node.cc
index 84ab765935c..fc076ea5376 100644
--- a/chromium/content/browser/frame_host/frame_tree_node.cc
+++ b/chromium/content/browser/frame_host/frame_tree_node.cc
@@ -11,7 +11,6 @@
#include "base/lazy_instance.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
@@ -24,7 +23,7 @@
#include "content/common/frame_messages.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/browser_side_navigation_policy.h"
-#include "third_party/WebKit/public/common/frame/sandbox_flags.h"
+#include "third_party/blink/public/common/frame/sandbox_flags.h"
namespace content {
@@ -146,6 +145,7 @@ FrameTreeNode::FrameTreeNode(FrameTree* frame_tree,
manager_delegate),
frame_tree_node_id_(next_frame_tree_node_id_++),
parent_(parent),
+ depth_(parent ? parent->depth_ + 1 : 0u),
opener_(nullptr),
original_opener_(nullptr),
has_committed_real_load_(false),
@@ -163,6 +163,7 @@ FrameTreeNode::FrameTreeNode(FrameTree* frame_tree,
is_created_by_script_(is_created_by_script),
devtools_frame_token_(devtools_frame_token),
frame_owner_properties_(frame_owner_properties),
+ was_discarded_(false),
blame_context_(frame_tree_node_id_, parent) {
std::pair<FrameTreeNodeIdMap::iterator, bool> result =
g_frame_tree_node_id_map.Get().insert(
@@ -489,6 +490,10 @@ void FrameTreeNode::CreatedNavigationRequest(
}
navigation_request_ = std::move(navigation_request);
+ if (was_discarded_) {
+ navigation_request_->set_was_discarded();
+ was_discarded_ = false;
+ }
render_manager()->DidCreateNavigationRequest(navigation_request_.get());
bool to_different_document = !FrameMsg_Navigate_Type::IsSameDocument(
@@ -598,7 +603,8 @@ bool FrameTreeNode::StopLoading() {
expected_pending_nav_entry_id =
navigation_request_->navigation_handle()->pending_nav_entry_id();
}
- navigator_->DiscardPendingEntryIfNeeded(expected_pending_nav_entry_id);
+ navigator_->DiscardPendingEntryIfNeeded(expected_pending_nav_entry_id,
+ false /* is_download */);
}
ResetNavigationRequest(false, true);
}
diff --git a/chromium/content/browser/frame_host/frame_tree_node.h b/chromium/content/browser/frame_host/frame_tree_node.h
index b1f9c6a0846..db49e3691d9 100644
--- a/chromium/content/browser/frame_host/frame_tree_node.h
+++ b/chromium/content/browser/frame_host/frame_tree_node.h
@@ -20,8 +20,8 @@
#include "content/common/content_export.h"
#include "content/common/frame_owner_properties.h"
#include "content/common/frame_replication_state.h"
-#include "third_party/WebKit/public/common/frame/frame_policy.h"
-#include "third_party/WebKit/public/platform/WebInsecureRequestPolicy.h"
+#include "third_party/blink/public/common/frame/frame_policy.h"
+#include "third_party/blink/public/platform/web_insecure_request_policy.h"
#include "url/gurl.h"
#include "url/origin.h"
@@ -126,6 +126,8 @@ class CONTENT_EXPORT FrameTreeNode {
return children_.size();
}
+ unsigned int depth() const { return depth_; }
+
FrameTreeNode* parent() const { return parent_; }
FrameTreeNode* opener() const { return opener_; }
@@ -370,6 +372,14 @@ class CONTENT_EXPORT FrameTreeNode {
return replication_state_.has_received_user_gesture;
}
+ // When a tab is discarded, WebContents sets was_discarded on its
+ // root FrameTreeNode.
+ // In addition, when a child frame is created, this bit is passed on from
+ // parent to child.
+ // When a navigation request is created, was_discarded is passed on to the
+ // request and reset to false in FrameTreeNode.
+ void set_was_discarded() { was_discarded_ = true; }
+
private:
FRIEND_TEST_ALL_PREFIXES(SitePerProcessFeaturePolicyBrowserTest,
ContainerPolicyDynamic);
@@ -403,6 +413,9 @@ class CONTENT_EXPORT FrameTreeNode {
// The parent node of this frame. |nullptr| if this node is the root.
FrameTreeNode* const parent_;
+ // Number of edges from this node to the root. 0 if this is the root.
+ const unsigned int depth_;
+
// The frame that opened this frame, if any. Will be set to null if the
// opener is closed, or if this frame disowns its opener by setting its
// window.opener to null.
@@ -477,6 +490,8 @@ class CONTENT_EXPORT FrameTreeNode {
base::TimeTicks last_focus_time_;
+ bool was_discarded_;
+
// A helper for tracing the snapshots of this FrameTreeNode and attributing
// browser process activities to this node (when possible). It is unrelated
// to the core logic of FrameTreeNode.
diff --git a/chromium/content/browser/frame_host/frame_tree_node_blame_context_unittest.cc b/chromium/content/browser/frame_host/frame_tree_node_blame_context_unittest.cc
index 330872e001b..5e9ee40d23a 100644
--- a/chromium/content/browser/frame_host/frame_tree_node_blame_context_unittest.cc
+++ b/chromium/content/browser/frame_host/frame_tree_node_blame_context_unittest.cc
@@ -17,7 +17,7 @@
#include "content/test/test_render_view_host.h"
#include "content/test/test_web_contents.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/common/frame/frame_policy.h"
+#include "third_party/blink/public/common/frame/frame_policy.h"
namespace content {
@@ -103,7 +103,7 @@ class FrameTreeNodeBlameContextTest : public RenderViewHostImplTestHarness {
blink::WebTreeScopeType::kDocument, std::string(),
base::StringPrintf("uniqueName%d", child_id), false,
base::UnguessableToken::Create(), blink::FramePolicy(),
- FrameOwnerProperties());
+ FrameOwnerProperties(), false);
FrameTreeNode* child = node->child_at(child_num - 1);
consumption += CreateSubframes(child, child_id, shape + consumption);
}
diff --git a/chromium/content/browser/frame_host/frame_tree_unittest.cc b/chromium/content/browser/frame_host/frame_tree_unittest.cc
index ee9e8de6f24..40a35831d96 100644
--- a/chromium/content/browser/frame_host/frame_tree_unittest.cc
+++ b/chromium/content/browser/frame_host/frame_tree_unittest.cc
@@ -1,4 +1,4 @@
-// Copyright 2013 The Chromium Authors. All rights reserved.
+// Copyright 2013 The Chromium Authors.All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@@ -24,7 +24,7 @@
#include "content/test/test_render_view_host.h"
#include "content/test/test_web_contents.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/common/frame/frame_policy.h"
+#include "third_party/blink/public/common/frame/frame_policy.h"
namespace content {
@@ -166,32 +166,32 @@ TEST_F(FrameTreeTest, Shape) {
CreateStubInterfaceProviderRequest(),
blink::WebTreeScopeType::kDocument, std::string(),
"uniqueName0", false, base::UnguessableToken::Create(),
- blink::FramePolicy(), FrameOwnerProperties());
+ blink::FramePolicy(), FrameOwnerProperties(), false);
frame_tree->AddFrame(root, process_id, 15,
CreateStubInterfaceProviderRequest(),
blink::WebTreeScopeType::kDocument, std::string(),
"uniqueName1", false, base::UnguessableToken::Create(),
- blink::FramePolicy(), FrameOwnerProperties());
+ blink::FramePolicy(), FrameOwnerProperties(), false);
frame_tree->AddFrame(root, process_id, 16,
CreateStubInterfaceProviderRequest(),
blink::WebTreeScopeType::kDocument, std::string(),
"uniqueName2", false, base::UnguessableToken::Create(),
- blink::FramePolicy(), FrameOwnerProperties());
+ blink::FramePolicy(), FrameOwnerProperties(), false);
frame_tree->AddFrame(root->child_at(0), process_id, 244,
CreateStubInterfaceProviderRequest(),
blink::WebTreeScopeType::kDocument, std::string(),
"uniqueName3", false, base::UnguessableToken::Create(),
- blink::FramePolicy(), FrameOwnerProperties());
+ blink::FramePolicy(), FrameOwnerProperties(), false);
frame_tree->AddFrame(root->child_at(1), process_id, 255,
CreateStubInterfaceProviderRequest(),
blink::WebTreeScopeType::kDocument, no_children_node,
"uniqueName4", false, base::UnguessableToken::Create(),
- blink::FramePolicy(), FrameOwnerProperties());
+ blink::FramePolicy(), FrameOwnerProperties(), false);
frame_tree->AddFrame(root->child_at(0), process_id, 245,
CreateStubInterfaceProviderRequest(),
blink::WebTreeScopeType::kDocument, std::string(),
"uniqueName5", false, base::UnguessableToken::Create(),
- blink::FramePolicy(), FrameOwnerProperties());
+ blink::FramePolicy(), FrameOwnerProperties(), false);
EXPECT_EQ(
"2: [14: [244: [], 245: []], "
@@ -204,49 +204,49 @@ TEST_F(FrameTreeTest, Shape) {
CreateStubInterfaceProviderRequest(),
blink::WebTreeScopeType::kDocument, std::string(),
"uniqueName6", false, base::UnguessableToken::Create(),
- blink::FramePolicy(), FrameOwnerProperties());
+ blink::FramePolicy(), FrameOwnerProperties(), false);
frame_tree->AddFrame(child_16, process_id, 265,
CreateStubInterfaceProviderRequest(),
blink::WebTreeScopeType::kDocument, std::string(),
"uniqueName7", false, base::UnguessableToken::Create(),
- blink::FramePolicy(), FrameOwnerProperties());
+ blink::FramePolicy(), FrameOwnerProperties(), false);
frame_tree->AddFrame(child_16, process_id, 266,
CreateStubInterfaceProviderRequest(),
blink::WebTreeScopeType::kDocument, std::string(),
"uniqueName8", false, base::UnguessableToken::Create(),
- blink::FramePolicy(), FrameOwnerProperties());
+ blink::FramePolicy(), FrameOwnerProperties(), false);
frame_tree->AddFrame(child_16, process_id, 267,
CreateStubInterfaceProviderRequest(),
blink::WebTreeScopeType::kDocument, deep_subtree,
"uniqueName9", false, base::UnguessableToken::Create(),
- blink::FramePolicy(), FrameOwnerProperties());
+ blink::FramePolicy(), FrameOwnerProperties(), false);
frame_tree->AddFrame(child_16, process_id, 268,
CreateStubInterfaceProviderRequest(),
blink::WebTreeScopeType::kDocument, std::string(),
"uniqueName10", false, base::UnguessableToken::Create(),
- blink::FramePolicy(), FrameOwnerProperties());
+ blink::FramePolicy(), FrameOwnerProperties(), false);
FrameTreeNode* child_267 = child_16->child_at(3);
frame_tree->AddFrame(child_267, process_id, 365,
CreateStubInterfaceProviderRequest(),
blink::WebTreeScopeType::kDocument, std::string(),
"uniqueName11", false, base::UnguessableToken::Create(),
- blink::FramePolicy(), FrameOwnerProperties());
+ blink::FramePolicy(), FrameOwnerProperties(), false);
frame_tree->AddFrame(child_267->child_at(0), process_id, 455,
CreateStubInterfaceProviderRequest(),
blink::WebTreeScopeType::kDocument, std::string(),
"uniqueName12", false, base::UnguessableToken::Create(),
- blink::FramePolicy(), FrameOwnerProperties());
+ blink::FramePolicy(), FrameOwnerProperties(), false);
frame_tree->AddFrame(child_267->child_at(0)->child_at(0), process_id, 555,
CreateStubInterfaceProviderRequest(),
blink::WebTreeScopeType::kDocument, std::string(),
"uniqueName13", false, base::UnguessableToken::Create(),
- blink::FramePolicy(), FrameOwnerProperties());
+ blink::FramePolicy(), FrameOwnerProperties(), false);
frame_tree->AddFrame(child_267->child_at(0)->child_at(0)->child_at(0),
process_id, 655, CreateStubInterfaceProviderRequest(),
blink::WebTreeScopeType::kDocument, std::string(),
"uniqueName14", false, base::UnguessableToken::Create(),
- blink::FramePolicy(), FrameOwnerProperties());
+ blink::FramePolicy(), FrameOwnerProperties(), false);
// Now that's it's fully built, verify the tree structure is as expected.
EXPECT_EQ(
@@ -505,7 +505,7 @@ TEST_F(FrameTreeTest, FailAddFrameWithWrongProcessId) {
root, process_id + 1, 1, CreateStubInterfaceProviderRequest(),
blink::WebTreeScopeType::kDocument, std::string(), "uniqueName0", false,
base::UnguessableToken::Create(), blink::FramePolicy(),
- FrameOwnerProperties()));
+ FrameOwnerProperties(), false));
ASSERT_EQ("2: []", GetTreeState(frame_tree));
}
diff --git a/chromium/content/browser/frame_host/input/legacy_ipc_frame_input_handler.cc b/chromium/content/browser/frame_host/input/legacy_ipc_frame_input_handler.cc
index 592c24ee194..9c14f5735ff 100644
--- a/chromium/content/browser/frame_host/input/legacy_ipc_frame_input_handler.cc
+++ b/chromium/content/browser/frame_host/input/legacy_ipc_frame_input_handler.cc
@@ -22,19 +22,9 @@ void LegacyIPCFrameInputHandler::SetCompositionFromExistingText(
int32_t start,
int32_t end,
const std::vector<ui::ImeTextSpan>& ui_ime_text_spans) {
- std::vector<blink::WebImeTextSpan> ime_text_spans;
- for (const auto& ime_text_span : ui_ime_text_spans) {
- blink::WebImeTextSpan blink_ime_text_span(
- ConvertUiImeTextSpanTypeToWebType(ime_text_span.type),
- ime_text_span.start_offset, ime_text_span.end_offset,
- ime_text_span.underline_color, ime_text_span.thick,
- ime_text_span.background_color,
- ime_text_span.suggestion_highlight_color, ime_text_span.suggestions);
- ime_text_spans.push_back(blink_ime_text_span);
- }
-
SendInput(std::make_unique<InputMsg_SetCompositionFromExistingText>(
- routing_id_, start, end, ime_text_spans));
+ routing_id_, start, end,
+ ConvertUiImeTextSpansToBlinkImeTextSpans(ui_ime_text_spans)));
}
void LegacyIPCFrameInputHandler::ExtendSelectionAndDelete(int32_t before,
diff --git a/chromium/content/browser/frame_host/interstitial_page_impl.cc b/chromium/content/browser/frame_host/interstitial_page_impl.cc
index 7c83d2a63b2..af9c604d578 100644
--- a/chromium/content/browser/frame_host/interstitial_page_impl.cc
+++ b/chromium/content/browser/frame_host/interstitial_page_impl.cc
@@ -38,7 +38,7 @@
#include "content/browser/site_instance_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/browser/web_contents/web_contents_view.h"
-#include "content/common/features.h"
+#include "content/common/buildflags.h"
#include "content/common/frame_messages.h"
#include "content/common/input_messages.h"
#include "content/common/view_messages.h"
@@ -548,6 +548,10 @@ const std::string& InterstitialPageImpl::GetUserAgentOverride() const {
return base::EmptyString();
}
+bool InterstitialPageImpl::ShouldOverrideUserAgentInNewTabs() {
+ return false;
+}
+
bool InterstitialPageImpl::ShowingInterstitialPage() const {
// An interstitial page never shows a second interstitial.
return false;
diff --git a/chromium/content/browser/frame_host/interstitial_page_impl.h b/chromium/content/browser/frame_host/interstitial_page_impl.h
index ea080f0f68f..79df2f4834c 100644
--- a/chromium/content/browser/frame_host/interstitial_page_impl.h
+++ b/chromium/content/browser/frame_host/interstitial_page_impl.h
@@ -97,6 +97,7 @@ class CONTENT_EXPORT InterstitialPageImpl : public InterstitialPage,
// NavigatorDelegate implementation.
WebContents* OpenURL(const OpenURLParams& params) override;
const std::string& GetUserAgentOverride() const override;
+ bool ShouldOverrideUserAgentInNewTabs() override;
bool ShowingInterstitialPage() const override;
protected:
diff --git a/chromium/content/browser/frame_host/interstitial_page_impl_browsertest.cc b/chromium/content/browser/frame_host/interstitial_page_impl_browsertest.cc
index 7e2eaff3476..37108eea53e 100644
--- a/chromium/content/browser/frame_host/interstitial_page_impl_browsertest.cc
+++ b/chromium/content/browser/frame_host/interstitial_page_impl_browsertest.cc
@@ -21,7 +21,7 @@
#include "content/public/test/test_utils.h"
#include "content/shell/browser/shell.h"
#include "ipc/message_filter.h"
-#include "third_party/WebKit/public/mojom/clipboard/clipboard.mojom.h"
+#include "third_party/blink/public/mojom/clipboard/clipboard.mojom.h"
#include "ui/base/clipboard/clipboard_monitor.h"
#include "ui/base/clipboard/clipboard_observer.h"
diff --git a/chromium/content/browser/frame_host/keep_alive_handle_factory.cc b/chromium/content/browser/frame_host/keep_alive_handle_factory.cc
index ceb21ec514f..a68870d4572 100644
--- a/chromium/content/browser/frame_host/keep_alive_handle_factory.cc
+++ b/chromium/content/browser/frame_host/keep_alive_handle_factory.cc
@@ -21,7 +21,8 @@ class KeepAliveHandleFactory::Context final : public base::RefCounted<Context> {
explicit Context(RenderProcessHost* process_host)
: process_id_(process_host->GetID()), weak_ptr_factory_(this) {
DCHECK(!process_host->IsKeepAliveRefCountDisabled());
- process_host->IncrementKeepAliveRefCount();
+ process_host->IncrementKeepAliveRefCount(
+ RenderProcessHost::KeepAliveClientType::kFetch);
}
void Detach() {
@@ -32,27 +33,16 @@ class KeepAliveHandleFactory::Context final : public base::RefCounted<Context> {
if (!process_host || process_host->IsKeepAliveRefCountDisabled())
return;
- process_host->DecrementKeepAliveRefCount();
+ process_host->DecrementKeepAliveRefCount(
+ RenderProcessHost::KeepAliveClientType::kFetch);
}
void DetachLater() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
- auto timeout = timeout_;
- int timeout_set_by_finch_in_sec = base::GetFieldTrialParamByFeatureAsInt(
- features::kKeepAliveRendererForKeepaliveRequests, "timeout_in_sec",
- timeout.InSeconds());
- // Adopt only "reasonable" values.
- if (timeout_set_by_finch_in_sec > 0 && timeout_set_by_finch_in_sec <= 60) {
- timeout = base::TimeDelta::FromSeconds(timeout_set_by_finch_in_sec);
- } else {
- DVLOG(0) << "'timeout_in_sec' param for "
- << "'keep-alive-renderer-for-keepalive-requests' is ignored "
- << "due to out of range.";
- }
BrowserThread::PostDelayedTask(
BrowserThread::UI, FROM_HERE,
base::BindOnce(&Context::Detach, weak_ptr_factory_.GetWeakPtr()),
- timeout);
+ timeout_);
}
void AddBinding(std::unique_ptr<mojom::KeepAliveHandle> impl,
diff --git a/chromium/content/browser/frame_host/mixed_content_navigation_throttle.h b/chromium/content/browser/frame_host/mixed_content_navigation_throttle.h
index 7cad03b202a..4c884abf890 100644
--- a/chromium/content/browser/frame_host/mixed_content_navigation_throttle.h
+++ b/chromium/content/browser/frame_host/mixed_content_navigation_throttle.h
@@ -13,7 +13,7 @@
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/navigation_throttle.h"
#include "content/public/common/request_context_type.h"
-#include "third_party/WebKit/public/platform/WebMixedContentContextType.h"
+#include "third_party/blink/public/platform/web_mixed_content_context_type.h"
namespace content {
diff --git a/chromium/content/browser/frame_host/navigation_controller_impl.cc b/chromium/content/browser/frame_host/navigation_controller_impl.cc
index ff1d3fcb6eb..475a2bd192d 100644
--- a/chromium/content/browser/frame_host/navigation_controller_impl.cc
+++ b/chromium/content/browser/frame_host/navigation_controller_impl.cc
@@ -80,7 +80,7 @@
#include "media/base/mime_util.h"
#include "net/base/escape.h"
#include "skia/ext/platform_canvas.h"
-#include "third_party/WebKit/public/common/mime_util/mime_util.h"
+#include "third_party/blink/public/common/mime_util/mime_util.h"
#include "url/url_constants.h"
namespace content {
diff --git a/chromium/content/browser/frame_host/navigation_controller_impl_browsertest.cc b/chromium/content/browser/frame_host/navigation_controller_impl_browsertest.cc
index c1f61006c26..ee48fdd3405 100644
--- a/chromium/content/browser/frame_host/navigation_controller_impl_browsertest.cc
+++ b/chromium/content/browser/frame_host/navigation_controller_impl_browsertest.cc
@@ -11,6 +11,7 @@
#include "base/bind.h"
#include "base/command_line.h"
+#include "base/files/scoped_temp_dir.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
@@ -19,6 +20,7 @@
#include "base/strings/utf_string_conversions.h"
#include "base/test/histogram_tester.h"
#include "base/threading/sequenced_task_runner_handle.h"
+#include "base/threading/thread_restrictions.h"
#include "build/build_config.h"
#include "content/browser/frame_host/frame_navigation_entry.h"
#include "content/browser/frame_host/frame_tree.h"
@@ -28,10 +30,13 @@
#include "content/browser/frame_host/render_frame_host_impl.h"
#include "content/browser/loader/resource_dispatcher_host_impl.h"
#include "content/browser/renderer_host/display_util.h"
+#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/browser/web_contents/web_contents_view.h"
#include "content/common/frame_messages.h"
#include "content/common/page_state_serialization.h"
+#include "content/public/browser/browser_context.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/resource_dispatcher_host.h"
@@ -49,9 +54,11 @@
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
+#include "content/public/test/download_test_observer.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_utils.h"
#include "content/shell/browser/shell.h"
+#include "content/shell/browser/shell_download_manager_delegate.h"
#include "content/shell/common/shell_switches.h"
#include "content/test/content_browser_test_utils_internal.h"
#include "content/test/did_commit_provisional_load_interceptor.h"
@@ -4051,9 +4058,6 @@ IN_PROC_BROWSER_TEST_F(NavigationControllerBrowserTest,
// replaced data.
IN_PROC_BROWSER_TEST_F(NavigationControllerBrowserTest,
ReplacedNavigationEntryData_ClientSideRedirect) {
- FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
- ->GetFrameTree()
- ->root();
const NavigationControllerImpl& controller =
static_cast<const NavigationControllerImpl&>(
shell()->web_contents()->GetController());
@@ -4063,11 +4067,13 @@ IN_PROC_BROWSER_TEST_F(NavigationControllerBrowserTest,
"/navigation_controller/simple_page_1.html"));
{
- // Load the redirecting page.
- FrameNavigateParamsCapturer capturer(root);
- capturer.set_navigations_remaining(2);
- ASSERT_TRUE(NavigateToURL(shell(), url1));
- capturer.Wait();
+ TestNavigationManager navigation_manager_1(shell()->web_contents(), url1);
+ TestNavigationManager navigation_manager_2(shell()->web_contents(), url2);
+
+ shell()->LoadURL(url1);
+
+ navigation_manager_1.WaitForNavigationFinished(); // Initial navigation.
+ navigation_manager_2.WaitForNavigationFinished(); // Client-side redirect.
ASSERT_EQ(1, controller.GetEntryCount());
NavigationEntry* entry1 = controller.GetEntryAtIndex(0);
@@ -4591,7 +4597,7 @@ IN_PROC_BROWSER_TEST_F(NavigationControllerBrowserTest,
shell()->web_contents()->GetMainFrame()->GetProcess();
RenderProcessHostWatcher crash_observer(
process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
- process->Shutdown(0, false);
+ process->Shutdown(0);
crash_observer.Wait();
{
TestNavigationObserver back_load_observer(shell()->web_contents());
@@ -6853,7 +6859,7 @@ class AllowDialogIPCOnCommitFilter : public BrowserMessageFilter,
using WebContentsObserver::Observe;
- void SetCallback(Callback callback) { callback_ = callback; }
+ void SetCallback(Callback callback) { callback_ = std::move(callback); }
private:
void DidFinishNavigation(NavigationHandle* navigation_handle) override {
@@ -7812,6 +7818,79 @@ IN_PROC_BROWSER_TEST_F(
EXPECT_EQ(0U, entry->root_node()->children[0]->children.size());
}
+// This test supplements SpareRenderProcessHostUnitTest to verify that the spare
+// RenderProcessHost is actually used in cross-process navigations.
+IN_PROC_BROWSER_TEST_F(NavigationControllerBrowserTest,
+ UtilizationOfSpareRenderProcessHost) {
+ GURL first_url = embedded_test_server()->GetURL("a.com", "/title1.html");
+ GURL second_url = embedded_test_server()->GetURL("b.com", "/title2.html");
+ RenderProcessHost* prev_spare = nullptr;
+ RenderProcessHost* curr_spare = nullptr;
+ RenderProcessHost* prev_host = nullptr;
+ RenderProcessHost* curr_host = nullptr;
+
+ // In the current implementation the spare is not warmed-up until the first
+ // real navigation. It might be okay to change that in the future.
+ curr_spare = RenderProcessHostImpl::GetSpareRenderProcessHostForTesting();
+ curr_host = shell()->web_contents()->GetMainFrame()->GetProcess();
+ EXPECT_FALSE(curr_spare);
+
+ // Navigate to the first URL.
+ prev_host = curr_host;
+ prev_spare = curr_spare;
+ EXPECT_TRUE(NavigateToURL(shell(), first_url));
+ curr_spare = RenderProcessHostImpl::GetSpareRenderProcessHostForTesting();
+ curr_host = shell()->web_contents()->GetMainFrame()->GetProcess();
+ EXPECT_NE(curr_spare, curr_host);
+ // No process swap when navigating away from the initial blank page.
+ EXPECT_EQ(prev_host, curr_host);
+ // We should always keep a spare RenderProcessHost around in site-per-process
+ // mode. We don't assert what should happen in other scenarios (to give
+ // flexibility to platform-specific decisions - e.g. on the desktop there
+ // might be no spare outside of site-per-process, but on Android the spare
+ // might still be opportunistically warmed up).
+ if (AreAllSitesIsolatedForTesting())
+ EXPECT_TRUE(curr_spare);
+
+ // Perform a cross-site omnibox navigation.
+ prev_host = curr_host;
+ prev_spare = curr_spare;
+ EXPECT_TRUE(NavigateToURL(shell(), second_url));
+ curr_spare = RenderProcessHostImpl::GetSpareRenderProcessHostForTesting();
+ curr_host = shell()->web_contents()->GetMainFrame()->GetProcess();
+ // The cross-site omnibox navigation should swap processes.
+ EXPECT_NE(prev_host, curr_host);
+ // If present, the spare RenderProcessHost should have been be used.
+ if (prev_spare)
+ EXPECT_EQ(prev_spare, curr_host);
+ // A new spare should be warmed-up in site-per-process mode.
+ if (AreAllSitesIsolatedForTesting()) {
+ EXPECT_TRUE(curr_spare);
+ EXPECT_NE(prev_spare, curr_spare);
+ }
+
+ // Perform a back navigation.
+ prev_host = curr_host;
+ prev_spare = curr_spare;
+ TestNavigationObserver back_load_observer(shell()->web_contents());
+ NavigationControllerImpl& controller = static_cast<NavigationControllerImpl&>(
+ shell()->web_contents()->GetController());
+ controller.GoBack();
+ back_load_observer.Wait();
+ curr_spare = RenderProcessHostImpl::GetSpareRenderProcessHostForTesting();
+ curr_host = shell()->web_contents()->GetMainFrame()->GetProcess();
+ // The cross-site back navigation should swap processes.
+ EXPECT_NE(prev_host, curr_host);
+ // If present, the spare RenderProcessHost should have been used.
+ if (prev_spare)
+ EXPECT_EQ(prev_spare, curr_host);
+ // A new spare should be warmed-up in site-per-process mode.
+ if (AreAllSitesIsolatedForTesting()) {
+ EXPECT_TRUE(curr_spare);
+ EXPECT_NE(prev_spare, curr_spare);
+ }
+}
+
class NavigationControllerControllableResponseBrowserTest
: public ContentBrowserTest {
protected:
@@ -8024,4 +8103,39 @@ IN_PROC_BROWSER_TEST_F(ContentBrowserTest, DataURLSameDocumentNavigation) {
EXPECT_TRUE(capturer.is_same_document());
}
+IN_PROC_BROWSER_TEST_F(ContentBrowserTest, HideDownloadFromUnmodifiedNewTab) {
+ GURL url("data:application/octet-stream,");
+
+ const NavigationControllerImpl& controller =
+ static_cast<const NavigationControllerImpl&>(
+ shell()->web_contents()->GetController());
+
+ {
+ base::ScopedAllowBlockingForTesting allow_blocking;
+ base::ScopedTempDir downloads_directory;
+ ASSERT_TRUE(downloads_directory.CreateUniqueTempDir());
+ DownloadManager* download_manager = BrowserContext::GetDownloadManager(
+ shell()->web_contents()->GetBrowserContext());
+ ShellDownloadManagerDelegate* download_delegate =
+ static_cast<ShellDownloadManagerDelegate*>(
+ download_manager->GetDelegate());
+ download_delegate->SetDownloadBehaviorForTesting(
+ downloads_directory.GetPath());
+
+ DownloadTestObserverTerminal observer(
+ download_manager, 1, DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL);
+
+ OpenURLParams params(url, Referrer(), WindowOpenDisposition::CURRENT_TAB,
+ ui::PAGE_TRANSITION_LINK, true);
+ params.suggested_filename = std::string("foo");
+
+ shell()->web_contents()->OpenURL(params);
+ WaitForLoadStop(shell()->web_contents());
+ observer.WaitForFinished();
+ }
+
+ EXPECT_FALSE(controller.GetPendingEntry());
+ EXPECT_FALSE(controller.GetVisibleEntry());
+}
+
} // namespace content
diff --git a/chromium/content/browser/frame_host/navigation_controller_impl_unittest.cc b/chromium/content/browser/frame_host/navigation_controller_impl_unittest.cc
index 81507d709e0..cfe018f6924 100644
--- a/chromium/content/browser/frame_host/navigation_controller_impl_unittest.cc
+++ b/chromium/content/browser/frame_host/navigation_controller_impl_unittest.cc
@@ -54,7 +54,7 @@
#include "services/network/public/cpp/resource_request_body.h"
#include "skia/ext/platform_canvas.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/common/frame/frame_policy.h"
+#include "third_party/blink/public/common/frame/frame_policy.h"
using base::Time;
@@ -1468,7 +1468,7 @@ TEST_F(NavigationControllerTest, ReloadOriginalRequestURL) {
EXPECT_EQ(0U, navigation_list_pruned_counter_);
main_test_rfh()->PrepareForCommitWithServerRedirect(final_url);
main_test_rfh()->SendNavigateWithModificationCallback(
- entry_id, true, final_url, set_original_url_callback);
+ entry_id, true, final_url, std::move(set_original_url_callback));
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
entry_id = controller.GetLastCommittedEntry()->GetUniqueID();
@@ -1526,7 +1526,7 @@ TEST_F(NavigationControllerTest,
EXPECT_EQ(0U, navigation_list_pruned_counter_);
main_test_rfh()->PrepareForCommitWithServerRedirect(final_url);
main_test_rfh()->SendNavigateWithModificationCallback(
- entry_id, true, final_url, set_original_url_callback);
+ entry_id, true, final_url, std::move(set_original_url_callback));
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
entry_id = controller.GetLastCommittedEntry()->GetUniqueID();
@@ -1636,8 +1636,8 @@ TEST_F(NavigationControllerTest, RedirectsAreNotResetByCommit) {
// Normal navigation will preserve redirects in the committed entry.
main_test_rfh()->PrepareForCommitWithServerRedirect(url2);
- main_test_rfh()->SendNavigateWithModificationCallback(entry_id, true, url1,
- set_redirects_callback);
+ main_test_rfh()->SendNavigateWithModificationCallback(
+ entry_id, true, url1, std::move(set_redirects_callback));
NavigationEntryImpl* committed_entry = controller.GetLastCommittedEntry();
ASSERT_EQ(1U, committed_entry->GetRedirectChain().size());
EXPECT_EQ(url2, committed_entry->GetRedirectChain()[0]);
diff --git a/chromium/content/browser/frame_host/navigation_entry_screenshot_manager.cc b/chromium/content/browser/frame_host/navigation_entry_screenshot_manager.cc
index 84ba9ad53bd..0b8b2df4b80 100644
--- a/chromium/content/browser/frame_host/navigation_entry_screenshot_manager.cc
+++ b/chromium/content/browser/frame_host/navigation_entry_screenshot_manager.cc
@@ -7,6 +7,7 @@
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/macros.h"
+#include "base/memory/ref_counted_memory.h"
#include "base/task_scheduler/post_task.h"
#include "content/browser/frame_host/navigation_controller_impl.h"
#include "content/browser/frame_host/navigation_entry_impl.h"
@@ -72,7 +73,7 @@ class ScreenshotData : public base::RefCountedThreadSafe<ScreenshotData> {
// Encode the A8 bitmap to grayscale PNG treating alpha as color intensity.
std::vector<unsigned char> data;
if (gfx::PNGCodec::EncodeA8SkBitmap(grayscale_bitmap, &data))
- data_ = new base::RefCountedBytes(data);
+ data_ = base::RefCountedBytes::TakeVector(&data);
}
scoped_refptr<base::RefCountedBytes> data_;
@@ -92,8 +93,10 @@ NavigationEntryScreenshotManager::~NavigationEntryScreenshotManager() {
}
void NavigationEntryScreenshotManager::TakeScreenshot() {
- if (OverscrollConfig::GetMode() != OverscrollConfig::Mode::kParallaxUi)
+ if (OverscrollConfig::GetHistoryNavigationMode() !=
+ OverscrollConfig::HistoryNavigationMode::kParallaxUi) {
return;
+ }
NavigationEntryImpl* entry = owner_->GetLastCommittedEntry();
if (!entry)
diff --git a/chromium/content/browser/frame_host/navigation_handle_impl.cc b/chromium/content/browser/frame_host/navigation_handle_impl.cc
index 2986bf0e340..0c0c4cbb9ef 100644
--- a/chromium/content/browser/frame_host/navigation_handle_impl.cc
+++ b/chromium/content/browser/frame_host/navigation_handle_impl.cc
@@ -57,19 +57,29 @@ void UpdateThrottleCheckResult(
*to_update = result;
}
-#define LOG_NAVIGATION_TIMING_HISTOGRAM(histogram, transition, value) \
- do { \
- UMA_HISTOGRAM_TIMES("Navigation." histogram, value); \
- if (transition & ui::PAGE_TRANSITION_FORWARD_BACK) { \
- UMA_HISTOGRAM_TIMES("Navigation." histogram ".BackForward", value); \
- } else if (ui::PageTransitionCoreTypeIs(transition, \
- ui::PAGE_TRANSITION_RELOAD)) { \
- UMA_HISTOGRAM_TIMES("Navigation." histogram ".Reload", value); \
- } else if (ui::PageTransitionIsNewNavigation(transition)) { \
- UMA_HISTOGRAM_TIMES("Navigation." histogram ".NewNavigation", value); \
- } else { \
- NOTREACHED() << "Invalid page transition: " << transition; \
- } \
+// TODO(csharrison,nasko): This macro is incorrect for subframe navigations,
+// which will only have subframe-specific transition types. This means that all
+// subframes currently are tagged as NewNavigations.
+#define LOG_NAVIGATION_TIMING_HISTOGRAM(histogram, transition, value, \
+ max_time) \
+ do { \
+ const base::TimeDelta kMinTime = base::TimeDelta::FromMilliseconds(1); \
+ const int kBuckets = 50; \
+ UMA_HISTOGRAM_CUSTOM_TIMES("Navigation." histogram, value, kMinTime, \
+ max_time, kBuckets); \
+ if (transition & ui::PAGE_TRANSITION_FORWARD_BACK) { \
+ UMA_HISTOGRAM_CUSTOM_TIMES("Navigation." histogram ".BackForward", \
+ value, kMinTime, max_time, kBuckets); \
+ } else if (ui::PageTransitionCoreTypeIs(transition, \
+ ui::PAGE_TRANSITION_RELOAD)) { \
+ UMA_HISTOGRAM_CUSTOM_TIMES("Navigation." histogram ".Reload", value, \
+ kMinTime, max_time, kBuckets); \
+ } else if (ui::PageTransitionIsNewNavigation(transition)) { \
+ UMA_HISTOGRAM_CUSTOM_TIMES("Navigation." histogram ".NewNavigation", \
+ value, kMinTime, max_time, kBuckets); \
+ } else { \
+ NOTREACHED() << "Invalid page transition: " << transition; \
+ } \
} while (0)
void LogIsSameProcess(ui::PageTransition transition, bool is_same_process) {
@@ -110,6 +120,7 @@ std::unique_ptr<NavigationHandleImpl> NavigationHandleImpl::Create(
const base::Optional<std::string>& suggested_filename,
std::unique_ptr<NavigationUIData> navigation_ui_data,
const std::string& method,
+ net::HttpRequestHeaders request_headers,
scoped_refptr<network::ResourceRequestBody> resource_request_body,
const Referrer& sanitized_referrer,
bool has_user_gesture,
@@ -122,9 +133,9 @@ std::unique_ptr<NavigationHandleImpl> NavigationHandleImpl::Create(
is_same_document, navigation_start, pending_nav_entry_id,
started_from_context_menu, should_check_main_world_csp,
is_form_submission, suggested_filename, std::move(navigation_ui_data),
- method, resource_request_body, sanitized_referrer, has_user_gesture,
- transition, is_external_protocol, request_context_type,
- mixed_content_context_type));
+ method, std::move(request_headers), resource_request_body,
+ sanitized_referrer, has_user_gesture, transition, is_external_protocol,
+ request_context_type, mixed_content_context_type));
}
NavigationHandleImpl::NavigationHandleImpl(
@@ -141,6 +152,7 @@ NavigationHandleImpl::NavigationHandleImpl(
const base::Optional<std::string>& suggested_filename,
std::unique_ptr<NavigationUIData> navigation_ui_data,
const std::string& method,
+ net::HttpRequestHeaders request_headers,
scoped_refptr<network::ResourceRequestBody> resource_request_body,
const Referrer& sanitized_referrer,
bool has_user_gesture,
@@ -163,8 +175,8 @@ NavigationHandleImpl::NavigationHandleImpl(
connection_info_(net::HttpResponseInfo::CONNECTION_INFO_UNKNOWN),
original_url_(url),
method_(method),
+ request_headers_(std::move(request_headers)),
state_(INITIAL),
- is_transferring_(false),
frame_tree_node_(frame_tree_node),
next_index_(0),
navigation_start_(navigation_start),
@@ -173,18 +185,20 @@ NavigationHandleImpl::NavigationHandleImpl(
mixed_content_context_type_(mixed_content_context_type),
navigation_ui_data_(std::move(navigation_ui_data)),
navigation_id_(CreateUniqueHandleID()),
- should_replace_current_entry_(false),
redirect_chain_(redirect_chain),
- is_download_(false),
- is_stream_(false),
- started_from_context_menu_(started_from_context_menu),
reload_type_(ReloadType::NONE),
restore_type_(RestoreType::NONE),
navigation_type_(NAVIGATION_TYPE_UNKNOWN),
should_check_main_world_csp_(should_check_main_world_csp),
- is_form_submission_(is_form_submission),
expected_render_process_host_id_(ChildProcessHost::kInvalidUniqueID),
suggested_filename_(suggested_filename),
+ is_transferring_(false),
+ is_form_submission_(is_form_submission),
+ should_replace_current_entry_(false),
+ is_download_(false),
+ is_stream_(false),
+ started_from_context_menu_(started_from_context_menu),
+ is_same_process_(true),
weak_factory_(this) {
TRACE_EVENT_ASYNC_BEGIN2("navigation", "NavigationHandle", this,
"frame_tree_node",
@@ -381,6 +395,10 @@ bool NavigationHandleImpl::IsSameDocument() {
return is_same_document_;
}
+const net::HttpRequestHeaders& NavigationHandleImpl::GetRequestHeaders() {
+ return request_headers_;
+}
+
const net::HttpResponseHeaders* NavigationHandleImpl::GetResponseHeaders() {
return response_headers_.get();
}
@@ -557,9 +575,17 @@ NavigationData* NavigationHandleImpl::GetNavigationData() {
return navigation_data_.get();
}
-void NavigationHandleImpl::SetOnDeferCallbackForTesting(
- const base::Closure& on_defer_callback) {
- on_defer_callback_for_testing_ = on_defer_callback;
+void NavigationHandleImpl::RegisterSubresourceOverride(
+ mojom::TransferrableURLLoaderPtr transferrable_loader) {
+ if (!transferrable_loader)
+ return;
+
+ NavigationRequest* request = frame_tree_node_->navigation_request();
+ if (!request)
+ request = frame_tree_node_->current_frame_host()->navigation_request();
+
+ if (request)
+ request->RegisterSubresourceOverride(std::move(transferrable_loader));
}
const GlobalRequestID& NavigationHandleImpl::GetGlobalRequestID() {
@@ -619,11 +645,8 @@ void NavigationHandleImpl::WillStartRequest(
navigation_ui_data_ = GetDelegate()->GetNavigationUIData(this);
// Notify each throttle of the request.
- base::Closure on_defer_callback_copy = on_defer_callback_for_testing_;
NavigationThrottle::ThrottleCheckResult result = CheckWillStartRequest();
if (result.action() == NavigationThrottle::DEFER) {
- if (!on_defer_callback_copy.is_null())
- on_defer_callback_copy.Run();
// DO NOT ADD CODE: the NavigationHandle might have been destroyed during
// one of the NavigationThrottle checks.
return;
@@ -696,11 +719,8 @@ void NavigationHandleImpl::WillRedirectRequest(
}
// Notify each throttle of the request.
- base::Closure on_defer_callback_copy = on_defer_callback_for_testing_;
NavigationThrottle::ThrottleCheckResult result = CheckWillRedirectRequest();
if (result.action() == NavigationThrottle::DEFER) {
- if (!on_defer_callback_copy.is_null())
- on_defer_callback_copy.Run();
// DO NOT ADD CODE: the NavigationHandle might have been destroyed during
// one of the NavigationThrottle checks.
return;
@@ -723,11 +743,8 @@ void NavigationHandleImpl::WillFailRequest(
state_ = WILL_FAIL_REQUEST;
// Notify each throttle of the request.
- base::Closure on_defer_callback_copy = on_defer_callback_for_testing_;
NavigationThrottle::ThrottleCheckResult result = CheckWillFailRequest();
if (result.action() == NavigationThrottle::DEFER) {
- if (!on_defer_callback_copy.is_null())
- on_defer_callback_copy.Run();
// DO NOT ADD CODE: the NavigationHandle might have been destroyed during
// one of the NavigationThrottle checks.
return;
@@ -766,11 +783,8 @@ void NavigationHandleImpl::WillProcessResponse(
complete_callback_ = callback;
// Notify each throttle of the response.
- base::Closure on_defer_callback_copy = on_defer_callback_for_testing_;
NavigationThrottle::ThrottleCheckResult result = CheckWillProcessResponse();
if (result.action() == NavigationThrottle::DEFER) {
- if (!on_defer_callback_copy.is_null())
- on_defer_callback_copy.Run();
// DO NOT ADD CODE: the NavigationHandle might have been destroyed during
// one of the NavigationThrottle checks.
return;
@@ -809,12 +823,25 @@ void NavigationHandleImpl::ReadyToCommitNavigation(
// Record metrics for the time it takes to get to this state from the
// beginning of the navigation.
if (!IsSameDocument() && !is_error) {
- LOG_NAVIGATION_TIMING_HISTOGRAM("TimeToReadyToCommit", transition_,
- ready_to_commit_time_ - navigation_start_);
- bool is_same_process =
+ is_same_process_ =
render_frame_host_->GetProcess()->GetID() ==
frame_tree_node_->current_frame_host()->GetProcess()->GetID();
- LogIsSameProcess(transition_, is_same_process);
+ LogIsSameProcess(transition_, is_same_process_);
+
+ // TODO(csharrison,nasko): Increase the max value to 3 minutes in M68 or
+ // M69.
+ base::TimeDelta delta = ready_to_commit_time_ - navigation_start_;
+ LOG_NAVIGATION_TIMING_HISTOGRAM("TimeToReadyToCommit", transition_, delta,
+ base::TimeDelta::FromSeconds(10));
+ if (is_same_process_) {
+ LOG_NAVIGATION_TIMING_HISTOGRAM("TimeToReadyToCommit.SameProcess",
+ transition_, delta,
+ base::TimeDelta::FromSeconds(10));
+ } else {
+ LOG_NAVIGATION_TIMING_HISTOGRAM("TimeToReadyToCommit.CrossProcess",
+ transition_, delta,
+ base::TimeDelta::FromSeconds(10));
+ }
}
SetExpectedProcess(render_frame_host->GetProcess());
@@ -857,12 +884,51 @@ void NavigationHandleImpl::DidCommitNavigation(
state_ = DID_COMMIT;
}
- // Record metrics for the time it takes to get from ReadyToCommit state
- // until this moment where the commit occurs.
- if (!ready_to_commit_time_.is_null() && !IsSameDocument() && !IsErrorPage()) {
- LOG_NAVIGATION_TIMING_HISTOGRAM(
- "ReadyToCommitUntilCommit", transition_,
- base::TimeTicks::Now() - ready_to_commit_time_);
+ // Record metrics for the time it took to commit the navigation if it was to
+ // another document without error.
+ if (!IsSameDocument() && !IsErrorPage()) {
+ base::TimeTicks now = base::TimeTicks::Now();
+ base::TimeDelta delta = now - navigation_start_;
+ ui::PageTransition transition = GetPageTransition();
+ // 3 minutes aligns with UMA_HISTOGRAM_MEDIUM_TIMES.
+ const base::TimeDelta kMaxTime = base::TimeDelta::FromMinutes(3);
+ LOG_NAVIGATION_TIMING_HISTOGRAM("StartToCommit", transition, delta,
+ kMaxTime);
+ if (IsInMainFrame()) {
+ LOG_NAVIGATION_TIMING_HISTOGRAM("StartToCommit.MainFrame", transition,
+ delta, kMaxTime);
+ } else {
+ LOG_NAVIGATION_TIMING_HISTOGRAM("StartToCommit.Subframe", transition,
+ delta, kMaxTime);
+ }
+ if (is_same_process_) {
+ LOG_NAVIGATION_TIMING_HISTOGRAM("StartToCommit.SameProcess", transition,
+ delta, kMaxTime);
+ if (IsInMainFrame()) {
+ LOG_NAVIGATION_TIMING_HISTOGRAM("StartToCommit.SameProcess.MainFrame",
+ transition, delta, kMaxTime);
+ } else {
+ LOG_NAVIGATION_TIMING_HISTOGRAM("StartToCommit.SameProcess.Subframe",
+ transition, delta, kMaxTime);
+ }
+ } else {
+ LOG_NAVIGATION_TIMING_HISTOGRAM("StartToCommit.CrossProcess", transition,
+ delta, kMaxTime);
+ if (IsInMainFrame()) {
+ LOG_NAVIGATION_TIMING_HISTOGRAM("StartToCommit.CrossProcess.MainFrame",
+ transition, delta, kMaxTime);
+ } else {
+ LOG_NAVIGATION_TIMING_HISTOGRAM("StartToCommit.CrossProcess.Subframe",
+ transition, delta, kMaxTime);
+ }
+ }
+
+ // 10 seconds aligns with UMA_HISTOGRAM_TIMES.
+ if (!ready_to_commit_time_.is_null()) {
+ LOG_NAVIGATION_TIMING_HISTOGRAM("ReadyToCommitUntilCommit", transition_,
+ now - ready_to_commit_time_,
+ base::TimeDelta::FromSeconds(10));
+ }
}
DCHECK(!IsInMainFrame() || navigation_entry_committed)
@@ -1118,12 +1184,9 @@ void NavigationHandleImpl::ResumeInternal() {
"Resume");
NavigationThrottle::ThrottleCheckResult result = NavigationThrottle::DEFER;
- base::Closure on_defer_callback_copy = on_defer_callback_for_testing_;
if (state_ == DEFERRING_START) {
result = CheckWillStartRequest();
if (result.action() == NavigationThrottle::DEFER) {
- if (!on_defer_callback_copy.is_null())
- on_defer_callback_copy.Run();
// DO NOT ADD CODE: the NavigationHandle might have been destroyed during
// one of the NavigationThrottle checks.
return;
@@ -1131,8 +1194,6 @@ void NavigationHandleImpl::ResumeInternal() {
} else if (state_ == DEFERRING_REDIRECT) {
result = CheckWillRedirectRequest();
if (result.action() == NavigationThrottle::DEFER) {
- if (!on_defer_callback_copy.is_null())
- on_defer_callback_copy.Run();
// DO NOT ADD CODE: the NavigationHandle might have been destroyed during
// one of the NavigationThrottle checks.
return;
@@ -1140,8 +1201,6 @@ void NavigationHandleImpl::ResumeInternal() {
} else if (state_ == DEFERRING_FAILURE) {
result = CheckWillFailRequest();
if (result.action() == NavigationThrottle::DEFER) {
- if (!on_defer_callback_copy.is_null())
- on_defer_callback_copy.Run();
// DO NOT ADD CODE: the NavigationHandle might have been destroyed during
// one of the NavigationThrottle checks.
return;
@@ -1149,8 +1208,6 @@ void NavigationHandleImpl::ResumeInternal() {
} else {
result = CheckWillProcessResponse();
if (result.action() == NavigationThrottle::DEFER) {
- if (!on_defer_callback_copy.is_null())
- on_defer_callback_copy.Run();
// DO NOT ADD CODE: the NavigationHandle might have been destroyed during
// one of the NavigationThrottle checks.
return;
@@ -1202,7 +1259,7 @@ void NavigationHandleImpl::RunCompleteCallback(
}
if (!callback.is_null())
- callback.Run(result);
+ std::move(callback).Run(result);
// No code after running the callback, as it might have resulted in our
// destruction.
diff --git a/chromium/content/browser/frame_host/navigation_handle_impl.h b/chromium/content/browser/frame_host/navigation_handle_impl.h
index fa25942b705..e2a7a8bd975 100644
--- a/chromium/content/browser/frame_host/navigation_handle_impl.h
+++ b/chromium/content/browser/frame_host/navigation_handle_impl.h
@@ -27,7 +27,7 @@
#include "content/public/browser/navigation_type.h"
#include "content/public/browser/restore_type.h"
#include "content/public/common/request_context_type.h"
-#include "third_party/WebKit/public/platform/WebMixedContentContextType.h"
+#include "third_party/blink/public/platform/web_mixed_content_context_type.h"
#include "url/gurl.h"
struct FrameHostMsg_DidCommitProvisionalLoad_Params;
@@ -69,6 +69,7 @@ class CONTENT_EXPORT NavigationHandleImpl : public NavigationHandle {
const base::Optional<std::string>& suggested_filename,
std::unique_ptr<NavigationUIData> navigation_ui_data,
const std::string& method = std::string(),
+ net::HttpRequestHeaders request_headers = net::HttpRequestHeaders(),
scoped_refptr<network::ResourceRequestBody> resource_request_body =
nullptr,
const Referrer& sanitized_referrer = content::Referrer(),
@@ -129,6 +130,7 @@ class CONTENT_EXPORT NavigationHandleImpl : public NavigationHandle {
bool ShouldUpdateHistory() override;
const GURL& GetPreviousURL() override;
net::HostPortPair GetSocketAddress() override;
+ const net::HttpRequestHeaders& GetRequestHeaders() override;
const net::HttpResponseHeaders* GetResponseHeaders() override;
net::HttpResponseInfo::ConnectionInfo GetConnectionInfo() override;
const net::SSLInfo& GetSSLInfo() override;
@@ -168,10 +170,11 @@ class CONTENT_EXPORT NavigationHandleImpl : public NavigationHandle {
NavigationThrottle::ThrottleCheckResult result);
NavigationData* GetNavigationData() override;
+ void RegisterSubresourceOverride(
+ mojom::TransferrableURLLoaderPtr transferrable_loader) override;
// Used in tests.
State state_for_testing() const { return state_; }
- void SetOnDeferCallbackForTesting(const base::Closure& on_defer_callback);
// The NavigatorDelegate to notify/query for various navigation events.
// Normally this is the WebContents, except if this NavigationHandle was
@@ -381,6 +384,7 @@ class CONTENT_EXPORT NavigationHandleImpl : public NavigationHandle {
const base::Optional<std::string>& suggested_filename,
std::unique_ptr<NavigationUIData> navigation_ui_data,
const std::string& method,
+ net::HttpRequestHeaders request_headers,
scoped_refptr<network::ResourceRequestBody> resource_request_body,
const Referrer& sanitized_referrer,
bool has_user_gesture,
@@ -456,6 +460,9 @@ class CONTENT_EXPORT NavigationHandleImpl : public NavigationHandle {
// The HTTP method used for the navigation.
std::string method_;
+ // The headers used for the request.
+ net::HttpRequestHeaders request_headers_;
+
// The POST body associated with this navigation. This will be null for GET
// and/or other non-POST requests (or if a response to a POST request was a
// redirect that changed the method to GET - for example 302).
@@ -464,10 +471,6 @@ class CONTENT_EXPORT NavigationHandleImpl : public NavigationHandle {
// The state the navigation is in.
State state_;
- // Whether the navigation is in the middle of a transfer. Set to false when
- // the DidStartProvisionalLoad is received from the new renderer.
- bool is_transferring_;
-
// The FrameTreeNode this navigation is happening in.
FrameTreeNode* frame_tree_node_;
@@ -523,19 +526,9 @@ class CONTENT_EXPORT NavigationHandleImpl : public NavigationHandle {
// The id of the URLRequest tied to this navigation.
GlobalRequestID request_id_;
- // Whether the current NavigationEntry should be replaced upon commit.
- bool should_replace_current_entry_;
-
// The chain of redirects.
std::vector<GURL> redirect_chain_;
- // Whether the navigation ended up being a download or a stream.
- bool is_download_;
- bool is_stream_;
-
- // False by default unless the navigation started within a context menu.
- bool started_from_context_menu_;
-
// Stores the reload type, or NONE if it's not a reload.
ReloadType reload_type_;
@@ -556,9 +549,6 @@ class CONTENT_EXPORT NavigationHandleImpl : public NavigationHandle {
// in the main world should not apply.
CSPDisposition should_check_main_world_csp_;
- // Whether or not the navigation results from the submission of a form.
- bool is_form_submission_;
-
// Information about the JavaScript that started the navigation. For
// navigations initiated by Javascript.
SourceLocation source_location_;
@@ -567,15 +557,31 @@ class CONTENT_EXPORT NavigationHandleImpl : public NavigationHandle {
// in it.
int expected_render_process_host_id_;
- // Used in tests. Called when the navigation is deferred by one of the
- // NavigationThrottles.
- base::Closure on_defer_callback_for_testing_;
-
// If this navigation was triggered by an anchor element with a download
// attribute, the |suggested_filename_| contains the attribute's (possibly
// empty) value.
base::Optional<std::string> suggested_filename_;
+ // Whether the navigation is in the middle of a transfer. Set to false when
+ // the DidStartProvisionalLoad is received from the new renderer.
+ bool is_transferring_;
+
+ // Whether or not the navigation results from the submission of a form.
+ bool is_form_submission_;
+
+ // Whether the current NavigationEntry should be replaced upon commit.
+ bool should_replace_current_entry_;
+
+ // Whether the navigation ended up being a download or a stream.
+ bool is_download_;
+ bool is_stream_;
+
+ // False by default unless the navigation started within a context menu.
+ bool started_from_context_menu_;
+
+ // Set in ReadyToCommitNavigation.
+ bool is_same_process_;
+
base::WeakPtrFactory<NavigationHandleImpl> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(NavigationHandleImpl);
diff --git a/chromium/content/browser/frame_host/navigation_handle_impl_browsertest.cc b/chromium/content/browser/frame_host/navigation_handle_impl_browsertest.cc
index 984943233b0..1e6c0406cf9 100644
--- a/chromium/content/browser/frame_host/navigation_handle_impl_browsertest.cc
+++ b/chromium/content/browser/frame_host/navigation_handle_impl_browsertest.cc
@@ -6,10 +6,12 @@
#include "base/files/scoped_temp_dir.h"
#include "base/memory/weak_ptr.h"
#include "base/strings/stringprintf.h"
+#include "base/test/histogram_tester.h"
#include "content/browser/frame_host/debug_urls.h"
#include "content/browser/frame_host/navigation_handle_impl.h"
#include "content/browser/frame_host/navigation_request.h"
#include "content/browser/web_contents/web_contents_impl.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/navigation_throttle.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
@@ -23,6 +25,7 @@
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/public/test/navigation_handle_observer.h"
+#include "content/public/test/test_frame_navigation_observer.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_utils.h"
#include "content/shell/browser/shell.h"
@@ -31,6 +34,7 @@
#include "content/test/content_browser_test_utils_internal.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/url_request/url_request_failed_job.h"
+#include "testing/gmock/include/gmock/gmock.h"
#include "ui/base/page_transition_types.h"
#include "url/url_constants.h"
@@ -1987,6 +1991,200 @@ IN_PROC_BROWSER_TEST_F(NavigationHandleImplBrowserTest,
}
}
+IN_PROC_BROWSER_TEST_F(NavigationHandleImplBrowserTest, StartToCommitMetrics) {
+ enum class FrameType {
+ kMain,
+ kSub,
+ };
+ enum class ProcessType {
+ kCross,
+ kSame,
+ };
+ enum class TransitionType {
+ kNew,
+ kReload,
+ kBackForward,
+ };
+
+ // Uses the provided ProcessType, FrameType, and TransitionType expected for
+ // this navigation to generate all combinations of Navigation.StartToCommit
+ // metrics.
+ auto check_navigation = [](const base::HistogramTester& histograms,
+ ProcessType process_type, FrameType frame_type,
+ TransitionType transition_type) {
+ const std::map<FrameType, std::string> kFrameSuffixes = {
+ {FrameType::kMain, ".MainFrame"}, {FrameType::kSub, ".Subframe"}};
+ const std::map<ProcessType, std::string> kProcessSuffixes = {
+ {ProcessType::kCross, ".CrossProcess"},
+ {ProcessType::kSame, ".SameProcess"}};
+ const std::map<TransitionType, std::string> kTransitionSuffixes = {
+ {TransitionType::kNew, ".NewNavigation"},
+ {TransitionType::kReload, ".Reload"},
+ {TransitionType::kBackForward, ".BackForward"},
+ };
+
+ // Add the suffix to all existing histogram names, and append the results to
+ // |names|.
+ std::vector<std::string> names{"Navigation.StartToCommit"};
+ auto add_suffix = [&names](std::string suffix) {
+ size_t original_size = names.size();
+ for (size_t i = 0; i < original_size; i++) {
+ names.push_back(names[i] + suffix);
+ }
+ };
+ add_suffix(kProcessSuffixes.at(process_type));
+ add_suffix(kFrameSuffixes.at(frame_type));
+ add_suffix(kTransitionSuffixes.at(transition_type));
+
+ // Check that all generated histogram names are logged exactly once.
+ for (const auto& name : names) {
+ histograms.ExpectTotalCount(name, 1);
+ }
+
+ // Check that no additional histograms with the StartToCommit prefix were
+ // logged.
+ base::HistogramTester::CountsMap counts =
+ histograms.GetTotalCountsForPrefix("Navigation.StartToCommit");
+ int32_t total_counts = 0;
+ for (const auto& it : counts) {
+ total_counts += it.second;
+ }
+ EXPECT_EQ(static_cast<int32_t>(names.size()), total_counts);
+ };
+
+ // Main frame tests.
+ IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess());
+ NavigateToURL(shell(), embedded_test_server()->GetURL("/hello.html"));
+ {
+ base::HistogramTester histograms;
+ GURL url(embedded_test_server()->GetURL("/title1.html"));
+ NavigateToURL(shell(), url);
+ check_navigation(histograms, ProcessType::kSame, FrameType::kMain,
+ TransitionType::kNew);
+ }
+ {
+ base::HistogramTester histograms;
+ GURL url(embedded_test_server()->GetURL("b.com", "/title1.html"));
+ NavigateToURL(shell(), url);
+ check_navigation(histograms, ProcessType::kCross, FrameType::kMain,
+ TransitionType::kNew);
+ }
+ {
+ base::HistogramTester histograms;
+ ReloadBlockUntilNavigationsComplete(shell(), 1);
+ check_navigation(histograms, ProcessType::kSame, FrameType::kMain,
+ TransitionType::kReload);
+ }
+ {
+ base::HistogramTester histograms;
+ TestNavigationObserver nav_observer(shell()->web_contents());
+ shell()->GoBackOrForward(-1);
+ nav_observer.Wait();
+ check_navigation(histograms, ProcessType::kCross, FrameType::kMain,
+ TransitionType::kBackForward);
+ }
+ {
+ base::HistogramTester histograms;
+ TestNavigationObserver nav_observer(shell()->web_contents());
+ shell()->GoBackOrForward(-1);
+ nav_observer.Wait();
+ check_navigation(histograms, ProcessType::kSame, FrameType::kMain,
+ TransitionType::kBackForward);
+ }
+ {
+ base::HistogramTester histograms;
+ NavigateToURL(shell(), GURL(url::kAboutBlankURL));
+ check_navigation(histograms, ProcessType::kSame, FrameType::kMain,
+ TransitionType::kNew);
+ }
+
+ // Subframe tests. All of these tests just navigate a frame within
+ // page_with_iframe.html.
+ EXPECT_TRUE(NavigateToURL(
+ shell(), embedded_test_server()->GetURL("/page_with_iframe.html")));
+ FrameTreeNode* first_child =
+ static_cast<WebContentsImpl*>(shell()->web_contents())
+ ->GetFrameTree()
+ ->root()
+ ->child_at(0);
+ {
+ base::HistogramTester histograms;
+ EXPECT_TRUE(NavigateToURLFromRenderer(
+ first_child, embedded_test_server()->GetURL("c.com", "/title1.html")));
+ check_navigation(histograms, ProcessType::kCross, FrameType::kSub,
+ TransitionType::kNew);
+ }
+ {
+ base::HistogramTester histograms;
+ TestFrameNavigationObserver nav_observer(first_child);
+ EXPECT_TRUE(ExecuteScript(first_child, "location.reload();"));
+ nav_observer.Wait();
+ // location.reload triggers the PAGE_TRANSITION_AUTO_SUBFRAME which
+ // corresponds to NewNavigation.
+ check_navigation(histograms, ProcessType::kSame, FrameType::kSub,
+ TransitionType::kNew);
+ }
+ {
+ base::HistogramTester histograms;
+ shell()->GoBackOrForward(-1);
+ EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
+ // History back triggers the PAGE_TRANSITION_AUTO_SUBFRAME which corresponds
+ // to NewNavigation.
+ check_navigation(histograms, ProcessType::kCross, FrameType::kSub,
+ TransitionType::kNew);
+ }
+ EXPECT_TRUE(NavigateToURLFromRenderer(
+ first_child, embedded_test_server()->GetURL("/simple_links.html")));
+ {
+ base::HistogramTester histograms;
+ TestFrameNavigationObserver nav_observer(first_child);
+ EXPECT_TRUE(ExecuteScript(first_child, "clickSameSiteLink();"));
+ nav_observer.Wait();
+ // Link clicking will trigger PAGE_TRANSITION_MANUAL_SUBFRAME which
+ // corresponds to NewNavigation.
+ check_navigation(histograms, ProcessType::kSame, FrameType::kSub,
+ TransitionType::kNew);
+ }
+}
+
+// Verify that the SameProcess vs CrossProcess version of the
+// TimeToReadyToCommit metric is correctly logged.
+IN_PROC_BROWSER_TEST_F(NavigationHandleImplBrowserTest,
+ TimeToReadyToCommitMetrics) {
+ EXPECT_TRUE(
+ NavigateToURL(shell(), embedded_test_server()->GetURL("/hello.html")));
+
+ // Check that only SameProcess version is logged and not CrossProcess.
+ {
+ base::HistogramTester histograms;
+ GURL url(embedded_test_server()->GetURL("/title1.html"));
+ EXPECT_TRUE(NavigateToURL(shell(), url));
+
+ base::HistogramTester::CountsMap expected_counts = {
+ {"Navigation.TimeToReadyToCommit.NewNavigation", 1},
+ {"Navigation.TimeToReadyToCommit.SameProcess", 1},
+ {"Navigation.TimeToReadyToCommit.SameProcess.NewNavigation", 1}};
+ EXPECT_THAT(
+ histograms.GetTotalCountsForPrefix("Navigation.TimeToReadyToCommit."),
+ testing::ContainerEq(expected_counts));
+ }
+
+ // Navigate cross-process and ensure that only CrossProcess is logged.
+ {
+ base::HistogramTester histograms;
+ GURL url(embedded_test_server()->GetURL("a.com", "/title2.html"));
+ EXPECT_TRUE(NavigateToURL(shell(), url));
+
+ base::HistogramTester::CountsMap expected_counts = {
+ {"Navigation.TimeToReadyToCommit.NewNavigation", 1},
+ {"Navigation.TimeToReadyToCommit.CrossProcess", 1},
+ {"Navigation.TimeToReadyToCommit.CrossProcess.NewNavigation", 1}};
+ EXPECT_THAT(
+ histograms.GetTotalCountsForPrefix("Navigation.TimeToReadyToCommit."),
+ testing::ContainerEq(expected_counts));
+ }
+}
+
IN_PROC_BROWSER_TEST_F(NavigationHandleImplDownloadBrowserTest, IsDownload) {
GURL url(embedded_test_server()->GetURL("/download-test1.lib"));
NavigationHandleObserver observer(shell()->web_contents(), url);
diff --git a/chromium/content/browser/frame_host/navigation_handle_impl_unittest.cc b/chromium/content/browser/frame_host/navigation_handle_impl_unittest.cc
index 389149c2cbf..6d0602750d0 100644
--- a/chromium/content/browser/frame_host/navigation_handle_impl_unittest.cc
+++ b/chromium/content/browser/frame_host/navigation_handle_impl_unittest.cc
@@ -260,7 +260,7 @@ class NavigationHandleImplTest : public RenderViewHostImplTestHarness {
false, // is_form_submission
base::nullopt, // suggested_filename
nullptr, // navigation_ui_data
- "GET",
+ "GET", net::HttpRequestHeaders(),
nullptr, // resource_request_body
Referrer(),
false, // has_user_gesture
diff --git a/chromium/content/browser/frame_host/navigation_request.cc b/chromium/content/browser/frame_host/navigation_request.cc
index cc193622958..9d8ca86d315 100644
--- a/chromium/content/browser/frame_host/navigation_request.cc
+++ b/chromium/content/browser/frame_host/navigation_request.cc
@@ -6,7 +6,6 @@
#include <utility>
-#include "base/memory/ptr_util.h"
#include "base/optional.h"
#include "base/strings/string_util.h"
#include "build/build_config.h"
@@ -26,10 +25,12 @@
#include "content/browser/frame_host/render_frame_host_impl.h"
#include "content/browser/loader/navigation_url_loader.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
+#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/service_worker/service_worker_context_wrapper.h"
#include "content/browser/service_worker/service_worker_navigation_handle.h"
#include "content/browser/site_instance_impl.h"
#include "content/common/appcache_interfaces.h"
+#include "content/common/content_constants_internal.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
@@ -46,6 +47,7 @@
#include "content/public/common/content_client.h"
#include "content/public/common/content_features.h"
#include "content/public/common/origin_util.h"
+#include "content/public/common/renderer_preferences.h"
#include "content/public/common/request_context_type.h"
#include "content/public/common/url_constants.h"
#include "content/public/common/url_utils.h"
@@ -60,8 +62,8 @@
#include "services/network/public/cpp/features.h"
#include "services/network/public/cpp/resource_request_body.h"
#include "services/network/public/cpp/resource_response.h"
-#include "third_party/WebKit/public/common/frame/sandbox_flags.h"
-#include "third_party/WebKit/public/platform/WebMixedContentContextType.h"
+#include "third_party/blink/public/common/frame/sandbox_flags.h"
+#include "third_party/blink/public/platform/web_mixed_content_context_type.h"
namespace content {
@@ -296,7 +298,7 @@ std::unique_ptr<NavigationRequest> NavigationRequest::CreateBrowserInitiated(
GURL() /* searchable_form_url */,
std::string() /* searchable_form_encoding */, initiator,
GURL() /* client_side_redirect_url */,
- nullptr /* devtools_initiator_info */),
+ base::nullopt /* devtools_initiator_info */),
request_params, browser_initiated, false /* from_begin_navigation */,
&frame_entry, &entry, std::move(navigation_ui_data)));
return navigation_request;
@@ -310,7 +312,8 @@ std::unique_ptr<NavigationRequest> NavigationRequest::CreateRendererInitiated(
mojom::BeginNavigationParamsPtr begin_params,
int current_history_list_offset,
int current_history_list_length,
- bool override_user_agent) {
+ bool override_user_agent,
+ scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
// Only normal navigations to a different document or reloads are expected.
// - Renderer-initiated fragment-navigations never take place in the browser,
// even with PlzNavigate.
@@ -345,6 +348,8 @@ std::unique_ptr<NavigationRequest> NavigationRequest::CreateRendererInitiated(
true, // from_begin_navigation
nullptr, entry,
nullptr)); // navigation_ui_data
+ navigation_request->blob_url_loader_factory_ =
+ std::move(blob_url_loader_factory);
return navigation_request;
}
@@ -449,6 +454,16 @@ NavigationRequest::NavigationRequest(
&request_params_.post_content_type);
}
}
+
+ BrowserContext* browser_context =
+ frame_tree_node_->navigator()->GetController()->GetBrowserContext();
+ RendererPreferences render_prefs = frame_tree_node_->render_manager()
+ ->current_host()
+ ->GetDelegate()
+ ->GetRendererPrefs(browser_context);
+ if (render_prefs.enable_do_not_track)
+ headers.SetHeader(kDoNotTrackHeader, "1");
+
begin_params_->headers = headers.ToString();
}
@@ -470,12 +485,19 @@ void NavigationRequest::BeginNavigation() {
#if defined(OS_ANDROID)
base::WeakPtr<NavigationRequest> this_ptr(weak_factory_.GetWeakPtr());
- bool should_override_url_loading =
- GetContentClient()->browser()->ShouldOverrideUrlLoading(
+ bool should_override_url_loading = false;
+
+ if (!GetContentClient()->browser()->ShouldOverrideUrlLoading(
frame_tree_node_->frame_tree_node_id(), browser_initiated_,
request_params_.original_url, request_params_.original_method,
common_params_.has_user_gesture, false,
- frame_tree_node_->IsMainFrame(), common_params_.transition);
+ frame_tree_node_->IsMainFrame(), common_params_.transition,
+ &should_override_url_loading)) {
+ // A Java exception was thrown by the embedding application; we
+ // need to return from this task. Specifically, it's not safe from
+ // this point on to make any JNI calls.
+ return;
+ }
// The content/ embedder might cause |this| to be deleted while
// |ShouldOverrideUrlLoading| is called.
@@ -574,6 +596,10 @@ void NavigationRequest::CreateNavigationHandle() {
bool is_external_protocol =
!GetContentClient()->browser()->IsHandledURL(common_params_.url);
+
+ net::HttpRequestHeaders headers;
+ headers.AddHeadersFromString(begin_params_->headers);
+
std::unique_ptr<NavigationHandleImpl> navigation_handle =
NavigationHandleImpl::Create(
common_params_.url, redirect_chain, frame_tree_node_,
@@ -585,7 +611,7 @@ void NavigationRequest::CreateNavigationHandle() {
common_params_.should_check_main_world_csp,
begin_params_->is_form_submission, common_params_.suggested_filename,
std::move(navigation_ui_data_), common_params_.method,
- common_params_.post_data,
+ std::move(headers), common_params_.post_data,
Referrer::SanitizeForRequest(common_params_.url,
common_params_.referrer),
common_params_.has_user_gesture, common_params_.transition,
@@ -641,19 +667,32 @@ void NavigationRequest::ResetForCrossDocumentRestart() {
state_ = NOT_STARTED;
}
+void NavigationRequest::RegisterSubresourceOverride(
+ mojom::TransferrableURLLoaderPtr transferrable_loader) {
+ if (!subresource_overrides_)
+ subresource_overrides_.emplace();
+
+ subresource_overrides_->push_back(std::move(transferrable_loader));
+}
+
void NavigationRequest::OnRequestRedirected(
const net::RedirectInfo& redirect_info,
const scoped_refptr<network::ResourceResponse>& response) {
#if defined(OS_ANDROID)
base::WeakPtr<NavigationRequest> this_ptr(weak_factory_.GetWeakPtr());
- bool should_override_url_loading =
- GetContentClient()->browser()->ShouldOverrideUrlLoading(
+ bool should_override_url_loading = false;
+ if (!GetContentClient()->browser()->ShouldOverrideUrlLoading(
frame_tree_node_->frame_tree_node_id(), browser_initiated_,
redirect_info.new_url, redirect_info.new_method,
// Redirects are always not counted as from user gesture.
false, true, frame_tree_node_->IsMainFrame(),
- common_params_.transition);
+ common_params_.transition, &should_override_url_loading)) {
+ // A Java exception was thrown by the embedding application; we
+ // need to return from this task. Specifically, it's not safe from
+ // this point on to make any JNI calls.
+ return;
+ }
// The content/ embedder might cause |this| to be deleted while
// |ShouldOverrideUrlLoading| is called.
@@ -764,6 +803,15 @@ void NavigationRequest::OnRequestRedirected(
speculative_site_instance_ =
site_instance->HasProcess() ? site_instance : nullptr;
+ // If the new site instance doesn't yet have a process, then tell the
+ // SpareRenderProcessHostManager so it can decide whether to start warming up
+ // the spare at this time (note that the actual behavior depends on
+ // RenderProcessHostImpl::IsSpareProcessKeptAtAllTimes).
+ if (!site_instance->HasProcess()) {
+ RenderProcessHostImpl::NotifySpareManagerAboutRecentlyUsedBrowserContext(
+ site_instance->GetBrowserContext());
+ }
+
// Check what the process of the SiteInstance is. It will be passed to the
// NavigationHandle, and informed to expect a navigation to the redirected
// URL.
@@ -789,7 +837,6 @@ void NavigationRequest::OnResponseStarted(
const scoped_refptr<network::ResourceResponse>& response,
network::mojom::URLLoaderClientEndpointsPtr url_loader_client_endpoints,
std::unique_ptr<StreamHandle> body,
- const net::SSLInfo& ssl_info,
std::unique_ptr<NavigationData> navigation_data,
const GlobalRequestID& request_id,
bool is_download,
@@ -812,18 +859,12 @@ void NavigationRequest::OnResponseStarted(
if (!response_should_be_rendered_)
navigation_handle_->set_net_error_code(net::ERR_ABORTED);
- // Update the service worker params of the request params.
- bool did_create_service_worker_host =
- navigation_handle_->service_worker_handle() &&
- navigation_handle_->service_worker_handle()
- ->service_worker_provider_host_id() !=
- kInvalidServiceWorkerProviderId;
+ // Update the service worker and AppCache params of the request params.
request_params_.service_worker_provider_id =
- did_create_service_worker_host
+ navigation_handle_->service_worker_handle()
? navigation_handle_->service_worker_handle()
->service_worker_provider_host_id()
: kInvalidServiceWorkerProviderId;
-
request_params_.appcache_host_id =
navigation_handle_->appcache_handle()
? navigation_handle_->appcache_handle()->appcache_host_id()
@@ -903,7 +944,8 @@ void NavigationRequest::OnResponseStarted(
response_ = response;
body_ = std::move(body);
url_loader_client_endpoints_ = std::move(url_loader_client_endpoints);
- ssl_info_ = ssl_info;
+ ssl_info_ = response->head.ssl_info.has_value() ? *response->head.ssl_info
+ : net::SSLInfo();
is_download_ = is_download;
subresource_loader_params_ = std::move(subresource_loader_params);
@@ -987,11 +1029,15 @@ void NavigationRequest::OnRequestFailedInternal(
if (navigation_handle_.get())
navigation_handle_->set_net_error_code(static_cast<net::Error>(net_error));
- int expected_pending_entry_id =
- navigation_handle_.get() ? navigation_handle_->pending_nav_entry_id()
- : nav_entry_id_;
+ int expected_pending_entry_id = nav_entry_id_;
+ bool is_download = false;
+ if (navigation_handle_.get()) {
+ expected_pending_entry_id = navigation_handle_->pending_nav_entry_id();
+ is_download = navigation_handle_->IsDownload();
+ }
+
frame_tree_node_->navigator()->DiscardPendingEntryIfNeeded(
- expected_pending_entry_id);
+ expected_pending_entry_id, is_download);
// If the request was canceled by the user do not show an error page.
if (net_error == net::ERR_ABORTED) {
@@ -1185,7 +1231,9 @@ void NavigationRequest::OnStartChecksComplete(
frame_tree_node_->frame_tree_node_id(), is_for_guests_only,
report_raw_headers,
navigating_frame_host->GetVisibilityState() ==
- blink::mojom::PageVisibilityState::kPrerender),
+ blink::mojom::PageVisibilityState::kPrerender,
+ blob_url_loader_factory_ ? blob_url_loader_factory_->Clone()
+ : nullptr),
std::move(navigation_ui_data),
navigation_handle_->service_worker_handle(),
navigation_handle_->appcache_handle(), this);
@@ -1366,7 +1414,14 @@ void NavigationRequest::CommitNavigation() {
render_frame_host->CommitNavigation(
response_.get(), std::move(url_loader_client_endpoints_),
std::move(body_), common_params_, request_params_, is_view_source_,
- std::move(subresource_loader_params_), devtools_navigation_token_);
+ std::move(subresource_loader_params_), std::move(subresource_overrides_),
+ devtools_navigation_token_);
+
+ // Give SpareRenderProcessHostManager a heads-up about the most recently used
+ // BrowserContext. This is mostly needed to make sure the spare is warmed-up
+ // if it wasn't done in RenderProcessHostImpl::GetProcessHostForSiteInstance.
+ RenderProcessHostImpl::NotifySpareManagerAboutRecentlyUsedBrowserContext(
+ render_frame_host->GetSiteInstance()->GetBrowserContext());
}
NavigationRequest::ContentSecurityPolicyCheckResult
diff --git a/chromium/content/browser/frame_host/navigation_request.h b/chromium/content/browser/frame_host/navigation_request.h
index 3f6d4546012..7582a5e3bc6 100644
--- a/chromium/content/browser/frame_host/navigation_request.h
+++ b/chromium/content/browser/frame_host/navigation_request.h
@@ -107,7 +107,8 @@ class CONTENT_EXPORT NavigationRequest : public NavigationURLLoaderDelegate {
mojom::BeginNavigationParamsPtr begin_params,
int current_history_list_offset,
int current_history_list_length,
- bool override_user_agent);
+ bool override_user_agent,
+ scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory);
~NavigationRequest() override;
@@ -161,6 +162,8 @@ class CONTENT_EXPORT NavigationRequest : public NavigationURLLoaderDelegate {
associated_site_instance_type_ = type;
}
+ void set_was_discarded() { request_params_.was_discarded = true; }
+
NavigationHandleImpl* navigation_handle() const {
return navigation_handle_.get();
}
@@ -202,6 +205,9 @@ class CONTENT_EXPORT NavigationRequest : public NavigationURLLoaderDelegate {
// due to another navigation committing in the meantime.
void ResetForCrossDocumentRestart();
+ void RegisterSubresourceOverride(
+ mojom::TransferrableURLLoaderPtr transferrable_loader);
+
private:
// This enum describes the result of a Content Security Policy (CSP) check for
// the request.
@@ -231,7 +237,6 @@ class CONTENT_EXPORT NavigationRequest : public NavigationURLLoaderDelegate {
const scoped_refptr<network::ResourceResponse>& response,
network::mojom::URLLoaderClientEndpointsPtr url_loader_client_endpoints,
std::unique_ptr<StreamHandle> body,
- const net::SSLInfo& ssl_info,
std::unique_ptr<NavigationData> navigation_data,
const GlobalRequestID& request_id,
bool is_download,
@@ -331,6 +336,9 @@ class CONTENT_EXPORT NavigationRequest : public NavigationURLLoaderDelegate {
// NavigationUIData at the beginning of the navigation.
std::unique_ptr<NavigationUIData> navigation_ui_data_;
+ // URLLoaderFactory to facilitate loading blob URLs.
+ scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory_;
+
NavigationState state_;
std::unique_ptr<NavigationURLLoader> loader_;
@@ -391,6 +399,9 @@ class CONTENT_EXPORT NavigationRequest : public NavigationURLLoaderDelegate {
// See comment on accessor.
base::UnguessableToken devtools_navigation_token_;
+ base::Optional<std::vector<mojom::TransferrableURLLoaderPtr>>
+ subresource_overrides_;
+
base::WeakPtrFactory<NavigationRequest> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(NavigationRequest);
diff --git a/chromium/content/browser/frame_host/navigation_request_info.cc b/chromium/content/browser/frame_host/navigation_request_info.cc
index 6982bf890f7..4e918bf1e6d 100644
--- a/chromium/content/browser/frame_host/navigation_request_info.cc
+++ b/chromium/content/browser/frame_host/navigation_request_info.cc
@@ -4,6 +4,7 @@
#include "content/browser/frame_host/navigation_request_info.h"
#include "content/common/service_worker/service_worker_types.h"
+#include "mojo/common/values_struct_traits.h"
namespace content {
@@ -17,7 +18,9 @@ NavigationRequestInfo::NavigationRequestInfo(
int frame_tree_node_id,
bool is_for_guests_only,
bool report_raw_headers,
- bool is_prerendering)
+ bool is_prerendering,
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo>
+ blob_url_loader_factory)
: common_params(common_params),
begin_params(std::move(begin_params)),
site_for_cookies(site_for_cookies),
@@ -27,7 +30,20 @@ NavigationRequestInfo::NavigationRequestInfo(
frame_tree_node_id(frame_tree_node_id),
is_for_guests_only(is_for_guests_only),
report_raw_headers(report_raw_headers),
- is_prerendering(is_prerendering) {}
+ is_prerendering(is_prerendering),
+ blob_url_loader_factory(std::move(blob_url_loader_factory)) {}
+
+NavigationRequestInfo::NavigationRequestInfo(const NavigationRequestInfo& other)
+ : common_params(other.common_params),
+ begin_params(other.begin_params.Clone()),
+ site_for_cookies(other.site_for_cookies),
+ is_main_frame(other.is_main_frame),
+ parent_is_main_frame(other.parent_is_main_frame),
+ are_ancestors_secure(other.are_ancestors_secure),
+ frame_tree_node_id(other.frame_tree_node_id),
+ is_for_guests_only(other.is_for_guests_only),
+ report_raw_headers(other.report_raw_headers),
+ is_prerendering(other.is_prerendering) {}
NavigationRequestInfo::~NavigationRequestInfo() {}
diff --git a/chromium/content/browser/frame_host/navigation_request_info.h b/chromium/content/browser/frame_host/navigation_request_info.h
index 65256b5feed..47dbca17b5c 100644
--- a/chromium/content/browser/frame_host/navigation_request_info.h
+++ b/chromium/content/browser/frame_host/navigation_request_info.h
@@ -12,6 +12,7 @@
#include "content/common/navigation_params.h"
#include "content/common/navigation_params.mojom.h"
#include "content/public/common/referrer.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "url/gurl.h"
#include "url/origin.h"
@@ -30,7 +31,10 @@ struct CONTENT_EXPORT NavigationRequestInfo {
int frame_tree_node_id,
bool is_for_guests_only,
bool report_raw_headers,
- bool is_prerendering);
+ bool is_prerendering,
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo>
+ blob_url_loader_factory);
+ NavigationRequestInfo(const NavigationRequestInfo& other);
~NavigationRequestInfo();
const CommonNavigationParams common_params;
@@ -54,6 +58,9 @@ struct CONTENT_EXPORT NavigationRequestInfo {
const bool report_raw_headers;
const bool is_prerendering;
+
+ // URLLoaderFactory to facilitate loading blob URLs.
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo> blob_url_loader_factory;
};
} // namespace content
diff --git a/chromium/content/browser/frame_host/navigator.cc b/chromium/content/browser/frame_host/navigator.cc
index a945fbcbcbc..ff6457f3ae7 100644
--- a/chromium/content/browser/frame_host/navigator.cc
+++ b/chromium/content/browser/frame_host/navigator.cc
@@ -38,6 +38,7 @@ base::TimeTicks Navigator::GetCurrentLoadStart() {
void Navigator::OnBeginNavigation(
FrameTreeNode* frame_tree_node,
const CommonNavigationParams& common_params,
- mojom::BeginNavigationParamsPtr begin_params) {}
+ mojom::BeginNavigationParamsPtr begin_params,
+ scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {}
} // namespace content
diff --git a/chromium/content/browser/frame_host/navigator.h b/chromium/content/browser/frame_host/navigator.h
index 771a0b98150..1ae19f9774e 100644
--- a/chromium/content/browser/frame_host/navigator.h
+++ b/chromium/content/browser/frame_host/navigator.h
@@ -13,7 +13,7 @@
#include "content/common/content_export.h"
#include "content/common/navigation_params.mojom.h"
#include "content/public/browser/navigation_controller.h"
-#include "third_party/WebKit/public/web/WebTriggeringEventInfo.h"
+#include "third_party/blink/public/web/web_triggering_event_info.h"
#include "ui/base/window_open_disposition.h"
class GURL;
@@ -159,9 +159,11 @@ class CONTENT_EXPORT Navigator : public base::RefCounted<Navigator> {
// Used to start a new renderer-initiated navigation, following a
// BeginNavigation IPC from the renderer.
- virtual void OnBeginNavigation(FrameTreeNode* frame_tree_node,
- const CommonNavigationParams& common_params,
- mojom::BeginNavigationParamsPtr begin_params);
+ virtual void OnBeginNavigation(
+ FrameTreeNode* frame_tree_node,
+ const CommonNavigationParams& common_params,
+ mojom::BeginNavigationParamsPtr begin_params,
+ scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory);
// Used to restart a navigation that was thought to be same-document in
// cross-document mode.
@@ -199,7 +201,8 @@ class CONTENT_EXPORT Navigator : public base::RefCounted<Navigator> {
// With sufficiently bad interleaving of IPCs, this may no longer be the
// pending NavigationEntry, in which case the pending NavigationEntry will not
// be discarded.
- virtual void DiscardPendingEntryIfNeeded(int expected_pending_entry_id) {}
+ virtual void DiscardPendingEntryIfNeeded(int expected_pending_entry_id,
+ bool is_download) {}
protected:
friend class base::RefCounted<Navigator>;
diff --git a/chromium/content/browser/frame_host/navigator_delegate.cc b/chromium/content/browser/frame_host/navigator_delegate.cc
index 786a58a1e85..11b17d4f597 100644
--- a/chromium/content/browser/frame_host/navigator_delegate.cc
+++ b/chromium/content/browser/frame_host/navigator_delegate.cc
@@ -10,6 +10,10 @@ bool NavigatorDelegate::CanOverscrollContent() const {
return false;
}
+bool NavigatorDelegate::ShouldOverrideUserAgentInNewTabs() {
+ return false;
+}
+
bool NavigatorDelegate::ShouldTransferNavigation(
bool is_main_frame_navigation) {
return true;
diff --git a/chromium/content/browser/frame_host/navigator_delegate.h b/chromium/content/browser/frame_host/navigator_delegate.h
index 4175febda4b..fe0275288b5 100644
--- a/chromium/content/browser/frame_host/navigator_delegate.h
+++ b/chromium/content/browser/frame_host/navigator_delegate.h
@@ -99,6 +99,10 @@ class CONTENT_EXPORT NavigatorDelegate {
// Returns the overriden user agent string if it's set.
virtual const std::string& GetUserAgentOverride() const = 0;
+ // Returns whether we should override the user agent in new tabs, e.g., for
+ // Android Webview's popup window when current entry.
+ virtual bool ShouldOverrideUserAgentInNewTabs() = 0;
+
// A RenderFrameHost in the specified |frame_tree_node| started loading a new
// document. This correponds to Blink's notion of the throbber starting.
// |to_different_document| will be true unless the load is a fragment
diff --git a/chromium/content/browser/frame_host/navigator_impl.cc b/chromium/content/browser/frame_host/navigator_impl.cc
index b5c21607f1d..bb33fd3b868 100644
--- a/chromium/content/browser/frame_host/navigator_impl.cc
+++ b/chromium/content/browser/frame_host/navigator_impl.cc
@@ -237,11 +237,13 @@ void NavigatorImpl::DidFailProvisionalLoadWithError(
}
// Discard the pending navigation entry if needed.
- int expected_pending_entry_id =
- render_frame_host->GetNavigationHandle()
- ? render_frame_host->GetNavigationHandle()->pending_nav_entry_id()
- : 0;
- DiscardPendingEntryIfNeeded(expected_pending_entry_id);
+ int expected_pending_entry_id = 0;
+ if (render_frame_host->GetNavigationHandle()) {
+ expected_pending_entry_id =
+ render_frame_host->GetNavigationHandle()->pending_nav_entry_id();
+ DCHECK(!render_frame_host->GetNavigationHandle()->IsDownload());
+ }
+ DiscardPendingEntryIfNeeded(expected_pending_entry_id, false);
}
void NavigatorImpl::DidFailLoadWithError(
@@ -312,9 +314,10 @@ bool NavigatorImpl::NavigateToEntry(
// "Open link in new tab"). We need to keep it above RFHM::Navigate() call to
// capture the time needed for the RenderFrameHost initialization.
base::TimeTicks navigation_start = base::TimeTicks::Now();
+ base::TimeTicks tracing_navigation_start = TRACE_TIME_TICKS_NOW();
TRACE_EVENT_INSTANT_WITH_TIMESTAMP0(
"navigation,rail", "NavigationTiming navigationStart",
- TRACE_EVENT_SCOPE_GLOBAL, navigation_start);
+ TRACE_EVENT_SCOPE_GLOBAL, tracing_navigation_start);
// Determine if Previews should be used for the navigation.
PreviewsState previews_state = PREVIEWS_UNSPECIFIED;
@@ -349,7 +352,7 @@ bool NavigatorImpl::NavigateToEntry(
TRACE_EVENT_ASYNC_BEGIN_WITH_TIMESTAMP1(
"navigation", "Navigation timeToNetworkStack",
frame_tree_node->navigation_request()->navigation_handle(),
- navigation_start, "FrameTreeNode id",
+ tracing_navigation_start, "FrameTreeNode id",
frame_tree_node->frame_tree_node_id());
}
@@ -471,16 +474,19 @@ void NavigatorImpl::DidNavigate(
}
}
- // Save the origin of the new page. Do this before calling
- // DidNavigateFrame(), because the origin needs to be included in the SwapOut
- // message, which is sent inside DidNavigateFrame(). SwapOut needs the
- // origin because it creates a RenderFrameProxy that needs this to initialize
- // its security context. This origin will also be sent to RenderFrameProxies
- // created via mojom::Renderer::CreateView and
- // mojom::Renderer::CreateFrameProxy.
+ // DidNavigateFrame() must be called before replicating the new origin and
+ // other properties to proxies. This is because it destroys the subframes of
+ // the frame we're navigating from, which might trigger those subframes to
+ // run unload handlers. Those unload handlers should still see the old
+ // frame's origin. See https://crbug.com/825283.
+ frame_tree_node->render_manager()->DidNavigateFrame(
+ render_frame_host, params.gesture == NavigationGestureUser);
+
+ // Save the new page's origin and other properties, and replicate them to
+ // proxies, including the proxy created in DidNavigateFrame() to replace the
+ // old frame in cross-process navigation cases.
frame_tree_node->SetCurrentOrigin(
params.origin, params.has_potentially_trustworthy_unique_origin);
-
frame_tree_node->SetInsecureRequestPolicy(params.insecure_request_policy);
frame_tree_node->SetInsecureNavigationsSet(params.insecure_navigations_set);
@@ -491,9 +497,6 @@ void NavigatorImpl::DidNavigate(
frame_tree_node->ResetForNavigation();
}
- frame_tree_node->render_manager()->DidNavigateFrame(
- render_frame_host, params.gesture == NavigationGestureUser);
-
// Update the site of the SiteInstance if it doesn't have one yet, unless
// assigning a site is not necessary for this URL or the commit was for an
// error page. In that case, the SiteInstance can still be considered unused
@@ -846,7 +849,8 @@ void NavigatorImpl::OnBeforeUnloadACK(FrameTreeNode* frame_tree_node,
void NavigatorImpl::OnBeginNavigation(
FrameTreeNode* frame_tree_node,
const CommonNavigationParams& common_params,
- mojom::BeginNavigationParamsPtr begin_params) {
+ mojom::BeginNavigationParamsPtr begin_params,
+ scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
// TODO(clamy): the url sent by the renderer should be validated with
// FilterURL.
// This is a renderer-initiated navigation.
@@ -895,13 +899,19 @@ void NavigatorImpl::OnBeginNavigation(
}
NavigationEntryImpl* pending_entry = controller_->GetPendingEntry();
NavigationEntryImpl* current_entry = controller_->GetLastCommittedEntry();
+ // Only consult the delegate for override state if there is no current entry,
+ // since that state should only apply to newly created tabs (and not cases
+ // where the NavigationEntry recorded the state).
bool override_user_agent =
- current_entry ? current_entry->GetIsOverridingUserAgent() : false;
+ current_entry
+ ? current_entry->GetIsOverridingUserAgent()
+ : delegate_ && delegate_->ShouldOverrideUserAgentInNewTabs();
frame_tree_node->CreatedNavigationRequest(
NavigationRequest::CreateRendererInitiated(
frame_tree_node, pending_entry, common_params,
std::move(begin_params), controller_->GetLastCommittedEntryIndex(),
- controller_->GetEntryCount(), override_user_agent));
+ controller_->GetEntryCount(), override_user_agent,
+ std::move(blob_url_loader_factory)));
NavigationRequest* navigation_request = frame_tree_node->navigation_request();
// For main frames, NavigationHandle will be created after the call to
@@ -976,14 +986,15 @@ void NavigatorImpl::LogBeforeUnloadTime(
}
}
-void NavigatorImpl::DiscardPendingEntryIfNeeded(int expected_pending_entry_id) {
+void NavigatorImpl::DiscardPendingEntryIfNeeded(int expected_pending_entry_id,
+ bool is_download) {
// Racy conditions can cause a fail message to arrive after its corresponding
// pending entry has been replaced by another navigation. If
// |DiscardPendingEntry| is called in this case, then the completely valid
// entry for the new navigation would be discarded. See crbug.com/513742. To
// catch this case, the current pending entry is compared against the current
// navigation handle's entry id, which should correspond to the failed load.
- NavigationEntry* pending_entry = controller_->GetPendingEntry();
+ NavigationEntryImpl* pending_entry = controller_->GetPendingEntry();
bool pending_matches_fail_msg =
pending_entry &&
expected_pending_entry_id == pending_entry->GetUniqueID();
@@ -1004,9 +1015,13 @@ void NavigatorImpl::DiscardPendingEntryIfNeeded(int expected_pending_entry_id) {
// allow the view to clear the pending entry and typed URL if the user
// requests (e.g., hitting Escape with focus in the address bar).
//
+ // Note that the pending entry does not need to be preserved for downloads,
+ // since the user is unlikely to try again.
+ //
// Note: don't touch the transient entry, since an interstitial may exist.
- bool should_preserve_entry = controller_->IsUnmodifiedBlankTab() ||
- delegate_->ShouldPreserveAbortedURLs();
+ bool should_preserve_entry = (controller_->IsUnmodifiedBlankTab() ||
+ delegate_->ShouldPreserveAbortedURLs()) &&
+ !is_download;
if (pending_entry != controller_->GetVisibleEntry() ||
!should_preserve_entry) {
controller_->DiscardPendingEntry(true);
diff --git a/chromium/content/browser/frame_host/navigator_impl.h b/chromium/content/browser/frame_host/navigator_impl.h
index a1bedd30434..b1bb76b4e7b 100644
--- a/chromium/content/browser/frame_host/navigator_impl.h
+++ b/chromium/content/browser/frame_host/navigator_impl.h
@@ -95,7 +95,9 @@ class CONTENT_EXPORT NavigatorImpl : public Navigator {
const base::TimeTicks& proceed_time) override;
void OnBeginNavigation(FrameTreeNode* frame_tree_node,
const CommonNavigationParams& common_params,
- mojom::BeginNavigationParamsPtr begin_params) override;
+ mojom::BeginNavigationParamsPtr begin_params,
+ scoped_refptr<network::SharedURLLoaderFactory>
+ blob_url_loader_factory) override;
void RestartNavigationAsCrossDocument(
std::unique_ptr<NavigationRequest> navigation_request) override;
void OnAbortNavigation(FrameTreeNode* frame_tree_node) override;
@@ -106,7 +108,8 @@ class CONTENT_EXPORT NavigatorImpl : public Navigator {
const base::TimeTicks& renderer_before_unload_end_time) override;
void CancelNavigation(FrameTreeNode* frame_tree_node,
bool inform_renderer) override;
- void DiscardPendingEntryIfNeeded(int expected_pending_entry_id) override;
+ void DiscardPendingEntryIfNeeded(int expected_pending_entry_id,
+ bool is_download) override;
private:
// Holds data used to track browser side navigation metrics.
diff --git a/chromium/content/browser/frame_host/popup_menu_helper_mac.h b/chromium/content/browser/frame_host/popup_menu_helper_mac.h
index 1fd5b95a450..2964f3cf3d5 100644
--- a/chromium/content/browser/frame_host/popup_menu_helper_mac.h
+++ b/chromium/content/browser/frame_host/popup_menu_helper_mac.h
@@ -5,6 +5,7 @@
#ifndef CONTENT_BROWSER_FRAME_HOST_POPUP_MENU_HELPER_MAC_H_
#define CONTENT_BROWSER_FRAME_HOST_POPUP_MENU_HELPER_MAC_H_
+#include <memory>
#include <vector>
#include "base/compiler_specific.h"
@@ -21,6 +22,10 @@
class WebMenuRunner;
#endif
+namespace base {
+class ScopedPumpMessagesInPrivateModes;
+}
+
namespace content {
class RenderFrameHost;
@@ -71,6 +76,9 @@ class PopupMenuHelper : public NotificationObserver {
WebMenuRunner* menu_runner_;
bool popup_was_hidden_;
+ // Controls whether messages can be pumped during the menu fade.
+ std::unique_ptr<base::ScopedPumpMessagesInPrivateModes> pump_in_fade_;
+
base::WeakPtrFactory<PopupMenuHelper> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(PopupMenuHelper);
diff --git a/chromium/content/browser/frame_host/popup_menu_helper_mac.mm b/chromium/content/browser/frame_host/popup_menu_helper_mac.mm
index c33a667e552..8896a7ca776 100644
--- a/chromium/content/browser/frame_host/popup_menu_helper_mac.mm
+++ b/chromium/content/browser/frame_host/popup_menu_helper_mac.mm
@@ -7,10 +7,12 @@
#import "base/mac/scoped_nsobject.h"
#import "base/mac/scoped_sending_event.h"
#include "base/message_loop/message_loop.h"
+#import "base/message_loop/message_pump_mac.h"
#include "content/browser/frame_host/frame_tree.h"
#include "content/browser/frame_host/frame_tree_node.h"
#include "content/browser/frame_host/render_frame_host_impl.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
+#import "content/browser/renderer_host/render_widget_host_view_cocoa.h"
#include "content/browser/renderer_host/render_widget_host_view_mac.h"
#include "content/browser/renderer_host/webmenurunner_mac.h"
#include "content/public/browser/notification_details.h"
@@ -93,6 +95,9 @@ void PopupMenuHelper::ShowPopupMenu(
// be done manually.
base::mac::ScopedSendingEvent sending_event_scoper;
+ // Ensure the UI can update while the menu is fading out.
+ pump_in_fade_ = std::make_unique<base::ScopedPumpMessagesInPrivateModes>();
+
// Now run a NESTED EVENT LOOP until the pop-up is finished.
[runner runMenuInView:cocoa_view
withBounds:[cocoa_view flipRectToNSRect:bounds]
@@ -102,6 +107,7 @@ void PopupMenuHelper::ShowPopupMenu(
if (!weak_ptr)
return; // Handle |this| being deleted.
+ pump_in_fade_ = nullptr;
menu_runner_ = nil;
// The RenderFrameHost may be deleted while running the menu, or it may have
@@ -117,6 +123,14 @@ void PopupMenuHelper::ShowPopupMenu(
}
void PopupMenuHelper::Hide() {
+ // Blink core reuses the PopupMenu of an element and first invokes Hide() over
+ // IPC if a menu is already showing. Attempting to show a new menu while the
+ // old menu is fading out confuses AppKit, since we're still in the NESTED
+ // EVENT LOOP of ShowPopupMenu(). Disable pumping of events in the fade
+ // animation of the old menu in this case so that it closes synchronously.
+ // See http://crbug.com/812260.
+ pump_in_fade_ = nullptr;
+
if (menu_runner_)
[menu_runner_ hide];
popup_was_hidden_ = true;
diff --git a/chromium/content/browser/frame_host/render_frame_host_android.cc b/chromium/content/browser/frame_host/render_frame_host_android.cc
index 9f36fd67264..8ef72144652 100644
--- a/chromium/content/browser/frame_host/render_frame_host_android.cc
+++ b/chromium/content/browser/frame_host/render_frame_host_android.cc
@@ -93,10 +93,10 @@ RenderFrameHostAndroid::GetAndroidOverlayRoutingToken(
env, render_frame_host_->GetOverlayRoutingToken());
}
-void RenderFrameHostAndroid::SetHasReceivedUserGesture(
+void RenderFrameHostAndroid::NotifyUserActivation(
JNIEnv* env,
const base::android::JavaParamRef<jobject>&) {
- render_frame_host_->SetHasReceivedUserGesture();
+ render_frame_host_->NotifyUserActivation();
}
} // namespace content
diff --git a/chromium/content/browser/frame_host/render_frame_host_android.h b/chromium/content/browser/frame_host/render_frame_host_android.h
index 90b9369c7f0..423e1a62778 100644
--- a/chromium/content/browser/frame_host/render_frame_host_android.h
+++ b/chromium/content/browser/frame_host/render_frame_host_android.h
@@ -49,8 +49,8 @@ class RenderFrameHostAndroid : public base::SupportsUserData::Data {
JNIEnv* env,
const base::android::JavaParamRef<jobject>&) const;
- void SetHasReceivedUserGesture(JNIEnv* env,
- const base::android::JavaParamRef<jobject>&);
+ void NotifyUserActivation(JNIEnv* env,
+ const base::android::JavaParamRef<jobject>&);
private:
RenderFrameHostImpl* const render_frame_host_;
diff --git a/chromium/content/browser/frame_host/render_frame_host_delegate.cc b/chromium/content/browser/frame_host/render_frame_host_delegate.cc
index 9d3a7d99e6b..017610ae62c 100644
--- a/chromium/content/browser/frame_host/render_frame_host_delegate.cc
+++ b/chromium/content/browser/frame_host/render_frame_host_delegate.cc
@@ -51,6 +51,7 @@ void RenderFrameHostDelegate::RequestMediaAccessPermission(
}
bool RenderFrameHostDelegate::CheckMediaAccessPermission(
+ RenderFrameHost* render_frame_host,
const url::Origin& security_origin,
MediaStreamType type) {
LOG(ERROR) << "RenderFrameHostDelegate::CheckMediaAccessPermission: "
diff --git a/chromium/content/browser/frame_host/render_frame_host_delegate.h b/chromium/content/browser/frame_host/render_frame_host_delegate.h
index 9d38f94bd8b..297accc301a 100644
--- a/chromium/content/browser/frame_host/render_frame_host_delegate.h
+++ b/chromium/content/browser/frame_host/render_frame_host_delegate.h
@@ -19,6 +19,7 @@
#include "content/public/browser/site_instance.h"
#include "content/public/common/javascript_dialog_type.h"
#include "content/public/common/media_stream_request.h"
+#include "content/public/common/resource_load_info.mojom.h"
#include "content/public/common/resource_type.h"
#include "mojo/public/cpp/bindings/scoped_interface_endpoint_handle.h"
#include "net/cert/cert_status_flags.h"
@@ -44,6 +45,7 @@ class Message;
namespace gfx {
class Rect;
+class Size;
}
namespace url {
@@ -177,7 +179,8 @@ class CONTENT_EXPORT RenderFrameHostDelegate {
// Checks if we have permission to access the microphone or camera. Note that
// this does not query the user. |type| must be MEDIA_DEVICE_AUDIO_CAPTURE
// or MEDIA_DEVICE_VIDEO_CAPTURE.
- virtual bool CheckMediaAccessPermission(const url::Origin& security_origin,
+ virtual bool CheckMediaAccessPermission(RenderFrameHost* render_frame_host,
+ const url::Origin& security_origin,
MediaStreamType type);
// Returns the ID of the default device for the given media device |type|.
@@ -344,12 +347,12 @@ class CONTENT_EXPORT RenderFrameHostDelegate {
// Notifies that the render frame started loading a subresource.
virtual void SubresourceResponseStarted(const GURL& url,
- const GURL& referrer,
- const std::string& method,
- ResourceType resource_type,
- const std::string& ip,
net::CertStatus cert_status) {}
+ // Notifies that the render finished loading a subresource.
+ virtual void ResourceLoadComplete(
+ mojom::ResourceLoadInfoPtr resource_load_info) {}
+
// Request to print a frame that is in a different process than its parent.
virtual void PrintCrossProcessSubframe(const gfx::Rect& rect,
int document_cookie,
@@ -357,7 +360,12 @@ class CONTENT_EXPORT RenderFrameHostDelegate {
// Updates the Picture-in-Picture controller with the relevant viz::SurfaceId
// of the video to be in Picture-in-Picture mode.
- virtual void UpdatePictureInPictureSurfaceId(viz::SurfaceId surface_id) {}
+ virtual void UpdatePictureInPictureSurfaceId(const viz::SurfaceId& surface_id,
+ const gfx::Size& natural_size) {}
+
+ // Updates the Picture-in-Picture controller with a signal that
+ // Picture-in-Picture mode has ended.
+ virtual void ExitPictureInPicture() {}
protected:
virtual ~RenderFrameHostDelegate() {}
diff --git a/chromium/content/browser/frame_host/render_frame_host_feature_policy_unittest.cc b/chromium/content/browser/frame_host/render_frame_host_feature_policy_unittest.cc
index daa5e98f26c..e4a6d38b68f 100644
--- a/chromium/content/browser/frame_host/render_frame_host_feature_policy_unittest.cc
+++ b/chromium/content/browser/frame_host/render_frame_host_feature_policy_unittest.cc
@@ -9,9 +9,9 @@
#include "content/public/test/navigation_simulator.h"
#include "content/public/test/test_renderer_host.h"
#include "content/test/test_render_frame_host.h"
-#include "third_party/WebKit/public/common/feature_policy/feature_policy.h"
-#include "third_party/WebKit/public/common/frame/frame_policy.h"
-#include "third_party/WebKit/public/common/frame/sandbox_flags.h"
+#include "third_party/blink/public/common/feature_policy/feature_policy.h"
+#include "third_party/blink/public/common/frame/frame_policy.h"
+#include "third_party/blink/public/common/frame/sandbox_flags.h"
#include "url/gurl.h"
#include "url/origin.h"
diff --git a/chromium/content/browser/frame_host/render_frame_host_impl.cc b/chromium/content/browser/frame_host/render_frame_host_impl.cc
index c9f6daa998d..d938013c90b 100644
--- a/chromium/content/browser/frame_host/render_frame_host_impl.cc
+++ b/chromium/content/browser/frame_host/render_frame_host_impl.cc
@@ -15,8 +15,11 @@
#include "base/lazy_instance.h"
#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
+#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
+#include "base/metrics/metrics_hashes.h"
#include "base/metrics/user_metrics.h"
+#include "base/numerics/safe_conversions.h"
#include "base/process/kill.h"
#include "base/task_scheduler/post_task.h"
#include "base/time/time.h"
@@ -83,10 +86,11 @@
#include "content/browser/shared_worker/shared_worker_service_impl.h"
#include "content/browser/storage_partition_impl.h"
#include "content/browser/webauth/authenticator_impl.h"
+#include "content/browser/webauth/scoped_virtual_authenticator_environment.h"
#include "content/browser/websockets/websocket_manager.h"
#include "content/browser/webui/url_data_manager_backend.h"
#include "content/browser/webui/web_ui_controller_factory_registry.h"
-#include "content/browser/webui/web_ui_url_loader_factory.h"
+#include "content/browser/webui/web_ui_url_loader_factory_internal.h"
#include "content/common/accessibility_messages.h"
#include "content/common/associated_interface_provider_impl.h"
#include "content/common/associated_interface_registry_impl.h"
@@ -104,6 +108,7 @@
#include "content/common/swapped_out_messages.h"
#include "content/common/url_loader_factory_bundle.mojom.h"
#include "content/common/widget.mojom.h"
+#include "content/common/wrapper_shared_url_loader_factory.h"
#include "content/public/browser/ax_event_notification_details.h"
#include "content/public/browser/browser_accessibility_state.h"
#include "content/public/browser/browser_context.h"
@@ -131,7 +136,7 @@
#include "media/audio/audio_manager.h"
#include "media/base/media_switches.h"
#include "media/base/user_input_monitor.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "media/mojo/interfaces/remoting.mojom.h"
#include "media/mojo/services/media_interface_provider.h"
#include "media/mojo/services/media_metrics_provider.h"
@@ -150,9 +155,12 @@
#include "services/resource_coordinator/public/cpp/resource_coordinator_features.h"
#include "services/service_manager/public/cpp/connector.h"
#include "services/service_manager/public/cpp/interface_provider.h"
-#include "third_party/WebKit/public/common/feature_policy/feature_policy.h"
-#include "third_party/WebKit/public/common/frame/frame_policy.h"
-#include "third_party/WebKit/public/mojom/page/page_visibility_state.mojom.h"
+#include "storage/browser/blob/blob_storage_context.h"
+#include "storage/browser/blob/blob_url_loader_factory.h"
+#include "third_party/blink/public/common/feature_policy/feature_policy.h"
+#include "third_party/blink/public/common/frame/frame_policy.h"
+#include "third_party/blink/public/mojom/page/page_visibility_state.mojom.h"
+#include "third_party/blink/public/platform/modules/webauth/virtual_authenticator.mojom.h"
#include "ui/accessibility/ax_tree.h"
#include "ui/accessibility/ax_tree_id_registry.h"
#include "ui/accessibility/ax_tree_update.h"
@@ -164,11 +172,7 @@
#if defined(OS_ANDROID)
#include "content/browser/android/java_interfaces_impl.h"
#include "content/browser/frame_host/render_frame_host_android.h"
-#include "content/browser/media/android/media_player_renderer.h"
#include "content/public/browser/android/java_interfaces.h"
-#include "media/base/audio_renderer_sink.h"
-#include "media/base/video_renderer_sink.h"
-#include "media/mojo/services/mojo_renderer_service.h" // nogncheck
#endif
#if defined(OS_MACOSX)
@@ -195,10 +199,6 @@ int g_next_javascript_callback_id = 1;
// Whether to allow injecting javascript into any kind of frame (for Android
// WebView).
bool g_allow_injecting_javascript = false;
-
-// Whether to allow data URL navigations for Android WebView.
-// TODO(meacer): Remove after PlzNavigate ships.
-bool g_allow_data_url_navigation = false;
#endif
// The (process id, routing id) pair that identifies one RenderFrame.
@@ -380,8 +380,59 @@ bool IsOutOfProcessNetworkService() {
switches::kSingleProcess);
}
+// Takes the lower 31 bits of the metric-name-hash of a Mojo interface |name|.
+base::Histogram::Sample HashInterfaceNameToHistogramSample(
+ base::StringPiece name) {
+ return base::strict_cast<base::Histogram::Sample>(
+ static_cast<int32_t>(base::HashMetricName(name) & 0x7fffffffull));
+}
+
} // namespace
+RenderFrameHostImpl::PendingNavigation::PendingNavigation(
+ const CommonNavigationParams& common_params,
+ mojom::BeginNavigationParamsPtr begin_params,
+ scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory)
+ : common_params(common_params),
+ begin_params(std::move(begin_params)),
+ blob_url_loader_factory(std::move(blob_url_loader_factory)) {}
+
+RenderFrameHostImpl::PendingNavigation::~PendingNavigation() = default;
+
+class RenderFrameHostImpl::DroppedInterfaceRequestLogger
+ : public service_manager::mojom::InterfaceProvider {
+ public:
+ DroppedInterfaceRequestLogger(
+ service_manager::mojom::InterfaceProviderRequest request)
+ : binding_(this) {
+ binding_.Bind(std::move(request));
+ }
+
+ ~DroppedInterfaceRequestLogger() override {
+ UMA_HISTOGRAM_EXACT_LINEAR("RenderFrameHostImpl.DroppedInterfaceRequests",
+ num_dropped_requests_, 20);
+ }
+
+ protected:
+ // service_manager::mojom::InterfaceProvider:
+ void GetInterface(const std::string& interface_name,
+ mojo::ScopedMessagePipeHandle pipe) override {
+ ++num_dropped_requests_;
+ base::UmaHistogramSparse(
+ "RenderFrameHostImpl.DroppedInterfaceRequestName",
+ HashInterfaceNameToHistogramSample(interface_name));
+ DLOG(WARNING)
+ << "InterfaceRequest was dropped, the document is no longer active: "
+ << interface_name;
+ }
+
+ private:
+ mojo::Binding<service_manager::mojom::InterfaceProvider> binding_;
+ int num_dropped_requests_ = 0;
+
+ DISALLOW_COPY_AND_ASSIGN(DroppedInterfaceRequestLogger);
+};
+
// static
RenderFrameHost* RenderFrameHost::FromID(int render_process_id,
int render_frame_id) {
@@ -393,37 +444,6 @@ RenderFrameHost* RenderFrameHost::FromID(int render_process_id,
void RenderFrameHost::AllowInjectingJavaScriptForAndroidWebView() {
g_allow_injecting_javascript = true;
}
-
-// static
-void RenderFrameHost::AllowDataUrlNavigationForAndroidWebView() {
- g_allow_data_url_navigation = true;
-}
-
-// static
-bool RenderFrameHost::IsDataUrlNavigationAllowedForAndroidWebView() {
- return g_allow_data_url_navigation;
-}
-
-void CreateMediaPlayerRenderer(int process_id,
- int routing_id,
- RenderFrameHostDelegate* delegate,
- media::mojom::RendererRequest request) {
- std::unique_ptr<MediaPlayerRenderer> renderer =
- std::make_unique<MediaPlayerRenderer>(process_id, routing_id,
- delegate->GetAsWebContents());
-
- // base::Unretained is safe here because the lifetime of the MediaPlayerRender
- // is tied to the lifetime of the MojoRendererService.
- media::MojoRendererService::InitiateSurfaceRequestCB surface_request_cb =
- base::Bind(&MediaPlayerRenderer::InitiateScopedSurfaceRequest,
- base::Unretained(renderer.get()));
-
- media::MojoRendererService::Create(
- nullptr, // CDMs are not supported.
- nullptr, // Manages its own audio_sink.
- nullptr, // Does not use video_sink. See StreamTextureWrapper instead.
- std::move(renderer), surface_request_cb, std::move(request));
-}
#endif // defined(OS_ANDROID)
// static
@@ -495,6 +515,7 @@ RenderFrameHostImpl::RenderFrameHostImpl(SiteInstance* site_instance,
render_frame_created_(false),
is_waiting_for_beforeunload_ack_(false),
unload_ack_is_for_navigation_(false),
+ was_discarded_(false),
is_loading_(false),
pending_commit_(false),
nav_entry_id_(0),
@@ -575,6 +596,7 @@ RenderFrameHostImpl::RenderFrameHostImpl(SiteInstance* site_instance,
DCHECK(!render_widget_host_->owned_by_render_frame_host());
render_widget_host_->SetWidget(std::move(widget));
}
+ render_widget_host_->SetFrameDepth(frame_tree_node_->depth());
render_widget_host_->SetWidgetInputHandler(std::move(widget_handler),
std::move(host_request));
render_widget_host_->input_router()->SetFrameTreeNodeId(
@@ -1314,8 +1336,9 @@ void RenderFrameHostImpl::Init() {
waiting_for_init_ = false;
if (pending_navigate_) {
frame_tree_node()->navigator()->OnBeginNavigation(
- frame_tree_node(), pending_navigate_->first,
- std::move(pending_navigate_->second));
+ frame_tree_node(), pending_navigate_->common_params,
+ std::move(pending_navigate_->begin_params),
+ std::move(pending_navigate_->blob_url_loader_factory));
pending_navigate_.reset();
}
}
@@ -1393,7 +1416,7 @@ void RenderFrameHostImpl::OnCreateChildFrame(
std::move(new_interface_provider_provider_request),
scope, frame_name, frame_unique_name,
is_created_by_script, devtools_frame_token,
- frame_policy, frame_owner_properties);
+ frame_policy, frame_owner_properties, was_discarded_);
}
void RenderFrameHostImpl::DidNavigate(
@@ -1430,6 +1453,11 @@ void RenderFrameHostImpl::SetLastCommittedOrigin(const url::Origin& origin) {
CSPContext::SetSelf(origin);
}
+void RenderFrameHostImpl::SetLastCommittedOriginForTesting(
+ const url::Origin& origin) {
+ SetLastCommittedOrigin(origin);
+}
+
void RenderFrameHostImpl::SetLastCommittedUrl(const GURL& url) {
last_committed_url_ = url;
}
@@ -1585,12 +1613,14 @@ void RenderFrameHostImpl::DidCommitProvisionalLoad(
OnBeforeUnloadACK(true, approx_renderer_start_time, base::TimeTicks::Now());
}
- // If we're waiting for an unload ack from this renderer and we receive a
- // Navigate message, then the renderer was navigating before it received the
- // unload request. It will either respond to the unload request soon or our
- // timer will expire. Either way, we should ignore this message, because we
- // have already committed to closing this renderer.
- if (IsWaitingForUnloadACK())
+ // If we're waiting for an unload ack from this frame and we receive a commit
+ // message, then the frame was navigating before it received the unload
+ // request. It will either respond to the unload request soon or our timer
+ // will expire. Either way, we should ignore this message, because we have
+ // already committed to destroying this RenderFrameHost. Note that we
+ // intentionally do not ignore commits that happen while the current tab is
+ // being closed - see https://crbug.com/805705.
+ if (is_waiting_for_swapout_ack_)
return;
// Retroactive sanity check:
@@ -1608,7 +1638,11 @@ void RenderFrameHostImpl::DidCommitProvisionalLoad(
// request end of a new InterfaceProvider connection that will be used by
// the new document to issue interface requests to access RenderFrameHost
// services.
- document_scoped_interface_provider_binding_.Close();
+ auto interface_provider_request_of_previous_document =
+ document_scoped_interface_provider_binding_.Unbind();
+ dropped_interface_request_logger_ =
+ std::make_unique<DroppedInterfaceRequestLogger>(
+ std::move(interface_provider_request_of_previous_document));
BindInterfaceProviderRequest(std::move(interface_provider_request));
} else {
// If there had already been a real load committed in the frame, and this is
@@ -1659,14 +1693,16 @@ void RenderFrameHostImpl::DidCommitSameDocumentNavigation(
frame_tree_node()->frame_tree()->root()->current_origin());
ScopedCommitStateResetter commit_state_resetter(this);
- // If we're waiting for an unload ack from this renderer and we receive a
- // Navigate message, then the renderer was navigating before it received the
- // unload request. It will either respond to the unload request soon or our
- // timer will expire. Either way, we should ignore this message, because we
- // have already committed to closing this renderer.
+ // If we're waiting for an unload ack from this frame and we receive a commit
+ // message, then the frame was navigating before it received the unload
+ // request. It will either respond to the unload request soon or our timer
+ // will expire. Either way, we should ignore this message, because we have
+ // already committed to destroying this RenderFrameHost. Note that we
+ // intentionally do not ignore commits that happen while the current tab is
+ // being closed - see https://crbug.com/805705.
// TODO(ahemery): Investigate to see if this can be removed when the
// NavigationClient interface is implemented.
- if (IsWaitingForUnloadACK())
+ if (is_waiting_for_swapout_ack_)
return;
TRACE_EVENT2("navigation",
@@ -1779,7 +1815,7 @@ void RenderFrameHostImpl::SwapOut(
// simulating the receipt of swap out ack.
is_waiting_for_swapout_ack_ = true;
if (frame_tree_node_->IsMainFrame())
- render_view_host_->set_is_active(false);
+ render_view_host_->SetIsActive(false);
}
void RenderFrameHostImpl::OnBeforeUnloadACK(
@@ -1890,8 +1926,8 @@ void RenderFrameHostImpl::OnRenderProcessGone(int status, int exit_code) {
// Execute any pending AX tree snapshot callbacks with an empty response,
// since we're never going to get a response from this renderer.
- for (const auto& iter : ax_tree_snapshot_callbacks_)
- iter.second.Run(ui::AXTreeUpdate());
+ for (auto& iter : ax_tree_snapshot_callbacks_)
+ std::move(iter.second).Run(ui::AXTreeUpdate());
#if defined(OS_ANDROID)
// Execute any pending Samsung smart clip callbacks.
@@ -1943,11 +1979,11 @@ void RenderFrameHostImpl::OnSwappedOut() {
ClearAllWebUI();
// If this is a main frame RFH that's about to be deleted, update its RVH's
- // swapped-out state here. https://crbug.com/505887
- if (frame_tree_node_->IsMainFrame()) {
- render_view_host_->set_is_active(false);
+ // swapped-out state here. https://crbug.com/505887. This should only be
+ // done if the RVH hasn't been already reused and marked as active by another
+ // navigation. See https://crbug.com/823567.
+ if (frame_tree_node_->IsMainFrame() && !render_view_host_->is_active())
render_view_host_->set_is_swapped_out(true);
- }
bool deleted =
frame_tree_node_->render_manager()->DeleteFromPendingList(this);
@@ -2042,12 +2078,13 @@ void RenderFrameHostImpl::OnVisualStateResponse(uint64_t id) {
void RenderFrameHostImpl::OnRunJavaScriptDialog(
const base::string16& message,
const base::string16& default_prompt,
- const GURL& frame_url,
JavaScriptDialogType dialog_type,
IPC::Message* reply_msg) {
if (dialog_type == JavaScriptDialogType::JAVASCRIPT_DIALOG_TYPE_ALERT)
GetFrameResourceCoordinator()->OnAlertFired();
+ // Don't show the dialog if it's triggered on a frame that's pending deletion
+ // (e.g., from an unload handler), or when the tab is being closed.
if (IsWaitingForUnloadACK()) {
SendJavaScriptDialogReply(reply_msg, true, base::string16());
return;
@@ -2064,27 +2101,16 @@ void RenderFrameHostImpl::OnRunJavaScriptDialog(
// process input events.
GetProcess()->SetIgnoreInputEvents(true);
- // TODO(nasko): It is strange to accept the frame URL as a parameter from
- // the renderer. Investigate and remove parameter, but for now let's
- // double check.
- DCHECK_EQ(frame_url, last_committed_url_);
-
delegate_->RunJavaScriptDialog(this, message, default_prompt, dialog_type,
reply_msg);
}
void RenderFrameHostImpl::OnRunBeforeUnloadConfirm(
- const GURL& frame_url,
bool is_reload,
IPC::Message* reply_msg) {
TRACE_EVENT1("navigation", "RenderFrameHostImpl::OnRunBeforeUnloadConfirm",
"frame_tree_node", frame_tree_node_->frame_tree_node_id());
- // TODO(nasko): It is strange to accept the frame URL as a parameter from
- // the renderer. Investigate and remove parameter, but for now let's
- // double check.
- DCHECK_EQ(frame_url, last_committed_url_);
-
// While a JS beforeunload dialog is showing, tabs in the same process
// shouldn't process input events.
GetProcess()->SetIgnoreInputEvents(true);
@@ -2384,9 +2410,15 @@ void RenderFrameHostImpl::FrameSizeChanged(const gfx::Size& frame_size) {
}
void RenderFrameHostImpl::OnUpdatePictureInPictureSurfaceId(
- const viz::SurfaceId& surface_id) {
+ const viz::SurfaceId& surface_id,
+ const gfx::Size& natural_size) {
+ if (delegate_)
+ delegate_->UpdatePictureInPictureSurfaceId(surface_id, natural_size);
+}
+
+void RenderFrameHostImpl::OnExitPictureInPicture() {
if (delegate_)
- delegate_->UpdatePictureInPictureSurfaceId(surface_id);
+ delegate_->ExitPictureInPicture();
}
void RenderFrameHostImpl::OnDidBlockFramebust(const GURL& url) {
@@ -2409,6 +2441,9 @@ void RenderFrameHostImpl::OnForwardResourceTimingToParent(
if (!is_active())
return;
+ // We should never be receiving this message from a speculative RFH.
+ DCHECK(IsCurrent());
+
RenderFrameProxyHost* proxy =
frame_tree_node()->render_manager()->GetProxyToParent();
if (!proxy) {
@@ -2430,6 +2465,9 @@ void RenderFrameHostImpl::OnDispatchLoad() {
if (!is_active())
return;
+ // We should never be receiving this message from a speculative RFH.
+ DCHECK(IsCurrent());
+
// Only frames with an out-of-process parent frame should be sending this
// message.
RenderFrameProxyHost* proxy =
@@ -2627,7 +2665,7 @@ void RenderFrameHostImpl::OnAccessibilitySnapshotResponse(
AXContentTreeDataToAXTreeData(&dst_snapshot.tree_data);
dst_snapshot.has_tree_data = true;
}
- it->second.Run(dst_snapshot);
+ std::move(it->second).Run(dst_snapshot);
ax_tree_snapshot_callbacks_.erase(it);
} else {
NOTREACHED() << "Received AX tree snapshot response for unknown id";
@@ -2734,6 +2772,7 @@ void RenderFrameHostImpl::OnDidStopLoading() {
if (!is_loading_)
return;
+ was_discarded_ = false;
is_loading_ = false;
navigation_request_.reset();
@@ -2778,8 +2817,8 @@ void RenderFrameHostImpl::OnFocusedNodeChanged(
bounds_in_frame_widget.size()));
}
-void RenderFrameHostImpl::SetHasReceivedUserGesture() {
- Send(new FrameMsg_SetHasReceivedUserGesture(routing_id_));
+void RenderFrameHostImpl::NotifyUserActivation() {
+ Send(new FrameMsg_NotifyUserActivation(routing_id_));
}
void RenderFrameHostImpl::OnSetHasReceivedUserGesture() {
@@ -2962,7 +3001,7 @@ void RenderFrameHostImpl::CreateNewWindow(
},
GlobalFrameRoutingId(render_process_id, main_frame_route_id));
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
- block_requests_for_route);
+ std::move(block_requests_for_route));
}
DCHECK(IsRenderFrameLive());
@@ -3013,12 +3052,6 @@ void RenderFrameHostImpl::CreateNewWindow(
void RenderFrameHostImpl::IssueKeepAliveHandle(
mojom::KeepAliveHandleRequest request) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
- if (!base::FeatureList::IsEnabled(
- features::kKeepAliveRendererForKeepaliveRequests)) {
- bad_message::ReceivedBadMessage(
- GetProcess(), bad_message::RFH_KEEP_ALIVE_HANDLE_REQUESTED_INCORRECTLY);
- return;
- }
if (GetProcess()->IsKeepAliveRefCountDisabled())
return;
@@ -3034,7 +3067,8 @@ void RenderFrameHostImpl::IssueKeepAliveHandle(
// otherwise mojo bad message reporting.
void RenderFrameHostImpl::BeginNavigation(
const CommonNavigationParams& common_params,
- mojom::BeginNavigationParamsPtr begin_params) {
+ mojom::BeginNavigationParamsPtr begin_params,
+ blink::mojom::BlobURLTokenPtr blob_url_token) {
if (!is_active())
return;
@@ -3065,24 +3099,38 @@ void RenderFrameHostImpl::BeginNavigation(
return;
}
+ if (blob_url_token && !validated_params.url.SchemeIsBlob()) {
+ mojo::ReportBadMessage("Blob URL Token, but not a blob: URL");
+ return;
+ }
+ scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory;
+ if (blob_url_token) {
+ blob_url_loader_factory =
+ ChromeBlobStorageContext::URLLoaderFactoryForToken(
+ GetSiteInstance()->GetBrowserContext(), std::move(blob_url_token));
+ }
+
if (waiting_for_init_) {
pending_navigate_ = std::make_unique<PendingNavigation>(
- validated_params, std::move(begin_params));
+ validated_params, std::move(begin_params),
+ std::move(blob_url_loader_factory));
return;
}
frame_tree_node()->navigator()->OnBeginNavigation(
- frame_tree_node(), validated_params, std::move(begin_params));
+ frame_tree_node(), validated_params, std::move(begin_params),
+ std::move(blob_url_loader_factory));
+}
+
+void RenderFrameHostImpl::SubresourceResponseStarted(
+ const GURL& url,
+ net::CertStatus cert_status) {
+ delegate_->SubresourceResponseStarted(url, cert_status);
}
-void RenderFrameHostImpl::SubresourceResponseStarted(const GURL& url,
- const GURL& referrer,
- const std::string& method,
- ResourceType resource_type,
- const std::string& ip,
- uint32_t cert_status) {
- delegate_->SubresourceResponseStarted(url, referrer, method, resource_type,
- ip, cert_status);
+void RenderFrameHostImpl::ResourceLoadComplete(
+ mojom::ResourceLoadInfoPtr resource_load_info) {
+ delegate_->ResourceLoadComplete(std::move(resource_load_info));
}
namespace {
@@ -3158,13 +3206,6 @@ void RenderFrameHostImpl::RegisterMojoInterfaces() {
registry_->AddInterface(
base::Bind(&MediaSessionServiceImpl::Create, base::Unretained(this)));
-#if defined(OS_ANDROID)
- // Creates a MojoRendererService, passing it a MediaPlayerRender.
- registry_->AddInterface<media::mojom::Renderer>(
- base::Bind(&content::CreateMediaPlayerRenderer, GetProcess()->GetID(),
- GetRoutingID(), delegate_));
-#endif // defined(OS_ANDROID)
-
registry_->AddInterface(base::Bind(
base::IgnoreResult(&RenderFrameHostImpl::CreateWebBluetoothService),
base::Unretained(this)));
@@ -3179,11 +3220,8 @@ void RenderFrameHostImpl::RegisterMojoInterfaces() {
base::Bind(&RenderFrameHostImpl::BindMediaInterfaceFactoryRequest,
base::Unretained(this)));
- // This is to support usage of WebSockets in cases in which there is an
- // associated RenderFrame. This is important for showing the correct security
- // state of the page and also honoring user override of bad certificates.
- registry_->AddInterface(base::Bind(&WebSocketManager::CreateWebSocketForFrame,
- process_->GetID(), routing_id_));
+ registry_->AddInterface(base::BindRepeating(
+ &RenderFrameHostImpl::CreateWebSocket, base::Unretained(this)));
registry_->AddInterface(base::Bind(&SharedWorkerConnectorImpl::Create,
process_->GetID(), routing_id_));
@@ -3236,7 +3274,7 @@ void RenderFrameHostImpl::RegisterMojoInterfaces() {
GetProcess()->GetID(), GetRoutingID()));
#endif // BUILDFLAG(ENABLE_MEDIA_REMOTING)
- registry_->AddInterface(base::Bind(
+ registry_->AddInterface(base::BindRepeating(
&KeyboardLockServiceImpl::CreateMojoService, base::Unretained(this)));
registry_->AddInterface(base::Bind(&ImageCaptureImpl::Create));
@@ -3246,6 +3284,14 @@ void RenderFrameHostImpl::RegisterMojoInterfaces() {
registry_->AddInterface(
base::Bind(&RenderFrameHostImpl::BindAuthenticatorRequest,
base::Unretained(this)));
+ if (base::CommandLine::ForCurrentProcess()->HasSwitch(
+ switches::kEnableWebAuthTestingAPI)) {
+ auto* environment_singleton =
+ ScopedVirtualAuthenticatorEnvironment::GetInstance();
+ registry_->AddInterface(base::BindRepeating(
+ &ScopedVirtualAuthenticatorEnvironment::AddBinding,
+ base::Unretained(environment_singleton)));
+ }
}
#endif // !defined(OS_ANDROID)
@@ -3365,6 +3411,7 @@ void RenderFrameHostImpl::NavigateToInterstitialURL(const GURL& data_url) {
CommitNavigation(nullptr, network::mojom::URLLoaderClientEndpointsPtr(),
std::unique_ptr<StreamHandle>(), common_params,
RequestNavigationParams(), false, base::nullopt,
+ base::nullopt /* subresource_overrides */,
base::UnguessableToken::Create() /* not traced */);
}
@@ -3513,6 +3560,8 @@ void RenderFrameHostImpl::CommitNavigation(
const RequestNavigationParams& request_params,
bool is_view_source,
base::Optional<SubresourceLoaderParams> subresource_loader_params,
+ base::Optional<std::vector<mojom::TransferrableURLLoaderPtr>>
+ subresource_overrides,
const base::UnguessableToken& devtools_navigation_token) {
TRACE_EVENT2("navigation", "RenderFrameHostImpl::CommitNavigation",
"frame_tree_node", frame_tree_node_->frame_tree_node_id(), "url",
@@ -3570,7 +3619,7 @@ void RenderFrameHostImpl::CommitNavigation(
const auto& schemes = URLDataManagerBackend::GetWebUISchemes();
if (std::find(schemes.begin(), schemes.end(), scheme) != schemes.end()) {
network::mojom::URLLoaderFactoryPtr factory_for_webui =
- CreateWebUIURLLoader(this, scheme);
+ CreateWebUIURLLoaderBinding(this, scheme);
if (enabled_bindings_ & BINDINGS_POLICY_WEB_UI) {
// If the renderer has webui bindings, then don't give it access to
// network loader for security reasons.
@@ -3624,6 +3673,9 @@ void RenderFrameHostImpl::CommitNavigation(
auto factory_request = mojo::MakeRequest(&factory_proxy_info);
GetContentClient()->browser()->WillCreateURLLoaderFactory(
this, false /* is_navigation */, &factory_request);
+ // Keep DevTools proxy lasy, i.e. closest to the network.
+ RenderFrameDevToolsAgentHost::WillCreateURLLoaderFactory(
+ this, false, &factory_request);
factory.second->Clone(std::move(factory_request));
subresource_loader_factories->factories_info().emplace(
factory.first, std::move(factory_proxy_info));
@@ -3657,6 +3709,7 @@ void RenderFrameHostImpl::CommitNavigation(
head, body_url, common_params, request_params,
std::move(url_loader_client_endpoints),
std::move(subresource_loader_factories),
+ std::move(subresource_overrides),
std::move(controller_service_worker_info), devtools_navigation_token);
// If a network request was made, update the Previews state.
@@ -3945,16 +3998,18 @@ bool RenderFrameHostImpl::IsSameSiteInstance(
}
void RenderFrameHostImpl::UpdateAccessibilityMode() {
- int accessibility_mode_raw = delegate_->GetAccessibilityMode().mode();
- Send(new FrameMsg_SetAccessibilityMode(routing_id_, accessibility_mode_raw));
+ Send(new FrameMsg_SetAccessibilityMode(routing_id_,
+ delegate_->GetAccessibilityMode()));
}
-void RenderFrameHostImpl::RequestAXTreeSnapshot(
- AXTreeSnapshotCallback callback) {
+void RenderFrameHostImpl::RequestAXTreeSnapshot(AXTreeSnapshotCallback callback,
+ ui::AXMode ax_mode) {
static int next_id = 1;
int callback_id = next_id++;
- Send(new AccessibilityMsg_SnapshotTree(routing_id_, callback_id));
- ax_tree_snapshot_callbacks_.insert(std::make_pair(callback_id, callback));
+ Send(new AccessibilityMsg_SnapshotTree(routing_id_, callback_id,
+ ax_mode.mode()));
+ ax_tree_snapshot_callbacks_.insert(
+ std::make_pair(callback_id, std::move(callback)));
}
void RenderFrameHostImpl::SetAccessibilityCallbackForTesting(
@@ -4152,10 +4207,14 @@ void RenderFrameHostImpl::UpdatePermissionsForNavigation(
GrantFileAccessFromResourceRequestBody(*common_params.post_data);
}
-void RenderFrameHostImpl::OnNetworkServiceConnectionError() {
+void RenderFrameHostImpl::UpdateSubresourceLoaderFactories() {
DCHECK(base::FeatureList::IsEnabled(network::features::kNetworkService));
- DCHECK(network_service_connection_error_handler_holder_.is_bound() &&
- network_service_connection_error_handler_holder_.encountered_error());
+ // We only send loader factory bundle upon navigation, so
+ // bail out if the frame hasn't commited any yet.
+ if (!has_committed_any_navigation_)
+ return;
+ DCHECK(network_service_connection_error_handler_holder_.is_bound());
+
network::mojom::URLLoaderFactoryPtrInfo default_factory_info;
CreateNetworkServiceDefaultFactoryAndObserve(
mojo::MakeRequest(&default_factory_info));
@@ -4173,6 +4232,9 @@ void RenderFrameHostImpl::CreateNetworkServiceDefaultFactoryAndObserve(
auto* context = GetSiteInstance()->GetBrowserContext();
GetContentClient()->browser()->WillCreateURLLoaderFactory(
this, false /* is_navigation */, &default_factory_request);
+ // Keep DevTools proxy lasy, i.e. closest to the network.
+ RenderFrameDevToolsAgentHost::WillCreateURLLoaderFactory(
+ this, false, &default_factory_request);
StoragePartitionImpl* storage_partition = static_cast<StoragePartitionImpl*>(
BrowserContext::GetStoragePartition(context, GetSiteInstance()));
if (g_create_network_factory_callback_for_test.Get().is_null()) {
@@ -4195,7 +4257,7 @@ void RenderFrameHostImpl::CreateNetworkServiceDefaultFactoryAndObserve(
GetProcess()->GetID());
network_service_connection_error_handler_holder_
.set_connection_error_handler(base::BindOnce(
- &RenderFrameHostImpl::OnNetworkServiceConnectionError,
+ &RenderFrameHostImpl::UpdateSubresourceLoaderFactories,
weak_ptr_factory_.GetWeakPtr()));
}
}
@@ -4334,8 +4396,8 @@ WebBluetoothServiceImpl* RenderFrameHostImpl::CreateWebBluetoothService(
auto web_bluetooth_service =
std::make_unique<WebBluetoothServiceImpl>(this, std::move(request));
web_bluetooth_service->SetClientConnectionErrorHandler(
- base::Bind(&RenderFrameHostImpl::DeleteWebBluetoothService,
- base::Unretained(this), web_bluetooth_service.get()));
+ base::BindOnce(&RenderFrameHostImpl::DeleteWebBluetoothService,
+ base::Unretained(this), web_bluetooth_service.get()));
web_bluetooth_services_.push_back(std::move(web_bluetooth_service));
return web_bluetooth_services_.back().get();
}
@@ -4421,6 +4483,25 @@ void RenderFrameHostImpl::BindMediaInterfaceFactoryRequest(
base::Unretained(this))));
}
+void RenderFrameHostImpl::CreateWebSocket(
+ network::mojom::WebSocketRequest request) {
+ if (base::FeatureList::IsEnabled(network::features::kNetworkService)) {
+ auto* context = GetSiteInstance()->GetBrowserContext();
+ auto* storage_partition = static_cast<StoragePartitionImpl*>(
+ BrowserContext::GetStoragePartition(context, GetSiteInstance()));
+ storage_partition->GetNetworkContext()->CreateWebSocket(
+ std::move(request), process_->GetID(), routing_id_,
+ last_committed_origin_);
+ } else {
+ // This is to support usage of WebSockets in cases in which there is an
+ // associated RenderFrame. This is important for showing the correct
+ // security state of the page and also honoring user override of bad
+ // certificates.
+ WebSocketManager::CreateWebSocketForFrame(process_->GetID(), routing_id_,
+ std::move(request));
+ }
+}
+
void RenderFrameHostImpl::OnMediaInterfaceFactoryConnectionError() {
DCHECK(media_interface_proxy_);
media_interface_proxy_.reset();
@@ -4468,7 +4549,7 @@ void RenderFrameHostImpl::GetInterface(
if (!registry_ ||
!registry_->TryBindInterface(interface_name, &interface_pipe)) {
delegate_->OnInterfaceRequest(this, interface_name, &interface_pipe);
- if (interface_pipe->is_valid() &&
+ if (interface_pipe.is_valid() &&
!TryBindFrameInterface(interface_name, &interface_pipe, this)) {
GetContentClient()->browser()->BindInterfaceRequestFromFrame(
this, interface_name, std::move(interface_pipe));
@@ -4833,6 +4914,9 @@ bool RenderFrameHostImpl::DidCommitNavigationInternal(
pending_commit_ = false;
}
+ if (navigation_request_)
+ was_discarded_ = navigation_request_->request_params().was_discarded;
+
// Find the appropriate NavigationHandle for this navigation.
std::unique_ptr<NavigationHandleImpl> navigation_handle;
diff --git a/chromium/content/browser/frame_host/render_frame_host_impl.h b/chromium/content/browser/frame_host/render_frame_host_impl.h
index c6c75f1e94f..5b85cfa21b9 100644
--- a/chromium/content/browser/frame_host/render_frame_host_impl.h
+++ b/chromium/content/browser/frame_host/render_frame_host_impl.h
@@ -36,10 +36,10 @@
#include "content/browser/site_instance_impl.h"
#include "content/browser/webui/web_ui_impl.h"
#include "content/common/ax_content_node_data.h"
+#include "content/common/buildflags.h"
#include "content/common/content_export.h"
#include "content/common/content_security_policy/csp_context.h"
#include "content/common/download/mhtml_save_status.h"
-#include "content/common/features.h"
#include "content/common/frame.mojom.h"
#include "content/common/frame_message_enums.h"
#include "content/common/frame_replication_state.h"
@@ -51,6 +51,7 @@
#include "content/public/browser/render_frame_host.h"
#include "content/public/common/javascript_dialog_type.h"
#include "content/public/common/previews_state.h"
+#include "content/public/common/transferrable_url_loader.mojom.h"
#include "media/mojo/interfaces/interface_factory.mojom.h"
#include "mojo/public/cpp/bindings/binding_set.h"
#include "mojo/public/cpp/system/data_pipe.h"
@@ -59,16 +60,16 @@
#include "services/service_manager/public/cpp/binder_registry.h"
#include "services/service_manager/public/mojom/interface_provider.mojom.h"
#include "services/viz/public/interfaces/hit_test/input_target_client.mojom.h"
-#include "third_party/WebKit/public/common/feature_policy/feature_policy.h"
-#include "third_party/WebKit/public/platform/WebFocusType.h"
-#include "third_party/WebKit/public/platform/WebInsecureRequestPolicy.h"
-#include "third_party/WebKit/public/platform/WebSuddenTerminationDisablerType.h"
-#include "third_party/WebKit/public/platform/modules/bluetooth/web_bluetooth.mojom.h"
-#include "third_party/WebKit/public/platform/modules/presentation/presentation.mojom.h"
-#include "third_party/WebKit/public/platform/modules/webauth/authenticator.mojom.h"
-#include "third_party/WebKit/public/web/WebTextDirection.h"
-#include "third_party/WebKit/public/web/WebTreeScopeType.h"
-#include "third_party/WebKit/public/web/commit_result.mojom.h"
+#include "third_party/blink/public/common/feature_policy/feature_policy.h"
+#include "third_party/blink/public/platform/modules/bluetooth/web_bluetooth.mojom.h"
+#include "third_party/blink/public/platform/modules/presentation/presentation.mojom.h"
+#include "third_party/blink/public/platform/modules/webauth/authenticator.mojom.h"
+#include "third_party/blink/public/platform/web_focus_type.h"
+#include "third_party/blink/public/platform/web_insecure_request_policy.h"
+#include "third_party/blink/public/platform/web_sudden_termination_disabler_type.h"
+#include "third_party/blink/public/web/commit_result.mojom.h"
+#include "third_party/blink/public/web/web_text_direction.h"
+#include "third_party/blink/public/web/web_tree_scope_type.h"
#include "ui/accessibility/ax_modes.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/base/mojo/window_open_disposition.mojom.h"
@@ -107,7 +108,7 @@ class Range;
namespace network {
class ResourceRequestBody;
struct ResourceResponse;
-}
+} // namespace network
namespace content {
class AssociatedInterfaceProviderImpl;
@@ -157,8 +158,7 @@ class CONTENT_EXPORT RenderFrameHostImpl
public CSPContext {
public:
using AXTreeSnapshotCallback =
- base::Callback<void(
- const ui::AXTreeUpdate&)>;
+ base::OnceCallback<void(const ui::AXTreeUpdate&)>;
// An accessibility reset is only allowed to prevent very rare corner cases
// or race conditions where the browser and renderer get out of sync. If
@@ -339,6 +339,9 @@ class CONTENT_EXPORT RenderFrameHostImpl
// cases, use GetLastCommittedURL instead.
const GURL& last_successful_url() { return last_successful_url_; }
+ // Allows overriding the last committed origin in tests.
+ void SetLastCommittedOriginForTesting(const url::Origin& origin);
+
// Fetch the link-rel canonical URL to be used for sharing to external
// applications.
void GetCanonicalUrlForSharing(
@@ -494,7 +497,8 @@ class CONTENT_EXPORT RenderFrameHostImpl
// Request a one-time snapshot of the accessibility tree without changing
// the accessibility mode.
- void RequestAXTreeSnapshot(AXTreeSnapshotCallback callback);
+ void RequestAXTreeSnapshot(AXTreeSnapshotCallback callback,
+ ui::AXMode ax_mode);
// Resets the accessibility serializer in the renderer.
void AccessibilityReset();
@@ -564,6 +568,8 @@ class CONTENT_EXPORT RenderFrameHostImpl
const RequestNavigationParams& request_params,
bool is_view_source,
base::Optional<SubresourceLoaderParams> subresource_loader_params,
+ base::Optional<std::vector<mojom::TransferrableURLLoaderPtr>>
+ subresource_overrides,
const base::UnguessableToken& devtools_navigation_token);
// Indicates that a navigation failed and that this RenderFrame should display
@@ -695,17 +701,22 @@ class CONTENT_EXPORT RenderFrameHostImpl
return active_sandbox_flags_;
}
- // Call |FlushForTesting()| on Network Service and FrameNavigationControl
+ // Calls |FlushForTesting()| on Network Service and FrameNavigationControl
// related interfaces to make sure all in-flight mojo messages have been
// received by the other end. For test use only.
void FlushNetworkAndNavigationInterfacesForTesting();
- // Notifies the render frame that a user gesture was received.
- void SetHasReceivedUserGesture();
+ // Notifies the render frame about a user activation from the browser side.
+ void NotifyUserActivation();
// Returns the current size for this frame.
const base::Optional<gfx::Size>& frame_size() const { return frame_size_; }
+ // Re-creates loader factories and pushes them to |RenderFrame|.
+ // Used in case we need to add or remove intercepting proxies to the
+ // running renderer, or in case of Network Service connection errors.
+ void UpdateSubresourceLoaderFactories();
+
protected:
friend class RenderFrameHostFactory;
@@ -748,6 +759,8 @@ class CONTENT_EXPORT RenderFrameHostImpl
FRIEND_TEST_ALL_PREFIXES(SitePerProcessBrowserTest,
RenderViewHostIsNotReusedAfterDelayedSwapOutACK);
FRIEND_TEST_ALL_PREFIXES(SitePerProcessBrowserTest,
+ RenderViewHostStaysActiveWithLateSwapoutACK);
+ FRIEND_TEST_ALL_PREFIXES(SitePerProcessBrowserTest,
LoadEventForwardingWhilePendingDeletion);
FRIEND_TEST_ALL_PREFIXES(SitePerProcessBrowserTest,
ContextMenuAfterCrossProcessNavigation);
@@ -756,6 +769,8 @@ class CONTENT_EXPORT RenderFrameHostImpl
FRIEND_TEST_ALL_PREFIXES(SecurityExploitBrowserTest,
AttemptDuplicateRenderViewHost);
+ class DroppedInterfaceRequestLogger;
+
// IPC Message handlers.
void OnDidAddMessageToConsole(int32_t level,
const base::string16& message,
@@ -788,12 +803,9 @@ class CONTENT_EXPORT RenderFrameHostImpl
void OnVisualStateResponse(uint64_t id);
void OnRunJavaScriptDialog(const base::string16& message,
const base::string16& default_prompt,
- const GURL& frame_url,
JavaScriptDialogType dialog_type,
IPC::Message* reply_msg);
- void OnRunBeforeUnloadConfirm(const GURL& frame_url,
- bool is_reload,
- IPC::Message* reply_msg);
+ void OnRunBeforeUnloadConfirm(bool is_reload, IPC::Message* reply_msg);
void OnRunFileChooser(const FileChooserParams& params);
void OnTextSurroundingSelectionResponse(const base::string16& content,
uint32_t start_offset,
@@ -888,13 +900,12 @@ class CONTENT_EXPORT RenderFrameHostImpl
std::unique_ptr<FrameHostMsg_DidCommitProvisionalLoad_Params>
validated_params) override;
void BeginNavigation(const CommonNavigationParams& common_params,
- mojom::BeginNavigationParamsPtr begin_params) override;
+ mojom::BeginNavigationParamsPtr begin_params,
+ blink::mojom::BlobURLTokenPtr blob_url_token) override;
void SubresourceResponseStarted(const GURL& url,
- const GURL& referrer,
- const std::string& method,
- ResourceType resource_type,
- const std::string& ip,
- uint32_t cert_status) override;
+ net::CertStatus cert_status) override;
+ void ResourceLoadComplete(
+ mojom::ResourceLoadInfoPtr resource_load_info) override;
void DidChangeName(const std::string& name,
const std::string& unique_name) override;
void EnforceInsecureRequestPolicy(
@@ -907,7 +918,9 @@ class CONTENT_EXPORT RenderFrameHostImpl
void UpdateEncoding(const std::string& encoding) override;
void FrameSizeChanged(const gfx::Size& frame_size) override;
void OnUpdatePictureInPictureSurfaceId(
- const viz::SurfaceId& surface_id) override;
+ const viz::SurfaceId& surface_id,
+ const gfx::Size& natural_size) override;
+ void OnExitPictureInPicture() override;
// Registers Mojo interfaces that this frame host makes available.
void RegisterMojoInterfaces();
@@ -949,10 +962,6 @@ class CONTENT_EXPORT RenderFrameHostImpl
const CommonNavigationParams& common_params,
const RequestNavigationParams& request_params);
- // Handle Network Service connection errors. Will re-create broken Network
- // Service-backed factories and send to |RenderFrame|.
- void OnNetworkServiceConnectionError();
-
// Creates a Network Service-backed factory from appropriate |NetworkContext|
// and sets a connection error handler to trigger
// |OnNetworkServiceConnectionError()| if the factory is out-of-process.
@@ -1019,6 +1028,8 @@ class CONTENT_EXPORT RenderFrameHostImpl
void BindMediaInterfaceFactoryRequest(
media::mojom::InterfaceFactoryRequest request);
+ void CreateWebSocket(network::mojom::WebSocketRequest request);
+
// Callback for connection error on the media::mojom::InterfaceFactory client.
void OnMediaInterfaceFactoryConnectionError();
@@ -1229,6 +1240,10 @@ class CONTENT_EXPORT RenderFrameHostImpl
// to OnBeforeUnloadACK(), or until the timeout triggers.
std::unique_ptr<TimeoutMonitor> beforeunload_timeout_;
+ // Returns whether the tab was previously discarded.
+ // This is passed to RequestNavigationParams in NavigationRequest.
+ bool was_discarded_;
+
// Indicates whether this RenderFrameHost is in the process of loading a
// document or not.
bool is_loading_;
@@ -1372,8 +1387,16 @@ class CONTENT_EXPORT RenderFrameHostImpl
// If true then this frame's document has a focused element which is editable.
bool has_focused_editable_element_;
- typedef std::pair<CommonNavigationParams, mojom::BeginNavigationParamsPtr>
- PendingNavigation;
+ struct PendingNavigation {
+ PendingNavigation(
+ const CommonNavigationParams& common_params,
+ mojom::BeginNavigationParamsPtr begin_params,
+ scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory);
+ ~PendingNavigation();
+ CommonNavigationParams common_params;
+ mojom::BeginNavigationParamsPtr begin_params;
+ scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory;
+ };
std::unique_ptr<PendingNavigation> pending_navigate_;
// A collection of non-network URLLoaderFactory implementations which are used
@@ -1473,6 +1496,14 @@ class CONTENT_EXPORT RenderFrameHostImpl
mojo::Binding<service_manager::mojom::InterfaceProvider>
document_scoped_interface_provider_binding_;
+ // Logs interface requests that arrive after the frame has already committed a
+ // non-same-document navigation, and has already unbound
+ // |document_scoped_interface_provider_binding_| from the interface connection
+ // that had been used to service RenderFrame::GetRemoteInterface for the
+ // previously active document in the frame.
+ std::unique_ptr<DroppedInterfaceRequestLogger>
+ dropped_interface_request_logger_;
+
// IPC-friendly token that represents this host for AndroidOverlays, if we
// have created one yet.
base::Optional<base::UnguessableToken> overlay_routing_token_;
diff --git a/chromium/content/browser/frame_host/render_frame_host_impl_browsertest.cc b/chromium/content/browser/frame_host/render_frame_host_impl_browsertest.cc
index 5255dae995c..f4b891346d8 100644
--- a/chromium/content/browser/frame_host/render_frame_host_impl_browsertest.cc
+++ b/chromium/content/browser/frame_host/render_frame_host_impl_browsertest.cc
@@ -10,6 +10,7 @@
#include "base/bind_helpers.h"
#include "base/run_loop.h"
#include "base/test/bind_test_util.h"
+#include "base/test/histogram_tester.h"
#include "base/test/mock_callback.h"
#include "build/build_config.h"
#include "content/browser/frame_host/navigation_handle_impl.h"
@@ -38,7 +39,7 @@
#include "net/test/embedded_test_server/http_request.h"
#include "services/network/public/cpp/features.h"
#include "testing/gmock/include/gmock/gmock.h"
-#include "third_party/WebKit/public/mojom/page/page_visibility_state.mojom.h"
+#include "third_party/blink/public/mojom/page/page_visibility_state.mojom.h"
namespace content {
@@ -275,6 +276,11 @@ class DropBeforeUnloadACKFilter : public BrowserMessageFilter {
DISALLOW_COPY_AND_ASSIGN(DropBeforeUnloadACKFilter);
};
+mojo::ScopedMessagePipeHandle CreateDisconnectedMessagePipeHandle() {
+ mojo::MessagePipe pipe;
+ return std::move(pipe.handle0);
+}
+
} // namespace
// Tests that a beforeunload dialog in an iframe doesn't stop the beforeunload
@@ -566,7 +572,7 @@ IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
RenderProcessHost* renderer_process = main_frame->GetProcess();
RenderProcessHostWatcher crash_observer(
renderer_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
- renderer_process->Shutdown(0, false);
+ renderer_process->Shutdown(0);
crash_observer.Wait();
// The |stream_handle_| must have been released now.
@@ -704,7 +710,7 @@ IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
RenderProcessHost* renderer_process = main_frame->GetProcess();
RenderProcessHostWatcher crash_observer(
renderer_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
- renderer_process->Shutdown(0, false);
+ renderer_process->Shutdown(0);
crash_observer.Wait();
EXPECT_FALSE(main_frame->GetSuddenTerminationDisablerState(
@@ -1299,4 +1305,93 @@ IN_PROC_BROWSER_TEST_F(
EXPECT_EQ(url::Origin::Create(kMainFrameURL), child->current_origin());
}
+// Verify that if the UMA histograms are correctly recording if interface
+// provider requests are getting dropped because they racily arrive from the
+// previously active document (after the next navigation already committed).
+IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
+ DroppedInterfaceRequestCounter) {
+ const GURL kUrl1(embedded_test_server()->GetURL("/title1.html"));
+ const GURL kUrl2(embedded_test_server()->GetURL("/title2.html"));
+ const GURL kUrl3(embedded_test_server()->GetURL("/title3.html"));
+ const GURL kUrl4(embedded_test_server()->GetURL("/empty.html"));
+
+ // The 31-bit hash of the string "content::mojom::BrowserTarget".
+ const int32_t kHashOfContentMojomBrowserTarget = 0x1CA01D37;
+
+ // Client ends of the fake interface provider requests injected for the first
+ // and second navigations.
+ service_manager::mojom::InterfaceProviderPtr interface_provider_1;
+ service_manager::mojom::InterfaceProviderPtr interface_provider_2;
+
+ base::RunLoop wait_until_connection_error_loop_1;
+ base::RunLoop wait_until_connection_error_loop_2;
+
+ {
+ ScopedFakeInterfaceProviderRequestInjector injector(
+ shell()->web_contents());
+ injector.set_fake_request_for_next_commit(
+ mojo::MakeRequest(&interface_provider_1));
+ interface_provider_1.set_connection_error_handler(
+ wait_until_connection_error_loop_1.QuitClosure());
+ ASSERT_TRUE(NavigateToURL(shell(), kUrl1));
+ }
+
+ {
+ ScopedFakeInterfaceProviderRequestInjector injector(
+ shell()->web_contents());
+ injector.set_fake_request_for_next_commit(
+ mojo::MakeRequest(&interface_provider_2));
+ interface_provider_2.set_connection_error_handler(
+ wait_until_connection_error_loop_2.QuitClosure());
+ ASSERT_TRUE(NavigateToURL(shell(), kUrl2));
+ }
+
+ // Simulate two interface requests corresponding to the first navigation
+ // arrived after the second navigation was committed, hence were dropped.
+ interface_provider_1->GetInterface("content::mojom::BrowserTarget",
+ CreateDisconnectedMessagePipeHandle());
+ interface_provider_1->GetInterface("content::mojom::BrowserTarget",
+ CreateDisconnectedMessagePipeHandle());
+
+ // RFHI destroys the DroppedInterfaceRequestLogger from navigation `n` on
+ // navigation `n+2`. Histrograms are recorded on destruction, there should
+ // be a single sample indicating two requests having been dropped for the
+ // first URL.
+ {
+ base::HistogramTester histogram_tester;
+ ASSERT_TRUE(NavigateToURL(shell(), kUrl3));
+ histogram_tester.ExpectUniqueSample(
+ "RenderFrameHostImpl.DroppedInterfaceRequests", 2, 1);
+ histogram_tester.ExpectUniqueSample(
+ "RenderFrameHostImpl.DroppedInterfaceRequestName",
+ kHashOfContentMojomBrowserTarget, 2);
+ }
+
+ // Simulate one interface request dropped for the second URL.
+ interface_provider_2->GetInterface("content::mojom::BrowserTarget",
+ CreateDisconnectedMessagePipeHandle());
+
+ // A final navigation should record the sample from the second URL.
+ {
+ base::HistogramTester histogram_tester;
+ ASSERT_TRUE(NavigateToURL(shell(), kUrl4));
+ histogram_tester.ExpectUniqueSample(
+ "RenderFrameHostImpl.DroppedInterfaceRequests", 1, 1);
+ histogram_tester.ExpectUniqueSample(
+ "RenderFrameHostImpl.DroppedInterfaceRequestName",
+ kHashOfContentMojomBrowserTarget, 1);
+ }
+
+ // Both the DroppedInterfaceRequestLogger for the first and second URLs are
+ // destroyed -- even more interfacerequests should not cause any crashes.
+ interface_provider_1->GetInterface("content::mojom::BrowserTarget",
+ CreateDisconnectedMessagePipeHandle());
+ interface_provider_2->GetInterface("content::mojom::BrowserTarget",
+ CreateDisconnectedMessagePipeHandle());
+
+ // The interface connections should be broken.
+ wait_until_connection_error_loop_1.Run();
+ wait_until_connection_error_loop_2.Run();
+}
+
} // namespace content
diff --git a/chromium/content/browser/frame_host/render_frame_host_manager.cc b/chromium/content/browser/frame_host/render_frame_host_manager.cc
index 6f16deeb5f4..d7875ac0c04 100644
--- a/chromium/content/browser/frame_host/render_frame_host_manager.cc
+++ b/chromium/content/browser/frame_host/render_frame_host_manager.cc
@@ -18,6 +18,7 @@
#include "base/memory/ptr_util.h"
#include "base/stl_util.h"
#include "base/trace_event/trace_event.h"
+#include "build/build_config.h"
#include "content/browser/child_process_security_policy_impl.h"
#include "content/browser/devtools/render_frame_devtools_agent_host.h"
#include "content/browser/frame_host/debug_urls.h"
@@ -35,7 +36,6 @@
#include "content/browser/renderer_host/render_view_host_factory.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/site_instance_impl.h"
-#include "content/browser/site_isolation_policy.h"
#include "content/browser/webui/web_ui_controller_factory_registry.h"
#include "content/common/frame_messages.h"
#include "content/common/frame_owner_properties.h"
@@ -46,11 +46,16 @@
#include "content/public/browser/render_process_host_observer.h"
#include "content/public/browser/render_widget_host_iterator.h"
#include "content/public/browser/render_widget_host_view.h"
+#include "content/public/browser/site_isolation_policy.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/referrer.h"
#include "content/public/common/url_constants.h"
#include "content/public/common/url_utils.h"
+#if defined(OS_MACOSX)
+#include "ui/gfx/mac/scoped_cocoa_disable_screen_updates.h"
+#endif // defined(OS_MACOSX)
+
namespace content {
RenderFrameHostManager::RenderFrameHostManager(
@@ -420,7 +425,7 @@ void RenderFrameHostManager::DiscardUnusedFrame(
// deleted below. See https://crbug.com/627400.
if (frame_tree_node_->IsMainFrame()) {
rvh->set_main_frame_routing_id(MSG_ROUTING_NONE);
- rvh->set_is_active(false);
+ rvh->SetIsActive(false);
rvh->set_is_swapped_out(true);
}
@@ -509,9 +514,12 @@ RenderFrameHostImpl* RenderFrameHostManager::GetFrameHostForNavigation(
// already updated its state properly, and doesn't need to be notified.
if (speculative_render_frame_host_->GetNavigationHandle() &&
request.from_begin_navigation()) {
+ DCHECK(!speculative_render_frame_host_->GetNavigationHandle()
+ ->IsDownload());
frame_tree_node_->navigator()->DiscardPendingEntryIfNeeded(
speculative_render_frame_host_->GetNavigationHandle()
- ->pending_nav_entry_id());
+ ->pending_nav_entry_id(),
+ false /* is_download */);
}
DiscardUnusedFrame(UnsetSpeculativeRenderFrameHost());
}
@@ -548,9 +556,12 @@ RenderFrameHostImpl* RenderFrameHostManager::GetFrameHostForNavigation(
if (speculative_render_frame_host_ &&
speculative_render_frame_host_->GetNavigationHandle() &&
request.from_begin_navigation()) {
+ DCHECK(!speculative_render_frame_host_->GetNavigationHandle()
+ ->IsDownload());
frame_tree_node_->navigator()->DiscardPendingEntryIfNeeded(
speculative_render_frame_host_->GetNavigationHandle()
- ->pending_nav_entry_id());
+ ->pending_nav_entry_id(),
+ false /* is_download */);
}
// If a previous speculative RenderFrameHost didn't exist or if its
@@ -1027,9 +1038,10 @@ RenderFrameHostManager::GetSiteInstanceForNavigation(
CHECK_NE(new_instance, current_instance);
if (new_instance == current_instance) {
- // If we're navigating to the same site instance, we won't need to use any
- // spare RenderProcessHost.
- RenderProcessHostImpl::CleanupSpareRenderProcessHost();
+ // If we're navigating to the same site instance, we won't need to use the
+ // current spare RenderProcessHost.
+ RenderProcessHostImpl::NotifySpareManagerAboutRecentlyUsedBrowserContext(
+ browser_context);
}
// Double-check that the new SiteInstance is associated with the right
@@ -1250,10 +1262,9 @@ RenderFrameHostManager::DetermineSiteInstanceForURL(
// redirect arbitary requests to those URLs using webRequest or
// declarativeWebRequest API. For these cases, the content isn't controlled
// by the source SiteInstance, so it need not use it.
- GURL about_blank(url::kAboutBlankURL);
GURL about_srcdoc(content::kAboutSrcDocURL);
bool dest_is_data_or_about = dest_url == about_srcdoc ||
- dest_url == about_blank ||
+ dest_url.IsAboutBlank() ||
dest_url.scheme() == url::kDataScheme;
if (source_instance && dest_is_data_or_about && !was_server_redirect)
return SiteInstanceDescriptor(source_instance);
@@ -1262,6 +1273,15 @@ RenderFrameHostManager::DetermineSiteInstanceForURL(
if (IsCurrentlySameSite(render_frame_host_.get(), dest_url))
return SiteInstanceDescriptor(render_frame_host_->GetSiteInstance());
+ // At this point, |dest_url| corresponds to a cross-site navigation. See if
+ // we can swap BrowsingInstances to avoid unneeded process sharing. This is
+ // done for certain main frame browser-initiated navigations. See
+ // https://crbug.com/803367.
+ if (IsBrowsingInstanceSwapAllowedForPageTransition(transition, dest_url)) {
+ return SiteInstanceDescriptor(browser_context, dest_url,
+ SiteInstanceRelation::UNRELATED);
+ }
+
// Shortcut some common cases for reusing an existing frame's SiteInstance.
// There are several reasons for this:
// - looking at the main frame and openers is required for TDI mode.
@@ -1338,6 +1358,43 @@ RenderFrameHostManager::DetermineSiteInstanceForURL(
SiteInstanceRelation::RELATED);
}
+bool RenderFrameHostManager::IsBrowsingInstanceSwapAllowedForPageTransition(
+ ui::PageTransition transition,
+ const GURL& dest_url) {
+ // Disallow BrowsingInstance swaps for subframes.
+ if (!frame_tree_node_->IsMainFrame())
+ return false;
+
+ // Skip data: and file: URLs, as some tests rely on browser-initiated
+ // navigations to those URLs to stay in the same process. Swapping
+ // BrowsingInstances for those URLs may not carry much benefit anyway, since
+ // they're likely less common.
+ //
+ // Note that such URLs are not considered same-site, but since their
+ // SiteInstance site URL is based only on scheme (e.g., all data URLs use a
+ // site URL of "data:"), a browser-initiated navigation from one such URL to
+ // another will still stay in the same SiteInstance, due to the matching site
+ // URL.
+ if (dest_url.SchemeIsFile() || dest_url.SchemeIs(url::kDataScheme))
+ return false;
+
+ // Allow page transitions corresponding to certain browser-initiated
+ // navigations: typing in the URL, using a bookmark, or using search.
+ switch (ui::PageTransitionStripQualifier(transition)) {
+ case ui::PAGE_TRANSITION_TYPED:
+ case ui::PAGE_TRANSITION_AUTO_BOOKMARK:
+ case ui::PAGE_TRANSITION_GENERATED:
+ case ui::PAGE_TRANSITION_KEYWORD:
+ return true;
+ // TODO(alexmos): PAGE_TRANSITION_AUTO_TOPLEVEL is not included due to a
+ // bug that would cause unneeded BrowsingInstance swaps for DevTools,
+ // https://crbug.com/733767. Once that bug is fixed, consider adding this
+ // transition here.
+ default:
+ return false;
+ }
+}
+
bool RenderFrameHostManager::IsRendererTransferNeededForNavigation(
RenderFrameHostImpl* rfh,
const GURL& dest_url) {
@@ -1505,6 +1562,20 @@ bool RenderFrameHostManager::IsCurrentlySameSite(RenderFrameHostImpl* candidate,
return true;
}
+ // If the last successful URL was "about:blank" with a unique origin (which
+ // implies that it was a browser-initiated navigation to "about:blank"), none
+ // of the cases above apply, but we should still allow a scenario like
+ // foo.com -> about:blank -> foo.com to be treated as same-site, as some
+ // tests rely on that behavior. To accomplish this, compare |dest_url|
+ // against the site URL.
+ if (candidate->last_successful_url().IsAboutBlank() &&
+ candidate->GetLastCommittedOrigin().unique() &&
+ SiteInstanceImpl::IsSameWebSite(
+ browser_context, candidate->GetSiteInstance()->original_url(),
+ dest_url, should_compare_effective_urls)) {
+ return true;
+ }
+
// Not same-site.
return false;
}
@@ -2011,6 +2082,17 @@ void RenderFrameHostManager::CommitPending() {
"FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
DCHECK(speculative_render_frame_host_);
+#if defined(OS_MACOSX)
+ // The old RenderWidgetHostView will be hidden before the new
+ // RenderWidgetHostView takes its contents. Ensure that Cocoa sees this as
+ // a single transaction.
+ // https://crbug.com/829523
+ // TODO(ccameron): This can be removed when the RenderWidgetHostViewMac uses
+ // the same ui::Compositor as MacViews.
+ // https://crbug.com/331669
+ gfx::ScopedCocoaDisableScreenUpdates disabler;
+#endif // defined(OS_MACOSX)
+
bool is_main_frame = frame_tree_node_->IsMainFrame();
// First check whether we're going to want to focus the location bar after
@@ -2038,15 +2120,6 @@ void RenderFrameHostManager::CommitPending() {
old_render_frame_host =
SetRenderFrameHost(std::move(speculative_render_frame_host_));
- // Save off the old background color before possibly deleting the
- // old RenderWidgetHostView.
- SkColor old_background_color = SK_ColorWHITE;
- bool has_old_background_color = false;
- if (old_render_frame_host->GetView()) {
- has_old_background_color = true;
- old_background_color = old_render_frame_host->GetView()->background_color();
- }
-
// For top-level frames, also hide the old RenderViewHost's view.
// TODO(creis): As long as show/hide are on RVH, we don't want to hide on
// subframe navigations or we will interfere with the top-level frame.
@@ -2088,8 +2161,13 @@ void RenderFrameHostManager::CommitPending() {
delegate_->NotifySwappedFromRenderManager(
old_render_frame_host.get(), render_frame_host_.get(), is_main_frame);
- if (has_old_background_color && render_frame_host_->GetView())
- render_frame_host_->GetView()->SetBackgroundColor(old_background_color);
+ // Make the new view show the contents of old view until it has something
+ // useful to show.
+ if (is_main_frame && old_render_frame_host->GetView() &&
+ render_frame_host_->GetView()) {
+ render_frame_host_->GetView()->TakeFallbackContentFrom(
+ old_render_frame_host->GetView());
+ }
// The RenderViewHost keeps track of the main RenderFrameHost routing id.
// If this is committing a main frame navigation, update it and set the
@@ -2109,7 +2187,7 @@ void RenderFrameHostManager::CommitPending() {
if (!rvh->is_active())
rvh->PostRenderViewReady();
- rvh->set_is_active(true);
+ rvh->SetIsActive(true);
rvh->set_is_swapped_out(false);
old_render_frame_host->render_view_host()->set_main_frame_routing_id(
MSG_ROUTING_NONE);
diff --git a/chromium/content/browser/frame_host/render_frame_host_manager.h b/chromium/content/browser/frame_host/render_frame_host_manager.h
index 60acbfeb0ce..a6f58d99c33 100644
--- a/chromium/content/browser/frame_host/render_frame_host_manager.h
+++ b/chromium/content/browser/frame_host/render_frame_host_manager.h
@@ -225,6 +225,9 @@ class CONTENT_EXPORT RenderFrameHostManager
// that contains the inner WebContents.
FrameTreeNode* GetOuterDelegateNode();
+ // Return a proxy for this frame in the parent frame's SiteInstance. Returns
+ // nullptr if this is a main frame or if such a proxy does not exist (for
+ // example, if this frame is same-site with its parent).
RenderFrameProxyHost* GetProxyToParent();
// Returns the proxy to inner WebContents in the outer WebContents's
@@ -595,6 +598,27 @@ class CONTENT_EXPORT RenderFrameHostManager
bool force_browsing_instance_swap,
bool was_server_redirect);
+ // Returns true if a navigation to |dest_url| that uses the specified
+ // PageTransition in the current frame is allowed to swap BrowsingInstances.
+ // DetermineSiteInstanceForURL() uses this helper to determine when it is
+ // allowed to swap BrowsingInstances to avoid unneeded process sharing. See
+ // https://crbug.com/803367.
+ //
+ // Note that this is different from
+ // ShouldSwapBrowsingInstancesForNavigation(), which identifies cases in
+ // which a BrowsingInstance swap is *required* (e.g., for security). This
+ // function only identifies cases where a BrowsingInstance swap *may* be
+ // performed to optimize process placement. In particular, this is true for
+ // certain browser-initiated transitions for main frame navigations.
+ //
+ // Returning true here doesn't imply that DetermineSiteInstanceForURL() will
+ // swap BrowsingInstances. For example, this swap will not be done for
+ // same-site navigations, for history navigations, or when starting from an
+ // uninitialized SiteInstance.
+ bool IsBrowsingInstanceSwapAllowedForPageTransition(
+ ui::PageTransition transition,
+ const GURL& dest_url);
+
// Converts a SiteInstanceDescriptor to the actual SiteInstance it describes.
// If a |candidate_instance| is provided (is not nullptr) and it matches the
// description, it is returned as is.
diff --git a/chromium/content/browser/frame_host/render_frame_host_manager_browsertest.cc b/chromium/content/browser/frame_host/render_frame_host_manager_browsertest.cc
index dd84768f09f..2a64b912f49 100644
--- a/chromium/content/browser/frame_host/render_frame_host_manager_browsertest.cc
+++ b/chromium/content/browser/frame_host/render_frame_host_manager_browsertest.cc
@@ -150,6 +150,12 @@ class RenderFrameHostManagerTest : public ContentBrowserTest {
original_file_path, replacement_text, replacement_path);
}
+ void SetUpCommandLine(base::CommandLine* command_line) override {
+ const char kBlinkPageLifecycleFeature[] = "PageLifecycle";
+ command_line->AppendSwitchASCII(switches::kEnableBlinkFeatures,
+ kBlinkPageLifecycleFeature);
+ }
+
void SetUpOnMainThread() override {
// Support multiple sites on the test server.
host_resolver()->AddRule("*", "127.0.0.1");
@@ -230,8 +236,8 @@ IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, NoScriptAccessAfterSwapOut) {
EXPECT_TRUE(success);
// Now navigate the new window to a different site.
- NavigateToURL(new_shell,
- embedded_test_server()->GetURL("foo.com", "/title1.html"));
+ EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(
+ new_shell, embedded_test_server()->GetURL("foo.com", "/title1.html")));
scoped_refptr<SiteInstance> new_site_instance(
new_shell->web_contents()->GetSiteInstance());
EXPECT_NE(orig_site_instance, new_site_instance);
@@ -661,7 +667,7 @@ IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest,
// Now navigate the new tab to a different site.
GURL cross_site_url(
embedded_test_server()->GetURL("foo.com", "/title1.html"));
- NavigateToURL(new_shell, cross_site_url);
+ EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(new_shell, cross_site_url));
scoped_refptr<SiteInstance> new_site_instance(
new_shell->web_contents()->GetSiteInstance());
EXPECT_NE(orig_site_instance, new_site_instance);
@@ -682,7 +688,7 @@ IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest,
// If it navigates away to another process, the original window should
// still be able to close it (using a cross-process close message).
- NavigateToURL(new_shell, cross_site_url);
+ EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(new_shell, cross_site_url));
EXPECT_EQ(new_site_instance.get(),
new_shell->web_contents()->GetSiteInstance());
WebContentsDestroyedWatcher close_watcher(new_shell->web_contents());
@@ -736,7 +742,7 @@ IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, MAYBE_DisownOpener) {
// Now navigate the new tab to a different site.
GURL cross_site_url(
embedded_test_server()->GetURL("foo.com", "/title1.html"));
- NavigateToURL(new_shell, cross_site_url);
+ EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(new_shell, cross_site_url));
scoped_refptr<SiteInstance> new_site_instance(
new_shell->web_contents()->GetSiteInstance());
EXPECT_NE(orig_site_instance, new_site_instance);
@@ -818,7 +824,7 @@ IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest,
// Now navigate the new tab to a different site.
GURL foo_url(embedded_test_server()->GetURL("foo.com", "/title2.html"));
- EXPECT_TRUE(NavigateToURL(new_shell, foo_url));
+ EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(new_shell, foo_url));
scoped_refptr<SiteInstance> new_site_instance(
new_shell->web_contents()->GetSiteInstance());
EXPECT_NE(orig_site_instance, new_site_instance);
@@ -833,7 +839,7 @@ IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest,
Shell* new_shell2 = OpenPopup(new_shell, GURL(url::kAboutBlankURL), "bar");
EXPECT_TRUE(new_shell2);
GURL bar_url(embedded_test_server()->GetURL("bar.com", "/title3.html"));
- EXPECT_TRUE(NavigateToURL(new_shell2, bar_url));
+ EXPECT_TRUE(NavigateToURLFromRenderer(new_shell2, bar_url));
// Check that the new popup's window.opener has name "foo", which verifies
// that new swapped-out RenderViews also propagate window.name. This has to
@@ -890,8 +896,9 @@ IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest,
WaitForLoadStop(foo_contents);
EXPECT_EQ("/navigate_opener.html",
foo_contents->GetLastCommittedURL().path());
- NavigateToURL(new_shell, embedded_test_server()->GetURL(
- "foo.com", "/post_message.html"));
+ EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(
+ new_shell,
+ embedded_test_server()->GetURL("foo.com", "/post_message.html")));
scoped_refptr<SiteInstance> foo_site_instance(
foo_contents->GetSiteInstance());
EXPECT_NE(orig_site_instance, foo_site_instance);
@@ -910,8 +917,8 @@ IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest,
WebContents* new_contents = new_shell2->web_contents();
WaitForLoadStop(new_contents);
EXPECT_EQ("/title2.html", new_contents->GetLastCommittedURL().path());
- NavigateToURL(new_shell2,
- embedded_test_server()->GetURL("/post_message.html"));
+ EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(
+ new_shell2, embedded_test_server()->GetURL("/post_message.html")));
EXPECT_EQ(orig_site_instance.get(), new_contents->GetSiteInstance());
RenderFrameHostManager* new_manager =
static_cast<WebContentsImpl*>(new_contents)->GetRenderManagerForTesting();
@@ -1025,8 +1032,9 @@ IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest,
WaitForLoadStop(foo_contents);
EXPECT_EQ("/navigate_opener.html",
foo_contents->GetLastCommittedURL().path());
- NavigateToURL(new_shell, embedded_test_server()->GetURL(
- "foo.com", "/post_message.html"));
+ EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(
+ new_shell,
+ embedded_test_server()->GetURL("foo.com", "/post_message.html")));
scoped_refptr<SiteInstance> foo_site_instance(
foo_contents->GetSiteInstance());
EXPECT_NE(orig_site_instance, foo_site_instance);
@@ -1110,8 +1118,8 @@ IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest,
EXPECT_EQ(orig_site_instance, blank_site_instance);
// Now navigate the original (opener) tab to a different site.
- NavigateToURL(shell(),
- embedded_test_server()->GetURL("foo.com", "/title1.html"));
+ EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(
+ shell(), embedded_test_server()->GetURL("foo.com", "/title1.html")));
scoped_refptr<SiteInstance> new_site_instance(
shell()->web_contents()->GetSiteInstance());
EXPECT_NE(orig_site_instance, new_site_instance);
@@ -1212,7 +1220,7 @@ IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest,
// Now navigate the opened window to a different site.
GURL cross_site_url(
embedded_test_server()->GetURL("foo.com", "/title1.html"));
- NavigateToURL(new_shell, cross_site_url);
+ EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(new_shell, cross_site_url));
scoped_refptr<SiteInstance> new_site_instance(
new_shell->web_contents()->GetSiteInstance());
EXPECT_NE(orig_site_instance, new_site_instance);
@@ -1227,7 +1235,7 @@ IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest,
RenderProcessHostWatcher exit_observer(
orig_process,
RenderProcessHostWatcher::WATCH_FOR_HOST_DESTRUCTION);
- NavigateToURL(shell(), cross_site_url);
+ EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(shell(), cross_site_url));
exit_observer.Wait();
scoped_refptr<SiteInstance> new_site_instance2(
shell()->web_contents()->GetSiteInstance());
@@ -1479,6 +1487,31 @@ IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerSpoofingTest,
EXPECT_FALSE(contents->GetController().GetVisibleEntry());
}
+IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest,
+ WasDiscardedWhenNavigationInterruptsReload) {
+ EXPECT_TRUE(embedded_test_server()->Start());
+ GURL discarded_url(embedded_test_server()->GetURL("a.com", "/title1.html"));
+ EXPECT_TRUE(NavigateToURL(shell(), discarded_url));
+ // Discard the page.
+ shell()->web_contents()->SetWasDiscarded(true);
+ // Reload the discarded page, but pretend that it's slow to commit.
+ TestNavigationManager first_reload(shell()->web_contents(), discarded_url);
+ shell()->web_contents()->GetController().Reload(
+ ReloadType::ORIGINAL_REQUEST_URL, false);
+ EXPECT_TRUE(first_reload.WaitForRequestStart());
+ // Before the response is received, simulate user navigating to another URL.
+ GURL second_url(embedded_test_server()->GetURL("b.com", "/title1.html"));
+ TestNavigationManager second_navigation(shell()->web_contents(), second_url);
+ shell()->LoadURL(second_url);
+ second_navigation.WaitForNavigationFinished();
+ const char kDiscardedStateJS[] =
+ "window.domAutomationController.send(window.document.wasDiscarded);";
+ bool discarded_result;
+ EXPECT_TRUE(content::ExecuteScriptAndExtractBool(shell(), kDiscardedStateJS,
+ &discarded_result));
+ EXPECT_FALSE(discarded_result);
+}
+
// Ensures that a pending navigation's URL is no longer visible after the
// speculative RFH is discarded due to a concurrent renderer-initiated
// navigation. See https://crbug.com/760342.
@@ -2057,19 +2090,18 @@ IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest,
// 2. Send the second tab to a different process.
GURL cross_site_url(
embedded_test_server()->GetURL("foo.com", "/title1.html"));
- NavigateToURL(new_shell, cross_site_url);
+ EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(new_shell, cross_site_url));
scoped_refptr<SiteInstance> new_site_instance(
new_shell->web_contents()->GetSiteInstance());
EXPECT_NE(orig_site_instance, new_site_instance);
// 3. Send the first tab to the second tab's process.
- NavigateToURL(shell(), cross_site_url);
+ EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(shell(), cross_site_url));
// Make sure it ends up at the right page.
WaitForLoadStop(shell()->web_contents());
EXPECT_EQ(cross_site_url, shell()->web_contents()->GetLastCommittedURL());
- EXPECT_EQ(new_site_instance.get(),
- shell()->web_contents()->GetSiteInstance());
+ EXPECT_EQ(new_site_instance, shell()->web_contents()->GetSiteInstance());
}
// Ensure that renderer-side debug URLs do not cause a process swap, since they
@@ -2252,7 +2284,7 @@ IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, WebUIGetsBindings) {
ASSERT_TRUE(initial_rvh);
// Navigate to url1 and check bindings.
- NavigateToURL(new_shell, url1);
+ EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(new_shell, url1));
// The navigation should have used the first SiteInstance, otherwise
// |initial_rvh| did not have a chance to be used.
EXPECT_EQ(new_web_contents->GetSiteInstance(), site_instance1);
@@ -2675,7 +2707,7 @@ IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest,
GURL cross_site_url =
embedded_test_server()->GetURL("foo.com", "/title2.html");
- EXPECT_TRUE(NavigateToURL(new_shell, cross_site_url));
+ EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(new_shell, cross_site_url));
scoped_refptr<SiteInstance> foo_site_instance(
new_shell->web_contents()->GetSiteInstance());
@@ -2686,7 +2718,7 @@ IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest,
popup_root->current_frame_host()->GetProcess();
RenderProcessHostWatcher crash_observer(
popup_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
- popup_process->Shutdown(0, false);
+ popup_process->Shutdown(0);
crash_observer.Wait();
EXPECT_FALSE(popup_root->current_frame_host()->IsRenderFrameLive());
EXPECT_FALSE(
@@ -2734,7 +2766,7 @@ IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, UpdateOpener) {
Shell* foo_shell = OpenPopup(shell(), GURL(url::kAboutBlankURL), "foo");
EXPECT_TRUE(foo_shell);
GURL foo_url(embedded_test_server()->GetURL("foo.com", "/post_message.html"));
- NavigateToURL(foo_shell, foo_url);
+ EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(foo_shell, foo_url));
GURL bar_url(embedded_test_server()->GetURL(
"/frame_tree/page_with_post_message_frames.html"));
@@ -2955,7 +2987,7 @@ IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest,
RenderProcessHost* process = popup_root->current_frame_host()->GetProcess();
RenderProcessHostWatcher crash_observer(
process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
- process->Shutdown(0, false);
+ process->Shutdown(0);
crash_observer.Wait();
EXPECT_FALSE(popup_root->current_frame_host()->IsRenderFrameLive());
EXPECT_FALSE(
@@ -3018,7 +3050,7 @@ IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest,
RenderProcessHost* process = rfh_a->GetProcess();
RenderProcessHostWatcher crash_observer(
process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
- process->Shutdown(0, false);
+ process->Shutdown(0);
crash_observer.Wait();
EXPECT_FALSE(popup_root->current_frame_host()->IsRenderFrameLive());
// |rfh_a| is now deleted, thanks to the bug fix.
@@ -3097,7 +3129,7 @@ IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest,
RenderProcessHost* process = rfh_a->GetProcess();
RenderProcessHostWatcher crash_observer(
process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
- process->Shutdown(0, false);
+ process->Shutdown(0);
crash_observer.Wait();
// |rfh_a| is now deleted, thanks to the bug fix.
@@ -3383,7 +3415,7 @@ IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest,
popup->web_contents()->GetMainFrame()->GetProcess();
RenderProcessHostWatcher crash_observer(
b_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
- b_process->Shutdown(0, false);
+ b_process->Shutdown(0);
crash_observer.Wait();
// The popup should now be showing the sad tab. Main tab should not be.
@@ -3781,4 +3813,173 @@ IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest,
EXPECT_TRUE(new_contents_observer.GetWebContents());
}
+// Verify that cross-site main frame navigations will swap BrowsingInstances
+// for certain browser-initiated navigations, such as user typing the URL into
+// the address bar. This helps avoid unneeded process sharing and should
+// happen even if the current frame has an opener. See
+// https://crbug.com/803367.
+IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest,
+ BrowserInitiatedNavigationsSwapBrowsingInstance) {
+ ASSERT_TRUE(embedded_test_server()->Start());
+
+ // Start with a page on a.com.
+ GURL a_url(embedded_test_server()->GetURL("a.com", "/title1.html"));
+ EXPECT_TRUE(NavigateToURL(shell(), a_url));
+ scoped_refptr<SiteInstance> a_site_instance(
+ shell()->web_contents()->GetSiteInstance());
+
+ // Open a popup for b.com. This should stay in the current BrowsingInstance.
+ GURL b_url(embedded_test_server()->GetURL("b.com", "/title1.html"));
+ Shell* popup = OpenPopup(shell(), b_url, "foo");
+ EXPECT_TRUE(WaitForLoadStop(popup->web_contents()));
+ scoped_refptr<SiteInstance> b_site_instance(
+ popup->web_contents()->GetSiteInstance());
+ EXPECT_TRUE(a_site_instance->IsRelatedSiteInstance(b_site_instance.get()));
+
+ // Same-site browser-initiated navigations shouldn't swap BrowsingInstances
+ // or SiteInstances.
+ EXPECT_TRUE(NavigateToURL(
+ popup, embedded_test_server()->GetURL("b.com", "/title2.html")));
+ EXPECT_EQ(b_site_instance, popup->web_contents()->GetSiteInstance());
+
+ // A cross-site browser-initiated navigation should swap BrowsingInstances,
+ // despite having an opener in the same site as the destination URL.
+ EXPECT_TRUE(NavigateToURL(
+ popup, embedded_test_server()->GetURL("a.com", "/title3.html")));
+ EXPECT_NE(b_site_instance, popup->web_contents()->GetSiteInstance());
+ EXPECT_NE(a_site_instance, popup->web_contents()->GetSiteInstance());
+ EXPECT_FALSE(a_site_instance->IsRelatedSiteInstance(
+ popup->web_contents()->GetSiteInstance()));
+ EXPECT_FALSE(b_site_instance->IsRelatedSiteInstance(
+ popup->web_contents()->GetSiteInstance()));
+
+ // Perform several cross-site browser-initiated navigations in the popup, all
+ // using page transitions that allow BrowsingInstance swaps:
+ auto transitions_that_swap_browsing_instances = {
+ ui::PAGE_TRANSITION_TYPED, /* user typing URL into address bar */
+ ui::PAGE_TRANSITION_AUTO_BOOKMARK, /* user clicking on a bookmark */
+ ui::PAGE_TRANSITION_GENERATED, /* search query */
+ ui::PAGE_TRANSITION_KEYWORD, /* search within a site from address bar */
+ };
+ int current_site = 0;
+ for (auto transition : transitions_that_swap_browsing_instances) {
+ GURL cross_site_url(embedded_test_server()->GetURL(
+ base::StringPrintf("site%d.com", current_site++), "/title1.html"));
+ scoped_refptr<SiteInstance> prev_instance(
+ popup->web_contents()->GetSiteInstance());
+ SCOPED_TRACE(base::StringPrintf(
+ "... expected BrowsingInstance swap for '%s' transition to %s",
+ ui::PageTransitionGetCoreTransitionString(transition),
+ cross_site_url.spec().c_str()));
+
+ TestNavigationObserver observer(popup->web_contents());
+ NavigationController::LoadURLParams params(cross_site_url);
+ params.transition_type = transition;
+ popup->web_contents()->GetController().LoadURLWithParams(params);
+ observer.Wait();
+
+ // This should swap BrowsingInstances.
+ scoped_refptr<SiteInstance> curr_instance(
+ popup->web_contents()->GetSiteInstance());
+ EXPECT_NE(a_site_instance, curr_instance);
+ EXPECT_FALSE(a_site_instance->IsRelatedSiteInstance(curr_instance.get()));
+ EXPECT_NE(prev_instance, curr_instance);
+ EXPECT_FALSE(prev_instance->IsRelatedSiteInstance(curr_instance.get()));
+ }
+
+ // Ensure that other page transitions don't cause a BrowsingInstance swap.
+ auto transitions_that_dont_swap_browsing_instances = {
+ ui::PAGE_TRANSITION_LINK, ui::PAGE_TRANSITION_AUTO_TOPLEVEL,
+ ui::PAGE_TRANSITION_FORM_SUBMIT,
+ };
+ scoped_refptr<SiteInstance> curr_instance(
+ popup->web_contents()->GetSiteInstance());
+ for (auto transition : transitions_that_dont_swap_browsing_instances) {
+ GURL cross_site_url(embedded_test_server()->GetURL(
+ base::StringPrintf("site%d.com", current_site++), "/title1.html"));
+ SCOPED_TRACE(base::StringPrintf(
+ "... expected no BrowsingInstance swap for '%s' transition to %s",
+ ui::PageTransitionGetCoreTransitionString(transition),
+ cross_site_url.spec().c_str()));
+
+ TestNavigationObserver observer(popup->web_contents());
+ NavigationController::LoadURLParams params(cross_site_url);
+ params.transition_type = transition;
+ popup->web_contents()->GetController().LoadURLWithParams(params);
+ observer.Wait();
+
+ // This should stay in the current BrowsingInstance.
+ EXPECT_TRUE(curr_instance->IsRelatedSiteInstance(
+ popup->web_contents()->GetSiteInstance()));
+ }
+}
+
+// Ensure that these two browser-initiated navigations:
+// foo.com -> about:blank -> foo.com
+// stay in the same SiteInstance. This isn't technically required for
+// correctness, but some tests (e.g., testEnsureHotFromScratch from
+// telemetry_unittests) currently depend on this behavior.
+IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest,
+ NavigateToAndFromAboutBlank) {
+ ASSERT_TRUE(embedded_test_server()->Start());
+ GURL foo_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
+ EXPECT_TRUE(NavigateToURL(shell(), foo_url));
+ scoped_refptr<SiteInstance> site_instance(
+ shell()->web_contents()->GetSiteInstance());
+
+ // Navigate to about:blank from address bar. This stays in the foo.com
+ // SiteInstance.
+ EXPECT_TRUE(NavigateToURL(shell(), GURL(url::kAboutBlankURL)));
+ EXPECT_EQ(site_instance, shell()->web_contents()->GetSiteInstance());
+
+ // Perform a browser-initiated navigation to foo.com. This should also stay
+ // in the original foo.com SiteInstance and BrowsingInstance.
+ EXPECT_TRUE(NavigateToURL(shell(), foo_url));
+ EXPECT_EQ(site_instance, shell()->web_contents()->GetSiteInstance());
+}
+
+// Check that with the following sequence of navigations:
+// foo.com -(1)-> bar.com -(2)-> about:blank -(3)-> foo.com
+// where (1) is renderer-initiated and (2)+(3) are browser-initiated, the last
+// navigation goes back to the first SiteInstance without --site-per-process,
+// and to a new SiteInstance and BrowsingInstance with --site-per-process.
+IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest,
+ NavigateToFooThenBarThenAboutBlankThenFoo) {
+ ASSERT_TRUE(embedded_test_server()->Start());
+ GURL foo_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
+ EXPECT_TRUE(NavigateToURL(shell(), foo_url));
+ scoped_refptr<SiteInstance> site_instance(
+ shell()->web_contents()->GetSiteInstance());
+
+ // Do a renderer-initiated navigation to bar.com, then navigate to
+ // about:blank from address bar, then back to foo.com.
+ GURL bar_url(embedded_test_server()->GetURL("bar.com", "/title1.html"));
+
+ EXPECT_TRUE(NavigateToURLFromRenderer(shell(), bar_url));
+ EXPECT_TRUE(NavigateToURL(shell(), GURL(url::kAboutBlankURL)));
+ EXPECT_TRUE(NavigateToURL(shell(), foo_url));
+
+ // This should again go back to the original foo.com SiteInstance without
+ // --site-per-process, as in that case both the bar.com and
+ // about:blank navigation will stay in the foo.com SiteInstance, and the
+ // final navigation to foo.com will be considered same-site with the current
+ // SiteInstance.
+ //
+ // With --site-per-process, bar.com should get its own SiteInstance, the
+ // about:blank navigation will stay in it, and thus the final foo.com
+ // navigation should be considered cross-site from the current SiteInstance.
+ // Since this is a browser-initiated, cross-site navigation, it will swap
+ // BrowsingInstances, and create a new foo.com SiteInstance, distinct from
+ // the initial one.
+ if (!AreAllSitesIsolatedForTesting()) {
+ EXPECT_EQ(site_instance, shell()->web_contents()->GetSiteInstance());
+ } else {
+ EXPECT_NE(site_instance, shell()->web_contents()->GetSiteInstance());
+ EXPECT_FALSE(site_instance->IsRelatedSiteInstance(
+ shell()->web_contents()->GetSiteInstance()));
+ EXPECT_EQ(site_instance->GetSiteURL(),
+ shell()->web_contents()->GetSiteInstance()->GetSiteURL());
+ }
+}
+
} // namespace content
diff --git a/chromium/content/browser/frame_host/render_frame_host_manager_unittest.cc b/chromium/content/browser/frame_host/render_frame_host_manager_unittest.cc
index 06218c1cbe8..754c2d88c63 100644
--- a/chromium/content/browser/frame_host/render_frame_host_manager_unittest.cc
+++ b/chromium/content/browser/frame_host/render_frame_host_manager_unittest.cc
@@ -14,7 +14,6 @@
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/histogram_tester.h"
@@ -62,8 +61,8 @@
#include "content/test/test_web_contents.h"
#include "net/base/load_flags.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/common/frame/frame_policy.h"
-#include "third_party/WebKit/public/platform/WebInsecureRequestPolicy.h"
+#include "third_party/blink/public/common/frame/frame_policy.h"
+#include "third_party/blink/public/platform/web_insecure_request_policy.h"
#include "ui/base/page_transition_types.h"
namespace content {
@@ -2198,12 +2197,12 @@ TEST_F(RenderFrameHostManagerTest, TraverseComplexOpenerChain) {
TestRenderFrameHost::CreateStubInterfaceProviderRequest(),
blink::WebTreeScopeType::kDocument, std::string(),
"uniqueName0", false, base::UnguessableToken::Create(),
- blink::FramePolicy(), FrameOwnerProperties());
+ blink::FramePolicy(), FrameOwnerProperties(), false);
tree1->AddFrame(root1, process_id, 13,
TestRenderFrameHost::CreateStubInterfaceProviderRequest(),
blink::WebTreeScopeType::kDocument, std::string(),
"uniqueName1", false, base::UnguessableToken::Create(),
- blink::FramePolicy(), FrameOwnerProperties());
+ blink::FramePolicy(), FrameOwnerProperties(), false);
std::unique_ptr<TestWebContents> tab2(
TestWebContents::Create(browser_context(), nullptr));
@@ -2215,12 +2214,12 @@ TEST_F(RenderFrameHostManagerTest, TraverseComplexOpenerChain) {
TestRenderFrameHost::CreateStubInterfaceProviderRequest(),
blink::WebTreeScopeType::kDocument, std::string(),
"uniqueName2", false, base::UnguessableToken::Create(),
- blink::FramePolicy(), FrameOwnerProperties());
+ blink::FramePolicy(), FrameOwnerProperties(), false);
tree2->AddFrame(root2, process_id, 23,
TestRenderFrameHost::CreateStubInterfaceProviderRequest(),
blink::WebTreeScopeType::kDocument, std::string(),
"uniqueName3", false, base::UnguessableToken::Create(),
- blink::FramePolicy(), FrameOwnerProperties());
+ blink::FramePolicy(), FrameOwnerProperties(), false);
std::unique_ptr<TestWebContents> tab3(
TestWebContents::Create(browser_context(), nullptr));
@@ -2237,7 +2236,7 @@ TEST_F(RenderFrameHostManagerTest, TraverseComplexOpenerChain) {
TestRenderFrameHost::CreateStubInterfaceProviderRequest(),
blink::WebTreeScopeType::kDocument, std::string(),
"uniqueName4", false, base::UnguessableToken::Create(),
- blink::FramePolicy(), FrameOwnerProperties());
+ blink::FramePolicy(), FrameOwnerProperties(), false);
root1->child_at(1)->SetOpener(root1->child_at(1));
root1->SetOpener(root2->child_at(1));
@@ -3096,12 +3095,11 @@ TEST_F(RenderFrameHostManagerTest,
EXPECT_EQ(kFooUrl, initial_instance->GetSiteURL());
// Simulate a browser-initiated navigation to an app URL, which should swap
- // processes and create a new related SiteInstance in the same
- // BrowsingInstance. This new SiteInstance should have correct site URL and
- // |original_url()|.
+ // processes and create a new SiteInstance in a new BrowsingInstance.
+ // This new SiteInstance should have correct site URL and |original_url()|.
NavigationSimulator::NavigateAndCommitFromBrowser(contents(), kOriginalUrl);
EXPECT_NE(initial_instance.get(), main_test_rfh()->GetSiteInstance());
- EXPECT_TRUE(initial_instance->IsRelatedSiteInstance(
+ EXPECT_FALSE(initial_instance->IsRelatedSiteInstance(
main_test_rfh()->GetSiteInstance()));
EXPECT_EQ(kOriginalUrl, main_test_rfh()->GetSiteInstance()->original_url());
EXPECT_EQ(kTranslatedUrl, main_test_rfh()->GetSiteInstance()->GetSiteURL());
diff --git a/chromium/content/browser/frame_host/render_frame_message_filter.cc b/chromium/content/browser/frame_host/render_frame_message_filter.cc
index b3653373a51..80fd7cf8957 100644
--- a/chromium/content/browser/frame_host/render_frame_message_filter.cc
+++ b/chromium/content/browser/frame_host/render_frame_message_filter.cc
@@ -23,6 +23,7 @@
#include "content/browser/gpu/gpu_data_manager_impl.h"
#include "content/browser/renderer_host/render_widget_helper.h"
#include "content/browser/resource_context_impl.h"
+#include "content/browser/storage_partition_impl.h"
#include "content/common/content_constants_internal.h"
#include "content/common/frame_messages.h"
#include "content/common/frame_owner_properties.h"
@@ -41,11 +42,11 @@
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#include "services/network/public/cpp/features.h"
#include "services/service_manager/public/mojom/interface_provider.mojom.h"
#include "storage/browser/blob/blob_storage_context.h"
-#include "third_party/WebKit/public/common/frame/frame_policy.h"
+#include "third_party/blink/public/common/frame/frame_policy.h"
#include "url/gurl.h"
#include "url/origin.h"
@@ -222,23 +223,22 @@ RenderFrameMessageFilter::RenderFrameMessageFilter(
int render_process_id,
PluginServiceImpl* plugin_service,
BrowserContext* browser_context,
- net::URLRequestContextGetter* request_context,
+ StoragePartition* storage_partition,
RenderWidgetHelper* render_widget_helper)
: BrowserMessageFilter(FrameMsgStart),
BrowserAssociatedInterface<mojom::RenderFrameMessageFilter>(this, this),
#if BUILDFLAG(ENABLE_PLUGINS)
plugin_service_(plugin_service),
- profile_data_directory_(browser_context->GetPath()),
+ profile_data_directory_(storage_partition->GetPath()),
#endif // ENABLE_PLUGINS
- request_context_(request_context),
+ request_context_(storage_partition->GetURLRequestContext()),
resource_context_(browser_context->GetResourceContext()),
render_widget_helper_(render_widget_helper),
incognito_(browser_context->IsOffTheRecord()),
render_process_id_(render_process_id) {
network::mojom::CookieManagerPtr cookie_manager;
- BrowserContext::GetDefaultStoragePartition(browser_context)
- ->GetNetworkContext()
- ->GetCookieManager(mojo::MakeRequest(&cookie_manager));
+ storage_partition->GetNetworkContext()->GetCookieManager(
+ mojo::MakeRequest(&cookie_manager));
// The PostTask below could finish before the constructor returns which would
// lead to this object being destructed prematurely.
@@ -477,16 +477,18 @@ void RenderFrameMessageFilter::SetCookie(int32_t render_frame_id,
render_frame_id, options))
return;
- if (base::FeatureList::IsEnabled(network::features::kNetworkService)) {
- // TODO(jam): modify GetRequestContextForURL to work with network service.
- // Merge this with code path below for non-network service.
+ net::URLRequestContext* context = GetRequestContextForURL(url);
+ // If the embedder overrides the URLRequestContext then always use it, even if
+ // the network service is enabled, instead of the CookieManager associated
+ // this process' StoragePartition.
+ if (base::FeatureList::IsEnabled(network::features::kNetworkService) &&
+ context == request_context_->GetURLRequestContext()) {
cookie_manager_->SetCanonicalCookie(*cookie, url.SchemeIsCryptographic(),
!options.exclude_httponly(),
net::CookieStore::SetCookiesCallback());
return;
}
- net::URLRequestContext* context = GetRequestContextForURL(url);
// Pass a null callback since we don't care about when the 'set' completes.
context->cookie_store()->SetCanonicalCookieAsync(
std::move(cookie), url.SchemeIsCryptographic(),
@@ -519,7 +521,12 @@ void RenderFrameMessageFilter::GetCookies(int render_frame_id,
net::CookieOptions::SameSiteCookieMode::DO_NOT_INCLUDE);
}
- if (base::FeatureList::IsEnabled(network::features::kNetworkService)) {
+ net::URLRequestContext* context = GetRequestContextForURL(url);
+ // If the embedder overrides the URLRequestContext then always use it, even if
+ // the network service is enabled, instead of the CookieManager associated
+ // this process' StoragePartition.
+ if (base::FeatureList::IsEnabled(network::features::kNetworkService) &&
+ context == request_context_->GetURLRequestContext()) {
// TODO(jam): modify GetRequestContextForURL to work with network service.
// Merge this with code path below for non-network service.
cookie_manager_->GetCookieList(
@@ -534,7 +541,6 @@ void RenderFrameMessageFilter::GetCookies(int render_frame_id,
// http://crbug.com/99242
DEBUG_ALIAS_FOR_GURL(url_buf, url);
- net::URLRequestContext* context = GetRequestContextForURL(url);
context->cookie_store()->GetCookieListWithOptionsAsync(
url, options,
base::BindOnce(&RenderFrameMessageFilter::CheckPolicyForCookies, this,
@@ -613,9 +619,10 @@ void RenderFrameMessageFilter::OnGetPluginInfo(
void RenderFrameMessageFilter::OnOpenChannelToPepperPlugin(
const base::FilePath& path,
+ const base::Optional<url::Origin>& origin_lock,
IPC::Message* reply_msg) {
plugin_service_->OpenChannelToPpapiPlugin(
- render_process_id_, path, profile_data_directory_,
+ render_process_id_, path, profile_data_directory_, origin_lock,
new OpenChannelToPpapiPluginCallback(this, reply_msg));
}
diff --git a/chromium/content/browser/frame_host/render_frame_message_filter.h b/chromium/content/browser/frame_host/render_frame_message_filter.h
index db9398a0760..871e11f6127 100644
--- a/chromium/content/browser/frame_host/render_frame_message_filter.h
+++ b/chromium/content/browser/frame_host/render_frame_message_filter.h
@@ -9,15 +9,17 @@
#include <set>
+#include "base/optional.h"
#include "content/common/frame_replication_state.h"
#include "content/common/render_frame_message_filter.mojom.h"
#include "content/public/browser/browser_associated_interface.h"
#include "content/public/browser/browser_message_filter.h"
#include "content/public/common/three_d_api_types.h"
#include "net/cookies/canonical_cookie.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#include "services/network/public/mojom/network_service.mojom.h"
-#include "third_party/WebKit/public/web/WebTreeScopeType.h"
+#include "third_party/blink/public/web/web_tree_scope_type.h"
+#include "url/origin.h"
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/common/pepper_renderer_instance_data.h"
@@ -46,6 +48,7 @@ class PluginServiceImpl;
struct Referrer;
class RenderWidgetHelper;
class ResourceContext;
+class StoragePartition;
struct WebPluginInfo;
// RenderFrameMessageFilter intercepts FrameHost messages on the IO thread
@@ -62,7 +65,7 @@ class CONTENT_EXPORT RenderFrameMessageFilter
RenderFrameMessageFilter(int render_process_id,
PluginServiceImpl* plugin_service,
BrowserContext* browser_context,
- net::URLRequestContextGetter* request_context,
+ StoragePartition* storage_partition,
RenderWidgetHelper* render_widget_helper);
// BrowserMessageFilter methods:
@@ -148,8 +151,10 @@ class CONTENT_EXPORT RenderFrameMessageFilter
bool* found,
WebPluginInfo* info,
std::string* actual_mime_type);
- void OnOpenChannelToPepperPlugin(const base::FilePath& path,
- IPC::Message* reply_msg);
+ void OnOpenChannelToPepperPlugin(
+ const base::FilePath& path,
+ const base::Optional<url::Origin>& origin_lock,
+ IPC::Message* reply_msg);
void OnDidCreateOutOfProcessPepperInstance(
int plugin_child_id,
int32_t pp_instance,
diff --git a/chromium/content/browser/frame_host/render_frame_message_filter_browsertest.cc b/chromium/content/browser/frame_host/render_frame_message_filter_browsertest.cc
index bdb8c43627a..9c11ebe6935 100644
--- a/chromium/content/browser/frame_host/render_frame_message_filter_browsertest.cc
+++ b/chromium/content/browser/frame_host/render_frame_message_filter_browsertest.cc
@@ -15,6 +15,7 @@
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/common/frame_messages.h"
#include "content/common/render_frame_message_filter.mojom.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test_utils.h"
diff --git a/chromium/content/browser/frame_host/render_frame_proxy_host.h b/chromium/content/browser/frame_host/render_frame_proxy_host.h
index cd7aa23e652..17869ebf616 100644
--- a/chromium/content/browser/frame_host/render_frame_proxy_host.h
+++ b/chromium/content/browser/frame_host/render_frame_proxy_host.h
@@ -14,7 +14,7 @@
#include "content/browser/site_instance_impl.h"
#include "ipc/ipc_listener.h"
#include "ipc/ipc_sender.h"
-#include "third_party/WebKit/public/platform/WebFocusType.h"
+#include "third_party/blink/public/platform/web_focus_type.h"
struct FrameHostMsg_OpenURL_Params;
struct FrameMsg_PostMessage_Params;
diff --git a/chromium/content/browser/frame_host/render_widget_host_view_guest.cc b/chromium/content/browser/frame_host/render_widget_host_view_guest.cc
index a58e2cb75c4..839017d8fee 100644
--- a/chromium/content/browser/frame_host/render_widget_host_view_guest.cc
+++ b/chromium/content/browser/frame_host/render_widget_host_view_guest.cc
@@ -36,10 +36,6 @@
#include "ui/events/base_event_utils.h"
#include "ui/gfx/geometry/dip_util.h"
-#if defined(OS_MACOSX)
-#import "content/browser/renderer_host/render_widget_host_view_mac_dictionary_helper.h"
-#endif
-
#if defined(USE_AURA)
#include "content/browser/renderer_host/ui_events_helper.h"
#include "ui/aura/env.h"
@@ -143,7 +139,7 @@ void RenderWidgetHostViewGuest::Show() {
// first place: http://crbug.com/273089.
//
// |guest_| is NULL during test.
- if ((guest_ && guest_->is_in_destruction()) || !host_->is_hidden())
+ if ((guest_ && guest_->is_in_destruction()) || !host()->is_hidden())
return;
// Make sure the size of this view matches the size of the WebContentsView.
// The two sizes may fall out of sync if we switch RenderWidgetHostViews,
@@ -157,14 +153,14 @@ void RenderWidgetHostViewGuest::Show() {
if (last_received_local_surface_id_.is_valid())
SendSurfaceInfoToEmbedder();
}
- host_->WasShown(ui::LatencyInfo());
+ host()->WasShown(ui::LatencyInfo());
}
void RenderWidgetHostViewGuest::Hide() {
// |guest_| is NULL during test.
- if ((guest_ && guest_->is_in_destruction()) || host_->is_hidden())
+ if ((guest_ && guest_->is_in_destruction()) || host()->is_hidden())
return;
- host_->WasHidden();
+ host()->WasHidden();
}
void RenderWidgetHostViewGuest::SetSize(const gfx::Size& size) {
@@ -178,7 +174,7 @@ void RenderWidgetHostViewGuest::Focus() {
// InterstitialPages are not WebContents, and so BrowserPluginGuest does not
// have direct access to the interstitial page's RenderWidgetHost.
if (guest_)
- guest_->SetFocus(host_, true, blink::kWebFocusTypeNone);
+ guest_->SetFocus(host(), true, blink::kWebFocusTypeNone);
}
bool RenderWidgetHostViewGuest::HasFocus() const {
@@ -366,7 +362,7 @@ void RenderWidgetHostViewGuest::SetTooltipText(
const base::string16& tooltip_text) {
RenderWidgetHostViewBase* root_view = GetRootView(this);
if (root_view)
- root_view->SetTooltipText(tooltip_text);
+ root_view->GetCursorManager()->SetTooltipTextForView(this, tooltip_text);
}
void RenderWidgetHostViewGuest::SendSurfaceInfoToEmbedderImpl(
@@ -375,23 +371,6 @@ void RenderWidgetHostViewGuest::SendSurfaceInfoToEmbedderImpl(
guest_->SetChildFrameSurface(surface_info);
}
-void RenderWidgetHostViewGuest::SubmitCompositorFrame(
- const viz::LocalSurfaceId& local_surface_id,
- viz::CompositorFrame frame,
- viz::mojom::HitTestRegionListPtr hit_test_region_list) {
- TRACE_EVENT0("content", "RenderWidgetHostViewGuest::OnSwapCompositorFrame");
-
- last_scroll_offset_ = frame.metadata.root_scroll_offset;
- ProcessCompositorFrame(local_surface_id, std::move(frame),
- std::move(hit_test_region_list));
-
- // If after detaching we are sent a frame, we should finish processing it, and
- // then we should clear the surface so that we are not holding resources we
- // no longer need.
- if (!guest_ || !guest_->attached())
- ClearCompositorSurfaceIfNecessary();
-}
-
void RenderWidgetHostViewGuest::OnAttached() {
RegisterFrameSinkId();
#if defined(USE_AURA)
@@ -589,42 +568,18 @@ void RenderWidgetHostViewGuest::SetActive(bool active) {
}
void RenderWidgetHostViewGuest::ShowDefinitionForSelection() {
- if (!guest_)
- return;
-
- gfx::Rect guest_bounds = GetViewBounds();
- RenderWidgetHostView* rwhv = guest_->GetOwnerRenderWidgetHostView();
- gfx::Rect embedder_bounds;
- if (rwhv)
- embedder_bounds = rwhv->GetViewBounds();
-
- gfx::Vector2d guest_offset = gfx::Vector2d(
- // Horizontal offset of guest from embedder.
- guest_bounds.x() - embedder_bounds.x(),
- // Vertical offset from guest's top to embedder's bottom edge.
- embedder_bounds.bottom() - guest_bounds.y());
-
- RenderWidgetHostViewMacDictionaryHelper helper(platform_view_.get());
- helper.SetTargetView(rwhv);
- helper.set_offset(guest_offset);
- helper.ShowDefinitionForSelection();
-}
-
-bool RenderWidgetHostViewGuest::SupportsSpeech() const {
- return platform_view_->SupportsSpeech();
+ // Note that if there were a dictionary overlay, that dictionary overlay
+ // would target |guest_|. This path does not actually support getting the
+ // attributed string and its point on the page, so it will not create an
+ // overlay (it will open Dictionary.app), so the target NSView need not be
+ // specified.
+ // https://crbug.com/152438
+ platform_view_->ShowDefinitionForSelection();
}
void RenderWidgetHostViewGuest::SpeakSelection() {
platform_view_->SpeakSelection();
}
-
-bool RenderWidgetHostViewGuest::IsSpeaking() const {
- return platform_view_->IsSpeaking();
-}
-
-void RenderWidgetHostViewGuest::StopSpeaking() {
- platform_view_->StopSpeaking();
-}
#endif // defined(OS_MACOSX)
RenderWidgetHostViewBase*
@@ -651,12 +606,11 @@ void RenderWidgetHostViewGuest::MaybeSendSyntheticTapGesture(
blink::WebGestureEvent gesture_tap_event(
blink::WebGestureEvent::kGestureTapDown,
blink::WebInputEvent::kNoModifiers,
- ui::EventTimeStampToSeconds(ui::EventTimeForNow()));
- gesture_tap_event.source_device = blink::kWebGestureDeviceTouchscreen;
- gesture_tap_event.x = position.x + offset.x();
- gesture_tap_event.y = position.y + offset.y();
- gesture_tap_event.global_x = screenPosition.x;
- gesture_tap_event.global_y = screenPosition.y;
+ ui::EventTimeStampToSeconds(ui::EventTimeForNow()),
+ blink::kWebGestureDeviceTouchscreen);
+ gesture_tap_event.SetPositionInWidget(
+ blink::WebFloatPoint(position.x + offset.x(), position.y + offset.y()));
+ gesture_tap_event.SetPositionInScreen(screenPosition);
GetOwnerRenderWidgetHostView()->ProcessGestureEvent(
gesture_tap_event, ui::LatencyInfo(ui::SourceEventType::TOUCH));
@@ -724,11 +678,28 @@ void RenderWidgetHostViewGuest::GetScreenInfo(ScreenInfo* screen_info) const {
RenderWidgetHostViewBase::GetScreenInfo(screen_info);
}
-void RenderWidgetHostViewGuest::ResizeDueToAutoResize(
+void RenderWidgetHostViewGuest::EnableAutoResize(const gfx::Size& min_size,
+ const gfx::Size& max_size) {
+ if (guest_)
+ guest_->EnableAutoResize(min_size, max_size);
+}
+
+void RenderWidgetHostViewGuest::DisableAutoResize(const gfx::Size& new_size) {
+ if (guest_)
+ guest_->DisableAutoResize();
+}
+
+viz::ScopedSurfaceIdAllocator RenderWidgetHostViewGuest::ResizeDueToAutoResize(
const gfx::Size& new_size,
uint64_t sequence_number) {
- if (guest_)
- guest_->ResizeDueToAutoResize(new_size, sequence_number);
+ // TODO(cblume): This doesn't currently suppress allocation.
+ // It maintains existing behavior while using the suppression style.
+ // This will be addressed in a follow-up patch.
+ // See https://crbug.com/805073
+ base::OnceCallback<void()> allocation_task =
+ base::BindOnce(&BrowserPluginGuest::ResizeDueToAutoResize, guest_,
+ new_size, sequence_number);
+ return viz::ScopedSurfaceIdAllocator(std::move(allocation_task));
}
bool RenderWidgetHostViewGuest::IsRenderWidgetHostViewGuest() {
@@ -755,19 +726,19 @@ void RenderWidgetHostViewGuest::OnHandleInputEvent(
rescaled_event.wheel_ticks_x /= current_device_scale_factor();
rescaled_event.wheel_ticks_y /= current_device_scale_factor();
ui::LatencyInfo latency_info(ui::SourceEventType::WHEEL);
- host_->ForwardWheelEventWithLatencyInfo(rescaled_event, latency_info);
+ host()->ForwardWheelEventWithLatencyInfo(rescaled_event, latency_info);
return;
}
- ScopedInputScaleDisabler disable(host_, current_device_scale_factor());
+ ScopedInputScaleDisabler disable(host(), current_device_scale_factor());
if (blink::WebInputEvent::IsMouseEventType(event->GetType())) {
- host_->ForwardMouseEvent(*static_cast<const blink::WebMouseEvent*>(event));
+ host()->ForwardMouseEvent(*static_cast<const blink::WebMouseEvent*>(event));
return;
}
if (event->GetType() == blink::WebInputEvent::kMouseWheel) {
ui::LatencyInfo latency_info(ui::SourceEventType::WHEEL);
- host_->ForwardWheelEventWithLatencyInfo(
+ host()->ForwardWheelEventWithLatencyInfo(
*static_cast<const blink::WebMouseWheelEvent*>(event), latency_info);
return;
}
@@ -775,7 +746,7 @@ void RenderWidgetHostViewGuest::OnHandleInputEvent(
if (blink::WebInputEvent::IsKeyboardEventType(event->GetType())) {
NativeWebKeyboardEvent keyboard_event(
*static_cast<const blink::WebKeyboardEvent*>(event), GetNativeView());
- host_->ForwardKeyboardEvent(keyboard_event);
+ host()->ForwardKeyboardEvent(keyboard_event);
return;
}
@@ -785,7 +756,7 @@ void RenderWidgetHostViewGuest::OnHandleInputEvent(
embedder->GetView()->Focus();
}
ui::LatencyInfo latency_info(ui::SourceEventType::TOUCH);
- host_->ForwardTouchEventWithLatencyInfo(
+ host()->ForwardTouchEventWithLatencyInfo(
*static_cast<const blink::WebTouchEvent*>(event), latency_info);
return;
}
@@ -807,7 +778,7 @@ void RenderWidgetHostViewGuest::OnHandleInputEvent(
blink::WebGestureEvent::kMomentumPhase) {
return;
}
- host_->ForwardGestureEvent(gesture_event);
+ host()->ForwardGestureEvent(gesture_event);
return;
}
}
diff --git a/chromium/content/browser/frame_host/render_widget_host_view_guest.h b/chromium/content/browser/frame_host/render_widget_host_view_guest.h
index 51888f851fc..374694e7faf 100644
--- a/chromium/content/browser/frame_host/render_widget_host_view_guest.h
+++ b/chromium/content/browser/frame_host/render_widget_host_view_guest.h
@@ -16,7 +16,7 @@
#include "content/browser/renderer_host/render_widget_host_view_child_frame.h"
#include "content/common/content_export.h"
#include "content/common/cursors/webcursor.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/events/event.h"
#include "ui/events/gestures/gesture_recognizer.h"
#include "ui/events/gestures/gesture_types.h"
@@ -111,10 +111,6 @@ class CONTENT_EXPORT RenderWidgetHostViewGuest
const gfx::Range& range) override;
void SelectionBoundsChanged(
const ViewHostMsg_SelectionBounds_Params& params) override;
- void SubmitCompositorFrame(
- const viz::LocalSurfaceId& local_surface_id,
- viz::CompositorFrame frame,
- viz::mojom::HitTestRegionListPtr hit_test_region_list) override;
#if defined(USE_AURA)
void ProcessAckedTouchEvent(const TouchEventWithLatencyInfo& touch,
InputEventAckState ack_result) override;
@@ -134,10 +130,7 @@ class CONTENT_EXPORT RenderWidgetHostViewGuest
// RenderWidgetHostView implementation.
void SetActive(bool active) override;
void ShowDefinitionForSelection() override;
- bool SupportsSpeech() const override;
void SpeakSelection() override;
- bool IsSpeaking() const override;
- void StopSpeaking() override;
#endif // defined(OS_MACOSX)
void WheelEventAck(const blink::WebMouseWheelEvent& event,
@@ -154,8 +147,13 @@ class CONTENT_EXPORT RenderWidgetHostViewGuest
void GetScreenInfo(ScreenInfo* screen_info) const override;
- void ResizeDueToAutoResize(const gfx::Size& new_size,
- uint64_t sequence_number) override;
+ void EnableAutoResize(const gfx::Size& min_size,
+ const gfx::Size& max_size) override;
+ void DisableAutoResize(const gfx::Size& new_size) override;
+
+ viz::ScopedSurfaceIdAllocator ResizeDueToAutoResize(
+ const gfx::Size& new_size,
+ uint64_t sequence_number) override;
private:
friend class RenderWidgetHostView;
diff --git a/chromium/content/browser/frame_host/render_widget_host_view_guest_unittest.cc b/chromium/content/browser/frame_host/render_widget_host_view_guest_unittest.cc
index b4e1ad7157f..90579b1591c 100644
--- a/chromium/content/browser/frame_host/render_widget_host_view_guest_unittest.cc
+++ b/chromium/content/browser/frame_host/render_widget_host_view_guest_unittest.cc
@@ -10,7 +10,6 @@
#include "base/macros.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
-#include "base/test/scoped_task_environment.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
#include "components/viz/service/frame_sinks/frame_sink_manager_impl.h"
@@ -19,6 +18,7 @@
#include "content/browser/browser_plugin/browser_plugin_guest.h"
#include "content/browser/compositor/test/test_image_transport_factory.h"
#include "content/browser/gpu/compositor_util.h"
+#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_delegate.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/common/view_messages.h"
@@ -26,6 +26,7 @@
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/test/mock_render_process_host.h"
#include "content/public/test/test_browser_context.h"
+#include "content/public/test/test_browser_thread_bundle.h"
#include "content/test/fake_renderer_compositor_frame_sink.h"
#include "content/test/mock_render_widget_host_delegate.h"
#include "content/test/mock_widget_impl.h"
@@ -40,9 +41,7 @@ namespace {
class RenderWidgetHostViewGuestTest : public testing::Test {
public:
- RenderWidgetHostViewGuestTest()
- : scoped_task_environment_(
- base::test::ScopedTaskEnvironment::MainThreadType::UI) {}
+ RenderWidgetHostViewGuestTest() {}
void SetUp() override {
#if !defined(OS_ANDROID)
@@ -79,8 +78,7 @@ class RenderWidgetHostViewGuestTest : public testing::Test {
}
protected:
- // Needed by base::PostTaskWithTraits in RenderWidgetHostImpl constructor.
- base::test::ScopedTaskEnvironment scoped_task_environment_;
+ TestBrowserThreadBundle thread_bundle_;
std::unique_ptr<BrowserContext> browser_context_;
MockRenderWidgetHostDelegate delegate_;
@@ -201,6 +199,7 @@ class RenderWidgetHostViewGuestSurfaceTest
}
protected:
+ ScopedMockRenderProcessHostFactory rph_factory_;
TestBrowserThreadBundle thread_bundle_;
std::unique_ptr<BrowserContext> browser_context_;
MockRenderWidgetHostDelegate delegate_;
@@ -218,6 +217,7 @@ class RenderWidgetHostViewGuestSurfaceTest
private:
viz::mojom::CompositorFrameSinkClientPtr renderer_compositor_frame_sink_ptr_;
+
DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostViewGuestSurfaceTest);
};
@@ -295,13 +295,6 @@ TEST_F(RenderWidgetHostViewGuestSurfaceTest, TestGuestSurface) {
browser_plugin_guest_->set_attached(false);
browser_plugin_guest_->ResetTestData();
-
- view_->SubmitCompositorFrame(
- local_surface_id,
- CreateDelegatedFrame(scale_factor, view_size, view_rect), nullptr);
- // Since guest is not attached, the CompositorFrame must be processed but the
- // frame must be evicted to return the resources immediately.
- EXPECT_FALSE(view_->has_frame());
}
} // namespace content
diff --git a/chromium/content/browser/generic_sensor_browsertest.cc b/chromium/content/browser/generic_sensor/generic_sensor_browsertest.cc
index 7d2bbdaed2f..ec3dff1a554 100644
--- a/chromium/content/browser/generic_sensor_browsertest.cc
+++ b/chromium/content/browser/generic_sensor/generic_sensor_browsertest.cc
@@ -28,6 +28,7 @@
#include "services/device/public/cpp/generic_sensor/platform_sensor_configuration.h"
#include "services/device/public/cpp/generic_sensor/sensor_reading.h"
#include "services/device/public/cpp/generic_sensor/sensor_traits.h"
+#include "services/device/public/cpp/test/fake_sensor_and_provider.h"
#include "services/device/public/mojom/constants.mojom.h"
#include "services/device/public/mojom/sensor.mojom.h"
#include "services/device/public/mojom/sensor_provider.mojom.h"
@@ -37,138 +38,7 @@ namespace content {
namespace {
-class FakeAmbientLightSensor : public device::mojom::Sensor {
- public:
- FakeAmbientLightSensor() {
- shared_buffer_handle_ = mojo::SharedBufferHandle::Create(
- sizeof(device::SensorReadingSharedBuffer) *
- static_cast<uint64_t>(device::mojom::SensorType::LAST));
-
- if (!shared_buffer_handle_.is_valid())
- return;
-
- // Create read/write mapping now, to ensure it is kept writable
- // after the region is sealed read-only on Android.
- shared_buffer_mapping_ = shared_buffer_handle_->MapAtOffset(
- device::mojom::SensorInitParams::kReadBufferSizeForTests,
- GetBufferOffset());
- }
-
- ~FakeAmbientLightSensor() override = default;
-
- // device::mojom::Sensor implemenation:
- void AddConfiguration(
- const device::PlatformSensorConfiguration& configuration,
- AddConfigurationCallback callback) override {
- std::move(callback).Run(true);
- SensorReadingChanged();
- }
-
- void GetDefaultConfiguration(
- GetDefaultConfigurationCallback callback) override {
- std::move(callback).Run(GetDefaultConfiguration());
- }
-
- void RemoveConfiguration(
- const device::PlatformSensorConfiguration& configuration) override {}
-
- void Suspend() override {}
- void Resume() override {}
- void ConfigureReadingChangeNotifications(bool enabled) override {}
-
- device::PlatformSensorConfiguration GetDefaultConfiguration() {
- return device::PlatformSensorConfiguration(
- device::SensorTraits<
- device::mojom::SensorType::AMBIENT_LIGHT>::kDefaultFrequency);
- }
-
- device::mojom::ReportingMode GetReportingMode() {
- return device::mojom::ReportingMode::ON_CHANGE;
- }
-
- double GetMaximumSupportedFrequency() {
- return device::SensorTraits<
- device::mojom::SensorType::AMBIENT_LIGHT>::kMaxAllowedFrequency;
- }
- double GetMinimumSupportedFrequency() { return 1.0; }
-
- device::mojom::SensorClientRequest GetClient() {
- return mojo::MakeRequest(&client_);
- }
-
- mojo::ScopedSharedBufferHandle GetSharedBufferHandle() {
- return shared_buffer_handle_->Clone(
- mojo::SharedBufferHandle::AccessMode::READ_ONLY);
- }
-
- uint64_t GetBufferOffset() {
- return device::SensorReadingSharedBuffer::GetOffset(
- device::mojom::SensorType::AMBIENT_LIGHT);
- }
-
- void SensorReadingChanged() {
- if (!shared_buffer_mapping_.get())
- return;
-
- device::SensorReading reading;
- reading.als.timestamp =
- (base::TimeTicks::Now() - base::TimeTicks()).InSecondsF();
- reading.als.value = 50;
-
- device::SensorReadingSharedBuffer* buffer =
- static_cast<device::SensorReadingSharedBuffer*>(
- shared_buffer_mapping_.get());
- auto& seqlock = buffer->seqlock.value();
- seqlock.WriteBegin();
- buffer->reading = reading;
- seqlock.WriteEnd();
-
- if (client_)
- client_->SensorReadingChanged();
- }
-
- private:
- mojo::ScopedSharedBufferHandle shared_buffer_handle_;
- mojo::ScopedSharedBufferMapping shared_buffer_mapping_;
- device::mojom::SensorClientPtr client_;
-
- DISALLOW_COPY_AND_ASSIGN(FakeAmbientLightSensor);
-};
-
-class FakeSensorProvider : public device::mojom::SensorProvider {
- public:
- FakeSensorProvider() = default;
- ~FakeSensorProvider() override = default;
-
- // device::mojom::sensorProvider implementation.
- void GetSensor(device::mojom::SensorType type,
- GetSensorCallback callback) override {
- switch (type) {
- case device::mojom::SensorType::AMBIENT_LIGHT: {
- auto sensor = std::make_unique<FakeAmbientLightSensor>();
-
- auto init_params = device::mojom::SensorInitParams::New();
- init_params->client_request = sensor->GetClient();
- init_params->memory = sensor->GetSharedBufferHandle();
- init_params->buffer_offset = sensor->GetBufferOffset();
- init_params->default_configuration = sensor->GetDefaultConfiguration();
- init_params->maximum_frequency = sensor->GetMaximumSupportedFrequency();
- init_params->minimum_frequency = sensor->GetMinimumSupportedFrequency();
-
- mojo::MakeStrongBinding(std::move(sensor),
- mojo::MakeRequest(&init_params->sensor));
- std::move(callback).Run(device::mojom::SensorCreationResult::SUCCESS,
- std::move(init_params));
- break;
- }
- default:
- NOTIMPLEMENTED();
- }
- }
-
- private:
- DISALLOW_COPY_AND_ASSIGN(FakeSensorProvider);
-};
+using device::FakeSensorProvider;
class GenericSensorBrowserTest : public ContentBrowserTest {
public:
@@ -227,11 +97,12 @@ class GenericSensorBrowserTest : public ContentBrowserTest {
if (!sensor_provider_available_)
return;
- if (!fake_sensor_provider_)
+ if (!fake_sensor_provider_) {
fake_sensor_provider_ = std::make_unique<FakeSensorProvider>();
+ fake_sensor_provider_->SetAmbientLightSensorData(50);
+ }
- sensor_provider_bindings_.AddBinding(
- fake_sensor_provider_.get(),
+ fake_sensor_provider_->Bind(
device::mojom::SensorProviderRequest(std::move(handle)));
}
@@ -247,7 +118,6 @@ class GenericSensorBrowserTest : public ContentBrowserTest {
base::WaitableEvent io_loop_finished_event_;
bool sensor_provider_available_ = true;
std::unique_ptr<FakeSensorProvider> fake_sensor_provider_;
- mojo::BindingSet<device::mojom::SensorProvider> sensor_provider_bindings_;
DISALLOW_COPY_AND_ASSIGN(GenericSensorBrowserTest);
};
diff --git a/chromium/content/browser/generic_sensor/sensor_provider_proxy_impl.cc b/chromium/content/browser/generic_sensor/sensor_provider_proxy_impl.cc
index b4511ecb8f2..552320b0d36 100644
--- a/chromium/content/browser/generic_sensor/sensor_provider_proxy_impl.cc
+++ b/chromium/content/browser/generic_sensor/sensor_provider_proxy_impl.cc
@@ -17,7 +17,7 @@
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "services/device/public/mojom/constants.mojom.h"
#include "services/service_manager/public/cpp/connector.h"
-#include "third_party/WebKit/public/mojom/feature_policy/feature_policy.mojom.h"
+#include "third_party/blink/public/mojom/feature_policy/feature_policy.mojom.h"
using device::mojom::SensorType;
@@ -66,17 +66,12 @@ void SensorProviderProxyImpl::GetSensor(SensorType type,
}
bool SensorProviderProxyImpl::CheckPermission() const {
- WebContents* web_contents =
- WebContents::FromRenderFrameHost(render_frame_host_);
- if (!web_contents)
- return false;
-
- const GURL& embedding_origin = web_contents->GetLastCommittedURL();
- const GURL& requesting_origin = render_frame_host_->GetLastCommittedURL();
+ const GURL& requesting_origin =
+ render_frame_host_->GetLastCommittedURL().GetOrigin();
blink::mojom::PermissionStatus permission_status =
- permission_manager_->GetPermissionStatus(
- PermissionType::SENSORS, requesting_origin, embedding_origin);
+ permission_manager_->GetPermissionStatusForFrame(
+ PermissionType::SENSORS, render_frame_host_, requesting_origin);
return permission_status == blink::mojom::PermissionStatus::GRANTED;
}
diff --git a/chromium/content/browser/geolocation/geolocation_service_impl.cc b/chromium/content/browser/geolocation/geolocation_service_impl.cc
index 0663e793c79..80bdba2932e 100644
--- a/chromium/content/browser/geolocation/geolocation_service_impl.cc
+++ b/chromium/content/browser/geolocation/geolocation_service_impl.cc
@@ -8,7 +8,7 @@
#include "content/public/browser/permission_type.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/common/content_features.h"
-#include "third_party/WebKit/public/mojom/feature_policy/feature_policy.mojom.h"
+#include "third_party/blink/public/mojom/feature_policy/feature_policy.mojom.h"
namespace content {
diff --git a/chromium/content/browser/geolocation/geolocation_service_impl.h b/chromium/content/browser/geolocation/geolocation_service_impl.h
index 4906f39656f..68f6a2000bd 100644
--- a/chromium/content/browser/geolocation/geolocation_service_impl.h
+++ b/chromium/content/browser/geolocation/geolocation_service_impl.h
@@ -10,7 +10,7 @@
#include "mojo/public/cpp/bindings/binding_set.h"
#include "services/device/public/mojom/geolocation.mojom.h"
#include "services/device/public/mojom/geolocation_context.mojom.h"
-#include "third_party/WebKit/public/platform/modules/geolocation/geolocation_service.mojom.h"
+#include "third_party/blink/public/platform/modules/geolocation/geolocation_service.mojom.h"
namespace blink {
namespace mojom {
diff --git a/chromium/content/browser/geolocation/geolocation_service_impl_unittest.cc b/chromium/content/browser/geolocation/geolocation_service_impl_unittest.cc
index ca5a0c2b8f5..895cd610fe8 100644
--- a/chromium/content/browser/geolocation/geolocation_service_impl_unittest.cc
+++ b/chromium/content/browser/geolocation/geolocation_service_impl_unittest.cc
@@ -23,7 +23,7 @@
#include "services/service_manager/public/cpp/bind_source_info.h"
#include "services/service_manager/public/cpp/connector.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/feature_policy/feature_policy.mojom.h"
+#include "third_party/blink/public/mojom/feature_policy/feature_policy.mojom.h"
using base::test::ScopedFeatureList;
using blink::mojom::PermissionStatus;
@@ -189,7 +189,7 @@ TEST_F(GeolocationServiceTest, PermissionGrantedNoPolicyViolation) {
[](base::Closure callback, GeopositionPtr geoposition) {
EXPECT_DOUBLE_EQ(kMockLatitude, geoposition->latitude);
EXPECT_DOUBLE_EQ(kMockLongitude, geoposition->longitude);
- callback.Run();
+ std::move(callback).Run();
},
loop.QuitClosure()));
loop.Run();
@@ -212,7 +212,7 @@ TEST_F(GeolocationServiceTest, PermissionGrantedSync) {
[](base::Closure callback, GeopositionPtr geoposition) {
EXPECT_DOUBLE_EQ(kMockLatitude, geoposition->latitude);
EXPECT_DOUBLE_EQ(kMockLongitude, geoposition->longitude);
- callback.Run();
+ std::move(callback).Run();
},
loop.QuitClosure()));
loop.Run();
@@ -259,7 +259,7 @@ TEST_F(GeolocationServiceTest, PermissionGrantedAsync) {
[](base::Closure callback, GeopositionPtr geoposition) {
EXPECT_DOUBLE_EQ(kMockLatitude, geoposition->latitude);
EXPECT_DOUBLE_EQ(kMockLongitude, geoposition->longitude);
- callback.Run();
+ std::move(callback).Run();
},
loop.QuitClosure()));
loop.Run();
diff --git a/chromium/content/browser/gpu/browser_gpu_channel_host_factory.cc b/chromium/content/browser/gpu/browser_gpu_channel_host_factory.cc
index b2a89383040..cdc4d3d678a 100644
--- a/chromium/content/browser/gpu/browser_gpu_channel_host_factory.cc
+++ b/chromium/content/browser/gpu/browser_gpu_channel_host_factory.cc
@@ -352,7 +352,7 @@ void BrowserGpuChannelHostFactory::RestartTimeout() {
return;
#if defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER) || \
- defined(SYZYASAN) || defined(CYGPROFILE_INSTRUMENTATION)
+ defined(CYGPROFILE_INSTRUMENTATION)
constexpr int64_t kGpuChannelTimeoutInSeconds = 40;
#else
// The GPU watchdog timeout is 15 seconds (1.5x the kGpuTimeout value due to
diff --git a/chromium/content/browser/gpu/browser_gpu_memory_buffer_manager.cc b/chromium/content/browser/gpu/browser_gpu_memory_buffer_manager.cc
index bab50551cf8..22d03d380b4 100644
--- a/chromium/content/browser/gpu/browser_gpu_memory_buffer_manager.cc
+++ b/chromium/content/browser/gpu/browser_gpu_memory_buffer_manager.cc
@@ -20,8 +20,9 @@
#include "content/common/child_process_host_impl.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
-#include "gpu/ipc/client/gpu_memory_buffer_impl.h"
-#include "gpu/ipc/client/gpu_memory_buffer_impl_shared_memory.h"
+#include "gpu/ipc/common/gpu_memory_buffer_impl.h"
+#include "gpu/ipc/common/gpu_memory_buffer_impl_shared_memory.h"
+#include "gpu/ipc/common/gpu_memory_buffer_support.h"
#include "ui/gfx/buffer_format_util.h"
#include "ui/gl/gl_switches.h"
@@ -66,7 +67,9 @@ struct BrowserGpuMemoryBufferManager::CreateGpuMemoryBufferRequest {
BrowserGpuMemoryBufferManager::BrowserGpuMemoryBufferManager(
int gpu_client_id,
uint64_t gpu_client_tracing_id)
- : native_configurations_(gpu::GetNativeGpuMemoryBufferConfigurations()),
+ : gpu_memory_buffer_support_(new gpu::GpuMemoryBufferSupport()),
+ native_configurations_(gpu::GetNativeGpuMemoryBufferConfigurations(
+ gpu_memory_buffer_support_.get())),
gpu_client_id_(gpu_client_id),
gpu_client_tracing_id_(gpu_client_tracing_id) {
DCHECK(!g_gpu_memory_buffer_manager);
@@ -105,13 +108,13 @@ void BrowserGpuMemoryBufferManager::AllocateGpuMemoryBufferForChildProcess(
gfx::BufferFormat format,
gfx::BufferUsage usage,
int child_client_id,
- const AllocationCallback& callback) {
+ AllocationCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
// Use service side allocation for native configurations.
if (IsNativeGpuMemoryBufferConfiguration(format, usage)) {
CreateGpuMemoryBufferOnIO(id, size, format, usage, gpu::kNullSurfaceHandle,
- child_client_id, callback);
+ child_client_id, std::move(callback));
return;
}
@@ -119,7 +122,7 @@ void BrowserGpuMemoryBufferManager::AllocateGpuMemoryBufferForChildProcess(
if (!gpu::GpuMemoryBufferImplSharedMemory::IsUsageSupported(usage) ||
!gpu::GpuMemoryBufferImplSharedMemory::IsSizeValidForFormat(size,
format)) {
- callback.Run(gfx::GpuMemoryBufferHandle());
+ std::move(callback).Run(gfx::GpuMemoryBufferHandle());
return;
}
@@ -131,14 +134,14 @@ void BrowserGpuMemoryBufferManager::AllocateGpuMemoryBufferForChildProcess(
if (!insert_result.second) {
DLOG(ERROR) << "Child process attempted to allocate a GpuMemoryBuffer with "
"an existing ID.";
- callback.Run(gfx::GpuMemoryBufferHandle());
+ std::move(callback).Run(gfx::GpuMemoryBufferHandle());
return;
}
auto handle = gpu::GpuMemoryBufferImplSharedMemory::CreateGpuMemoryBuffer(
id, size, format, usage);
buffers.find(id)->second.shared_memory_guid = handle.handle.GetGUID();
- callback.Run(handle);
+ std::move(callback).Run(handle);
}
void BrowserGpuMemoryBufferManager::SetDestructionSyncToken(
@@ -272,7 +275,7 @@ void BrowserGpuMemoryBufferManager::HandleCreateGpuMemoryBufferOnIO(
CreateGpuMemoryBufferOnIO(
new_id, request->size, request->format, request->usage,
request->surface_handle, request->client_id,
- base::Bind(
+ base::BindOnce(
&BrowserGpuMemoryBufferManager::HandleGpuMemoryBufferCreatedOnIO,
base::Unretained(this), base::Unretained(request)));
return;
@@ -318,13 +321,15 @@ void BrowserGpuMemoryBufferManager::HandleGpuMemoryBufferCreatedOnIO(
// Note: Unretained is safe as IO thread is stopped before manager is
// destroyed.
- request->result = gpu::GpuMemoryBufferImpl::CreateFromHandle(
- handle, request->size, request->format, request->usage,
- base::Bind(
- &GpuMemoryBufferDeleted,
- BrowserThread::GetTaskRunnerForThread(BrowserThread::IO),
- base::Bind(&BrowserGpuMemoryBufferManager::DestroyGpuMemoryBufferOnIO,
- base::Unretained(this), handle.id, request->client_id)));
+ request->result =
+ gpu_memory_buffer_support_->CreateGpuMemoryBufferImplFromHandle(
+ handle, request->size, request->format, request->usage,
+ base::Bind(
+ &GpuMemoryBufferDeleted,
+ BrowserThread::GetTaskRunnerForThread(BrowserThread::IO),
+ base::Bind(
+ &BrowserGpuMemoryBufferManager::DestroyGpuMemoryBufferOnIO,
+ base::Unretained(this), handle.id, request->client_id)));
request->event.Signal();
}
@@ -335,7 +340,7 @@ void BrowserGpuMemoryBufferManager::CreateGpuMemoryBufferOnIO(
gfx::BufferUsage usage,
gpu::SurfaceHandle surface_handle,
int client_id,
- const CreateCallback& callback) {
+ CreateCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
BufferMap& buffers = clients_[client_id];
@@ -347,23 +352,23 @@ void BrowserGpuMemoryBufferManager::CreateGpuMemoryBufferOnIO(
if (!insert_result.second) {
DLOG(ERROR) << "Child process attempted to create a GpuMemoryBuffer with "
"an existing ID.";
- callback.Run(gfx::GpuMemoryBufferHandle());
+ std::move(callback).Run(gfx::GpuMemoryBufferHandle());
return;
}
GpuProcessHost* host = GpuProcessHost::Get();
if (!host) {
DLOG(ERROR) << "Cannot allocate GpuMemoryBuffer with no GpuProcessHost.";
- callback.Run(gfx::GpuMemoryBufferHandle());
+ std::move(callback).Run(gfx::GpuMemoryBufferHandle());
return;
}
// Note: Unretained is safe as IO thread is stopped before manager is
// destroyed.
host->CreateGpuMemoryBuffer(
id, size, format, usage, client_id, surface_handle,
- base::Bind(&BrowserGpuMemoryBufferManager::GpuMemoryBufferCreatedOnIO,
- base::Unretained(this), id, surface_handle, client_id,
- host->host_id(), callback));
+ base::BindOnce(&BrowserGpuMemoryBufferManager::GpuMemoryBufferCreatedOnIO,
+ base::Unretained(this), id, surface_handle, client_id,
+ host->host_id(), std::move(callback)));
}
void BrowserGpuMemoryBufferManager::GpuMemoryBufferCreatedOnIO(
@@ -371,7 +376,7 @@ void BrowserGpuMemoryBufferManager::GpuMemoryBufferCreatedOnIO(
gpu::SurfaceHandle surface_handle,
int client_id,
int gpu_host_id,
- const CreateCallback& callback,
+ CreateCallback callback,
const gfx::GpuMemoryBufferHandle& handle,
GpuProcessHost::BufferCreationStatus status) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
@@ -385,7 +390,7 @@ void BrowserGpuMemoryBufferManager::GpuMemoryBufferCreatedOnIO(
if (host)
host->DestroyGpuMemoryBuffer(handle.id, client_id, gpu::SyncToken());
}
- callback.Run(gfx::GpuMemoryBufferHandle());
+ std::move(callback).Run(gfx::GpuMemoryBufferHandle());
return;
}
@@ -411,12 +416,12 @@ void BrowserGpuMemoryBufferManager::GpuMemoryBufferCreatedOnIO(
// Remove the buffer entry and call CreateGpuMemoryBufferOnIO again.
buffers.erase(buffer_it);
CreateGpuMemoryBufferOnIO(id, size, format, usage, surface_handle,
- client_id, callback);
+ client_id, std::move(callback));
} else {
// Remove the buffer entry and run the allocation callback with an empty
// handle to indicate failure.
buffers.erase(buffer_it);
- callback.Run(gfx::GpuMemoryBufferHandle());
+ std::move(callback).Run(gfx::GpuMemoryBufferHandle());
}
return;
}
@@ -427,7 +432,7 @@ void BrowserGpuMemoryBufferManager::GpuMemoryBufferCreatedOnIO(
buffer_it->second.gpu_host_id = gpu_host_id;
buffer_it->second.shared_memory_guid = handle.handle.GetGUID();
- callback.Run(handle);
+ std::move(callback).Run(handle);
}
void BrowserGpuMemoryBufferManager::DestroyGpuMemoryBufferOnIO(
diff --git a/chromium/content/browser/gpu/browser_gpu_memory_buffer_manager.h b/chromium/content/browser/gpu/browser_gpu_memory_buffer_manager.h
index a6c05b737d3..41843a9309c 100644
--- a/chromium/content/browser/gpu/browser_gpu_memory_buffer_manager.h
+++ b/chromium/content/browser/gpu/browser_gpu_memory_buffer_manager.h
@@ -22,6 +22,10 @@
#include "gpu/ipc/common/surface_handle.h"
#include "gpu/ipc/host/gpu_memory_buffer_support.h"
+namespace gpu {
+class GpuMemoryBufferSupport;
+}
+
namespace content {
class CONTENT_EXPORT BrowserGpuMemoryBufferManager
@@ -29,7 +33,7 @@ class CONTENT_EXPORT BrowserGpuMemoryBufferManager
public base::trace_event::MemoryDumpProvider {
public:
using CreateCallback =
- base::Callback<void(const gfx::GpuMemoryBufferHandle& handle)>;
+ base::OnceCallback<void(const gfx::GpuMemoryBufferHandle& handle)>;
using AllocationCallback = CreateCallback;
BrowserGpuMemoryBufferManager(int gpu_client_id,
@@ -51,13 +55,12 @@ class CONTENT_EXPORT BrowserGpuMemoryBufferManager
bool OnMemoryDump(const base::trace_event::MemoryDumpArgs& args,
base::trace_event::ProcessMemoryDump* pmd) override;
- void AllocateGpuMemoryBufferForChildProcess(
- gfx::GpuMemoryBufferId id,
- const gfx::Size& size,
- gfx::BufferFormat format,
- gfx::BufferUsage usage,
- int child_client_id,
- const AllocationCallback& callback);
+ void AllocateGpuMemoryBufferForChildProcess(gfx::GpuMemoryBufferId id,
+ const gfx::Size& size,
+ gfx::BufferFormat format,
+ gfx::BufferUsage usage,
+ int child_client_id,
+ AllocationCallback callback);
void ChildProcessDeletedGpuMemoryBuffer(
gfx::GpuMemoryBufferId id,
int child_client_id,
@@ -106,12 +109,12 @@ class CONTENT_EXPORT BrowserGpuMemoryBufferManager
gfx::BufferUsage usage,
gpu::SurfaceHandle surface_handle,
int client_id,
- const CreateCallback& callback);
+ CreateCallback callback);
void GpuMemoryBufferCreatedOnIO(gfx::GpuMemoryBufferId id,
gpu::SurfaceHandle surface_handle,
int client_id,
int gpu_host_id,
- const CreateCallback& callback,
+ CreateCallback callback,
const gfx::GpuMemoryBufferHandle& handle,
GpuProcessHost::BufferCreationStatus status);
void DestroyGpuMemoryBufferOnIO(gfx::GpuMemoryBufferId id,
@@ -120,6 +123,8 @@ class CONTENT_EXPORT BrowserGpuMemoryBufferManager
uint64_t ClientIdToTracingProcessId(int client_id) const;
+ std::unique_ptr<gpu::GpuMemoryBufferSupport> gpu_memory_buffer_support_;
+
const gpu::GpuMemoryBufferConfigurationSet native_configurations_;
const int gpu_client_id_;
const uint64_t gpu_client_tracing_id_;
diff --git a/chromium/content/browser/gpu/compositor_util.cc b/chromium/content/browser/gpu/compositor_util.cc
index 63705c8f0b4..7af07718719 100644
--- a/chromium/content/browser/gpu/compositor_util.cc
+++ b/chromium/content/browser/gpu/compositor_util.cc
@@ -20,7 +20,9 @@
#include "build/build_config.h"
#include "cc/base/switches.h"
#include "components/viz/common/features.h"
+#include "content/browser/compositor/image_transport_factory.h"
#include "content/browser/gpu/gpu_data_manager_impl.h"
+#include "content/browser/gpu/gpu_process_host.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "gpu/command_buffer/common/gpu_memory_buffer_support.h"
@@ -28,7 +30,7 @@
#include "gpu/config/gpu_finch_features.h"
#include "gpu/config/gpu_switches.h"
#include "gpu/ipc/host/gpu_memory_buffer_support.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "ui/gl/gl_switches.h"
namespace content {
@@ -53,21 +55,43 @@ bool IsForceGpuRasterizationEnabled() {
return command_line->HasSwitch(switches::kForceGpuRasterization);
}
+gpu::GpuFeatureStatus SafeGetFeatureStatus(GpuDataManagerImpl* manager,
+ gpu::GpuFeatureType feature) {
+ if (!manager->IsGpuFeatureInfoAvailable()) {
+ // The GPU process probably crashed during startup, but we can't
+ // assert this as the test bots are slow, and recording the crash
+ // is racy. Be robust and just say that all features are disabled.
+ return gpu::kGpuFeatureStatusDisabled;
+ }
+ return manager->GetFeatureStatus(feature);
+}
+
+gpu::GpuFeatureStatus GetGpuCompositingStatus() {
+ gpu::GpuFeatureStatus status = SafeGetFeatureStatus(
+ GpuDataManagerImpl::GetInstance(), gpu::GPU_FEATURE_TYPE_GPU_COMPOSITING);
+#if defined(USE_AURA) || defined(OS_MACOSX)
+ if (status == gpu::kGpuFeatureStatusEnabled &&
+ ImageTransportFactory::GetInstance()->IsGpuCompositingDisabled()) {
+ status = gpu::kGpuFeatureStatusDisabled;
+ }
+#endif
+ return status;
+}
+
const GpuFeatureData GetGpuFeatureData(size_t index, bool* eof) {
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
GpuDataManagerImpl* manager = GpuDataManagerImpl::GetInstance();
- DCHECK(manager->IsGpuFeatureInfoAvailable());
const GpuFeatureData kGpuFeatureData[] = {
{"2d_canvas",
- manager->GetFeatureStatus(gpu::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS),
+ SafeGetFeatureStatus(manager,
+ gpu::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS),
command_line.HasSwitch(switches::kDisableAccelerated2dCanvas),
"Accelerated 2D canvas is unavailable: either disabled via blacklist or"
" the command line.",
true},
- {"gpu_compositing",
- manager->GetFeatureStatus(gpu::GPU_FEATURE_TYPE_GPU_COMPOSITING),
+ {"gpu_compositing", GetGpuCompositingStatus(),
command_line.HasSwitch(switches::kDisableGpuCompositing),
"Gpu compositing has been disabled, either via blacklist, about:flags"
" or the command line. The browser will fall back to software "
@@ -75,36 +99,37 @@ const GpuFeatureData GetGpuFeatureData(size_t index, bool* eof) {
" and hardware acceleration will be unavailable.",
true},
{"webgl",
- manager->GetFeatureStatus(gpu::GPU_FEATURE_TYPE_ACCELERATED_WEBGL),
+ SafeGetFeatureStatus(manager, gpu::GPU_FEATURE_TYPE_ACCELERATED_WEBGL),
command_line.HasSwitch(switches::kDisableWebGL),
"WebGL has been disabled via blacklist or the command line.", false},
- {"flash_3d", manager->GetFeatureStatus(gpu::GPU_FEATURE_TYPE_FLASH3D),
+ {"flash_3d", SafeGetFeatureStatus(manager, gpu::GPU_FEATURE_TYPE_FLASH3D),
command_line.HasSwitch(switches::kDisableFlash3d),
"Using 3d in flash has been disabled, either via blacklist, about:flags "
"or"
" the command line.",
true},
{"flash_stage3d",
- manager->GetFeatureStatus(gpu::GPU_FEATURE_TYPE_FLASH_STAGE3D),
+ SafeGetFeatureStatus(manager, gpu::GPU_FEATURE_TYPE_FLASH_STAGE3D),
command_line.HasSwitch(switches::kDisableFlashStage3d),
"Using Stage3d in Flash has been disabled, either via blacklist,"
" about:flags or the command line.",
true},
{"flash_stage3d_baseline",
- manager->GetFeatureStatus(gpu::GPU_FEATURE_TYPE_FLASH_STAGE3D_BASELINE),
+ SafeGetFeatureStatus(manager,
+ gpu::GPU_FEATURE_TYPE_FLASH_STAGE3D_BASELINE),
command_line.HasSwitch(switches::kDisableFlashStage3d),
"Using Stage3d Baseline profile in Flash has been disabled, either"
" via blacklist, about:flags or the command line.",
true},
{"video_decode",
- manager->GetFeatureStatus(
- gpu::GPU_FEATURE_TYPE_ACCELERATED_VIDEO_DECODE),
+ SafeGetFeatureStatus(manager,
+ gpu::GPU_FEATURE_TYPE_ACCELERATED_VIDEO_DECODE),
command_line.HasSwitch(switches::kDisableAcceleratedVideoDecode),
"Accelerated video decode has been disabled, either via blacklist,"
" about:flags or the command line.",
true},
{"rasterization",
- manager->GetFeatureStatus(gpu::GPU_FEATURE_TYPE_GPU_RASTERIZATION),
+ SafeGetFeatureStatus(manager, gpu::GPU_FEATURE_TYPE_GPU_RASTERIZATION),
(command_line.HasSwitch(switches::kDisableGpuRasterization) &&
!IsForceGpuRasterizationEnabled()),
"Accelerated rasterization has been disabled, either via blacklist,"
@@ -124,10 +149,13 @@ const GpuFeatureData GetGpuFeatureData(size_t index, bool* eof) {
"line.",
false},
{"webgl2",
- manager->GetFeatureStatus(gpu::GPU_FEATURE_TYPE_ACCELERATED_WEBGL2),
+ SafeGetFeatureStatus(manager, gpu::GPU_FEATURE_TYPE_ACCELERATED_WEBGL2),
(command_line.HasSwitch(switches::kDisableWebGL) ||
command_line.HasSwitch(switches::kDisableWebGL2)),
"WebGL2 has been disabled via blacklist or the command line.", false},
+ {"viz_display_compositor", gpu::kGpuFeatureStatusEnabled,
+ !base::FeatureList::IsEnabled(features::kVizDisplayCompositor),
+ "Viz service display compositor is not enabled by default.", false},
{"checker_imaging", gpu::kGpuFeatureStatusEnabled,
!IsCheckerImagingEnabled(),
"Checker-imaging has been disabled via finch trial or the command line.",
@@ -265,17 +293,6 @@ bool IsCheckerImagingEnabled() {
return false;
}
-bool IsCompositorImageAnimationEnabled() {
- if (base::CommandLine::ForCurrentProcess()->HasSwitch(
- switches::kEnableCompositorImageAnimations))
- return true;
-
- if (base::FeatureList::IsEnabled(features::kCompositorImageAnimation))
- return true;
-
- return false;
-}
-
std::unique_ptr<base::DictionaryValue> GetFeatureStatus() {
GpuDataManagerImpl* manager = GpuDataManagerImpl::GetInstance();
std::string gpu_access_blocked_reason;
@@ -328,6 +345,10 @@ std::unique_ptr<base::DictionaryValue> GetFeatureStatus() {
if (features::IsSurfaceSynchronizationEnabled())
status += "_on";
}
+ if (gpu_feature_data.name == "viz_display_compositor") {
+ if (base::FeatureList::IsEnabled(features::kVizDisplayCompositor))
+ status += "_on";
+ }
}
feature_status_dict->SetString(gpu_feature_data.name, status);
}
diff --git a/chromium/content/browser/gpu/gpu_client.cc b/chromium/content/browser/gpu/gpu_client.cc
index a1e66633311..541bdd0c9bc 100644
--- a/chromium/content/browser/gpu/gpu_client.cc
+++ b/chromium/content/browser/gpu/gpu_client.cc
@@ -9,8 +9,8 @@
#include "content/common/child_process_host_impl.h"
#include "content/public/browser/browser_thread.h"
#include "gpu/ipc/client/gpu_channel_host.h"
-#include "gpu/ipc/client/gpu_memory_buffer_impl.h"
-#include "gpu/ipc/client/gpu_memory_buffer_impl_shared_memory.h"
+#include "gpu/ipc/common/gpu_memory_buffer_impl.h"
+#include "gpu/ipc/common/gpu_memory_buffer_impl_shared_memory.h"
namespace content {
@@ -61,13 +61,13 @@ void GpuClient::OnEstablishGpuChannel(
if (status == GpuProcessHost::EstablishChannelStatus::GPU_HOST_INVALID) {
// GPU process may have crashed or been killed. Try again.
- EstablishGpuChannel(callback);
+ EstablishGpuChannel(std::move(callback));
return;
}
if (callback) {
// A request is waiting.
- callback.Run(render_process_id_, std::move(channel_handle), gpu_info,
- gpu_feature_info);
+ std::move(callback).Run(render_process_id_, std::move(channel_handle),
+ gpu_info, gpu_feature_info);
return;
}
if (status == GpuProcessHost::EstablishChannelStatus::SUCCESS) {
@@ -80,22 +80,21 @@ void GpuClient::OnEstablishGpuChannel(
}
void GpuClient::OnCreateGpuMemoryBuffer(
- const CreateGpuMemoryBufferCallback& callback,
+ CreateGpuMemoryBufferCallback callback,
const gfx::GpuMemoryBufferHandle& handle) {
- callback.Run(handle);
+ std::move(callback).Run(handle);
}
void GpuClient::ClearCallback() {
if (!callback_)
return;
EstablishGpuChannelCallback callback = std::move(callback_);
- callback.Run(render_process_id_, mojo::ScopedMessagePipeHandle(),
- gpu::GPUInfo(), gpu::GpuFeatureInfo());
+ std::move(callback).Run(render_process_id_, mojo::ScopedMessagePipeHandle(),
+ gpu::GPUInfo(), gpu::GpuFeatureInfo());
DCHECK(!callback_);
}
-void GpuClient::EstablishGpuChannel(
- const EstablishGpuChannelCallback& callback) {
+void GpuClient::EstablishGpuChannel(EstablishGpuChannelCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
// At most one channel should be requested. So clear previous request first.
ClearCallback();
@@ -105,8 +104,8 @@ void GpuClient::EstablishGpuChannel(
// 2) if callback is empty, it's PreEstablishGpyChannel() being called
// more than once, no need to do anything.
if (callback) {
- callback.Run(render_process_id_, std::move(channel_handle_), gpu_info_,
- gpu_feature_info_);
+ std::move(callback).Run(render_process_id_, std::move(channel_handle_),
+ gpu_info_, gpu_feature_info_);
DCHECK(!channel_handle_.is_valid());
}
return;
@@ -114,12 +113,13 @@ void GpuClient::EstablishGpuChannel(
GpuProcessHost* host = GpuProcessHost::Get();
if (!host) {
if (callback) {
- callback.Run(render_process_id_, mojo::ScopedMessagePipeHandle(),
- gpu::GPUInfo(), gpu::GpuFeatureInfo());
+ std::move(callback).Run(render_process_id_,
+ mojo::ScopedMessagePipeHandle(), gpu::GPUInfo(),
+ gpu::GpuFeatureInfo());
}
return;
}
- callback_ = callback;
+ callback_ = std::move(callback);
if (gpu_channel_requested_)
return;
gpu_channel_requested_ = true;
@@ -156,21 +156,21 @@ void GpuClient::CreateGpuMemoryBuffer(
const gfx::Size& size,
gfx::BufferFormat format,
gfx::BufferUsage usage,
- const ui::mojom::Gpu::CreateGpuMemoryBufferCallback& callback) {
+ ui::mojom::Gpu::CreateGpuMemoryBufferCallback callback) {
DCHECK(BrowserGpuMemoryBufferManager::current());
base::CheckedNumeric<int> bytes = size.width();
bytes *= size.height();
if (!bytes.IsValid()) {
- OnCreateGpuMemoryBuffer(callback, gfx::GpuMemoryBufferHandle());
+ OnCreateGpuMemoryBuffer(std::move(callback), gfx::GpuMemoryBufferHandle());
return;
}
BrowserGpuMemoryBufferManager::current()
->AllocateGpuMemoryBufferForChildProcess(
id, size, format, usage, render_process_id_,
- base::Bind(&GpuClient::OnCreateGpuMemoryBuffer,
- weak_factory_.GetWeakPtr(), callback));
+ base::BindOnce(&GpuClient::OnCreateGpuMemoryBuffer,
+ weak_factory_.GetWeakPtr(), std::move(callback)));
}
void GpuClient::DestroyGpuMemoryBuffer(gfx::GpuMemoryBufferId id,
diff --git a/chromium/content/browser/gpu/gpu_client.h b/chromium/content/browser/gpu/gpu_client.h
index a0a36fa2623..89d0d9cdf6c 100644
--- a/chromium/content/browser/gpu/gpu_client.h
+++ b/chromium/content/browser/gpu/gpu_client.h
@@ -27,13 +27,12 @@ class GpuClient : public ui::mojom::Gpu {
const gpu::GPUInfo& gpu_info,
const gpu::GpuFeatureInfo& gpu_feature_info,
GpuProcessHost::EstablishChannelStatus status);
- void OnCreateGpuMemoryBuffer(const CreateGpuMemoryBufferCallback& callback,
+ void OnCreateGpuMemoryBuffer(CreateGpuMemoryBufferCallback callback,
const gfx::GpuMemoryBufferHandle& handle);
void ClearCallback();
// ui::mojom::Gpu overrides:
- void EstablishGpuChannel(
- const EstablishGpuChannelCallback& callback) override;
+ void EstablishGpuChannel(EstablishGpuChannelCallback callback) override;
void CreateJpegDecodeAccelerator(
media::mojom::JpegDecodeAcceleratorRequest jda_request) override;
void CreateVideoEncodeAcceleratorProvider(
@@ -44,7 +43,7 @@ class GpuClient : public ui::mojom::Gpu {
const gfx::Size& size,
gfx::BufferFormat format,
gfx::BufferUsage usage,
- const ui::mojom::Gpu::CreateGpuMemoryBufferCallback& callback) override;
+ ui::mojom::Gpu::CreateGpuMemoryBufferCallback callback) override;
void DestroyGpuMemoryBuffer(gfx::GpuMemoryBufferId id,
const gpu::SyncToken& sync_token) override;
diff --git a/chromium/content/browser/gpu/gpu_data_manager_impl.cc b/chromium/content/browser/gpu/gpu_data_manager_impl.cc
index a8ad7fb68f7..13f75be6f01 100644
--- a/chromium/content/browser/gpu/gpu_data_manager_impl.cc
+++ b/chromium/content/browser/gpu/gpu_data_manager_impl.cc
@@ -74,11 +74,6 @@ void GpuDataManagerImpl::RemoveObserver(
private_->RemoveObserver(observer);
}
-void GpuDataManagerImpl::UnblockDomainFrom3DAPIs(const GURL& url) {
- base::AutoLock auto_lock(lock_);
- private_->UnblockDomainFrom3DAPIs(url);
-}
-
void GpuDataManagerImpl::DisableHardwareAcceleration() {
base::AutoLock auto_lock(lock_);
private_->DisableHardwareAcceleration();
@@ -89,6 +84,11 @@ void GpuDataManagerImpl::BlockSwiftShader() {
private_->BlockSwiftShader();
}
+bool GpuDataManagerImpl::SwiftShaderAllowed() const {
+ base::AutoLock auto_lock(lock_);
+ return private_->SwiftShaderAllowed();
+}
+
bool GpuDataManagerImpl::HardwareAccelerationEnabled() const {
base::AutoLock auto_lock(lock_);
return private_->HardwareAccelerationEnabled();
@@ -100,6 +100,16 @@ void GpuDataManagerImpl::GetDisabledExtensions(
private_->GetDisabledExtensions(disabled_extensions);
}
+void GpuDataManagerImpl::RequestGpuSupportedRuntimeVersion() const {
+ base::AutoLock auto_lock(lock_);
+ private_->RequestGpuSupportedRuntimeVersion();
+}
+
+bool GpuDataManagerImpl::GpuProcessStartAllowed() const {
+ base::AutoLock auto_lock(lock_);
+ return private_->GpuProcessStartAllowed();
+}
+
void GpuDataManagerImpl::GetDisabledWebGLExtensions(
std::string* disabled_webgl_extensions) const {
base::AutoLock auto_lock(lock_);
@@ -182,6 +192,11 @@ bool GpuDataManagerImpl::Are3DAPIsBlocked(const GURL& top_origin_url,
top_origin_url, render_process_id, render_frame_id, requester);
}
+void GpuDataManagerImpl::UnblockDomainFrom3DAPIs(const GURL& url) {
+ base::AutoLock auto_lock(lock_);
+ private_->UnblockDomainFrom3DAPIs(url);
+}
+
void GpuDataManagerImpl::DisableDomainBlockingFor3DAPIsForTesting() {
base::AutoLock auto_lock(lock_);
private_->DisableDomainBlockingFor3DAPIsForTesting();
@@ -193,13 +208,9 @@ bool GpuDataManagerImpl::UpdateActiveGpu(uint32_t vendor_id,
return private_->UpdateActiveGpu(vendor_id, device_id);
}
-void GpuDataManagerImpl::Notify3DAPIBlocked(const GURL& top_origin_url,
- int render_process_id,
- int render_frame_id,
- ThreeDAPIType requester) {
+void GpuDataManagerImpl::NotifyGpuInfoUpdate() {
base::AutoLock auto_lock(lock_);
- private_->Notify3DAPIBlocked(
- top_origin_url, render_process_id, render_frame_id, requester);
+ private_->NotifyGpuInfoUpdate();
}
void GpuDataManagerImpl::OnGpuProcessInitFailure() {
diff --git a/chromium/content/browser/gpu/gpu_data_manager_impl.h b/chromium/content/browser/gpu/gpu_data_manager_impl.h
index 0fa3ce2d7f9..b77578834a6 100644
--- a/chromium/content/browser/gpu/gpu_data_manager_impl.h
+++ b/chromium/content/browser/gpu/gpu_data_manager_impl.h
@@ -79,11 +79,13 @@ class CONTENT_EXPORT GpuDataManagerImpl : public GpuDataManager {
// callbacks, should probably be required to occur on the UI thread.
void AddObserver(GpuDataManagerObserver* observer) override;
void RemoveObserver(GpuDataManagerObserver* observer) override;
- void UnblockDomainFrom3DAPIs(const GURL& url) override;
void DisableHardwareAcceleration() override;
bool HardwareAccelerationEnabled() const override;
void GetDisabledExtensions(std::string* disabled_extensions) const override;
+ void RequestGpuSupportedRuntimeVersion() const;
+ bool GpuProcessStartAllowed() const;
+
void GetDisabledWebGLExtensions(std::string* disabled_webgl_extensions) const;
bool IsGpuFeatureInfoAvailable() const;
@@ -134,31 +136,29 @@ class CONTENT_EXPORT GpuDataManagerImpl : public GpuDataManager {
//
// The given URL may be a partial URL (including at least the host)
// or a full URL to a page.
- //
- // Note that the unblocking API must be part of the content API
- // because it is called from Chrome side code.
void BlockDomainFrom3DAPIs(const GURL& url, DomainGuilt guilt);
bool Are3DAPIsBlocked(const GURL& top_origin_url,
int render_process_id,
int render_frame_id,
ThreeDAPIType requester);
+ void UnblockDomainFrom3DAPIs(const GURL& url);
// Disables domain blocking for 3D APIs. For use only in tests.
void DisableDomainBlockingFor3DAPIsForTesting();
- void Notify3DAPIBlocked(const GURL& top_origin_url,
- int render_process_id,
- int render_frame_id,
- ThreeDAPIType requester);
-
// Set the active gpu.
// Return true if it's a different GPU from the previous active one.
bool UpdateActiveGpu(uint32_t vendor_id, uint32_t device_id);
+ // Notify all observers whenever there is a GPU info or GPU feature
+ // status update.
+ void NotifyGpuInfoUpdate();
+
// Called when GPU process initialization failed.
void OnGpuProcessInitFailure();
void BlockSwiftShader();
+ bool SwiftShaderAllowed() const;
private:
friend class GpuDataManagerImplPrivate;
diff --git a/chromium/content/browser/gpu/gpu_data_manager_impl_private.cc b/chromium/content/browser/gpu/gpu_data_manager_impl_private.cc
index e69f7a8c7a5..657b6381461 100644
--- a/chromium/content/browser/gpu/gpu_data_manager_impl_private.cc
+++ b/chromium/content/browser/gpu/gpu_data_manager_impl_private.cc
@@ -12,7 +12,7 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
-#include "base/memory/ptr_util.h"
+#include "base/feature_list.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
@@ -21,6 +21,7 @@
#include "base/version.h"
#include "build/build_config.h"
#include "cc/base/switches.h"
+#include "components/viz/common/features.h"
#include "content/browser/gpu/browser_gpu_memory_buffer_manager.h"
#include "content/browser/gpu/compositor_util.h"
#include "content/browser/gpu/gpu_process_host.h"
@@ -44,7 +45,7 @@
#include "gpu/ipc/common/gpu_preferences_util.h"
#include "gpu/ipc/common/memory_stats.h"
#include "gpu/ipc/host/shader_disk_cache.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "ui/base/ui_base_switches.h"
#include "ui/gfx/switches.h"
#include "ui/gl/gl_features.h"
@@ -314,6 +315,11 @@ bool GpuDataManagerImplPrivate::GpuAccessAllowed(
return true;
}
+bool GpuDataManagerImplPrivate::GpuProcessStartAllowed() const {
+ return base::FeatureList::IsEnabled(features::kVizDisplayCompositor) ||
+ GpuAccessAllowed(nullptr);
+}
+
void GpuDataManagerImplPrivate::RequestCompleteGpuInfoIfNeeded() {
if (complete_gpu_info_already_requested_)
return;
@@ -338,6 +344,21 @@ void GpuDataManagerImplPrivate::RequestCompleteGpuInfoIfNeeded() {
}));
}
+void GpuDataManagerImplPrivate::RequestGpuSupportedRuntimeVersion() {
+#if defined(OS_WIN)
+ base::OnceClosure task = base::BindOnce([]() {
+ GpuProcessHost* host = GpuProcessHost::Get(
+ GpuProcessHost::GPU_PROCESS_KIND_UNSANDBOXED, true /* force_create */);
+ if (!host)
+ return;
+ host->gpu_service()->GetGpuSupportedRuntimeVersion();
+ });
+
+ BrowserThread::PostDelayedTask(BrowserThread::IO, FROM_HERE, std::move(task),
+ base::TimeDelta::FromMilliseconds(15000));
+#endif
+}
+
bool GpuDataManagerImplPrivate::IsEssentialGpuInfoAvailable() const {
// We always update GPUInfo and GpuFeatureInfo from GPU process together.
return IsGpuFeatureInfoAvailable();
@@ -386,6 +407,13 @@ void GpuDataManagerImplPrivate::UnblockDomainFrom3DAPIs(const GURL& url) {
//
// These policies could be refined, but at a certain point the behavior
// will become difficult to explain.
+
+ // Shortcut in the common case where no blocking has occurred. This
+ // is important to not regress navigation performance, since this is
+ // now called on every user-initiated navigation.
+ if (blocked_domains_.empty() && timestamps_of_gpu_resets_.empty())
+ return;
+
std::string domain = GetDomainFromURL(url);
blocked_domains_.erase(domain);
@@ -439,8 +467,7 @@ void GpuDataManagerImplPrivate::AppendGpuCommandLine(
gpu::GpuPreferencesToSwitchValue(gpu_prefs));
std::string use_gl;
- if (card_disabled_ && !swiftshader_blocked_ &&
- !browser_command_line->HasSwitch(switches::kDisableSoftwareRasterizer)) {
+ if (card_disabled_ && SwiftShaderAllowed()) {
use_gl = gl::kGLImplementationSwiftShaderForWebGLName;
} else {
use_gl = browser_command_line->GetSwitchValueASCII(switches::kUseGL);
@@ -491,15 +518,8 @@ void GpuDataManagerImplPrivate::UpdateGpuPreferences(
void GpuDataManagerImplPrivate::DisableHardwareAcceleration() {
card_disabled_ = true;
- bool gpu_process_blocked = true;
-#if BUILDFLAG(ENABLE_SWIFTSHADER)
- if (!swiftshader_blocked_ &&
- !base::CommandLine::ForCurrentProcess()->HasSwitch(
- switches::kDisableSoftwareRasterizer))
- gpu_process_blocked = false;
-#endif
- if (gpu_process_blocked)
- OnGpuProcessBlocked();
+ if (!SwiftShaderAllowed())
+ OnGpuBlocked();
}
bool GpuDataManagerImplPrivate::HardwareAccelerationEnabled() const {
@@ -508,12 +528,21 @@ bool GpuDataManagerImplPrivate::HardwareAccelerationEnabled() const {
void GpuDataManagerImplPrivate::BlockSwiftShader() {
swiftshader_blocked_ = true;
- OnGpuProcessBlocked();
+ OnGpuBlocked();
+}
+
+bool GpuDataManagerImplPrivate::SwiftShaderAllowed() const {
+#if !BUILDFLAG(ENABLE_SWIFTSHADER)
+ return false;
+#else
+ return !swiftshader_blocked_ &&
+ !base::CommandLine::ForCurrentProcess()->HasSwitch(
+ switches::kDisableSoftwareRasterizer);
+#endif
}
-void GpuDataManagerImplPrivate::OnGpuProcessBlocked() {
- gpu::GpuFeatureInfo gpu_feature_info =
- gpu::ComputeGpuFeatureInfoWithNoGpuProcess();
+void GpuDataManagerImplPrivate::OnGpuBlocked() {
+ gpu::GpuFeatureInfo gpu_feature_info = gpu::ComputeGpuFeatureInfoWithNoGpu();
UpdateGpuFeatureInfo(gpu_feature_info);
// Some observers might be waiting.
@@ -652,19 +681,8 @@ bool GpuDataManagerImplPrivate::Are3DAPIsBlocked(const GURL& top_origin_url,
int render_process_id,
int render_frame_id,
ThreeDAPIType requester) {
- bool blocked = Are3DAPIsBlockedAtTime(top_origin_url, base::Time::Now()) !=
- GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_NOT_BLOCKED;
- if (blocked) {
- // Unretained is ok, because it's posted to UI thread, the thread
- // where the singleton GpuDataManagerImpl lives until the end.
- BrowserThread::PostTask(
- BrowserThread::UI, FROM_HERE,
- base::BindOnce(&GpuDataManagerImpl::Notify3DAPIBlocked,
- base::Unretained(owner_), top_origin_url,
- render_process_id, render_frame_id, requester));
- }
-
- return blocked;
+ return Are3DAPIsBlockedAtTime(top_origin_url, base::Time::Now()) !=
+ GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_NOT_BLOCKED;
}
void GpuDataManagerImplPrivate::DisableDomainBlockingFor3DAPIsForTesting() {
@@ -756,11 +774,14 @@ GpuDataManagerImplPrivate::Are3DAPIsBlockedAtTime(
// require adjusting the associated unit tests.
std::string domain = GetDomainFromURL(url);
- if (blocked_domains_.find(domain) != blocked_domains_.end()) {
- // Err on the side of caution, and assume that if a particular
- // domain shows up in the block map, it's there for a good
- // reason and don't let its presence there automatically expire.
- return GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_BLOCKED;
+ {
+ DomainBlockMap::const_iterator iter = blocked_domains_.find(domain);
+ if (iter != blocked_domains_.end()) {
+ // Err on the side of caution, and assume that if a particular
+ // domain shows up in the block map, it's there for a good
+ // reason and don't let its presence there automatically expire.
+ return GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_BLOCKED;
+ }
}
// Look at the timestamps of the recent GPU resets to see if there are
@@ -818,30 +839,21 @@ bool GpuDataManagerImplPrivate::NeedsCompleteGpuInfoCollection() const {
#endif
}
-void GpuDataManagerImplPrivate::Notify3DAPIBlocked(const GURL& top_origin_url,
- int render_process_id,
- int render_frame_id,
- ThreeDAPIType requester) {
- GpuDataManagerImpl::UnlockedSession session(owner_);
- observer_list_->Notify(FROM_HERE, &GpuDataManagerObserver::DidBlock3DAPIs,
- top_origin_url, render_process_id, render_frame_id,
- requester);
-}
-
void GpuDataManagerImplPrivate::OnGpuProcessInitFailure() {
if (!card_disabled_) {
DisableHardwareAcceleration();
return;
}
- if (!swiftshader_blocked_) {
+ if (SwiftShaderAllowed()) {
BlockSwiftShader();
return;
}
- // If GPU process fails to launch with hardware GPU, and then fails
- // to launch with SwiftShader if available, then GPU process should
- // not launch again.
- // TODO(zmo): In viz mode, we will have a GPU process no matter what.
- NOTREACHED();
+ if (!base::FeatureList::IsEnabled(features::kVizDisplayCompositor)) {
+ // When Viz display compositor is not enabled, if GPU process fails to
+ // launch with hardware GPU, and then fails to launch with SwiftShader if
+ // available, then GPU process should not launch again.
+ NOTREACHED();
+ }
}
} // namespace content
diff --git a/chromium/content/browser/gpu/gpu_data_manager_impl_private.h b/chromium/content/browser/gpu/gpu_data_manager_impl_private.h
index 9fc03cd8de7..08b4cae2f11 100644
--- a/chromium/content/browser/gpu/gpu_data_manager_impl_private.h
+++ b/chromium/content/browser/gpu/gpu_data_manager_impl_private.h
@@ -42,7 +42,9 @@ class CONTENT_EXPORT GpuDataManagerImplPrivate {
void BlacklistWebGLForTesting();
gpu::GPUInfo GetGPUInfo() const;
bool GpuAccessAllowed(std::string* reason) const;
+ bool GpuProcessStartAllowed() const;
void RequestCompleteGpuInfoIfNeeded();
+ void RequestGpuSupportedRuntimeVersion();
bool IsEssentialGpuInfoAvailable() const;
bool IsGpuFeatureInfoAvailable() const;
gpu::GpuFeatureStatus GetFeatureStatus(gpu::GpuFeatureType feature) const;
@@ -55,6 +57,7 @@ class CONTENT_EXPORT GpuDataManagerImplPrivate {
void DisableHardwareAcceleration();
bool HardwareAccelerationEnabled() const;
void BlockSwiftShader();
+ bool SwiftShaderAllowed() const;
void UpdateGpuInfo(const gpu::GPUInfo& gpu_info);
void UpdateGpuFeatureInfo(const gpu::GpuFeatureInfo& gpu_feature_info);
@@ -99,6 +102,9 @@ class CONTENT_EXPORT GpuDataManagerImplPrivate {
void OnGpuProcessInitFailure();
+ // Notify all observers whenever there is a GPU info update.
+ void NotifyGpuInfoUpdate();
+
virtual ~GpuDataManagerImplPrivate();
private:
@@ -141,11 +147,9 @@ class CONTENT_EXPORT GpuDataManagerImplPrivate {
explicit GpuDataManagerImplPrivate(GpuDataManagerImpl* owner);
- // Notify all observers whenever there is a GPU info update.
- void NotifyGpuInfoUpdate();
-
- // Called when gpu process becomes blocked.
- void OnGpuProcessBlocked();
+ // Called when GPU access (hardware acceleration and swiftshader) becomes
+ // blocked.
+ void OnGpuBlocked();
// Helper to extract the domain from a given URL.
std::string GetDomainFromURL(const GURL& url) const;
diff --git a/chromium/content/browser/gpu/gpu_feature_checker_impl.cc b/chromium/content/browser/gpu/gpu_feature_checker_impl.cc
index 271ef924eb2..4a14d2c41ea 100644
--- a/chromium/content/browser/gpu/gpu_feature_checker_impl.cc
+++ b/chromium/content/browser/gpu/gpu_feature_checker_impl.cc
@@ -15,7 +15,7 @@ namespace content {
scoped_refptr<GpuFeatureChecker> GpuFeatureChecker::Create(
gpu::GpuFeatureType feature,
FeatureAvailableCallback callback) {
- return new GpuFeatureCheckerImpl(feature, callback);
+ return new GpuFeatureCheckerImpl(feature, std::move(callback));
}
GpuFeatureCheckerImpl::GpuFeatureCheckerImpl(gpu::GpuFeatureType feature,
diff --git a/chromium/content/browser/gpu/gpu_internals_ui.cc b/chromium/content/browser/gpu/gpu_internals_ui.cc
index 67dc866d498..210eb5fe2da 100644
--- a/chromium/content/browser/gpu/gpu_internals_ui.cc
+++ b/chromium/content/browser/gpu/gpu_internals_ui.cc
@@ -16,7 +16,6 @@
#include "base/environment.h"
#include "base/i18n/time_formatting.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringize_macros.h"
@@ -40,6 +39,7 @@
#include "gpu/config/gpu_feature_type.h"
#include "gpu/config/gpu_info.h"
#include "gpu/config/gpu_lists_version.h"
+#include "gpu/ipc/common/gpu_memory_buffer_support.h"
#include "gpu/ipc/host/gpu_memory_buffer_support.h"
#include "skia/ext/skia_commit_hash.h"
#include "third_party/angle/src/common/version.h"
@@ -153,8 +153,6 @@ std::unique_ptr<base::DictionaryValue> GpuInfoAsDictionaryValue() {
basic_info->Append(NewDescriptionValuePair(
"Optimus", std::make_unique<base::Value>(gpu_info.optimus)));
basic_info->Append(NewDescriptionValuePair(
- "Optimus", std::make_unique<base::Value>(gpu_info.optimus)));
- basic_info->Append(NewDescriptionValuePair(
"AMD switchable",
std::make_unique<base::Value>(gpu_info.amd_switchable)));
#if defined(OS_WIN)
@@ -177,6 +175,13 @@ std::unique_ptr<base::DictionaryValue> GpuInfoAsDictionaryValue() {
basic_info->Append(
NewDescriptionValuePair(description_string, size_string));
}
+
+ basic_info->Append(NewDescriptionValuePair(
+ "DX12", std::make_unique<base::Value>(gpu_info.supports_dx12)));
+
+ basic_info->Append(NewDescriptionValuePair(
+ "Vulkan", std::make_unique<base::Value>(gpu_info.supports_vulkan)));
+
#endif
std::string disabled_extensions;
@@ -307,8 +312,10 @@ std::unique_ptr<base::ListValue> CompositorInfo() {
std::unique_ptr<base::ListValue> GpuMemoryBufferInfo() {
auto gpu_memory_buffer_info = std::make_unique<base::ListValue>();
+ gpu::GpuMemoryBufferSupport gpu_memory_buffer_support;
+
const auto native_configurations =
- gpu::GetNativeGpuMemoryBufferConfigurations();
+ gpu::GetNativeGpuMemoryBufferConfigurations(&gpu_memory_buffer_support);
for (size_t format = 0;
format < static_cast<size_t>(gfx::BufferFormat::LAST) + 1; format++) {
std::string native_usage_support;
@@ -495,12 +502,13 @@ GpuMessageHandler::~GpuMessageHandler() {
void GpuMessageHandler::RegisterMessages() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
- web_ui()->RegisterMessageCallback("browserBridgeInitialized",
- base::Bind(&GpuMessageHandler::OnBrowserBridgeInitialized,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("callAsync",
- base::Bind(&GpuMessageHandler::OnCallAsync,
- base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "browserBridgeInitialized",
+ base::BindRepeating(&GpuMessageHandler::OnBrowserBridgeInitialized,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "callAsync", base::BindRepeating(&GpuMessageHandler::OnCallAsync,
+ base::Unretained(this)));
}
void GpuMessageHandler::OnCallAsync(const base::ListValue* args) {
diff --git a/chromium/content/browser/gpu/gpu_ipc_browsertests.cc b/chromium/content/browser/gpu/gpu_ipc_browsertests.cc
index 789e7094380..31f2ab76871 100644
--- a/chromium/content/browser/gpu/gpu_ipc_browsertests.cc
+++ b/chromium/content/browser/gpu/gpu_ipc_browsertests.cc
@@ -3,7 +3,6 @@
// found in the LICENSE file.
#include "base/command_line.h"
-#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "build/build_config.h"
#include "components/viz/common/gpu/context_provider.h"
@@ -15,6 +14,7 @@
#include "content/public/browser/gpu_utils.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/content_browser_test.h"
+#include "content/test/gpu_browsertest_helpers.h"
#include "gpu/ipc/client/command_buffer_proxy_impl.h"
#include "gpu/ipc/client/gpu_channel_host.h"
#include "services/ui/public/cpp/gpu/context_provider_command_buffer.h"
@@ -27,50 +27,6 @@
namespace {
-scoped_refptr<ui::ContextProviderCommandBuffer> CreateContext(
- scoped_refptr<gpu::GpuChannelHost> gpu_channel_host) {
- gpu::GpuChannelEstablishFactory* factory =
- content::BrowserMainLoop::GetInstance()->gpu_channel_establish_factory();
- // This is for an offscreen context, so the default framebuffer doesn't need
- // any alpha, depth, stencil, antialiasing.
- gpu::ContextCreationAttribs attributes;
- attributes.alpha_size = -1;
- attributes.depth_size = 0;
- attributes.stencil_size = 0;
- attributes.samples = 0;
- attributes.sample_buffers = 0;
- attributes.bind_generates_resource = false;
- constexpr bool automatic_flushes = false;
- constexpr bool support_locking = false;
- return base::MakeRefCounted<ui::ContextProviderCommandBuffer>(
- std::move(gpu_channel_host), factory->GetGpuMemoryBufferManager(),
- content::kGpuStreamIdDefault, content::kGpuStreamPriorityDefault,
- gpu::kNullSurfaceHandle, GURL(), automatic_flushes, support_locking,
- gpu::SharedMemoryLimits(), attributes, nullptr,
- ui::command_buffer_metrics::OFFSCREEN_CONTEXT_FOR_TESTING);
-}
-
-void OnEstablishedGpuChannel(
- const base::Closure& quit_closure,
- scoped_refptr<gpu::GpuChannelHost>* retvalue,
- scoped_refptr<gpu::GpuChannelHost> established_host) {
- if (retvalue)
- *retvalue = std::move(established_host);
- quit_closure.Run();
-}
-
-scoped_refptr<gpu::GpuChannelHost> EstablishGpuChannelSyncRunLoop() {
- gpu::GpuChannelEstablishFactory* factory =
- content::BrowserMainLoop::GetInstance()->gpu_channel_establish_factory();
- CHECK(factory);
- base::RunLoop run_loop;
- scoped_refptr<gpu::GpuChannelHost> gpu_channel_host;
- factory->EstablishGpuChannel(base::BindOnce(
- &OnEstablishedGpuChannel, run_loop.QuitClosure(), &gpu_channel_host));
- run_loop.Run();
- return gpu_channel_host;
-}
-
// RunLoop implementation that runs until it observes OnContextLost().
class ContextLostRunLoop : public viz::ContextLostObserver {
public:
@@ -101,10 +57,11 @@ class ContextTestBase : public content::ContentBrowserTest {
return;
scoped_refptr<gpu::GpuChannelHost> gpu_channel_host =
- EstablishGpuChannelSyncRunLoop();
+ content::GpuBrowsertestEstablishGpuChannelSyncRunLoop();
CHECK(gpu_channel_host);
- provider_ = CreateContext(std::move(gpu_channel_host));
+ provider_ =
+ content::GpuBrowsertestCreateContext(std::move(gpu_channel_host));
auto result = provider_->BindToCurrentThread();
CHECK_EQ(result, gpu::ContextResult::kSuccess);
gl_ = provider_->ContextGL();
@@ -131,6 +88,7 @@ class ContextTestBase : public content::ContentBrowserTest {
// Include the shared tests.
#define CONTEXT_TEST_F IN_PROC_BROWSER_TEST_F
+#include "content/public/browser/browser_thread.h"
#include "gpu/ipc/client/gpu_context_tests.h"
namespace content {
@@ -179,7 +137,7 @@ class BrowserGpuChannelHostFactoryTest : public ContentBrowserTest {
}
void EstablishAndWait() {
- gpu_channel_host_ = EstablishGpuChannelSyncRunLoop();
+ gpu_channel_host_ = content::GpuBrowsertestEstablishGpuChannelSyncRunLoop();
}
gpu::GpuChannelHost* GetGpuChannel() { return gpu_channel_host_.get(); }
@@ -274,7 +232,7 @@ IN_PROC_BROWSER_TEST_F(BrowserGpuChannelHostFactoryTest,
// Step 2: verify that holding onto the provider's GrContext will
// retain the host after provider is destroyed.
scoped_refptr<ui::ContextProviderCommandBuffer> provider =
- CreateContext(GetGpuChannel());
+ content::GpuBrowsertestCreateContext(GetGpuChannel());
ASSERT_EQ(provider->BindToCurrentThread(), gpu::ContextResult::kSuccess);
sk_sp<GrContext> gr_context = sk_ref_sp(provider->GrContext());
@@ -321,7 +279,7 @@ IN_PROC_BROWSER_TEST_F(BrowserGpuChannelHostFactoryTest,
scoped_refptr<gpu::GpuChannelHost> host = GetGpuChannel();
scoped_refptr<ui::ContextProviderCommandBuffer> provider =
- CreateContext(GetGpuChannel());
+ content::GpuBrowsertestCreateContext(GetGpuChannel());
ContextLostRunLoop run_loop(provider.get());
ASSERT_EQ(provider->BindToCurrentThread(), gpu::ContextResult::kSuccess);
GpuProcessHost::CallOnIO(GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
diff --git a/chromium/content/browser/gpu/gpu_process_host.cc b/chromium/content/browser/gpu/gpu_process_host.cc
index 82b4c0148a6..c68ef4f4382 100644
--- a/chromium/content/browser/gpu/gpu_process_host.cc
+++ b/chromium/content/browser/gpu/gpu_process_host.cc
@@ -15,9 +15,9 @@
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/command_line.h"
+#include "base/feature_list.h"
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/field_trial.h"
@@ -30,6 +30,7 @@
#include "build/build_config.h"
#include "components/discardable_memory/service/discardable_shared_memory_manager.h"
#include "components/tracing/common/tracing_switches.h"
+#include "components/viz/common/features.h"
#include "components/viz/common/switches.h"
#include "content/browser/browser_child_process_host_impl.h"
#include "content/browser/browser_main_loop.h"
@@ -61,7 +62,7 @@
#include "gpu/config/gpu_driver_bug_workaround_type.h"
#include "gpu/ipc/host/shader_disk_cache.h"
#include "media/base/media_switches.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "mojo/edk/embedder/embedder.h"
#include "services/service_manager/public/cpp/binder_registry.h"
#include "services/service_manager/public/cpp/connector.h"
@@ -106,12 +107,13 @@
namespace content {
-bool GpuProcessHost::gpu_enabled_ = true;
-bool GpuProcessHost::hardware_gpu_enabled_ = true;
base::subtle::Atomic32 GpuProcessHost::gpu_crash_count_ = 0;
int GpuProcessHost::gpu_recent_crash_count_ = 0;
bool GpuProcessHost::crashed_before_ = false;
int GpuProcessHost::swiftshader_crash_count_ = 0;
+int GpuProcessHost::swiftshader_recent_crash_count_ = 0;
+int GpuProcessHost::display_compositor_crash_count_ = 0;
+int GpuProcessHost::display_compositor_recent_crash_count_ = 0;
namespace {
@@ -142,14 +144,14 @@ static const char* const kSwitchNames[] = {
switches::kEnableHeapProfiling,
switches::kEnableLogging,
switches::kEnableOOPRasterization,
+ switches::kEnableVizDevTools,
switches::kHeadless,
switches::kLoggingLevel,
switches::kEnableLowEndDeviceMode,
switches::kDisableLowEndDeviceMode,
switches::kNoSandbox,
+ switches::kRunAllCompositorStagesBeforeDraw,
switches::kTestGLLib,
- switches::kTraceConfigFile,
- switches::kTraceStartup,
switches::kTraceToConsole,
switches::kUseFakeJpegDecodeAccelerator,
switches::kUseGpuInTests,
@@ -461,8 +463,8 @@ GpuProcessHost* GpuProcessHost::Get(GpuProcessKind kind, bool force_create) {
// Don't grant further access to GPU if it is not allowed.
GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
DCHECK(gpu_data_manager);
- if (!gpu_data_manager->GpuAccessAllowed(nullptr)) {
- DLOG(ERROR) << "!GpuDataManagerImpl::GpuAccessAllowed()";
+ if (!gpu_data_manager->GpuProcessStartAllowed()) {
+ DLOG(ERROR) << "!GpuDataManagerImpl::GpuProcessStartAllowed()";
return nullptr;
}
@@ -552,11 +554,29 @@ int GpuProcessHost::GetGpuCrashCount() {
return static_cast<int>(base::subtle::NoBarrier_Load(&gpu_crash_count_));
}
+// static
+void GpuProcessHost::IncrementCrashCount(int* crash_count) {
+ // Last time the process crashed.
+ static base::Time last_crash_time;
+
+ // Allow about 1 crash per hour to be removed from the crash count, so very
+ // occasional crashes won't eventually add up and prevent the process from
+ // launching.
+ base::Time current_time = base::Time::Now();
+ if (crashed_before_) {
+ int hours_different = (current_time - last_crash_time).InHours();
+ *crash_count = std::max(0, *crash_count - hours_different);
+ }
+ ++(*crash_count);
+
+ crashed_before_ = true;
+ last_crash_time = current_time;
+}
+
GpuProcessHost::GpuProcessHost(int host_id, GpuProcessKind kind)
: host_id_(host_id),
valid_(true),
in_process_(false),
- swiftshader_rendering_(false),
kind_(kind),
process_launched_(false),
status_(UNKNOWN),
@@ -864,11 +884,11 @@ void GpuProcessHost::CreateGpuMemoryBuffer(
gfx::BufferUsage usage,
int client_id,
gpu::SurfaceHandle surface_handle,
- const CreateGpuMemoryBufferCallback& callback) {
+ CreateGpuMemoryBufferCallback callback) {
TRACE_EVENT0("gpu", "GpuProcessHost::CreateGpuMemoryBuffer");
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
- create_gpu_memory_buffer_requests_.push(callback);
+ create_gpu_memory_buffer_requests_.push(std::move(callback));
gpu_service_ptr_->CreateGpuMemoryBuffer(
id, size, format, usage, client_id, surface_handle,
base::BindOnce(&GpuProcessHost::OnGpuMemoryBufferCreated,
@@ -884,8 +904,7 @@ void GpuProcessHost::DestroyGpuMemoryBuffer(gfx::GpuMemoryBufferId id,
void GpuProcessHost::ConnectFrameSinkManager(
viz::mojom::FrameSinkManagerRequest request,
- viz::mojom::FrameSinkManagerClientPtrInfo client,
- viz::mojom::CompositingModeWatcherPtrInfo mode_watcher) {
+ viz::mojom::FrameSinkManagerClientPtrInfo client) {
TRACE_EVENT0("gpu", "GpuProcessHost::ConnectFrameSinkManager");
viz::mojom::FrameSinkManagerParamsPtr params =
viz::mojom::FrameSinkManagerParams::New();
@@ -897,7 +916,6 @@ void GpuProcessHost::ConnectFrameSinkManager(
activation_deadline_in_frames.value_or(0u);
params->frame_sink_manager = std::move(request);
params->frame_sink_manager_client = std::move(client);
- params->compositing_mode_watcher = std::move(mode_watcher);
gpu_main_ptr_->CreateFrameSinkManager(std::move(params));
}
@@ -960,9 +978,9 @@ void GpuProcessHost::OnGpuMemoryBufferCreated(
TRACE_EVENT0("gpu", "GpuProcessHost::OnGpuMemoryBufferCreated");
DCHECK(!create_gpu_memory_buffer_requests_.empty());
- auto callback = create_gpu_memory_buffer_requests_.front();
+ auto callback = std::move(create_gpu_memory_buffer_requests_.front());
create_gpu_memory_buffer_requests_.pop();
- callback.Run(handle, BufferCreationStatus::SUCCESS);
+ std::move(callback).Run(handle, BufferCreationStatus::SUCCESS);
}
#if defined(OS_ANDROID)
@@ -1056,7 +1074,12 @@ void GpuProcessHost::DidCreateOffscreenContext(const GURL& url) {
}
void GpuProcessHost::DidDestroyOffscreenContext(const GURL& url) {
- urls_with_live_offscreen_contexts_.erase(url);
+ // We only want to remove *one* of the entries in the multiset for
+ // this particular URL, so can't use the erase method taking a key.
+ auto candidate = urls_with_live_offscreen_contexts_.find(url);
+ if (candidate != urls_with_live_offscreen_contexts_.end()) {
+ urls_with_live_offscreen_contexts_.erase(candidate);
+ }
}
void GpuProcessHost::DidDestroyChannel(int32_t client_id) {
@@ -1203,6 +1226,7 @@ bool GpuProcessHost::LaunchGpuProcess() {
cmd_line->AppendSwitchASCII(switches::kProcessType, switches::kGpuProcess);
BrowserChildProcessHostImpl::CopyFeatureAndFieldTrialFlags(cmd_line.get());
+ BrowserChildProcessHostImpl::CopyTraceStartupFlags(cmd_line.get());
#if defined(OS_WIN)
cmd_line->AppendArg(switches::kPrefetchArgumentGpu);
@@ -1230,20 +1254,12 @@ bool GpuProcessHost::LaunchGpuProcess() {
cmd_line.get(), process_->GetData().id);
GpuDataManagerImpl::GetInstance()->AppendGpuCommandLine(cmd_line.get());
- if (cmd_line->HasSwitch(switches::kUseGL)) {
- swiftshader_rendering_ = (cmd_line->GetSwitchValueASCII(switches::kUseGL) ==
- gl::kGLImplementationSwiftShaderForWebGLName);
- }
-
- bool current_gpu_type_enabled =
- swiftshader_rendering_ ? gpu_enabled_ : hardware_gpu_enabled_;
- if (!current_gpu_type_enabled) {
- SendOutstandingReplies(EstablishChannelStatus::GPU_ACCESS_DENIED);
- return false;
- }
+ bool swiftshader_rendering =
+ (cmd_line->GetSwitchValueASCII(switches::kUseGL) ==
+ gl::kGLImplementationSwiftShaderForWebGLName);
UMA_HISTOGRAM_BOOLEAN("GPU.GPUProcessSoftwareRendering",
- swiftshader_rendering_);
+ swiftshader_rendering);
// If specified, prepend a launcher program to the command line.
if (!gpu_launcher.empty())
@@ -1272,15 +1288,15 @@ void GpuProcessHost::SendOutstandingReplies(
while (!channel_requests_.empty()) {
auto callback = channel_requests_.front();
channel_requests_.pop();
- callback.Run(mojo::ScopedMessagePipeHandle(), gpu::GPUInfo(),
- gpu::GpuFeatureInfo(), failure_status);
+ std::move(callback).Run(mojo::ScopedMessagePipeHandle(), gpu::GPUInfo(),
+ gpu::GpuFeatureInfo(), failure_status);
}
while (!create_gpu_memory_buffer_requests_.empty()) {
- auto callback = create_gpu_memory_buffer_requests_.front();
+ auto callback = std::move(create_gpu_memory_buffer_requests_.front());
create_gpu_memory_buffer_requests_.pop();
- callback.Run(gfx::GpuMemoryBufferHandle(),
- BufferCreationStatus::GPU_HOST_INVALID);
+ std::move(callback).Run(gfx::GpuMemoryBufferHandle(),
+ BufferCreationStatus::GPU_HOST_INVALID);
}
if (!send_destroying_video_surface_done_cb_.is_null())
@@ -1315,9 +1331,6 @@ void GpuProcessHost::RecordProcessCrash() {
const int kGpuMaxCrashCount = 6;
#endif
- // Last time the GPU process crashed.
- static base::Time last_gpu_crash_time;
-
bool disable_crash_limit = base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableGpuProcessCrashLimit);
@@ -1325,19 +1338,7 @@ void GpuProcessHost::RecordProcessCrash() {
// was intended for actual rendering (and not just checking caps or other
// options).
if (process_launched_ && kind_ == GPU_PROCESS_KIND_SANDBOXED) {
- if (swiftshader_rendering_) {
- UMA_HISTOGRAM_EXACT_LINEAR(
- "GPU.SwiftShaderLifetimeEvents",
- DIED_FIRST_TIME + swiftshader_crash_count_,
- static_cast<int>(GPU_PROCESS_LIFETIME_EVENT_MAX));
-
- if (++swiftshader_crash_count_ >= kGpuMaxCrashCount &&
- !disable_crash_limit) {
- // SwiftShader is too unstable to use. Disable it for current session.
- gpu_enabled_ = false;
- GpuDataManagerImpl::GetInstance()->BlockSwiftShader();
- }
- } else {
+ if (GpuDataManagerImpl::GetInstance()->HardwareAccelerationEnabled()) {
int count = static_cast<int>(
base::subtle::NoBarrier_AtomicIncrement(&gpu_crash_count_, 1));
UMA_HISTOGRAM_EXACT_LINEAR(
@@ -1345,20 +1346,7 @@ void GpuProcessHost::RecordProcessCrash() {
std::min(DIED_FIRST_TIME + count, GPU_PROCESS_LIFETIME_EVENT_MAX - 1),
static_cast<int>(GPU_PROCESS_LIFETIME_EVENT_MAX));
- // Allow about 1 GPU crash per hour to be removed from the crash count,
- // so very occasional crashes won't eventually add up and prevent the
- // GPU process from launching.
- ++gpu_recent_crash_count_;
- base::Time current_time = base::Time::Now();
- if (crashed_before_) {
- int hours_different = (current_time - last_gpu_crash_time).InHours();
- gpu_recent_crash_count_ =
- std::max(0, gpu_recent_crash_count_ - hours_different);
- }
-
- crashed_before_ = true;
- last_gpu_crash_time = current_time;
-
+ IncrementCrashCount(&gpu_recent_crash_count_);
if ((gpu_recent_crash_count_ >= kGpuMaxCrashCount ||
status_ == FAILURE) &&
!disable_crash_limit) {
@@ -1374,10 +1362,36 @@ void GpuProcessHost::RecordProcessCrash() {
#else
// The GPU process is too unstable to use. Disable it for current
// session.
- hardware_gpu_enabled_ = false;
GpuDataManagerImpl::GetInstance()->DisableHardwareAcceleration();
#endif
}
+ } else if (GpuDataManagerImpl::GetInstance()->SwiftShaderAllowed()) {
+ UMA_HISTOGRAM_EXACT_LINEAR(
+ "GPU.SwiftShaderLifetimeEvents",
+ DIED_FIRST_TIME + swiftshader_crash_count_,
+ static_cast<int>(GPU_PROCESS_LIFETIME_EVENT_MAX));
+ ++swiftshader_crash_count_;
+
+ IncrementCrashCount(&swiftshader_recent_crash_count_);
+ if (swiftshader_recent_crash_count_ >= kGpuMaxCrashCount &&
+ !disable_crash_limit) {
+ // SwiftShader is too unstable to use. Disable it for current session.
+ GpuDataManagerImpl::GetInstance()->BlockSwiftShader();
+ }
+ } else {
+ UMA_HISTOGRAM_EXACT_LINEAR(
+ "GPU.DisplayCompositorLifetimeEvents",
+ DIED_FIRST_TIME + display_compositor_crash_count_,
+ static_cast<int>(GPU_PROCESS_LIFETIME_EVENT_MAX));
+ ++display_compositor_crash_count_;
+
+ IncrementCrashCount(&display_compositor_recent_crash_count_);
+ if (display_compositor_recent_crash_count_ >= kGpuMaxCrashCount &&
+ !disable_crash_limit) {
+ // Viz display compositor is too unstable. Crash chrome to reset
+ // everything.
+ LOG(FATAL) << "Unable to start viz process, giving up.";
+ }
}
}
}
diff --git a/chromium/content/browser/gpu/gpu_process_host.h b/chromium/content/browser/gpu/gpu_process_host.h
index ced7049a1d2..51b57b61eb4 100644
--- a/chromium/content/browser/gpu/gpu_process_host.h
+++ b/chromium/content/browser/gpu/gpu_process_host.h
@@ -80,8 +80,8 @@ class GpuProcessHost : public BrowserChildProcessHostDelegate,
SUCCESS,
};
using CreateGpuMemoryBufferCallback =
- base::Callback<void(const gfx::GpuMemoryBufferHandle& handle,
- BufferCreationStatus status)>;
+ base::OnceCallback<void(const gfx::GpuMemoryBufferHandle& handle,
+ BufferCreationStatus status)>;
using RequestGPUInfoCallback = base::Callback<void(const gpu::GPUInfo&)>;
using RequestHDRStatusCallback = base::Callback<void(bool)>;
@@ -138,7 +138,7 @@ class GpuProcessHost : public BrowserChildProcessHostDelegate,
gfx::BufferUsage usage,
int client_id,
gpu::SurfaceHandle surface_handle,
- const CreateGpuMemoryBufferCallback& callback);
+ CreateGpuMemoryBufferCallback callback);
// Tells the GPU process to destroy GPU memory buffer.
void DestroyGpuMemoryBuffer(gfx::GpuMemoryBufferId id,
@@ -150,8 +150,7 @@ class GpuProcessHost : public BrowserChildProcessHostDelegate,
// browser must submit CompositorFrames over IPC.
void ConnectFrameSinkManager(
viz::mojom::FrameSinkManagerRequest request,
- viz::mojom::FrameSinkManagerClientPtrInfo client,
- viz::mojom::CompositingModeWatcherPtrInfo mode_watcher);
+ viz::mojom::FrameSinkManagerClientPtrInfo client);
void RequestGPUInfo(RequestGPUInfoCallback request_cb);
void RequestHDRStatus(RequestHDRStatusCallback request_cb);
@@ -183,6 +182,10 @@ class GpuProcessHost : public BrowserChildProcessHostDelegate,
static bool ValidateHost(GpuProcessHost* host);
+ // Increments the given crash count. Also, for each hour passed since the
+ // previous crash, removes an old crash from the count.
+ static void IncrementCrashCount(int* crash_count);
+
GpuProcessHost(int host_id, GpuProcessKind kind);
~GpuProcessHost() override;
@@ -270,7 +273,6 @@ class GpuProcessHost : public BrowserChildProcessHostDelegate,
// of a separate GPU process.
bool in_process_;
- bool swiftshader_rendering_;
GpuProcessKind kind_;
// Whether we actually launched a GPU process.
@@ -281,16 +283,13 @@ class GpuProcessHost : public BrowserChildProcessHostDelegate,
// Time Init started. Used to log total GPU process startup time to UMA.
base::TimeTicks init_start_time_;
- // Master switch for enabling/disabling GPU acceleration for the current
- // browser session.
- static bool gpu_enabled_;
-
- static bool hardware_gpu_enabled_;
-
static base::subtle::Atomic32 gpu_crash_count_;
static int gpu_recent_crash_count_;
static bool crashed_before_;
static int swiftshader_crash_count_;
+ static int swiftshader_recent_crash_count_;
+ static int display_compositor_crash_count_;
+ static int display_compositor_recent_crash_count_;
// Here the bottom-up destruction order matters:
// The GPU thread depends on its host so stop the host last.
diff --git a/chromium/content/browser/gpu/in_process_gpu_thread_browsertests.cc b/chromium/content/browser/gpu/in_process_gpu_thread_browsertests.cc
index 029288bd105..22cc546f4c4 100644
--- a/chromium/content/browser/gpu/in_process_gpu_thread_browsertests.cc
+++ b/chromium/content/browser/gpu/in_process_gpu_thread_browsertests.cc
@@ -7,6 +7,7 @@
#include "content/browser/browser_main_loop.h"
#include "content/browser/gpu/gpu_process_host.h"
#include "content/gpu/in_process_gpu_thread.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/content_browser_test.h"
diff --git a/chromium/content/browser/histogram_internals_url_loader.cc b/chromium/content/browser/histogram_internals_url_loader.cc
index fa8e3a095ca..63cbaa16931 100644
--- a/chromium/content/browser/histogram_internals_url_loader.cc
+++ b/chromium/content/browser/histogram_internals_url_loader.cc
@@ -7,7 +7,7 @@
#include "base/metrics/histogram_macros.h"
#include "base/metrics/statistics_recorder.h"
#include "content/browser/histogram_internals_request_job.h"
-#include "mojo/common/data_pipe_utils.h"
+#include "mojo/public/cpp/system/data_pipe_utils.h"
namespace content {
@@ -19,12 +19,12 @@ void StartHistogramInternalsURLLoader(
network::ResourceResponseHead resource_response;
resource_response.headers = headers;
resource_response.mime_type = "text/html";
- client->OnReceiveResponse(resource_response, base::nullopt, nullptr);
+ client->OnReceiveResponse(resource_response, nullptr);
base::StatisticsRecorder::ImportProvidedHistograms();
std::string data = HistogramInternalsRequestJob::GenerateHTML(request.url);
mojo::DataPipe data_pipe(data.size());
- CHECK(mojo::common::BlockingCopyFromString(data, data_pipe.producer_handle));
+ CHECK(mojo::BlockingCopyFromString(data, data_pipe.producer_handle));
client->OnStartLoadingResponseBody(std::move(data_pipe.consumer_handle));
network::URLLoaderCompletionStatus status(net::OK);
diff --git a/chromium/content/browser/histogram_synchronizer.cc b/chromium/content/browser/histogram_synchronizer.cc
index 76d0bf9806a..796c34fbe21 100644
--- a/chromium/content/browser/histogram_synchronizer.cc
+++ b/chromium/content/browser/histogram_synchronizer.cc
@@ -242,7 +242,7 @@ void HistogramSynchronizer::RegisterAndNotifyAllProcesses(
base::Unretained(this),
sequence_number);
- RequestContext::Register(callback, sequence_number);
+ RequestContext::Register(std::move(callback), sequence_number);
// Get histogram data from renderer and browser child processes.
HistogramController::GetInstance()->GetHistogramData(sequence_number);
@@ -299,7 +299,7 @@ void HistogramSynchronizer::SetTaskRunnerAndCallback(
async_sequence_number_ = kNeverUsableSequenceNumber;
}
// Just in case there was a task pending....
- InternalPostTask(std::move(old_task_runner), old_callback);
+ InternalPostTask(std::move(old_task_runner), std::move(old_callback));
}
void HistogramSynchronizer::ForceHistogramSynchronizationDoneCallback(
@@ -314,7 +314,7 @@ void HistogramSynchronizer::ForceHistogramSynchronizationDoneCallback(
task_runner = std::move(callback_task_runner_);
callback_.Reset();
}
- InternalPostTask(std::move(task_runner), callback);
+ InternalPostTask(std::move(task_runner), std::move(callback));
}
void HistogramSynchronizer::InternalPostTask(
diff --git a/chromium/content/browser/host_zoom_level_context.cc b/chromium/content/browser/host_zoom_level_context.cc
index ee758b8d0fc..bc5e28d3c59 100644
--- a/chromium/content/browser/host_zoom_level_context.cc
+++ b/chromium/content/browser/host_zoom_level_context.cc
@@ -23,7 +23,7 @@ HostZoomLevelContext::HostZoomLevelContext(
HostZoomLevelContext::~HostZoomLevelContext() {}
void HostZoomLevelContext::DeleteOnCorrectThread() const {
- if (BrowserThread::IsMessageLoopValid(BrowserThread::UI) &&
+ if (BrowserThread::IsThreadInitialized(BrowserThread::UI) &&
!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
BrowserThread::DeleteSoon(BrowserThread::UI, FROM_HERE, this);
return;
diff --git a/chromium/content/browser/host_zoom_map_impl_unittest.cc b/chromium/content/browser/host_zoom_map_impl_unittest.cc
index 6681b36e973..c6676920158 100644
--- a/chromium/content/browser/host_zoom_map_impl_unittest.cc
+++ b/chromium/content/browser/host_zoom_map_impl_unittest.cc
@@ -7,7 +7,6 @@
#include <stddef.h>
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop/message_loop.h"
#include "base/test/simple_test_clock.h"
@@ -134,11 +133,19 @@ TEST_F(HostZoomMapTest, ClearZoomLevels) {
host_zoom_map.SetZoomLevelForHost("zoomzoom.com", 3.5);
test_clock.SetNow(now - base::TimeDelta::FromHours(1));
host_zoom_map.SetZoomLevelForHost("zoom.com", 1.5);
- EXPECT_EQ(2u, host_zoom_map.GetAllZoomLevels().size());
+ test_clock.SetNow(now - base::TimeDelta::FromDays(31));
+ host_zoom_map.SetZoomLevelForHost("zoom2.com", 2.5);
+ EXPECT_EQ(3u, host_zoom_map.GetAllZoomLevels().size());
host_zoom_map.ClearZoomLevels(now - base::TimeDelta::FromHours(2),
base::Time::Max());
- EXPECT_EQ(1u, host_zoom_map.GetAllZoomLevels().size());
+ ASSERT_EQ(2u, host_zoom_map.GetAllZoomLevels().size());
+ EXPECT_EQ("zoom2.com", host_zoom_map.GetAllZoomLevels()[0].host);
+ EXPECT_EQ("zoomzoom.com", host_zoom_map.GetAllZoomLevels()[1].host);
+
+ host_zoom_map.ClearZoomLevels(base::Time(),
+ now - base::TimeDelta::FromDays(30));
+ ASSERT_EQ(1u, host_zoom_map.GetAllZoomLevels().size());
EXPECT_EQ("zoomzoom.com", host_zoom_map.GetAllZoomLevels()[0].host);
host_zoom_map.ClearZoomLevels(base::Time(), base::Time::Max());
diff --git a/chromium/content/browser/host_zoom_map_observer.cc b/chromium/content/browser/host_zoom_map_observer.cc
index caf5f606079..84203456779 100644
--- a/chromium/content/browser/host_zoom_map_observer.cc
+++ b/chromium/content/browser/host_zoom_map_observer.cc
@@ -9,7 +9,7 @@
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/storage_partition.h"
-#include "third_party/WebKit/public/common/associated_interfaces/associated_interface_provider.h"
+#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
namespace content {
diff --git a/chromium/content/browser/hyphenation/DEPS b/chromium/content/browser/hyphenation/DEPS
index 1f557f4a15b..9b7ca8ca456 100644
--- a/chromium/content/browser/hyphenation/DEPS
+++ b/chromium/content/browser/hyphenation/DEPS
@@ -1,5 +1,5 @@
include_rules = [
"-content",
"+content/browser/hyphenation",
- "+third_party/WebKit/public/platform/modules/hyphenation/hyphenation.mojom.h",
+ "+third_party/blink/public/platform/modules/hyphenation/hyphenation.mojom.h",
]
diff --git a/chromium/content/browser/hyphenation/hyphenation_impl.cc b/chromium/content/browser/hyphenation/hyphenation_impl.cc
index a943bf4297a..ab21104f132 100644
--- a/chromium/content/browser/hyphenation/hyphenation_impl.cc
+++ b/chromium/content/browser/hyphenation/hyphenation_impl.cc
@@ -10,7 +10,6 @@
#include "base/files/file.h"
#include "base/files/file_path.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
diff --git a/chromium/content/browser/hyphenation/hyphenation_impl.h b/chromium/content/browser/hyphenation/hyphenation_impl.h
index 878f0c24dda..05014dd9f85 100644
--- a/chromium/content/browser/hyphenation/hyphenation_impl.h
+++ b/chromium/content/browser/hyphenation/hyphenation_impl.h
@@ -7,7 +7,7 @@
#include "base/macros.h"
#include "mojo/public/cpp/bindings/interface_request.h"
-#include "third_party/WebKit/public/platform/modules/hyphenation/hyphenation.mojom.h"
+#include "third_party/blink/public/platform/modules/hyphenation/hyphenation.mojom.h"
namespace hyphenation {
diff --git a/chromium/content/browser/image_capture/image_capture_impl.cc b/chromium/content/browser/image_capture/image_capture_impl.cc
index 0c6afe43c09..5198e94e456 100644
--- a/chromium/content/browser/image_capture/image_capture_impl.cc
+++ b/chromium/content/browser/image_capture/image_capture_impl.cc
@@ -7,7 +7,6 @@
#include <utility>
#include "base/bind_helpers.h"
-#include "base/memory/ptr_util.h"
#include "content/browser/browser_main_loop.h"
#include "content/browser/renderer_host/media/media_stream_manager.h"
#include "content/browser/renderer_host/media/video_capture_manager.h"
@@ -15,7 +14,7 @@
#include "content/public/common/content_features.h"
#include "content/public/common/media_stream_request.h"
#include "media/base/bind_to_current_loop.h"
-#include "media/capture/mojo/image_capture_types.h"
+#include "media/capture/mojom/image_capture_types.h"
#include "media/capture/video/video_capture_device.h"
#include "mojo/public/cpp/bindings/callback_helpers.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
@@ -29,9 +28,6 @@ void GetPhotoStateOnIOThread(const std::string& source_id,
ImageCaptureImpl::GetPhotoStateCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
-// TODO(mcasas): Enable PhotoState collection in Windows when understood why it
-// prevents normal capture https://crbug.com/722038.
-#if !defined(OS_WIN)
const int session_id =
media_stream_manager->VideoDeviceIdToSessionId(source_id);
@@ -39,7 +35,6 @@ void GetPhotoStateOnIOThread(const std::string& source_id,
return;
media_stream_manager->video_capture_manager()->GetPhotoState(
session_id, std::move(callback));
-#endif
}
void SetOptionsOnIOThread(const std::string& source_id,
diff --git a/chromium/content/browser/image_capture/image_capture_impl.h b/chromium/content/browser/image_capture/image_capture_impl.h
index b8c57e893ef..3a4342b9845 100644
--- a/chromium/content/browser/image_capture/image_capture_impl.h
+++ b/chromium/content/browser/image_capture/image_capture_impl.h
@@ -5,7 +5,7 @@
#ifndef CONTENT_BROWSER_IMAGE_CAPTURE_IMAGE_CAPTURE_IMPL_H_
#define CONTENT_BROWSER_IMAGE_CAPTURE_IMAGE_CAPTURE_IMPL_H_
-#include "media/capture/mojo/image_capture.mojom.h"
+#include "media/capture/mojom/image_capture.mojom.h"
namespace content {
diff --git a/chromium/content/browser/indexed_db/cursor_impl.cc b/chromium/content/browser/indexed_db/cursor_impl.cc
index 281ff4bd11c..6506a21219b 100644
--- a/chromium/content/browser/indexed_db/cursor_impl.cc
+++ b/chromium/content/browser/indexed_db/cursor_impl.cc
@@ -4,7 +4,6 @@
#include "content/browser/indexed_db/cursor_impl.h"
-#include "base/memory/ptr_util.h"
#include "base/sequenced_task_runner.h"
#include "content/browser/indexed_db/indexed_db_callbacks.h"
#include "content/browser/indexed_db/indexed_db_cursor.h"
diff --git a/chromium/content/browser/indexed_db/database_impl.cc b/chromium/content/browser/indexed_db/database_impl.cc
index 072e96a56d8..9c305053f7d 100644
--- a/chromium/content/browser/indexed_db/database_impl.cc
+++ b/chromium/content/browser/indexed_db/database_impl.cc
@@ -4,7 +4,6 @@
#include "content/browser/indexed_db/database_impl.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/numerics/safe_math.h"
#include "base/sequence_checker.h"
@@ -16,10 +15,11 @@
#include "content/browser/indexed_db/indexed_db_dispatcher_host.h"
#include "content/browser/indexed_db/indexed_db_transaction.h"
#include "content/browser/indexed_db/indexed_db_value.h"
+#include "content/public/browser/browser_thread.h"
#include "storage/browser/blob/blob_storage_context.h"
#include "storage/browser/quota/quota_manager_proxy.h"
-#include "third_party/WebKit/public/mojom/quota/quota_types.mojom.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBDatabaseException.h"
+#include "third_party/blink/public/mojom/quota/quota_types.mojom.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_exception.h"
using std::swap;
@@ -912,8 +912,8 @@ void DatabaseImpl::IDBSequenceHelper::Commit(int64_t transaction_id) {
indexed_db_context_->quota_manager_proxy()->GetUsageAndQuota(
indexed_db_context_->TaskRunner(), origin_,
blink::mojom::StorageType::kTemporary,
- base::Bind(&IDBSequenceHelper::OnGotUsageAndQuotaForCommit,
- weak_factory_.GetWeakPtr(), transaction_id));
+ base::BindOnce(&IDBSequenceHelper::OnGotUsageAndQuotaForCommit,
+ weak_factory_.GetWeakPtr(), transaction_id));
}
void DatabaseImpl::IDBSequenceHelper::OnGotUsageAndQuotaForCommit(
diff --git a/chromium/content/browser/indexed_db/indexed_db_active_blob_registry_unittest.cc b/chromium/content/browser/indexed_db/indexed_db_active_blob_registry_unittest.cc
index 85e3489d970..d05736ca0d3 100644
--- a/chromium/content/browser/indexed_db/indexed_db_active_blob_registry_unittest.cc
+++ b/chromium/content/browser/indexed_db/indexed_db_active_blob_registry_unittest.cc
@@ -7,7 +7,6 @@
#include <set>
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/test/test_simple_task_runner.h"
#include "content/browser/indexed_db/indexed_db_active_blob_registry.h"
#include "content/browser/indexed_db/indexed_db_backing_store.h"
@@ -143,13 +142,13 @@ TEST_F(IndexedDBActiveBlobRegistryTest, SimpleUse) {
registry()->GetAddBlobRefCallback(kDatabaseId0, kBlobKey0);
ReleaseCallback release =
registry()->GetFinalReleaseCallback(kDatabaseId0, kBlobKey0);
- add_ref.Run();
+ std::move(add_ref).Run();
RunUntilIdle();
EXPECT_TRUE(factory()->CheckSingleOriginInUse(backing_store()->origin()));
EXPECT_TRUE(backing_store()->CheckUnusedBlobsEmpty());
- release.Run(base::FilePath());
+ std::move(release).Run(base::FilePath());
RunUntilIdle();
EXPECT_TRUE(factory()->CheckNoOriginsInUse());
@@ -165,7 +164,7 @@ TEST_F(IndexedDBActiveBlobRegistryTest, DeleteWhileInUse) {
ReleaseCallback release =
registry()->GetFinalReleaseCallback(kDatabaseId0, kBlobKey0);
- add_ref.Run();
+ std::move(add_ref).Run();
RunUntilIdle();
EXPECT_TRUE(factory()->CheckSingleOriginInUse(backing_store()->origin()));
@@ -177,7 +176,7 @@ TEST_F(IndexedDBActiveBlobRegistryTest, DeleteWhileInUse) {
EXPECT_TRUE(factory()->CheckSingleOriginInUse(backing_store()->origin()));
EXPECT_TRUE(backing_store()->CheckUnusedBlobsEmpty());
- release.Run(base::FilePath());
+ std::move(release).Run(base::FilePath());
RunUntilIdle();
EXPECT_TRUE(factory()->CheckNoOriginsInUse());
@@ -205,16 +204,16 @@ TEST_F(IndexedDBActiveBlobRegistryTest, MultipleBlobs) {
ReleaseCallback release_11 =
registry()->GetFinalReleaseCallback(kDatabaseId1, kBlobKey1);
- add_ref_00.Run();
- add_ref_01.Run();
+ std::move(add_ref_00).Run();
+ std::move(add_ref_01).Run();
RunUntilIdle();
EXPECT_TRUE(factory()->CheckSingleOriginInUse(backing_store()->origin()));
EXPECT_TRUE(backing_store()->CheckUnusedBlobsEmpty());
- release_00.Run(base::FilePath());
- add_ref_10.Run();
- add_ref_11.Run();
+ std::move(release_00).Run(base::FilePath());
+ std::move(add_ref_10).Run();
+ std::move(add_ref_11).Run();
RunUntilIdle();
EXPECT_TRUE(factory()->CheckSingleOriginInUse(backing_store()->origin()));
@@ -226,14 +225,14 @@ TEST_F(IndexedDBActiveBlobRegistryTest, MultipleBlobs) {
EXPECT_TRUE(factory()->CheckSingleOriginInUse(backing_store()->origin()));
EXPECT_TRUE(backing_store()->CheckUnusedBlobsEmpty());
- release_01.Run(base::FilePath());
- release_11.Run(base::FilePath());
+ std::move(release_01).Run(base::FilePath());
+ std::move(release_11).Run(base::FilePath());
RunUntilIdle();
EXPECT_TRUE(factory()->CheckSingleOriginInUse(backing_store()->origin()));
EXPECT_TRUE(backing_store()->CheckSingleUnusedBlob(kDatabaseId0, kBlobKey1));
- release_10.Run(base::FilePath());
+ std::move(release_10).Run(base::FilePath());
RunUntilIdle();
EXPECT_TRUE(factory()->CheckNoOriginsInUse());
@@ -253,7 +252,7 @@ TEST_F(IndexedDBActiveBlobRegistryTest, ForceShutdown) {
ReleaseCallback release_1 =
registry()->GetFinalReleaseCallback(kDatabaseId0, kBlobKey1);
- add_ref_0.Run();
+ std::move(add_ref_0).Run();
RunUntilIdle();
EXPECT_TRUE(factory()->CheckSingleOriginInUse(backing_store()->origin()));
@@ -261,15 +260,15 @@ TEST_F(IndexedDBActiveBlobRegistryTest, ForceShutdown) {
registry()->ForceShutdown();
- add_ref_1.Run();
+ std::move(add_ref_1).Run();
RunUntilIdle();
// Nothing changes.
EXPECT_TRUE(factory()->CheckSingleOriginInUse(backing_store()->origin()));
EXPECT_TRUE(backing_store()->CheckUnusedBlobsEmpty());
- release_0.Run(base::FilePath());
- release_1.Run(base::FilePath());
+ std::move(release_0).Run(base::FilePath());
+ std::move(release_1).Run(base::FilePath());
RunUntilIdle();
// Nothing changes.
diff --git a/chromium/content/browser/indexed_db/indexed_db_backing_store.cc b/chromium/content/browser/indexed_db/indexed_db_backing_store.cc
index c4478349afe..774da43bac0 100644
--- a/chromium/content/browser/indexed_db/indexed_db_backing_store.cc
+++ b/chromium/content/browser/indexed_db/indexed_db_backing_store.cc
@@ -51,7 +51,7 @@
#include "storage/browser/fileapi/local_file_stream_writer.h"
#include "storage/common/database/database_identifier.h"
#include "storage/common/fileapi/file_system_mount_option.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBTypes.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_types.h"
#include "third_party/leveldatabase/env_chromium.h"
using base::FilePath;
@@ -728,7 +728,8 @@ WARN_UNUSED_RESULT Status IndexedDBBackingStore::SetUpMetadata() {
DatabaseNameKey::EncodeMinKeyForOrigin(origin_identifier_);
const std::string stop_key =
DatabaseNameKey::EncodeStopKeyForOrigin(origin_identifier_);
- std::unique_ptr<LevelDBIterator> it = db_->CreateIterator();
+ std::unique_ptr<LevelDBIterator> it =
+ db_->CreateIterator(db_->DefaultReadOptions());
for (s = it->Seek(start_key);
s.ok() && it->IsValid() && CompareKeys(it->Key(), stop_key) < 0;
s = it->Next()) {
@@ -1160,7 +1161,9 @@ Status IndexedDBBackingStore::DeleteDatabase(const base::string16& name) {
DatabaseMetaDataKey::Encode(id + 1, DatabaseMetaDataKey::ORIGIN_NAME);
{
IDB_TRACE("IndexedDBBackingStore::DeleteDatabase.DeleteEntries");
- std::unique_ptr<LevelDBIterator> it = db_->CreateIterator();
+ leveldb::ReadOptions options = db_->DefaultReadOptions();
+ options.fill_cache = false;
+ std::unique_ptr<LevelDBIterator> it = db_->CreateIterator(options);
for (s = it->Seek(start_key);
s.ok() && it->IsValid() && CompareKeys(it->Key(), stop_key) < 0;
s = it->Next())
diff --git a/chromium/content/browser/indexed_db/indexed_db_backing_store_unittest.cc b/chromium/content/browser/indexed_db/indexed_db_backing_store_unittest.cc
index b89ad3a4a35..c7eb42be40b 100644
--- a/chromium/content/browser/indexed_db/indexed_db_backing_store_unittest.cc
+++ b/chromium/content/browser/indexed_db/indexed_db_backing_store_unittest.cc
@@ -13,7 +13,6 @@
#include "base/files/scoped_temp_dir.h"
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/sequenced_task_runner.h"
#include "base/strings/string16.h"
#include "base/strings/utf_string_conversions.h"
@@ -34,7 +33,7 @@
#include "storage/browser/test/mock_quota_manager_proxy.h"
#include "storage/browser/test/mock_special_storage_policy.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBTypes.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_types.h"
using base::ASCIIToUTF16;
using url::Origin;
diff --git a/chromium/content/browser/indexed_db/indexed_db_browsertest.cc b/chromium/content/browser/indexed_db/indexed_db_browsertest.cc
index 820b52485c8..860e36aee5b 100644
--- a/chromium/content/browser/indexed_db/indexed_db_browsertest.cc
+++ b/chromium/content/browser/indexed_db/indexed_db_browsertest.cc
@@ -828,7 +828,7 @@ IN_PROC_BROWSER_TEST_F(
base::string16 expected_title16(ASCIIToUTF16("setVersion(3) complete"));
TitleWatcher title_watcher(new_shell->web_contents(), expected_title16);
- shell()->web_contents()->GetMainFrame()->GetProcess()->Shutdown(0, true);
+ shell()->web_contents()->GetMainFrame()->GetProcess()->Shutdown(0);
shell()->Close();
EXPECT_EQ(expected_title16, title_watcher.WaitAndGetTitle());
diff --git a/chromium/content/browser/indexed_db/indexed_db_callbacks.cc b/chromium/content/browser/indexed_db/indexed_db_callbacks.cc
index 78c22df7476..8e16c5dbeab 100644
--- a/chromium/content/browser/indexed_db/indexed_db_callbacks.cc
+++ b/chromium/content/browser/indexed_db/indexed_db_callbacks.cc
@@ -11,7 +11,6 @@
#include <utility>
#include "base/guid.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/sequenced_task_runner.h"
#include "base/strings/utf_string_conversions.h"
@@ -31,7 +30,6 @@
#include "content/browser/indexed_db/indexed_db_value.h"
#include "content/common/indexed_db/indexed_db_constants.h"
#include "content/common/indexed_db/indexed_db_metadata.h"
-#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_features.h"
#include "mojo/public/cpp/bindings/strong_associated_binding.h"
#include "storage/browser/blob/blob_data_builder.h"
diff --git a/chromium/content/browser/indexed_db/indexed_db_callbacks.h b/chromium/content/browser/indexed_db/indexed_db_callbacks.h
index cddc86b2bf1..f654d0e144c 100644
--- a/chromium/content/browser/indexed_db/indexed_db_callbacks.h
+++ b/chromium/content/browser/indexed_db/indexed_db_callbacks.h
@@ -21,6 +21,7 @@
#include "content/common/indexed_db/indexed_db.mojom.h"
#include "content/common/indexed_db/indexed_db_key.h"
#include "content/common/indexed_db/indexed_db_key_path.h"
+#include "content/public/browser/browser_thread.h"
#include "url/origin.h"
namespace base {
diff --git a/chromium/content/browser/indexed_db/indexed_db_class_factory.h b/chromium/content/browser/indexed_db/indexed_db_class_factory.h
index 1c4c2dc19fc..21fc4381b64 100644
--- a/chromium/content/browser/indexed_db/indexed_db_class_factory.h
+++ b/chromium/content/browser/indexed_db/indexed_db_class_factory.h
@@ -15,7 +15,7 @@
#include "content/browser/indexed_db/indexed_db_backing_store.h"
#include "content/browser/indexed_db/indexed_db_database.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBTypes.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_types.h"
namespace leveldb {
class Iterator;
diff --git a/chromium/content/browser/indexed_db/indexed_db_cleanup_on_io_error_unittest.cc b/chromium/content/browser/indexed_db/indexed_db_cleanup_on_io_error_unittest.cc
index 9ee60096832..0c702bf0f8f 100644
--- a/chromium/content/browser/indexed_db/indexed_db_cleanup_on_io_error_unittest.cc
+++ b/chromium/content/browser/indexed_db/indexed_db_cleanup_on_io_error_unittest.cc
@@ -8,7 +8,6 @@
#include "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/string16.h"
#include "base/strings/utf_string_conversions.h"
#include "content/browser/indexed_db/indexed_db_backing_store.h"
diff --git a/chromium/content/browser/indexed_db/indexed_db_context_impl.cc b/chromium/content/browser/indexed_db/indexed_db_context_impl.cc
index c1e0a7d0f00..d242a9db6a8 100644
--- a/chromium/content/browser/indexed_db/indexed_db_context_impl.cc
+++ b/chromium/content/browser/indexed_db/indexed_db_context_impl.cc
@@ -12,7 +12,6 @@
#include "base/files/file_enumerator.h"
#include "base/files/file_util.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/sequenced_task_runner.h"
#include "base/strings/string_util.h"
@@ -36,7 +35,7 @@
#include "content/public/common/content_switches.h"
#include "storage/browser/database/database_util.h"
#include "storage/common/database/database_identifier.h"
-#include "third_party/WebKit/public/mojom/quota/quota_types.mojom.h"
+#include "third_party/blink/public/mojom/quota/quota_types.mojom.h"
#include "ui/base/text/bytes_formatting.h"
#include "url/origin.h"
diff --git a/chromium/content/browser/indexed_db/indexed_db_cursor.cc b/chromium/content/browser/indexed_db/indexed_db_cursor.cc
index 979a8b16fe0..bd12dd62086 100644
--- a/chromium/content/browser/indexed_db/indexed_db_cursor.cc
+++ b/chromium/content/browser/indexed_db/indexed_db_cursor.cc
@@ -15,7 +15,7 @@
#include "content/browser/indexed_db/indexed_db_tracing.h"
#include "content/browser/indexed_db/indexed_db_transaction.h"
#include "content/browser/indexed_db/indexed_db_value.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBDatabaseException.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_exception.h"
namespace content {
namespace {
diff --git a/chromium/content/browser/indexed_db/indexed_db_cursor.h b/chromium/content/browser/indexed_db/indexed_db_cursor.h
index 1d10e901d70..d0cc7e74e37 100644
--- a/chromium/content/browser/indexed_db/indexed_db_cursor.h
+++ b/chromium/content/browser/indexed_db/indexed_db_cursor.h
@@ -17,7 +17,7 @@
#include "content/browser/indexed_db/indexed_db_database.h"
#include "content/browser/indexed_db/indexed_db_transaction.h"
#include "content/common/indexed_db/indexed_db_key_range.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBTypes.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_types.h"
namespace content {
diff --git a/chromium/content/browser/indexed_db/indexed_db_data_format_version.cc b/chromium/content/browser/indexed_db/indexed_db_data_format_version.cc
index b23f82d7a26..7fa06ed72d2 100644
--- a/chromium/content/browser/indexed_db/indexed_db_data_format_version.cc
+++ b/chromium/content/browser/indexed_db/indexed_db_data_format_version.cc
@@ -4,7 +4,7 @@
#include "content/browser/indexed_db/indexed_db_data_format_version.h"
-#include "third_party/WebKit/public/web/WebSerializedScriptValueVersion.h"
+#include "third_party/blink/public/web/web_serialized_script_value_version.h"
#include "v8/include/v8-value-serializer-version.h"
namespace content {
diff --git a/chromium/content/browser/indexed_db/indexed_db_data_loss_info.h b/chromium/content/browser/indexed_db/indexed_db_data_loss_info.h
index 3670226df9e..8c36dd38666 100644
--- a/chromium/content/browser/indexed_db/indexed_db_data_loss_info.h
+++ b/chromium/content/browser/indexed_db/indexed_db_data_loss_info.h
@@ -7,7 +7,7 @@
#include <string>
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBTypes.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_types.h"
namespace content {
diff --git a/chromium/content/browser/indexed_db/indexed_db_database.cc b/chromium/content/browser/indexed_db/indexed_db_database.cc
index 95032b2d656..fff36197e29 100644
--- a/chromium/content/browser/indexed_db/indexed_db_database.cc
+++ b/chromium/content/browser/indexed_db/indexed_db_database.cc
@@ -13,7 +13,6 @@
#include "base/auto_reset.h"
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/numerics/safe_conversions.h"
#include "base/stl_util.h"
@@ -37,7 +36,7 @@
#include "content/common/indexed_db/indexed_db_key_range.h"
#include "content/public/common/content_switches.h"
#include "storage/browser/blob/blob_data_handle.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBDatabaseException.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_exception.h"
#include "third_party/leveldatabase/env_chromium.h"
#include "url/origin.h"
diff --git a/chromium/content/browser/indexed_db/indexed_db_database.h b/chromium/content/browser/indexed_db/indexed_db_database.h
index c04ba2bd709..0fc4f636c2b 100644
--- a/chromium/content/browser/indexed_db/indexed_db_database.h
+++ b/chromium/content/browser/indexed_db/indexed_db_database.h
@@ -29,7 +29,7 @@
#include "content/browser/indexed_db/list_set.h"
#include "content/common/content_export.h"
#include "content/common/indexed_db/indexed_db_metadata.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBTypes.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_types.h"
namespace url {
class Origin;
diff --git a/chromium/content/browser/indexed_db/indexed_db_database_unittest.cc b/chromium/content/browser/indexed_db/indexed_db_database_unittest.cc
index e2825b4967c..fd5e26400ab 100644
--- a/chromium/content/browser/indexed_db/indexed_db_database_unittest.cc
+++ b/chromium/content/browser/indexed_db/indexed_db_database_unittest.cc
@@ -11,7 +11,6 @@
#include "base/auto_reset.h"
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/strings/string16.h"
#include "base/strings/utf_string_conversions.h"
diff --git a/chromium/content/browser/indexed_db/indexed_db_dispatcher_host.cc b/chromium/content/browser/indexed_db/indexed_db_dispatcher_host.cc
index 1876af1b042..52deffba26f 100644
--- a/chromium/content/browser/indexed_db/indexed_db_dispatcher_host.cc
+++ b/chromium/content/browser/indexed_db/indexed_db_dispatcher_host.cc
@@ -8,7 +8,6 @@
#include "base/bind.h"
#include "base/files/file_path.h"
-#include "base/memory/ptr_util.h"
#include "base/process/process.h"
#include "base/sequenced_task_runner.h"
#include "base/stl_util.h"
diff --git a/chromium/content/browser/indexed_db/indexed_db_dispatcher_host_unittest.cc b/chromium/content/browser/indexed_db/indexed_db_dispatcher_host_unittest.cc
index 91c0d00b2ef..ff718191b32 100644
--- a/chromium/content/browser/indexed_db/indexed_db_dispatcher_host_unittest.cc
+++ b/chromium/content/browser/indexed_db/indexed_db_dispatcher_host_unittest.cc
@@ -7,14 +7,12 @@
#include "base/barrier_closure.h"
#include "base/callback.h"
#include "base/files/scoped_temp_dir.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/utf_offset_string_conversions.h"
#include "base/test/test_simple_task_runner.h"
#include "base/threading/thread.h"
-#include "content/browser/browser_thread_impl.h"
#include "content/browser/indexed_db/indexed_db_callbacks.h"
#include "content/browser/indexed_db/indexed_db_context_impl.h"
#include "content/browser/indexed_db/indexed_db_database_callbacks.h"
@@ -34,7 +32,7 @@
#include "storage/browser/test/mock_special_storage_policy.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBDatabaseException.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_exception.h"
#include "url/origin.h"
using indexed_db::mojom::Callbacks;
@@ -279,7 +277,7 @@ TEST_F(IndexedDBDispatcherHostTest, CloseAfterUpgrade) {
*connection.open_callbacks,
MockedSuccessDatabase(IsAssociatedInterfacePtrInfoValid(false), _))
.Times(1)
- .WillOnce(RunClosure(quit_closure));
+ .WillOnce(RunClosure(std::move(quit_closure)));
ASSERT_TRUE(connection.database.is_bound());
connection.database->CreateObjectStore(kTransactionId, kObjectStoreId,
@@ -346,7 +344,7 @@ TEST_F(IndexedDBDispatcherHostTest, OpenNewConnectionWhileUpgrading) {
MockedSuccessDatabase(IsAssociatedInterfacePtrInfoValid(true), _))
.WillOnce(testing::DoAll(MoveArg<0>(&database_info2),
testing::SaveArg<1>(&metadata2),
- RunClosure(quit_closure)));
+ RunClosure(std::move(quit_closure))));
// Create object store.
ASSERT_TRUE(connection1.database.is_bound());
@@ -419,7 +417,7 @@ TEST_F(IndexedDBDispatcherHostTest, PutWithInvalidBlob) {
EXPECT_CALL(*connection.open_callbacks,
Error(blink::kWebIDBDatabaseExceptionAbortError, _))
.Times(1)
- .WillOnce(RunClosure(quit_closure));
+ .WillOnce(RunClosure(std::move(quit_closure)));
ASSERT_TRUE(connection.database.is_bound());
connection.database->CreateObjectStore(kTransactionId, kObjectStoreId,
@@ -883,7 +881,7 @@ TEST_F(IndexedDBDispatcherHostTest, DISABLED_NotifyIndexedDBListChanged) {
*connection1.open_callbacks,
MockedSuccessDatabase(IsAssociatedInterfacePtrInfoValid(false), _))
.Times(1)
- .WillOnce(RunClosure(quit_closure));
+ .WillOnce(RunClosure(std::move(quit_closure)));
ASSERT_TRUE(connection1.database.is_bound());
connection1.database->CreateObjectStore(kTransactionId1, kObjectStoreId,
@@ -938,7 +936,7 @@ TEST_F(IndexedDBDispatcherHostTest, DISABLED_NotifyIndexedDBListChanged) {
*connection2.open_callbacks,
MockedSuccessDatabase(IsAssociatedInterfacePtrInfoValid(false), _))
.Times(1)
- .WillOnce(RunClosure(quit_closure));
+ .WillOnce(RunClosure(std::move(quit_closure)));
ASSERT_TRUE(connection2.database.is_bound());
connection2.database->DeleteIndex(kTransactionId2, kObjectStoreId,
@@ -988,7 +986,7 @@ TEST_F(IndexedDBDispatcherHostTest, DISABLED_NotifyIndexedDBListChanged) {
*connection3.open_callbacks,
MockedSuccessDatabase(IsAssociatedInterfacePtrInfoValid(false), _))
.Times(1)
- .WillOnce(RunClosure(quit_closure));
+ .WillOnce(RunClosure(std::move(quit_closure)));
ASSERT_TRUE(connection3.database.is_bound());
connection3.database->DeleteObjectStore(kTransactionId3, kObjectStoreId);
@@ -1058,7 +1056,7 @@ TEST_F(IndexedDBDispatcherHostTest, NotifyIndexedDBContentChanged) {
*connection1.open_callbacks,
MockedSuccessDatabase(IsAssociatedInterfacePtrInfoValid(false), _))
.Times(1)
- .WillOnce(RunClosure(quit_closure));
+ .WillOnce(RunClosure(std::move(quit_closure)));
ASSERT_TRUE(connection1.database.is_bound());
connection1.database->CreateObjectStore(kTransactionId1, kObjectStoreId,
@@ -1124,7 +1122,7 @@ TEST_F(IndexedDBDispatcherHostTest, NotifyIndexedDBContentChanged) {
*connection2.open_callbacks,
MockedSuccessDatabase(IsAssociatedInterfacePtrInfoValid(false), _))
.Times(1)
- .WillOnce(RunClosure(quit_closure));
+ .WillOnce(RunClosure(std::move(quit_closure)));
ASSERT_TRUE(connection2.database.is_bound());
connection2.database->Clear(kTransactionId2, kObjectStoreId,
diff --git a/chromium/content/browser/indexed_db/indexed_db_factory_impl.cc b/chromium/content/browser/indexed_db/indexed_db_factory_impl.cc
index fa8fd12ffa9..eea4df4c465 100644
--- a/chromium/content/browser/indexed_db/indexed_db_factory_impl.cc
+++ b/chromium/content/browser/indexed_db/indexed_db_factory_impl.cc
@@ -12,7 +12,6 @@
#include "base/callback_helpers.h"
#include "base/feature_list.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/rand_util.h"
#include "base/strings/string_util.h"
@@ -27,7 +26,7 @@
#include "content/browser/indexed_db/indexed_db_tombstone_sweeper.h"
#include "content/browser/indexed_db/indexed_db_tracing.h"
#include "content/browser/indexed_db/indexed_db_transaction_coordinator.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBDatabaseException.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_exception.h"
#include "third_party/leveldatabase/env_chromium.h"
using base::ASCIIToUTF16;
diff --git a/chromium/content/browser/indexed_db/indexed_db_factory_unittest.cc b/chromium/content/browser/indexed_db/indexed_db_factory_unittest.cc
index 73d2f19e1da..2384f769124 100644
--- a/chromium/content/browser/indexed_db/indexed_db_factory_unittest.cc
+++ b/chromium/content/browser/indexed_db/indexed_db_factory_unittest.cc
@@ -10,7 +10,6 @@
#include "base/files/scoped_temp_dir.h"
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/scoped_feature_list.h"
@@ -28,8 +27,8 @@
#include "content/public/test/test_utils.h"
#include "storage/browser/test/mock_quota_manager_proxy.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBDatabaseException.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBTypes.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_exception.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_types.h"
#include "url/gurl.h"
#include "url/origin.h"
diff --git a/chromium/content/browser/indexed_db/indexed_db_index_writer.cc b/chromium/content/browser/indexed_db/indexed_db_index_writer.cc
index 6493041b243..f18444c36f8 100644
--- a/chromium/content/browser/indexed_db/indexed_db_index_writer.cc
+++ b/chromium/content/browser/indexed_db/indexed_db_index_writer.cc
@@ -8,7 +8,6 @@
#include <utility>
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/utf_string_conversions.h"
#include "content/browser/indexed_db/indexed_db_backing_store.h"
#include "content/browser/indexed_db/indexed_db_tracing.h"
diff --git a/chromium/content/browser/indexed_db/indexed_db_internals_ui.cc b/chromium/content/browser/indexed_db/indexed_db_internals_ui.cc
index 1e55bd8864d..48bf8b22774 100644
--- a/chromium/content/browser/indexed_db/indexed_db_internals_ui.cc
+++ b/chromium/content/browser/indexed_db/indexed_db_internals_ui.cc
@@ -52,17 +52,16 @@ bool AllowWhitelistedPaths(const std::vector<base::FilePath>& allowed_paths,
IndexedDBInternalsUI::IndexedDBInternalsUI(WebUI* web_ui)
: WebUIController(web_ui) {
web_ui->RegisterMessageCallback(
- "getAllOrigins",
- base::Bind(&IndexedDBInternalsUI::GetAllOrigins, base::Unretained(this)));
+ "getAllOrigins", base::BindRepeating(&IndexedDBInternalsUI::GetAllOrigins,
+ base::Unretained(this)));
web_ui->RegisterMessageCallback(
"downloadOriginData",
- base::Bind(&IndexedDBInternalsUI::DownloadOriginData,
- base::Unretained(this)));
+ base::BindRepeating(&IndexedDBInternalsUI::DownloadOriginData,
+ base::Unretained(this)));
web_ui->RegisterMessageCallback(
- "forceClose",
- base::Bind(&IndexedDBInternalsUI::ForceCloseOrigin,
- base::Unretained(this)));
+ "forceClose", base::BindRepeating(&IndexedDBInternalsUI::ForceCloseOrigin,
+ base::Unretained(this)));
WebUIDataSource* source =
WebUIDataSource::Create(kChromeUIIndexedDBInternalsHost);
@@ -99,7 +98,7 @@ void IndexedDBInternalsUI::GetAllOrigins(const base::ListValue* args) {
BrowserContext::StoragePartitionCallback cb =
base::Bind(&IndexedDBInternalsUI::AddContextFromStoragePartition,
base::Unretained(this));
- BrowserContext::ForEachStoragePartition(browser_context, cb);
+ BrowserContext::ForEachStoragePartition(browser_context, std::move(cb));
}
void IndexedDBInternalsUI::GetAllOriginsOnIndexedDBThread(
@@ -170,7 +169,7 @@ bool IndexedDBInternalsUI::GetOriginContext(
StoragePartition* result_partition;
BrowserContext::StoragePartitionCallback cb =
base::Bind(&FindContext, path, &result_partition, context);
- BrowserContext::ForEachStoragePartition(browser_context, cb);
+ BrowserContext::ForEachStoragePartition(browser_context, std::move(cb));
if (!result_partition || !(context->get()))
return false;
diff --git a/chromium/content/browser/indexed_db/indexed_db_leveldb_coding.cc b/chromium/content/browser/indexed_db/indexed_db_leveldb_coding.cc
index ca991f9bb82..d407f6018cf 100644
--- a/chromium/content/browser/indexed_db/indexed_db_leveldb_coding.cc
+++ b/chromium/content/browser/indexed_db/indexed_db_leveldb_coding.cc
@@ -8,7 +8,6 @@
#include <limits>
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/string16.h"
#include "base/strings/utf_string_conversions.h"
#include "base/sys_byteorder.h"
diff --git a/chromium/content/browser/indexed_db/indexed_db_metadata_coding.cc b/chromium/content/browser/indexed_db/indexed_db_metadata_coding.cc
index daeb252b409..dfb98770800 100644
--- a/chromium/content/browser/indexed_db/indexed_db_metadata_coding.cc
+++ b/chromium/content/browser/indexed_db/indexed_db_metadata_coding.cc
@@ -33,7 +33,7 @@ using indexed_db::PutVarInt;
namespace {
std::unique_ptr<LevelDBIterator> CreateIterator(LevelDBDatabase* database) {
- return database->CreateIterator();
+ return database->CreateIterator(database->DefaultReadOptions());
}
std::unique_ptr<LevelDBIterator> CreateIterator(
diff --git a/chromium/content/browser/indexed_db/indexed_db_observer.h b/chromium/content/browser/indexed_db/indexed_db_observer.h
index 6c108905b5b..c648455a75e 100644
--- a/chromium/content/browser/indexed_db/indexed_db_observer.h
+++ b/chromium/content/browser/indexed_db/indexed_db_observer.h
@@ -14,7 +14,7 @@
#include "base/macros.h"
#include "base/stl_util.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBTypes.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_types.h"
namespace content {
diff --git a/chromium/content/browser/indexed_db/indexed_db_quota_client.cc b/chromium/content/browser/indexed_db/indexed_db_quota_client.cc
index a167c4b1953..1ffd3368282 100644
--- a/chromium/content/browser/indexed_db/indexed_db_quota_client.cc
+++ b/chromium/content/browser/indexed_db/indexed_db_quota_client.cc
@@ -13,7 +13,7 @@
#include "content/public/browser/browser_thread.h"
#include "net/base/url_util.h"
#include "storage/browser/database/database_util.h"
-#include "third_party/WebKit/public/mojom/quota/quota_types.mojom.h"
+#include "third_party/blink/public/mojom/quota/quota_types.mojom.h"
using blink::mojom::StorageType;
using storage::QuotaClient;
diff --git a/chromium/content/browser/indexed_db/indexed_db_quota_client.h b/chromium/content/browser/indexed_db/indexed_db_quota_client.h
index 1217e85625f..e491dba9e80 100644
--- a/chromium/content/browser/indexed_db/indexed_db_quota_client.h
+++ b/chromium/content/browser/indexed_db/indexed_db_quota_client.h
@@ -14,7 +14,7 @@
#include "content/common/content_export.h"
#include "storage/browser/quota/quota_client.h"
#include "storage/browser/quota/quota_task.h"
-#include "third_party/WebKit/public/mojom/quota/quota_types.mojom.h"
+#include "third_party/blink/public/mojom/quota/quota_types.mojom.h"
#include "url/origin.h"
namespace content {
diff --git a/chromium/content/browser/indexed_db/indexed_db_quota_client_unittest.cc b/chromium/content/browser/indexed_db/indexed_db_quota_client_unittest.cc
index 61a4ef4e45b..f209ddf7f4a 100644
--- a/chromium/content/browser/indexed_db/indexed_db_quota_client_unittest.cc
+++ b/chromium/content/browser/indexed_db/indexed_db_quota_client_unittest.cc
@@ -15,7 +15,6 @@
#include "base/threading/sequenced_task_runner_handle.h"
#include "base/threading/thread.h"
#include "base/threading/thread_task_runner_handle.h"
-#include "content/browser/browser_thread_impl.h"
#include "content/browser/indexed_db/indexed_db_context_impl.h"
#include "content/browser/indexed_db/indexed_db_quota_client.h"
#include "content/public/browser/storage_partition.h"
diff --git a/chromium/content/browser/indexed_db/indexed_db_tombstone_sweeper.h b/chromium/content/browser/indexed_db/indexed_db_tombstone_sweeper.h
index 5ce9f30aa1d..ef335a71440 100644
--- a/chromium/content/browser/indexed_db/indexed_db_tombstone_sweeper.h
+++ b/chromium/content/browser/indexed_db/indexed_db_tombstone_sweeper.h
@@ -140,7 +140,7 @@ class CONTENT_EXPORT IndexedDBTombstoneSweeper
sweep_state_.start_index_seed = index_seed;
}
- void SetClockForTesting(base::TickClock* clock) {
+ void SetClockForTesting(const base::TickClock* clock) {
clock_for_testing_ = clock;
}
@@ -177,7 +177,7 @@ class CONTENT_EXPORT IndexedDBTombstoneSweeper
int total_indices_ = 0;
// Used to measure total time of the task.
- base::TickClock* clock_for_testing_ = nullptr;
+ const base::TickClock* clock_for_testing_ = nullptr;
base::Optional<base::TimeTicks> start_time_;
leveldb::DB* database_ = nullptr;
diff --git a/chromium/content/browser/indexed_db/indexed_db_tombstone_sweeper_unittest.cc b/chromium/content/browser/indexed_db/indexed_db_tombstone_sweeper_unittest.cc
index 86be8f46699..e0d69eac84f 100644
--- a/chromium/content/browser/indexed_db/indexed_db_tombstone_sweeper_unittest.cc
+++ b/chromium/content/browser/indexed_db/indexed_db_tombstone_sweeper_unittest.cc
@@ -7,7 +7,6 @@
#include <memory>
#include "base/files/scoped_temp_dir.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/histogram_tester.h"
@@ -66,7 +65,7 @@ class MockTickClock : public base::TickClock {
MockTickClock() {}
~MockTickClock() override {}
- MOCK_METHOD0(NowTicks, base::TimeTicks());
+ MOCK_CONST_METHOD0(NowTicks, base::TimeTicks());
};
class Comparator : public LevelDBComparator {
diff --git a/chromium/content/browser/indexed_db/indexed_db_transaction.cc b/chromium/content/browser/indexed_db/indexed_db_transaction.cc
index 5288b189c70..a0878c2dce7 100644
--- a/chromium/content/browser/indexed_db/indexed_db_transaction.cc
+++ b/chromium/content/browser/indexed_db/indexed_db_transaction.cc
@@ -7,7 +7,6 @@
#include "base/bind.h"
#include "base/location.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/stl_util.h"
#include "base/strings/utf_string_conversions.h"
@@ -18,7 +17,7 @@
#include "content/browser/indexed_db/indexed_db_database_callbacks.h"
#include "content/browser/indexed_db/indexed_db_tracing.h"
#include "content/browser/indexed_db/indexed_db_transaction_coordinator.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBDatabaseException.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_exception.h"
#include "third_party/leveldatabase/env_chromium.h"
namespace content {
diff --git a/chromium/content/browser/indexed_db/indexed_db_transaction.h b/chromium/content/browser/indexed_db/indexed_db_transaction.h
index e25fdf673d7..7196f25943e 100644
--- a/chromium/content/browser/indexed_db/indexed_db_transaction.h
+++ b/chromium/content/browser/indexed_db/indexed_db_transaction.h
@@ -24,7 +24,7 @@
#include "content/browser/indexed_db/indexed_db_database_error.h"
#include "content/browser/indexed_db/indexed_db_observer.h"
#include "content/common/indexed_db/indexed_db.mojom.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBTypes.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_types.h"
namespace content {
diff --git a/chromium/content/browser/indexed_db/indexed_db_transaction_coordinator.cc b/chromium/content/browser/indexed_db/indexed_db_transaction_coordinator.cc
index e32dfe3b382..eb714dde14d 100644
--- a/chromium/content/browser/indexed_db/indexed_db_transaction_coordinator.cc
+++ b/chromium/content/browser/indexed_db/indexed_db_transaction_coordinator.cc
@@ -7,7 +7,7 @@
#include "base/logging.h"
#include "content/browser/indexed_db/indexed_db_tracing.h"
#include "content/browser/indexed_db/indexed_db_transaction.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBTypes.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_types.h"
namespace content {
namespace {
diff --git a/chromium/content/browser/indexed_db/indexed_db_transaction_unittest.cc b/chromium/content/browser/indexed_db/indexed_db_transaction_unittest.cc
index 5afb7917eff..cf1812c0f0e 100644
--- a/chromium/content/browser/indexed_db/indexed_db_transaction_unittest.cc
+++ b/chromium/content/browser/indexed_db/indexed_db_transaction_unittest.cc
@@ -10,7 +10,6 @@
#include "base/bind.h"
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/strings/utf_string_conversions.h"
#include "content/browser/indexed_db/fake_indexed_db_metadata_coding.h"
@@ -23,7 +22,7 @@
#include "content/browser/indexed_db/mock_indexed_db_factory.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBDatabaseException.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_exception.h"
namespace content {
namespace indexed_db_transaction_unittest {
diff --git a/chromium/content/browser/indexed_db/indexed_db_unittest.cc b/chromium/content/browser/indexed_db/indexed_db_unittest.cc
index 80c9b85019b..705a2ed309c 100644
--- a/chromium/content/browser/indexed_db/indexed_db_unittest.cc
+++ b/chromium/content/browser/indexed_db/indexed_db_unittest.cc
@@ -8,7 +8,6 @@
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "content/browser/indexed_db/indexed_db_connection.h"
diff --git a/chromium/content/browser/indexed_db/leveldb/leveldb_database.cc b/chromium/content/browser/indexed_db/leveldb/leveldb_database.cc
index 415c057faa8..20a4218d2b2 100644
--- a/chromium/content/browser/indexed_db/leveldb/leveldb_database.cc
+++ b/chromium/content/browser/indexed_db/leveldb/leveldb_database.cc
@@ -430,20 +430,15 @@ leveldb::Status LevelDBDatabase::Write(const LevelDBWriteBatch& write_batch) {
}
std::unique_ptr<LevelDBIterator> LevelDBDatabase::CreateIterator(
- const LevelDBSnapshot* snapshot) {
- leveldb::ReadOptions read_options;
- read_options.verify_checksums = true; // TODO(jsbell): Disable this if the
- // performance impact is too great.
- read_options.snapshot = snapshot ? snapshot->snapshot_ : nullptr;
-
+ const leveldb::ReadOptions& options) {
num_iterators_++;
max_iterators_ = std::max(max_iterators_, num_iterators_);
// Iterator isn't added to lru cache until it is used, as memory isn't loaded
// for the iterator until it's first Seek call.
- std::unique_ptr<leveldb::Iterator> i(db_->NewIterator(read_options));
+ std::unique_ptr<leveldb::Iterator> i(db_->NewIterator(options));
return std::unique_ptr<LevelDBIterator>(
IndexedDBClassFactory::Get()->CreateIteratorImpl(std::move(i), this,
- read_options.snapshot));
+ options.snapshot));
}
const LevelDBComparator* LevelDBDatabase::Comparator() const {
@@ -464,6 +459,19 @@ void LevelDBDatabase::CompactAll() {
db_->CompactRange(nullptr, nullptr);
}
+leveldb::ReadOptions LevelDBDatabase::DefaultReadOptions() {
+ return DefaultReadOptions(nullptr);
+}
+
+leveldb::ReadOptions LevelDBDatabase::DefaultReadOptions(
+ const LevelDBSnapshot* snapshot) {
+ leveldb::ReadOptions read_options;
+ read_options.verify_checksums = true; // TODO(jsbell): Disable this if the
+ // performance impact is too great.
+ read_options.snapshot = snapshot ? snapshot->snapshot_ : nullptr;
+ return read_options;
+}
+
bool LevelDBDatabase::OnMemoryDump(
const base::trace_event::MemoryDumpArgs& args,
base::trace_event::ProcessMemoryDump* pmd) {
diff --git a/chromium/content/browser/indexed_db/leveldb/leveldb_database.h b/chromium/content/browser/indexed_db/leveldb/leveldb_database.h
index 039cccc317f..46118ce1d3a 100644
--- a/chromium/content/browser/indexed_db/leveldb/leveldb_database.h
+++ b/chromium/content/browser/indexed_db/leveldb/leveldb_database.h
@@ -17,6 +17,7 @@
#include "base/trace_event/memory_dump_provider.h"
#include "content/common/content_export.h"
#include "third_party/leveldatabase/src/include/leveldb/comparator.h"
+#include "third_party/leveldatabase/src/include/leveldb/options.h"
#include "third_party/leveldatabase/src/include/leveldb/status.h"
namespace leveldb {
@@ -84,11 +85,16 @@ class CONTENT_EXPORT LevelDBDatabase
bool* found,
const LevelDBSnapshot* = 0);
leveldb::Status Write(const LevelDBWriteBatch& write_batch);
- std::unique_ptr<LevelDBIterator> CreateIterator(const LevelDBSnapshot* = 0);
+ // Note: Use DefaultReadOptions() and then adjust any values afterwards.
+ std::unique_ptr<LevelDBIterator> CreateIterator(
+ const leveldb::ReadOptions& options);
const LevelDBComparator* Comparator() const;
void Compact(const base::StringPiece& start, const base::StringPiece& stop);
void CompactAll();
+ leveldb::ReadOptions DefaultReadOptions();
+ leveldb::ReadOptions DefaultReadOptions(const LevelDBSnapshot* snapshot);
+
// base::trace_event::MemoryDumpProvider implementation.
bool OnMemoryDump(const base::trace_event::MemoryDumpArgs& args,
base::trace_event::ProcessMemoryDump* pmd) override;
diff --git a/chromium/content/browser/indexed_db/leveldb/leveldb_transaction.cc b/chromium/content/browser/indexed_db/leveldb/leveldb_transaction.cc
index dc1452d0cad..89035f6fb43 100644
--- a/chromium/content/browser/indexed_db/leveldb/leveldb_transaction.cc
+++ b/chromium/content/browser/indexed_db/leveldb/leveldb_transaction.cc
@@ -240,8 +240,8 @@ LevelDBTransaction::TransactionIterator::TransactionIterator(
: transaction_(transaction),
comparator_(transaction_->comparator_),
data_iterator_(DataIterator::Create(transaction_.get())),
- db_iterator_(
- transaction_->db_->CreateIterator(&transaction_->snapshot_)) {
+ db_iterator_(transaction_->db_->CreateIterator(
+ transaction_->db_->DefaultReadOptions(&transaction_->snapshot_))) {
transaction_->RegisterIterator(this);
}
diff --git a/chromium/content/browser/indexed_db/leveldb/leveldb_transaction_unittest.cc b/chromium/content/browser/indexed_db/leveldb/leveldb_transaction_unittest.cc
index 3428346eaed..373fe388ce6 100644
--- a/chromium/content/browser/indexed_db/leveldb/leveldb_transaction_unittest.cc
+++ b/chromium/content/browser/indexed_db/leveldb/leveldb_transaction_unittest.cc
@@ -11,7 +11,6 @@
#include "base/files/file.h"
#include "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/string_piece.h"
#include "content/browser/indexed_db/leveldb/leveldb_comparator.h"
#include "content/browser/indexed_db/leveldb/leveldb_database.h"
diff --git a/chromium/content/browser/indexed_db/list_set_unittest.cc b/chromium/content/browser/indexed_db/list_set_unittest.cc
index 615b547955a..e7dec0f078f 100644
--- a/chromium/content/browser/indexed_db/list_set_unittest.cc
+++ b/chromium/content/browser/indexed_db/list_set_unittest.cc
@@ -6,7 +6,6 @@
#include <memory>
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "testing/gtest/include/gtest/gtest.h"
diff --git a/chromium/content/browser/indexed_db/mock_browsertest_indexed_db_class_factory.h b/chromium/content/browser/indexed_db/mock_browsertest_indexed_db_class_factory.h
index 80e69e72b59..0c520868636 100644
--- a/chromium/content/browser/indexed_db/mock_browsertest_indexed_db_class_factory.h
+++ b/chromium/content/browser/indexed_db/mock_browsertest_indexed_db_class_factory.h
@@ -14,7 +14,7 @@
#include "content/browser/indexed_db/indexed_db_backing_store.h"
#include "content/browser/indexed_db/indexed_db_class_factory.h"
#include "content/browser/indexed_db/indexed_db_database.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBTypes.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_types.h"
namespace content {
diff --git a/chromium/content/browser/installedapp/installed_app_provider_impl_default.h b/chromium/content/browser/installedapp/installed_app_provider_impl_default.h
index 0eb589aed1c..dcd26cafba8 100644
--- a/chromium/content/browser/installedapp/installed_app_provider_impl_default.h
+++ b/chromium/content/browser/installedapp/installed_app_provider_impl_default.h
@@ -8,8 +8,8 @@
#include <string>
#include <vector>
-#include "third_party/WebKit/public/platform/modules/installedapp/installed_app_provider.mojom.h"
-#include "third_party/WebKit/public/platform/modules/installedapp/related_application.mojom.h"
+#include "third_party/blink/public/platform/modules/installedapp/installed_app_provider.mojom.h"
+#include "third_party/blink/public/platform/modules/installedapp/related_application.mojom.h"
namespace content {
diff --git a/chromium/content/browser/isolated_origin_browsertest.cc b/chromium/content/browser/isolated_origin_browsertest.cc
index befb2eb6bd3..eae2d0c881d 100644
--- a/chromium/content/browser/isolated_origin_browsertest.cc
+++ b/chromium/content/browser/isolated_origin_browsertest.cc
@@ -67,7 +67,7 @@ class IsolatedOriginTest : public ContentBrowserTest {
// Check that navigating a main frame from an non-isolated origin to an
// isolated origin and vice versa swaps processes and uses a new SiteInstance,
-// both for browser-initiated and renderer-initiated navigations.
+// both for renderer-initiated and browser-initiated navigations.
IN_PROC_BROWSER_TEST_F(IsolatedOriginTest, MainFrameNavigation) {
GURL unisolated_url(
embedded_test_server()->GetURL("www.foo.com", "/title1.html"));
@@ -83,42 +83,29 @@ IN_PROC_BROWSER_TEST_F(IsolatedOriginTest, MainFrameNavigation) {
RenderProcessHost* unisolated_process =
popup->web_contents()->GetMainFrame()->GetProcess();
- // Perform a browser-initiated navigation to an isolated origin and ensure
- // that this ends up in a new process and SiteInstance for isolated.foo.com.
- EXPECT_TRUE(NavigateToURL(shell(), isolated_url));
-
+ // Go to isolated.foo.com with a renderer-initiated navigation.
+ EXPECT_TRUE(NavigateToURLFromRenderer(web_contents(), isolated_url));
scoped_refptr<SiteInstance> isolated_instance =
web_contents()->GetSiteInstance();
- EXPECT_NE(isolated_instance, unisolated_instance);
- EXPECT_NE(web_contents()->GetMainFrame()->GetProcess(), unisolated_process);
+ EXPECT_EQ(isolated_instance, web_contents()->GetSiteInstance());
+ EXPECT_NE(unisolated_process, web_contents()->GetMainFrame()->GetProcess());
// The site URL for isolated.foo.com should be the full origin rather than
// scheme and eTLD+1.
EXPECT_EQ(isolated_url.GetOrigin(), isolated_instance->GetSiteURL());
- // Now perform a renderer-initiated navigation to an unisolated origin,
- // www.foo.com. This should end up in the |popup|'s process.
- {
- TestNavigationObserver observer(web_contents());
- EXPECT_TRUE(ExecuteScript(
- web_contents(), "location.href = '" + unisolated_url.spec() + "'"));
- observer.Wait();
- }
-
+ // Now use a renderer-initiated navigation to go to an unisolated origin,
+ // www.foo.com. This should end up back in the |popup|'s process.
+ EXPECT_TRUE(NavigateToURLFromRenderer(web_contents(), unisolated_url));
EXPECT_EQ(unisolated_instance, web_contents()->GetSiteInstance());
EXPECT_EQ(unisolated_process, web_contents()->GetMainFrame()->GetProcess());
- // Go to isolated.foo.com again, this time with a renderer-initiated
- // navigation from the unisolated www.foo.com.
- {
- TestNavigationObserver observer(web_contents());
- EXPECT_TRUE(ExecuteScript(web_contents(),
- "location.href = '" + isolated_url.spec() + "'"));
- observer.Wait();
- }
-
- EXPECT_EQ(isolated_instance, web_contents()->GetSiteInstance());
- EXPECT_NE(unisolated_process, web_contents()->GetMainFrame()->GetProcess());
+ // Now, perform a browser-initiated navigation to an isolated origin and
+ // ensure that this ends up in a new process and SiteInstance for
+ // isolated.foo.com.
+ EXPECT_TRUE(NavigateToURL(shell(), isolated_url));
+ EXPECT_NE(web_contents()->GetSiteInstance(), unisolated_instance);
+ EXPECT_NE(web_contents()->GetMainFrame()->GetProcess(), unisolated_process);
// Go back to www.foo.com: this should end up in the unisolated process.
{
@@ -144,14 +131,7 @@ IN_PROC_BROWSER_TEST_F(IsolatedOriginTest, MainFrameNavigation) {
// isolated origin and ensure there is a different isolated process.
GURL second_isolated_url(
embedded_test_server()->GetURL("isolated.bar.com", "/title3.html"));
- {
- TestNavigationObserver observer(web_contents());
- EXPECT_TRUE(
- ExecuteScript(web_contents(),
- "location.href = '" + second_isolated_url.spec() + "'"));
- observer.Wait();
- }
-
+ EXPECT_TRUE(NavigateToURLFromRenderer(web_contents(), second_isolated_url));
EXPECT_EQ(second_isolated_url.GetOrigin(),
web_contents()->GetSiteInstance()->GetSiteURL());
EXPECT_NE(isolated_instance, web_contents()->GetSiteInstance());
diff --git a/chromium/content/browser/keyboard_lock/keyboard_lock_service_impl.cc b/chromium/content/browser/keyboard_lock/keyboard_lock_service_impl.cc
index a5f583a3d84..d8bafd5dff6 100644
--- a/chromium/content/browser/keyboard_lock/keyboard_lock_service_impl.cc
+++ b/chromium/content/browser/keyboard_lock/keyboard_lock_service_impl.cc
@@ -7,10 +7,20 @@
#include <memory>
#include <utility>
-#include "base/memory/ptr_util.h"
+#include "base/bind.h"
+#include "base/callback.h"
+#include "base/containers/flat_set.h"
+#include "base/logging.h"
#include "base/metrics/histogram_macros.h"
+#include "base/optional.h"
+#include "content/browser/frame_host/render_frame_host_impl.h"
+#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/public/browser/render_frame_host.h"
-#include "content/public/browser/web_contents.h"
+#include "content/public/browser/render_widget_host.h"
+#include "content/public/common/content_features.h"
+#include "ui/events/keycodes/dom/keycode_converter.h"
+
+using blink::mojom::KeyboardLockRequestResult;
namespace content {
@@ -36,8 +46,8 @@ void LogKeyboardLockMethodCalled(KeyboardLockMethods method) {
KeyboardLockServiceImpl::KeyboardLockServiceImpl(
RenderFrameHost* render_frame_host)
- : web_contents_(WebContents::FromRenderFrameHost(render_frame_host)) {
- DCHECK(web_contents_);
+ : render_frame_host_(static_cast<RenderFrameHostImpl*>(render_frame_host)) {
+ DCHECK(render_frame_host_);
}
KeyboardLockServiceImpl::~KeyboardLockServiceImpl() = default;
@@ -59,14 +69,54 @@ void KeyboardLockServiceImpl::RequestKeyboardLock(
else
LogKeyboardLockMethodCalled(KeyboardLockMethods::kRequestSomeKeys);
- // TODO(joedow): Implementation required.
- std::move(callback).Run(blink::mojom::KeyboardLockRequestResult::SUCCESS);
+ if (!base::FeatureList::IsEnabled(features::kKeyboardLockAPI)) {
+ std::move(callback).Run(KeyboardLockRequestResult::kSuccess);
+ return;
+ }
+
+ if (!render_frame_host_->IsCurrent()) {
+ std::move(callback).Run(KeyboardLockRequestResult::kFrameDetachedError);
+ return;
+ }
+
+ if (render_frame_host_->GetParent()) {
+ std::move(callback).Run(KeyboardLockRequestResult::kChildFrameError);
+ return;
+ }
+
+ // Per base::flat_set usage notes, the proper way to init a flat_set is
+ // inserting into a vector and using that to init the flat_set.
+ std::vector<int> native_key_codes;
+ const int invalid_key_code = ui::KeycodeConverter::InvalidNativeKeycode();
+ for (const std::string& code : key_codes) {
+ int native_key_code = ui::KeycodeConverter::CodeStringToNativeKeycode(code);
+ if (native_key_code != invalid_key_code)
+ native_key_codes.push_back(native_key_code);
+ }
+
+ // If we are provided with a vector containing only invalid keycodes, then
+ // exit without enabling keyboard lock. An empty vector is treated as
+ // 'capture all keys' which is not what the caller intended.
+ if (!key_codes.empty() && native_key_codes.empty()) {
+ std::move(callback).Run(KeyboardLockRequestResult::kNoValidKeyCodesError);
+ return;
+ }
+
+ base::Optional<base::flat_set<int>> key_code_set;
+ if (!native_key_codes.empty())
+ key_code_set = std::move(native_key_codes);
+
+ render_frame_host_->GetRenderWidgetHost()->RequestKeyboardLock(
+ std::move(key_code_set));
+
+ std::move(callback).Run(KeyboardLockRequestResult::kSuccess);
}
void KeyboardLockServiceImpl::CancelKeyboardLock() {
LogKeyboardLockMethodCalled(KeyboardLockMethods::kCancelLock);
- // TODO(joedow): Implementation required.
+ if (base::FeatureList::IsEnabled(features::kKeyboardLockAPI))
+ render_frame_host_->GetRenderWidgetHost()->CancelKeyboardLock();
}
} // namespace content
diff --git a/chromium/content/browser/keyboard_lock/keyboard_lock_service_impl.h b/chromium/content/browser/keyboard_lock/keyboard_lock_service_impl.h
index e217d71c8ea..aafcbd92317 100644
--- a/chromium/content/browser/keyboard_lock/keyboard_lock_service_impl.h
+++ b/chromium/content/browser/keyboard_lock/keyboard_lock_service_impl.h
@@ -10,12 +10,12 @@
#include "content/common/content_export.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
-#include "third_party/WebKit/public/platform/modules/keyboard_lock/keyboard_lock.mojom.h"
+#include "third_party/blink/public/platform/modules/keyboard_lock/keyboard_lock.mojom.h"
namespace content {
class RenderFrameHost;
-class WebContents;
+class RenderFrameHostImpl;
class CONTENT_EXPORT KeyboardLockServiceImpl
: public blink::mojom::KeyboardLockService {
@@ -27,15 +27,15 @@ class CONTENT_EXPORT KeyboardLockServiceImpl
RenderFrameHost* render_frame_host,
blink::mojom::KeyboardLockServiceRequest request);
- // blink::mojom::KeyboardLockService implementations.
+ // blink::mojom::KeyboardLockService implementation.
void RequestKeyboardLock(const std::vector<std::string>& key_codes,
RequestKeyboardLockCallback callback) override;
void CancelKeyboardLock() override;
private:
- WebContents* const web_contents_;
+ RenderFrameHostImpl* const render_frame_host_;
};
-} // namespace
+} // namespace content
#endif // CONTENT_BROWSER_KEYBOARD_LOCK_KEYBOARD_LOCK_SERVICE_IMPL_H_
diff --git a/chromium/content/browser/keyboard_lock_browsertest.cc b/chromium/content/browser/keyboard_lock_browsertest.cc
new file mode 100644
index 00000000000..1279c21f547
--- /dev/null
+++ b/chromium/content/browser/keyboard_lock_browsertest.cc
@@ -0,0 +1,605 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include <vector>
+
+#include "base/macros.h"
+#include "base/test/scoped_feature_list.h"
+#include "build/build_config.h"
+#include "content/browser/renderer_host/render_widget_host_impl.h"
+#include "content/browser/web_contents/web_contents_impl.h"
+#include "content/public/common/content_features.h"
+#include "content/public/test/browser_test_utils.h"
+#include "content/public/test/content_browser_test.h"
+#include "content/public/test/content_browser_test_utils.h"
+#include "content/public/test/test_utils.h"
+#include "content/shell/browser/shell.h"
+#include "content/test/content_browser_test_utils_internal.h"
+#include "net/test/embedded_test_server/embedded_test_server.h"
+#include "ui/gfx/native_widget_types.h"
+
+#ifdef USE_AURA
+#include "content/browser/renderer_host/render_widget_host_view_aura.h"
+#include "content/browser/web_contents/web_contents_view_aura.h"
+#endif // USE_AURA
+
+namespace content {
+
+namespace {
+
+// TODO(joedow): Enable tests on additional platforms as they are implemented.
+#if defined(OS_WIN)
+#define MAYBE_RUN(test_name) test_name
+#else
+#define MAYBE_RUN(test_name) DISABLED_##test_name
+#endif
+
+constexpr char kFullscreenFrameName[] = "/fullscreen_frame.html";
+
+constexpr char kKeyboardLockMethodExistanceCheck[] =
+ "window.domAutomationController.send("
+ " (navigator.keyboard != undefined) &&"
+ " (navigator.keyboard.lock != undefined));";
+
+constexpr char kKeyboardLockMethodCallWithAllKeys[] =
+ "navigator.keyboard.lock().then("
+ " () => { window.domAutomationController.send(true); },"
+ " () => { window.domAutomationController.send(false); },"
+ ");";
+
+constexpr char kKeyboardLockMethodCallWithSomeKeys[] =
+ "navigator.keyboard.lock(['MetaLeft', 'Tab', 'AltLeft']).then("
+ " () => { window.domAutomationController.send(true); },"
+ " () => { window.domAutomationController.send(false); },"
+ ");";
+
+// Calling lock() with no valid key codes will cause the promise to be rejected.
+constexpr char kKeyboardLockMethodCallWithAllInvalidKeys[] =
+ "navigator.keyboard.lock(['BlerghLeft', 'BlarghRight']).then("
+ " () => { window.domAutomationController.send(false); },"
+ " () => { window.domAutomationController.send(true); },"
+ ");";
+
+constexpr char kKeyboardLockMethodCallWithSomeInvalidKeys[] =
+ "navigator.keyboard.lock(['Tab', 'BlarghTab', 'Space', 'BlerghLeft']).then("
+ " () => { window.domAutomationController.send(true); },"
+ " () => { window.domAutomationController.send(false); },"
+ ");";
+
+constexpr char kKeyboardUnlockMethodCall[] = "navigator.keyboard.unlock()";
+
+bool g_window_has_focus = false;
+
+#if defined(USE_AURA)
+class TestRenderWidgetHostView : public RenderWidgetHostViewAura {
+ public:
+ TestRenderWidgetHostView(RenderWidgetHost* host, bool is_guest_view_hack)
+ : RenderWidgetHostViewAura(host,
+ is_guest_view_hack,
+ false /* is_mus_browser_plugin_guest */) {}
+ ~TestRenderWidgetHostView() override {}
+
+ bool HasFocus() const override { return g_window_has_focus; }
+
+ void OnWindowFocused(aura::Window* gained_focus,
+ aura::Window* lost_focus) override {
+ // Ignore all focus events.
+ }
+};
+
+void InstallCreateHooksForKeyboardLockBrowserTests() {
+ WebContentsViewAura::InstallCreateHookForTests(
+ [](RenderWidgetHost* host,
+ bool is_guest_view_hack) -> RenderWidgetHostViewAura* {
+ return new TestRenderWidgetHostView(host, is_guest_view_hack);
+ });
+}
+#endif // USE_AURA
+
+class FakeKeyboardLockWebContentsDelegate : public WebContentsDelegate {
+ public:
+ FakeKeyboardLockWebContentsDelegate() {}
+ ~FakeKeyboardLockWebContentsDelegate() override {}
+
+ // WebContentsDelegate overrides.
+ void EnterFullscreenModeForTab(WebContents* web_contents,
+ const GURL& origin) override;
+ void ExitFullscreenModeForTab(WebContents* web_contents) override;
+ bool IsFullscreenForTabOrPending(
+ const WebContents* web_contents) const override;
+ void RequestKeyboardLock(WebContents* web_contents,
+ bool esc_key_locked) override;
+ void CancelKeyboardLockRequest(WebContents* web_contents) override;
+
+ private:
+ bool is_fullscreen_ = false;
+ bool keyboard_lock_requested_ = false;
+
+ DISALLOW_COPY_AND_ASSIGN(FakeKeyboardLockWebContentsDelegate);
+};
+
+void FakeKeyboardLockWebContentsDelegate::EnterFullscreenModeForTab(
+ WebContents* web_contents,
+ const GURL& origin) {
+ is_fullscreen_ = true;
+ if (keyboard_lock_requested_)
+ web_contents->GotResponseToKeyboardLockRequest(/*allowed=*/true);
+}
+
+void FakeKeyboardLockWebContentsDelegate::ExitFullscreenModeForTab(
+ WebContents* web_contents) {
+ is_fullscreen_ = false;
+ if (keyboard_lock_requested_)
+ web_contents->GotResponseToKeyboardLockRequest(/*allowed=*/false);
+}
+
+bool FakeKeyboardLockWebContentsDelegate::IsFullscreenForTabOrPending(
+ const WebContents* web_contents) const {
+ return is_fullscreen_;
+}
+
+void FakeKeyboardLockWebContentsDelegate::RequestKeyboardLock(
+ WebContents* web_contents,
+ bool esc_key_locked) {
+ keyboard_lock_requested_ = true;
+ if (is_fullscreen_)
+ web_contents->GotResponseToKeyboardLockRequest(/*allowed=*/true);
+}
+
+void FakeKeyboardLockWebContentsDelegate::CancelKeyboardLockRequest(
+ WebContents* web_contents) {
+ keyboard_lock_requested_ = false;
+}
+
+} // namespace
+
+class KeyboardLockBrowserTest : public ContentBrowserTest {
+ public:
+ KeyboardLockBrowserTest();
+ ~KeyboardLockBrowserTest() override;
+
+ protected:
+ // ContentBrowserTest overrides.
+ void SetUp() override;
+ void SetUpCommandLine(base::CommandLine* command_line) override;
+ void SetUpOnMainThread() override;
+
+ virtual void SetUpFeatureList();
+
+ // Helper methods for common tasks.
+ bool KeyboardLockApiExists();
+ void NavigateToTestURL();
+ void RequestKeyboardLock(const base::Location& from_here,
+ bool lock_all_keys = true);
+ void CancelKeyboardLock(const base::Location& from_here);
+ void EnterFullscreen(const base::Location& from_here);
+ void ExitFullscreen(const base::Location& from_here);
+ void FocusContent(const base::Location& from_here);
+ void BlurContent(const base::Location& from_here);
+ void VerifyKeyboardLockState(const base::Location& from_here);
+
+ WebContentsImpl* web_contents() const {
+ return static_cast<WebContentsImpl*>(shell()->web_contents());
+ }
+
+ net::EmbeddedTestServer* https_test_server() { return &https_test_server_; }
+
+ GURL https_fullscreen_frame() {
+ return https_test_server()->GetURL(kFullscreenFrameName);
+ }
+
+ base::test::ScopedFeatureList* feature_list() {
+ return &scoped_feature_list_;
+ }
+
+ private:
+ base::test::ScopedFeatureList scoped_feature_list_;
+ net::EmbeddedTestServer https_test_server_;
+ FakeKeyboardLockWebContentsDelegate web_contents_delegate_;
+};
+
+KeyboardLockBrowserTest::KeyboardLockBrowserTest()
+ : https_test_server_(net::EmbeddedTestServer::TYPE_HTTPS) {}
+
+KeyboardLockBrowserTest::~KeyboardLockBrowserTest() = default;
+
+void KeyboardLockBrowserTest::SetUp() {
+ // Assume we have focus to start with.
+ g_window_has_focus = true;
+#if defined(USE_AURA)
+ InstallCreateHooksForKeyboardLockBrowserTests();
+#endif
+ SetUpFeatureList();
+ ContentBrowserTest::SetUp();
+}
+
+void KeyboardLockBrowserTest::SetUpCommandLine(
+ base::CommandLine* command_line) {
+ IsolateAllSitesForTesting(command_line);
+}
+
+void KeyboardLockBrowserTest::SetUpOnMainThread() {
+ web_contents()->SetDelegate(&web_contents_delegate_);
+
+ // KeyboardLock requires a secure context (HTTPS).
+ https_test_server()->AddDefaultHandlers(
+ base::FilePath(FILE_PATH_LITERAL("content/test/data")));
+ ASSERT_TRUE(https_test_server()->Start());
+}
+
+void KeyboardLockBrowserTest::SetUpFeatureList() {
+ feature_list()->InitAndEnableFeature(features::kKeyboardLockAPI);
+}
+
+bool KeyboardLockBrowserTest::KeyboardLockApiExists() {
+ bool api_exists = false;
+ EXPECT_TRUE(ExecuteScriptAndExtractBool(
+ web_contents(), kKeyboardLockMethodExistanceCheck, &api_exists));
+ return api_exists;
+}
+
+void KeyboardLockBrowserTest::NavigateToTestURL() {
+ ASSERT_TRUE(NavigateToURL(shell(), https_fullscreen_frame()));
+
+ ASSERT_TRUE(KeyboardLockApiExists());
+
+ // Ensure the window has focus and is in windowed mode after the navigation.
+ FocusContent(FROM_HERE);
+ ExitFullscreen(FROM_HERE);
+}
+
+void KeyboardLockBrowserTest::RequestKeyboardLock(
+ const base::Location& from_here,
+ bool lock_all_keys /*=true*/) {
+ bool result;
+ // keyboardLock() is an async call which requires a promise handling dance.
+ ASSERT_TRUE(ExecuteScriptAndExtractBool(
+ web_contents(),
+ lock_all_keys ? kKeyboardLockMethodCallWithAllKeys
+ : kKeyboardLockMethodCallWithSomeKeys,
+ &result))
+ << "Location: " << from_here.ToString();
+
+ ASSERT_TRUE(result) << "Location: " << from_here.ToString();
+
+ ASSERT_EQ(result, web_contents()->GetKeyboardLockWidget() != nullptr)
+ << "Location: " << from_here.ToString();
+
+ VerifyKeyboardLockState(from_here);
+}
+
+void KeyboardLockBrowserTest::CancelKeyboardLock(
+ const base::Location& from_here) {
+ // keyboardUnlock() is a synchronous call.
+ ASSERT_TRUE(ExecuteScript(web_contents(), kKeyboardUnlockMethodCall));
+
+ ASSERT_EQ(nullptr, web_contents()->GetKeyboardLockWidget())
+ << "Location: " << from_here.ToString();
+
+ VerifyKeyboardLockState(from_here);
+}
+
+void KeyboardLockBrowserTest::EnterFullscreen(const base::Location& from_here) {
+ web_contents()->EnterFullscreenMode(https_fullscreen_frame());
+
+ ASSERT_TRUE(web_contents()->IsFullscreenForCurrentTab())
+ << "Location: " << from_here.ToString();
+
+ VerifyKeyboardLockState(from_here);
+}
+
+void KeyboardLockBrowserTest::ExitFullscreen(const base::Location& from_here) {
+ web_contents()->ExitFullscreenMode(/*should_resize=*/true);
+
+ ASSERT_FALSE(web_contents()->IsFullscreenForCurrentTab())
+ << "Location: " << from_here.ToString();
+
+ VerifyKeyboardLockState(from_here);
+}
+
+void KeyboardLockBrowserTest::FocusContent(const base::Location& from_here) {
+ g_window_has_focus = true;
+ RenderWidgetHostImpl* host = RenderWidgetHostImpl::From(
+ web_contents()->GetRenderWidgetHostView()->GetRenderWidgetHost());
+ host->GotFocus();
+ host->SetActive(true);
+
+ ASSERT_TRUE(web_contents()->GetRenderWidgetHostView()->HasFocus())
+ << "Location: " << from_here.ToString();
+
+ VerifyKeyboardLockState(from_here);
+}
+
+void KeyboardLockBrowserTest::BlurContent(const base::Location& from_here) {
+ g_window_has_focus = false;
+ RenderWidgetHostImpl* host = RenderWidgetHostImpl::From(
+ web_contents()->GetRenderWidgetHostView()->GetRenderWidgetHost());
+ host->SetActive(false);
+ host->LostFocus();
+
+ ASSERT_FALSE(web_contents()->GetRenderWidgetHostView()->HasFocus())
+ << "Location: " << from_here.ToString();
+
+ VerifyKeyboardLockState(from_here);
+}
+
+void KeyboardLockBrowserTest::VerifyKeyboardLockState(
+ const base::Location& from_here) {
+ bool keyboard_lock_requested = !!web_contents()->GetKeyboardLockWidget();
+
+ bool ux_conditions_satisfied =
+ web_contents()->GetRenderWidgetHostView()->HasFocus() &&
+ web_contents()->IsFullscreenForCurrentTab();
+
+ bool keyboard_lock_active =
+ web_contents()->GetRenderWidgetHostView()->IsKeyboardLocked();
+
+ // Keyboard lock only active when requested and the UX is in the right state.
+ ASSERT_EQ(keyboard_lock_active,
+ ux_conditions_satisfied && keyboard_lock_requested)
+ << "Location: " << from_here.ToString();
+}
+
+class KeyboardLockDisabledBrowserTest : public KeyboardLockBrowserTest {
+ public:
+ KeyboardLockDisabledBrowserTest() = default;
+ ~KeyboardLockDisabledBrowserTest() override = default;
+
+ protected:
+ // KeyboardLockBrowserTest override.
+ void SetUpFeatureList() override;
+};
+
+void KeyboardLockDisabledBrowserTest::SetUpFeatureList() {
+ feature_list()->InitAndDisableFeature(features::kKeyboardLockAPI);
+}
+
+IN_PROC_BROWSER_TEST_F(KeyboardLockBrowserTest, MAYBE_RUN(SingleLockCall)) {
+ NavigateToTestURL();
+ RequestKeyboardLock(FROM_HERE);
+ // Don't explicitly call CancelKeyboardLock().
+}
+
+IN_PROC_BROWSER_TEST_F(KeyboardLockBrowserTest,
+ MAYBE_RUN(SingleLockCallForSomeKeys)) {
+ NavigateToTestURL();
+ RequestKeyboardLock(FROM_HERE, /*lock_all_keys=*/false);
+ // Don't explicitly call CancelKeyboardLock().
+}
+
+IN_PROC_BROWSER_TEST_F(KeyboardLockBrowserTest,
+ MAYBE_RUN(SingleLockWithCancelCall)) {
+ NavigateToTestURL();
+ RequestKeyboardLock(FROM_HERE);
+ CancelKeyboardLock(FROM_HERE);
+}
+
+IN_PROC_BROWSER_TEST_F(KeyboardLockBrowserTest,
+ MAYBE_RUN(LockCalledBeforeFullscreen)) {
+ NavigateToTestURL();
+ RequestKeyboardLock(FROM_HERE);
+ EnterFullscreen(FROM_HERE);
+}
+
+IN_PROC_BROWSER_TEST_F(KeyboardLockBrowserTest,
+ MAYBE_RUN(LockCalledAfterFullscreen)) {
+ NavigateToTestURL();
+ EnterFullscreen(FROM_HERE);
+ RequestKeyboardLock(FROM_HERE);
+}
+
+IN_PROC_BROWSER_TEST_F(KeyboardLockBrowserTest,
+ MAYBE_RUN(LockAndCancelCyclingNoActivation)) {
+ NavigateToTestURL();
+
+ RequestKeyboardLock(FROM_HERE);
+ CancelKeyboardLock(FROM_HERE);
+ RequestKeyboardLock(FROM_HERE, /*lock_all_keys=*/false);
+ CancelKeyboardLock(FROM_HERE);
+ RequestKeyboardLock(FROM_HERE);
+ CancelKeyboardLock(FROM_HERE);
+ RequestKeyboardLock(FROM_HERE);
+ CancelKeyboardLock(FROM_HERE);
+}
+
+IN_PROC_BROWSER_TEST_F(KeyboardLockBrowserTest,
+ MAYBE_RUN(LockAndCancelCyclingInFullscreen)) {
+ NavigateToTestURL();
+
+ EnterFullscreen(FROM_HERE);
+
+ RequestKeyboardLock(FROM_HERE);
+ CancelKeyboardLock(FROM_HERE);
+ RequestKeyboardLock(FROM_HERE, /*lock_all_keys=*/false);
+ CancelKeyboardLock(FROM_HERE);
+ RequestKeyboardLock(FROM_HERE, /*lock_all_keys=*/false);
+ CancelKeyboardLock(FROM_HERE);
+ RequestKeyboardLock(FROM_HERE);
+ CancelKeyboardLock(FROM_HERE);
+ RequestKeyboardLock(FROM_HERE);
+ CancelKeyboardLock(FROM_HERE);
+}
+
+IN_PROC_BROWSER_TEST_F(KeyboardLockBrowserTest, MAYBE_RUN(CancelInFullscreen)) {
+ NavigateToTestURL();
+
+ RequestKeyboardLock(FROM_HERE);
+ EnterFullscreen(FROM_HERE);
+ CancelKeyboardLock(FROM_HERE);
+ ExitFullscreen(FROM_HERE);
+}
+
+IN_PROC_BROWSER_TEST_F(KeyboardLockBrowserTest,
+ MAYBE_RUN(EnterAndExitFullscreenCycling)) {
+ NavigateToTestURL();
+
+ RequestKeyboardLock(FROM_HERE);
+
+ EnterFullscreen(FROM_HERE);
+ ExitFullscreen(FROM_HERE);
+ EnterFullscreen(FROM_HERE);
+ ExitFullscreen(FROM_HERE);
+ EnterFullscreen(FROM_HERE);
+ ExitFullscreen(FROM_HERE);
+ EnterFullscreen(FROM_HERE);
+ ExitFullscreen(FROM_HERE);
+}
+
+IN_PROC_BROWSER_TEST_F(KeyboardLockBrowserTest,
+ MAYBE_RUN(GainAndLoseFocusInWindowMode)) {
+ NavigateToTestURL();
+
+ RequestKeyboardLock(FROM_HERE);
+
+ FocusContent(FROM_HERE);
+ BlurContent(FROM_HERE);
+ FocusContent(FROM_HERE);
+ BlurContent(FROM_HERE);
+}
+
+IN_PROC_BROWSER_TEST_F(KeyboardLockBrowserTest,
+ MAYBE_RUN(EnterFullscreenWithoutFocus)) {
+ NavigateToTestURL();
+
+ RequestKeyboardLock(FROM_HERE);
+
+ BlurContent(FROM_HERE);
+ EnterFullscreen(FROM_HERE);
+ ExitFullscreen(FROM_HERE);
+
+ EnterFullscreen(FROM_HERE);
+ FocusContent(FROM_HERE);
+}
+
+IN_PROC_BROWSER_TEST_F(KeyboardLockBrowserTest,
+ MAYBE_RUN(GainAndLoseFocusCyclingInFullscreen)) {
+ NavigateToTestURL();
+
+ RequestKeyboardLock(FROM_HERE);
+
+ BlurContent(FROM_HERE);
+ EnterFullscreen(FROM_HERE);
+
+ FocusContent(FROM_HERE);
+ BlurContent(FROM_HERE);
+ FocusContent(FROM_HERE);
+ BlurContent(FROM_HERE);
+ FocusContent(FROM_HERE);
+ BlurContent(FROM_HERE);
+ FocusContent(FROM_HERE);
+ BlurContent(FROM_HERE);
+
+ ExitFullscreen(FROM_HERE);
+}
+
+IN_PROC_BROWSER_TEST_F(KeyboardLockBrowserTest, MAYBE_RUN(CancelWithoutLock)) {
+ NavigateToTestURL();
+ CancelKeyboardLock(FROM_HERE);
+ CancelKeyboardLock(FROM_HERE);
+}
+
+IN_PROC_BROWSER_TEST_F(KeyboardLockBrowserTest, MAYBE_RUN(MultipleLockCalls)) {
+ NavigateToTestURL();
+
+ RequestKeyboardLock(FROM_HERE);
+ RequestKeyboardLock(FROM_HERE);
+ RequestKeyboardLock(FROM_HERE);
+}
+
+IN_PROC_BROWSER_TEST_F(KeyboardLockBrowserTest,
+ MAYBE_RUN(MultipleCancelCalls)) {
+ NavigateToTestURL();
+
+ RequestKeyboardLock(FROM_HERE);
+
+ CancelKeyboardLock(FROM_HERE);
+ CancelKeyboardLock(FROM_HERE);
+ CancelKeyboardLock(FROM_HERE);
+}
+
+IN_PROC_BROWSER_TEST_F(KeyboardLockBrowserTest,
+ MAYBE_RUN(LockCallWithAllInvalidKeys)) {
+ NavigateToTestURL();
+
+ bool result;
+ ASSERT_TRUE(ExecuteScriptAndExtractBool(
+ web_contents(), kKeyboardLockMethodCallWithAllInvalidKeys, &result));
+ ASSERT_TRUE(result);
+
+ // If no valid Keys are passed in, then KeyboardLock will not be requested.
+ ASSERT_EQ(nullptr, web_contents()->GetKeyboardLockWidget());
+
+ EnterFullscreen(FROM_HERE);
+}
+
+IN_PROC_BROWSER_TEST_F(KeyboardLockBrowserTest,
+ MAYBE_RUN(LockCallWithSomeInvalidKeys)) {
+ NavigateToTestURL();
+
+ bool result;
+ ASSERT_TRUE(ExecuteScriptAndExtractBool(
+ web_contents(), kKeyboardLockMethodCallWithSomeInvalidKeys, &result));
+ ASSERT_TRUE(result);
+
+ // If some valid Keys are passed in, then KeyboardLock will be requested.
+ ASSERT_NE(nullptr, web_contents()->GetKeyboardLockWidget());
+
+ EnterFullscreen(FROM_HERE);
+}
+
+IN_PROC_BROWSER_TEST_F(KeyboardLockDisabledBrowserTest,
+ MAYBE_RUN(NoKeyboardLockWhenDisabled)) {
+ ASSERT_TRUE(NavigateToURL(shell(), https_fullscreen_frame()));
+ ASSERT_FALSE(KeyboardLockApiExists());
+}
+
+IN_PROC_BROWSER_TEST_F(KeyboardLockBrowserTest,
+ MAYBE_RUN(KeyboardLockNotAllowedForIFrame)) {
+ // TODO(joedow): IMPLEMENT.
+}
+
+IN_PROC_BROWSER_TEST_F(KeyboardLockBrowserTest,
+ MAYBE_RUN(KeyboardUnlockedWhenNavigatingAway)) {
+ // TODO(joedow): IMPLEMENT.
+}
+
+IN_PROC_BROWSER_TEST_F(KeyboardLockBrowserTest,
+ MAYBE_RUN(CrossOriginIFrameDoesNotReceiveInput)) {
+ // TODO(joedow): Added per code review feedback.
+ // Steps: Main frame initiates keyboard lock and goes fullscreen. Is input
+ // delivered to cross-origin iFrame?
+}
+
+IN_PROC_BROWSER_TEST_F(KeyboardLockBrowserTest,
+ MAYBE_RUN(CrossOriginIFrameRequestsFullscreen)) {
+ // TODO(joedow): Added per code review feedback.
+ // Steps: Main frame requests keyboard lock, cross-origin iFrame goes
+ // fullscreen. Should KeyboardLock be triggered in that case (presumably no).
+}
+
+IN_PROC_BROWSER_TEST_F(KeyboardLockBrowserTest,
+ MAYBE_RUN(LockRequestWhileIFrameIsFullscreen)) {
+ // TODO(joedow): Added per code review feedback.
+ // Steps: 1. Load a page with a cross-site iframe: call main frame "A" and the
+ // subframe "B"
+ // 2. B goes fullscreen.
+ // 3. A initiates keyboard lock.
+}
+
+IN_PROC_BROWSER_TEST_F(KeyboardLockBrowserTest,
+ MAYBE_RUN(LockRequestFailsFromInnerWebContents)) {
+ // TODO(joedow): Added per code review feedback.
+ // Steps: Try requesting KeyboardLock from with an inner WebContents context.
+ // See: CreateAndAttachInnerContents() helper method in
+ // https://cs.chromium.org/chromium/src/content/public/test/test_utils.h
+}
+
+IN_PROC_BROWSER_TEST_F(KeyboardLockBrowserTest, MAYBE_RUN(HistogramTest)) {
+ // TODO(joedow): Added per code review feedback.
+ // Steps: Call the API methods and verify the histogram data is accurate using
+ // base::HistogramTester. Alternatively, this could be integrated with the
+ // test fixture as well. window_open_apitest.cc (line 317()) is an example.
+}
+
+} // namespace content
diff --git a/chromium/content/browser/leveldb_wrapper_impl.cc b/chromium/content/browser/leveldb_wrapper_impl.cc
index d5173bf1ad1..c17743445aa 100644
--- a/chromium/content/browser/leveldb_wrapper_impl.cc
+++ b/chromium/content/browser/leveldb_wrapper_impl.cc
@@ -6,12 +6,11 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/trace_event/memory_dump_manager.h"
#include "base/trace_event/process_memory_dump.h"
-#include "components/leveldb/public/cpp/util.h"
+#include "components/services/leveldb/public/cpp/util.h"
#include "content/public/browser/browser_thread.h"
namespace content {
@@ -63,7 +62,17 @@ LevelDBWrapperImpl::LevelDBWrapperImpl(
const std::string& prefix,
Delegate* delegate,
const Options& options)
- : prefix_(leveldb::StdStringToUint8Vector(prefix)),
+ : LevelDBWrapperImpl(database,
+ leveldb::StdStringToUint8Vector(prefix),
+ delegate,
+ options) {}
+
+LevelDBWrapperImpl::LevelDBWrapperImpl(
+ leveldb::mojom::LevelDBDatabase* database,
+ std::vector<uint8_t> prefix,
+ Delegate* delegate,
+ const Options& options)
+ : prefix_(std::move(prefix)),
delegate_(delegate),
database_(database),
cache_mode_(database ? options.cache_mode : CacheMode::KEYS_AND_VALUES),
@@ -105,8 +114,16 @@ std::unique_ptr<LevelDBWrapperImpl> LevelDBWrapperImpl::ForkToNewPrefix(
const std::string& new_prefix,
Delegate* delegate,
const Options& options) {
+ return ForkToNewPrefix(leveldb::StdStringToUint8Vector(new_prefix), delegate,
+ options);
+}
+
+std::unique_ptr<LevelDBWrapperImpl> LevelDBWrapperImpl::ForkToNewPrefix(
+ std::vector<uint8_t> new_prefix,
+ Delegate* delegate,
+ const Options& options) {
auto forked_wrapper = std::make_unique<LevelDBWrapperImpl>(
- database_, new_prefix, delegate, options);
+ database_, std::move(new_prefix), delegate, options);
forked_wrapper->map_state_ = MapState::LOADING_FROM_FORK;
@@ -196,13 +213,25 @@ void LevelDBWrapperImpl::SetCacheModeForTesting(CacheMode cache_mode) {
SetCacheMode(cache_mode);
}
+mojo::InterfacePtrSetElementId LevelDBWrapperImpl::AddObserver(
+ mojom::LevelDBObserverAssociatedPtr observer) {
+ if (cache_mode_ == CacheMode::KEYS_AND_VALUES)
+ observer->ShouldSendOldValueOnMutations(false);
+ return observers_.AddPtr(std::move(observer));
+}
+
+bool LevelDBWrapperImpl::HasObserver(mojo::InterfacePtrSetElementId id) {
+ return observers_.HasPtr(id);
+}
+
+mojom::LevelDBObserverAssociatedPtr LevelDBWrapperImpl::RemoveObserver(
+ mojo::InterfacePtrSetElementId id) {
+ return observers_.RemovePtr(id);
+}
+
void LevelDBWrapperImpl::AddObserver(
mojom::LevelDBObserverAssociatedPtrInfo observer) {
- mojom::LevelDBObserverAssociatedPtr observer_ptr;
- observer_ptr.Bind(std::move(observer));
- if (cache_mode_ == CacheMode::KEYS_AND_VALUES)
- observer_ptr->ShouldSendOldValueOnMutations(false);
- observers_.AddPtr(std::move(observer_ptr));
+ AddObserver(mojom::LevelDBObserverAssociatedPtr(std::move(observer)));
}
void LevelDBWrapperImpl::Put(
@@ -724,7 +753,6 @@ void LevelDBWrapperImpl::CommitChanges() {
bool has_changes = !operations.empty() ||
!commit_batch_->changed_values.empty() ||
!commit_batch_->changed_keys.empty();
-
if (commit_batch_->clear_all_first) {
BatchedOperationPtr item = BatchedOperation::New();
item->type = leveldb::mojom::BatchOperationType::DELETE_PREFIXED_KEY;
diff --git a/chromium/content/browser/leveldb_wrapper_impl.h b/chromium/content/browser/leveldb_wrapper_impl.h
index bf6855d2d04..e120d20acfa 100644
--- a/chromium/content/browser/leveldb_wrapper_impl.h
+++ b/chromium/content/browser/leveldb_wrapper_impl.h
@@ -87,12 +87,17 @@ class CONTENT_EXPORT LevelDBWrapperImpl : public mojom::LevelDBWrapper {
int max_commits_per_hour = 0;
};
- // |no_bindings_callback| will be called when this object has no more
+ // |Delegate::OnNoBindings| will be called when this object has no more
// bindings and all pending modifications have been processed.
LevelDBWrapperImpl(leveldb::mojom::LevelDBDatabase* database,
const std::string& prefix,
Delegate* delegate,
const Options& options);
+ LevelDBWrapperImpl(leveldb::mojom::LevelDBDatabase* database,
+ std::vector<uint8_t> prefix,
+ Delegate* delegate,
+ const Options& options);
+
~LevelDBWrapperImpl() override;
void Bind(mojom::LevelDBWrapperRequest request);
@@ -104,6 +109,10 @@ class CONTENT_EXPORT LevelDBWrapperImpl : public mojom::LevelDBWrapper {
const std::string& new_prefix,
Delegate* delegate,
const Options& options);
+ std::unique_ptr<LevelDBWrapperImpl> ForkToNewPrefix(
+ std::vector<uint8_t> new_prefix,
+ Delegate* delegate,
+ const Options& options);
// Cancels all pending load tasks. Useful for emergency destructions. If the
// wrapper is unloaded (initialized() returns false), this will DROP all
@@ -132,6 +141,8 @@ class CONTENT_EXPORT LevelDBWrapperImpl : public mojom::LevelDBWrapper {
const std::vector<uint8_t>& prefix() { return prefix_; }
+ leveldb::mojom::LevelDBDatabase* database() { return database_; }
+
// Commence aggressive flushing. This should be called early during startup,
// before any localStorage writing. Currently scheduled writes will not be
// rescheduled and will be flushed at the scheduled time after which
@@ -156,6 +167,13 @@ class CONTENT_EXPORT LevelDBWrapperImpl : public mojom::LevelDBWrapper {
// SetCacheMode().
void SetCacheModeForTesting(CacheMode cache_mode);
+ // Returns a pointer ID for use with HasObserver and RemoveObserver.
+ mojo::InterfacePtrSetElementId AddObserver(
+ mojom::LevelDBObserverAssociatedPtr observer);
+ bool HasObserver(mojo::InterfacePtrSetElementId id);
+ mojom::LevelDBObserverAssociatedPtr RemoveObserver(
+ mojo::InterfacePtrSetElementId id);
+
// LevelDBWrapper:
void AddObserver(mojom::LevelDBObserverAssociatedPtrInfo observer) override;
void Put(const std::vector<uint8_t>& key,
diff --git a/chromium/content/browser/leveldb_wrapper_impl_unittest.cc b/chromium/content/browser/leveldb_wrapper_impl_unittest.cc
index 59624ee1269..5e63e99a0f7 100644
--- a/chromium/content/browser/leveldb_wrapper_impl_unittest.cc
+++ b/chromium/content/browser/leveldb_wrapper_impl_unittest.cc
@@ -13,8 +13,8 @@
#include "base/task_scheduler/post_task.h"
#include "base/test/test_simple_task_runner.h"
#include "base/threading/thread.h"
-#include "components/leveldb/public/cpp/util.h"
-#include "components/leveldb/public/interfaces/leveldb.mojom.h"
+#include "components/services/leveldb/public/cpp/util.h"
+#include "components/services/leveldb/public/interfaces/leveldb.mojom.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "content/test/fake_leveldb_database.h"
#include "mojo/public/cpp/bindings/associated_binding.h"
diff --git a/chromium/content/browser/linux_ipc_browsertest.cc b/chromium/content/browser/linux_ipc_browsertest.cc
index 8f917dfdf72..0654dff6924 100644
--- a/chromium/content/browser/linux_ipc_browsertest.cc
+++ b/chromium/content/browser/linux_ipc_browsertest.cc
@@ -16,7 +16,6 @@
#include "testing/gmock/include/gmock/gmock-matchers.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "ui/gfx/test/fontconfig_util_linux.h"
namespace content {
@@ -25,7 +24,6 @@ class LinuxIPCBrowserTest : public ContentBrowserTest,
public testing::WithParamInterface<std::string> {
public:
LinuxIPCBrowserTest() {
- SetUpFontConfigForTest();
SandboxIPCHandler::SetObserverForTests(this);
}
~LinuxIPCBrowserTest() override {}
@@ -39,16 +37,6 @@ class LinuxIPCBrowserTest : public ContentBrowserTest,
}
}
- // Override the system fontconfig configuration with a test configuration so
- // that the tested font fallback will work the same across systems.
- void SetUpFontConfigForTest() {
- gfx::SetUpFontconfig();
- for (size_t i = 0; i < gfx::kNumSystemFontsForFontconfig; ++i) {
- gfx::LoadFontIntoFontconfig(
- base::FilePath(gfx::kSystemFontsForFontconfig[i]));
- }
- }
-
void OnFontOpen(int id) override {
base::AutoLock lock(lock_);
opened_fonts_.insert(font_names_[id]);
diff --git a/chromium/content/browser/loader/OWNERS b/chromium/content/browser/loader/OWNERS
index 466c50011c4..42dffa71fa4 100644
--- a/chromium/content/browser/loader/OWNERS
+++ b/chromium/content/browser/loader/OWNERS
@@ -1,6 +1,5 @@
csharrison@chromium.org
mmenke@chromium.org
-rdsmith@chromium.org
yhirano@chromium.org
# TEAM: net-dev@chromium.org
diff --git a/chromium/content/browser/loader/cors_file_origin_browsertest.cc b/chromium/content/browser/loader/cors_file_origin_browsertest.cc
new file mode 100644
index 00000000000..5bd57848cbc
--- /dev/null
+++ b/chromium/content/browser/loader/cors_file_origin_browsertest.cc
@@ -0,0 +1,211 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "base/bind.h"
+#include "base/bind_helpers.h"
+#include "base/command_line.h"
+#include "base/files/file_path.h"
+#include "base/macros.h"
+#include "base/path_service.h"
+#include "base/strings/string16.h"
+#include "base/strings/stringprintf.h"
+#include "base/strings/utf_string_conversions.h"
+#include "base/synchronization/waitable_event.h"
+#include "content/public/common/content_paths.h"
+#include "content/public/test/browser_test_utils.h"
+#include "content/public/test/content_browser_test.h"
+#include "content/public/test/content_browser_test_utils.h"
+#include "content/shell/browser/shell.h"
+#include "net/http/http_request_headers.h"
+#include "net/http/http_status_code.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 "net/test/embedded_test_server/request_handler_util.h"
+#include "services/network/public/cpp/cors/cors.h"
+#include "testing/gtest/include/gtest/gtest.h"
+#include "url/gurl.h"
+
+namespace content {
+
+namespace {
+
+using net::test_server::BasicHttpResponse;
+using net::test_server::HttpRequest;
+using net::test_server::HttpResponse;
+
+// Tests end to end Origin header and CORS check behaviors without
+// --allow-file-access-from-files flag.
+class CORSFileOriginBrowserTest : public ContentBrowserTest {
+ public:
+ CORSFileOriginBrowserTest()
+ : pass_string_(base::ASCIIToUTF16("PASS")),
+ fail_string_(base::ASCIIToUTF16("FAIL")) {}
+ ~CORSFileOriginBrowserTest() override = default;
+
+ protected:
+ GURL CreateTestDataURL(const std::string& relative_path) {
+ base::AutoLock lock(lock_);
+ base::FilePath path(test_data_loader_path_);
+ path = path.AppendASCII(relative_path);
+ // This is wrong if developers checkout the source code in a path that
+ // contains non-ASCII characters to run the browser tests.
+ std::string url = "file://" + path.MaybeAsASCII();
+ return GURL(url);
+ }
+
+ std::unique_ptr<TitleWatcher> CreateWatcher() {
+ // Register all possible result strings here.
+ std::unique_ptr<TitleWatcher> watcher =
+ std::make_unique<TitleWatcher>(shell()->web_contents(), pass_string());
+ watcher->AlsoWaitForTitle(fail_string());
+
+ // Does not appear in the expectations, but the title can be on unexpected
+ // failures.
+ base::string16 wrong_origin_string =
+ base::ASCIIToUTF16("FAIL: request origin does not match");
+ watcher->AlsoWaitForTitle(wrong_origin_string);
+ return watcher;
+ }
+
+ const base::string16& pass_string() const { return pass_string_; }
+ const base::string16& fail_string() const { return fail_string_; }
+
+ uint16_t port() {
+ base::AutoLock lock(lock_);
+ return port_;
+ }
+
+ bool is_preflight_requested() {
+ base::AutoLock lock(lock_);
+ return is_preflight_requested_;
+ }
+
+ private:
+ bool AllowFileAccessFromFiles() const override { return false; }
+
+ void SetUpOnMainThread() override {
+ base::AutoLock lock(lock_);
+
+ // Need to obtain the path on the main thread.
+ ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &test_data_loader_path_));
+ test_data_loader_path_ =
+ test_data_loader_path_.Append(FILE_PATH_LITERAL("loader"));
+
+ embedded_test_server()->RegisterRequestHandler(base::BindRepeating(
+ &CORSFileOriginBrowserTest::HandleWithAccessControlAllowOrigin,
+ base::Unretained(this)));
+
+ ASSERT_TRUE(embedded_test_server()->Start());
+
+ port_ = embedded_test_server()->port();
+ }
+
+ std::unique_ptr<HttpResponse> HandleWithAccessControlAllowOrigin(
+ const HttpRequest& request) {
+ std::unique_ptr<BasicHttpResponse> response;
+
+ if (net::test_server::ShouldHandle(request, "/test")) {
+ // Accept XHR CORS requests.
+ response = std::make_unique<BasicHttpResponse>();
+ response->set_code(net::HTTP_OK);
+ auto query = net::test_server::ParseQuery(request.GetURL());
+ response->AddCustomHeader(
+ network::cors::header_names::kAccessControlAllowOrigin,
+ query["allow"][0]);
+ if (request.method == net::test_server::METHOD_OPTIONS) {
+ // For CORS-preflight request.
+ response->AddCustomHeader(
+ network::cors::header_names::kAccessControlAllowMethods,
+ "GET, OPTIONS");
+ response->AddCustomHeader(
+ network::cors::header_names::kAccessControlAllowHeaders,
+ "X-NotSimple");
+ response->AddCustomHeader(
+ network::cors::header_names::kAccessControlMaxAge, "0");
+ response->AddCustomHeader(net::HttpRequestHeaders::kCacheControl,
+ "no-store");
+ base::AutoLock lock(lock_);
+ is_preflight_requested_ = true;
+ }
+
+ // Return the request origin header as the body so that JavaScript can
+ // check if it sent the expected origin header.
+ auto origin = request.headers.find(net::HttpRequestHeaders::kOrigin);
+ if (origin != request.headers.end())
+ response->set_content(origin->second);
+ }
+ return response;
+ }
+
+ base::Lock lock_;
+ base::FilePath test_data_loader_path_;
+ uint16_t port_;
+ bool is_preflight_requested_ = false;
+
+ const base::string16 pass_string_;
+ const base::string16 fail_string_;
+
+ DISALLOW_COPY_AND_ASSIGN(CORSFileOriginBrowserTest);
+};
+
+// Tests end to end Origin header and CORS check behaviors with
+// --allow-file-access-from-files flag.
+class CORSFileOriginBrowserTestWithAllowFileAccessFromFiles
+ : public CORSFileOriginBrowserTest {
+ private:
+ bool AllowFileAccessFromFiles() const override { return true; }
+};
+
+IN_PROC_BROWSER_TEST_F(CORSFileOriginBrowserTest,
+ AccessControlAllowOriginIsNull) {
+ std::unique_ptr<TitleWatcher> watcher = CreateWatcher();
+ EXPECT_TRUE(NavigateToURL(
+ shell(), CreateTestDataURL(base::StringPrintf(
+ "cors_file_origin_test.html?port=%d&allow=%s&origin=%s",
+ port(), "null", "null"))));
+
+ EXPECT_EQ(pass_string(), watcher->WaitAndGetTitle());
+ EXPECT_TRUE(is_preflight_requested());
+}
+
+IN_PROC_BROWSER_TEST_F(CORSFileOriginBrowserTest,
+ AccessControlAllowOriginIsFile) {
+ std::unique_ptr<TitleWatcher> watcher = CreateWatcher();
+ EXPECT_TRUE(NavigateToURL(
+ shell(), CreateTestDataURL(base::StringPrintf(
+ "cors_file_origin_test.html?port=%d&allow=%s&origin=%s",
+ port(), "file://", "null"))));
+
+ EXPECT_EQ(fail_string(), watcher->WaitAndGetTitle());
+ EXPECT_TRUE(is_preflight_requested());
+}
+
+IN_PROC_BROWSER_TEST_F(CORSFileOriginBrowserTestWithAllowFileAccessFromFiles,
+ AccessControlAllowOriginIsNull) {
+ std::unique_ptr<TitleWatcher> watcher = CreateWatcher();
+ EXPECT_TRUE(NavigateToURL(
+ shell(), CreateTestDataURL(base::StringPrintf(
+ "cors_file_origin_test.html?port=%d&allow=%s&origin=%s",
+ port(), "null", "file://"))));
+
+ EXPECT_EQ(fail_string(), watcher->WaitAndGetTitle());
+ EXPECT_TRUE(is_preflight_requested());
+}
+
+IN_PROC_BROWSER_TEST_F(CORSFileOriginBrowserTestWithAllowFileAccessFromFiles,
+ AccessControlAllowOriginIsFile) {
+ std::unique_ptr<TitleWatcher> watcher = CreateWatcher();
+ EXPECT_TRUE(NavigateToURL(
+ shell(), CreateTestDataURL(base::StringPrintf(
+ "cors_file_origin_test.html?port=%d&allow=%s&origin=%s",
+ port(), "file://", "file://"))));
+
+ EXPECT_EQ(pass_string(), watcher->WaitAndGetTitle());
+ EXPECT_TRUE(is_preflight_requested());
+}
+
+} // namespace
+
+} // namespace content
diff --git a/chromium/content/browser/loader/cross_origin_read_blocking_explainer.md b/chromium/content/browser/loader/cross_origin_read_blocking_explainer.md
index b22f92754eb..1e46013470a 100644
--- a/chromium/content/browser/loader/cross_origin_read_blocking_explainer.md
+++ b/chromium/content/browser/loader/cross_origin_read_blocking_explainer.md
@@ -1,719 +1,4 @@
# Cross-Origin Read Blocking (CORB)
-This document outlines Cross-Origin Read Blocking, an algorithm by which
-dubious cross-origin resource loads may be identified and blocked by web
-browsers before they reach the web page. CORB offers a way to maintain
-same-origin protections on user data, even in the presence of side channel
-attacks.
-
-### The problem
-
-The same-origin policy generally prevents one origin from reading arbitrary
-network resources from another origin. In practice, enforcing this policy is not
-as simple as blocking all cross-origin loads: exceptions must be established for
-web features, like `<img>` or `<script>`, which can target cross-origin
-resources for historical reasons, and for the CORS mechanism, which allows some
-resources to be selectively read across origins.
-
-Certain type of content, however, can be shown to be incompatible with all of
-the historically-allowed permissive contexts. JSON is one such type: a JSON
-response will result in a decode error when targeted by the `<img>` tag, either
-a no-op or syntax error when targeted by the `<script>` tag, and so on. The
-only case where a web page can load JSON with observable consequences, is via
-`fetch()` or `XMLHttpRequest`; and in those cases, cross-origin reads are
-moderated by CORS.
-
-By detecting and blocking loads of CORB-protected resources early -- that is,
-before the response makes it to the image decoder or JavaScript parser stage --
-CORB defends against side channel vulnerabilities that may be present in the
-stages which are skipped.
-
-### What attacks does CORB mitigate?
-
-CORB mitigates the following attack vectors:
-
-* Cross-Site Script Inclusion (XSSI)
- * XSSI is the technique of pointing the `<script>` tag at a target resource
- which is not JavaScript, and observing some side effects when the resulting
- resource is interpreted as JavaScript. An early example of this attack was
- discovered in 2006: by overwriting the JavaScript Array constructor, the
- contents of JSON lists could be intercepted as simply as:
- `<script src="https://example.com/secret.json">`.
- While the array constructor attack vector is fixed in current
- browsers, numerous similar exploits have been found and fixed in the
- subsequent decade. For example, see the
- [slides here](https://www.owasp.org/images/6/6a/OWASPLondon20161124_JSON_Hijacking_Gareth_Heyes.pdf).
- * CORB prevents this class of attacks, because a CORB-protected resource will
- be blocked from ever being delivered to a cross-site `<script>` element.
- * CORB is particularly valuable in absence of other XSSI defenses like XSRF
- tokens and/or JSON parser breakers. The presence of other XSSI
- defenses like JSON parser breakers can be used as a signal to the CORB
- algorithm that a resource should be CORB-protected.
-
-* Speculative Side Channel Attack (e.g. Spectre).
- * For example, an attacker may 1) use an `<img
- src="https://example.com/secret.json">` element to pull a cross-site secret
- into the process where the attacker's JavaScript runs, and then 2) use a
- speculative side channel attack [(e.g. Spectre)](https://spectreattack.com)
- to read the secret.
- * CORB can prevent this class of attacks when used in tandem with Site
- Isolation, by preventing the JSON resource from being present in the
- memory of a process hosting a cross-site page.
-
-### Algorithm Goals
-
-CORB asks a question of each resource loaded by a webpage: if the resource were
-replaced with an empty or placeholder value, would the webpage be able to tell
-the difference? If not, then the resource can be classified as CORB-protected,
-and blocked. Such an algorithm ought to have the following properties:
-* The bodies and headers of CORB-protected resources should be blocked from
- reaching cross-site pages, unless explicitly permitted by CORS.
-* CORB should protect as many resources as possible.
-* CORB should cause minimal web-compatibility breakages.
-* CORB should be resilient to the most frequent Content-Type mislabelings,
- unless the site owner asserts that the response is labelled correctly via
- `X-Content-Type-Options: nosniff` header.
-* CORB should provide a means for web authors to affirmatively protect resources
- which are not intended for cross-origin access.
-
-### How does CORB "block" a response?
-
-When CORB decides that a response needs to be CORB-protected, the response is
-modified as follows:
-* The response body is replaced with an empty body.
-* The response headers are filtered down to the following ones
- (i.e. all other response headers are removed from the response):
- - [CORS safelisted response headers](https://fetch.spec.whatwg.org/#cors-safelisted-response-header-name)
- - [CORS response headers](https://fetch.spec.whatwg.org/#http-responses)
-
-To be effective against speculative side-channel attacks, CORB blocking must
-take place before the response reaches the process hosting the cross-origin
-initiator of the request. In other words, CORB blocking should prevent CORB-
-protected response data from ever being present in the memory of the process
-hosting a cross-origin website (even temporarily or for a short term). This is
-different from the concept of [filtered responses](https://fetch.spec.whatwg.org/#concept-filtered-response)
-(e.g. [CORS filtered response](https://fetch.spec.whatwg.org/#concept-filtered-response-cors) or
-[opaque filtered response](https://fetch.spec.whatwg.org/#concept-filtered-response-opaque))
-which just provide a limited view into full data that remains stored in an
-[internal response](https://fetch.spec.whatwg.org/#concept-internal-response)
-and may be implemented inside the renderer process.
-
-### What kinds of requests are CORB-eligible?
-
-The following kinds of requests are CORB-exempt:
-
-* [navigation requests](https://fetch.spec.whatwg.org/#navigation-request)
- or requests where the
- [request destination](https://fetch.spec.whatwg.org/#concept-request-destination)
- is "object" or "embed".
- Enforcing isolation between cross-origin `<iframe>`s or `<object>`s is
- outside the scope of CORB (and depends on Site Isolation approach specific to
- each browser).
-
-> [nick@chromium.org] TODO: Although Site Isolation is out of scope for CORB,
-> it should be noted that if a browser handles `<iframe>` elements by loading
-> cross-site subdocuments in-process, then this provides a route by which
-> CORS-protected HTML resources can be loaded into the process, and thereby
-> potentially vulnerable to speculative side channel attacks.
-
-> [lukasza@chromium.org] TODO: Figure out how
-> [Edge's VM-based isolation](https://cloudblogs.microsoft.com/microsoftsecure/2017/10/23/making-microsoft-edge-the-most-secure-browser-with-windows-defender-application-guard/)
-> works (e.g. if some origins are off-limits in particular renderers, then this
-> would greatly increase utility of CORB in Edge).
-
-> [lukasza@chromium.org] TODO: Figure out how other browsers approach Site
-> Isolation (e.g. even if there is no active work, maybe there are some bugs we
-> can reference here).
-
-* Download requests (e.g. requests where the
- [initiator](https://fetch.spec.whatwg.org/#concept-request-initiator)
- is "download"). In this case the data from the response is saved to disk
- (instead of being shared to a cross-origin context) and therefore wouldn't
- benefit from CORB protection.
-
-> [lukasza@chromium.org] AFAIK, in Chrome a response to a download request never
-> passes through memory of a renderer process. Not sure if this is true in
-> other browsers.
-
-All other kinds of requests may be CORB-eligible. This includes:
-* [XHR](https://xhr.spec.whatwg.org/)
- and [fetch()](https://fetch.spec.whatwg.org/#dom-global-fetch)
-* `ping`, `navigator.sendBeacon()`
-* `<link rel="prefetch" ...>`
-* Requests with the following
- [request destination](https://fetch.spec.whatwg.org/#concept-request-destination):
- - "image" requests like `<img>` tag, `/favicon.ico`, SVG's `<image>`,
- CSS' `background-image`, etc.
- - [script-like destinations](https://fetch.spec.whatwg.org/#request-destination-script-like)
- like `<script>`, `importScripts()`, `navigator.serviceWorker.register()`,
- `audioWorklet.addModule()`, etc.
- - "audio", "video" or "track"
- - "font"
- - "style"
- - "report" requests like CSP reports, NEL reports, etc.
-
-The essential idea of CORB is to consider whether a particular resource might be
-unsuitable for use in *every* context listed above. If every possible usage
-would result in either a CORS error, a syntax/decoding error, or no observable
-consequence, CORB ought to be able to block the cross-origin load without
-changing the observable consequences of the load. Prior to CORB, details are
-already suppressed from cross-origin errors, to prevent information leaks. Thus,
-the observable consequences of such errors are already limited, and feasible to
-preserve while blocking.
-
-### Which responses can be protected by CORB?
-
-It will be shown that the following types of content can be CORB-protected:
- * JSON
- * HTML (assuming out-of-process `<iframe>` support)
- * XML
- * Plain text
- * Any response, when prefixed with certain XSSI-defeating patterns (this is
- a common convention for conveying JSON).
-
-These are each discussed in the following sections.
-
-#### Protecting JSON
-
-JSON is a widely used data format on the web; support for JSON is built into the
-web platform. As such, JSON responses are very likely to contain user data worth
-protecting. Additionally, unlike HTML or image formats, there are no legacy HTML
-mechanisms (that is, predating CORS) which allow cross-origin embedding of JSON
-resources.
-
-Because the JSON syntax is derived from and overlaps with JavaScript, care must
-be employed to handle the possibility of JavaScript/JSON polyglots. Treatment of
-JSON by CORB breaks into three cases:
- * Non-empty JSON object literal: A non-empty JSON object
- (such as `{"key": "value"}`). This is precisely the subset of JSON syntax
- which is invalid JavaScript syntax -- the colon after the first string
- literal will generate a syntax error. CORB can protect these cases, even if
- labeled with a different Content-Type, by sniffing the response body.
- * Other JSON literals: The remaining subset of the JSON syntax (for example,
- `null` or `[1, 2, "3"]`) also happens to be valid JavaScript syntax. In
- particular, when evaluated as script, they are value expressions that should
- have no side effects. Thus, if they can be detected, they can be CORB-
- protected. Detection here is possible, but requires implementing a validator
- that understands the full JSON syntax:
- * If the response is not labeled with a JSON Content Type, CORB might detect
- these cases either by buffering and validating the entire response body as
- JSON; the entire response must be considered because of the potential for
- a valid, side-effect-having JavaScript program like `[1, 2,
- "3"].map(...)`.
- * If the response is indeed labeled with a JSON Content Type, CORB may
- decide to sniff the response to confirm for valid JSON, only up to a
- certain number of bytes. This avoids buffering and parsing that might
- consume an unbounded amount of memory.
- * JSON served with an XSSI-defeating prefix: As a mitigation for past browser
- vulnerabilities, many actual websites and frameworks employ a convention of
- prefixing their fetchable resources with a prefix designed to force a JavaScript error.
- These prefixes have not been standardized prior to CORB, but a few approaches
- seem prevalent:
-
- * The character sequence `)]}'` is built into [the angular.js
- framework](https://docs.angularjs.org/api/ng/service/$http), [the Java
- Spring framework](https://goo.gl/xP7FWn), and is observed in wide use on
- the google.com domain.
- * The character sequence `{} &&` was [historically built into the Java
- Spring framework](https://goo.gl/JYPFAv).
- * Infinite loops, such as `for(;;);`, are observed in wide use on the
- facebook.com domain.
-
- The presence of a recognized XSSI defense like a JSON parser breakers is a
- strong signal to the CORB algorithm that a resource should be CORB-protected.
- As such, these prefixes should trigger CORB protection in almost every case,
- no matter what follows them. This is argued to be safe because:
- * A JSON parser breaker would cause a syntax error (or a hang) if present
- in an `application/javascript`.
- * These JSON parser breaker patterns are not known to collide with binary
- resources like images, videos or fonts (which typically require
- the first few bytes to be hardcoded to a specific sequence - for example
- `FF D8 FF` for image/jpeg).
- * Collisions with `text/css` stylesheets is theoretically possible, because
- it is possible to construct a file that begins with a JSON parser
- breaker, but at the same parses fine as a stylesheet - for example:
-```css
-)]}'
-{}
-h1 { color: red; }
-```
- `text/css` is therefore established as an exception, even though the
- practical likelihood of such a scenario seems low.
-
-JSON is also being employed by some web features. One example is `<link
-rel="manifest">`, whose `href` attribute specifies a JSON manifest file.
-Fortunately, this mechanism requires CORS when the manifest is specified cross-
-origin, so its CORB treatment works identically to the rules applied to fetch().
-
-> [nick@chromium.org] TODO: Is there a spec link for JSON being side-effect
-> free when interpreted as script?
-
-#### Protecting HTML
-
-HTML can be embedded cross-origin via `<iframe>`, but browsers can choose to
-implement such embeddings by loading parent and child documents in separate
-processes as appropriate.
-
-Other than navigation (including `<iframe>` navigations), HTML documents can
-only be loaded by fetch() and XHR, both of which require CORS. HTML sniffing is
-already well-understood, so (unlike JSON) it is relatively easy to identify HTML
-resources with high confidence. Only one ambiguous polyglot case has been
-identified that CORB needs to handle conservatively: HTML-style comments, which
-are part of the JavaScript syntax. CORB handles these by skipping over HTML
-comment blocks when sniffing to confirm a HTML content type.
-
-> [nick@chromium.org] TODO: What subset of HTML responses are worth blocking, if
-> out-of-process iframes and site isolation are not available? Is it valuable to
-> hoist the `X-Frame-Options` into CORB in that scenario?
-
-#### Protecting XML
-
-XML, like JSON, is a widely used data exchange format, and like HTML, is a
-document format that's built into the web platform (notably via XmlHttpRequest).
-
-Confirming an XML content-type via sniffing is more straightforward than JSON or
-HTML: XML is signified by the pattern `<?xml`, possibly preceded by whitespace.
-
-The only identified XML case that requires special treatment by CORB is
-`image/svg+xml`, which is an image type. All other XML mime types are treated as
-CORB-protected.
-
-#### Protecting text/plain
-
-If a text/plain response sniffs as one of the other CORB-protected types, the
-response can be CORB-protected.
-
-> [nick@chromium.org] This section needs a strong justification for why
-> text/plain gets this special interpretation. Ideally data showing that
-> text/plain is commonly used to serve HTML, JSON, or XML. Treatment of
-> text/plain in our current implementation may actually be an artifact of
-> an earlier prototype, which ran after standard mime sniffing, and may have
-> seen 'text/plain' MIME types applied as a default MIME type when the response
-> omitted a Content-Type header.
-
-> [lukasza@chromium.org] TODO: Should application/octet-stream be protected
-> similarly?
-
-### Multipart responses and HTTP range requests
-
-Responses marked as `multipart/*` are conservatively considered CORB-exempt, and
-not blocked. This avoids having to parse the content types of the nested parts.
-We recommend not supporting multipart range requests for sensitive documents.
-
-### Detecting resources incorrectly labeled with a CORB-protected MIME type
-
-CORB can't always rely solely on the MIME type of the HTTP response to
-distinguish documents from resources, since the MIME type on network responses
-is sometimes wrong. For example, some HTTP servers return a JPEG image with
-a `Content-Type` header incorrectly saying `text/html`.
-
-To avoid breaking existing websites, CORB may attempt to confirm if the response
-body really matches the CORB-protected Content-Type response header:
-
-* CORB will only sniff to confirm the classification based on the `Content-Type`
- header (i.e. if the `Content-Type` header is `text/json` then CORB will sniff
- for JSON and will not sniff for HTML and/or XML).
-
-* If some syntax elements are shared between CORB-protected and
- non-CORB-protected MIME types, then these elements have to be ignored by CORB
- sniffing. For example, when sniffing for (CORB-protected) HTML, CORB ignores
- and skips HTML comments, because
- [they can also be present](http://www.ecma-international.org/ecma-262/6.0/#sec-html-like-comments)
- in (non-CORB-protected) JavaScript. This is different from the
- [HTML sniffing rules](https://mimesniff.spec.whatwg.org/#rules-for-identifying-an-unknown-mime-type),
- used in other contexts.
-
-> [lukasza@chromium.org] Is it practical to try teaching CORB about sniffing all
-> possible types of non-webby content like `application/pdf`, `application/zip`,
-> etc?
-
-> [lukasza@chromium.org] Some MIME types types are inherently not sniffable
-> (for example `application/octet-stream`).
-
-CORB should trust the `Content-Type` header in scenarios where sniffing
-shouldn't or cannot be done:
-
-* When `X-Content-Type-Options: nosniff` header is present.
-
-* When the response is a partial, 206 response.
-
-> [lukasza@chromium.org] An alternative behavior would be to allow (instead of
-> blocking) 206 responses that would be sniffable otherwise (so one of HTML, XML
-> or JSON + not accompanied by a nosniff header). This alternative behavior
-> would decrease the risk of blocking mislabeled resources, but would increase
-> the risk of not blocking documents that need protection (an attacker could
-> just need to issue a range request - protection in this case would depend on
-> whether 1) the response includes a nosniff header and/or 2) the server rejects
-> range requests altogether). Note that the alternative behavior doesn't help
-> with mislabeled text/plain responses (see also https://crbug.com/801709).
-
-> [lukasza@chromium.org] We believe that mislabeling as HTML, JSON or XML is
-> most common. TODO: are we able to back this up with some numbers?
-
-> [lukasza@chromium.org] Note that range requests are typically not issued
-> when making requests for scripts and/or stylesheets.
-
-Sniffing is a best-effort heuristic and for best security results, we
-recommend 1) marking responses with the correct Content-Type header and 2)
-opting out of sniffing by using the `X-Content-Type-Options: nosniff` header.
-
-### Why can't JSONP be protected?
-
-CORB cannot protect JSONP responses, because JSONP is just JavaScript, and
-JavaScript resources are CORB-exempt due to the `<script>` work cross-origin.
-JSONP should be a discouraged pattern on the modern web.
-
-> JSONP should not be confused with the convention of prefixing JSON responses
-> with parser-breaking prefixes. Parser-breaking prefixes are synergistic with
-> CORB, if the prefix is one known to CORB.
-
-### How does CORB interact with images?
-
-CORB should have no observable impact on `<img>` tags unless the image resource
-is both 1) mislabeled with an incorrect, non-image, CORB-protected Content-Type
-and 2) served with the `X-Content-Type-Options: nosniff` response header.
-
-Examples:
-
-* **Correctly-labeled HTML document**
- * Resource used in an `<img>` tag:
- * Body: an HTML document
- * `Content-Type: text/html`
- * No `X-Content-Type-Options` header
- * Expected behavior: **no observable difference** in behavior with and without
- CORB. The rendered image should be the same broken image when 1) attempting
- to render an html document as an image (without CORB) and 2) attempting to
- render an empty response as an image (when CORB blocks the response).
- * WPT test: `fetch/corb/img-html-correctly-labeled.sub.html`
-
-* **Mislabeled image (with sniffing)**
- * Resource used in an `<img>` tag:
- * Body: an image
- * `Content-Type: text/html`
- * No `X-Content-Type-Options` header
- * Expected behavior: **no difference** in behavior with and without CORB.
- CORB will sniff that the response body is *not* actually a CORB-protected
- type and therefore will allow the response.
- * WPT test: `fetch/corb/img-png-mislabeled-as-html.sub.html`
-
-* **Mislabeled image (nosniff)**
- * Resource used in an `<img>` tag:
- * Body: an image
- * `Content-Type: text/html`
- * `X-Content-Type-Options: nosniff`
- * Expected behavior: **observable difference** in behavior in presence of CORB.
- Because of the `nosniff` header, CORB will have to rely on the
- `Content-Type` header. Because this response is mislabeled (the body is an
- image, but the `Content-Type` header says that it is a html document), CORB
- will incorrectly classify the response as requiring CORB-protection.
- * WPT test: `fetch/corb/img-png-mislabeled-as-html-nosniff.tentative.sub.html`
-
-In addition to the HTML `<img>` tag, the examples above should apply to other
-web features that consume images: `/favicon.ico`, SVG's `<image>`,
-`background-image` in stylesheets, painting images onto (potentially tainted)
-HTML's `<canvas>`, etc.
-
-> [lukasza@chromium.org] TODO: Figure out if we can measure and share how many
-> of CORB-blocked responses are 1) for `<img>` tag, 2) `nosniff`, 3) 200-or-206
-> status code, 4) non-zero (or non-available) Content-Length. Cursory manual
-> testing on major websites indicates that most CORB-blocked images are tracking
-> pixels and therefore blocking them won't have any observable effect.
-
-> [lukasza@chromium.org] Earlier attempts to block nosniff images with
-> incompatible MIME types
-> [failed](https://github.com/whatwg/fetch/issues/395).
-> We think that CORB will succeed, because
-> 1) it will only block a subset of CORB-protected MIME types
-> (e.g. it won't block `application/octet-stream` quoted
-> in a
-> [Firefox bug](https://bugzilla.mozilla.org/show_bug.cgi?id=1302539))
-> 2) CORB is an important response to the recent announcement of new
-> side-channel attacks like Spectre.
-
-
-### How CORB interacts with other multimedia?
-
-TODO.
-
-* TODO: audio/video - mostly like images, but note that 206 response is more
- likely (which today CORB treats as a nosniff signal - not sure if this is
- right: we need to block test/html+206+nosniff, but I am not sure if should
- block text/html+206 without nosniff - especially since we already recommend
- against supporting range requests for sensitive documents).
-
-### How CORB interacts with scripts?
-
-CORB should have no observable impact on `<script>` tags except for cases where
-a CORB-protected, non-JavaScript resource labeled with its correct MIME type is
-loaded as a script - in these cases the resource will usually result in a syntax
-error, but CORB-protected response's empty body will result in no error.
-
-Examples:
-
-* **Correctly-labeled HTML document**
- * Resource used in a `<script>` tag:
- * Body: an HTML document
- * `Content-Type: text/html`
- * No `X-Content-Type-Options` header
- * Expected behavior: **observable difference** via
- [GlobalEventHandlers.onerror](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror).
- Most CORB-protected resources would result in a syntax error when parsed as
- JavaScript. The syntax error goes away after CORB blocks a response,
- because the empty body of the blocked response parses fine as JavaScript.
- * WPT test: `fetch/corb/script-html-correctly-labeled.tentative.sub.html`
-
-> [lukasza@chromium.org] In theory, using a non-empty response in CORB-blocked
-> responses might reintroduce the lost syntax error. We didn't go down that
-> path, because
-> 1) using a non-empty response would be inconsistent with other parts of the
-> Fetch spec (like
-> [opaque filtered response](https://fetch.spec.whatwg.org/#concept-filtered-response-opaque)).
-> 2) retaining the presence of the syntax error might require changing the
-> contents of a CORB-blocked response body depending on whether the original
-> response body would have caused a syntax error or not. This would add
-> extra complexity that seems undesirable both for CORB implementors and for
-> web developers.
-
-* **Mislabeled script (with sniffing)**
- * Resource used in a `<script>` tag:
- * Body: a proper JavaScript script
- * `Content-Type: text/html`
- * No `X-Content-Type-Options` header
- * Expected behavior: **no difference** in behavior with and without CORB.
- CORB will sniff that the response body is *not* actually a CORB-protected
- type and therefore will allow the response. Note that CORB sniffing is
- resilient to the fact that some syntax elements are shared across HTML
- and JavaScript (e.g.
- [comments](http://www.ecma-international.org/ecma-262/6.0/#sec-html-like-comments)).
- * WPT test: `fetch/corb/script-js-mislabeled-as-html.sub.html`
-
-* **Mislabeled script (nosniff)**
- * Resource used in a `<script>` tag:
- * Body: a proper JavaScript script
- * `Content-Type: text/html`
- * `X-Content-Type-Options: nosniff`
- * Expected behavior: **no observable difference** in behavior with and without CORB.
- Both with and without CORB, the script will not execute, because the
- `nosniff` response header response will cause the response to be blocked
- when its MIME type (`text/html` in the example) is not a
- [JavaScript MIME type](https://html.spec.whatwg.org/multipage/scripting.html#javaScript-mime-type)
- (this behavior is required by the
- [Fetch spec](https://fetch.spec.whatwg.org/#should-response-to-request-be-blocked-due-to-nosniff?)).
- * WPT test: `fetch/corb/script-js-mislabeled-as-html-nosniff.sub.html`
-
-In addition to the HTML `<script>` tag, the examples above should apply to other
-web features that consume JavaScript including
-[script-like destinations](https://fetch.spec.whatwg.org/#request-destination-script-like)
-like `importScripts()`, `navigator.serviceWorker.register()`,
-`audioWorklet.addModule()`, etc.
-
-
-### How does CORB interact with stylesheets?
-
-CORB should have no observable impact on stylesheets.
-
-Examples:
-
-* **Anything not labeled as text/css**
- * Examples of resources used in a `<link rel="stylesheet" href="...">` tag:
- * Body: an HTML document OR a simple, valid stylesheet OR a polyglot
- HTML/CSS stylesheet
- * `Content-Type: text/html`
- * No `X-Content-Type-Options` header
- * Expected behavior: **no observable difference** in behavior with and without
- CORB. Even without CORB, such stylesheet examples will be rejected, because
- due to the
- [relaxed syntax rules](https://scarybeastsecurity.blogspot.dk/2009/12/generic-cross-browser-cross-domain.html)
- of CSS, cross-origin CSS requires a correct Content-Type header
- (restrictions vary by browser:
- [IE](http://msdn.microsoft.com/en-us/library/ie/gg622939%28v=vs.85%29.aspx),
- [Firefox](http://www.mozilla.org/security/announce/2010/mfsa2010-46.html),
- [Chrome](https://bugs.chromium.org/p/chromium/issues/detail?id=9877),
- [Safari](http://support.apple.com/kb/HT4070)
- (scroll down to CVE-2010-0051) and
- [Opera](http://www.opera.com/support/kb/view/943/)).
- This behavior is covered by
- [the HTML spec](https://html.spec.whatwg.org/#link-type-stylesheet)
- which 1) asks to only assume `text/css` Content-Type
- if the document embedding the stylesheet has been set to quirks mode and has
- the same origin and 2) only asks to run the steps for creating a CSS style
- sheet if Content-Type of the obtained resource is `text/css`.
-
- * WPT tests:
- `fetch/corb/style-css-mislabeled-as-html.sub.html`,
- `fetch/corb/style-html-correctly-labeled.sub.html`
-
-* **Anything not labeled as text/css (nosniff)**
- * Resource used in a `<link rel="stylesheet" href="...">` tag:
- * Body: a simple stylesheet
- * `Content-Type: text/html`
- * `X-Content-Type-Options: nosniff`
- * Expected behavior: **no observable difference** in behavior with and without CORB.
- Both with and without CORB, the stylesheet will not load, because the
- `nosniff` response header response will cause the response to be blocked
- when its MIME type (`text/html` in the example) is not `text/css`
- (this behavior is required by the
- [Fetch spec](https://fetch.spec.whatwg.org/#should-response-to-request-be-blocked-due-to-nosniff?)).
- * WPT test: `fetch/corb/style-css-mislabeled-as-html-nosniff.sub.html`
-
-* **Correctly-labeled stylesheet with JSON parser breaker**
- * Resource used in a `<link rel="stylesheet" href="...">` tag:
- * Body: a stylesheet that begins with a JSON parser breaker
- * `Content-Type: text/css`
- * No `X-Content-Type-Options` header
- * Expected behavior: **no difference** in behavior with and without CORB,
- because CORB sniffing for JSON-parser-breakers is not performed for
- responses labeled as `Content-Type: text/css`.
- * WPT test: `fetch/corb/style-css-with-json-parser-breaker.sub.html`
-
-
-### How does CORB interact with other web platform features?
-
-CORB has no impact on the following scenarios:
-
-* **[XHR](https://xhr.spec.whatwg.org/) and
- [fetch()](https://fetch.spec.whatwg.org/#dom-global-fetch)**
- * CORB has no observable effect, because [XHR](https://xhr.spec.whatwg.org/)
- and [fetch()](https://fetch.spec.whatwg.org/#dom-global-fetch) already apply
- same-origin policy to the responses (e.g. CORB should only block responses
- that would result in cross-origin XHR errors because of lack of CORS).
-
-* **[Prefetch](https://html.spec.whatwg.org/#link-type-prefetch)**
- * CORB blocks response body from reaching a cross-origin renderer, but
- CORB doesn't prevent the response body from being cached by the browser
- process (and subsequently delivered into another, same-origin renderer
- process).
-
-* **Tracking and reporting**
- * Various techniques try to check that a user has accessed some content
- by triggering a web request to a HTTP server that logs the user visit.
- The web request is frequently triggered by an invisible `img` element
- to a HTTP URI that usually replies either with a 204 or with a
- short HTML document. In addition to the `img` tag, websites may use
- `style`, `script` and other tags to track usage.
- * CORB won't impact these techniques, as they don't depend on the actual
- content being returned by the HTTP server. This also applies to other
- web features that don't care about the response: beacons, pings, CSP
- violation reports, etc.
-
-* **Service workers**
- * Service workers may intercept cross-origin requests and artificially
- construct a response *within* the service worker (i.e. without crossing
- origins and/or security boundaries). CORB will not block such responses.
- * When service workers cache actual cross-origin responses (e.g. in 'no-cors'
- request mode), the responses are 'opaque' and therefore CORB can block such
- responses without changing the service worker's behavior ('opaque' responses
- have a non-accessible body even without CORB).
-
-* **Blob and File API**
- * Fetching cross-origin blob URLs is blocked even without CORB
- (see https://github.com/whatwg/fetch/issues/666).
- * WPT test: `script-html-via-cross-origin-blob-url.sub.html`
- (and also tests for navigation requests covered by the
- [commit here](https://github.com/mkruisselbrink/web-platform-tests/commit/9524a71919340eacc8aaa6e55ffe0b5aa72f9bfd)).
-
-
-* **Content scripts and plugins**
- * TODO...
-
-> [lukasza@chromium.org] TODO: Do we need to be more explicit about handling of
-> requests initiated by plugins?
-> - Should CORB attempt to intercept and parse
-> [crossdomain.xml](https://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html)
-> which tells Adobe Flash whether a particular cross-origin request is okay or
-> not (similarly to how CORB needs to understand CORS response headers)?
-> - If CORB doesn't have knowledge about `crossdomain.xml`, then it will be
-> forced to allow all responses to Flash-initiated requests. We should
-> clarify why CORB still provides security benefits in this scenario.
-> - Also - not sure if plugin behavior is in-scope of
-> https://fetch.spec.whatwg.org?
-
-
-### Demo page
-
-To test CORB one can turn on the feature in Chrome M63+ by launching it with the
-`--enable-features=CrossSiteDocumentBlockingAlways` cmdline flag.
-
-CORB demo page: https://anforowicz.github.io/xsdb-demo/index.html
-
-### Summary of CORB behavior
-
-* Protected origins
- * CORB SHOULD allow same-origin responses.
- * CORB SHOULD block cross-origin responses from HTTP and/or HTTPS origins
- (this includes responses from `filesystem:` and `blob:` URIs if their nested
- origin has a HTTP and/or HTTPS scheme).
- * CORB MAY block cross-origin responses from non-HTTP/HTTPS origins.
-
-> [lukasza@chromium.org] Should the filesystem/blob part be somehow weaved into
-> one of explainer sections above? WPT tests?
-
-* Initiator origins
- * CORB SHOULD block responses for requests initiated from HTTP/HTTPS origins.
- * CORB SHOULD block responses for requests initiated from
- opaque/unique/sandboxed origins.
- * CORB MAY allow responses for requests initiated from `file:` origins.
- * CORB MAY allow responses for requests initiated from content scripts of
- browser extensions.
-
-* Interoperability with other origin-related policies
- * CORB SHOULD allow responses that are otherwise allowed by CORS
- * CORB SHOULD allow non-opaque responses from service workers
- * CORB SHOULD block opaque responses from service workers
-
-* Classification rules based on Content-Type and response data:
- * Classification based on Content-Type header alone:
- * CORB SHOULD classify as CORB-exempt all responses with the following
- Content-Types:
- * `text/css`
- * Classification based on response body alone:
- * CORB MAY classify as CORB-protected any response whose body meets any
- of the criteria below, regardless of its Content-Type and regardless of
- the presence of `X-Content-Type-Options: nosniff` header.
- * Response body begins with a JSON parser breaker such as:
- * `)]}'`
- * `{}&&`
- * `for(;;);`
- * Response body has a prefix that indicates a valid, non-empty JSON
- object.
-
- * Classification based on Content-Type and sniffing:
- * CORB SHOULD classify as CORB-exempt all responses
- `image/svg+xml`
- * CORB SHOULD classify as CORB-protected all responses with the following
- Content-Type if either 1) the response body sniffs as the reported type or
- 2) the `X-Content-Type-Options: nosniff` header is present:
- * [HTML MIME type](https://mimesniff.spec.whatwg.org/#html-mime-type)
- * [XML MIME type](https://mimesniff.spec.whatwg.org/#xml-mime-type)
- (except `image/svg+xml` which is CORB-exempt, per rules above)
- * JSON MIME type - one of `text/json`, `text/json+*`, `text/x-json`,
- `text/x-json+*`, `application/json`, `application/json+*` or `*+json`
- * CORB MAY classify as a CORB-protected any response with a missing
- Content-Type response header, if the response body sniffs as one of the
- CORB-protected types listed above.
- * CORB SHOULD classify as CORB-exempt any response with a Content-Type not
- explicitly listed in this section.
-
-* Sniffing to confirm the Content-Type of the response
- * CORB SHOULD NOT sniff if `X-Content-Type-Options: nosniff` is present.
- * CORB MAY avoid sniffing 206 content range responses with a single-range.
- * CORB MAY limit sniffing to the first few network packets.
- * If Content-Type is `text/html` then CORB SHOULD allow the response
- if it doesn't sniff as `text/html` according to the [sniffing rules]
- (https://mimesniff.spec.whatwg.org/#rules-for-identifying-an-unknown-mime-type),
- amended so that the pattern `"<!--"` is removed from the matching table.
- * If Content-Type is one of TODO then CORB SHOULD allow the response
- if it doesn't
- [sniff as `text/xml`](https://mimesniff.spec.whatwg.org/#rules-for-identifying-an-unknown-mime-type).
- * If Content-Type is one of TODO then CORB SHOULD allow the response
- if it doesn't sniff as JSON. TODO: define "sniff as JSON".
-
-
-### Related specs
-
-* https://fetch.spec.whatwg.org/#concept-filtered-response-opaque
-* https://fetch.spec.whatwg.org/#cors-safelisted-response-header-name
-* https://fetch.spec.whatwg.org/#http-cors-protocol
-* https://fetch.spec.whatwg.org/#should-response-to-request-be-blocked-due-to-nosniff?
-* https://fetch.spec.whatwg.org/#x-content-type-options-header
-* https://tools.ietf.org/html/rfc7233#section-4 (Responses to a Range Request)
+The Cross-Origin Read Blocking (CORB) explainer has been moved to
+[`//services/network/cross_origin_read_blocking.md`](https://chromium.googlesource.com/chromium/src/+/master/services/network/cross_origin_read_blocking_explainer.md).
diff --git a/chromium/content/browser/loader/cross_site_document_blocking_browsertest.cc b/chromium/content/browser/loader/cross_site_document_blocking_browsertest.cc
index 21e8d52f373..0f195de5327 100644
--- a/chromium/content/browser/loader/cross_site_document_blocking_browsertest.cc
+++ b/chromium/content/browser/loader/cross_site_document_blocking_browsertest.cc
@@ -15,11 +15,14 @@
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "content/browser/loader/cross_site_document_resource_handler.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/navigation_entry.h"
+#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/resource_type.h"
+#include "content/public/common/web_preferences.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
@@ -27,6 +30,7 @@
#include "content/public/test/test_utils.h"
#include "content/public/test/url_loader_interceptor.h"
#include "content/shell/browser/shell.h"
+#include "content/test/test_content_browser_client.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "services/network/public/cpp/network_switches.h"
#include "services/network/test/test_url_loader_client.h"
@@ -252,6 +256,23 @@ class RequestInterceptor {
DISALLOW_COPY_AND_ASSIGN(RequestInterceptor);
};
+// Custom ContentBrowserClient that disables web security in the renderer
+// process without actually using --disable-web-security (which disables CORB).
+// This disables the same origin policy to let the renderer see cross-origin
+// fetches if they are received.
+class DisableWebSecurityContentBrowserClient : public TestContentBrowserClient {
+ public:
+ DisableWebSecurityContentBrowserClient() : TestContentBrowserClient() {}
+
+ ~DisableWebSecurityContentBrowserClient() override {}
+
+ // ContentBrowserClient overrides:
+ void OverrideWebkitPrefs(RenderViewHost* render_view_host,
+ WebPreferences* prefs) override {
+ prefs->web_security_enabled = false;
+ }
+};
+
} // namespace
// These tests verify that the browser process blocks cross-site HTML, XML,
@@ -262,9 +283,9 @@ class RequestInterceptor {
// including cases that may be mislabeled as blocked MIME type.
//
// Many of these tests work by turning off the Same Origin Policy in the
-// renderer process via --disable-web-security, and then trying to access the
-// resource via a cross-origin XHR. If the response is blocked, the XHR should
-// see an empty response body.
+// renderer process via WebPreferences::web_security_enabled, and then trying to
+// access the resource via a cross-origin XHR. If the response is blocked, the
+// XHR should see an empty response body.
//
// Note that this BaseTest class does not specify an isolation mode via
// command-line flags. Most of the tests are in the --site-per-process subclass
@@ -289,20 +310,25 @@ class CrossSiteDocumentBlockingBaseTest : public ContentBrowserTest {
network::switches::kHostResolverRules,
"MAP * " + embedded_test_server()->host_port_pair().ToString() +
",EXCLUDE localhost");
-
- // To test that the renderer process does not receive blocked documents, we
- // disable the same origin policy to let it see cross-origin fetches if they
- // are received.
- command_line->AppendSwitch(switches::kDisableWebSecurity);
}
void SetUpOnMainThread() override {
// Complete the manual Start() after ContentBrowserTest's own
// initialization, ref. comment on InitializeAndListen() above.
embedded_test_server()->StartAcceptingConnections();
+
+ // Disable web security via the ContentBrowserClient and notify the current
+ // renderer process.
+ old_client = SetBrowserClientForTesting(&new_client);
+ shell()->web_contents()->GetRenderViewHost()->OnWebkitPreferencesChanged();
}
+ void TearDown() override { SetBrowserClientForTesting(old_client); }
+
private:
+ DisableWebSecurityContentBrowserClient new_client;
+ ContentBrowserClient* old_client = nullptr;
+
DISALLOW_COPY_AND_ASSIGN(CrossSiteDocumentBlockingBaseTest);
};
@@ -391,11 +417,24 @@ IN_PROC_BROWSER_TEST_F(CrossSiteDocumentBlockingTest, BlockDocuments) {
// jsonp.* - JSONP (i.e., script) mislabeled as a document.
// img.* - Contents that won't match the document label.
// valid.* - Correctly labeled responses of non-document types.
- const char* sniff_allowed_resources[] = {
- "js.html", "comment_js.html", "js.xml", "js.json",
- "js.txt", "jsonp.html", "jsonp.xml", "jsonp.json",
- "jsonp.txt", "img.html", "img.xml", "img.json",
- "img.txt", "valid.js", "json-list.js", "nosniff.json-list.js"};
+ const char* sniff_allowed_resources[] = {"js.html",
+ "comment_js.html",
+ "js.xml",
+ "js.json",
+ "js.txt",
+ "jsonp.html",
+ "jsonp.xml",
+ "jsonp.json",
+ "jsonp.txt",
+ "img.html",
+ "img.xml",
+ "img.json",
+ "img.txt",
+ "valid.js",
+ "json-list.js",
+ "nosniff.json-list.js",
+ "js-html-polyglot.html",
+ "js-html-polyglot2.html"};
for (const char* resource : sniff_allowed_resources) {
SCOPED_TRACE(base::StringPrintf("... while testing page: %s", resource));
base::HistogramTester histograms;
@@ -595,12 +634,6 @@ class CrossSiteDocumentBlockingServiceWorkerTest : public ContentBrowserTest {
void SetUpCommandLine(base::CommandLine* command_line) override {
IsolateAllSitesForTesting(command_line);
-
- // To test that the renderer process does not receive blocked documents, we
- // disable the same origin policy to let it see cross-origin fetches if they
- // are received.
- command_line->AppendSwitch(switches::kDisableWebSecurity);
-
ContentBrowserTest::SetUpCommandLine(command_line);
}
@@ -623,8 +656,15 @@ class CrossSiteDocumentBlockingServiceWorkerTest : public ContentBrowserTest {
ASSERT_FALSE(SiteInstance::IsSameWebSite(
shell()->web_contents()->GetBrowserContext(),
GetURLOnServiceWorkerServer("/"), GetURLOnCrossOriginServer("/")));
+
+ // Disable web security via the ContentBrowserClient and notify the current
+ // renderer process.
+ old_client = SetBrowserClientForTesting(&new_client);
+ shell()->web_contents()->GetRenderViewHost()->OnWebkitPreferencesChanged();
}
+ void TearDown() override { SetBrowserClientForTesting(old_client); }
+
GURL GetURLOnServiceWorkerServer(const std::string& path) {
return service_worker_https_server_.GetURL(path);
}
@@ -677,6 +717,9 @@ class CrossSiteDocumentBlockingServiceWorkerTest : public ContentBrowserTest {
net::EmbeddedTestServer service_worker_https_server_;
net::EmbeddedTestServer cross_origin_https_server_;
+ DisableWebSecurityContentBrowserClient new_client;
+ ContentBrowserClient* old_client = nullptr;
+
DISALLOW_COPY_AND_ASSIGN(CrossSiteDocumentBlockingServiceWorkerTest);
};
@@ -789,6 +832,65 @@ IN_PROC_BROWSER_TEST_F(CrossSiteDocumentBlockingKillSwitchTest,
EXPECT_FALSE(was_blocked);
}
+// Test class to verify that --disable-web-security turns off CORB. This
+// inherits from CrossSiteDocumentBlockingTest, so it runs in SitePerProcess.
+class CrossSiteDocumentBlockingDisableWebSecurityTest
+ : public CrossSiteDocumentBlockingTest {
+ public:
+ CrossSiteDocumentBlockingDisableWebSecurityTest() {}
+ ~CrossSiteDocumentBlockingDisableWebSecurityTest() override {}
+
+ void SetUpCommandLine(base::CommandLine* command_line) override {
+ command_line->AppendSwitch(switches::kDisableWebSecurity);
+ CrossSiteDocumentBlockingTest::SetUpCommandLine(command_line);
+ }
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(CrossSiteDocumentBlockingDisableWebSecurityTest);
+};
+
+IN_PROC_BROWSER_TEST_F(CrossSiteDocumentBlockingDisableWebSecurityTest,
+ DisableBlocking) {
+ // Load a page that issues illegal cross-site document requests.
+ GURL foo_url("http://foo.com/cross_site_document_blocking/request.html");
+ EXPECT_TRUE(NavigateToURL(shell(), foo_url));
+
+ bool was_blocked;
+ ASSERT_TRUE(ExecuteScriptAndExtractBool(
+ shell(), "sendRequest(\"valid.html\");", &was_blocked));
+ EXPECT_FALSE(was_blocked);
+}
+
+// Test class to verify that kCrossSiteDocumentBlockingAlways does not take
+// precedence over --disable-web-security. This inherits from
+// CrossSiteDocumentBlockingTest, so it runs in SitePerProcess.
+class CrossSiteDocumentBlockingDisableVsFeatureTest
+ : public CrossSiteDocumentBlockingDisableWebSecurityTest {
+ public:
+ CrossSiteDocumentBlockingDisableVsFeatureTest() {
+ scoped_feature_list_.InitAndEnableFeature(
+ features::kCrossSiteDocumentBlockingAlways);
+ }
+ ~CrossSiteDocumentBlockingDisableVsFeatureTest() override {}
+
+ private:
+ base::test::ScopedFeatureList scoped_feature_list_;
+
+ DISALLOW_COPY_AND_ASSIGN(CrossSiteDocumentBlockingDisableVsFeatureTest);
+};
+
+IN_PROC_BROWSER_TEST_F(CrossSiteDocumentBlockingDisableVsFeatureTest,
+ DisableBlocking) {
+ // Load a page that issues illegal cross-site document requests.
+ GURL foo_url("http://foo.com/cross_site_document_blocking/request.html");
+ EXPECT_TRUE(NavigateToURL(shell(), foo_url));
+
+ bool was_blocked;
+ ASSERT_TRUE(ExecuteScriptAndExtractBool(
+ shell(), "sendRequest(\"valid.html\");", &was_blocked));
+ EXPECT_FALSE(was_blocked);
+}
+
// Without any Site Isolation (in the base test class), there should be no
// document blocking.
IN_PROC_BROWSER_TEST_F(CrossSiteDocumentBlockingBaseTest,
diff --git a/chromium/content/browser/loader/cross_site_document_resource_handler.cc b/chromium/content/browser/loader/cross_site_document_resource_handler.cc
index f5bd0bee3b8..a6aedd72e8a 100644
--- a/chromium/content/browser/loader/cross_site_document_resource_handler.cc
+++ b/chromium/content/browser/loader/cross_site_document_resource_handler.cc
@@ -22,10 +22,10 @@
#include "content/browser/loader/detachable_resource_handler.h"
#include "content/browser/loader/resource_request_info_impl.h"
#include "content/browser/site_instance_impl.h"
-#include "content/browser/site_isolation_policy.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/resource_context.h"
+#include "content/public/browser/site_isolation_policy.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_client.h"
#include "net/base/io_buffer.h"
@@ -34,8 +34,39 @@
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/metrics/public/cpp/ukm_recorder.h"
+using MimeType = network::CrossOriginReadBlocking::MimeType;
+using SniffingResult = network::CrossOriginReadBlocking::SniffingResult;
+
namespace content {
+// An interface to enable incremental content sniffing. These are instantiated
+// for each each request; thus they can be stateful.
+class CrossSiteDocumentResourceHandler::ConfirmationSniffer {
+ public:
+ virtual ~ConfirmationSniffer() = default;
+
+ // Called after data is read from the network. |sniffing_buffer| contains the
+ // entire response body delivered thus far. To support streaming,
+ // |new_data_offset| gives the offset into |sniffing_buffer| at which new data
+ // was appended since the last read.
+ virtual void OnDataAvailable(base::StringPiece sniffing_buffer,
+ size_t new_data_offset) = 0;
+
+ // Returns true if the return value of IsConfirmedContentType() might change
+ // with the addition of more data. Returns false if a final decision is
+ // available.
+ virtual bool WantsMoreData() const = 0;
+
+ // Returns true if the data has been confirmed to be of the CORB-protected
+ // content type that this sniffer is intended to detect.
+ virtual bool IsConfirmedContentType() const = 0;
+
+ // Called when this sniffer's decision was used to block a response. This will
+ // only be invoked when an earlier call to IsConfirmedContentType() returned
+ // true.
+ virtual void LogBlockedResponse(ResourceType resource_type) const {}
+};
+
namespace {
void LogCrossSiteDocumentAction(
@@ -44,6 +75,72 @@ void LogCrossSiteDocumentAction(
CrossSiteDocumentResourceHandler::Action::kCount);
}
+// A ConfirmationSniffer that wraps one of the sniffing functions from
+// network::CrossOriginReadBlocking.
+class SimpleConfirmationSniffer
+ : public CrossSiteDocumentResourceHandler::ConfirmationSniffer {
+ public:
+ // The function pointer type corresponding to one of the available sniffing
+ // functions from network::CrossOriginReadBlocking.
+ using SnifferFunction =
+ decltype(&network::CrossOriginReadBlocking::SniffForHTML);
+
+ explicit SimpleConfirmationSniffer(SnifferFunction sniffer_function)
+ : sniffer_function_(sniffer_function) {}
+ ~SimpleConfirmationSniffer() override = default;
+
+ void OnDataAvailable(base::StringPiece sniffing_buffer,
+ size_t new_data_offset) final {
+ DCHECK_LE(new_data_offset, sniffing_buffer.length());
+ if (new_data_offset == sniffing_buffer.length()) {
+ // No new data -- do nothing. This happens at end-of-stream.
+ return;
+ }
+ // The sniffing functions don't support streaming, so with each new chunk of
+ // data, call the sniffer on the whole buffer.
+ last_sniff_result_ = (*sniffer_function_)(sniffing_buffer);
+ }
+
+ bool WantsMoreData() const final {
+ // kNo and kYes results are final, meaning that sniffing can stop once they
+ // occur. A kMaybe result corresponds to an indeterminate state, that could
+ // change to kYes or kNo with more data.
+ return last_sniff_result_ == SniffingResult::kMaybe;
+ }
+
+ bool IsConfirmedContentType() const final {
+ // Only confirm the mime type if an affirmative pattern (e.g. an HTML tag,
+ // if using the HTML sniffer) was detected.
+ //
+ // Note that if the stream ends (or net::kMaxBytesToSniff has been reached)
+ // and |last_sniff_result_| is kMaybe, the response is allowed to go
+ // through.
+ return last_sniff_result_ == SniffingResult::kYes;
+ }
+
+ private:
+ // The function that actually knows how to sniff for a content type.
+ SnifferFunction sniffer_function_;
+
+ // Result of sniffing the data available thus far.
+ SniffingResult last_sniff_result_ = SniffingResult::kMaybe;
+};
+
+// A ConfirmationSniffer for parser breakers (fetch-only resources). This logs
+// to an UMA histogram whenever it is the reason for a response being blocked.
+class FetchOnlyResourceSniffer : public SimpleConfirmationSniffer {
+ public:
+ FetchOnlyResourceSniffer()
+ : SimpleConfirmationSniffer(
+ &network::CrossOriginReadBlocking::SniffForFetchOnlyResource) {}
+
+ void LogBlockedResponse(ResourceType resource_type) const final {
+ UMA_HISTOGRAM_ENUMERATION(
+ "SiteIsolation.XSD.Browser.BlockedForParserBreaker", resource_type,
+ content::RESOURCE_TYPE_LAST_TYPE);
+ }
+};
+
// An IOBuffer to enable writing into a existing IOBuffer at a given offset.
class LocalIoBufferWithOffset : public net::WrappedIOBuffer {
public:
@@ -56,19 +153,6 @@ class LocalIoBufferWithOffset : public net::WrappedIOBuffer {
scoped_refptr<net::IOBuffer> buf_;
};
-// Helper for the text/plain case.
-CrossSiteDocumentClassifier::Result SniffForHtmlXmlOrJson(
- base::StringPiece data) {
- DCHECK_LT(CrossSiteDocumentClassifier::kNo,
- CrossSiteDocumentClassifier::kMaybe);
- auto result = CrossSiteDocumentClassifier::SniffForHTML(data);
- if (result != CrossSiteDocumentClassifier::kYes)
- result = std::max(CrossSiteDocumentClassifier::SniffForXML(data), result);
- if (result != CrossSiteDocumentClassifier::kYes)
- result = std::max(CrossSiteDocumentClassifier::SniffForJSON(data), result);
- return result;
-}
-
// Headers from
// https://fetch.spec.whatwg.org/#cors-safelisted-response-header-name.
//
@@ -129,13 +213,13 @@ void SanitizeResourceResponse(
void CrossSiteDocumentResourceHandler::LogBlockedResponseOnUIThread(
ResourceRequestInfo::WebContentsGetter web_contents_getter,
bool needed_sniffing,
- CrossSiteDocumentMimeType canonical_mime_type,
+ MimeType canonical_mime_type,
ResourceType resource_type,
int http_response_code,
int64_t content_length) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
- WebContents* web_contents = web_contents_getter.Run();
+ WebContents* web_contents = std::move(web_contents_getter).Run();
if (!web_contents)
return;
@@ -143,7 +227,7 @@ void CrossSiteDocumentResourceHandler::LogBlockedResponseOnUIThread(
ukm::SourceId source_id = ukm::UkmRecorder::GetNewSourceID();
recorder->UpdateSourceURL(source_id, web_contents->GetLastCommittedURL());
ukm::builders::SiteIsolation_XSD_Browser_Blocked(source_id)
- .SetCanonicalMimeType(canonical_mime_type)
+ .SetCanonicalMimeType(static_cast<int64_t>(canonical_mime_type))
.SetContentLengthWasZero(content_length == 0)
.SetContentResourceType(resource_type)
.SetHttpResponseCode(http_response_code)
@@ -155,10 +239,13 @@ void CrossSiteDocumentResourceHandler::LogBlockedResponseOnUIThread(
void CrossSiteDocumentResourceHandler::LogBlockedResponse(
ResourceRequestInfoImpl* resource_request_info,
bool needed_sniffing,
- bool found_parser_breaker,
- CrossSiteDocumentMimeType canonical_mime_type,
+ MimeType canonical_mime_type,
int http_response_code,
int64_t content_length) {
+ DCHECK(resource_request_info);
+ DCHECK_NE(network::CrossOriginReadBlocking::MimeType::kInvalid,
+ canonical_mime_type);
+
LogCrossSiteDocumentAction(
needed_sniffing
? CrossSiteDocumentResourceHandler::Action::kBlockedAfterSniffing
@@ -176,33 +263,28 @@ void CrossSiteDocumentResourceHandler::LogBlockedResponse(
ResourceType resource_type = resource_request_info->GetResourceType();
UMA_HISTOGRAM_ENUMERATION("SiteIsolation.XSD.Browser.Blocked", resource_type,
content::RESOURCE_TYPE_LAST_TYPE);
- if (found_parser_breaker) {
- UMA_HISTOGRAM_ENUMERATION(
- "SiteIsolation.XSD.Browser.BlockedForParserBreaker", resource_type,
- content::RESOURCE_TYPE_LAST_TYPE);
- }
switch (canonical_mime_type) {
- case CROSS_SITE_DOCUMENT_MIME_TYPE_HTML:
+ case MimeType::kHtml:
UMA_HISTOGRAM_ENUMERATION("SiteIsolation.XSD.Browser.Blocked.HTML",
resource_type,
content::RESOURCE_TYPE_LAST_TYPE);
break;
- case CROSS_SITE_DOCUMENT_MIME_TYPE_XML:
+ case MimeType::kXml:
UMA_HISTOGRAM_ENUMERATION("SiteIsolation.XSD.Browser.Blocked.XML",
resource_type,
content::RESOURCE_TYPE_LAST_TYPE);
break;
- case CROSS_SITE_DOCUMENT_MIME_TYPE_JSON:
+ case MimeType::kJson:
UMA_HISTOGRAM_ENUMERATION("SiteIsolation.XSD.Browser.Blocked.JSON",
resource_type,
content::RESOURCE_TYPE_LAST_TYPE);
break;
- case CROSS_SITE_DOCUMENT_MIME_TYPE_PLAIN:
+ case MimeType::kPlain:
UMA_HISTOGRAM_ENUMERATION("SiteIsolation.XSD.Browser.Blocked.Plain",
resource_type,
content::RESOURCE_TYPE_LAST_TYPE);
break;
- case CROSS_SITE_DOCUMENT_MIME_TYPE_OTHERS:
+ case MimeType::kOthers:
UMA_HISTOGRAM_ENUMERATION("SiteIsolation.XSD.Browser.Blocked.Others",
resource_type,
content::RESOURCE_TYPE_LAST_TYPE);
@@ -443,26 +525,26 @@ void CrossSiteDocumentResourceHandler::OnReadCompleted(
// buffer and either report that zero bytes were read (to indicate the
// response is empty and complete), or copy the sniffed data to the next
// handler's buffer and resume the response without blocking.
- bool found_parser_breaker = false;
- auto confirmed_blockable = CrossSiteDocumentClassifier::kNo;
+ bool confirmed_blockable = false;
+ ResourceRequestInfoImpl* info = GetRequestInfo();
if (!needs_sniffing_) {
// If sniffing is impossible (e.g., because this is a range request), or
// if sniffing is disabled due to a nosniff header AND the server returned
// a protected mime type, then we have enough information to block
// immediately.
- confirmed_blockable = CrossSiteDocumentClassifier::kYes;
- } else if (bytes_read == 0) {
- // We haven't blocked the response yet (because previous reads yielded a
- // kMaybe result), and there is no more data. Allow the response.
- confirmed_blockable = CrossSiteDocumentClassifier::kNo;
+ confirmed_blockable = true;
} else {
// Sniff the data to see if it likely matches the MIME type that caused us
// to decide to block it. If it doesn't match, it may be JavaScript,
// JSONP, or another allowable data type and we should let it through.
// Record how many bytes were read to see how often it's too small. (This
// will typically be under 100,000.)
+ const size_t new_data_offset = local_buffer_bytes_read_;
local_buffer_bytes_read_ += bytes_read;
DCHECK_LE(local_buffer_bytes_read_, next_handler_buffer_size_);
+ const bool more_data_possible =
+ bytes_read != 0 && local_buffer_bytes_read_ < net::kMaxBytesToSniff &&
+ local_buffer_bytes_read_ < next_handler_buffer_size_;
// To ensure determinism with respect to network packet ordering and
// sizing, never examine more than kMaxBytesToSniff bytes, even if more
@@ -471,38 +553,33 @@ void CrossSiteDocumentResourceHandler::OnReadCompleted(
std::min(local_buffer_bytes_read_, net::kMaxBytesToSniff);
base::StringPiece data(local_buffer_->data(), bytes_to_sniff);
- // If the server returned a protected mime type, sniff the response to
- // confirm it.
- if (canonical_mime_type_ == CROSS_SITE_DOCUMENT_MIME_TYPE_HTML) {
- confirmed_blockable = CrossSiteDocumentClassifier::SniffForHTML(data);
- } else if (canonical_mime_type_ == CROSS_SITE_DOCUMENT_MIME_TYPE_XML) {
- confirmed_blockable = CrossSiteDocumentClassifier::SniffForXML(data);
- } else if (canonical_mime_type_ == CROSS_SITE_DOCUMENT_MIME_TYPE_JSON) {
- confirmed_blockable = CrossSiteDocumentClassifier::SniffForJSON(data);
- } else if (canonical_mime_type_ == CROSS_SITE_DOCUMENT_MIME_TYPE_PLAIN) {
- // For responses labeled as plain text, only block them if the data
- // sniffs as one of the formats we would block in the first place.
- confirmed_blockable = SniffForHtmlXmlOrJson(data);
+ for (size_t i = 0; i < sniffers_.size();) {
+ sniffers_[i]->OnDataAvailable(data, new_data_offset);
+
+ if (!more_data_possible || !sniffers_[i]->WantsMoreData()) {
+ if (sniffers_[i]->IsConfirmedContentType()) {
+ // We're done sniffing; this response is CORB-protected.
+ confirmed_blockable = true;
+ sniffers_[i]->LogBlockedResponse(info->GetResourceType());
+ break;
+ }
+
+ // This response is CORB-exempt as far as this sniffer is concerned;
+ // remove it from the list.
+ sniffers_.erase(sniffers_.begin() + i);
+ } else {
+ i++;
+ }
}
- // Additionally, on all mime types (including _OTHERS), look for
- // Javascript parser breakers. These are affirmative patterns that
- // indicate this resource should only be consumed by XHR/fetch (and we've
- // already verified that this response isn't a permissable cross-origin
- // XHR/fetch).
- if (confirmed_blockable != CrossSiteDocumentClassifier::kYes &&
- non_stylesheet_mime_type_ /* see https://crbug.com/809259 */) {
- auto result =
- CrossSiteDocumentClassifier::SniffForFetchOnlyResource(data);
- found_parser_breaker = (result == CrossSiteDocumentClassifier::kYes);
- confirmed_blockable = std::max(confirmed_blockable, result);
- }
+ // When there are no sniffers left, the response is allowed.
+ const bool confirmed_allowed = sniffers_.empty();
+ DCHECK(!(confirmed_blockable && confirmed_allowed));
+ DCHECK(confirmed_blockable || confirmed_allowed || more_data_possible);
// If sniffing didn't yield a conclusive response, and we haven't read too
- // many bytes yet, buffer up some more data.
- if (confirmed_blockable == CrossSiteDocumentClassifier::kMaybe &&
- local_buffer_bytes_read_ < net::kMaxBytesToSniff &&
- local_buffer_bytes_read_ < next_handler_buffer_size_) {
+ // many bytes yet or hit the end of the stream, buffer up some more data.
+ if (!(confirmed_blockable || confirmed_allowed) && more_data_possible) {
controller->Resume();
return;
}
@@ -527,7 +604,7 @@ void CrossSiteDocumentResourceHandler::OnReadCompleted(
base::BindOnce(&CrossSiteDocumentResourceHandler::Resume,
weak_this_.GetWeakPtr()));
- if (confirmed_blockable == CrossSiteDocumentClassifier::kYes) {
+ if (confirmed_blockable) {
// Log the blocking event. Inline the Serialize call to avoid it when
// tracing is disabled.
TRACE_EVENT2("navigation",
@@ -538,13 +615,11 @@ void CrossSiteDocumentResourceHandler::OnReadCompleted(
: "null",
"url", request()->url().spec());
- LogBlockedResponse(GetRequestInfo(), needs_sniffing_, found_parser_breaker,
- canonical_mime_type_, http_response_code_,
- content_length_);
+ LogBlockedResponse(info, needs_sniffing_, canonical_mime_type_,
+ http_response_code_, content_length_);
// Block the response and throw away the data. Report zero bytes read.
blocked_read_completed_ = true;
- ResourceRequestInfoImpl* info = GetRequestInfo();
info->set_blocked_cross_site_document(true);
SanitizeResourceResponse(pending_response_start_);
@@ -680,22 +755,6 @@ bool CrossSiteDocumentResourceHandler::ShouldBlockBasedOnHeaders(
return false;
}
- // CORB should look directly at the Content-Type header if one has been
- // received from the network. Ignoring |response->head.mime_type| helps avoid
- // breaking legitimate websites (which might happen more often when blocking
- // would be based on the mime type sniffed by MimeSniffingResourceHandler).
- //
- // TODO(nick): What if the mime type is omitted? Should that be treated the
- // same as text/plain? https://crbug.com/795971
- std::string mime_type;
- if (response->head.headers)
- response->head.headers->GetMimeType(&mime_type);
- // Canonicalize the MIME type. Note that even if it doesn't claim to be a
- // blockable type (i.e., HTML, XML, JSON, or plain text), it may still fail
- // the checks during the SniffForFetchOnlyResource() phase.
- canonical_mime_type_ =
- CrossSiteDocumentClassifier::GetCanonicalMimeType(mime_type);
-
// Treat a missing initiator as an empty origin to be safe, though we don't
// expect this to happen. Unfortunately, this requires a copy.
url::Origin initiator;
@@ -709,7 +768,8 @@ bool CrossSiteDocumentResourceHandler::ShouldBlockBasedOnHeaders(
// Only block documents from HTTP(S) schemes. Checking the scheme of
// |target_origin| ensures that we also protect content of blob: and
// filesystem: URLs if their nested origins have a HTTP(S) scheme.
- if (!CrossSiteDocumentClassifier::IsBlockableScheme(target_origin.GetURL()))
+ if (!network::CrossOriginReadBlocking::IsBlockableScheme(
+ target_origin.GetURL()))
return false;
// Allow requests from file:// URLs for now.
@@ -718,23 +778,27 @@ bool CrossSiteDocumentResourceHandler::ShouldBlockBasedOnHeaders(
if (initiator.scheme() == url::kFileScheme)
return false;
+ // Give embedder a chance to skip document blocking for this response.
+ const char* initiator_scheme_exception =
+ GetContentClient()
+ ->browser()
+ ->GetInitatorSchemeBypassingDocumentBlocking();
+ if (initiator_scheme_exception &&
+ initiator.scheme() == initiator_scheme_exception) {
+ return false;
+ }
+
// Only block if this is a request made from a renderer process.
const ResourceRequestInfoImpl* info = GetRequestInfo();
if (!info || info->GetChildID() == -1)
return false;
- // Give embedder a chance to skip document blocking for this response.
- if (GetContentClient()->browser()->ShouldBypassDocumentBlocking(
- initiator, url, info->GetResourceType())) {
- return false;
- }
-
// Allow the response through if it has valid CORS headers.
std::string cors_header;
response->head.headers->GetNormalizedHeader("access-control-allow-origin",
&cors_header);
- if (CrossSiteDocumentClassifier::IsValidCorsHeaderSet(initiator,
- cors_header)) {
+ if (network::CrossOriginReadBlocking::IsValidCorsHeaderSet(initiator,
+ cors_header)) {
return false;
}
@@ -781,30 +845,89 @@ bool CrossSiteDocumentResourceHandler::ShouldBlockBasedOnHeaders(
bool has_nosniff_header =
base::LowerCaseEqualsASCII(nosniff_header, "nosniff");
- // If this is an HTTP range request, sniffing isn't possible.
- std::string range_header;
- response->head.headers->GetNormalizedHeader("content-range", &range_header);
- bool has_range_header = !range_header.empty();
+ // CORB should look directly at the Content-Type header if one has been
+ // received from the network. Ignoring |response->head.mime_type| helps avoid
+ // breaking legitimate websites (which might happen more often when blocking
+ // would be based on the mime type sniffed by MimeSniffingResourceHandler).
+ //
+ // TODO(nick): What if the mime type is omitted? Should that be treated the
+ // same as text/plain? https://crbug.com/795971
+ std::string mime_type;
+ if (response->head.headers)
+ response->head.headers->GetMimeType(&mime_type);
+ // Canonicalize the MIME type. Note that even if it doesn't claim to be a
+ // blockable type (i.e., HTML, XML, JSON, or plain text), it may still fail
+ // the checks during the SniffForFetchOnlyResource() phase.
+ canonical_mime_type_ =
+ network::CrossOriginReadBlocking::GetCanonicalMimeType(mime_type);
// If this is a partial response, sniffing is not possible, so allow the
// response if it's not a protected mime type.
- if (has_range_header &&
- canonical_mime_type_ == CROSS_SITE_DOCUMENT_MIME_TYPE_OTHERS) {
- return false;
+ std::string range_header;
+ response->head.headers->GetNormalizedHeader("content-range", &range_header);
+ if (!range_header.empty()) {
+ needs_sniffing_ = false;
+ switch (canonical_mime_type_) {
+ case MimeType::kOthers:
+ case MimeType::kPlain: // See also https://crbug.com/801709
+ return false;
+ case MimeType::kHtml:
+ case MimeType::kJson:
+ case MimeType::kXml:
+ return true;
+ case MimeType::kMax:
+ NOTREACHED();
+ return true;
+ }
}
// We need to sniff unprotected mime types (e.g. for parser breakers), and
// unless the nosniff header is set, we also need to sniff protected mime
// types to verify that they're not mislabeled.
needs_sniffing_ =
- (canonical_mime_type_ == CROSS_SITE_DOCUMENT_MIME_TYPE_OTHERS) ||
- !(has_range_header || has_nosniff_header);
+ (canonical_mime_type_ == MimeType::kOthers) || !has_nosniff_header;
// Stylesheets shouldn't be sniffed for JSON parser breakers - see
// https://crbug.com/809259.
- non_stylesheet_mime_type_ =
- !response->head.mime_type.empty() &&
- !base::LowerCaseEqualsASCII(response->head.mime_type, "text/css");
+ if (response->head.mime_type.empty() ||
+ base::LowerCaseEqualsASCII(response->head.mime_type, "text/css")) {
+ return false;
+ }
+
+ // Create one or more |sniffers_| to confirm that the body is actually the
+ // MIME type advertised in the Content-Type header.
+ if (needs_sniffing_) {
+ // When the MIME type is "text/plain", create sniffers for HTML, XML and
+ // JSON. If any of these sniffers match, the response will be blocked.
+ const bool use_all = canonical_mime_type_ == MimeType::kPlain;
+
+ // HTML sniffer.
+ if (use_all || canonical_mime_type_ == MimeType::kHtml) {
+ sniffers_.push_back(std::make_unique<SimpleConfirmationSniffer>(
+ &network::CrossOriginReadBlocking::SniffForHTML));
+ }
+
+ // XML sniffer.
+ if (use_all || canonical_mime_type_ == MimeType::kXml) {
+ sniffers_.push_back(std::make_unique<SimpleConfirmationSniffer>(
+ &network::CrossOriginReadBlocking::SniffForXML));
+ }
+
+ // JSON sniffer.
+ if (use_all || canonical_mime_type_ == MimeType::kJson) {
+ sniffers_.push_back(std::make_unique<SimpleConfirmationSniffer>(
+ &network::CrossOriginReadBlocking::SniffForJSON));
+ }
+
+ // Parser-breaker sniffer.
+ //
+ // Because these prefixes are an XSSI-defeating mechanism, CORB considers
+ // them distinctive enough to be worth blocking no matter the Content-Type
+ // header. So this sniffer is created unconditionally.
+ //
+ // For MimeType::kOthers, this will be the only sniffer that's active.
+ sniffers_.push_back(std::make_unique<FetchOnlyResourceSniffer>());
+ }
return true;
}
diff --git a/chromium/content/browser/loader/cross_site_document_resource_handler.h b/chromium/content/browser/loader/cross_site_document_resource_handler.h
index 02dba000842..ba0c4d4484b 100644
--- a/chromium/content/browser/loader/cross_site_document_resource_handler.h
+++ b/chromium/content/browser/loader/cross_site_document_resource_handler.h
@@ -12,9 +12,9 @@
#include "base/memory/weak_ptr.h"
#include "content/browser/loader/layered_resource_handler.h"
#include "content/browser/loader/resource_request_info_impl.h"
-#include "content/common/cross_site_document_classifier.h"
#include "content/public/browser/resource_request_info.h"
#include "content/public/common/resource_type.h"
+#include "services/network/cross_origin_read_blocking.h"
namespace net {
class URLRequest;
@@ -55,6 +55,8 @@ namespace content {
class CONTENT_EXPORT CrossSiteDocumentResourceHandler
: public LayeredResourceHandler {
public:
+ class ConfirmationSniffer;
+
// This enum backs a histogram, so do not change the order of entries or
// remove entries. Put new entries before |kCount| and update enums.xml (see
// the SiteIsolationResponseAction enum).
@@ -134,16 +136,16 @@ class CONTENT_EXPORT CrossSiteDocumentResourceHandler
static void LogBlockedResponseOnUIThread(
ResourceRequestInfo::WebContentsGetter web_contents_getter,
bool needed_sniffing,
- CrossSiteDocumentMimeType canonical_mime_type,
+ network::CrossOriginReadBlocking::MimeType canonical_mime_type,
ResourceType resource_type,
int http_response_code,
int64_t content_length);
- static void LogBlockedResponse(ResourceRequestInfoImpl* resource_request_info,
- bool needed_sniffing,
- bool found_parser_breaker,
- CrossSiteDocumentMimeType canonical_mime_type,
- int http_response_code,
- int64_t content_length);
+ static void LogBlockedResponse(
+ ResourceRequestInfoImpl* resource_request_info,
+ bool needed_sniffing,
+ network::CrossOriginReadBlocking::MimeType canonical_mime_type,
+ int http_response_code,
+ int64_t content_length);
// WeakPtrFactory for |next_handler_|.
base::WeakPtrFactory<ResourceHandler> weak_next_handler_;
@@ -169,11 +171,8 @@ class CONTENT_EXPORT CrossSiteDocumentResourceHandler
// A canonicalization of the specified MIME type, to determine if blocking the
// response is needed, as well as which type of sniffing to perform.
- CrossSiteDocumentMimeType canonical_mime_type_ =
- CROSS_SITE_DOCUMENT_MIME_TYPE_OTHERS;
-
- // True if the response had a non-empty Content-Type other than text/css.
- bool non_stylesheet_mime_type_ = false;
+ network::CrossOriginReadBlocking::MimeType canonical_mime_type_ =
+ network::CrossOriginReadBlocking::MimeType::kInvalid;
// Indicates whether this request was made by a plugin and was not using CORS.
// Such requests are exempt from blocking, while other plugin requests must be
@@ -214,6 +213,9 @@ class CONTENT_EXPORT CrossSiteDocumentResourceHandler
// Content length if available. -1 if not available.
int64_t content_length_ = -1;
+ // The sniffers to be used.
+ std::vector<std::unique_ptr<ConfirmationSniffer>> sniffers_;
+
base::WeakPtrFactory<CrossSiteDocumentResourceHandler> weak_this_;
DISALLOW_COPY_AND_ASSIGN(CrossSiteDocumentResourceHandler);
diff --git a/chromium/content/browser/loader/cross_site_document_resource_handler_unittest.cc b/chromium/content/browser/loader/cross_site_document_resource_handler_unittest.cc
index e3938b05845..e69ddb4d243 100644
--- a/chromium/content/browser/loader/cross_site_document_resource_handler_unittest.cc
+++ b/chromium/content/browser/loader/cross_site_document_resource_handler_unittest.cc
@@ -18,7 +18,6 @@
#include "base/location.h"
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/weak_ptr.h"
#include "base/single_thread_task_runner.h"
#include "base/test/histogram_tester.h"
@@ -45,6 +44,8 @@
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
+using MimeType = network::CrossOriginReadBlocking::MimeType;
+
namespace content {
namespace {
@@ -81,8 +82,9 @@ struct TestScenario {
// Attributes of the HTTP response.
const char* response_mime_type;
- CrossSiteDocumentMimeType canonical_mime_type;
+ MimeType canonical_mime_type;
bool include_no_sniff_header;
+ bool simulate_range_response;
AccessControlAllowOriginHeader cors_response;
// |packets| specifies the response data which may arrive over the course of
// several writes.
@@ -163,6 +165,8 @@ struct TestScenario {
<< "\n canonical_mime_type = " << scenario.canonical_mime_type
<< "\n include_no_sniff = "
<< (scenario.include_no_sniff_header ? "true" : "false")
+ << "\n range_response = "
+ << (scenario.simulate_range_response ? "true" : "false")
<< "\n cors_response = " << cors_response
<< "\n packets = " << packets
<< "\n verdict = " << verdict
@@ -204,8 +208,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/html", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_HTML, // canonical_mime_type
+ MimeType::kInvalid, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"<html><head>this should sniff as HTML"}, // packets
Verdict::kAllow, // verdict
@@ -219,8 +224,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/html", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_HTML, // canonical_mime_type
+ MimeType::kInvalid, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{")]}',\n[true, true, false, \"user@chromium.org\"]"}, // packets
Verdict::kAllow, // verdict
@@ -234,8 +240,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/json", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_JSON, // canonical_mime_type
+ MimeType::kInvalid, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{")]}'\n[true, true, false, \"user@chromium.org\"]"}, // packets
Verdict::kAllow, // verdict
@@ -249,8 +256,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"application/javascript", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_OTHERS, // canonical_mime_type
+ MimeType::kOthers, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"var x=3;"}, // packets
Verdict::kAllow, // verdict
@@ -259,13 +267,14 @@ const TestScenario kScenarios[] = {
{
"Allowed: Cross-site XHR to HTML with CORS for origin",
__LINE__,
- "http://www.b.com/resource.html", // target_url
- RESOURCE_TYPE_XHR, // resource_type
- "http://www.a.com/", // initiator_origin
- OriginHeader::kInclude, // cors_request
- "text/html", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_HTML, // canonical_mime_type
- false, // include_no_sniff_header
+ "http://www.b.com/resource.html", // target_url
+ RESOURCE_TYPE_XHR, // resource_type
+ "http://www.a.com/", // initiator_origin
+ OriginHeader::kInclude, // cors_request
+ "text/html", // response_mime_type
+ MimeType::kInvalid, // canonical_mime_type
+ false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kAllowInitiatorOrigin, // cors_response
{"<html><head>this should sniff as HTML"}, // packets
Verdict::kAllow, // verdict
@@ -279,8 +288,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kInclude, // cors_request
"application/rss+xml", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_XML, // canonical_mime_type
+ MimeType::kInvalid, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kAllowAny, // cors_response
{"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"}, // packets
Verdict::kAllow, // verdict
@@ -294,8 +304,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kInclude, // cors_request
"text/json", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_JSON, // canonical_mime_type
+ MimeType::kInvalid, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kAllowNull, // cors_response
{"{\"x\" : 3}"}, // packets
Verdict::kAllow, // verdict
@@ -309,8 +320,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/html", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_HTML, // canonical_mime_type
+ MimeType::kInvalid, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"<html><head>this should sniff as HTML"}, // packets
Verdict::kAllow, // verdict
@@ -324,8 +336,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/html", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_HTML, // canonical_mime_type
+ MimeType::kInvalid, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"<html><head>this should sniff as HTML"}, // packets
Verdict::kAllow, // verdict
@@ -339,8 +352,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/html", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_HTML, // canonical_mime_type
+ MimeType::kInvalid, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"<html><head>this should sniff as HTML"}, // packets
Verdict::kAllow, // verdict
@@ -349,13 +363,14 @@ const TestScenario kScenarios[] = {
{
"Allowed: Cross-site fetch HTML from NaCl with CORS response",
__LINE__,
- "http://www.b.com/plugin.html", // target_url
- RESOURCE_TYPE_PLUGIN_RESOURCE, // resource_type
- "http://www.a.com/", // initiator_origin
- OriginHeader::kInclude, // cors_request
- "text/html", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_HTML, // canonical_mime_type
- false, // include_no_sniff_header
+ "http://www.b.com/plugin.html", // target_url
+ RESOURCE_TYPE_PLUGIN_RESOURCE, // resource_type
+ "http://www.a.com/", // initiator_origin
+ OriginHeader::kInclude, // cors_request
+ "text/html", // response_mime_type
+ MimeType::kInvalid, // canonical_mime_type
+ false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kAllowInitiatorOrigin, // cors_response
{"<html><head>this should sniff as HTML"}, // first_chunk
Verdict::kAllow, // verdict
@@ -369,8 +384,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kInclude, // cors_request
"application/javascript", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_OTHERS, // canonical_mime_type
+ MimeType::kInvalid, // canonical_mime_type
true, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kAllowAny, // cors_response
{")]}'\n[true, false]"}, // packets
Verdict::kAllow, // verdict
@@ -384,8 +400,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"application/javascript", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_OTHERS, // canonical_mime_type
+ MimeType::kOthers, // canonical_mime_type
true, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"{ \"key\"", ": true }"}, // packets
Verdict::kBlock, // verdict
@@ -399,8 +416,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"image/png", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_OTHERS, // canonical_mime_type
+ MimeType::kOthers, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{}, // packets
Verdict::kAllow, // verdict
@@ -414,8 +432,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"image/png", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_OTHERS, // canonical_mime_type
+ MimeType::kOthers, // canonical_mime_type
true, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{}, // packets
Verdict::kAllow, // verdict
@@ -431,8 +450,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/html", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_HTML, // canonical_mime_type
+ MimeType::kHtml, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"foo({\"x\" : 3})"}, // packets
Verdict::kAllow, // verdict
@@ -446,8 +466,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/plain", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_PLAIN, // canonical_mime_type
+ MimeType::kPlain, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"var x = 3;"}, // packets
Verdict::kAllow, // verdict
@@ -461,8 +482,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/plain", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_PLAIN, // canonical_mime_type
+ MimeType::kPlain, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"{", " \n", "var x = 3;\n", "console.log('hello');"}, // packets
Verdict::kAllow, // verdict
@@ -477,8 +499,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/json", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_JSON, // canonical_mime_type
+ MimeType::kJson, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"invoke({ \"key\": true });"}, // packets
Verdict::kAllow, // verdict
@@ -492,8 +515,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/plain", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_PLAIN, // canonical_mime_type
+ MimeType::kPlain, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"[1, 2, {}, true, false, \"yay\"]"}, // packets
Verdict::kAllow, // verdict
@@ -507,8 +531,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/plain", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_PLAIN, // canonical_mime_type
+ MimeType::kPlain, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"[1, 2, {}, true, false, \"yay\"]", ".map(x => console.log(x))",
".map(x => console.log(x));"}, // packets
@@ -523,8 +548,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"application/xml", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_XML, // canonical_mime_type
+ MimeType::kXml, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"Won't sniff as XML"}, // packets
Verdict::kAllow, // verdict
@@ -537,9 +563,10 @@ const TestScenario kScenarios[] = {
RESOURCE_TYPE_XHR, // resource_type
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
- "text/x-json", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_JSON, // canonical_mime_type
+ "text/json", // response_mime_type
+ MimeType::kJson, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"Won't sniff as JSON"}, // packets
Verdict::kAllow, // verdict
@@ -553,8 +580,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/html", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_HTML, // canonical_mime_type
+ MimeType::kHtml, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"<htm"}, // packets
Verdict::kAllow, // verdict
@@ -568,8 +596,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/html", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_HTML, // canonical_mime_type
+ MimeType::kHtml, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{kHTMLWithTooLongComment}, // packets
Verdict::kAllow, // verdict
@@ -583,8 +612,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/html", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_HTML, // canonical_mime_type
+ MimeType::kHtml, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{}, // packets
Verdict::kAllow, // verdict
@@ -598,8 +628,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/html", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_HTML, // canonical_mime_type
+ MimeType::kInvalid, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"<html><head>this should sniff as HTML"}, // packets
Verdict::kAllow, // verdict
@@ -613,8 +644,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/html", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_HTML, // canonical_mime_type
+ MimeType::kInvalid, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"<html><head>this should sniff as HTML"}, // packets
Verdict::kAllow, // verdict
@@ -630,8 +662,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/html", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_HTML, // canonical_mime_type
+ MimeType::kHtml, // canonical_mime_type
true, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"<html><head>this should sniff as HTML"}, // packets
Verdict::kBlock, // verdict
@@ -645,8 +678,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/html; charset=utf-8", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_HTML, // canonical_mime_type
+ MimeType::kHtml, // canonical_mime_type
true, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"<html><head>this should sniff as HTML"}, // packets
Verdict::kBlock, // verdict
@@ -660,8 +694,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/html", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_HTML, // canonical_mime_type
+ MimeType::kHtml, // canonical_mime_type
true, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"Wouldn't sniff as HTML"}, // packets
Verdict::kBlock, // verdict
@@ -675,8 +710,9 @@ const TestScenario kScenarios[] = {
"https://bar.site.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/html", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_HTML, // canonical_mime_type
+ MimeType::kHtml, // canonical_mime_type
true, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"<html><head>this should sniff as HTML"}, // packets
Verdict::kBlock, // verdict
@@ -687,13 +723,14 @@ const TestScenario kScenarios[] = {
// Note that initiator_origin is cross-origin, but same-site in relation
// to the CORS response.
__LINE__,
- "http://www.b.com/resource.html", // target_url
- RESOURCE_TYPE_XHR, // resource_type
- "http://foo.example.com/", // initiator_origin
- OriginHeader::kInclude, // cors_request
- "text/html", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_HTML, // canonical_mime_type
- false, // include_no_sniff_header
+ "http://www.b.com/resource.html", // target_url
+ RESOURCE_TYPE_XHR, // resource_type
+ "http://foo.example.com/", // initiator_origin
+ OriginHeader::kInclude, // cors_request
+ "text/html", // response_mime_type
+ MimeType::kHtml, // canonical_mime_type
+ false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kAllowExampleDotCom, // cors_response
{"<hTmL><head>this should sniff as HTML"}, // packets
Verdict::kBlock, // verdict
@@ -711,8 +748,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kInclude, // cors_request
"text/html", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_HTML, // canonical_mime_type
+ MimeType::kHtml, // canonical_mime_type
true, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{}, // packets
Verdict::kBlock, // verdict
@@ -728,8 +766,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/html", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_HTML, // canonical_mime_type
+ MimeType::kHtml, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"<html><head>this should sniff as HTML"}, // packets
Verdict::kBlock, // verdict
@@ -743,8 +782,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"application/xml", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_XML, // canonical_mime_type
+ MimeType::kXml, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"}, // packets
Verdict::kBlock, // verdict
@@ -758,8 +798,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"application/json", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_JSON, // canonical_mime_type
+ MimeType::kJson, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"{\"x\" : 3}"}, // packets
Verdict::kBlock, // verdict
@@ -773,8 +814,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/plain", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_PLAIN, // canonical_mime_type
+ MimeType::kPlain, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{" ", "\t", "{", "\"x\" ", " ", ": 3}"}, // packets
Verdict::kBlock, // verdict
@@ -788,8 +830,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/plain", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_PLAIN, // canonical_mime_type
+ MimeType::kPlain, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{" ", "\t", "<", "?", "x", "m", "l", ">"}, // packets
Verdict::kBlock, // verdict
@@ -803,13 +846,14 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/plain", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_PLAIN, // canonical_mime_type
+ MimeType::kPlain, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
- {" <!--", "\t -", "-", "->", "<", "s", "c", "r", "i", "p",
+ {" <!--", "\t -", "-", "->", "\n", "<", "s", "c", "r", "i", "p",
"t"}, // packets
Verdict::kBlock, // verdict
- 10, // verdict_packet
+ 11, // verdict_packet
},
{
"Blocked: slow-arriving html with commented-out xml tag",
@@ -819,11 +863,12 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/plain", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_PLAIN, // canonical_mime_type
+ MimeType::kPlain, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
- {" <!--", " <?xml ", "-->", "<", "h", "e", "a", "d"}, // packets
- Verdict::kBlock, // verdict
+ {" <!--", " <?xml ", "-->\n", "<", "h", "e", "a", "d"}, // packets
+ Verdict::kBlock, // verdict
7, // verdict_packet
},
{
@@ -834,8 +879,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/plain", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_PLAIN, // canonical_mime_type
+ MimeType::kPlain, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"<html><head>this should sniff as HTML"}, // packets
Verdict::kBlock, // verdict
@@ -849,8 +895,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/html", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_HTML, // canonical_mime_type
+ MimeType::kHtml, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"<!doc", "type html><html itemscope=\"\" ",
"itemtype=\"http://schema.org/SearchResultsPage\" ",
@@ -861,13 +908,14 @@ const TestScenario kScenarios[] = {
{
"Blocked: Cross-site XHR to HTML with wrong CORS",
__LINE__,
- "http://www.b.com/resource.html", // target_url
- RESOURCE_TYPE_XHR, // resource_type
- "http://www.a.com/", // initiator_origin
- OriginHeader::kInclude, // cors_request
- "text/html", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_HTML, // canonical_mime_type
- false, // include_no_sniff_header
+ "http://www.b.com/resource.html", // target_url
+ RESOURCE_TYPE_XHR, // resource_type
+ "http://www.a.com/", // initiator_origin
+ OriginHeader::kInclude, // cors_request
+ "text/html", // response_mime_type
+ MimeType::kHtml, // canonical_mime_type
+ false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kAllowExampleDotCom, // cors_response
{"<hTmL><head>this should sniff as HTML"}, // packets
Verdict::kBlock, // verdict
@@ -881,8 +929,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kInclude, // cors_request
"text/html", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_HTML, // canonical_mime_type
+ MimeType::kHtml, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"<html><head>this should sniff as HTML"}, // first_chunk
Verdict::kBlock, // verdict
@@ -896,8 +945,9 @@ const TestScenario kScenarios[] = {
"http://c.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/json", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_JSON, // canonical_mime_type
+ MimeType::kJson, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{")]", "}'\n[true, true, false, \"user@chromium.org\"]"}, // packets
Verdict::kBlock, // verdict
@@ -911,8 +961,9 @@ const TestScenario kScenarios[] = {
"http://c.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"audio/x-wav", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_OTHERS, // canonical_mime_type
+ MimeType::kOthers, // canonical_mime_type
true, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{")]", "}'\n[true, true, false, \"user@chromium.org\"]"}, // packets
Verdict::kBlock, // verdict
@@ -926,8 +977,9 @@ const TestScenario kScenarios[] = {
"http://c.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"application/javascript", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_OTHERS, // canonical_mime_type
+ MimeType::kOthers, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"for(;;)", ";[true, true, false, \"user@chromium.org\"]"}, // packets
Verdict::kBlock, // verdict
@@ -941,8 +993,9 @@ const TestScenario kScenarios[] = {
"http://c.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/html", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_HTML, // canonical_mime_type
+ MimeType::kHtml, // canonical_mime_type
true, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{")]", "}'\n[true, true, false, \"user@chromium.org\"]"}, // packets
Verdict::kBlock, // verdict
@@ -952,13 +1005,14 @@ const TestScenario kScenarios[] = {
"Blocked: JSON object + mismatching CORS with parser-breaker labeled "
"as JavaScript",
__LINE__,
- "http://www.b.com/resource.html", // target_url
- RESOURCE_TYPE_SCRIPT, // resource_type
- "http://www.a.com/", // initiator_origin
- OriginHeader::kInclude, // cors_request
- "application/javascript", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_OTHERS, // canonical_mime_type
- true, // include_no_sniff_header
+ "http://www.b.com/resource.html", // target_url
+ RESOURCE_TYPE_SCRIPT, // resource_type
+ "http://www.a.com/", // initiator_origin
+ OriginHeader::kInclude, // cors_request
+ "application/javascript", // response_mime_type
+ MimeType::kOthers, // canonical_mime_type
+ true, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kAllowExampleDotCom, // cors_response
{")]}'\n[true, false]"}, // packets
Verdict::kBlock, // verdict
@@ -972,8 +1026,9 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/html", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_HTML, // canonical_mime_type
+ MimeType::kHtml, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"<html><head>this should sniff as HTML"}, // packets
Verdict::kBlock, // verdict
@@ -987,13 +1042,46 @@ const TestScenario kScenarios[] = {
"http://www.a.com/", // initiator_origin
OriginHeader::kOmit, // cors_request
"text/html", // response_mime_type
- CROSS_SITE_DOCUMENT_MIME_TYPE_HTML, // canonical_mime_type
+ MimeType::kHtml, // canonical_mime_type
false, // include_no_sniff_header
+ false, // simulate_range_response
AccessControlAllowOriginHeader::kOmit, // cors_response
{"<html><head>this should sniff as HTML"}, // packets
Verdict::kBlock, // verdict
0, // verdict_packet
},
+ {
+ "Allowed: text/plain 206 media",
+ __LINE__,
+ "http://www.b.com/movie.txt", // target_url
+ RESOURCE_TYPE_MEDIA, // resource_type
+ "http://www.a.com/", // initiator_origin
+ OriginHeader::kOmit, // cors_request
+ "text/plain", // response_mime_type
+ MimeType::kPlain, // canonical_mime_type
+ false, // include_no_sniff_header
+ true, // simulate_range_response
+ AccessControlAllowOriginHeader::kOmit, // cors_response
+ {"movie content"}, // packets
+ Verdict::kAllow, // verdict
+ -1, // verdict_packet
+ },
+ {
+ "Blocked: text/html 206 media",
+ __LINE__,
+ "http://www.b.com/movie.html", // target_url
+ RESOURCE_TYPE_MEDIA, // resource_type
+ "http://www.a.com/", // initiator_origin
+ OriginHeader::kOmit, // cors_request
+ "text/html", // response_mime_type
+ MimeType::kHtml, // canonical_mime_type
+ false, // include_no_sniff_header
+ true, // simulate_range_response
+ AccessControlAllowOriginHeader::kOmit, // cors_response
+ {"simulated *middle*-of-html content"}, // packets
+ Verdict::kBlock, // verdict
+ -1, // verdict_packet
+ },
};
// TestResourceDispatcherHost is a ResourceDispatcherHostImpl that the test
@@ -1103,12 +1191,14 @@ class CrossSiteDocumentResourceHandlerTest
scoped_refptr<network::ResourceResponse> CreateResponse(
const char* response_mime_type,
bool include_no_sniff_header,
+ bool simulate_range_response,
AccessControlAllowOriginHeader cors_response,
const char* initiator_origin) {
scoped_refptr<network::ResourceResponse> response =
base::MakeRefCounted<network::ResourceResponse>();
scoped_refptr<net::HttpResponseHeaders> response_headers =
- base::MakeRefCounted<net::HttpResponseHeaders>("");
+ base::MakeRefCounted<net::HttpResponseHeaders>(
+ simulate_range_response ? "HTTP/1.1 206 OK" : "HTTP/1.1 200 OK");
// Content-Type header.
std::string charset;
@@ -1125,6 +1215,12 @@ class CrossSiteDocumentResourceHandlerTest
if (include_no_sniff_header)
response_headers->AddHeader("X-Content-Type-Options: nosniff");
+ // Range response. The product code doesn't currently look at the exact
+ // range specified, so we can get away with testing with arbitrary/random
+ // values.
+ if (simulate_range_response)
+ response_headers->AddHeader("Content-Range: bytes 200-1000/67589");
+
// CORS header.
if (cors_response == AccessControlAllowOriginHeader::kAllowAny) {
response_headers->AddHeader("Access-Control-Allow-Origin: *");
@@ -1229,7 +1325,8 @@ TEST_P(CrossSiteDocumentResourceHandlerTest, ResponseBlocking) {
// Set up response based on scenario.
scoped_refptr<network::ResourceResponse> response = CreateResponse(
scenario.response_mime_type, scenario.include_no_sniff_header,
- scenario.cors_response, scenario.initiator_origin);
+ scenario.simulate_range_response, scenario.cors_response,
+ scenario.initiator_origin);
ASSERT_EQ(MockResourceLoader::Status::IDLE,
mock_loader_->OnResponseStarted(response));
@@ -1406,23 +1503,26 @@ TEST_P(CrossSiteDocumentResourceHandlerTest, ResponseBlocking) {
std::string histogram_base = "SiteIsolation.XSD.Browser";
std::string bucket;
switch (scenario.canonical_mime_type) {
- case CROSS_SITE_DOCUMENT_MIME_TYPE_HTML:
+ case MimeType::kHtml:
bucket = "HTML";
break;
- case CROSS_SITE_DOCUMENT_MIME_TYPE_XML:
+ case MimeType::kXml:
bucket = "XML";
break;
- case CROSS_SITE_DOCUMENT_MIME_TYPE_JSON:
+ case MimeType::kJson:
bucket = "JSON";
break;
- case CROSS_SITE_DOCUMENT_MIME_TYPE_PLAIN:
+ case MimeType::kPlain:
bucket = "Plain";
break;
- case CROSS_SITE_DOCUMENT_MIME_TYPE_OTHERS:
+ case MimeType::kOthers:
bucket = "Others";
break;
- default:
- NOTREACHED();
+ case MimeType::kInvalid:
+ DCHECK_EQ(Verdict::kAllow, scenario.verdict);
+ DCHECK_EQ(-1, scenario.verdict_packet);
+ bucket = "No blocking = no bucket";
+ break;
}
int start_action = static_cast<int>(
CrossSiteDocumentResourceHandler::Action::kResponseStarted);
@@ -1446,13 +1546,13 @@ TEST_P(CrossSiteDocumentResourceHandlerTest, ResponseBlocking) {
// The parser-breaker detection only on responses that are not blocked by
// normal mime-sniffing.
bool scenario_requires_parser_breaker_detection =
- (CrossSiteDocumentClassifier::kYes ==
- CrossSiteDocumentClassifier::SniffForFetchOnlyResource(
+ (network::CrossOriginReadBlocking::kYes ==
+ network::CrossOriginReadBlocking::SniffForFetchOnlyResource(
scenario.data())) &&
- !((CrossSiteDocumentClassifier::kYes ==
- CrossSiteDocumentClassifier::SniffForJSON(scenario.data())) &&
- (scenario.canonical_mime_type == CROSS_SITE_DOCUMENT_MIME_TYPE_JSON ||
- scenario.canonical_mime_type == CROSS_SITE_DOCUMENT_MIME_TYPE_PLAIN));
+ !((network::CrossOriginReadBlocking::kYes ==
+ network::CrossOriginReadBlocking::SniffForJSON(scenario.data())) &&
+ (scenario.canonical_mime_type == MimeType::kJson ||
+ scenario.canonical_mime_type == MimeType::kPlain));
if (should_be_blocked && expected_to_sniff &&
scenario_requires_parser_breaker_detection) {
expected_counts[histogram_base + ".BlockedForParserBreaker"] = 1;
@@ -1516,7 +1616,8 @@ TEST_P(CrossSiteDocumentResourceHandlerTest, OnWillReadDefer) {
// Set up response based on scenario.
scoped_refptr<network::ResourceResponse> response = CreateResponse(
scenario.response_mime_type, scenario.include_no_sniff_header,
- scenario.cors_response, scenario.initiator_origin);
+ scenario.simulate_range_response, scenario.cors_response,
+ scenario.initiator_origin);
ASSERT_EQ(MockResourceLoader::Status::IDLE,
mock_loader_->OnResponseStarted(response));
@@ -1657,7 +1758,8 @@ TEST_P(CrossSiteDocumentResourceHandlerTest, MimeSnifferInterop) {
// Set up response based on scenario.
scoped_refptr<network::ResourceResponse> response = CreateResponse(
scenario.response_mime_type, scenario.include_no_sniff_header,
- scenario.cors_response, scenario.initiator_origin);
+ scenario.simulate_range_response, scenario.cors_response,
+ scenario.initiator_origin);
// Call OnResponseStarted. Note that MimeSniffingResourceHandler will not
// immediately forward the call to CrossSiteDocumentResourceHandler.
diff --git a/chromium/content/browser/loader/data_pipe_to_source_stream.cc b/chromium/content/browser/loader/data_pipe_to_source_stream.cc
index 2748b6f46f3..8a5c372798f 100644
--- a/chromium/content/browser/loader/data_pipe_to_source_stream.cc
+++ b/chromium/content/browser/loader/data_pipe_to_source_stream.cc
@@ -13,7 +13,9 @@ DataPipeToSourceStream::DataPipeToSourceStream(
mojo::ScopedDataPipeConsumerHandle body)
: net::SourceStream(net::SourceStream::TYPE_NONE),
body_(std::move(body)),
- handle_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL) {
+ handle_watcher_(FROM_HERE,
+ mojo::SimpleWatcher::ArmingPolicy::MANUAL,
+ base::SequencedTaskRunnerHandle::Get()) {
handle_watcher_.Watch(
body_.get(), MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_PEER_CLOSED,
base::BindRepeating(&DataPipeToSourceStream::OnReadable,
diff --git a/chromium/content/browser/loader/detachable_resource_handler.cc b/chromium/content/browser/loader/detachable_resource_handler.cc
index fa43dfc2322..b8222d203d1 100644
--- a/chromium/content/browser/loader/detachable_resource_handler.cc
+++ b/chromium/content/browser/loader/detachable_resource_handler.cc
@@ -7,7 +7,6 @@
#include <utility>
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/time/time.h"
#include "content/browser/loader/null_resource_controller.h"
#include "content/browser/loader/resource_controller.h"
diff --git a/chromium/content/browser/loader/detachable_resource_handler_unittest.cc b/chromium/content/browser/loader/detachable_resource_handler_unittest.cc
index 25cc0655e42..a477ded4641 100644
--- a/chromium/content/browser/loader/detachable_resource_handler_unittest.cc
+++ b/chromium/content/browser/loader/detachable_resource_handler_unittest.cc
@@ -8,7 +8,6 @@
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/weak_ptr.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
diff --git a/chromium/content/browser/loader/downloaded_temp_file_impl.cc b/chromium/content/browser/loader/downloaded_temp_file_impl.cc
index 759bd05a963..f699d84df04 100644
--- a/chromium/content/browser/loader/downloaded_temp_file_impl.cc
+++ b/chromium/content/browser/loader/downloaded_temp_file_impl.cc
@@ -4,7 +4,6 @@
#include "content/browser/loader/downloaded_temp_file_impl.h"
-#include "base/memory/ptr_util.h"
#include "content/browser/loader/resource_dispatcher_host_impl.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
diff --git a/chromium/content/browser/loader/intercepting_resource_handler.cc b/chromium/content/browser/loader/intercepting_resource_handler.cc
index 131edd05aa5..0b038d238a1 100644
--- a/chromium/content/browser/loader/intercepting_resource_handler.cc
+++ b/chromium/content/browser/loader/intercepting_resource_handler.cc
@@ -7,7 +7,6 @@
#include "base/auto_reset.h"
#include "base/location.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/string_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/browser/loader/null_resource_controller.h"
diff --git a/chromium/content/browser/loader/intercepting_resource_handler_unittest.cc b/chromium/content/browser/loader/intercepting_resource_handler_unittest.cc
index 6b8be7911bf..7d1f3365b75 100644
--- a/chromium/content/browser/loader/intercepting_resource_handler_unittest.cc
+++ b/chromium/content/browser/loader/intercepting_resource_handler_unittest.cc
@@ -13,7 +13,6 @@
#include "base/location.h"
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/weak_ptr.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
diff --git a/chromium/content/browser/loader/loader_delegate.h b/chromium/content/browser/loader/loader_delegate.h
index 92d5f897a11..1484631025b 100644
--- a/chromium/content/browser/loader/loader_delegate.h
+++ b/chromium/content/browser/loader/loader_delegate.h
@@ -8,13 +8,12 @@
#include <inttypes.h>
#include <memory>
+#include <string>
#include "content/common/content_export.h"
#include "content/public/browser/resource_request_info.h"
#include "net/base/load_states.h"
-class GURL;
-
namespace content {
// Delegate from loader to the rest of content. Should be interacted with on the
@@ -31,13 +30,11 @@ class CONTENT_EXPORT LoaderDelegate {
// Notification that the load state for the given WebContents has changed.
// NOTE: this method is called on the UI thread.
- virtual void LoadStateChanged(
- WebContents* web_contents,
- const GURL& url,
- const net::LoadStateWithParam& load_state,
- uint64_t upload_position,
- uint64_t upload_size) = 0;
-
+ virtual void LoadStateChanged(WebContents* web_contents,
+ const std::string& host,
+ const net::LoadStateWithParam& load_state,
+ uint64_t upload_position,
+ uint64_t upload_size) = 0;
};
} // namespace content
diff --git a/chromium/content/browser/loader/merkle_integrity_source_stream.cc b/chromium/content/browser/loader/merkle_integrity_source_stream.cc
index ded5a16d2e4..4643113b761 100644
--- a/chromium/content/browser/loader/merkle_integrity_source_stream.cc
+++ b/chromium/content/browser/loader/merkle_integrity_source_stream.cc
@@ -4,37 +4,50 @@
#include "content/browser/loader/merkle_integrity_source_stream.h"
+#include <string.h>
+
#include "base/base64url.h"
#include "base/big_endian.h"
-#include "crypto/sha2.h"
+#include "base/numerics/safe_conversions.h"
#include "net/base/io_buffer.h"
namespace content {
namespace {
-// Limit the record size to 5MiB to prevent browser OOM.
-constexpr uint64_t kMaxRecordSize = 5 * 1024 * 1024;
+// Limit the record size to 16KiB to prevent browser OOM. This matches the
+// maximum record size in TLS and the default maximum frame size in HTTP/2.
+constexpr uint64_t kMaxRecordSize = 16 * 1024;
constexpr char kMiSha256Header[] = "mi-sha256=";
-constexpr int kMiSha256HeaderLength = sizeof(kMiSha256Header) - 1;
+constexpr size_t kMiSha256HeaderLength = sizeof(kMiSha256Header) - 1;
+
+// Copies as many bytes from |input| as will fit in |output| and advances both.
+size_t CopyClamped(base::span<const char>* input, base::span<char>* output) {
+ size_t size = std::min(output->size(), input->size());
+ memcpy(output->data(), input->data(), size);
+ *output = output->subspan(size);
+ *input = input->subspan(size);
+ return size;
+}
} // namespace
MerkleIntegritySourceStream::MerkleIntegritySourceStream(
- const std::string& mi_header_value,
+ base::StringPiece mi_header_value,
std::unique_ptr<SourceStream> upstream)
// TODO(ksakamoto): Use appropriate SourceType.
- : net::FilterSourceStream(SourceStream::TYPE_NONE, std::move(upstream)),
- record_size_(0),
- failed_(false) {
+ : net::FilterSourceStream(SourceStream::TYPE_NONE, std::move(upstream)) {
// TODO(ksakamoto): Support quoted parameter value.
- if (mi_header_value.substr(0, kMiSha256HeaderLength) != kMiSha256Header ||
+ std::string next_proof;
+ if (!mi_header_value.starts_with(kMiSha256Header) ||
!base::Base64UrlDecode(mi_header_value.substr(kMiSha256HeaderLength),
base::Base64UrlDecodePolicy::DISALLOW_PADDING,
- &next_proof_) ||
- next_proof_.size() != crypto::kSHA256Length) {
+ &next_proof) ||
+ next_proof.size() != SHA256_DIGEST_LENGTH) {
failed_ = true;
+ } else {
+ memcpy(next_proof_, next_proof.data(), SHA256_DIGEST_LENGTH);
}
}
@@ -46,76 +59,180 @@ int MerkleIntegritySourceStream::FilterData(net::IOBuffer* output_buffer,
int input_buffer_size,
int* consumed_bytes,
bool upstream_eof_reached) {
- if (failed_)
+ if (failed_) {
return net::ERR_CONTENT_DECODING_FAILED;
+ }
- // TODO(ksakamoto): Avoid unnecessary buffer copying.
- input_.append(input_buffer->data(), input_buffer_size);
- *consumed_bytes = input_buffer_size;
-
- if (!ProcessInput(upstream_eof_reached)) {
+ base::span<const char> remaining_input = base::make_span(
+ input_buffer->data(), base::checked_cast<size_t>(input_buffer_size));
+ base::span<char> remaining_output = base::make_span(
+ output_buffer->data(), base::checked_cast<size_t>(output_buffer_size));
+ bool ok =
+ FilterDataImpl(&remaining_output, &remaining_input, upstream_eof_reached);
+ *consumed_bytes =
+ input_buffer_size - base::checked_cast<int>(remaining_input.size());
+ if (!ok) {
failed_ = true;
return net::ERR_CONTENT_DECODING_FAILED;
}
+ return output_buffer_size - base::checked_cast<int>(remaining_output.size());
+}
- int bytes_out =
- std::min(output_.size(), static_cast<size_t>(output_buffer_size));
- output_.copy(output_buffer->data(), bytes_out);
- output_.erase(0, bytes_out);
- return bytes_out;
+std::string MerkleIntegritySourceStream::GetTypeAsString() const {
+ return "MI-SHA256";
}
-bool MerkleIntegritySourceStream::ProcessInput(bool upstream_eof_reached) {
- // TODO(ksakamoto): Use shift iterator or StringPiece instead of substr/erase.
+bool MerkleIntegritySourceStream::FilterDataImpl(base::span<char>* output,
+ base::span<const char>* input,
+ bool upstream_eof_reached) {
+ std::string storage;
- // Read the record size (the first 8 octets of the stream).
- if (!record_size_) {
- if (input_.size() < 8)
+ // Process the record size in front, if we haven't yet.
+ if (record_size_ == 0) {
+ base::span<const char> bytes;
+ if (!ConsumeBytes(input, 8, &bytes, &storage)) {
return !upstream_eof_reached;
-
- base::ReadBigEndian(input_.data(), &record_size_);
- input_.erase(0, 8);
- if (record_size_ == 0)
+ }
+ uint64_t record_size;
+ base::ReadBigEndian(bytes.data(), &record_size);
+ if (record_size == 0) {
return false;
- if (record_size_ > kMaxRecordSize) {
+ }
+ if (record_size > kMaxRecordSize) {
DVLOG(1)
<< "Rejecting MI content encoding because record size is too big: "
- << record_size_;
+ << record_size;
return false;
}
+ record_size_ = base::checked_cast<size_t>(record_size);
}
- // Process records other than the last.
- while (input_.size() >= record_size_ + crypto::kSHA256Length) {
- std::string chunk = input_.substr(0, record_size_ + crypto::kSHA256Length);
- input_.erase(0, record_size_ + crypto::kSHA256Length);
- chunk.push_back('\x01');
- std::string hash = crypto::SHA256HashString(chunk);
- if (next_proof_ != hash)
- return false;
- output_.append(chunk.substr(0, record_size_));
- next_proof_ = chunk.substr(record_size_, crypto::kSHA256Length);
+ // Clear any previous output before continuing.
+ if (!CopyPartialOutput(output)) {
+ DCHECK(output->empty());
+ return true;
}
- // Process the last record.
- if (upstream_eof_reached && !next_proof_.empty()) {
- if (input_.size() > record_size_)
+ // Process records until we're done or there's no more room in |output|.
+ while (!output->empty() && !final_record_done_) {
+ base::span<const char> record;
+ if (!ConsumeBytes(input, record_size_ + SHA256_DIGEST_LENGTH, &record,
+ &storage)) {
+ DCHECK(input->empty());
+ if (!upstream_eof_reached) {
+ return true; // Wait for more data later.
+ }
+
+ // The final record is shorter and does not contain a hash. Process all
+ // remaining input the final record.
+ //
+ // TODO(davidben): This matches the previous implementation in that it
+ // allows empty final records, but this does not match the specification
+ // and means some inputs have two valid encodings. However, the
+ // specification's version cannot represent the empty string. Update this
+ // when https://github.com/martinthomson/http-mice/issues/3 is resolved.
+ if (partial_input_.size() > record_size_) {
+ return false;
+ }
+ record = partial_input_;
+ final_record_done_ = true;
+ }
+ if (!ProcessRecord(record, final_record_done_, output)) {
return false;
+ }
+ }
- input_.push_back('\0');
- std::string hash = crypto::SHA256HashString(input_);
- if (next_proof_ != hash)
- return false;
+ if (final_record_done_) {
+ DCHECK(upstream_eof_reached);
+ DCHECK(input->empty());
+ }
+ return true;
+}
- output_.append(input_.substr(0, input_.size() - 1));
- input_.clear();
- next_proof_.clear();
+bool MerkleIntegritySourceStream::CopyPartialOutput(base::span<char>* output) {
+ if (partial_output_offset_ == partial_output_.size()) {
+ return true;
}
+ base::span<const char> partial =
+ base::make_span(partial_output_).subspan(partial_output_offset_);
+ partial_output_offset_ += CopyClamped(&partial, output);
+ if (partial_output_offset_ < partial_output_.size()) {
+ return false;
+ }
+ partial_output_.clear();
+ partial_output_offset_ = 0;
return true;
}
-std::string MerkleIntegritySourceStream::GetTypeAsString() const {
- return "MI-256";
+bool MerkleIntegritySourceStream::ConsumeBytes(base::span<const char>* input,
+ size_t len,
+ base::span<const char>* result,
+ std::string* storage) {
+ // This comes from the requirement that, when ConsumeBytes returns false, the
+ // next call must use the same |len|.
+ DCHECK_LT(partial_input_.size(), len);
+
+ // Return data directly from |input| if possible.
+ if (partial_input_.empty() && input->size() >= len) {
+ *result = input->subspan(0, len);
+ *input = input->subspan(len);
+ return true;
+ }
+
+ // Reassemble |len| bytes from |partial_input_| and |input|.
+ size_t to_copy = std::min(len - partial_input_.size(), input->size());
+ partial_input_.append(input->data(), to_copy);
+ *input = input->subspan(to_copy);
+
+ if (partial_input_.size() < len) {
+ return false;
+ }
+ *storage = std::move(partial_input_);
+ partial_input_.clear();
+ *result = *storage;
+ return true;
+}
+
+bool MerkleIntegritySourceStream::ProcessRecord(base::span<const char> record,
+ bool is_final,
+ base::span<char>* output) {
+ DCHECK(partial_output_.empty());
+
+ // Check the hash.
+ SHA256_CTX ctx;
+ SHA256_Init(&ctx);
+ SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(record.data()),
+ record.size());
+ uint8_t type = is_final ? 0 : 1;
+ SHA256_Update(&ctx, &type, 1);
+ uint8_t sha256[SHA256_DIGEST_LENGTH];
+ SHA256_Final(sha256, &ctx);
+#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
+ // The fuzzer will have a hard time fixing up chains of hashes, so, if
+ // building in fuzzer mode, everything hashes to the same garbage value.
+ memset(sha256, 0x42, SHA256_DIGEST_LENGTH);
+#endif
+ if (memcmp(sha256, next_proof_, SHA256_DIGEST_LENGTH) != 0) {
+ return false;
+ }
+
+ if (!is_final) {
+ // Split into data and a hash.
+ base::span<const char> hash = record.subspan(record_size_);
+ record = record.subspan(0, record_size_);
+
+ // Save the next proof.
+ CHECK_EQ(static_cast<size_t>(SHA256_DIGEST_LENGTH), hash.size());
+ memcpy(next_proof_, hash.data(), SHA256_DIGEST_LENGTH);
+ }
+
+ // Copy whatever output there is room for.
+ CopyClamped(&record, output);
+
+ // If it didn't all fit, save the remaining in |partial_output_|.
+ DCHECK(record.empty() || output->empty());
+ partial_output_.append(record.data(), record.size());
+ return true;
}
} // namespace content
diff --git a/chromium/content/browser/loader/merkle_integrity_source_stream.h b/chromium/content/browser/loader/merkle_integrity_source_stream.h
index 74a45ca5c4b..d2554372a48 100644
--- a/chromium/content/browser/loader/merkle_integrity_source_stream.h
+++ b/chromium/content/browser/loader/merkle_integrity_source_stream.h
@@ -8,9 +8,12 @@
#include <stdint.h>
#include <string>
+#include "base/containers/span.h"
#include "base/macros.h"
+#include "base/strings/string_piece.h"
#include "content/common/content_export.h"
#include "net/filter/filter_source_stream.h"
+#include "third_party/boringssl/src/include/openssl/sha.h"
namespace content {
@@ -21,7 +24,7 @@ namespace content {
class CONTENT_EXPORT MerkleIntegritySourceStream
: public net::FilterSourceStream {
public:
- MerkleIntegritySourceStream(const std::string& mi_header_value,
+ MerkleIntegritySourceStream(base::StringPiece mi_header_value,
std::unique_ptr<SourceStream> upstream);
~MerkleIntegritySourceStream() override;
@@ -35,14 +38,48 @@ class CONTENT_EXPORT MerkleIntegritySourceStream
std::string GetTypeAsString() const override;
private:
- bool ProcessInput(bool upstream_eof_reached);
-
- std::string input_;
- std::string output_;
- // SHA-256 hash for the next record, or empty if validation is completed.
- std::string next_proof_;
- uint64_t record_size_;
- bool failed_;
+ // Processes as many bytes of |input| as are available or fit in
+ // |output|. Both |input| and |output| are advanced past any bytes consumed or
+ // written to, respectively. Returns true if all input processed, possibly
+ // none, was valid and false on fatal error.
+ bool FilterDataImpl(base::span<char>* output,
+ base::span<const char>* input,
+ bool upstream_eof_reached);
+
+ // Copies |partial_output_| to output, as much as fits and advances both
+ // buffers. Returns whether all output was copied.
+ bool CopyPartialOutput(base::span<char>* output);
+
+ // Consumes the next |len| bytes of data from |partial_input_| and |input|
+ // and, if available, points |result| to it and returns true. |result| will
+ // point into either |input| or data copied to |storage|. |input| is advanced
+ // past any consumed bytes. If |len| bytes are not available, returns false
+ // and fully consumes |input| |partial_input_| for a future call.
+ bool ConsumeBytes(base::span<const char>* input,
+ size_t len,
+ base::span<const char>* result,
+ std::string* storage);
+
+ // Processes a record and returns whether it was valid. If valid, writes the
+ // contents into |output|, advancing past any bytes written. If |output| was
+ // not large enough, excess data will be copied into an internal buffer for a
+ // future call.
+ bool ProcessRecord(base::span<const char> record,
+ bool is_final,
+ base::span<char>* output);
+
+ // The partial input block, if the previous input buffer was too small.
+ std::string partial_input_;
+ // The partial output block, if the previous output buffer was too small.
+ std::string partial_output_;
+ // The index of |partial_output_| that has not been returned yet.
+ size_t partial_output_offset_ = 0;
+ // SHA-256 hash for the next record, if |final_record_done_| is false.
+ uint8_t next_proof_[SHA256_DIGEST_LENGTH];
+ size_t record_size_ = 0;
+ bool failed_ = false;
+ // Whether the final record has been processed.
+ bool final_record_done_ = false;
DISALLOW_COPY_AND_ASSIGN(MerkleIntegritySourceStream);
};
diff --git a/chromium/content/browser/loader/merkle_integrity_source_stream_unittest.cc b/chromium/content/browser/loader/merkle_integrity_source_stream_unittest.cc
index 732bded9a14..dc1d802e457 100644
--- a/chromium/content/browser/loader/merkle_integrity_source_stream_unittest.cc
+++ b/chromium/content/browser/loader/merkle_integrity_source_stream_unittest.cc
@@ -22,6 +22,8 @@ const char kMISingleRecord[] =
"mi-sha256=dcRDgR2GM35DluAV13PzgnG6-pvQwPywfFvAu1UeFrs";
const char kMIMultipleRecords[] =
"mi-sha256=IVa9shfs0nyKEhHqtB3WVNANJ2Njm5KjQLjRtnbkYJ4";
+const char kMIWholeNumberOfRecords[] =
+ "mi-sha256=L2vdwBplKvIr0ZPkcuskWZfEVDgVdHa6aD363UpKuZs";
enum class ReadResultType {
// Each call to AddReadResult is a separate read from the lower layer
@@ -161,6 +163,14 @@ TEST_P(MerkleIntegritySourceStreamTest, EmptyStream) {
EXPECT_EQ(net::ERR_CONTENT_DECODING_FAILED, result);
}
+TEST_P(MerkleIntegritySourceStreamTest, TooShortMIHeader) {
+ Init("z");
+ source()->AddReadResult(nullptr, 0, net::OK, GetParam().mode);
+ std::string actual_output;
+ int result = ReadStream(&actual_output);
+ EXPECT_EQ(net::ERR_CONTENT_DECODING_FAILED, result);
+}
+
TEST_P(MerkleIntegritySourceStreamTest, MalformedMIHeader) {
Init("invalid-MI-header-value");
source()->AddReadResult(nullptr, 0, net::OK, GetParam().mode);
@@ -169,34 +179,94 @@ TEST_P(MerkleIntegritySourceStreamTest, MalformedMIHeader) {
EXPECT_EQ(net::ERR_CONTENT_DECODING_FAILED, result);
}
+TEST_P(MerkleIntegritySourceStreamTest, WrongMIAttributeName) {
+ Init("mi-sha255=bjQLnP-zepicpUTmu3gKLHiQHT-zNzh2hRGjBhevoB0");
+ source()->AddReadResult(nullptr, 0, net::OK, GetParam().mode);
+ std::string actual_output;
+ int result = ReadStream(&actual_output);
+ EXPECT_EQ(net::ERR_CONTENT_DECODING_FAILED, result);
+}
+
+TEST_P(MerkleIntegritySourceStreamTest, HashTooShort) {
+ Init("mi-sha256=bjQLnP-zepicpUTmu3gKLHiQHT-zNzh2hRGjBhevoA");
+ source()->AddReadResult(nullptr, 0, net::OK, GetParam().mode);
+ std::string actual_output;
+ int result = ReadStream(&actual_output);
+ EXPECT_EQ(net::ERR_CONTENT_DECODING_FAILED, result);
+}
+
+TEST_P(MerkleIntegritySourceStreamTest, HashTooLong) {
+ Init("mi-sha256=bjQLnP-zepicpUTmu3gKLHiQHT-zNzh2hRGjBhevoB0A");
+ source()->AddReadResult(nullptr, 0, net::OK, GetParam().mode);
+ std::string actual_output;
+ int result = ReadStream(&actual_output);
+ EXPECT_EQ(net::ERR_CONTENT_DECODING_FAILED, result);
+}
+
TEST_P(MerkleIntegritySourceStreamTest, RecordSizeOnly) {
Init(kMIEmptyBody);
- const uint8_t record_size[] = {0, 0, 0, 0, 0, 0, 0, 10};
- source()->AddReadResult(reinterpret_cast<const char*>(record_size),
- sizeof(record_size), net::OK, GetParam().mode);
+ const uint8_t kRecordSize[] = {0, 0, 0, 0, 0, 0, 0, 10};
+ source()->AddReadResult(reinterpret_cast<const char*>(kRecordSize),
+ sizeof(kRecordSize), net::OK, GetParam().mode);
source()->AddReadResult(nullptr, 0, net::OK, GetParam().mode);
std::string actual_output;
int result = ReadStream(&actual_output);
EXPECT_EQ(net::OK, result);
}
+TEST_P(MerkleIntegritySourceStreamTest, TruncatedRecordSize) {
+ Init(kMIEmptyBody);
+ const uint8_t kRecordSize[] = {0, 0, 0, 0, 0, 0, 1};
+ source()->AddReadResult(reinterpret_cast<const char*>(kRecordSize),
+ sizeof(kRecordSize), net::OK, GetParam().mode);
+ source()->AddReadResult(nullptr, 0, net::OK, GetParam().mode);
+ std::string actual_output;
+ int result = ReadStream(&actual_output);
+ EXPECT_EQ(net::ERR_CONTENT_DECODING_FAILED, result);
+}
+
TEST_P(MerkleIntegritySourceStreamTest, RecordSizeOnlyWrongHash) {
Init(kMISingleRecord);
- const uint8_t record_size[] = {0, 0, 0, 0, 0, 0, 0, 10};
- source()->AddReadResult(reinterpret_cast<const char*>(record_size),
- sizeof(record_size), net::OK, GetParam().mode);
+ const uint8_t kRecordSize[] = {0, 0, 0, 0, 0, 0, 0, 10};
+ source()->AddReadResult(reinterpret_cast<const char*>(kRecordSize),
+ sizeof(kRecordSize), net::OK, GetParam().mode);
source()->AddReadResult(nullptr, 0, net::OK, GetParam().mode);
std::string actual_output;
int result = ReadStream(&actual_output);
EXPECT_EQ(net::ERR_CONTENT_DECODING_FAILED, result);
}
-TEST_P(MerkleIntegritySourceStreamTest, RecordSizeTooBig) {
+TEST_P(MerkleIntegritySourceStreamTest, RecordSizeHuge) {
Init(kMIEmptyBody);
- const uint8_t record_size[] = {0xff, 0xff, 0xff, 0xff,
+ // 2^64 - 1 is far too large.
+ const uint8_t kRecordSize[] = {0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff};
- source()->AddReadResult(reinterpret_cast<const char*>(record_size),
- sizeof(record_size), net::OK, GetParam().mode);
+ source()->AddReadResult(reinterpret_cast<const char*>(kRecordSize),
+ sizeof(kRecordSize), net::OK, GetParam().mode);
+ std::string actual_output;
+ int result = ReadStream(&actual_output);
+ EXPECT_EQ(net::ERR_CONTENT_DECODING_FAILED, result);
+}
+
+TEST_P(MerkleIntegritySourceStreamTest, RecordSizeTooBig) {
+ Init(kMIEmptyBody);
+ // 2^16 + 1 just exceeds the limit.
+ const uint8_t kRecordSize[] = {0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x40, 0x01};
+ source()->AddReadResult(reinterpret_cast<const char*>(kRecordSize),
+ sizeof(kRecordSize), net::OK, GetParam().mode);
+ std::string actual_output;
+ int result = ReadStream(&actual_output);
+ EXPECT_EQ(net::ERR_CONTENT_DECODING_FAILED, result);
+}
+
+TEST_P(MerkleIntegritySourceStreamTest, RecordSizeZero) {
+ Init(kMIEmptyBody);
+ // Zero is not a valid record size.
+ const uint8_t kRecordSize[] = {0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00};
+ source()->AddReadResult(reinterpret_cast<const char*>(kRecordSize),
+ sizeof(kRecordSize), net::OK, GetParam().mode);
std::string actual_output;
int result = ReadStream(&actual_output);
EXPECT_EQ(net::ERR_CONTENT_DECODING_FAILED, result);
@@ -205,26 +275,26 @@ TEST_P(MerkleIntegritySourceStreamTest, RecordSizeTooBig) {
// https://tools.ietf.org/html/draft-thomson-http-mice-02#section-4.1
TEST_P(MerkleIntegritySourceStreamTest, SingleRecord) {
Init(kMISingleRecord);
- const uint8_t record_size[] = {0, 0, 0, 0, 0, 0, 0, 0x29};
- const std::string message("When I grow up, I want to be a watermelon");
- source()->AddReadResult(reinterpret_cast<const char*>(record_size),
- sizeof(record_size), net::OK, GetParam().mode);
- source()->AddReadResult(message.data(), message.size(), net::OK,
+ const uint8_t kRecordSize[] = {0, 0, 0, 0, 0, 0, 0, 41};
+ const std::string kMessage("When I grow up, I want to be a watermelon");
+ source()->AddReadResult(reinterpret_cast<const char*>(kRecordSize),
+ sizeof(kRecordSize), net::OK, GetParam().mode);
+ source()->AddReadResult(kMessage.data(), kMessage.size(), net::OK,
GetParam().mode);
source()->AddReadResult(nullptr, 0, net::OK, GetParam().mode);
std::string actual_output;
int rv = ReadStream(&actual_output);
- EXPECT_EQ(static_cast<int>(message.size()), rv);
- EXPECT_EQ(message, actual_output);
+ EXPECT_EQ(static_cast<int>(kMessage.size()), rv);
+ EXPECT_EQ(kMessage, actual_output);
}
TEST_P(MerkleIntegritySourceStreamTest, SingleRecordWrongHash) {
Init(kMIEmptyBody);
- const uint8_t record_size[] = {0, 0, 0, 0, 0, 0, 0, 0x29};
- const std::string message("When I grow up, I want to be a watermelon");
- source()->AddReadResult(reinterpret_cast<const char*>(record_size),
- sizeof(record_size), net::OK, GetParam().mode);
- source()->AddReadResult(message.data(), message.size(), net::OK,
+ const uint8_t kRecordSize[] = {0, 0, 0, 0, 0, 0, 0, 41};
+ const std::string kMessage("When I grow up, I want to be a watermelon");
+ source()->AddReadResult(reinterpret_cast<const char*>(kRecordSize),
+ sizeof(kRecordSize), net::OK, GetParam().mode);
+ source()->AddReadResult(kMessage.data(), kMessage.size(), net::OK,
GetParam().mode);
source()->AddReadResult(nullptr, 0, net::OK, GetParam().mode);
std::string actual_output;
@@ -233,55 +303,244 @@ TEST_P(MerkleIntegritySourceStreamTest, SingleRecordWrongHash) {
EXPECT_EQ(0u, actual_output.size());
}
+// The final record may not be larger than the record size.
+TEST_P(MerkleIntegritySourceStreamTest, SingleRecordTooLarge) {
+ Init(kMISingleRecord);
+ const uint8_t kRecordSize[] = {0, 0, 0, 0, 0, 0, 0, 40};
+ const std::string kMessage("When I grow up, I want to be a watermelon");
+ source()->AddReadResult(reinterpret_cast<const char*>(kRecordSize),
+ sizeof(kRecordSize), net::OK, GetParam().mode);
+ source()->AddReadResult(kMessage.data(), kMessage.size(), net::OK,
+ GetParam().mode);
+ source()->AddReadResult(nullptr, 0, net::OK, GetParam().mode);
+ std::string actual_output;
+ int rv = ReadStream(&actual_output);
+ EXPECT_EQ(net::ERR_CONTENT_DECODING_FAILED, rv);
+ EXPECT_EQ("", actual_output);
+}
+
// https://tools.ietf.org/html/draft-thomson-http-mice-02#section-4.2
TEST_P(MerkleIntegritySourceStreamTest, MultipleRecords) {
Init(kMIMultipleRecords);
- const uint8_t record_size[] = {0, 0, 0, 0, 0, 0, 0, 16};
- const std::string message("When I grow up, I want to be a watermelon");
+ const uint8_t kRecordSize[] = {0, 0, 0, 0, 0, 0, 0, 16};
+ const std::string kMessage("When I grow up, I want to be a watermelon");
- source()->AddReadResult(reinterpret_cast<const char*>(record_size),
- sizeof(record_size), net::OK, GetParam().mode);
- source()->AddReadResult(message.data(), 16, net::OK, GetParam().mode);
+ source()->AddReadResult(reinterpret_cast<const char*>(kRecordSize),
+ sizeof(kRecordSize), net::OK, GetParam().mode);
+ source()->AddReadResult(kMessage.data(), 16, net::OK, GetParam().mode);
std::string hash1 =
Base64Decode("OElbplJlPK-Rv6JNK6p5_515IaoPoZo-2elWL7OQ60A");
source()->AddReadResult(hash1.data(), 32, net::OK, GetParam().mode);
- source()->AddReadResult(message.data() + 16, 16, net::OK, GetParam().mode);
+ source()->AddReadResult(kMessage.data() + 16, 16, net::OK, GetParam().mode);
std::string hash2 =
Base64Decode("iPMpmgExHPrbEX3_RvwP4d16fWlK4l--p75PUu_KyN0");
source()->AddReadResult(hash2.data(), 32, net::OK, GetParam().mode);
- source()->AddReadResult(message.data() + 32, message.size() - 32, net::OK,
+ source()->AddReadResult(kMessage.data() + 32, kMessage.size() - 32, net::OK,
GetParam().mode);
source()->AddReadResult(nullptr, 0, net::OK, GetParam().mode);
std::string actual_output;
int rv = ReadStream(&actual_output);
- EXPECT_EQ(static_cast<int>(message.size()), rv);
- EXPECT_EQ(message, actual_output);
+ EXPECT_EQ(static_cast<int>(kMessage.size()), rv);
+ EXPECT_EQ(kMessage, actual_output);
+}
+
+TEST_P(MerkleIntegritySourceStreamTest, MultipleRecordsAllAtOnce) {
+ Init(kMIMultipleRecords);
+ const uint8_t kRecordSize[] = {0, 0, 0, 0, 0, 0, 0, 16};
+ const std::string kMessage("When I grow up, I want to be a watermelon");
+
+ std::string body(reinterpret_cast<const char*>(kRecordSize),
+ sizeof(kRecordSize));
+ body += kMessage.substr(0, 16);
+ body += Base64Decode("OElbplJlPK-Rv6JNK6p5_515IaoPoZo-2elWL7OQ60A");
+ body += kMessage.substr(16, 16);
+ body += Base64Decode("iPMpmgExHPrbEX3_RvwP4d16fWlK4l--p75PUu_KyN0");
+ body += kMessage.substr(32);
+
+ source()->AddReadResult(body.data(), body.size(), net::OK, GetParam().mode);
+ source()->AddReadResult(nullptr, 0, net::OK, GetParam().mode);
+ std::string actual_output;
+ int rv = ReadStream(&actual_output);
+ EXPECT_EQ(static_cast<int>(kMessage.size()), rv);
+ EXPECT_EQ(kMessage, actual_output);
}
TEST_P(MerkleIntegritySourceStreamTest, MultipleRecordsWrongLastRecordHash) {
Init(kMIMultipleRecords);
- const uint8_t record_size[] = {0, 0, 0, 0, 0, 0, 0, 16};
- const std::string message("When I grow up, I want to be a watermelon!");
+ const uint8_t kRecordSize[] = {0, 0, 0, 0, 0, 0, 0, 16};
+ const std::string kMessage("When I grow up, I want to be a watermelon!");
- source()->AddReadResult(reinterpret_cast<const char*>(record_size),
- sizeof(record_size), net::OK, GetParam().mode);
- source()->AddReadResult(message.data(), 16, net::OK, GetParam().mode);
+ source()->AddReadResult(reinterpret_cast<const char*>(kRecordSize),
+ sizeof(kRecordSize), net::OK, GetParam().mode);
+ source()->AddReadResult(kMessage.data(), 16, net::OK, GetParam().mode);
std::string hash1 =
Base64Decode("OElbplJlPK-Rv6JNK6p5_515IaoPoZo-2elWL7OQ60A");
source()->AddReadResult(hash1.data(), 32, net::OK, GetParam().mode);
- source()->AddReadResult(message.data() + 16, 16, net::OK, GetParam().mode);
+ source()->AddReadResult(kMessage.data() + 16, 16, net::OK, GetParam().mode);
std::string hash2 =
Base64Decode("iPMpmgExHPrbEX3_RvwP4d16fWlK4l--p75PUu_KyN0");
source()->AddReadResult(hash2.data(), 32, net::OK, GetParam().mode);
- source()->AddReadResult(message.data() + 32, message.size() - 32, net::OK,
+ source()->AddReadResult(kMessage.data() + 32, kMessage.size() - 32, net::OK,
GetParam().mode);
source()->AddReadResult(nullptr, 0, net::OK, GetParam().mode);
std::string actual_output;
int rv = ReadStream(&actual_output);
EXPECT_EQ(net::ERR_CONTENT_DECODING_FAILED, rv);
- EXPECT_EQ(message.substr(0, 32), actual_output);
+ EXPECT_EQ(kMessage.substr(0, 32), actual_output);
+}
+
+TEST_P(MerkleIntegritySourceStreamTest, MultipleRecordsWrongFirstRecordHash) {
+ Init(kMIEmptyBody);
+ const uint8_t kRecordSize[] = {0, 0, 0, 0, 0, 0, 0, 16};
+ const std::string kMessage("When I grow up, I want to be a watermelon!");
+
+ source()->AddReadResult(reinterpret_cast<const char*>(kRecordSize),
+ sizeof(kRecordSize), net::OK, GetParam().mode);
+ source()->AddReadResult(kMessage.data(), 16, net::OK, GetParam().mode);
+ std::string hash1 =
+ Base64Decode("OElbplJlPK-Rv6JNK6p5_515IaoPoZo-2elWL7OQ60A");
+ source()->AddReadResult(hash1.data(), 32, net::OK, GetParam().mode);
+
+ std::string actual_output;
+ int rv = ReadStream(&actual_output);
+ EXPECT_EQ(net::ERR_CONTENT_DECODING_FAILED, rv);
+ EXPECT_EQ("", actual_output);
+}
+
+TEST_P(MerkleIntegritySourceStreamTest, TrailingNetError) {
+ Init(kMIMultipleRecords);
+ const uint8_t kRecordSize[] = {0, 0, 0, 0, 0, 0, 0, 16};
+ const std::string kMessage("When I grow up, I want to be a watermelon");
+
+ source()->AddReadResult(reinterpret_cast<const char*>(kRecordSize),
+ sizeof(kRecordSize), net::OK, GetParam().mode);
+ source()->AddReadResult(kMessage.data(), 16, net::OK, GetParam().mode);
+ std::string hash1 =
+ Base64Decode("OElbplJlPK-Rv6JNK6p5_515IaoPoZo-2elWL7OQ60A");
+ source()->AddReadResult(hash1.data(), 32, net::OK, GetParam().mode);
+ source()->AddReadResult(kMessage.data() + 16, 16, net::OK, GetParam().mode);
+ std::string hash2 =
+ Base64Decode("iPMpmgExHPrbEX3_RvwP4d16fWlK4l--p75PUu_KyN0");
+ source()->AddReadResult(hash2.data(), 32, net::OK, GetParam().mode);
+ source()->AddReadResult(kMessage.data() + 32, kMessage.size() - 32, net::OK,
+ GetParam().mode);
+ source()->AddReadResult(nullptr, 0, net::ERR_FAILED, GetParam().mode);
+
+ std::string actual_output;
+ int rv = ReadStream(&actual_output);
+ EXPECT_EQ(net::ERR_FAILED, rv);
+ // MerkleIntegritySourceStream cannot read the last record without a clean EOF
+ // to denote its end.
+ EXPECT_EQ(kMessage.substr(0, 32), actual_output);
+}
+
+// Test that truncations are noticed, by way of the final record not matching
+// the hash.
+TEST_P(MerkleIntegritySourceStreamTest, Truncated) {
+ Init(kMIMultipleRecords);
+ const uint8_t kRecordSize[] = {0, 0, 0, 0, 0, 0, 0, 16};
+ const std::string kMessage("When I grow up, I want to be a w");
+
+ source()->AddReadResult(reinterpret_cast<const char*>(kRecordSize),
+ sizeof(kRecordSize), net::OK, GetParam().mode);
+ source()->AddReadResult(kMessage.data(), 16, net::OK, GetParam().mode);
+ std::string hash1 =
+ Base64Decode("OElbplJlPK-Rv6JNK6p5_515IaoPoZo-2elWL7OQ60A");
+ source()->AddReadResult(hash1.data(), 32, net::OK, GetParam().mode);
+ source()->AddReadResult(kMessage.data() + 16, 16, net::OK, GetParam().mode);
+ std::string hash2 =
+ Base64Decode("iPMpmgExHPrbEX3_RvwP4d16fWlK4l--p75PUu_KyN0");
+ source()->AddReadResult(hash2.data(), 32, net::OK, GetParam().mode);
+ // |hash2| is the hash of "atermelon", but this stream ends early. Decoding
+ // thus should fail.
+ source()->AddReadResult(nullptr, 0, net::OK, GetParam().mode);
+
+ std::string actual_output;
+ int rv = ReadStream(&actual_output);
+ EXPECT_EQ(net::ERR_CONTENT_DECODING_FAILED, rv);
+ EXPECT_EQ(kMessage, actual_output);
+}
+
+// Test that the final record is allowed to be empty.
+//
+// TODO(davidben): This does not match the specification and means some inputs
+// have two valid encodings. However, the specification's version cannot
+// represent the empty string. Update the code and possibly this test depending
+// on how https://github.com/martinthomson/http-mice/issues/3 is resolved.
+TEST_P(MerkleIntegritySourceStreamTest, EmptyFinalRecord) {
+ Init("mi-sha256=JJnIuaOEc2247K9V88VQAQy1GJuQ6ylaVM7mG69QkE4");
+ const uint8_t kRecordSize[] = {0, 0, 0, 0, 0, 0, 0, 16};
+ const std::string kMessage(
+ "When I grow up, I want to be a watermelon!! \xf0\x9f\x8d\x89");
+
+ source()->AddReadResult(reinterpret_cast<const char*>(kRecordSize),
+ sizeof(kRecordSize), net::OK, GetParam().mode);
+ source()->AddReadResult(kMessage.data(), 16, net::OK, GetParam().mode);
+ std::string hash1 =
+ Base64Decode("hhJEKpkbuZoWUjzBPAZxMUN2DXdJ6epkS0McZh77IXo");
+ source()->AddReadResult(hash1.data(), 32, net::OK, GetParam().mode);
+ source()->AddReadResult(kMessage.data() + 16, 16, net::OK, GetParam().mode);
+ std::string hash2 =
+ Base64Decode("RKTTVSMiH3bkxUQKreVATPL1KUd5eqRdmDgRQcZq_80");
+ source()->AddReadResult(hash2.data(), 32, net::OK, GetParam().mode);
+ source()->AddReadResult(kMessage.data() + 32, 16, net::OK, GetParam().mode);
+ std::string hash3 =
+ Base64Decode("bjQLnP-zepicpUTmu3gKLHiQHT-zNzh2hRGjBhevoB0");
+ source()->AddReadResult(hash3.data(), 32, net::OK, GetParam().mode);
+ source()->AddReadResult(nullptr, 0, net::OK, GetParam().mode);
+
+ std::string actual_output;
+ int rv = ReadStream(&actual_output);
+ EXPECT_EQ(static_cast<int>(kMessage.size()), rv);
+ EXPECT_EQ(kMessage, actual_output);
+}
+
+TEST_P(MerkleIntegritySourceStreamTest, WholeNumberOfRecords) {
+ Init(kMIWholeNumberOfRecords);
+ const uint8_t kRecordSize[] = {0, 0, 0, 0, 0, 0, 0, 16};
+ const std::string kMessage(
+ "When I grow up, I want to be a watermelon!! \xf0\x9f\x8d\x89");
+
+ source()->AddReadResult(reinterpret_cast<const char*>(kRecordSize),
+ sizeof(kRecordSize), net::OK, GetParam().mode);
+ source()->AddReadResult(kMessage.data(), 16, net::OK, GetParam().mode);
+ std::string hash1 =
+ Base64Decode("2s-MNG6NrTt556s__HYnQTjG3WOktEcXZ61O8mzG9f4");
+ source()->AddReadResult(hash1.data(), 32, net::OK, GetParam().mode);
+ source()->AddReadResult(kMessage.data() + 16, 16, net::OK, GetParam().mode);
+ std::string hash2 =
+ Base64Decode("qa_cQSMjFyZsm0cnYG4H6LqwOM_hzMSclK6I8iVoZYQ");
+ source()->AddReadResult(hash2.data(), 32, net::OK, GetParam().mode);
+ source()->AddReadResult(kMessage.data() + 32, 16, net::OK, GetParam().mode);
+
+ source()->AddReadResult(nullptr, 0, net::OK, GetParam().mode);
+ std::string actual_output;
+ int rv = ReadStream(&actual_output);
+ EXPECT_EQ(static_cast<int>(kMessage.size()), rv);
+ EXPECT_EQ(kMessage, actual_output);
+}
+
+TEST_P(MerkleIntegritySourceStreamTest, WholeNumberOfRecordsAllAtOnce) {
+ Init(kMIWholeNumberOfRecords);
+ const uint8_t kRecordSize[] = {0, 0, 0, 0, 0, 0, 0, 16};
+ const std::string kMessage(
+ "When I grow up, I want to be a watermelon!! \xf0\x9f\x8d\x89");
+ std::string body(reinterpret_cast<const char*>(kRecordSize),
+ sizeof(kRecordSize));
+ body += kMessage.substr(0, 16);
+ body += Base64Decode("2s-MNG6NrTt556s__HYnQTjG3WOktEcXZ61O8mzG9f4");
+ body += kMessage.substr(16, 16);
+ body += Base64Decode("qa_cQSMjFyZsm0cnYG4H6LqwOM_hzMSclK6I8iVoZYQ");
+ body += kMessage.substr(32, 16);
+
+ source()->AddReadResult(body.data(), body.size(), net::OK, GetParam().mode);
+ source()->AddReadResult(nullptr, 0, net::OK, GetParam().mode);
+ std::string actual_output;
+ int rv = ReadStream(&actual_output);
+ EXPECT_EQ(static_cast<int>(kMessage.size()), rv);
+ EXPECT_EQ(kMessage, actual_output);
}
} // namespace content
diff --git a/chromium/content/browser/loader/mime_sniffing_resource_handler.cc b/chromium/content/browser/loader/mime_sniffing_resource_handler.cc
index a9322bc8b5d..577f62b57ff 100644
--- a/chromium/content/browser/loader/mime_sniffing_resource_handler.cc
+++ b/chromium/content/browser/loader/mime_sniffing_resource_handler.cc
@@ -37,10 +37,10 @@
#include "net/http/http_content_disposition.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_request.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#include "services/network/loader_util.h"
#include "services/network/public/cpp/resource_response.h"
-#include "third_party/WebKit/public/common/mime_util/mime_util.h"
+#include "third_party/blink/public/common/mime_util/mime_util.h"
#include "url/origin.h"
namespace content {
diff --git a/chromium/content/browser/loader/mime_sniffing_resource_handler.h b/chromium/content/browser/loader/mime_sniffing_resource_handler.h
index 807f77e09db..b1223d34f3d 100644
--- a/chromium/content/browser/loader/mime_sniffing_resource_handler.h
+++ b/chromium/content/browser/loader/mime_sniffing_resource_handler.h
@@ -15,7 +15,7 @@
#include "content/browser/loader/resource_controller.h"
#include "content/common/content_export.h"
#include "content/public/common/request_context_type.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
namespace net {
class URLRequest;
diff --git a/chromium/content/browser/loader/mime_sniffing_resource_handler_unittest.cc b/chromium/content/browser/loader/mime_sniffing_resource_handler_unittest.cc
index 60db4bac8f8..6ac35383ea9 100644
--- a/chromium/content/browser/loader/mime_sniffing_resource_handler_unittest.cc
+++ b/chromium/content/browser/loader/mime_sniffing_resource_handler_unittest.cc
@@ -13,7 +13,6 @@
#include "base/location.h"
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
@@ -31,7 +30,7 @@
#include "content/test/fake_plugin_service.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "net/url_request/url_request_context.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#include "services/network/public/cpp/resource_response.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
diff --git a/chromium/content/browser/loader/mock_resource_loader.cc b/chromium/content/browser/loader/mock_resource_loader.cc
index 309760febfa..7444b0ad792 100644
--- a/chromium/content/browser/loader/mock_resource_loader.cc
+++ b/chromium/content/browser/loader/mock_resource_loader.cc
@@ -6,7 +6,6 @@
#include <memory>
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "content/browser/loader/resource_controller.h"
#include "content/browser/loader/resource_handler.h"
diff --git a/chromium/content/browser/loader/mojo_async_resource_handler.cc b/chromium/content/browser/loader/mojo_async_resource_handler.cc
index 8ad8f67ab93..601641fd9f0 100644
--- a/chromium/content/browser/loader/mojo_async_resource_handler.cc
+++ b/chromium/content/browser/loader/mojo_async_resource_handler.cc
@@ -12,7 +12,6 @@
#include "base/location.h"
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/time/time.h"
#include "content/browser/loader/downloaded_temp_file_impl.h"
#include "content/browser/loader/navigation_metrics.h"
@@ -104,7 +103,9 @@ MojoAsyncResourceHandler::MojoAsyncResourceHandler(
rdh_(rdh),
binding_(this, std::move(mojo_request)),
url_loader_options_(url_loader_options),
- handle_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL),
+ handle_watcher_(FROM_HERE,
+ mojo::SimpleWatcher::ArmingPolicy::MANUAL,
+ base::SequencedTaskRunnerHandle::Get()),
url_loader_client_(std::move(url_loader_client)),
weak_factory_(this) {
DCHECK(IsResourceTypeFrame(resource_type) ||
@@ -192,12 +193,13 @@ void MojoAsyncResourceHandler::OnResponseStarted(
response->head.download_file_path);
}
- base::Optional<net::SSLInfo> ssl_info;
- if (url_loader_options_ &
- network::mojom::kURLLoadOptionSendSSLInfoWithResponse)
- ssl_info = request()->ssl_info();
+ if ((url_loader_options_ &
+ network::mojom::kURLLoadOptionSendSSLInfoWithResponse) &&
+ request()->ssl_info().cert) {
+ response->head.ssl_info = request()->ssl_info();
+ }
- url_loader_client_->OnReceiveResponse(response->head, std::move(ssl_info),
+ url_loader_client_->OnReceiveResponse(response->head,
std::move(downloaded_file_ptr));
net::IOBufferWithSize* metadata = GetResponseMetadata(request());
@@ -486,6 +488,11 @@ void MojoAsyncResourceHandler::OnResponseCompleted(
network::URLLoaderCompletionStatus loader_status;
loader_status.error_code = error_code;
+ if (error_code == net::ERR_QUIC_PROTOCOL_ERROR) {
+ net::NetErrorDetails details;
+ request()->PopulateNetErrorDetails(&details);
+ loader_status.extended_error_code = details.quic_connection_error;
+ }
loader_status.exists_in_cache = request()->response_info().was_cached;
loader_status.completion_time = base::TimeTicks::Now();
loader_status.encoded_data_length = request()->GetTotalReceivedBytes();
diff --git a/chromium/content/browser/loader/mojo_async_resource_handler_unittest.cc b/chromium/content/browser/loader/mojo_async_resource_handler_unittest.cc
index 7e49dc562ff..b71fba4bfb3 100644
--- a/chromium/content/browser/loader/mojo_async_resource_handler_unittest.cc
+++ b/chromium/content/browser/loader/mojo_async_resource_handler_unittest.cc
@@ -14,7 +14,6 @@
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/weak_ptr.h"
#include "base/run_loop.h"
#include "base/test/gtest_util.h"
@@ -45,6 +44,7 @@
#include "net/http/http_status_code.h"
#include "net/http/http_util.h"
#include "net/ssl/ssl_info.h"
+#include "net/test/cert_test_util.h"
#include "net/test/url_request/url_request_mock_data_job.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "net/url_request/url_request.h"
@@ -132,13 +132,6 @@ class TestResourceDispatcherHostDelegate final
ADD_FAILURE() << "DownloadStarting should not be called.";
}
- bool HandleExternalProtocol(
- const GURL& url,
- ResourceRequestInfo* resource_request_info) override {
- ADD_FAILURE() << "HandleExternalProtocol should not be called.";
- return false;
- }
-
bool ShouldInterceptResourceAsStream(net::URLRequest* request,
const std::string& mime_type,
GURL* origin,
@@ -403,6 +396,13 @@ class MojoAsyncResourceHandlerTestBase {
handler_->upload_progress_tracker()->current_time_ += delta;
}
+ void SetupRequestSSLInfo() {
+ net::CertificateList certs;
+ ASSERT_TRUE(net::LoadCertificateFiles({"multi-root-B-by-C.pem"}, &certs));
+ ASSERT_EQ(1U, certs.size());
+ const_cast<net::SSLInfo&>(request_->ssl_info()).cert = certs[0];
+ }
+
TestBrowserThreadBundle thread_bundle_;
TestResourceDispatcherHostDelegate rdh_delegate_;
ResourceDispatcherHostImpl rdh_;
@@ -1401,6 +1401,7 @@ TEST_F(MojoAsyncResourceHandlerDeferOnResponseStartedTest,
// Test that SSLInfo is not attached to OnResponseStarted when there is no
// kURLLoadOptionsSendSSLInfoWithResponse option.
TEST_F(MojoAsyncResourceHandlerTest, SSLInfoOnResponseStarted) {
+ SetupRequestSSLInfo();
EXPECT_TRUE(CallOnWillStartAndOnResponseStarted());
EXPECT_FALSE(url_loader_client_.ssl_info());
}
@@ -1409,6 +1410,7 @@ TEST_F(MojoAsyncResourceHandlerTest, SSLInfoOnResponseStarted) {
// kURLLoadOptionsSendSSLInfoWithResponse option.
TEST_F(MojoAsyncResourceHandlerSendSSLInfoWithResponseTest,
SSLInfoOnResponseStarted) {
+ SetupRequestSSLInfo();
EXPECT_TRUE(CallOnWillStartAndOnResponseStarted());
EXPECT_TRUE(url_loader_client_.ssl_info());
}
diff --git a/chromium/content/browser/loader/url_loader_request_handler.cc b/chromium/content/browser/loader/navigation_loader_interceptor.cc
index d4aa8e24cf7..957753b1a9a 100644
--- a/chromium/content/browser/loader/url_loader_request_handler.cc
+++ b/chromium/content/browser/loader/navigation_loader_interceptor.cc
@@ -2,18 +2,18 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "content/browser/loader/url_loader_request_handler.h"
+#include "content/browser/loader/navigation_loader_interceptor.h"
#include "content/common/navigation_subresource_loader_params.h"
namespace content {
base::Optional<SubresourceLoaderParams>
-URLLoaderRequestHandler::MaybeCreateSubresourceLoaderParams() {
+NavigationLoaderInterceptor::MaybeCreateSubresourceLoaderParams() {
return base::nullopt;
}
-bool URLLoaderRequestHandler::MaybeCreateLoaderForResponse(
+bool NavigationLoaderInterceptor::MaybeCreateLoaderForResponse(
const network::ResourceResponseHead& response,
network::mojom::URLLoaderPtr* loader,
network::mojom::URLLoaderClientRequest* client_request,
diff --git a/chromium/content/browser/loader/url_loader_request_handler.h b/chromium/content/browser/loader/navigation_loader_interceptor.h
index 46976df9dfe..2f4ad19e0ba 100644
--- a/chromium/content/browser/loader/url_loader_request_handler.h
+++ b/chromium/content/browser/loader/navigation_loader_interceptor.h
@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef CONTENT_BROWSER_LOADER_URL_LOADER_REQUEST_HANDLER_H_
-#define CONTENT_BROWSER_LOADER_URL_LOADER_REQUEST_HANDLER_H_
+#ifndef CONTENT_BROWSER_LOADER_NAVIGATION_LOADER_INTERCEPTOR_H_
+#define CONTENT_BROWSER_LOADER_NAVIGATION_LOADER_INTERCEPTOR_H_
#include <memory>
@@ -23,12 +23,15 @@ struct ResourceRequest;
struct SubresourceLoaderParams;
class ThrottlingURLLoader;
-// An instance of this class is a per-request object and kept around during
-// the lifetime of a request (including multiple redirect legs) on IO thread.
-class CONTENT_EXPORT URLLoaderRequestHandler {
+// NavigationLoaderInterceptor is given a chance to create a URLLoader and
+// intercept a navigation request before the request is handed off to the
+// default URLLoader, e.g. the one from the network service.
+// NavigationLoaderInterceptor is a per-request object and kept around during
+// the lifetime of a navigation request (including multiple redirect legs).
+class CONTENT_EXPORT NavigationLoaderInterceptor {
public:
- URLLoaderRequestHandler() = default;
- virtual ~URLLoaderRequestHandler() = default;
+ NavigationLoaderInterceptor() = default;
+ virtual ~NavigationLoaderInterceptor() = default;
using LoaderCallback =
base::OnceCallback<void(SingleRequestURLLoaderFactory::RequestHandler)>;
@@ -73,4 +76,4 @@ class CONTENT_EXPORT URLLoaderRequestHandler {
} // namespace content
-#endif // CONTENT_BROWSER_LOADER_URL_LOADER_REQUEST_HANDLER_H_
+#endif // CONTENT_BROWSER_LOADER_NAVIGATION_LOADER_INTERCEPTOR_H_
diff --git a/chromium/content/browser/loader/navigation_resource_handler.cc b/chromium/content/browser/loader/navigation_resource_handler.cc
index f4bb551151b..e0ee350c523 100644
--- a/chromium/content/browser/loader/navigation_resource_handler.cc
+++ b/chromium/content/browser/loader/navigation_resource_handler.cc
@@ -120,6 +120,8 @@ void NavigationResourceHandler::OnResponseStarted(
ResourceRequestInfoImpl* info = GetRequestInfo();
response->head.encoded_data_length = request()->raw_header_size();
+ if (request()->ssl_info().cert)
+ response->head.ssl_info = request()->ssl_info();
std::unique_ptr<NavigationData> cloned_data;
if (resource_dispatcher_host_delegate_) {
@@ -132,10 +134,9 @@ void NavigationResourceHandler::OnResponseStarted(
cloned_data = navigation_data->Clone();
}
- core_->NotifyResponseStarted(response, std::move(stream_handle_),
- request()->ssl_info(), std::move(cloned_data),
- info->GetGlobalRequestID(), info->IsDownload(),
- info->is_stream());
+ core_->NotifyResponseStarted(
+ response, std::move(stream_handle_), std::move(cloned_data),
+ info->GetGlobalRequestID(), info->IsDownload(), info->is_stream());
HoldController(std::move(controller));
response_ = response;
}
diff --git a/chromium/content/browser/loader/navigation_url_loader.cc b/chromium/content/browser/loader/navigation_url_loader.cc
index 3eecf603364..7222ef1fa7c 100644
--- a/chromium/content/browser/loader/navigation_url_loader.cc
+++ b/chromium/content/browser/loader/navigation_url_loader.cc
@@ -7,12 +7,11 @@
#include <utility>
#include "base/command_line.h"
-#include "base/memory/ptr_util.h"
#include "content/browser/frame_host/navigation_request_info.h"
+#include "content/browser/loader/navigation_loader_interceptor.h"
#include "content/browser/loader/navigation_url_loader_factory.h"
#include "content/browser/loader/navigation_url_loader_impl.h"
#include "content/browser/loader/navigation_url_loader_network_service.h"
-#include "content/browser/loader/url_loader_request_handler.h"
#include "content/public/browser/navigation_ui_data.h"
#include "content/public/common/browser_side_navigation_policy.h"
#include "services/network/public/cpp/features.h"
@@ -34,12 +33,11 @@ std::unique_ptr<NavigationURLLoader> NavigationURLLoader::Create(
resource_context, storage_partition, std::move(request_info),
std::move(navigation_ui_data), service_worker_handle, delegate);
}
- if (base::FeatureList::IsEnabled(network::features::kNetworkService) ||
- IsNavigationMojoResponseEnabled()) {
+ if (IsNavigationMojoResponseEnabled()) {
return std::make_unique<NavigationURLLoaderNetworkService>(
resource_context, storage_partition, std::move(request_info),
std::move(navigation_ui_data), service_worker_handle, appcache_handle,
- delegate, std::vector<std::unique_ptr<URLLoaderRequestHandler>>());
+ delegate, std::vector<std::unique_ptr<NavigationLoaderInterceptor>>());
} else {
return std::make_unique<NavigationURLLoaderImpl>(
resource_context, storage_partition, std::move(request_info),
diff --git a/chromium/content/browser/loader/navigation_url_loader_delegate.h b/chromium/content/browser/loader/navigation_url_loader_delegate.h
index c3d6fa5881a..d7f694a942f 100644
--- a/chromium/content/browser/loader/navigation_url_loader_delegate.h
+++ b/chromium/content/browser/loader/navigation_url_loader_delegate.h
@@ -52,7 +52,6 @@ class CONTENT_EXPORT NavigationURLLoaderDelegate {
const scoped_refptr<network::ResourceResponse>& response,
network::mojom::URLLoaderClientEndpointsPtr url_loader_client_endpoints,
std::unique_ptr<StreamHandle> body_stream,
- const net::SSLInfo& ssl_info,
std::unique_ptr<NavigationData> navigation_data,
const GlobalRequestID& request_id,
bool is_download,
diff --git a/chromium/content/browser/loader/navigation_url_loader_impl.cc b/chromium/content/browser/loader/navigation_url_loader_impl.cc
index 00f550504d4..687e6a6aff9 100644
--- a/chromium/content/browser/loader/navigation_url_loader_impl.cc
+++ b/chromium/content/browser/loader/navigation_url_loader_impl.cc
@@ -98,7 +98,6 @@ void NavigationURLLoaderImpl::NotifyRequestRedirected(
void NavigationURLLoaderImpl::NotifyResponseStarted(
const scoped_refptr<network::ResourceResponse>& response,
std::unique_ptr<StreamHandle> body,
- const net::SSLInfo& ssl_info,
std::unique_ptr<NavigationData> navigation_data,
const GlobalRequestID& request_id,
bool is_download,
@@ -107,9 +106,10 @@ void NavigationURLLoaderImpl::NotifyResponseStarted(
delegate_->OnResponseStarted(
response, network::mojom::URLLoaderClientEndpointsPtr(), std::move(body),
- ssl_info, std::move(navigation_data), request_id, is_download, is_stream,
+ std::move(navigation_data), request_id, is_download, is_stream,
base::nullopt);
}
+
void NavigationURLLoaderImpl::NotifyRequestFailed(
bool in_cache,
int net_error,
diff --git a/chromium/content/browser/loader/navigation_url_loader_impl.h b/chromium/content/browser/loader/navigation_url_loader_impl.h
index 396939d705c..7060fce6580 100644
--- a/chromium/content/browser/loader/navigation_url_loader_impl.h
+++ b/chromium/content/browser/loader/navigation_url_loader_impl.h
@@ -60,7 +60,6 @@ class NavigationURLLoaderImpl : public NavigationURLLoader {
void NotifyResponseStarted(
const scoped_refptr<network::ResourceResponse>& response,
std::unique_ptr<StreamHandle> body,
- const net::SSLInfo& ssl_info,
std::unique_ptr<NavigationData> navigation_data,
const GlobalRequestID& request_id,
bool is_download,
diff --git a/chromium/content/browser/loader/navigation_url_loader_impl_core.cc b/chromium/content/browser/loader/navigation_url_loader_impl_core.cc
index 0889976055d..c4683b44905 100644
--- a/chromium/content/browser/loader/navigation_url_loader_impl_core.cc
+++ b/chromium/content/browser/loader/navigation_url_loader_impl_core.cc
@@ -50,6 +50,10 @@ void NavigationURLLoaderImplCore::Start(
base::WeakPtr<NavigationURLLoaderImplCore> weak_this =
weak_factory_.GetWeakPtr();
+ uint32_t options = network::mojom::kURLLoadOptionSendSSLInfoWithResponse;
+ if (request_info->is_main_frame)
+ options |= network::mojom::kURLLoadOptionSendSSLInfoForCertificateError;
+
// The ResourceDispatcherHostImpl can be null in unit tests.
if (ResourceDispatcherHostImpl::Get()) {
GlobalRequestID global_request_id; // unused.
@@ -59,8 +63,7 @@ void NavigationURLLoaderImplCore::Start(
std::move(navigation_ui_data), this,
network::mojom::URLLoaderClientPtr(),
network::mojom::URLLoaderRequest(), service_worker_handle_core,
- appcache_handle_core, network::mojom::kURLLoadOptionNone,
- &global_request_id);
+ appcache_handle_core, options, &global_request_id);
}
// Careful, |this| could be destroyed at this point. Don't notify start if
@@ -121,7 +124,6 @@ void NavigationURLLoaderImplCore::NotifyRequestRedirected(
void NavigationURLLoaderImplCore::NotifyResponseStarted(
network::ResourceResponse* response,
std::unique_ptr<StreamHandle> body,
- const net::SSLInfo& ssl_info,
std::unique_ptr<NavigationData> navigation_data,
const GlobalRequestID& request_id,
bool is_download,
@@ -143,7 +145,7 @@ void NavigationURLLoaderImplCore::NotifyResponseStarted(
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::BindOnce(&NavigationURLLoaderImpl::NotifyResponseStarted, loader_,
- response->DeepCopy(), std::move(body), ssl_info,
+ response->DeepCopy(), std::move(body),
std::move(navigation_data), request_id, is_download,
is_stream));
}
diff --git a/chromium/content/browser/loader/navigation_url_loader_impl_core.h b/chromium/content/browser/loader/navigation_url_loader_impl_core.h
index 60986764bd0..5b3bad89726 100644
--- a/chromium/content/browser/loader/navigation_url_loader_impl_core.h
+++ b/chromium/content/browser/loader/navigation_url_loader_impl_core.h
@@ -78,7 +78,6 @@ class NavigationURLLoaderImplCore
// Notifies |loader_| on the UI thread that the response started.
void NotifyResponseStarted(network::ResourceResponse* response,
std::unique_ptr<StreamHandle> body,
- const net::SSLInfo& ssl_info,
std::unique_ptr<NavigationData> navigation_data,
const GlobalRequestID& request_id,
bool is_download,
diff --git a/chromium/content/browser/loader/navigation_url_loader_network_service.cc b/chromium/content/browser/loader/navigation_url_loader_network_service.cc
index 6e0b9d68ccb..4b7db1b992e 100644
--- a/chromium/content/browser/loader/navigation_url_loader_network_service.cc
+++ b/chromium/content/browser/loader/navigation_url_loader_network_service.cc
@@ -16,14 +16,15 @@
#include "content/browser/appcache/appcache_navigation_handle.h"
#include "content/browser/appcache/appcache_request_handler.h"
#include "content/browser/blob_storage/chrome_blob_storage_context.h"
+#include "content/browser/devtools/render_frame_devtools_agent_host.h"
#include "content/browser/file_url_loader_factory.h"
#include "content/browser/frame_host/frame_tree_node.h"
#include "content/browser/frame_host/navigation_request_info.h"
+#include "content/browser/loader/navigation_loader_interceptor.h"
#include "content/browser/loader/navigation_resource_handler.h"
#include "content/browser/loader/navigation_url_loader_delegate.h"
#include "content/browser/loader/resource_dispatcher_host_impl.h"
#include "content/browser/loader/resource_request_info_impl.h"
-#include "content/browser/loader/url_loader_request_handler.h"
#include "content/browser/resource_context_impl.h"
#include "content/browser/service_worker/service_worker_navigation_handle.h"
#include "content/browser/service_worker/service_worker_navigation_handle_core.h"
@@ -31,13 +32,14 @@
#include "content/browser/storage_partition_impl.h"
#include "content/browser/url_loader_factory_getter.h"
#include "content/browser/web_contents/web_contents_impl.h"
+#include "content/browser/web_package/signed_exchange_consts.h"
#include "content/browser/web_package/signed_exchange_url_loader_factory_for_non_network_service.h"
#include "content/browser/web_package/web_package_request_handler.h"
#include "content/browser/webui/url_data_manager_backend.h"
-#include "content/browser/webui/web_ui_url_loader_factory.h"
+#include "content/browser/webui/web_ui_url_loader_factory_internal.h"
#include "content/common/navigation_subresource_loader_params.h"
+#include "content/common/service_worker/service_worker_utils.h"
#include "content/common/throttling_url_loader.h"
-#include "content/common/weak_wrapper_shared_url_loader_factory.h"
#include "content/common/wrapper_shared_url_loader_factory.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
@@ -48,10 +50,13 @@
#include "content/public/browser/resource_dispatcher_host_delegate.h"
#include "content/public/browser/ssl_status.h"
#include "content/public/browser/stream_handle.h"
+#include "content/public/common/browser_side_navigation_policy.h"
#include "content/public/common/content_features.h"
#include "content/public/common/referrer.h"
#include "content/public/common/url_constants.h"
#include "content/public/common/url_utils.h"
+#include "content/public/common/weak_wrapper_shared_url_loader_factory.h"
+#include "mojo/common/values_struct_traits.h"
#include "net/base/load_flags.h"
#include "net/http/http_content_disposition.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
@@ -64,15 +69,17 @@
#include "services/network/public/mojom/request_context_frame_type.mojom.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
#include "services/service_manager/public/cpp/connector.h"
-#include "third_party/WebKit/public/common/mime_util/mime_util.h"
+#include "third_party/blink/public/common/mime_util/mime_util.h"
namespace content {
namespace {
-bool IsRequestHandlerEnabled() {
+// Returns true if interception by NavigationLoaderInterceptors is enabled.
+bool IsLoaderInterceptionEnabled() {
return base::FeatureList::IsEnabled(network::features::kNetworkService) ||
- base::FeatureList::IsEnabled(features::kSignedHTTPExchange);
+ base::FeatureList::IsEnabled(features::kSignedHTTPExchange) ||
+ ServiceWorkerUtils::IsServicificationEnabled();
}
// Request ID for browser initiated requests. We start at -2 on the same lines
@@ -221,8 +228,14 @@ std::unique_ptr<network::ResourceRequest> CreateResourceRequest(
request_info->common_params.referrer.policy);
new_request->headers.AddHeadersFromString(
request_info->begin_params->headers);
- new_request->headers.SetHeader(network::kAcceptHeader,
- network::kFrameAcceptHeader);
+
+ std::string accept_value = network::kFrameAcceptHeader;
+ if (base::FeatureList::IsEnabled(features::kSignedHTTPExchange)) {
+ DCHECK(!accept_value.empty());
+ accept_value.append(kAcceptHeaderSignedExchangeSuffix);
+ }
+
+ new_request->headers.SetHeader(network::kAcceptHeader, accept_value);
new_request->resource_type = request_info->is_main_frame
? RESOURCE_TYPE_MAIN_FRAME
@@ -231,7 +244,6 @@ std::unique_ptr<network::ResourceRequest> CreateResourceRequest(
new_request->update_first_party_url_on_redirect = true;
int load_flags = request_info->begin_params->load_flags;
- load_flags |= net::LOAD_VERIFY_EV_CERT;
if (request_info->is_main_frame)
load_flags |= net::LOAD_MAIN_FRAME_DEPRECATED;
@@ -250,15 +262,61 @@ std::unique_ptr<network::ResourceRequest> CreateResourceRequest(
new_request->fetch_credentials_mode =
network::mojom::FetchCredentialsMode::kInclude;
new_request->fetch_redirect_mode = network::mojom::FetchRedirectMode::kManual;
+ new_request->fetch_request_context_type =
+ request_info->begin_params->request_context_type;
return new_request;
}
+// Used only when NetworkService is disabled but IsLoaderInterceptionEnabled()
+// is true.
+std::unique_ptr<NavigationRequestInfo> CreateNavigationRequestInfoForRedirect(
+ const NavigationRequestInfo& previous_request_info,
+ const network::ResourceRequest& updated_resource_request) {
+ DCHECK(!base::FeatureList::IsEnabled(network::features::kNetworkService));
+ DCHECK(IsLoaderInterceptionEnabled());
+
+ CommonNavigationParams new_common_params =
+ previous_request_info.common_params;
+ new_common_params.url = updated_resource_request.url;
+ new_common_params.referrer =
+ Referrer(updated_resource_request.url,
+ Referrer::NetReferrerPolicyToBlinkReferrerPolicy(
+ updated_resource_request.referrer_policy));
+ new_common_params.method = updated_resource_request.method;
+ new_common_params.post_data = updated_resource_request.request_body;
+ // TODO(shimazu): Set correct base url and history url for a data URL.
+
+ mojom::BeginNavigationParamsPtr new_begin_params =
+ previous_request_info.begin_params.Clone();
+ new_begin_params->headers = updated_resource_request.headers.ToString();
+
+ return std::make_unique<NavigationRequestInfo>(
+ std::move(new_common_params), std::move(new_begin_params),
+ updated_resource_request.site_for_cookies,
+ previous_request_info.is_main_frame,
+ previous_request_info.parent_is_main_frame,
+ previous_request_info.are_ancestors_secure,
+ previous_request_info.frame_tree_node_id,
+ previous_request_info.is_for_guests_only,
+ previous_request_info.report_raw_headers,
+ previous_request_info.is_prerendering,
+ nullptr /* blob_url_loader_factory */);
+}
+
+// Called for requests that we don't have a URLLoaderFactory for.
+void UnknownSchemeCallback(bool handled_externally,
+ network::mojom::URLLoaderRequest request,
+ network::mojom::URLLoaderClientPtr client) {
+ client->OnComplete(network::URLLoaderCompletionStatus(
+ handled_externally ? net::ERR_ABORTED : net::ERR_UNKNOWN_URL_SCHEME));
+}
+
} // namespace
// Kept around during the lifetime of the navigation request, and is
// responsible for dispatching a ResourceRequest to the appropriate
// URLLoader. In order to get the right URLLoader it builds a vector
-// of URLLoaderRequestHandler's and successively calls MaybeCreateLoader
+// of NavigationLoaderInterceptors and successively calls MaybeCreateLoader
// on each until the request is successfully handled. The same sequence
// may be performed multiple times when redirects happen.
// TODO(michaeln): Expose this class and add more unittests.
@@ -266,7 +324,8 @@ class NavigationURLLoaderNetworkService::URLLoaderRequestController
: public network::mojom::URLLoaderClient {
public:
URLLoaderRequestController(
- std::vector<std::unique_ptr<URLLoaderRequestHandler>> initial_handlers,
+ std::vector<std::unique_ptr<NavigationLoaderInterceptor>>
+ initial_interceptors,
std::unique_ptr<network::ResourceRequest> resource_request,
ResourceContext* resource_context,
scoped_refptr<URLLoaderFactoryGetter> default_url_loader_factory_getter,
@@ -275,8 +334,9 @@ class NavigationURLLoaderNetworkService::URLLoaderRequestController
base::Optional<std::string> suggested_filename,
network::mojom::URLLoaderFactoryRequest proxied_factory_request,
network::mojom::URLLoaderFactoryPtrInfo proxied_factory_info,
+ std::set<std::string> known_schemes,
const base::WeakPtr<NavigationURLLoaderNetworkService>& owner)
- : handlers_(std::move(initial_handlers)),
+ : interceptors_(std::move(initial_interceptors)),
resource_request_(std::move(resource_request)),
resource_context_(resource_context),
default_url_loader_factory_getter_(default_url_loader_factory_getter),
@@ -287,6 +347,7 @@ class NavigationURLLoaderNetworkService::URLLoaderRequestController
response_loader_binding_(this),
proxied_factory_request_(std::move(proxied_factory_request)),
proxied_factory_info_(std::move(proxied_factory_info)),
+ known_schemes_(std::move(known_schemes)),
weak_factory_(this) {}
~URLLoaderRequestController() override {
@@ -310,11 +371,26 @@ class NavigationURLLoaderNetworkService::URLLoaderRequestController
return options;
}
+ SingleRequestURLLoaderFactory::RequestHandler
+ CreateDefaultRequestHandlerForNonNetworkService(
+ net::URLRequestContextGetter* url_request_context_getter,
+ storage::FileSystemContext* upload_file_system_context,
+ ServiceWorkerNavigationHandleCore* service_worker_navigation_handle_core,
+ AppCacheNavigationHandleCore* appcache_handle_core) const {
+ return base::BindOnce(
+ &URLLoaderRequestController::CreateNonNetworkServiceURLLoader,
+ weak_factory_.GetWeakPtr(),
+ base::Unretained(url_request_context_getter),
+ base::Unretained(upload_file_system_context),
+ std::make_unique<NavigationRequestInfo>(*request_info_),
+ base::Unretained(service_worker_navigation_handle_core),
+ base::Unretained(appcache_handle_core));
+ }
+
void CreateNonNetworkServiceURLLoader(
net::URLRequestContextGetter* url_request_context_getter,
storage::FileSystemContext* upload_file_system_context,
std::unique_ptr<NavigationRequestInfo> request_info,
- std::unique_ptr<NavigationUIData> navigation_ui_data,
ServiceWorkerNavigationHandleCore* service_worker_navigation_handle_core,
AppCacheNavigationHandleCore* appcache_handle_core,
network::mojom::URLLoaderRequest url_loader,
@@ -325,19 +401,21 @@ class NavigationURLLoaderNetworkService::URLLoaderRequestController
default_loader_used_ = true;
if (base::FeatureList::IsEnabled(features::kSignedHTTPExchange)) {
DCHECK(!default_url_loader_factory_getter_);
- // It is safa to pass the callback of CreateURLLoaderThrottles with the
+ // It is safe to pass the callback of CreateURLLoaderThrottles with the
// unretained |this|, because the passed callback will be used by a
// SignedExchangeHandler which is indirectly owned by |this| until its
// header is verified and parsed, that's where the getter is used.
- handlers_.push_back(std::make_unique<WebPackageRequestHandler>(
+ interceptors_.push_back(std::make_unique<WebPackageRequestHandler>(
url::Origin::Create(request_info->common_params.url),
GetURLLoaderOptions(request_info->is_main_frame),
+ request_info->frame_tree_node_id,
base::MakeRefCounted<
SignedExchangeURLLoaderFactoryForNonNetworkService>(
resource_context_, url_request_context_getter),
base::BindRepeating(
&URLLoaderRequestController::CreateURLLoaderThrottles,
- base::Unretained(this))));
+ base::Unretained(this)),
+ url_request_context_getter));
}
// The ResourceDispatcherHostImpl can be null in unit tests.
@@ -345,7 +423,7 @@ class NavigationURLLoaderNetworkService::URLLoaderRequestController
ResourceDispatcherHostImpl::Get()->BeginNavigationRequest(
resource_context_, url_request_context_getter->GetURLRequestContext(),
upload_file_system_context, *request_info,
- std::move(navigation_ui_data), nullptr, std::move(url_loader_client),
+ std::move(navigation_ui_data_), nullptr, std::move(url_loader_client),
std::move(url_loader), service_worker_navigation_handle_core,
appcache_handle_core,
GetURLLoaderOptions(request_info->is_main_frame),
@@ -368,36 +446,68 @@ class NavigationURLLoaderNetworkService::URLLoaderRequestController
AppCacheNavigationHandleCore* appcache_handle_core,
std::unique_ptr<NavigationRequestInfo> request_info,
std::unique_ptr<NavigationUIData> navigation_ui_data) {
+ DCHECK(IsNavigationMojoResponseEnabled());
DCHECK(!base::FeatureList::IsEnabled(network::features::kNetworkService));
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DCHECK(!started_);
started_ = true;
-
- frame_tree_node_id_ = request_info->frame_tree_node_id;
+ request_info_ = std::move(request_info);
+ frame_tree_node_id_ = request_info_->frame_tree_node_id;
web_contents_getter_ = base::BindRepeating(
&GetWebContentsFromFrameTreeNodeID, frame_tree_node_id_);
-
- std::vector<std::unique_ptr<content::URLLoaderThrottle>> throttles =
- GetContentClient()->browser()->CreateURLLoaderThrottles(
- *resource_request_, resource_context_, web_contents_getter_,
- navigation_ui_data.get(), frame_tree_node_id_);
-
- auto load_single_request = base::BindOnce(
- &URLLoaderRequestController::CreateNonNetworkServiceURLLoader,
- weak_factory_.GetWeakPtr(),
- base::Unretained(url_request_context_getter),
- base::Unretained(upload_file_system_context), std::move(request_info),
- std::move(navigation_ui_data),
+ navigation_ui_data_ = std::move(navigation_ui_data);
+ default_request_handler_factory_ = base::BindRepeating(
+ &URLLoaderRequestController::
+ CreateDefaultRequestHandlerForNonNetworkService,
+ // base::Unretained(this) is safe since
+ // |default_request_handler_factory_| could be called only from |this|.
+ base::Unretained(this), base::Unretained(url_request_context_getter),
+ base::Unretained(upload_file_system_context),
base::Unretained(service_worker_navigation_handle_core),
base::Unretained(appcache_handle_core));
- url_loader_ = ThrottlingURLLoader::CreateLoaderAndStart(
- base::MakeRefCounted<SingleRequestURLLoaderFactory>(
- std::move(load_single_request)),
- std::move(throttles), -1 /* routing_id */, 0 /* request_id */,
- network::mojom::kURLLoadOptionNone, resource_request_.get(),
- this /* client */, kNavigationUrlLoaderTrafficAnnotation,
- base::ThreadTaskRunnerHandle::Get());
+ // If S13nServiceWorker is disabled, just use
+ // |default_request_handler_factory_| and return. The non network service
+ // request handling goes through ResourceDispatcherHost which has legacy
+ // hooks for service worker (ServiceWorkerRequestInterceptor), so no service
+ // worker interception is needed here.
+ if (!ServiceWorkerUtils::IsServicificationEnabled() ||
+ !service_worker_navigation_handle_core) {
+ url_loader_ = ThrottlingURLLoader::CreateLoaderAndStart(
+ base::MakeRefCounted<SingleRequestURLLoaderFactory>(
+ default_request_handler_factory_.Run()),
+ CreateURLLoaderThrottles(), -1 /* routing_id */, 0 /* request_id */,
+ network::mojom::kURLLoadOptionNone, resource_request_.get(),
+ this /* client */, kNavigationUrlLoaderTrafficAnnotation,
+ base::ThreadTaskRunnerHandle::Get());
+ return;
+ }
+
+ // Otherwise, if S13nServiceWorker is enabled, create an interceptor so
+ // S13nServiceWorker has a chance to intercept the request.
+ std::unique_ptr<NavigationLoaderInterceptor> service_worker_interceptor =
+ CreateServiceWorkerInterceptor(*request_info_,
+ service_worker_navigation_handle_core);
+ // If an interceptor is not created for some reasons (e.g. the origin is not
+ // secure), we no longer have to go through the rest of the network service
+ // code.
+ if (!service_worker_interceptor) {
+ url_loader_ = ThrottlingURLLoader::CreateLoaderAndStart(
+ base::MakeRefCounted<SingleRequestURLLoaderFactory>(
+ default_request_handler_factory_.Run()),
+ CreateURLLoaderThrottles(), -1 /* routing_id */, 0 /* request_id */,
+ network::mojom::kURLLoadOptionNone, resource_request_.get(),
+ this /* client */, kNavigationUrlLoaderTrafficAnnotation,
+ base::ThreadTaskRunnerHandle::Get());
+ return;
+ }
+
+ interceptors_.push_back(std::move(service_worker_interceptor));
+
+ // TODO(shimazu): Make sure we have a consistent global id for the
+ // navigation request.
+ global_request_id_ = MakeGlobalRequestID();
+ Restart();
}
void Start(
@@ -418,9 +528,6 @@ class NavigationURLLoaderNetworkService::URLLoaderRequestController
web_contents_getter_ =
base::Bind(&GetWebContentsFromFrameTreeNodeID, frame_tree_node_id);
navigation_ui_data_ = std::move(navigation_ui_data);
- const ResourceType resource_type = request_info->is_main_frame
- ? RESOURCE_TYPE_MAIN_FRAME
- : RESOURCE_TYPE_SUB_FRAME;
if (resource_request_->request_body) {
GetBodyBlobDataHandles(resource_request_->request_body.get(),
@@ -440,48 +547,54 @@ class NavigationURLLoaderNetworkService::URLLoaderRequestController
return;
}
+ // Requests to Blob scheme won't get redirected to/from other schemes
+ // or be intercepted, so we just let it go here.
+ if (request_info->common_params.url.SchemeIsBlob() &&
+ request_info->blob_url_loader_factory) {
+ url_loader_ = ThrottlingURLLoader::CreateLoaderAndStart(
+ network::SharedURLLoaderFactory::Create(
+ std::move(request_info->blob_url_loader_factory)),
+ GetContentClient()->browser()->CreateURLLoaderThrottles(
+ *resource_request_, resource_context_, web_contents_getter_,
+ navigation_ui_data_.get(), frame_tree_node_id_),
+ 0 /* routing_id */, 0 /* request_id? */,
+ network::mojom::kURLLoadOptionNone, resource_request_.get(), this,
+ kNavigationUrlLoaderTrafficAnnotation,
+ base::ThreadTaskRunnerHandle::Get());
+ return;
+ }
+
if (service_worker_navigation_handle_core) {
- network::mojom::RequestContextFrameType frame_type =
- request_info->is_main_frame
- ? network::mojom::RequestContextFrameType::kTopLevel
- : network::mojom::RequestContextFrameType::kNested;
-
- storage::BlobStorageContext* blob_storage_context = GetBlobStorageContext(
- GetChromeBlobStorageContextForResourceContext(resource_context_));
- std::unique_ptr<URLLoaderRequestHandler> service_worker_handler =
- ServiceWorkerRequestHandler::InitializeForNavigationNetworkService(
- *resource_request_, resource_context_,
- service_worker_navigation_handle_core, blob_storage_context,
- request_info->begin_params->skip_service_worker, resource_type,
- request_info->begin_params->request_context_type, frame_type,
- request_info->are_ancestors_secure,
- request_info->common_params.post_data, web_contents_getter_);
- if (service_worker_handler)
- handlers_.push_back(std::move(service_worker_handler));
+ std::unique_ptr<NavigationLoaderInterceptor> service_worker_interceptor =
+ CreateServiceWorkerInterceptor(*request_info,
+ service_worker_navigation_handle_core);
+ if (service_worker_interceptor)
+ interceptors_.push_back(std::move(service_worker_interceptor));
}
if (appcache_handle_core) {
- std::unique_ptr<URLLoaderRequestHandler> appcache_handler =
+ std::unique_ptr<NavigationLoaderInterceptor> appcache_interceptor =
AppCacheRequestHandler::InitializeForNavigationNetworkService(
*resource_request_, appcache_handle_core,
default_url_loader_factory_getter_.get());
- if (appcache_handler)
- handlers_.push_back(std::move(appcache_handler));
+ if (appcache_interceptor)
+ interceptors_.push_back(std::move(appcache_interceptor));
}
if (base::FeatureList::IsEnabled(features::kSignedHTTPExchange)) {
- // It is safa to pass the callback of CreateURLLoaderThrottles with the
+ // It is safe to pass the callback of CreateURLLoaderThrottles with the
// unretained |this|, because the passed callback will be used by a
// SignedExchangeHandler which is indirectly owned by |this| until its
// header is verified and parsed, that's where the getter is used.
- handlers_.push_back(std::make_unique<WebPackageRequestHandler>(
+ interceptors_.push_back(std::make_unique<WebPackageRequestHandler>(
url::Origin::Create(request_info->common_params.url),
GetURLLoaderOptions(request_info->is_main_frame),
- base::MakeRefCounted<WeakWrapperSharedURLLoaderFactory>(
- default_url_loader_factory_getter_->GetNetworkFactory()),
+ request_info->frame_tree_node_id,
+ default_url_loader_factory_getter_->GetNetworkFactory(),
base::BindRepeating(
&URLLoaderRequestController::CreateURLLoaderThrottles,
- base::Unretained(this))));
+ base::Unretained(this)),
+ url_request_context_getter));
}
Restart();
@@ -489,30 +602,32 @@ class NavigationURLLoaderNetworkService::URLLoaderRequestController
// This could be called multiple times to follow a chain of redirects.
void Restart() {
- DCHECK(IsRequestHandlerEnabled());
+ DCHECK(IsLoaderInterceptionEnabled());
// Clear |url_loader_| if it's not the default one (network). This allows
// the restarted request to use a new loader, instead of, e.g., reusing the
// AppCache or service worker loader. For an optimization, we keep and reuse
- // the default url loader if the all |handlers_| doesn't handle the
+ // the default url loader if the all |interceptors_| doesn't handle the
// redirected request.
if (!default_loader_used_)
url_loader_.reset();
- handler_index_ = 0;
+ interceptor_index_ = 0;
received_response_ = false;
- MaybeStartLoader(nullptr /* handler */, {} /* single_request_handler */);
+ MaybeStartLoader(nullptr /* interceptor */,
+ {} /* single_request_handler */);
}
- // |handler| is the one who called this method (as a LoaderCallback), nullptr
- // if this method is not called by a handler.
- // |single_request_handler| is the RequestHandler given by the |handler|,
- // non-null if the handler wants to handle the request.
+ // |interceptor| is non-null if this is called by one of the interceptors
+ // (via a LoaderCallback).
+ // |single_request_handler| is the RequestHandler given by the |interceptor|,
+ // non-null if the interceptor wants to handle the request.
void MaybeStartLoader(
- URLLoaderRequestHandler* handler,
+ NavigationLoaderInterceptor* interceptor,
SingleRequestURLLoaderFactory::RequestHandler single_request_handler) {
- DCHECK(IsRequestHandlerEnabled());
+ DCHECK(IsLoaderInterceptionEnabled());
if (single_request_handler) {
- // |handler| wants to handle the request.
- DCHECK(handler);
+ // |interceptor| wants to handle the request with
+ // |single_request_handler|.
+ DCHECK(interceptor);
default_loader_used_ = false;
url_loader_ = ThrottlingURLLoader::CreateLoaderAndStart(
base::MakeRefCounted<SingleRequestURLLoaderFactory>(
@@ -523,39 +638,42 @@ class NavigationURLLoaderNetworkService::URLLoaderRequestController
base::ThreadTaskRunnerHandle::Get());
subresource_loader_params_ =
- handler->MaybeCreateSubresourceLoaderParams();
+ interceptor->MaybeCreateSubresourceLoaderParams();
return;
}
- // Before falling back to the next handler, see if |handler| still wants
- // to give additional info to the frame for subresource loading.
- // In that case we will just fall back to the default loader (i.e.
- // won't go on to the next handlers) but send the subresource_loader_params
- // to the child process. This is necessary for correctness in the cases
- // where, e.g. there's a controlling ServiceWorker that doesn't handle main
- // resource loading, but may still want to control the page and/or handle
- // subresource loading. In that case we want to skip AppCache.
- if (handler) {
+ // Before falling back to the next interceptor, see if |interceptor| still
+ // wants to give additional info to the frame for subresource loading. In
+ // that case we will just fall back to the default loader (i.e. won't go on
+ // to the next interceptors) but send the subresource_loader_params to the
+ // child process. This is necessary for correctness in the cases where, e.g.
+ // there's a controlling ServiceWorker that doesn't handle main resource
+ // loading, but may still want to control the page and/or handle subresource
+ // loading. In that case we want to skip AppCache.
+ if (interceptor) {
subresource_loader_params_ =
- handler->MaybeCreateSubresourceLoaderParams();
+ interceptor->MaybeCreateSubresourceLoaderParams();
// If non-null |subresource_loader_params_| is returned, make sure
- // we skip the next handlers.
+ // we skip the next interceptors.
if (subresource_loader_params_)
- handler_index_ = handlers_.size();
+ interceptor_index_ = interceptors_.size();
}
- // See if the next handler wants to handle the request.
- if (handler_index_ < handlers_.size()) {
- auto* next_handler = handlers_[handler_index_++].get();
- next_handler->MaybeCreateLoader(
+ // See if the next interceptor wants to handle the request.
+ if (interceptor_index_ < interceptors_.size()) {
+ auto* next_interceptor = interceptors_[interceptor_index_++].get();
+ next_interceptor->MaybeCreateLoader(
*resource_request_, resource_context_,
base::BindOnce(&URLLoaderRequestController::MaybeStartLoader,
- base::Unretained(this), next_handler));
+ base::Unretained(this), next_interceptor));
return;
}
+ // If we already have the default |url_loader_| we must come here after
+ // a redirect. No interceptors wanted to intercept the redirected request,
+ // so let it just follow the redirect.
if (url_loader_) {
DCHECK(!redirect_info_.new_url.is_empty());
url_loader_->FollowRedirect();
@@ -565,45 +683,80 @@ class NavigationURLLoaderNetworkService::URLLoaderRequestController
// TODO(https://crbug.com/796425): We temporarily wrap raw
// mojom::URLLoaderFactory pointers into SharedURLLoaderFactory. Need to
// further refactor the factory getters to avoid this.
- scoped_refptr<SharedURLLoaderFactory> factory;
- DCHECK_EQ(handlers_.size(), handler_index_);
+ scoped_refptr<network::SharedURLLoaderFactory> factory;
+ DCHECK_EQ(interceptors_.size(), interceptor_index_);
+
+ // If NetworkService is not enabled (which means we come here because one of
+ // the loader interceptors is enabled), use the default request handler
+ // instead of going through the NetworkService path.
+ if (!base::FeatureList::IsEnabled(network::features::kNetworkService)) {
+ DCHECK(!interceptors_.empty());
+ DCHECK(default_request_handler_factory_);
+ default_loader_used_ = true;
+ // Update |request_info_| when following a redirect.
+ if (url_chain_.size() > 0) {
+ request_info_ = CreateNavigationRequestInfoForRedirect(
+ *request_info_, *resource_request_);
+ }
+ url_loader_ = ThrottlingURLLoader::CreateLoaderAndStart(
+ base::MakeRefCounted<SingleRequestURLLoaderFactory>(
+ default_request_handler_factory_.Run()),
+ CreateURLLoaderThrottles(), frame_tree_node_id_, 0 /* request_id */,
+ network::mojom::kURLLoadOptionNone, resource_request_.get(),
+ this /* client */, kNavigationUrlLoaderTrafficAnnotation,
+ base::ThreadTaskRunnerHandle::Get());
+ return;
+ }
+
if (resource_request_->url.SchemeIs(url::kBlobScheme)) {
factory = base::MakeRefCounted<WeakWrapperSharedURLLoaderFactory>(
default_url_loader_factory_getter_->GetBlobFactory());
} else if (!IsURLHandledByNetworkService(resource_request_->url) &&
!resource_request_->url.SchemeIs(url::kDataScheme)) {
- network::mojom::URLLoaderFactoryPtr& non_network_factory =
- non_network_url_loader_factories_[resource_request_->url.scheme()];
- if (!non_network_factory.is_bound()) {
- BrowserThread::PostTask(
- BrowserThread::UI, FROM_HERE,
- base::BindOnce(&NavigationURLLoaderNetworkService ::
- BindNonNetworkURLLoaderFactoryRequest,
- owner_, frame_tree_node_id_, resource_request_->url,
- mojo::MakeRequest(&non_network_factory)));
+ if (known_schemes_.find(resource_request_->url.scheme()) ==
+ known_schemes_.end()) {
+ bool handled = GetContentClient()->browser()->HandleExternalProtocol(
+ resource_request_->url, web_contents_getter_,
+ ChildProcessHost::kInvalidUniqueID, navigation_ui_data_.get(),
+ resource_request_->resource_type == RESOURCE_TYPE_MAIN_FRAME,
+ static_cast<ui::PageTransition>(resource_request_->transition_type),
+ resource_request_->has_user_gesture);
+ factory = base::MakeRefCounted<SingleRequestURLLoaderFactory>(
+ base::BindOnce(UnknownSchemeCallback, handled));
+ } else {
+ network::mojom::URLLoaderFactoryPtr& non_network_factory =
+ non_network_url_loader_factories_[resource_request_->url.scheme()];
+ if (!non_network_factory.is_bound()) {
+ BrowserThread::PostTask(
+ BrowserThread::UI, FROM_HERE,
+ base::BindOnce(&NavigationURLLoaderNetworkService ::
+ BindNonNetworkURLLoaderFactoryRequest,
+ owner_, frame_tree_node_id_,
+ resource_request_->url,
+ mojo::MakeRequest(&non_network_factory)));
+ }
+ factory = base::MakeRefCounted<WeakWrapperSharedURLLoaderFactory>(
+ non_network_factory.get());
}
- factory = base::MakeRefCounted<WeakWrapperSharedURLLoaderFactory>(
- non_network_factory.get());
} else {
- auto* raw_factory =
- default_url_loader_factory_getter_->GetNetworkFactory();
default_loader_used_ = true;
// NOTE: We only support embedders proxying network-service-bound requests
- // not handled by URLLoaderRequestHandlers above (e.g. Service Worker or
- // AppCache). Hence this code is only reachable when one of the above
- // handlers isn't used and the URL is either a data URL or has a scheme
- // which is handled by the network service. We explicitly avoid proxying
- // the data URL case here.
+ // not handled by NavigationLoaderInterceptors above (e.g. Service Worker
+ // or AppCache). Hence this code is only reachable when one of the above
+ // interceptors isn't used and the URL is either a data URL or has a
+ // scheme which is handled by the network service. We explicitly avoid
+ // proxying the data URL case here.
if (proxied_factory_request_.is_pending() &&
!resource_request_->url.SchemeIs(url::kDataScheme)) {
DCHECK(proxied_factory_info_.is_valid());
- raw_factory->Clone(std::move(proxied_factory_request_));
+ // We don't worry about reconnection since it's a single navigation.
+ default_url_loader_factory_getter_->CloneNetworkFactory(
+ std::move(proxied_factory_request_));
factory = base::MakeRefCounted<WrapperSharedURLLoaderFactory>(
std::move(proxied_factory_info_));
} else {
- factory = base::MakeRefCounted<WeakWrapperSharedURLLoaderFactory>(
- raw_factory);
+ factory = default_url_loader_factory_getter_->GetNetworkFactory();
}
}
url_chain_.push_back(resource_request_->url);
@@ -620,14 +773,15 @@ class NavigationURLLoaderNetworkService::URLLoaderRequestController
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DCHECK(!redirect_info_.new_url.is_empty());
- if (!IsRequestHandlerEnabled()) {
+ if (!IsLoaderInterceptionEnabled()) {
url_loader_->FollowRedirect();
return;
}
- // Update resource_request_ and call Restart to give our handlers_ a chance
- // at handling the new location. If no handler wants to take over, we'll
- // use the existing url_loader to follow the redirect, see MaybeStartLoader.
+ // Update |resource_request_| and call Restart to give our |interceptors_| a
+ // chance at handling the new location. If no interceptor wants to take
+ // over, we'll use the existing url_loader to follow the redirect, see
+ // MaybeStartLoader.
// TODO(michaeln): This is still WIP and is based on URLRequest::Redirect,
// there likely remains more to be done.
// a. For subframe navigations, the Origin header may need to be modified
@@ -662,19 +816,23 @@ class NavigationURLLoaderNetworkService::URLLoaderRequestController
// network::mojom::URLLoaderClient implementation:
void OnReceiveResponse(
const network::ResourceResponseHead& head,
- const base::Optional<net::SSLInfo>& ssl_info,
network::mojom::DownloadedTempFilePtr downloaded_file) override {
received_response_ = true;
// If the default loader (network) was used to handle the URL load request
- // we need to see if the handlers want to potentially create a new loader
- // for the response. e.g. AppCache.
+ // we need to see if the interceptors want to potentially create a new
+ // loader for the response. e.g. AppCache.
if (MaybeCreateLoaderForResponse(head))
return;
network::mojom::URLLoaderClientEndpointsPtr url_loader_client_endpoints;
+
+ // Currently only plugin handlers may intercept the response. Don't treat
+ // the response as download if it has been handled by plugins.
+ bool response_intercepted = false;
if (url_loader_) {
url_loader_client_endpoints = url_loader_->Unbind();
+ response_intercepted = url_loader_->response_intercepted();
} else {
url_loader_client_endpoints =
network::mojom::URLLoaderClientEndpoints::New(
@@ -689,8 +847,9 @@ class NavigationURLLoaderNetworkService::URLLoaderRequestController
bool is_download;
bool is_stream;
std::unique_ptr<NavigationData> cloned_navigation_data;
- if (IsRequestHandlerEnabled()) {
- is_download = IsDownload(*response.get(), url_, url_chain_,
+ if (IsLoaderInterceptionEnabled()) {
+ is_download = !response_intercepted &&
+ IsDownload(*response.get(), url_, url_chain_,
initiator_origin_, suggested_filename_);
is_stream = false;
} else {
@@ -708,7 +867,7 @@ class NavigationURLLoaderNetworkService::URLLoaderRequestController
ResourceRequestInfoImpl* info =
ResourceRequestInfoImpl::ForRequest(url_request);
- is_download = info->IsDownload();
+ is_download = !response_intercepted && info->IsDownload();
is_stream = info->is_stream();
if (rdh->delegate()) {
NavigationData* navigation_data =
@@ -752,9 +911,8 @@ class NavigationURLLoaderNetworkService::URLLoaderRequestController
base::BindOnce(&NavigationURLLoaderNetworkService::OnReceiveResponse,
owner_, response->DeepCopy(),
std::move(url_loader_client_endpoints),
- std::move(ssl_info), std::move(cloned_navigation_data),
- global_request_id_, is_download, is_stream,
- std::move(downloaded_file)));
+ std::move(cloned_navigation_data), global_request_id_,
+ is_download, is_stream, std::move(downloaded_file)));
}
void OnReceiveRedirect(const net::RedirectInfo& redirect_info,
@@ -766,7 +924,7 @@ class NavigationURLLoaderNetworkService::URLLoaderRequestController
}
// Store the redirect_info for later use in FollowRedirect where we give
- // our handlers_ a chance to intercept the request for the new location.
+ // our interceptors_ a chance to intercept the request for the new location.
redirect_info_ = redirect_info;
scoped_refptr<network::ResourceResponse> response(
@@ -811,7 +969,7 @@ class NavigationURLLoaderNetworkService::URLLoaderRequestController
if (status.error_code != net::OK && !received_response_) {
// If the default loader (network) was used to handle the URL load
- // request we need to see if the handlers want to potentially create a
+ // request we need to see if the interceptors want to potentially create a
// new loader for the response. e.g. AppCache.
if (MaybeCreateLoaderForResponse(network::ResourceResponseHead()))
return;
@@ -824,21 +982,21 @@ class NavigationURLLoaderNetworkService::URLLoaderRequestController
status));
}
- // Returns true if a handler wants to handle the response, i.e. return a
+ // Returns true if an interceptor wants to handle the response, i.e. return a
// different response. For e.g. AppCache may have fallback content.
bool MaybeCreateLoaderForResponse(
const network::ResourceResponseHead& response) {
- if (!IsRequestHandlerEnabled())
+ if (!IsLoaderInterceptionEnabled())
return false;
if (!default_loader_used_)
return false;
- for (auto& handler : handlers_) {
+ for (auto& interceptor : interceptors_) {
network::mojom::URLLoaderClientRequest response_client_request;
- if (handler->MaybeCreateLoaderForResponse(response, &response_url_loader_,
- &response_client_request,
- url_loader_.get())) {
+ if (interceptor->MaybeCreateLoaderForResponse(
+ response, &response_url_loader_, &response_client_request,
+ url_loader_.get())) {
response_loader_binding_.Bind(std::move(response_client_request));
default_loader_used_ = false;
url_loader_.reset();
@@ -855,10 +1013,35 @@ class NavigationURLLoaderNetworkService::URLLoaderRequestController
navigation_ui_data_.get(), frame_tree_node_id_);
}
- std::vector<std::unique_ptr<URLLoaderRequestHandler>> handlers_;
- size_t handler_index_ = 0;
+ std::unique_ptr<NavigationLoaderInterceptor> CreateServiceWorkerInterceptor(
+ const NavigationRequestInfo& request_info,
+ ServiceWorkerNavigationHandleCore* service_worker_navigation_handle_core)
+ const {
+ const ResourceType resource_type = request_info.is_main_frame
+ ? RESOURCE_TYPE_MAIN_FRAME
+ : RESOURCE_TYPE_SUB_FRAME;
+ network::mojom::RequestContextFrameType frame_type =
+ request_info.is_main_frame
+ ? network::mojom::RequestContextFrameType::kTopLevel
+ : network::mojom::RequestContextFrameType::kNested;
+ storage::BlobStorageContext* blob_storage_context = GetBlobStorageContext(
+ GetChromeBlobStorageContextForResourceContext(resource_context_));
+ return ServiceWorkerRequestHandler::InitializeForNavigationNetworkService(
+ *resource_request_, resource_context_,
+ service_worker_navigation_handle_core, blob_storage_context,
+ request_info.begin_params->skip_service_worker, resource_type,
+ request_info.begin_params->request_context_type, frame_type,
+ request_info.are_ancestors_secure, request_info.common_params.post_data,
+ web_contents_getter_);
+ }
+
+ std::vector<std::unique_ptr<NavigationLoaderInterceptor>> interceptors_;
+ size_t interceptor_index_ = 0;
std::unique_ptr<network::ResourceRequest> resource_request_;
+ // Non-NetworkService: |request_info_| is updated along with
+ // |resource_request_| on redirects.
+ std::unique_ptr<NavigationRequestInfo> request_info_;
int frame_tree_node_id_ = 0;
GlobalRequestID global_request_id_;
net::RedirectInfo redirect_info_;
@@ -913,6 +1096,14 @@ class NavigationURLLoaderNetworkService::URLLoaderRequestController
std::map<std::string, network::mojom::URLLoaderFactoryPtr>
non_network_url_loader_factories_;
+ // Non-NetworkService:
+ // Generator of a request handler for sending request to the network. This
+ // captures all of parameters to create a
+ // SingleRequestURLLoaderFactory::RequestHandler. Used only when
+ // NetworkService is disabled but IsLoaderInterceptionEnabled() is true.
+ base::RepeatingCallback<SingleRequestURLLoaderFactory::RequestHandler()>
+ default_request_handler_factory_;
+
// The completion status if it has been received. This is needed to handle
// the case that the response is intercepted by download, and OnComplete() is
// already called while we are transferring the |url_loader_| and response
@@ -929,7 +1120,11 @@ class NavigationURLLoaderNetworkService::URLLoaderRequestController
network::mojom::URLLoaderFactoryRequest proxied_factory_request_;
network::mojom::URLLoaderFactoryPtrInfo proxied_factory_info_;
- base::WeakPtrFactory<URLLoaderRequestController> weak_factory_;
+ // The schemes that this loader can use. For anything else we'll try external
+ // protocol handlers.
+ std::set<std::string> known_schemes_;
+
+ mutable base::WeakPtrFactory<URLLoaderRequestController> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(URLLoaderRequestController);
};
@@ -944,7 +1139,8 @@ NavigationURLLoaderNetworkService::NavigationURLLoaderNetworkService(
ServiceWorkerNavigationHandle* service_worker_navigation_handle,
AppCacheNavigationHandle* appcache_handle,
NavigationURLLoaderDelegate* delegate,
- std::vector<std::unique_ptr<URLLoaderRequestHandler>> initial_handlers)
+ std::vector<std::unique_ptr<NavigationLoaderInterceptor>>
+ initial_interceptors)
: delegate_(delegate),
allow_download_(request_info->common_params.allow_download),
weak_factory_(this) {
@@ -970,15 +1166,15 @@ NavigationURLLoaderNetworkService::NavigationURLLoaderNetworkService(
if (!base::FeatureList::IsEnabled(network::features::kNetworkService)) {
DCHECK(!request_controller_);
request_controller_ = std::make_unique<URLLoaderRequestController>(
- /* initial_handlers = */
- std::vector<std::unique_ptr<URLLoaderRequestHandler>>(),
+ /* initial_interceptors = */
+ std::vector<std::unique_ptr<NavigationLoaderInterceptor>>(),
std::move(new_request), resource_context,
/* default_url_factory_getter = */ nullptr,
request_info->common_params.url,
request_info->begin_params->initiator_origin,
request_info->common_params.suggested_filename,
/* proxied_url_loader_factory_request */ nullptr,
- /* proxied_url_loader_factory_info */ nullptr,
+ /* proxied_url_loader_factory_info */ nullptr, std::set<std::string>(),
weak_factory_.GetWeakPtr());
BrowserThread::PostTask(
@@ -1001,9 +1197,9 @@ NavigationURLLoaderNetworkService::NavigationURLLoaderNetworkService(
const auto& schemes = URLDataManagerBackend::GetWebUISchemes();
std::string scheme = new_request->url.scheme();
if (std::find(schemes.begin(), schemes.end(), scheme) != schemes.end()) {
- factory_for_webui =
- CreateWebUIURLLoader(frame_tree_node->current_frame_host(), scheme)
- .PassInterface();
+ factory_for_webui = CreateWebUIURLLoaderBinding(
+ frame_tree_node->current_frame_host(), scheme)
+ .PassInterface();
}
network::mojom::URLLoaderFactoryPtrInfo proxied_factory_info;
@@ -1022,23 +1218,38 @@ NavigationURLLoaderNetworkService::NavigationURLLoaderNetworkService(
// connected if the request type supports proxying.
network::mojom::URLLoaderFactoryPtrInfo factory_info;
auto factory_request = mojo::MakeRequest(&factory_info);
- if (GetContentClient()->browser()->WillCreateURLLoaderFactory(
- frame_tree_node->current_frame_host(), true /* is_navigation */,
- &factory_request)) {
+ bool use_proxy = GetContentClient()->browser()->WillCreateURLLoaderFactory(
+ frame_tree_node->current_frame_host(), true /* is_navigation */,
+ &factory_request);
+ if (RenderFrameDevToolsAgentHost::WillCreateURLLoaderFactory(
+ frame_tree_node->current_frame_host(), true, &factory_request)) {
+ use_proxy = true;
+ }
+ if (use_proxy) {
proxied_factory_request = std::move(factory_request);
proxied_factory_info = std::move(factory_info);
}
}
auto* partition = static_cast<StoragePartitionImpl*>(storage_partition);
+ non_network_url_loader_factories_[url::kFileScheme] =
+ std::make_unique<FileURLLoaderFactory>(
+ partition->browser_context()->GetPath(),
+ base::CreateSequencedTaskRunnerWithTraits(
+ {base::MayBlock(), base::TaskPriority::BACKGROUND,
+ base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}));
+ std::set<std::string> known_schemes;
+ for (auto& iter : non_network_url_loader_factories_)
+ known_schemes.insert(iter.first);
+
DCHECK(!request_controller_);
request_controller_ = std::make_unique<URLLoaderRequestController>(
- std::move(initial_handlers), std::move(new_request), resource_context,
+ std::move(initial_interceptors), std::move(new_request), resource_context,
partition->url_loader_factory_getter(), request_info->common_params.url,
request_info->begin_params->initiator_origin,
request_info->common_params.suggested_filename,
std::move(proxied_factory_request), std::move(proxied_factory_info),
- weak_factory_.GetWeakPtr());
+ std::move(known_schemes), weak_factory_.GetWeakPtr());
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(
@@ -1049,13 +1260,6 @@ NavigationURLLoaderNetworkService::NavigationURLLoaderNetworkService(
std::move(request_info), std::move(navigation_ui_data),
std::move(factory_for_webui), frame_tree_node_id,
ServiceManagerConnection::GetForProcess()->GetConnector()->Clone()));
-
- non_network_url_loader_factories_[url::kFileScheme] =
- std::make_unique<FileURLLoaderFactory>(
- partition->browser_context()->GetPath(),
- base::CreateSequencedTaskRunnerWithTraits(
- {base::MayBlock(), base::TaskPriority::BACKGROUND,
- base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}));
}
NavigationURLLoaderNetworkService::~NavigationURLLoaderNetworkService() {
@@ -1075,7 +1279,6 @@ void NavigationURLLoaderNetworkService::ProceedWithResponse() {}
void NavigationURLLoaderNetworkService::OnReceiveResponse(
scoped_refptr<network::ResourceResponse> response,
network::mojom::URLLoaderClientEndpointsPtr url_loader_client_endpoints,
- const base::Optional<net::SSLInfo>& maybe_ssl_info,
std::unique_ptr<NavigationData> navigation_data,
const GlobalRequestID& global_request_id,
bool is_download,
@@ -1087,13 +1290,10 @@ void NavigationURLLoaderNetworkService::OnReceiveResponse(
// TODO(scottmg): This needs to do more of what
// NavigationResourceHandler::OnResponseStarted() does.
- net::SSLInfo ssl_info;
- if (maybe_ssl_info.has_value())
- ssl_info = maybe_ssl_info.value();
delegate_->OnResponseStarted(
std::move(response), std::move(url_loader_client_endpoints), nullptr,
- std::move(ssl_info), std::move(navigation_data), global_request_id,
+ std::move(navigation_data), global_request_id,
allow_download_ && is_download, is_stream,
request_controller_->TakeSubresourceLoaderParams());
}
diff --git a/chromium/content/browser/loader/navigation_url_loader_network_service.h b/chromium/content/browser/loader/navigation_url_loader_network_service.h
index 42473778a43..7a3ee671914 100644
--- a/chromium/content/browser/loader/navigation_url_loader_network_service.h
+++ b/chromium/content/browser/loader/navigation_url_loader_network_service.h
@@ -25,7 +25,7 @@ class NavigationData;
class NavigationPostDataHandler;
class ResourceContext;
class StoragePartition;
-class URLLoaderRequestHandler;
+class NavigationLoaderInterceptor;
struct GlobalRequestID;
// This is an implementation of NavigationURLLoader used when
@@ -34,7 +34,7 @@ class CONTENT_EXPORT NavigationURLLoaderNetworkService
: public NavigationURLLoader {
public:
// The caller is responsible for ensuring that |delegate| outlives the loader.
- // Note |initial_handlers| is there for test purposes only.
+ // Note |initial_interceptors| is there for test purposes only.
NavigationURLLoaderNetworkService(
ResourceContext* resource_context,
StoragePartition* storage_partition,
@@ -43,7 +43,8 @@ class CONTENT_EXPORT NavigationURLLoaderNetworkService
ServiceWorkerNavigationHandle* service_worker_handle,
AppCacheNavigationHandle* appcache_handle,
NavigationURLLoaderDelegate* delegate,
- std::vector<std::unique_ptr<URLLoaderRequestHandler>> initial_handlers);
+ std::vector<std::unique_ptr<NavigationLoaderInterceptor>>
+ initial_interceptors);
~NavigationURLLoaderNetworkService() override;
// NavigationURLLoader implementation:
@@ -53,7 +54,6 @@ class CONTENT_EXPORT NavigationURLLoaderNetworkService
void OnReceiveResponse(
scoped_refptr<network::ResourceResponse> response,
network::mojom::URLLoaderClientEndpointsPtr url_loader_client_endpoints,
- const base::Optional<net::SSLInfo>& maybe_ssl_info,
std::unique_ptr<NavigationData> navigation_data,
const GlobalRequestID& global_request_id,
bool is_download,
diff --git a/chromium/content/browser/loader/navigation_url_loader_network_service_unittest.cc b/chromium/content/browser/loader/navigation_url_loader_network_service_unittest.cc
index 63c010e4080..b6e28afd3be 100644
--- a/chromium/content/browser/loader/navigation_url_loader_network_service_unittest.cc
+++ b/chromium/content/browser/loader/navigation_url_loader_network_service_unittest.cc
@@ -7,8 +7,8 @@
#include "base/run_loop.h"
#include "base/test/scoped_feature_list.h"
#include "content/browser/frame_host/navigation_request_info.h"
+#include "content/browser/loader/navigation_loader_interceptor.h"
#include "content/browser/loader/navigation_url_loader.h"
-#include "content/browser/loader/url_loader_request_handler.h"
#include "content/common/navigation_params.h"
#include "content/common/navigation_params.mojom.h"
#include "content/common/service_manager/service_manager_connection_impl.h"
@@ -32,15 +32,15 @@
#include "services/network/url_loader.h"
#include "services/network/url_request_context_owner.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/page/page_visibility_state.mojom.h"
+#include "third_party/blink/public/mojom/page/page_visibility_state.mojom.h"
namespace content {
namespace {
-class TestURLLoaderRequestHandler : public URLLoaderRequestHandler {
+class TestNavigationLoaderInterceptor : public NavigationLoaderInterceptor {
public:
- explicit TestURLLoaderRequestHandler(
+ explicit TestNavigationLoaderInterceptor(
base::Optional<network::ResourceRequest>* most_recent_resource_request)
: most_recent_resource_request_(most_recent_resource_request),
resource_scheduler_(false) {
@@ -57,7 +57,8 @@ class TestURLLoaderRequestHandler : public URLLoaderRequestHandler {
context_->GetURLRequestContext()->network_quality_estimator());
}
- ~TestURLLoaderRequestHandler() override {
+ ~TestNavigationLoaderInterceptor() override {
+ url_loader_ = nullptr;
resource_scheduler_client_ = nullptr;
context_->NotifyContextShuttingDown();
}
@@ -66,7 +67,7 @@ class TestURLLoaderRequestHandler : public URLLoaderRequestHandler {
ResourceContext* resource_context,
LoaderCallback callback) override {
std::move(callback).Run(
- base::BindOnce(&TestURLLoaderRequestHandler::StartLoader,
+ base::BindOnce(&TestNavigationLoaderInterceptor::StartLoader,
base::Unretained(this), resource_request));
}
@@ -74,12 +75,14 @@ class TestURLLoaderRequestHandler : public URLLoaderRequestHandler {
network::mojom::URLLoaderRequest request,
network::mojom::URLLoaderClientPtr client) {
*most_recent_resource_request_ = resource_request;
- // The URLLoader will delete itself upon completion.
- new network::URLLoader(context_, nullptr, std::move(request),
- 0 /* options */, resource_request,
- false /* report_raw_headers */, std::move(client),
- TRAFFIC_ANNOTATION_FOR_TESTS, 0 /* process_id */,
- resource_scheduler_client_, nullptr);
+ url_loader_ = std::make_unique<network::URLLoader>(
+ context_, nullptr, base::BindOnce([](network::URLLoader*) {
+ // Ignore self-deletion requests, for simplicity.
+ }),
+ std::move(request), 0 /* options */, resource_request,
+ false /* report_raw_headers */, std::move(client),
+ TRAFFIC_ANNOTATION_FOR_TESTS, 0 /* process_id */, 0, /* request_id */
+ resource_scheduler_client_, nullptr);
}
bool MaybeCreateLoaderForResponse(
@@ -96,6 +99,7 @@ class TestURLLoaderRequestHandler : public URLLoaderRequestHandler {
network::ResourceScheduler resource_scheduler_;
scoped_refptr<network::NetworkURLRequestContextGetter> context_;
scoped_refptr<network::ResourceSchedulerClient> resource_scheduler_client_;
+ std::unique_ptr<network::URLLoader> url_loader_;
};
} // namespace
@@ -140,7 +144,7 @@ class NavigationURLLoaderNetworkServiceTest : public testing::Test {
false /* is_form_submission */, GURL() /* searchable_form_url */,
std::string() /* searchable_form_encoding */,
url::Origin::Create(url), GURL() /* client_side_redirect_url */,
- nullptr /* devtools_initiator_info */);
+ base::nullopt /* devtools_initiator_info */);
CommonNavigationParams common_params;
common_params.url = url;
@@ -152,10 +156,11 @@ class NavigationURLLoaderNetworkServiceTest : public testing::Test {
common_params, std::move(begin_params), url, is_main_frame,
false /* parent_is_main_frame */, false /* are_ancestors_secure */,
-1 /* frame_tree_node_id */, false /* is_for_guests_only */,
- false /* report_raw_headers */, false /* is_prerenering */));
- std::vector<std::unique_ptr<URLLoaderRequestHandler>> handlers;
+ false /* report_raw_headers */, false /* is_prerenering */,
+ nullptr /* blob_url_loader_factory */));
+ std::vector<std::unique_ptr<NavigationLoaderInterceptor>> interceptors;
most_recent_resource_request_ = base::nullopt;
- handlers.push_back(std::make_unique<TestURLLoaderRequestHandler>(
+ interceptors.push_back(std::make_unique<TestNavigationLoaderInterceptor>(
&most_recent_resource_request_));
return std::make_unique<NavigationURLLoaderNetworkService>(
@@ -163,7 +168,7 @@ class NavigationURLLoaderNetworkServiceTest : public testing::Test {
BrowserContext::GetDefaultStoragePartition(browser_context_.get()),
std::move(request_info), nullptr /* navigation_ui_data */,
nullptr /* service_worker_handle */, nullptr /* appcache_handle */,
- delegate, std::move(handlers));
+ delegate, std::move(interceptors));
}
// Requests |redirect_url|, which must return a HTTP 3xx redirect. It's also
diff --git a/chromium/content/browser/loader/navigation_url_loader_unittest.cc b/chromium/content/browser/loader/navigation_url_loader_unittest.cc
index e23ef685679..a4ee76574ab 100644
--- a/chromium/content/browser/loader/navigation_url_loader_unittest.cc
+++ b/chromium/content/browser/loader/navigation_url_loader_unittest.cc
@@ -8,7 +8,6 @@
#include "base/bind.h"
#include "base/command_line.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/run_loop.h"
#include "content/browser/frame_host/navigation_request_info.h"
@@ -43,7 +42,7 @@
#include "net/url_request/url_request_test_job.h"
#include "net/url_request/url_request_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/page/page_visibility_state.mojom.h"
+#include "third_party/blink/public/mojom/page/page_visibility_state.mojom.h"
#include "url/origin.h"
namespace content {
@@ -117,13 +116,14 @@ class NavigationURLLoaderTest : public testing::Test {
false /* is_form_submission */, GURL() /* searchable_form_url */,
std::string() /* searchable_form_encoding */,
url::Origin::Create(url), GURL() /* client_side_redirect_url */,
- nullptr /* devtools_initiator_info */);
+ base::nullopt /* devtools_initiator_info */);
CommonNavigationParams common_params;
common_params.url = url;
std::unique_ptr<NavigationRequestInfo> request_info(
new NavigationRequestInfo(common_params, std::move(begin_params), url,
- true, false, false, -1, false, false, false));
+ true, false, false, -1, false, false, false,
+ nullptr));
return NavigationURLLoader::Create(
browser_context_->GetResourceContext(),
BrowserContext::GetDefaultStoragePartition(browser_context_.get()),
@@ -161,7 +161,7 @@ TEST_F(NavigationURLLoaderTest, RequestFailedNoCertError) {
// Wait for the request to fail as expected.
delegate.WaitForRequestFailed();
- EXPECT_EQ(net::ERR_UNKNOWN_URL_SCHEME, delegate.net_error());
+ EXPECT_EQ(net::ERR_ABORTED, delegate.net_error());
EXPECT_FALSE(delegate.ssl_info().is_valid());
EXPECT_EQ(1, delegate.on_request_handled_counter());
}
diff --git a/chromium/content/browser/loader/prefetch_browsertest.cc b/chromium/content/browser/loader/prefetch_browsertest.cc
index b489e4c0f10..da0ea6f9f64 100644
--- a/chromium/content/browser/loader/prefetch_browsertest.cc
+++ b/chromium/content/browser/loader/prefetch_browsertest.cc
@@ -15,6 +15,7 @@
#include "content/browser/storage_partition_impl.h"
#include "content/browser/web_package/mock_signed_exchange_handler.h"
#include "content/browser/web_package/web_package_loader.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_features.h"
#include "content/public/test/browser_test_utils.h"
@@ -343,9 +344,9 @@ IN_PROC_BROWSER_TEST_P(PrefetchBrowserTest, WebPackageWithPreload) {
RegisterResponse(
target_htxg,
// We mock the SignedExchangeHandler, so just return a HTML content
- // as application/http-exchange+cbor.
+ // as "application/signed-exchange;v=b0".
ResponseEntry("<head><title>Prefetch Target (HTXG)</title></head>",
- "application/http-exchange+cbor"));
+ "application/signed-exchange;v=b0"));
RegisterResponse(preload_url_in_htxg,
ResponseEntry("function foo() {}", "text/javascript"));
diff --git a/chromium/content/browser/loader/prefetch_url_loader.cc b/chromium/content/browser/loader/prefetch_url_loader.cc
index dfb0bc72dee..a9b0fa9cc26 100644
--- a/chromium/content/browser/loader/prefetch_url_loader.cc
+++ b/chromium/content/browser/loader/prefetch_url_loader.cc
@@ -7,9 +7,9 @@
#include "base/feature_list.h"
#include "content/browser/web_package/web_package_prefetch_handler.h"
#include "content/public/common/content_features.h"
-#include "content/public/common/shared_url_loader_factory.h"
#include "net/url_request/url_request_context_getter.h"
#include "services/network/public/cpp/features.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
namespace content {
@@ -17,14 +17,16 @@ PrefetchURLLoader::PrefetchURLLoader(
int32_t routing_id,
int32_t request_id,
uint32_t options,
+ int frame_tree_node_id,
const network::ResourceRequest& resource_request,
network::mojom::URLLoaderClientPtr client,
const net::MutableNetworkTrafficAnnotationTag& traffic_annotation,
- scoped_refptr<SharedURLLoaderFactory> network_loader_factory,
+ scoped_refptr<network::SharedURLLoaderFactory> network_loader_factory,
URLLoaderThrottlesGetter url_loader_throttles_getter,
ResourceContext* resource_context,
scoped_refptr<net::URLRequestContextGetter> request_context_getter)
- : network_loader_factory_(std::move(network_loader_factory)),
+ : frame_tree_node_id_(frame_tree_node_id),
+ network_loader_factory_(std::move(network_loader_factory)),
client_binding_(this),
forwarding_client_(std::move(client)),
url_loader_throttles_getter_(url_loader_throttles_getter),
@@ -76,7 +78,6 @@ void PrefetchURLLoader::ResumeReadingBodyFromNet() {
void PrefetchURLLoader::OnReceiveResponse(
const network::ResourceResponseHead& response,
- const base::Optional<net::SSLInfo>& ssl_info,
network::mojom::DownloadedTempFilePtr downloaded_file) {
if (WebPackagePrefetchHandler::IsResponseForWebPackage(response)) {
DCHECK(!web_package_prefetch_handler_);
@@ -84,14 +85,13 @@ void PrefetchURLLoader::OnReceiveResponse(
// Note that after this point this doesn't directly get upcalls from the
// network. (Until |this| calls the handler's FollowRedirect.)
web_package_prefetch_handler_ = std::make_unique<WebPackagePrefetchHandler>(
- response, std::move(loader_), client_binding_.Unbind(),
- network_loader_factory_, request_initiator_,
+ frame_tree_node_id_, response, std::move(loader_),
+ client_binding_.Unbind(), network_loader_factory_, request_initiator_,
url_loader_throttles_getter_, resource_context_,
request_context_getter_, this);
return;
}
- forwarding_client_->OnReceiveResponse(response, ssl_info,
- std::move(downloaded_file));
+ forwarding_client_->OnReceiveResponse(response, std::move(downloaded_file));
}
void PrefetchURLLoader::OnReceiveRedirect(
@@ -128,7 +128,7 @@ void PrefetchURLLoader::OnStartLoadingResponseBody(
// the renderer for prefetch.
DCHECK(!pipe_drainer_);
pipe_drainer_ =
- std::make_unique<mojo::common::DataPipeDrainer>(this, std::move(body));
+ std::make_unique<mojo::DataPipeDrainer>(this, std::move(body));
}
void PrefetchURLLoader::OnComplete(
diff --git a/chromium/content/browser/loader/prefetch_url_loader.h b/chromium/content/browser/loader/prefetch_url_loader.h
index b4d84595b5b..7522e0484b5 100644
--- a/chromium/content/browser/loader/prefetch_url_loader.h
+++ b/chromium/content/browser/loader/prefetch_url_loader.h
@@ -9,8 +9,8 @@
#include "base/macros.h"
#include "content/common/content_export.h"
-#include "mojo/common/data_pipe_drainer.h"
#include "mojo/public/cpp/bindings/binding.h"
+#include "mojo/public/cpp/system/data_pipe_drainer.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
#include "url/gurl.h"
@@ -19,18 +19,20 @@ namespace net {
class URLRequestContextGetter;
}
+namespace network {
+class SharedURLLoaderFactory;
+}
+
namespace content {
class ResourceContext;
-class SharedURLLoaderFactory;
class URLLoaderThrottle;
class WebPackagePrefetchHandler;
// PrefetchURLLoader which basically just keeps draining the data.
-class CONTENT_EXPORT PrefetchURLLoader
- : public network::mojom::URLLoader,
- public network::mojom::URLLoaderClient,
- public mojo::common::DataPipeDrainer::Client {
+class CONTENT_EXPORT PrefetchURLLoader : public network::mojom::URLLoader,
+ public network::mojom::URLLoaderClient,
+ public mojo::DataPipeDrainer::Client {
public:
using URLLoaderThrottlesGetter = base::RepeatingCallback<
std::vector<std::unique_ptr<content::URLLoaderThrottle>>()>;
@@ -43,10 +45,11 @@ class CONTENT_EXPORT PrefetchURLLoader
int32_t routing_id,
int32_t request_id,
uint32_t options,
+ int frame_tree_node_id,
const network::ResourceRequest& resource_request,
network::mojom::URLLoaderClientPtr client,
const net::MutableNetworkTrafficAnnotationTag& traffic_annotation,
- scoped_refptr<SharedURLLoaderFactory> network_loader_factory,
+ scoped_refptr<network::SharedURLLoaderFactory> network_loader_factory,
URLLoaderThrottlesGetter url_loader_throttles_getter,
ResourceContext* resource_context,
scoped_refptr<net::URLRequestContextGetter> request_context_getter);
@@ -64,7 +67,6 @@ class CONTENT_EXPORT PrefetchURLLoader
// network::mojom::URLLoaderClient overrides:
void OnReceiveResponse(
const network::ResourceResponseHead& head,
- const base::Optional<net::SSLInfo>& ssl_info,
network::mojom::DownloadedTempFilePtr downloaded_file) override;
void OnReceiveRedirect(const net::RedirectInfo& redirect_info,
const network::ResourceResponseHead& head) override;
@@ -78,14 +80,16 @@ class CONTENT_EXPORT PrefetchURLLoader
mojo::ScopedDataPipeConsumerHandle body) override;
void OnComplete(const network::URLLoaderCompletionStatus& status) override;
- // mojo::common::DataPipeDrainer::Client overrides:
+ // mojo::DataPipeDrainer::Client overrides:
// This just does nothing but keep reading.
void OnDataAvailable(const void* data, size_t num_bytes) override {}
void OnDataComplete() override {}
void OnNetworkConnectionError();
- scoped_refptr<SharedURLLoaderFactory> network_loader_factory_;
+ const int frame_tree_node_id_;
+
+ scoped_refptr<network::SharedURLLoaderFactory> network_loader_factory_;
// For the actual request.
network::mojom::URLLoaderPtr loader_;
@@ -102,7 +106,7 @@ class CONTENT_EXPORT PrefetchURLLoader
ResourceContext* resource_context_;
scoped_refptr<net::URLRequestContextGetter> request_context_getter_;
- std::unique_ptr<mojo::common::DataPipeDrainer> pipe_drainer_;
+ std::unique_ptr<mojo::DataPipeDrainer> pipe_drainer_;
std::unique_ptr<WebPackagePrefetchHandler> web_package_prefetch_handler_;
diff --git a/chromium/content/browser/loader/prefetch_url_loader_service.cc b/chromium/content/browser/loader/prefetch_url_loader_service.cc
index 01257fcd97e..afaed7c6c25 100644
--- a/chromium/content/browser/loader/prefetch_url_loader_service.cc
+++ b/chromium/content/browser/loader/prefetch_url_loader_service.cc
@@ -7,16 +7,16 @@
#include "base/feature_list.h"
#include "content/browser/loader/prefetch_url_loader.h"
#include "content/browser/url_loader_factory_getter.h"
-#include "content/common/weak_wrapper_shared_url_loader_factory.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_client.h"
#include "content/public/common/resource_type.h"
-#include "content/public/common/shared_url_loader_factory.h"
#include "content/public/common/url_loader_throttle.h"
+#include "content/public/common/weak_wrapper_shared_url_loader_factory.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "net/url_request/url_request_context_getter.h"
#include "services/network/public/cpp/features.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
namespace content {
@@ -55,7 +55,7 @@ void PrefetchURLLoaderService::CreateLoaderAndStart(
const network::ResourceRequest& resource_request,
network::mojom::URLLoaderClientPtr client,
const net::MutableNetworkTrafficAnnotationTag& traffic_annotation,
- scoped_refptr<SharedURLLoaderFactory> network_loader_factory,
+ scoped_refptr<network::SharedURLLoaderFactory> network_loader_factory,
int frame_tree_node_id) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DCHECK_EQ(RESOURCE_TYPE_PREFETCH, resource_request.resource_type);
@@ -70,8 +70,9 @@ void PrefetchURLLoaderService::CreateLoaderAndStart(
// TODO(kinuko): Revisit this.
mojo::MakeStrongBinding(
std::make_unique<PrefetchURLLoader>(
- routing_id, request_id, options, resource_request, std::move(client),
- traffic_annotation, std::move(network_loader_factory),
+ routing_id, request_id, options, frame_tree_node_id, resource_request,
+ std::move(client), traffic_annotation,
+ std::move(network_loader_factory),
base::BindRepeating(
&PrefetchURLLoaderService::CreateURLLoaderThrottles, this,
resource_request, frame_tree_node_id),
@@ -98,23 +99,11 @@ void PrefetchURLLoaderService::CreateLoaderAndStart(
const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DCHECK(base::FeatureList::IsEnabled(network::features::kNetworkService));
- if (!network_loader_factory_ || network_loader_factory_.encountered_error()) {
- loader_factory_getter_->GetNetworkFactory()->Clone(
- mojo::MakeRequest(&network_loader_factory_));
- }
int frame_tree_node_id = loader_factory_bindings_.dispatch_context();
- CreateLoaderAndStart(
- std::move(request), routing_id, request_id, options, resource_request,
- std::move(client), traffic_annotation,
- // NOTE: This should be fine in most cases, where the loader
- // factory may become invalid if Network Service process is killed
- // and restarted. The load can just fail in the case here, but if
- // we want to be extra sure this should create a SharedURLLoaderFactory
- // that internally holds a ref to the URLLoaderFactoryGetter so that
- // it can re-obtain the factory if necessary.
- base::MakeRefCounted<WeakWrapperSharedURLLoaderFactory>(
- network_loader_factory_.get()),
- frame_tree_node_id);
+ CreateLoaderAndStart(std::move(request), routing_id, request_id, options,
+ resource_request, std::move(client), traffic_annotation,
+ loader_factory_getter_->GetNetworkFactory(),
+ frame_tree_node_id);
}
void PrefetchURLLoaderService::Clone(
diff --git a/chromium/content/browser/loader/prefetch_url_loader_service.h b/chromium/content/browser/loader/prefetch_url_loader_service.h
index eb3964d6448..2d6c020ef45 100644
--- a/chromium/content/browser/loader/prefetch_url_loader_service.h
+++ b/chromium/content/browser/loader/prefetch_url_loader_service.h
@@ -12,16 +12,19 @@
#include "content/public/browser/browser_thread.h"
#include "mojo/public/cpp/bindings/strong_binding_set.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
-#include "third_party/WebKit/public/mojom/loader/prefetch_url_loader_service.mojom.h"
+#include "third_party/blink/public/mojom/loader/prefetch_url_loader_service.mojom.h"
namespace net {
class URLRequestContextGetter;
}
+namespace network {
+class SharedURLLoaderFactory;
+}
+
namespace content {
class ResourceContext;
-class SharedURLLoaderFactory;
class URLLoaderFactoryGetter;
class URLLoaderThrottle;
@@ -59,7 +62,7 @@ class CONTENT_EXPORT PrefetchURLLoaderService final
const network::ResourceRequest& resource_request,
network::mojom::URLLoaderClientPtr client,
const net::MutableNetworkTrafficAnnotationTag& traffic_annotation,
- scoped_refptr<SharedURLLoaderFactory> network_loader_factory,
+ scoped_refptr<network::SharedURLLoaderFactory> network_loader_factory,
int frame_tree_node_id = -1);
// Register a callback that is fired right before a prefetch load is started
@@ -101,7 +104,6 @@ class CONTENT_EXPORT PrefetchURLLoaderService final
ResourceContext* resource_context_ = nullptr;
scoped_refptr<net::URLRequestContextGetter> request_context_getter_;
- network::mojom::URLLoaderFactoryPtr network_loader_factory_;
mojo::BindingSet<network::mojom::URLLoaderFactory,
int /* frame_tree_node_id */>
loader_factory_bindings_;
diff --git a/chromium/content/browser/loader/redirect_to_file_resource_handler_unittest.cc b/chromium/content/browser/loader/redirect_to_file_resource_handler_unittest.cc
index afdb0efc4da..ac012a09e0e 100644
--- a/chromium/content/browser/loader/redirect_to_file_resource_handler_unittest.cc
+++ b/chromium/content/browser/loader/redirect_to_file_resource_handler_unittest.cc
@@ -17,7 +17,6 @@
#include "base/location.h"
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/run_loop.h"
diff --git a/chromium/content/browser/loader/resource_dispatcher_host_browsertest.cc b/chromium/content/browser/loader/resource_dispatcher_host_browsertest.cc
index e56c4ff8b24..78188404651 100644
--- a/chromium/content/browser/loader/resource_dispatcher_host_browsertest.cc
+++ b/chromium/content/browser/loader/resource_dispatcher_host_browsertest.cc
@@ -11,7 +11,6 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/run_loop.h"
#include "base/strings/string_util.h"
@@ -48,6 +47,7 @@
#include "net/test/url_request/url_request_failed_job.h"
#include "net/test/url_request/url_request_mock_http_job.h"
#include "net/url_request/url_request.h"
+#include "services/network/public/cpp/features.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "url/gurl.h"
@@ -140,6 +140,10 @@ IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest, DynamicTitle2) {
IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest,
SniffHTMLWithNoContentType) {
+ // Covered by URLLoaderTest.SniffMimeType.
+ if (base::FeatureList::IsEnabled(network::features::kNetworkService))
+ return;
+
CheckTitleTest(
net::URLRequestMockHTTPJob::GetMockUrl("content-sniffer-test0.html"),
"Content Sniffer Test 0");
@@ -147,12 +151,20 @@ IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest,
IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest,
RespectNoSniffDirective) {
+ // Covered by URLLoaderTest.RespectNoSniff.
+ if (base::FeatureList::IsEnabled(network::features::kNetworkService))
+ return;
+
CheckTitleTest(net::URLRequestMockHTTPJob::GetMockUrl("nosniff-test.html"),
"mock.http/nosniff-test.html");
}
IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest,
DoNotSniffHTMLFromTextPlain) {
+ // Covered by URLLoaderTest.DoNotSniffHTMLFromTextPlain.
+ if (base::FeatureList::IsEnabled(network::features::kNetworkService))
+ return;
+
CheckTitleTest(
net::URLRequestMockHTTPJob::GetMockUrl("content-sniffer-test1.html"),
"mock.http/content-sniffer-test1.html");
@@ -160,6 +172,10 @@ IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest,
IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest,
DoNotSniffHTMLFromImageGIF) {
+ // Covered by URLLoaderTest.DoNotSniffHTMLFromImageGIF.
+ if (base::FeatureList::IsEnabled(network::features::kNetworkService))
+ return;
+
CheckTitleTest(
net::URLRequestMockHTTPJob::GetMockUrl("content-sniffer-test2.html"),
"mock.http/content-sniffer-test2.html");
@@ -593,6 +609,10 @@ class PageTransitionResourceDispatcherHostDelegate
// when encountering a meta refresh tag.
IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest,
PageTransitionClientRedirect) {
+ // TODO(crbug.com/818445): Fix the flakiness on Network Service.
+ if (base::FeatureList::IsEnabled(network::features::kNetworkService))
+ return;
+
ASSERT_TRUE(embedded_test_server()->Start());
PageTransitionResourceDispatcherHostDelegate delegate(
diff --git a/chromium/content/browser/loader/resource_dispatcher_host_impl.cc b/chromium/content/browser/loader/resource_dispatcher_host_impl.cc
index 0c57d207698..6c35edcd265 100644
--- a/chromium/content/browser/loader/resource_dispatcher_host_impl.cc
+++ b/chromium/content/browser/loader/resource_dispatcher_host_impl.cc
@@ -22,7 +22,6 @@
#include "base/feature_list.h"
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/shared_memory.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/field_trial.h"
@@ -64,10 +63,10 @@
#include "content/browser/service_worker/service_worker_context_wrapper.h"
#include "content/browser/service_worker/service_worker_navigation_handle_core.h"
#include "content/browser/service_worker/service_worker_request_handler.h"
-#include "content/browser/site_isolation_policy.h"
#include "content/browser/streams/stream.h"
#include "content/browser/streams/stream_context.h"
#include "content/browser/streams/stream_registry.h"
+#include "content/browser/web_package/signed_exchange_consts.h"
#include "content/common/net/url_request_service_worker_data.h"
#include "content/common/view_messages.h"
#include "content/public/browser/browser_child_process_host.h"
@@ -75,11 +74,12 @@
#include "content/public/browser/child_process_data.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/global_request_id.h"
+#include "content/public/browser/login_delegate.h"
#include "content/public/browser/navigation_ui_data.h"
#include "content/public/browser/plugin_service.h"
#include "content/public/browser/resource_dispatcher_host_delegate.h"
-#include "content/public/browser/resource_dispatcher_host_login_delegate.h"
#include "content/public/browser/resource_throttle.h"
+#include "content/public/browser/site_isolation_policy.h"
#include "content/public/browser/stream_handle.h"
#include "content/public/browser/stream_info.h"
#include "content/public/common/browser_side_navigation_policy.h"
@@ -88,6 +88,7 @@
#include "content/public/common/content_constants.h"
#include "content/public/common/content_features.h"
#include "content/public/common/origin_util.h"
+#include "content/public/common/resource_type.h"
#include "net/base/auth.h"
#include "net/base/load_flags.h"
#include "net/base/mime_util.h"
@@ -107,13 +108,14 @@
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_request_job_factory.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#include "services/network/loader_util.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/resource_request_body.h"
#include "services/network/public/cpp/url_loader_completion_status.h"
#include "services/network/public/mojom/request_context_frame_type.mojom.h"
#include "services/network/resource_scheduler.h"
+#include "services/network/url_loader_factory.h"
#include "storage/browser/blob/blob_data_handle.h"
#include "storage/browser/blob/blob_storage_context.h"
#include "storage/browser/blob/blob_url_request_job_factory.h"
@@ -139,9 +141,6 @@ static ResourceDispatcherHostImpl* g_resource_dispatcher_host;
// The interval for calls to ResourceDispatcherHostImpl::UpdateLoadStates
const int kUpdateLoadStatesIntervalMsec = 250;
-// The interval for calls to RecordOutstandingRequestsStats.
-const int kRecordOutstandingRequestsStatsIntervalSec = 60;
-
// Maximum byte "cost" of all the outstanding requests for a renderer.
// See declaration of |max_outstanding_requests_cost_per_process_| for details.
// This bound is 25MB, which allows for around 6000 outstanding requests.
@@ -276,11 +275,6 @@ void LogBackForwardNavigationFlagsHistogram(int load_flags) {
} // namespace
-constexpr int ResourceDispatcherHostImpl::kMaxKeepaliveConnections;
-constexpr int ResourceDispatcherHostImpl::kMaxKeepaliveConnectionsPerProcess;
-constexpr int
- ResourceDispatcherHostImpl::kMaxKeepaliveConnectionsPerProcessForFetchAPI;
-
class ResourceDispatcherHostImpl::ScheduledResourceRequestAdapter final
: public ResourceThrottle {
public:
@@ -340,7 +334,8 @@ ResourceDispatcherHostImpl::ResourceDispatcherHostImpl(
allow_cross_origin_auth_prompt_(false),
create_download_handler_intercept_(download_handler_intercept),
main_thread_task_runner_(base::ThreadTaskRunnerHandle::Get()),
- io_thread_task_runner_(io_thread_runner) {
+ io_thread_task_runner_(io_thread_runner),
+ weak_ptr_factory_(this) {
DCHECK(main_thread_task_runner_->BelongsToCurrentThread());
DCHECK(!g_resource_dispatcher_host);
g_resource_dispatcher_host = this;
@@ -353,16 +348,7 @@ ResourceDispatcherHostImpl::ResourceDispatcherHostImpl(
FROM_HERE, base::BindOnce(&ResourceDispatcherHostImpl::OnInit,
base::Unretained(this)));
- update_load_states_timer_ = std::make_unique<base::RepeatingTimer>();
-
- // Monitor per-tab outstanding requests only if OOPIF is not enabled, because
- // the routing id doesn't represent tabs in OOPIF modes.
- if (!SiteIsolationPolicy::UseDedicatedProcessesForAllSites() &&
- !SiteIsolationPolicy::IsTopDocumentIsolationEnabled() &&
- !SiteIsolationPolicy::AreIsolatedOriginsEnabled()) {
- record_outstanding_requests_stats_timer_ =
- std::make_unique<base::RepeatingTimer>();
- }
+ update_load_info_timer_ = std::make_unique<base::OneShotTimer>();
}
// The default ctor is only used by unittests. It is reasonable to assume that
@@ -374,7 +360,6 @@ ResourceDispatcherHostImpl::ResourceDispatcherHostImpl()
ResourceDispatcherHostImpl::~ResourceDispatcherHostImpl() {
DCHECK(outstanding_requests_stats_map_.empty());
- DCHECK(outstanding_requests_per_tab_map_.empty());
DCHECK(g_resource_dispatcher_host);
DCHECK(main_thread_task_runner_->BelongsToCurrentThread());
g_resource_dispatcher_host = nullptr;
@@ -556,8 +541,7 @@ ResourceDispatcherHostImpl::MaybeInterceptAsStream(
return std::move(handler);
}
-ResourceDispatcherHostLoginDelegate*
-ResourceDispatcherHostImpl::CreateLoginDelegate(
+scoped_refptr<LoginDelegate> ResourceDispatcherHostImpl::CreateLoginDelegate(
ResourceLoader* loader,
net::AuthChallengeInfo* auth_info) {
if (!delegate_)
@@ -568,16 +552,18 @@ ResourceDispatcherHostImpl::CreateLoginDelegate(
ResourceRequestInfoImpl* resource_request_info =
ResourceRequestInfoImpl::ForRequest(request);
DCHECK(resource_request_info);
- bool is_main_frame = resource_request_info->IsMainFrame();
+ bool is_main_frame =
+ resource_request_info->GetResourceType() == RESOURCE_TYPE_MAIN_FRAME;
+ GlobalRequestID request_id = resource_request_info->GetGlobalRequestID();
GURL url = request->url();
- ResourceDispatcherHostLoginDelegate* login_delegate =
+ scoped_refptr<LoginDelegate> login_delegate =
GetContentClient()->browser()->CreateLoginDelegate(
auth_info, resource_request_info->GetWebContentsGetterForRequest(),
is_main_frame, url, resource_request_info->first_auth_attempt(),
base::Bind(&ResourceDispatcherHostImpl::RunAuthRequiredCallback,
- base::Unretained(this), request));
+ base::Unretained(this), request_id));
resource_request_info->set_first_auth_attempt(false);
@@ -586,9 +572,6 @@ ResourceDispatcherHostImpl::CreateLoginDelegate(
bool ResourceDispatcherHostImpl::HandleExternalProtocol(ResourceLoader* loader,
const GURL& url) {
- if (!delegate_)
- return false;
-
ResourceRequestInfoImpl* info = loader->GetRequestInfo();
if (!IsResourceTypeFrame(info->GetResourceType()))
@@ -599,24 +582,15 @@ bool ResourceDispatcherHostImpl::HandleExternalProtocol(ResourceLoader* loader,
if (!url.is_valid() || job_factory->IsHandledProtocol(url.scheme()))
return false;
- return delegate_->HandleExternalProtocol(url, info);
+ return GetContentClient()->browser()->HandleExternalProtocol(
+ url, info->GetWebContentsGetterForRequest(), info->GetChildID(),
+ info->GetNavigationUIData(), info->IsMainFrame(),
+ info->GetPageTransition(), info->HasUserGesture());
}
void ResourceDispatcherHostImpl::DidStartRequest(ResourceLoader* loader) {
// Make sure we have the load state monitors running.
- if (!update_load_states_timer_->IsRunning() &&
- scheduler_->DeprecatedHasLoadingClients()) {
- update_load_states_timer_->Start(
- FROM_HERE, TimeDelta::FromMilliseconds(kUpdateLoadStatesIntervalMsec),
- this, &ResourceDispatcherHostImpl::UpdateLoadInfo);
- }
- if (record_outstanding_requests_stats_timer_ &&
- !record_outstanding_requests_stats_timer_->IsRunning()) {
- record_outstanding_requests_stats_timer_->Start(
- FROM_HERE,
- TimeDelta::FromSeconds(kRecordOutstandingRequestsStatsIntervalSec),
- this, &ResourceDispatcherHostImpl::RecordOutstandingRequestsStats);
- }
+ MaybeStartUpdateLoadInfoTimer();
}
void ResourceDispatcherHostImpl::DidReceiveRedirect(
@@ -718,15 +692,13 @@ void ResourceDispatcherHostImpl::OnShutdown() {
DCHECK(io_thread_task_runner_->BelongsToCurrentThread());
is_shutdown_ = true;
- keepalive_statistics_recorder_.Shutdown();
pending_loaders_.clear();
- // Make sure we shutdown the timers now, otherwise by the time our destructor
+ // Make sure we shutdown the timer now, otherwise by the time our destructor
// runs if the timer is still running the Task is deleted twice (once by
// the MessageLoop and the second time by RepeatingTimer).
- update_load_states_timer_.reset();
- record_outstanding_requests_stats_timer_.reset();
+ update_load_info_timer_.reset();
// Clear blocked requests if any left.
// Note that we have to do this in 2 passes as we cannot call
@@ -1120,6 +1092,8 @@ void ResourceDispatcherHostImpl::ContinuePendingBeginRequest(
new_request->set_method(request_data.method);
new_request->set_site_for_cookies(request_data.site_for_cookies);
+ new_request->set_attach_same_site_cookies(
+ request_data.attach_same_site_cookies);
// The initiator should normally be present, unless this is a navigation.
// Browser-initiated navigations don't have an initiator document, the
@@ -1269,14 +1243,11 @@ void ResourceDispatcherHostImpl::ContinuePendingBeginRequest(
std::move(url_loader_client),
static_cast<ResourceType>(request_data.resource_type));
} else {
- // Initialize the service worker handler for the request. We don't use
- // ServiceWorker for synchronous loads to avoid renderer deadlocks.
- const bool skip_service_worker =
- is_sync_load || request_data.skip_service_worker;
+ // Initialize the service worker handler for the request.
ServiceWorkerRequestHandler::InitializeHandler(
new_request.get(), requester_info->service_worker_context(),
blob_context, child_id, request_data.service_worker_provider_id,
- skip_service_worker, request_data.fetch_request_mode,
+ request_data.skip_service_worker, request_data.fetch_request_mode,
request_data.fetch_credentials_mode, request_data.fetch_redirect_mode,
request_data.fetch_integrity, request_data.keepalive,
static_cast<ResourceType>(request_data.resource_type),
@@ -1610,9 +1581,7 @@ void ResourceDispatcherHostImpl::CancelRequestsForRoute(
any_requests_transferring = true;
if (cancel_all_routes || route_id == info->GetRenderFrameID()) {
if (info->detachable_handler()) {
- if (base::FeatureList::IsEnabled(
- features::kKeepAliveRendererForKeepaliveRequests) &&
- info->keepalive()) {
+ if (info->keepalive()) {
// If the feature is enabled, the renderer process's lifetime is
// prolonged so there's no need to detach.
if (cancel_all_routes) {
@@ -1737,18 +1706,6 @@ void ResourceDispatcherHostImpl::UpdateOutstandingRequestsStats(
outstanding_requests_stats_map_[info.GetChildID()] = stats;
}
-void ResourceDispatcherHostImpl::IncrementOutstandingRequestsPerTab(
- int count,
- const ResourceRequestInfoImpl& info) {
- auto key = std::make_pair(info.GetChildID(), info.GetRouteID());
- OutstandingRequestsPerTabMap::iterator entry =
- outstanding_requests_per_tab_map_.insert(std::make_pair(key, 0)).first;
- entry->second += count;
- DCHECK_GE(entry->second, 0);
- if (entry->second == 0)
- outstanding_requests_per_tab_map_.erase(entry);
-}
-
ResourceDispatcherHostImpl::OustandingRequestsStats
ResourceDispatcherHostImpl::IncrementOutstandingRequestsMemory(
int count,
@@ -1784,8 +1741,6 @@ ResourceDispatcherHostImpl::IncrementOutstandingRequestsCount(
DCHECK_GE(stats.num_requests, 0);
UpdateOutstandingRequestsStats(*info, stats);
- IncrementOutstandingRequestsPerTab(count, *info);
-
if (num_in_flight_requests_ > largest_outstanding_request_count_seen_) {
largest_outstanding_request_count_seen_ = num_in_flight_requests_;
UMA_HISTOGRAM_COUNTS_1M(
@@ -1801,14 +1756,6 @@ ResourceDispatcherHostImpl::IncrementOutstandingRequestsCount(
largest_outstanding_request_per_process_count_seen_);
}
- if (num_in_flight_requests_ > peak_outstanding_request_count_)
- peak_outstanding_request_count_ = num_in_flight_requests_;
-
- if (HasRequestsFromMultipleActiveTabs() &&
- num_in_flight_requests_ > peak_outstanding_request_count_multitab_) {
- peak_outstanding_request_count_multitab_ = num_in_flight_requests_;
- }
-
return stats;
}
@@ -1886,7 +1833,6 @@ void ResourceDispatcherHostImpl::BeginNavigationRequest(
}
int load_flags = info.begin_params->load_flags;
- load_flags |= net::LOAD_VERIFY_EV_CERT;
if (info.is_main_frame)
load_flags |= net::LOAD_MAIN_FRAME_DEPRECATED;
@@ -1916,7 +1862,14 @@ void ResourceDispatcherHostImpl::BeginNavigationRequest(
net::HttpRequestHeaders headers;
headers.AddHeadersFromString(info.begin_params->headers);
- headers.SetHeader(network::kAcceptHeader, network::kFrameAcceptHeader);
+
+ std::string accept_value = network::kFrameAcceptHeader;
+ if (base::FeatureList::IsEnabled(features::kSignedHTTPExchange)) {
+ DCHECK(!accept_value.empty());
+ accept_value.append(kAcceptHeaderSignedExchangeSuffix);
+ }
+
+ headers.SetHeader(network::kAcceptHeader, accept_value);
new_request->SetExtraRequestHeaders(headers);
new_request->SetLoadFlags(load_flags);
@@ -2142,6 +2095,14 @@ void ResourceDispatcherHostImpl::BeginRequestInternal(
// requests with keepalive set have additional limitations.
if (info->keepalive()) {
+ constexpr auto kMaxKeepaliveConnections =
+ network::URLLoaderFactory::kMaxKeepaliveConnections;
+ constexpr auto kMaxKeepaliveConnectionsPerProcess =
+ network::URLLoaderFactory::kMaxKeepaliveConnectionsPerProcess;
+ constexpr auto kMaxKeepaliveConnectionsPerProcessForFetchAPI = network::
+ URLLoaderFactory::kMaxKeepaliveConnectionsPerProcessForFetchAPI;
+ // URLLoaderFactory::CreateLoaderAndStart has the duplicate logic.
+ // Update there too when this logic is updated.
const auto& recorder = keepalive_statistics_recorder_;
if (recorder.num_inflight_requests() >= kMaxKeepaliveConnections)
exhausted = true;
@@ -2330,8 +2291,7 @@ void ResourceDispatcherHostImpl::UpdateLoadStateOnUI(
PickMoreInterestingLoadInfos(std::move(infos));
for (const auto& load_info: *info_map) {
loader_delegate->LoadStateChanged(
- load_info.first,
- load_info.second.url, load_info.second.load_state,
+ load_info.first, load_info.second.host, load_info.second.load_state,
load_info.second.upload_position, load_info.second.upload_size);
}
}
@@ -2340,7 +2300,7 @@ void ResourceDispatcherHostImpl::UpdateLoadStateOnUI(
std::unique_ptr<ResourceDispatcherHostImpl::LoadInfoMap>
ResourceDispatcherHostImpl::PickMoreInterestingLoadInfos(
std::unique_ptr<LoadInfoList> infos) {
- std::unique_ptr<LoadInfoMap> info_map(new LoadInfoMap);
+ auto info_map = std::make_unique<LoadInfoMap>();
for (const auto& load_info : *infos) {
WebContents* web_contents = load_info.web_contents_getter.Run();
if (!web_contents)
@@ -2356,61 +2316,74 @@ ResourceDispatcherHostImpl::PickMoreInterestingLoadInfos(
}
std::unique_ptr<ResourceDispatcherHostImpl::LoadInfoList>
-ResourceDispatcherHostImpl::GetLoadInfoForAllRoutes() {
- std::unique_ptr<LoadInfoList> infos(new LoadInfoList);
-
+ResourceDispatcherHostImpl::GetInterestingPerFrameLoadInfos() {
+ auto infos = std::make_unique<LoadInfoList>();
+ std::map<GlobalFrameRoutingId, LoadInfo> frame_infos;
for (const auto& loader : pending_loaders_) {
net::URLRequest* request = loader.second->request();
net::UploadProgress upload_progress = request->GetUploadProgress();
LoadInfo load_info;
- load_info.web_contents_getter =
- loader.second->GetRequestInfo()->GetWebContentsGetterForRequest();
- load_info.url = request->url();
+ load_info.host = request->url().host();
load_info.load_state = request->GetLoadState();
load_info.upload_size = upload_progress.size();
load_info.upload_position = upload_progress.position();
- infos->push_back(load_info);
+
+ ResourceRequestInfoImpl* request_info = loader.second->GetRequestInfo();
+ load_info.web_contents_getter =
+ request_info->GetWebContentsGetterForRequest();
+
+ // Navigation requests have frame_tree_node_ids, and may not have frame
+ // routing ids. Just include them unconditionally.
+ if (request_info->frame_tree_node_id() != -1) {
+ infos->push_back(load_info);
+ } else {
+ GlobalFrameRoutingId id(request_info->GetChildID(),
+ request_info->GetRenderFrameID());
+ auto existing = frame_infos.find(id);
+ if (existing == frame_infos.end() ||
+ LoadInfoIsMoreInteresting(load_info, existing->second)) {
+ frame_infos[id] = std::move(load_info);
+ }
+ }
+ }
+
+ for (auto it : frame_infos) {
+ infos->push_back(std::move(it.second));
}
return infos;
}
void ResourceDispatcherHostImpl::UpdateLoadInfo() {
- std::unique_ptr<LoadInfoList> infos(GetLoadInfoForAllRoutes());
-
- // Stop the timer if there are no more pending requests. Future new requests
- // will restart it as necessary.
- // Also stop the timer if there are no loading clients, to avoid waking up
- // unnecessarily when there is a long running (hanging get) request.
- if (infos->empty() || !scheduler_->DeprecatedHasLoadingClients()) {
- update_load_states_timer_->Stop();
- return;
- }
+ std::unique_ptr<LoadInfoList> infos(GetInterestingPerFrameLoadInfos());
// We need to be able to compare all requests to find the most important one
// per tab. Since some requests may be navigation requests and we don't have
// their render frame routing IDs yet (which is what we have for subresource
// requests), we must go to the UI thread and compare the requests using their
// WebContents.
- main_thread_task_runner_->PostTask(
+ waiting_on_load_state_ack_ = true;
+ main_thread_task_runner_->PostTaskAndReply(
FROM_HERE,
- base::BindOnce(UpdateLoadStateOnUI, loader_delegate_, std::move(infos)));
+ base::BindOnce(UpdateLoadStateOnUI, loader_delegate_, std::move(infos)),
+ base::BindOnce(&ResourceDispatcherHostImpl::AckUpdateLoadInfo,
+ weak_ptr_factory_.GetWeakPtr()));
}
-void ResourceDispatcherHostImpl::RecordOutstandingRequestsStats() {
- if (peak_outstanding_request_count_ != 0) {
- UMA_HISTOGRAM_COUNTS_1M(
- "Net.ResourceDispatcherHost.PeakOutstandingRequests",
- peak_outstanding_request_count_);
- peak_outstanding_request_count_ = num_in_flight_requests_;
- }
+void ResourceDispatcherHostImpl::AckUpdateLoadInfo() {
+ DCHECK(waiting_on_load_state_ack_);
+ waiting_on_load_state_ack_ = false;
+ MaybeStartUpdateLoadInfoTimer();
+}
- if (peak_outstanding_request_count_multitab_ != 0) {
- UMA_HISTOGRAM_COUNTS_1M(
- "Net.ResourceDispatcherHost.PeakOutstandingRequests.MultiTabLoading",
- peak_outstanding_request_count_multitab_);
- peak_outstanding_request_count_multitab_ =
- HasRequestsFromMultipleActiveTabs() ? num_in_flight_requests_ : 0;
+void ResourceDispatcherHostImpl::MaybeStartUpdateLoadInfoTimer() {
+ // If shutdown has occurred, |update_load_info_timer_| is nullptr.
+ if (!is_shutdown_ && !waiting_on_load_state_ack_ &&
+ !update_load_info_timer_->IsRunning() &&
+ scheduler_->DeprecatedHasLoadingClients() && !pending_loaders_.empty()) {
+ update_load_info_timer_->Start(
+ FROM_HERE, TimeDelta::FromMilliseconds(kUpdateLoadStatesIntervalMsec),
+ this, &ResourceDispatcherHostImpl::UpdateLoadInfo);
}
}
@@ -2592,41 +2565,27 @@ ResourceDispatcherHostImpl::HandleDownloadStarted(
return handler;
}
-bool ResourceDispatcherHostImpl::HasRequestsFromMultipleActiveTabs() {
- if (outstanding_requests_per_tab_map_.size() < 2)
- return false;
-
- int active_tabs = 0;
- for (auto iter = outstanding_requests_per_tab_map_.begin();
- iter != outstanding_requests_per_tab_map_.end(); ++iter) {
- if (iter->second > 2) {
- active_tabs++;
- if (active_tabs >= 2)
- return true;
- }
- }
- return false;
-}
-
void ResourceDispatcherHostImpl::RunAuthRequiredCallback(
- net::URLRequest* url_request,
+ GlobalRequestID request_id,
const base::Optional<net::AuthCredentials>& credentials) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
+ ResourceLoader* loader = GetLoader(request_id);
+ if (!loader)
+ return;
+
+ net::URLRequest* url_request = loader->request();
+ if (!url_request)
+ return;
+
if (!credentials.has_value()) {
url_request->CancelAuth();
} else {
url_request->SetAuth(credentials.value());
}
- // Clears the ResourceDispatcherHostLoginDelegate associated with the request.
- ResourceRequestInfoImpl* info =
- ResourceRequestInfoImpl::ForRequest(url_request);
- if (info) {
- ResourceLoader* loader = GetLoader(info->GetGlobalRequestID());
- if (loader)
- loader->ClearLoginDelegate();
- }
+ // Clears the LoginDelegate associated with the request.
+ loader->ClearLoginDelegate();
}
// static
diff --git a/chromium/content/browser/loader/resource_dispatcher_host_impl.h b/chromium/content/browser/loader/resource_dispatcher_host_impl.h
index efc95f33dc2..80be7b79b0f 100644
--- a/chromium/content/browser/loader/resource_dispatcher_host_impl.h
+++ b/chromium/content/browser/loader/resource_dispatcher_host_impl.h
@@ -23,6 +23,7 @@
#include "base/gtest_prod_util.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
+#include "base/memory/weak_ptr.h"
#include "base/observer_list.h"
#include "base/optional.h"
#include "base/single_thread_task_runner.h"
@@ -47,7 +48,7 @@
namespace base {
class FilePath;
-class RepeatingTimer;
+class OneShotTimer;
}
namespace net {
@@ -359,6 +360,7 @@ class CONTENT_EXPORT ResourceDispatcherHostImpl
FRIEND_TEST_ALL_PREFIXES(ResourceDispatcherHostTest, LoadInfoSamePriority);
FRIEND_TEST_ALL_PREFIXES(ResourceDispatcherHostTest, LoadInfoUploadProgress);
FRIEND_TEST_ALL_PREFIXES(ResourceDispatcherHostTest, LoadInfoTwoRenderViews);
+ FRIEND_TEST_ALL_PREFIXES(WebContentsImplBrowserTest, UpdateLoadState);
struct OustandingRequestsStats {
int memory_cost;
@@ -375,7 +377,11 @@ class CONTENT_EXPORT ResourceDispatcherHostImpl
~LoadInfo();
ResourceRequestInfo::WebContentsGetter web_contents_getter;
- GURL url;
+
+ // Comes directly from GURL::host() to avoid copying an entire GURL between
+ // threads.
+ std::string host;
+
net::LoadStateWithParam load_state;
uint64_t upload_position;
uint64_t upload_size;
@@ -403,7 +409,7 @@ class CONTENT_EXPORT ResourceDispatcherHostImpl
typedef std::map<std::string, HeaderInterceptorInfo> HeaderInterceptorMap;
// ResourceLoaderDelegate implementation:
- ResourceDispatcherHostLoginDelegate* CreateLoginDelegate(
+ scoped_refptr<LoginDelegate> CreateLoginDelegate(
ResourceLoader* loader,
net::AuthChallengeInfo* auth_info) override;
bool HandleExternalProtocol(ResourceLoader* loader, const GURL& url) override;
@@ -460,13 +466,6 @@ class CONTENT_EXPORT ResourceDispatcherHostImpl
int count,
ResourceRequestInfoImpl* info);
- // Called from IncrementOutstandingRequestsCount to update the per-tab
- // request stats in |outstanding_requests_per_tab_map_|.
- // TODO(ksakamoto): This is just for temporary metrics collection for the
- // Loading Dispatcher v0 (crbug.com/723233), and will be removed soon.
- void IncrementOutstandingRequestsPerTab(int count,
- const ResourceRequestInfoImpl& info);
-
// Estimate how much heap space |request| will consume to run.
static int CalculateApproximateMemoryCost(net::URLRequest* request);
@@ -517,15 +516,25 @@ class CONTENT_EXPORT ResourceDispatcherHostImpl
static std::unique_ptr<LoadInfoMap> PickMoreInterestingLoadInfos(
std::unique_ptr<LoadInfoList> infos);
- // Gets all the LoadInfos for each pending request.
- std::unique_ptr<LoadInfoList> GetLoadInfoForAllRoutes();
+ // Gets the most interesting LoadInfos for each GlobalFrameRoutingIds.
+ // Includes the LoadInfo for all navigation requests, which may not have valid
+ // frame ids.
+ //
+ // We aggregate per-frame on the IO thread, and per-WebContents on the UI
+ // thread. The IO thread aggregation is used to avoid copying state for every
+ // request across threads.
+ std::unique_ptr<LoadInfoList> GetInterestingPerFrameLoadInfos();
// Checks all pending requests and updates the load info if necessary.
void UpdateLoadInfo();
- // Records statistics about outstanding requests since the last call, and
- // reset the stats.
- void RecordOutstandingRequestsStats();
+ // Invoked on the IO thread once load state has been updated on the UI thread,
+ // starts timer call UpdateLoadInfo() again, if needed.
+ void AckUpdateLoadInfo();
+
+ // Starts the timer to call UpdateLoadInfo(), if timer isn't already running,
+ // |waiting_on_load_state_ack_| is false, and there are live ResourceLoaders.
+ void MaybeStartUpdateLoadInfoTimer();
// Resumes or cancels (if |cancel_requests| is true) any blocked requests.
void ProcessBlockedRequestsForRoute(
@@ -687,13 +696,9 @@ class CONTENT_EXPORT ResourceDispatcherHostImpl
bool is_new_request);
void RunAuthRequiredCallback(
- net::URLRequest* url_request,
+ GlobalRequestID request_id,
const base::Optional<net::AuthCredentials>& credentials);
- // Returns true if there are two or more tabs that are not network 2-quiet
- // (i.e. have at least three outstanding requests).
- bool HasRequestsFromMultipleActiveTabs();
-
static net::NetworkTrafficAnnotationTag GetTrafficAnnotation();
LoaderMap pending_loaders_;
@@ -707,13 +712,13 @@ class CONTENT_EXPORT ResourceDispatcherHostImpl
RegisteredTempFiles; // key is child process id
RegisteredTempFiles registered_temp_files_;
- // A timer that periodically calls UpdateLoadInfo while pending_loaders_ is
- // not empty and at least one RenderViewHost is loading.
- std::unique_ptr<base::RepeatingTimer> update_load_states_timer_;
-
- // A timer that periodically calls RecordOutstandingRequestsStats.
- std::unique_ptr<base::RepeatingTimer>
- record_outstanding_requests_stats_timer_;
+ // A timer that periodically calls UpdateLoadInfo while |pending_loaders_| is
+ // not empty, at least one RenderViewHost is loading, and not waiting on an
+ // ACK from the UI thread for the last sent LoadInfoList.
+ std::unique_ptr<base::OneShotTimer> update_load_info_timer_;
+ // True if a LoadInfoList has been sent to the UI thread, but has yet to be
+ // acknowledged.
+ bool waiting_on_load_state_ack_ = false;
// Request ID for browser initiated requests. request_ids generated by
// child processes are counted up from 0, while browser created requests
@@ -739,14 +744,6 @@ class CONTENT_EXPORT ResourceDispatcherHostImpl
typedef std::map<int, OustandingRequestsStats> OutstandingRequestsStatsMap;
OutstandingRequestsStatsMap outstanding_requests_stats_map_;
- // Maps (child_id, route_id) to the number of outstanding requests.
- // Used only when OOPIF is not enabled, since in OOPIF modes routing_id
- // doesn't represent tabs.
- // TODO(ksakamoto): This is just for temporary metrics collection for the
- // Loading Dispatcher v0 (crbug.com/723233), and will be removed soon.
- typedef std::map<std::pair<int, int>, int> OutstandingRequestsPerTabMap;
- OutstandingRequestsPerTabMap outstanding_requests_per_tab_map_;
-
// |num_in_flight_requests_| is the total number of requests currently issued
// summed across all renderers.
int num_in_flight_requests_;
@@ -778,15 +775,6 @@ class CONTENT_EXPORT ResourceDispatcherHostImpl
// Largest number of outstanding requests seen so far in any single process.
int largest_outstanding_request_per_process_count_seen_;
- // Largest number of outstanding requests seen since the last call to
- // RecordOutstandingRequestsStats.
- int peak_outstanding_request_count_ = 0;
-
- // Largest number of outstanding requests seen while there are outstanding
- // requests from two or more tabs, since the last call to
- // RecordOutstandingRequestsStats.
- int peak_outstanding_request_count_multitab_ = 0;
-
// Time of the last user gesture. Stored so that we can add a load
// flag to requests occurring soon after a gesture to indicate they
// may be because of explicit user action.
@@ -814,9 +802,7 @@ class CONTENT_EXPORT ResourceDispatcherHostImpl
// Task runner for the IO thead.
scoped_refptr<base::SingleThreadTaskRunner> io_thread_task_runner_;
- static constexpr int kMaxKeepaliveConnections = 256;
- static constexpr int kMaxKeepaliveConnectionsPerProcess = 20;
- static constexpr int kMaxKeepaliveConnectionsPerProcessForFetchAPI = 10;
+ base::WeakPtrFactory<ResourceDispatcherHostImpl> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(ResourceDispatcherHostImpl);
};
diff --git a/chromium/content/browser/loader/resource_dispatcher_host_unittest.cc b/chromium/content/browser/loader/resource_dispatcher_host_unittest.cc
index a7297fd938b..7e099c63746 100644
--- a/chromium/content/browser/loader/resource_dispatcher_host_unittest.cc
+++ b/chromium/content/browser/loader/resource_dispatcher_host_unittest.cc
@@ -13,7 +13,6 @@
#include "base/files/file_util.h"
#include "base/location.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
@@ -23,7 +22,6 @@
#include "base/task_scheduler/task_traits.h"
#include "base/test/scoped_feature_list.h"
#include "base/threading/thread_task_runner_handle.h"
-#include "content/browser/browser_thread_impl.h"
#include "content/browser/child_process_security_policy_impl.h"
#include "content/browser/download/download_manager_impl.h"
#include "content/browser/download/download_resource_handler.h"
@@ -60,7 +58,7 @@
#include "content/public/test/test_utils.h"
#include "content/test/test_content_browser_client.h"
#include "content/test/test_navigation_url_loader_delegate.h"
-#include "mojo/common/data_pipe_utils.h"
+#include "mojo/public/cpp/system/data_pipe_utils.h"
#include "net/base/chunked_upload_data_stream.h"
#include "net/base/elements_upload_data_stream.h"
#include "net/base/load_flags.h"
@@ -83,7 +81,7 @@
#include "services/network/test/test_url_loader_client.h"
#include "storage/browser/blob/shareable_file_reference.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/page/page_visibility_state.mojom.h"
+#include "third_party/blink/public/mojom/page/page_visibility_state.mojom.h"
// TODO(eroman): Write unit tests for SafeBrowsing that exercise
// SafeBrowsingResourceHandler.
@@ -105,7 +103,6 @@ static network::ResourceRequest CreateResourceRequest(const char* method,
request.load_flags = 0;
request.plugin_child_id = -1;
request.resource_type = type;
- request.request_context = 0;
request.appcache_host_id = kAppCacheNoHostId;
request.download_to_file = false;
request.should_reset_appcache = false;
@@ -815,12 +812,13 @@ class ResourceDispatcherHostTest : public testing::Test {
false /* is_form_submission */, GURL() /* searchable_form_url */,
std::string() /* searchable_form_encoding */,
url::Origin::Create(url), GURL() /* client_side_redirect_url */,
- nullptr /* devtools_initiator_info */);
+ base::nullopt /* devtools_initiator_info */);
CommonNavigationParams common_params;
common_params.url = url;
std::unique_ptr<NavigationRequestInfo> request_info(
new NavigationRequestInfo(common_params, std::move(begin_params), url,
- true, false, false, -1, false, false, false));
+ true, false, false, -1, false, false, false,
+ nullptr));
std::unique_ptr<NavigationURLLoader> test_loader =
NavigationURLLoader::Create(
browser_context_->GetResourceContext(),
@@ -964,7 +962,7 @@ void CheckSuccessfulRequest(network::TestURLLoaderClient* client,
ASSERT_TRUE(body.is_valid());
std::string actual;
- EXPECT_TRUE(mojo::common::BlockingCopyToString(std::move(body), &actual));
+ EXPECT_TRUE(mojo::BlockingCopyToString(std::move(body), &actual));
EXPECT_EQ(reference_data, actual);
}
client->RunUntilComplete();
@@ -1068,60 +1066,41 @@ TEST_F(ResourceDispatcherHostTest, DetachedResourceTimesOut) {
// If the filter has disappeared then detachable resources should continue to
// load.
-// RESOURCE_TYPE_PING requests Handling is affected by
-// "KeepAliveRendererForKeepaliveRequests" feature. We keep this test so that
-// we can unship the feature easily if needed.
-// TODO(yhirano): Add a corresponding test case with the feature.
TEST_F(ResourceDispatcherHostTest, DeletedFilterDetached) {
- network::mojom::URLLoaderPtr loader1, loader2;
- network::TestURLLoaderClient client1, client2;
+ network::mojom::URLLoaderPtr loader1;
+ network::TestURLLoaderClient client1;
base::test::ScopedFeatureList feature_list;
- feature_list.InitAndDisableFeature(
- features::kKeepAliveRendererForKeepaliveRequests);
// test_url_1's data is available synchronously, so use 2 and 3.
network::ResourceRequest request_prefetch = CreateResourceRequest(
"GET", RESOURCE_TYPE_PREFETCH, net::URLRequestTestJob::test_url_2());
- network::ResourceRequest request_ping = CreateResourceRequest(
- "GET", RESOURCE_TYPE_PING, net::URLRequestTestJob::test_url_3());
filter_->CreateLoaderAndStart(
mojo::MakeRequest(&loader1), 0, 1, network::mojom::kURLLoadOptionNone,
request_prefetch, client1.CreateInterfacePtr(),
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS));
- filter_->CreateLoaderAndStart(
- mojo::MakeRequest(&loader2), 0, 2, network::mojom::kURLLoadOptionNone,
- request_ping, client2.CreateInterfacePtr(),
- net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS));
-
// Remove the filter before processing the requests by simulating channel
// closure.
ResourceRequestInfoImpl* info_prefetch = ResourceRequestInfoImpl::ForRequest(
host_.GetURLRequest(GlobalRequestID(filter_->child_id(), 1)));
- ResourceRequestInfoImpl* info_ping = ResourceRequestInfoImpl::ForRequest(
- host_.GetURLRequest(GlobalRequestID(filter_->child_id(), 2)));
DCHECK_EQ(filter_.get(), info_prefetch->requester_info()->filter());
- DCHECK_EQ(filter_.get(), info_ping->requester_info()->filter());
filter_->OnChannelClosing();
client1.RunUntilComplete();
- client2.RunUntilComplete();
EXPECT_EQ(net::ERR_ABORTED, client1.completion_status().error_code);
- EXPECT_EQ(net::ERR_ABORTED, client2.completion_status().error_code);
// But it continues detached.
- EXPECT_EQ(2, host_.pending_requests());
+ EXPECT_EQ(1, host_.pending_requests());
EXPECT_TRUE(info_prefetch->detachable_handler()->is_detached());
- EXPECT_TRUE(info_ping->detachable_handler()->is_detached());
// Make sure the requests weren't canceled early.
- EXPECT_EQ(2, host_.pending_requests());
+ EXPECT_EQ(1, host_.pending_requests());
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
content::RunAllTasksUntilIdle();
EXPECT_EQ(0, host_.pending_requests());
- EXPECT_EQ(2, network_delegate()->completed_requests());
+ EXPECT_EQ(1, network_delegate()->completed_requests());
EXPECT_EQ(0, network_delegate()->canceled_requests());
EXPECT_EQ(0, network_delegate()->error_count());
}
@@ -1348,16 +1327,10 @@ TEST_F(ResourceDispatcherHostTest, CancelInDelegate) {
EXPECT_EQ(net::ERR_ACCESS_DENIED, client.completion_status().error_code);
}
-// RESOURCE_TYPE_PING requests Handling is affected by
-// "KeepAliveRendererForKeepaliveRequests" feature. We keep this test so that
-// we can unship the feature easily if needed.
-// TODO(yhirano): Add a corresponding test case with the feature.
TEST_F(ResourceDispatcherHostTest, CancelRequestsForRoute) {
network::mojom::URLLoaderPtr loader1, loader2, loader3, loader4;
network::TestURLLoaderClient client1, client2, client3, client4;
base::test::ScopedFeatureList feature_list;
- feature_list.InitAndDisableFeature(
- features::kKeepAliveRendererForKeepaliveRequests);
job_factory_->SetDelayedStartJobGeneration(true);
MakeTestRequestWithRenderFrame(0, 11, 1, net::URLRequestTestJob::test_url_1(),
RESOURCE_TYPE_XHR, mojo::MakeRequest(&loader1),
@@ -1370,12 +1343,12 @@ TEST_F(ResourceDispatcherHostTest, CancelRequestsForRoute) {
EXPECT_EQ(2, host_.pending_requests());
MakeTestRequestWithRenderFrame(
- 0, 11, 3, net::URLRequestTestJob::test_url_3(), RESOURCE_TYPE_PING,
+ 0, 11, 3, net::URLRequestTestJob::test_url_3(), RESOURCE_TYPE_PREFETCH,
mojo::MakeRequest(&loader3), client3.CreateInterfacePtr());
EXPECT_EQ(3, host_.pending_requests());
MakeTestRequestWithRenderFrame(
- 0, 12, 4, net::URLRequestTestJob::test_url_4(), RESOURCE_TYPE_PING,
+ 0, 12, 4, net::URLRequestTestJob::test_url_4(), RESOURCE_TYPE_PREFETCH,
mojo::MakeRequest(&loader4), client4.CreateInterfacePtr());
EXPECT_EQ(4, host_.pending_requests());
@@ -2145,15 +2118,47 @@ TEST_F(ResourceDispatcherHostTest, CancelRequestsForContextDetached) {
EXPECT_EQ(0, host_.pending_requests());
}
+namespace {
+
+class ExternalProtocolBrowserClient : public TestContentBrowserClient {
+ public:
+ ExternalProtocolBrowserClient() {}
+
+ bool HandleExternalProtocol(
+ const GURL& url,
+ ResourceRequestInfo::WebContentsGetter web_contents_getter,
+ int child_id,
+ NavigationUIData* navigation_data,
+ bool is_main_frame,
+ ui::PageTransition page_transition,
+ bool has_user_gesture) override {
+ return false;
+ }
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(ExternalProtocolBrowserClient);
+};
+
+} // namespace
+
+// Verifies that if the embedder says that it didn't handle an unkonown protocol
+// the request is cancelled and net::ERR_ABORTED is returned. Otherwise it is
+// not aborted and net/ layer cancels it with net::ERR_UNKNOWN_URL_SCHEME.
TEST_F(ResourceDispatcherHostTest, UnknownURLScheme) {
EXPECT_EQ(0, host_.pending_requests());
HandleScheme("http");
- const GURL invalid_sheme_url = GURL("foo://bar");
- const int expected_error_code = net::ERR_UNKNOWN_URL_SCHEME;
+ ExternalProtocolBrowserClient test_client;
+ ContentBrowserClient* old_client = SetBrowserClientForTesting(&test_client);
+
+ const GURL invalid_scheme_url = GURL("foo://bar");
+ int expected_error_code = net::ERR_UNKNOWN_URL_SCHEME;
+ CompleteFailingMainResourceRequest(invalid_scheme_url, expected_error_code);
+ SetBrowserClientForTesting(old_client);
- CompleteFailingMainResourceRequest(invalid_sheme_url, expected_error_code);
+ expected_error_code = net::ERR_ABORTED;
+ CompleteFailingMainResourceRequest(invalid_scheme_url, expected_error_code);
}
// Request a very large detachable resource and cancel part way. Some of the
@@ -2346,24 +2351,24 @@ TEST_F(ResourceDispatcherHostTest, LoadInfo) {
info.web_contents_getter = base::Bind(WebContentsBinder, wc1);
info.load_state = net::LoadStateWithParam(net::LOAD_STATE_SENDING_REQUEST,
base::string16());
- info.url = GURL("test://1/");
+ info.host = "a.com";
info.upload_position = 0;
info.upload_size = 0;
infos->push_back(info);
- info.url = GURL("test://2/");
+ info.host = "b.com";
info.load_state = net::LoadStateWithParam(net::LOAD_STATE_READING_RESPONSE,
base::string16());
infos->push_back(info);
- info.url = GURL("test://3/");
+ info.host = "c.com";
std::unique_ptr<LoadInfoMap> load_info_map =
ResourceDispatcherHostImpl::PickMoreInterestingLoadInfos(
std::move(infos));
ASSERT_EQ(1u, load_info_map->size());
ASSERT_TRUE(load_info_map->find(wc1) != load_info_map->end());
- EXPECT_EQ(GURL("test://2/"), (*load_info_map)[wc1].url);
+ EXPECT_EQ("b.com", (*load_info_map)[wc1].host);
EXPECT_EQ(net::LOAD_STATE_READING_RESPONSE,
(*load_info_map)[wc1].load_state.state);
EXPECT_EQ(0u, (*load_info_map)[wc1].upload_position);
@@ -2379,12 +2384,12 @@ TEST_F(ResourceDispatcherHostTest, LoadInfoSamePriority) {
info.web_contents_getter = base::Bind(WebContentsBinder, wc1);
info.load_state = net::LoadStateWithParam(net::LOAD_STATE_IDLE,
base::string16());
- info.url = GURL("test://1/");
+ info.host = "a.com";
info.upload_position = 0;
info.upload_size = 0;
infos->push_back(info);
- info.url = GURL("test://2/");
+ info.host = "b.com";
infos->push_back(info);
std::unique_ptr<LoadInfoMap> load_info_map =
@@ -2392,7 +2397,7 @@ TEST_F(ResourceDispatcherHostTest, LoadInfoSamePriority) {
std::move(infos));
ASSERT_EQ(1u, load_info_map->size());
ASSERT_TRUE(load_info_map->find(wc1) != load_info_map->end());
- EXPECT_EQ(GURL("test://1/"), (*load_info_map)[wc1].url);
+ EXPECT_EQ("a.com", (*load_info_map)[wc1].host);
EXPECT_EQ(net::LOAD_STATE_IDLE, (*load_info_map)[wc1].load_state.state);
EXPECT_EQ(0u, (*load_info_map)[wc1].upload_position);
EXPECT_EQ(0u, (*load_info_map)[wc1].upload_size);
@@ -2406,7 +2411,7 @@ TEST_F(ResourceDispatcherHostTest, LoadInfoUploadProgress) {
info.web_contents_getter = base::Bind(WebContentsBinder, wc1);
info.load_state = net::LoadStateWithParam(net::LOAD_STATE_READING_RESPONSE,
base::string16());
- info.url = GURL("test://1/");
+ info.host = "a.com";
info.upload_position = 0;
info.upload_size = 0;
infos->push_back(info);
@@ -2415,21 +2420,21 @@ TEST_F(ResourceDispatcherHostTest, LoadInfoUploadProgress) {
info.upload_size = 1000;
infos->push_back(info);
- info.url = GURL("test://2/");
+ info.host = "b.com";
info.load_state = net::LoadStateWithParam(net::LOAD_STATE_SENDING_REQUEST,
base::string16());
info.upload_position = 50;
info.upload_size = 100;
infos->push_back(info);
- info.url = GURL("test://1/");
+ info.host = "a.com";
info.load_state = net::LoadStateWithParam(net::LOAD_STATE_READING_RESPONSE,
base::string16());
info.upload_position = 1000;
info.upload_size = 1000;
infos->push_back(info);
- info.url = GURL("test://3/");
+ info.host = "c.com";
info.upload_position = 0;
info.upload_size = 0;
infos->push_back(info);
@@ -2439,7 +2444,7 @@ TEST_F(ResourceDispatcherHostTest, LoadInfoUploadProgress) {
std::move(infos));
ASSERT_EQ(1u, load_info_map->size());
ASSERT_TRUE(load_info_map->find(wc1) != load_info_map->end());
- EXPECT_EQ(GURL("test://2/"), (*load_info_map)[wc1].url);
+ EXPECT_EQ("b.com", (*load_info_map)[wc1].host);
EXPECT_EQ(net::LOAD_STATE_SENDING_REQUEST,
(*load_info_map)[wc1].load_state.state);
EXPECT_EQ(50u, (*load_info_map)[wc1].upload_position);
@@ -2456,7 +2461,7 @@ TEST_F(ResourceDispatcherHostTest, LoadInfoTwoRenderViews) {
info.web_contents_getter = base::Bind(WebContentsBinder, wc1);
info.load_state = net::LoadStateWithParam(net::LOAD_STATE_CONNECTING,
base::string16());
- info.url = GURL("test://1/");
+ info.host = "a.com";
info.upload_position = 0;
info.upload_size = 0;
infos->push_back(info);
@@ -2465,17 +2470,17 @@ TEST_F(ResourceDispatcherHostTest, LoadInfoTwoRenderViews) {
info.web_contents_getter = base::Bind(WebContentsBinder, wc2);
info.load_state = net::LoadStateWithParam(net::LOAD_STATE_IDLE,
base::string16());
- info.url = GURL("test://2/");
+ info.host = "b.com";
infos->push_back(info);
info.web_contents_getter = base::Bind(WebContentsBinder, wc1);
- info.url = GURL("test://3/");
+ info.host = "c.com";
infos->push_back(info);
info.web_contents_getter = base::Bind(WebContentsBinder, wc2);
info.load_state = net::LoadStateWithParam(net::LOAD_STATE_CONNECTING,
base::string16());
- info.url = GURL("test://4/");
+ info.host = "d.com";
infos->push_back(info);
std::unique_ptr<LoadInfoMap> load_info_map =
@@ -2484,14 +2489,14 @@ TEST_F(ResourceDispatcherHostTest, LoadInfoTwoRenderViews) {
ASSERT_EQ(2u, load_info_map->size());
ASSERT_TRUE(load_info_map->find(wc1) != load_info_map->end());
- EXPECT_EQ(GURL("test://1/"), (*load_info_map)[wc1].url);
+ EXPECT_EQ("a.com", (*load_info_map)[wc1].host);
EXPECT_EQ(net::LOAD_STATE_CONNECTING,
(*load_info_map)[wc1].load_state.state);
EXPECT_EQ(0u, (*load_info_map)[wc1].upload_position);
EXPECT_EQ(0u, (*load_info_map)[wc1].upload_size);
ASSERT_TRUE(load_info_map->find(wc2) != load_info_map->end());
- EXPECT_EQ(GURL("test://4/"), (*load_info_map)[wc2].url);
+ EXPECT_EQ("d.com", (*load_info_map)[wc2].host);
EXPECT_EQ(net::LOAD_STATE_CONNECTING,
(*load_info_map)[wc2].load_state.state);
EXPECT_EQ(0u, (*load_info_map)[wc2].upload_position);
diff --git a/chromium/content/browser/loader/resource_hints_impl.cc b/chromium/content/browser/loader/resource_hints_impl.cc
index 6b1451c8de6..259dfa23ec6 100644
--- a/chromium/content/browser/loader/resource_hints_impl.cc
+++ b/chromium/content/browser/loader/resource_hints_impl.cc
@@ -4,7 +4,6 @@
#include <string>
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/trace_event/trace_event.h"
#include "content/browser/loader/resource_dispatcher_host_impl.h"
diff --git a/chromium/content/browser/loader/resource_loader.cc b/chromium/content/browser/loader/resource_loader.cc
index 12e44acf2c5..bad80bb69bc 100644
--- a/chromium/content/browser/loader/resource_loader.cc
+++ b/chromium/content/browser/loader/resource_loader.cc
@@ -9,7 +9,6 @@
#include "base/callback_helpers.h"
#include "base/command_line.h"
#include "base/location.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
@@ -26,7 +25,7 @@
#include "content/browser/ssl/ssl_client_auth_handler.h"
#include "content/browser/ssl/ssl_manager.h"
#include "content/public/browser/content_browser_client.h"
-#include "content/public/browser/resource_dispatcher_host_login_delegate.h"
+#include "content/public/browser/login_delegate.h"
#include "content/public/common/appcache_info.h"
#include "content/public/common/browser_side_navigation_policy.h"
#include "content/public/common/content_client.h"
@@ -35,7 +34,6 @@
#include "net/base/io_buffer.h"
#include "net/base/load_flags.h"
#include "net/cert/symantec_certs.h"
-#include "net/cert/x509_util.h"
#include "net/http/http_response_headers.h"
#include "net/nqe/effective_connection_type.h"
#include "net/nqe/network_quality_estimator.h"
@@ -72,6 +70,8 @@ void PopulateResourceResponse(
response_info.alpn_negotiated_protocol;
response->head.connection_info = response_info.connection_info;
response->head.socket_address = response_info.socket_address;
+ response->head.was_fetched_via_proxy = request->was_fetched_via_proxy();
+ response->head.network_accessed = response_info.network_accessed;
const content::ResourceRequestInfo* request_info =
content::ResourceRequestInfo::ForRequest(request);
if (request_info) {
@@ -116,25 +116,9 @@ void PopulateResourceResponse(
(!net::IsCertStatusError(response->head.cert_status) ||
net::IsCertStatusMinorError(response->head.cert_status)) &&
net::IsLegacySymantecCert(request->ssl_info().public_key_hashes);
- if (info->ShouldReportRawHeaders()) {
- // Only pass these members when the network panel of the DevTools is open,
- // i.e. ShouldReportRawHeaders() is set. These data are used to populate
- // the requests in the security panel too.
- response->head.ssl_connection_status =
- request->ssl_info().connection_status;
- response->head.ssl_key_exchange_group =
- request->ssl_info().key_exchange_group;
- response->head.signed_certificate_timestamps =
- request->ssl_info().signed_certificate_timestamps;
- response->head.certificate.emplace_back(
- net::x509_util::CryptoBufferAsStringPiece(
- request->ssl_info().cert->cert_buffer()));
- for (const auto& cert :
- request->ssl_info().cert->intermediate_buffers()) {
- response->head.certificate.emplace_back(
- net::x509_util::CryptoBufferAsStringPiece(cert.get()));
- }
- }
+
+ if (info->ShouldReportRawHeaders())
+ response->head.ssl_info = request->ssl_info();
} else {
// We should not have any SSL state.
DCHECK(!request->ssl_info().cert_status);
@@ -473,7 +457,8 @@ void ResourceLoader::OnCertificateRequested(
std::unique_ptr<net::ClientCertStore> client_cert_store =
GetContentClient()->browser()->CreateClientCertStore(resource_context_);
ssl_client_auth_handler_.reset(new SSLClientAuthHandler(
- std::move(client_cert_store), web_contents_getter, cert_info, this));
+ std::move(client_cert_store), std::move(web_contents_getter), cert_info,
+ this));
ssl_client_auth_handler_->SelectCertificate();
}
diff --git a/chromium/content/browser/loader/resource_loader.h b/chromium/content/browser/loader/resource_loader.h
index 78975c9e4d1..e5276077af1 100644
--- a/chromium/content/browser/loader/resource_loader.h
+++ b/chromium/content/browser/loader/resource_loader.h
@@ -27,7 +27,7 @@ class X509Certificate;
}
namespace content {
-class ResourceDispatcherHostLoginDelegate;
+class LoginDelegate;
class ResourceHandler;
class ResourceLoaderDelegate;
class ResourceRequestInfoImpl;
@@ -158,7 +158,7 @@ class CONTENT_EXPORT ResourceLoader : public net::URLRequest::Delegate,
std::unique_ptr<ResourceHandler> handler_;
ResourceLoaderDelegate* delegate_;
- scoped_refptr<ResourceDispatcherHostLoginDelegate> login_delegate_;
+ scoped_refptr<LoginDelegate> login_delegate_;
std::unique_ptr<SSLClientAuthHandler> ssl_client_auth_handler_;
base::TimeTicks read_deferral_start_time_;
diff --git a/chromium/content/browser/loader/resource_loader_delegate.h b/chromium/content/browser/loader/resource_loader_delegate.h
index 003ecd0b1ec..f2f448c531b 100644
--- a/chromium/content/browser/loader/resource_loader_delegate.h
+++ b/chromium/content/browser/loader/resource_loader_delegate.h
@@ -5,6 +5,7 @@
#ifndef CONTENT_BROWSER_LOADER_RESOURCE_LOADER_DELEGATE_H_
#define CONTENT_BROWSER_LOADER_RESOURCE_LOADER_DELEGATE_H_
+#include "base/memory/scoped_refptr.h"
#include "content/common/content_export.h"
class GURL;
@@ -18,12 +19,12 @@ struct ResourceResponse;
}
namespace content {
-class ResourceDispatcherHostLoginDelegate;
+class LoginDelegate;
class ResourceLoader;
class CONTENT_EXPORT ResourceLoaderDelegate {
public:
- virtual ResourceDispatcherHostLoginDelegate* CreateLoginDelegate(
+ virtual scoped_refptr<LoginDelegate> CreateLoginDelegate(
ResourceLoader* loader,
net::AuthChallengeInfo* auth_info) = 0;
diff --git a/chromium/content/browser/loader/resource_loader_unittest.cc b/chromium/content/browser/loader/resource_loader_unittest.cc
index 38a7b177339..0fcaeedb1aa 100644
--- a/chromium/content/browser/loader/resource_loader_unittest.cc
+++ b/chromium/content/browser/loader/resource_loader_unittest.cc
@@ -20,10 +20,10 @@
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
-#include "content/browser/browser_thread_impl.h"
#include "content/browser/loader/resource_loader_delegate.h"
#include "content/browser/loader/test_resource_handler.h"
#include "content/public/browser/client_certificate_delegate.h"
+#include "content/public/browser/login_delegate.h"
#include "content/public/browser/resource_request_info.h"
#include "content/public/common/content_paths.h"
#include "content/public/common/resource_type.h"
@@ -489,7 +489,7 @@ class ResourceLoaderTest : public testing::Test,
}
// ResourceLoaderDelegate:
- ResourceDispatcherHostLoginDelegate* CreateLoginDelegate(
+ scoped_refptr<LoginDelegate> CreateLoginDelegate(
ResourceLoader* loader,
net::AuthChallengeInfo* auth_info) override {
return nullptr;
diff --git a/chromium/content/browser/loader/resource_message_filter.cc b/chromium/content/browser/loader/resource_message_filter.cc
index 89aba72ed74..c86ba1ee886 100644
--- a/chromium/content/browser/loader/resource_message_filter.cc
+++ b/chromium/content/browser/loader/resource_message_filter.cc
@@ -14,11 +14,11 @@
#include "content/browser/loader/url_loader_factory_impl.h"
#include "content/browser/service_worker/service_worker_context_wrapper.h"
#include "content/common/resource_messages.h"
-#include "content/common/weak_wrapper_shared_url_loader_factory.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/resource_context.h"
#include "content/public/common/content_features.h"
-#include "services/network/public/cpp/cors/cors_url_loader_factory.h"
+#include "content/public/common/weak_wrapper_shared_url_loader_factory.h"
+#include "services/network/cors/cors_url_loader_factory.h"
#include "services/network/public/cpp/features.h"
#include "storage/browser/fileapi/file_system_context.h"
@@ -166,7 +166,7 @@ void ResourceMessageFilter::InitializeOnIOThread() {
url_loader_factory_ = std::make_unique<URLLoaderFactoryImpl>(requester_info_);
if (base::FeatureList::IsEnabled(network::features::kOutOfBlinkCORS)) {
- url_loader_factory_ = std::make_unique<network::CORSURLLoaderFactory>(
+ url_loader_factory_ = std::make_unique<network::cors::CORSURLLoaderFactory>(
std::move(url_loader_factory_));
}
}
diff --git a/chromium/content/browser/loader/resource_request_info_impl.cc b/chromium/content/browser/loader/resource_request_info_impl.cc
index 0f17cd2ac86..704bce310f0 100644
--- a/chromium/content/browser/loader/resource_request_info_impl.cc
+++ b/chromium/content/browser/loader/resource_request_info_impl.cc
@@ -182,7 +182,7 @@ ResourceRequestInfoImpl::ResourceRequestInfoImpl(
context_(context),
report_raw_headers_(report_raw_headers),
is_async_(is_async),
- canceled_by_devtools_(false),
+ devtools_status_(DevToolsStatus::kNotCanceled),
previews_state_(previews_state),
body_(body),
initiated_in_secure_context_(initiated_in_secure_context),
@@ -319,8 +319,9 @@ NavigationUIData* ResourceRequestInfoImpl::GetNavigationUIData() const {
return navigation_ui_data_.get();
}
-bool ResourceRequestInfoImpl::CanceledByDevTools() const {
- return canceled_by_devtools_;
+ResourceRequestInfo::DevToolsStatus ResourceRequestInfoImpl::GetDevToolsStatus()
+ const {
+ return devtools_status_;
}
base::StringPiece ResourceRequestInfoImpl::GetCustomCancelReason() const {
diff --git a/chromium/content/browser/loader/resource_request_info_impl.h b/chromium/content/browser/loader/resource_request_info_impl.h
index 5571a8cde5b..10cfae2d9b4 100644
--- a/chromium/content/browser/loader/resource_request_info_impl.h
+++ b/chromium/content/browser/loader/resource_request_info_impl.h
@@ -103,7 +103,7 @@ class ResourceRequestInfoImpl : public ResourceRequestInfo,
PreviewsState GetPreviewsState() const override;
bool ShouldReportRawHeaders() const;
NavigationUIData* GetNavigationUIData() const override;
- bool CanceledByDevTools() const override;
+ DevToolsStatus GetDevToolsStatus() const override;
base::StringPiece GetCustomCancelReason() const override;
CONTENT_EXPORT void AssociateWithRequest(net::URLRequest* request);
@@ -202,8 +202,8 @@ class ResourceRequestInfoImpl : public ResourceRequestInfo,
on_transfer_ = on_transfer;
}
- void set_canceled_by_devtools(bool canceled_by_devtools) {
- canceled_by_devtools_ = canceled_by_devtools;
+ void set_devtools_status(DevToolsStatus devtools_status) {
+ devtools_status_ = devtools_status;
}
void SetBlobHandles(BlobHandles blob_handles);
@@ -262,7 +262,7 @@ class ResourceRequestInfoImpl : public ResourceRequestInfo,
ResourceContext* context_;
bool report_raw_headers_;
bool is_async_;
- bool canceled_by_devtools_;
+ DevToolsStatus devtools_status_;
PreviewsState previews_state_;
scoped_refptr<network::ResourceRequestBody> body_;
bool initiated_in_secure_context_;
diff --git a/chromium/content/browser/loader/resource_requester_info.cc b/chromium/content/browser/loader/resource_requester_info.cc
index 874bd21a70e..9bde2f2936a 100644
--- a/chromium/content/browser/loader/resource_requester_info.cc
+++ b/chromium/content/browser/loader/resource_requester_info.cc
@@ -6,12 +6,12 @@
#include "base/feature_list.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "content/browser/appcache/chrome_appcache_service.h"
#include "content/browser/blob_storage/chrome_blob_storage_context.h"
#include "content/browser/service_worker/service_worker_context_wrapper.h"
#include "content/public/browser/resource_context.h"
#include "content/public/common/browser_side_navigation_policy.h"
+#include "content/public/common/child_process_host.h"
#include "content/public/common/content_features.h"
#include "services/network/public/cpp/features.h"
#include "storage/browser/fileapi/file_system_context.h"
@@ -86,10 +86,10 @@ scoped_refptr<ResourceRequesterInfo>
ResourceRequesterInfo::CreateForBrowserSideNavigation(
scoped_refptr<ServiceWorkerContextWrapper> service_worker_context) {
return scoped_refptr<ResourceRequesterInfo>(new ResourceRequesterInfo(
- RequesterType::BROWSER_SIDE_NAVIGATION, -1,
- nullptr /* appcache_service */, nullptr /* blob_storage_context */,
- nullptr /* file_system_context */, service_worker_context.get(),
- GetContextsCallback()));
+ RequesterType::BROWSER_SIDE_NAVIGATION,
+ ChildProcessHost::kInvalidUniqueID, nullptr /* appcache_service */,
+ nullptr /* blob_storage_context */, nullptr /* file_system_context */,
+ service_worker_context.get(), GetContextsCallback()));
}
scoped_refptr<ResourceRequesterInfo>
@@ -123,9 +123,11 @@ ResourceRequesterInfo::CreateForNavigationPreload(
}
return scoped_refptr<ResourceRequesterInfo>(new ResourceRequesterInfo(
- RequesterType::NAVIGATION_PRELOAD, -1, nullptr /* appcache_service */,
- nullptr /* blob_storage_context */, nullptr /* file_system_context */,
- original_request_info->service_worker_context(), get_contexts_callback));
+ RequesterType::NAVIGATION_PRELOAD, ChildProcessHost::kInvalidUniqueID,
+ nullptr /* appcache_service */, nullptr /* blob_storage_context */,
+ nullptr /* file_system_context */,
+ original_request_info->service_worker_context(),
+ std::move(get_contexts_callback)));
}
scoped_refptr<ResourceRequesterInfo>
@@ -134,10 +136,10 @@ ResourceRequesterInfo::CreateForCertificateFetcherForSignedExchange(
DCHECK(!base::FeatureList::IsEnabled(network::features::kNetworkService));
DCHECK(base::FeatureList::IsEnabled(features::kSignedHTTPExchange));
return scoped_refptr<ResourceRequesterInfo>(new ResourceRequesterInfo(
- RequesterType::CERTIFICATE_FETCHER_FOR_SIGNED_EXCHANGE, -1,
- nullptr /* appcache_service */, nullptr /* blob_storage_context */,
- nullptr /* file_system_context */, nullptr /* service_worker_context */,
- get_contexts_callback));
+ RequesterType::CERTIFICATE_FETCHER_FOR_SIGNED_EXCHANGE,
+ ChildProcessHost::kInvalidUniqueID, nullptr /* appcache_service */,
+ nullptr /* blob_storage_context */, nullptr /* file_system_context */,
+ nullptr /* service_worker_context */, get_contexts_callback));
}
} // namespace content
diff --git a/chromium/content/browser/loader/resource_scheduler_browsertest.cc b/chromium/content/browser/loader/resource_scheduler_browsertest.cc
index e5d07767a03..f6ea7f5a0f3 100644
--- a/chromium/content/browser/loader/resource_scheduler_browsertest.cc
+++ b/chromium/content/browser/loader/resource_scheduler_browsertest.cc
@@ -5,7 +5,6 @@
#include <map>
#include <string>
-#include "base/memory/ptr_util.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
diff --git a/chromium/content/browser/loader/source_stream_to_data_pipe.cc b/chromium/content/browser/loader/source_stream_to_data_pipe.cc
index 01f4b330118..569344921a8 100644
--- a/chromium/content/browser/loader/source_stream_to_data_pipe.cc
+++ b/chromium/content/browser/loader/source_stream_to_data_pipe.cc
@@ -17,7 +17,8 @@ SourceStreamToDataPipe::SourceStreamToDataPipe(
dest_(std::move(dest)),
completion_callback_(std::move(completion_callback)),
writable_handle_watcher_(FROM_HERE,
- mojo::SimpleWatcher::ArmingPolicy::MANUAL),
+ mojo::SimpleWatcher::ArmingPolicy::MANUAL,
+ base::SequencedTaskRunnerHandle::Get()),
weak_factory_(this) {
writable_handle_watcher_.Watch(
dest_.get(), MOJO_HANDLE_SIGNAL_WRITABLE,
diff --git a/chromium/content/browser/loader/temporary_file_stream.cc b/chromium/content/browser/loader/temporary_file_stream.cc
index f1493e705bb..07e008dce6a 100644
--- a/chromium/content/browser/loader/temporary_file_stream.cc
+++ b/chromium/content/browser/loader/temporary_file_stream.cc
@@ -63,8 +63,8 @@ void CreateTemporaryFileStream(
base::FileProxy* proxy = file_proxy.get();
proxy->CreateTemporary(
base::File::FLAG_ASYNC,
- base::Bind(&DidCreateTemporaryFile, callback, Passed(&file_proxy),
- std::move(task_runner)));
+ base::BindOnce(&DidCreateTemporaryFile, callback, std::move(file_proxy),
+ std::move(task_runner)));
}
} // namespace content
diff --git a/chromium/content/browser/loader/test_resource_handler.cc b/chromium/content/browser/loader/test_resource_handler.cc
index a2098a7f605..b4c9f869b52 100644
--- a/chromium/content/browser/loader/test_resource_handler.cc
+++ b/chromium/content/browser/loader/test_resource_handler.cc
@@ -5,7 +5,6 @@
#include "content/browser/loader/test_resource_handler.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "content/browser/loader/resource_controller.h"
#include "services/network/public/cpp/resource_response.h"
#include "testing/gtest/include/gtest/gtest.h"
diff --git a/chromium/content/browser/loader/upload_data_stream_builder.cc b/chromium/content/browser/loader/upload_data_stream_builder.cc
index 802a4ae5800..020fd504f50 100644
--- a/chromium/content/browser/loader/upload_data_stream_builder.cc
+++ b/chromium/content/browser/loader/upload_data_stream_builder.cc
@@ -12,7 +12,6 @@
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/single_thread_task_runner.h"
#include "net/base/elements_upload_data_stream.h"
@@ -110,6 +109,7 @@ std::unique_ptr<net::UploadDataStream> UploadDataStreamBuilder::Build(
}
case network::DataElement::TYPE_RAW_FILE:
case network::DataElement::TYPE_DATA_PIPE:
+ case network::DataElement::TYPE_CHUNKED_DATA_PIPE:
case network::DataElement::TYPE_UNKNOWN:
NOTREACHED();
break;
diff --git a/chromium/content/browser/loader/url_loader_factory_impl.cc b/chromium/content/browser/loader/url_loader_factory_impl.cc
index 6c3ad0d1971..9beee7ae75d 100644
--- a/chromium/content/browser/loader/url_loader_factory_impl.cc
+++ b/chromium/content/browser/loader/url_loader_factory_impl.cc
@@ -4,7 +4,6 @@
#include "content/browser/loader/url_loader_factory_impl.h"
-#include "base/memory/ptr_util.h"
#include "content/browser/loader/resource_dispatcher_host_impl.h"
#include "content/browser/loader/resource_requester_info.h"
#include "content/public/browser/browser_thread.h"
diff --git a/chromium/content/browser/loader/url_loader_factory_impl_unittest.cc b/chromium/content/browser/loader/url_loader_factory_impl_unittest.cc
index f40bbfd5777..c1e1aa06fb5 100644
--- a/chromium/content/browser/loader/url_loader_factory_impl_unittest.cc
+++ b/chromium/content/browser/loader/url_loader_factory_impl_unittest.cc
@@ -15,7 +15,6 @@
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/location.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/path_service.h"
@@ -82,9 +81,7 @@ class RejectingResourceDispatcherHostDelegate final
class URLLoaderFactoryImplTest : public ::testing::TestWithParam<size_t> {
public:
URLLoaderFactoryImplTest()
- : thread_bundle_(
- new TestBrowserThreadBundle(TestBrowserThreadBundle::IO_MAINLOOP)),
- browser_context_(new TestBrowserContext()),
+ : browser_context_(new TestBrowserContext()),
resource_message_filter_(new ResourceMessageFilter(
kChildId,
nullptr,
@@ -125,7 +122,6 @@ class URLLoaderFactoryImplTest : public ::testing::TestWithParam<size_t> {
base::RunLoop().RunUntilIdle();
MojoAsyncResourceHandler::SetAllocationSizeForTesting(
MojoAsyncResourceHandler::kDefaultAllocationSize);
- thread_bundle_.reset(nullptr);
}
void GetContexts(ResourceType resource_type,
@@ -136,7 +132,9 @@ class URLLoaderFactoryImplTest : public ::testing::TestWithParam<size_t> {
browser_context_->GetResourceContext()->GetRequestContext();
}
- std::unique_ptr<TestBrowserThreadBundle> thread_bundle_;
+ // Must outlive all members below.
+ TestBrowserThreadBundle thread_bundle_{TestBrowserThreadBundle::IO_MAINLOOP};
+
LoaderDelegateImpl loader_deleate_;
ResourceDispatcherHostImpl rdh_;
std::unique_ptr<TestBrowserContext> browser_context_;
diff --git a/chromium/content/browser/loader_delegate_impl.cc b/chromium/content/browser/loader_delegate_impl.cc
index ec35a938105..ae788cdbfac 100644
--- a/chromium/content/browser/loader_delegate_impl.cc
+++ b/chromium/content/browser/loader_delegate_impl.cc
@@ -20,13 +20,13 @@ LoaderDelegateImpl::~LoaderDelegateImpl() {}
void LoaderDelegateImpl::LoadStateChanged(
WebContents* web_contents,
- const GURL& url,
+ const std::string& host,
const net::LoadStateWithParam& load_state,
uint64_t upload_position,
uint64_t upload_size) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
- static_cast<WebContentsImpl*>(web_contents)->LoadStateChanged(
- url, load_state, upload_position, upload_size);
+ static_cast<WebContentsImpl*>(web_contents)
+ ->LoadStateChanged(host, load_state, upload_position, upload_size);
}
} // namespace content
diff --git a/chromium/content/browser/loader_delegate_impl.h b/chromium/content/browser/loader_delegate_impl.h
index 30cf93ab7b0..732de809c26 100644
--- a/chromium/content/browser/loader_delegate_impl.h
+++ b/chromium/content/browser/loader_delegate_impl.h
@@ -5,6 +5,8 @@
#ifndef CONTENT_BROWSER_LOADER_DELEGATE_IMPL_H_
#define CONTENT_BROWSER_LOADER_DELEGATE_IMPL_H_
+#include <string>
+
#include "content/browser/loader/loader_delegate.h"
#include "content/common/content_export.h"
@@ -15,12 +17,11 @@ class CONTENT_EXPORT LoaderDelegateImpl : public LoaderDelegate {
~LoaderDelegateImpl() override;
// LoaderDelegate implementation:
- void LoadStateChanged(
- WebContents* web_contents,
- const GURL& url,
- const net::LoadStateWithParam& load_state,
- uint64_t upload_position,
- uint64_t upload_size) override;
+ void LoadStateChanged(WebContents* web_contents,
+ const std::string& host,
+ const net::LoadStateWithParam& load_state,
+ uint64_t upload_position,
+ uint64_t upload_size) override;
};
} // namespace content
diff --git a/chromium/content/browser/locks/lock_manager.cc b/chromium/content/browser/locks/lock_manager.cc
index 8e0c5f1fa4c..a7768d01d7b 100644
--- a/chromium/content/browser/locks/lock_manager.cc
+++ b/chromium/content/browser/locks/lock_manager.cc
@@ -206,9 +206,6 @@ class LockManager::OriginState {
}
void ProcessRequests(LockManager* lock_manager, const url::Origin& origin) {
- if (requested_.empty())
- return;
-
shared_.clear();
exclusive_.clear();
for (const auto& id_lock_pair : held_) {
diff --git a/chromium/content/browser/locks/lock_manager.h b/chromium/content/browser/locks/lock_manager.h
index 177a810de9f..0bf240933ac 100644
--- a/chromium/content/browser/locks/lock_manager.h
+++ b/chromium/content/browser/locks/lock_manager.h
@@ -13,7 +13,7 @@
#include "base/sequence_checker.h"
#include "content/public/browser/browser_context.h"
#include "mojo/public/cpp/bindings/binding_set.h"
-#include "third_party/WebKit/public/platform/modules/locks/lock_manager.mojom.h"
+#include "third_party/blink/public/platform/modules/locks/lock_manager.mojom.h"
#include "url/origin.h"
namespace content {
diff --git a/chromium/content/browser/mach_broker_mac.h b/chromium/content/browser/mach_broker_mac.h
index 32ff5d6e548..d146728bece 100644
--- a/chromium/content/browser/mach_broker_mac.h
+++ b/chromium/content/browser/mach_broker_mac.h
@@ -15,8 +15,7 @@
#include "base/process/process_handle.h"
#include "base/synchronization/lock.h"
#include "content/public/browser/browser_child_process_observer.h"
-#include "content/public/browser/notification_observer.h"
-#include "content/public/browser/notification_registrar.h"
+#include "content/public/browser/render_process_host_observer.h"
namespace content {
@@ -24,7 +23,7 @@ namespace content {
// access to mach task ports for content child processes.
class CONTENT_EXPORT MachBroker : public base::PortProvider,
public BrowserChildProcessObserver,
- public NotificationObserver,
+ public RenderProcessHostObserver,
public base::PortProvider::Observer {
public:
// For use in child processes. This will send the task port of the current
@@ -59,10 +58,11 @@ class CONTENT_EXPORT MachBroker : public base::PortProvider,
void BrowserChildProcessCrashed(const ChildProcessData& data,
int exit_code) override;
- // Implement |NotificationObserver|.
- void Observe(int type,
- const NotificationSource& source,
- const NotificationDetails& details) override;
+ // Implement |RenderProcessHostObserver|.
+ void RenderProcessExited(RenderProcessHost* host,
+ base::TerminationStatus status,
+ int exit_code) override;
+ void RenderProcessHostDestroyed(RenderProcessHost* host) override;
// Returns the Mach port name to use when sending or receiving messages.
// Does the Right Thing in the browser and in child processes.
@@ -87,10 +87,6 @@ class CONTENT_EXPORT MachBroker : public base::PortProvider,
// Whether or not the class has been initialized.
bool initialized_;
- // Used to register for notifications received by NotificationObserver.
- // Accessed only on the UI thread.
- NotificationRegistrar registrar_;
-
// Stores the Child process unique id (RenderProcessHost ID) for every
// process. Protected by base::MachPortBroker::GetLock().
typedef std::map<int, base::ProcessHandle> ChildProcessIdMap;
diff --git a/chromium/content/browser/mach_broker_mac.mm b/chromium/content/browser/mach_broker_mac.mm
index dfbf71f600b..3cdb0b00781 100644
--- a/chromium/content/browser/mach_broker_mac.mm
+++ b/chromium/content/browser/mach_broker_mac.mm
@@ -8,11 +8,9 @@
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/logging.h"
-#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/child_process_data.h"
-#include "content/public/browser/notification_service.h"
-#include "content/public/browser/notification_types.h"
+#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_switches.h"
namespace content {
@@ -75,20 +73,14 @@ void MachBroker::BrowserChildProcessCrashed(const ChildProcessData& data,
InvalidateChildProcessId(data.id);
}
-void MachBroker::Observe(int type,
- const NotificationSource& source,
- const NotificationDetails& details) {
- switch (type) {
- case NOTIFICATION_RENDERER_PROCESS_TERMINATED:
- case NOTIFICATION_RENDERER_PROCESS_CLOSED: {
- RenderProcessHost* host = Source<RenderProcessHost>(source).ptr();
- InvalidateChildProcessId(host->GetID());
- break;
- }
- default:
- NOTREACHED() << "Unexpected notification";
- break;
- }
+void MachBroker::RenderProcessExited(RenderProcessHost* host,
+ base::TerminationStatus status,
+ int exit_code) {
+ InvalidateChildProcessId(host->GetID());
+}
+
+void MachBroker::RenderProcessHostDestroyed(RenderProcessHost* host) {
+ InvalidateChildProcessId(host->GetID());
}
// static
@@ -123,11 +115,6 @@ void MachBroker::InvalidateChildProcessId(int child_process_id) {
}
void MachBroker::RegisterNotifications() {
- registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_CLOSED,
- NotificationService::AllBrowserContextsAndSources());
- registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_TERMINATED,
- NotificationService::AllBrowserContextsAndSources());
-
// No corresponding StopObservingBrowserChildProcesses,
// we leak this singleton.
BrowserChildProcessObserver::Add(this);
diff --git a/chromium/content/browser/manifest/manifest_browsertest.cc b/chromium/content/browser/manifest/manifest_browsertest.cc
index 1d3c55af95f..d8b4b2d615e 100644
--- a/chromium/content/browser/manifest/manifest_browsertest.cc
+++ b/chromium/content/browser/manifest/manifest_browsertest.cc
@@ -22,8 +22,8 @@
#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/common/associated_interfaces/associated_interface_provider.h"
-#include "third_party/WebKit/public/platform/modules/manifest/manifest_manager.mojom.h"
+#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
+#include "third_party/blink/public/platform/modules/manifest/manifest_manager.mojom.h"
namespace content {
@@ -73,9 +73,8 @@ class ManifestBrowserTest : public ContentBrowserTest,
}
void GetManifestAndWait() {
- shell()->web_contents()->GetManifest(
- base::Bind(&ManifestBrowserTest::OnGetManifest,
- base::Unretained(this)));
+ shell()->web_contents()->GetManifest(base::BindOnce(
+ &ManifestBrowserTest::OnGetManifest, base::Unretained(this)));
message_loop_runner_ = new MessageLoopRunner();
message_loop_runner_->Run();
diff --git a/chromium/content/browser/manifest/manifest_icon_downloader.cc b/chromium/content/browser/manifest/manifest_icon_downloader.cc
index 1747af94623..903eca621bb 100644
--- a/chromium/content/browser/manifest/manifest_icon_downloader.cc
+++ b/chromium/content/browser/manifest/manifest_icon_downloader.cc
@@ -59,10 +59,10 @@ bool ManifestIconDownloader::Download(
false, // is_favicon
0, // max_bitmap_size - 0 means no maximum size.
false, // bypass_cache
- base::Bind(&ManifestIconDownloader::OnIconFetched, ideal_icon_size_in_px,
- minimum_icon_size_in_px,
- base::Owned(new DevToolsConsoleHelper(web_contents)),
- callback));
+ base::BindOnce(&ManifestIconDownloader::OnIconFetched,
+ ideal_icon_size_in_px, minimum_icon_size_in_px,
+ base::Owned(new DevToolsConsoleHelper(web_contents)),
+ callback));
return true;
}
diff --git a/chromium/content/browser/manifest/manifest_icon_selector.cc b/chromium/content/browser/manifest/manifest_icon_selector.cc
index d81cb702676..90d9bb53200 100644
--- a/chromium/content/browser/manifest/manifest_icon_selector.cc
+++ b/chromium/content/browser/manifest/manifest_icon_selector.cc
@@ -8,7 +8,7 @@
#include "base/stl_util.h"
#include "base/strings/utf_string_conversions.h"
-#include "third_party/WebKit/public/common/mime_util/mime_util.h"
+#include "third_party/blink/public/common/mime_util/mime_util.h"
namespace content {
diff --git a/chromium/content/browser/manifest/manifest_manager_host.cc b/chromium/content/browser/manifest/manifest_manager_host.cc
index 5e5067e072a..0269f2c1446 100644
--- a/chromium/content/browser/manifest/manifest_manager_host.cc
+++ b/chromium/content/browser/manifest/manifest_manager_host.cc
@@ -6,13 +6,12 @@
#include <stdint.h>
-#include "base/memory/ptr_util.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/manifest.h"
#include "services/service_manager/public/cpp/interface_provider.h"
-#include "third_party/WebKit/public/common/associated_interfaces/associated_interface_provider.h"
+#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
namespace content {
@@ -30,10 +29,10 @@ void ManifestManagerHost::RenderFrameDeleted(
OnConnectionError();
}
-void ManifestManagerHost::GetManifest(const GetManifestCallback& callback) {
+void ManifestManagerHost::GetManifest(GetManifestCallback callback) {
auto& manifest_manager = GetManifestManager();
- int request_id =
- callbacks_.Add(std::make_unique<GetManifestCallback>(callback));
+ int request_id = callbacks_.Add(
+ std::make_unique<GetManifestCallback>(std::move(callback)));
manifest_manager.RequestManifest(
base::BindOnce(&ManifestManagerHost::OnRequestManifestResponse,
base::Unretained(this), request_id));
@@ -67,7 +66,7 @@ void ManifestManagerHost::OnConnectionError() {
}
callbacks_.Clear();
for (auto& callback : callbacks)
- callback.Run(GURL(), Manifest());
+ std::move(callback).Run(GURL(), Manifest());
}
void ManifestManagerHost::OnRequestManifestResponse(int request_id,
@@ -75,7 +74,7 @@ void ManifestManagerHost::OnRequestManifestResponse(int request_id,
const Manifest& manifest) {
auto callback = std::move(*callbacks_.Lookup(request_id));
callbacks_.Remove(request_id);
- callback.Run(url, manifest);
+ std::move(callback).Run(url, manifest);
}
void ManifestManagerHost::ManifestUrlChanged(
diff --git a/chromium/content/browser/manifest/manifest_manager_host.h b/chromium/content/browser/manifest/manifest_manager_host.h
index 0898480757b..40c5c86e002 100644
--- a/chromium/content/browser/manifest/manifest_manager_host.h
+++ b/chromium/content/browser/manifest/manifest_manager_host.h
@@ -11,7 +11,7 @@
#include "content/common/manifest_observer.mojom.h"
#include "content/public/browser/web_contents_binding_set.h"
#include "content/public/browser/web_contents_observer.h"
-#include "third_party/WebKit/public/platform/modules/manifest/manifest_manager.mojom.h"
+#include "third_party/blink/public/platform/modules/manifest/manifest_manager.mojom.h"
namespace content {
@@ -30,12 +30,12 @@ class ManifestManagerHost : public WebContentsObserver,
~ManifestManagerHost() override;
using GetManifestCallback =
- base::Callback<void(const GURL&, const Manifest&)>;
+ base::OnceCallback<void(const GURL&, const Manifest&)>;
// Calls the given callback with the manifest associated with the main frame.
// If the main frame has no manifest or if getting it failed the callback will
// have an empty manifest.
- void GetManifest(const GetManifestCallback& callback);
+ void GetManifest(GetManifestCallback callback);
void RequestManifestDebugInfo(
blink::mojom::ManifestManager::RequestManifestDebugInfoCallback callback);
diff --git a/chromium/content/browser/media/android/browser_media_player_manager.cc b/chromium/content/browser/media/android/browser_media_player_manager.cc
index 1a5ae4769eb..d916fcbcaad 100644
--- a/chromium/content/browser/media/android/browser_media_player_manager.cc
+++ b/chromium/content/browser/media/android/browser_media_player_manager.cc
@@ -7,7 +7,6 @@
#include <utility>
#include "base/android/scoped_java_ref.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/singleton.h"
#include "content/browser/frame_host/render_frame_host_impl.h"
#include "content/browser/media/android/media_resource_getter_impl.h"
@@ -81,12 +80,6 @@ BrowserMediaPlayerManager* BrowserMediaPlayerManager::Create(
: nullptr;
}
-#if !defined(USE_AURA)
-ContentViewCore* BrowserMediaPlayerManager::GetContentViewCore() const {
- return ContentViewCore::FromWebContents(web_contents());
-}
-#endif
-
std::unique_ptr<MediaPlayerAndroid>
BrowserMediaPlayerManager::CreateMediaPlayer(
const MediaPlayerHostMsg_Initialize_Params& media_player_params,
@@ -342,10 +335,7 @@ void BrowserMediaPlayerManager::OnEnterFullscreen(int player_id) {
base::android::ScopedJavaLocalRef<jobject> embedder(
web_contents()->GetDelegate()->GetContentVideoViewEmbedder());
video_view_.reset(
- new ContentVideoView(this,
- GetContentViewCore(),
- embedder,
- natural_video_size));
+ new ContentVideoView(this, web_contents(), embedder, natural_video_size));
base::android::ScopedJavaLocalRef<jobject> j_content_video_view =
video_view_->GetJavaObject(base::android::AttachCurrentThread());
diff --git a/chromium/content/browser/media/android/browser_surface_view_manager.cc b/chromium/content/browser/media/android/browser_surface_view_manager.cc
index 2569903f921..54a75fe8150 100644
--- a/chromium/content/browser/media/android/browser_surface_view_manager.cc
+++ b/chromium/content/browser/media/android/browser_surface_view_manager.cc
@@ -6,10 +6,10 @@
#include "base/android/build_info.h"
#include "base/trace_event/trace_event.h"
-#include "content/browser/android/content_view_core.h"
#include "content/browser/gpu/gpu_process_host.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/common/media/surface_view_manager_messages_android.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents_delegate.h"
#include "gpu/ipc/common/gpu_surface_tracker.h"
@@ -96,11 +96,10 @@ void BrowserSurfaceViewManager::OnCreateFullscreenSurface(
SendSurfaceID(media::SurfaceManager::kNoSurfaceID);
return;
}
- ContentViewCore* cvc = ContentViewCore::FromWebContents(web_contents);
- content_video_view_.reset(
- new ContentVideoView(this, cvc,
- web_contents->GetDelegate()->GetContentVideoViewEmbedder(),
- video_natural_size));
+ content_video_view_.reset(new ContentVideoView(
+ this, web_contents,
+ web_contents->GetDelegate()->GetContentVideoViewEmbedder(),
+ video_natural_size));
}
void BrowserSurfaceViewManager::OnNaturalSizeChanged(const gfx::Size& size) {
diff --git a/chromium/content/browser/media/android/media_resource_getter_impl.cc b/chromium/content/browser/media/android/media_resource_getter_impl.cc
index e9b8a423240..73d5d89a975 100644
--- a/chromium/content/browser/media/android/media_resource_getter_impl.cc
+++ b/chromium/content/browser/media/android/media_resource_getter_impl.cc
@@ -4,9 +4,6 @@
#include "content/browser/media/android/media_resource_getter_impl.h"
-#include "base/android/jni_android.h"
-#include "base/android/jni_string.h"
-#include "base/android/scoped_java_ref.h"
#include "base/bind.h"
#include "base/macros.h"
#include "base/path_service.h"
@@ -20,7 +17,6 @@
#include "content/public/browser/storage_partition.h"
#include "content/public/common/content_client.h"
#include "content/public/common/url_constants.h"
-#include "jni/MediaResourceGetter_jni.h"
#include "media/base/android/media_url_interceptor.h"
#include "net/base/auth.h"
#include "net/cookies/canonical_cookie.h"
@@ -31,26 +27,63 @@
#include "net/url_request/url_request_context_getter.h"
#include "url/gurl.h"
-using base::android::ConvertUTF8ToJavaString;
-using base::android::JavaRef;
-using base::android::ScopedJavaLocalRef;
-
namespace content {
-static void ReturnStringResultOnUIThread(
+namespace {
+
+// Returns the cookie service for the |browser_context| at the client end of the
+// mojo pipe.
+network::mojom::CookieManager* GetCookieServiceForContext(
+ BrowserContext* browser_context) {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ return BrowserContext::GetDefaultStoragePartition(browser_context)
+ ->GetCookieManagerForBrowserProcess();
+}
+
+void ReturnResultOnUIThread(
base::OnceCallback<void(const std::string&)> callback,
const std::string& result) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
base::BindOnce(std::move(callback), result));
}
-static void ReturnCookieListResultOnUIThread(
- net::CookieStore::GetCookieListCallback callback,
- const net::CookieList& result) {
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
- base::BindOnce(std::move(callback), result));
+// Checks the policy for get cookies and returns the cookie line if allowed.
+std::string GetCookiesOnIO(const GURL& url,
+ const GURL& site_for_cookies,
+ content::ResourceContext* resource_context,
+ int render_process_id,
+ int render_frame_id,
+ const net::CookieList& cookie_list) {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+
+ if (!GetContentClient()->browser()->AllowGetCookie(
+ url, site_for_cookies, cookie_list, resource_context,
+ render_process_id, render_frame_id)) {
+ return std::string();
+ }
+
+ return net::CanonicalCookie::BuildCookieLine(cookie_list);
+}
+
+void CheckPolicyForCookies(const GURL& url,
+ const GURL& site_for_cookies,
+ content::ResourceContext* resource_context,
+ int render_process_id,
+ int render_frame_id,
+ MediaResourceGetterImpl::GetCookieCB callback,
+ const net::CookieList& cookie_list) {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+
+ // AllowGetCookie has to be called on IO thread.
+ BrowserThread::PostTaskAndReplyWithResult(
+ BrowserThread::IO, FROM_HERE,
+ base::BindOnce(&GetCookiesOnIO, url, site_for_cookies, resource_context,
+ render_process_id, render_frame_id, cookie_list),
+ std::move(callback));
}
+} // namespace
+
static void RequestPlaformPathFromFileSystemURL(
const GURL& url,
int render_process_id,
@@ -66,60 +99,9 @@ static void RequestPlaformPathFromFileSystemURL(
base::FilePath data_storage_path;
PathService::Get(base::DIR_ANDROID_APP_DATA, &data_storage_path);
if (data_storage_path.IsParent(platform_path))
- ReturnStringResultOnUIThread(std::move(callback), platform_path.value());
+ ReturnResultOnUIThread(std::move(callback), platform_path.value());
else
- ReturnStringResultOnUIThread(std::move(callback), std::string());
-}
-
-// Posts a task to the UI thread to run the callback function.
-static void PostMediaMetadataCallbackTask(
- media::MediaResourceGetter::ExtractMediaMetadataCB callback,
- JNIEnv* env,
- ScopedJavaLocalRef<jobject>& j_metadata) {
- BrowserThread::PostTask(
- BrowserThread::UI, FROM_HERE,
- base::BindOnce(
- std::move(callback),
- base::TimeDelta::FromMilliseconds(
- Java_MediaMetadata_getDurationInMilliseconds(env, j_metadata)),
- Java_MediaMetadata_getWidth(env, j_metadata),
- Java_MediaMetadata_getHeight(env, j_metadata),
- Java_MediaMetadata_isSuccess(env, j_metadata)));
-}
-
-// Gets the metadata from a media URL. When finished, a task is posted to the UI
-// thread to run the callback function.
-static void GetMediaMetadata(
- const std::string& url,
- const std::string& cookies,
- const std::string& user_agent,
- media::MediaResourceGetter::ExtractMediaMetadataCB callback) {
- JNIEnv* env = base::android::AttachCurrentThread();
-
- ScopedJavaLocalRef<jstring> j_url_string = ConvertUTF8ToJavaString(env, url);
- ScopedJavaLocalRef<jstring> j_cookies = ConvertUTF8ToJavaString(env, cookies);
- ScopedJavaLocalRef<jstring> j_user_agent = ConvertUTF8ToJavaString(
- env, user_agent);
- ScopedJavaLocalRef<jobject> j_metadata =
- Java_MediaResourceGetter_extractMediaMetadata(env, j_url_string,
- j_cookies, j_user_agent);
- PostMediaMetadataCallbackTask(std::move(callback), env, j_metadata);
-}
-
-// Gets the metadata from a file descriptor. When finished, a task is posted to
-// the UI thread to run the callback function.
-static void GetMediaMetadataFromFd(
- const int fd,
- const int64_t offset,
- const int64_t size,
- media::MediaResourceGetter::ExtractMediaMetadataCB callback) {
- JNIEnv* env = base::android::AttachCurrentThread();
-
- ScopedJavaLocalRef<jobject> j_metadata =
- Java_MediaResourceGetter_extractMediaMetadataFromFd(
- env, fd, offset, size);
-
- PostMediaMetadataCallbackTask(std::move(callback), env, j_metadata);
+ ReturnResultOnUIThread(std::move(callback), std::string());
}
// The task object that retrieves media resources on the IO thread.
@@ -129,17 +111,11 @@ static void GetMediaMetadataFromFd(
class MediaResourceGetterTask
: public base::RefCountedThreadSafe<MediaResourceGetterTask> {
public:
- MediaResourceGetterTask(BrowserContext* browser_context,
- int render_process_id, int render_frame_id);
+ MediaResourceGetterTask(BrowserContext* browser_context);
// Called by MediaResourceGetterImpl to start getting auth credentials.
net::AuthCredentials RequestAuthCredentials(const GURL& url) const;
- // Called by MediaResourceGetterImpl to start getting cookies for a URL.
- void RequestCookies(const GURL& url,
- const GURL& site_for_cookies,
- net::CookieStore::GetCookieListCallback callback);
-
// Returns the task runner that all methods should be called.
scoped_refptr<base::SingleThreadTaskRunner> GetTaskRunner() const;
@@ -147,34 +123,17 @@ class MediaResourceGetterTask
friend class base::RefCountedThreadSafe<MediaResourceGetterTask>;
virtual ~MediaResourceGetterTask();
- void CheckPolicyForCookies(const GURL& url,
- const GURL& site_for_cookies,
- net::CookieStore::GetCookieListCallback callback,
- const net::CookieList& cookie_list);
-
// Context getter used to get the CookieStore and auth cache.
net::URLRequestContextGetter* context_getter_;
- // Resource context for checking cookie policies.
- ResourceContext* resource_context_;
-
- // Render process id, used to check whether the process can access cookies.
- int render_process_id_;
-
- // Render frame id, used to check tab specific cookie policy.
- int render_frame_id_;
-
DISALLOW_COPY_AND_ASSIGN(MediaResourceGetterTask);
};
MediaResourceGetterTask::MediaResourceGetterTask(
- BrowserContext* browser_context, int render_process_id, int render_frame_id)
- : context_getter_(BrowserContext::GetDefaultStoragePartition(
- browser_context)->GetURLRequestContext()),
- resource_context_(browser_context->GetResourceContext()),
- render_process_id_(render_process_id),
- render_frame_id_(render_frame_id) {
-}
+ BrowserContext* browser_context)
+ : context_getter_(
+ BrowserContext::GetDefaultStoragePartition(browser_context)
+ ->GetURLRequestContext()) {}
MediaResourceGetterTask::~MediaResourceGetterTask() {}
@@ -201,49 +160,11 @@ net::AuthCredentials MediaResourceGetterTask::RequestAuthCredentials(
return net::AuthCredentials();
}
-void MediaResourceGetterTask::RequestCookies(
- const GURL& url,
- const GURL& site_for_cookies,
- net::CookieStore::GetCookieListCallback callback) {
- DCHECK(GetTaskRunner()->BelongsToCurrentThread());
- ChildProcessSecurityPolicyImpl* policy =
- ChildProcessSecurityPolicyImpl::GetInstance();
- if (!policy->CanAccessDataForOrigin(render_process_id_, url)) {
- std::move(callback).Run(net::CookieList());
- return;
- }
-
- net::CookieStore* cookie_store =
- context_getter_->GetURLRequestContext()->cookie_store();
- if (!cookie_store) {
- std::move(callback).Run(net::CookieList());
- return;
- }
-
- cookie_store->GetAllCookiesForURLAsync(
- url, base::BindOnce(&MediaResourceGetterTask::CheckPolicyForCookies, this,
- url, site_for_cookies, std::move(callback)));
-}
-
scoped_refptr<base::SingleThreadTaskRunner>
MediaResourceGetterTask::GetTaskRunner() const {
return context_getter_->GetNetworkTaskRunner();
}
-void MediaResourceGetterTask::CheckPolicyForCookies(
- const GURL& url,
- const GURL& site_for_cookies,
- net::CookieStore::GetCookieListCallback callback,
- const net::CookieList& cookie_list) {
- if (GetContentClient()->browser()->AllowGetCookie(
- url, site_for_cookies, cookie_list, resource_context_,
- render_process_id_, render_frame_id_)) {
- std::move(callback).Run(cookie_list);
- } else {
- std::move(callback).Run(net::CookieList());
- }
-}
-
MediaResourceGetterImpl::MediaResourceGetterImpl(
BrowserContext* browser_context,
storage::FileSystemContext* file_system_context,
@@ -262,8 +183,7 @@ void MediaResourceGetterImpl::GetAuthCredentials(
const GURL& url,
GetAuthCredentialsCB callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
- scoped_refptr<MediaResourceGetterTask> task = new MediaResourceGetterTask(
- browser_context_, 0, 0);
+ auto task = base::MakeRefCounted<MediaResourceGetterTask>(browser_context_);
PostTaskAndReplyWithResult(
task->GetTaskRunner().get(), FROM_HERE,
@@ -277,17 +197,28 @@ void MediaResourceGetterImpl::GetCookies(const GURL& url,
const GURL& site_for_cookies,
GetCookieCB callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
- scoped_refptr<MediaResourceGetterTask> task = new MediaResourceGetterTask(
- browser_context_, render_process_id_, render_frame_id_);
- net::CookieStore::GetCookieListCallback cb =
- base::BindOnce(&MediaResourceGetterImpl::GetCookiesCallback,
- weak_factory_.GetWeakPtr(), std::move(callback));
- task->GetTaskRunner()->PostTask(
- FROM_HERE,
- base::BindOnce(
- &MediaResourceGetterTask::RequestCookies, task, url, site_for_cookies,
- base::BindOnce(&ReturnCookieListResultOnUIThread, std::move(cb))));
+ ChildProcessSecurityPolicyImpl* policy =
+ ChildProcessSecurityPolicyImpl::GetInstance();
+ if (!policy->CanAccessDataForOrigin(render_process_id_, url)) {
+ // Running the callback asynchronously on the caller thread to avoid
+ // reentrancy issues.
+ ReturnResultOnUIThread(std::move(callback), std::string());
+ return;
+ }
+
+ net::CookieOptions options;
+ options.set_include_httponly();
+ options.set_same_site_cookie_mode(
+ net::CookieOptions::SameSiteCookieMode::INCLUDE_STRICT_AND_LAX);
+ options.set_do_not_update_access_time();
+ GetCookieServiceForContext(browser_context_)
+ ->GetCookieList(
+ url, options,
+ base::BindOnce(&CheckPolicyForCookies, url, site_for_cookies,
+ browser_context_->GetResourceContext(),
+ render_process_id_, render_frame_id_,
+ std::move(callback)));
}
void MediaResourceGetterImpl::GetAuthCredentialsCallback(
@@ -297,14 +228,6 @@ void MediaResourceGetterImpl::GetAuthCredentialsCallback(
std::move(callback).Run(credentials.username(), credentials.password());
}
-void MediaResourceGetterImpl::GetCookiesCallback(
- GetCookieCB callback,
- const net::CookieList& cookie_list) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- std::string cookie_line = net::CanonicalCookie::BuildCookieLine(cookie_list);
- std::move(callback).Run(std::move(cookie_line));
-}
-
void MediaResourceGetterImpl::GetPlatformPathFromURL(
const GURL& url,
GetPlatformPathCB callback) {
@@ -328,28 +251,4 @@ void MediaResourceGetterImpl::GetPlatformPathCallback(
std::move(callback).Run(platform_path);
}
-void MediaResourceGetterImpl::ExtractMediaMetadata(
- const std::string& url,
- const std::string& cookies,
- const std::string& user_agent,
- ExtractMediaMetadataCB callback) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- base::PostTaskWithTraits(FROM_HERE,
- {base::MayBlock(), base::TaskPriority::USER_VISIBLE},
- base::BindOnce(&GetMediaMetadata, url, cookies,
- user_agent, std::move(callback)));
-}
-
-void MediaResourceGetterImpl::ExtractMediaMetadata(
- const int fd,
- const int64_t offset,
- const int64_t size,
- ExtractMediaMetadataCB callback) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- base::PostTaskWithTraits(FROM_HERE,
- {base::MayBlock(), base::TaskPriority::USER_VISIBLE},
- base::BindOnce(&GetMediaMetadataFromFd, fd, offset,
- size, std::move(callback)));
-}
-
} // namespace content
diff --git a/chromium/content/browser/media/android/media_resource_getter_impl.h b/chromium/content/browser/media/android/media_resource_getter_impl.h
index c2258c03ffd..1b1b0654bfb 100644
--- a/chromium/content/browser/media/android/media_resource_getter_impl.h
+++ b/chromium/content/browser/media/android/media_resource_getter_impl.h
@@ -49,24 +49,12 @@ class MediaResourceGetterImpl : public media::MediaResourceGetter {
GetCookieCB callback) override;
void GetPlatformPathFromURL(const GURL& url,
GetPlatformPathCB callback) override;
- void ExtractMediaMetadata(const std::string& url,
- const std::string& cookies,
- const std::string& user_agent,
- ExtractMediaMetadataCB callback) override;
- void ExtractMediaMetadata(const int fd,
- const int64_t offset,
- const int64_t size,
- ExtractMediaMetadataCB callback) override;
private:
// Called when GetAuthCredentials() finishes.
void GetAuthCredentialsCallback(GetAuthCredentialsCB callback,
const net::AuthCredentials& credentials);
- // Called when GetCookies() finishes.
- void GetCookiesCallback(GetCookieCB callback,
- const net::CookieList& cookie_list);
-
// Called when GetPlatformPathFromFileSystemURL() finishes.
void GetPlatformPathCallback(GetPlatformPathCB callback,
const std::string& platform_path);
diff --git a/chromium/content/browser/media/audible_metrics.cc b/chromium/content/browser/media/audible_metrics.cc
index b02977ca954..8244c11ad92 100644
--- a/chromium/content/browser/media/audible_metrics.cc
+++ b/chromium/content/browser/media/audible_metrics.cc
@@ -31,7 +31,7 @@ void AudibleMetrics::UpdateAudibleWebContentsState(
RemoveAudibleWebContents(web_contents);
}
-void AudibleMetrics::SetClockForTest(base::TickClock* test_clock) {
+void AudibleMetrics::SetClockForTest(const base::TickClock* test_clock) {
clock_ = test_clock;
}
diff --git a/chromium/content/browser/media/audible_metrics.h b/chromium/content/browser/media/audible_metrics.h
index 3c90da942d4..02d98671223 100644
--- a/chromium/content/browser/media/audible_metrics.h
+++ b/chromium/content/browser/media/audible_metrics.h
@@ -29,7 +29,7 @@ class CONTENT_EXPORT AudibleMetrics {
void UpdateAudibleWebContentsState(const WebContents* web_contents,
bool audible);
- void SetClockForTest(base::TickClock* test_clock);
+ void SetClockForTest(const base::TickClock* test_clock);
private:
void AddAudibleWebContents(const WebContents* web_contents);
@@ -37,7 +37,7 @@ class CONTENT_EXPORT AudibleMetrics {
base::TimeTicks concurrent_web_contents_start_time_;
size_t max_concurrent_audible_web_contents_in_session_;
- base::TickClock* clock_;
+ const base::TickClock* clock_;
std::set<const WebContents*> audible_web_contents_;
diff --git a/chromium/content/browser/media/audio_stream_monitor.h b/chromium/content/browser/media/audio_stream_monitor.h
index febec7c5a56..84a1a706e51 100644
--- a/chromium/content/browser/media/audio_stream_monitor.h
+++ b/chromium/content/browser/media/audio_stream_monitor.h
@@ -126,7 +126,7 @@ class CONTENT_EXPORT AudioStreamMonitor : public WebContentsObserver {
// Note: |clock_| is always a DefaultTickClock, except during unit
// testing.
- base::TickClock* const clock_;
+ const base::TickClock* const clock_;
// Confirms single-threaded access in debug builds.
base::ThreadChecker thread_checker_;
diff --git a/chromium/content/browser/media/audio_stream_monitor_unittest.cc b/chromium/content/browser/media/audio_stream_monitor_unittest.cc
index 4b9dc715be9..ffdea7dd6d8 100644
--- a/chromium/content/browser/media/audio_stream_monitor_unittest.cc
+++ b/chromium/content/browser/media/audio_stream_monitor_unittest.cc
@@ -58,7 +58,7 @@ class AudioStreamMonitorTest : public RenderViewHostTestHarness {
web_contents->SetDelegate(&mock_web_contents_delegate_);
monitor_ = web_contents->audio_stream_monitor();
- const_cast<base::TickClock*&>(monitor_->clock_) = &clock_;
+ const_cast<const base::TickClock*&>(monitor_->clock_) = &clock_;
}
base::TimeTicks GetTestClockTime() { return clock_.NowTicks(); }
diff --git a/chromium/content/browser/media/capture/audio_mirroring_manager.cc b/chromium/content/browser/media/capture/audio_mirroring_manager.cc
index 35793ad3965..1daaf6bf4d3 100644
--- a/chromium/content/browser/media/capture/audio_mirroring_manager.cc
+++ b/chromium/content/browser/media/capture/audio_mirroring_manager.cc
@@ -4,6 +4,7 @@
#include "content/browser/media/capture/audio_mirroring_manager.h"
+#include <stdint.h>
#include <algorithm>
#include "base/bind.h"
@@ -17,19 +18,16 @@ AudioMirroringManager* AudioMirroringManager::GetInstance() {
return manager;
}
-AudioMirroringManager::AudioMirroringManager() {
- // Only *after* construction, check that AudioMirroringManager is being
- // invoked on the same single thread.
- thread_checker_.DetachFromThread();
-}
+AudioMirroringManager::AudioMirroringManager() {}
AudioMirroringManager::~AudioMirroringManager() {}
void AudioMirroringManager::AddDiverter(
int render_process_id, int render_frame_id, Diverter* diverter) {
- DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(diverter);
+ base::AutoLock scoped_lock(lock_);
+
// DCHECK(diverter not already in routes_)
#ifndef NDEBUG
for (StreamRoutes::const_iterator it = routes_.begin();
@@ -49,7 +47,7 @@ void AudioMirroringManager::AddDiverter(
}
void AudioMirroringManager::RemoveDiverter(Diverter* diverter) {
- DCHECK(thread_checker_.CalledOnValidThread());
+ base::AutoLock scoped_lock(lock_);
// Find and remove the entry from the routing table. If the stream is being
// diverted, it is stopped.
@@ -70,9 +68,10 @@ void AudioMirroringManager::RemoveDiverter(Diverter* diverter) {
}
void AudioMirroringManager::StartMirroring(MirroringDestination* destination) {
- DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(destination);
+ base::AutoLock scoped_lock(lock_);
+
// Insert an entry into the set of active mirroring sessions, if this is a
// previously-unknown destination.
if (std::find(sessions_.begin(), sessions_.end(), destination) ==
@@ -99,7 +98,7 @@ void AudioMirroringManager::StartMirroring(MirroringDestination* destination) {
}
void AudioMirroringManager::StopMirroring(MirroringDestination* destination) {
- DCHECK(thread_checker_.CalledOnValidThread());
+ base::AutoLock scoped_lock(lock_);
// Stop diverting each audio stream in the mirroring session being stopped.
// Each stopped stream becomes a candidate to be diverted to another
@@ -129,10 +128,38 @@ void AudioMirroringManager::StopMirroring(MirroringDestination* destination) {
sessions_.erase(dest_it);
}
+AudioMirroringManager::AddDiverterCallback
+AudioMirroringManager::GetAddDiverterCallback() {
+ return base::BindRepeating(
+ [](AudioMirroringManager* self,
+ const base::UnguessableToken& guessable_token, Diverter* diverter) {
+ const int render_process_id =
+ static_cast<int>(guessable_token.GetHighForSerialization());
+ const int render_frame_id =
+ static_cast<int>(guessable_token.GetLowForSerialization());
+ self->AddDiverter(render_process_id, render_frame_id, diverter);
+ },
+ base::Unretained(this));
+}
+
+AudioMirroringManager::RemoveDiverterCallback
+AudioMirroringManager::GetRemoveDiverterCallback() {
+ return base::BindRepeating(&AudioMirroringManager::RemoveDiverter,
+ base::Unretained(this));
+}
+
+// static
+base::UnguessableToken AudioMirroringManager::ToGroupId(int render_process_id,
+ int render_frame_id) {
+ return base::UnguessableToken::Deserialize(
+ static_cast<uint64_t>(render_process_id),
+ static_cast<uint64_t>(render_frame_id));
+}
+
void AudioMirroringManager::InitiateQueriesToFindNewDestination(
MirroringDestination* old_destination,
const std::set<SourceFrameRef>& candidates) {
- DCHECK(thread_checker_.CalledOnValidThread());
+ lock_.AssertAcquired();
for (Destinations::const_iterator it = sessions_.begin();
it != sessions_.end(); ++it) {
@@ -151,6 +178,8 @@ void AudioMirroringManager::UpdateRoutesToDestination(
bool add_only,
const std::set<SourceFrameRef>& matches,
bool is_duplicate) {
+ base::AutoLock scoped_lock(lock_);
+
if (is_duplicate)
UpdateRoutesToDuplicateDestination(destination, add_only, matches);
else
@@ -161,7 +190,7 @@ void AudioMirroringManager::UpdateRoutesToDivertDestination(
MirroringDestination* destination,
bool add_only,
const std::set<SourceFrameRef>& matches) {
- DCHECK(thread_checker_.CalledOnValidThread());
+ lock_.AssertAcquired();
if (std::find(sessions_.begin(), sessions_.end(), destination) ==
sessions_.end()) {
@@ -195,7 +224,8 @@ void AudioMirroringManager::UpdateRoutesToDuplicateDestination(
MirroringDestination* destination,
bool add_only,
const std::set<SourceFrameRef>& matches) {
- DCHECK(thread_checker_.CalledOnValidThread());
+ lock_.AssertAcquired();
+
if (std::find(sessions_.begin(), sessions_.end(), destination) ==
sessions_.end()) {
return; // Query result callback invoked after StopMirroring().
diff --git a/chromium/content/browser/media/capture/audio_mirroring_manager.h b/chromium/content/browser/media/capture/audio_mirroring_manager.h
index b98cf018c59..67ee6fbdc3c 100644
--- a/chromium/content/browser/media/capture/audio_mirroring_manager.h
+++ b/chromium/content/browser/media/capture/audio_mirroring_manager.h
@@ -4,8 +4,7 @@
//
// AudioMirroringManager is a singleton object that maintains a set of active
// audio mirroring destinations and auto-connects/disconnects audio streams
-// to/from those destinations. It is meant to be used exclusively on the IO
-// thread.
+// to/from those destinations.
//
// How it works:
//
@@ -39,7 +38,8 @@
#include "base/callback_forward.h"
#include "base/macros.h"
-#include "base/threading/thread_checker.h"
+#include "base/synchronization/lock.h"
+#include "base/unguessable_token.h"
#include "content/common/content_export.h"
#include "media/audio/audio_source_diverter.h"
@@ -119,6 +119,20 @@ class CONTENT_EXPORT AudioMirroringManager {
virtual void StartMirroring(MirroringDestination* destination);
virtual void StopMirroring(MirroringDestination* destination);
+ // TODO(crbug/824019): The following are temporary, as a middle-ground step
+ // necessary to resolve a chicken-and-egg problem as we migrate audio
+ // mirroring into the new AudioService. See media::AudioManager::AddDiverter()
+ // comments for further details.
+ using AddDiverterCallback =
+ base::RepeatingCallback<void(const base::UnguessableToken&,
+ media::AudioSourceDiverter*)>;
+ AddDiverterCallback GetAddDiverterCallback();
+ using RemoveDiverterCallback =
+ base::RepeatingCallback<void(media::AudioSourceDiverter*)>;
+ RemoveDiverterCallback GetRemoveDiverterCallback();
+ static base::UnguessableToken ToGroupId(int render_process_id,
+ int render_frame_id);
+
private:
friend class AudioMirroringManagerTest;
@@ -190,8 +204,9 @@ class CONTENT_EXPORT AudioMirroringManager {
// All active mirroring sessions.
Destinations sessions_;
- // Used to check that all AudioMirroringManager code runs on the same thread.
- base::ThreadChecker thread_checker_;
+ // Allows calls to Add/RemoveDiverter() and Start/StopMirroring() to be made
+ // from different threads.
+ base::Lock lock_;
DISALLOW_COPY_AND_ASSIGN(AudioMirroringManager);
};
diff --git a/chromium/content/browser/media/capture/audio_mirroring_manager_unittest.cc b/chromium/content/browser/media/capture/audio_mirroring_manager_unittest.cc
index 94e796fd49d..2d6efe047d8 100644
--- a/chromium/content/browser/media/capture/audio_mirroring_manager_unittest.cc
+++ b/chromium/content/browser/media/capture/audio_mirroring_manager_unittest.cc
@@ -11,7 +11,9 @@
#include "base/bind_helpers.h"
#include "base/macros.h"
#include "base/synchronization/waitable_event.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/test/test_browser_thread_bundle.h"
+#include "content/public/test/test_utils.h"
#include "media/base/audio_parameters.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -70,7 +72,9 @@ class MockMirroringDestination
candidates.end()) {
result.insert(SourceFrameRef(render_process_id_, render_frame_id_));
}
- results_callback.Run(result, is_duplication_);
+ BrowserThread::PostTask(
+ BrowserThread::IO, FROM_HERE,
+ base::BindOnce(results_callback, std::move(result), is_duplication_));
}
media::AudioOutputStream* SimulateAddInput(
@@ -141,6 +145,7 @@ class AudioMirroringManagerTest : public testing::Test {
mirroring_manager_.AddDiverter(
render_process_id, render_frame_id, diverter);
+ RunAllPendingInMessageLoop();
return diverter;
}
@@ -173,10 +178,12 @@ class AudioMirroringManagerTest : public testing::Test {
}
mirroring_manager_.StartMirroring(dest.get());
+ RunAllPendingInMessageLoop();
}
void StopMirroringTo(const std::unique_ptr<MockMirroringDestination>& dest) {
mirroring_manager_.StopMirroring(dest.get());
+ RunAllPendingInMessageLoop();
}
int CountStreamsDivertedTo(
diff --git a/chromium/content/browser/media/capture/aura_window_capture_machine.cc b/chromium/content/browser/media/capture/aura_window_capture_machine.cc
index 3797696f4ba..2f6caae4995 100644
--- a/chromium/content/browser/media/capture/aura_window_capture_machine.cc
+++ b/chromium/content/browser/media/capture/aura_window_capture_machine.cc
@@ -367,7 +367,7 @@ bool AuraWindowCaptureMachine::ProcessCopyOutputResponse(
base::Bind(&CopyOutputFinishedForVideo, weak_factory_.GetWeakPtr(),
event_time, capture_frame_cb, video_frame, region_in_frame,
base::Passed(&release_callback)));
- media::LetterboxYUV(video_frame.get(), region_in_frame);
+ media::LetterboxVideoFrame(video_frame.get(), region_in_frame);
return true;
}
diff --git a/chromium/content/browser/media/capture/cursor_renderer.cc b/chromium/content/browser/media/capture/cursor_renderer.cc
index e2126dce672..66352cc8a80 100644
--- a/chromium/content/browser/media/capture/cursor_renderer.cc
+++ b/chromium/content/browser/media/capture/cursor_renderer.cc
@@ -10,7 +10,6 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/numerics/safe_conversions.h"
#include "skia/ext/image_operations.h"
#include "ui/gfx/geometry/rect.h"
diff --git a/chromium/content/browser/media/capture/cursor_renderer_aura.cc b/chromium/content/browser/media/capture/cursor_renderer_aura.cc
index 63741500879..d390783b242 100644
--- a/chromium/content/browser/media/capture/cursor_renderer_aura.cc
+++ b/chromium/content/browser/media/capture/cursor_renderer_aura.cc
@@ -4,7 +4,6 @@
#include "content/browser/media/capture/cursor_renderer_aura.h"
-#include "base/memory/ptr_util.h"
#include "ui/aura/client/screen_position_client.h"
#include "ui/aura/env.h"
#include "ui/aura/window.h"
diff --git a/chromium/content/browser/media/capture/cursor_renderer_mac.mm b/chromium/content/browser/media/capture/cursor_renderer_mac.mm
index 7d6054d6805..800bef2619d 100644
--- a/chromium/content/browser/media/capture/cursor_renderer_mac.mm
+++ b/chromium/content/browser/media/capture/cursor_renderer_mac.mm
@@ -10,7 +10,6 @@
#include "base/bind.h"
#include "base/logging.h"
#include "base/mac/mac_util.h"
-#include "base/memory/ptr_util.h"
#include "skia/ext/skia_utils_mac.h"
#include "ui/gfx/image/image.h"
diff --git a/chromium/content/browser/media/capture/cursor_renderer_mac_unittest.mm b/chromium/content/browser/media/capture/cursor_renderer_mac_unittest.mm
index 3bf343b17e7..68f70d37be6 100644
--- a/chromium/content/browser/media/capture/cursor_renderer_mac_unittest.mm
+++ b/chromium/content/browser/media/capture/cursor_renderer_mac_unittest.mm
@@ -7,7 +7,6 @@
#include <Cocoa/Cocoa.h>
#include "base/mac/scoped_nsobject.h"
-#include "base/memory/ptr_util.h"
#include "base/test/scoped_task_environment.h"
#include "base/time/time.h"
#include "media/base/video_frame.h"
diff --git a/chromium/content/browser/media/capture/desktop_capture_device.cc b/chromium/content/browser/media/capture/desktop_capture_device.cc
index 9d2deac2fed..df6078bc5f7 100644
--- a/chromium/content/browser/media/capture/desktop_capture_device.cc
+++ b/chromium/content/browser/media/capture/desktop_capture_device.cc
@@ -117,7 +117,7 @@ class DesktopCaptureDevice::Core : public webrtc::DesktopCapturer::Callback {
void SetMockTimeForTesting(
scoped_refptr<base::SingleThreadTaskRunner> task_runner,
- std::unique_ptr<base::TickClock> tick_clock);
+ const base::TickClock* tick_clock);
private:
// webrtc::DesktopCapturer::Callback interface.
@@ -166,7 +166,7 @@ class DesktopCaptureDevice::Core : public webrtc::DesktopCapturer::Callback {
// be returned to the caller directly then this is NULL.
std::unique_ptr<webrtc::DesktopFrame> output_frame_;
- std::unique_ptr<base::TickClock> tick_clock_;
+ const base::TickClock* tick_clock_ = nullptr;
// Timer used to capture the frame.
std::unique_ptr<base::OneShotTimer> capture_timer_;
@@ -204,7 +204,6 @@ DesktopCaptureDevice::Core::Core(
DesktopMediaID::Type type)
: task_runner_(task_runner),
desktop_capturer_(std::move(capturer)),
- tick_clock_(nullptr),
capture_timer_(new base::OneShotTimer()),
max_cpu_consumption_percentage_(GetMaximumCpuConsumptionPercentage()),
capture_in_progress_(false),
@@ -247,10 +246,14 @@ void DesktopCaptureDevice::Core::AllocateAndStart(
DCHECK(!wake_lock_);
// Gets a service_manager::Connector first, then request a wake lock.
- BrowserThread::PostTaskAndReplyWithResult(
- BrowserThread::UI, FROM_HERE, base::BindOnce(&GetServiceConnector),
- base::BindOnce(&DesktopCaptureDevice::Core::RequestWakeLock,
- weak_factory_.GetWeakPtr()));
+ // TODO(https://crbug.com/823869): Fix DesktopCaptureDeviceTest and remove
+ // this conditional.
+ if (BrowserThread::IsThreadInitialized(BrowserThread::UI)) {
+ BrowserThread::PostTaskAndReplyWithResult(
+ BrowserThread::UI, FROM_HERE, base::BindOnce(&GetServiceConnector),
+ base::BindOnce(&DesktopCaptureDevice::Core::RequestWakeLock,
+ weak_factory_.GetWeakPtr()));
+ }
desktop_capturer_->Start(this);
// Assume it will be always started successfully for now.
@@ -268,9 +271,9 @@ void DesktopCaptureDevice::Core::SetNotificationWindowId(
void DesktopCaptureDevice::Core::SetMockTimeForTesting(
scoped_refptr<base::SingleThreadTaskRunner> task_runner,
- std::unique_ptr<base::TickClock> tick_clock) {
- tick_clock_ = std::move(tick_clock);
- capture_timer_.reset(new base::OneShotTimer(tick_clock_.get()));
+ const base::TickClock* tick_clock) {
+ tick_clock_ = tick_clock;
+ capture_timer_.reset(new base::OneShotTimer(tick_clock_));
capture_timer_->SetTaskRunner(task_runner);
}
@@ -496,8 +499,7 @@ std::unique_ptr<media::VideoCaptureDevice> DesktopCaptureDevice::Create(
webrtc::DesktopCapturer::CreateScreenCapturer(options));
if (screen_capturer && screen_capturer->SelectSource(source.id)) {
capturer.reset(new webrtc::DesktopAndCursorComposer(
- screen_capturer.release(),
- webrtc::MouseCursorMonitor::CreateForScreen(options, source.id)));
+ std::move(screen_capturer), options));
IncrementDesktopCaptureCounter(SCREEN_CAPTURER_CREATED);
IncrementDesktopCaptureCounter(
source.audio_share ? SCREEN_CAPTURER_CREATED_WITH_AUDIO
@@ -512,8 +514,7 @@ std::unique_ptr<media::VideoCaptureDevice> DesktopCaptureDevice::Create(
if (window_capturer && window_capturer->SelectSource(source.id)) {
window_capturer->FocusOnSelectedSource();
capturer.reset(new webrtc::DesktopAndCursorComposer(
- window_capturer.release(),
- webrtc::MouseCursorMonitor::CreateForWindow(options, source.id)));
+ std::move(window_capturer), options));
IncrementDesktopCaptureCounter(WINDOW_CAPTURER_CREATED);
}
break;
@@ -563,8 +564,8 @@ DesktopCaptureDevice::DesktopCaptureDevice(
std::unique_ptr<webrtc::DesktopCapturer> capturer,
DesktopMediaID::Type type)
: thread_("desktopCaptureThread") {
-#if defined(OS_WIN)
- // On Windows the thread must be a UI thread.
+#if defined(OS_WIN) || defined(OS_MACOSX)
+ // On Windows/OSX the thread must be a UI thread.
base::MessageLoop::Type thread_type = base::MessageLoop::TYPE_UI;
#else
base::MessageLoop::Type thread_type = base::MessageLoop::TYPE_DEFAULT;
@@ -577,8 +578,8 @@ DesktopCaptureDevice::DesktopCaptureDevice(
void DesktopCaptureDevice::SetMockTimeForTesting(
scoped_refptr<base::SingleThreadTaskRunner> task_runner,
- std::unique_ptr<base::TickClock> tick_clock) {
- core_->SetMockTimeForTesting(task_runner, std::move(tick_clock));
+ const base::TickClock* tick_clock) {
+ core_->SetMockTimeForTesting(task_runner, tick_clock);
}
} // namespace content
diff --git a/chromium/content/browser/media/capture/desktop_capture_device.h b/chromium/content/browser/media/capture/desktop_capture_device.h
index 5263d45d726..07719176eea 100644
--- a/chromium/content/browser/media/capture/desktop_capture_device.h
+++ b/chromium/content/browser/media/capture/desktop_capture_device.h
@@ -63,7 +63,7 @@ class CONTENT_EXPORT DesktopCaptureDevice : public media::VideoCaptureDevice {
// other testing entities inheriting the common runner and tick interfaces.
void SetMockTimeForTesting(
scoped_refptr<base::SingleThreadTaskRunner> task_runner,
- std::unique_ptr<base::TickClock> tick_clock);
+ const base::TickClock* tick_clock);
base::Thread thread_;
std::unique_ptr<Core> core_;
diff --git a/chromium/content/browser/media/capture/desktop_capture_device_unittest.cc b/chromium/content/browser/media/capture/desktop_capture_device_unittest.cc
index 3ca88ac86ef..08f262b5262 100644
--- a/chromium/content/browser/media/capture/desktop_capture_device_unittest.cc
+++ b/chromium/content/browser/media/capture/desktop_capture_device_unittest.cc
@@ -13,13 +13,13 @@
#include "base/command_line.h"
#include "base/macros.h"
+#include "base/message_loop/message_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/synchronization/waitable_event.h"
#include "base/test/test_mock_time_task_runner.h"
#include "base/test/test_timeouts.h"
#include "base/time/tick_clock.h"
#include "base/time/time.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 "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h"
diff --git a/chromium/content/browser/media/capture/fake_webcontent_capture_machine.cc b/chromium/content/browser/media/capture/fake_webcontent_capture_machine.cc
index cedac4e2b0c..f18b8835d6e 100644
--- a/chromium/content/browser/media/capture/fake_webcontent_capture_machine.cc
+++ b/chromium/content/browser/media/capture/fake_webcontent_capture_machine.cc
@@ -5,7 +5,6 @@
#include "content/browser/media/capture/fake_webcontent_capture_machine.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
namespace content {
diff --git a/chromium/content/browser/media/capture/frame_sink_video_capture_device.cc b/chromium/content/browser/media/capture/frame_sink_video_capture_device.cc
index c9ce3834771..8db3dc88281 100644
--- a/chromium/content/browser/media/capture/frame_sink_video_capture_device.cc
+++ b/chromium/content/browser/media/capture/frame_sink_video_capture_device.cc
@@ -18,7 +18,7 @@
#include "components/viz/host/host_frame_sink_manager.h"
#include "content/browser/compositor/surface_utils.h"
#include "media/base/bind_to_current_loop.h"
-#include "media/capture/mojo/video_capture_types.mojom.h"
+#include "media/capture/mojom/video_capture_types.mojom.h"
#include "mojo/public/cpp/system/buffer.h"
namespace content {
@@ -258,12 +258,10 @@ void FrameSinkVideoCaptureDevice::OnFrameCaptured(
// Set the INTERACTIVE_CONTENT frame metadata.
media::VideoFrameMetadata modified_metadata;
- if (info->metadata) {
- modified_metadata.MergeInternalValuesFrom(*info->metadata);
- }
+ modified_metadata.MergeInternalValuesFrom(info->metadata);
modified_metadata.SetBoolean(media::VideoFrameMetadata::INTERACTIVE_CONTENT,
cursor_renderer_->IsUserInteractingWithView());
- info->metadata = modified_metadata.CopyInternalValues();
+ info->metadata = modified_metadata.GetInternalValues().Clone();
// Pass the video frame to the VideoFrameReceiver. This is done by first
// passing the shared memory buffer handle and then notifying it that a new
diff --git a/chromium/content/browser/media/capture/frame_sink_video_capture_device_unittest.cc b/chromium/content/browser/media/capture/frame_sink_video_capture_device_unittest.cc
index 55821bfb7ab..f52055ef111 100644
--- a/chromium/content/browser/media/capture/frame_sink_video_capture_device_unittest.cc
+++ b/chromium/content/browser/media/capture/frame_sink_video_capture_device_unittest.cc
@@ -86,10 +86,12 @@ class MockFrameSinkVideoCapturer : public viz::mojom::FrameSinkVideoCapturer {
void(media::VideoPixelFormat format,
media::ColorSpace color_space));
MOCK_METHOD1(SetMinCapturePeriod, void(base::TimeDelta min_period));
+ MOCK_METHOD1(SetMinSizeChangePeriod, void(base::TimeDelta));
MOCK_METHOD3(SetResolutionConstraints,
void(const gfx::Size& min_size,
const gfx::Size& max_size,
bool use_fixed_aspect_ratio));
+ MOCK_METHOD1(SetAutoThrottlingEnabled, void(bool));
MOCK_METHOD1(ChangeTarget, void(const viz::FrameSinkId& frame_sink_id));
void Start(viz::mojom::FrameSinkVideoConsumerPtr consumer) final {
DCHECK_NOT_ON_DEVICE_THREAD();
@@ -345,7 +347,8 @@ class FrameSinkVideoCaptureDeviceTest : public testing::Test {
device->OnFrameCaptured(
std::move(buffer), buffer_size,
media::mojom::VideoFrameInfo::New(
- kMinCapturePeriod * frame_number, nullptr, kFormat, kStorage,
+ kMinCapturePeriod * frame_number,
+ base::Value(base::Value::Type::DICTIONARY), kFormat, kStorage,
kResolution, gfx::Rect(kResolution)),
gfx::Rect(kResolution), gfx::Rect(kResolution),
viz::mojom::FrameSinkVideoConsumerFrameCallbacksPtr(
diff --git a/chromium/content/browser/media/capture/screen_capture_device_android.cc b/chromium/content/browser/media/capture/screen_capture_device_android.cc
index a249ce5ec80..1e93e1c1ce3 100644
--- a/chromium/content/browser/media/capture/screen_capture_device_android.cc
+++ b/chromium/content/browser/media/capture/screen_capture_device_android.cc
@@ -5,7 +5,6 @@
#include "content/browser/media/capture/screen_capture_device_android.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "media/capture/content/android/screen_capture_machine_android.h"
namespace content {
diff --git a/chromium/content/browser/media/capture/screen_capture_device_android_unittest.cc b/chromium/content/browser/media/capture/screen_capture_device_android_unittest.cc
index 7d18ecc702d..994bfae8014 100644
--- a/chromium/content/browser/media/capture/screen_capture_device_android_unittest.cc
+++ b/chromium/content/browser/media/capture/screen_capture_device_android_unittest.cc
@@ -4,7 +4,6 @@
#include "content/browser/media/capture/screen_capture_device_android.h"
-#include "base/memory/ptr_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
diff --git a/chromium/content/browser/media/capture/web_contents_video_capture_device_browsertest.cc b/chromium/content/browser/media/capture/web_contents_video_capture_device_browsertest.cc
index c717c84aa8a..5a6951ca012 100644
--- a/chromium/content/browser/media/capture/web_contents_video_capture_device_browsertest.cc
+++ b/chromium/content/browser/media/capture/web_contents_video_capture_device_browsertest.cc
@@ -126,9 +126,7 @@ class FakeVideoCaptureStack {
reinterpret_cast<uint8_t*>(mapping.get()), mapped_size,
frame_info->timestamp);
CHECK(frame);
- if (frame_info->metadata) {
- frame->metadata()->MergeInternalValuesFrom(*frame_info->metadata);
- }
+ frame->metadata()->MergeInternalValuesFrom(frame_info->metadata);
// This destruction observer will unmap the shared memory when the
// VideoFrame goes out-of-scope.
frame->AddDestructionObserver(base::BindOnce(
diff --git a/chromium/content/browser/media/cdm_file_impl.cc b/chromium/content/browser/media/cdm_file_impl.cc
index 12e6e826adf..4c1657d1b6c 100644
--- a/chromium/content/browser/media/cdm_file_impl.cc
+++ b/chromium/content/browser/media/cdm_file_impl.cc
@@ -174,8 +174,8 @@ void CdmFileImpl::Initialize(OpenFileCallback callback) {
lock_state_ = LockState::kFileLocked;
pending_open_callback_ = std::move(callback);
OpenFile(file_name_, base::File::FLAG_OPEN_ALWAYS | base::File::FLAG_READ,
- base::Bind(&CdmFileImpl::OnFileOpenedForReading,
- weak_factory_.GetWeakPtr()));
+ base::BindOnce(&CdmFileImpl::OnFileOpenedForReading,
+ weak_factory_.GetWeakPtr()));
}
void CdmFileImpl::OpenFile(const std::string& file_name,
@@ -248,8 +248,8 @@ void CdmFileImpl::OpenFileForWriting(OpenFileForWritingCallback callback) {
pending_open_callback_ = std::move(callback);
OpenFile(temp_file_name_,
base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE,
- base::Bind(&CdmFileImpl::OnTempFileOpenedForWriting,
- weak_factory_.GetWeakPtr()));
+ base::BindOnce(&CdmFileImpl::OnTempFileOpenedForWriting,
+ weak_factory_.GetWeakPtr()));
}
void CdmFileImpl::OnTempFileOpenedForWriting(
@@ -312,7 +312,7 @@ void CdmFileImpl::CommitWrite(CommitWriteCallback callback) {
file_util->MoveFileLocal(
std::move(operation_context), src_file_url, dest_file_url,
storage::FileSystemOperation::OPTION_NONE,
- base::Bind(&CdmFileImpl::OnFileRenamed, weak_factory_.GetWeakPtr()));
+ base::BindOnce(&CdmFileImpl::OnFileRenamed, weak_factory_.GetWeakPtr()));
}
void CdmFileImpl::OnFileRenamed(base::File::Error move_result) {
@@ -334,8 +334,8 @@ void CdmFileImpl::OnFileRenamed(base::File::Error move_result) {
// Reopen the original file for reading. Specifying FLAG_OPEN as the file
// has to exist or something's wrong.
OpenFile(file_name_, base::File::FLAG_OPEN | base::File::FLAG_READ,
- base::Bind(&CdmFileImpl::OnFileOpenedForReading,
- weak_factory_.GetWeakPtr()));
+ base::BindOnce(&CdmFileImpl::OnFileOpenedForReading,
+ weak_factory_.GetWeakPtr()));
}
storage::FileSystemURL CdmFileImpl::CreateFileSystemURL(
diff --git a/chromium/content/browser/media/encrypted_media_browsertest.cc b/chromium/content/browser/media/encrypted_media_browsertest.cc
index 74387d25c06..9a01d1a44e9 100644
--- a/chromium/content/browser/media/encrypted_media_browsertest.cc
+++ b/chromium/content/browser/media/encrypted_media_browsertest.cc
@@ -2,6 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
+#include <tuple>
+
#include "base/command_line.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
@@ -14,8 +16,8 @@
#include "media/base/media.h"
#include "media/base/media_switches.h"
#include "media/base/test_data_util.h"
-#include "media/media_features.h"
-#include "media/mojo/features.h"
+#include "media/media_buildflags.h"
+#include "media/mojo/buildflags.h"
#if defined(OS_ANDROID)
#include "base/android/build_info.h"
@@ -49,6 +51,9 @@ const char kWebMVP8VideoOnly[] = "video/webm; codecs=\"vp8\"";
const char kWebMVP9VideoOnly[] = "video/webm; codecs=\"vp9\"";
const char kWebMOpusAudioVP9Video[] = "video/webm; codecs=\"opus, vp9\"";
const char kWebMVorbisAudioVP8Video[] = "video/webm; codecs=\"vorbis, vp8\"";
+#if BUILDFLAG(USE_PROPRIETARY_CODECS)
+const char kMP4VideoOnly[] = "video/mp4; codecs=\"avc1.64001E\"";
+#endif // BUILDFLAG(USE_PROPRIETARY_CODECS)
// EME-specific test results and errors.
const char kEmeKeyError[] = "KEYERROR";
@@ -72,19 +77,15 @@ enum class ConfigChangeType {
// - SrcType: The type of video src used to load media, MSE or SRC.
// It is okay to run this test as a non-parameterized test, in this case,
// GetParam() should not be called.
-class EncryptedMediaTest : public MediaBrowserTest,
- public testing::WithParamInterface<
- std::tr1::tuple<const char*, SrcType>> {
+class EncryptedMediaTest
+ : public MediaBrowserTest,
+ public testing::WithParamInterface<std::tuple<const char*, SrcType>> {
public:
// Can only be used in parameterized (*_P) tests.
- const std::string CurrentKeySystem() {
- return std::tr1::get<0>(GetParam());
- }
+ const std::string CurrentKeySystem() { return std::get<0>(GetParam()); }
// Can only be used in parameterized (*_P) tests.
- SrcType CurrentSourceType() {
- return std::tr1::get<1>(GetParam());
- }
+ SrcType CurrentSourceType() { return std::get<1>(GetParam()); }
void TestSimplePlayback(const std::string& encrypted_media,
const std::string& media_type) {
@@ -140,6 +141,19 @@ class EncryptedMediaTest : public MediaBrowserTest,
src_type, media::kEnded);
}
+#if BUILDFLAG(USE_PROPRIETARY_CODECS)
+ void TestMP4EncryptionPlayback(const std::string& media_file,
+ const std::string& expected_title) {
+ if (CurrentSourceType() != SrcType::MSE) {
+ DVLOG(0) << "Skipping test; Can only play MP4 encrypted streams by MSE.";
+ return;
+ }
+
+ RunEncryptedMediaTest(kDefaultEmePlayer, media_file, kMP4VideoOnly,
+ CurrentKeySystem(), SrcType::MSE, expected_title);
+ }
+#endif // BUILDFLAG(USE_PROPRIETARY_CODECS)
+
protected:
// We want to fail quickly when a test fails because an error is encountered.
void AddTitlesToAwait(content::TitleWatcher* title_watcher) override {
@@ -270,6 +284,28 @@ IN_PROC_BROWSER_TEST_P(EncryptedMediaTest, MAYBE_FrameSizeChangeVideo) {
TestFrameSizeChange();
}
+#if BUILDFLAG(USE_PROPRIETARY_CODECS)
+IN_PROC_BROWSER_TEST_P(EncryptedMediaTest, Playback_Encryption_CENC) {
+ TestMP4EncryptionPlayback("bear-640x360-v_frag-cenc.mp4", media::kEnded);
+}
+
+IN_PROC_BROWSER_TEST_P(EncryptedMediaTest, Playback_Encryption_CBC1) {
+ TestMP4EncryptionPlayback("bear-640x360-v_frag-cbc1.mp4", media::kError);
+}
+
+IN_PROC_BROWSER_TEST_P(EncryptedMediaTest, Playback_Encryption_CENS) {
+ TestMP4EncryptionPlayback("bear-640x360-v_frag-cens.mp4", media::kError);
+}
+
+IN_PROC_BROWSER_TEST_P(EncryptedMediaTest, Playback_Encryption_CBCS) {
+#if BUILDFLAG(ENABLE_CBCS_ENCRYPTION_SCHEME)
+ TestMP4EncryptionPlayback("bear-640x360-v_frag-cbcs.mp4", media::kEnded);
+#else
+ TestMP4EncryptionPlayback("bear-640x360-v_frag-cbcs.mp4", media::kError);
+#endif
+}
+#endif // BUILDFLAG(USE_PROPRIETARY_CODECS)
+
IN_PROC_BROWSER_TEST_F(EncryptedMediaTest, UnknownKeySystemThrowsException) {
RunEncryptedMediaTest(kDefaultEmePlayer, "bear-a_enc-a.webm",
kWebMVorbisAudioOnly, "com.example.foo", SrcType::MSE,
diff --git a/chromium/content/browser/media/key_system_support_impl.cc b/chromium/content/browser/media/key_system_support_impl.cc
index 52aebf438af..0092ef764f1 100644
--- a/chromium/content/browser/media/key_system_support_impl.cc
+++ b/chromium/content/browser/media/key_system_support_impl.cc
@@ -14,30 +14,10 @@
#include "media/base/key_systems.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
-#if DCHECK_IS_ON()
-#include "base/strings/utf_string_conversions.h"
-#include "content/public/browser/plugin_service.h"
-#include "content/public/common/webplugininfo.h"
-#endif // DCHECK_IS_ON()
-
namespace content {
namespace {
-#if DCHECK_IS_ON()
-// TODO(crbug.com/772160) Remove this when pepper CDM support removed.
-bool IsPepperPluginRegistered(const std::string& plugin_name) {
- std::vector<WebPluginInfo> plugins;
- PluginService::GetInstance()->GetInternalPlugins(&plugins);
- for (const auto& plugin : plugins) {
- if (plugin.is_pepper_plugin() &&
- plugin.name == base::ASCIIToUTF16(plugin_name))
- return true;
- }
- return false;
-}
-#endif // DCHECK_IS_ON()
-
void SendCdmAvailableUMA(const std::string& key_system, bool available) {
base::UmaHistogramBoolean("Media.EME." +
media::GetKeySystemNameForUMA(key_system) +
@@ -86,11 +66,6 @@ void KeySystemSupportImpl::IsKeySystemSupported(
return;
}
-#if DCHECK_IS_ON()
- DCHECK(IsPepperPluginRegistered(cdm->name))
- << "Pepper plugin for " << key_system << " should also be registered.";
-#endif
-
SendCdmAvailableUMA(key_system, true);
std::move(callback).Run(true, cdm->supported_video_codecs,
cdm->supports_persistent_license);
diff --git a/chromium/content/browser/media/media_browsertest.cc b/chromium/content/browser/media/media_browsertest.cc
index 9fc250d87d9..8e6045d5d33 100644
--- a/chromium/content/browser/media/media_browsertest.cc
+++ b/chromium/content/browser/media/media_browsertest.cc
@@ -15,7 +15,7 @@
#include "content/shell/browser/shell.h"
#include "media/base/media_switches.h"
#include "media/base/test_data_util.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "url/url_util.h"
diff --git a/chromium/content/browser/media/media_canplaytype_browsertest.cc b/chromium/content/browser/media/media_canplaytype_browsertest.cc
index 6bab3960e94..11bfbc8548e 100644
--- a/chromium/content/browser/media/media_canplaytype_browsertest.cc
+++ b/chromium/content/browser/media/media_canplaytype_browsertest.cc
@@ -14,7 +14,7 @@
#include "content/public/test/content_browser_test_utils.h"
#include "content/shell/browser/shell.h"
#include "media/base/media_switches.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "third_party/libaom/av1_features.h"
#include "ui/display/display_switches.h"
diff --git a/chromium/content/browser/media/media_color_browsertest.cc b/chromium/content/browser/media/media_color_browsertest.cc
index 55d4cdc519d..158109139a5 100644
--- a/chromium/content/browser/media/media_color_browsertest.cc
+++ b/chromium/content/browser/media/media_color_browsertest.cc
@@ -6,7 +6,7 @@
#include "content/browser/media/media_browsertest.h"
#include "content/public/test/browser_test_utils.h"
#include "media/base/test_data_util.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
namespace content {
diff --git a/chromium/content/browser/media/media_devices_permission_checker.cc b/chromium/content/browser/media/media_devices_permission_checker.cc
index c3c2545748b..6a8aee944a5 100644
--- a/chromium/content/browser/media/media_devices_permission_checker.cc
+++ b/chromium/content/browser/media/media_devices_permission_checker.cc
@@ -39,8 +39,8 @@ MediaDevicesManager::BoolDeviceTypes DoCheckPermissionsOnUIThread(
RenderFrameHostDelegate* delegate = frame_host->delegate();
url::Origin origin = frame_host->GetLastCommittedOrigin();
- bool audio_permission =
- delegate->CheckMediaAccessPermission(origin, MEDIA_DEVICE_AUDIO_CAPTURE);
+ bool audio_permission = delegate->CheckMediaAccessPermission(
+ frame_host, origin, MEDIA_DEVICE_AUDIO_CAPTURE);
bool mic_feature_policy = true;
bool camera_feature_policy = true;
if (base::FeatureList::IsEnabled(features::kUseFeaturePolicyForPermissions)) {
@@ -66,7 +66,7 @@ MediaDevicesManager::BoolDeviceTypes DoCheckPermissionsOnUIThread(
// Camera.
result[MEDIA_DEVICE_TYPE_VIDEO_INPUT] =
requested_device_types[MEDIA_DEVICE_TYPE_VIDEO_INPUT] &&
- delegate->CheckMediaAccessPermission(origin,
+ delegate->CheckMediaAccessPermission(frame_host, origin,
MEDIA_DEVICE_VIDEO_CAPTURE) &&
camera_feature_policy;
diff --git a/chromium/content/browser/media/media_devices_permission_checker_unittest.cc b/chromium/content/browser/media/media_devices_permission_checker_unittest.cc
index 621fa853d6e..5e95d2bdd69 100644
--- a/chromium/content/browser/media/media_devices_permission_checker_unittest.cc
+++ b/chromium/content/browser/media/media_devices_permission_checker_unittest.cc
@@ -15,7 +15,7 @@
#include "content/public/test/test_renderer_host.h"
#include "content/test/test_render_view_host.h"
#include "content/test/test_web_contents.h"
-#include "third_party/WebKit/public/common/feature_policy/feature_policy.h"
+#include "third_party/blink/public/common/feature_policy/feature_policy.h"
#include "url/origin.h"
namespace content {
@@ -26,7 +26,7 @@ class TestWebContentsDelegate : public content::WebContentsDelegate {
public:
~TestWebContentsDelegate() override {}
- bool CheckMediaAccessPermission(WebContents* web_contents,
+ bool CheckMediaAccessPermission(RenderFrameHost* render_Frame_host,
const GURL& security_origin,
MediaStreamType type) override {
return true;
diff --git a/chromium/content/browser/media/media_interface_proxy.cc b/chromium/content/browser/media/media_interface_proxy.cc
index 86ec886c227..31bf2c0f4d8 100644
--- a/chromium/content/browser/media/media_interface_proxy.cc
+++ b/chromium/content/browser/media/media_interface_proxy.cc
@@ -10,12 +10,13 @@
#include "base/logging.h"
#include "base/macros.h"
#include "base/strings/string_util.h"
-#include "build/build_config.h"
+#include "content/browser/frame_host/render_frame_host_delegate.h"
+#include "content/browser/frame_host/render_frame_host_impl.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/common/content_client.h"
#include "content/public/common/service_manager_connection.h"
-#include "media/mojo/features.h"
+#include "media/mojo/buildflags.h"
#include "media/mojo/interfaces/constants.mojom.h"
#include "media/mojo/interfaces/media_service.mojom.h"
#include "media/mojo/services/media_interface_provider.h"
@@ -43,6 +44,11 @@
#endif // defined(OS_MACOSX)
#endif // BUILDFLAG(ENABLE_LIBRARY_CDMS)
+#if defined(OS_ANDROID)
+#include "content/browser/media/android/media_player_renderer.h"
+#include "media/mojo/services/mojo_renderer_service.h" // nogncheck
+#endif
+
namespace content {
#if BUILDFLAG(ENABLE_LIBRARY_CDMS) && defined(OS_MACOSX)
@@ -145,12 +151,21 @@ void MediaInterfaceProxy::CreateVideoDecoder(
}
void MediaInterfaceProxy::CreateRenderer(
- const std::string& audio_device_id,
+ media::mojom::HostedRendererType type,
+ const std::string& type_specific_id,
media::mojom::RendererRequest request) {
DCHECK(thread_checker_.CalledOnValidThread());
+
+#if defined(OS_ANDROID)
+ if (type == media::mojom::HostedRendererType::kMediaPlayer) {
+ CreateMediaPlayerRenderer(std::move(request));
+ return;
+ }
+#endif
+
InterfaceFactory* factory = GetMediaInterfaceFactory();
if (factory)
- factory->CreateRenderer(audio_device_id, std::move(request));
+ factory->CreateRenderer(type, type_specific_id, std::move(request));
}
void MediaInterfaceProxy::CreateCdm(
@@ -355,4 +370,25 @@ void MediaInterfaceProxy::CreateCdmProxyInternal(
}
#endif // BUILDFLAG(ENABLE_LIBRARY_CDMS)
+#if defined(OS_ANDROID)
+void MediaInterfaceProxy::CreateMediaPlayerRenderer(
+ media::mojom::RendererRequest request) {
+ auto renderer = std::make_unique<MediaPlayerRenderer>(
+ render_frame_host_->GetProcess()->GetID(),
+ render_frame_host_->GetRoutingID(),
+ static_cast<RenderFrameHostImpl*>(render_frame_host_)
+ ->delegate()
+ ->GetAsWebContents());
+
+ // base::Unretained is safe here because the lifetime of the MediaPlayerRender
+ // is tied to the lifetime of the MojoRendererService.
+ media::MojoRendererService::InitiateSurfaceRequestCB surface_request_cb =
+ base::BindRepeating(&MediaPlayerRenderer::InitiateScopedSurfaceRequest,
+ base::Unretained(renderer.get()));
+
+ media::MojoRendererService::Create(std::move(renderer), surface_request_cb,
+ std::move(request));
+}
+#endif // defined(OS_ANDROID)
+
} // namespace content
diff --git a/chromium/content/browser/media/media_interface_proxy.h b/chromium/content/browser/media/media_interface_proxy.h
index b2c2839cc1a..08b7661a4a2 100644
--- a/chromium/content/browser/media/media_interface_proxy.h
+++ b/chromium/content/browser/media/media_interface_proxy.h
@@ -11,7 +11,8 @@
#include "base/macros.h"
#include "base/threading/thread_checker.h"
-#include "media/media_features.h"
+#include "build/build_config.h"
+#include "media/media_buildflags.h"
#include "media/mojo/interfaces/content_decryption_module.mojom.h"
#include "media/mojo/interfaces/interface_factory.mojom.h"
#include "mojo/public/cpp/bindings/binding.h"
@@ -45,7 +46,8 @@ class MediaInterfaceProxy : public media::mojom::InterfaceFactory {
// media::mojom::InterfaceFactory implementation.
void CreateAudioDecoder(media::mojom::AudioDecoderRequest request) final;
void CreateVideoDecoder(media::mojom::VideoDecoderRequest request) final;
- void CreateRenderer(const std::string& audio_device_id,
+ void CreateRenderer(media::mojom::HostedRendererType type,
+ const std::string& type_specific_id,
media::mojom::RendererRequest request) final;
void CreateCdm(const std::string& key_system,
media::mojom::ContentDecryptionModuleRequest request) final;
@@ -95,6 +97,10 @@ class MediaInterfaceProxy : public media::mojom::InterfaceFactory {
media::mojom::CdmProxyRequest request);
#endif // BUILDFLAG(ENABLE_LIBRARY_CDMS)
+#if defined(OS_ANDROID)
+ void CreateMediaPlayerRenderer(media::mojom::RendererRequest request);
+#endif
+
// Safe to hold a raw pointer since |this| is owned by RenderFrameHostImpl.
RenderFrameHost* const render_frame_host_;
diff --git a/chromium/content/browser/media/media_internals.cc b/chromium/content/browser/media/media_internals.cc
index a0759caccd5..6e58bdce30f 100644
--- a/chromium/content/browser/media/media_internals.cc
+++ b/chromium/content/browser/media/media_internals.cc
@@ -419,7 +419,14 @@ void MediaInternals::MediaInternalsUMAHandler::SavePlayerState(
if (event.params.HasKey("pipeline_buffering_state")) {
std::string buffering_state;
event.params.GetString("pipeline_buffering_state", &buffering_state);
- if (buffering_state == "BUFFERING_HAVE_ENOUGH")
+
+ bool for_suspended_start;
+ event.params.GetBoolean("for_suspended_start", &for_suspended_start);
+
+ // Ignore the BUFFERING_HAVE_ENOUGH event if it was for a suspended
+ // start. Otherwise we won't reflect reductions to the HasEverPlayed
+ // statistic.
+ if (buffering_state == "BUFFERING_HAVE_ENOUGH" && !for_suspended_start)
player_info.has_reached_have_enough = true;
}
break;
diff --git a/chromium/content/browser/media/media_internals_handler.cc b/chromium/content/browser/media/media_internals_handler.cc
index aafe26ea259..196e76755ad 100644
--- a/chromium/content/browser/media/media_internals_handler.cc
+++ b/chromium/content/browser/media/media_internals_handler.cc
@@ -27,9 +27,10 @@ void MediaInternalsMessageHandler::RegisterMessages() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
proxy_->Attach(this);
- web_ui()->RegisterMessageCallback("getEverything",
- base::Bind(&MediaInternalsMessageHandler::OnGetEverything,
- base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "getEverything",
+ base::BindRepeating(&MediaInternalsMessageHandler::OnGetEverything,
+ base::Unretained(this)));
}
void MediaInternalsMessageHandler::OnGetEverything(
diff --git a/chromium/content/browser/media/media_internals_ui.cc b/chromium/content/browser/media/media_internals_ui.cc
index c31ba5b24f6..7d4b7fe5fe4 100644
--- a/chromium/content/browser/media/media_internals_ui.cc
+++ b/chromium/content/browser/media/media_internals_ui.cc
@@ -5,7 +5,6 @@
#include "content/browser/media/media_internals_ui.h"
#include "base/command_line.h"
-#include "base/memory/ptr_util.h"
#include "content/browser/media/media_internals_handler.h"
#include "content/grit/content_resources.h"
#include "content/public/browser/web_contents.h"
diff --git a/chromium/content/browser/media/media_internals_unittest.cc b/chromium/content/browser/media/media_internals_unittest.cc
index 671f282345c..506227d219e 100644
--- a/chromium/content/browser/media/media_internals_unittest.cc
+++ b/chromium/content/browser/media/media_internals_unittest.cc
@@ -126,6 +126,8 @@ TEST_F(MediaInternalsVideoCaptureDeviceTest,
std::map<VideoCaptureApi, std::string> api_to_string_map;
api_to_string_map[VideoCaptureApi::LINUX_V4L2_SINGLE_PLANE] = "V4L2 SPLANE";
api_to_string_map[VideoCaptureApi::WIN_MEDIA_FOUNDATION] = "Media Foundation";
+ api_to_string_map[VideoCaptureApi::WIN_MEDIA_FOUNDATION_SENSOR] =
+ "Media Foundation Sensor Camera";
api_to_string_map[VideoCaptureApi::WIN_DIRECT_SHOW] = "Direct Show";
api_to_string_map[VideoCaptureApi::MACOSX_AVFOUNDATION] = "AV Foundation";
api_to_string_map[VideoCaptureApi::MACOSX_DECKLINK] = "DeckLink";
diff --git a/chromium/content/browser/media/media_redirect_browsertest.cc b/chromium/content/browser/media/media_redirect_browsertest.cc
index 8be45ca6a53..c1f24e8e290 100644
--- a/chromium/content/browser/media/media_redirect_browsertest.cc
+++ b/chromium/content/browser/media/media_redirect_browsertest.cc
@@ -7,7 +7,7 @@
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_browser_test_utils.h"
#include "media/base/test_data_util.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.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"
diff --git a/chromium/content/browser/media/media_source_browsertest.cc b/chromium/content/browser/media/media_source_browsertest.cc
index f19606cdd20..e5571a3b16c 100644
--- a/chromium/content/browser/media/media_source_browsertest.cc
+++ b/chromium/content/browser/media/media_source_browsertest.cc
@@ -8,7 +8,7 @@
#include "content/browser/media/media_browsertest.h"
#include "media/base/media_switches.h"
#include "media/base/test_data_util.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#if defined(OS_ANDROID)
#include "base/android/build_info.h"
diff --git a/chromium/content/browser/media/media_web_contents_observer.cc b/chromium/content/browser/media/media_web_contents_observer.cc
index 5c6a7728857..065f2f24773 100644
--- a/chromium/content/browser/media/media_web_contents_observer.cc
+++ b/chromium/content/browser/media/media_web_contents_observer.cc
@@ -16,7 +16,7 @@
#include "ipc/ipc_message_macros.h"
#include "mojo/public/cpp/bindings/interface_request.h"
#include "services/device/public/mojom/wake_lock_context.mojom.h"
-#include "third_party/WebKit/public/platform/WebFullscreenVideoStatus.h"
+#include "third_party/blink/public/platform/web_fullscreen_video_status.h"
#include "ui/gfx/geometry/size.h"
namespace content {
@@ -41,6 +41,17 @@ void CheckFullscreenDetectionEnabled(WebContents* web_contents) {
#endif // defined(OS_ANDROID)
}
+// Returns true if |player_id| exists in |player_map|.
+bool MediaPlayerEntryExists(
+ const WebContentsObserver::MediaPlayerId& player_id,
+ const MediaWebContentsObserver::ActiveMediaPlayerMap& player_map) {
+ const auto& players = player_map.find(player_id.first);
+ if (players == player_map.end())
+ return false;
+
+ return players->second.find(player_id.second) != players->second.end();
+}
+
} // anonymous namespace
MediaWebContentsObserver::MediaWebContentsObserver(WebContents* web_contents)
@@ -58,10 +69,10 @@ void MediaWebContentsObserver::RenderFrameDeleted(
ClearWakeLocks(render_frame_host);
session_controllers_manager_.RenderFrameDeleted(render_frame_host);
- if (fullscreen_player_ && fullscreen_player_->first == render_frame_host)
+ if (fullscreen_player_ && fullscreen_player_->first == render_frame_host) {
+ picture_in_picture_allowed_in_fullscreen_.reset();
fullscreen_player_.reset();
-
- picture_in_picture_allowed_in_fullscreen_.reset();
+ }
}
void MediaWebContentsObserver::MaybeUpdateAudibleState() {
@@ -83,13 +94,7 @@ bool MediaWebContentsObserver::HasActiveEffectivelyFullscreenVideo() const {
return false;
// Check that the player is active.
- const auto& players = active_video_players_.find(fullscreen_player_->first);
- if (players == active_video_players_.end())
- return false;
- if (players->second.find(fullscreen_player_->second) == players->second.end())
- return false;
-
- return true;
+ return MediaPlayerEntryExists(*fullscreen_player_, active_video_players_);
}
bool MediaWebContentsObserver::IsPictureInPictureAllowedForFullscreenVideo()
@@ -105,6 +110,11 @@ MediaWebContentsObserver::GetFullscreenVideoMediaPlayerId() const {
return fullscreen_player_;
}
+const base::Optional<WebContentsObserver::MediaPlayerId>&
+MediaWebContentsObserver::GetPictureInPictureVideoMediaPlayerId() const {
+ return pip_player_;
+}
+
bool MediaWebContentsObserver::OnMessageReceived(
const IPC::Message& msg,
RenderFrameHost* render_frame_host) {
@@ -123,6 +133,11 @@ bool MediaWebContentsObserver::OnMessageReceived(
OnMediaEffectivelyFullscreenChanged)
IPC_MESSAGE_HANDLER(MediaPlayerDelegateHostMsg_OnMediaSizeChanged,
OnMediaSizeChanged)
+ IPC_MESSAGE_HANDLER(
+ MediaPlayerDelegateHostMsg_OnPictureInPictureSourceChanged,
+ OnPictureInPictureSourceChanged)
+ IPC_MESSAGE_HANDLER(MediaPlayerDelegateHostMsg_OnPictureInPictureModeEnded,
+ OnPictureInPictureModeEnded)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
@@ -161,10 +176,23 @@ void MediaWebContentsObserver::RequestPersistentVideo(bool value) {
target_frame->GetRoutingID(), delegate_id, value));
}
+bool MediaWebContentsObserver::IsPlayerActive(
+ const MediaPlayerId& player_id) const {
+ if (MediaPlayerEntryExists(player_id, active_video_players_))
+ return true;
+
+ return MediaPlayerEntryExists(player_id, active_audio_players_);
+}
+
void MediaWebContentsObserver::OnMediaDestroyed(
RenderFrameHost* render_frame_host,
int delegate_id) {
OnMediaPaused(render_frame_host, delegate_id, true);
+
+ if (pip_player_ &&
+ pip_player_ == MediaPlayerId(render_frame_host, delegate_id)) {
+ pip_player_.reset();
+ }
}
void MediaWebContentsObserver::OnMediaPaused(RenderFrameHost* render_frame_host,
@@ -246,10 +274,10 @@ void MediaWebContentsObserver::OnMediaEffectivelyFullscreenChanged(
picture_in_picture_allowed_in_fullscreen_ = false;
break;
case blink::WebFullscreenVideoStatus::kNotEffectivelyFullscreen:
- picture_in_picture_allowed_in_fullscreen_.reset();
if (!fullscreen_player_ || *fullscreen_player_ != id)
return;
+ picture_in_picture_allowed_in_fullscreen_.reset();
fullscreen_player_.reset();
break;
}
@@ -268,6 +296,18 @@ void MediaWebContentsObserver::OnMediaSizeChanged(
web_contents_impl()->MediaResized(size, id);
}
+void MediaWebContentsObserver::OnPictureInPictureSourceChanged(
+ RenderFrameHost* render_frame_host,
+ int delegate_id) {
+ pip_player_ = MediaPlayerId(render_frame_host, delegate_id);
+}
+
+void MediaWebContentsObserver::OnPictureInPictureModeEnded(
+ RenderFrameHost* render_frame_host,
+ int delegate_id) {
+ pip_player_.reset();
+}
+
void MediaWebContentsObserver::ClearWakeLocks(
RenderFrameHost* render_frame_host) {
std::set<MediaPlayerId> video_players;
diff --git a/chromium/content/browser/media/media_web_contents_observer.h b/chromium/content/browser/media/media_web_contents_observer.h
index 7012c147de4..7b9f1f1d399 100644
--- a/chromium/content/browser/media/media_web_contents_observer.h
+++ b/chromium/content/browser/media/media_web_contents_observer.h
@@ -44,6 +44,9 @@ class CONTENT_EXPORT MediaWebContentsObserver : public WebContentsObserver {
explicit MediaWebContentsObserver(WebContents* web_contents);
~MediaWebContentsObserver() override;
+ using PlayerSet = std::set<int>;
+ using ActiveMediaPlayerMap = std::map<RenderFrameHost*, PlayerSet>;
+
// Called by WebContentsImpl when the audible state may have changed.
void MaybeUpdateAudibleState();
@@ -62,6 +65,10 @@ class CONTENT_EXPORT MediaWebContentsObserver : public WebContentsObserver {
// Gets the MediaPlayerId of the fullscreen video if it exists.
const base::Optional<MediaPlayerId>& GetFullscreenVideoMediaPlayerId() const;
+ // Gets the MediaPlayerId of the picture in picture video if it exists.
+ const base::Optional<MediaPlayerId>& GetPictureInPictureVideoMediaPlayerId()
+ const;
+
// WebContentsObserver implementation.
void WebContentsDestroyed() override;
void RenderFrameDeleted(RenderFrameHost* render_frame_host) override;
@@ -75,6 +82,9 @@ class CONTENT_EXPORT MediaWebContentsObserver : public WebContentsObserver {
// fullscreening video element to the same place.
void RequestPersistentVideo(bool value);
+ // Returns whether or not the given player id is active.
+ bool IsPlayerActive(const MediaPlayerId& player_id) const;
+
bool has_audio_wake_lock_for_testing() const {
return has_audio_wake_lock_for_testing_;
}
@@ -109,6 +119,10 @@ class CONTENT_EXPORT MediaWebContentsObserver : public WebContentsObserver {
void OnMediaMutedStatusChanged(RenderFrameHost* render_frame_host,
int delegate_id,
bool muted);
+ void OnPictureInPictureSourceChanged(RenderFrameHost* render_frame_host,
+ int delegate_id);
+ void OnPictureInPictureModeEnded(RenderFrameHost* render_frame_host,
+ int delegate_id);
// Clear |render_frame_host|'s tracking entry for its WakeLocks.
void ClearWakeLocks(RenderFrameHost* render_frame_host);
@@ -124,8 +138,6 @@ class CONTENT_EXPORT MediaWebContentsObserver : public WebContentsObserver {
void MaybeCancelVideoLock();
// Helper methods for adding or removing player entries in |player_map|.
- using PlayerSet = std::set<int>;
- using ActiveMediaPlayerMap = std::map<RenderFrameHost*, PlayerSet>;
void AddMediaPlayerEntry(const MediaPlayerId& id,
ActiveMediaPlayerMap* player_map);
// Returns true if an entry is actually removed.
@@ -146,6 +158,7 @@ class CONTENT_EXPORT MediaWebContentsObserver : public WebContentsObserver {
device::mojom::WakeLockPtr audio_wake_lock_;
device::mojom::WakeLockPtr video_wake_lock_;
base::Optional<MediaPlayerId> fullscreen_player_;
+ base::Optional<MediaPlayerId> pip_player_;
base::Optional<bool> picture_in_picture_allowed_in_fullscreen_;
bool has_audio_wake_lock_for_testing_ = false;
bool has_video_wake_lock_for_testing_ = false;
diff --git a/chromium/content/browser/media/midi_host.cc b/chromium/content/browser/media/midi_host.cc
index ea36120f745..cc77c0a6895 100644
--- a/chromium/content/browser/media/midi_host.cc
+++ b/chromium/content/browser/media/midi_host.cc
@@ -6,7 +6,6 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
-#include "base/memory/ptr_util.h"
#include "base/process/process.h"
#include "base/trace_event/trace_event.h"
#include "content/browser/bad_message.h"
diff --git a/chromium/content/browser/media/session/audio_focus_manager.cc b/chromium/content/browser/media/session/audio_focus_manager.cc
index 92cee28ed71..6a9e7215d5c 100644
--- a/chromium/content/browser/media/session/audio_focus_manager.cc
+++ b/chromium/content/browser/media/session/audio_focus_manager.cc
@@ -4,7 +4,6 @@
#include "content/browser/media/session/audio_focus_manager.h"
-#include "base/memory/ptr_util.h"
#include "content/browser/media/session/media_session_impl.h"
#include "content/public/browser/web_contents.h"
diff --git a/chromium/content/browser/media/session/media_session_impl.cc b/chromium/content/browser/media/session/media_session_impl.cc
index 107932af73d..311371a2770 100644
--- a/chromium/content/browser/media/session/media_session_impl.cc
+++ b/chromium/content/browser/media/session/media_session_impl.cc
@@ -6,7 +6,7 @@
#include <algorithm>
-#include "base/memory/ptr_util.h"
+#include "base/numerics/ranges.h"
#include "content/browser/media/session/audio_focus_delegate.h"
#include "content/browser/media/session/media_session_controller.h"
#include "content/browser/media/session/media_session_player_observer.h"
@@ -17,7 +17,7 @@
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/web_contents.h"
#include "media/base/media_content_type.h"
-#include "third_party/WebKit/public/platform/modules/mediasession/media_session.mojom.h"
+#include "third_party/blink/public/platform/modules/mediasession/media_session.mojom.h"
#if defined(OS_ANDROID)
#include "content/browser/media/session/media_session_android.h"
@@ -29,8 +29,8 @@ using MediaSessionUserAction = MediaSessionUmaHelper::MediaSessionUserAction;
namespace {
-const double kDefaultVolumeMultiplier = 1.0;
-const double kDuckingVolumeMultiplier = 0.2;
+const double kUnduckedVolumeMultiplier = 1.0;
+const double kDefaultDuckingVolumeMultiplier = 0.2;
using MapRenderFrameHostToDepth = std::map<RenderFrameHost*, size_t>;
@@ -423,6 +423,10 @@ bool MediaSessionImpl::IsActuallyPaused() const {
return !IsActive();
}
+void MediaSessionImpl::SetDuckingVolumeMultiplier(double multiplier) {
+ ducking_volume_multiplier_ = base::ClampToRange(multiplier, 0.0, 1.0);
+}
+
void MediaSessionImpl::StartDucking() {
if (is_ducking_)
return;
@@ -445,7 +449,7 @@ void MediaSessionImpl::UpdateVolumeMultiplier() {
}
double MediaSessionImpl::GetVolumeMultiplier() const {
- return is_ducking_ ? kDuckingVolumeMultiplier : kDefaultVolumeMultiplier;
+ return is_ducking_ ? ducking_volume_multiplier_ : kUnduckedVolumeMultiplier;
}
bool MediaSessionImpl::IsActive() const {
@@ -532,7 +536,8 @@ void MediaSessionImpl::OnSuspendInternal(SuspendType suspend_type,
}
for (const auto& it : pepper_players_)
- it.observer->OnSetVolumeMultiplier(it.player_id, kDuckingVolumeMultiplier);
+ it.observer->OnSetVolumeMultiplier(it.player_id,
+ ducking_volume_multiplier_);
NotifyAboutStateChange();
}
@@ -558,6 +563,7 @@ MediaSessionImpl::MediaSessionImpl(WebContents* web_contents)
audio_focus_type_(
AudioFocusManager::AudioFocusType::GainTransientMayDuck),
is_ducking_(false),
+ ducking_volume_multiplier_(kDefaultDuckingVolumeMultiplier),
routed_service_(nullptr) {
#if defined(OS_ANDROID)
session_android_.reset(new MediaSessionAndroid(this));
@@ -713,7 +719,7 @@ void MediaSessionImpl::DidReceiveAction(
for (const auto& player : pepper_players_) {
if (player.observer->render_frame_host() != rfh_of_routed_service) {
player.observer->OnSetVolumeMultiplier(player.player_id,
- kDuckingVolumeMultiplier);
+ ducking_volume_multiplier_);
}
}
for (const auto& player : one_shot_players_) {
diff --git a/chromium/content/browser/media/session/media_session_impl.h b/chromium/content/browser/media/session/media_session_impl.h
index 0bcdca3c3f8..3a681b8b3bc 100644
--- a/chromium/content/browser/media/session/media_session_impl.h
+++ b/chromium/content/browser/media/session/media_session_impl.h
@@ -141,6 +141,9 @@ class MediaSessionImpl : public MediaSession,
// MediaSessionService declared state and guessed state (audio_focus_state_).
CONTENT_EXPORT bool IsActuallyPaused() const override;
+ // Set the volume multiplier applied during ducking.
+ CONTENT_EXPORT void SetDuckingVolumeMultiplier(double multiplier) override;
+
// Let the media session start ducking such that the volume multiplier is
// reduced.
CONTENT_EXPORT void StartDucking() override;
@@ -302,6 +305,8 @@ class MediaSessionImpl : public MediaSession,
// StopDucking().
bool is_ducking_;
+ double ducking_volume_multiplier_;
+
base::CallbackList<void(State)> media_session_state_listeners_;
base::ObserverList<MediaSessionObserver> observers_;
diff --git a/chromium/content/browser/media/session/media_session_impl_browsertest.cc b/chromium/content/browser/media/session/media_session_impl_browsertest.cc
index 7ffbda7158d..df48df6df53 100644
--- a/chromium/content/browser/media/session/media_session_impl_browsertest.cc
+++ b/chromium/content/browser/media/session/media_session_impl_browsertest.cc
@@ -44,6 +44,7 @@ namespace {
const double kDefaultVolumeMultiplier = 1.0;
const double kDuckingVolumeMultiplier = 0.2;
+const double kDifferentDuckingVolumeMultiplier = 0.018;
class MockAudioFocusDelegate : public AudioFocusDelegate {
public:
@@ -314,6 +315,23 @@ IN_PROC_BROWSER_TEST_F(MediaSessionImplBrowserTest,
EXPECT_EQ(kDefaultVolumeMultiplier, player_observer->GetVolumeMultiplier(2));
}
+IN_PROC_BROWSER_TEST_F(MediaSessionImplBrowserTest,
+ DuckingUsesConfiguredMultiplier) {
+ auto player_observer = std::make_unique<MockMediaSessionPlayerObserver>();
+
+ StartNewPlayer(player_observer.get(), media::MediaContentType::Persistent);
+ StartNewPlayer(player_observer.get(), media::MediaContentType::Persistent);
+ media_session_->SetDuckingVolumeMultiplier(kDifferentDuckingVolumeMultiplier);
+ SystemStartDucking();
+ EXPECT_EQ(kDifferentDuckingVolumeMultiplier,
+ player_observer->GetVolumeMultiplier(0));
+ EXPECT_EQ(kDifferentDuckingVolumeMultiplier,
+ player_observer->GetVolumeMultiplier(1));
+ SystemStopDucking();
+ EXPECT_EQ(kDefaultVolumeMultiplier, player_observer->GetVolumeMultiplier(0));
+ EXPECT_EQ(kDefaultVolumeMultiplier, player_observer->GetVolumeMultiplier(1));
+}
+
IN_PROC_BROWSER_TEST_F(MediaSessionImplBrowserTest, AudioFocusInitialState) {
EXPECT_FALSE(IsActive());
}
diff --git a/chromium/content/browser/media/session/media_session_impl_service_routing_unittest.cc b/chromium/content/browser/media/session/media_session_impl_service_routing_unittest.cc
index 7933899da71..e546e116819 100644
--- a/chromium/content/browser/media/session/media_session_impl_service_routing_unittest.cc
+++ b/chromium/content/browser/media/session/media_session_impl_service_routing_unittest.cc
@@ -7,7 +7,6 @@
#include <map>
#include <memory>
-#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/strings/utf_string_conversions.h"
#include "content/browser/media/session/media_session_player_observer.h"
@@ -16,7 +15,7 @@
#include "content/test/test_render_view_host.h"
#include "content/test/test_web_contents.h"
#include "media/base/media_content_type.h"
-#include "third_party/WebKit/public/platform/modules/mediasession/media_session.mojom.h"
+#include "third_party/blink/public/platform/modules/mediasession/media_session.mojom.h"
using ::testing::_;
using ::testing::AnyNumber;
diff --git a/chromium/content/browser/media/session/media_session_impl_uma_unittest.cc b/chromium/content/browser/media/session/media_session_impl_uma_unittest.cc
index cf8d5d35ad2..95e428bd4c6 100644
--- a/chromium/content/browser/media/session/media_session_impl_uma_unittest.cc
+++ b/chromium/content/browser/media/session/media_session_impl_uma_unittest.cc
@@ -13,7 +13,7 @@
#include "content/test/test_render_view_host.h"
#include "content/test/test_web_contents.h"
#include "media/base/media_content_type.h"
-#include "third_party/WebKit/public/platform/modules/mediasession/media_session.mojom.h"
+#include "third_party/blink/public/platform/modules/mediasession/media_session.mojom.h"
namespace content {
diff --git a/chromium/content/browser/media/session/media_session_service_impl.h b/chromium/content/browser/media/session/media_session_service_impl.h
index edcca6dc052..3614d5ee147 100644
--- a/chromium/content/browser/media/session/media_session_service_impl.h
+++ b/chromium/content/browser/media/session/media_session_service_impl.h
@@ -8,7 +8,7 @@
#include "base/optional.h"
#include "content/public/common/media_metadata.h"
#include "mojo/public/cpp/bindings/binding.h"
-#include "third_party/WebKit/public/platform/modules/mediasession/media_session.mojom.h"
+#include "third_party/blink/public/platform/modules/mediasession/media_session.mojom.h"
namespace content {
diff --git a/chromium/content/browser/media/session/media_session_uma_helper.cc b/chromium/content/browser/media/session/media_session_uma_helper.cc
index 10073466529..32195e450cb 100644
--- a/chromium/content/browser/media/session/media_session_uma_helper.cc
+++ b/chromium/content/browser/media/session/media_session_uma_helper.cc
@@ -65,7 +65,8 @@ void MediaSessionUmaHelper::OnSessionInactive() {
total_active_time_ = base::TimeDelta();
}
-void MediaSessionUmaHelper::SetClockForTest(base::TickClock* testing_clock) {
+void MediaSessionUmaHelper::SetClockForTest(
+ const base::TickClock* testing_clock) {
clock_ = testing_clock;
}
diff --git a/chromium/content/browser/media/session/media_session_uma_helper.h b/chromium/content/browser/media/session/media_session_uma_helper.h
index bd928c3e016..99f40c552e9 100644
--- a/chromium/content/browser/media/session/media_session_uma_helper.h
+++ b/chromium/content/browser/media/session/media_session_uma_helper.h
@@ -58,12 +58,12 @@ class CONTENT_EXPORT MediaSessionUmaHelper {
void OnSessionSuspended();
void OnSessionInactive();
- void SetClockForTest(base::TickClock* testing_clock);
+ void SetClockForTest(const base::TickClock* testing_clock);
private:
base::TimeDelta total_active_time_;
base::TimeTicks current_active_time_;
- base::TickClock* clock_;
+ const base::TickClock* clock_;
};
} // namespace content
diff --git a/chromium/content/browser/media/url_provision_fetcher.cc b/chromium/content/browser/media/url_provision_fetcher.cc
index 8cf4c2cec35..e6f57a7964b 100644
--- a/chromium/content/browser/media/url_provision_fetcher.cc
+++ b/chromium/content/browser/media/url_provision_fetcher.cc
@@ -4,7 +4,6 @@
#include "content/browser/media/url_provision_fetcher.h"
-#include "base/memory/ptr_util.h"
#include "content/public/browser/provision_fetcher_factory.h"
#include "media/base/bind_to_current_loop.h"
#include "net/base/load_flags.h"
diff --git a/chromium/content/browser/memory/memory_coordinator_impl.cc b/chromium/content/browser/memory/memory_coordinator_impl.cc
index 8c916774c9d..ad14cde1f5b 100644
--- a/chromium/content/browser/memory/memory_coordinator_impl.cc
+++ b/chromium/content/browser/memory/memory_coordinator_impl.cc
@@ -5,7 +5,6 @@
#include "content/browser/memory/memory_coordinator_impl.h"
#include "base/memory/memory_coordinator_client_registry.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/process/process_handle.h"
#include "base/threading/thread_task_runner_handle.h"
@@ -55,16 +54,6 @@ const char* MemoryConditionToString(MemoryCondition condition) {
return "N/A";
}
-void RecordBrowserPurge(size_t before) {
- auto metrics = base::ProcessMetrics::CreateCurrentProcessMetrics();
- size_t after = metrics->GetWorkingSetSize();
- int64_t bytes = static_cast<int64_t>(before) - static_cast<int64_t>(after);
- if (bytes < 0)
- bytes = 0;
- UMA_HISTOGRAM_MEMORY_LARGE_MB("Memory.Experimental.Browser.PurgedMemory",
- bytes / 1024 / 1024);
-}
-
} // namespace
// The implementation of MemoryCoordinatorHandle. See memory_coordinator.mojom
@@ -236,24 +225,6 @@ bool MemoryCoordinatorImpl::SetChildMemoryState(int render_process_id,
return true;
}
-bool MemoryCoordinatorImpl::TryToPurgeMemoryFromBrowser() {
- base::TimeTicks now = tick_clock_->NowTicks();
- if (can_purge_after_ > now)
- return false;
-
- auto metrics = base::ProcessMetrics::CreateCurrentProcessMetrics();
- size_t before = metrics->GetWorkingSetSize();
- task_runner_->PostDelayedTask(FROM_HERE,
- base::BindOnce(&RecordBrowserPurge, before),
- base::TimeDelta::FromSeconds(2));
-
- // Suppress purging in the browser process until a certain period of time is
- // passed.
- can_purge_after_ = now + base::TimeDelta::FromMinutes(2);
- base::MemoryCoordinatorClientRegistry::GetInstance()->PurgeMemory();
- return true;
-}
-
bool MemoryCoordinatorImpl::TryToPurgeMemoryFromChild(int render_process_id) {
auto iter = children().find(render_process_id);
if (iter == children().end())
@@ -363,7 +334,7 @@ void MemoryCoordinatorImpl::AddChildForTesting(
}
void MemoryCoordinatorImpl::SetTickClockForTesting(
- base::TickClock* tick_clock) {
+ const base::TickClock* tick_clock) {
tick_clock_ = tick_clock;
}
diff --git a/chromium/content/browser/memory/memory_coordinator_impl.h b/chromium/content/browser/memory/memory_coordinator_impl.h
index 8f42d98d386..7291b1e03b3 100644
--- a/chromium/content/browser/memory/memory_coordinator_impl.h
+++ b/chromium/content/browser/memory/memory_coordinator_impl.h
@@ -105,9 +105,6 @@ class CONTENT_EXPORT MemoryCoordinatorImpl : public base::MemoryCoordinator,
// returns false otherwise.
bool SetChildMemoryState(int render_process_id, MemoryState memory_state);
- // Tries to purge memory from the browser process.
- bool TryToPurgeMemoryFromBrowser();
-
// Tries to purge memory from the provided child process.
bool TryToPurgeMemoryFromChild(int render_process_id);
@@ -169,7 +166,7 @@ class CONTENT_EXPORT MemoryCoordinatorImpl : public base::MemoryCoordinator,
mojom::ChildMemoryCoordinatorPtr child);
// Sets a TickClock for testing.
- void SetTickClockForTesting(base::TickClock* tick_clock);
+ void SetTickClockForTesting(const base::TickClock* tick_clock);
// Callback invoked by mojo when the child connection goes down. Exposed
// for testing.
@@ -207,7 +204,7 @@ class CONTENT_EXPORT MemoryCoordinatorImpl : public base::MemoryCoordinator,
std::unique_ptr<MemoryCoordinatorDelegate> delegate_;
std::unique_ptr<MemoryMonitor> memory_monitor_;
std::unique_ptr<MemoryConditionObserver> condition_observer_;
- base::TickClock* tick_clock_;
+ const base::TickClock* tick_clock_;
NotificationRegistrar notification_registrar_;
// The current memory condition.
diff --git a/chromium/content/browser/memory/memory_coordinator_impl_browsertest.cc b/chromium/content/browser/memory/memory_coordinator_impl_browsertest.cc
index fe00ec1f588..9966aafe47a 100644
--- a/chromium/content/browser/memory/memory_coordinator_impl_browsertest.cc
+++ b/chromium/content/browser/memory/memory_coordinator_impl_browsertest.cc
@@ -4,9 +4,9 @@
#include "content/browser/memory/memory_coordinator_impl.h"
-#include "base/memory/ptr_util.h"
#include "base/test/scoped_feature_list.h"
#include "content/browser/browser_main_loop.h"
+#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/public/common/content_features.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
@@ -35,7 +35,20 @@ class MemoryCoordinatorImplBrowserTest : public ContentBrowserTest {
IN_PROC_BROWSER_TEST_F(MemoryCoordinatorImplBrowserTest, HandleAdded) {
GURL url = GetTestUrl("", "simple_page.html");
NavigateToURL(shell(), url);
- size_t num_children = MemoryCoordinatorImpl::GetInstance()->children().size();
+
+ size_t num_children = 0;
+ for (auto const& it : MemoryCoordinatorImpl::GetInstance()->children()) {
+ int process_id = it.first;
+
+ // Ignore the spare process.
+ RenderProcessHost* spare_process =
+ RenderProcessHostImpl::GetSpareRenderProcessHostForTesting();
+ if (spare_process && process_id == spare_process->GetID())
+ continue;
+
+ num_children++;
+ }
+
EXPECT_EQ(1u, num_children);
}
diff --git a/chromium/content/browser/memory/memory_coordinator_impl_unittest.cc b/chromium/content/browser/memory/memory_coordinator_impl_unittest.cc
index 2418018e57c..7cafc26c995 100644
--- a/chromium/content/browser/memory/memory_coordinator_impl_unittest.cc
+++ b/chromium/content/browser/memory/memory_coordinator_impl_unittest.cc
@@ -7,7 +7,6 @@
#include "base/memory/memory_coordinator_client_registry.h"
#include "base/memory/memory_coordinator_proxy.h"
#include "base/memory/memory_pressure_monitor.h"
-#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/test/multiprocess_test.h"
@@ -18,6 +17,7 @@
#include "content/public/common/content_features.h"
#include "content/public/test/mock_render_process_host.h"
#include "content/public/test/test_browser_context.h"
+#include "content/public/test/test_browser_thread_bundle.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -158,9 +158,7 @@ class TestMemoryCoordinatorImpl : public MemoryCoordinatorImpl {
std::make_unique<MockMemoryMonitor>()) {
SetDelegateForTesting(std::make_unique<TestMemoryCoordinatorDelegate>());
SetPolicyForTesting(std::make_unique<MockMemoryCoordinatorPolicy>(this));
-
- clock_ = task_runner->GetMockTickClock();
- SetTickClockForTesting(clock_.get());
+ SetTickClockForTesting(task_runner->GetMockTickClock());
}
~TestMemoryCoordinatorImpl() override {}
@@ -206,10 +204,6 @@ class TestMemoryCoordinatorImpl : public MemoryCoordinatorImpl {
return result;
}
- // TODO(tzik): Remove |clock_| after updating GetMockTickClock to own the
- // instance.
- std::unique_ptr<base::TickClock> clock_;
-
TestBrowserContext browser_context_;
std::vector<std::unique_ptr<Child>> children_;
std::map<int, std::unique_ptr<MockRenderProcessHost>> render_process_hosts_;
@@ -226,7 +220,8 @@ class MemoryCoordinatorImplTest : public base::MultiProcessTest {
scoped_feature_list_.InitAndEnableFeature(features::kMemoryCoordinator);
task_runner_ = new base::TestMockTimeTaskRunner();
- coordinator_.reset(new TestMemoryCoordinatorImpl(task_runner_));
+ thread_bundle_ = std::make_unique<TestBrowserThreadBundle>();
+ coordinator_ = std::make_unique<TestMemoryCoordinatorImpl>(task_runner_);
}
MockMemoryMonitor* GetMockMemoryMonitor() {
@@ -234,10 +229,10 @@ class MemoryCoordinatorImplTest : public base::MultiProcessTest {
}
protected:
- std::unique_ptr<TestMemoryCoordinatorImpl> coordinator_;
- scoped_refptr<base::TestMockTimeTaskRunner> task_runner_;
- base::MessageLoop message_loop_;
base::test::ScopedFeatureList scoped_feature_list_;
+ scoped_refptr<base::TestMockTimeTaskRunner> task_runner_;
+ std::unique_ptr<content::TestBrowserThreadBundle> thread_bundle_;
+ std::unique_ptr<TestMemoryCoordinatorImpl> coordinator_;
};
TEST_F(MemoryCoordinatorImplTest, ChildRemovedOnConnectionError) {
diff --git a/chromium/content/browser/memory/memory_monitor_chromeos.cc b/chromium/content/browser/memory/memory_monitor_chromeos.cc
index b0315ecebfe..64450af8dc9 100644
--- a/chromium/content/browser/memory/memory_monitor_chromeos.cc
+++ b/chromium/content/browser/memory/memory_monitor_chromeos.cc
@@ -4,7 +4,6 @@
#include "content/browser/memory/memory_monitor_chromeos.h"
-#include "base/memory/ptr_util.h"
#include "base/process/process_metrics.h"
namespace content {
diff --git a/chromium/content/browser/memory/memory_monitor_linux.cc b/chromium/content/browser/memory/memory_monitor_linux.cc
index 2901e7f4371..43f108d74c5 100644
--- a/chromium/content/browser/memory/memory_monitor_linux.cc
+++ b/chromium/content/browser/memory/memory_monitor_linux.cc
@@ -4,7 +4,6 @@
#include "content/browser/memory/memory_monitor_linux.h"
-#include "base/memory/ptr_util.h"
#include "base/process/process_metrics.h"
namespace content {
diff --git a/chromium/content/browser/message_port_provider.cc b/chromium/content/browser/message_port_provider.cc
index b419a751813..86ebc20d724 100644
--- a/chromium/content/browser/message_port_provider.cc
+++ b/chromium/content/browser/message_port_provider.cc
@@ -4,11 +4,11 @@
#include "content/public/browser/message_port_provider.h"
-#include "content/browser/browser_thread_impl.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/common/frame_messages.h"
+#include "content/public/browser/browser_thread.h"
#if defined(OS_ANDROID)
#include "base/android/jni_string.h"
diff --git a/chromium/content/browser/mime_registry_impl.cc b/chromium/content/browser/mime_registry_impl.cc
index e5b26a666ac..19a50c1ce71 100644
--- a/chromium/content/browser/mime_registry_impl.cc
+++ b/chromium/content/browser/mime_registry_impl.cc
@@ -5,7 +5,6 @@
#include "content/browser/mime_registry_impl.h"
#include "base/files/file_path.h"
-#include "base/memory/ptr_util.h"
#include "content/public/browser/browser_thread.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "net/base/mime_util.h"
diff --git a/chromium/content/browser/mime_registry_impl.h b/chromium/content/browser/mime_registry_impl.h
index 6424eed48c5..66502353bcf 100644
--- a/chromium/content/browser/mime_registry_impl.h
+++ b/chromium/content/browser/mime_registry_impl.h
@@ -7,7 +7,7 @@
#include "base/macros.h"
#include "base/sequence_checker.h"
-#include "third_party/WebKit/public/platform/mime_registry.mojom.h"
+#include "third_party/blink/public/platform/mime_registry.mojom.h"
namespace content {
diff --git a/chromium/content/browser/mojo_sandbox_browsertest.cc b/chromium/content/browser/mojo_sandbox_browsertest.cc
index 56a44b96ea5..8ec022566d6 100644
--- a/chromium/content/browser/mojo_sandbox_browsertest.cc
+++ b/chromium/content/browser/mojo_sandbox_browsertest.cc
@@ -9,9 +9,10 @@
#include "base/bind.h"
#include "base/macros.h"
#include "base/run_loop.h"
-#include "content/browser/utility_process_host_impl.h"
+#include "content/browser/utility_process_host.h"
+#include "content/browser/utility_process_host_client.h"
#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/utility_process_host_client.h"
+#include "content/public/common/bind_interface_helpers.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/test_service.mojom.h"
#include "services/service_manager/public/cpp/interface_provider.h"
@@ -46,11 +47,11 @@ class MojoSandboxTest : public ContentBrowserTest {
}
protected:
- std::unique_ptr<UtilityProcessHostImpl> host_;
+ std::unique_ptr<UtilityProcessHost> host_;
private:
void StartUtilityProcessOnIoThread() {
- host_.reset(new UtilityProcessHostImpl(nullptr, nullptr));
+ host_.reset(new UtilityProcessHost(nullptr, nullptr));
ASSERT_TRUE(host_->Start());
}
diff --git a/chromium/content/browser/net/accept_header_browsertest.cc b/chromium/content/browser/net/accept_header_browsertest.cc
index 8115f83fc14..d3a6a676497 100644
--- a/chromium/content/browser/net/accept_header_browsertest.cc
+++ b/chromium/content/browser/net/accept_header_browsertest.cc
@@ -16,7 +16,7 @@
#include "content/public/test/content_browser_test_utils.h"
#include "content/shell/browser/shell.h"
#include "net/test/embedded_test_server/http_request.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/test/ppapi/ppapi_test.h"
@@ -149,7 +149,7 @@ IN_PROC_BROWSER_TEST_F(AcceptHeaderTest, Check) {
EXPECT_EQ("custom/type", GetFor("/xhr_with_accept_header"));
shell()->web_contents()->GetManifest(
- base::BindRepeating([](const GURL&, const content::Manifest&) {}));
+ base::BindOnce([](const GURL&, const content::Manifest&) {}));
// RESOURCE_TYPE_SUB_RESOURCE
EXPECT_EQ("*/*", GetFor("/manifest"));
diff --git a/chromium/content/browser/net/network_quality_observer_impl.cc b/chromium/content/browser/net/network_quality_observer_impl.cc
index dfb3e4a3b4c..6dd157e8218 100644
--- a/chromium/content/browser/net/network_quality_observer_impl.cc
+++ b/chromium/content/browser/net/network_quality_observer_impl.cc
@@ -4,7 +4,6 @@
#include "content/browser/net/network_quality_observer_impl.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/common/view_messages.h"
diff --git a/chromium/content/browser/net/network_quality_observer_impl_unittest.cc b/chromium/content/browser/net/network_quality_observer_impl_unittest.cc
index 1112635130e..19e9d677fe8 100644
--- a/chromium/content/browser/net/network_quality_observer_impl_unittest.cc
+++ b/chromium/content/browser/net/network_quality_observer_impl_unittest.cc
@@ -4,10 +4,10 @@
#include "content/browser/net/network_quality_observer_impl.h"
-#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/test/histogram_tester.h"
#include "base/time/time.h"
+#include "content/public/test/test_browser_thread_bundle.h"
#include "net/nqe/effective_connection_type.h"
#include "net/nqe/network_quality_estimator_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -16,7 +16,8 @@ namespace content {
namespace {
TEST(NetworkQualityObserverImplTest, TestObserverNotified) {
- base::MessageLoopForIO message_loop;
+ content::TestBrowserThreadBundle thread_bundle(
+ content::TestBrowserThreadBundle::Options::IO_MAINLOOP);
net::TestNetworkQualityEstimator estimator;
estimator.SetStartTimeNullHttpRtt(base::TimeDelta::FromMilliseconds(1));
@@ -45,4 +46,4 @@ TEST(NetworkQualityObserverImplTest, TestObserverNotified) {
}
} // namespace
-} // namespace content \ No newline at end of file
+} // namespace content
diff --git a/chromium/content/browser/net/quota_policy_cookie_store.cc b/chromium/content/browser/net/quota_policy_cookie_store.cc
index 9eaa19e028d..98068af557c 100644
--- a/chromium/content/browser/net/quota_policy_cookie_store.cc
+++ b/chromium/content/browser/net/quota_policy_cookie_store.cc
@@ -33,24 +33,29 @@ QuotaPolicyCookieStore::QuotaPolicyCookieStore(
}
QuotaPolicyCookieStore::~QuotaPolicyCookieStore() {
+ using CookieOrigin = net::SQLitePersistentCookieStore::CookieOrigin;
if (!special_storage_policy_.get() ||
!special_storage_policy_->HasSessionOnlyOrigins()) {
return;
}
- std::list<net::SQLitePersistentCookieStore::CookieOrigin>
- session_only_cookies;
- for (const auto& cookie : cookies_per_origin_) {
- if (cookie.second == 0) {
+ std::list<CookieOrigin> session_only_cookies;
+ auto delete_cookie_predicate =
+ special_storage_policy_->CreateDeleteCookieOnExitPredicate();
+ DCHECK(delete_cookie_predicate);
+
+ for (const auto& entry : cookies_per_origin_) {
+ if (entry.second == 0) {
continue;
}
- const GURL url(net::cookie_util::CookieOriginToURL(cookie.first.first,
- cookie.first.second));
+ const CookieOrigin& cookie = entry.first;
+ const GURL url(
+ net::cookie_util::CookieOriginToURL(cookie.first, cookie.second));
if (!url.is_valid() ||
- !special_storage_policy_->ShouldDeleteCookieOnExit(url))
+ !delete_cookie_predicate.Run(cookie.first, cookie.second)) {
continue;
-
- session_only_cookies.push_back(cookie.first);
+ }
+ session_only_cookies.push_back(cookie);
}
persistent_store_->DeleteAllInList(session_only_cookies);
diff --git a/chromium/content/browser/net/reporting_service_proxy.cc b/chromium/content/browser/net/reporting_service_proxy.cc
index 99f7d73919a..a729bc91dc4 100644
--- a/chromium/content/browser/net/reporting_service_proxy.cc
+++ b/chromium/content/browser/net/reporting_service_proxy.cc
@@ -18,7 +18,7 @@
#include "net/reporting/reporting_service.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
-#include "third_party/WebKit/public/platform/reporting.mojom.h"
+#include "third_party/blink/public/platform/reporting.mojom.h"
#include "url/gurl.h"
namespace content {
@@ -116,7 +116,10 @@ class ReportingServiceProxyImpl : public blink::mojom::ReportingServiceProxy {
return;
}
- reporting_service->QueueReport(url, group, type, std::move(body));
+ // Depth is only non-zero for NEL reports, and those can't come from the
+ // renderer.
+ reporting_service->QueueReport(url, group, type, std::move(body),
+ /* depth= */ 0);
}
scoped_refptr<net::URLRequestContextGetter> request_context_getter_;
diff --git a/chromium/content/browser/net/reporting_service_proxy.h b/chromium/content/browser/net/reporting_service_proxy.h
index 527830c49f2..cd0f42ea121 100644
--- a/chromium/content/browser/net/reporting_service_proxy.h
+++ b/chromium/content/browser/net/reporting_service_proxy.h
@@ -5,7 +5,7 @@
#ifndef CONTENT_BROWSER_NET_REPORTING_SERVICE_PROXY_H_
#define CONTENT_BROWSER_NET_REPORTING_SERVICE_PROXY_H_
-#include "third_party/WebKit/public/platform/reporting.mojom.h"
+#include "third_party/blink/public/platform/reporting.mojom.h"
namespace content {
diff --git a/chromium/content/browser/network_service_client.cc b/chromium/content/browser/network_service_client.cc
index bcb2ec416db..85848f344f9 100644
--- a/chromium/content/browser/network_service_client.cc
+++ b/chromium/content/browser/network_service_client.cc
@@ -5,15 +5,17 @@
#include "content/browser/network_service_client.h"
#include "base/optional.h"
+#include "content/browser/devtools/devtools_url_loader_interceptor.h"
#include "content/browser/ssl/ssl_client_auth_handler.h"
#include "content/browser/ssl/ssl_error_handler.h"
#include "content/browser/ssl/ssl_manager.h"
#include "content/browser/ssl_private_key_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/browser/browser_context.h"
-#include "content/public/browser/render_frame_host.h"
-#include "content/public/browser/resource_dispatcher_host_login_delegate.h"
+#include "content/public/browser/browser_thread.h"
+#include "content/public/browser/login_delegate.h"
#include "content/public/browser/resource_request_info.h"
+#include "content/public/common/resource_type.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "net/ssl/client_cert_store.h"
@@ -132,9 +134,9 @@ class SSLClientAuthDelegate : public SSLClientAuthHandler::Delegate {
ResourceRequestInfo::WebContentsGetter web_contents_getter) {
std::unique_ptr<net::ClientCertStore> client_cert_store =
GetContentClient()->browser()->CreateClientCertStore(resource_context);
- ssl_client_auth_handler_.reset(
- new SSLClientAuthHandler(std::move(client_cert_store),
- web_contents_getter, cert_info_.get(), this));
+ ssl_client_auth_handler_.reset(new SSLClientAuthHandler(
+ std::move(client_cert_store), std::move(web_contents_getter),
+ cert_info_.get(), this));
ssl_client_auth_handler_->SelectCertificate();
}
@@ -159,6 +161,9 @@ class LoginHandlerDelegate {
ResourceRequestInfo::WebContentsGetter web_contents_getter,
scoped_refptr<net::AuthChallengeInfo> auth_info,
bool is_main_frame,
+ uint32_t process_id,
+ uint32_t routing_id,
+ uint32_t request_id,
const GURL& url,
bool first_auth_attempt)
: callback_(std::move(callback)),
@@ -169,11 +174,31 @@ class LoginHandlerDelegate {
web_contents_getter_(web_contents_getter) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
- base::Bind(&LoginHandlerDelegate::CreateLoginDelegate,
- base::Unretained(this)));
+ base::BindOnce(&LoginHandlerDelegate::DispatchInterceptorHookAndStart,
+ base::Unretained(this), process_id, routing_id,
+ request_id));
}
private:
+ void DispatchInterceptorHookAndStart(uint32_t process_id,
+ uint32_t routing_id,
+ uint32_t request_id) {
+ DevToolsURLLoaderInterceptor::HandleAuthRequest(
+ process_id, routing_id, request_id, auth_info_,
+ base::BindOnce(&LoginHandlerDelegate::ContinueAfterInterceptor,
+ base::Unretained(this)));
+ }
+
+ void ContinueAfterInterceptor(
+ bool use_fallback,
+ const base::Optional<net::AuthCredentials>& auth_credentials) {
+ DCHECK(!(use_fallback && auth_credentials.has_value()));
+ if (use_fallback)
+ CreateLoginDelegate();
+ else
+ RunAuthRequiredCallback(auth_credentials);
+ }
+
void CreateLoginDelegate() {
login_delegate_ = GetContentClient()->browser()->CreateLoginDelegate(
auth_info_.get(), web_contents_getter_, is_main_frame_, url_,
@@ -191,14 +216,8 @@ class LoginHandlerDelegate {
const base::Optional<net::AuthCredentials>& auth_credentials) {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
- base::Bind(&LoginHandlerDelegate::RunCallbackOnUI,
- base::Unretained(this), auth_credentials));
- }
-
- void RunCallbackOnUI(
- const base::Optional<net::AuthCredentials>& auth_credentials) {
- std::move(callback_).Run(auth_credentials);
- BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, this);
+ base::BindOnce(std::move(callback_), auth_credentials));
+ delete this;
}
network::mojom::NetworkServiceClient::OnAuthRequiredCallback callback_;
@@ -207,7 +226,7 @@ class LoginHandlerDelegate {
GURL url_;
bool first_auth_attempt_;
ResourceRequestInfo::WebContentsGetter web_contents_getter_;
- scoped_refptr<ResourceDispatcherHostLoginDelegate> login_delegate_;
+ scoped_refptr<LoginDelegate> login_delegate_;
};
} // namespace
@@ -221,6 +240,8 @@ NetworkServiceClient::~NetworkServiceClient() = default;
void NetworkServiceClient::OnAuthRequired(
uint32_t process_id,
uint32_t routing_id,
+ uint32_t request_id,
+ int32_t resource_type,
const GURL& url,
bool first_auth_attempt,
const scoped_refptr<net::AuthChallengeInfo>& auth_info,
@@ -235,19 +256,18 @@ void NetworkServiceClient::OnAuthRequired(
return;
}
- RenderFrameHost* rfh =
- process_id
- ? RenderFrameHost::FromID(process_id, routing_id)
- : FrameTreeNode::GloballyFindByID(routing_id)->current_frame_host();
- bool is_main_frame = !rfh->GetParent();
- new LoginHandlerDelegate(std::move(callback), web_contents_getter, auth_info,
- is_main_frame, url,
+ bool is_main_frame =
+ static_cast<ResourceType>(resource_type) == RESOURCE_TYPE_MAIN_FRAME;
+ new LoginHandlerDelegate(std::move(callback), std::move(web_contents_getter),
+ auth_info, is_main_frame, process_id, routing_id,
+ request_id, url,
first_auth_attempt); // deletes self
}
void NetworkServiceClient::OnCertificateRequested(
uint32_t process_id,
uint32_t routing_id,
+ uint32_t request_id,
const scoped_refptr<net::SSLCertRequestInfo>& cert_info,
network::mojom::NetworkServiceClient::OnCertificateRequestedCallback
callback) {
@@ -263,15 +283,16 @@ void NetworkServiceClient::OnCertificateRequested(
true /* cancel_certificate_selection */);
return;
}
- new SSLClientAuthDelegate(std::move(callback), web_contents_getter,
+ new SSLClientAuthDelegate(std::move(callback), std::move(web_contents_getter),
cert_info); // deletes self
}
void NetworkServiceClient::OnSSLCertificateError(
- int32_t resource_type,
- const GURL& url,
uint32_t process_id,
uint32_t routing_id,
+ uint32_t request_id,
+ int32_t resource_type,
+ const GURL& url,
const net::SSLInfo& ssl_info,
bool fatal,
OnSSLCertificateErrorCallback response) {
@@ -281,9 +302,9 @@ void NetworkServiceClient::OnSSLCertificateError(
process_id ? base::Bind(WebContentsImpl::FromRenderFrameHostID,
process_id, routing_id)
: base::Bind(WebContents::FromFrameTreeNodeId, routing_id);
- SSLManager::OnSSLCertificateError(delegate->GetWeakPtr(),
- static_cast<ResourceType>(resource_type),
- url, web_contents_getter, ssl_info, fatal);
+ SSLManager::OnSSLCertificateError(
+ delegate->GetWeakPtr(), static_cast<ResourceType>(resource_type), url,
+ std::move(web_contents_getter), ssl_info, fatal);
}
} // namespace content
diff --git a/chromium/content/browser/network_service_client.h b/chromium/content/browser/network_service_client.h
index 59665e92d70..149b307cdd6 100644
--- a/chromium/content/browser/network_service_client.h
+++ b/chromium/content/browser/network_service_client.h
@@ -22,6 +22,8 @@ class NetworkServiceClient : public network::mojom::NetworkServiceClient {
void OnAuthRequired(
uint32_t process_id,
uint32_t routing_id,
+ uint32_t request_id,
+ int32_t resource_type,
const GURL& url,
bool first_auth_attempt,
const scoped_refptr<net::AuthChallengeInfo>& auth_info,
@@ -30,13 +32,15 @@ class NetworkServiceClient : public network::mojom::NetworkServiceClient {
void OnCertificateRequested(
uint32_t process_id,
uint32_t routing_id,
+ uint32_t request_id,
const scoped_refptr<net::SSLCertRequestInfo>& cert_info,
network::mojom::NetworkServiceClient::OnCertificateRequestedCallback
callback) override;
- void OnSSLCertificateError(int32_t resource_type,
- const GURL& url,
- uint32_t process_id,
+ void OnSSLCertificateError(uint32_t process_id,
uint32_t routing_id,
+ uint32_t request_id,
+ int32_t resource_type,
+ const GURL& url,
const net::SSLInfo& ssl_info,
bool fatal,
OnSSLCertificateErrorCallback response) override;
diff --git a/chromium/content/browser/network_service_restart_browsertest.cc b/chromium/content/browser/network_service_restart_browsertest.cc
index affd935d677..6dcb8876dfc 100644
--- a/chromium/content/browser/network_service_restart_browsertest.cc
+++ b/chromium/content/browser/network_service_restart_browsertest.cc
@@ -9,6 +9,7 @@
#include "content/browser/storage_partition_impl.h"
#include "content/browser/url_loader_factory_getter.h"
#include "content/public/browser/browser_context.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_switches.h"
@@ -29,6 +30,9 @@ namespace content {
namespace {
+using SharedURLLoaderFactoryGetterCallback =
+ base::OnceCallback<scoped_refptr<network::SharedURLLoaderFactory>()>;
+
network::mojom::NetworkContextPtr CreateNetworkContext() {
network::mojom::NetworkContextPtr network_context;
network::mojom::NetworkContextParamsPtr context_params =
@@ -38,37 +42,47 @@ network::mojom::NetworkContextPtr CreateNetworkContext() {
return network_context;
}
+network::SimpleURLLoader::BodyAsStringCallback RunOnUIThread(
+ network::SimpleURLLoader::BodyAsStringCallback ui_callback) {
+ return base::BindOnce(
+ [](network::SimpleURLLoader::BodyAsStringCallback callback,
+ std::unique_ptr<std::string> response_body) {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+ BrowserThread::PostTask(
+ BrowserThread::UI, FROM_HERE,
+ base::BindOnce(std::move(callback), std::move(response_body)));
+ },
+ std::move(ui_callback));
+}
+
int LoadBasicRequestOnIOThread(
- URLLoaderFactoryGetter* url_loader_factory_getter,
+ network::mojom::URLLoaderFactory* url_loader_factory,
const GURL& url) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
auto request = std::make_unique<network::ResourceRequest>();
request->url = url;
+ // |simple_loader_helper| lives on UI thread and shouldn't be accessed on
+ // other threads.
SimpleURLLoaderTestHelper simple_loader_helper;
- // Wait for callback on UI thread to avoid nesting IO message loops.
- simple_loader_helper.SetRunLoopQuitThread(BrowserThread::UI);
std::unique_ptr<network::SimpleURLLoader> simple_loader =
network::SimpleURLLoader::Create(std::move(request),
TRAFFIC_ANNOTATION_FOR_TESTS);
- // |URLLoaderFactoryGetter::GetNetworkFactory()| can only be accessed on IO
- // thread.
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(
[](network::SimpleURLLoader* loader,
- URLLoaderFactoryGetter* factory_getter,
+ network::mojom::URLLoaderFactory* factory,
network::SimpleURLLoader::BodyAsStringCallback
body_as_string_callback) {
loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
- factory_getter->GetNetworkFactory(),
- std::move(body_as_string_callback));
+ factory, std::move(body_as_string_callback));
},
base::Unretained(simple_loader.get()),
- base::Unretained(url_loader_factory_getter),
- simple_loader_helper.GetCallback()));
+ base::Unretained(url_loader_factory),
+ RunOnUIThread(simple_loader_helper.GetCallback())));
simple_loader_helper.WaitForCallback();
return simple_loader->NetError();
@@ -91,6 +105,49 @@ int LoadBasicRequestOnUIThread(
return simple_loader->NetError();
}
+scoped_refptr<network::SharedURLLoaderFactory> GetSharedFactoryOnIOThread(
+ SharedURLLoaderFactoryGetterCallback shared_url_loader_factory_getter) {
+ scoped_refptr<network::SharedURLLoaderFactory> shared_factory;
+ base::RunLoop run_loop;
+ BrowserThread::PostTaskAndReply(
+ BrowserThread::IO, FROM_HERE,
+ base::BindOnce(
+ [](SharedURLLoaderFactoryGetterCallback getter,
+ scoped_refptr<network::SharedURLLoaderFactory>*
+ shared_factory_ptr) {
+ *shared_factory_ptr = std::move(getter).Run();
+ },
+ std::move(shared_url_loader_factory_getter),
+ base::Unretained(&shared_factory)),
+ run_loop.QuitClosure());
+ run_loop.Run();
+ return shared_factory;
+}
+
+scoped_refptr<network::SharedURLLoaderFactory> GetSharedFactoryOnIOThread(
+ URLLoaderFactoryGetter* url_loader_factory_getter) {
+ return GetSharedFactoryOnIOThread(
+ base::BindOnce(&URLLoaderFactoryGetter::GetNetworkFactory,
+ base::Unretained(url_loader_factory_getter)));
+}
+
+scoped_refptr<network::SharedURLLoaderFactory> GetSharedFactoryOnIOThread(
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo> info) {
+ return GetSharedFactoryOnIOThread(base::BindOnce(
+ &network::SharedURLLoaderFactory::Create, std::move(info)));
+}
+
+void ReleaseOnIOThread(
+ scoped_refptr<network::SharedURLLoaderFactory> shared_factory) {
+ BrowserThread::PostTask(
+ BrowserThread::IO, FROM_HERE,
+ base::BindOnce(
+ [](scoped_refptr<network::SharedURLLoaderFactory> factory) {
+ factory = nullptr;
+ },
+ std::move(shared_factory)));
+}
+
} // namespace
// This test source has been excluded from Android as Android doesn't have
@@ -301,8 +358,13 @@ IN_PROC_BROWSER_TEST_F(NetworkServiceRestartBrowserTest,
BrowserContext::GetDefaultStoragePartition(browser_context()));
scoped_refptr<URLLoaderFactoryGetter> url_loader_factory_getter =
partition->url_loader_factory_getter();
- EXPECT_EQ(net::OK, LoadBasicRequestOnIOThread(url_loader_factory_getter.get(),
- GetTestURL()));
+
+ scoped_refptr<network::SharedURLLoaderFactory> shared_factory =
+ GetSharedFactoryOnIOThread(url_loader_factory_getter.get());
+ EXPECT_EQ(net::OK,
+ LoadBasicRequestOnIOThread(shared_factory.get(), GetTestURL()));
+ ReleaseOnIOThread(std::move(shared_factory));
+
// Crash the NetworkService process. Existing interfaces should receive error
// notifications at some point.
SimulateNetworkServiceCrash();
@@ -312,8 +374,61 @@ IN_PROC_BROWSER_TEST_F(NetworkServiceRestartBrowserTest,
// |url_loader_factory_getter| should be able to get a valid new pointer after
// crash.
- EXPECT_EQ(net::OK, LoadBasicRequestOnIOThread(url_loader_factory_getter.get(),
- GetTestURL()));
+ shared_factory = GetSharedFactoryOnIOThread(url_loader_factory_getter.get());
+ EXPECT_EQ(net::OK,
+ LoadBasicRequestOnIOThread(shared_factory.get(), GetTestURL()));
+ ReleaseOnIOThread(std::move(shared_factory));
+}
+
+// Make sure the factory returned from
+// |URLLoaderFactoryGetter::GetNetworkFactory()| continues to work after
+// crashes.
+IN_PROC_BROWSER_TEST_F(NetworkServiceRestartBrowserTest,
+ BrowserIOSharedURLLoaderFactory) {
+ StoragePartitionImpl* partition = static_cast<StoragePartitionImpl*>(
+ BrowserContext::GetDefaultStoragePartition(browser_context()));
+
+ scoped_refptr<network::SharedURLLoaderFactory> shared_factory =
+ GetSharedFactoryOnIOThread(partition->url_loader_factory_getter().get());
+
+ EXPECT_EQ(net::OK,
+ LoadBasicRequestOnIOThread(shared_factory.get(), GetTestURL()));
+
+ // Crash the NetworkService process. Existing interfaces should receive error
+ // notifications at some point.
+ SimulateNetworkServiceCrash();
+ // Flush the interface to make sure the error notification was received.
+ partition->FlushNetworkInterfaceForTesting();
+ partition->url_loader_factory_getter()
+ ->FlushNetworkInterfaceOnIOThreadForTesting();
+
+ // |shared_factory| should continue to work.
+ EXPECT_EQ(net::OK,
+ LoadBasicRequestOnIOThread(shared_factory.get(), GetTestURL()));
+ ReleaseOnIOThread(std::move(shared_factory));
+}
+
+// Make sure the factory returned from
+// |URLLoaderFactoryGetter::GetNetworkFactory()| doesn't crash if
+// it's called after the StoragePartition is deleted.
+IN_PROC_BROWSER_TEST_F(NetworkServiceRestartBrowserTest,
+ BrowserIOSharedFactoryAfterStoragePartitionGone) {
+ base::ScopedAllowBlockingForTesting allow_blocking;
+ std::unique_ptr<ShellBrowserContext> browser_context =
+ std::make_unique<ShellBrowserContext>(true, nullptr);
+ auto* partition = static_cast<StoragePartitionImpl*>(
+ BrowserContext::GetDefaultStoragePartition(browser_context.get()));
+ scoped_refptr<network::SharedURLLoaderFactory> shared_factory(
+ GetSharedFactoryOnIOThread(partition->url_loader_factory_getter().get()));
+
+ EXPECT_EQ(net::OK,
+ LoadBasicRequestOnIOThread(shared_factory.get(), GetTestURL()));
+
+ browser_context.reset();
+
+ EXPECT_EQ(net::ERR_FAILED,
+ LoadBasicRequestOnIOThread(shared_factory.get(), GetTestURL()));
+ ReleaseOnIOThread(std::move(shared_factory));
}
// Make sure basic navigation works after crash.
@@ -387,7 +502,7 @@ IN_PROC_BROWSER_TEST_F(NetworkServiceRestartBrowserTest,
std::make_unique<ShellBrowserContext>(true, nullptr);
auto* partition =
BrowserContext::GetDefaultStoragePartition(browser_context.get());
- scoped_refptr<content::SharedURLLoaderFactory> factory(
+ scoped_refptr<network::SharedURLLoaderFactory> factory(
partition->GetURLLoaderFactoryForBrowserProcess());
EXPECT_EQ(net::OK, LoadBasicRequestOnUIThread(factory.get(), GetTestURL()));
@@ -398,6 +513,80 @@ IN_PROC_BROWSER_TEST_F(NetworkServiceRestartBrowserTest,
LoadBasicRequestOnUIThread(factory.get(), GetTestURL()));
}
+// Make sure the factory returned from
+// |StoragePartition::GetURLLoaderFactoryForBrowserProcessIOThread()| continues
+// to work after crashes.
+IN_PROC_BROWSER_TEST_F(NetworkServiceRestartBrowserTest, BrowserIOFactory) {
+ auto* partition =
+ BrowserContext::GetDefaultStoragePartition(browser_context());
+ scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory =
+ GetSharedFactoryOnIOThread(
+ partition->GetURLLoaderFactoryForBrowserProcessIOThread());
+
+ EXPECT_EQ(net::OK, LoadBasicRequestOnIOThread(shared_url_loader_factory.get(),
+ GetTestURL()));
+
+ SimulateNetworkServiceCrash();
+ // Flush the interface to make sure the error notification was received.
+ partition->FlushNetworkInterfaceForTesting();
+ static_cast<StoragePartitionImpl*>(partition)
+ ->url_loader_factory_getter()
+ ->FlushNetworkInterfaceOnIOThreadForTesting();
+
+ EXPECT_EQ(net::OK, LoadBasicRequestOnIOThread(shared_url_loader_factory.get(),
+ GetTestURL()));
+ ReleaseOnIOThread(std::move(shared_url_loader_factory));
+}
+
+// Make sure the factory getter returned from
+// |StoragePartition::GetURLLoaderFactoryForBrowserProcessIOThread()| doesn't
+// crash if it's called after the StoragePartition is deleted.
+IN_PROC_BROWSER_TEST_F(NetworkServiceRestartBrowserTest,
+ BrowserIOFactoryGetterAfterStoragePartitionGone) {
+ base::ScopedAllowBlockingForTesting allow_blocking;
+ std::unique_ptr<ShellBrowserContext> browser_context =
+ std::make_unique<ShellBrowserContext>(true, nullptr);
+ auto* partition =
+ BrowserContext::GetDefaultStoragePartition(browser_context.get());
+ auto shared_url_loader_factory_info =
+ partition->GetURLLoaderFactoryForBrowserProcessIOThread();
+
+ browser_context.reset();
+
+ scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory =
+ GetSharedFactoryOnIOThread(std::move(shared_url_loader_factory_info));
+
+ EXPECT_EQ(net::ERR_FAILED,
+ LoadBasicRequestOnIOThread(shared_url_loader_factory.get(),
+ GetTestURL()));
+ ReleaseOnIOThread(std::move(shared_url_loader_factory));
+}
+
+// Make sure the factory returned from
+// |StoragePartition::GetURLLoaderFactoryForBrowserProcessIOThread()| doesn't
+// crash if it's called after the StoragePartition is deleted.
+IN_PROC_BROWSER_TEST_F(NetworkServiceRestartBrowserTest,
+ BrowserIOFactoryAfterStoragePartitionGone) {
+ base::ScopedAllowBlockingForTesting allow_blocking;
+ std::unique_ptr<ShellBrowserContext> browser_context =
+ std::make_unique<ShellBrowserContext>(true, nullptr);
+ auto* partition =
+ BrowserContext::GetDefaultStoragePartition(browser_context.get());
+ scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory =
+ GetSharedFactoryOnIOThread(
+ partition->GetURLLoaderFactoryForBrowserProcessIOThread());
+
+ EXPECT_EQ(net::OK, LoadBasicRequestOnIOThread(shared_url_loader_factory.get(),
+ GetTestURL()));
+
+ browser_context.reset();
+
+ EXPECT_EQ(net::ERR_FAILED,
+ LoadBasicRequestOnIOThread(shared_url_loader_factory.get(),
+ GetTestURL()));
+ ReleaseOnIOThread(std::move(shared_url_loader_factory));
+}
+
// Make sure the window from |window.open()| can load XHR after crash.
IN_PROC_BROWSER_TEST_F(NetworkServiceRestartBrowserTest, WindowOpenXHR) {
StoragePartitionImpl* partition = static_cast<StoragePartitionImpl*>(
diff --git a/chromium/content/browser/notifications/DEPS b/chromium/content/browser/notifications/DEPS
index adad170be21..a8b95f1e113 100644
--- a/chromium/content/browser/notifications/DEPS
+++ b/chromium/content/browser/notifications/DEPS
@@ -1,4 +1,4 @@
include_rules = [
"+third_party/leveldatabase",
- "+third_party/WebKit/public/platform/modules/notifications/notification_service.mojom.h",
+ "+third_party/blink/public/platform/modules/notifications/notification_service.mojom.h",
]
diff --git a/chromium/content/browser/notifications/OWNERS b/chromium/content/browser/notifications/OWNERS
index 81314bdfb3a..c172d4bfa29 100644
--- a/chromium/content/browser/notifications/OWNERS
+++ b/chromium/content/browser/notifications/OWNERS
@@ -4,8 +4,8 @@
# //content/renderer/notifications/
# //content/test/mock_platform_notification_service.*
+awdf@chromium.org
mkwst@chromium.org
-mvanouwerkerk@chromium.org
peter@chromium.org
# TEAM: platform-capabilities@chromium.org
diff --git a/chromium/content/browser/notifications/blink_notification_service_impl.cc b/chromium/content/browser/notifications/blink_notification_service_impl.cc
index 7bbfd53c36c..605a9ed20ce 100644
--- a/chromium/content/browser/notifications/blink_notification_service_impl.cc
+++ b/chromium/content/browser/notifications/blink_notification_service_impl.cc
@@ -10,6 +10,7 @@
#include "base/strings/string16.h"
#include "content/browser/notifications/notification_event_dispatcher_impl.h"
#include "content/browser/notifications/platform_notification_context_impl.h"
+#include "content/common/service_worker/service_worker_status_code.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/notification_database_data.h"
@@ -17,7 +18,7 @@
#include "content/public/common/content_client.h"
#include "content/public/common/notification_resources.h"
#include "content/public/common/platform_notification_data.h"
-#include "third_party/WebKit/public/platform/modules/permissions/permission_status.mojom.h"
+#include "third_party/blink/public/platform/modules/permissions/permission_status.mojom.h"
#include "url/gurl.h"
namespace content {
@@ -35,12 +36,14 @@ BlinkNotificationServiceImpl::BlinkNotificationServiceImpl(
PlatformNotificationContextImpl* notification_context,
BrowserContext* browser_context,
ResourceContext* resource_context,
+ scoped_refptr<ServiceWorkerContextWrapper> service_worker_context,
int render_process_id,
const url::Origin& origin,
mojo::InterfaceRequest<blink::mojom::NotificationService> request)
: notification_context_(notification_context),
browser_context_(browser_context),
resource_context_(resource_context),
+ service_worker_context_(std::move(service_worker_context)),
render_process_id_(render_process_id),
origin_(origin),
binding_(this, std::move(request)),
@@ -188,25 +191,100 @@ void BlinkNotificationServiceImpl::DisplayPersistentNotificationWithId(
DisplayPersistentNotificationCallback callback,
bool success,
const std::string& notification_id) {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+
if (!success) {
std::move(callback).Run(
blink::mojom::PersistentNotificationError::INTERNAL_ERROR);
return;
}
+ service_worker_context_->FindReadyRegistrationForId(
+ service_worker_registration_id, origin_.GetURL(),
+ base::BindOnce(&BlinkNotificationServiceImpl::
+ DisplayPersistentNotificationWithIdForServiceWorker,
+ weak_ptr_factory_.GetWeakPtr(), notification_id,
+ platform_notification_data, notification_resources,
+ std::move(callback)));
+}
+
+void BlinkNotificationServiceImpl::
+ DisplayPersistentNotificationWithIdForServiceWorker(
+ const std::string& notification_id,
+ const PlatformNotificationData& platform_notification_data,
+ const NotificationResources& notification_resources,
+ DisplayPersistentNotificationCallback callback,
+ content::ServiceWorkerStatusCode service_worker_status,
+ scoped_refptr<content::ServiceWorkerRegistration> registration) {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+
+ if (service_worker_status != SERVICE_WORKER_OK) {
+ std::move(callback).Run(
+ blink::mojom::PersistentNotificationError::INTERNAL_ERROR);
+ LOG(ERROR) << "Registration not found for " << origin_.GetURL().spec();
+ // TODO(peter): Add UMA to track how often this occurs.
+ return;
+ }
+
+ if (registration->pattern().GetOrigin() != origin_.GetURL()) {
+ // Bail out, something's wrong.
+ std::move(callback).Run(
+ blink::mojom::PersistentNotificationError::INTERNAL_ERROR);
+ return;
+ }
+
// Using base::Unretained here is safe because Service() returns a singleton.
- // TODO(https://crbug.com/796991): Get service worker registration from its
- // ID, and pass the service worker scope (instead of the origin twice) below.
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::BindOnce(
&PlatformNotificationService::DisplayPersistentNotification,
base::Unretained(Service()), browser_context_, notification_id,
- origin_.GetURL() /* service_worker_scope */,
- origin_.GetURL() /* origin */, platform_notification_data,
+ registration->pattern(), origin_.GetURL(), platform_notification_data,
notification_resources));
std::move(callback).Run(blink::mojom::PersistentNotificationError::NONE);
}
+void BlinkNotificationServiceImpl::GetNotifications(
+ int64_t service_worker_registration_id,
+ const std::string& filter_tag,
+ GetNotificationsCallback callback) {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+
+ if (CheckPermissionStatus() != blink::mojom::PermissionStatus::GRANTED) {
+ // No permission has been granted for the given origin. It is harmless to
+ // try to get notifications without permission, so return empty vectors
+ // indicating that no (accessible) notifications exist at this time.
+ std::move(callback).Run(std::vector<std::string>(),
+ std::vector<PlatformNotificationData>());
+ return;
+ }
+
+ notification_context_->ReadAllNotificationDataForServiceWorkerRegistration(
+ origin_.GetURL(), service_worker_registration_id,
+ base::AdaptCallbackForRepeating(base::BindOnce(
+ &BlinkNotificationServiceImpl::DidGetNotifications,
+ weak_ptr_factory_.GetWeakPtr(), filter_tag, std::move(callback))));
+}
+
+void BlinkNotificationServiceImpl::DidGetNotifications(
+ const std::string& filter_tag,
+ GetNotificationsCallback callback,
+ bool success,
+ const std::vector<NotificationDatabaseData>& notifications) {
+ std::vector<std::string> ids;
+ std::vector<PlatformNotificationData> datas;
+
+ for (const NotificationDatabaseData& database_data : notifications) {
+ // An empty filter tag matches all, else we need an exact match.
+ if (filter_tag.empty() ||
+ filter_tag == database_data.notification_data.tag) {
+ ids.push_back(database_data.notification_id);
+ datas.push_back(database_data.notification_data);
+ }
+ }
+
+ std::move(callback).Run(ids, datas);
+}
+
} // namespace content
diff --git a/chromium/content/browser/notifications/blink_notification_service_impl.h b/chromium/content/browser/notifications/blink_notification_service_impl.h
index 5453d9d6c58..98819833d8c 100644
--- a/chromium/content/browser/notifications/blink_notification_service_impl.h
+++ b/chromium/content/browser/notifications/blink_notification_service_impl.h
@@ -7,15 +7,17 @@
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
+#include "content/browser/service_worker/service_worker_context_wrapper.h"
#include "content/common/content_export.h"
#include "content/public/browser/browser_context.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "mojo/public/cpp/bindings/interface_request.h"
-#include "third_party/WebKit/public/platform/modules/notifications/notification_service.mojom.h"
+#include "third_party/blink/public/platform/modules/notifications/notification_service.mojom.h"
#include "url/origin.h"
namespace content {
+struct NotificationDatabaseData;
class PlatformNotificationContextImpl;
struct PlatformNotificationData;
class ResourceContext;
@@ -30,6 +32,7 @@ class CONTENT_EXPORT BlinkNotificationServiceImpl
PlatformNotificationContextImpl* notification_context,
BrowserContext* browser_context,
ResourceContext* resource_context,
+ scoped_refptr<ServiceWorkerContextWrapper> service_worker_context,
int render_process_id,
const url::Origin& origin,
mojo::InterfaceRequest<blink::mojom::NotificationService> request);
@@ -48,6 +51,9 @@ class CONTENT_EXPORT BlinkNotificationServiceImpl
const PlatformNotificationData& platform_notification_data,
const NotificationResources& notification_resources,
DisplayPersistentNotificationCallback) override;
+ void GetNotifications(int64_t service_worker_registration_id,
+ const std::string& filter_tag,
+ GetNotificationsCallback callback) override;
private:
// Called when an error is detected on binding_.
@@ -68,11 +74,25 @@ class CONTENT_EXPORT BlinkNotificationServiceImpl
bool success,
const std::string& notification_id);
+ void DisplayPersistentNotificationWithIdForServiceWorker(
+ const std::string& notification_id,
+ const PlatformNotificationData& platform_notification_data,
+ const NotificationResources& notification_resources,
+ DisplayPersistentNotificationCallback callback,
+ content::ServiceWorkerStatusCode service_worker_status,
+ scoped_refptr<content::ServiceWorkerRegistration> registration);
+
void CloseNonPersistentNotificationOnUIThread(
const std::string& notification_id);
blink::mojom::PermissionStatus CheckPermissionStatus();
+ void DidGetNotifications(
+ const std::string& filter_tag,
+ GetNotificationsCallback callback,
+ bool success,
+ const std::vector<NotificationDatabaseData>& notifications);
+
// The notification context that owns this service instance.
PlatformNotificationContextImpl* notification_context_;
@@ -80,6 +100,8 @@ class CONTENT_EXPORT BlinkNotificationServiceImpl
ResourceContext* resource_context_;
+ scoped_refptr<ServiceWorkerContextWrapper> service_worker_context_;
+
int render_process_id_;
// The origin that this notification service is communicating with.
diff --git a/chromium/content/browser/notifications/blink_notification_service_impl_unittest.cc b/chromium/content/browser/notifications/blink_notification_service_impl_unittest.cc
index 66064f1b673..e171e48bf69 100644
--- a/chromium/content/browser/notifications/blink_notification_service_impl_unittest.cc
+++ b/chromium/content/browser/notifications/blink_notification_service_impl_unittest.cc
@@ -7,6 +7,7 @@
#include <vector>
#include "base/callback_forward.h"
+#include "base/callback_helpers.h"
#include "base/macros.h"
#include "base/memory/scoped_refptr.h"
#include "base/run_loop.h"
@@ -14,7 +15,9 @@
#include "base/threading/thread_task_runner_handle.h"
#include "content/browser/notifications/blink_notification_service_impl.h"
#include "content/browser/notifications/platform_notification_context_impl.h"
+#include "content/browser/service_worker/embedded_worker_test_helper.h"
#include "content/browser/service_worker/service_worker_context_wrapper.h"
+#include "content/common/service_worker/service_worker_types.h"
#include "content/public/test/mock_resource_context.h"
#include "content/public/test/test_browser_context.h"
#include "content/public/test/test_browser_thread_bundle.h"
@@ -24,16 +27,17 @@
#include "mojo/public/cpp/bindings/binding.h"
#include "mojo/public/cpp/bindings/interface_request.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/modules/notifications/notification_service.mojom.h"
-#include "third_party/WebKit/public/platform/modules/permissions/permission_status.mojom.h"
+#include "third_party/blink/public/platform/modules/notifications/notification_service.mojom.h"
+#include "third_party/blink/public/platform/modules/permissions/permission_status.mojom.h"
namespace content {
namespace {
const int kFakeRenderProcessId = 1;
+
const char kTestOrigin[] = "https://example.com";
-const int64_t kFakeServiceWorkerRegistrationId = 1234;
+const char kTestServiceWorkerUrl[] = "https://example.com/sw.js";
class MockNonPersistentNotificationListener
: public blink::mojom::NonPersistentNotificationListener {
@@ -79,6 +83,8 @@ class BlinkNotificationServiceImplTest : public ::testing::Test {
// at time of writing EmbeddedWorkerTestHelper didn't seem to support that.
BlinkNotificationServiceImplTest()
: thread_bundle_(TestBrowserThreadBundle::IO_MAINLOOP),
+ embedded_worker_helper_(
+ std::make_unique<EmbeddedWorkerTestHelper>(base::FilePath())),
notification_browser_client_(&mock_platform_service_) {
SetBrowserClientForTesting(&notification_browser_client_);
}
@@ -89,7 +95,7 @@ class BlinkNotificationServiceImplTest : public ::testing::Test {
void SetUp() override {
notification_context_ = new PlatformNotificationContextImpl(
base::FilePath(), &browser_context_,
- nullptr /* service_worker_context */);
+ embedded_worker_helper_->context_wrapper());
notification_context_->Initialize();
// Wait for notification context to be initialized to avoid TSAN detecting
@@ -100,10 +106,88 @@ class BlinkNotificationServiceImplTest : public ::testing::Test {
blink::mojom::NotificationServicePtr notification_service_ptr;
notification_service_ = std::make_unique<BlinkNotificationServiceImpl>(
notification_context_.get(), &browser_context_, &resource_context_,
- kFakeRenderProcessId, url::Origin::Create(GURL(kTestOrigin)),
+ embedded_worker_helper_->context_wrapper(), kFakeRenderProcessId,
+ url::Origin::Create(GURL(kTestOrigin)),
mojo::MakeRequest(&notification_service_ptr));
}
+ void TearDown() override {
+ embedded_worker_helper_.reset();
+
+ // Give pending shutdown operations a chance to finish.
+ base::RunLoop().RunUntilIdle();
+ }
+
+ void RegisterServiceWorker(
+ scoped_refptr<ServiceWorkerRegistration>* service_worker_registration) {
+ int64_t service_worker_registration_id =
+ blink::mojom::kInvalidServiceWorkerRegistrationId;
+
+ blink::mojom::ServiceWorkerRegistrationOptions options;
+ options.scope = GURL(kTestOrigin);
+
+ {
+ base::RunLoop run_loop;
+ embedded_worker_helper_->context()->RegisterServiceWorker(
+ GURL(kTestServiceWorkerUrl), options,
+ base::AdaptCallbackForRepeating(base::BindOnce(
+ &BlinkNotificationServiceImplTest::DidRegisterServiceWorker,
+ base::Unretained(this), &service_worker_registration_id,
+ run_loop.QuitClosure())));
+ run_loop.Run();
+ }
+
+ if (service_worker_registration_id ==
+ blink::mojom::kInvalidServiceWorkerRegistrationId) {
+ ADD_FAILURE() << "Could not obtain a valid Service Worker registration";
+ }
+
+ {
+ base::RunLoop run_loop;
+ embedded_worker_helper_->context()->storage()->FindRegistrationForId(
+ service_worker_registration_id, GURL(kTestOrigin),
+ base::BindOnce(&BlinkNotificationServiceImplTest::
+ DidFindServiceWorkerRegistration,
+ base::Unretained(this), service_worker_registration,
+ run_loop.QuitClosure()));
+
+ run_loop.Run();
+ }
+
+ // Wait for the worker to be activated.
+ base::RunLoop().RunUntilIdle();
+
+ if (!*service_worker_registration) {
+ ADD_FAILURE() << "Could not find the new Service Worker registration.";
+ }
+ }
+
+ void DidRegisterServiceWorker(int64_t* out_service_worker_registration_id,
+ base::OnceClosure quit_closure,
+ ServiceWorkerStatusCode status,
+ const std::string& status_message,
+ int64_t service_worker_registration_id) {
+ DCHECK(out_service_worker_registration_id);
+ EXPECT_EQ(SERVICE_WORKER_OK, status) << ServiceWorkerStatusToString(status);
+
+ *out_service_worker_registration_id = service_worker_registration_id;
+
+ std::move(quit_closure).Run();
+ }
+
+ void DidFindServiceWorkerRegistration(
+ scoped_refptr<ServiceWorkerRegistration>* out_service_worker_registration,
+ base::OnceClosure quit_closure,
+ ServiceWorkerStatusCode status,
+ scoped_refptr<ServiceWorkerRegistration> service_worker_registration) {
+ DCHECK(out_service_worker_registration);
+ EXPECT_EQ(SERVICE_WORKER_OK, status) << ServiceWorkerStatusToString(status);
+
+ *out_service_worker_registration = service_worker_registration;
+
+ std::move(quit_closure).Run();
+ }
+
void DidGetPermissionStatus(
blink::mojom::PermissionStatus permission_status) {
permission_callback_result_ = permission_status;
@@ -120,6 +204,14 @@ class BlinkNotificationServiceImplTest : public ::testing::Test {
std::move(quit_closure).Run();
}
+ void DidGetNotifications(
+ base::OnceClosure quit_closure,
+ const std::vector<std::string>& notification_ids,
+ const std::vector<PlatformNotificationData>& notification_datas) {
+ get_notifications_callback_result_ = notification_ids;
+ std::move(quit_closure).Run();
+ }
+
void DidGetDisplayedNotifications(
base::OnceClosure quit_closure,
std::unique_ptr<std::set<std::string>> notification_ids,
@@ -128,17 +220,32 @@ class BlinkNotificationServiceImplTest : public ::testing::Test {
std::move(quit_closure).Run();
}
- void DisplayPersistentNotificationSync() {
+ void DisplayPersistentNotificationSync(
+ int64_t service_worker_registration_id,
+ const PlatformNotificationData& platform_notification_data,
+ const NotificationResources& notification_resources) {
base::RunLoop run_loop;
notification_service_->DisplayPersistentNotification(
- kFakeServiceWorkerRegistrationId, PlatformNotificationData(),
- NotificationResources(),
+ service_worker_registration_id, platform_notification_data,
+ notification_resources,
base::BindOnce(
&BlinkNotificationServiceImplTest::DidDisplayPersistentNotification,
base::Unretained(this), run_loop.QuitClosure()));
run_loop.Run();
}
+ std::vector<std::string> GetNotificationsSync(
+ int64_t service_worker_registration_id,
+ const std::string& filter_tag) {
+ base::RunLoop run_loop;
+ notification_service_->GetNotifications(
+ service_worker_registration_id, filter_tag,
+ base::BindOnce(&BlinkNotificationServiceImplTest::DidGetNotifications,
+ base::Unretained(this), run_loop.QuitClosure()));
+ run_loop.Run();
+ return get_notifications_callback_result_;
+ }
+
// Synchronous wrapper of
// PlatformNotificationService::GetDisplayedNotifications
std::set<std::string> GetDisplayedNotifications() {
@@ -155,6 +262,8 @@ class BlinkNotificationServiceImplTest : public ::testing::Test {
protected:
TestBrowserThreadBundle thread_bundle_; // Must be first member.
+ std::unique_ptr<EmbeddedWorkerTestHelper> embedded_worker_helper_;
+
std::unique_ptr<BlinkNotificationServiceImpl> notification_service_;
TestBrowserContext browser_context_;
@@ -175,6 +284,8 @@ class BlinkNotificationServiceImplTest : public ::testing::Test {
std::set<std::string> get_displayed_callback_result_;
+ std::vector<std::string> get_notifications_callback_result_;
+
MockResourceContext resource_context_;
DISALLOW_COPY_AND_ASSIGN(BlinkNotificationServiceImplTest);
@@ -245,7 +356,11 @@ TEST_F(BlinkNotificationServiceImplTest,
DisplayPersistentNotificationWithPermission) {
mock_platform_service_.SetPermission(blink::mojom::PermissionStatus::GRANTED);
- DisplayPersistentNotificationSync();
+ scoped_refptr<ServiceWorkerRegistration> registration;
+ RegisterServiceWorker(&registration);
+
+ DisplayPersistentNotificationSync(
+ registration->id(), PlatformNotificationData(), NotificationResources());
EXPECT_EQ(blink::mojom::PersistentNotificationError::NONE,
display_persistent_callback_result_);
@@ -260,7 +375,11 @@ TEST_F(BlinkNotificationServiceImplTest,
DisplayPersistentNotificationWithoutPermission) {
mock_platform_service_.SetPermission(blink::mojom::PermissionStatus::DENIED);
- DisplayPersistentNotificationSync();
+ scoped_refptr<ServiceWorkerRegistration> registration;
+ RegisterServiceWorker(&registration);
+
+ DisplayPersistentNotificationSync(
+ registration->id(), PlatformNotificationData(), NotificationResources());
EXPECT_EQ(blink::mojom::PersistentNotificationError::PERMISSION_DENIED,
display_persistent_callback_result_);
@@ -275,13 +394,85 @@ TEST_F(BlinkNotificationServiceImplTest,
DisplayMultiplePersistentNotifications) {
mock_platform_service_.SetPermission(blink::mojom::PermissionStatus::GRANTED);
- DisplayPersistentNotificationSync();
+ scoped_refptr<ServiceWorkerRegistration> registration;
+ RegisterServiceWorker(&registration);
+
+ DisplayPersistentNotificationSync(
+ registration->id(), PlatformNotificationData(), NotificationResources());
- DisplayPersistentNotificationSync();
+ DisplayPersistentNotificationSync(
+ registration->id(), PlatformNotificationData(), NotificationResources());
// Wait for service to receive all the Display calls.
RunAllTasksUntilIdle();
EXPECT_EQ(2u, GetDisplayedNotifications().size());
}
+
+TEST_F(BlinkNotificationServiceImplTest, GetNotifications) {
+ mock_platform_service_.SetPermission(blink::mojom::PermissionStatus::GRANTED);
+
+ scoped_refptr<ServiceWorkerRegistration> registration;
+ RegisterServiceWorker(&registration);
+
+ EXPECT_EQ(
+ 0u, GetNotificationsSync(registration->id(), "" /* filter_tag */).size());
+
+ DisplayPersistentNotificationSync(
+ registration->id(), PlatformNotificationData(), NotificationResources());
+
+ // Wait for service to receive all the Display calls.
+ RunAllTasksUntilIdle();
+
+ EXPECT_EQ(
+ 1u, GetNotificationsSync(registration->id(), "" /* filter_tag */).size());
+}
+
+TEST_F(BlinkNotificationServiceImplTest, GetNotificationsWithoutPermission) {
+ mock_platform_service_.SetPermission(blink::mojom::PermissionStatus::GRANTED);
+
+ scoped_refptr<ServiceWorkerRegistration> registration;
+ RegisterServiceWorker(&registration);
+
+ DisplayPersistentNotificationSync(
+ registration->id(), PlatformNotificationData(), NotificationResources());
+
+ // Wait for service to receive all the Display calls.
+ RunAllTasksUntilIdle();
+
+ mock_platform_service_.SetPermission(blink::mojom::PermissionStatus::DENIED);
+
+ EXPECT_EQ(
+ 0u, GetNotificationsSync(registration->id(), "" /* filter_tag */).size());
+}
+
+TEST_F(BlinkNotificationServiceImplTest, GetNotificationsWithFilter) {
+ mock_platform_service_.SetPermission(blink::mojom::PermissionStatus::GRANTED);
+
+ scoped_refptr<ServiceWorkerRegistration> registration;
+ RegisterServiceWorker(&registration);
+
+ PlatformNotificationData platform_notification_data;
+ platform_notification_data.tag = "tagA";
+
+ PlatformNotificationData other_platform_notification_data;
+ other_platform_notification_data.tag = "tagB";
+
+ DisplayPersistentNotificationSync(
+ registration->id(), platform_notification_data, NotificationResources());
+
+ DisplayPersistentNotificationSync(registration->id(),
+ other_platform_notification_data,
+ NotificationResources());
+
+ // Wait for service to receive all the Display calls.
+ RunAllTasksUntilIdle();
+
+ EXPECT_EQ(2u, GetNotificationsSync(registration->id(), "").size());
+ EXPECT_EQ(1u, GetNotificationsSync(registration->id(), "tagA").size());
+ EXPECT_EQ(1u, GetNotificationsSync(registration->id(), "tagB").size());
+ EXPECT_EQ(0u, GetNotificationsSync(registration->id(), "tagC").size());
+ EXPECT_EQ(0u, GetNotificationsSync(registration->id(), "tag").size());
+}
+
} // namespace content
diff --git a/chromium/content/browser/notifications/notification_database.cc b/chromium/content/browser/notifications/notification_database.cc
index 8f212af7f83..c148fdc656d 100644
--- a/chromium/content/browser/notifications/notification_database.cc
+++ b/chromium/content/browser/notifications/notification_database.cc
@@ -14,7 +14,7 @@
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_database_data.h"
#include "storage/common/database/database_identifier.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
#include "third_party/leveldatabase/env_chromium.h"
#include "third_party/leveldatabase/leveldb_chrome.h"
#include "third_party/leveldatabase/src/include/leveldb/db.h"
diff --git a/chromium/content/browser/notifications/notification_database_data_unittest.cc b/chromium/content/browser/notifications/notification_database_data_unittest.cc
index e1c1038c51f..5bdbb4ce880 100644
--- a/chromium/content/browser/notifications/notification_database_data_unittest.cc
+++ b/chromium/content/browser/notifications/notification_database_data_unittest.cc
@@ -15,7 +15,7 @@
#include "content/public/browser/notification_database_data.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/modules/notifications/WebNotificationConstants.h"
+#include "third_party/blink/public/platform/modules/notifications/web_notification_constants.h"
namespace content {
diff --git a/chromium/content/browser/notifications/notification_event_dispatcher_impl.h b/chromium/content/browser/notifications/notification_event_dispatcher_impl.h
index 80c3583b944..e77b7ddf789 100644
--- a/chromium/content/browser/notifications/notification_event_dispatcher_impl.h
+++ b/chromium/content/browser/notifications/notification_event_dispatcher_impl.h
@@ -12,7 +12,7 @@
#include "content/common/content_export.h"
#include "content/public/browser/notification_database_data.h"
#include "content/public/browser/notification_event_dispatcher.h"
-#include "third_party/WebKit/public/platform/modules/notifications/notification_service.mojom.h"
+#include "third_party/blink/public/platform/modules/notifications/notification_service.mojom.h"
namespace content {
diff --git a/chromium/content/browser/notifications/notification_event_dispatcher_impl_unittest.cc b/chromium/content/browser/notifications/notification_event_dispatcher_impl_unittest.cc
index 2bf90ca13ec..dac1cc89ca3 100644
--- a/chromium/content/browser/notifications/notification_event_dispatcher_impl_unittest.cc
+++ b/chromium/content/browser/notifications/notification_event_dispatcher_impl_unittest.cc
@@ -14,7 +14,7 @@
#include "mojo/public/cpp/bindings/binding.h"
#include "mojo/public/cpp/bindings/interface_request.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/modules/notifications/notification_service.mojom.h"
+#include "third_party/blink/public/platform/modules/notifications/notification_service.mojom.h"
namespace content {
diff --git a/chromium/content/browser/notifications/notification_message_filter.cc b/chromium/content/browser/notifications/notification_message_filter.cc
index 83db315fd57..518fdf07991 100644
--- a/chromium/content/browser/notifications/notification_message_filter.cc
+++ b/chromium/content/browser/notifications/notification_message_filter.cc
@@ -24,7 +24,7 @@
#include "content/public/common/content_client.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
-#include "third_party/WebKit/public/platform/modules/notifications/WebNotificationConstants.h"
+#include "third_party/blink/public/platform/modules/notifications/web_notification_constants.h"
namespace content {
diff --git a/chromium/content/browser/notifications/notification_message_filter.h b/chromium/content/browser/notifications/notification_message_filter.h
index 3f28c07e22a..948e0f18e0c 100644
--- a/chromium/content/browser/notifications/notification_message_filter.h
+++ b/chromium/content/browser/notifications/notification_message_filter.h
@@ -14,7 +14,7 @@
#include "content/common/service_worker/service_worker_status_code.h"
#include "content/public/browser/browser_message_filter.h"
#include "content/public/browser/notification_database_data.h"
-#include "third_party/WebKit/public/platform/modules/permissions/permission_status.mojom.h"
+#include "third_party/blink/public/platform/modules/permissions/permission_status.mojom.h"
class GURL;
diff --git a/chromium/content/browser/notifications/platform_notification_context_impl.cc b/chromium/content/browser/notifications/platform_notification_context_impl.cc
index b37ec6983f2..e174998b4d5 100644
--- a/chromium/content/browser/notifications/platform_notification_context_impl.cc
+++ b/chromium/content/browser/notifications/platform_notification_context_impl.cc
@@ -140,8 +140,8 @@ void PlatformNotificationContextImpl::CreateServiceOnIO(
mojo::InterfaceRequest<blink::mojom::NotificationService> request) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
services_.push_back(std::make_unique<BlinkNotificationServiceImpl>(
- this, browser_context_, resource_context, render_process_id, origin,
- std::move(request)));
+ this, browser_context_, resource_context, service_worker_context_,
+ render_process_id, origin, std::move(request)));
}
void PlatformNotificationContextImpl::RemoveService(
diff --git a/chromium/content/browser/notifications/platform_notification_context_impl.h b/chromium/content/browser/notifications/platform_notification_context_impl.h
index 157a54c54ec..a780c453cca 100644
--- a/chromium/content/browser/notifications/platform_notification_context_impl.h
+++ b/chromium/content/browser/notifications/platform_notification_context_impl.h
@@ -21,7 +21,7 @@
#include "content/common/content_export.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/platform_notification_context.h"
-#include "third_party/WebKit/public/platform/modules/notifications/notification_service.mojom.h"
+#include "third_party/blink/public/platform/modules/notifications/notification_service.mojom.h"
class GURL;
diff --git a/chromium/content/browser/notifications/platform_notification_context_unittest.cc b/chromium/content/browser/notifications/platform_notification_context_unittest.cc
index 04b485fe389..d661a252d6f 100644
--- a/chromium/content/browser/notifications/platform_notification_context_unittest.cc
+++ b/chromium/content/browser/notifications/platform_notification_context_unittest.cc
@@ -21,7 +21,7 @@
#include "content/test/mock_platform_notification_service.h"
#include "content/test/test_content_browser_client.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
#include "url/gurl.h"
namespace content {
@@ -334,8 +334,8 @@ TEST_F(PlatformNotificationContextTest, ServiceWorkerUnregistered) {
options.scope = origin;
embedded_worker_test_helper->context()->RegisterServiceWorker(
script_url, options,
- base::Bind(&PlatformNotificationContextTest::DidRegisterServiceWorker,
- base::Unretained(this), &service_worker_registration_id));
+ base::BindOnce(&PlatformNotificationContextTest::DidRegisterServiceWorker,
+ base::Unretained(this), &service_worker_registration_id));
base::RunLoop().RunUntilIdle();
ASSERT_NE(service_worker_registration_id,
@@ -358,9 +358,9 @@ TEST_F(PlatformNotificationContextTest, ServiceWorkerUnregistered) {
// Now drop the Service Worker registration which owns that notification.
embedded_worker_test_helper->context()->UnregisterServiceWorker(
- origin,
- base::Bind(&PlatformNotificationContextTest::DidUnregisterServiceWorker,
- base::Unretained(this), &unregister_status));
+ origin, base::BindOnce(
+ &PlatformNotificationContextTest::DidUnregisterServiceWorker,
+ base::Unretained(this), &unregister_status));
base::RunLoop().RunUntilIdle();
ASSERT_EQ(SERVICE_WORKER_OK, unregister_status);
diff --git a/chromium/content/browser/oop_browsertest.cc b/chromium/content/browser/oop_browsertest.cc
index 840c83b7164..e3502bb016c 100644
--- a/chromium/content/browser/oop_browsertest.cc
+++ b/chromium/content/browser/oop_browsertest.cc
@@ -5,6 +5,7 @@
#include "base/bind.h"
#include "base/callback.h"
#include "base/command_line.h"
+#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_view_host.h"
diff --git a/chromium/content/browser/origin_manifest/origin_manifest_parser.h b/chromium/content/browser/origin_manifest/origin_manifest_parser.h
index 87111974a82..fa3ef6ba71f 100644
--- a/chromium/content/browser/origin_manifest/origin_manifest_parser.h
+++ b/chromium/content/browser/origin_manifest/origin_manifest_parser.h
@@ -9,7 +9,7 @@
#include "base/values.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/common/origin_manifest/origin_manifest.h"
+#include "third_party/blink/public/common/origin_manifest/origin_manifest.h"
namespace base {
class Value;
diff --git a/chromium/content/browser/payments/OWNERS b/chromium/content/browser/payments/OWNERS
index 81e07870aeb..f601d5da683 100644
--- a/chromium/content/browser/payments/OWNERS
+++ b/chromium/content/browser/payments/OWNERS
@@ -1,4 +1,5 @@
jinho.bang@samsung.com
rouslan@chromium.org
+gogerald@chromium.org
# COMPONENT: UI>Browser>Payments
diff --git a/chromium/content/browser/payments/payment_app.proto b/chromium/content/browser/payments/payment_app.proto
index 3a357433d41..35848b1d5da 100644
--- a/chromium/content/browser/payments/payment_app.proto
+++ b/chromium/content/browser/payments/payment_app.proto
@@ -28,7 +28,7 @@ message StoredPaymentInstrumentProto {
optional int64 registration_id = 1;
optional string instrument_key = 2;
optional string name = 3;
- repeated string enabled_methods = 4;
+ optional string method = 4;
optional string stringified_capabilities = 5;
repeated StoredPaymentInstrumentImageObject icons = 6;
optional string decoded_instrument_icon = 7;
diff --git a/chromium/content/browser/payments/payment_app_browsertest.cc b/chromium/content/browser/payments/payment_app_browsertest.cc
index e6ca27a68fd..53fe0b064f4 100644
--- a/chromium/content/browser/payments/payment_app_browsertest.cc
+++ b/chromium/content/browser/payments/payment_app_browsertest.cc
@@ -17,8 +17,8 @@
#include "content/shell/browser/shell.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
-#include "third_party/WebKit/public/platform/modules/payments/payment_app.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/platform/modules/payments/payment_app.mojom.h"
namespace content {
namespace {
diff --git a/chromium/content/browser/payments/payment_app_content_unittest_base.cc b/chromium/content/browser/payments/payment_app_content_unittest_base.cc
index 4e0c343f4e9..94b10e0fda4 100644
--- a/chromium/content/browser/payments/payment_app_content_unittest_base.cc
+++ b/chromium/content/browser/payments/payment_app_content_unittest_base.cc
@@ -21,7 +21,7 @@
#include "content/public/test/test_browser_thread_bundle.h"
#include "mojo/public/cpp/bindings/associated_interface_ptr.h"
#include "mojo/public/cpp/bindings/interface_request.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
@@ -149,7 +149,8 @@ PaymentManager* PaymentAppContentUnitTestBase::CreatePaymentManager(
registration_opt.scope = scope_url;
worker_helper_->context()->RegisterServiceWorker(
sw_script_url, registration_opt,
- base::Bind(&RegisterServiceWorkerCallback, &called, &registration_id));
+ base::BindOnce(&RegisterServiceWorkerCallback, &called,
+ &registration_id));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(called);
@@ -204,7 +205,7 @@ void PaymentAppContentUnitTestBase::UnregisterServiceWorker(
// Unregister service worker.
bool called = false;
worker_helper_->context()->UnregisterServiceWorker(
- scope_url, base::Bind(&UnregisterServiceWorkerCallback, &called));
+ scope_url, base::BindOnce(&UnregisterServiceWorkerCallback, &called));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(called);
}
diff --git a/chromium/content/browser/payments/payment_app_content_unittest_base.h b/chromium/content/browser/payments/payment_app_content_unittest_base.h
index 5d1d7b3908c..7b3c482c414 100644
--- a/chromium/content/browser/payments/payment_app_content_unittest_base.h
+++ b/chromium/content/browser/payments/payment_app_content_unittest_base.h
@@ -13,7 +13,7 @@
#include "base/memory/ref_counted.h"
#include "content/browser/payments/payment_manager.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/modules/payments/payment_app.mojom.h"
+#include "third_party/blink/public/platform/modules/payments/payment_app.mojom.h"
#include "url/gurl.h"
namespace content {
diff --git a/chromium/content/browser/payments/payment_app_context_impl.h b/chromium/content/browser/payments/payment_app_context_impl.h
index e6f3b2c375e..8c8ce926912 100644
--- a/chromium/content/browser/payments/payment_app_context_impl.h
+++ b/chromium/content/browser/payments/payment_app_context_impl.h
@@ -15,7 +15,7 @@
#include "content/browser/payments/payment_app_database.h"
#include "content/common/content_export.h"
#include "content/public/browser/browser_thread.h"
-#include "third_party/WebKit/public/platform/modules/payments/payment_app.mojom.h"
+#include "third_party/blink/public/platform/modules/payments/payment_app.mojom.h"
namespace content {
diff --git a/chromium/content/browser/payments/payment_app_database.cc b/chromium/content/browser/payments/payment_app_database.cc
index ba8cf8e2261..41360d31265 100644
--- a/chromium/content/browser/payments/payment_app_database.cc
+++ b/chromium/content/browser/payments/payment_app_database.cc
@@ -9,7 +9,6 @@
#include "base/base64.h"
#include "base/bind.h"
-#include "base/memory/ptr_util.h"
#include "base/optional.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
@@ -80,8 +79,7 @@ PaymentInstrumentPtr ToPaymentInstrumentForMojo(const std::string& input) {
}
instrument->icons.emplace_back(icon);
}
- for (const auto& method : instrument_proto.enabled_methods())
- instrument->enabled_methods.push_back(method);
+ instrument->method = instrument_proto.method();
instrument->stringified_capabilities =
instrument_proto.stringified_capabilities();
@@ -138,8 +136,7 @@ void PaymentAppDatabase::ReadAllPaymentApps(
service_worker_context_->GetUserDataForAllRegistrationsByKeyPrefix(
kPaymentAppPrefix,
base::BindOnce(&PaymentAppDatabase::DidReadAllPaymentApps,
- weak_ptr_factory_.GetWeakPtr(),
- base::Passed(std::move(callback))));
+ weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void PaymentAppDatabase::DeletePaymentInstrument(
@@ -152,8 +149,7 @@ void PaymentAppDatabase::DeletePaymentInstrument(
scope,
base::BindOnce(
&PaymentAppDatabase::DidFindRegistrationToDeletePaymentInstrument,
- weak_ptr_factory_.GetWeakPtr(), instrument_key,
- base::Passed(std::move(callback))));
+ weak_ptr_factory_.GetWeakPtr(), instrument_key, std::move(callback)));
}
void PaymentAppDatabase::ReadPaymentInstrument(
@@ -166,8 +162,7 @@ void PaymentAppDatabase::ReadPaymentInstrument(
scope,
base::BindOnce(
&PaymentAppDatabase::DidFindRegistrationToReadPaymentInstrument,
- weak_ptr_factory_.GetWeakPtr(), instrument_key,
- base::Passed(std::move(callback))));
+ weak_ptr_factory_.GetWeakPtr(), instrument_key, std::move(callback)));
}
void PaymentAppDatabase::KeysOfPaymentInstruments(
@@ -176,9 +171,9 @@ void PaymentAppDatabase::KeysOfPaymentInstruments(
DCHECK_CURRENTLY_ON(BrowserThread::IO);
service_worker_context_->FindReadyRegistrationForPattern(
- scope, base::BindOnce(&PaymentAppDatabase::DidFindRegistrationToGetKeys,
- weak_ptr_factory_.GetWeakPtr(),
- base::Passed(std::move(callback))));
+ scope,
+ base::BindOnce(&PaymentAppDatabase::DidFindRegistrationToGetKeys,
+ weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void PaymentAppDatabase::HasPaymentInstrument(
@@ -188,10 +183,10 @@ void PaymentAppDatabase::HasPaymentInstrument(
DCHECK_CURRENTLY_ON(BrowserThread::IO);
service_worker_context_->FindReadyRegistrationForPattern(
- scope, base::BindOnce(
- &PaymentAppDatabase::DidFindRegistrationToHasPaymentInstrument,
- weak_ptr_factory_.GetWeakPtr(), instrument_key,
- base::Passed(std::move(callback))));
+ scope,
+ base::BindOnce(
+ &PaymentAppDatabase::DidFindRegistrationToHasPaymentInstrument,
+ weak_ptr_factory_.GetWeakPtr(), instrument_key, std::move(callback)));
}
void PaymentAppDatabase::WritePaymentInstrument(
@@ -215,8 +210,7 @@ void PaymentAppDatabase::WritePaymentInstrument(
base::BindOnce(
&PaymentAppDatabase::DidFindRegistrationToWritePaymentInstrument,
weak_ptr_factory_.GetWeakPtr(), instrument_key,
- base::Passed(std::move(instrument)), std::string(),
- base::Passed(std::move(callback))));
+ std::move(instrument), std::string(), std::move(callback)));
}
}
@@ -237,43 +231,38 @@ void PaymentAppDatabase::DidFetchedPaymentInstrumentIcon(
scope,
base::BindOnce(
&PaymentAppDatabase::DidFindRegistrationToWritePaymentInstrument,
- weak_ptr_factory_.GetWeakPtr(), instrument_key,
- base::Passed(std::move(instrument)), icon,
- base::Passed(std::move(callback))));
+ weak_ptr_factory_.GetWeakPtr(), instrument_key, std::move(instrument),
+ icon, std::move(callback)));
}
-void PaymentAppDatabase::FetchAndWritePaymentAppInfo(
+void PaymentAppDatabase::FetchAndUpdatePaymentAppInfo(
const GURL& context,
const GURL& scope,
- const std::string& user_hint,
- FetchAndWritePaymentAppInfoCallback callback) {
+ FetchAndUpdatePaymentAppInfoCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
PaymentAppInfoFetcher::Start(
context, service_worker_context_,
base::BindOnce(&PaymentAppDatabase::FetchPaymentAppInfoCallback,
- weak_ptr_factory_.GetWeakPtr(), scope, user_hint,
+ weak_ptr_factory_.GetWeakPtr(), scope,
std::move(callback)));
}
void PaymentAppDatabase::FetchPaymentAppInfoCallback(
const GURL& scope,
- const std::string& user_hint,
- FetchAndWritePaymentAppInfoCallback callback,
+ FetchAndUpdatePaymentAppInfoCallback callback,
std::unique_ptr<PaymentAppInfoFetcher::PaymentAppInfo> app_info) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
service_worker_context_->FindReadyRegistrationForPattern(
scope, base::BindOnce(
- &PaymentAppDatabase::DidFindRegistrationToWritePaymentAppInfo,
- weak_ptr_factory_.GetWeakPtr(), user_hint,
- base::Passed(std::move(callback)),
- base::Passed(std::move(app_info))));
+ &PaymentAppDatabase::DidFindRegistrationToUpdatePaymentAppInfo,
+ weak_ptr_factory_.GetWeakPtr(), std::move(callback),
+ std::move(app_info)));
}
-void PaymentAppDatabase::DidFindRegistrationToWritePaymentAppInfo(
- const std::string& user_hint,
- FetchAndWritePaymentAppInfoCallback callback,
+void PaymentAppDatabase::DidFindRegistrationToUpdatePaymentAppInfo(
+ FetchAndUpdatePaymentAppInfoCallback callback,
std::unique_ptr<PaymentAppInfoFetcher::PaymentAppInfo> app_info,
ServiceWorkerStatusCode status,
scoped_refptr<ServiceWorkerRegistration> registration) {
@@ -283,11 +272,40 @@ void PaymentAppDatabase::DidFindRegistrationToWritePaymentAppInfo(
return;
}
+ service_worker_context_->GetRegistrationUserDataByKeyPrefix(
+ registration->id(), CreatePaymentAppKey(registration->pattern().spec()),
+ base::BindOnce(
+ &PaymentAppDatabase::DidGetPaymentAppInfoToUpdatePaymentAppInfo,
+ weak_ptr_factory_.GetWeakPtr(), std::move(callback),
+ std::move(app_info), registration));
+}
+
+void PaymentAppDatabase::DidGetPaymentAppInfoToUpdatePaymentAppInfo(
+ FetchAndUpdatePaymentAppInfoCallback callback,
+ std::unique_ptr<PaymentAppInfoFetcher::PaymentAppInfo> app_info,
+ scoped_refptr<ServiceWorkerRegistration> registration,
+ const std::vector<std::string>& data,
+ ServiceWorkerStatusCode status) {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+ if (status != SERVICE_WORKER_OK) {
+ std::move(callback).Run(PaymentHandlerStatus::NO_ACTIVE_WORKER);
+ return;
+ }
+
+ DCHECK_LE(data.size(), 1U);
StoredPaymentAppProto payment_app_proto;
+ if (data.size() == 1U) {
+ payment_app_proto.ParseFromString(data[0]);
+ }
payment_app_proto.set_registration_id(registration->id());
payment_app_proto.set_scope(registration->pattern().spec());
- payment_app_proto.set_name(app_info->name);
- payment_app_proto.set_icon(app_info->icon);
+ // Do not override name and icon if they are invalid.
+ if (!app_info->name.empty()) {
+ payment_app_proto.set_name(app_info->name);
+ }
+ if (!app_info->icon.empty()) {
+ payment_app_proto.set_icon(app_info->icon);
+ }
payment_app_proto.set_prefer_related_applications(
app_info->prefer_related_applications);
for (const auto& related_app : app_info->related_applications) {
@@ -296,7 +314,6 @@ void PaymentAppDatabase::DidFindRegistrationToWritePaymentAppInfo(
related_app_proto->set_platform(related_app.platform);
related_app_proto->set_id(related_app.id);
}
- payment_app_proto.set_user_hint(user_hint);
std::string serialized_payment_app;
bool success = payment_app_proto.SerializeToString(&serialized_payment_app);
@@ -306,14 +323,13 @@ void PaymentAppDatabase::DidFindRegistrationToWritePaymentAppInfo(
registration->id(), registration->pattern().GetOrigin(),
{{CreatePaymentAppKey(registration->pattern().spec()),
serialized_payment_app}},
- base::Bind(&PaymentAppDatabase::DidWritePaymentApp,
- weak_ptr_factory_.GetWeakPtr(),
- base::Passed(std::move(callback)),
- app_info->name.empty() | app_info->icon.empty()));
+ base::BindOnce(&PaymentAppDatabase::DidUpdatePaymentApp,
+ weak_ptr_factory_.GetWeakPtr(), std::move(callback),
+ app_info->name.empty() | app_info->icon.empty()));
}
-void PaymentAppDatabase::DidWritePaymentApp(
- FetchAndWritePaymentAppInfoCallback callback,
+void PaymentAppDatabase::DidUpdatePaymentApp(
+ FetchAndUpdatePaymentAppInfoCallback callback,
bool fetch_app_info_failed,
ServiceWorkerStatusCode status) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
@@ -337,8 +353,7 @@ void PaymentAppDatabase::ClearPaymentInstruments(
scope,
base::BindOnce(
&PaymentAppDatabase::DidFindRegistrationToClearPaymentInstruments,
- weak_ptr_factory_.GetWeakPtr(), scope,
- base::Passed(std::move(callback))));
+ weak_ptr_factory_.GetWeakPtr(), scope, std::move(callback)));
}
void PaymentAppDatabase::SetPaymentAppUserHint(const GURL& scope,
@@ -391,8 +406,8 @@ void PaymentAppDatabase::DidGetPaymentAppInfoToSetUserHint(
service_worker_context_->StoreRegistrationUserData(
registration_id, pattern.GetOrigin(),
{{CreatePaymentAppKey(pattern.spec()), serialized_payment_app}},
- base::Bind(&PaymentAppDatabase::DidSetPaymentAppUserHint,
- weak_ptr_factory_.GetWeakPtr()));
+ base::BindOnce(&PaymentAppDatabase::DidSetPaymentAppUserHint,
+ weak_ptr_factory_.GetWeakPtr()));
}
void PaymentAppDatabase::DidSetPaymentAppUserHint(
@@ -405,21 +420,23 @@ void PaymentAppDatabase::SetPaymentAppInfoForRegisteredServiceWorker(
int64_t registration_id,
const std::string& instrument_key,
const std::string& name,
- const std::vector<std::string>& enabled_methods,
+ const std::string& icon,
+ const std::string& method,
SetPaymentAppInfoCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
service_worker_context_->FindReadyRegistrationForIdOnly(
registration_id,
base::BindOnce(&PaymentAppDatabase::DidFindRegistrationToSetPaymentApp,
- weak_ptr_factory_.GetWeakPtr(), instrument_key, name,
- enabled_methods, std::move(callback)));
+ weak_ptr_factory_.GetWeakPtr(), instrument_key, name, icon,
+ method, std::move(callback)));
}
void PaymentAppDatabase::DidFindRegistrationToSetPaymentApp(
const std::string& instrument_key,
const std::string& name,
- const std::vector<std::string>& enabled_methods,
+ const std::string& icon,
+ const std::string& method,
SetPaymentAppInfoCallback callback,
ServiceWorkerStatusCode status,
scoped_refptr<ServiceWorkerRegistration> registration) {
@@ -434,6 +451,7 @@ void PaymentAppDatabase::DidFindRegistrationToSetPaymentApp(
payment_app_proto.set_registration_id(registration->id());
payment_app_proto.set_scope(registration->pattern().spec());
payment_app_proto.set_name(name);
+ payment_app_proto.set_icon(icon);
std::string serialized_payment_app;
bool success = payment_app_proto.SerializeToString(&serialized_payment_app);
@@ -443,17 +461,16 @@ void PaymentAppDatabase::DidFindRegistrationToSetPaymentApp(
registration->id(), registration->pattern().GetOrigin(),
{{CreatePaymentAppKey(registration->pattern().spec()),
serialized_payment_app}},
- base::Bind(&PaymentAppDatabase::DidWritePaymentAppForSetPaymentApp,
- weak_ptr_factory_.GetWeakPtr(), instrument_key,
- enabled_methods, base::Passed(std::move(callback)),
- std::move(registration)));
+ base::BindOnce(&PaymentAppDatabase::DidWritePaymentAppForSetPaymentApp,
+ weak_ptr_factory_.GetWeakPtr(), instrument_key, method,
+ std::move(callback), std::move(registration)));
return;
}
void PaymentAppDatabase::DidWritePaymentAppForSetPaymentApp(
const std::string& instrument_key,
- const std::vector<std::string>& enabled_methods,
+ const std::string& method,
SetPaymentAppInfoCallback callback,
scoped_refptr<ServiceWorkerRegistration> registration,
ServiceWorkerStatusCode status) {
@@ -467,9 +484,7 @@ void PaymentAppDatabase::DidWritePaymentAppForSetPaymentApp(
StoredPaymentInstrumentProto instrument_proto;
instrument_proto.set_registration_id(registration->id());
instrument_proto.set_instrument_key(instrument_key);
- for (const auto& method : enabled_methods) {
- instrument_proto.add_enabled_methods(method);
- }
+ instrument_proto.set_method(method);
std::string serialized_instrument;
bool success = instrument_proto.SerializeToString(&serialized_instrument);
@@ -488,9 +503,9 @@ void PaymentAppDatabase::DidWritePaymentAppForSetPaymentApp(
{{CreatePaymentInstrumentKey(instrument_key), serialized_instrument},
{CreatePaymentInstrumentKeyInfoKey(instrument_key),
serialized_key_info}},
- base::Bind(&PaymentAppDatabase::DidWritePaymentInstrumentForSetPaymentApp,
- weak_ptr_factory_.GetWeakPtr(),
- base::Passed(std::move(callback))));
+ base::BindOnce(
+ &PaymentAppDatabase::DidWritePaymentInstrumentForSetPaymentApp,
+ weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void PaymentAppDatabase::DidWritePaymentInstrumentForSetPaymentApp(
@@ -529,9 +544,8 @@ void PaymentAppDatabase::DidReadAllPaymentApps(
service_worker_context_->GetUserDataForAllRegistrationsByKeyPrefix(
kPaymentInstrumentPrefix,
base::BindOnce(&PaymentAppDatabase::DidReadAllPaymentInstruments,
- weak_ptr_factory_.GetWeakPtr(),
- base::Passed(std::move(apps)),
- base::Passed(std::move(callback))));
+ weak_ptr_factory_.GetWeakPtr(), std::move(apps),
+ std::move(callback)));
}
void PaymentAppDatabase::DidReadAllPaymentInstruments(
@@ -554,10 +568,7 @@ void PaymentAppDatabase::DidReadAllPaymentInstruments(
if (!base::ContainsKey(apps, id))
continue;
- for (const auto& method : instrument_proto.enabled_methods()) {
- apps[id]->enabled_methods.push_back(method);
- }
-
+ apps[id]->enabled_methods.emplace_back(instrument_proto.method());
apps[id]->capabilities.emplace_back(StoredCapabilities());
for (const auto& network : instrument_proto.supported_card_networks()) {
apps[id]->capabilities.back().supported_card_networks.emplace_back(
@@ -586,7 +597,7 @@ void PaymentAppDatabase::DidFindRegistrationToDeletePaymentInstrument(
registration->id(), {CreatePaymentInstrumentKey(instrument_key)},
base::BindOnce(&PaymentAppDatabase::DidFindPaymentInstrument,
weak_ptr_factory_.GetWeakPtr(), registration->id(),
- instrument_key, base::Passed(std::move(callback))));
+ instrument_key, std::move(callback)));
}
void PaymentAppDatabase::DidFindPaymentInstrument(
@@ -605,9 +616,8 @@ void PaymentAppDatabase::DidFindPaymentInstrument(
registration_id,
{CreatePaymentInstrumentKey(instrument_key),
CreatePaymentInstrumentKeyInfoKey(instrument_key)},
- base::Bind(&PaymentAppDatabase::DidDeletePaymentInstrument,
- weak_ptr_factory_.GetWeakPtr(),
- base::Passed(std::move(callback))));
+ base::BindOnce(&PaymentAppDatabase::DidDeletePaymentInstrument,
+ weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void PaymentAppDatabase::DidDeletePaymentInstrument(
@@ -634,8 +644,7 @@ void PaymentAppDatabase::DidFindRegistrationToReadPaymentInstrument(
service_worker_context_->GetRegistrationUserData(
registration->id(), {CreatePaymentInstrumentKey(instrument_key)},
base::BindOnce(&PaymentAppDatabase::DidReadPaymentInstrument,
- weak_ptr_factory_.GetWeakPtr(),
- base::Passed(std::move(callback))));
+ weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void PaymentAppDatabase::DidReadPaymentInstrument(
@@ -673,8 +682,7 @@ void PaymentAppDatabase::DidFindRegistrationToGetKeys(
service_worker_context_->GetRegistrationUserDataByKeyPrefix(
registration->id(), {kPaymentInstrumentKeyInfoPrefix},
base::BindOnce(&PaymentAppDatabase::DidGetKeysOfPaymentInstruments,
- weak_ptr_factory_.GetWeakPtr(),
- base::Passed(std::move(callback))));
+ weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void PaymentAppDatabase::DidGetKeysOfPaymentInstruments(
@@ -710,8 +718,7 @@ void PaymentAppDatabase::DidFindRegistrationToHasPaymentInstrument(
service_worker_context_->GetRegistrationUserData(
registration->id(), {CreatePaymentInstrumentKey(instrument_key)},
base::BindOnce(&PaymentAppDatabase::DidHasPaymentInstrument,
- weak_ptr_factory_.GetWeakPtr(),
- base::Passed(std::move(callback))));
+ weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void PaymentAppDatabase::DidHasPaymentInstrument(
@@ -745,9 +752,7 @@ void PaymentAppDatabase::DidFindRegistrationToWritePaymentInstrument(
instrument_proto.set_decoded_instrument_icon(decoded_instrument_icon);
instrument_proto.set_instrument_key(instrument_key);
instrument_proto.set_name(instrument->name);
- for (const auto& method : instrument->enabled_methods) {
- instrument_proto.add_enabled_methods(method);
- }
+ instrument_proto.set_method(instrument->method);
for (const auto& icon : instrument->icons) {
StoredPaymentInstrumentImageObject* image_object_proto =
instrument_proto.add_icons();
@@ -785,9 +790,8 @@ void PaymentAppDatabase::DidFindRegistrationToWritePaymentInstrument(
{{CreatePaymentInstrumentKey(instrument_key), serialized_instrument},
{CreatePaymentInstrumentKeyInfoKey(instrument_key),
serialized_key_info}},
- base::Bind(&PaymentAppDatabase::DidWritePaymentInstrument,
- weak_ptr_factory_.GetWeakPtr(),
- base::Passed(std::move(callback))));
+ base::BindOnce(&PaymentAppDatabase::DidWritePaymentInstrument,
+ weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void PaymentAppDatabase::DidWritePaymentInstrument(
@@ -843,9 +847,8 @@ void PaymentAppDatabase::DidGetKeysToClearPaymentInstruments(
service_worker_context_->ClearRegistrationUserData(
registration->id(), keys_with_prefix,
- base::Bind(&PaymentAppDatabase::DidClearPaymentInstruments,
- weak_ptr_factory_.GetWeakPtr(),
- base::Passed(std::move(callback))));
+ base::BindOnce(&PaymentAppDatabase::DidClearPaymentInstruments,
+ weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void PaymentAppDatabase::DidClearPaymentInstruments(
diff --git a/chromium/content/browser/payments/payment_app_database.h b/chromium/content/browser/payments/payment_app_database.h
index f10c7f33eec..baca8a422be 100644
--- a/chromium/content/browser/payments/payment_app_database.h
+++ b/chromium/content/browser/payments/payment_app_database.h
@@ -19,7 +19,7 @@
#include "content/common/service_worker/service_worker_status_code.h"
#include "content/public/browser/stored_payment_app.h"
#include "mojo/public/cpp/bindings/binding.h"
-#include "third_party/WebKit/public/platform/modules/payments/payment_app.mojom.h"
+#include "third_party/blink/public/platform/modules/payments/payment_app.mojom.h"
namespace content {
@@ -42,7 +42,7 @@ class CONTENT_EXPORT PaymentAppDatabase {
base::OnceCallback<void(payments::mojom::PaymentHandlerStatus)>;
using WritePaymentInstrumentCallback =
base::OnceCallback<void(payments::mojom::PaymentHandlerStatus)>;
- using FetchAndWritePaymentAppInfoCallback =
+ using FetchAndUpdatePaymentAppInfoCallback =
base::OnceCallback<void(payments::mojom::PaymentHandlerStatus)>;
using ClearPaymentInstrumentsCallback =
base::OnceCallback<void(payments::mojom::PaymentHandlerStatus)>;
@@ -70,11 +70,10 @@ class CONTENT_EXPORT PaymentAppDatabase {
const std::string& instrument_key,
payments::mojom::PaymentInstrumentPtr instrument,
WritePaymentInstrumentCallback callback);
- void FetchAndWritePaymentAppInfo(
+ void FetchAndUpdatePaymentAppInfo(
const GURL& context,
const GURL& scope,
- const std::string& user_hint,
- FetchAndWritePaymentAppInfoCallback callback);
+ FetchAndUpdatePaymentAppInfoCallback callback);
void ClearPaymentInstruments(const GURL& scope,
ClearPaymentInstrumentsCallback callback);
void SetPaymentAppUserHint(const GURL& scope, const std::string& user_hint);
@@ -82,7 +81,8 @@ class CONTENT_EXPORT PaymentAppDatabase {
int64_t registration_id,
const std::string& instrument_key,
const std::string& name,
- const std::vector<std::string>& enabled_methods,
+ const std::string& icon,
+ const std::string& method,
SetPaymentAppInfoCallback callback);
private:
@@ -151,21 +151,25 @@ class CONTENT_EXPORT PaymentAppDatabase {
void DidWritePaymentInstrument(WritePaymentInstrumentCallback callback,
ServiceWorkerStatusCode status);
- // FetchAndWritePaymentAppInfo callbacks.
+ // FetchAndUpdatePaymentAppInfo callbacks.
void FetchPaymentAppInfoCallback(
const GURL& scope,
- const std::string& user_hint,
- FetchAndWritePaymentAppInfoCallback callback,
+ FetchAndUpdatePaymentAppInfoCallback callback,
std::unique_ptr<PaymentAppInfoFetcher::PaymentAppInfo> app_info);
- void DidFindRegistrationToWritePaymentAppInfo(
- const std::string& user_hint,
- FetchAndWritePaymentAppInfoCallback callback,
+ void DidFindRegistrationToUpdatePaymentAppInfo(
+ FetchAndUpdatePaymentAppInfoCallback callback,
std::unique_ptr<PaymentAppInfoFetcher::PaymentAppInfo> app_info,
ServiceWorkerStatusCode status,
scoped_refptr<ServiceWorkerRegistration> registration);
- void DidWritePaymentApp(FetchAndWritePaymentAppInfoCallback callback,
- bool fetch_app_info_failed,
- ServiceWorkerStatusCode status);
+ void DidGetPaymentAppInfoToUpdatePaymentAppInfo(
+ FetchAndUpdatePaymentAppInfoCallback callback,
+ std::unique_ptr<PaymentAppInfoFetcher::PaymentAppInfo> app_info,
+ scoped_refptr<ServiceWorkerRegistration> registration,
+ const std::vector<std::string>& data,
+ ServiceWorkerStatusCode status);
+ void DidUpdatePaymentApp(FetchAndUpdatePaymentAppInfoCallback callback,
+ bool fetch_app_info_failed,
+ ServiceWorkerStatusCode status);
// PaymentInstrumentIconFetcherCallback.
void DidFetchedPaymentInstrumentIcon(
@@ -205,13 +209,14 @@ class CONTENT_EXPORT PaymentAppDatabase {
void DidFindRegistrationToSetPaymentApp(
const std::string& instrument_key,
const std::string& name,
- const std::vector<std::string>& enabled_methods,
+ const std::string& icon,
+ const std::string& method,
SetPaymentAppInfoCallback callback,
ServiceWorkerStatusCode status,
scoped_refptr<ServiceWorkerRegistration> registration);
void DidWritePaymentAppForSetPaymentApp(
const std::string& instrument_key,
- const std::vector<std::string>& enabled_methods,
+ const std::string& method,
SetPaymentAppInfoCallback callback,
scoped_refptr<ServiceWorkerRegistration> registration,
ServiceWorkerStatusCode status);
diff --git a/chromium/content/browser/payments/payment_app_info_fetcher.cc b/chromium/content/browser/payments/payment_app_info_fetcher.cc
index ba2c16ec34d..2d3e5e39810 100644
--- a/chromium/content/browser/payments/payment_app_info_fetcher.cc
+++ b/chromium/content/browser/payments/payment_app_info_fetcher.cc
@@ -107,9 +107,9 @@ void PaymentAppInfoFetcher::SelfDeleteFetcher::Start(
std::make_unique<WebContentsHelper>(top_level_web_content);
top_level_web_content->GetManifest(
- base::Bind(&PaymentAppInfoFetcher::SelfDeleteFetcher::
- FetchPaymentAppManifestCallback,
- base::Unretained(this)));
+ base::BindOnce(&PaymentAppInfoFetcher::SelfDeleteFetcher::
+ FetchPaymentAppManifestCallback,
+ base::Unretained(this)));
return;
}
diff --git a/chromium/content/browser/payments/payment_app_installer.cc b/chromium/content/browser/payments/payment_app_installer.cc
index d01fb931d35..6a6e31bdb07 100644
--- a/chromium/content/browser/payments/payment_app_installer.cc
+++ b/chromium/content/browser/payments/payment_app_installer.cc
@@ -28,14 +28,17 @@ class SelfDeleteInstaller
public:
SelfDeleteInstaller(WebContents* web_contents,
const std::string& app_name,
+ const std::string& app_icon,
const GURL& sw_url,
const GURL& scope,
bool use_cache,
- const std::vector<std::string>& enabled_methods,
+ const std::string& method,
PaymentAppInstaller::InstallPaymentAppCallback callback)
: app_name_(app_name),
+ app_icon_(app_icon),
sw_url_(sw_url),
scope_(scope),
+ method_(method),
callback_(std::move(callback)) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
@@ -43,9 +46,6 @@ class SelfDeleteInstaller
// installation early.
Observe(web_contents);
- std::copy(enabled_methods.begin(), enabled_methods.end(),
- std::back_inserter(enabled_methods_));
-
content::BrowserContext* browser_context =
web_contents->GetBrowserContext();
ServiceWorkerContextWrapper* service_worker_context =
@@ -135,7 +135,7 @@ class SelfDeleteInstaller
BrowserThread::IO, FROM_HERE,
base::BindOnce(&SelfDeleteInstaller::SetPaymentAppInfoOnIO, this,
payment_app_context, registration_id_, scope_.spec(),
- app_name_, enabled_methods_));
+ app_name_, app_icon_, method_));
}
void SetPaymentAppInfoOnIO(
@@ -143,12 +143,13 @@ class SelfDeleteInstaller
int64_t registration_id,
const std::string& instrument_key,
const std::string& name,
- const std::vector<std::string>& enabled_methods) {
+ const std::string& app_icon,
+ const std::string& method) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
payment_app_context->payment_app_database()
->SetPaymentAppInfoForRegisteredServiceWorker(
- registration_id, instrument_key, name, enabled_methods,
+ registration_id, instrument_key, name, app_icon, method,
base::BindOnce(&SelfDeleteInstaller::OnSetPaymentAppInfo, this));
}
@@ -186,9 +187,10 @@ class SelfDeleteInstaller
}
std::string app_name_;
+ std::string app_icon_;
GURL sw_url_;
GURL scope_;
- std::vector<std::string> enabled_methods_;
+ std::string method_;
PaymentAppInstaller::InstallPaymentAppCallback callback_;
int64_t registration_id_ = -1; // Take -1 as an invalid registration Id.
@@ -200,18 +202,18 @@ class SelfDeleteInstaller
} // namespace.
// Static
-void PaymentAppInstaller::Install(
- WebContents* web_contents,
- const std::string& app_name,
- const GURL& sw_url,
- const GURL& scope,
- bool use_cache,
- const std::vector<std::string>& enabled_methods,
- InstallPaymentAppCallback callback) {
+void PaymentAppInstaller::Install(WebContents* web_contents,
+ const std::string& app_name,
+ const std::string& app_icon,
+ const GURL& sw_url,
+ const GURL& scope,
+ bool use_cache,
+ const std::string& method,
+ InstallPaymentAppCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
- new SelfDeleteInstaller(web_contents, app_name, sw_url, scope, use_cache,
- enabled_methods, std::move(callback));
+ new SelfDeleteInstaller(web_contents, app_name, app_icon, sw_url, scope,
+ use_cache, method, std::move(callback));
}
-} // namespace content \ No newline at end of file
+} // namespace content
diff --git a/chromium/content/browser/payments/payment_app_installer.h b/chromium/content/browser/payments/payment_app_installer.h
index e864c970c6a..67e9e5b38d9 100644
--- a/chromium/content/browser/payments/payment_app_installer.h
+++ b/chromium/content/browser/payments/payment_app_installer.h
@@ -27,6 +27,7 @@ class PaymentAppInstaller {
// Installs the payment app.
// |app_name| is the name of the payment app.
+ // |app_icon| is the icon of the payment app.
// |sw_url| is the url to get the service worker js script.
// |scope| is the registration scope.
// |use_cache| indicates whether to use cache.
@@ -34,10 +35,11 @@ class PaymentAppInstaller {
// |callback| to send back registeration result.
static void Install(WebContents* web_contents,
const std::string& app_name,
+ const std::string& app_icon,
const GURL& sw_url,
const GURL& scope,
bool use_cache,
- const std::vector<std::string>& enabled_methods,
+ const std::string& method,
InstallPaymentAppCallback callback);
private:
@@ -46,4 +48,4 @@ class PaymentAppInstaller {
} // namespace content.
-#endif // CONTENT_BROWSER_PAYMENTS_PAYMENT_APP_INSTALLER_H_ \ No newline at end of file
+#endif // CONTENT_BROWSER_PAYMENTS_PAYMENT_APP_INSTALLER_H_
diff --git a/chromium/content/browser/payments/payment_app_provider_impl.cc b/chromium/content/browser/payments/payment_app_provider_impl.cc
index d899d32fd38..5d4aefd1644 100644
--- a/chromium/content/browser/payments/payment_app_provider_impl.cc
+++ b/chromium/content/browser/payments/payment_app_provider_impl.cc
@@ -4,6 +4,7 @@
#include "content/browser/payments/payment_app_provider_impl.h"
+#include "base/base64.h"
#include "base/strings/string_util.h"
#include "content/browser/payments/payment_app_context_impl.h"
#include "content/browser/payments/payment_app_installer.h"
@@ -13,10 +14,15 @@
#include "content/browser/storage_partition_impl.h"
#include "content/common/service_worker/service_worker_status_code.h"
#include "content/public/browser/browser_thread.h"
+#include "content/public/browser/permission_manager.h"
+#include "content/public/browser/permission_type.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
-#include "mojo/common/time.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_provider_type.mojom.h"
+#include "mojo/public/mojom/base/time.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_provider_type.mojom.h"
+#include "third_party/blink/public/platform/modules/permissions/permission_status.mojom.h"
+#include "third_party/skia/include/core/SkBitmap.h"
+#include "ui/gfx/image/image.h"
namespace content {
namespace {
@@ -31,10 +37,12 @@ class RespondWithCallbacks
: public payments::mojom::PaymentHandlerResponseCallback {
public:
RespondWithCallbacks(
+ BrowserContext* browser_context,
ServiceWorkerMetrics::EventType event_type,
scoped_refptr<ServiceWorkerVersion> service_worker_version,
PaymentAppProvider::InvokePaymentAppCallback callback)
- : service_worker_version_(service_worker_version),
+ : browser_context_(browser_context),
+ service_worker_version_(service_worker_version),
invoke_payment_app_callback_(std::move(callback)),
binding_(this),
weak_ptr_factory_(this) {
@@ -74,7 +82,9 @@ class RespondWithCallbacks
base::BindOnce(std::move(invoke_payment_app_callback_),
std::move(response)));
- CloseClientWindows();
+ BrowserThread::PostTask(
+ BrowserThread::UI, FROM_HERE,
+ base::BindOnce(&CloseClientWindowOnUIThread, browser_context_));
delete this;
}
@@ -100,7 +110,9 @@ class RespondWithCallbacks
base::BindOnce(std::move(payment_event_result_callback_),
payment_aborted));
- CloseClientWindows();
+ BrowserThread::PostTask(
+ BrowserThread::UI, FROM_HERE,
+ base::BindOnce(&CloseClientWindowOnUIThread, browser_context_));
delete this;
}
@@ -123,7 +135,9 @@ class RespondWithCallbacks
if (event_type_ == ServiceWorkerMetrics::EventType::PAYMENT_REQUEST ||
event_type_ == ServiceWorkerMetrics::EventType::ABORT_PAYMENT) {
- CloseClientWindows();
+ BrowserThread::PostTask(
+ BrowserThread::UI, FROM_HERE,
+ base::BindOnce(&CloseClientWindowOnUIThread, browser_context_));
}
delete this;
}
@@ -133,51 +147,14 @@ class RespondWithCallbacks
private:
~RespondWithCallbacks() override {}
- // Close all the windows in the payment handler service worker scope.
- // Note that this will close not only the windows opened through
- // PaymentRequestEvent.openWindow and Clients.openWindow(), but also the
- // windows opened through typing the url in the ominibox only if they are in
- // the payment handler service worker scope.
- void CloseClientWindows() {
- std::vector<std::pair<int, int>> ids;
- for (const auto& controllee : service_worker_version_->controllee_map()) {
- if (controllee.second->provider_type() ==
- blink::mojom::ServiceWorkerProviderType::kForWindow) {
- ids.emplace_back(std::make_pair(controllee.second->process_id(),
- controllee.second->frame_id()));
- }
- }
- if (ids.size() == 0)
- return;
+ static void CloseClientWindowOnUIThread(BrowserContext* browser_context) {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
- BrowserThread::PostTask(
- BrowserThread::UI, FROM_HERE,
- base::BindOnce(&RespondWithCallbacks::CloseClientWindowsOnUIThread,
- ids));
- }
-
- static void CloseClientWindowsOnUIThread(
- const std::vector<std::pair<int, int>>& ids) {
- for (const auto& id : ids) {
- RenderFrameHost* frame_host =
- RenderFrameHost::FromID(id.first, id.second);
- if (frame_host == nullptr)
- continue;
-
- // Don't close windows that embed iframes with the payment app scope. Only
- // top level contexts with the payment app scope should be closed.
- if (frame_host->GetParent() != nullptr)
- continue;
-
- WebContents* web_contents = WebContents::FromRenderFrameHost(frame_host);
- if (web_contents == nullptr)
- continue;
-
- web_contents->Close();
- }
+ PaymentAppProvider::GetInstance()->CloseOpenedWindow(browser_context);
}
int request_id_;
+ BrowserContext* browser_context_;
ServiceWorkerMetrics::EventType event_type_;
scoped_refptr<ServiceWorkerVersion> service_worker_version_;
PaymentAppProvider::InvokePaymentAppCallback invoke_payment_app_callback_;
@@ -263,6 +240,7 @@ void DispatchCanMakePaymentEvent(
}
void DispatchPaymentRequestEvent(
+ BrowserContext* browser_context,
payments::mojom::PaymentRequestEventDataPtr event_data,
PaymentAppProvider::InvokePaymentAppCallback callback,
scoped_refptr<ServiceWorkerVersion> active_version,
@@ -283,9 +261,9 @@ void DispatchPaymentRequestEvent(
ServiceWorkerMetrics::EventType::PAYMENT_REQUEST, base::DoNothing());
// This object self-deletes after either success or error callback is invoked.
- RespondWithCallbacks* invocation_callbacks =
- new RespondWithCallbacks(ServiceWorkerMetrics::EventType::PAYMENT_REQUEST,
- active_version, std::move(callback));
+ RespondWithCallbacks* invocation_callbacks = new RespondWithCallbacks(
+ browser_context, ServiceWorkerMetrics::EventType::PAYMENT_REQUEST,
+ active_version, std::move(callback));
active_version->event_dispatcher()->DispatchPaymentRequestEvent(
invocation_callbacks->request_id(), std::move(event_data),
@@ -355,6 +333,32 @@ void OnInstallPaymentApp(payments::mojom::PaymentRequestEventDataPtr event_data,
}
}
+void CheckPermissionForPaymentApps(
+ BrowserContext* browser_context,
+ PaymentAppProvider::GetAllPaymentAppsCallback callback,
+ PaymentAppProvider::PaymentApps apps) {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+
+ PermissionManager* permission_manager =
+ browser_context->GetPermissionManager();
+ if (!permission_manager) {
+ std::move(callback).Run(PaymentAppProvider::PaymentApps());
+ return;
+ }
+
+ PaymentAppProvider::PaymentApps permitted_apps;
+ for (auto& app : apps) {
+ GURL origin = app.second->scope.GetOrigin();
+ if (permission_manager->GetPermissionStatus(PermissionType::PAYMENT_HANDLER,
+ origin, origin) ==
+ blink::mojom::PermissionStatus::GRANTED) {
+ permitted_apps[app.first] = std::move(app.second);
+ }
+ }
+
+ std::move(callback).Run(std::move(permitted_apps));
+}
+
} // namespace
// static
@@ -381,7 +385,8 @@ void PaymentAppProviderImpl::GetAllPaymentApps(
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&GetAllPaymentAppsOnIO, payment_app_context,
- std::move(callback)));
+ base::BindOnce(&CheckPermissionForPaymentApps,
+ browser_context, std::move(callback))));
}
void PaymentAppProviderImpl::InvokePaymentApp(
@@ -393,18 +398,19 @@ void PaymentAppProviderImpl::InvokePaymentApp(
StartServiceWorkerForDispatch(
browser_context, registration_id,
- base::BindOnce(&DispatchPaymentRequestEvent, std::move(event_data),
- std::move(callback)));
+ base::BindOnce(&DispatchPaymentRequestEvent, browser_context,
+ std::move(event_data), std::move(callback)));
}
void PaymentAppProviderImpl::InstallAndInvokePaymentApp(
WebContents* web_contents,
payments::mojom::PaymentRequestEventDataPtr event_data,
const std::string& app_name,
+ const SkBitmap& app_icon,
const std::string& sw_js_url,
const std::string& sw_scope,
bool sw_use_cache,
- const std::vector<std::string>& enabled_methods,
+ const std::string& method,
InvokePaymentAppCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
@@ -412,7 +418,7 @@ void PaymentAppProviderImpl::InstallAndInvokePaymentApp(
GURL url = GURL(sw_js_url);
DCHECK(base::IsStringUTF8(sw_scope));
GURL scope = GURL(sw_scope);
- if (!url.is_valid() || !scope.is_valid() || enabled_methods.size() == 0) {
+ if (!url.is_valid() || !scope.is_valid() || method.empty()) {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::BindOnce(std::move(callback),
@@ -420,8 +426,19 @@ void PaymentAppProviderImpl::InstallAndInvokePaymentApp(
return;
}
+ std::string string_encoded_icon;
+ if (!app_icon.empty()) {
+ gfx::Image decoded_image = gfx::Image::CreateFrom1xBitmap(app_icon);
+ scoped_refptr<base::RefCountedMemory> raw_data =
+ decoded_image.As1xPNGBytes();
+ base::Base64Encode(
+ base::StringPiece(raw_data->front_as<char>(), raw_data->size()),
+ &string_encoded_icon);
+ }
+
PaymentAppInstaller::Install(
- web_contents, app_name, url, scope, sw_use_cache, enabled_methods,
+ web_contents, app_name, string_encoded_icon, url, scope, sw_use_cache,
+ method,
base::BindOnce(&OnInstallPaymentApp, std::move(event_data),
std::move(callback)));
}
@@ -449,8 +466,36 @@ void PaymentAppProviderImpl::AbortPayment(BrowserContext* browser_context,
base::BindOnce(&DispatchAbortPaymentEvent, std::move(callback)));
}
-PaymentAppProviderImpl::PaymentAppProviderImpl() {}
+void PaymentAppProviderImpl::SetOpenedWindow(WebContents* web_contents) {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+
+ CloseOpenedWindow(web_contents->GetBrowserContext());
+
+ payment_handler_windows_[web_contents->GetBrowserContext()] =
+ std::make_unique<PaymentHandlerWindowObserver>(web_contents);
+}
+
+void PaymentAppProviderImpl::CloseOpenedWindow(
+ BrowserContext* browser_context) {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+
+ auto it = payment_handler_windows_.find(browser_context);
+ if (it != payment_handler_windows_.end()) {
+ if (it->second->web_contents() != nullptr) {
+ it->second->web_contents()->Close();
+ }
+ payment_handler_windows_.erase(it);
+ }
+}
+
+PaymentAppProviderImpl::PaymentAppProviderImpl() = default;
+
+PaymentAppProviderImpl::~PaymentAppProviderImpl() = default;
-PaymentAppProviderImpl::~PaymentAppProviderImpl() {}
+PaymentAppProviderImpl::PaymentHandlerWindowObserver::
+ PaymentHandlerWindowObserver(WebContents* web_contents)
+ : WebContentsObserver(web_contents) {}
+PaymentAppProviderImpl::PaymentHandlerWindowObserver::
+ ~PaymentHandlerWindowObserver() = default;
} // namespace content
diff --git a/chromium/content/browser/payments/payment_app_provider_impl.h b/chromium/content/browser/payments/payment_app_provider_impl.h
index 620baa3f3c1..09cd78ff9f5 100644
--- a/chromium/content/browser/payments/payment_app_provider_impl.h
+++ b/chromium/content/browser/payments/payment_app_provider_impl.h
@@ -9,6 +9,7 @@
#include "base/memory/singleton.h"
#include "content/common/content_export.h"
#include "content/public/browser/payment_app_provider.h"
+#include "content/public/browser/web_contents_observer.h"
namespace content {
@@ -28,10 +29,11 @@ class CONTENT_EXPORT PaymentAppProviderImpl : public PaymentAppProvider {
WebContents* web_contents,
payments::mojom::PaymentRequestEventDataPtr event_data,
const std::string& app_name,
+ const SkBitmap& app_icon,
const std::string& sw_js_url,
const std::string& sw_scope,
bool sw_use_cache,
- const std::vector<std::string>& enabled_methods,
+ const std::string& method,
InvokePaymentAppCallback callback) override;
void CanMakePayment(BrowserContext* browser_context,
int64_t registration_id,
@@ -40,6 +42,8 @@ class CONTENT_EXPORT PaymentAppProviderImpl : public PaymentAppProvider {
void AbortPayment(BrowserContext* browser_context,
int64_t registration_id,
PaymentEventResultCallback callback) override;
+ void SetOpenedWindow(WebContents* web_contents) override;
+ void CloseOpenedWindow(BrowserContext* browser_context) override;
private:
PaymentAppProviderImpl();
@@ -47,6 +51,17 @@ class CONTENT_EXPORT PaymentAppProviderImpl : public PaymentAppProvider {
friend struct base::DefaultSingletonTraits<PaymentAppProviderImpl>;
+ // Note that constructor of WebContentsObserver is protected.
+ class PaymentHandlerWindowObserver : public WebContentsObserver {
+ public:
+ explicit PaymentHandlerWindowObserver(WebContents* web_contents);
+ ~PaymentHandlerWindowObserver() override;
+ };
+
+ // Map to maintain at most one opened window per browser context.
+ std::map<BrowserContext*, std::unique_ptr<PaymentHandlerWindowObserver>>
+ payment_handler_windows_;
+
DISALLOW_COPY_AND_ASSIGN(PaymentAppProviderImpl);
};
diff --git a/chromium/content/browser/payments/payment_app_provider_impl_unittest.cc b/chromium/content/browser/payments/payment_app_provider_impl_unittest.cc
index aca22ef2092..ef9b9a68aa4 100644
--- a/chromium/content/browser/payments/payment_app_provider_impl_unittest.cc
+++ b/chromium/content/browser/payments/payment_app_provider_impl_unittest.cc
@@ -10,8 +10,13 @@
#include "base/run_loop.h"
#include "content/browser/payments/payment_app_content_unittest_base.h"
#include "content/browser/payments/payment_app_provider_impl.h"
+#include "content/public/browser/permission_type.h"
+#include "content/public/test/mock_permission_manager.h"
+#include "content/public/test/test_browser_context.h"
+#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/modules/payments/payment_app.mojom.h"
+#include "third_party/blink/public/platform/modules/payments/payment_app.mojom.h"
+#include "third_party/blink/public/platform/modules/permissions/permission_status.mojom.h"
#include "url/gurl.h"
namespace content {
@@ -51,7 +56,17 @@ void PaymentEventResultCallback(base::OnceClosure callback,
class PaymentAppProviderTest : public PaymentAppContentUnitTestBase {
public:
- PaymentAppProviderTest() {}
+ PaymentAppProviderTest() {
+ std::unique_ptr<MockPermissionManager> mock_permission_manager(
+ new testing::NiceMock<MockPermissionManager>());
+ ON_CALL(*mock_permission_manager,
+ GetPermissionStatus(PermissionType::PAYMENT_HANDLER, testing::_,
+ testing::_))
+ .WillByDefault(
+ testing::Return(blink::mojom::PermissionStatus::GRANTED));
+ static_cast<TestBrowserContext*>(browser_context())
+ ->SetPermissionManager(std::move(mock_permission_manager));
+ }
~PaymentAppProviderTest() override {}
void SetPaymentInstrument(
@@ -196,17 +211,17 @@ TEST_F(PaymentAppProviderTest, GetAllPaymentAppsTest) {
PaymentHandlerStatus status;
PaymentInstrumentPtr instrument_1 = PaymentInstrument::New();
- instrument_1->enabled_methods.push_back("hellopay");
+ instrument_1->method = "hellopay";
SetPaymentInstrument(manager1, "test_key1", std::move(instrument_1),
base::BindOnce(&SetPaymentInstrumentCallback, &status));
PaymentInstrumentPtr instrument_2 = PaymentInstrument::New();
- instrument_2->enabled_methods.push_back("hellopay");
+ instrument_2->method = "hellopay";
SetPaymentInstrument(manager2, "test_key2", std::move(instrument_2),
base::BindOnce(&SetPaymentInstrumentCallback, &status));
PaymentInstrumentPtr instrument_3 = PaymentInstrument::New();
- instrument_3->enabled_methods.push_back("bobpay");
+ instrument_3->method = "bobpay";
SetPaymentInstrument(manager2, "test_key3", std::move(instrument_3),
base::BindOnce(&SetPaymentInstrumentCallback, &status));
@@ -229,17 +244,17 @@ TEST_F(PaymentAppProviderTest, GetAllPaymentAppsFromTheSameOriginTest) {
PaymentHandlerStatus status;
PaymentInstrumentPtr instrument_1 = PaymentInstrument::New();
- instrument_1->enabled_methods.push_back("hellopay");
+ instrument_1->method = "hellopay";
SetPaymentInstrument(manager1, "test_key1", std::move(instrument_1),
base::BindOnce(&SetPaymentInstrumentCallback, &status));
PaymentInstrumentPtr instrument_2 = PaymentInstrument::New();
- instrument_2->enabled_methods.push_back("hellopay");
+ instrument_2->method = "hellopay";
SetPaymentInstrument(manager2, "test_key2", std::move(instrument_2),
base::BindOnce(&SetPaymentInstrumentCallback, &status));
PaymentInstrumentPtr instrument_3 = PaymentInstrument::New();
- instrument_3->enabled_methods.push_back("bobpay");
+ instrument_3->method = "bobpay";
SetPaymentInstrument(manager2, "test_key3", std::move(instrument_3),
base::BindOnce(&SetPaymentInstrumentCallback, &status));
diff --git a/chromium/content/browser/payments/payment_instrument_icon_fetcher.h b/chromium/content/browser/payments/payment_instrument_icon_fetcher.h
index c28d8165f2b..9e4f9adb866 100644
--- a/chromium/content/browser/payments/payment_instrument_icon_fetcher.h
+++ b/chromium/content/browser/payments/payment_instrument_icon_fetcher.h
@@ -12,7 +12,7 @@
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "content/public/common/manifest.h"
-#include "third_party/WebKit/public/platform/modules/payments/payment_app.mojom.h"
+#include "third_party/blink/public/platform/modules/payments/payment_app.mojom.h"
namespace content {
diff --git a/chromium/content/browser/payments/payment_manager.cc b/chromium/content/browser/payments/payment_manager.cc
index e2a44953105..f3631656678 100644
--- a/chromium/content/browser/payments/payment_manager.cc
+++ b/chromium/content/browser/payments/payment_manager.cc
@@ -121,8 +121,8 @@ void PaymentManager::SetPaymentInstrumentIntermediateCallback(
return;
}
- payment_app_context_->payment_app_database()->FetchAndWritePaymentAppInfo(
- context_url_, scope_, user_hint_, std::move(callback));
+ payment_app_context_->payment_app_database()->FetchAndUpdatePaymentAppInfo(
+ context_url_, scope_, std::move(callback));
should_set_payment_app_info_ = false;
}
@@ -135,12 +135,8 @@ void PaymentManager::ClearPaymentInstruments(
}
void PaymentManager::SetUserHint(const std::string& user_hint) {
- user_hint_ = user_hint;
- if (should_set_payment_app_info_)
- return;
-
payment_app_context_->payment_app_database()->SetPaymentAppUserHint(
- scope_, user_hint_);
+ scope_, user_hint);
}
void PaymentManager::OnConnectionError() {
diff --git a/chromium/content/browser/payments/payment_manager.h b/chromium/content/browser/payments/payment_manager.h
index 58b7cb3592b..87a63ae300c 100644
--- a/chromium/content/browser/payments/payment_manager.h
+++ b/chromium/content/browser/payments/payment_manager.h
@@ -11,7 +11,7 @@
#include "base/memory/weak_ptr.h"
#include "content/common/content_export.h"
#include "mojo/public/cpp/bindings/binding.h"
-#include "third_party/WebKit/public/platform/modules/payments/payment_app.mojom.h"
+#include "third_party/blink/public/platform/modules/payments/payment_app.mojom.h"
#include "url/gurl.h"
namespace content {
@@ -62,7 +62,6 @@ class CONTENT_EXPORT PaymentManager : public payments::mojom::PaymentManager {
bool should_set_payment_app_info_;
GURL context_url_;
GURL scope_;
- std::string user_hint_;
mojo::Binding<payments::mojom::PaymentManager> binding_;
base::WeakPtrFactory<PaymentManager> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(PaymentManager);
diff --git a/chromium/content/browser/payments/payment_manager_unittest.cc b/chromium/content/browser/payments/payment_manager_unittest.cc
index 94eec8bf828..b1320ce7ad5 100644
--- a/chromium/content/browser/payments/payment_manager_unittest.cc
+++ b/chromium/content/browser/payments/payment_manager_unittest.cc
@@ -8,7 +8,7 @@
#include "base/run_loop.h"
#include "content/browser/payments/payment_app_content_unittest_base.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/modules/payments/payment_app.mojom.h"
+#include "third_party/blink/public/platform/modules/payments/payment_app.mojom.h"
#include "url/gurl.h"
namespace content {
@@ -126,8 +126,8 @@ class PaymentManagerTest : public PaymentAppContentUnitTestBase {
TEST_F(PaymentManagerTest, SetAndGetPaymentInstrument) {
PaymentHandlerStatus write_status = PaymentHandlerStatus::NOT_FOUND;
PaymentInstrumentPtr write_details = PaymentInstrument::New();
- write_details->name = "Visa ending ****4756",
- write_details->enabled_methods.push_back("visa");
+ write_details->name = "Visa ending ****4756";
+ write_details->method = "visa";
write_details->stringified_capabilities = "{}";
SetPaymentInstrument("test_key", std::move(write_details), &write_status);
// Write the first instrument of a web payment app will return
@@ -141,8 +141,7 @@ TEST_F(PaymentManagerTest, SetAndGetPaymentInstrument) {
GetPaymentInstrument("test_key", &read_details, &read_status);
ASSERT_EQ(PaymentHandlerStatus::SUCCESS, read_status);
EXPECT_EQ("Visa ending ****4756", read_details->name);
- ASSERT_EQ(1U, read_details->enabled_methods.size());
- EXPECT_EQ("visa", read_details->enabled_methods[0]);
+ EXPECT_EQ("visa", read_details->method);
EXPECT_EQ("{}", read_details->stringified_capabilities);
}
@@ -156,8 +155,8 @@ TEST_F(PaymentManagerTest, GetUnstoredPaymentInstrument) {
TEST_F(PaymentManagerTest, DeletePaymentInstrument) {
PaymentHandlerStatus write_status = PaymentHandlerStatus::NOT_FOUND;
PaymentInstrumentPtr write_details = PaymentInstrument::New();
- write_details->name = "Visa ending ****4756",
- write_details->enabled_methods.push_back("visa");
+ write_details->name = "Visa ending ****4756";
+ write_details->method = "visa";
write_details->stringified_capabilities = "{}";
SetPaymentInstrument("test_key", std::move(write_details), &write_status);
// Write the first instrument of a web payment app will return
@@ -183,8 +182,8 @@ TEST_F(PaymentManagerTest, DeletePaymentInstrument) {
TEST_F(PaymentManagerTest, HasPaymentInstrument) {
PaymentHandlerStatus write_status = PaymentHandlerStatus::NOT_FOUND;
PaymentInstrumentPtr write_details = PaymentInstrument::New();
- write_details->name = "Visa ending ****4756",
- write_details->enabled_methods.push_back("visa");
+ write_details->name = "Visa ending ****4756";
+ write_details->method = "visa";
write_details->stringified_capabilities = "{}";
SetPaymentInstrument("test_key", std::move(write_details), &write_status);
// Write the first instrument of a web payment app will return
diff --git a/chromium/content/browser/permissions/permission_service_context.h b/chromium/content/browser/permissions/permission_service_context.h
index 9aaf008d030..6c0dda7c6bc 100644
--- a/chromium/content/browser/permissions/permission_service_context.h
+++ b/chromium/content/browser/permissions/permission_service_context.h
@@ -10,7 +10,7 @@
#include "content/public/browser/permission_type.h"
#include "content/public/browser/web_contents_observer.h"
#include "mojo/public/cpp/bindings/strong_binding_set.h"
-#include "third_party/WebKit/public/platform/modules/permissions/permission.mojom.h"
+#include "third_party/blink/public/platform/modules/permissions/permission.mojom.h"
namespace url {
class Origin;
diff --git a/chromium/content/browser/permissions/permission_service_impl.cc b/chromium/content/browser/permissions/permission_service_impl.cc
index ef2b048c77a..f6c0538a690 100644
--- a/chromium/content/browser/permissions/permission_service_impl.cc
+++ b/chromium/content/browser/permissions/permission_service_impl.cc
@@ -10,7 +10,6 @@
#include <utility>
#include "base/bind.h"
-#include "base/memory/ptr_util.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/permission_manager.h"
#include "content/public/browser/permission_type.h"
@@ -229,11 +228,14 @@ PermissionStatus PermissionServiceImpl::GetPermissionStatusFromType(
return PermissionStatus::DENIED;
GURL requesting_origin(origin_.GetURL());
- // If the embedding_origin is empty we'll use |origin_| instead.
- GURL embedding_origin = context_->GetEmbeddingOrigin();
+ if (context_->render_frame_host()) {
+ return browser_context->GetPermissionManager()->GetPermissionStatusForFrame(
+ type, context_->render_frame_host(), requesting_origin);
+ }
+
+ DCHECK(context_->GetEmbeddingOrigin().is_empty());
return browser_context->GetPermissionManager()->GetPermissionStatus(
- type, requesting_origin,
- embedding_origin.is_empty() ? requesting_origin : embedding_origin);
+ type, requesting_origin, requesting_origin);
}
void PermissionServiceImpl::ResetPermissionStatus(PermissionType type) {
diff --git a/chromium/content/browser/permissions/permission_service_impl.h b/chromium/content/browser/permissions/permission_service_impl.h
index 6e0c9bc825e..ae0e8a4df99 100644
--- a/chromium/content/browser/permissions/permission_service_impl.h
+++ b/chromium/content/browser/permissions/permission_service_impl.h
@@ -11,7 +11,7 @@
#include "base/memory/weak_ptr.h"
#include "content/browser/permissions/permission_service_context.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/modules/permissions/permission.mojom.h"
+#include "third_party/blink/public/platform/modules/permissions/permission.mojom.h"
#include "url/origin.h"
namespace content {
diff --git a/chromium/content/browser/picture_in_picture/OWNERS b/chromium/content/browser/picture_in_picture/OWNERS
new file mode 100644
index 00000000000..645933b2f35
--- /dev/null
+++ b/chromium/content/browser/picture_in_picture/OWNERS
@@ -0,0 +1,4 @@
+apacible@chromium.org
+mlamouri@chromium.org
+
+# COMPONENT: Internals>Media>UI
diff --git a/chromium/content/browser/picture_in_picture/overlay_surface_embedder.cc b/chromium/content/browser/picture_in_picture/overlay_surface_embedder.cc
new file mode 100644
index 00000000000..6af72c47f20
--- /dev/null
+++ b/chromium/content/browser/picture_in_picture/overlay_surface_embedder.cc
@@ -0,0 +1,40 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/picture_in_picture/overlay_surface_embedder.h"
+
+#include "ui/compositor/layer.h"
+
+namespace content {
+
+OverlaySurfaceEmbedder::OverlaySurfaceEmbedder(OverlayWindow* window)
+ : window_(window) {
+ DCHECK(window_);
+ surface_layer_ = std::make_unique<ui::Layer>(ui::LAYER_TEXTURED);
+ surface_layer_->SetMasksToBounds(true);
+
+ // The frame provided by the parent window's layer needs to show through
+ // |surface_layer_|.
+ surface_layer_->SetFillsBoundsOpaquely(false);
+ // |surface_layer_| bounds are set with the (0, 0) origin point. The
+ // positioning of |window_| is dictated by itself.
+ // TODO(apacible): Update |surface_layer_| size when the window is resized.
+ // http://crbug.com/726621
+ surface_layer_->SetBounds(
+ gfx::Rect(gfx::Point(0, 0), window_->GetBounds().size()));
+ window_->GetLayer()->Add(surface_layer_.get());
+}
+
+OverlaySurfaceEmbedder::~OverlaySurfaceEmbedder() = default;
+
+void OverlaySurfaceEmbedder::SetPrimarySurfaceId(
+ const viz::SurfaceId& surface_id) {
+ // SurfaceInfo has information about the embedded surface.
+ surface_layer_->SetShowPrimarySurface(
+ surface_id, window_->GetBounds().size(), SK_ColorBLACK,
+ cc::DeadlinePolicy::UseDefaultDeadline(),
+ true /* stretch_content_to_fill_bounds */);
+}
+
+} // namespace content
diff --git a/chromium/content/browser/picture_in_picture/overlay_surface_embedder.h b/chromium/content/browser/picture_in_picture/overlay_surface_embedder.h
new file mode 100644
index 00000000000..5b0858944b1
--- /dev/null
+++ b/chromium/content/browser/picture_in_picture/overlay_surface_embedder.h
@@ -0,0 +1,41 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_BROWSER_PICTURE_IN_PICTURE_OVERLAY_SURFACE_EMBEDDER_H_
+#define CONTENT_BROWSER_PICTURE_IN_PICTURE_OVERLAY_SURFACE_EMBEDDER_H_
+
+#include <memory>
+
+#include "content/public/browser/overlay_window.h"
+
+namespace viz {
+class SurfaceId;
+}
+
+namespace content {
+
+// Embed a surface into the OverlayWindow to show content. Responsible for
+// setting up the surface layers that contain content to show on the
+// OverlayWindow.
+class OverlaySurfaceEmbedder {
+ public:
+ explicit OverlaySurfaceEmbedder(OverlayWindow* window);
+ ~OverlaySurfaceEmbedder();
+
+ void SetPrimarySurfaceId(const viz::SurfaceId& surface_id);
+
+ private:
+ // The window which embeds the client. Weak pointer since the
+ // PictureInPictureWindowController owns the window.
+ OverlayWindow* window_;
+
+ // Contains the client's content.
+ std::unique_ptr<ui::Layer> surface_layer_;
+
+ DISALLOW_COPY_AND_ASSIGN(OverlaySurfaceEmbedder);
+};
+
+} // namespace content
+
+#endif // CONTENT_BROWSER_PICTURE_IN_PICTURE_OVERLAY_SURFACE_EMBEDDER_H_
diff --git a/chromium/content/browser/picture_in_picture/picture_in_picture_window_controller_impl.cc b/chromium/content/browser/picture_in_picture/picture_in_picture_window_controller_impl.cc
new file mode 100644
index 00000000000..e3c6e4fa4ed
--- /dev/null
+++ b/chromium/content/browser/picture_in_picture/picture_in_picture_window_controller_impl.cc
@@ -0,0 +1,106 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/picture_in_picture/picture_in_picture_window_controller_impl.h"
+
+#include "components/viz/common/surfaces/surface_id.h"
+#include "content/browser/media/media_web_contents_observer.h"
+#include "content/browser/picture_in_picture/overlay_surface_embedder.h"
+#include "content/browser/web_contents/web_contents_impl.h"
+#include "content/common/media/media_player_delegate_messages.h"
+#include "content/public/browser/content_browser_client.h"
+#include "content/public/browser/overlay_window.h"
+#include "content/public/browser/web_contents.h"
+#include "content/public/common/content_client.h"
+
+namespace content {
+
+DEFINE_WEB_CONTENTS_USER_DATA_KEY(PictureInPictureWindowControllerImpl);
+
+// static
+PictureInPictureWindowController*
+PictureInPictureWindowController::GetOrCreateForWebContents(
+ WebContents* web_contents) {
+ return PictureInPictureWindowControllerImpl::GetOrCreateForWebContents(
+ web_contents);
+}
+
+// static
+PictureInPictureWindowControllerImpl*
+PictureInPictureWindowControllerImpl::GetOrCreateForWebContents(
+ WebContents* web_contents) {
+ DCHECK(web_contents);
+
+ // This is a no-op if the controller already exists.
+ CreateForWebContents(web_contents);
+ return FromWebContents(web_contents);
+}
+
+PictureInPictureWindowControllerImpl::~PictureInPictureWindowControllerImpl() {
+ if (window_)
+ window_->Close();
+}
+
+PictureInPictureWindowControllerImpl::PictureInPictureWindowControllerImpl(
+ WebContents* initiator)
+ : initiator_(initiator) {
+ DCHECK(initiator_);
+
+ window_ =
+ content::GetContentClient()->browser()->CreateWindowForPictureInPicture(
+ this);
+ DCHECK(window_) << "Picture in Picture requires a valid window.";
+}
+
+void PictureInPictureWindowControllerImpl::Show() {
+ DCHECK(window_);
+ DCHECK(surface_id_.is_valid());
+ window_->Show();
+}
+
+void PictureInPictureWindowControllerImpl::Close() {
+ if (window_)
+ window_->Close();
+
+ surface_id_ = viz::SurfaceId();
+}
+
+void PictureInPictureWindowControllerImpl::EmbedSurface(
+ const viz::SurfaceId& surface_id,
+ const gfx::Size& natural_size) {
+ DCHECK(window_);
+ DCHECK(surface_id.is_valid());
+ surface_id_ = surface_id;
+
+ window_->UpdateVideoSize(natural_size);
+
+ if (!embedder_)
+ embedder_.reset(new OverlaySurfaceEmbedder(window_.get()));
+ embedder_->SetPrimarySurfaceId(surface_id_);
+}
+
+OverlayWindow* PictureInPictureWindowControllerImpl::GetWindowForTesting() {
+ return window_.get();
+}
+
+void PictureInPictureWindowControllerImpl::TogglePlayPause() {
+ DCHECK(window_ && window_->IsActive());
+
+ content::MediaWebContentsObserver* observer =
+ static_cast<content::WebContentsImpl* const>(initiator_)
+ ->media_web_contents_observer();
+ base::Optional<content::WebContentsObserver::MediaPlayerId> player_id =
+ observer->GetPictureInPictureVideoMediaPlayerId();
+ DCHECK(player_id.has_value());
+
+ if (observer->IsPlayerActive(*player_id)) {
+ player_id->first->Send(new MediaPlayerDelegateMsg_Pause(
+ player_id->first->GetRoutingID(), player_id->second));
+ } else {
+ player_id->first->Send(new MediaPlayerDelegateMsg_Play(
+ player_id->first->GetRoutingID(), player_id->second));
+ }
+}
+
+} // namespace content \ No newline at end of file
diff --git a/chromium/content/browser/picture_in_picture/picture_in_picture_window_controller_impl.h b/chromium/content/browser/picture_in_picture/picture_in_picture_window_controller_impl.h
new file mode 100644
index 00000000000..4746e6915a1
--- /dev/null
+++ b/chromium/content/browser/picture_in_picture/picture_in_picture_window_controller_impl.h
@@ -0,0 +1,62 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_BROWSER_PICTURE_IN_PICTURE_PICTURE_IN_PICTURE_WINDOW_CONTROLLER_IMPL_H_
+#define CONTENT_BROWSER_PICTURE_IN_PICTURE_PICTURE_IN_PICTURE_WINDOW_CONTROLLER_IMPL_H_
+
+#include "base/memory/weak_ptr.h"
+#include "components/viz/common/surfaces/parent_local_surface_id_allocator.h"
+#include "content/public/browser/picture_in_picture_window_controller.h"
+#include "content/public/browser/web_contents_user_data.h"
+
+namespace content {
+class OverlaySurfaceEmbedder;
+class WebContents;
+
+// TODO(thakis,mlamouri): PictureInPictureWindowControllerImpl isn't
+// CONTENT_EXPORT'd because it creates complicated build issues with
+// WebContentsUserData being a non-exported template. As a result, the class
+// uses CONTENT_EXPORT for methods that are being used from tests.
+// CONTENT_EXPORT should be moved back to the class when the Windows build will
+// work with it. https://crbug.com/589840.
+class PictureInPictureWindowControllerImpl
+ : public PictureInPictureWindowController,
+ public WebContentsUserData<PictureInPictureWindowControllerImpl> {
+ public:
+ // Gets a reference to the controller associated with |initiator| and creates
+ // one if it does not exist. The returned pointer is guaranteed to be
+ // non-null.
+ CONTENT_EXPORT static PictureInPictureWindowControllerImpl*
+ GetOrCreateForWebContents(WebContents* initiator);
+
+ ~PictureInPictureWindowControllerImpl() override;
+
+ // PictureInPictureWindowController:
+ CONTENT_EXPORT void Show() override;
+ CONTENT_EXPORT void Close() override;
+ CONTENT_EXPORT void EmbedSurface(const viz::SurfaceId& surface_id,
+ const gfx::Size& natural_size) override;
+ CONTENT_EXPORT OverlayWindow* GetWindowForTesting() override;
+ CONTENT_EXPORT void TogglePlayPause() override;
+
+ private:
+ friend class WebContentsUserData<PictureInPictureWindowControllerImpl>;
+
+ // Use PictureInPictureWindowControllerImpl::GetOrCreateForWebContents() to
+ // create an instance.
+ CONTENT_EXPORT explicit PictureInPictureWindowControllerImpl(
+ WebContents* initiator);
+
+ std::unique_ptr<OverlayWindow> window_;
+ std::unique_ptr<OverlaySurfaceEmbedder> embedder_;
+ content::WebContents* const initiator_;
+
+ viz::SurfaceId surface_id_;
+
+ DISALLOW_COPY_AND_ASSIGN(PictureInPictureWindowControllerImpl);
+};
+
+} // namespace content
+
+#endif // CONTENT_BROWSER_PICTURE_IN_PICTURE_PICTURE_IN_PICTURE_WINDOW_CONTROLLER_IMPL_H_ \ No newline at end of file
diff --git a/chromium/content/browser/plugin_private_storage_helper.cc b/chromium/content/browser/plugin_private_storage_helper.cc
index 12ee66f4f43..60fa438616b 100644
--- a/chromium/content/browser/plugin_private_storage_helper.cc
+++ b/chromium/content/browser/plugin_private_storage_helper.cc
@@ -10,6 +10,7 @@
#include <memory>
#include <set>
#include <string>
+#include <utility>
#include "base/bind.h"
#include "base/compiler_specific.h"
@@ -18,7 +19,6 @@
#include "base/files/file_path.h"
#include "base/location.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/stl_util.h"
#include "base/strings/utf_string_conversions.h"
#include "content/public/browser/browser_thread.h"
@@ -181,21 +181,23 @@ void PluginPrivateDataByOriginChecker::OnDirectoryRead(
storage::AsyncFileUtil* file_util = filesystem_context_->GetAsyncFileUtil(
storage::kFileSystemTypePluginPrivate);
for (const auto& file : file_list) {
- DVLOG(3) << __func__ << " file: " << file.name;
- DCHECK(!file.is_directory); // Nested directories not implemented.
+ DVLOG(3) << __func__ << " file: " << file.name.value();
+ // Nested directories not implemented.
+ DCHECK_NE(file.type, filesystem::mojom::FsFileType::DIRECTORY);
std::unique_ptr<storage::FileSystemOperationContext> operation_context =
std::make_unique<storage::FileSystemOperationContext>(
filesystem_context_);
storage::FileSystemURL file_url = filesystem_context_->CrackURL(
- GURL(root + StringTypeToString(file.name)));
+ GURL(root + StringTypeToString(file.name.value())));
IncrementTaskCount();
file_util->GetFileInfo(
std::move(operation_context), file_url,
storage::FileSystemOperation::GET_METADATA_FIELD_SIZE |
storage::FileSystemOperation::GET_METADATA_FIELD_LAST_MODIFIED,
- base::Bind(&PluginPrivateDataByOriginChecker::OnFileInfo,
- base::Unretained(this), StringTypeToString(file.name)));
+ base::BindOnce(&PluginPrivateDataByOriginChecker::OnFileInfo,
+ base::Unretained(this),
+ StringTypeToString(file.name.value())));
}
}
diff --git a/chromium/content/browser/plugin_private_storage_helper.h b/chromium/content/browser/plugin_private_storage_helper.h
index 8b80f6f8ed7..2f92bfa51a4 100644
--- a/chromium/content/browser/plugin_private_storage_helper.h
+++ b/chromium/content/browser/plugin_private_storage_helper.h
@@ -5,7 +5,7 @@
#ifndef CONTENT_BROWSER_PLUGIN_PRIVATE_STORAGE_HELPER_H_
#define CONTENT_BROWSER_PLUGIN_PRIVATE_STORAGE_HELPER_H_
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#if !BUILDFLAG(ENABLE_PLUGINS)
#error This file should only be included when plugins are enabled.
diff --git a/chromium/content/browser/plugin_service_impl.cc b/chromium/content/browser/plugin_service_impl.cc
index 130f4d8e92e..dcdae19642b 100644
--- a/chromium/content/browser/plugin_service_impl.cc
+++ b/chromium/content/browser/plugin_service_impl.cc
@@ -124,16 +124,31 @@ void PluginServiceImpl::Init() {
PpapiPluginProcessHost* PluginServiceImpl::FindPpapiPluginProcess(
const base::FilePath& plugin_path,
- const base::FilePath& profile_data_directory) {
+ const base::FilePath& profile_data_directory,
+ const base::Optional<url::Origin>& origin_lock) {
for (PpapiPluginProcessHostIterator iter; !iter.Done(); ++iter) {
if (iter->plugin_path() == plugin_path &&
- iter->profile_data_directory() == profile_data_directory) {
+ iter->profile_data_directory() == profile_data_directory &&
+ (!iter->origin_lock() || iter->origin_lock() == origin_lock)) {
return *iter;
}
}
return nullptr;
}
+int PluginServiceImpl::CountPpapiPluginProcessesForProfile(
+ const base::FilePath& plugin_path,
+ const base::FilePath& profile_data_directory) {
+ int count = 0;
+ for (PpapiPluginProcessHostIterator iter; !iter.Done(); ++iter) {
+ if (iter->plugin_path() == plugin_path &&
+ iter->profile_data_directory() == profile_data_directory) {
+ ++count;
+ }
+ }
+ return count;
+}
+
PpapiPluginProcessHost* PluginServiceImpl::FindPpapiBrokerProcess(
const base::FilePath& broker_path) {
for (PpapiBrokerProcessHostIterator iter; !iter.Done(); ++iter) {
@@ -147,7 +162,8 @@ PpapiPluginProcessHost* PluginServiceImpl::FindPpapiBrokerProcess(
PpapiPluginProcessHost* PluginServiceImpl::FindOrStartPpapiPluginProcess(
int render_process_id,
const base::FilePath& plugin_path,
- const base::FilePath& profile_data_directory) {
+ const base::FilePath& profile_data_directory,
+ const base::Optional<url::Origin>& origin_lock) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (filter_ && !filter_->CanLoadPlugin(render_process_id, plugin_path)) {
@@ -155,11 +171,6 @@ PpapiPluginProcessHost* PluginServiceImpl::FindOrStartPpapiPluginProcess(
return nullptr;
}
- PpapiPluginProcessHost* plugin_host =
- FindPpapiPluginProcess(plugin_path, profile_data_directory);
- if (plugin_host)
- return plugin_host;
-
// Validate that the plugin is actually registered.
PepperPluginInfo* info = GetRegisteredPpapiPluginInfo(plugin_path);
if (!info) {
@@ -168,6 +179,11 @@ PpapiPluginProcessHost* PluginServiceImpl::FindOrStartPpapiPluginProcess(
return nullptr;
}
+ PpapiPluginProcessHost* plugin_host =
+ FindPpapiPluginProcess(plugin_path, profile_data_directory, origin_lock);
+ if (plugin_host)
+ return plugin_host;
+
// Record when PPAPI Flash process is started for the first time.
static bool counted = false;
if (!counted && info->name == kFlashPluginName) {
@@ -177,9 +193,16 @@ PpapiPluginProcessHost* PluginServiceImpl::FindOrStartPpapiPluginProcess(
FLASH_USAGE_ENUM_COUNT);
}
+ // Avoid fork bomb.
+ if (origin_lock.has_value() && CountPpapiPluginProcessesForProfile(
+ plugin_path, profile_data_directory) >=
+ max_ppapi_processes_per_profile_) {
+ return nullptr;
+ }
+
// This plugin isn't loaded by any plugin process, so create a new process.
plugin_host = PpapiPluginProcessHost::CreatePluginHost(
- *info, profile_data_directory);
+ *info, profile_data_directory, origin_lock);
if (!plugin_host) {
VLOG(1) << "Unable to create ppapi plugin process for: "
<< plugin_path.MaybeAsASCII();
@@ -216,9 +239,10 @@ void PluginServiceImpl::OpenChannelToPpapiPlugin(
int render_process_id,
const base::FilePath& plugin_path,
const base::FilePath& profile_data_directory,
+ const base::Optional<url::Origin>& origin_lock,
PpapiPluginProcessHost::PluginClient* client) {
PpapiPluginProcessHost* plugin_host = FindOrStartPpapiPluginProcess(
- render_process_id, plugin_path, profile_data_directory);
+ render_process_id, plugin_path, profile_data_directory, origin_lock);
if (plugin_host) {
plugin_host->OpenChannelToPlugin(client);
} else {
diff --git a/chromium/content/browser/plugin_service_impl.h b/chromium/content/browser/plugin_service_impl.h
index e6de4ca6c8b..4e11056a3dc 100644
--- a/chromium/content/browser/plugin_service_impl.h
+++ b/chromium/content/browser/plugin_service_impl.h
@@ -8,7 +8,7 @@
#ifndef CONTENT_BROWSER_PLUGIN_SERVICE_IMPL_H_
#define CONTENT_BROWSER_PLUGIN_SERVICE_IMPL_H_
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#if !BUILDFLAG(ENABLE_PLUGINS)
#error "Plugins should be enabled"
@@ -21,6 +21,7 @@
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/memory/singleton.h"
+#include "base/optional.h"
#include "base/sequence_checker.h"
#include "base/sequenced_task_runner.h"
#include "base/synchronization/waitable_event_watcher.h"
@@ -32,6 +33,7 @@
#include "content/public/common/pepper_plugin_info.h"
#include "ipc/ipc_channel_handle.h"
#include "url/gurl.h"
+#include "url/origin.h"
#if defined(OS_WIN)
#include "base/win/registry.h"
@@ -86,6 +88,9 @@ class CONTENT_EXPORT PluginServiceImpl : public PluginService {
void GetInternalPlugins(std::vector<WebPluginInfo>* plugins) override;
bool PpapiDevChannelSupported(BrowserContext* browser_context,
const GURL& document_url) override;
+ int CountPpapiPluginProcessesForProfile(
+ const base::FilePath& plugin_path,
+ const base::FilePath& profile_data_directory) override;
// Returns the plugin process host corresponding to the plugin process that
// has been started by this service. This will start a process to host the
@@ -94,7 +99,8 @@ class CONTENT_EXPORT PluginServiceImpl : public PluginService {
PpapiPluginProcessHost* FindOrStartPpapiPluginProcess(
int render_process_id,
const base::FilePath& plugin_path,
- const base::FilePath& profile_data_directory);
+ const base::FilePath& profile_data_directory,
+ const base::Optional<url::Origin>& origin_lock);
PpapiPluginProcessHost* FindOrStartPpapiBrokerProcess(
int render_process_id, const base::FilePath& plugin_path);
@@ -104,6 +110,7 @@ class CONTENT_EXPORT PluginServiceImpl : public PluginService {
void OpenChannelToPpapiPlugin(int render_process_id,
const base::FilePath& plugin_path,
const base::FilePath& profile_data_directory,
+ const base::Optional<url::Origin>& origin_lock,
PpapiPluginProcessHost::PluginClient* client);
void OpenChannelToPpapiBroker(int render_process_id,
int render_frame_id,
@@ -113,9 +120,17 @@ class CONTENT_EXPORT PluginServiceImpl : public PluginService {
// Used to monitor plugin stability.
void RegisterPluginCrash(const base::FilePath& plugin_path);
+ // For testing without creating many, many processes.
+ void SetMaxPpapiProcessesPerProfileForTesting(int number) {
+ max_ppapi_processes_per_profile_ = number;
+ }
+
private:
friend struct base::DefaultSingletonTraits<PluginServiceImpl>;
+ // Pulled out of the air, seems reasonable.
+ static constexpr int kDefaultMaxPpapiProcessesPerProfile = 15;
+
// Helper for recording URLs to UKM.
static void RecordBrokerUsage(int render_process_id, int render_frame_id);
@@ -133,7 +148,8 @@ class CONTENT_EXPORT PluginServiceImpl : public PluginService {
// started.
PpapiPluginProcessHost* FindPpapiPluginProcess(
const base::FilePath& plugin_path,
- const base::FilePath& profile_data_directory);
+ const base::FilePath& profile_data_directory,
+ const base::Optional<url::Origin>& origin_lock);
PpapiPluginProcessHost* FindPpapiBrokerProcess(
const base::FilePath& broker_path);
@@ -144,6 +160,8 @@ class CONTENT_EXPORT PluginServiceImpl : public PluginService {
std::vector<PepperPluginInfo> ppapi_plugins_;
+ int max_ppapi_processes_per_profile_ = kDefaultMaxPpapiProcessesPerProfile;
+
// Weak pointer; outlives us.
PluginServiceFilter* filter_;
diff --git a/chromium/content/browser/plugin_service_impl_browsertest.cc b/chromium/content/browser/plugin_service_impl_browsertest.cc
new file mode 100644
index 00000000000..1dfaa4d45c8
--- /dev/null
+++ b/chromium/content/browser/plugin_service_impl_browsertest.cc
@@ -0,0 +1,174 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/plugin_service_impl.h"
+
+#include <memory>
+#include <string>
+#include <utility>
+
+#include "base/optional.h"
+#include "base/strings/stringprintf.h"
+#include "base/strings/utf_string_conversions.h"
+#include "build/build_config.h"
+#include "content/browser/ppapi_plugin_process_host.h"
+#include "content/public/browser/browser_thread.h"
+#include "content/public/test/content_browser_test.h"
+#include "testing/gtest/include/gtest/gtest.h"
+
+namespace content {
+
+namespace {
+
+constexpr char kURL1[] = "http://google.com/";
+constexpr char kURL2[] = "http://youtube.com/";
+
+class TestPluginClient : public PpapiPluginProcessHost::PluginClient {
+ public:
+ void GetPpapiChannelInfo(base::ProcessHandle* renderer_handle,
+ int* renderer_id) override {}
+ void OnPpapiChannelOpened(const IPC::ChannelHandle& channel_handle,
+ base::ProcessId plugin_pid,
+ int plugin_child_id) override {
+ plugin_pid_ = plugin_pid;
+ run_loop_->Quit();
+ }
+ bool Incognito() override { return false; }
+
+ base::ProcessId plugin_pid() const { return plugin_pid_; }
+ void SetRunLoop(base::RunLoop* run_loop) { run_loop_ = run_loop; }
+ void WaitForQuit() { run_loop_->Run(); }
+
+ private:
+ base::ProcessId plugin_pid_ = 0;
+ base::RunLoop* run_loop_ = nullptr;
+};
+
+} // anonymous namespace
+
+class PluginServiceImplBrowserTest : public ContentBrowserTest {
+ public:
+ PluginServiceImplBrowserTest()
+ : plugin_path_(FILE_PATH_LITERAL("internal-nonesuch")),
+ profile_dir_(FILE_PATH_LITERAL("/fake/user/foo/dir")) {}
+
+ ~PluginServiceImplBrowserTest() override = default;
+
+ void RegisterFakePlugin() {
+ WebPluginInfo fake_info;
+ fake_info.name = base::ASCIIToUTF16("fake_plugin");
+ fake_info.path = plugin_path_;
+ fake_info.type = WebPluginInfo::PLUGIN_TYPE_PEPPER_OUT_OF_PROCESS;
+
+ PluginServiceImpl* service = PluginServiceImpl::GetInstance();
+ service->RegisterInternalPlugin(fake_info, true);
+ service->Init();
+
+ // Force plugins to load and wait for completion.
+ base::RunLoop run_loop;
+ service->GetPlugins(base::BindOnce(
+ [](base::OnceClosure callback,
+ const std::vector<WebPluginInfo>& ignore) {
+ std::move(callback).Run();
+ },
+ run_loop.QuitClosure()));
+ run_loop.Run();
+ }
+
+ void OpenChannelToFakePlugin(const base::Optional<url::Origin>& origin,
+ TestPluginClient* client) {
+ base::RunLoop run_loop;
+ client->SetRunLoop(&run_loop);
+
+ PluginServiceImpl* service = PluginServiceImpl::GetInstance();
+ BrowserThread::PostTask(
+ BrowserThread::IO, FROM_HERE,
+ base::BindOnce(&PluginServiceImpl::OpenChannelToPpapiPlugin,
+ base::Unretained(service), 0, plugin_path_, profile_dir_,
+ origin, base::Unretained(client)));
+ client->WaitForQuit();
+ client->SetRunLoop(nullptr);
+ }
+
+ base::FilePath plugin_path_;
+ base::FilePath profile_dir_;
+};
+
+IN_PROC_BROWSER_TEST_F(PluginServiceImplBrowserTest, OriginLock) {
+ RegisterFakePlugin();
+
+ url::Origin origin1 = url::Origin::Create(GURL(kURL1));
+ url::Origin origin2 = url::Origin::Create(GURL(kURL2));
+
+ TestPluginClient client1;
+ OpenChannelToFakePlugin(origin1, &client1);
+ EXPECT_NE(base::kNullProcessId, client1.plugin_pid());
+
+ TestPluginClient client2a;
+ OpenChannelToFakePlugin(origin2, &client2a);
+ EXPECT_NE(base::kNullProcessId, client2a.plugin_pid());
+
+ TestPluginClient client2b;
+ OpenChannelToFakePlugin(origin2, &client2b);
+ EXPECT_NE(base::kNullProcessId, client2b.plugin_pid());
+
+ // Actual test: how plugins got lumped into two pids.
+ EXPECT_NE(client1.plugin_pid(), client2a.plugin_pid());
+ EXPECT_NE(client1.plugin_pid(), client2b.plugin_pid());
+ EXPECT_EQ(client2a.plugin_pid(), client2b.plugin_pid());
+
+ // Empty origins all go to same pid.
+ TestPluginClient client3a;
+ OpenChannelToFakePlugin(base::nullopt, &client3a);
+ EXPECT_NE(base::kNullProcessId, client3a.plugin_pid());
+
+ TestPluginClient client3b;
+ OpenChannelToFakePlugin(base::nullopt, &client3b);
+ EXPECT_NE(base::kNullProcessId, client3b.plugin_pid());
+
+ // Actual test: how empty origins got lumped into pids.
+ EXPECT_NE(client1.plugin_pid(), client3a.plugin_pid());
+ EXPECT_NE(client1.plugin_pid(), client3b.plugin_pid());
+ EXPECT_NE(client2a.plugin_pid(), client3a.plugin_pid());
+ EXPECT_NE(client2a.plugin_pid(), client3b.plugin_pid());
+ EXPECT_EQ(client3a.plugin_pid(), client3b.plugin_pid());
+}
+
+IN_PROC_BROWSER_TEST_F(PluginServiceImplBrowserTest, NoForkBombs) {
+ RegisterFakePlugin();
+
+ PluginServiceImpl* service = PluginServiceImpl::GetInstance();
+ service->SetMaxPpapiProcessesPerProfileForTesting(4);
+
+ const char* kFakeURLTemplate = "https://foo.fake%d.com/";
+ TestPluginClient client;
+ for (int i = 0; i < 4; ++i) {
+ std::string url = base::StringPrintf(kFakeURLTemplate, i);
+ url::Origin origin = url::Origin::Create(GURL(url));
+ OpenChannelToFakePlugin(origin, &client);
+ EXPECT_NE(base::kNullProcessId, client.plugin_pid());
+ }
+
+ // After a while we stop handing out processes per-origin.
+ for (int i = 4; i < 8; ++i) {
+ std::string url = base::StringPrintf(kFakeURLTemplate, i);
+ url::Origin origin = url::Origin::Create(GURL(url));
+ OpenChannelToFakePlugin(origin, &client);
+ EXPECT_EQ(base::kNullProcessId, client.plugin_pid());
+ }
+
+ // But there's always room for the empty origin case.
+ OpenChannelToFakePlugin(base::nullopt, &client);
+ EXPECT_NE(base::kNullProcessId, client.plugin_pid());
+
+ // And re-using existing processes is always possible.
+ for (int i = 0; i < 4; ++i) {
+ std::string url = base::StringPrintf(kFakeURLTemplate, i);
+ url::Origin origin = url::Origin::Create(GURL(url));
+ OpenChannelToFakePlugin(origin, &client);
+ EXPECT_NE(base::kNullProcessId, client.plugin_pid());
+ }
+}
+
+} // namespace content
diff --git a/chromium/content/browser/pointer_lock_browsertest.cc b/chromium/content/browser/pointer_lock_browsertest.cc
index 44ec6a523ed..b60766b97b4 100644
--- a/chromium/content/browser/pointer_lock_browsertest.cc
+++ b/chromium/content/browser/pointer_lock_browsertest.cc
@@ -310,6 +310,78 @@ IN_PROC_BROWSER_TEST_F(PointerLockBrowserTest, PointerLockChildFrameDetached) {
web_contents()->GetMouseLockWidget());
}
+// Tests that the browser will unlock the pointer if a RenderWidgetHostView that
+// holds the pointer lock crashes.
+IN_PROC_BROWSER_TEST_F(PointerLockBrowserTest,
+ PointerLockInnerContentsCrashes) {
+ GURL main_url(embedded_test_server()->GetURL(
+ "a.com", "/cross_site_iframe_factory.html?a(b(b))"));
+ EXPECT_TRUE(NavigateToURL(shell(), main_url));
+
+ FrameTreeNode* root = web_contents()->GetFrameTree()->root();
+
+ // Attach an inner WebContents; it's owned by the FrameTree, so we obtain an
+ // observer to it.
+ WebContents* inner_contents = CreateAndAttachInnerContents(
+ root->child_at(0)->child_at(0)->current_frame_host());
+ WebContentsDestroyedWatcher inner_death_observer(inner_contents);
+
+ // Override the delegate so that we can stub out pointer lock events.
+ inner_contents->SetDelegate(&web_contents_delegate_);
+
+ // Navigate the inner webcontents to a page.
+ EXPECT_TRUE(NavigateToURLFromRenderer(
+ inner_contents, embedded_test_server()->GetURL(
+ "c.com", "/cross_site_iframe_factory.html?c(d)")));
+
+ // Request a pointer lock to the inner WebContents's document.body.
+ std::string result;
+ EXPECT_TRUE(ExecuteScriptAndExtractString(inner_contents->GetMainFrame(), R"(
+ (new Promise((resolve, reject) => {
+ document.addEventListener('pointerlockchange', resolve);
+ document.addEventListener('pointerlockerror', reject);
+ }).then(() => {
+ window.domAutomationController.send(
+ (document.pointerLockElement == document.body) ?
+ "success" : "error");
+ }).catch(error => {
+ window.domAutomationController.send("" + error);
+ }));
+ document.body.requestPointerLock();)",
+ &result));
+ EXPECT_EQ("success", result);
+
+ // Root (platform) RenderWidgetHostView should have the pointer locked.
+ EXPECT_TRUE(root->current_frame_host()->GetView()->IsMouseLocked());
+
+ // The widget doing the lock is the one from the inner WebContents. A link
+ // to that RWH is saved into the outer webcontents.
+ RenderWidgetHost* expected_lock_widget =
+ inner_contents->GetMainFrame()->GetView()->GetRenderWidgetHost();
+ EXPECT_EQ(expected_lock_widget, web_contents()->GetMouseLockWidget());
+ EXPECT_EQ(expected_lock_widget, web_contents()->mouse_lock_widget_);
+ EXPECT_EQ(expected_lock_widget,
+ static_cast<WebContentsImpl*>(inner_contents)->mouse_lock_widget_);
+
+ // Crash the subframe process.
+ RenderProcessHost* crash_process =
+ root->child_at(0)->current_frame_host()->GetProcess();
+ RenderProcessHostWatcher crash_observer(
+ crash_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
+ crash_process->Shutdown(0);
+ crash_observer.Wait();
+
+ // Wait for destruction of |inner_contents|.
+ inner_death_observer.Wait();
+ inner_contents = nullptr;
+
+ // This should cancel the pointer lock.
+ EXPECT_EQ(nullptr, web_contents()->GetMouseLockWidget());
+ EXPECT_EQ(nullptr, web_contents()->mouse_lock_widget_);
+ EXPECT_FALSE(web_contents()->HasMouseLock(
+ root->current_frame_host()->GetRenderWidgetHost()));
+}
+
IN_PROC_BROWSER_TEST_F(PointerLockBrowserTest, PointerLockWheelEventRouting) {
GURL main_url(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b)"));
@@ -438,4 +510,37 @@ IN_PROC_BROWSER_TEST_F(PointerLockBrowserTest, PointerLockWheelEventRouting) {
EXPECT_EQ(17, deltaY);
}
+IN_PROC_BROWSER_TEST_F(PointerLockBrowserTest, PointerLockWidgetHidden) {
+ GURL main_url(embedded_test_server()->GetURL(
+ "a.com", "/cross_site_iframe_factory.html?a(b)"));
+ EXPECT_TRUE(NavigateToURL(shell(), main_url));
+
+ FrameTreeNode* root = web_contents()->GetFrameTree()->root();
+ FrameTreeNode* child = root->child_at(0);
+ RenderWidgetHostViewBase* child_view = static_cast<RenderWidgetHostViewBase*>(
+ child->current_frame_host()->GetView());
+
+ WaitForChildFrameSurfaceReady(child->current_frame_host());
+
+ // Request a pointer lock on the child frame's body.
+ EXPECT_TRUE(ExecuteScript(child, "document.body.requestPointerLock()"));
+
+ // Child frame should have been granted pointer lock.
+ bool locked = false;
+ EXPECT_TRUE(ExecuteScriptAndExtractBool(child,
+ "window.domAutomationController.send("
+ "document.pointerLockElement == "
+ "document.body);",
+ &locked));
+ EXPECT_TRUE(locked);
+ EXPECT_TRUE(child_view->IsMouseLocked());
+ EXPECT_EQ(child_view->host(), web_contents()->GetMouseLockWidget());
+
+ child_view->Hide();
+
+ // Child frame should've released the mouse lock when hidden.
+ EXPECT_FALSE(child_view->IsMouseLocked());
+ EXPECT_EQ(nullptr, web_contents()->GetMouseLockWidget());
+}
+
} // namespace content
diff --git a/chromium/content/browser/posix_file_descriptor_info_impl.cc b/chromium/content/browser/posix_file_descriptor_info_impl.cc
index 50639bd7e7c..d0a071d24b5 100644
--- a/chromium/content/browser/posix_file_descriptor_info_impl.cc
+++ b/chromium/content/browser/posix_file_descriptor_info_impl.cc
@@ -6,7 +6,6 @@
#include <utility>
-#include "base/memory/ptr_util.h"
#include "base/stl_util.h"
namespace content {
diff --git a/chromium/content/browser/power_monitor_browsertest.cc b/chromium/content/browser/power_monitor_browsertest.cc
index 7cc26dd2ce1..76132c11da8 100644
--- a/chromium/content/browser/power_monitor_browsertest.cc
+++ b/chromium/content/browser/power_monitor_browsertest.cc
@@ -6,12 +6,13 @@
#include "base/macros.h"
#include "base/run_loop.h"
#include "base/strings/utf_string_conversions.h"
+#include "content/browser/renderer_host/render_process_host_impl.h"
+#include "content/browser/utility_process_host.h"
+#include "content/browser/utility_process_host_client.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/gpu_service_registry.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
-#include "content/public/browser/utility_process_host.h"
-#include "content/public/browser/utility_process_host_client.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/service_names.mojom.h"
#include "content/public/test/browser_test_utils.h"
@@ -43,7 +44,9 @@ void VerifyPowerStateInChildProcess(mojom::PowerMonitorTest* power_monitor_test,
}
void StartUtilityProcessOnIOThread(mojom::PowerMonitorTestRequest request) {
- UtilityProcessHost* host = UtilityProcessHost::Create(nullptr, nullptr);
+ UtilityProcessHost* host =
+ new UtilityProcessHost(/*client=*/nullptr,
+ /*client_task_runner=*/nullptr);
host->SetName(base::ASCIIToUTF16("TestProcess"));
EXPECT_TRUE(host->Start());
@@ -106,10 +109,15 @@ class PowerMonitorTest : public ContentBrowserTest {
mojo::ScopedMessagePipeHandle handle,
const service_manager::BindSourceInfo& source_info) {
if (source_info.identity.name() == mojom::kRendererServiceName) {
- ++request_count_from_renderer_;
-
- DCHECK(renderer_bound_closure_);
- std::move(renderer_bound_closure_).Run();
+ // We can receive binding requests for the spare RenderProcessHost - this
+ // might happen before the test has provided the
+ // |renderer_bound_closure_|.
+ if (renderer_bound_closure_) {
+ ++request_count_from_renderer_;
+ std::move(renderer_bound_closure_).Run();
+ } else {
+ DCHECK(RenderProcessHostImpl::GetSpareRenderProcessHostForTesting());
+ }
} else if (source_info.identity.name() == mojom::kUtilityServiceName) {
++request_count_from_utility_;
@@ -137,7 +145,7 @@ class PowerMonitorTest : public ContentBrowserTest {
protected:
void StartUtilityProcess(mojom::PowerMonitorTestPtr* power_monitor_test,
base::Closure utility_bound_closure) {
- utility_bound_closure_ = utility_bound_closure;
+ utility_bound_closure_ = std::move(utility_bound_closure);
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&StartUtilityProcessOnIOThread,
@@ -145,11 +153,11 @@ class PowerMonitorTest : public ContentBrowserTest {
}
void set_renderer_bound_closure(base::Closure closure) {
- renderer_bound_closure_ = closure;
+ renderer_bound_closure_ = std::move(closure);
}
void set_gpu_bound_closure(base::Closure closure) {
- gpu_bound_closure_ = closure;
+ gpu_bound_closure_ = std::move(closure);
}
int request_count_from_renderer() { return request_count_from_renderer_; }
diff --git a/chromium/content/browser/ppapi_plugin_process_host.cc b/chromium/content/browser/ppapi_plugin_process_host.cc
index 420f5e14b3b..251df387700 100644
--- a/chromium/content/browser/ppapi_plugin_process_host.cc
+++ b/chromium/content/browser/ppapi_plugin_process_host.cc
@@ -13,7 +13,6 @@
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/field_trial.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
@@ -31,7 +30,7 @@
#include "content/public/common/process_type.h"
#include "content/public/common/sandboxed_process_launcher_delegate.h"
#include "content/public/common/service_names.mojom.h"
-#include "content/public/common/zygote_features.h"
+#include "content/public/common/zygote_buildflags.h"
#include "mojo/edk/embedder/embedder.h"
#include "net/base/network_change_notifier.h"
#include "ppapi/proxy/ppapi_messages.h"
@@ -164,10 +163,10 @@ PpapiPluginProcessHost::~PpapiPluginProcessHost() {
// static
PpapiPluginProcessHost* PpapiPluginProcessHost::CreatePluginHost(
const PepperPluginInfo& info,
- const base::FilePath& profile_data_directory) {
- PpapiPluginProcessHost* plugin_host = new PpapiPluginProcessHost(
- info, profile_data_directory);
- DCHECK(plugin_host);
+ const base::FilePath& profile_data_directory,
+ const base::Optional<url::Origin>& origin_lock) {
+ PpapiPluginProcessHost* plugin_host =
+ new PpapiPluginProcessHost(info, profile_data_directory, origin_lock);
if (plugin_host->Init(info))
return plugin_host;
@@ -274,8 +273,10 @@ void PpapiPluginProcessHost::OpenChannelToPlugin(Client* client) {
PpapiPluginProcessHost::PpapiPluginProcessHost(
const PepperPluginInfo& info,
- const base::FilePath& profile_data_directory)
+ const base::FilePath& profile_data_directory,
+ const base::Optional<url::Origin>& origin_lock)
: profile_data_directory_(profile_data_directory),
+ origin_lock_(origin_lock),
is_broker_(false) {
uint32_t base_permissions = info.permissions;
@@ -286,13 +287,12 @@ PpapiPluginProcessHost::PpapiPluginProcessHost(
base_permissions |= ppapi::PERMISSION_DEV_CHANNEL;
permissions_ = ppapi::PpapiPermissions::GetForCommandLine(base_permissions);
- process_.reset(new BrowserChildProcessHostImpl(
- PROCESS_TYPE_PPAPI_PLUGIN, this, mojom::kPluginServiceName));
+ process_ = std::make_unique<BrowserChildProcessHostImpl>(
+ PROCESS_TYPE_PPAPI_PLUGIN, this, mojom::kPluginServiceName);
- host_impl_.reset(new BrowserPpapiHostImpl(this, permissions_, info.name,
- info.path, profile_data_directory,
- false /* in_process */,
- false /* external_plugin */));
+ host_impl_ = std::make_unique<BrowserPpapiHostImpl>(
+ this, permissions_, info.name, info.path, profile_data_directory,
+ false /* in_process */, false /* external_plugin */);
filter_ = new PepperMessageFilter();
process_->AddFilter(filter_.get());
@@ -302,21 +302,19 @@ PpapiPluginProcessHost::PpapiPluginProcessHost(
// Only request network status updates if the plugin has dev permissions.
if (permissions_.HasPermission(ppapi::PERMISSION_DEV))
- network_observer_.reset(new PluginNetworkObserver(this));
+ network_observer_ = std::make_unique<PluginNetworkObserver>(this);
}
PpapiPluginProcessHost::PpapiPluginProcessHost() : is_broker_(true) {
- process_.reset(new BrowserChildProcessHostImpl(
- PROCESS_TYPE_PPAPI_BROKER, this, mojom::kPluginServiceName));
+ process_ = std::make_unique<BrowserChildProcessHostImpl>(
+ PROCESS_TYPE_PPAPI_BROKER, this, mojom::kPluginServiceName);
ppapi::PpapiPermissions permissions; // No permissions.
// The plugin name, path and profile data directory shouldn't be needed for
// the broker.
- host_impl_.reset(new BrowserPpapiHostImpl(this, permissions,
- std::string(), base::FilePath(),
- base::FilePath(),
- false /* in_process */,
- false /* external_plugin */));
+ host_impl_ = std::make_unique<BrowserPpapiHostImpl>(
+ this, permissions, std::string(), base::FilePath(), base::FilePath(),
+ false /* in_process */, false /* external_plugin */);
}
bool PpapiPluginProcessHost::Init(const PepperPluginInfo& info) {
@@ -352,6 +350,7 @@ bool PpapiPluginProcessHost::Init(const PepperPluginInfo& info) {
is_broker_ ? switches::kPpapiBrokerProcess
: switches::kPpapiPluginProcess);
BrowserChildProcessHostImpl::CopyFeatureAndFieldTrialFlags(cmd_line.get());
+ BrowserChildProcessHostImpl::CopyTraceStartupFlags(cmd_line.get());
#if defined(OS_WIN)
cmd_line->AppendArg(is_broker_ ? switches::kPrefetchArgumentPpapiBroker
@@ -417,8 +416,8 @@ bool PpapiPluginProcessHost::Init(const PepperPluginInfo& info) {
}
void PpapiPluginProcessHost::RequestPluginChannel(Client* client) {
- base::ProcessHandle process_handle;
- int renderer_child_id;
+ base::ProcessHandle process_handle = base::kNullProcessHandle;
+ int renderer_child_id = base::kNullProcessId;
client->GetPpapiChannelInfo(&process_handle, &renderer_child_id);
base::ProcessId process_id = base::kNullProcessId;
diff --git a/chromium/content/browser/ppapi_plugin_process_host.h b/chromium/content/browser/ppapi_plugin_process_host.h
index e631d09dbeb..05f656da0c9 100644
--- a/chromium/content/browser/ppapi_plugin_process_host.h
+++ b/chromium/content/browser/ppapi_plugin_process_host.h
@@ -15,6 +15,7 @@
#include "base/files/file_path.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
+#include "base/optional.h"
#include "base/process/process.h"
#include "base/strings/string16.h"
#include "content/browser/renderer_host/pepper/browser_ppapi_host_impl.h"
@@ -23,6 +24,7 @@
#include "content/public/browser/browser_child_process_host_iterator.h"
#include "ipc/ipc_sender.h"
#include "ppapi/shared_impl/ppapi_permissions.h"
+#include "url/origin.h"
namespace content {
class BrowserChildProcessHostImpl;
@@ -72,7 +74,9 @@ class PpapiPluginProcessHost : public BrowserChildProcessHostDelegate,
static PpapiPluginProcessHost* CreatePluginHost(
const PepperPluginInfo& info,
- const base::FilePath& profile_data_directory);
+ const base::FilePath& profile_data_directory,
+ const base::Optional<url::Origin>& origin_lock);
+
static PpapiPluginProcessHost* CreateBrokerHost(
const PepperPluginInfo& info);
@@ -109,6 +113,9 @@ class PpapiPluginProcessHost : public BrowserChildProcessHostDelegate,
BrowserPpapiHostImpl* host_impl() { return host_impl_.get(); }
const BrowserChildProcessHostImpl* process() { return process_.get(); }
+ const base::Optional<url::Origin>& origin_lock() const {
+ return origin_lock_;
+ }
const base::FilePath& plugin_path() const { return plugin_path_; }
const base::FilePath& profile_data_directory() const {
return profile_data_directory_;
@@ -122,7 +129,8 @@ class PpapiPluginProcessHost : public BrowserChildProcessHostDelegate,
// Constructors for plugin and broker process hosts, respectively.
// You must call Init before doing anything else.
PpapiPluginProcessHost(const PepperPluginInfo& info,
- const base::FilePath& profile_data_directory);
+ const base::FilePath& profile_data_directory,
+ const base::Optional<url::Origin>& origin_lock);
PpapiPluginProcessHost();
// Actually launches the process with the given plugin info. Returns true
@@ -132,7 +140,6 @@ class PpapiPluginProcessHost : public BrowserChildProcessHostDelegate,
void RequestPluginChannel(Client* client);
void OnProcessLaunched() override;
-
void OnProcessCrashed(int exit_code) override;
bool OnMessageReceived(const IPC::Message& msg) override;
void OnChannelConnected(int32_t peer_pid) override;
@@ -164,7 +171,11 @@ class PpapiPluginProcessHost : public BrowserChildProcessHostDelegate,
base::FilePath plugin_path_;
// Path to the top-level plugin data directory (differs based upon profile).
- base::FilePath profile_data_directory_;
+ const base::FilePath profile_data_directory_;
+
+ // Specific origin to which this is bound, omitted to allow any origin to
+ // re-use the plugin host.
+ const base::Optional<url::Origin> origin_lock_;
const bool is_broker_;
diff --git a/chromium/content/browser/presentation/presentation_service_impl.cc b/chromium/content/browser/presentation/presentation_service_impl.cc
index 72224d6478f..367e9558162 100644
--- a/chromium/content/browser/presentation/presentation_service_impl.cc
+++ b/chromium/content/browser/presentation/presentation_service_impl.cc
@@ -68,6 +68,9 @@ PresentationServiceImpl::PresentationServiceImpl(
if (auto* delegate = GetPresentationServiceDelegate())
delegate->AddObserver(render_process_id_, render_frame_id_, this);
+
+ bindings_.set_connection_error_handler(base::BindRepeating(
+ &PresentationServiceImpl::OnConnectionError, base::Unretained(this)));
}
PresentationServiceImpl::~PresentationServiceImpl() {
@@ -118,6 +121,8 @@ void PresentationServiceImpl::SetController(
return;
}
controller_ = std::move(controller);
+ controller_.set_connection_error_handler(base::BindOnce(
+ &PresentationServiceImpl::OnConnectionError, base::Unretained(this)));
}
void PresentationServiceImpl::SetReceiver(
@@ -138,6 +143,8 @@ void PresentationServiceImpl::SetReceiver(
}
receiver_ = std::move(receiver);
+ receiver_.set_connection_error_handler(base::BindOnce(
+ &PresentationServiceImpl::OnConnectionError, base::Unretained(this)));
receiver_delegate_->RegisterReceiverConnectionAvailableCallback(
base::Bind(&PresentationServiceImpl::OnReceiverConnectionAvailable,
weak_factory_.GetWeakPtr()));
@@ -387,6 +394,10 @@ bool PresentationServiceImpl::FrameMatches(
render_frame_host->GetRoutingID() == render_frame_id_;
}
+void PresentationServiceImpl::OnConnectionError() {
+ Reset();
+}
+
PresentationServiceDelegate*
PresentationServiceImpl::GetPresentationServiceDelegate() {
return receiver_delegate_
diff --git a/chromium/content/browser/presentation/presentation_service_impl.h b/chromium/content/browser/presentation/presentation_service_impl.h
index aa3c96e44cd..4a3155bc541 100644
--- a/chromium/content/browser/presentation/presentation_service_impl.h
+++ b/chromium/content/browser/presentation/presentation_service_impl.h
@@ -25,7 +25,7 @@
#include "content/public/browser/web_contents_observer.h"
#include "content/public/common/frame_navigate_params.h"
#include "mojo/public/cpp/bindings/binding_set.h"
-#include "third_party/WebKit/public/platform/modules/presentation/presentation.mojom.h"
+#include "third_party/blink/public/platform/modules/presentation/presentation.mojom.h"
#include "url/gurl.h"
namespace content {
@@ -239,6 +239,10 @@ class CONTENT_EXPORT PresentationServiceImpl
// Returns true if this object is associated with |render_frame_host|.
bool FrameMatches(content::RenderFrameHost* render_frame_host) const;
+ // Invoked on Mojo connection error. Closes all Mojo message pipes held by
+ // |this|.
+ void OnConnectionError();
+
// Returns |controller_delegate| if current frame is controller frame; Returns
// |receiver_delegate| if current frame is receiver frame.
PresentationServiceDelegate* GetPresentationServiceDelegate();
diff --git a/chromium/content/browser/presentation/presentation_service_impl_unittest.cc b/chromium/content/browser/presentation/presentation_service_impl_unittest.cc
index f335ea499fd..58ce9132e07 100644
--- a/chromium/content/browser/presentation/presentation_service_impl_unittest.cc
+++ b/chromium/content/browser/presentation/presentation_service_impl_unittest.cc
@@ -134,6 +134,11 @@ class MockPresentationServiceDelegate
void(int render_process_id,
int render_frame_id,
const std::string& presentation_id));
+ MOCK_METHOD3(GetMediaController,
+ std::unique_ptr<content::MediaController>(
+ int render_process_id,
+ int render_frame_id,
+ const std::string& presentation_id));
// PresentationConnectionMessage is move-only.
// TODO(crbug.com/729950): Use MOCK_METHOD directly once GMock gets the
diff --git a/chromium/content/browser/push_messaging/OWNERS b/chromium/content/browser/push_messaging/OWNERS
index 674687c5a7d..3e980213fe1 100644
--- a/chromium/content/browser/push_messaging/OWNERS
+++ b/chromium/content/browser/push_messaging/OWNERS
@@ -6,8 +6,8 @@
# //chrome/browser/push_messaging/
# //content/child/push_messaging/
# //content/renderer/push_messaging/
-# //third_party/WebKit/Source/modules/push_messaging/
-# //third_party/WebKit/public/platform/modules/push_messaging/
+# //third_party/blink/renderer/modules/push_messaging/
+# //third_party/blink/public/platform/modules/push_messaging/
johnme@chromium.org
mvanouwerkerk@chromium.org
diff --git a/chromium/content/browser/push_messaging/push_messaging_manager.cc b/chromium/content/browser/push_messaging/push_messaging_manager.cc
index c8d415a99d2..fef1c37b56c 100644
--- a/chromium/content/browser/push_messaging/push_messaging_manager.cc
+++ b/chromium/content/browser/push_messaging/push_messaging_manager.cc
@@ -12,7 +12,6 @@
#include "base/command_line.h"
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/string_number_conversions.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
@@ -30,7 +29,7 @@
#include "content/public/common/console_message_level.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/push_messaging_status.mojom.h"
-#include "third_party/WebKit/public/platform/modules/permissions/permission_status.mojom.h"
+#include "third_party/blink/public/platform/modules/permissions/permission_status.mojom.h"
namespace content {
@@ -55,22 +54,16 @@ const char kIncognitoPushUnsupportedMessage[] =
void RecordRegistrationStatus(mojom::PushRegistrationStatus status) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO) ||
BrowserThread::CurrentlyOn(BrowserThread::UI));
- UMA_HISTOGRAM_ENUMERATION(
- "PushMessaging.RegistrationStatus", status,
- static_cast<int>(mojom::PushRegistrationStatus::LAST) + 1);
+ UMA_HISTOGRAM_ENUMERATION("PushMessaging.RegistrationStatus", status);
}
void RecordUnregistrationStatus(mojom::PushUnregistrationStatus status) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
- UMA_HISTOGRAM_ENUMERATION(
- "PushMessaging.UnregistrationStatus", status,
- static_cast<int>(mojom::PushUnregistrationStatus::LAST) + 1);
+ UMA_HISTOGRAM_ENUMERATION("PushMessaging.UnregistrationStatus", status);
}
void RecordGetRegistrationStatus(mojom::PushGetRegistrationStatus status) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO) ||
BrowserThread::CurrentlyOn(BrowserThread::UI));
- UMA_HISTOGRAM_ENUMERATION(
- "PushMessaging.GetRegistrationStatus", status,
- static_cast<int>(mojom::PushGetRegistrationStatus::LAST) + 1);
+ UMA_HISTOGRAM_ENUMERATION("PushMessaging.GetRegistrationStatus", status);
}
const char* PushUnregistrationStatusToString(
@@ -336,7 +329,7 @@ void PushMessagingManager::Subscribe(int32_t render_frame_id,
registration_id,
{kPushRegistrationIdServiceWorkerKey, kPushSenderIdServiceWorkerKey},
base::BindOnce(&PushMessagingManager::DidCheckForExistingRegistration,
- weak_factory_io_to_io_.GetWeakPtr(), base::Passed(&data)));
+ weak_factory_io_to_io_.GetWeakPtr(), std::move(data)));
}
void PushMessagingManager::DidCheckForExistingRegistration(
@@ -385,8 +378,7 @@ void PushMessagingManager::DidCheckForExistingRegistration(
service_worker_context_->GetRegistrationUserData(
registration_id, {kPushSenderIdServiceWorkerKey},
base::BindOnce(&PushMessagingManager::DidGetSenderIdFromStorage,
- weak_factory_io_to_io_.GetWeakPtr(),
- base::Passed(&data)));
+ weak_factory_io_to_io_.GetWeakPtr(), std::move(data)));
}
}
@@ -560,9 +552,9 @@ void PushMessagingManager::PersistRegistrationOnIO(
registration_id, requesting_origin,
{{kPushRegistrationIdServiceWorkerKey, push_subscription_id},
{kPushSenderIdServiceWorkerKey, sender_info}},
- base::Bind(&PushMessagingManager::DidPersistRegistrationOnIO,
- weak_factory_io_to_io_.GetWeakPtr(), base::Passed(&data),
- push_subscription_id, p256dh, auth, status));
+ base::BindOnce(&PushMessagingManager::DidPersistRegistrationOnIO,
+ weak_factory_io_to_io_.GetWeakPtr(), std::move(data),
+ push_subscription_id, p256dh, auth, status));
}
void PushMessagingManager::DidPersistRegistrationOnIO(
@@ -636,8 +628,8 @@ void PushMessagingManager::Unsubscribe(int64_t service_worker_registration_id,
service_worker_context_->GetRegistrationUserData(
service_worker_registration_id, {kPushSenderIdServiceWorkerKey},
base::BindOnce(&PushMessagingManager::UnsubscribeHavingGottenSenderId,
- weak_factory_io_to_io_.GetWeakPtr(),
- base::Passed(&callback), service_worker_registration_id,
+ weak_factory_io_to_io_.GetWeakPtr(), std::move(callback),
+ service_worker_registration_id,
service_worker_registration->pattern().GetOrigin()));
}
@@ -746,8 +738,8 @@ void PushMessagingManager::GetSubscription(
service_worker_registration_id,
{kPushRegistrationIdServiceWorkerKey, kPushSenderIdServiceWorkerKey},
base::BindOnce(&PushMessagingManager::DidGetSubscription,
- weak_factory_io_to_io_.GetWeakPtr(),
- base::Passed(&callback), service_worker_registration_id));
+ weak_factory_io_to_io_.GetWeakPtr(), std::move(callback),
+ service_worker_registration_id));
}
void PushMessagingManager::DidGetSubscription(
diff --git a/chromium/content/browser/quota_dispatcher_host.cc b/chromium/content/browser/quota_dispatcher_host.cc
index 566848c76b8..c32742729ad 100644
--- a/chromium/content/browser/quota_dispatcher_host.cc
+++ b/chromium/content/browser/quota_dispatcher_host.cc
@@ -94,9 +94,8 @@ void QuotaDispatcherHost::QueryStorageUsageAndQuota(
QueryStorageUsageAndQuotaCallback callback) {
quota_manager_->GetUsageAndQuotaForWebApps(
origin.GetURL(), storage_type,
- base::Bind(&QuotaDispatcherHost::DidQueryStorageUsageAndQuota,
- weak_factory_.GetWeakPtr(),
- base::Passed(std::move(callback))));
+ base::BindOnce(&QuotaDispatcherHost::DidQueryStorageUsageAndQuota,
+ weak_factory_.GetWeakPtr(), std::move(callback)));
}
void QuotaDispatcherHost::RequestStorageQuota(
@@ -126,15 +125,15 @@ void QuotaDispatcherHost::RequestStorageQuota(
if (storage_type == StorageType::kPersistent) {
quota_manager_->GetUsageAndQuotaForWebApps(
origin.GetURL(), storage_type,
- base::Bind(&QuotaDispatcherHost::DidGetPersistentUsageAndQuota,
- weak_factory_.GetWeakPtr(), origin, storage_type,
- requested_size, base::Passed(std::move(callback))));
+ base::BindOnce(&QuotaDispatcherHost::DidGetPersistentUsageAndQuota,
+ weak_factory_.GetWeakPtr(), origin, storage_type,
+ requested_size, std::move(callback)));
} else {
quota_manager_->GetUsageAndQuotaForWebApps(
origin.GetURL(), storage_type,
- base::Bind(&QuotaDispatcherHost::DidGetTemporaryUsageAndQuota,
- weak_factory_.GetWeakPtr(), requested_size,
- base::Passed(std::move(callback))));
+ base::BindOnce(&QuotaDispatcherHost::DidGetTemporaryUsageAndQuota,
+ weak_factory_.GetWeakPtr(), requested_size,
+ std::move(callback)));
}
}
@@ -209,9 +208,9 @@ void QuotaDispatcherHost::DidGetPermissionResponse(
// rewrite to just convert the host to a string directly.
quota_manager_->SetPersistentHostQuota(
net::GetHostOrSpecFromURL(origin.GetURL()), requested_quota,
- base::Bind(&QuotaDispatcherHost::DidSetHostQuota,
- weak_factory_.GetWeakPtr(), current_usage,
- base::Passed(std::move(callback))));
+ base::BindOnce(&QuotaDispatcherHost::DidSetHostQuota,
+ weak_factory_.GetWeakPtr(), current_usage,
+ std::move(callback)));
}
void QuotaDispatcherHost::DidSetHostQuota(int64_t current_usage,
diff --git a/chromium/content/browser/quota_dispatcher_host.h b/chromium/content/browser/quota_dispatcher_host.h
index 1f706b0a82e..e42257d5457 100644
--- a/chromium/content/browser/quota_dispatcher_host.h
+++ b/chromium/content/browser/quota_dispatcher_host.h
@@ -7,7 +7,7 @@
#include "base/macros.h"
#include "content/public/browser/quota_permission_context.h"
-#include "third_party/WebKit/public/mojom/quota/quota_dispatcher_host.mojom.h"
+#include "third_party/blink/public/mojom/quota/quota_dispatcher_host.mojom.h"
namespace storage {
class QuotaManager;
diff --git a/chromium/content/browser/renderer_host/DEPS b/chromium/content/browser/renderer_host/DEPS
index eb2fa51abf2..e2a73e36e6d 100644
--- a/chromium/content/browser/renderer_host/DEPS
+++ b/chromium/content/browser/renderer_host/DEPS
@@ -4,7 +4,7 @@ include_rules = [
"+components/viz/host",
"+components/viz/service",
"+services/ui/public",
- "+third_party/WebKit/public/platform/WebGestureCurve.h",
+ "+third_party/blink/public/platform/web_gesture_curve.h",
"+third_party/zlib",
"+ui/events/gestures/blink/web_gesture_curve_impl.h",
"+ui/latency",
@@ -32,6 +32,10 @@ specific_include_rules = {
# embedded in mus won't be able to talk to the native ozone.
"+ui/ozone/public/ozone_switches.h",
],
+ "render_widget_host_view_cocoa\.mm": [
+ "+content/browser/frame_host",
+ "+content/public/browser/web_contents.h",
+ ],
"render_widget_host_view_mac\.mm": [
"+content/browser/frame_host",
"+content/public/browser/web_contents.h",
diff --git a/chromium/content/browser/renderer_host/browser_compositor_view_mac.h b/chromium/content/browser/renderer_host/browser_compositor_view_mac.h
index 7426062f738..e7d40839956 100644
--- a/chromium/content/browser/renderer_host/browser_compositor_view_mac.h
+++ b/chromium/content/browser/renderer_host/browser_compositor_view_mac.h
@@ -27,10 +27,11 @@ class RecyclableCompositorMac;
class BrowserCompositorMacClient {
public:
virtual SkColor BrowserCompositorMacGetGutterColor() const = 0;
- virtual void BrowserCompositorMacOnBeginFrame() = 0;
+ virtual void BrowserCompositorMacOnBeginFrame(base::TimeTicks frame_time) = 0;
virtual void OnFrameTokenChanged(uint32_t frame_token) = 0;
virtual void DidReceiveFirstFrameAfterNavigation() = 0;
virtual void DestroyCompositorForShutdown() = 0;
+ virtual void WasResized() = 0;
};
// This class owns a DelegatedFrameHost, and will dynamically attach and
@@ -48,6 +49,7 @@ class CONTENT_EXPORT BrowserCompositorMac : public DelegatedFrameHostClient {
BrowserCompositorMacClient* client,
bool render_widget_host_is_hidden,
bool ns_view_attached_to_window,
+ const display::Display& initial_display,
const viz::FrameSinkId& frame_sink_id);
~BrowserCompositorMac() override;
@@ -67,12 +69,14 @@ class CONTENT_EXPORT BrowserCompositorMac : public DelegatedFrameHostClient {
const base::TimeDelta& interval);
void SetNeedsBeginFrames(bool needs_begin_frames);
void SetWantsAnimateOnlyBeginFrames();
+ void TakeFallbackContentFrom(BrowserCompositorMac* other);
// Update the renderer's SurfaceId to reflect the current dimensions of the
// NSView. This will allocate a new SurfaceId if needed. This will return
// true if any properties that need to be communicated to the
// RenderWidgetHostImpl have changed.
- bool UpdateNSViewAndDisplay();
+ bool UpdateNSViewAndDisplay(const gfx::Size& new_size_dip,
+ const display::Display& new_display);
// Update the renderer's SurfaceId to reflect |size_dip| in anticipation of
// the NSView resizing during auto-resize.
@@ -94,9 +98,7 @@ class CONTENT_EXPORT BrowserCompositorMac : public DelegatedFrameHostClient {
const gfx::Size& GetRendererSize() const { return dfh_size_dip_; }
void GetRendererScreenInfo(ScreenInfo* screen_info) const;
- const viz::LocalSurfaceId& GetRendererLocalSurfaceId() const {
- return dfh_surface_id_;
- }
+ const viz::LocalSurfaceId& GetRendererLocalSurfaceId() const;
// Indicate that the recyclable compositor should be destroyed, and no future
// compositors should be recycled.
@@ -115,6 +117,10 @@ class CONTENT_EXPORT BrowserCompositorMac : public DelegatedFrameHostClient {
void OnFrameTokenChanged(uint32_t frame_token) override;
void DidReceiveFirstFrameAfterNavigation() override;
+ base::WeakPtr<BrowserCompositorMac> GetWeakPtr() {
+ return weak_factory_.GetWeakPtr();
+ }
+
// Returns nullptr if no compositor is attached.
ui::Compositor* CompositorForTesting() const;
@@ -174,17 +180,17 @@ class CONTENT_EXPORT BrowserCompositorMac : public DelegatedFrameHostClient {
viz::mojom::CompositorFrameSinkClient* renderer_compositor_frame_sink_ =
nullptr;
- // The surface for the delegated frame host, rendered into by the renderer
+ // The viz::ParentLocalSurfaceIdAllocator for the delegated frame host
+ // dispenses viz::LocalSurfaceIds that are renderered into by the renderer
// process.
- viz::LocalSurfaceId dfh_surface_id_;
+ viz::ParentLocalSurfaceIdAllocator dfh_local_surface_id_allocator_;
gfx::Size dfh_size_pixels_;
gfx::Size dfh_size_dip_;
display::Display dfh_display_;
- // The surface for the ui::Compositor, which will embed |dfh_surface_id_|
- // into its tree. Updated to match the delegated frame host values when
- // attached and at OnFirstSurfaceActivation.
- viz::LocalSurfaceId compositor_surface_id_;
+ // The viz::ParentLocalSurfaceIdAllocator for the ui::Compositor dispenses
+ // viz::LocalSurfaceIds that are renderered into by the ui::Compositor.
+ viz::ParentLocalSurfaceIdAllocator compositor_local_surface_id_allocator_;
gfx::Size compositor_size_pixels_;
float compositor_scale_factor_ = 1.f;
@@ -201,7 +207,7 @@ class CONTENT_EXPORT BrowserCompositorMac : public DelegatedFrameHostClient {
} repaint_state_ = RepaintState::None;
bool repaint_auto_resize_enabled_ = false;
- viz::ParentLocalSurfaceIdAllocator parent_local_surface_id_allocator_;
+ bool is_first_navigation_ = true;
base::WeakPtrFactory<BrowserCompositorMac> weak_factory_;
};
diff --git a/chromium/content/browser/renderer_host/browser_compositor_view_mac.mm b/chromium/content/browser/renderer_host/browser_compositor_view_mac.mm
index 7fcc24c15c3..3d5a2193bd5 100644
--- a/chromium/content/browser/renderer_host/browser_compositor_view_mac.mm
+++ b/chromium/content/browser/renderer_host/browser_compositor_view_mac.mm
@@ -141,8 +141,8 @@ std::unique_ptr<RecyclableCompositorMac> RecyclableCompositorMac::Create() {
DCHECK(ui::WindowResizeHelperMac::Get()->task_runner());
if (!g_spare_recyclable_compositors.Get().empty()) {
std::unique_ptr<RecyclableCompositorMac> result;
- result = std::move(g_spare_recyclable_compositors.Get().front());
- g_spare_recyclable_compositors.Get().pop_front();
+ result = std::move(g_spare_recyclable_compositors.Get().back());
+ g_spare_recyclable_compositors.Get().pop_back();
return result;
}
return std::unique_ptr<RecyclableCompositorMac>(new RecyclableCompositorMac);
@@ -172,9 +172,11 @@ BrowserCompositorMac::BrowserCompositorMac(
BrowserCompositorMacClient* client,
bool render_widget_host_is_hidden,
bool ns_view_attached_to_window,
+ const display::Display& initial_display,
const viz::FrameSinkId& frame_sink_id)
: client_(client),
accelerated_widget_mac_ns_view_(accelerated_widget_mac_ns_view),
+ dfh_display_(initial_display),
weak_factory_(this) {
g_browser_compositors.Get().insert(this);
@@ -184,8 +186,6 @@ BrowserCompositorMac::BrowserCompositorMac(
base::FeatureList::IsEnabled(features::kVizDisplayCompositor),
true /* should_register_frame_sink_id */));
- dfh_display_ = display::Screen::GetScreen()->GetDisplayNearestView(nil);
-
SetRenderWidgetHostIsHidden(render_widget_host_is_hidden);
SetNSViewAttachedToWindow(ns_view_attached_to_window);
}
@@ -233,7 +233,7 @@ void BrowserCompositorMac::ClearCompositorFrame() {
}
viz::FrameSinkId BrowserCompositorMac::GetRootFrameSinkId() {
- if (recyclable_compositor_->compositor())
+ if (recyclable_compositor_)
return recyclable_compositor_->compositor()->frame_sink_id();
return viz::FrameSinkId();
}
@@ -256,12 +256,9 @@ void BrowserCompositorMac::SetBackgroundColor(SkColor background_color) {
}
}
-bool BrowserCompositorMac::UpdateNSViewAndDisplay() {
- NSView* ns_view =
- accelerated_widget_mac_ns_view_->AcceleratedWidgetGetNSView();
- display::Display new_display =
- display::Screen::GetScreen()->GetDisplayNearestView(ns_view);
- gfx::Size new_size_dip([ns_view bounds].size);
+bool BrowserCompositorMac::UpdateNSViewAndDisplay(
+ const gfx::Size& new_size_dip,
+ const display::Display& new_display) {
if (new_size_dip == dfh_size_dip_ && new_display == dfh_display_)
return false;
@@ -275,11 +272,10 @@ bool BrowserCompositorMac::UpdateNSViewAndDisplay() {
dfh_size_dip_);
if (needs_new_surface_id) {
- dfh_surface_id_ = parent_local_surface_id_allocator_.GenerateId();
if (recyclable_compositor_)
recyclable_compositor_->Suspend();
GetDelegatedFrameHost()->WasResized(
- dfh_surface_id_, dfh_size_dip_,
+ dfh_local_surface_id_allocator_.GenerateId(), dfh_size_dip_,
cc::DeadlinePolicy::UseExistingDeadline());
}
@@ -297,12 +293,11 @@ void BrowserCompositorMac::UpdateForAutoResize(const gfx::Size& new_size_dip) {
dfh_size_dip_ = new_size_dip;
dfh_size_pixels_ = gfx::ConvertSizeToPixel(dfh_display_.device_scale_factor(),
dfh_size_dip_);
- dfh_surface_id_ = parent_local_surface_id_allocator_.GenerateId();
if (recyclable_compositor_)
recyclable_compositor_->Suspend();
GetDelegatedFrameHost()->WasResized(
- dfh_surface_id_, dfh_size_dip_,
+ dfh_local_surface_id_allocator_.GenerateId(), dfh_size_dip_,
cc::DeadlinePolicy::UseExistingDeadline());
}
@@ -326,12 +321,19 @@ void BrowserCompositorMac::SetNSViewAttachedToWindow(bool attached) {
}
void BrowserCompositorMac::UpdateState() {
- if (!render_widget_host_is_hidden_)
+ // If the host is visible then a compositor is required.
+ if (!render_widget_host_is_hidden_) {
TransitionToState(HasAttachedCompositor);
- else if (ns_view_attached_to_window_)
+ return;
+ }
+ // If the host is not visible but we are attached to a window then keep around
+ // a compositor only if it already exists.
+ if (ns_view_attached_to_window_ && state_ != HasNoCompositor) {
TransitionToState(HasDetachedCompositor);
- else
- TransitionToState(HasNoCompositor);
+ return;
+ }
+ // Otherwise put the compositor up for recycling.
+ TransitionToState(HasNoCompositor);
}
void BrowserCompositorMac::TransitionToState(State new_state) {
@@ -350,7 +352,7 @@ void BrowserCompositorMac::TransitionToState(State new_state) {
// Transition HasDetachedCompositor -> HasAttachedCompositor.
if (state_ == HasDetachedCompositor && new_state == HasAttachedCompositor) {
delegated_frame_host_->SetCompositor(recyclable_compositor_->compositor());
- delegated_frame_host_->WasShown(dfh_surface_id_, dfh_size_dip_,
+ delegated_frame_host_->WasShown(GetRendererLocalSurfaceId(), dfh_size_dip_,
ui::LatencyInfo());
// If there exists a saved frame ready to display, unsuspend the compositor
@@ -361,13 +363,11 @@ void BrowserCompositorMac::TransitionToState(State new_state) {
compositor_size_pixels_ != dfh_size_pixels_) {
compositor_scale_factor_ = dfh_display_.device_scale_factor();
compositor_size_pixels_ = dfh_size_pixels_;
- compositor_surface_id_ =
- parent_local_surface_id_allocator_.GenerateId();
root_layer_->SetBounds(gfx::Rect(gfx::ConvertSizeToDIP(
compositor_scale_factor_, compositor_size_pixels_)));
recyclable_compositor_->compositor()->SetScaleAndSize(
compositor_scale_factor_, compositor_size_pixels_,
- compositor_surface_id_);
+ compositor_local_surface_id_allocator_.GenerateId());
}
recyclable_compositor_->Unsuspend();
}
@@ -392,10 +392,10 @@ void BrowserCompositorMac::TransitionToState(State new_state) {
recyclable_compositor_->accelerated_widget_mac()->ResetNSView();
compositor_scale_factor_ = 1.f;
compositor_size_pixels_ = gfx::Size();
- compositor_surface_id_ = viz::LocalSurfaceId();
+ compositor_local_surface_id_allocator_.Invalidate();
recyclable_compositor_->compositor()->SetScaleAndSize(
compositor_scale_factor_, compositor_size_pixels_,
- compositor_surface_id_);
+ compositor_local_surface_id_allocator_.GetCurrentLocalSurfaceId());
recyclable_compositor_->compositor()->SetRootLayer(nullptr);
RecyclableCompositorMac::Recycle(std::move(recyclable_compositor_));
state_ = HasNoCompositor;
@@ -423,6 +423,21 @@ void BrowserCompositorMac::SetWantsAnimateOnlyBeginFrames() {
delegated_frame_host_->SetWantsAnimateOnlyBeginFrames();
}
+void BrowserCompositorMac::TakeFallbackContentFrom(
+ BrowserCompositorMac* other) {
+ // We will have a flash if we can't recycle the compositor from |other|.
+ if (other->state_ != HasDetachedCompositor || state_ != HasNoCompositor) {
+ return;
+ }
+
+ delegated_frame_host_->TakeFallbackContentFrom(
+ other->delegated_frame_host_.get());
+ other->recyclable_compositor_->accelerated_widget_mac()
+ ->ResetNSViewPreservingContents();
+ other->TransitionToState(HasNoCompositor);
+ TransitionToState(HasAttachedCompositor);
+}
+
////////////////////////////////////////////////////////////////////////////////
// DelegatedFrameHost, public:
@@ -463,12 +478,11 @@ void BrowserCompositorMac::OnFirstSurfaceActivation(
}
compositor_size_pixels_ = surface_info.size_in_pixels();
compositor_scale_factor_ = surface_info.device_scale_factor();
- compositor_surface_id_ = parent_local_surface_id_allocator_.GenerateId();
root_layer_->SetBounds(gfx::Rect(gfx::ConvertSizeToDIP(
compositor_scale_factor_, compositor_size_pixels_)));
recyclable_compositor_->compositor()->SetScaleAndSize(
compositor_scale_factor_, compositor_size_pixels_,
- compositor_surface_id_);
+ compositor_local_surface_id_allocator_.GenerateId());
// Disable screen updates until the frame of the new size appears (because the
// content is drawn in the GPU process, it may change before we want it to).
@@ -484,7 +498,7 @@ void BrowserCompositorMac::OnFirstSurfaceActivation(
}
void BrowserCompositorMac::OnBeginFrame(base::TimeTicks frame_time) {
- client_->BrowserCompositorMacOnBeginFrame();
+ client_->BrowserCompositorMacOnBeginFrame(frame_time);
}
bool BrowserCompositorMac::IsAutoResizeEnabled() const {
@@ -503,9 +517,17 @@ ui::Compositor* BrowserCompositorMac::CompositorForTesting() const {
}
void BrowserCompositorMac::DidNavigate() {
- dfh_surface_id_ = parent_local_surface_id_allocator_.GenerateId();
- delegated_frame_host_->WasResized(dfh_surface_id_, dfh_size_dip_,
- cc::DeadlinePolicy::UseExistingDeadline());
+ // The first navigation does not need a new LocalSurfaceID. The renderer can
+ // use the ID that was already provided.
+ if (!is_first_navigation_) {
+ const viz::LocalSurfaceId& new_local_surface_id =
+ dfh_local_surface_id_allocator_.GenerateId();
+ delegated_frame_host_->WasResized(
+ new_local_surface_id, dfh_size_dip_,
+ cc::DeadlinePolicy::UseExistingDeadline());
+ }
+ is_first_navigation_ = false;
+ client_->WasResized();
delegated_frame_host_->DidNavigate();
}
@@ -542,4 +564,9 @@ void BrowserCompositorMac::GetRendererScreenInfo(
DisplayUtil::DisplayToScreenInfo(screen_info, dfh_display_);
}
+const viz::LocalSurfaceId& BrowserCompositorMac::GetRendererLocalSurfaceId()
+ const {
+ return dfh_local_surface_id_allocator_.GetCurrentLocalSurfaceId();
+}
+
} // namespace content
diff --git a/chromium/content/browser/renderer_host/clipboard_host_impl.cc b/chromium/content/browser/renderer_host/clipboard_host_impl.cc
index 470888414be..219539bad29 100644
--- a/chromium/content/browser/renderer_host/clipboard_host_impl.cc
+++ b/chromium/content/browser/renderer_host/clipboard_host_impl.cc
@@ -20,6 +20,7 @@
#include "content/browser/blob_storage/chrome_blob_storage_context.h"
#include "content/public/browser/blob_handle.h"
#include "content/public/browser/browser_context.h"
+#include "content/public/browser/browser_thread.h"
#include "ipc/ipc_message_macros.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "mojo/public/cpp/system/platform_handle.h"
diff --git a/chromium/content/browser/renderer_host/clipboard_host_impl.h b/chromium/content/browser/renderer_host/clipboard_host_impl.h
index 525fe113bcc..f0a867c5490 100644
--- a/chromium/content/browser/renderer_host/clipboard_host_impl.h
+++ b/chromium/content/browser/renderer_host/clipboard_host_impl.h
@@ -19,7 +19,7 @@
#include "content/common/content_export.h"
#include "content/public/browser/browser_associated_interface.h"
#include "content/public/browser/browser_message_filter.h"
-#include "third_party/WebKit/public/mojom/clipboard/clipboard.mojom.h"
+#include "third_party/blink/public/mojom/clipboard/clipboard.mojom.h"
#include "ui/base/clipboard/clipboard.h"
class GURL;
diff --git a/chromium/content/browser/renderer_host/compositor_impl_android.cc b/chromium/content/browser/renderer_host/compositor_impl_android.cc
index 172f5dc2a16..6cbf42626e1 100644
--- a/chromium/content/browser/renderer_host/compositor_impl_android.cc
+++ b/chromium/content/browser/renderer_host/compositor_impl_android.cc
@@ -18,7 +18,6 @@
#include "base/containers/hash_tables.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/weak_ptr.h"
#include "base/single_thread_task_runner.h"
#include "base/synchronization/lock.h"
@@ -35,6 +34,7 @@
#include "cc/resources/ui_resource_manager.h"
#include "cc/trees/layer_tree_host.h"
#include "cc/trees/layer_tree_settings.h"
+#include "components/viz/client/frame_eviction_manager.h"
#include "components/viz/common/features.h"
#include "components/viz/common/gl_helper.h"
#include "components/viz/common/gpu/context_provider.h"
@@ -54,6 +54,7 @@
#include "content/browser/browser_main_loop.h"
#include "content/browser/compositor/surface_utils.h"
#include "content/browser/gpu/compositor_util.h"
+#include "content/browser/gpu/gpu_process_host.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/common/gpu_stream_constants.h"
#include "content/public/browser/android/compositor.h"
@@ -65,7 +66,7 @@
#include "gpu/ipc/client/command_buffer_proxy_impl.h"
#include "gpu/ipc/client/gpu_channel_host.h"
#include "gpu/ipc/common/gpu_surface_tracker.h"
-#include "gpu/vulkan/features.h"
+#include "gpu/vulkan/buildflags.h"
#include "gpu/vulkan/vulkan_surface.h"
#include "services/ui/public/cpp/gpu/context_provider_command_buffer.h"
#include "third_party/khronos/GLES2/gl2.h"
@@ -234,14 +235,15 @@ void CreateContextProviderAfterGpuChannelEstablished(
constexpr bool automatic_flushes = false;
constexpr bool support_locking = false;
+ constexpr bool support_grcontext = false;
auto context_provider =
base::MakeRefCounted<ui::ContextProviderCommandBuffer>(
std::move(gpu_channel_host), factory->GetGpuMemoryBufferManager(),
stream_id, stream_priority, handle,
GURL(std::string("chrome://gpu/Compositor::CreateContextProvider")),
- automatic_flushes, support_locking, shared_memory_limits, attributes,
- nullptr /* shared_context */,
+ automatic_flushes, support_locking, support_grcontext,
+ shared_memory_limits, attributes, nullptr /* shared_context */,
ui::command_buffer_metrics::CONTEXT_TYPE_UNKNOWN);
callback.Run(std::move(context_provider));
}
@@ -289,6 +291,8 @@ class AndroidOutputSurface
GetCommandBufferProxy()->SetSwapBuffersCompletionCallback(
base::Bind(&AndroidOutputSurface::OnSwapBuffersCompleted,
weak_ptr_factory_.GetWeakPtr()));
+ GetCommandBufferProxy()->SetPresentationCallback(base::BindRepeating(
+ &AndroidOutputSurface::OnPresentation, weak_ptr_factory_.GetWeakPtr()));
}
void EnsureBackbuffer() override {}
@@ -349,6 +353,11 @@ class AndroidOutputSurface
latency_info_cache_.OnSwapBuffersCompleted(params.swap_response);
}
+ void OnPresentation(uint64_t swap_id,
+ const gfx::PresentationFeedback& feedback) {
+ client_->DidReceivePresentationFeedback(swap_id, feedback);
+ }
+
private:
viz::OutputSurfaceClient* client_ = nullptr;
base::Closure swap_buffers_callback_;
@@ -535,11 +544,6 @@ void CompositorImpl::SetRootWindow(gfx::NativeWindow root_window) {
root_window_ = root_window;
root_window_->SetLayer(root_layer ? root_layer : cc::Layer::Create());
root_window_->GetLayer()->SetBounds(size_);
- if (!readback_layer_tree_) {
- readback_layer_tree_ = cc::Layer::Create();
- readback_layer_tree_->SetHideLayerAndSubtree(true);
- }
- root_window->GetLayer()->AddChild(readback_layer_tree_);
root_window->AttachCompositor(this);
if (!host_) {
CreateLayerTreeHost();
@@ -652,11 +656,13 @@ void CompositorImpl::SetVisible(bool visible) {
root_window_->GetBeginFrameSource());
}
display_.reset();
+ EnqueueLowEndBackgroundCleanup();
} else {
host_->SetVisible(true);
has_submitted_frame_since_became_visible_ = false;
if (layer_tree_frame_sink_request_pending_)
HandlePendingLayerTreeFrameSinkRequest();
+ low_end_background_cleanup_task_.Cancel();
}
}
@@ -789,6 +795,7 @@ void CompositorImpl::OnGpuChannelEstablished(
constexpr bool support_locking = false;
constexpr bool automatic_flushes = false;
+ constexpr bool support_grcontext = true;
display_color_space_ = display::Screen::GetScreen()
->GetDisplayNearestWindow(root_window_)
.color_space();
@@ -800,7 +807,7 @@ void CompositorImpl::OnGpuChannelEstablished(
stream_id, stream_priority, surface_handle_,
GURL(std::string("chrome://gpu/CompositorImpl::") +
std::string("CompositorContextProvider")),
- automatic_flushes, support_locking,
+ automatic_flushes, support_locking, support_grcontext,
GetCompositorContextSharedMemoryLimits(root_window_),
GetCompositorContextAttributes(display_color_space_,
requires_alpha_channel_),
@@ -916,8 +923,17 @@ void CompositorImpl::DidCommit() {
root_window_->OnCompositingDidCommit();
}
-void CompositorImpl::AttachLayerForReadback(scoped_refptr<cc::Layer> layer) {
- readback_layer_tree_->AddChild(layer);
+base::WeakPtr<ui::WindowAndroidCompositor> CompositorImpl::GetWeakPtr() {
+ return weak_factory_.GetWeakPtr();
+}
+
+void CompositorImpl::IncrementReadbackRequestCount() {
+ pending_readback_request_count_++;
+}
+
+void CompositorImpl::DecrementReadbackRequestCount() {
+ DCHECK_GT(pending_readback_request_count_, 0u);
+ pending_readback_request_count_--;
}
void CompositorImpl::RequestCopyOfOutputOnRootLayer(
@@ -979,7 +995,7 @@ void CompositorImpl::OnDisplayMetricsChanged(const display::Display& display,
}
bool CompositorImpl::HavePendingReadbacks() {
- return !readback_layer_tree_->children().empty();
+ return pending_readback_request_count_ > 0u;
}
std::unique_ptr<ui::CompositorLock> CompositorImpl::GetCompositorLock(
@@ -997,4 +1013,35 @@ void CompositorImpl::OnCompositorLockStateChanged(bool locked) {
host_->SetDeferCommits(locked);
}
+void CompositorImpl::EnqueueLowEndBackgroundCleanup() {
+ if (base::SysInfo::IsLowEndDevice()) {
+ low_end_background_cleanup_task_.Reset(
+ base::BindOnce(&CompositorImpl::DoLowEndBackgroundCleanup,
+ weak_factory_.GetWeakPtr()));
+ base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
+ FROM_HERE, low_end_background_cleanup_task_.callback(),
+ base::TimeDelta::FromSeconds(5));
+ }
+}
+
+void CompositorImpl::DoLowEndBackgroundCleanup() {
+ // When we become visible, we immediately cancel the callback that runs this
+ // code.
+ DCHECK(!host_->IsVisible());
+
+ // First, evict all unlocked frames, allowing resources to be reclaimed.
+ viz::FrameEvictionManager::GetInstance()->PurgeAllUnlockedFrames();
+
+ // Next, notify the GPU process to do background processing, which will
+ // lose all renderer contexts.
+ content::GpuProcessHost::CallOnIO(
+ content::GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
+ false /* force_create */,
+ base::BindRepeating([](content::GpuProcessHost* host) {
+ if (host) {
+ host->gpu_service()->OnBackgrounded();
+ }
+ }));
+}
+
} // namespace content
diff --git a/chromium/content/browser/renderer_host/compositor_impl_android.h b/chromium/content/browser/renderer_host/compositor_impl_android.h
index 716f928b986..a037726c11d 100644
--- a/chromium/content/browser/renderer_host/compositor_impl_android.h
+++ b/chromium/content/browser/renderer_host/compositor_impl_android.h
@@ -22,7 +22,7 @@
#include "content/public/browser/android/compositor.h"
#include "gpu/command_buffer/common/capabilities.h"
#include "gpu/ipc/common/surface_handle.h"
-#include "gpu/vulkan/features.h"
+#include "gpu/vulkan/buildflags.h"
#include "services/ui/public/cpp/gpu/context_provider_command_buffer.h"
#include "third_party/khronos/GLES2/gl2.h"
#include "ui/android/resources/resource_manager_impl.h"
@@ -77,6 +77,10 @@ class CONTENT_EXPORT CompositorImpl
void DeleteUIResource(cc::UIResourceId resource_id) override;
bool SupportsETC1NonPowerOfTwo() const override;
+ // Test functions:
+ bool IsLockedForTesting() const { return lock_manager_.IsLocked(); }
+ void SetVisibleForTesting(bool visible) { SetVisible(visible); }
+
private:
// Compositor implementation.
void SetRootWindow(gfx::NativeWindow root_window) override;
@@ -118,7 +122,9 @@ class CONTENT_EXPORT CompositorImpl
void DidLoseLayerTreeFrameSink() override;
// WindowAndroidCompositor implementation.
- void AttachLayerForReadback(scoped_refptr<cc::Layer> layer) override;
+ base::WeakPtr<ui::WindowAndroidCompositor> GetWeakPtr() override;
+ void IncrementReadbackRequestCount() override;
+ void DecrementReadbackRequestCount() override;
void RequestCopyOfOutputOnRootLayer(
std::unique_ptr<viz::CopyOutputRequest> request) override;
void SetNeedsAnimate() override;
@@ -160,15 +166,17 @@ class CONTENT_EXPORT CompositorImpl
void DetachRootWindow();
+ // Helper functions to perform delayed cleanup after the compositor is no
+ // longer visible on low-end devices.
+ void EnqueueLowEndBackgroundCleanup();
+ void DoLowEndBackgroundCleanup();
+
viz::FrameSinkId frame_sink_id_;
// root_layer_ is the persistent internal root layer, while subroot_layer_
// is the one attached by the compositor client.
scoped_refptr<cc::Layer> subroot_layer_;
- // Subtree for hidden layers with CopyOutputRequests on them.
- scoped_refptr<cc::Layer> readback_layer_tree_;
-
// Destruction order matters here:
std::unique_ptr<cc::AnimationHost> animation_host_;
std::unique_ptr<cc::LayerTreeHost> host_;
@@ -206,6 +214,13 @@ class CONTENT_EXPORT CompositorImpl
pending_child_frame_sink_ids_;
ui::CompositorLockManager lock_manager_;
bool has_submitted_frame_since_became_visible_ = false;
+
+ unsigned int pending_readback_request_count_ = 0u;
+
+ // A task which runs cleanup tasks on low-end Android after a delay. Enqueued
+ // when we hide, canceled when we're shown.
+ base::CancelableOnceClosure low_end_background_cleanup_task_;
+
base::WeakPtrFactory<CompositorImpl> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(CompositorImpl);
diff --git a/chromium/content/browser/renderer_host/compositor_impl_android_browsertest.cc b/chromium/content/browser/renderer_host/compositor_impl_android_browsertest.cc
new file mode 100644
index 00000000000..bfaadc54359
--- /dev/null
+++ b/chromium/content/browser/renderer_host/compositor_impl_android_browsertest.cc
@@ -0,0 +1,170 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "base/base_switches.h"
+#include "content/browser/browser_main_loop.h"
+#include "content/browser/gpu/gpu_process_host.h"
+#include "content/browser/renderer_host/compositor_impl_android.h"
+#include "content/browser/renderer_host/render_widget_host_view_android.h"
+#include "content/browser/web_contents/web_contents_impl.h"
+#include "content/common/gpu_stream_constants.h"
+#include "content/public/common/content_switches.h"
+#include "content/public/test/browser_test_utils.h"
+#include "content/public/test/content_browser_test.h"
+#include "content/public/test/content_browser_test_utils.h"
+#include "content/shell/browser/shell.h"
+#include "content/test/content_browser_test_utils_internal.h"
+#include "content/test/gpu_browsertest_helpers.h"
+#include "gpu/command_buffer/client/gles2_interface.h"
+#include "gpu/ipc/client/gpu_channel_host.h"
+#include "net/test/embedded_test_server/embedded_test_server.h"
+#include "ui/android/window_android.h"
+#include "url/gurl.h"
+
+namespace content {
+
+namespace {
+
+class CompositorImplLowEndBrowserTest : public ContentBrowserTest {
+ public:
+ CompositorImplLowEndBrowserTest() {}
+ void SetUpCommandLine(base::CommandLine* command_line) override {
+ command_line->AppendSwitch(switches::kEnableLowEndDeviceMode);
+ command_line->AppendSwitch(switches::kInProcessGPU);
+ content::ContentBrowserTest::SetUpCommandLine(command_line);
+ }
+
+ protected:
+ void SetUpOnMainThread() override {
+ ASSERT_TRUE(embedded_test_server()->Start());
+ net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS);
+ https_server.ServeFilesFromSourceDirectory("content/test/data");
+ ASSERT_TRUE(https_server.Start());
+ GURL http_url(embedded_test_server()->GetURL("/title1.html"));
+ ASSERT_TRUE(NavigateToURL(shell(), http_url));
+ }
+
+ ui::WindowAndroid* window() const {
+ return web_contents()->GetTopLevelNativeWindow();
+ }
+
+ CompositorImpl* compositor_impl() const {
+ return static_cast<CompositorImpl*>(window()->GetCompositor());
+ }
+
+ WebContentsImpl* web_contents() const {
+ return static_cast<WebContentsImpl*>(shell()->web_contents());
+ }
+
+ RenderWidgetHostViewAndroid* render_widget_host_view_android() const {
+ return static_cast<RenderWidgetHostViewAndroid*>(
+ web_contents()->GetRenderWidgetHostView());
+ }
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(CompositorImplLowEndBrowserTest);
+};
+
+// RunLoop implementation that calls glFlush() every second until it observes
+// OnContextLost().
+class ContextLostRunLoop : public viz::ContextLostObserver {
+ public:
+ ContextLostRunLoop(viz::ContextProvider* context_provider)
+ : context_provider_(context_provider) {
+ context_provider_->AddObserver(this);
+ }
+ ~ContextLostRunLoop() override { context_provider_->RemoveObserver(this); }
+
+ void RunUntilContextLost() {
+ CheckForContextLoss();
+ run_loop_.Run();
+ }
+
+ void CheckForContextLoss() {
+ if (did_lose_context_) {
+ run_loop_.Quit();
+ return;
+ }
+ context_provider_->ContextGL()->Flush();
+ base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
+ FROM_HERE,
+ base::BindOnce(&ContextLostRunLoop::CheckForContextLoss,
+ base::Unretained(this)),
+ base::TimeDelta::FromSeconds(1));
+ }
+
+ private:
+ // viz::LostContextProvider:
+ void OnContextLost() override { did_lose_context_ = true; }
+
+ viz::ContextProvider* const context_provider_;
+ bool did_lose_context_ = false;
+ base::RunLoop run_loop_;
+
+ DISALLOW_COPY_AND_ASSIGN(ContextLostRunLoop);
+};
+
+// RunLoop implementation that runs until it observes a compositor frame.
+class CompositorFrameRunLoop : public ui::WindowAndroidObserver {
+ public:
+ CompositorFrameRunLoop(ui::WindowAndroid* window) : window_(window) {
+ window_->AddObserver(this);
+ }
+ ~CompositorFrameRunLoop() override { window_->RemoveObserver(this); }
+
+ void RunUntilFrame() { run_loop_.Run(); }
+
+ private:
+ // ui::WindowAndroidObserver:
+ void OnCompositingDidCommit() override { run_loop_.Quit(); }
+ void OnRootWindowVisibilityChanged(bool visible) override {}
+ void OnAttachCompositor() override {}
+ void OnDetachCompositor() override {}
+ void OnActivityStopped() override {}
+ void OnActivityStarted() override {}
+
+ ui::WindowAndroid* const window_;
+ base::RunLoop run_loop_;
+
+ DISALLOW_COPY_AND_ASSIGN(CompositorFrameRunLoop);
+};
+
+IN_PROC_BROWSER_TEST_F(CompositorImplLowEndBrowserTest,
+ CompositorImplDropsResourcesOnBackground) {
+ auto* rwhva = render_widget_host_view_android();
+ auto* compositor = compositor_impl();
+ auto context = GpuBrowsertestCreateContext(
+ GpuBrowsertestEstablishGpuChannelSyncRunLoop());
+ context->BindToCurrentThread();
+
+ CompositorFrameRunLoop(window()).RunUntilFrame();
+ EXPECT_TRUE(rwhva->HasValidFrame());
+
+ ContextLostRunLoop run_loop(context.get());
+ compositor->SetVisibleForTesting(false);
+ rwhva->OnRootWindowVisibilityChanged(false);
+ rwhva->Hide();
+
+ // Ensure that context is eventually dropped and at that point we do not have
+ // a valid frame.
+ run_loop.RunUntilContextLost();
+ EXPECT_FALSE(rwhva->HasValidFrame());
+
+ // Become visible again:
+ compositor->SetVisibleForTesting(true);
+ rwhva->Show();
+ rwhva->OnRootWindowVisibilityChanged(true);
+
+ // We should have taken the compositor lock on resume.
+ EXPECT_TRUE(compositor->IsLockedForTesting());
+ EXPECT_FALSE(rwhva->HasValidFrame());
+
+ // The compositor should eventually be unlocked and produce a frame.
+ CompositorFrameRunLoop(window()).RunUntilFrame();
+ EXPECT_FALSE(compositor->IsLockedForTesting());
+ EXPECT_TRUE(rwhva->HasValidFrame());
+}
+
+} // namespace
+} // namespace content
diff --git a/chromium/content/browser/renderer_host/compositor_resize_lock_unittest.cc b/chromium/content/browser/renderer_host/compositor_resize_lock_unittest.cc
index cfd6a3d5a07..f4c42a1c4f9 100644
--- a/chromium/content/browser/renderer_host/compositor_resize_lock_unittest.cc
+++ b/chromium/content/browser/renderer_host/compositor_resize_lock_unittest.cc
@@ -6,7 +6,6 @@
#include "base/bind.h"
#include "base/callback.h"
-#include "base/memory/ptr_util.h"
#include "base/test/null_task_runner.h"
#include "testing/gtest/include/gtest/gtest.h"
diff --git a/chromium/content/browser/renderer_host/cursor_manager.cc b/chromium/content/browser/renderer_host/cursor_manager.cc
index e32ad8e37ba..724d64cd472 100644
--- a/chromium/content/browser/renderer_host/cursor_manager.cc
+++ b/chromium/content/browser/renderer_host/cursor_manager.cc
@@ -9,7 +9,9 @@
namespace content {
CursorManager::CursorManager(RenderWidgetHostViewBase* root)
- : view_under_cursor_(root), root_view_(root) {}
+ : view_under_cursor_(root),
+ root_view_(root),
+ tooltip_observer_for_testing_(nullptr) {}
CursorManager::~CursorManager() {}
@@ -20,7 +22,27 @@ void CursorManager::UpdateCursor(RenderWidgetHostViewBase* view,
root_view_->DisplayCursor(cursor);
}
+void CursorManager::SetTooltipTextForView(const RenderWidgetHostViewBase* view,
+ const base::string16& tooltip_text) {
+ if (view == view_under_cursor_) {
+ root_view_->DisplayTooltipText(tooltip_text);
+ if (tooltip_observer_for_testing_ && view) {
+ tooltip_observer_for_testing_->OnSetTooltipTextForView(view,
+ tooltip_text);
+ }
+ }
+}
+
void CursorManager::UpdateViewUnderCursor(RenderWidgetHostViewBase* view) {
+ if (view == view_under_cursor_)
+ return;
+
+ // Whenever we switch from one view to another, clear the tooltip: as the
+ // mouse moves, the view now controlling the cursor will send a new tooltip,
+ // though this is only guaranteed if the view's tooltip is non-empty, so
+ // clearing here is important. Tooltips sent from the previous view will be
+ // ignored.
+ SetTooltipTextForView(view_under_cursor_, base::string16());
view_under_cursor_ = view;
WebCursor cursor;
@@ -50,4 +72,8 @@ bool CursorManager::GetCursorForTesting(RenderWidgetHostViewBase* view,
return true;
}
-} // namespace content \ No newline at end of file
+void CursorManager::SetTooltipObserverForTesting(TooltipObserver* observer) {
+ tooltip_observer_for_testing_ = observer;
+}
+
+} // namespace content
diff --git a/chromium/content/browser/renderer_host/cursor_manager.h b/chromium/content/browser/renderer_host/cursor_manager.h
index d1480279522..a835fdd5abf 100644
--- a/chromium/content/browser/renderer_host/cursor_manager.h
+++ b/chromium/content/browser/renderer_host/cursor_manager.h
@@ -21,6 +21,15 @@ class RenderWidgetHostViewBase;
// update was received for the current view.
class CONTENT_EXPORT CursorManager {
public:
+ class TooltipObserver {
+ public:
+ virtual ~TooltipObserver() {}
+
+ virtual void OnSetTooltipTextForView(
+ const RenderWidgetHostViewBase* view,
+ const base::string16& tooltip_text) = 0;
+ };
+
CursorManager(RenderWidgetHostViewBase* root);
~CursorManager();
@@ -31,6 +40,11 @@ class CONTENT_EXPORT CursorManager {
// Called when the mouse moves over a different RenderWidgetHostView.
void UpdateViewUnderCursor(RenderWidgetHostViewBase*);
+ // Accepts TooltipText updates from views, but only updates what's displayed
+ // if the requesting view is currently under the mouse cursor.
+ void SetTooltipTextForView(const RenderWidgetHostViewBase* view,
+ const base::string16& tooltip_text);
+
// Notification of a RenderWidgetHostView being destroyed, so that its
// cursor map entry can be removed if it has one. If it is the current
// view_under_cursor_, then the root_view_'s cursor will be displayed.
@@ -41,6 +55,8 @@ class CONTENT_EXPORT CursorManager {
// the cursor otherwise.
bool GetCursorForTesting(RenderWidgetHostViewBase*, WebCursor&);
+ void SetTooltipObserverForTesting(TooltipObserver* observer);
+
private:
// Stores the last received cursor from each RenderWidgetHostView.
std::map<RenderWidgetHostViewBase*, WebCursor> cursor_map_;
@@ -52,8 +68,10 @@ class CONTENT_EXPORT CursorManager {
// The root view is the target for DisplayCursor calls whenever the active
// cursor needs to change.
RenderWidgetHostViewBase* root_view_;
+
+ TooltipObserver* tooltip_observer_for_testing_;
};
} // namespace content
-#endif // CONTENT_BROWSER_RENDERER_HOST_CURSOR_MANAGER_H_ \ No newline at end of file
+#endif // CONTENT_BROWSER_RENDERER_HOST_CURSOR_MANAGER_H_
diff --git a/chromium/content/browser/renderer_host/cursor_manager_unittest.cc b/chromium/content/browser/renderer_host/cursor_manager_unittest.cc
index b1773b51f43..80b769dc43f 100644
--- a/chromium/content/browser/renderer_host/cursor_manager_unittest.cc
+++ b/chromium/content/browser/renderer_host/cursor_manager_unittest.cc
@@ -4,7 +4,6 @@
#include "content/browser/renderer_host/cursor_manager.h"
-#include "base/test/scoped_task_environment.h"
#include "build/build_config.h"
#include "content/browser/renderer_host/render_widget_host_delegate.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
@@ -13,6 +12,7 @@
#include "content/public/common/cursor_info.h"
#include "content/public/test/mock_render_process_host.h"
#include "content/public/test/test_browser_context.h"
+#include "content/public/test/test_browser_thread_bundle.h"
#include "content/test/mock_render_widget_host_delegate.h"
#include "content/test/mock_widget_impl.h"
#include "content/test/test_render_view_host.h"
@@ -79,9 +79,7 @@ class MockRenderWidgetHost : public RenderWidgetHostImpl {
class CursorManagerTest : public testing::Test {
public:
- CursorManagerTest()
- : scoped_task_environment_(
- base::test::ScopedTaskEnvironment::MainThreadType::UI) {}
+ CursorManagerTest() {}
void SetUp() override {
browser_context_.reset(new TestBrowserContext);
@@ -106,7 +104,7 @@ class CursorManagerTest : public testing::Test {
}
protected:
- base::test::ScopedTaskEnvironment scoped_task_environment_;
+ TestBrowserThreadBundle thread_bundle_;
std::unique_ptr<BrowserContext> browser_context_;
std::unique_ptr<MockRenderProcessHost> process_host_;
diff --git a/chromium/content/browser/renderer_host/delegated_frame_host.cc b/chromium/content/browser/renderer_host/delegated_frame_host.cc
index 407bd2e2ef5..f5882bcd792 100644
--- a/chromium/content/browser/renderer_host/delegated_frame_host.cc
+++ b/chromium/content/browser/renderer_host/delegated_frame_host.cc
@@ -11,7 +11,6 @@
#include "base/callback_helpers.h"
#include "base/command_line.h"
-#include "base/memory/ptr_util.h"
#include "base/time/default_tick_clock.h"
#include "build/build_config.h"
#include "cc/base/switches.h"
@@ -132,12 +131,6 @@ void DelegatedFrameHost::CopyFromCompositingSurface(
const gfx::Rect& src_subrect,
const gfx::Size& output_size,
base::OnceCallback<void(const SkBitmap&)> callback) {
- if (!CanCopyFromCompositingSurface() ||
- current_frame_size_in_dip_.IsEmpty()) {
- std::move(callback).Run(SkBitmap());
- return;
- }
-
std::unique_ptr<viz::CopyOutputRequest> request =
std::make_unique<viz::CopyOutputRequest>(
viz::CopyOutputRequest::ResultFormat::RGBA_BITMAP,
@@ -148,32 +141,41 @@ void DelegatedFrameHost::CopyFromCompositingSurface(
},
std::move(callback)));
- if (src_subrect.IsEmpty()) {
- request->set_area(gfx::Rect(current_frame_size_in_dip_));
- } else {
+ if (!src_subrect.IsEmpty())
request->set_area(src_subrect);
- }
+ if (!output_size.IsEmpty())
+ request->set_result_selection(gfx::Rect(output_size));
- // If VIZ display compositing is disabled, the request will be issued directly
- // to CompositorFrameSinkSupport, which requires Surface pixel coordinates.
- if (!enable_viz_) {
- request->set_area(
- gfx::ScaleToRoundedRect(request->area(), active_device_scale_factor_));
- }
+ // If there is enough information to populate the copy output request fields,
+ // then process it now. Otherwise, wait until the information becomes
+ // available.
+ if (CanCopyFromCompositingSurface())
+ ProcessCopyOutputRequest(std::move(request));
+ else
+ pending_first_frame_requests_.push_back(std::move(request));
+}
- if (!output_size.IsEmpty()) {
- request->set_result_selection(gfx::Rect(output_size));
+void DelegatedFrameHost::ProcessCopyOutputRequest(
+ std::unique_ptr<viz::CopyOutputRequest> request) {
+ if (!request->has_area())
+ request->set_area(gfx::Rect(pending_surface_dip_size_));
+
+ // TODO(vmpstr): Should use pending device scale factor. We need to plumb
+ // it here.
+ request->set_area(
+ gfx::ScaleToRoundedRect(request->area(), active_device_scale_factor_));
+
+ if (request->has_result_selection()) {
+ const gfx::Rect& area = request->area();
+ const gfx::Rect& result_selection = request->result_selection();
request->SetScaleRatio(
- gfx::Vector2d(request->area().width(), request->area().height()),
- gfx::Vector2d(output_size.width(), output_size.height()));
+ gfx::Vector2d(area.width(), area.height()),
+ gfx::Vector2d(result_selection.width(), result_selection.height()));
}
- if (enable_viz_) {
- client_->DelegatedFrameHostGetLayer()->RequestCopyOfOutput(
- std::move(request));
- } else {
- support_->RequestCopyOfSurface(std::move(request));
- }
+ GetHostFrameSinkManager()->RequestCopyOfOutput(
+ viz::SurfaceId(frame_sink_id_, pending_local_surface_id_),
+ std::move(request));
}
bool DelegatedFrameHost::CanCopyFromCompositingSurface() const {
@@ -292,19 +294,25 @@ void DelegatedFrameHost::WasResized(
if (!primary_surface_id ||
primary_surface_id->local_surface_id() != pending_local_surface_id_) {
- current_frame_size_in_dip_ = pending_surface_dip_size_;
-
viz::SurfaceId surface_id(frame_sink_id_, pending_local_surface_id_);
#if defined(OS_WIN) || defined(USE_X11)
// On Windows and Linux, we would like to produce new content as soon as
// possible or the OS will create an additional black gutter. Until we can
// block resize on surface synchronization on these platforms, we will not
- // block UI on the top-level renderer.
- deadline_policy = cc::DeadlinePolicy::UseSpecifiedDeadline(0u);
+ // block UI on the top-level renderer. The exception to this is if we're
+ // using an infinite deadline, in which case we should respect the
+ // specified deadline and block UI since that's what was requested.
+ if (deadline_policy.policy_type() !=
+ cc::DeadlinePolicy::kUseInfiniteDeadline &&
+ !current_frame_size_in_dip_.IsEmpty() &&
+ current_frame_size_in_dip_ != pending_surface_dip_size_) {
+ deadline_policy = cc::DeadlinePolicy::UseSpecifiedDeadline(0u);
+ }
#endif
+ current_frame_size_in_dip_ = pending_surface_dip_size_;
client_->DelegatedFrameHostGetLayer()->SetShowPrimarySurface(
surface_id, current_frame_size_in_dip_, GetGutterColor(),
- deadline_policy);
+ deadline_policy, false /* stretch_content_to_fill_bounds */);
if (compositor_ && !base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableResizeLock)) {
compositor_->OnChildResizing();
@@ -537,7 +545,8 @@ void DelegatedFrameHost::OnFirstSurfaceActivation(
} else {
client_->DelegatedFrameHostGetLayer()->SetShowPrimarySurface(
surface_info.id(), frame_size_in_dip, GetGutterColor(),
- cc::DeadlinePolicy::UseDefaultDeadline());
+ cc::DeadlinePolicy::UseDefaultDeadline(),
+ false /* stretch_content_to_fill_bounds */);
}
client_->DelegatedFrameHostGetLayer()->SetFallbackSurfaceId(
@@ -559,6 +568,13 @@ void DelegatedFrameHost::OnFirstSurfaceActivation(
frame_evictor_->SwappedFrame(client_->DelegatedFrameHostIsVisible());
// Note: the frame may have been evicted immediately.
+
+ if (!pending_first_frame_requests_.empty()) {
+ DCHECK(CanCopyFromCompositingSurface());
+ for (auto& request : pending_first_frame_requests_)
+ ProcessCopyOutputRequest(std::move(request));
+ pending_first_frame_requests_.clear();
+ }
}
void DelegatedFrameHost::OnFrameTokenChanged(uint32_t frame_token) {
@@ -572,13 +588,9 @@ void DelegatedFrameHost::OnBeginFrame(const viz::BeginFrameArgs& args) {
}
void DelegatedFrameHost::EvictDelegatedFrame() {
- if (!HasSavedFrame())
- return;
-
- std::vector<viz::SurfaceId> surface_ids = {GetCurrentSurfaceId()};
-
- GetHostFrameSinkManager()->EvictSurfaces(surface_ids);
-
+ // It is possible that we are embedding the contents of previous
+ // DelegatedFrameHost. In this case, HasSavedFrame() will return false but we
+ // still need to clear the layer.
if (enable_surface_synchronization_) {
if (HasFallbackSurface()) {
client_->DelegatedFrameHostGetLayer()->SetFallbackSurfaceId(
@@ -590,6 +602,10 @@ void DelegatedFrameHost::EvictDelegatedFrame() {
UpdateGutters();
}
+ if (!HasSavedFrame())
+ return;
+ std::vector<viz::SurfaceId> surface_ids = {GetCurrentSurfaceId()};
+ GetHostFrameSinkManager()->EvictSurfaces(surface_ids);
frame_evictor_->DiscardedFrame();
}
@@ -726,4 +742,31 @@ bool DelegatedFrameHost::IsPrimarySurfaceEvicted() const {
!HasSavedFrame();
}
+void DelegatedFrameHost::WindowTitleChanged(const std::string& title) {
+ auto* host_frame_sink_manager = GetHostFrameSinkManager();
+ if (host_frame_sink_manager)
+ host_frame_sink_manager->SetFrameSinkDebugLabel(frame_sink_id_, title);
+}
+
+void DelegatedFrameHost::TakeFallbackContentFrom(DelegatedFrameHost* other) {
+ if (!other->HasFallbackSurface())
+ return;
+ if (HasFallbackSurface())
+ return;
+ if (!HasPrimarySurface()) {
+ client_->DelegatedFrameHostGetLayer()->SetShowPrimarySurface(
+ *other->client_->DelegatedFrameHostGetLayer()->GetFallbackSurfaceId(),
+ other->client_->DelegatedFrameHostGetLayer()->size(),
+ other->client_->DelegatedFrameHostGetLayer()->background_color(),
+ cc::DeadlinePolicy::UseDefaultDeadline(),
+ false /* stretch_content_to_fill_bounds */);
+ }
+ client_->DelegatedFrameHostGetLayer()->SetFallbackSurfaceId(
+ *other->client_->DelegatedFrameHostGetLayer()->GetFallbackSurfaceId());
+ if (!enable_surface_synchronization_) {
+ current_frame_size_in_dip_ = other->current_frame_size_in_dip_;
+ UpdateGutters();
+ }
+}
+
} // namespace content
diff --git a/chromium/content/browser/renderer_host/delegated_frame_host.h b/chromium/content/browser/renderer_host/delegated_frame_host.h
index 6009c048221..c8a99f8374e 100644
--- a/chromium/content/browser/renderer_host/delegated_frame_host.h
+++ b/chromium/content/browser/renderer_host/delegated_frame_host.h
@@ -199,6 +199,12 @@ class CONTENT_EXPORT DelegatedFrameHost
bool IsPrimarySurfaceEvicted() const;
+ void WindowTitleChanged(const std::string& title);
+
+ // If our SurfaceLayer doesn't have a fallback, use the fallback info of
+ // |other|.
+ void TakeFallbackContentFrom(DelegatedFrameHost* other);
+
private:
friend class DelegatedFrameHostClient;
FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest,
@@ -227,6 +233,9 @@ class CONTENT_EXPORT DelegatedFrameHost
void CreateCompositorFrameSinkSupport();
void ResetCompositorFrameSinkSupport();
+ void ProcessCopyOutputRequest(
+ std::unique_ptr<viz::CopyOutputRequest> request);
+
const viz::FrameSinkId frame_sink_id_;
DelegatedFrameHostClient* const client_;
const bool enable_surface_synchronization_;
@@ -254,7 +263,7 @@ class CONTENT_EXPORT DelegatedFrameHost
gfx::Size current_frame_size_in_dip_;
// Overridable tick clock used for testing functions using current time.
- base::TickClock* tick_clock_;
+ const base::TickClock* tick_clock_;
// True after a delegated frame has been skipped, until a frame is not
// skipped.
@@ -292,6 +301,9 @@ class CONTENT_EXPORT DelegatedFrameHost
uint32_t first_parent_sequence_number_after_navigation_ = 0;
bool received_frame_after_navigation_ = false;
+
+ std::vector<std::unique_ptr<viz::CopyOutputRequest>>
+ pending_first_frame_requests_;
};
} // namespace content
diff --git a/chromium/content/browser/renderer_host/direct_manipulation_browsertest.cc b/chromium/content/browser/renderer_host/direct_manipulation_browsertest.cc
new file mode 100644
index 00000000000..38c2793c6fc
--- /dev/null
+++ b/chromium/content/browser/renderer_host/direct_manipulation_browsertest.cc
@@ -0,0 +1,329 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "ui/base/win/direct_manipulation.h"
+
+#include <windows.h>
+
+#include "base/macros.h"
+#include "base/test/scoped_feature_list.h"
+#include "base/win/windows_version.h"
+#include "content/browser/renderer_host/legacy_render_widget_host_win.h"
+#include "content/browser/renderer_host/render_widget_host_view_aura.h"
+#include "content/browser/web_contents/web_contents_impl.h"
+#include "content/public/test/content_browser_test.h"
+#include "content/public/test/content_browser_test_utils.h"
+#include "content/shell/browser/shell.h"
+#include "ui/aura/window.h"
+#include "ui/aura/window_tree_host.h"
+#include "ui/base/ui_base_features.h"
+#include "ui/base/win/window_event_target.h"
+#include "ui/events/event_rewriter.h"
+#include "ui/events/event_source.h"
+#include "url/gurl.h"
+
+namespace content {
+
+class DirectManipulationBrowserTest : public ContentBrowserTest,
+ public testing::WithParamInterface<bool> {
+ public:
+ DirectManipulationBrowserTest() {
+ if (GetParam()) {
+ scoped_feature_list_.InitWithFeatures(
+ {features::kPrecisionTouchpad,
+ features::kPrecisionTouchpadScrollPhase},
+ {});
+ } else {
+ scoped_feature_list_.InitWithFeatures(
+ {features::kPrecisionTouchpad},
+ {features::kPrecisionTouchpadScrollPhase});
+ }
+ }
+
+ ~DirectManipulationBrowserTest() override {}
+
+ LegacyRenderWidgetHostHWND* GetLegacyRenderWidgetHostHWND() {
+ RenderWidgetHostViewAura* rwhva = static_cast<RenderWidgetHostViewAura*>(
+ shell()->web_contents()->GetRenderWidgetHostView());
+ return rwhva->legacy_render_widget_host_HWND_;
+ }
+
+ HWND GetSubWindowHWND() {
+ LegacyRenderWidgetHostHWND* lrwhh = GetLegacyRenderWidgetHostHWND();
+
+ return lrwhh->hwnd();
+ }
+
+ ui::WindowEventTarget* GetWindowEventTarget() {
+ LegacyRenderWidgetHostHWND* lrwhh = GetLegacyRenderWidgetHostHWND();
+
+ return lrwhh->GetWindowEventTarget(lrwhh->GetParent());
+ }
+
+ void SimulatePointerHitTest() {
+ LegacyRenderWidgetHostHWND* lrwhh = GetLegacyRenderWidgetHostHWND();
+
+ lrwhh->direct_manipulation_helper_->need_poll_events_ = true;
+ lrwhh->CreateAnimationObserver();
+ }
+
+ void UpdateParent(HWND hwnd) {
+ LegacyRenderWidgetHostHWND* lrwhh = GetLegacyRenderWidgetHostHWND();
+
+ lrwhh->UpdateParent(hwnd);
+ }
+
+ bool HasCompositorAnimationObserver(LegacyRenderWidgetHostHWND* lrwhh) {
+ return lrwhh->compositor_animation_observer_ != nullptr;
+ }
+
+ private:
+ base::test::ScopedFeatureList scoped_feature_list_;
+
+ DISALLOW_COPY_AND_ASSIGN(DirectManipulationBrowserTest);
+};
+
+INSTANTIATE_TEST_CASE_P(WithScrollEventPhase,
+ DirectManipulationBrowserTest,
+ testing::Bool());
+
+// Ensure the AnimationObserver destroy when hwnd reparent to other hwnd.
+IN_PROC_BROWSER_TEST_P(DirectManipulationBrowserTest, HWNDReparent) {
+ if (base::win::GetVersion() < base::win::VERSION_WIN10)
+ return;
+
+ NavigateToURL(shell(), GURL(url::kAboutBlankURL));
+
+ LegacyRenderWidgetHostHWND* lrwhh = GetLegacyRenderWidgetHostHWND();
+ ASSERT_TRUE(lrwhh);
+
+ // The observer should not create before it needed.
+ ASSERT_TRUE(!HasCompositorAnimationObserver(lrwhh));
+
+ // Add AnimationObserver to tab to simulate direct manipulation start.
+ SimulatePointerHitTest();
+ ASSERT_TRUE(HasCompositorAnimationObserver(lrwhh));
+
+ // Create another browser.
+ Shell* shell2 = CreateBrowser();
+ NavigateToURL(shell2, GURL(url::kAboutBlankURL));
+
+ // Move to the tab to browser2.
+ UpdateParent(
+ shell2->window()->GetRootWindow()->GetHost()->GetAcceleratedWidget());
+
+ shell()->Close();
+
+ // The animation observer should be removed.
+ EXPECT_FALSE(HasCompositorAnimationObserver(lrwhh));
+}
+
+// EventLogger is to obserser the events sent from WindowEventTarget (the root
+// window).
+class EventLogger : public ui::EventRewriter {
+ public:
+ EventLogger() {}
+ ~EventLogger() override {}
+
+ std::unique_ptr<ui::Event> ReleaseLastEvent() {
+ return std::move(last_event_);
+ }
+
+ private:
+ // ui::EventRewriter
+ ui::EventRewriteStatus RewriteEvent(
+ const ui::Event& event,
+ std::unique_ptr<ui::Event>* new_event) override {
+ DCHECK(!last_event_);
+ last_event_ = ui::Event::Clone(event);
+ return ui::EVENT_REWRITE_CONTINUE;
+ }
+
+ // ui::EventRewriter
+ ui::EventRewriteStatus NextDispatchEvent(
+ const ui::Event& last_event,
+ std::unique_ptr<ui::Event>* new_event) override {
+ return ui::EVENT_REWRITE_CONTINUE;
+ }
+
+ std::unique_ptr<ui::Event> last_event_ = nullptr;
+
+ DISALLOW_COPY_AND_ASSIGN(EventLogger);
+};
+
+// Check DirectManipulation events convert to ui::event correctly.
+IN_PROC_BROWSER_TEST_P(DirectManipulationBrowserTest, EventConvert) {
+ if (base::win::GetVersion() < base::win::VERSION_WIN10)
+ return;
+
+ NavigateToURL(shell(), GURL(url::kAboutBlankURL));
+
+ LegacyRenderWidgetHostHWND* lrwhh = GetLegacyRenderWidgetHostHWND();
+ ASSERT_TRUE(lrwhh);
+
+ HWND hwnd =
+ shell()->window()->GetRootWindow()->GetHost()->GetAcceleratedWidget();
+
+ ui::EventSource* dwthw = static_cast<ui::EventSource*>(
+ aura::WindowTreeHost::GetForAcceleratedWidget(hwnd));
+ EventLogger event_logger;
+ dwthw->AddEventRewriter(&event_logger);
+
+ ui::WindowEventTarget* target = GetWindowEventTarget();
+
+ {
+ target->ApplyPanGestureScroll(1, 2);
+ std::unique_ptr<ui::Event> event = event_logger.ReleaseLastEvent();
+ ASSERT_TRUE(event);
+
+ if (GetParam()) {
+ EXPECT_EQ(ui::ET_SCROLL, event->type());
+ ui::ScrollEvent* scroll_event = event->AsScrollEvent();
+ EXPECT_EQ(1, scroll_event->x_offset());
+ EXPECT_EQ(2, scroll_event->y_offset());
+ EXPECT_EQ(ui::EventMomentumPhase::NONE, scroll_event->momentum_phase());
+ EXPECT_EQ(ui::ScrollEventPhase::kUpdate,
+ scroll_event->scroll_event_phase());
+ } else {
+ EXPECT_EQ(ui::ET_MOUSEWHEEL, event->type());
+ ui::MouseWheelEvent* wheel_event = event->AsMouseWheelEvent();
+ EXPECT_EQ(1, wheel_event->x_offset());
+ EXPECT_EQ(2, wheel_event->y_offset());
+ EXPECT_TRUE(wheel_event->flags() & ui::EF_PRECISION_SCROLLING_DELTA);
+ }
+ }
+
+ {
+ target->ApplyPanGestureFling(1, 2);
+ std::unique_ptr<ui::Event> event = event_logger.ReleaseLastEvent();
+ ASSERT_TRUE(event);
+
+ if (GetParam()) {
+ EXPECT_EQ(ui::ET_SCROLL, event->type());
+ ui::ScrollEvent* scroll_event = event->AsScrollEvent();
+ EXPECT_EQ(1, scroll_event->x_offset());
+ EXPECT_EQ(2, scroll_event->y_offset());
+ EXPECT_EQ(ui::EventMomentumPhase::INERTIAL_UPDATE,
+ scroll_event->momentum_phase());
+ EXPECT_EQ(ui::ScrollEventPhase::kNone,
+ scroll_event->scroll_event_phase());
+ } else {
+ EXPECT_EQ(ui::ET_MOUSEWHEEL, event->type());
+ ui::MouseWheelEvent* wheel_event = event->AsMouseWheelEvent();
+ EXPECT_EQ(1, wheel_event->x_offset());
+ EXPECT_EQ(2, wheel_event->y_offset());
+ EXPECT_TRUE(wheel_event->flags() & ui::EF_PRECISION_SCROLLING_DELTA);
+ }
+ }
+
+ {
+ target->ApplyPanGestureScrollBegin(1, 2);
+ std::unique_ptr<ui::Event> event = event_logger.ReleaseLastEvent();
+
+ if (GetParam()) {
+ ASSERT_TRUE(event);
+ EXPECT_EQ(ui::ET_SCROLL, event->type());
+ ui::ScrollEvent* scroll_event = event->AsScrollEvent();
+ EXPECT_EQ(1, scroll_event->x_offset());
+ EXPECT_EQ(2, scroll_event->y_offset());
+ EXPECT_EQ(ui::EventMomentumPhase::NONE, scroll_event->momentum_phase());
+ EXPECT_EQ(ui::ScrollEventPhase::kBegan,
+ scroll_event->scroll_event_phase());
+ } else {
+ EXPECT_EQ(ui::ET_MOUSEWHEEL, event->type());
+ ui::MouseWheelEvent* wheel_event = event->AsMouseWheelEvent();
+ EXPECT_EQ(1, wheel_event->x_offset());
+ EXPECT_EQ(2, wheel_event->y_offset());
+ EXPECT_TRUE(wheel_event->flags() & ui::EF_PRECISION_SCROLLING_DELTA);
+ }
+ }
+
+ {
+ target->ApplyPanGestureScrollEnd();
+ std::unique_ptr<ui::Event> event = event_logger.ReleaseLastEvent();
+
+ if (GetParam()) {
+ ASSERT_TRUE(event);
+ EXPECT_EQ(ui::ET_SCROLL, event->type());
+ ui::ScrollEvent* scroll_event = event->AsScrollEvent();
+ EXPECT_EQ(0, scroll_event->x_offset());
+ EXPECT_EQ(0, scroll_event->y_offset());
+ EXPECT_EQ(ui::EventMomentumPhase::NONE, scroll_event->momentum_phase());
+ EXPECT_EQ(ui::ScrollEventPhase::kEnd, scroll_event->scroll_event_phase());
+ } else {
+ ASSERT_FALSE(event);
+ }
+ }
+
+ {
+ target->ApplyPanGestureFlingBegin();
+ std::unique_ptr<ui::Event> event = event_logger.ReleaseLastEvent();
+
+ if (GetParam()) {
+ ASSERT_TRUE(event);
+ EXPECT_EQ(ui::ET_SCROLL, event->type());
+ ui::ScrollEvent* scroll_event = event->AsScrollEvent();
+ EXPECT_EQ(0, scroll_event->x_offset());
+ EXPECT_EQ(0, scroll_event->y_offset());
+ EXPECT_EQ(ui::EventMomentumPhase::BEGAN, scroll_event->momentum_phase());
+ EXPECT_EQ(ui::ScrollEventPhase::kNone,
+ scroll_event->scroll_event_phase());
+ } else {
+ ASSERT_FALSE(event);
+ }
+ }
+
+ {
+ target->ApplyPanGestureFlingEnd();
+ std::unique_ptr<ui::Event> event = event_logger.ReleaseLastEvent();
+
+ if (GetParam()) {
+ ASSERT_TRUE(event);
+ EXPECT_EQ(ui::ET_SCROLL, event->type());
+ ui::ScrollEvent* scroll_event = event->AsScrollEvent();
+ EXPECT_EQ(0, scroll_event->x_offset());
+ EXPECT_EQ(0, scroll_event->y_offset());
+ EXPECT_EQ(ui::EventMomentumPhase::END, scroll_event->momentum_phase());
+ EXPECT_EQ(ui::ScrollEventPhase::kNone,
+ scroll_event->scroll_event_phase());
+ } else {
+ ASSERT_FALSE(event);
+ }
+ }
+
+ {
+ target->ApplyPinchZoomBegin();
+ std::unique_ptr<ui::Event> event = event_logger.ReleaseLastEvent();
+ ASSERT_TRUE(event);
+ EXPECT_EQ(ui::ET_GESTURE_PINCH_BEGIN, event->type());
+ ui::GestureEvent* gesture_event = event->AsGestureEvent();
+ EXPECT_EQ(ui::GestureDeviceType::DEVICE_TOUCHPAD,
+ gesture_event->details().device_type());
+ }
+
+ {
+ target->ApplyPinchZoomScale(1.1f);
+ std::unique_ptr<ui::Event> event = event_logger.ReleaseLastEvent();
+ ASSERT_TRUE(event);
+ EXPECT_EQ(ui::ET_GESTURE_PINCH_UPDATE, event->type());
+ ui::GestureEvent* gesture_event = event->AsGestureEvent();
+ EXPECT_EQ(ui::GestureDeviceType::DEVICE_TOUCHPAD,
+ gesture_event->details().device_type());
+ EXPECT_EQ(1.1f, gesture_event->details().scale());
+ }
+
+ {
+ target->ApplyPinchZoomEnd();
+ std::unique_ptr<ui::Event> event = event_logger.ReleaseLastEvent();
+ ASSERT_TRUE(event);
+ EXPECT_EQ(ui::ET_GESTURE_PINCH_END, event->type());
+ ui::GestureEvent* gesture_event = event->AsGestureEvent();
+ EXPECT_EQ(ui::GestureDeviceType::DEVICE_TOUCHPAD,
+ gesture_event->details().device_type());
+ }
+
+ dwthw->RemoveEventRewriter(&event_logger);
+}
+
+} // namespace content
diff --git a/chromium/content/browser/renderer_host/display_util.cc b/chromium/content/browser/renderer_host/display_util.cc
index 3c1a80d3c11..204211f7404 100644
--- a/chromium/content/browser/renderer_host/display_util.cc
+++ b/chromium/content/browser/renderer_host/display_util.cc
@@ -58,12 +58,9 @@ void DisplayUtil::GetDefaultScreenInfo(ScreenInfo* screen_info) {
*screen_info = ScreenInfo();
return;
}
-#if defined(OS_MACOSX) || defined(USE_AURA)
- // On macOS, we use the display nearest the nullptr view to return the most
- // recently active screen, instead of the primary screen
- // https://crbug.com/357443
- // On Aura, this decision may or may not have been taken intentionally, and
- // may or may not have any effect.
+#if defined(USE_AURA)
+ // This behavior difference between Aura and other platforms may or may not
+ // be intentional, and may or may not have any effect.
gfx::NativeView null_native_view = nullptr;
display::Display display = screen->GetDisplayNearestView(null_native_view);
#else
@@ -81,14 +78,9 @@ void DisplayUtil::GetNativeViewScreenInfo(ScreenInfo* screen_info,
*screen_info = ScreenInfo();
return;
}
-#if defined(OS_MACOSX)
- // See previous comment regarding https://crbug.com/357443
- display::Display display = screen->GetDisplayNearestView(native_view);
-#else
display::Display display = native_view
? screen->GetDisplayNearestView(native_view)
: screen->GetPrimaryDisplay();
-#endif
DisplayToScreenInfo(screen_info, display);
}
diff --git a/chromium/content/browser/renderer_host/frame_connector_delegate.cc b/chromium/content/browser/renderer_host/frame_connector_delegate.cc
index a03a4045970..9ec6c756d3c 100644
--- a/chromium/content/browser/renderer_host/frame_connector_delegate.cc
+++ b/chromium/content/browser/renderer_host/frame_connector_delegate.cc
@@ -7,6 +7,7 @@
#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_view_child_frame.h"
#include "content/common/content_switches_internal.h"
+#include "content/common/frame_resize_params.h"
namespace content {
@@ -25,16 +26,13 @@ FrameConnectorDelegate::GetRootRenderWidgetHostView() {
}
void FrameConnectorDelegate::UpdateResizeParams(
- const gfx::Rect& screen_space_rect,
- const gfx::Size& local_frame_size,
- const ScreenInfo& screen_info,
- uint64_t sequence_number,
- const viz::SurfaceId& surface_id) {
- screen_info_ = screen_info;
+ const viz::SurfaceId& surface_id,
+ const FrameResizeParams& resize_params) {
+ screen_info_ = resize_params.screen_info;
local_surface_id_ = surface_id.local_surface_id();
- SetScreenSpaceRect(screen_space_rect);
- SetLocalFrameSize(local_frame_size);
+ SetScreenSpaceRect(resize_params.screen_space_rect);
+ SetLocalFrameSize(resize_params.local_frame_size);
if (!view_)
return;
@@ -42,11 +40,16 @@ void FrameConnectorDelegate::UpdateResizeParams(
view_->SetFrameSinkId(surface_id.frame_sink_id());
#endif // defined(USE_AURA)
- RenderWidgetHostImpl* render_widget_host = view_->GetRenderWidgetHostImpl();
+ RenderWidgetHostImpl* render_widget_host = view_->host();
DCHECK(render_widget_host);
+ render_widget_host->SetAutoResize(resize_params.auto_resize_enabled,
+ resize_params.min_size_for_auto_resize,
+ resize_params.max_size_for_auto_resize);
+
if (render_widget_host->auto_resize_enabled()) {
- render_widget_host->DidAllocateLocalSurfaceIdForAutoResize(sequence_number);
+ render_widget_host->DidAllocateLocalSurfaceIdForAutoResize(
+ resize_params.auto_resize_sequence_number);
return;
}
@@ -83,6 +86,11 @@ bool FrameConnectorDelegate::LockMouse() {
return false;
}
+void FrameConnectorDelegate::EnableAutoResize(const gfx::Size& min_size,
+ const gfx::Size& max_size) {}
+
+void FrameConnectorDelegate::DisableAutoResize() {}
+
bool FrameConnectorDelegate::IsInert() const {
return false;
}
diff --git a/chromium/content/browser/renderer_host/frame_connector_delegate.h b/chromium/content/browser/renderer_host/frame_connector_delegate.h
index af0b0ff300a..577db6d0147 100644
--- a/chromium/content/browser/renderer_host/frame_connector_delegate.h
+++ b/chromium/content/browser/renderer_host/frame_connector_delegate.h
@@ -30,6 +30,7 @@ namespace content {
class RenderWidgetHostViewBase;
class RenderWidgetHostViewChildFrame;
class WebCursor;
+struct FrameResizeParams;
//
// FrameConnectorDelegate
@@ -72,11 +73,8 @@ class CONTENT_EXPORT FrameConnectorDelegate {
const blink::WebIntrinsicSizingInfo&) {}
// Sends new resize parameters to the sub-frame's renderer.
- void UpdateResizeParams(const gfx::Rect& screen_space_rect,
- const gfx::Size& local_frame_size,
- const ScreenInfo& screen_info,
- uint64_t sequence_number,
- const viz::SurfaceId& surface_id);
+ void UpdateResizeParams(const viz::SurfaceId& surface_id,
+ const FrameResizeParams& resize_params);
// Return the size of the CompositorFrame to use in the child renderer.
const gfx::Size& local_frame_size_in_pixels() {
@@ -160,10 +158,16 @@ class CONTENT_EXPORT FrameConnectorDelegate {
// Returns a rect that represents the intersection of the current view's
// content bounds with the top-level browser viewport.
- const gfx::Rect& ViewportIntersection() const {
+ const gfx::Rect& viewport_intersection_rect() const {
return viewport_intersection_rect_;
}
+ // Returns a rect in physical pixels that indicates the area of the current
+ // view's content bounds that should be rastered by the compositor.
+ const gfx::Rect& compositor_visible_rect() const {
+ return compositor_visible_rect_;
+ }
+
// Returns the viz::LocalSurfaceId propagated from the parent to be used by
// this child frame.
const viz::LocalSurfaceId& local_surface_id() const {
@@ -178,6 +182,14 @@ class CONTENT_EXPORT FrameConnectorDelegate {
screen_info_ = screen_info;
}
+ // Informs the parent the child will enter auto-resize mode, automatically
+ // resizing itself to the provided |min_size| and |max_size| constraints.
+ virtual void EnableAutoResize(const gfx::Size& min_size,
+ const gfx::Size& max_size);
+
+ // Turns off auto-resize mode.
+ virtual void DisableAutoResize();
+
// Determines whether the current view's content is inert, either because
// an HTMLDialogElement is being modally displayed in a higher-level frame,
// or because the inert attribute has been specified.
@@ -233,6 +245,8 @@ class CONTENT_EXPORT FrameConnectorDelegate {
// ViewportIntersection() can return a reference.
gfx::Rect viewport_intersection_rect_;
+ gfx::Rect compositor_visible_rect_;
+
ScreenInfo screen_info_;
gfx::Size local_frame_size_in_dip_;
gfx::Size local_frame_size_in_pixels_;
diff --git a/chromium/content/browser/renderer_host/frame_token_message_queue.cc b/chromium/content/browser/renderer_host/frame_token_message_queue.cc
index 98ed2cf04cd..e471c3a1dc2 100644
--- a/chromium/content/browser/renderer_host/frame_token_message_queue.cc
+++ b/chromium/content/browser/renderer_host/frame_token_message_queue.cc
@@ -22,49 +22,54 @@ void FrameTokenMessageQueue::DidProcessFrame(uint32_t frame_token) {
last_received_frame_token_ = frame_token;
- while (queued_messages_.size() &&
- queued_messages_.front().first <= frame_token) {
- ProcessSwapMessages(std::move(queued_messages_.front().second));
- queued_messages_.pop();
- }
+ // Gets the first callback associated with a token after |frame_token| or
+ // callback_map_.end().
+ auto upper_bound = callback_map_.upper_bound(frame_token);
+
+ // std::multimap already sorts on keys, so this will process all enqueued
+ // messages up to the current frame token.
+ for (auto it = callback_map_.begin(); it != upper_bound; ++it)
+ std::move(it->second).Run();
+
+ // Clear all callbacks up to the current frame token.
+ callback_map_.erase(callback_map_.begin(), upper_bound);
}
-void FrameTokenMessageQueue::OnFrameSwapMessagesReceived(
+void FrameTokenMessageQueue::EnqueueOrRunFrameTokenCallback(
uint32_t frame_token,
- std::vector<IPC::Message> messages) {
+ base::OnceClosure callback) {
// Zero token is invalid.
if (!frame_token) {
client_->OnInvalidFrameToken(frame_token);
return;
}
- // Frame tokens always increase.
- if (queued_messages_.size() && frame_token <= queued_messages_.back().first) {
- client_->OnInvalidFrameToken(frame_token);
- return;
- }
-
if (frame_token <= last_received_frame_token_) {
- ProcessSwapMessages(std::move(messages));
+ std::move(callback).Run();
return;
}
+ callback_map_.insert(std::make_pair(frame_token, std::move(callback)));
+}
- queued_messages_.push(std::make_pair(frame_token, std::move(messages)));
+void FrameTokenMessageQueue::OnFrameSwapMessagesReceived(
+ uint32_t frame_token,
+ std::vector<IPC::Message> messages) {
+ EnqueueOrRunFrameTokenCallback(
+ frame_token, base::BindOnce(&FrameTokenMessageQueue::ProcessSwapMessages,
+ base::Unretained(this), std::move(messages)));
}
void FrameTokenMessageQueue::Reset() {
last_received_frame_token_ = 0;
- // base::queue does not contain a clear.
- auto doomed = std::move(queued_messages_);
+ callback_map_.clear();
}
void FrameTokenMessageQueue::ProcessSwapMessages(
std::vector<IPC::Message> messages) {
- for (std::vector<IPC::Message>::const_iterator i = messages.begin();
- i != messages.end(); ++i) {
- client_->OnProcessSwapMessage(*i);
- if (i->dispatch_error())
- client_->OnMessageDispatchError(*i);
+ for (const IPC::Message& i : messages) {
+ client_->OnProcessSwapMessage(i);
+ if (i.dispatch_error())
+ client_->OnMessageDispatchError(i);
}
}
diff --git a/chromium/content/browser/renderer_host/frame_token_message_queue.h b/chromium/content/browser/renderer_host/frame_token_message_queue.h
index 48204ac1b86..209044764b6 100644
--- a/chromium/content/browser/renderer_host/frame_token_message_queue.h
+++ b/chromium/content/browser/renderer_host/frame_token_message_queue.h
@@ -5,9 +5,10 @@
#ifndef CONTENT_BROWSER_RENDERER_HOST_FRAME_TOKEN_MESSAGE_QUEUE_H_
#define CONTENT_BROWSER_RENDERER_HOST_FRAME_TOKEN_MESSAGE_QUEUE_H_
+#include <map>
#include <vector>
-#include "base/containers/queue.h"
+#include "base/callback.h"
#include "base/macros.h"
#include "content/common/content_export.h"
@@ -17,17 +18,20 @@ class Message;
namespace content {
-// The Renderer sends various IPC::Messages which are not to be processed until
-// after their associated frame has been processed. These messages are provided
-// with a FrameToken to be used for synchronizing.
+// The Renderer sends various messages which are not to be processed until after
+// their associated frame has been processed. These messages are provided with a
+// FrameToken to be used for synchronizing.
//
// Viz processes the frames, after which it notifies the Browser of which
// FrameToken has completed processing.
//
// This enqueues all IPC::Messages associated with a FrameToken.
//
+// Additionally other callbacks can be enqueued with
+// EnqueueOrRunFrameTokenCallback.
+//
// Upon receipt of DidProcessFrame all IPC::Messages associated with the
-// provided FrameToken are then dispatched.
+// provided FrameToken are then dispatched, and all enqueued callbacks are ran.
class CONTENT_EXPORT FrameTokenMessageQueue {
public:
// Notified of errors in processing messages, as well as of the actual
@@ -52,6 +56,12 @@ class CONTENT_EXPORT FrameTokenMessageQueue {
// there are any queued messages belonging to it, they will be processed.
void DidProcessFrame(uint32_t frame_token);
+ // Enqueues |callback| to be called upon the arrival of |frame_token| in
+ // DidProcessFrame. However if |frame_token| has already arrived |callback| is
+ // ran immediately.
+ void EnqueueOrRunFrameTokenCallback(uint32_t frame_token,
+ base::OnceClosure callback);
+
// Enqueues the swap messages.
void OnFrameSwapMessagesReceived(uint32_t frame_token,
std::vector<IPC::Message> messages);
@@ -60,7 +70,7 @@ class CONTENT_EXPORT FrameTokenMessageQueue {
// consistent incase a new renderer is created.
void Reset();
- uint32_t size() const { return queued_messages_.size(); }
+ uint32_t size() const { return callback_map_.size(); }
protected:
// Once both the frame and its swap messages arrive, we call this method to
@@ -75,9 +85,9 @@ class CONTENT_EXPORT FrameTokenMessageQueue {
// having a token less than or equal to this value will be processed.
uint32_t last_received_frame_token_ = 0;
- // List of all swap messages that their corresponding frames have not arrived.
+ // Map of all callbacks for which their corresponding frame have not arrived.
// Sorted by frame token.
- base::queue<std::pair<uint32_t, std::vector<IPC::Message>>> queued_messages_;
+ std::multimap<uint32_t, base::OnceClosure> callback_map_;
DISALLOW_COPY_AND_ASSIGN(FrameTokenMessageQueue);
};
diff --git a/chromium/content/browser/renderer_host/frame_token_message_queue_unittest.cc b/chromium/content/browser/renderer_host/frame_token_message_queue_unittest.cc
new file mode 100644
index 00000000000..96e171cdc89
--- /dev/null
+++ b/chromium/content/browser/renderer_host/frame_token_message_queue_unittest.cc
@@ -0,0 +1,665 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/renderer_host/frame_token_message_queue.h"
+
+#include <vector>
+
+#include "base/macros.h"
+#include "ipc/ipc_message.h"
+#include "testing/gtest/include/gtest/gtest.h"
+
+namespace content {
+
+namespace {
+
+// Test verision of FrameTokenMessageQueue::Client which tracks the number of
+// calls to client methods, and the associated input parameters.
+class TestFrameTokenMessageQueueClient : public FrameTokenMessageQueue::Client {
+ public:
+ TestFrameTokenMessageQueueClient() {}
+ ~TestFrameTokenMessageQueueClient() {}
+
+ // Resets all method counters.
+ void Reset();
+
+ // All subsequent IPC::Messages received in OnProcessSwapMessage will be
+ // marked as having a dispatch error.
+ void SetErrorOnMessageProcess();
+
+ // FrameTokenMessageQueue::Client:
+ void OnInvalidFrameToken(uint32_t frame_token) override;
+ void OnMessageDispatchError(const IPC::Message& message) override;
+ void OnProcessSwapMessage(const IPC::Message& message) override;
+
+ bool invalid_frame_token_called() const {
+ return invalid_frame_token_called_;
+ }
+ uint32_t invalid_frame_token() const { return invalid_frame_token_; }
+ int on_message_dispatch_error_count() const {
+ return on_message_dispatch_error_count_;
+ }
+ int on_process_swap_message_count() const {
+ return on_process_swap_message_count_;
+ }
+
+ private:
+ // If true the each IPC::Message received will be marked as having a dispatch
+ // error.
+ bool set_error_on_process_ = false;
+ bool invalid_frame_token_called_ = false;
+ uint32_t invalid_frame_token_ = 0u;
+ int on_message_dispatch_error_count_ = 0;
+ int on_process_swap_message_count_ = 0;
+ DISALLOW_COPY_AND_ASSIGN(TestFrameTokenMessageQueueClient);
+};
+
+void TestFrameTokenMessageQueueClient::Reset() {
+ invalid_frame_token_called_ = false;
+ invalid_frame_token_ = 0u;
+ on_message_dispatch_error_count_ = 0;
+ on_process_swap_message_count_ = 0;
+}
+
+void TestFrameTokenMessageQueueClient::SetErrorOnMessageProcess() {
+ set_error_on_process_ = true;
+}
+
+void TestFrameTokenMessageQueueClient::OnInvalidFrameToken(
+ uint32_t frame_token) {
+ invalid_frame_token_called_ = true;
+ invalid_frame_token_ = frame_token;
+}
+
+void TestFrameTokenMessageQueueClient::OnMessageDispatchError(
+ const IPC::Message& message) {
+ ++on_message_dispatch_error_count_;
+}
+
+void TestFrameTokenMessageQueueClient::OnProcessSwapMessage(
+ const IPC::Message& message) {
+ if (set_error_on_process_)
+ message.set_dispatch_error();
+ ++on_process_swap_message_count_;
+}
+
+// Test class which provides FrameTokenCallback() to be used as a closure when
+// enqueueing non-IPC callbacks. This only tracks if the callback was called.
+class TestNonIPCMessageEnqueuer {
+ public:
+ TestNonIPCMessageEnqueuer() {}
+ ~TestNonIPCMessageEnqueuer() {}
+
+ void FrameTokenCallback();
+
+ bool frame_token_callback_called() const {
+ return frame_token_callback_called_;
+ }
+
+ private:
+ bool frame_token_callback_called_ = false;
+ DISALLOW_COPY_AND_ASSIGN(TestNonIPCMessageEnqueuer);
+};
+
+void TestNonIPCMessageEnqueuer::FrameTokenCallback() {
+ frame_token_callback_called_ = true;
+}
+
+} // namespace
+
+class FrameTokenMessageQueueTest : public testing::Test {
+ public:
+ FrameTokenMessageQueueTest();
+ ~FrameTokenMessageQueueTest() override {}
+
+ TestFrameTokenMessageQueueClient* test_client() { return &test_client_; }
+ TestNonIPCMessageEnqueuer* test_non_ipc_enqueuer() {
+ return &test_non_ipc_enqueuer_;
+ }
+ FrameTokenMessageQueue* frame_token_message_queue() {
+ return &frame_token_message_queue_;
+ }
+
+ private:
+ TestFrameTokenMessageQueueClient test_client_;
+ TestNonIPCMessageEnqueuer test_non_ipc_enqueuer_;
+ FrameTokenMessageQueue frame_token_message_queue_;
+ DISALLOW_COPY_AND_ASSIGN(FrameTokenMessageQueueTest);
+};
+
+FrameTokenMessageQueueTest::FrameTokenMessageQueueTest()
+ : frame_token_message_queue_(&test_client_) {}
+
+// Tests that if a valid IPC::Message is enqueued, that it is processed when its
+// matching frame token arrives.
+TEST_F(FrameTokenMessageQueueTest, OnlyIPCMessageCorrectFrameToken) {
+ FrameTokenMessageQueue* queue = frame_token_message_queue();
+ TestFrameTokenMessageQueueClient* client = test_client();
+ ASSERT_EQ(0u, queue->size());
+
+ const uint32_t frame_token = 42;
+ IPC::Message msg(0, 1, IPC::Message::PRIORITY_NORMAL);
+ std::vector<IPC::Message> messages;
+ messages.push_back(msg);
+
+ // Adding to the queue with a new frame token should not cause processing.
+ queue->OnFrameSwapMessagesReceived(frame_token, std::move(messages));
+ EXPECT_EQ(1u, queue->size());
+ EXPECT_EQ(0, client->on_process_swap_message_count());
+
+ queue->DidProcessFrame(frame_token);
+ EXPECT_EQ(0u, queue->size());
+ EXPECT_FALSE(client->invalid_frame_token_called());
+ EXPECT_EQ(1, client->on_process_swap_message_count());
+ EXPECT_EQ(0, client->on_message_dispatch_error_count());
+}
+
+// Tests that if a valid IPC::Message is enqueued after its frame token has
+// arrived that it is processed immediately.
+TEST_F(FrameTokenMessageQueueTest, EnqueueAfterFrameTokenProcesses) {
+ FrameTokenMessageQueue* queue = frame_token_message_queue();
+ TestFrameTokenMessageQueueClient* client = test_client();
+ ASSERT_EQ(0u, queue->size());
+
+ const uint32_t frame_token = 42;
+ IPC::Message msg(0, 1, IPC::Message::PRIORITY_NORMAL);
+ std::vector<IPC::Message> messages;
+ messages.push_back(msg);
+
+ queue->DidProcessFrame(frame_token);
+ EXPECT_EQ(0u, queue->size());
+ EXPECT_FALSE(client->invalid_frame_token_called());
+ EXPECT_EQ(0, client->on_process_swap_message_count());
+ EXPECT_EQ(0, client->on_message_dispatch_error_count());
+
+ // Enqueuing after frame token arrival should immediately process.
+ queue->OnFrameSwapMessagesReceived(frame_token, std::move(messages));
+ EXPECT_EQ(0u, queue->size());
+ EXPECT_FALSE(client->invalid_frame_token_called());
+ EXPECT_EQ(1, client->on_process_swap_message_count());
+ EXPECT_EQ(0, client->on_message_dispatch_error_count());
+}
+
+// Tests that if a valid IPC::Message is enqueued and that subsequently a
+// non-IPC callback is enqueued, that both get called once the frame token
+// arrives.
+TEST_F(FrameTokenMessageQueueTest, EnqueueBothIPCMessageAndNonIPCCallback) {
+ FrameTokenMessageQueue* queue = frame_token_message_queue();
+ TestFrameTokenMessageQueueClient* client = test_client();
+ TestNonIPCMessageEnqueuer* enqueuer = test_non_ipc_enqueuer();
+ ASSERT_EQ(0u, queue->size());
+
+ const uint32_t frame_token = 42;
+ IPC::Message msg(0, 1, IPC::Message::PRIORITY_NORMAL);
+ std::vector<IPC::Message> messages;
+ messages.push_back(msg);
+
+ // Adding to the queue with a new frame token should not cause processing.
+ queue->OnFrameSwapMessagesReceived(frame_token, std::move(messages));
+ EXPECT_EQ(1u, queue->size());
+ EXPECT_EQ(0, client->on_process_swap_message_count());
+
+ queue->EnqueueOrRunFrameTokenCallback(
+ frame_token,
+ base::BindOnce(&TestNonIPCMessageEnqueuer::FrameTokenCallback,
+ base::Unretained(enqueuer)));
+ EXPECT_FALSE(enqueuer->frame_token_callback_called());
+ EXPECT_FALSE(client->invalid_frame_token_called());
+
+ queue->DidProcessFrame(frame_token);
+ EXPECT_EQ(0u, queue->size());
+ EXPECT_FALSE(client->invalid_frame_token_called());
+ EXPECT_EQ(1, client->on_process_swap_message_count());
+ EXPECT_EQ(0, client->on_message_dispatch_error_count());
+ EXPECT_TRUE(enqueuer->frame_token_callback_called());
+}
+
+// Tests that if a valid non-IPC callback is enqueued before an IPC::Message,
+// that both get called once the frame token arrives.
+TEST_F(FrameTokenMessageQueueTest, EnqueueNonIPCCallbackFirst) {
+ FrameTokenMessageQueue* queue = frame_token_message_queue();
+ TestFrameTokenMessageQueueClient* client = test_client();
+ TestNonIPCMessageEnqueuer* enqueuer = test_non_ipc_enqueuer();
+ ASSERT_EQ(0u, queue->size());
+
+ const uint32_t frame_token = 42;
+ IPC::Message msg(0, 1, IPC::Message::PRIORITY_NORMAL);
+ std::vector<IPC::Message> messages;
+ messages.push_back(msg);
+
+ queue->EnqueueOrRunFrameTokenCallback(
+ frame_token,
+ base::BindOnce(&TestNonIPCMessageEnqueuer::FrameTokenCallback,
+ base::Unretained(enqueuer)));
+ EXPECT_FALSE(enqueuer->frame_token_callback_called());
+ EXPECT_EQ(0, client->on_process_swap_message_count());
+
+ // We should be able to enqueue even though it is for the same frame token.
+ queue->OnFrameSwapMessagesReceived(frame_token, std::move(messages));
+ EXPECT_EQ(2u, queue->size());
+ EXPECT_EQ(0, client->on_process_swap_message_count());
+ EXPECT_FALSE(client->invalid_frame_token_called());
+
+ queue->DidProcessFrame(frame_token);
+ EXPECT_EQ(0u, queue->size());
+ EXPECT_FALSE(client->invalid_frame_token_called());
+ EXPECT_EQ(1, client->on_process_swap_message_count());
+ EXPECT_EQ(0, client->on_message_dispatch_error_count());
+ EXPECT_TRUE(enqueuer->frame_token_callback_called());
+}
+
+// Tests that if we only have a non-IPC callback enqueued that it is called once
+// the frame token arrive.
+TEST_F(FrameTokenMessageQueueTest, EnqueueOnlyNonIPC) {
+ FrameTokenMessageQueue* queue = frame_token_message_queue();
+ TestFrameTokenMessageQueueClient* client = test_client();
+ TestNonIPCMessageEnqueuer* enqueuer = test_non_ipc_enqueuer();
+ ASSERT_EQ(0u, queue->size());
+
+ const uint32_t frame_token = 42;
+ queue->EnqueueOrRunFrameTokenCallback(
+ frame_token,
+ base::BindOnce(&TestNonIPCMessageEnqueuer::FrameTokenCallback,
+ base::Unretained(enqueuer)));
+ EXPECT_FALSE(enqueuer->frame_token_callback_called());
+ EXPECT_EQ(0, client->on_process_swap_message_count());
+ EXPECT_EQ(1u, queue->size());
+
+ queue->DidProcessFrame(frame_token);
+ EXPECT_EQ(0u, queue->size());
+ EXPECT_FALSE(client->invalid_frame_token_called());
+ EXPECT_EQ(0, client->on_process_swap_message_count());
+ EXPECT_EQ(0, client->on_message_dispatch_error_count());
+ EXPECT_TRUE(enqueuer->frame_token_callback_called());
+}
+
+// Tests that if we have messages enqueued, and receive a frame token that is
+// larger, that we still process the messages.
+TEST_F(FrameTokenMessageQueueTest, MessagesWhereFrameTokenSkipped) {
+ FrameTokenMessageQueue* queue = frame_token_message_queue();
+ TestFrameTokenMessageQueueClient* client = test_client();
+ TestNonIPCMessageEnqueuer* enqueuer = test_non_ipc_enqueuer();
+ ASSERT_EQ(0u, queue->size());
+
+ const uint32_t frame_token = 42;
+ IPC::Message msg(0, 1, IPC::Message::PRIORITY_NORMAL);
+ std::vector<IPC::Message> messages;
+ messages.push_back(msg);
+
+ queue->EnqueueOrRunFrameTokenCallback(
+ frame_token,
+ base::BindOnce(&TestNonIPCMessageEnqueuer::FrameTokenCallback,
+ base::Unretained(enqueuer)));
+ EXPECT_FALSE(enqueuer->frame_token_callback_called());
+ EXPECT_EQ(0, client->on_process_swap_message_count());
+
+ // We should be able to enqueue even though it is for the same frame token.
+ queue->OnFrameSwapMessagesReceived(frame_token, std::move(messages));
+ EXPECT_EQ(2u, queue->size());
+ EXPECT_EQ(0, client->on_process_swap_message_count());
+ EXPECT_FALSE(client->invalid_frame_token_called());
+
+ const uint32_t larger_frame_token = 1337;
+ queue->DidProcessFrame(larger_frame_token);
+ EXPECT_EQ(0u, queue->size());
+ EXPECT_FALSE(client->invalid_frame_token_called());
+ EXPECT_EQ(1, client->on_process_swap_message_count());
+ EXPECT_EQ(0, client->on_message_dispatch_error_count());
+ EXPECT_TRUE(enqueuer->frame_token_callback_called());
+}
+
+// Verifies that if there are multiple IPC::Messages that they are all
+// processed.
+TEST_F(FrameTokenMessageQueueTest, MultipleIPCMessages) {
+ FrameTokenMessageQueue* queue = frame_token_message_queue();
+ TestFrameTokenMessageQueueClient* client = test_client();
+ ASSERT_EQ(0u, queue->size());
+
+ const uint32_t frame_token = 42;
+ IPC::Message msg1(0, 1, IPC::Message::PRIORITY_NORMAL);
+ IPC::Message msg2(1, 2, IPC::Message::PRIORITY_LOW);
+ std::vector<IPC::Message> messages;
+ messages.push_back(msg1);
+ messages.push_back(msg2);
+
+ // Adding to the queue with a new frame token should not cause processing.
+ queue->OnFrameSwapMessagesReceived(frame_token, std::move(messages));
+ // All IPCs are enqueued as one.
+ EXPECT_EQ(1u, queue->size());
+ EXPECT_EQ(0, client->on_process_swap_message_count());
+
+ queue->DidProcessFrame(frame_token);
+ EXPECT_EQ(0u, queue->size());
+ EXPECT_FALSE(client->invalid_frame_token_called());
+ EXPECT_EQ(2, client->on_process_swap_message_count());
+ EXPECT_EQ(0, client->on_message_dispatch_error_count());
+}
+
+// Verifies that if there are multiple non-IPC messages enqueued that they are
+// all called.
+TEST_F(FrameTokenMessageQueueTest, MultipleNonIPCMessages) {
+ FrameTokenMessageQueue* queue = frame_token_message_queue();
+ TestFrameTokenMessageQueueClient* client = test_client();
+ TestNonIPCMessageEnqueuer* enqueuer = test_non_ipc_enqueuer();
+ ASSERT_EQ(0u, queue->size());
+
+ const uint32_t frame_token = 42;
+ queue->EnqueueOrRunFrameTokenCallback(
+ frame_token,
+ base::BindOnce(&TestNonIPCMessageEnqueuer::FrameTokenCallback,
+ base::Unretained(enqueuer)));
+ EXPECT_FALSE(enqueuer->frame_token_callback_called());
+ EXPECT_EQ(1u, queue->size());
+
+ // Create a second callback
+ TestNonIPCMessageEnqueuer second_enqueuer;
+ queue->EnqueueOrRunFrameTokenCallback(
+ frame_token,
+ base::BindOnce(&TestNonIPCMessageEnqueuer::FrameTokenCallback,
+ base::Unretained(&second_enqueuer)));
+ EXPECT_FALSE(second_enqueuer.frame_token_callback_called());
+ EXPECT_EQ(2u, queue->size());
+
+ queue->DidProcessFrame(frame_token);
+ EXPECT_EQ(0u, queue->size());
+ EXPECT_FALSE(client->invalid_frame_token_called());
+ EXPECT_TRUE(enqueuer->frame_token_callback_called());
+ EXPECT_TRUE(second_enqueuer.frame_token_callback_called());
+}
+
+// Tests that if a non-IPC callback is enqueued, after its frame token as been
+// received, that it is immediately processed.
+TEST_F(FrameTokenMessageQueueTest, EnqueuedAfterFrameTokenImmediatelyRuns) {
+ FrameTokenMessageQueue* queue = frame_token_message_queue();
+ TestFrameTokenMessageQueueClient* client = test_client();
+ TestNonIPCMessageEnqueuer* enqueuer = test_non_ipc_enqueuer();
+ ASSERT_EQ(0u, queue->size());
+
+ const uint32_t frame_token = 42;
+ queue->DidProcessFrame(frame_token);
+ EXPECT_EQ(0u, queue->size());
+ EXPECT_FALSE(client->invalid_frame_token_called());
+ EXPECT_FALSE(enqueuer->frame_token_callback_called());
+
+ queue->EnqueueOrRunFrameTokenCallback(
+ frame_token,
+ base::BindOnce(&TestNonIPCMessageEnqueuer::FrameTokenCallback,
+ base::Unretained(enqueuer)));
+ EXPECT_EQ(0u, queue->size());
+ EXPECT_FALSE(client->invalid_frame_token_called());
+ EXPECT_TRUE(enqueuer->frame_token_callback_called());
+}
+
+// Tests that if IPC::Messages are enqueued for different frame tokens, that
+// we only process the messages associated with the arriving token, and keep the
+// others enqueued.
+TEST_F(FrameTokenMessageQueueTest, DifferentFrameTokensEnqueuedIPC) {
+ FrameTokenMessageQueue* queue = frame_token_message_queue();
+ TestFrameTokenMessageQueueClient* client = test_client();
+ ASSERT_EQ(0u, queue->size());
+
+ const uint32_t frame_token_1 = 42;
+ IPC::Message msg1(0, 1, IPC::Message::PRIORITY_NORMAL);
+ std::vector<IPC::Message> messages_1;
+ messages_1.push_back(msg1);
+
+ queue->OnFrameSwapMessagesReceived(frame_token_1, std::move(messages_1));
+ EXPECT_EQ(1u, queue->size());
+ EXPECT_EQ(0, client->on_process_swap_message_count());
+
+ const uint32_t frame_token_2 = 1337;
+ IPC::Message msg2(1, 2, IPC::Message::PRIORITY_LOW);
+ std::vector<IPC::Message> messages_2;
+ messages_2.push_back(msg2);
+
+ queue->OnFrameSwapMessagesReceived(frame_token_2, std::move(messages_2));
+ // With no frame token yet the second set of IPC::Messages should be enqueud
+ // separately.
+ EXPECT_EQ(2u, queue->size());
+ EXPECT_EQ(0, client->on_process_swap_message_count());
+
+ // We should only process the first IPC::Message.
+ queue->DidProcessFrame(frame_token_1);
+ EXPECT_EQ(1u, queue->size());
+ EXPECT_FALSE(client->invalid_frame_token_called());
+ EXPECT_EQ(1, client->on_process_swap_message_count());
+ EXPECT_EQ(0, client->on_message_dispatch_error_count());
+
+ // Clear the counts from the first token.
+ client->Reset();
+
+ // The second IPC::Message should be processed.
+ queue->DidProcessFrame(frame_token_2);
+ EXPECT_EQ(0u, queue->size());
+ EXPECT_FALSE(client->invalid_frame_token_called());
+ EXPECT_EQ(1, client->on_process_swap_message_count());
+ EXPECT_EQ(0, client->on_message_dispatch_error_count());
+}
+
+// Test that if non-IPC callbacks are enqueued for different frame tokens, that
+// we only process the messages associated with the arriving token, and keep the
+// others enqueued.
+TEST_F(FrameTokenMessageQueueTest, DifferentFrameTokensEnqueuedNonIPC) {
+ FrameTokenMessageQueue* queue = frame_token_message_queue();
+ TestFrameTokenMessageQueueClient* client = test_client();
+ TestNonIPCMessageEnqueuer* enqueuer = test_non_ipc_enqueuer();
+ ASSERT_EQ(0u, queue->size());
+
+ const uint32_t frame_token_1 = 42;
+ queue->EnqueueOrRunFrameTokenCallback(
+ frame_token_1,
+ base::BindOnce(&TestNonIPCMessageEnqueuer::FrameTokenCallback,
+ base::Unretained(enqueuer)));
+ EXPECT_FALSE(enqueuer->frame_token_callback_called());
+ EXPECT_EQ(1u, queue->size());
+
+ // Create a second callback
+ const uint32_t frame_token_2 = 1337;
+ TestNonIPCMessageEnqueuer second_enqueuer;
+ queue->EnqueueOrRunFrameTokenCallback(
+ frame_token_2,
+ base::BindOnce(&TestNonIPCMessageEnqueuer::FrameTokenCallback,
+ base::Unretained(&second_enqueuer)));
+ EXPECT_FALSE(second_enqueuer.frame_token_callback_called());
+ EXPECT_EQ(2u, queue->size());
+
+ queue->DidProcessFrame(frame_token_1);
+ EXPECT_EQ(1u, queue->size());
+ EXPECT_FALSE(client->invalid_frame_token_called());
+ EXPECT_TRUE(enqueuer->frame_token_callback_called());
+ EXPECT_FALSE(second_enqueuer.frame_token_callback_called());
+
+ queue->DidProcessFrame(frame_token_2);
+ EXPECT_TRUE(second_enqueuer.frame_token_callback_called());
+}
+
+// An empty frame token is considered invalid, so this tests that attempting to
+// enqueue for that is rejected.
+TEST_F(FrameTokenMessageQueueTest, EmptyTokenForIPCMessageIsRejected) {
+ FrameTokenMessageQueue* queue = frame_token_message_queue();
+ TestFrameTokenMessageQueueClient* client = test_client();
+ ASSERT_EQ(0u, queue->size());
+
+ const uint32_t invalid_frame_token = 0;
+ IPC::Message msg(0, 1, IPC::Message::PRIORITY_NORMAL);
+ std::vector<IPC::Message> messages;
+ messages.push_back(msg);
+
+ // Adding to the queue with a new frame token should not cause processing.
+ queue->OnFrameSwapMessagesReceived(invalid_frame_token, std::move(messages));
+ EXPECT_EQ(0u, queue->size());
+ EXPECT_TRUE(client->invalid_frame_token_called());
+ EXPECT_EQ(invalid_frame_token, client->invalid_frame_token());
+ EXPECT_EQ(0, client->on_process_swap_message_count());
+}
+
+// Tests that when adding an IPC::Message for an earlier frame token, that it is
+// enqueued.
+TEST_F(FrameTokenMessageQueueTest, EarlierTokenForIPCMessageIsNotRejected) {
+ FrameTokenMessageQueue* queue = frame_token_message_queue();
+ TestFrameTokenMessageQueueClient* client = test_client();
+ ASSERT_EQ(0u, queue->size());
+
+ const uint32_t valid_frame_token = 42;
+ IPC::Message msg1(0, 1, IPC::Message::PRIORITY_NORMAL);
+ std::vector<IPC::Message> messages_1;
+ messages_1.push_back(msg1);
+
+ // Adding to the queue with a new frame token should not cause processing.
+ queue->OnFrameSwapMessagesReceived(valid_frame_token, std::move(messages_1));
+ EXPECT_EQ(1u, queue->size());
+ EXPECT_EQ(0, client->on_process_swap_message_count());
+
+ const uint32_t earlier_frame_token = 1;
+ IPC::Message msg2(1, 2, IPC::Message::PRIORITY_NORMAL);
+ std::vector<IPC::Message> messages_2;
+ messages_2.push_back(msg1);
+
+ // Adding an earlier frame token should be enqueued.
+ queue->OnFrameSwapMessagesReceived(earlier_frame_token,
+ std::move(messages_2));
+ EXPECT_EQ(2u, queue->size());
+ EXPECT_FALSE(client->invalid_frame_token_called());
+ EXPECT_EQ(0, client->on_process_swap_message_count());
+}
+
+// Tests that if DidProcessFrame is called with an invalid token, that it is
+// rejected, and that no callbacks are processed.
+TEST_F(FrameTokenMessageQueueTest, InvalidDidProcessFrameTokenNotProcessed) {
+ FrameTokenMessageQueue* queue = frame_token_message_queue();
+ TestFrameTokenMessageQueueClient* client = test_client();
+ TestNonIPCMessageEnqueuer* enqueuer = test_non_ipc_enqueuer();
+ ASSERT_EQ(0u, queue->size());
+
+ const uint32_t frame_token = 42;
+ IPC::Message msg(0, 1, IPC::Message::PRIORITY_NORMAL);
+ std::vector<IPC::Message> messages;
+ messages.push_back(msg);
+
+ queue->OnFrameSwapMessagesReceived(frame_token, std::move(messages));
+ EXPECT_EQ(1u, queue->size());
+ EXPECT_EQ(0, client->on_process_swap_message_count());
+
+ queue->EnqueueOrRunFrameTokenCallback(
+ frame_token,
+ base::BindOnce(&TestNonIPCMessageEnqueuer::FrameTokenCallback,
+ base::Unretained(enqueuer)));
+ EXPECT_FALSE(enqueuer->frame_token_callback_called());
+ EXPECT_FALSE(client->invalid_frame_token_called());
+
+ // Empty token should be invalid even with no process frames processed.
+ const uint32_t invalid_frame_token = 0;
+ queue->DidProcessFrame(invalid_frame_token);
+ EXPECT_EQ(2u, queue->size());
+ EXPECT_TRUE(client->invalid_frame_token_called());
+ EXPECT_EQ(invalid_frame_token, client->invalid_frame_token());
+ EXPECT_EQ(0, client->on_process_swap_message_count());
+ EXPECT_EQ(0, client->on_message_dispatch_error_count());
+ EXPECT_FALSE(enqueuer->frame_token_callback_called());
+}
+
+// Test that if DidProcessFrame is called with an earlier frame token, that it
+// is rejected, and that no callbacks are processed.
+TEST_F(FrameTokenMessageQueueTest, EarlierTokenForDidProcessFrameRejected) {
+ FrameTokenMessageQueue* queue = frame_token_message_queue();
+ TestFrameTokenMessageQueueClient* client = test_client();
+ TestNonIPCMessageEnqueuer* enqueuer = test_non_ipc_enqueuer();
+ ASSERT_EQ(0u, queue->size());
+
+ // Settings a low value frame token will not block enqueueing.
+ const uint32_t earlier_frame_token = 42;
+ queue->DidProcessFrame(earlier_frame_token);
+
+ const uint32_t frame_token = 1337;
+ IPC::Message msg(0, 1, IPC::Message::PRIORITY_NORMAL);
+ std::vector<IPC::Message> messages;
+ messages.push_back(msg);
+
+ queue->OnFrameSwapMessagesReceived(frame_token, std::move(messages));
+ EXPECT_EQ(1u, queue->size());
+ EXPECT_EQ(0, client->on_process_swap_message_count());
+
+ queue->EnqueueOrRunFrameTokenCallback(
+ frame_token,
+ base::BindOnce(&TestNonIPCMessageEnqueuer::FrameTokenCallback,
+ base::Unretained(enqueuer)));
+ EXPECT_FALSE(enqueuer->frame_token_callback_called());
+ EXPECT_FALSE(client->invalid_frame_token_called());
+
+ // Using a frame token that is earlier than the last received should be
+ // rejected.
+ const uint32_t invalid_frame_token = earlier_frame_token - 1;
+ queue->DidProcessFrame(invalid_frame_token);
+ EXPECT_EQ(2u, queue->size());
+ EXPECT_TRUE(client->invalid_frame_token_called());
+ EXPECT_EQ(invalid_frame_token, client->invalid_frame_token());
+ EXPECT_EQ(0, client->on_process_swap_message_count());
+ EXPECT_EQ(0, client->on_message_dispatch_error_count());
+ EXPECT_FALSE(enqueuer->frame_token_callback_called());
+}
+
+// Tests that if an IPC::Message has a dispatch error that the client is
+// notified.
+TEST_F(FrameTokenMessageQueueTest, DispatchError) {
+ FrameTokenMessageQueue* queue = frame_token_message_queue();
+ TestFrameTokenMessageQueueClient* client = test_client();
+ ASSERT_EQ(0u, queue->size());
+
+ const uint32_t frame_token = 42;
+ IPC::Message msg(0, 1, IPC::Message::PRIORITY_NORMAL);
+ std::vector<IPC::Message> messages;
+ messages.push_back(msg);
+
+ queue->OnFrameSwapMessagesReceived(frame_token, std::move(messages));
+ EXPECT_EQ(1u, queue->size());
+ EXPECT_EQ(0, client->on_process_swap_message_count());
+
+ // Dispatch error should be notified during processing.
+ client->SetErrorOnMessageProcess();
+ queue->DidProcessFrame(frame_token);
+ EXPECT_EQ(0u, queue->size());
+ EXPECT_FALSE(client->invalid_frame_token_called());
+ EXPECT_EQ(1, client->on_process_swap_message_count());
+ EXPECT_EQ(1, client->on_message_dispatch_error_count());
+}
+
+// Tests that if we have already enqueued a callback for a frame token, that if
+// a request for an earlier frame token arrives, that it is still enqueued. Then
+// once the large frame token arrives, both are processed.
+TEST_F(FrameTokenMessageQueueTest, OutOfOrderFrameTokensEnqueue) {
+ FrameTokenMessageQueue* queue = frame_token_message_queue();
+ TestFrameTokenMessageQueueClient* client = test_client();
+ TestNonIPCMessageEnqueuer* enqueuer = test_non_ipc_enqueuer();
+ ASSERT_EQ(0u, queue->size());
+
+ const uint32_t larger_frame_token = 1337;
+ queue->EnqueueOrRunFrameTokenCallback(
+ larger_frame_token,
+ base::BindOnce(&TestNonIPCMessageEnqueuer::FrameTokenCallback,
+ base::Unretained(enqueuer)));
+ EXPECT_EQ(1u, queue->size());
+ EXPECT_FALSE(enqueuer->frame_token_callback_called());
+ EXPECT_FALSE(client->invalid_frame_token_called());
+
+ const uint32_t smaller_frame_token = 42;
+ IPC::Message msg(0, 1, IPC::Message::PRIORITY_NORMAL);
+ std::vector<IPC::Message> messages;
+ messages.push_back(msg);
+
+ // Enqueuing for a smaller token, which has not yet arrived, should still
+ // enqueue.
+ queue->OnFrameSwapMessagesReceived(smaller_frame_token, std::move(messages));
+ EXPECT_EQ(2u, queue->size());
+ EXPECT_EQ(0, client->on_process_swap_message_count());
+
+ // Process both with the larger frame token arriving.
+ queue->DidProcessFrame(larger_frame_token);
+ EXPECT_EQ(0u, queue->size());
+ EXPECT_FALSE(client->invalid_frame_token_called());
+ EXPECT_EQ(1, client->on_process_swap_message_count());
+ EXPECT_EQ(0, client->on_message_dispatch_error_count());
+ EXPECT_TRUE(enqueuer->frame_token_callback_called());
+}
+
+} // namespace content
diff --git a/chromium/content/browser/renderer_host/input/non_blocking_event_browsertest.cc b/chromium/content/browser/renderer_host/input/compositor_event_ack_browsertest.cc
index 466a50140f5..d8f9d3d57b7 100644
--- a/chromium/content/browser/renderer_host/input/non_blocking_event_browsertest.cc
+++ b/chromium/content/browser/renderer_host/input/compositor_event_ack_browsertest.cc
@@ -25,7 +25,8 @@
#include "content/public/test/content_browser_test_utils.h"
#include "content/public/test/test_utils.h"
#include "content/shell/browser/shell.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
+#include "ui/events/base_event_utils.h"
#include "ui/events/event_switches.h"
#include "ui/latency/latency_info.h"
@@ -38,7 +39,10 @@ namespace {
// tests.
const int kWebsiteHeight = 10000;
-const char kNonBlockingEventDataURL[] =
+// The event listeners will block the renderer's main thread for both wheel and
+// touchstart. This will lead to the compositor impl thread to perform
+// scrolling.
+const char kCompositorEventAckDataURL[] =
"data:text/html;charset=utf-8,"
"<!DOCTYPE html>"
"<meta name='viewport' content='width=device-width'/>"
@@ -57,6 +61,8 @@ const char kNonBlockingEventDataURL[] =
" document.title='ready';"
"</script>";
+// The event listeners will block the renderer's main thread for both
+// touchstart and touchend.
const char kPassiveTouchStartBlockingTouchEndDataURL[] =
"data:text/html;charset=utf-8,"
"<!DOCTYPE html>"
@@ -75,14 +81,36 @@ const char kPassiveTouchStartBlockingTouchEndDataURL[] =
" document.title='ready';"
"</script>";
+// The event listeners will block the renderer's main thread for touchstart.
+const char kBlockingTouchStartDataURL[] =
+ "data:text/html;charset=utf-8,"
+ "<!DOCTYPE html>"
+ "<meta name='viewport' content='width=device-width'/>"
+ "<style>"
+ "html, body {"
+ " margin: 0;"
+ "}"
+ ".spacer { height: 10000px; }"
+ "</style>"
+ "<div class=spacer></div>"
+ "<script>"
+ " document.addEventListener('touchstart', function(e) { while(true) {} }, "
+ "{'passive': false});"
+ " document.title='ready';"
+ "</script>";
+
} // namespace
namespace content {
-class NonBlockingEventBrowserTest : public ContentBrowserTest {
+// This test will used event listeners which block the renderer's main thread.
+// This test verifies that the compositor sends back an event ack that is not
+// blocked by the main thread. Then that subsequently the compositor will
+// perform scrolling from the impl thread.
+class CompositorEventAckBrowserTest : public ContentBrowserTest {
public:
- NonBlockingEventBrowserTest() {}
- ~NonBlockingEventBrowserTest() override {}
+ CompositorEventAckBrowserTest() {}
+ ~CompositorEventAckBrowserTest() override {}
RenderWidgetHostImpl* GetWidgetHost() {
return RenderWidgetHostImpl::From(
@@ -132,19 +160,26 @@ class NonBlockingEventBrowserTest : public ContentBrowserTest {
auto input_msg_watcher = std::make_unique<InputMsgWatcher>(
GetWidgetHost(), blink::WebInputEvent::kMouseWheel);
+ // This event never completes its processing. As kCompositorEventAckDataURL
+ // will block the renderer's main thread once it is received.
blink::WebMouseWheelEvent wheel_event =
SyntheticWebMouseWheelEventBuilder::Build(10, 10, 0, -53, 0, true);
wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan;
GetWidgetHost()->ForwardWheelEvent(wheel_event);
- // Runs until we get the InputMsgAck callback
+ // The compositor should send the event ack, and not be blocked by the event
+ // above. The event watcher runs until we get the InputMsgAck callback
EXPECT_EQ(INPUT_EVENT_ACK_STATE_SET_NON_BLOCKING,
input_msg_watcher->WaitForAck());
// Expect that the compositor scrolled at least one pixel while the
// main thread was in a busy loop.
- while (observer.LastRenderFrameMetadata().root_scroll_offset.y() <= 0)
+ gfx::Vector2dF default_scroll_offset;
+ while (observer.LastRenderFrameMetadata()
+ .root_scroll_offset.value_or(default_scroll_offset)
+ .y() <= 0) {
observer.WaitForMetadataChange();
+ }
}
void DoTouchScroll() {
@@ -167,21 +202,25 @@ class NonBlockingEventBrowserTest : public ContentBrowserTest {
GetWidgetHost()->QueueSyntheticGesture(
std::move(gesture),
base::BindOnce(
- &NonBlockingEventBrowserTest::OnSyntheticGestureCompleted,
+ &CompositorEventAckBrowserTest::OnSyntheticGestureCompleted,
base::Unretained(this)));
// Expect that the compositor scrolled at least one pixel while the
// main thread was in a busy loop.
- while (observer.LastRenderFrameMetadata().root_scroll_offset.y() <= 0)
+ gfx::Vector2dF default_scroll_offset;
+ while (observer.LastRenderFrameMetadata()
+ .root_scroll_offset.value_or(default_scroll_offset)
+ .y() <= 0) {
observer.WaitForMetadataChange();
+ }
}
private:
- DISALLOW_COPY_AND_ASSIGN(NonBlockingEventBrowserTest);
+ DISALLOW_COPY_AND_ASSIGN(CompositorEventAckBrowserTest);
};
-IN_PROC_BROWSER_TEST_F(NonBlockingEventBrowserTest, MouseWheel) {
- LoadURL(kNonBlockingEventDataURL);
+IN_PROC_BROWSER_TEST_F(CompositorEventAckBrowserTest, MouseWheel) {
+ LoadURL(kCompositorEventAckDataURL);
DoWheelScroll();
}
@@ -191,20 +230,75 @@ IN_PROC_BROWSER_TEST_F(NonBlockingEventBrowserTest, MouseWheel) {
#else
#define MAYBE_TouchStart TouchStart
#endif
-IN_PROC_BROWSER_TEST_F(NonBlockingEventBrowserTest, MAYBE_TouchStart) {
- LoadURL(kNonBlockingEventDataURL);
+IN_PROC_BROWSER_TEST_F(CompositorEventAckBrowserTest, MAYBE_TouchStart) {
+ LoadURL(kCompositorEventAckDataURL);
DoTouchScroll();
}
// Disabled on MacOS because it doesn't support touch input.
#if defined(OS_MACOSX)
+#define MAYBE_TouchStartDuringFling DISABLED_TouchStartDuringFling
+#else
+#define MAYBE_TouchStartDuringFling TouchStartDuringFling
+#endif
+IN_PROC_BROWSER_TEST_F(CompositorEventAckBrowserTest,
+ MAYBE_TouchStartDuringFling) {
+ LoadURL(kBlockingTouchStartDataURL);
+
+ // Send GSB to start scrolling sequence.
+ blink::WebGestureEvent gesture_scroll_begin(
+ blink::WebGestureEvent::kGestureScrollBegin,
+ blink::WebInputEvent::kNoModifiers,
+ ui::EventTimeStampToSeconds(ui::EventTimeForNow()));
+ gesture_scroll_begin.SetSourceDevice(blink::kWebGestureDeviceTouchscreen);
+ gesture_scroll_begin.data.scroll_begin.delta_hint_units =
+ blink::WebGestureEvent::ScrollUnits::kPrecisePixels;
+ gesture_scroll_begin.data.scroll_begin.delta_x_hint = 0.f;
+ gesture_scroll_begin.data.scroll_begin.delta_y_hint = -5.f;
+ GetWidgetHost()->ForwardGestureEvent(gesture_scroll_begin);
+
+ // Send a GFS and wait for the page to scroll making sure that fling progress
+ // has started.
+ blink::WebGestureEvent gesture_fling_start(
+ blink::WebGestureEvent::kGestureFlingStart,
+ blink::WebInputEvent::kNoModifiers,
+ ui::EventTimeStampToSeconds(ui::EventTimeForNow()));
+ gesture_fling_start.SetSourceDevice(blink::kWebGestureDeviceTouchscreen);
+ gesture_fling_start.data.fling_start.velocity_x = 0.f;
+ gesture_fling_start.data.fling_start.velocity_y = -2000.f;
+ GetWidgetHost()->ForwardGestureEvent(gesture_fling_start);
+ RenderFrameSubmissionObserver observer(
+ GetWidgetHost()->render_frame_metadata_provider());
+ gfx::Vector2dF default_scroll_offset;
+ while (observer.LastRenderFrameMetadata()
+ .root_scroll_offset.value_or(default_scroll_offset)
+ .y() <= 0)
+ observer.WaitForMetadataChange();
+
+ // Send a touch start event and wait for its ack. The touch start must be
+ // uncancelable since there is an on-going fling with touchscreen source. The
+ // test will timeout if the touch start event is cancelable since there is a
+ // busy loop in the blocking touch start event listener.
+ InputEventAckWaiter touch_start_ack_observer(GetWidgetHost(),
+ WebInputEvent::kTouchStart);
+ SyntheticWebTouchEvent touch_event;
+ touch_event.PressPoint(50, 50);
+ touch_event.SetTimeStampSeconds(
+ ui::EventTimeStampToSeconds(ui::EventTimeForNow()));
+ GetWidgetHost()->ForwardTouchEventWithLatencyInfo(touch_event,
+ ui::LatencyInfo());
+ touch_start_ack_observer.Wait();
+}
+
+// Disabled on MacOS because it doesn't support touch input.
+#if defined(OS_MACOSX)
#define MAYBE_PassiveTouchStartBlockingTouchEnd \
DISABLED_PassiveTouchStartBlockingTouchEnd
#else
#define MAYBE_PassiveTouchStartBlockingTouchEnd \
PassiveTouchStartBlockingTouchEnd
#endif
-IN_PROC_BROWSER_TEST_F(NonBlockingEventBrowserTest,
+IN_PROC_BROWSER_TEST_F(CompositorEventAckBrowserTest,
MAYBE_PassiveTouchStartBlockingTouchEnd) {
LoadURL(kPassiveTouchStartBlockingTouchEndDataURL);
DoTouchScroll();
diff --git a/chromium/content/browser/renderer_host/input/fling_browsertest.cc b/chromium/content/browser/renderer_host/input/fling_browsertest.cc
new file mode 100644
index 00000000000..00d86d6ccff
--- /dev/null
+++ b/chromium/content/browser/renderer_host/input/fling_browsertest.cc
@@ -0,0 +1,162 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "build/build_config.h"
+#include "content/browser/web_contents/web_contents_impl.h"
+#include "content/public/test/browser_test_utils.h"
+#include "content/public/test/content_browser_test.h"
+#include "content/public/test/content_browser_test_utils.h"
+#include "content/shell/browser/shell.h"
+#include "third_party/blink/public/platform/web_input_event.h"
+#include "ui/events/base_event_utils.h"
+
+using blink::WebInputEvent;
+
+namespace {
+
+const std::string kBrowserFlingDataURL = R"HTML(
+ <!DOCTYPE html>
+ <meta name='viewport' content='width=device-width'/>
+ <style>
+ html, body {
+ margin: 0;
+ }
+ .spacer { height: 10000px; }
+ </style>
+ <div class=spacer></div>
+ <script>
+ document.title='ready';
+ </script>)HTML";
+} // namespace
+
+namespace content {
+
+class BrowserSideFlingBrowserTest : public ContentBrowserTest {
+ public:
+ BrowserSideFlingBrowserTest() {}
+ ~BrowserSideFlingBrowserTest() override {}
+
+ void SetUpCommandLine(base::CommandLine* command_line) override {
+ command_line->AppendSwitchASCII("--enable-blink-features",
+ "MiddleClickAutoscroll");
+ }
+
+ protected:
+ RenderWidgetHostImpl* GetWidgetHost() {
+ return RenderWidgetHostImpl::From(
+ shell()->web_contents()->GetRenderViewHost()->GetWidget());
+ }
+
+ void LoadURL(const std::string& page_data) {
+ const GURL data_url("data:text/html," + page_data);
+ NavigateToURL(shell(), data_url);
+
+ RenderWidgetHostImpl* host = GetWidgetHost();
+ host->GetView()->SetSize(gfx::Size(400, 400));
+
+ base::string16 ready_title(base::ASCIIToUTF16("ready"));
+ TitleWatcher watcher(shell()->web_contents(), ready_title);
+ ignore_result(watcher.WaitAndGetTitle());
+
+ MainThreadFrameObserver main_thread_sync(host);
+ main_thread_sync.Wait();
+ }
+
+ void SimulateMiddleClick(int x, int y, int modifiers) {
+ // Simulate and send middle click mouse down.
+ blink::WebMouseEvent down_event = SyntheticWebMouseEventBuilder::Build(
+ blink::WebInputEvent::kMouseDown, x, y, modifiers);
+ down_event.button = blink::WebMouseEvent::Button::kMiddle;
+ down_event.SetTimeStampSeconds(
+ ui::EventTimeStampToSeconds(ui::EventTimeForNow()));
+ down_event.SetPositionInScreen(x, y);
+ GetWidgetHost()->ForwardMouseEvent(down_event);
+
+ // Simulate and send middle click mouse up.
+ blink::WebMouseEvent up_event = SyntheticWebMouseEventBuilder::Build(
+ blink::WebInputEvent::kMouseUp, x, y, modifiers);
+ up_event.button = blink::WebMouseEvent::Button::kMiddle;
+ up_event.SetTimeStampSeconds(
+ ui::EventTimeStampToSeconds(ui::EventTimeForNow()));
+ up_event.SetPositionInScreen(x, y);
+ GetWidgetHost()->ForwardMouseEvent(up_event);
+ }
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(BrowserSideFlingBrowserTest);
+};
+
+// TODO(sahel): This test is flaking on OS_CHROMEOS https://crbug.com/838769
+#if defined(OS_ANDROID) || defined(OS_CHROMEOS)
+#define MAYBE_AutoscrollFling DISABLED_AutoscrollFling
+#else
+#define MAYBE_AutoscrollFling AutoscrollFling
+#endif
+IN_PROC_BROWSER_TEST_F(BrowserSideFlingBrowserTest, MAYBE_AutoscrollFling) {
+ LoadURL(kBrowserFlingDataURL);
+
+ // Start autoscroll with middle click.
+ auto input_msg_watcher = std::make_unique<InputMsgWatcher>(
+ GetWidgetHost(), blink::WebInputEvent::kGestureScrollBegin);
+ SimulateMiddleClick(10, 10, blink::WebInputEvent::kNoModifiers);
+ input_msg_watcher->WaitForAck();
+
+ // The page should start scrolling with mouse move.
+ RenderFrameSubmissionObserver observer(
+ GetWidgetHost()->render_frame_metadata_provider());
+ blink::WebMouseEvent move_event = SyntheticWebMouseEventBuilder::Build(
+ blink::WebInputEvent::kMouseMove, 30, 30,
+ blink::WebInputEvent::kNoModifiers);
+ move_event.SetTimeStampSeconds(
+ ui::EventTimeStampToSeconds(ui::EventTimeForNow()));
+ move_event.SetPositionInScreen(30, 30);
+ GetWidgetHost()->ForwardMouseEvent(move_event);
+ gfx::Vector2dF default_scroll_offset;
+ while (observer.LastRenderFrameMetadata()
+ .root_scroll_offset.value_or(default_scroll_offset)
+ .y() <= 0) {
+ observer.WaitForMetadataChange();
+ }
+}
+
+#if !defined(OS_ANDROID)
+#define MAYBE_WheelScrollingWorksAfterAutoscrollCancel \
+ WheelScrollingWorksAfterAutoscrollCancel
+#else
+#define MAYBE_WheelScrollingWorksAfterAutoscrollCancel \
+ DISABLED_WheelScrollingWorksAfterAutoscrollCancel
+#endif
+// Checks that wheel scrolling works after autoscroll cancelation.
+IN_PROC_BROWSER_TEST_F(BrowserSideFlingBrowserTest,
+ MAYBE_WheelScrollingWorksAfterAutoscrollCancel) {
+ LoadURL(kBrowserFlingDataURL);
+
+ // Start autoscroll with middle click.
+ auto input_msg_watcher = std::make_unique<InputMsgWatcher>(
+ GetWidgetHost(), blink::WebInputEvent::kGestureScrollBegin);
+ SimulateMiddleClick(10, 10, blink::WebInputEvent::kNoModifiers);
+ input_msg_watcher->WaitForAck();
+
+ // Without moving the mouse cancel the autoscroll fling with another click.
+ input_msg_watcher = std::make_unique<InputMsgWatcher>(
+ GetWidgetHost(), blink::WebInputEvent::kGestureScrollEnd);
+ SimulateMiddleClick(10, 10, blink::WebInputEvent::kNoModifiers);
+ input_msg_watcher->WaitForAck();
+
+ // The mouse wheel scrolling must work after autoscroll cancellation.
+ RenderFrameSubmissionObserver observer(
+ GetWidgetHost()->render_frame_metadata_provider());
+ blink::WebMouseWheelEvent wheel_event =
+ SyntheticWebMouseWheelEventBuilder::Build(10, 10, 0, -53, 0, true);
+ wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan;
+ GetWidgetHost()->ForwardWheelEvent(wheel_event);
+ gfx::Vector2dF default_scroll_offset;
+ while (observer.LastRenderFrameMetadata()
+ .root_scroll_offset.value_or(default_scroll_offset)
+ .y() <= 0) {
+ observer.WaitForMetadataChange();
+ }
+}
+
+} // namespace content \ No newline at end of file
diff --git a/chromium/content/browser/renderer_host/input/fling_controller.cc b/chromium/content/browser/renderer_host/input/fling_controller.cc
index 6670aad686e..e09036a18b7 100644
--- a/chromium/content/browser/renderer_host/input/fling_controller.cc
+++ b/chromium/content/browser/renderer_host/input/fling_controller.cc
@@ -59,8 +59,7 @@ bool FlingController::ShouldForwardForGFCFiltering(
if (fling_in_progress_)
return !fling_booster_->fling_cancellation_is_deferred();
- // Touchpad fling with wheel scroll latching disabled, touchscreen, and
- // auto-scroll flings are still handled by renderer.
+ // Auto-scroll flings are still handled by renderer.
return !gesture_event_queue_->ShouldDiscardFlingCancelEvent(gesture_event);
}
@@ -68,10 +67,10 @@ bool FlingController::ShouldForwardForTapSuppression(
const GestureEventWithLatencyInfo& gesture_event) {
switch (gesture_event.event.GetType()) {
case WebInputEvent::kGestureFlingCancel:
- if (gesture_event.event.source_device ==
+ if (gesture_event.event.SourceDevice() ==
blink::kWebGestureDeviceTouchscreen) {
touchscreen_tap_suppression_controller_.GestureFlingCancel();
- } else if (gesture_event.event.source_device ==
+ } else if (gesture_event.event.SourceDevice() ==
blink::kWebGestureDeviceTouchpad) {
touchpad_tap_suppression_controller_.GestureFlingCancel();
}
@@ -85,7 +84,7 @@ bool FlingController::ShouldForwardForTapSuppression(
case WebInputEvent::kGestureLongPress:
case WebInputEvent::kGestureLongTap:
case WebInputEvent::kGestureTwoFingerTap:
- if (gesture_event.event.source_device ==
+ if (gesture_event.event.SourceDevice() ==
blink::kWebGestureDeviceTouchscreen) {
return !touchscreen_tap_suppression_controller_.FilterTapEvent(
gesture_event);
@@ -105,7 +104,7 @@ bool FlingController::FilterGestureEventForFlingBoosting(
// touchscreen fling is implemented, move the fling_controller_ from
// GestureEventQueue to RednerWidgetHostImpl. This will gaurantee proper
// gesture scroll event order in RednerWidgetHostImpl while boosting.
- if (gesture_event.event.source_device == blink::kWebGestureDeviceTouchpad)
+ if (gesture_event.event.SourceDevice() == blink::kWebGestureDeviceTouchpad)
return false;
bool cancel_current_fling;
@@ -136,20 +135,12 @@ void FlingController::OnGestureEventAck(
InputEventAckState ack_result) {
bool processed = (INPUT_EVENT_ACK_STATE_CONSUMED == ack_result);
switch (acked_event.event.GetType()) {
- case WebInputEvent::kGestureFlingCancel: {
- blink::WebGestureDevice source_device = acked_event.event.source_device;
- if (source_device == blink::kWebGestureDeviceTouchscreen) {
- touchscreen_tap_suppression_controller_.GestureFlingCancelAck(
- processed);
- } else if (source_device == blink::kWebGestureDeviceTouchpad) {
- touchpad_tap_suppression_controller_.GestureFlingCancelAck(processed);
- }
- break;
- }
case WebInputEvent::kGestureScrollUpdate:
if (acked_event.event.data.scroll_update.inertial_phase ==
WebGestureEvent::kMomentumPhase &&
- fling_curve_ && !processed) {
+ fling_curve_ && !processed &&
+ current_fling_parameters_.source_device !=
+ blink::kWebGestureDeviceSyntheticAutoscroll) {
CancelCurrentFling();
}
break;
@@ -164,6 +155,7 @@ void FlingController::ProcessGestureFlingStart(
const float vy = gesture_event.event.data.fling_start.velocity_y;
if (!UpdateCurrentFlingState(gesture_event.event, gfx::Vector2dF(vx, vy)))
return;
+
has_fling_animation_started_ = false;
fling_in_progress_ = true;
fling_booster_ = std::make_unique<ui::FlingBooster>(
@@ -180,29 +172,32 @@ void FlingController::ScheduleFlingProgress() {
void FlingController::ProcessGestureFlingCancel(
const GestureEventWithLatencyInfo& gesture_event) {
fling_in_progress_ = false;
+ bool processed = false;
if (fling_curve_) {
CancelCurrentFling();
-
- // FlingCancelEvent handled without being sent to the renderer.
- touchpad_tap_suppression_controller_.GestureFlingCancelAck(true);
- return;
+ processed = true;
+ }
+ // FlingCancelEvent handled without being sent to the renderer.
+ blink::WebGestureDevice source_device = gesture_event.event.SourceDevice();
+ if (source_device == blink::kWebGestureDeviceTouchscreen) {
+ touchscreen_tap_suppression_controller_.GestureFlingCancelAck(processed);
+ } else if (source_device == blink::kWebGestureDeviceTouchpad) {
+ touchpad_tap_suppression_controller_.GestureFlingCancelAck(processed);
}
-
- // FlingCancelEvent ignored without being sent to the renderer.
- touchpad_tap_suppression_controller_.GestureFlingCancelAck(false);
}
-void FlingController::ProgressFling(base::TimeTicks current_time) {
+gfx::Vector2dF FlingController::ProgressFling(base::TimeTicks current_time) {
if (!fling_curve_)
- return;
+ return gfx::Vector2dF();
DCHECK(fling_booster_);
fling_booster_->set_last_fling_animation_time(
(current_time - base::TimeTicks()).InSecondsF());
if (fling_booster_->MustCancelDeferredFling()) {
CancelCurrentFling();
- return;
+ return gfx::Vector2dF();
}
+
if (!has_fling_animation_started_) {
// Guard against invalid, future or sufficiently stale start times, as there
// are no guarantees fling event and progress timestamps are compatible.
@@ -212,30 +207,30 @@ void FlingController::ProgressFling(base::TimeTicks current_time) {
kMaxMicrosecondsFromFlingTimestampToFirstProgress) {
current_fling_parameters_.start_time = current_time;
ScheduleFlingProgress();
- return;
+ return current_fling_parameters_.velocity;
}
}
- gfx::Vector2dF current_velocity;
gfx::Vector2dF delta_to_scroll;
bool fling_is_active = fling_curve_->Advance(
(current_time - current_fling_parameters_.start_time).InSecondsF(),
- current_velocity, delta_to_scroll);
+ current_fling_parameters_.velocity, delta_to_scroll);
if (fling_is_active) {
if (delta_to_scroll != gfx::Vector2d()) {
- blink::WebMouseWheelEvent::Phase phase =
- has_fling_animation_started_
- ? blink::WebMouseWheelEvent::kPhaseChanged
- : blink::WebMouseWheelEvent::kPhaseBegan;
- GenerateAndSendWheelEvents(delta_to_scroll, phase);
+ GenerateAndSendFlingProgressEvents(delta_to_scroll);
has_fling_animation_started_ = true;
}
// As long as the fling curve is active, the fling progress must get
// scheduled even when the last delta to scroll was zero.
ScheduleFlingProgress();
- } else { // !is_fling_active
+ return current_fling_parameters_.velocity;
+ }
+
+ if (current_fling_parameters_.source_device !=
+ blink::kWebGestureDeviceSyntheticAutoscroll) {
CancelCurrentFling();
}
+ return gfx::Vector2dF();
}
void FlingController::StopFling() {
@@ -246,7 +241,7 @@ void FlingController::StopFling() {
}
void FlingController::GenerateAndSendWheelEvents(
- gfx::Vector2dF delta,
+ const gfx::Vector2dF& delta,
blink::WebMouseWheelEvent::Phase phase) {
MouseWheelEventWithLatencyInfo synthetic_wheel(
WebInputEvent::kMouseWheel, current_fling_parameters_.modifiers,
@@ -257,11 +252,9 @@ void FlingController::GenerateAndSendWheelEvents(
synthetic_wheel.event.has_precise_scrolling_deltas = true;
synthetic_wheel.event.momentum_phase = phase;
synthetic_wheel.event.has_synthetic_phase = true;
- synthetic_wheel.event.SetPositionInWidget(
- current_fling_parameters_.point.x(), current_fling_parameters_.point.y());
+ synthetic_wheel.event.SetPositionInWidget(current_fling_parameters_.point);
synthetic_wheel.event.SetPositionInScreen(
- current_fling_parameters_.global_point.x(),
- current_fling_parameters_.global_point.y());
+ current_fling_parameters_.global_point);
// Send wheel end events nonblocking since they have zero delta and are not
// sent to JS.
if (phase == blink::WebMouseWheelEvent::kPhaseEnded) {
@@ -275,67 +268,151 @@ void FlingController::GenerateAndSendWheelEvents(
client_->SendGeneratedWheelEvent(synthetic_wheel);
}
+void FlingController::GenerateAndSendGestureScrollEvents(
+ WebInputEvent::Type type,
+ const gfx::Vector2dF& delta /* = gfx::Vector2dF() */) {
+ GestureEventWithLatencyInfo synthetic_gesture(
+ type, current_fling_parameters_.modifiers,
+ ui::EventTimeStampToSeconds(base::TimeTicks::Now()),
+ ui::LatencyInfo(ui::SourceEventType::TOUCH));
+ synthetic_gesture.event.SetPositionInWidget(current_fling_parameters_.point);
+ synthetic_gesture.event.SetPositionInScreen(
+ current_fling_parameters_.global_point);
+ synthetic_gesture.event.primary_pointer_type =
+ blink::WebPointerProperties::PointerType::kTouch;
+ synthetic_gesture.event.SetSourceDevice(
+ current_fling_parameters_.source_device);
+ if (type == WebInputEvent::kGestureScrollUpdate) {
+ synthetic_gesture.event.data.scroll_update.delta_x = delta.x();
+ synthetic_gesture.event.data.scroll_update.delta_y = delta.y();
+ synthetic_gesture.event.data.scroll_update.inertial_phase =
+ WebGestureEvent::kMomentumPhase;
+ } else {
+ DCHECK_EQ(WebInputEvent::kGestureScrollEnd, type);
+ synthetic_gesture.event.data.scroll_end.inertial_phase =
+ WebGestureEvent::kMomentumPhase;
+ }
+ client_->SendGeneratedGestureScrollEvents(synthetic_gesture);
+}
+
+void FlingController::GenerateAndSendFlingProgressEvents(
+ const gfx::Vector2dF& delta) {
+ switch (current_fling_parameters_.source_device) {
+ case blink::kWebGestureDeviceTouchpad: {
+ blink::WebMouseWheelEvent::Phase phase =
+ has_fling_animation_started_
+ ? blink::WebMouseWheelEvent::kPhaseChanged
+ : blink::WebMouseWheelEvent::kPhaseBegan;
+ GenerateAndSendWheelEvents(delta, phase);
+ break;
+ }
+ case blink::kWebGestureDeviceTouchscreen:
+ case blink::kWebGestureDeviceSyntheticAutoscroll:
+ GenerateAndSendGestureScrollEvents(WebInputEvent::kGestureScrollUpdate,
+ delta);
+ break;
+ default:
+ NOTREACHED()
+ << "Fling controller doesn't handle flings with source device:"
+ << current_fling_parameters_.source_device;
+ }
+}
+
+void FlingController::GenerateAndSendFlingEndEvents() {
+ switch (current_fling_parameters_.source_device) {
+ case blink::kWebGestureDeviceTouchpad:
+ GenerateAndSendWheelEvents(gfx::Vector2d(),
+ blink::WebMouseWheelEvent::kPhaseEnded);
+ break;
+ case blink::kWebGestureDeviceTouchscreen:
+ case blink::kWebGestureDeviceSyntheticAutoscroll:
+ GenerateAndSendGestureScrollEvents(WebInputEvent::kGestureScrollEnd);
+ break;
+ default:
+ NOTREACHED()
+ << "Fling controller doesn't handle flings with source device:"
+ << current_fling_parameters_.source_device;
+ }
+}
+
void FlingController::CancelCurrentFling() {
+ bool had_active_fling = !!fling_curve_;
fling_curve_.reset();
has_fling_animation_started_ = false;
fling_in_progress_ = false;
- GenerateAndSendWheelEvents(gfx::Vector2d(),
- blink::WebMouseWheelEvent::kPhaseEnded);
+ gesture_event_queue_->FlingHasBeenHalted();
+
+ // Extract the last event filtered by the fling booster if it exists.
+ bool fling_cancellation_is_deferred =
+ fling_booster_ && fling_booster_->fling_cancellation_is_deferred();
+ WebGestureEvent last_fling_boost_event;
+ if (fling_cancellation_is_deferred)
+ last_fling_boost_event = fling_booster_->last_boost_event();
+
+ // Reset the state of the fling.
+ fling_booster_.reset();
+ GenerateAndSendFlingEndEvents();
current_fling_parameters_ = ActiveFlingParameters();
- if (fling_booster_) {
- if (fling_booster_->fling_cancellation_is_deferred()) {
- WebGestureEvent last_fling_boost_event =
- fling_booster_->last_boost_event();
- fling_booster_.reset();
- if (last_fling_boost_event.GetType() ==
- WebInputEvent::kGestureScrollBegin ||
- last_fling_boost_event.GetType() ==
- WebInputEvent::kGestureScrollUpdate) {
- // Synthesize a GestureScrollBegin, as the original event was
- // suppressed.
- WebGestureEvent scroll_begin_event = last_fling_boost_event;
- scroll_begin_event.SetType(WebInputEvent::kGestureScrollBegin);
- scroll_begin_event.SetTimeStampSeconds(
- ui::EventTimeStampToSeconds(base::TimeTicks::Now()));
- bool is_update = last_fling_boost_event.GetType() ==
- WebInputEvent::kGestureScrollUpdate;
- float delta_x_hint =
- is_update ? last_fling_boost_event.data.scroll_update.delta_x
- : last_fling_boost_event.data.scroll_begin.delta_x_hint;
- float delta_y_hint =
- is_update ? last_fling_boost_event.data.scroll_update.delta_y
- : last_fling_boost_event.data.scroll_begin.delta_y_hint;
- scroll_begin_event.data.scroll_begin.delta_x_hint = delta_x_hint;
- scroll_begin_event.data.scroll_begin.delta_y_hint = delta_y_hint;
- gesture_event_queue_->QueueEvent(GestureEventWithLatencyInfo(
- scroll_begin_event, ui::LatencyInfo(ui::SourceEventType::WHEEL)));
- }
- } else {
- fling_booster_.reset();
+ // Synthesize a GestureScrollBegin, as the original event was suppressed. It
+ // is important to send the GSB after resetting the fling_booster_ otherwise
+ // it will get filtered by the booster again.
+ if (fling_cancellation_is_deferred &&
+ (last_fling_boost_event.GetType() == WebInputEvent::kGestureScrollBegin ||
+ last_fling_boost_event.GetType() ==
+ WebInputEvent::kGestureScrollUpdate)) {
+ WebGestureEvent scroll_begin_event = last_fling_boost_event;
+ scroll_begin_event.SetType(WebInputEvent::kGestureScrollBegin);
+ scroll_begin_event.SetTimeStampSeconds(
+ ui::EventTimeStampToSeconds(base::TimeTicks::Now()));
+ bool is_update =
+ last_fling_boost_event.GetType() == WebInputEvent::kGestureScrollUpdate;
+ float delta_x_hint =
+ is_update ? last_fling_boost_event.data.scroll_update.delta_x
+ : last_fling_boost_event.data.scroll_begin.delta_x_hint;
+ float delta_y_hint =
+ is_update ? last_fling_boost_event.data.scroll_update.delta_y
+ : last_fling_boost_event.data.scroll_begin.delta_y_hint;
+ scroll_begin_event.data.scroll_begin.delta_x_hint = delta_x_hint;
+ scroll_begin_event.data.scroll_begin.delta_y_hint = delta_y_hint;
+ ui::SourceEventType latency_source_event_type =
+ ui::SourceEventType::UNKNOWN;
+ if (scroll_begin_event.SourceDevice() ==
+ blink::kWebGestureDeviceTouchscreen) {
+ latency_source_event_type = ui::SourceEventType::TOUCH;
+ } else if (scroll_begin_event.SourceDevice() ==
+ blink::kWebGestureDeviceTouchpad) {
+ latency_source_event_type = ui::SourceEventType::WHEEL;
}
+
+ client_->SendGeneratedGestureScrollEvents(GestureEventWithLatencyInfo(
+ scroll_begin_event, ui::LatencyInfo(latency_source_event_type)));
}
+
+ if (had_active_fling)
+ client_->DidStopFlingingOnBrowser();
}
bool FlingController::UpdateCurrentFlingState(
const WebGestureEvent& fling_start_event,
const gfx::Vector2dF& velocity) {
DCHECK_EQ(WebInputEvent::kGestureFlingStart, fling_start_event.GetType());
- if (velocity.IsZero()) {
- CancelCurrentFling();
- return false;
- }
current_fling_parameters_.velocity = velocity;
- current_fling_parameters_.point =
- gfx::Vector2d(fling_start_event.x, fling_start_event.y);
- current_fling_parameters_.global_point =
- gfx::Vector2d(fling_start_event.global_x, fling_start_event.global_y);
+ current_fling_parameters_.point = fling_start_event.PositionInWidget();
+ current_fling_parameters_.global_point = fling_start_event.PositionInScreen();
current_fling_parameters_.modifiers = fling_start_event.GetModifiers();
- current_fling_parameters_.source_device = fling_start_event.source_device;
+ current_fling_parameters_.source_device = fling_start_event.SourceDevice();
current_fling_parameters_.start_time =
base::TimeTicks() +
base::TimeDelta::FromSecondsD(fling_start_event.TimeStampSeconds());
+
+ if (velocity.IsZero() && fling_start_event.SourceDevice() !=
+ blink::kWebGestureDeviceSyntheticAutoscroll) {
+ CancelCurrentFling();
+ return false;
+ }
+
fling_curve_ = std::unique_ptr<blink::WebGestureCurve>(
ui::WebGestureCurveImpl::CreateFromDefaultPlatformCurve(
current_fling_parameters_.source_device,
@@ -344,6 +421,15 @@ bool FlingController::UpdateCurrentFlingState(
return true;
}
+bool FlingController::FlingCancellationIsDeferred() const {
+ return fling_booster_ && fling_booster_->fling_cancellation_is_deferred();
+}
+
+bool FlingController::TouchscreenFlingInProgress() const {
+ return fling_in_progress_ && current_fling_parameters_.source_device ==
+ blink::kWebGestureDeviceTouchscreen;
+}
+
TouchpadTapSuppressionController*
FlingController::GetTouchpadTapSuppressionController() {
return &touchpad_tap_suppression_controller_;
diff --git a/chromium/content/browser/renderer_host/input/fling_controller.h b/chromium/content/browser/renderer_host/input/fling_controller.h
index 3fc6840cce5..c762b57c02c 100644
--- a/chromium/content/browser/renderer_host/input/fling_controller.h
+++ b/chromium/content/browser/renderer_host/input/fling_controller.h
@@ -21,7 +21,8 @@ namespace content {
class GestureEventQueue;
-// Interface with which the FlingController can forward generated wheel events.
+// Interface with which the FlingController can forward generated fling progress
+// events.
class CONTENT_EXPORT FlingControllerClient {
public:
virtual ~FlingControllerClient() {}
@@ -29,7 +30,12 @@ class CONTENT_EXPORT FlingControllerClient {
virtual void SendGeneratedWheelEvent(
const MouseWheelEventWithLatencyInfo& wheel_event) = 0;
+ virtual void SendGeneratedGestureScrollEvents(
+ const GestureEventWithLatencyInfo& gesture_event) = 0;
+
virtual void SetNeedsBeginFrameForFlingProgress() = 0;
+
+ virtual void DidStopFlingingOnBrowser() = 0;
};
class CONTENT_EXPORT FlingController {
@@ -46,8 +52,8 @@ class CONTENT_EXPORT FlingController {
struct ActiveFlingParameters {
gfx::Vector2dF velocity;
- gfx::Vector2d point;
- gfx::Vector2d global_point;
+ gfx::PointF point;
+ gfx::PointF global_point;
int modifiers;
blink::WebGestureDevice source_device;
base::TimeTicks start_time;
@@ -62,8 +68,9 @@ class CONTENT_EXPORT FlingController {
~FlingController();
- // Used to progress an active fling on every begin frame.
- void ProgressFling(base::TimeTicks current_time);
+ // Used to progress an active fling on every begin frame and return the
+ // current fling velocity.
+ gfx::Vector2dF ProgressFling(base::TimeTicks current_time);
// Used to halt an active fling progress whenever needed.
void StopFling();
@@ -81,6 +88,10 @@ class CONTENT_EXPORT FlingController {
bool fling_in_progress() const { return fling_in_progress_; }
+ bool FlingCancellationIsDeferred() const;
+
+ bool TouchscreenFlingInProgress() const;
+
// Returns the |TouchpadTapSuppressionController| instance.
TouchpadTapSuppressionController* GetTouchpadTapSuppressionController();
@@ -104,9 +115,25 @@ class CONTENT_EXPORT FlingController {
void ScheduleFlingProgress();
// Used to generate synthetic wheel events from touchpad fling and send them.
- void GenerateAndSendWheelEvents(gfx::Vector2dF delta,
+ void GenerateAndSendWheelEvents(const gfx::Vector2dF& delta,
blink::WebMouseWheelEvent::Phase phase);
+ // Used to generate synthetic gesture scroll events from touchscreen fling and
+ // send them.
+ void GenerateAndSendGestureScrollEvents(
+ blink::WebInputEvent::Type type,
+ const gfx::Vector2dF& delta = gfx::Vector2dF());
+
+ // Calls one of the GenerateAndSendWheelEvents or
+ // GenerateAndSendGestureScrollEvents functions depending on the source
+ // device of the current_fling_parameters_. We send GSU and wheel events
+ // to progress flings with touchscreen and touchpad source respectively.
+ // The reason for this difference is that during the touchpad fling we still
+ // send wheel events to JS and generating GSU events directly is not enough.
+ void GenerateAndSendFlingProgressEvents(const gfx::Vector2dF& delta);
+
+ void GenerateAndSendFlingEndEvents();
+
void CancelCurrentFling();
bool UpdateCurrentFlingState(const blink::WebGestureEvent& fling_start_event,
@@ -131,8 +158,7 @@ class CONTENT_EXPORT FlingController {
ActiveFlingParameters current_fling_parameters_;
- // True while no GestureFlingCancel has arrived after the FlingController has
- // processed a GestureFlingStart.
+ // True when a fling is active.
bool fling_in_progress_;
// Whether an active fling has seen a |ProgressFling()| call. This is useful
diff --git a/chromium/content/browser/renderer_host/input/fling_controller_unittest.cc b/chromium/content/browser/renderer_host/input/fling_controller_unittest.cc
index ec1f772b284..d95159d2c7b 100644
--- a/chromium/content/browser/renderer_host/input/fling_controller_unittest.cc
+++ b/chromium/content/browser/renderer_host/input/fling_controller_unittest.cc
@@ -70,18 +70,24 @@ class FlingControllerTest : public testing::Test,
const MouseWheelEventWithLatencyInfo& wheel_event) override {
last_sent_wheel_ = wheel_event.event;
}
+ void SendGeneratedGestureScrollEvents(
+ const GestureEventWithLatencyInfo& gesture_event) override {
+ last_sent_gesture_ = gesture_event.event;
+ }
void SetNeedsBeginFrameForFlingProgress() override {
DCHECK(!scheduled_next_fling_progress_);
scheduled_next_fling_progress_ = true;
}
+ void DidStopFlingingOnBrowser() override {
+ notified_client_after_fling_stop_ = true;
+ }
void SimulateFlingStart(blink::WebGestureDevice source_device,
const gfx::Vector2dF& velocity) {
scheduled_next_fling_progress_ = false;
WebGestureEvent fling_start(
WebInputEvent::kGestureFlingStart, 0,
- ui::EventTimeStampToSeconds(base::TimeTicks::Now()));
- fling_start.source_device = source_device;
+ ui::EventTimeStampToSeconds(base::TimeTicks::Now()), source_device);
fling_start.data.fling_start.velocity_x = velocity.x();
fling_start.data.fling_start.velocity_y = velocity.y();
GestureEventWithLatencyInfo fling_start_with_latency(fling_start);
@@ -90,10 +96,13 @@ class FlingControllerTest : public testing::Test,
}
void SimulateFlingCancel(blink::WebGestureDevice source_device) {
+ notified_client_after_fling_stop_ = false;
WebGestureEvent fling_cancel(
WebInputEvent::kGestureFlingCancel, 0,
- ui::EventTimeStampToSeconds(base::TimeTicks::Now()));
- fling_cancel.source_device = source_device;
+ ui::EventTimeStampToSeconds(base::TimeTicks::Now()), source_device);
+ // autoscroll fling cancel doesn't allow fling boosting.
+ if (source_device == blink::kWebGestureDeviceSyntheticAutoscroll)
+ fling_cancel.data.fling_cancel.prevent_boosting = true;
GestureEventWithLatencyInfo fling_cancel_with_latency(fling_cancel);
last_fling_cancel_filtered_ =
fling_controller_->FilterGestureEvent(fling_cancel_with_latency);
@@ -113,8 +122,10 @@ class FlingControllerTest : public testing::Test,
protected:
std::unique_ptr<FakeFlingController> fling_controller_;
WebMouseWheelEvent last_sent_wheel_;
+ WebGestureEvent last_sent_gesture_;
bool last_fling_cancel_filtered_;
bool scheduled_next_fling_progress_;
+ bool notified_client_after_fling_stop_;
private:
base::test::ScopedTaskEnvironment scoped_task_environment_;
@@ -122,7 +133,8 @@ class FlingControllerTest : public testing::Test,
base::test::ScopedFeatureList feature_list_;
};
-TEST_F(FlingControllerTest, ControllerSendsWheelEndOnFlingWithZeroVelocity) {
+TEST_F(FlingControllerTest,
+ ControllerSendsWheelEndOnTouchpadFlingWithZeroVelocity) {
SimulateFlingStart(blink::kWebGestureDeviceTouchpad, gfx::Vector2dF());
// The controller doesn't start a fling and sends a wheel end event
// immediately.
@@ -132,7 +144,15 @@ TEST_F(FlingControllerTest, ControllerSendsWheelEndOnFlingWithZeroVelocity) {
EXPECT_EQ(0.f, last_sent_wheel_.delta_y);
}
-TEST_F(FlingControllerTest, ControllerHandlesGestureFling) {
+TEST_F(FlingControllerTest,
+ ControllerSendsGSEOnTouchscreenFlingWithZeroVelocity) {
+ SimulateFlingStart(blink::kWebGestureDeviceTouchscreen, gfx::Vector2dF());
+ // The controller doesn't start a fling and sends a GSE immediately.
+ EXPECT_FALSE(FlingInProgress());
+ EXPECT_EQ(WebInputEvent::kGestureScrollEnd, last_sent_gesture_.GetType());
+}
+
+TEST_F(FlingControllerTest, ControllerHandlesTouchpadGestureFling) {
base::TimeTicks progress_time = base::TimeTicks::Now();
SimulateFlingStart(blink::kWebGestureDeviceTouchpad, gfx::Vector2dF(1000, 0));
EXPECT_TRUE(FlingInProgress());
@@ -155,7 +175,33 @@ TEST_F(FlingControllerTest, ControllerHandlesGestureFling) {
EXPECT_EQ(0.f, last_sent_wheel_.delta_y);
}
-TEST_F(FlingControllerTest, ControllerSendsWheelEndWhenFlingIsOver) {
+TEST_F(FlingControllerTest, ControllerHandlesTouchscreenGestureFling) {
+ base::TimeTicks progress_time = base::TimeTicks::Now();
+ SimulateFlingStart(blink::kWebGestureDeviceTouchscreen,
+ gfx::Vector2dF(1000, 0));
+ EXPECT_TRUE(FlingInProgress());
+
+ // The fling progress will generate and send GSU events with inertial state.
+ progress_time += base::TimeDelta::FromMilliseconds(17);
+ ProgressFling(progress_time);
+ ASSERT_EQ(WebInputEvent::kGestureScrollUpdate, last_sent_gesture_.GetType());
+ EXPECT_EQ(WebGestureEvent::kMomentumPhase,
+ last_sent_gesture_.data.scroll_update.inertial_phase);
+ EXPECT_GT(last_sent_gesture_.data.scroll_update.delta_x, 0.f);
+
+ // Now cancel the fling. The GFC will get suppressed by fling booster.
+ SimulateFlingCancel(blink::kWebGestureDeviceTouchscreen);
+ EXPECT_TRUE(last_fling_cancel_filtered_);
+ EXPECT_TRUE(FlingInProgress());
+
+ // Wait for the boosting timer to expire. The delayed cancelation must work.
+ progress_time += base::TimeDelta::FromMilliseconds(500);
+ ProgressFling(progress_time);
+ EXPECT_FALSE(FlingInProgress());
+ EXPECT_EQ(WebInputEvent::kGestureScrollEnd, last_sent_gesture_.GetType());
+}
+
+TEST_F(FlingControllerTest, ControllerSendsWheelEndWhenTouchpadFlingIsOver) {
base::TimeTicks progress_time = base::TimeTicks::Now();
SimulateFlingStart(blink::kWebGestureDeviceTouchpad, gfx::Vector2dF(100, 0));
EXPECT_TRUE(FlingInProgress());
@@ -179,7 +225,29 @@ TEST_F(FlingControllerTest, ControllerSendsWheelEndWhenFlingIsOver) {
EXPECT_EQ(0.f, last_sent_wheel_.delta_y);
}
-TEST_F(FlingControllerTest, EarlyFlingCancelationOnInertialGSUAckNotConsumed) {
+TEST_F(FlingControllerTest, ControllerSendsGSEWhenTouchscreenFlingIsOver) {
+ base::TimeTicks progress_time = base::TimeTicks::Now();
+ SimulateFlingStart(blink::kWebGestureDeviceTouchscreen,
+ gfx::Vector2dF(100, 0));
+ EXPECT_TRUE(FlingInProgress());
+
+ progress_time += base::TimeDelta::FromMilliseconds(17);
+ ProgressFling(progress_time);
+ while (FlingInProgress()) {
+ ASSERT_EQ(WebInputEvent::kGestureScrollUpdate,
+ last_sent_gesture_.GetType());
+ EXPECT_EQ(WebGestureEvent::kMomentumPhase,
+ last_sent_gesture_.data.scroll_update.inertial_phase);
+ EXPECT_GT(last_sent_gesture_.data.scroll_update.delta_x, 0.f);
+ progress_time += base::TimeDelta::FromMilliseconds(17);
+ ProgressFling(progress_time);
+ }
+
+ EXPECT_EQ(WebInputEvent::kGestureScrollEnd, last_sent_gesture_.GetType());
+}
+
+TEST_F(FlingControllerTest,
+ EarlyTouchpadFlingCancelationOnInertialGSUAckNotConsumed) {
base::TimeTicks progress_time = base::TimeTicks::Now();
SimulateFlingStart(blink::kWebGestureDeviceTouchpad, gfx::Vector2dF(1000, 0));
EXPECT_TRUE(FlingInProgress());
@@ -204,7 +272,34 @@ TEST_F(FlingControllerTest, EarlyFlingCancelationOnInertialGSUAckNotConsumed) {
EXPECT_EQ(0.f, last_sent_wheel_.delta_y);
}
-TEST_F(FlingControllerTest, EarlyFlingCancelationOnFlingStop) {
+TEST_F(FlingControllerTest,
+ EarlyTouchscreenFlingCancelationOnInertialGSUAckNotConsumed) {
+ base::TimeTicks progress_time = base::TimeTicks::Now();
+ SimulateFlingStart(blink::kWebGestureDeviceTouchscreen,
+ gfx::Vector2dF(1000, 0));
+ EXPECT_TRUE(FlingInProgress());
+ progress_time += base::TimeDelta::FromMilliseconds(17);
+ ProgressFling(progress_time);
+ ASSERT_EQ(WebInputEvent::kGestureScrollUpdate, last_sent_gesture_.GetType());
+ EXPECT_EQ(WebGestureEvent::kMomentumPhase,
+ last_sent_gesture_.data.scroll_update.inertial_phase);
+ EXPECT_GT(last_sent_gesture_.data.scroll_update.delta_x, 0.f);
+
+ // A non-consumed GSU ack in inertial state cancels out the rest of the fling.
+ WebGestureEvent scroll_update(
+ WebInputEvent::kGestureScrollUpdate, 0,
+ ui::EventTimeStampToSeconds(base::TimeTicks::Now()));
+ scroll_update.data.scroll_update.inertial_phase =
+ WebGestureEvent::kMomentumPhase;
+
+ fling_controller_->OnGestureEventAck(
+ GestureEventWithLatencyInfo(scroll_update),
+ INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
+ EXPECT_FALSE(FlingInProgress());
+ EXPECT_EQ(WebInputEvent::kGestureScrollEnd, last_sent_gesture_.GetType());
+}
+
+TEST_F(FlingControllerTest, EarlyTouchpadFlingCancelationOnFlingStop) {
base::TimeTicks progress_time = base::TimeTicks::Now();
SimulateFlingStart(blink::kWebGestureDeviceTouchpad, gfx::Vector2dF(1000, 0));
EXPECT_TRUE(FlingInProgress());
@@ -220,9 +315,96 @@ TEST_F(FlingControllerTest, EarlyFlingCancelationOnFlingStop) {
EXPECT_EQ(0.f, last_sent_wheel_.delta_y);
}
+TEST_F(FlingControllerTest, EarlyTouchscreenFlingCancelationOnFlingStop) {
+ base::TimeTicks progress_time = base::TimeTicks::Now();
+ SimulateFlingStart(blink::kWebGestureDeviceTouchscreen,
+ gfx::Vector2dF(1000, 0));
+ EXPECT_TRUE(FlingInProgress());
+
+ // progress fling must send GSU events.
+ progress_time += base::TimeDelta::FromMilliseconds(17);
+ ProgressFling(progress_time);
+ ASSERT_EQ(WebInputEvent::kGestureScrollUpdate, last_sent_gesture_.GetType());
+ EXPECT_EQ(WebGestureEvent::kMomentumPhase,
+ last_sent_gesture_.data.scroll_update.inertial_phase);
+ EXPECT_GT(last_sent_gesture_.data.scroll_update.delta_x, 0.f);
+
+ fling_controller_->StopFling();
+ EXPECT_FALSE(FlingInProgress());
+ EXPECT_EQ(WebInputEvent::kGestureScrollEnd, last_sent_gesture_.GetType());
+}
+
+TEST_F(FlingControllerTest, GestureFlingCancelsFiltered) {
+ // GFC without previous GFS is dropped.
+ SimulateFlingCancel(blink::kWebGestureDeviceTouchscreen);
+ EXPECT_TRUE(last_fling_cancel_filtered_);
+
+ // GFC after previous GFS is filtered by fling booster.
+ SimulateFlingStart(blink::kWebGestureDeviceTouchscreen,
+ gfx::Vector2dF(1000, 0));
+ EXPECT_TRUE(FlingInProgress());
+ SimulateFlingCancel(blink::kWebGestureDeviceTouchscreen);
+ EXPECT_TRUE(last_fling_cancel_filtered_);
+ EXPECT_TRUE(FlingInProgress());
+
+ // Any other GFC while the fling cancelation is deferred gets filtered.
+ SimulateFlingCancel(blink::kWebGestureDeviceTouchscreen);
+ EXPECT_TRUE(last_fling_cancel_filtered_);
+}
+
+TEST_F(FlingControllerTest, GestureFlingNotCancelledBySmallTimeDelta) {
+ base::TimeTicks progress_time = base::TimeTicks::Now();
+ SimulateFlingStart(blink::kWebGestureDeviceTouchscreen,
+ gfx::Vector2dF(1000, 0));
+ EXPECT_TRUE(FlingInProgress());
+
+ // If we the first progress tick happens too close to the fling_start time,
+ // the controller won't send any GSU events, but the fling is still active.
+ // progress_time += base::TimeDelta::FromMilliseconds(1);
+ ProgressFling(progress_time);
+ EXPECT_EQ(blink::kWebGestureDeviceUninitialized,
+ last_sent_gesture_.SourceDevice());
+ EXPECT_TRUE(FlingInProgress());
+
+ // The rest of the progress flings must advance the fling normally.
+ progress_time += base::TimeDelta::FromMilliseconds(17);
+ ProgressFling(progress_time);
+ EXPECT_EQ(blink::kWebGestureDeviceTouchscreen,
+ last_sent_gesture_.SourceDevice());
+ ASSERT_EQ(WebInputEvent::kGestureScrollUpdate, last_sent_gesture_.GetType());
+ EXPECT_EQ(WebGestureEvent::kMomentumPhase,
+ last_sent_gesture_.data.scroll_update.inertial_phase);
+ EXPECT_GT(last_sent_gesture_.data.scroll_update.delta_x, 0.f);
+}
+
+TEST_F(FlingControllerTest, GestureFlingWithNegativeTimeDelta) {
+ base::TimeTicks progress_time = base::TimeTicks::Now();
+ SimulateFlingStart(blink::kWebGestureDeviceTouchscreen,
+ gfx::Vector2dF(1000, 0));
+ EXPECT_TRUE(FlingInProgress());
+
+ // If we get a negative time delta, that is, the Progress tick time happens
+ // before the fling's start time then we should *not* try progressing the
+ // fling and instead reset the fling start time.
+ progress_time -= base::TimeDelta::FromMilliseconds(5);
+ ProgressFling(progress_time);
+ EXPECT_EQ(blink::kWebGestureDeviceUninitialized,
+ last_sent_gesture_.SourceDevice());
+
+ // The rest of the progress flings must advance the fling normally.
+ progress_time += base::TimeDelta::FromMilliseconds(17);
+ ProgressFling(progress_time);
+ EXPECT_EQ(blink::kWebGestureDeviceTouchscreen,
+ last_sent_gesture_.SourceDevice());
+ ASSERT_EQ(WebInputEvent::kGestureScrollUpdate, last_sent_gesture_.GetType());
+ EXPECT_EQ(WebGestureEvent::kMomentumPhase,
+ last_sent_gesture_.data.scroll_update.inertial_phase);
+ EXPECT_GT(last_sent_gesture_.data.scroll_update.delta_x, 0.f);
+}
+
// TODO(sahel): Enable the test once boosting is enabled for touchpad fling.
// https://crbug.com/249063
-TEST_F(FlingControllerTest, DISABLED_ControllerBoostsFling) {
+TEST_F(FlingControllerTest, DISABLED_ControllerBoostsTouchpadFling) {
base::TimeTicks progress_time = base::TimeTicks::Now();
SimulateFlingStart(blink::kWebGestureDeviceTouchpad, gfx::Vector2dF(1000, 0));
EXPECT_TRUE(FlingInProgress());
@@ -249,4 +431,78 @@ TEST_F(FlingControllerTest, DISABLED_ControllerBoostsFling) {
EXPECT_TRUE(FlingBoosted());
}
+TEST_F(FlingControllerTest, ControllerBoostsTouchscreenFling) {
+ base::TimeTicks progress_time = base::TimeTicks::Now();
+ SimulateFlingStart(blink::kWebGestureDeviceTouchscreen,
+ gfx::Vector2dF(1000, 0));
+ EXPECT_TRUE(FlingInProgress());
+
+ // Fling progress must send GSU events.
+ progress_time += base::TimeDelta::FromMilliseconds(17);
+ ProgressFling(progress_time);
+ ASSERT_EQ(WebInputEvent::kGestureScrollUpdate, last_sent_gesture_.GetType());
+ EXPECT_EQ(WebGestureEvent::kMomentumPhase,
+ last_sent_gesture_.data.scroll_update.inertial_phase);
+ EXPECT_GT(last_sent_gesture_.data.scroll_update.delta_x, 0.f);
+
+ // Now cancel the fling. The GFC will get suppressed by fling booster.
+ SimulateFlingCancel(blink::kWebGestureDeviceTouchscreen);
+ EXPECT_TRUE(last_fling_cancel_filtered_);
+ EXPECT_TRUE(FlingInProgress());
+
+ // The second GFS will boost the current active fling.
+ SimulateFlingStart(blink::kWebGestureDeviceTouchscreen,
+ gfx::Vector2dF(1000, 0));
+ EXPECT_TRUE(FlingInProgress());
+ EXPECT_TRUE(FlingBoosted());
+}
+
+TEST_F(FlingControllerTest, ControllerNotifiesTheClientAfterFlingStart) {
+ base::TimeTicks progress_time = base::TimeTicks::Now();
+ SimulateFlingStart(blink::kWebGestureDeviceTouchscreen,
+ gfx::Vector2dF(1000, 0));
+ EXPECT_TRUE(FlingInProgress());
+
+ // Now cancel the fling. The GFC will get suppressed by fling booster.
+ SimulateFlingCancel(blink::kWebGestureDeviceTouchscreen);
+ EXPECT_TRUE(last_fling_cancel_filtered_);
+ EXPECT_TRUE(FlingInProgress());
+
+ // Wait for the boosting timer to expire. The delayed cancelation must work
+ // and the client must be notified after fling cancelation.
+ progress_time += base::TimeDelta::FromMilliseconds(500);
+ ProgressFling(progress_time);
+ EXPECT_FALSE(FlingInProgress());
+ EXPECT_EQ(WebInputEvent::kGestureScrollEnd, last_sent_gesture_.GetType());
+ EXPECT_TRUE(notified_client_after_fling_stop_);
+}
+
+TEST_F(FlingControllerTest, MiddleClickAutoScrollFling) {
+ base::TimeTicks progress_time = base::TimeTicks::Now();
+ SimulateFlingStart(blink::kWebGestureDeviceSyntheticAutoscroll,
+ gfx::Vector2dF(1000, 0));
+ EXPECT_TRUE(FlingInProgress());
+
+ progress_time += base::TimeDelta::FromMilliseconds(17);
+ ProgressFling(progress_time);
+ ASSERT_EQ(WebInputEvent::kGestureScrollUpdate, last_sent_gesture_.GetType());
+ EXPECT_EQ(WebGestureEvent::kMomentumPhase,
+ last_sent_gesture_.data.scroll_update.inertial_phase);
+ EXPECT_GT(last_sent_gesture_.data.scroll_update.delta_x, 0.f);
+
+ // Now send a new fling with different velocity and without sending a fling
+ // cancel event, the new fling should always replace the old one even when
+ // they are in the same direction.
+ SimulateFlingStart(blink::kWebGestureDeviceSyntheticAutoscroll,
+ gfx::Vector2dF(2000, 0));
+ EXPECT_TRUE(FlingInProgress());
+ EXPECT_FALSE(FlingBoosted());
+
+ // Now cancel the fling. The GFC won't get suppressed by fling booster since
+ // autoscroll fling doesn't have boosting.
+ SimulateFlingCancel(blink::kWebGestureDeviceSyntheticAutoscroll);
+ EXPECT_FALSE(last_fling_cancel_filtered_);
+ EXPECT_FALSE(FlingInProgress());
+}
+
} // namespace content
diff --git a/chromium/content/browser/renderer_host/input/gesture_event_queue.cc b/chromium/content/browser/renderer_host/input/gesture_event_queue.cc
index 4a8bab1eb4e..673be7eae63 100644
--- a/chromium/content/browser/renderer_host/input/gesture_event_queue.cc
+++ b/chromium/content/browser/renderer_host/input/gesture_event_queue.cc
@@ -55,13 +55,11 @@ bool GestureEventQueue::QueueEvent(
return false;
}
- // fling_controller_ is in charge of handling GFS events from touchpad source
- // when wheel scroll latching is enabled. In this case instead of queuing the
- // GFS event to be sent to the renderer, the controller processes the fling
- // and generates wheel events with momentum phase which are handled in the
- // renderer normally.
- if (gesture_event.event.GetType() == WebInputEvent::kGestureFlingStart &&
- gesture_event.event.source_device == blink::kWebGestureDeviceTouchpad) {
+ // fling_controller_ is in charge of handling GFS events and the events are
+ // not sent to the renderer, the controller processes the fling and generates
+ // fling progress events (wheel events for touchpad and GSU events for
+ // touchscreen and autoscroll) which are handled normally.
+ if (gesture_event.event.GetType() == WebInputEvent::kGestureFlingStart) {
fling_controller_.ProcessGestureFlingStart(gesture_event);
fling_in_progress_ = true;
return false;
@@ -69,8 +67,7 @@ bool GestureEventQueue::QueueEvent(
// If the GestureFlingStart event is processed by the fling_controller_, the
// GestureFlingCancel event should be the same.
- if (gesture_event.event.GetType() == WebInputEvent::kGestureFlingCancel &&
- fling_controller_.fling_in_progress()) {
+ if (gesture_event.event.GetType() == WebInputEvent::kGestureFlingCancel) {
fling_controller_.ProcessGestureFlingCancel(gesture_event);
fling_in_progress_ = false;
return false;
@@ -80,8 +77,8 @@ bool GestureEventQueue::QueueEvent(
return true;
}
-void GestureEventQueue::ProgressFling(base::TimeTicks current_time) {
- fling_controller_.ProgressFling(current_time);
+gfx::Vector2dF GestureEventQueue::ProgressFling(base::TimeTicks current_time) {
+ return fling_controller_.ProgressFling(current_time);
}
void GestureEventQueue::StopFling() {
@@ -89,6 +86,14 @@ void GestureEventQueue::StopFling() {
fling_controller_.StopFling();
}
+bool GestureEventQueue::FlingCancellationIsDeferred() const {
+ return fling_controller_.FlingCancellationIsDeferred();
+}
+
+bool GestureEventQueue::TouchscreenFlingInProgress() const {
+ return fling_controller_.TouchscreenFlingInProgress();
+}
+
bool GestureEventQueue::ShouldDiscardFlingCancelEvent(
const GestureEventWithLatencyInfo& gesture_event) const {
// When the GFS is processed by the fling_controller_ the controller handles
diff --git a/chromium/content/browser/renderer_host/input/gesture_event_queue.h b/chromium/content/browser/renderer_host/input/gesture_event_queue.h
index fd80709c55a..fbba8a4597e 100644
--- a/chromium/content/browser/renderer_host/input/gesture_event_queue.h
+++ b/chromium/content/browser/renderer_host/input/gesture_event_queue.h
@@ -17,7 +17,7 @@
#include "content/common/content_export.h"
#include "content/public/common/input_event_ack_source.h"
#include "content/public/common/input_event_ack_state.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
namespace content {
class GestureEventQueueTest;
@@ -110,12 +110,16 @@ class CONTENT_EXPORT GestureEventQueue {
const GestureEventWithLatencyInfo& gesture_event) const;
// Calls |fling_controller_.ProgressFling| to advance an active fling on every
- // begin frame.
- void ProgressFling(base::TimeTicks current_time);
+ // begin frame and returns the current fling velocity if a fling is active.
+ gfx::Vector2dF ProgressFling(base::TimeTicks current_time);
// Calls |fling_controller_.StopFling| to halt an active fling if such exists.
void StopFling();
+ bool FlingCancellationIsDeferred() const;
+
+ bool TouchscreenFlingInProgress() const;
+
void set_debounce_interval_time_ms_for_testing(int interval_ms) {
debounce_interval_ = base::TimeDelta::FromMilliseconds(interval_ms);
}
diff --git a/chromium/content/browser/renderer_host/input/gesture_event_queue_unittest.cc b/chromium/content/browser/renderer_host/input/gesture_event_queue_unittest.cc
index b2f26f5fc0e..75ad2cd71de 100644
--- a/chromium/content/browser/renderer_host/input/gesture_event_queue_unittest.cc
+++ b/chromium/content/browser/renderer_host/input/gesture_event_queue_unittest.cc
@@ -24,7 +24,7 @@
#include "content/common/input/synthetic_web_input_event_builders.h"
#include "content/public/common/input_event_ack_state.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/events/blink/blink_features.h"
using base::TimeDelta;
@@ -108,7 +108,10 @@ class GestureEventQueueTest : public testing::Test,
// FlingControllerClient
void SendGeneratedWheelEvent(
const MouseWheelEventWithLatencyInfo& wheel_event) override {}
+ void SendGeneratedGestureScrollEvents(
+ const GestureEventWithLatencyInfo& gesture_event) override {}
void SetNeedsBeginFrameForFlingProgress() override {}
+ void DidStopFlingingOnBrowser() override {}
protected:
static GestureEventQueue::Config DefaultConfig() {
@@ -260,7 +263,7 @@ TEST_F(GestureEventQueueTest, CoalescesScrollGestureEvents) {
WebGestureEvent merged_event = GestureEventLastQueueEvent();
EXPECT_EQ(2U, GestureEventQueueSize());
EXPECT_EQ(WebInputEvent::kGestureScrollUpdate, merged_event.GetType());
- EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device);
+ EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice());
// Coalesced.
SimulateGestureScrollUpdateEvent(8, -6, 0);
@@ -271,7 +274,7 @@ TEST_F(GestureEventQueueTest, CoalescesScrollGestureEvents) {
EXPECT_EQ(0, merged_event.GetModifiers());
EXPECT_EQ(16, merged_event.data.scroll_update.delta_x);
EXPECT_EQ(-11, merged_event.data.scroll_update.delta_y);
- EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device);
+ EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice());
// Enqueued.
SimulateGestureScrollUpdateEvent(8, -7, 1);
@@ -280,7 +283,7 @@ TEST_F(GestureEventQueueTest, CoalescesScrollGestureEvents) {
merged_event = GestureEventLastQueueEvent();
EXPECT_EQ(WebInputEvent::kGestureScrollUpdate, merged_event.GetType());
EXPECT_EQ(1, merged_event.GetModifiers());
- EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device);
+ EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice());
// Different.
SimulateGestureEvent(WebInputEvent::kGestureScrollEnd,
@@ -334,33 +337,33 @@ TEST_F(GestureEventQueueTest,
// Make sure that the queue contains what we think it should.
EXPECT_EQ(2U, GestureEventQueueSize());
EXPECT_EQ(blink::kWebGestureDeviceTouchscreen,
- GestureEventLastQueueEvent().source_device);
+ GestureEventLastQueueEvent().SourceDevice());
// Coalesced.
SimulateGestureScrollUpdateEvent(8, -6, 0);
EXPECT_EQ(2U, GestureEventQueueSize());
EXPECT_EQ(blink::kWebGestureDeviceTouchscreen,
- GestureEventLastQueueEvent().source_device);
+ GestureEventLastQueueEvent().SourceDevice());
// Enqueued.
SimulateGestureEvent(WebInputEvent::kGestureScrollUpdate,
blink::kWebGestureDeviceTouchpad);
EXPECT_EQ(3U, GestureEventQueueSize());
EXPECT_EQ(blink::kWebGestureDeviceTouchpad,
- GestureEventLastQueueEvent().source_device);
+ GestureEventLastQueueEvent().SourceDevice());
// Coalesced.
SimulateGestureEvent(WebInputEvent::kGestureScrollUpdate,
blink::kWebGestureDeviceTouchpad);
EXPECT_EQ(3U, GestureEventQueueSize());
EXPECT_EQ(blink::kWebGestureDeviceTouchpad,
- GestureEventLastQueueEvent().source_device);
+ GestureEventLastQueueEvent().SourceDevice());
// Enqueued.
SimulateGestureScrollUpdateEvent(8, -7, 0);
EXPECT_EQ(4U, GestureEventQueueSize());
EXPECT_EQ(blink::kWebGestureDeviceTouchscreen,
- GestureEventLastQueueEvent().source_device);
+ GestureEventLastQueueEvent().SourceDevice());
}
TEST_F(GestureEventQueueTest, CoalescesScrollAndPinchEvents) {
@@ -391,13 +394,13 @@ TEST_F(GestureEventQueueTest, CoalescesScrollAndPinchEvents) {
EXPECT_EQ(WebInputEvent::kGesturePinchUpdate, merged_event.GetType());
EXPECT_EQ(1.5, merged_event.data.pinch_update.scale);
EXPECT_EQ(1, merged_event.GetModifiers());
- EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device);
+ EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice());
merged_event = GestureEventSecondFromLastQueueEvent();
EXPECT_EQ(WebInputEvent::kGestureScrollUpdate, merged_event.GetType());
EXPECT_EQ(8, merged_event.data.scroll_update.delta_x);
EXPECT_EQ(-4, merged_event.data.scroll_update.delta_y);
EXPECT_EQ(1, merged_event.GetModifiers());
- EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device);
+ EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice());
// Enqueued.
SimulateGestureScrollUpdateEvent(6, -3, 1);
@@ -408,13 +411,13 @@ TEST_F(GestureEventQueueTest, CoalescesScrollAndPinchEvents) {
EXPECT_EQ(WebInputEvent::kGesturePinchUpdate, merged_event.GetType());
EXPECT_EQ(1.5, merged_event.data.pinch_update.scale);
EXPECT_EQ(1, merged_event.GetModifiers());
- EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device);
+ EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice());
merged_event = GestureEventSecondFromLastQueueEvent();
EXPECT_EQ(WebInputEvent::kGestureScrollUpdate, merged_event.GetType());
EXPECT_EQ(12, merged_event.data.scroll_update.delta_x);
EXPECT_EQ(-6, merged_event.data.scroll_update.delta_y);
EXPECT_EQ(1, merged_event.GetModifiers());
- EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device);
+ EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice());
// Enqueued.
SimulateGesturePinchUpdateEvent(2, 60, 60, 1);
@@ -425,13 +428,13 @@ TEST_F(GestureEventQueueTest, CoalescesScrollAndPinchEvents) {
EXPECT_EQ(WebInputEvent::kGesturePinchUpdate, merged_event.GetType());
EXPECT_EQ(3, merged_event.data.pinch_update.scale);
EXPECT_EQ(1, merged_event.GetModifiers());
- EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device);
+ EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice());
merged_event = GestureEventSecondFromLastQueueEvent();
EXPECT_EQ(WebInputEvent::kGestureScrollUpdate, merged_event.GetType());
EXPECT_EQ(12, merged_event.data.scroll_update.delta_x);
EXPECT_EQ(-6, merged_event.data.scroll_update.delta_y);
EXPECT_EQ(1, merged_event.GetModifiers());
- EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device);
+ EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice());
// Enqueued.
SimulateGesturePinchUpdateEvent(2, 60, 60, 1);
@@ -442,13 +445,13 @@ TEST_F(GestureEventQueueTest, CoalescesScrollAndPinchEvents) {
EXPECT_EQ(WebInputEvent::kGesturePinchUpdate, merged_event.GetType());
EXPECT_EQ(6, merged_event.data.pinch_update.scale);
EXPECT_EQ(1, merged_event.GetModifiers());
- EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device);
+ EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice());
merged_event = GestureEventSecondFromLastQueueEvent();
EXPECT_EQ(WebInputEvent::kGestureScrollUpdate, merged_event.GetType());
EXPECT_EQ(12, merged_event.data.scroll_update.delta_x);
EXPECT_EQ(-6, merged_event.data.scroll_update.delta_y);
EXPECT_EQ(1, merged_event.GetModifiers());
- EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device);
+ EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice());
// Check that only the first event was sent.
EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
@@ -468,13 +471,13 @@ TEST_F(GestureEventQueueTest, CoalescesScrollAndPinchEvents) {
EXPECT_EQ(WebInputEvent::kGesturePinchUpdate, merged_event.GetType());
EXPECT_EQ(6, merged_event.data.pinch_update.scale);
EXPECT_EQ(1, merged_event.GetModifiers());
- EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device);
+ EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice());
merged_event = GestureEventSecondFromLastQueueEvent();
EXPECT_EQ(WebInputEvent::kGestureScrollUpdate, merged_event.GetType());
EXPECT_EQ(13, merged_event.data.scroll_update.delta_x);
EXPECT_EQ(-7, merged_event.data.scroll_update.delta_y);
EXPECT_EQ(1, merged_event.GetModifiers());
- EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device);
+ EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice());
// At this point ACKs shouldn't be getting ignored.
EXPECT_FALSE(WillIgnoreNextACK());
@@ -498,12 +501,12 @@ TEST_F(GestureEventQueueTest, CoalescesScrollAndPinchEvents) {
EXPECT_EQ(1, merged_event.data.scroll_update.delta_x);
EXPECT_EQ(-1, merged_event.data.scroll_update.delta_y);
EXPECT_EQ(1, merged_event.GetModifiers());
- EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device);
+ EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice());
merged_event = GestureEventSecondFromLastQueueEvent();
EXPECT_EQ(WebInputEvent::kGesturePinchUpdate, merged_event.GetType());
EXPECT_EQ(6, merged_event.data.pinch_update.scale);
EXPECT_EQ(1, merged_event.GetModifiers());
- EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device);
+ EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice());
// Enqueued.
SimulateGestureScrollUpdateEvent(2, -2, 1);
@@ -515,12 +518,12 @@ TEST_F(GestureEventQueueTest, CoalescesScrollAndPinchEvents) {
EXPECT_EQ(3, merged_event.data.scroll_update.delta_x);
EXPECT_EQ(-3, merged_event.data.scroll_update.delta_y);
EXPECT_EQ(1, merged_event.GetModifiers());
- EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device);
+ EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice());
merged_event = GestureEventSecondFromLastQueueEvent();
EXPECT_EQ(WebInputEvent::kGesturePinchUpdate, merged_event.GetType());
EXPECT_EQ(6, merged_event.data.pinch_update.scale);
EXPECT_EQ(1, merged_event.GetModifiers());
- EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device);
+ EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice());
// Enqueued.
SimulateGesturePinchUpdateEvent(0.5, 60, 60, 1);
@@ -531,13 +534,13 @@ TEST_F(GestureEventQueueTest, CoalescesScrollAndPinchEvents) {
EXPECT_EQ(WebInputEvent::kGesturePinchUpdate, merged_event.GetType());
EXPECT_EQ(0.5, merged_event.data.pinch_update.scale);
EXPECT_EQ(1, merged_event.GetModifiers());
- EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device);
+ EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice());
merged_event = GestureEventSecondFromLastQueueEvent();
EXPECT_EQ(WebInputEvent::kGestureScrollUpdate, merged_event.GetType());
EXPECT_EQ(3, merged_event.data.scroll_update.delta_x);
EXPECT_EQ(-3, merged_event.data.scroll_update.delta_y);
EXPECT_EQ(1, merged_event.GetModifiers());
- EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device);
+ EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice());
// Check that the ACK gets ignored.
SendInputEventACK(WebInputEvent::kGestureScrollUpdate,
@@ -558,12 +561,12 @@ TEST_F(GestureEventQueueTest, CoalescesScrollAndPinchEvents) {
EXPECT_EQ(2, merged_event.data.scroll_update.delta_x);
EXPECT_EQ(-2, merged_event.data.scroll_update.delta_y);
EXPECT_EQ(2, merged_event.GetModifiers());
- EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device);
+ EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice());
merged_event = GestureEventSecondFromLastQueueEvent();
EXPECT_EQ(WebInputEvent::kGesturePinchUpdate, merged_event.GetType());
EXPECT_EQ(0.5, merged_event.data.pinch_update.scale);
EXPECT_EQ(1, merged_event.GetModifiers());
- EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device);
+ EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice());
// Check that the ACK sends the next scroll pinch pair.
SendInputEventACK(WebInputEvent::kGesturePinchUpdate,
@@ -995,99 +998,6 @@ TEST_F(GestureEventQueueTest, CoalescesScrollAndPinchEventWithSyncAck) {
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
}
-TEST_P(GestureEventQueueWithSourceTest, GestureFlingCancelsFiltered) {
- WebGestureDevice source_device = GetParam();
-
- // GFS and GFC events with touchpad source are not queued since fling
- // controller handles them.
- if (source_device == blink::kWebGestureDeviceTouchpad)
- return;
-
- // GFC without previous GFS is dropped.
- SimulateGestureEvent(WebInputEvent::kGestureFlingCancel, source_device);
- EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
- EXPECT_EQ(0U, GestureEventQueueSize());
-
- // GFC after previous GFS is dispatched and acked.
- SimulateGestureFlingStartEvent(0, -10, source_device);
- EXPECT_TRUE(FlingInProgress());
- SendInputEventACK(WebInputEvent::kGestureFlingStart,
- INPUT_EVENT_ACK_STATE_CONSUMED);
- RunUntilIdle();
- EXPECT_EQ(1U, GetAndResetAckedGestureEventCount());
- SimulateGestureEvent(WebInputEvent::kGestureFlingCancel, source_device);
- EXPECT_FALSE(FlingInProgress());
- EXPECT_EQ(2U, GetAndResetSentGestureEventCount());
- SendInputEventACK(WebInputEvent::kGestureFlingCancel,
- INPUT_EVENT_ACK_STATE_CONSUMED);
- RunUntilIdle();
- EXPECT_EQ(1U, GetAndResetAckedGestureEventCount());
- EXPECT_EQ(0U, GestureEventQueueSize());
-
- // GFC before previous GFS is acked.
- SimulateGestureFlingStartEvent(0, -10, source_device);
- EXPECT_TRUE(FlingInProgress());
- SimulateGestureEvent(WebInputEvent::kGestureFlingCancel, source_device);
- EXPECT_FALSE(FlingInProgress());
- EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
- EXPECT_EQ(2U, GestureEventQueueSize());
-
- // Advance state realistically.
- SendInputEventACK(WebInputEvent::kGestureFlingStart,
- INPUT_EVENT_ACK_STATE_CONSUMED);
- RunUntilIdle();
- EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
- SendInputEventACK(WebInputEvent::kGestureFlingCancel,
- INPUT_EVENT_ACK_STATE_CONSUMED);
- RunUntilIdle();
- EXPECT_EQ(2U, GetAndResetAckedGestureEventCount());
- EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
- EXPECT_EQ(0U, GestureEventQueueSize());
-
- // GFS is added to the queue if another event is pending
- SimulateGestureScrollUpdateEvent(8, -7, 0);
- SimulateGestureFlingStartEvent(0, -10, source_device);
- EXPECT_EQ(2U, GestureEventQueueSize());
- EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
- WebGestureEvent merged_event = GestureEventLastQueueEvent();
- EXPECT_EQ(WebInputEvent::kGestureFlingStart, merged_event.GetType());
- EXPECT_TRUE(FlingInProgress());
- EXPECT_EQ(2U, GestureEventQueueSize());
-
- // GFS in queue means that a GFC is added to the queue
- SimulateGestureEvent(WebInputEvent::kGestureFlingCancel, source_device);
- merged_event = GestureEventLastQueueEvent();
- EXPECT_EQ(WebInputEvent::kGestureFlingCancel, merged_event.GetType());
- EXPECT_FALSE(FlingInProgress());
- EXPECT_EQ(3U, GestureEventQueueSize());
-
- // Adding a second GFC is dropped.
- SimulateGestureEvent(WebInputEvent::kGestureFlingCancel, source_device);
- EXPECT_FALSE(FlingInProgress());
- EXPECT_EQ(3U, GestureEventQueueSize());
-
- // Adding another GFS will add it to the queue.
- SimulateGestureFlingStartEvent(0, -10, source_device);
- merged_event = GestureEventLastQueueEvent();
- EXPECT_EQ(WebInputEvent::kGestureFlingStart, merged_event.GetType());
- EXPECT_TRUE(FlingInProgress());
- EXPECT_EQ(4U, GestureEventQueueSize());
-
- // GFS in queue means that a GFC is added to the queue
- SimulateGestureEvent(WebInputEvent::kGestureFlingCancel, source_device);
- merged_event = GestureEventLastQueueEvent();
- EXPECT_EQ(WebInputEvent::kGestureFlingCancel, merged_event.GetType());
- EXPECT_FALSE(FlingInProgress());
- EXPECT_EQ(5U, GestureEventQueueSize());
-
- // Adding another GFC with a GFC already there is dropped.
- SimulateGestureEvent(WebInputEvent::kGestureFlingCancel, source_device);
- merged_event = GestureEventLastQueueEvent();
- EXPECT_EQ(WebInputEvent::kGestureFlingCancel, merged_event.GetType());
- EXPECT_FALSE(FlingInProgress());
- EXPECT_EQ(5U, GestureEventQueueSize());
-}
-
INSTANTIATE_TEST_CASE_P(AllSources,
GestureEventQueueWithSourceTest,
testing::Values(blink::kWebGestureDeviceTouchscreen,
@@ -1252,25 +1162,24 @@ TEST_F(GestureEventQueueTest, TapGetsSuppressedAfterTapDownCancellsFling) {
SetUpForTapSuppression(400, 200);
SimulateGestureFlingStartEvent(0, -10, blink::kWebGestureDeviceTouchscreen);
EXPECT_TRUE(FlingInProgress());
- SendInputEventACK(WebInputEvent::kGestureFlingStart,
- INPUT_EVENT_ACK_STATE_CONSUMED);
- EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
- EXPECT_EQ(1U, GetAndResetAckedGestureEventCount());
+ // The fling start event is not sent to the renderer.
+ EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
+ EXPECT_EQ(0U, GetAndResetAckedGestureEventCount());
RunUntilIdle();
+ // Simulate a fling cancel event before sending a gesture tap down event. The
+ // fling cancel event is not sent to the renderer.
SimulateGestureEvent(WebInputEvent::kGestureFlingCancel,
blink::kWebGestureDeviceTouchscreen);
EXPECT_FALSE(FlingInProgress());
- EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
- EXPECT_EQ(1U, GestureEventQueueSize());
+ EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
+ EXPECT_EQ(0U, GestureEventQueueSize());
RunUntilIdle();
- // Simulate a fling cancelling tap down by sending a gesture tap down event
- // before arrival of the fling cancel ack. The tap down must get suppressed.
+ // Simulate a fling cancelling tap down. The tap down must get suppressed
+ // since the fling cancel event is processed by the fling controller.
SimulateGestureEvent(WebInputEvent::kGestureTapDown,
blink::kWebGestureDeviceTouchscreen);
- SendInputEventACK(WebInputEvent::kGestureFlingCancel,
- INPUT_EVENT_ACK_STATE_CONSUMED);
EXPECT_EQ(0U, GestureEventQueueSize());
// The tap event must get suppressed since its corresponding tap down event
diff --git a/chromium/content/browser/renderer_host/input/input_disposition_handler.h b/chromium/content/browser/renderer_host/input/input_disposition_handler.h
index efc6d557f6e..5aeb26278a1 100644
--- a/chromium/content/browser/renderer_host/input/input_disposition_handler.h
+++ b/chromium/content/browser/renderer_host/input/input_disposition_handler.h
@@ -9,7 +9,7 @@
#include "content/public/browser/native_web_keyboard_event.h"
#include "content/public/common/input_event_ack_source.h"
#include "content/public/common/input_event_ack_state.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
namespace content {
diff --git a/chromium/content/browser/renderer_host/input/input_router.h b/chromium/content/browser/renderer_host/input/input_router.h
index 3ba9a057176..dbced13759e 100644
--- a/chromium/content/browser/renderer_host/input/input_router.h
+++ b/chromium/content/browser/renderer_host/input/input_router.h
@@ -13,7 +13,7 @@
#include "content/public/browser/native_web_keyboard_event.h"
#include "content/public/common/input_event_ack_state.h"
#include "ipc/ipc_listener.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
namespace content {
@@ -75,6 +75,9 @@ class InputRouter : public IPC::Listener {
// Used to stop an active fling if such exists.
virtual void StopFling() = 0;
+
+ // Used to check if a fling cancellation is deferred due to boosting or not.
+ virtual bool FlingCancellationIsDeferred() = 0;
};
} // namespace content
diff --git a/chromium/content/browser/renderer_host/input/input_router_client.h b/chromium/content/browser/renderer_host/input/input_router_client.h
index dfd8960ca84..7d776d1e4c2 100644
--- a/chromium/content/browser/renderer_host/input/input_router_client.h
+++ b/chromium/content/browser/renderer_host/input/input_router_client.h
@@ -11,7 +11,7 @@
#include "content/public/browser/native_web_keyboard_event.h"
#include "content/public/common/input_event_ack_source.h"
#include "content/public/common/input_event_ack_state.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
namespace ui {
class LatencyInfo;
@@ -54,6 +54,9 @@ class CONTENT_EXPORT InputRouterClient {
// Called when a renderer fling has terminated.
virtual void DidStopFlinging() = 0;
+ // Called when a GSB has started scrolling a viewport.
+ virtual void DidStartScrollingViewport() = 0;
+
// Called when the input router generates an event. It is intended that the
// client will do some processing on |gesture_event| and then send it back
// to the InputRouter via SendGestureEvent.
diff --git a/chromium/content/browser/renderer_host/input/input_router_impl.cc b/chromium/content/browser/renderer_host/input/input_router_impl.cc
index 8db3e2a2f1b..be695174e56 100644
--- a/chromium/content/browser/renderer_host/input/input_router_impl.cc
+++ b/chromium/content/browser/renderer_host/input/input_router_impl.cc
@@ -10,7 +10,6 @@
#include "base/auto_reset.h"
#include "base/command_line.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/string_number_conversions.h"
#include "content/browser/renderer_host/input/gesture_event_queue.h"
@@ -117,6 +116,7 @@ void InputRouterImpl::SendWheelEvent(
void InputRouterImpl::SendKeyboardEvent(
const NativeWebKeyboardEventWithLatencyInfo& key_event) {
+ gesture_event_queue_.StopFling();
gesture_event_queue_.FlingHasBeenHalted();
mojom::WidgetInputHandler::DispatchEventCallback callback = base::BindOnce(
&InputRouterImpl::KeyboardEventHandled, weak_this_, key_event);
@@ -126,7 +126,8 @@ void InputRouterImpl::SendKeyboardEvent(
void InputRouterImpl::SendGestureEvent(
const GestureEventWithLatencyInfo& original_gesture_event) {
- input_stream_validator_.Validate(original_gesture_event.event);
+ input_stream_validator_.Validate(original_gesture_event.event,
+ FlingCancellationIsDeferred());
GestureEventWithLatencyInfo gesture_event(original_gesture_event);
@@ -139,7 +140,7 @@ void InputRouterImpl::SendGestureEvent(
wheel_event_queue_.OnGestureScrollEvent(gesture_event);
- if (gesture_event.event.source_device ==
+ if (gesture_event.event.SourceDevice() ==
blink::kWebGestureDeviceTouchscreen) {
if (gesture_event.event.GetType() ==
blink::WebInputEvent::kGestureScrollBegin) {
@@ -209,13 +210,22 @@ void InputRouterImpl::BindHost(mojom::WidgetInputHandlerHostRequest request,
}
void InputRouterImpl::ProgressFling(base::TimeTicks current_time) {
- gesture_event_queue_.ProgressFling(current_time);
+ current_fling_velocity_ = gesture_event_queue_.ProgressFling(current_time);
}
void InputRouterImpl::StopFling() {
gesture_event_queue_.StopFling();
}
+bool InputRouterImpl::FlingCancellationIsDeferred() {
+ return gesture_event_queue_.FlingCancellationIsDeferred();
+}
+
+void InputRouterImpl::DidStopFlingingOnBrowser() {
+ current_fling_velocity_ = gfx::Vector2dF();
+ client_->DidStopFlinging();
+}
+
void InputRouterImpl::CancelTouchTimeout() {
touch_event_queue_.SetAckTimeoutEnabled(false);
}
@@ -231,7 +241,10 @@ void InputRouterImpl::SetWhiteListedTouchAction(cc::TouchAction touch_action,
}
void InputRouterImpl::DidOverscroll(const ui::DidOverscrollParams& params) {
- client_->DidOverscroll(params);
+ // Touchpad and Touchscreen flings are handled on the browser side.
+ ui::DidOverscrollParams fling_updated_params = params;
+ fling_updated_params.current_fling_velocity = current_fling_velocity_;
+ client_->DidOverscroll(fling_updated_params);
}
void InputRouterImpl::DidStopFlinging() {
@@ -243,6 +256,10 @@ void InputRouterImpl::DidStopFlinging() {
client_->DidStopFlinging();
}
+void InputRouterImpl::DidStartScrollingViewport() {
+ client_->DidStartScrollingViewport();
+}
+
void InputRouterImpl::ImeCancelComposition() {
client_->OnImeCancelComposition();
}
@@ -341,6 +358,10 @@ void InputRouterImpl::OnFilteringTouchEvent(const WebTouchEvent& touch_event) {
output_stream_validator_.Validate(touch_event);
}
+bool InputRouterImpl::TouchscreenFlingInProgress() {
+ return gesture_event_queue_.TouchscreenFlingInProgress();
+}
+
void InputRouterImpl::SendGestureEventImmediately(
const GestureEventWithLatencyInfo& gesture_event) {
mojom::WidgetInputHandler::DispatchEventCallback callback = base::BindOnce(
@@ -363,6 +384,12 @@ void InputRouterImpl::SendGeneratedWheelEvent(
wheel_event.latency);
}
+void InputRouterImpl::SendGeneratedGestureScrollEvents(
+ const GestureEventWithLatencyInfo& gesture_event) {
+ client_->ForwardGestureEventWithLatencyInfo(gesture_event.event,
+ gesture_event.latency);
+}
+
void InputRouterImpl::SetNeedsBeginFrameForFlingProgress() {
client_->SetNeedsBeginFrameForFlingProgress();
}
@@ -404,6 +431,8 @@ void InputRouterImpl::FilterAndSendWebInputEvent(
InputEventAckState filtered_state =
client_->FilterInputEvent(input_event, latency_info);
if (WasHandled(filtered_state)) {
+ TRACE_EVENT_INSTANT0("input", "InputEventFiltered",
+ TRACE_EVENT_SCOPE_THREAD);
if (filtered_state != INPUT_EVENT_ACK_STATE_UNKNOWN) {
std::move(callback).Run(InputEventAckSource::BROWSER, latency_info,
filtered_state, base::nullopt, base::nullopt);
@@ -415,10 +444,14 @@ void InputRouterImpl::FilterAndSendWebInputEvent(
ScaleEvent(input_event, device_scale_factor_), latency_info);
if (WebInputEventTraits::ShouldBlockEventStream(
input_event, wheel_scroll_latching_enabled_)) {
+ TRACE_EVENT_INSTANT0("input", "InputEventSentBlocking",
+ TRACE_EVENT_SCOPE_THREAD);
client_->IncrementInFlightEventCount();
client_->GetWidgetInputHandler()->DispatchEvent(std::move(event),
std::move(callback));
} else {
+ TRACE_EVENT_INSTANT0("input", "InputEventSentNonBlocking",
+ TRACE_EVENT_SCOPE_THREAD);
client_->GetWidgetInputHandler()->DispatchNonBlockingEvent(
std::move(event));
std::move(callback).Run(InputEventAckSource::BROWSER, latency_info,
diff --git a/chromium/content/browser/renderer_host/input/input_router_impl.h b/chromium/content/browser/renderer_host/input/input_router_impl.h
index 5f476e766ce..a7da333622a 100644
--- a/chromium/content/browser/renderer_host/input/input_router_impl.h
+++ b/chromium/content/browser/renderer_host/input/input_router_impl.h
@@ -38,6 +38,8 @@ namespace content {
class InputDispositionHandler;
+class MockRenderWidgetHost;
+
class CONTENT_EXPORT InputRouterImplClient : public InputRouterClient {
public:
virtual mojom::WidgetInputHandler* GetWidgetInputHandler() = 0;
@@ -81,6 +83,8 @@ class CONTENT_EXPORT InputRouterImpl
bool frame_handler) override;
void ProgressFling(base::TimeTicks current_time) override;
void StopFling() override;
+ bool FlingCancellationIsDeferred() override;
+ void DidStopFlingingOnBrowser() override;
// InputHandlerHost impl
void CancelTouchTimeout() override;
@@ -90,6 +94,7 @@ class CONTENT_EXPORT InputRouterImpl
void DidOverscroll(const ui::DidOverscrollParams& params) override;
void DidStopFlinging() override;
void ImeCancelComposition() override;
+ void DidStartScrollingViewport() override;
void ImeCompositionRangeChanged(
const gfx::Range& range,
const std::vector<gfx::Rect>& bounds) override;
@@ -99,6 +104,7 @@ class CONTENT_EXPORT InputRouterImpl
private:
friend class InputRouterImplTest;
+ friend class MockRenderWidgetHost;
// Keeps track of last position of touch points and sets MovementXY for them.
void SetMovementXYForTouchPoints(blink::WebTouchEvent* event);
@@ -114,6 +120,7 @@ class CONTENT_EXPORT InputRouterImpl
InputEventAckSource ack_source,
InputEventAckState ack_result) override;
void OnFilteringTouchEvent(const blink::WebTouchEvent& touch_event) override;
+ bool TouchscreenFlingInProgress() override;
// GestureEventFilterClient
void SendGestureEventImmediately(
@@ -125,6 +132,8 @@ class CONTENT_EXPORT InputRouterImpl
// FlingControllerClient
void SendGeneratedWheelEvent(
const MouseWheelEventWithLatencyInfo& wheel_event) override;
+ void SendGeneratedGestureScrollEvents(
+ const GestureEventWithLatencyInfo& gesture_event) override;
void SetNeedsBeginFrameForFlingProgress() override;
// MouseWheelEventQueueClient
@@ -212,6 +221,8 @@ class CONTENT_EXPORT InputRouterImpl
float device_scale_factor_;
+ gfx::Vector2dF current_fling_velocity_;
+
// Last touch position relative to screen. Used to compute movementX/Y.
base::flat_map<int, gfx::Point> global_touch_position_;
diff --git a/chromium/content/browser/renderer_host/input/input_router_impl_unittest.cc b/chromium/content/browser/renderer_host/input/input_router_impl_unittest.cc
index 7a388a0a030..1761884fa5b 100644
--- a/chromium/content/browser/renderer_host/input/input_router_impl_unittest.cc
+++ b/chromium/content/browser/renderer_host/input/input_router_impl_unittest.cc
@@ -15,7 +15,6 @@
#include "base/command_line.h"
#include "base/location.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
@@ -144,6 +143,10 @@ class MockInputRouterImplClient : public InputRouterImplClient {
void DidStopFlinging() override { input_router_client_.DidStopFlinging(); }
+ void DidStartScrollingViewport() override {
+ input_router_client_.DidStartScrollingViewport();
+ }
+
void SetNeedsBeginFrameForFlingProgress() override {
input_router_client_.SetNeedsBeginFrameForFlingProgress();
}
@@ -327,14 +330,14 @@ class InputRouterImplTest : public testing::Test {
void SimulateGestureEvent(WebGestureEvent gesture) {
if (gesture.GetType() == WebInputEvent::kGestureScrollBegin &&
- gesture.source_device == blink::kWebGestureDeviceTouchscreen &&
+ gesture.SourceDevice() == blink::kWebGestureDeviceTouchscreen &&
!gesture.data.scroll_begin.delta_x_hint &&
!gesture.data.scroll_begin.delta_y_hint) {
// Ensure non-zero scroll-begin offset-hint to make the event sane,
// prevents unexpected filtering at TouchActionFilter.
gesture.data.scroll_begin.delta_y_hint = 2.f;
} else if (gesture.GetType() == WebInputEvent::kGestureFlingStart &&
- gesture.source_device == blink::kWebGestureDeviceTouchscreen &&
+ gesture.SourceDevice() == blink::kWebGestureDeviceTouchscreen &&
!gesture.data.fling_start.velocity_x &&
!gesture.data.fling_start.velocity_y) {
// Ensure non-zero touchscreen fling velocities, as the router will
@@ -968,22 +971,30 @@ TEST_F(InputRouterImplTest, GestureTypesIgnoringAck) {
SimulateGestureEvent(type, blink::kWebGestureDeviceTouchscreen);
DispatchedMessages dispatched_messages = GetAndResetDispatchedMessages();
- if (type == WebInputEvent::kGestureScrollUpdate)
- EXPECT_EQ(2U, dispatched_messages.size());
- else
- EXPECT_EQ(1U, dispatched_messages.size());
- EXPECT_EQ(0U, disposition_handler_->GetAndResetAckCount());
- EXPECT_EQ(1, client_->in_flight_event_count());
- EXPECT_TRUE(HasPendingEvents());
- ASSERT_TRUE(
- dispatched_messages[dispatched_messages.size() - 1]->ToEvent());
-
- dispatched_messages[dispatched_messages.size() - 1]
- ->ToEvent()
- ->CallCallback(INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
+ if (type != WebInputEvent::kGestureFlingStart &&
+ type != WebInputEvent::kGestureFlingCancel) {
+ if (type == WebInputEvent::kGestureScrollUpdate)
+ EXPECT_EQ(2U, dispatched_messages.size());
+ else
+ EXPECT_EQ(1U, dispatched_messages.size());
+ EXPECT_EQ(0U, disposition_handler_->GetAndResetAckCount());
+ EXPECT_EQ(1, client_->in_flight_event_count());
+ EXPECT_TRUE(HasPendingEvents());
+ ASSERT_TRUE(
+ dispatched_messages[dispatched_messages.size() - 1]->ToEvent());
+
+ dispatched_messages[dispatched_messages.size() - 1]
+ ->ToEvent()
+ ->CallCallback(INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
+ }
EXPECT_EQ(0U, GetAndResetDispatchedMessages().size());
- EXPECT_EQ(1U, disposition_handler_->GetAndResetAckCount());
+ if (type == WebInputEvent::kGestureFlingCancel) {
+ // fling controller generates and sends a GSE while handling the GFC.
+ EXPECT_EQ(2U, disposition_handler_->GetAndResetAckCount());
+ } else {
+ EXPECT_EQ(1U, disposition_handler_->GetAndResetAckCount());
+ }
EXPECT_EQ(0, client_->in_flight_event_count());
EXPECT_FALSE(HasPendingEvents());
continue;
@@ -1674,10 +1685,10 @@ TEST_F(InputRouterImplTest, TouchpadPinchUpdate) {
ASSERT_EQ(WebInputEvent::kGesturePinchUpdate, input_event->GetType());
const WebGestureEvent* gesture_event =
static_cast<const WebGestureEvent*>(input_event);
- EXPECT_EQ(20, gesture_event->x);
- EXPECT_EQ(25, gesture_event->y);
- EXPECT_EQ(20, gesture_event->global_x);
- EXPECT_EQ(25, gesture_event->global_y);
+ EXPECT_EQ(20, gesture_event->PositionInWidget().x);
+ EXPECT_EQ(25, gesture_event->PositionInWidget().y);
+ EXPECT_EQ(20, gesture_event->PositionInScreen().x);
+ EXPECT_EQ(25, gesture_event->PositionInScreen().y);
dispatched_messages[0]->ToEvent()->CallCallback(
INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
@@ -1813,8 +1824,11 @@ void InputRouterImplTest::OverscrollDispatch() {
client_overscroll.accumulated_overscroll);
EXPECT_EQ(overscroll.latest_overscroll_delta,
client_overscroll.latest_overscroll_delta);
- EXPECT_EQ(overscroll.current_fling_velocity,
- client_overscroll.current_fling_velocity);
+ // With browser side fling, the fling velocity doesn't come from overscroll
+ // params of the renderer, instead the input router sets the
+ // params.current_fling_velocity based on the velocity received from the fling
+ // controller.
+ EXPECT_EQ(gfx::Vector2dF(), client_overscroll.current_fling_velocity);
DidOverscrollParams wheel_overscroll;
wheel_overscroll.accumulated_overscroll = gfx::Vector2dF(7, -7);
@@ -1838,8 +1852,11 @@ void InputRouterImplTest::OverscrollDispatch() {
client_overscroll.accumulated_overscroll);
EXPECT_EQ(wheel_overscroll.latest_overscroll_delta,
client_overscroll.latest_overscroll_delta);
- EXPECT_EQ(wheel_overscroll.current_fling_velocity,
- client_overscroll.current_fling_velocity);
+ // With browser side fling, the fling velocity doesn't come from overscroll
+ // params of the renderer, instead the input router sets the
+ // params.current_fling_velocity based on the velocity received from the fling
+ // controller.
+ EXPECT_EQ(gfx::Vector2dF(), client_overscroll.current_fling_velocity);
}
TEST_F(InputRouterImplTest, OverscrollDispatch) {
@@ -2136,17 +2153,17 @@ class InputRouterImplScaleGestureEventTest
InputRouterImplScaleGestureEventTest() {}
WebGestureEvent BuildGestureEvent(WebInputEvent::Type type,
- const gfx::Point& point) {
+ const gfx::PointF& point) {
WebGestureEvent event = SyntheticWebGestureEventBuilder::Build(
type, blink::kWebGestureDeviceTouchpad);
- event.global_x = event.x = point.x();
- event.global_y = event.y = point.y();
+ event.SetPositionInWidget(point);
+ event.SetPositionInScreen(point);
return event;
}
void TestTap(const std::string& name, WebInputEvent::Type type) {
SCOPED_TRACE(name);
- const gfx::Point orig(10, 20), scaled(20, 40);
+ const gfx::PointF orig(10, 20), scaled(20, 40);
WebGestureEvent event = BuildGestureEvent(type, orig);
event.data.tap.width = 30;
event.data.tap.height = 40;
@@ -2166,7 +2183,7 @@ class InputRouterImplScaleGestureEventTest
}
void TestLongPress(const std::string& name, WebInputEvent::Type type) {
- const gfx::Point orig(10, 20), scaled(20, 40);
+ const gfx::PointF orig(10, 20), scaled(20, 40);
WebGestureEvent event = BuildGestureEvent(type, orig);
event.data.long_press.width = 30;
event.data.long_press.height = 40;
@@ -2193,20 +2210,20 @@ class InputRouterImplScaleGestureEventTest
}
void TestLocationInSentEvent(const WebGestureEvent* sent_event,
- const gfx::Point& orig,
- const gfx::Point& scaled) {
- EXPECT_EQ(20, sent_event->x);
- EXPECT_EQ(40, sent_event->y);
- EXPECT_EQ(10, sent_event->global_x);
- EXPECT_EQ(20, sent_event->global_y);
+ const gfx::PointF& orig,
+ const gfx::PointF& scaled) {
+ EXPECT_EQ(20, sent_event->PositionInWidget().x);
+ EXPECT_EQ(40, sent_event->PositionInWidget().y);
+ EXPECT_EQ(10, sent_event->PositionInScreen().x);
+ EXPECT_EQ(20, sent_event->PositionInScreen().y);
}
void TestLocationInFilterEvent(const WebGestureEvent* filter_event,
- const gfx::Point& point) {
- EXPECT_EQ(10, filter_event->x);
- EXPECT_EQ(20, filter_event->y);
- EXPECT_EQ(10, filter_event->global_x);
- EXPECT_EQ(20, filter_event->global_y);
+ const gfx::PointF& point) {
+ EXPECT_EQ(10, filter_event->PositionInWidget().x);
+ EXPECT_EQ(20, filter_event->PositionInWidget().y);
+ EXPECT_EQ(10, filter_event->PositionInScreen().x);
+ EXPECT_EQ(20, filter_event->PositionInScreen().y);
}
private:
@@ -2246,7 +2263,7 @@ TEST_F(InputRouterImplScaleGestureEventTest, GestureScrollBegin) {
}
TEST_F(InputRouterImplScaleGestureEventTest, GesturePinchUpdate) {
- const gfx::Point orig(10, 20), scaled(20, 40);
+ const gfx::PointF orig(10, 20), scaled(20, 40);
SimulateGesturePinchUpdateEvent(1.5f, orig.x(), orig.y(), 0,
blink::kWebGestureDeviceTouchpad);
FlushGestureEvent(WebInputEvent::kGesturePinchUpdate);
@@ -2261,7 +2278,7 @@ TEST_F(InputRouterImplScaleGestureEventTest, GesturePinchUpdate) {
}
TEST_F(InputRouterImplScaleGestureEventTest, GestureTapDown) {
- const gfx::Point orig(10, 20), scaled(20, 40);
+ const gfx::PointF orig(10, 20), scaled(20, 40);
WebGestureEvent event =
BuildGestureEvent(WebInputEvent::kGestureTapDown, orig);
event.data.tap_down.width = 30;
@@ -2287,7 +2304,7 @@ TEST_F(InputRouterImplScaleGestureEventTest, GestureTapOthers) {
}
TEST_F(InputRouterImplScaleGestureEventTest, GestureShowPress) {
- const gfx::Point orig(10, 20), scaled(20, 40);
+ const gfx::PointF orig(10, 20), scaled(20, 40);
WebGestureEvent event =
BuildGestureEvent(WebInputEvent::kGestureShowPress, orig);
event.data.show_press.width = 30;
@@ -2314,22 +2331,22 @@ TEST_F(InputRouterImplScaleGestureEventTest, GestureLongPress) {
TEST_F(InputRouterImplScaleGestureEventTest, GestureTwoFingerTap) {
WebGestureEvent event = BuildGestureEvent(WebInputEvent::kGestureTwoFingerTap,
- gfx::Point(10, 20));
+ gfx::PointF(10, 20));
event.data.two_finger_tap.first_finger_width = 30;
event.data.two_finger_tap.first_finger_height = 40;
SimulateGestureEvent(event);
FlushGestureEvent(WebInputEvent::kGestureTwoFingerTap);
const WebGestureEvent* sent_event = GetSentWebInputEvent<WebGestureEvent>();
- EXPECT_EQ(20, sent_event->x);
- EXPECT_EQ(40, sent_event->y);
+ EXPECT_EQ(20, sent_event->PositionInWidget().x);
+ EXPECT_EQ(40, sent_event->PositionInWidget().y);
EXPECT_EQ(60, sent_event->data.two_finger_tap.first_finger_width);
EXPECT_EQ(80, sent_event->data.two_finger_tap.first_finger_height);
const WebGestureEvent* filter_event =
GetFilterWebInputEvent<WebGestureEvent>();
- EXPECT_EQ(10, filter_event->x);
- EXPECT_EQ(20, filter_event->y);
+ EXPECT_EQ(10, filter_event->PositionInWidget().x);
+ EXPECT_EQ(20, filter_event->PositionInWidget().y);
EXPECT_EQ(30, filter_event->data.two_finger_tap.first_finger_width);
EXPECT_EQ(40, filter_event->data.two_finger_tap.first_finger_height);
}
@@ -2346,28 +2363,36 @@ TEST_F(InputRouterImplScaleGestureEventTest, MAYBE_GestureFlingStart) {
10.f, 20.f, blink::kWebGestureDeviceTouchscreen));
FlushGestureEvent(WebInputEvent::kGestureScrollBegin);
- const gfx::Point orig(10, 20), scaled(20, 40);
+ const gfx::PointF orig(10, 20), scaled(20, 40);
WebGestureEvent event =
BuildGestureEvent(WebInputEvent::kGestureFlingStart, orig);
- // Set the source device to touchscreen to make sure that the event gets
- // dispatched to the renderer. When wheel scroll latching is enabled touchpad
- // flings are not dispatched to the renderer, instead they are handled on the
- // browser side.
- event.source_device = blink::kWebGestureDeviceTouchscreen;
+ event.SetSourceDevice(blink::kWebGestureDeviceTouchscreen);
event.data.fling_start.velocity_x = 30;
event.data.fling_start.velocity_y = 40;
SimulateGestureEvent(event);
- FlushGestureEvent(WebInputEvent::kGestureFlingStart);
+ // Fling events don't get sent to the renderer.
+ UpdateDispatchedMessages();
+ ASSERT_EQ(0u, dispatched_messages_.size());
- const WebGestureEvent* sent_event = GetSentWebInputEvent<WebGestureEvent>();
+ // Progress the fling and check the first GestureScrollUpdate generated by
+ // fling progress, note that |at(0)| is TouchScrollStarted.
+ base::TimeTicks progress_time =
+ base::TimeTicks::Now() + base::TimeDelta::FromMilliseconds(17);
+ input_router_->ProgressFling(progress_time);
+ UpdateDispatchedMessages();
+ ASSERT_EQ(2u, dispatched_messages_.size());
+ const WebGestureEvent* sent_event = static_cast<const WebGestureEvent*>(
+ dispatched_messages_[1]->ToEvent()->Event()->web_event.get());
TestLocationInSentEvent(sent_event, orig, scaled);
- EXPECT_EQ(60, sent_event->data.fling_start.velocity_x);
- EXPECT_EQ(80, sent_event->data.fling_start.velocity_y);
+ float sent_delta_x = sent_event->data.scroll_update.delta_x;
+ float sent_delta_y = sent_event->data.scroll_update.delta_y;
+ EXPECT_LT(0, sent_delta_x);
+ EXPECT_LT(0, sent_delta_y);
const WebGestureEvent* filter_event =
GetFilterWebInputEvent<WebGestureEvent>();
TestLocationInFilterEvent(filter_event, orig);
- EXPECT_EQ(30, filter_event->data.fling_start.velocity_x);
- EXPECT_EQ(40, filter_event->data.fling_start.velocity_y);
+ EXPECT_FLOAT_EQ(sent_delta_x, 2 * filter_event->data.scroll_update.delta_x);
+ EXPECT_FLOAT_EQ(sent_delta_y, 2 * filter_event->data.scroll_update.delta_y);
}
} // namespace content
diff --git a/chromium/content/browser/renderer_host/input/interaction_mq_dynamic_browsertest.cc b/chromium/content/browser/renderer_host/input/interaction_mq_dynamic_browsertest.cc
index 6a1c8fff238..76a8d8c78d9 100644
--- a/chromium/content/browser/renderer_host/input/interaction_mq_dynamic_browsertest.cc
+++ b/chromium/content/browser/renderer_host/input/interaction_mq_dynamic_browsertest.cc
@@ -31,11 +31,16 @@ class InteractionMediaQueriesDynamicTest : public ContentBrowserTest {
(defined(OS_ANDROID) && !defined(ADDRESS_SANITIZER))
IN_PROC_BROWSER_TEST_F(InteractionMediaQueriesDynamicTest,
PointerMediaQueriesDynamic) {
+ RenderViewHost* rvh = shell()->web_contents()->GetRenderViewHost();
+ ui::SetAvailablePointerAndHoverTypesForTesting(ui::POINTER_TYPE_NONE,
+ ui::HOVER_TYPE_NONE);
+ rvh->OnWebkitPreferencesChanged();
+
GURL test_url = GetTestUrl("", "interaction-mq-dynamic.html");
const base::string16 kSuccessTitle(base::ASCIIToUTF16("SUCCESS"));
TitleWatcher title_watcher(shell()->web_contents(), kSuccessTitle);
NavigateToURL(shell(), test_url);
- RenderViewHost* rvh = shell()->web_contents()->GetRenderViewHost();
+
ui::SetAvailablePointerAndHoverTypesForTesting(ui::POINTER_TYPE_COARSE,
ui::HOVER_TYPE_HOVER);
rvh->OnWebkitPreferencesChanged();
diff --git a/chromium/content/browser/renderer_host/input/legacy_input_router_impl.cc b/chromium/content/browser/renderer_host/input/legacy_input_router_impl.cc
index d0ea15b1fa8..9a96150ec70 100644
--- a/chromium/content/browser/renderer_host/input/legacy_input_router_impl.cc
+++ b/chromium/content/browser/renderer_host/input/legacy_input_router_impl.cc
@@ -10,7 +10,6 @@
#include "base/auto_reset.h"
#include "base/command_line.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/string_number_conversions.h"
#include "content/browser/renderer_host/input/gesture_event_queue.h"
@@ -129,7 +128,8 @@ void LegacyInputRouterImpl::SendKeyboardEvent(
void LegacyInputRouterImpl::SendGestureEvent(
const GestureEventWithLatencyInfo& original_gesture_event) {
- input_stream_validator_.Validate(original_gesture_event.event);
+ input_stream_validator_.Validate(original_gesture_event.event,
+ FlingCancellationIsDeferred());
GestureEventWithLatencyInfo gesture_event(original_gesture_event);
@@ -138,7 +138,7 @@ void LegacyInputRouterImpl::SendGestureEvent(
wheel_event_queue_.OnGestureScrollEvent(gesture_event);
- if (gesture_event.event.source_device ==
+ if (gesture_event.event.SourceDevice() ==
blink::kWebGestureDeviceTouchscreen) {
if (gesture_event.event.GetType() ==
blink::WebInputEvent::kGestureScrollBegin) {
@@ -208,13 +208,22 @@ void LegacyInputRouterImpl::BindHost(
}
void LegacyInputRouterImpl::ProgressFling(base::TimeTicks current_time) {
- gesture_event_queue_.ProgressFling(current_time);
+ current_fling_velocity_ = gesture_event_queue_.ProgressFling(current_time);
}
void LegacyInputRouterImpl::StopFling() {
gesture_event_queue_.StopFling();
}
+bool LegacyInputRouterImpl::FlingCancellationIsDeferred() {
+ return gesture_event_queue_.FlingCancellationIsDeferred();
+}
+
+void LegacyInputRouterImpl::DidStopFlingingOnBrowser() {
+ current_fling_velocity_ = gfx::Vector2dF();
+ client_->DidStopFlinging();
+}
+
bool LegacyInputRouterImpl::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(LegacyInputRouterImpl, message)
@@ -230,6 +239,8 @@ bool LegacyInputRouterImpl::OnMessageReceived(const IPC::Message& message) {
IPC_MESSAGE_HANDLER(InputHostMsg_SetWhiteListedTouchAction,
OnSetWhiteListedTouchAction)
IPC_MESSAGE_HANDLER(InputHostMsg_DidStopFlinging, OnDidStopFlinging)
+ IPC_MESSAGE_HANDLER(InputHostMsg_DidStartScrollingViewport,
+ OnDidStartScrollingViewport)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
@@ -268,6 +279,10 @@ void LegacyInputRouterImpl::OnFilteringTouchEvent(
output_stream_validator_.Validate(touch_event);
}
+bool LegacyInputRouterImpl::TouchscreenFlingInProgress() {
+ return gesture_event_queue_.TouchscreenFlingInProgress();
+}
+
void LegacyInputRouterImpl::OnGestureEventAck(
const GestureEventWithLatencyInfo& event,
InputEventAckSource ack_source,
@@ -288,6 +303,12 @@ void LegacyInputRouterImpl::SendGeneratedWheelEvent(
wheel_event.latency);
}
+void LegacyInputRouterImpl::SendGeneratedGestureScrollEvents(
+ const GestureEventWithLatencyInfo& gesture_event) {
+ client_->ForwardGestureEventWithLatencyInfo(gesture_event.event,
+ gesture_event.latency);
+}
+
void LegacyInputRouterImpl::SetNeedsBeginFrameForFlingProgress() {
client_->SetNeedsBeginFrameForFlingProgress();
}
@@ -452,7 +473,10 @@ void LegacyInputRouterImpl::OnInputEventAck(const InputEventAck& ack) {
void LegacyInputRouterImpl::OnDidOverscroll(
const ui::DidOverscrollParams& params) {
- client_->DidOverscroll(params);
+ // Touchpad and Touchscreen flings are handled on the browser side.
+ ui::DidOverscrollParams fling_updated_params = params;
+ fling_updated_params.current_fling_velocity = current_fling_velocity_;
+ client_->DidOverscroll(fling_updated_params);
}
void LegacyInputRouterImpl::OnMsgMoveCaretAck() {
@@ -523,6 +547,10 @@ void LegacyInputRouterImpl::OnDidStopFlinging() {
client_->DidStopFlinging();
}
+void LegacyInputRouterImpl::OnDidStartScrollingViewport() {
+ client_->DidStartScrollingViewport();
+}
+
void LegacyInputRouterImpl::ProcessInputEventAck(
WebInputEvent::Type event_type,
InputEventAckSource ack_source,
diff --git a/chromium/content/browser/renderer_host/input/legacy_input_router_impl.h b/chromium/content/browser/renderer_host/input/legacy_input_router_impl.h
index b762f814544..ca897e6dd5b 100644
--- a/chromium/content/browser/renderer_host/input/legacy_input_router_impl.h
+++ b/chromium/content/browser/renderer_host/input/legacy_input_router_impl.h
@@ -40,6 +40,8 @@ class InputDispositionHandler;
class InputRouterClient;
struct InputEventAck;
+class MockRenderWidgetHost;
+
// An implementation for browser input event routing based on
// Chrome IPC. This class is named "legacy" because it is largely tied to
// Chrome IPC which is deprecated. This class will be replaced with a Mojo
@@ -77,6 +79,8 @@ class CONTENT_EXPORT LegacyInputRouterImpl
bool frame_handler) override;
void ProgressFling(base::TimeTicks current_time) override;
void StopFling() override;
+ bool FlingCancellationIsDeferred() override;
+ void DidStopFlingingOnBrowser() override;
// IPC::Listener
bool OnMessageReceived(const IPC::Message& message) override;
@@ -91,6 +95,8 @@ class CONTENT_EXPORT LegacyInputRouterImpl
private:
friend class LegacyInputRouterImplTest;
+ friend class MockRenderWidgetHost;
+
FRIEND_TEST_ALL_PREFIXES(SitePerProcessHitTestBrowserTest,
SubframeTouchEventRouting);
FRIEND_TEST_ALL_PREFIXES(SitePerProcessHitTestBrowserTest,
@@ -110,6 +116,7 @@ class CONTENT_EXPORT LegacyInputRouterImpl
InputEventAckSource ack_source,
InputEventAckState ack_result) override;
void OnFilteringTouchEvent(const blink::WebTouchEvent& touch_event) override;
+ bool TouchscreenFlingInProgress() override;
// GestureEventFilterClient
void SendGestureEventImmediately(
@@ -121,6 +128,8 @@ class CONTENT_EXPORT LegacyInputRouterImpl
// FlingControllerClient
void SendGeneratedWheelEvent(
const MouseWheelEventWithLatencyInfo& wheel_event) override;
+ void SendGeneratedGestureScrollEvents(
+ const GestureEventWithLatencyInfo& gesture_event) override;
void SetNeedsBeginFrameForFlingProgress() override;
// MouseWheelEventQueueClient
@@ -168,6 +177,7 @@ class CONTENT_EXPORT LegacyInputRouterImpl
uint32_t unique_touch_event_id,
InputEventAckState ack_result);
void OnDidStopFlinging();
+ void OnDidStartScrollingViewport();
// Note: This function may result in |this| being deleted, and as such
// should be the last method called in any internal chain of event handling.
@@ -270,6 +280,8 @@ class CONTENT_EXPORT LegacyInputRouterImpl
// Last touch position relative to screen. Used to compute movementX/Y.
std::map<int, gfx::Point> global_touch_position_;
+ gfx::Vector2dF current_fling_velocity_;
+
DISALLOW_COPY_AND_ASSIGN(LegacyInputRouterImpl);
};
diff --git a/chromium/content/browser/renderer_host/input/legacy_input_router_impl_perftest.cc b/chromium/content/browser/renderer_host/input/legacy_input_router_impl_perftest.cc
index 0e3e7b1f569..97d32e7e5fc 100644
--- a/chromium/content/browser/renderer_host/input/legacy_input_router_impl_perftest.cc
+++ b/chromium/content/browser/renderer_host/input/legacy_input_router_impl_perftest.cc
@@ -98,6 +98,7 @@ class NullInputRouterClient : public InputRouterClient {
void OnSetWhiteListedTouchAction(
cc::TouchAction white_listed_touch_action) override {}
void DidStopFlinging() override {}
+ void DidStartScrollingViewport() override {}
void ForwardWheelEventWithLatencyInfo(
const blink::WebMouseWheelEvent& event,
const ui::LatencyInfo& latency_info) override {}
@@ -140,16 +141,14 @@ Gestures BuildScrollSequence(size_t steps,
WebGestureEvent gesture(WebInputEvent::kGestureScrollBegin,
WebInputEvent::kNoModifiers,
ui::EventTimeStampToSeconds(ui::EventTimeForNow()));
- gesture.x = origin.x();
- gesture.y = origin.y();
+ gesture.SetPositionInWidget(gfx::PointF(origin.x(), origin.y()));
gestures.push_back(gesture);
gesture.SetType(WebInputEvent::kGestureScrollUpdate);
gesture.data.scroll_update.delta_x = delta.x();
gesture.data.scroll_update.delta_y = delta.y();
for (size_t i = 0; i < steps; ++i) {
- gesture.x += delta.x();
- gesture.y += delta.y();
+ gesture.SetPositionInWidget(gesture.PositionInWidget() + delta);
gestures.push_back(gesture);
}
diff --git a/chromium/content/browser/renderer_host/input/legacy_input_router_impl_unittest.cc b/chromium/content/browser/renderer_host/input/legacy_input_router_impl_unittest.cc
index f9d617eba77..baa4ff3b31c 100644
--- a/chromium/content/browser/renderer_host/input/legacy_input_router_impl_unittest.cc
+++ b/chromium/content/browser/renderer_host/input/legacy_input_router_impl_unittest.cc
@@ -15,13 +15,11 @@
#include "base/command_line.h"
#include "base/location.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/scoped_feature_list.h"
-#include "base/test/scoped_task_environment.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
#include "cc/input/touch_action.h"
@@ -38,6 +36,7 @@
#include "content/public/common/content_switches.h"
#include "content/public/test/mock_render_process_host.h"
#include "content/public/test/test_browser_context.h"
+#include "content/public/test/test_browser_thread_bundle.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/events/base_event_utils.h"
#include "ui/events/blink/blink_features.h"
@@ -134,9 +133,7 @@ class LegacyInputRouterImplTest : public testing::Test {
LegacyInputRouterImplTest(
WheelScrollingMode wheel_scrolling_mode = kWheelScrollLatching)
: wheel_scroll_latching_enabled_(wheel_scrolling_mode !=
- kWheelScrollingModeNone),
- scoped_task_environment_(
- base::test::ScopedTaskEnvironment::MainThreadType::UI) {
+ kWheelScrollingModeNone) {
if (wheel_scrolling_mode == kAsyncWheelEvents) {
feature_list_.InitWithFeatures({features::kTouchpadAndWheelScrollLatching,
features::kAsyncWheelEvents},
@@ -253,14 +250,14 @@ class LegacyInputRouterImplTest : public testing::Test {
void SimulateGestureEvent(WebGestureEvent gesture) {
if (gesture.GetType() == WebInputEvent::kGestureScrollBegin &&
- gesture.source_device == blink::kWebGestureDeviceTouchscreen &&
+ gesture.SourceDevice() == blink::kWebGestureDeviceTouchscreen &&
!gesture.data.scroll_begin.delta_x_hint &&
!gesture.data.scroll_begin.delta_y_hint) {
// Ensure non-zero scroll-begin offset-hint to make the event sane,
// prevents unexpected filtering at TouchActionFilter.
gesture.data.scroll_begin.delta_y_hint = 2.f;
} else if (gesture.GetType() == WebInputEvent::kGestureFlingStart &&
- gesture.source_device == blink::kWebGestureDeviceTouchscreen &&
+ gesture.SourceDevice() == blink::kWebGestureDeviceTouchscreen &&
!gesture.data.fling_start.velocity_x &&
!gesture.data.fling_start.velocity_y) {
// Ensure non-zero touchscreen fling velocities, as the router will
@@ -398,7 +395,7 @@ class LegacyInputRouterImplTest : public testing::Test {
bool wheel_scroll_latching_enabled_;
private:
- base::test::ScopedTaskEnvironment scoped_task_environment_;
+ TestBrowserThreadBundle thread_bundle_;
SyntheticWebTouchEvent touch_event_;
base::test::ScopedFeatureList vsync_feature_list_;
@@ -1085,17 +1082,31 @@ TEST_F(LegacyInputRouterImplTest, GestureTypesIgnoringAck) {
WebInputEvent::Type type = eventTypes[i];
if (ShouldBlockEventStream(GetEventWithType(type))) {
SimulateGestureEvent(type, blink::kWebGestureDeviceTouchscreen);
- if (type == WebInputEvent::kGestureScrollUpdate)
- EXPECT_EQ(2U, GetSentMessageCountAndResetSink());
- else
+ if (type == WebInputEvent::kGestureFlingStart) {
+ // Fling start event is not sent to the renderer.
+ EXPECT_EQ(0U, GetSentMessageCountAndResetSink());
+ EXPECT_EQ(0U, disposition_handler_->GetAndResetAckCount());
+ } else if (type == WebInputEvent::kGestureFlingCancel) {
+ // The fling controller processes the GFC to generate and send a GSE.
EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
- EXPECT_EQ(0U, disposition_handler_->GetAndResetAckCount());
- EXPECT_EQ(1, client_->in_flight_event_count());
- EXPECT_TRUE(HasPendingEvents());
-
- SendInputEventACK(type, INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
- EXPECT_EQ(0U, GetSentMessageCountAndResetSink());
- EXPECT_EQ(1U, disposition_handler_->GetAndResetAckCount());
+ EXPECT_EQ(1U, disposition_handler_->GetAndResetAckCount());
+ EXPECT_EQ(WebInputEvent::kGestureScrollEnd,
+ disposition_handler_->acked_gesture_event().GetType());
+ } else { // type!=WebInputEvent::kGestureFlingStart && type !=
+ // WebInputEvent::kGestureFlingCancel)
+ if (type == WebInputEvent::kGestureScrollUpdate)
+ EXPECT_EQ(2U, GetSentMessageCountAndResetSink());
+ else
+ EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
+ EXPECT_EQ(0U, disposition_handler_->GetAndResetAckCount());
+ EXPECT_EQ(1, client_->in_flight_event_count());
+ EXPECT_TRUE(HasPendingEvents());
+
+ SendInputEventACK(type, INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
+
+ EXPECT_EQ(0U, GetSentMessageCountAndResetSink());
+ EXPECT_EQ(1U, disposition_handler_->GetAndResetAckCount());
+ }
EXPECT_EQ(0, client_->in_flight_event_count());
EXPECT_FALSE(HasPendingEvents());
continue;
@@ -1669,10 +1680,10 @@ TEST_F(LegacyInputRouterImplTest, TouchpadPinchUpdate) {
ASSERT_EQ(WebInputEvent::kGesturePinchUpdate, input_event->GetType());
const WebGestureEvent* gesture_event =
static_cast<const WebGestureEvent*>(input_event);
- EXPECT_EQ(20, gesture_event->x);
- EXPECT_EQ(25, gesture_event->y);
- EXPECT_EQ(20, gesture_event->global_x);
- EXPECT_EQ(25, gesture_event->global_y);
+ EXPECT_EQ(20, gesture_event->PositionInWidget().x);
+ EXPECT_EQ(25, gesture_event->PositionInWidget().y);
+ EXPECT_EQ(20, gesture_event->PositionInScreen().x);
+ EXPECT_EQ(25, gesture_event->PositionInScreen().y);
EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
// Indicate that the wheel event was unhandled.
@@ -1800,8 +1811,11 @@ void LegacyInputRouterImplTest::OverscrollDispatch() {
client_overscroll.accumulated_overscroll);
EXPECT_EQ(overscroll.latest_overscroll_delta,
client_overscroll.latest_overscroll_delta);
- EXPECT_EQ(overscroll.current_fling_velocity,
- client_overscroll.current_fling_velocity);
+ // With browser side fling, the fling velocity doesn't come from overscroll
+ // params of the renderer, instead the input router sets the
+ // params.current_fling_velocity based on the velocity received from the fling
+ // controller.
+ EXPECT_EQ(gfx::Vector2dF(), client_overscroll.current_fling_velocity);
DidOverscrollParams wheel_overscroll;
wheel_overscroll.accumulated_overscroll = gfx::Vector2dF(7, -7);
@@ -1822,8 +1836,11 @@ void LegacyInputRouterImplTest::OverscrollDispatch() {
client_overscroll.accumulated_overscroll);
EXPECT_EQ(wheel_overscroll.latest_overscroll_delta,
client_overscroll.latest_overscroll_delta);
- EXPECT_EQ(wheel_overscroll.current_fling_velocity,
- client_overscroll.current_fling_velocity);
+ // With browser side fling, the fling velocity doesn't come from overscroll
+ // params of the renderer, instead the input router sets the
+ // params.current_fling_velocity based on the velocity received from the fling
+ // controller.
+ EXPECT_EQ(gfx::Vector2dF(), client_overscroll.current_fling_velocity);
}
TEST_F(LegacyInputRouterImplTest, OverscrollDispatch) {
OverscrollDispatch();
@@ -2094,17 +2111,17 @@ class LegacyInputRouterImplScaleGestureEventTest
LegacyInputRouterImplScaleGestureEventTest() {}
WebGestureEvent BuildGestureEvent(WebInputEvent::Type type,
- const gfx::Point& point) {
+ const gfx::PointF& point) {
WebGestureEvent event = SyntheticWebGestureEventBuilder::Build(
type, blink::kWebGestureDeviceTouchpad);
- event.global_x = event.x = point.x();
- event.global_y = event.y = point.y();
+ event.SetPositionInWidget(point);
+ event.SetPositionInScreen(point);
return event;
}
void TestTap(const std::string& name, WebInputEvent::Type type) {
SCOPED_TRACE(name);
- const gfx::Point orig(10, 20), scaled(20, 40);
+ const gfx::PointF orig(10, 20), scaled(20, 40);
WebGestureEvent event = BuildGestureEvent(type, orig);
event.data.tap.width = 30;
event.data.tap.height = 40;
@@ -2125,7 +2142,7 @@ class LegacyInputRouterImplScaleGestureEventTest
}
void TestLongPress(const std::string& name, WebInputEvent::Type type) {
- const gfx::Point orig(10, 20), scaled(20, 40);
+ const gfx::PointF orig(10, 20), scaled(20, 40);
WebGestureEvent event = BuildGestureEvent(type, orig);
event.data.long_press.width = 30;
event.data.long_press.height = 40;
@@ -2150,20 +2167,20 @@ class LegacyInputRouterImplScaleGestureEventTest
}
void TestLocationInSentEvent(const WebGestureEvent* sent_event,
- const gfx::Point& orig,
- const gfx::Point& scaled) {
- EXPECT_EQ(20, sent_event->x);
- EXPECT_EQ(40, sent_event->y);
- EXPECT_EQ(10, sent_event->global_x);
- EXPECT_EQ(20, sent_event->global_y);
+ const gfx::PointF& orig,
+ const gfx::PointF& scaled) {
+ EXPECT_EQ(20, sent_event->PositionInWidget().x);
+ EXPECT_EQ(40, sent_event->PositionInWidget().y);
+ EXPECT_EQ(10, sent_event->PositionInScreen().x);
+ EXPECT_EQ(20, sent_event->PositionInScreen().y);
}
void TestLocationInFilterEvent(const WebGestureEvent* filter_event,
- const gfx::Point& point) {
- EXPECT_EQ(10, filter_event->x);
- EXPECT_EQ(20, filter_event->y);
- EXPECT_EQ(10, filter_event->global_x);
- EXPECT_EQ(20, filter_event->global_y);
+ const gfx::PointF& point) {
+ EXPECT_EQ(10, filter_event->PositionInWidget().x);
+ EXPECT_EQ(20, filter_event->PositionInWidget().y);
+ EXPECT_EQ(10, filter_event->PositionInScreen().x);
+ EXPECT_EQ(20, filter_event->PositionInScreen().y);
}
private:
@@ -2201,7 +2218,7 @@ TEST_F(LegacyInputRouterImplScaleGestureEventTest, GestureScrollBegin) {
}
TEST_F(LegacyInputRouterImplScaleGestureEventTest, GesturePinchUpdate) {
- const gfx::Point orig(10, 20), scaled(20, 40);
+ const gfx::PointF orig(10, 20), scaled(20, 40);
SimulateGesturePinchUpdateEvent(1.5f, orig.x(), orig.y(), 0,
blink::kWebGestureDeviceTouchpad);
FlushGestureEvent(WebInputEvent::kGesturePinchUpdate);
@@ -2216,7 +2233,7 @@ TEST_F(LegacyInputRouterImplScaleGestureEventTest, GesturePinchUpdate) {
}
TEST_F(LegacyInputRouterImplScaleGestureEventTest, GestureTapDown) {
- const gfx::Point orig(10, 20), scaled(20, 40);
+ const gfx::PointF orig(10, 20), scaled(20, 40);
WebGestureEvent event =
BuildGestureEvent(WebInputEvent::kGestureTapDown, orig);
event.data.tap_down.width = 30;
@@ -2242,7 +2259,7 @@ TEST_F(LegacyInputRouterImplScaleGestureEventTest, GestureTapOthers) {
}
TEST_F(LegacyInputRouterImplScaleGestureEventTest, GestureShowPress) {
- const gfx::Point orig(10, 20), scaled(20, 40);
+ const gfx::PointF orig(10, 20), scaled(20, 40);
WebGestureEvent event =
BuildGestureEvent(WebInputEvent::kGestureShowPress, orig);
event.data.show_press.width = 30;
@@ -2268,21 +2285,21 @@ TEST_F(LegacyInputRouterImplScaleGestureEventTest, GestureLongPress) {
TEST_F(LegacyInputRouterImplScaleGestureEventTest, GestureTwoFingerTap) {
WebGestureEvent event = BuildGestureEvent(WebInputEvent::kGestureTwoFingerTap,
- gfx::Point(10, 20));
+ gfx::PointF(10, 20));
event.data.two_finger_tap.first_finger_width = 30;
event.data.two_finger_tap.first_finger_height = 40;
SimulateGestureEvent(event);
const WebGestureEvent* sent_event = GetSentWebInputEvent<WebGestureEvent>();
- EXPECT_EQ(20, sent_event->x);
- EXPECT_EQ(40, sent_event->y);
+ EXPECT_EQ(20, sent_event->PositionInWidget().x);
+ EXPECT_EQ(40, sent_event->PositionInWidget().y);
EXPECT_EQ(60, sent_event->data.two_finger_tap.first_finger_width);
EXPECT_EQ(80, sent_event->data.two_finger_tap.first_finger_height);
const WebGestureEvent* filter_event =
GetFilterWebInputEvent<WebGestureEvent>();
- EXPECT_EQ(10, filter_event->x);
- EXPECT_EQ(20, filter_event->y);
+ EXPECT_EQ(10, filter_event->PositionInWidget().x);
+ EXPECT_EQ(20, filter_event->PositionInWidget().y);
EXPECT_EQ(30, filter_event->data.two_finger_tap.first_finger_width);
EXPECT_EQ(40, filter_event->data.two_finger_tap.first_finger_height);
}
@@ -2299,28 +2316,35 @@ TEST_F(LegacyInputRouterImplScaleGestureEventTest, MAYBE_GestureFlingStart) {
10.f, 20.f, blink::kWebGestureDeviceTouchscreen));
process_->sink().ClearMessages();
- const gfx::Point orig(10, 20), scaled(20, 40);
+ const gfx::PointF orig(10, 20), scaled(20, 40);
WebGestureEvent event =
BuildGestureEvent(WebInputEvent::kGestureFlingStart, orig);
- // Set the source device to touchscreen to make sure that the event gets
- // dispatched to the renderer. When wheel scroll latching is enabled touchpad
- // flings are not dispatched to the renderer, instead they are handled on the
- // browser side.
- event.source_device = blink::kWebGestureDeviceTouchscreen;
+ event.SetSourceDevice(blink::kWebGestureDeviceTouchscreen);
event.data.fling_start.velocity_x = 30;
event.data.fling_start.velocity_y = 40;
SimulateGestureEvent(event);
-
- const WebGestureEvent* sent_event = GetSentWebInputEvent<WebGestureEvent>();
+ // Fling events don't get sent to the renderer.
+ EXPECT_EQ(0u, process_->sink().message_count());
+
+ // Progress the fling and check the first GestureScrollUpdate generated by
+ // fling progress, note that |at(0)| is TouchScrollStarted.
+ base::TimeTicks progress_time =
+ base::TimeTicks::Now() + base::TimeDelta::FromMilliseconds(17);
+ input_router_->ProgressFling(progress_time);
+ EXPECT_EQ(2u, process_->sink().message_count());
+ const WebGestureEvent* sent_event = static_cast<const WebGestureEvent*>(
+ GetInputEventFromMessage(*process_->sink().GetMessageAt(1)));
TestLocationInSentEvent(sent_event, orig, scaled);
- EXPECT_EQ(60, sent_event->data.fling_start.velocity_x);
- EXPECT_EQ(80, sent_event->data.fling_start.velocity_y);
+ float sent_delta_x = sent_event->data.scroll_update.delta_x;
+ float sent_delta_y = sent_event->data.scroll_update.delta_y;
+ EXPECT_LT(0, sent_delta_x);
+ EXPECT_LT(0, sent_delta_y);
const WebGestureEvent* filter_event =
GetFilterWebInputEvent<WebGestureEvent>();
TestLocationInFilterEvent(filter_event, orig);
- EXPECT_EQ(30, filter_event->data.fling_start.velocity_x);
- EXPECT_EQ(40, filter_event->data.fling_start.velocity_y);
+ EXPECT_FLOAT_EQ(sent_delta_x, 2 * filter_event->data.scroll_update.delta_x);
+ EXPECT_FLOAT_EQ(sent_delta_y, 2 * filter_event->data.scroll_update.delta_y);
}
} // namespace content
diff --git a/chromium/content/browser/renderer_host/input/legacy_ipc_widget_input_handler.cc b/chromium/content/browser/renderer_host/input/legacy_ipc_widget_input_handler.cc
index afe47ceaba1..a620b5931fc 100644
--- a/chromium/content/browser/renderer_host/input/legacy_ipc_widget_input_handler.cc
+++ b/chromium/content/browser/renderer_host/input/legacy_ipc_widget_input_handler.cc
@@ -13,24 +13,6 @@
namespace content {
-namespace {
-
-std::vector<blink::WebImeTextSpan> ConvertToBlinkImeTextSpan(
- const std::vector<ui::ImeTextSpan>& ui_ime_text_spans) {
- std::vector<blink::WebImeTextSpan> ime_text_spans;
- for (const auto& ime_text_span : ui_ime_text_spans) {
- ime_text_spans.emplace_back(blink::WebImeTextSpan(
- ConvertUiImeTextSpanTypeToWebType(ime_text_span.type),
- ime_text_span.start_offset, ime_text_span.end_offset,
- ime_text_span.underline_color, ime_text_span.thick,
- ime_text_span.background_color,
- ime_text_span.suggestion_highlight_color, ime_text_span.suggestions));
- }
- return ime_text_spans;
-}
-
-} // namespace
-
LegacyIPCWidgetInputHandler::LegacyIPCWidgetInputHandler(
LegacyInputRouterImpl* input_router)
: input_router_(input_router) {}
@@ -61,7 +43,7 @@ void LegacyIPCWidgetInputHandler::ImeSetComposition(
int32_t start,
int32_t end) {
std::vector<blink::WebImeTextSpan> ime_text_spans =
- ConvertToBlinkImeTextSpan(ui_ime_text_spans);
+ ConvertUiImeTextSpansToBlinkImeTextSpans(ui_ime_text_spans);
SendInput(std::make_unique<InputMsg_ImeSetComposition>(
input_router_->routing_id(), text, ime_text_spans, range, start, end));
}
@@ -72,7 +54,7 @@ void LegacyIPCWidgetInputHandler::ImeCommitText(
const gfx::Range& range,
int32_t relative_cursor_position) {
std::vector<blink::WebImeTextSpan> ime_text_spans =
- ConvertToBlinkImeTextSpan(ui_ime_text_spans);
+ ConvertUiImeTextSpansToBlinkImeTextSpans(ui_ime_text_spans);
SendInput(std::make_unique<InputMsg_ImeCommitText>(
input_router_->routing_id(), text, ime_text_spans, range,
relative_cursor_position));
diff --git a/chromium/content/browser/renderer_host/input/main_thread_event_queue_browsertest.cc b/chromium/content/browser/renderer_host/input/main_thread_event_queue_browsertest.cc
index eb216341d07..4dc17f33d2b 100644
--- a/chromium/content/browser/renderer_host/input/main_thread_event_queue_browsertest.cc
+++ b/chromium/content/browser/renderer_host/input/main_thread_event_queue_browsertest.cc
@@ -25,7 +25,7 @@
#include "content/public/test/content_browser_test_utils.h"
#include "content/public/test/test_utils.h"
#include "content/shell/browser/shell.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/events/event_switches.h"
#include "ui/latency/latency_info.h"
diff --git a/chromium/content/browser/renderer_host/input/mock_input_router_client.cc b/chromium/content/browser/renderer_host/input/mock_input_router_client.cc
index 203b66833b0..c971609225e 100644
--- a/chromium/content/browser/renderer_host/input/mock_input_router_client.cc
+++ b/chromium/content/browser/renderer_host/input/mock_input_router_client.cc
@@ -63,6 +63,8 @@ void MockInputRouterClient::OnSetWhiteListedTouchAction(
void MockInputRouterClient::DidStopFlinging() {
}
+void MockInputRouterClient::DidStartScrollingViewport() {}
+
void MockInputRouterClient::SetNeedsBeginFrameForFlingProgress() {}
void MockInputRouterClient::ForwardGestureEventWithLatencyInfo(
diff --git a/chromium/content/browser/renderer_host/input/mock_input_router_client.h b/chromium/content/browser/renderer_host/input/mock_input_router_client.h
index 5ce892b7ad0..057c571d914 100644
--- a/chromium/content/browser/renderer_host/input/mock_input_router_client.h
+++ b/chromium/content/browser/renderer_host/input/mock_input_router_client.h
@@ -32,6 +32,7 @@ class MockInputRouterClient : public InputRouterClient {
void DidOverscroll(const ui::DidOverscrollParams& params) override;
void OnSetWhiteListedTouchAction(cc::TouchAction touch_action) override;
void DidStopFlinging() override;
+ void DidStartScrollingViewport() override;
void SetNeedsBeginFrameForFlingProgress() override;
void ForwardWheelEventWithLatencyInfo(
const blink::WebMouseWheelEvent& wheel_event,
diff --git a/chromium/content/browser/renderer_host/input/motion_event_web.h b/chromium/content/browser/renderer_host/input/motion_event_web.h
index 67cd606188d..de4f1225f8c 100644
--- a/chromium/content/browser/renderer_host/input/motion_event_web.h
+++ b/chromium/content/browser/renderer_host/input/motion_event_web.h
@@ -10,7 +10,7 @@
#include "base/macros.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebTouchEvent.h"
+#include "third_party/blink/public/platform/web_touch_event.h"
#include "ui/events/gesture_detection/motion_event.h"
namespace content {
diff --git a/chromium/content/browser/renderer_host/input/mouse_wheel_event_queue.cc b/chromium/content/browser/renderer_host/input/mouse_wheel_event_queue.cc
index 5d5beadba93..57993daaf3d 100644
--- a/chromium/content/browser/renderer_host/input/mouse_wheel_event_queue.cc
+++ b/chromium/content/browser/renderer_host/input/mouse_wheel_event_queue.cc
@@ -4,7 +4,6 @@
#include "content/browser/renderer_host/input/mouse_wheel_event_queue.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/trace_event/trace_event.h"
#include "content/common/input/input_event_dispatch_type.h"
@@ -96,15 +95,13 @@ void MouseWheelEventQueue::ProcessMouseWheelAck(
scrolling_device_ == blink::kWebGestureDeviceTouchpad)) {
WebGestureEvent scroll_update(
WebInputEvent::kGestureScrollUpdate, WebInputEvent::kNoModifiers,
- event_sent_for_gesture_ack_->event.TimeStampSeconds());
-
- scroll_update.x = event_sent_for_gesture_ack_->event.PositionInWidget().x;
- scroll_update.y = event_sent_for_gesture_ack_->event.PositionInWidget().y;
- scroll_update.global_x =
- event_sent_for_gesture_ack_->event.PositionInScreen().x;
- scroll_update.global_y =
- event_sent_for_gesture_ack_->event.PositionInScreen().y;
- scroll_update.source_device = blink::kWebGestureDeviceTouchpad;
+ event_sent_for_gesture_ack_->event.TimeStampSeconds(),
+ blink::kWebGestureDeviceTouchpad);
+
+ scroll_update.SetPositionInWidget(
+ event_sent_for_gesture_ack_->event.PositionInWidget());
+ scroll_update.SetPositionInScreen(
+ event_sent_for_gesture_ack_->event.PositionInScreen());
scroll_update.resending_plugin_id = -1;
// Swap X & Y if Shift is down and when there is no horizontal movement.
@@ -267,8 +264,8 @@ void MouseWheelEventQueue::OnGestureScrollEvent(
const GestureEventWithLatencyInfo& gesture_event) {
if (gesture_event.event.GetType() ==
blink::WebInputEvent::kGestureScrollBegin) {
- scrolling_device_ = gesture_event.event.source_device;
- } else if (scrolling_device_ == gesture_event.event.source_device &&
+ scrolling_device_ = gesture_event.event.SourceDevice();
+ } else if (scrolling_device_ == gesture_event.event.SourceDevice() &&
(gesture_event.event.GetType() ==
blink::WebInputEvent::kGestureScrollEnd ||
(gesture_event.event.GetType() ==
diff --git a/chromium/content/browser/renderer_host/input/mouse_wheel_event_queue.h b/chromium/content/browser/renderer_host/input/mouse_wheel_event_queue.h
index a724bb7661c..106f166df55 100644
--- a/chromium/content/browser/renderer_host/input/mouse_wheel_event_queue.h
+++ b/chromium/content/browser/renderer_host/input/mouse_wheel_event_queue.h
@@ -13,7 +13,7 @@
#include "content/common/content_export.h"
#include "content/public/common/input_event_ack_source.h"
#include "content/public/common/input_event_ack_state.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
namespace content {
diff --git a/chromium/content/browser/renderer_host/input/mouse_wheel_event_queue_unittest.cc b/chromium/content/browser/renderer_host/input/mouse_wheel_event_queue_unittest.cc
index 9db17edb664..7460716e0de 100644
--- a/chromium/content/browser/renderer_host/input/mouse_wheel_event_queue_unittest.cc
+++ b/chromium/content/browser/renderer_host/input/mouse_wheel_event_queue_unittest.cc
@@ -21,7 +21,7 @@
#include "content/common/input/synthetic_web_input_event_builders.h"
#include "content/public/common/content_features.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/events/base_event_utils.h"
using blink::WebGestureEvent;
@@ -38,10 +38,10 @@ const float kWheelScrollGlobalY = 72;
#define EXPECT_GESTURE_SCROLL_BEGIN_IMPL(event) \
EXPECT_EQ(WebInputEvent::kGestureScrollBegin, event->GetType()); \
- EXPECT_EQ(kWheelScrollX, event->x); \
- EXPECT_EQ(kWheelScrollY, event->y); \
- EXPECT_EQ(kWheelScrollGlobalX, event->global_x); \
- EXPECT_EQ(kWheelScrollGlobalY, event->global_y); \
+ EXPECT_EQ(kWheelScrollX, event->PositionInWidget().x); \
+ EXPECT_EQ(kWheelScrollY, event->PositionInWidget().y); \
+ EXPECT_EQ(kWheelScrollGlobalX, event->PositionInScreen().x); \
+ EXPECT_EQ(kWheelScrollGlobalY, event->PositionInScreen().y); \
EXPECT_EQ(scroll_units, event->data.scroll_begin.delta_hint_units);
#define EXPECT_GESTURE_SCROLL_BEGIN(event) \
@@ -77,10 +77,10 @@ const float kWheelScrollGlobalY = 72;
#define EXPECT_GESTURE_SCROLL_UPDATE_IMPL(event) \
EXPECT_EQ(WebInputEvent::kGestureScrollUpdate, event->GetType()); \
EXPECT_EQ(scroll_units, event->data.scroll_update.delta_units); \
- EXPECT_EQ(kWheelScrollX, event->x); \
- EXPECT_EQ(kWheelScrollY, event->y); \
- EXPECT_EQ(kWheelScrollGlobalX, event->global_x); \
- EXPECT_EQ(kWheelScrollGlobalY, event->global_y);
+ EXPECT_EQ(kWheelScrollX, event->PositionInWidget().x); \
+ EXPECT_EQ(kWheelScrollY, event->PositionInWidget().y); \
+ EXPECT_EQ(kWheelScrollGlobalX, event->PositionInScreen().x); \
+ EXPECT_EQ(kWheelScrollGlobalY, event->PositionInScreen().y);
#define EXPECT_GESTURE_SCROLL_UPDATE(event) \
EXPECT_GESTURE_SCROLL_UPDATE_IMPL(event); \
@@ -100,10 +100,10 @@ const float kWheelScrollGlobalY = 72;
#define EXPECT_GESTURE_SCROLL_END_IMPL(event) \
EXPECT_EQ(WebInputEvent::kGestureScrollEnd, event->GetType()); \
EXPECT_EQ(scroll_units, event->data.scroll_end.delta_units); \
- EXPECT_EQ(kWheelScrollX, event->x); \
- EXPECT_EQ(kWheelScrollY, event->y); \
- EXPECT_EQ(kWheelScrollGlobalX, event->global_x); \
- EXPECT_EQ(kWheelScrollGlobalY, event->global_y);
+ EXPECT_EQ(kWheelScrollX, event->PositionInWidget().x); \
+ EXPECT_EQ(kWheelScrollY, event->PositionInWidget().y); \
+ EXPECT_EQ(kWheelScrollGlobalX, event->PositionInScreen().x); \
+ EXPECT_EQ(kWheelScrollGlobalY, event->PositionInScreen().y);
#define EXPECT_GESTURE_SCROLL_END(event) \
EXPECT_GESTURE_SCROLL_END_IMPL(event); \
@@ -344,8 +344,8 @@ class MouseWheelEventQueueTest
void SendGestureEvent(WebInputEvent::Type type) {
WebGestureEvent event(type, WebInputEvent::kNoModifiers,
- ui::EventTimeStampToSeconds(ui::EventTimeForNow()));
- event.source_device = blink::kWebGestureDeviceTouchscreen;
+ ui::EventTimeStampToSeconds(ui::EventTimeForNow()),
+ blink::kWebGestureDeviceTouchscreen);
queue_->OnGestureScrollEvent(
GestureEventWithLatencyInfo(event, ui::LatencyInfo()));
}
diff --git a/chromium/content/browser/renderer_host/input/mouse_wheel_phase_handler.cc b/chromium/content/browser/renderer_host/input/mouse_wheel_phase_handler.cc
index dab166dc6a5..acf8f012a83 100644
--- a/chromium/content/browser/renderer_host/input/mouse_wheel_phase_handler.cc
+++ b/chromium/content/browser/renderer_host/input/mouse_wheel_phase_handler.cc
@@ -11,10 +11,8 @@
namespace content {
MouseWheelPhaseHandler::MouseWheelPhaseHandler(
- RenderWidgetHostImpl* const host,
RenderWidgetHostViewBase* const host_view)
- : host_(host),
- host_view_(host_view),
+ : host_view_(host_view),
mouse_wheel_end_dispatch_timeout_(kDefaultMouseWheelLatchingTransaction),
scroll_phase_state_(SCROLL_STATE_UNKNOWN) {}
@@ -50,8 +48,9 @@ void MouseWheelPhaseHandler::AddPhaseIfNeededAndScheduleEndEvent(
mouse_wheel_event.has_synthetic_phase = true;
// Break the latching when the location difference between the current
// and the initial wheel event positions exceeds the maximum allowed
- // threshold.
+ // threshold or when the event modifiers have changed.
if (!IsWithinSlopRegion(mouse_wheel_event) ||
+ HasDifferentModifiers(mouse_wheel_event) ||
ShouldBreakLatchingDueToDirectionChange(mouse_wheel_event)) {
DispatchPendingWheelEndEvent();
}
@@ -97,7 +96,7 @@ void MouseWheelPhaseHandler::DispatchPendingWheelEndEvent() {
base::Closure task = mouse_wheel_end_dispatch_timer_.user_task();
mouse_wheel_end_dispatch_timer_.Stop();
- task.Run();
+ std::move(task).Run();
}
void MouseWheelPhaseHandler::IgnorePendingWheelEndEvent() {
@@ -110,9 +109,14 @@ void MouseWheelPhaseHandler::ResetScrollSequence() {
void MouseWheelPhaseHandler::SendWheelEndIfNeeded() {
if (scroll_phase_state_ == SCROLL_IN_PROGRESS) {
- DCHECK(host_);
- bool should_route_event =
- host_->delegate() && host_->delegate()->GetInputEventRouter();
+ RenderWidgetHostImpl* widget_host = host_view_->host();
+ if (!widget_host) {
+ ResetScrollSequence();
+ return;
+ }
+
+ bool should_route_event = widget_host->delegate() &&
+ widget_host->delegate()->GetInputEventRouter();
SendSyntheticWheelEventWithPhaseEnded(should_route_event);
}
@@ -137,7 +141,12 @@ void MouseWheelPhaseHandler::SendSyntheticWheelEventWithPhaseEnded(
blink::WebInputEvent::DispatchType::kEventNonBlocking;
if (should_route_event) {
- host_->delegate()->GetInputEventRouter()->RouteMouseWheelEvent(
+ RenderWidgetHostImpl* widget_host = host_view_->host();
+ if (!widget_host || !widget_host->delegate() ||
+ !widget_host->delegate()->GetInputEventRouter())
+ return;
+
+ widget_host->delegate()->GetInputEventRouter()->RouteMouseWheelEvent(
host_view_, &last_mouse_wheel_event_,
ui::LatencyInfo(ui::SourceEventType::WHEEL));
} else {
@@ -156,7 +165,10 @@ void MouseWheelPhaseHandler::ScheduleMouseWheelEndDispatching(
}
bool MouseWheelPhaseHandler::IsWithinSlopRegion(
- blink::WebMouseWheelEvent wheel_event) const {
+ const blink::WebMouseWheelEvent& wheel_event) const {
+ // This function is called to check if breaking timer-based wheel scroll
+ // latching sequence is needed or not, and timer-based wheel scroll latching
+ // happens only when scroll state is unknown.
DCHECK(scroll_phase_state_ == SCROLL_STATE_UNKNOWN);
gfx::Vector2dF current_wheel_location(wheel_event.PositionInWidget().x,
wheel_event.PositionInWidget().y);
@@ -164,6 +176,15 @@ bool MouseWheelPhaseHandler::IsWithinSlopRegion(
kWheelLatchingSlopRegion * kWheelLatchingSlopRegion;
}
+bool MouseWheelPhaseHandler::HasDifferentModifiers(
+ const blink::WebMouseWheelEvent& wheel_event) const {
+ // This function is called to check if breaking timer-based wheel scroll
+ // latching sequence is needed or not, and timer-based wheel scroll latching
+ // happens only when scroll state is unknown.
+ DCHECK(scroll_phase_state_ == SCROLL_STATE_UNKNOWN);
+ return wheel_event.GetModifiers() != initial_wheel_event_.GetModifiers();
+}
+
bool MouseWheelPhaseHandler::ShouldBreakLatchingDueToDirectionChange(
const blink::WebMouseWheelEvent& wheel_event) const {
// This function is called to check if breaking timer-based wheel scroll
diff --git a/chromium/content/browser/renderer_host/input/mouse_wheel_phase_handler.h b/chromium/content/browser/renderer_host/input/mouse_wheel_phase_handler.h
index 2d3771ab800..343f8172d85 100644
--- a/chromium/content/browser/renderer_host/input/mouse_wheel_phase_handler.h
+++ b/chromium/content/browser/renderer_host/input/mouse_wheel_phase_handler.h
@@ -8,10 +8,9 @@
#include "base/timer/timer.h"
#include "content/browser/renderer_host/render_widget_host_delegate.h"
#include "content/public/common/input_event_ack_state.h"
-#include "third_party/WebKit/public/platform/WebMouseWheelEvent.h"
+#include "third_party/blink/public/platform/web_mouse_wheel_event.h"
namespace content {
-class RenderWidgetHostImpl;
class RenderWidgetHostViewBase;
// The duration after which a synthetic wheel with zero deltas and
@@ -52,8 +51,7 @@ enum class FirstScrollUpdateAckState {
class MouseWheelPhaseHandler {
public:
- MouseWheelPhaseHandler(RenderWidgetHostImpl* const host,
- RenderWidgetHostViewBase* const host_view);
+ MouseWheelPhaseHandler(RenderWidgetHostViewBase* const host_view);
~MouseWheelPhaseHandler() {}
void AddPhaseIfNeededAndScheduleEndEvent(
@@ -81,11 +79,12 @@ class MouseWheelPhaseHandler {
bool should_route_event);
void ScheduleMouseWheelEndDispatching(bool should_route_event,
const base::TimeDelta timeout);
- bool IsWithinSlopRegion(blink::WebMouseWheelEvent wheel_event) const;
+ bool IsWithinSlopRegion(const blink::WebMouseWheelEvent& wheel_event) const;
+ bool HasDifferentModifiers(
+ const blink::WebMouseWheelEvent& wheel_event) const;
bool ShouldBreakLatchingDueToDirectionChange(
const blink::WebMouseWheelEvent& wheel_event) const;
- RenderWidgetHostImpl* const host_;
RenderWidgetHostViewBase* const host_view_;
base::OneShotTimer mouse_wheel_end_dispatch_timer_;
base::TimeDelta mouse_wheel_end_dispatch_timeout_;
diff --git a/chromium/content/browser/renderer_host/input/mouse_wheel_rails_filter_mac.h b/chromium/content/browser/renderer_host/input/mouse_wheel_rails_filter_mac.h
index d58516d0524..3d51d4568ba 100644
--- a/chromium/content/browser/renderer_host/input/mouse_wheel_rails_filter_mac.h
+++ b/chromium/content/browser/renderer_host/input/mouse_wheel_rails_filter_mac.h
@@ -6,7 +6,7 @@
#define CONTENT_BROWSER_RENDERER_HOST_INPUT_MOUSE_WHEEL_RAILS_FILTER_MAC_H_
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebMouseWheelEvent.h"
+#include "third_party/blink/public/platform/web_mouse_wheel_event.h"
#include "ui/gfx/geometry/vector2d_f.h"
namespace content {
diff --git a/chromium/content/browser/renderer_host/input/passthrough_touch_event_queue.cc b/chromium/content/browser/renderer_host/input/passthrough_touch_event_queue.cc
index 2a5358cb5f6..cb692ca6b5d 100644
--- a/chromium/content/browser/renderer_host/input/passthrough_touch_event_queue.cc
+++ b/chromium/content/browser/renderer_host/input/passthrough_touch_event_queue.cc
@@ -8,7 +8,6 @@
#include "base/auto_reset.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/trace_event/trace_event.h"
#include "content/browser/renderer_host/input/touch_timeout_handler.h"
diff --git a/chromium/content/browser/renderer_host/input/passthrough_touch_event_queue.h b/chromium/content/browser/renderer_host/input/passthrough_touch_event_queue.h
index 65d881e9f48..bc5f7931272 100644
--- a/chromium/content/browser/renderer_host/input/passthrough_touch_event_queue.h
+++ b/chromium/content/browser/renderer_host/input/passthrough_touch_event_queue.h
@@ -33,6 +33,8 @@ class CONTENT_EXPORT PassthroughTouchEventQueueClient {
virtual void OnFilteringTouchEvent(
const blink::WebTouchEvent& touch_event) = 0;
+
+ virtual bool TouchscreenFlingInProgress() = 0;
};
// A queue that processes a touch-event and forwards it on to the
diff --git a/chromium/content/browser/renderer_host/input/passthrough_touch_event_queue_unittest.cc b/chromium/content/browser/renderer_host/input/passthrough_touch_event_queue_unittest.cc
index e8c7dafe321..59148caf04b 100644
--- a/chromium/content/browser/renderer_host/input/passthrough_touch_event_queue_unittest.cc
+++ b/chromium/content/browser/renderer_host/input/passthrough_touch_event_queue_unittest.cc
@@ -21,7 +21,7 @@
#include "content/common/input/synthetic_web_input_event_builders.h"
#include "content/common/input/web_touch_event_traits.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/events/base_event_utils.h"
using blink::WebGestureEvent;
@@ -95,6 +95,8 @@ class PassthroughTouchEventQueueTest : public testing::Test,
void OnFilteringTouchEvent(const blink::WebTouchEvent& touch_event) override {
}
+ bool TouchscreenFlingInProgress() override { return false; }
+
protected:
void SetUpForTouchMoveSlopTesting(double slop_length_dips) {
slop_length_dips_ = slop_length_dips;
diff --git a/chromium/content/browser/renderer_host/input/scroll_latency_browsertest.cc b/chromium/content/browser/renderer_host/input/scroll_latency_browsertest.cc
index 2e02cd28d31..3918ef2265a 100644
--- a/chromium/content/browser/renderer_host/input/scroll_latency_browsertest.cc
+++ b/chromium/content/browser/renderer_host/input/scroll_latency_browsertest.cc
@@ -128,6 +128,7 @@ IN_PROC_BROWSER_TEST_F(ScrollLatencyBrowserTest, SmoothWheelScroll) {
size_t num_samples = 0;
while (num_samples == 0) {
+ FetchHistogramsFromChildProcesses();
num_samples =
histogram_tester
.GetAllSamples(
diff --git a/chromium/content/browser/renderer_host/input/synthetic_gesture_controller_unittest.cc b/chromium/content/browser/renderer_host/input/synthetic_gesture_controller_unittest.cc
index 35381a52fc5..544b8944583 100644
--- a/chromium/content/browser/renderer_host/input/synthetic_gesture_controller_unittest.cc
+++ b/chromium/content/browser/renderer_host/input/synthetic_gesture_controller_unittest.cc
@@ -32,7 +32,7 @@
#include "content/public/test/test_browser_context.h"
#include "content/test/test_render_view_host.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/vector2d.h"
diff --git a/chromium/content/browser/renderer_host/input/synthetic_gesture_target_android.cc b/chromium/content/browser/renderer_host/input/synthetic_gesture_target_android.cc
index 316737ef097..e3b3cacd789 100644
--- a/chromium/content/browser/renderer_host/input/synthetic_gesture_target_android.cc
+++ b/chromium/content/browser/renderer_host/input/synthetic_gesture_target_android.cc
@@ -8,10 +8,10 @@
#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_view_base.h"
#include "jni/SyntheticGestureTarget_jni.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
-#include "third_party/WebKit/public/platform/WebMouseEvent.h"
-#include "third_party/WebKit/public/platform/WebMouseWheelEvent.h"
-#include "third_party/WebKit/public/platform/WebTouchEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
+#include "third_party/blink/public/platform/web_mouse_event.h"
+#include "third_party/blink/public/platform/web_mouse_wheel_event.h"
+#include "third_party/blink/public/platform/web_touch_event.h"
#include "ui/android/view_android.h"
#include "ui/gfx/android/view_configuration.h"
diff --git a/chromium/content/browser/renderer_host/input/synthetic_gesture_target_base.cc b/chromium/content/browser/renderer_host/input/synthetic_gesture_target_base.cc
index 3abbe83aa73..3691e3f563a 100644
--- a/chromium/content/browser/renderer_host/input/synthetic_gesture_target_base.cc
+++ b/chromium/content/browser/renderer_host/input/synthetic_gesture_target_base.cc
@@ -8,7 +8,7 @@
#include "content/browser/renderer_host/render_widget_host_view_base.h"
#include "content/browser/renderer_host/ui_events_helper.h"
#include "content/common/input_messages.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/events/blink/web_input_event_traits.h"
#include "ui/events/event.h"
#include "ui/latency/latency_info.h"
diff --git a/chromium/content/browser/renderer_host/input/synthetic_gesture_target_mac.mm b/chromium/content/browser/renderer_host/input/synthetic_gesture_target_mac.mm
index 36c25c462ad..71b3c5906b6 100644
--- a/chromium/content/browser/renderer_host/input/synthetic_gesture_target_mac.mm
+++ b/chromium/content/browser/renderer_host/input/synthetic_gesture_target_mac.mm
@@ -6,6 +6,7 @@
#include "base/mac/scoped_nsautorelease_pool.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
+#import "content/browser/renderer_host/render_widget_host_view_cocoa.h"
// Unlike some event APIs, Apple does not provide a way to programmatically
// build a zoom event. To work around this, we leverage ObjectiveC's flexible
@@ -94,8 +95,9 @@ void SyntheticGestureTargetMac::DispatchInputEventToPlatform(
case WebInputEvent::kGesturePinchBegin: {
id cocoa_event = [SyntheticPinchEvent
eventWithMagnification:0.0f
- locationInWindow:NSMakePoint(gesture_event->x,
- gesture_event->y)
+ locationInWindow:NSMakePoint(
+ gesture_event->PositionInWidget().x,
+ gesture_event->PositionInWidget().y)
phase:NSEventPhaseBegan];
[cocoa_view_ handleBeginGestureWithEvent:cocoa_event];
return;
@@ -103,8 +105,9 @@ void SyntheticGestureTargetMac::DispatchInputEventToPlatform(
case WebInputEvent::kGesturePinchEnd: {
id cocoa_event = [SyntheticPinchEvent
eventWithMagnification:0.0f
- locationInWindow:NSMakePoint(gesture_event->x,
- gesture_event->y)
+ locationInWindow:NSMakePoint(
+ gesture_event->PositionInWidget().x,
+ gesture_event->PositionInWidget().y)
phase:NSEventPhaseEnded];
[cocoa_view_ handleEndGestureWithEvent:cocoa_event];
return;
@@ -112,8 +115,9 @@ void SyntheticGestureTargetMac::DispatchInputEventToPlatform(
case WebInputEvent::kGesturePinchUpdate: {
id cocoa_event = [SyntheticPinchEvent
eventWithMagnification:gesture_event->data.pinch_update.scale - 1.0f
- locationInWindow:NSMakePoint(gesture_event->x,
- gesture_event->y)
+ locationInWindow:NSMakePoint(
+ gesture_event->PositionInWidget().x,
+ gesture_event->PositionInWidget().y)
phase:NSEventPhaseChanged];
[cocoa_view_ magnifyWithEvent:cocoa_event];
return;
diff --git a/chromium/content/browser/renderer_host/input/synthetic_pointer_action.cc b/chromium/content/browser/renderer_host/input/synthetic_pointer_action.cc
index 3740118e2fa..38de025910c 100644
--- a/chromium/content/browser/renderer_host/input/synthetic_pointer_action.cc
+++ b/chromium/content/browser/renderer_host/input/synthetic_pointer_action.cc
@@ -5,7 +5,7 @@
#include "content/browser/renderer_host/input/synthetic_pointer_action.h"
#include "base/logging.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/latency/latency_info.h"
namespace content {
diff --git a/chromium/content/browser/renderer_host/input/synthetic_pointer_action_unittest.cc b/chromium/content/browser/renderer_host/input/synthetic_pointer_action_unittest.cc
index aeaae359c62..ed27b10655e 100644
--- a/chromium/content/browser/renderer_host/input/synthetic_pointer_action_unittest.cc
+++ b/chromium/content/browser/renderer_host/input/synthetic_pointer_action_unittest.cc
@@ -2,13 +2,13 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
+#include "content/browser/renderer_host/input/synthetic_pointer_action.h"
#include "base/bind.h"
#include "base/time/time.h"
#include "content/browser/renderer_host/input/synthetic_gesture.h"
#include "content/browser/renderer_host/input/synthetic_gesture_target.h"
-#include "content/browser/renderer_host/input/synthetic_pointer_action.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/point_f.h"
diff --git a/chromium/content/browser/renderer_host/input/synthetic_pointer_driver.cc b/chromium/content/browser/renderer_host/input/synthetic_pointer_driver.cc
index 0189ef1bc6e..38cfd5c9c75 100644
--- a/chromium/content/browser/renderer_host/input/synthetic_pointer_driver.cc
+++ b/chromium/content/browser/renderer_host/input/synthetic_pointer_driver.cc
@@ -4,7 +4,6 @@
#include "content/browser/renderer_host/input/synthetic_pointer_driver.h"
-#include "base/memory/ptr_util.h"
#include "content/browser/renderer_host/input/synthetic_mouse_driver.h"
#include "content/browser/renderer_host/input/synthetic_pen_driver.h"
#include "content/browser/renderer_host/input/synthetic_touch_driver.h"
diff --git a/chromium/content/browser/renderer_host/input/synthetic_smooth_move_gesture.h b/chromium/content/browser/renderer_host/input/synthetic_smooth_move_gesture.h
index 8cbe4ac2664..353336c1f5c 100644
--- a/chromium/content/browser/renderer_host/input/synthetic_smooth_move_gesture.h
+++ b/chromium/content/browser/renderer_host/input/synthetic_smooth_move_gesture.h
@@ -15,7 +15,7 @@
#include "content/common/content_export.h"
#include "content/common/input/synthetic_smooth_drag_gesture_params.h"
#include "content/common/input/synthetic_smooth_scroll_gesture_params.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/gfx/geometry/vector2d.h"
#include "ui/gfx/geometry/vector2d_f.h"
diff --git a/chromium/content/browser/renderer_host/input/synthetic_tap_gesture.cc b/chromium/content/browser/renderer_host/input/synthetic_tap_gesture.cc
index 3a3a3b7c93a..80503e564d7 100644
--- a/chromium/content/browser/renderer_host/input/synthetic_tap_gesture.cc
+++ b/chromium/content/browser/renderer_host/input/synthetic_tap_gesture.cc
@@ -5,7 +5,7 @@
#include "content/browser/renderer_host/input/synthetic_tap_gesture.h"
#include "base/logging.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/latency/latency_info.h"
namespace content {
diff --git a/chromium/content/browser/renderer_host/input/synthetic_touchpad_pinch_gesture.h b/chromium/content/browser/renderer_host/input/synthetic_touchpad_pinch_gesture.h
index 761940f5024..7417dcbba70 100644
--- a/chromium/content/browser/renderer_host/input/synthetic_touchpad_pinch_gesture.h
+++ b/chromium/content/browser/renderer_host/input/synthetic_touchpad_pinch_gesture.h
@@ -12,7 +12,7 @@
#include "content/common/content_export.h"
#include "content/common/input/synthetic_pinch_gesture_params.h"
#include "content/common/input/synthetic_web_input_event_builders.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
namespace content {
diff --git a/chromium/content/browser/renderer_host/input/synthetic_touchscreen_pinch_gesture.h b/chromium/content/browser/renderer_host/input/synthetic_touchscreen_pinch_gesture.h
index aff6f1e670c..addfb1800e3 100644
--- a/chromium/content/browser/renderer_host/input/synthetic_touchscreen_pinch_gesture.h
+++ b/chromium/content/browser/renderer_host/input/synthetic_touchscreen_pinch_gesture.h
@@ -13,7 +13,7 @@
#include "content/common/content_export.h"
#include "content/common/input/synthetic_pinch_gesture_params.h"
#include "content/common/input/synthetic_web_input_event_builders.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
namespace content {
diff --git a/chromium/content/browser/renderer_host/input/timeout_monitor.cc b/chromium/content/browser/renderer_host/input/timeout_monitor.cc
index f46464a194f..470206aab7c 100644
--- a/chromium/content/browser/renderer_host/input/timeout_monitor.cc
+++ b/chromium/content/browser/renderer_host/input/timeout_monitor.cc
@@ -109,4 +109,9 @@ bool TimeoutMonitor::IsRunning() const {
!time_when_considered_timed_out_.is_null();
}
+base::TimeDelta TimeoutMonitor::GetCurrentDelay() {
+ DCHECK(!time_when_considered_timed_out_.is_null());
+ return time_when_considered_timed_out_ - TimeTicks::Now();
+}
+
} // namespace content
diff --git a/chromium/content/browser/renderer_host/input/timeout_monitor.h b/chromium/content/browser/renderer_host/input/timeout_monitor.h
index f2d96f259ac..ddec7c10dbb 100644
--- a/chromium/content/browser/renderer_host/input/timeout_monitor.h
+++ b/chromium/content/browser/renderer_host/input/timeout_monitor.h
@@ -30,6 +30,8 @@ class CONTENT_EXPORT TimeoutMonitor {
void Stop();
bool IsRunning() const;
+ base::TimeDelta GetCurrentDelay();
+
private:
void StartImpl(base::TimeDelta delay);
void CheckTimedOut();
diff --git a/chromium/content/browser/renderer_host/input/touch_action_browsertest.cc b/chromium/content/browser/renderer_host/input/touch_action_browsertest.cc
index 5683304b4b8..474c78dfe2d 100644
--- a/chromium/content/browser/renderer_host/input/touch_action_browsertest.cc
+++ b/chromium/content/browser/renderer_host/input/touch_action_browsertest.cc
@@ -29,7 +29,7 @@
#include "content/public/test/content_browser_test_utils.h"
#include "content/public/test/test_utils.h"
#include "content/shell/browser/shell.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/latency/latency_info.h"
using blink::WebInputEvent;
@@ -91,7 +91,7 @@ class TouchActionBrowserTest : public ContentBrowserTest {
NavigateToURL(shell(), data_url);
RenderWidgetHostImpl* host = GetWidgetHost();
- RenderFrameSubmissionObserver frame_observer(
+ frame_observer_ = std::make_unique<RenderFrameSubmissionObserver>(
host->render_frame_metadata_provider());
host->GetView()->SetSize(gfx::Size(400, 400));
@@ -103,7 +103,7 @@ class TouchActionBrowserTest : public ContentBrowserTest {
// otherwise the injection of the synthetic gestures may get
// dropped because of MainThread/Impl thread sync of touch event
// regions.
- frame_observer.WaitForAnyFrameSubmission();
+ frame_observer_->WaitForAnyFrameSubmission();
}
// ContentBrowserTest:
@@ -115,6 +115,13 @@ class TouchActionBrowserTest : public ContentBrowserTest {
cmd->AppendSwitch(switches::kEnableExperimentalWebPlatformFeatures);
}
+ // ContentBrowserTest:
+ void PostRunTestOnMainThread() override {
+ // Delete this before the WebContents is destroyed.
+ frame_observer_.reset();
+ ContentBrowserTest::PostRunTestOnMainThread();
+ }
+
int ExecuteScriptAndExtractInt(const std::string& script) {
int value = 0;
EXPECT_TRUE(content::ExecuteScriptAndExtractInt(
@@ -145,9 +152,6 @@ class TouchActionBrowserTest : public ContentBrowserTest {
ExecuteScriptAndExtractInt("document.documentElement.scrollHeight");
EXPECT_EQ(10200, scroll_height);
- RenderFrameSubmissionObserver frame_metadata_observer(
- GetWidgetHost()->render_frame_metadata_provider());
-
SyntheticSmoothScrollGestureParams params;
params.gesture_source_type = SyntheticGestureParams::TOUCH_INPUT;
params.anchor = gfx::PointF(point);
@@ -168,10 +172,12 @@ class TouchActionBrowserTest : public ContentBrowserTest {
// Expect that the compositor scrolled at least one pixel while the
// main thread was in a busy loop.
+ gfx::Vector2dF default_scroll_offset;
while (wait_until_scrolled &&
- frame_metadata_observer.LastRenderFrameMetadata()
- .root_scroll_offset.y() < (distance.y() / 2)) {
- frame_metadata_observer.WaitForMetadataChange();
+ frame_observer_->LastRenderFrameMetadata()
+ .root_scroll_offset.value_or(default_scroll_offset)
+ .y() < (distance.y() / 2)) {
+ frame_observer_->WaitForMetadataChange();
}
// Check the scroll offset
@@ -185,6 +191,7 @@ class TouchActionBrowserTest : public ContentBrowserTest {
}
private:
+ std::unique_ptr<RenderFrameSubmissionObserver> frame_observer_;
scoped_refptr<MessageLoopRunner> runner_;
DISALLOW_COPY_AND_ASSIGN(TouchActionBrowserTest);
diff --git a/chromium/content/browser/renderer_host/input/touch_action_filter.cc b/chromium/content/browser/renderer_host/input/touch_action_filter.cc
index ab9e5570950..d6e89f5aa5b 100644
--- a/chromium/content/browser/renderer_host/input/touch_action_filter.cc
+++ b/chromium/content/browser/renderer_host/input/touch_action_filter.cc
@@ -8,7 +8,7 @@
#include "base/logging.h"
#include "base/metrics/histogram_macros.h"
-#include "third_party/WebKit/public/platform/WebGestureEvent.h"
+#include "third_party/blink/public/platform/web_gesture_event.h"
using blink::WebInputEvent;
using blink::WebGestureEvent;
@@ -39,11 +39,10 @@ TouchActionFilter::TouchActionFilter()
drop_current_tap_ending_event_(false),
allow_current_double_tap_event_(true),
force_enable_zoom_(false),
- allowed_touch_action_(cc::kTouchActionAuto),
- white_listed_touch_action_(cc::kTouchActionAuto) {}
+ allowed_touch_action_(cc::kTouchActionAuto) {}
bool TouchActionFilter::FilterGestureEvent(WebGestureEvent* gesture_event) {
- if (gesture_event->source_device != blink::kWebGestureDeviceTouchscreen)
+ if (gesture_event->SourceDevice() != blink::kWebGestureDeviceTouchscreen)
return false;
// Filter for allowable touch actions first (eg. before the TouchEventQueue
@@ -192,8 +191,11 @@ void TouchActionFilter::ReportAndResetTouchAction() {
// Report how often the effective touch action computed by blink is or is
// not equivalent to the whitelisted touch action computed by the
// compositor.
- UMA_HISTOGRAM_BOOLEAN("TouchAction.EquivalentEffectiveAndWhiteListed",
- allowed_touch_action_ == white_listed_touch_action_);
+ if (white_listed_touch_action_.has_value()) {
+ UMA_HISTOGRAM_BOOLEAN(
+ "TouchAction.EquivalentEffectiveAndWhiteListed",
+ allowed_touch_action_ == white_listed_touch_action_.value());
+ }
ResetTouchAction();
}
@@ -201,22 +203,19 @@ void TouchActionFilter::ResetTouchAction() {
// Note that resetting the action mid-sequence is tolerated. Gestures that had
// their begin event(s) suppressed will be suppressed until the next sequence.
allowed_touch_action_ = cc::kTouchActionAuto;
- white_listed_touch_action_ = cc::kTouchActionAuto;
+ white_listed_touch_action_.reset();
}
void TouchActionFilter::OnSetWhiteListedTouchAction(
cc::TouchAction white_listed_touch_action) {
- // For multiple fingers, we take the intersection of the touch actions for all
- // fingers that have gone down during this action. In the majority of
- // real-world scenarios the touch action for all fingers will be the same.
- // This is left as implementation because of the relationship of gestures
- // (which are off limits for the spec). We believe the following are
- // desirable properties of this choice:
- // 1. Not sensitive to finger touch order. Behavior of putting two fingers
- // down "at once" will be deterministic.
- // 2. Only subtractive - eg. can't trigger scrolling on an element that
- // otherwise has scrolling disabling by the addition of a finger.
- white_listed_touch_action_ &= white_listed_touch_action;
+ // We use '&' here to account for the multiple-finger case, which is the same
+ // as OnSetTouchAction.
+ if (white_listed_touch_action_.has_value()) {
+ white_listed_touch_action_ =
+ white_listed_touch_action_.value() & white_listed_touch_action;
+ } else {
+ white_listed_touch_action_ = white_listed_touch_action;
+ }
}
bool TouchActionFilter::ShouldSuppressManipulation(
diff --git a/chromium/content/browser/renderer_host/input/touch_action_filter.h b/chromium/content/browser/renderer_host/input/touch_action_filter.h
index 44002ed8582..fd6d5e6cd0a 100644
--- a/chromium/content/browser/renderer_host/input/touch_action_filter.h
+++ b/chromium/content/browser/renderer_host/input/touch_action_filter.h
@@ -6,6 +6,7 @@
#define CONTENT_BROWSER_RENDERER_HOST_INPUT_TOUCH_ACTION_FILTER_H_
#include "base/macros.h"
+#include "base/optional.h"
#include "cc/input/touch_action.h"
#include "content/common/content_export.h"
@@ -15,6 +16,8 @@ class WebGestureEvent;
namespace content {
+class MockRenderWidgetHost;
+
// The TouchActionFilter is responsible for filtering scroll and pinch gesture
// events according to the CSS touch-action values the renderer has sent for
// each touch point.
@@ -53,6 +56,8 @@ class CONTENT_EXPORT TouchActionFilter {
void SetForceEnableZoom(bool enabled) { force_enable_zoom_ = enabled; }
private:
+ friend class MockRenderWidgetHost;
+
bool ShouldSuppressManipulation(const blink::WebGestureEvent&);
bool FilterManipulationEventAndResetState();
@@ -76,7 +81,7 @@ class CONTENT_EXPORT TouchActionFilter {
cc::TouchAction allowed_touch_action_;
// Whitelisted touch action received from the compositor.
- cc::TouchAction white_listed_touch_action_;
+ base::Optional<cc::TouchAction> white_listed_touch_action_;
DISALLOW_COPY_AND_ASSIGN(TouchActionFilter);
};
diff --git a/chromium/content/browser/renderer_host/input/touch_action_filter_unittest.cc b/chromium/content/browser/renderer_host/input/touch_action_filter_unittest.cc
index e645b3334e2..11e64ae5579 100644
--- a/chromium/content/browser/renderer_host/input/touch_action_filter_unittest.cc
+++ b/chromium/content/browser/renderer_host/input/touch_action_filter_unittest.cc
@@ -7,7 +7,7 @@
#include "content/common/input/synthetic_web_input_event_builders.h"
#include "content/public/common/input_event_ack_state.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
using blink::WebGestureEvent;
using blink::WebInputEvent;
diff --git a/chromium/content/browser/renderer_host/input/touch_emulator.cc b/chromium/content/browser/renderer_host/input/touch_emulator.cc
index 1fcec1be63e..8c110ea6985 100644
--- a/chromium/content/browser/renderer_host/input/touch_emulator.cc
+++ b/chromium/content/browser/renderer_host/input/touch_emulator.cc
@@ -12,9 +12,9 @@
#include "content/grit/content_resources.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_switches.h"
-#include "third_party/WebKit/public/platform/WebCursorInfo.h"
-#include "third_party/WebKit/public/platform/WebKeyboardEvent.h"
-#include "third_party/WebKit/public/platform/WebMouseEvent.h"
+#include "third_party/blink/public/platform/web_cursor_info.h"
+#include "third_party/blink/public/platform/web_keyboard_event.h"
+#include "third_party/blink/public/platform/web_mouse_event.h"
#include "ui/base/ui_base_types.h"
#include "ui/events/base_event_utils.h"
#include "ui/events/blink/blink_event_util.h"
@@ -459,7 +459,7 @@ void TouchEmulator::PinchBegin(const WebGestureEvent& event) {
DCHECK(InPinchGestureMode());
DCHECK(!pinch_gesture_active_);
pinch_gesture_active_ = true;
- pinch_anchor_ = gfx::Point(event.x, event.y);
+ pinch_anchor_ = event.PositionInWidget();
pinch_scale_ = 1.f;
WebGestureEvent pinch_event =
GetPinchGestureEvent(WebInputEvent::kGesturePinchBegin, event);
@@ -468,7 +468,7 @@ void TouchEmulator::PinchBegin(const WebGestureEvent& event) {
void TouchEmulator::PinchUpdate(const WebGestureEvent& event) {
DCHECK(pinch_gesture_active_);
- int dy = pinch_anchor_.y() - event.y;
+ float dy = pinch_anchor_.y() - event.PositionInWidget().y;
float scale = exp(dy * 0.002f);
WebGestureEvent pinch_event =
GetPinchGestureEvent(WebInputEvent::kGesturePinchUpdate, event);
@@ -486,10 +486,9 @@ void TouchEmulator::PinchEnd(const WebGestureEvent& event) {
}
void TouchEmulator::ScrollEnd(const WebGestureEvent& event) {
- WebGestureEvent scroll_event(WebInputEvent::kGestureScrollEnd,
- ModifiersWithoutMouseButtons(event),
- event.TimeStampSeconds());
- scroll_event.source_device = blink::kWebGestureDeviceTouchscreen;
+ WebGestureEvent scroll_event(
+ WebInputEvent::kGestureScrollEnd, ModifiersWithoutMouseButtons(event),
+ event.TimeStampSeconds(), blink::kWebGestureDeviceTouchscreen);
client_->ForwardEmulatedGestureEvent(scroll_event);
}
@@ -497,10 +496,9 @@ WebGestureEvent TouchEmulator::GetPinchGestureEvent(
WebInputEvent::Type type,
const WebInputEvent& original_event) {
WebGestureEvent event(type, ModifiersWithoutMouseButtons(original_event),
- original_event.TimeStampSeconds());
- event.source_device = blink::kWebGestureDeviceTouchscreen;
- event.x = pinch_anchor_.x();
- event.y = pinch_anchor_.y();
+ original_event.TimeStampSeconds(),
+ blink::kWebGestureDeviceTouchscreen);
+ event.SetPositionInWidget(pinch_anchor_);
return event;
}
diff --git a/chromium/content/browser/renderer_host/input/touch_emulator.h b/chromium/content/browser/renderer_host/input/touch_emulator.h
index f7faf48f3e2..9c53f845f5d 100644
--- a/chromium/content/browser/renderer_host/input/touch_emulator.h
+++ b/chromium/content/browser/renderer_host/input/touch_emulator.h
@@ -13,7 +13,7 @@
#include "content/browser/renderer_host/input/touch_emulator_client.h"
#include "content/common/cursors/webcursor.h"
#include "content/public/common/input_event_ack_state.h"
-#include "third_party/WebKit/public/platform/WebTouchEvent.h"
+#include "third_party/blink/public/platform/web_touch_event.h"
#include "ui/events/gesture_detection/filtered_gesture_provider.h"
#include "ui/events/gesture_detection/gesture_provider_config_helper.h"
#include "ui/gfx/geometry/size_f.h"
@@ -150,7 +150,7 @@ class CONTENT_EXPORT TouchEmulator : public ui::GestureProviderClient {
bool suppress_next_fling_cancel_;
// Point which does not move while pinch-zooming.
- gfx::Point pinch_anchor_;
+ gfx::PointF pinch_anchor_;
// The cumulative scale change from the start of pinch gesture.
float pinch_scale_;
bool pinch_gesture_active_;
diff --git a/chromium/content/browser/renderer_host/input/touch_emulator_client.h b/chromium/content/browser/renderer_host/input/touch_emulator_client.h
index 5214406b226..991e0e16d21 100644
--- a/chromium/content/browser/renderer_host/input/touch_emulator_client.h
+++ b/chromium/content/browser/renderer_host/input/touch_emulator_client.h
@@ -7,8 +7,8 @@
#include "content/common/content_export.h"
#include "content/common/cursors/webcursor.h"
-#include "third_party/WebKit/public/platform/WebGestureEvent.h"
-#include "third_party/WebKit/public/platform/WebTouchEvent.h"
+#include "third_party/blink/public/platform/web_gesture_event.h"
+#include "third_party/blink/public/platform/web_touch_event.h"
#include "ui/base/ui_base_types.h"
namespace content {
diff --git a/chromium/content/browser/renderer_host/input/touch_emulator_unittest.cc b/chromium/content/browser/renderer_host/input/touch_emulator_unittest.cc
index 03f5a2470c2..4b3f9b0b069 100644
--- a/chromium/content/browser/renderer_host/input/touch_emulator_unittest.cc
+++ b/chromium/content/browser/renderer_host/input/touch_emulator_unittest.cc
@@ -13,8 +13,8 @@
#include "base/time/time.h"
#include "content/browser/renderer_host/input/touch_emulator_client.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebKeyboardEvent.h"
-#include "third_party/WebKit/public/platform/WebMouseWheelEvent.h"
+#include "third_party/blink/public/platform/web_keyboard_event.h"
+#include "third_party/blink/public/platform/web_mouse_wheel_event.h"
#include "ui/base/ui_base_types.h"
#include "ui/events/blink/web_input_event_traits.h"
diff --git a/chromium/content/browser/renderer_host/input/touch_input_browsertest.cc b/chromium/content/browser/renderer_host/input/touch_input_browsertest.cc
index 206e524e2ab..645bc4be2b5 100644
--- a/chromium/content/browser/renderer_host/input/touch_input_browsertest.cc
+++ b/chromium/content/browser/renderer_host/input/touch_input_browsertest.cc
@@ -23,7 +23,7 @@
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/shell/browser/shell.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/latency/latency_info.h"
using blink::WebInputEvent;
diff --git a/chromium/content/browser/renderer_host/input/touch_selection_controller_client_aura.cc b/chromium/content/browser/renderer_host/input/touch_selection_controller_client_aura.cc
index 31fc6845001..746afa48833 100644
--- a/chromium/content/browser/renderer_host/input/touch_selection_controller_client_aura.cc
+++ b/chromium/content/browser/renderer_host/input/touch_selection_controller_client_aura.cc
@@ -174,9 +174,9 @@ void TouchSelectionControllerClientAura::OnScrollCompleted() {
bool TouchSelectionControllerClientAura::HandleContextMenu(
const ContextMenuParams& params) {
- if (params.source_type == ui::MENU_SOURCE_LONG_PRESS &&
- params.is_editable &&
- params.selection_text.empty() &&
+ if ((params.source_type == ui::MENU_SOURCE_LONG_PRESS ||
+ params.source_type == ui::MENU_SOURCE_LONG_TAP) &&
+ params.is_editable && params.selection_text.empty() &&
IsQuickMenuAvailable()) {
quick_menu_requested_ = true;
UpdateQuickMenu();
@@ -184,6 +184,7 @@ bool TouchSelectionControllerClientAura::HandleContextMenu(
}
const bool from_touch = params.source_type == ui::MENU_SOURCE_LONG_PRESS ||
+ params.source_type == ui::MENU_SOURCE_LONG_TAP ||
params.source_type == ui::MENU_SOURCE_TOUCH;
if (from_touch && !params.selection_text.empty())
return true;
@@ -339,8 +340,7 @@ void TouchSelectionControllerClientAura::MoveCaret(
void TouchSelectionControllerClientAura::InternalClient::MoveCaret(
const gfx::PointF& position) {
- RenderWidgetHostDelegate* host_delegate =
- rwhva_->GetRenderWidgetHostImpl()->delegate();
+ RenderWidgetHostDelegate* host_delegate = rwhva_->host()->delegate();
if (host_delegate)
host_delegate->MoveCaret(gfx::ToRoundedPoint(position));
}
@@ -352,8 +352,7 @@ void TouchSelectionControllerClientAura::MoveRangeSelectionExtent(
void TouchSelectionControllerClientAura::InternalClient::
MoveRangeSelectionExtent(const gfx::PointF& extent) {
- RenderWidgetHostDelegate* host_delegate =
- rwhva_->GetRenderWidgetHostImpl()->delegate();
+ RenderWidgetHostDelegate* host_delegate = rwhva_->host()->delegate();
if (host_delegate)
host_delegate->MoveRangeSelectionExtent(gfx::ToRoundedPoint(extent));
}
@@ -367,8 +366,7 @@ void TouchSelectionControllerClientAura::SelectBetweenCoordinates(
void TouchSelectionControllerClientAura::InternalClient::
SelectBetweenCoordinates(const gfx::PointF& base,
const gfx::PointF& extent) {
- RenderWidgetHostDelegate* host_delegate =
- rwhva_->GetRenderWidgetHostImpl()->delegate();
+ RenderWidgetHostDelegate* host_delegate = rwhva_->host()->delegate();
if (host_delegate) {
host_delegate->SelectRange(gfx::ToRoundedPoint(base),
gfx::ToRoundedPoint(extent));
@@ -477,8 +475,7 @@ bool TouchSelectionControllerClientAura::IsCommandIdEnabled(
void TouchSelectionControllerClientAura::ExecuteCommand(int command_id,
int event_flags) {
rwhva_->selection_controller()->HideAndDisallowShowingAutomatically();
- RenderWidgetHostDelegate* host_delegate =
- rwhva_->GetRenderWidgetHostImpl()->delegate();
+ RenderWidgetHostDelegate* host_delegate = rwhva_->host()->delegate();
if (!host_delegate)
return;
@@ -503,7 +500,7 @@ void TouchSelectionControllerClientAura::RunContextMenu() {
rwhva_->selection_controller()->GetRectBetweenBounds();
gfx::PointF anchor_point =
gfx::PointF(anchor_rect.CenterPoint().x(), anchor_rect.y());
- RenderWidgetHostImpl* host = rwhva_->GetRenderWidgetHostImpl();
+ RenderWidgetHostImpl* host = rwhva_->host();
host->ShowContextMenuAtPoint(gfx::ToRoundedPoint(anchor_point),
ui::MENU_SOURCE_TOUCH_EDIT_MENU);
diff --git a/chromium/content/browser/renderer_host/input/touch_selection_controller_client_aura_browsertest.cc b/chromium/content/browser/renderer_host/input/touch_selection_controller_client_aura_browsertest.cc
index c7d35568b2e..cdc42a2d79f 100644
--- a/chromium/content/browser/renderer_host/input/touch_selection_controller_client_aura_browsertest.cc
+++ b/chromium/content/browser/renderer_host/input/touch_selection_controller_client_aura_browsertest.cc
@@ -19,7 +19,7 @@
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
-#include "content/public/test/scoped_overscroll_mode.h"
+#include "content/public/test/scoped_overscroll_modes.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_utils.h"
#include "content/shell/browser/shell.h"
@@ -857,7 +857,8 @@ IN_PROC_BROWSER_TEST_F(TouchSelectionControllerClientAuraTest, HiddenOnScroll) {
// This only happens in the gesture nav with parallax effect.
IN_PROC_BROWSER_TEST_F(TouchSelectionControllerClientAuraTest,
HiddenAfterOverscroll) {
- ScopedOverscrollMode scoped_mode(OverscrollConfig::Mode::kParallaxUi);
+ ScopedHistoryNavigationMode scoped_mode(
+ OverscrollConfig::HistoryNavigationMode::kParallaxUi);
// Set the page up.
ASSERT_NO_FATAL_FAILURE(StartTestWithPage("/touch_selection.html"));
diff --git a/chromium/content/browser/renderer_host/input/touch_selection_controller_client_child_frame.cc b/chromium/content/browser/renderer_host/input/touch_selection_controller_client_child_frame.cc
index 75bbdf3ab36..e419b3fbed8 100644
--- a/chromium/content/browser/renderer_host/input/touch_selection_controller_client_child_frame.cc
+++ b/chromium/content/browser/renderer_host/input/touch_selection_controller_client_child_frame.cc
@@ -113,16 +113,14 @@ void TouchSelectionControllerClientChildFrame::SetNeedsAnimate() {
void TouchSelectionControllerClientChildFrame::MoveCaret(
const gfx::PointF& position) {
- RenderWidgetHostDelegate* host_delegate =
- rwhv_->GetRenderWidgetHostImpl()->delegate();
+ RenderWidgetHostDelegate* host_delegate = rwhv_->host()->delegate();
if (host_delegate)
host_delegate->MoveCaret(ConvertFromRoot(position));
}
void TouchSelectionControllerClientChildFrame::MoveRangeSelectionExtent(
const gfx::PointF& extent) {
- RenderWidgetHostDelegate* host_delegate =
- rwhv_->GetRenderWidgetHostImpl()->delegate();
+ RenderWidgetHostDelegate* host_delegate = rwhv_->host()->delegate();
if (host_delegate)
host_delegate->MoveRangeSelectionExtent(ConvertFromRoot(extent));
}
@@ -130,8 +128,7 @@ void TouchSelectionControllerClientChildFrame::MoveRangeSelectionExtent(
void TouchSelectionControllerClientChildFrame::SelectBetweenCoordinates(
const gfx::PointF& base,
const gfx::PointF& extent) {
- RenderWidgetHostDelegate* host_delegate =
- rwhv_->GetRenderWidgetHostImpl()->delegate();
+ RenderWidgetHostDelegate* host_delegate = rwhv_->host()->delegate();
if (host_delegate) {
host_delegate->SelectRange(ConvertFromRoot(base), ConvertFromRoot(extent));
}
@@ -181,8 +178,7 @@ void TouchSelectionControllerClientChildFrame::ExecuteCommand(int command_id,
int event_flags) {
manager_->GetTouchSelectionController()
->HideAndDisallowShowingAutomatically();
- RenderWidgetHostDelegate* host_delegate =
- rwhv_->GetRenderWidgetHostImpl()->delegate();
+ RenderWidgetHostDelegate* host_delegate = rwhv_->host()->delegate();
if (!host_delegate)
return;
@@ -209,7 +205,7 @@ void TouchSelectionControllerClientChildFrame::RunContextMenu() {
gfx::PointF(anchor_rect.CenterPoint().x(), anchor_rect.y());
gfx::PointF origin = rwhv_->TransformPointToRootCoordSpaceF(gfx::PointF());
anchor_point.Offset(-origin.x(), -origin.y());
- RenderWidgetHostImpl* host = rwhv_->GetRenderWidgetHostImpl();
+ RenderWidgetHostImpl* host = rwhv_->host();
host->Send(new ViewMsg_ShowContextMenu(host->GetRoutingID(),
ui::MENU_SOURCE_TOUCH_EDIT_MENU,
gfx::ToRoundedPoint(anchor_point)));
diff --git a/chromium/content/browser/renderer_host/input/touch_selection_controller_client_manager_android.cc b/chromium/content/browser/renderer_host/input/touch_selection_controller_client_manager_android.cc
index 3c48234cdda..fc968742ec8 100644
--- a/chromium/content/browser/renderer_host/input/touch_selection_controller_client_manager_android.cc
+++ b/chromium/content/browser/renderer_host/input/touch_selection_controller_client_manager_android.cc
@@ -71,8 +71,10 @@ void TouchSelectionControllerClientManagerAndroid::UpdateClientSelectionBounds(
// Notify TouchSelectionController if anything should change here. Only
// update if the client is different and not making a change to empty, or
// is the same client.
- GetTouchSelectionController()->OnSelectionBoundsChanged(
- manager_selection_start_, manager_selection_end_);
+ if (GetTouchSelectionController()) {
+ GetTouchSelectionController()->OnSelectionBoundsChanged(
+ manager_selection_start_, manager_selection_end_);
+ }
}
void TouchSelectionControllerClientManagerAndroid::InvalidateClient(
diff --git a/chromium/content/browser/renderer_host/input/touch_timeout_handler.cc b/chromium/content/browser/renderer_host/input/touch_timeout_handler.cc
index 2c95426a4d7..3c192c8ef0b 100644
--- a/chromium/content/browser/renderer_host/input/touch_timeout_handler.cc
+++ b/chromium/content/browser/renderer_host/input/touch_timeout_handler.cc
@@ -8,7 +8,6 @@
#include "base/auto_reset.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/trace_event/trace_event.h"
#include "content/browser/renderer_host/input/passthrough_touch_event_queue.h"
diff --git a/chromium/content/browser/renderer_host/input/touchpad_tap_suppression_controller.h b/chromium/content/browser/renderer_host/input/touchpad_tap_suppression_controller.h
index 88b0805819c..cbacd339366 100644
--- a/chromium/content/browser/renderer_host/input/touchpad_tap_suppression_controller.h
+++ b/chromium/content/browser/renderer_host/input/touchpad_tap_suppression_controller.h
@@ -10,7 +10,7 @@
#include "content/browser/renderer_host/input/tap_suppression_controller.h"
#include "content/browser/renderer_host/input/tap_suppression_controller_client.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
namespace content {
diff --git a/chromium/content/browser/renderer_host/input/web_input_event_builders_android.cc b/chromium/content/browser/renderer_host/input/web_input_event_builders_android.cc
index a8547dbc35c..349b3f3d6ca 100644
--- a/chromium/content/browser/renderer_host/input/web_input_event_builders_android.cc
+++ b/chromium/content/browser/renderer_host/input/web_input_event_builders_android.cc
@@ -168,14 +168,13 @@ WebMouseWheelEvent WebMouseWheelEventBuilder::Build(
WebGestureEvent WebGestureEventBuilder::Build(WebInputEvent::Type type,
double time_sec,
- int x,
- int y) {
+ float x,
+ float y) {
DCHECK(WebInputEvent::IsGestureEventType(type));
- WebGestureEvent result(type, WebInputEvent::kNoModifiers, time_sec);
+ WebGestureEvent result(type, WebInputEvent::kNoModifiers, time_sec,
+ blink::kWebGestureDeviceTouchscreen);
- result.x = x;
- result.y = y;
- result.source_device = blink::kWebGestureDeviceTouchscreen;
+ result.SetPositionInWidget(gfx::PointF(x, y));
return result;
}
diff --git a/chromium/content/browser/renderer_host/input/web_input_event_builders_android.h b/chromium/content/browser/renderer_host/input/web_input_event_builders_android.h
index ce475e34b47..9994384e284 100644
--- a/chromium/content/browser/renderer_host/input/web_input_event_builders_android.h
+++ b/chromium/content/browser/renderer_host/input/web_input_event_builders_android.h
@@ -9,10 +9,10 @@
#include "base/android/scoped_java_ref.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebGestureEvent.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
-#include "third_party/WebKit/public/platform/WebKeyboardEvent.h"
-#include "third_party/WebKit/public/platform/WebMouseWheelEvent.h"
+#include "third_party/blink/public/platform/web_gesture_event.h"
+#include "third_party/blink/public/platform/web_input_event.h"
+#include "third_party/blink/public/platform/web_keyboard_event.h"
+#include "third_party/blink/public/platform/web_mouse_wheel_event.h"
#include "ui/events/android/motion_event_android.h"
namespace content {
@@ -49,8 +49,8 @@ class WebGestureEventBuilder {
public:
static blink::WebGestureEvent Build(blink::WebInputEvent::Type type,
double time_sec,
- int x,
- int y);
+ float x,
+ float y);
};
} // namespace content
diff --git a/chromium/content/browser/renderer_host/input/web_input_event_builders_android_unittest.cc b/chromium/content/browser/renderer_host/input/web_input_event_builders_android_unittest.cc
index 22b364998c8..387ed8237d3 100644
--- a/chromium/content/browser/renderer_host/input/web_input_event_builders_android_unittest.cc
+++ b/chromium/content/browser/renderer_host/input/web_input_event_builders_android_unittest.cc
@@ -9,7 +9,7 @@
#include "base/android/jni_android.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/events/android/key_event_utils.h"
#include "ui/events/gesture_detection/motion_event.h"
#include "ui/events/keycodes/dom/dom_code.h"
diff --git a/chromium/content/browser/renderer_host/input/web_input_event_builders_mac.h b/chromium/content/browser/renderer_host/input/web_input_event_builders_mac.h
index dd33a8bfee0..d5755a74318 100644
--- a/chromium/content/browser/renderer_host/input/web_input_event_builders_mac.h
+++ b/chromium/content/browser/renderer_host/input/web_input_event_builders_mac.h
@@ -6,10 +6,10 @@
#define CONTENT_BROWSER_RENDERER_HOST_INPUT_WEB_INPUT_EVENT_BUILDERS_MAC_H_
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebGestureEvent.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
-#include "third_party/WebKit/public/platform/WebKeyboardEvent.h"
-#include "third_party/WebKit/public/platform/WebMouseWheelEvent.h"
+#include "third_party/blink/public/platform/web_gesture_event.h"
+#include "third_party/blink/public/platform/web_input_event.h"
+#include "third_party/blink/public/platform/web_keyboard_event.h"
+#include "third_party/blink/public/platform/web_mouse_wheel_event.h"
@class NSEvent;
@class NSView;
diff --git a/chromium/content/browser/renderer_host/input/web_input_event_builders_mac.mm b/chromium/content/browser/renderer_host/input/web_input_event_builders_mac.mm
index eca937f8469..db697391cf6 100644
--- a/chromium/content/browser/renderer_host/input/web_input_event_builders_mac.mm
+++ b/chromium/content/browser/renderer_host/input/web_input_event_builders_mac.mm
@@ -37,7 +37,7 @@
#include "base/mac/sdk_forward_declarations.h"
#include "base/strings/string_util.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/base/cocoa/cocoa_base_utils.h"
#include "ui/events/blink/blink_event_util.h"
#import "ui/events/cocoa/cocoa_event_utils.h"
@@ -523,15 +523,14 @@ blink::WebGestureEvent WebGestureEventBuilder::Build(NSEvent* event,
blink::WebMouseEvent temp;
SetWebEventLocationFromEventInView(&temp, event, view);
- result.x = temp.PositionInWidget().x;
- result.y = temp.PositionInWidget().y;
- result.global_x = temp.PositionInScreen().x;
- result.global_y = temp.PositionInScreen().y;
+ result.SetPositionInWidget(temp.PositionInWidget());
+ result.SetPositionInScreen(temp.PositionInScreen());
result.SetModifiers(ModifiersFromEvent(event));
result.SetTimeStampSeconds([event timestamp]);
- result.source_device = blink::kWebGestureDeviceTouchpad;
+ result.SetSourceDevice(blink::kWebGestureDeviceTouchpad);
+
switch ([event type]) {
case NSEventTypeMagnify:
result.SetType(blink::WebInputEvent::kGesturePinchUpdate);
diff --git a/chromium/content/browser/renderer_host/input/web_input_event_util_unittest.cc b/chromium/content/browser/renderer_host/input/web_input_event_util_unittest.cc
index 3552f3608c0..33429778f0f 100644
--- a/chromium/content/browser/renderer_host/input/web_input_event_util_unittest.cc
+++ b/chromium/content/browser/renderer_host/input/web_input_event_util_unittest.cc
@@ -109,11 +109,11 @@ TEST(WebInputEventUtilTest, ScrollUpdateConversion) {
EXPECT_EQ(0, web_event.GetModifiers());
EXPECT_EQ((timestamp - base::TimeTicks()).InSecondsF(),
web_event.TimeStampSeconds());
- EXPECT_EQ(gfx::ToFlooredInt(pos.x()), web_event.x);
- EXPECT_EQ(gfx::ToFlooredInt(pos.y()), web_event.y);
- EXPECT_EQ(gfx::ToFlooredInt(raw_pos.x()), web_event.global_x);
- EXPECT_EQ(gfx::ToFlooredInt(raw_pos.y()), web_event.global_y);
- EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, web_event.source_device);
+ EXPECT_EQ(pos.x(), web_event.PositionInWidget().x);
+ EXPECT_EQ(pos.y(), web_event.PositionInWidget().y);
+ EXPECT_EQ(raw_pos.x(), web_event.PositionInScreen().x);
+ EXPECT_EQ(raw_pos.y(), web_event.PositionInScreen().y);
+ EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, web_event.SourceDevice());
EXPECT_EQ(delta.x(), web_event.data.scroll_update.delta_x);
EXPECT_EQ(delta.y(), web_event.data.scroll_update.delta_y);
EXPECT_TRUE(
diff --git a/chromium/content/browser/renderer_host/input/wheel_scroll_latching_browsertest.cc b/chromium/content/browser/renderer_host/input/wheel_scroll_latching_browsertest.cc
index fbd77cb7d43..97b99a35fff 100644
--- a/chromium/content/browser/renderer_host/input/wheel_scroll_latching_browsertest.cc
+++ b/chromium/content/browser/renderer_host/input/wheel_scroll_latching_browsertest.cc
@@ -378,17 +378,15 @@ void WheelScrollLatchingBrowserTest::
blink::WebGestureEvent gesture_scroll_begin(
blink::WebGestureEvent::kGestureScrollBegin,
blink::WebInputEvent::kNoModifiers,
- blink::WebInputEvent::GetStaticTimeStampForTests());
- gesture_scroll_begin.source_device = blink::kWebGestureDeviceTouchpad;
+ blink::WebInputEvent::GetStaticTimeStampForTests(),
+ blink::kWebGestureDeviceTouchpad);
gesture_scroll_begin.data.scroll_begin.delta_hint_units =
precise ? blink::WebGestureEvent::ScrollUnits::kPrecisePixels
: blink::WebGestureEvent::ScrollUnits::kPixels;
gesture_scroll_begin.data.scroll_begin.delta_x_hint = 0.f;
gesture_scroll_begin.data.scroll_begin.delta_y_hint = -20.f;
- gesture_scroll_begin.x = x;
- gesture_scroll_begin.y = y;
- gesture_scroll_begin.global_x = x;
- gesture_scroll_begin.global_y = y;
+ gesture_scroll_begin.SetPositionInWidget(gfx::PointF(x, y));
+ gesture_scroll_begin.SetPositionInScreen(gfx::PointF(x, y));
GetRootView()->ProcessGestureEvent(gesture_scroll_begin, ui::LatencyInfo());
// Send the first GSU event.
diff --git a/chromium/content/browser/renderer_host/legacy_render_widget_host_win.cc b/chromium/content/browser/renderer_host/legacy_render_widget_host_win.cc
index 7b880c4bee0..e09ded934c1 100644
--- a/chromium/content/browser/renderer_host/legacy_render_widget_host_win.cc
+++ b/chromium/content/browser/renderer_host/legacy_render_widget_host_win.cc
@@ -18,11 +18,14 @@
#include "content/browser/renderer_host/render_widget_host_view_aura.h"
#include "content/public/common/content_switches.h"
#include "ui/accessibility/platform/ax_system_caret_win.h"
+#include "ui/aura/window.h"
+#include "ui/aura/window_tree_host.h"
#include "ui/base/ui_base_features.h"
#include "ui/base/view_prop.h"
#include "ui/base/win/direct_manipulation.h"
#include "ui/base/win/internal_constants.h"
#include "ui/base/win/window_event_target.h"
+#include "ui/compositor/compositor.h"
#include "ui/display/win/screen_win.h"
#include "ui/gfx/geometry/rect.h"
@@ -33,6 +36,43 @@ namespace content {
// accessibility support.
const int kIdScreenReaderHoneyPot = 1;
+// DirectManipulation needs to poll for new events every frame while finger
+// gesturing on touchpad.
+class CompositorAnimationObserverForDirectManipulation
+ : public ui::CompositorAnimationObserver {
+ public:
+ CompositorAnimationObserverForDirectManipulation(
+ LegacyRenderWidgetHostHWND* render_widget_host_hwnd,
+ ui::Compositor* compositor)
+ : render_widget_host_hwnd_(render_widget_host_hwnd),
+ compositor_(compositor) {
+ DCHECK(compositor_);
+ compositor_->AddAnimationObserver(this);
+ }
+
+ ~CompositorAnimationObserverForDirectManipulation() override {
+ if (compositor_)
+ compositor_->RemoveAnimationObserver(this);
+ }
+
+ // ui::CompositorAnimationObserver
+ void OnAnimationStep(base::TimeTicks timestamp) override {
+ render_widget_host_hwnd_->PollForNextEvent();
+ }
+
+ // ui::CompositorAnimationObserver
+ void OnCompositingShuttingDown(ui::Compositor* compositor) override {
+ compositor->RemoveAnimationObserver(this);
+ compositor_ = nullptr;
+ }
+
+ private:
+ LegacyRenderWidgetHostHWND* render_widget_host_hwnd_;
+ ui::Compositor* compositor_;
+
+ DISALLOW_COPY_AND_ASSIGN(CompositorAnimationObserverForDirectManipulation);
+};
+
// static
LegacyRenderWidgetHostHWND* LegacyRenderWidgetHostHWND::Create(
HWND parent) {
@@ -57,6 +97,9 @@ LegacyRenderWidgetHostHWND* LegacyRenderWidgetHostHWND::Create(
}
void LegacyRenderWidgetHostHWND::Destroy() {
+ // Stop the AnimationObserver when window close.
+ DestroyAnimationObserver();
+ host_ = nullptr;
if (::IsWindow(hwnd()))
::DestroyWindow(hwnd());
}
@@ -64,6 +107,9 @@ void LegacyRenderWidgetHostHWND::Destroy() {
void LegacyRenderWidgetHostHWND::UpdateParent(HWND parent) {
if (GetWindowEventTarget(GetParent()))
GetWindowEventTarget(GetParent())->HandleParentChanged();
+ // Stop the AnimationObserver when window hide. eg. tab switch, move tab to
+ // another window.
+ DestroyAnimationObserver();
::SetParent(hwnd(), parent);
}
@@ -73,10 +119,14 @@ HWND LegacyRenderWidgetHostHWND::GetParent() {
void LegacyRenderWidgetHostHWND::Show() {
::ShowWindow(hwnd(), SW_SHOW);
+ if (direct_manipulation_helper_)
+ direct_manipulation_helper_->Activate();
}
void LegacyRenderWidgetHostHWND::Hide() {
::ShowWindow(hwnd(), SW_HIDE);
+ if (direct_manipulation_helper_)
+ direct_manipulation_helper_->Deactivate();
}
void LegacyRenderWidgetHostHWND::SetBounds(const gfx::Rect& bounds) {
@@ -85,8 +135,6 @@ void LegacyRenderWidgetHostHWND::SetBounds(const gfx::Rect& bounds) {
::SetWindowPos(hwnd(), NULL, bounds_in_pixel.x(), bounds_in_pixel.y(),
bounds_in_pixel.width(), bounds_in_pixel.height(),
SWP_NOREDRAW);
- if (direct_manipulation_helper_)
- direct_manipulation_helper_->SetBounds(bounds_in_pixel);
}
void LegacyRenderWidgetHostHWND::MoveCaretTo(const gfx::Rect& bounds) {
@@ -143,9 +191,8 @@ bool LegacyRenderWidgetHostHWND::Init() {
// Direct Manipulation is enabled on Windows 10+. The CreateInstance function
// returns NULL if Direct Manipulation is not available.
direct_manipulation_helper_ =
- ui::win::DirectManipulationHelper::CreateInstance();
- if (direct_manipulation_helper_)
- direct_manipulation_helper_->Initialize(hwnd());
+ ui::win::DirectManipulationHelper::CreateInstance(
+ hwnd(), GetWindowEventTarget(GetParent()));
// Disable pen flicks (http://crbug.com/506977)
base::win::DisableFlicks(hwnd());
@@ -280,12 +327,6 @@ LRESULT LegacyRenderWidgetHostHWND::OnMouseRange(UINT message,
handled = TRUE;
}
}
-
- if (direct_manipulation_helper_ &&
- (message == WM_MOUSEWHEEL || message == WM_MOUSEHWHEEL)) {
- direct_manipulation_helper_->HandleMouseWheel(hwnd(), message, w_param,
- l_param);
- }
return ret;
}
@@ -442,13 +483,57 @@ LRESULT LegacyRenderWidgetHostHWND::OnWindowPosChanged(UINT message,
WINDOWPOS* window_pos = reinterpret_cast<WINDOWPOS*>(l_param);
if (direct_manipulation_helper_) {
if (window_pos->flags & SWP_SHOWWINDOW) {
- direct_manipulation_helper_->Activate(hwnd());
+ direct_manipulation_helper_->Activate();
} else if (window_pos->flags & SWP_HIDEWINDOW) {
- direct_manipulation_helper_->Deactivate(hwnd());
+ direct_manipulation_helper_->Deactivate();
}
}
SetMsgHandled(FALSE);
return 0;
}
+LRESULT LegacyRenderWidgetHostHWND::OnPointerHitTest(UINT message,
+ WPARAM w_param,
+ LPARAM l_param) {
+ if (!direct_manipulation_helper_)
+ return 0;
+
+ // Update window event target for each DM_POINTERHITTEST.
+ if (direct_manipulation_helper_->OnPointerHitTest(
+ w_param, GetWindowEventTarget(GetParent()))) {
+ if (compositor_animation_observer_) {
+ // This is reach if Windows send a DM_POINTERHITTEST before the last
+ // DM_POINTERHITTEST receive READY status. We never see this but still
+ // worth to handle it.
+ return 0;
+ }
+
+ CreateAnimationObserver();
+ }
+
+ return 0;
+}
+
+void LegacyRenderWidgetHostHWND::PollForNextEvent() {
+ DCHECK(direct_manipulation_helper_);
+
+ if (!direct_manipulation_helper_->PollForNextEvent())
+ DestroyAnimationObserver();
+}
+
+void LegacyRenderWidgetHostHWND::CreateAnimationObserver() {
+ DCHECK(!compositor_animation_observer_);
+ DCHECK(host_);
+ DCHECK(host_->GetNativeView()->GetHost());
+ DCHECK(host_->GetNativeView()->GetHost()->compositor());
+
+ compositor_animation_observer_ =
+ std::make_unique<CompositorAnimationObserverForDirectManipulation>(
+ this, host_->GetNativeView()->GetHost()->compositor());
+}
+
+void LegacyRenderWidgetHostHWND::DestroyAnimationObserver() {
+ compositor_animation_observer_.reset();
+}
+
} // namespace content
diff --git a/chromium/content/browser/renderer_host/legacy_render_widget_host_win.h b/chromium/content/browser/renderer_host/legacy_render_widget_host_win.h
index c3d61410e90..79bad955ddc 100644
--- a/chromium/content/browser/renderer_host/legacy_render_widget_host_win.h
+++ b/chromium/content/browser/renderer_host/legacy_render_widget_host_win.h
@@ -15,10 +15,12 @@
#include "base/macros.h"
#include "content/common/content_export.h"
+#include "ui/compositor/compositor_animation_observer.h"
#include "ui/gfx/geometry/rect.h"
namespace ui {
class AXSystemCaretWin;
+class DirectManipulationHelper;
class WindowEventTarget;
namespace win {
class DirectManipulationHelper;
@@ -28,6 +30,8 @@ class DirectManipulationHelper;
namespace content {
class RenderWidgetHostViewAura;
+class DirectManipulationBrowserTest;
+
// Reasons for the existence of this class outlined below:-
// 1. Some screen readers expect every tab / every unique web content container
// to be in its own HWND with class name Chrome_RenderWidgetHostHWND.
@@ -95,6 +99,7 @@ class CONTENT_EXPORT LegacyRenderWidgetHostHWND
MESSAGE_HANDLER_EX(WM_NCCALCSIZE, OnNCCalcSize)
MESSAGE_HANDLER_EX(WM_SIZE, OnSize)
MESSAGE_HANDLER_EX(WM_WINDOWPOSCHANGED, OnWindowPosChanged)
+ MESSAGE_HANDLER_EX(DM_POINTERHITTEST, OnPointerHitTest)
END_MSG_MAP()
HWND hwnd() { return m_hWnd; }
@@ -122,10 +127,16 @@ class CONTENT_EXPORT LegacyRenderWidgetHostHWND
// Changes the position of the system caret used for accessibility.
void MoveCaretTo(const gfx::Rect& bounds);
+ // DirectManipulation needs to poll for new events every frame while finger
+ // gesturing on touchpad.
+ void PollForNextEvent();
+
protected:
void OnFinalMessage(HWND hwnd) override;
private:
+ friend class DirectManipulationBrowserTest;
+
explicit LegacyRenderWidgetHostHWND(HWND parent);
~LegacyRenderWidgetHostHWND() override;
@@ -154,6 +165,12 @@ class CONTENT_EXPORT LegacyRenderWidgetHostHWND
LRESULT OnSize(UINT message, WPARAM w_param, LPARAM l_param);
LRESULT OnWindowPosChanged(UINT message, WPARAM w_param, LPARAM l_param);
+ LRESULT OnPointerHitTest(UINT message, WPARAM w_param, LPARAM l_param);
+
+ void CreateAnimationObserver();
+
+ void DestroyAnimationObserver();
+
Microsoft::WRL::ComPtr<IAccessible> window_accessible_;
// Set to true if we turned on mouse tracking.
@@ -170,6 +187,9 @@ class CONTENT_EXPORT LegacyRenderWidgetHostHWND
std::unique_ptr<ui::win::DirectManipulationHelper>
direct_manipulation_helper_;
+ std::unique_ptr<ui::CompositorAnimationObserver>
+ compositor_animation_observer_;
+
DISALLOW_COPY_AND_ASSIGN(LegacyRenderWidgetHostHWND);
};
diff --git a/chromium/content/browser/renderer_host/media/audio_input_delegate_impl_unittest.cc b/chromium/content/browser/renderer_host/media/audio_input_delegate_impl_unittest.cc
index 47e404a76ef..f1a04982a98 100644
--- a/chromium/content/browser/renderer_host/media/audio_input_delegate_impl_unittest.cc
+++ b/chromium/content/browser/renderer_host/media/audio_input_delegate_impl_unittest.cc
@@ -12,7 +12,6 @@
#include "base/bind.h"
#include "base/command_line.h"
-#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/optional.h"
#include "base/run_loop.h"
@@ -45,6 +44,7 @@ using ::testing::NotNull;
using ::testing::StrictMock;
using ::testing::NiceMock;
using ::testing::Return;
+using ::testing::InvokeWithoutArgs;
namespace content {
@@ -65,6 +65,32 @@ media::AudioParameters ValidAudioParameters() {
return media::AudioParameters::UnavailableDeviceParams();
}
+media::AudioOutputStream* ExpectNoOutputStreamCreation(
+ const media::AudioParameters&,
+ const std::string&) {
+ CHECK(false);
+ return nullptr;
+}
+
+media::AudioInputStream* ExpectNoInputStreamCreation(
+ const media::AudioParameters&,
+ const std::string&) {
+ CHECK(false);
+ return nullptr;
+}
+
+media::AudioInputStream* MakeInputStreamCallback(
+ media::AudioInputStream* stream,
+ bool* created,
+ const media::AudioParameters&,
+ const std::string&) {
+ CHECK(!*created);
+ *created = true;
+ return stream;
+}
+
+} // namespace
+
class MockEventHandler : public media::AudioInputDelegate::EventHandler {
public:
void OnStreamCreated(int stream_id,
@@ -89,20 +115,6 @@ class MockUserInputMonitor : public media::UserInputMonitor {
MOCK_METHOD0(StopKeyboardMonitoring, void());
};
-media::AudioOutputStream* ExpectNoOutputStreamCreation(
- const media::AudioParameters&,
- const std::string&) {
- CHECK(false);
- return nullptr;
-}
-
-media::AudioInputStream* ExpectNoInputStreamCreation(
- const media::AudioParameters&,
- const std::string&) {
- CHECK(false);
- return nullptr;
-}
-
class MockAudioInputStream : public media::AudioInputStream {
public:
MockAudioInputStream() {}
@@ -120,31 +132,22 @@ class MockAudioInputStream : public media::AudioInputStream {
MOCK_METHOD0(IsMuted, bool());
};
-media::AudioInputStream* MakeInputStreamCallback(
- media::AudioInputStream* stream,
- bool* created,
- const media::AudioParameters&,
- const std::string&) {
- CHECK(!*created);
- *created = true;
- return stream;
-}
+class MockMediaStreamProviderListener : public MediaStreamProviderListener {
+ public:
+ MockMediaStreamProviderListener() {}
+ ~MockMediaStreamProviderListener() override {}
-} // namespace
+ MOCK_METHOD2(Opened,
+ void(MediaStreamType stream_type, int capture_session_id));
+ void Closed(MediaStreamType stream_type, int capture_session_id) override {}
+ void Aborted(MediaStreamType stream_type, int capture_session_id) override {}
+};
-// These tests are single-threaded.
-// In the real life we have AudioManager living on separate thread (or on the UI
-// thread on Mac), but AudioInputDelegate interacts with it on the IO thread via
-// AudioInputController, so we don't care much about AudioManager threading and
-// can use the main thread to run it. AudioInputDelegate lives on the IO thread,
-// it only posts notifications to the UI thread. MediaStreamManager lives on the
-// UI thread, but AID interacts with it on the IO thread, so we can have the IO
-// thread as a main thread for tests
class AudioInputDelegateTest : public testing::Test {
public:
AudioInputDelegateTest()
: thread_bundle_(base::in_place),
- audio_manager_(std::make_unique<media::TestAudioThread>()),
+ audio_manager_(std::make_unique<media::TestAudioThread>(true)),
audio_system_(&audio_manager_),
media_stream_manager_(&audio_system_, audio_manager_.GetTaskRunner()) {
audio_manager_.SetMakeInputStreamCB(
@@ -165,9 +168,22 @@ class AudioInputDelegateTest : public testing::Test {
// AudioInputDelegateImpl will allow them to be used.
int MakeDeviceAvailable(const std::string& device_id,
const std::string& name) {
+ // Authorize device for use and wait for completion.
+ MockMediaStreamProviderListener listener;
+ media_stream_manager_.audio_input_device_manager()->RegisterListener(
+ &listener);
+
int session_id = media_stream_manager_.audio_input_device_manager()->Open(
MediaStreamDevice(MEDIA_DEVICE_AUDIO_CAPTURE, device_id, name));
- base::RunLoop().RunUntilIdle();
+
+ // Block for completion.
+ base::RunLoop loop;
+ EXPECT_CALL(listener, Opened(MEDIA_DEVICE_AUDIO_CAPTURE, session_id))
+ .WillOnce(InvokeWithoutArgs(&loop, &base::RunLoop::Quit));
+ loop.Run();
+ media_stream_manager_.audio_input_device_manager()->UnregisterListener(
+ &listener);
+
return session_id;
}
@@ -186,6 +202,15 @@ class AudioInputDelegateTest : public testing::Test {
&event_handler_);
}
+ void SyncWithAudioThread() {
+ base::RunLoop().RunUntilIdle();
+
+ base::RunLoop run_loop;
+ audio_manager_.GetTaskRunner()->PostTask(
+ FROM_HERE, media::BindToCurrentLoop(run_loop.QuitClosure()));
+ run_loop.Run();
+ }
+
base::Optional<TestBrowserThreadBundle> thread_bundle_;
media::MockAudioManager audio_manager_;
media::AudioSystemImpl audio_system_;
@@ -233,112 +258,101 @@ TEST_F(AudioInputDelegateTest, CreateWebContentsCaptureStream) {
TEST_F(AudioInputDelegateTest, CreateOrdinaryCaptureStream) {
int session_id = MakeDeviceAvailable(kDefaultDeviceId, kDefaultDeviceName);
- auto delegate =
- CreateDelegate(kDefaultSharedMemoryCount, session_id, kDoNotEnableAGC);
- EXPECT_NE(delegate, nullptr);
-
StrictMock<MockAudioInputStream> stream;
EXPECT_CALL(stream, Open()).WillOnce(Return(true));
EXPECT_CALL(stream, SetAutomaticGainControl(false))
-
.WillOnce(Return(true));
EXPECT_CALL(stream, IsMuted()).WillOnce(Return(false));
EXPECT_CALL(event_handler_, MockOnStreamCreated(kStreamId, false));
bool created = false;
audio_manager_.SetMakeInputStreamCB(
base::BindRepeating(&MakeInputStreamCallback, &stream, &created));
+ auto delegate =
+ CreateDelegate(kDefaultSharedMemoryCount, session_id, kDoNotEnableAGC);
+ EXPECT_NE(delegate, nullptr);
+ SyncWithAudioThread();
- base::RunLoop().RunUntilIdle();
- delegate.reset();
EXPECT_CALL(stream, Close());
- base::RunLoop().RunUntilIdle();
+ delegate.reset();
+ SyncWithAudioThread();
}
TEST_F(AudioInputDelegateTest, CreateOrdinaryStreamWithAGC_AGCPropagates) {
int session_id = MakeDeviceAvailable(kDefaultDeviceId, kDefaultDeviceName);
- auto delegate =
- CreateDelegate(kDefaultSharedMemoryCount, session_id, kDoEnableAGC);
- EXPECT_NE(delegate, nullptr);
-
StrictMock<MockAudioInputStream> stream;
EXPECT_CALL(stream, Open()).WillOnce(Return(true));
EXPECT_CALL(stream, SetAutomaticGainControl(true))
-
.WillOnce(Return(true));
EXPECT_CALL(stream, IsMuted()).WillOnce(Return(false));
EXPECT_CALL(event_handler_, MockOnStreamCreated(kStreamId, false));
bool created = false;
audio_manager_.SetMakeInputStreamCB(
base::BindRepeating(&MakeInputStreamCallback, &stream, &created));
+ auto delegate =
+ CreateDelegate(kDefaultSharedMemoryCount, session_id, kDoEnableAGC);
+ EXPECT_NE(delegate, nullptr);
+ SyncWithAudioThread();
- base::RunLoop().RunUntilIdle();
- delegate.reset();
EXPECT_CALL(stream, Close());
- base::RunLoop().RunUntilIdle();
+ delegate.reset();
+ SyncWithAudioThread();
}
TEST_F(AudioInputDelegateTest, Record) {
int session_id = MakeDeviceAvailable(kDefaultDeviceId, kDefaultDeviceName);
- auto delegate =
- CreateDelegate(kDefaultSharedMemoryCount, session_id, kDoNotEnableAGC);
- EXPECT_NE(delegate, nullptr);
-
StrictMock<MockAudioInputStream> stream;
EXPECT_CALL(stream, Open()).WillOnce(Return(true));
EXPECT_CALL(stream, SetAutomaticGainControl(false))
-
.WillOnce(Return(true));
EXPECT_CALL(stream, IsMuted()).WillOnce(Return(false));
EXPECT_CALL(event_handler_, MockOnStreamCreated(kStreamId, false));
bool created = false;
audio_manager_.SetMakeInputStreamCB(
base::BindRepeating(&MakeInputStreamCallback, &stream, &created));
+ auto delegate =
+ CreateDelegate(kDefaultSharedMemoryCount, session_id, kDoNotEnableAGC);
+ EXPECT_NE(delegate, nullptr);
+ SyncWithAudioThread();
- base::RunLoop().RunUntilIdle();
-
- delegate->OnRecordStream();
EXPECT_CALL(stream, Start(NotNull()));
- base::RunLoop().RunUntilIdle();
+ delegate->OnRecordStream();
+ SyncWithAudioThread();
- delegate.reset();
EXPECT_CALL(stream, Stop());
EXPECT_CALL(stream, Close());
- base::RunLoop().RunUntilIdle();
+ delegate.reset();
+ SyncWithAudioThread();
}
TEST_F(AudioInputDelegateTest, SetVolume) {
int session_id = MakeDeviceAvailable(kDefaultDeviceId, kDefaultDeviceName);
- auto delegate =
- CreateDelegate(kDefaultSharedMemoryCount, session_id, kDoNotEnableAGC);
- EXPECT_NE(delegate, nullptr);
-
StrictMock<MockAudioInputStream> stream;
EXPECT_CALL(stream, Open()).WillOnce(Return(true));
EXPECT_CALL(stream, SetAutomaticGainControl(false))
-
.WillOnce(Return(true));
EXPECT_CALL(stream, IsMuted()).WillOnce(Return(false));
EXPECT_CALL(event_handler_, MockOnStreamCreated(kStreamId, false));
bool created = false;
audio_manager_.SetMakeInputStreamCB(
base::BindRepeating(&MakeInputStreamCallback, &stream, &created));
-
- base::RunLoop().RunUntilIdle();
-
- delegate->OnSetVolume(kNewVolume);
+ auto delegate =
+ CreateDelegate(kDefaultSharedMemoryCount, session_id, kDoNotEnableAGC);
+ EXPECT_NE(delegate, nullptr);
+ SyncWithAudioThread();
// Note: The AudioInputController is supposed to access the max volume of the
// stream and map [0, 1] to [0, max_volume].
EXPECT_CALL(stream, GetMaxVolume()).WillOnce(Return(kVolumeScale));
EXPECT_CALL(stream, SetVolume(DoubleEq(kNewVolume * kVolumeScale)));
- base::RunLoop().RunUntilIdle();
+ delegate->OnSetVolume(kNewVolume);
+ SyncWithAudioThread();
- delegate.reset();
EXPECT_CALL(stream, Close());
- base::RunLoop().RunUntilIdle();
+ delegate.reset();
+ SyncWithAudioThread();
}
} // namespace content
diff --git a/chromium/content/browser/renderer_host/media/audio_input_renderer_host.cc b/chromium/content/browser/renderer_host/media/audio_input_renderer_host.cc
index 227de774485..6d613a96ad1 100644
--- a/chromium/content/browser/renderer_host/media/audio_input_renderer_host.cc
+++ b/chromium/content/browser/renderer_host/media/audio_input_renderer_host.cc
@@ -17,6 +17,7 @@
#include "content/browser/renderer_host/media/audio_input_delegate_impl.h"
#include "content/browser/renderer_host/media/audio_input_device_manager.h"
#include "content/browser/renderer_host/media/media_stream_manager.h"
+#include "content/public/browser/browser_thread.h"
#include "media/audio/audio_manager.h"
namespace content {
diff --git a/chromium/content/browser/renderer_host/media/audio_input_renderer_host_unittest.cc b/chromium/content/browser/renderer_host/media/audio_input_renderer_host_unittest.cc
index b28fea1ca11..edfdea31c8c 100644
--- a/chromium/content/browser/renderer_host/media/audio_input_renderer_host_unittest.cc
+++ b/chromium/content/browser/renderer_host/media/audio_input_renderer_host_unittest.cc
@@ -9,7 +9,6 @@
#include "base/bind.h"
#include "base/command_line.h"
-#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
diff --git a/chromium/content/browser/renderer_host/media/audio_output_authorization_handler.cc b/chromium/content/browser/renderer_host/media/audio_output_authorization_handler.cc
index da89c36284c..83d47fd31e3 100644
--- a/chromium/content/browser/renderer_host/media/audio_output_authorization_handler.cc
+++ b/chromium/content/browser/renderer_host/media/audio_output_authorization_handler.cc
@@ -5,7 +5,6 @@
#include "content/browser/renderer_host/media/audio_output_authorization_handler.h"
#include "base/bind.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/task_runner_util.h"
#include "content/browser/media/media_devices_permission_checker.h"
diff --git a/chromium/content/browser/renderer_host/media/audio_output_authorization_handler_unittest.cc b/chromium/content/browser/renderer_host/media/audio_output_authorization_handler_unittest.cc
index 2e43aca4166..eccbda52379 100644
--- a/chromium/content/browser/renderer_host/media/audio_output_authorization_handler_unittest.cc
+++ b/chromium/content/browser/renderer_host/media/audio_output_authorization_handler_unittest.cc
@@ -8,10 +8,8 @@
#include "base/bind.h"
#include "base/command_line.h"
-#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/test/mock_callback.h"
-#include "content/browser/browser_thread_impl.h"
#include "content/public/test/mock_render_process_host.h"
#include "content/public/test/test_browser_context.h"
#include "content/public/test/test_browser_thread.h"
diff --git a/chromium/content/browser/renderer_host/media/audio_output_delegate_impl.cc b/chromium/content/browser/renderer_host/media/audio_output_delegate_impl.cc
index 98e7b64e274..da2c826ccb8 100644
--- a/chromium/content/browser/renderer_host/media/audio_output_delegate_impl.cc
+++ b/chromium/content/browser/renderer_host/media/audio_output_delegate_impl.cc
@@ -8,7 +8,6 @@
#include "base/bind.h"
#include "base/callback.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/stringprintf.h"
#include "content/browser/media/audio_stream_monitor.h"
#include "content/browser/media/capture/audio_mirroring_manager.h"
@@ -100,7 +99,6 @@ std::unique_ptr<media::AudioOutputDelegate> AudioOutputDelegateImpl::Create(
EventHandler* handler,
media::AudioManager* audio_manager,
media::mojom::AudioLogPtr audio_log,
- AudioMirroringManager* mirroring_manager,
MediaObserver* media_observer,
int stream_id,
int render_frame_id,
@@ -117,9 +115,8 @@ std::unique_ptr<media::AudioOutputDelegate> AudioOutputDelegateImpl::Create(
return std::make_unique<AudioOutputDelegateImpl>(
std::move(reader), std::move(socket), handler, audio_manager,
- std::move(audio_log), mirroring_manager, media_observer, stream_id,
- render_frame_id, render_process_id, params, std::move(observer),
- output_device_id);
+ std::move(audio_log), media_observer, stream_id, render_frame_id,
+ render_process_id, params, std::move(observer), output_device_id);
}
AudioOutputDelegateImpl::AudioOutputDelegateImpl(
@@ -128,7 +125,6 @@ AudioOutputDelegateImpl::AudioOutputDelegateImpl(
EventHandler* handler,
media::AudioManager* audio_manager,
media::mojom::AudioLogPtr audio_log,
- AudioMirroringManager* mirroring_manager,
MediaObserver* media_observer,
int stream_id,
int render_frame_id,
@@ -140,17 +136,13 @@ AudioOutputDelegateImpl::AudioOutputDelegateImpl(
audio_log_(std::move(audio_log)),
reader_(std::move(reader)),
foreign_socket_(std::move(foreign_socket)),
- mirroring_manager_(mirroring_manager),
stream_id_(stream_id),
- render_frame_id_(render_frame_id),
- render_process_id_(render_process_id),
observer_(std::move(observer)),
weak_factory_(this) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DCHECK(subscriber_);
DCHECK(audio_manager);
DCHECK(audio_log_);
- DCHECK(mirroring_manager_);
DCHECK(reader_);
DCHECK(observer_);
// Since the event handler never directly calls functions on |this| but rather
@@ -160,12 +152,11 @@ AudioOutputDelegateImpl::AudioOutputDelegateImpl(
weak_factory_.GetWeakPtr(), stream_id_);
controller_ = media::AudioOutputController::Create(
audio_manager, controller_event_handler_.get(), params, output_device_id,
+ AudioMirroringManager::ToGroupId(render_process_id, render_frame_id),
reader_.get());
DCHECK(controller_);
if (media_observer)
media_observer->OnCreatingAudioStream(render_process_id, render_frame_id);
- mirroring_manager_->AddDiverter(render_process_id, render_frame_id,
- controller_.get());
}
AudioOutputDelegateImpl::~AudioOutputDelegateImpl() {
@@ -178,26 +169,14 @@ AudioOutputDelegateImpl::~AudioOutputDelegateImpl() {
// the IO thread) when it's done closing, and it is only after that call that
// we can delete |controller_event_handler_| and |reader_|. By giving the
// closure ownership of these, we keep them alive until |controller_| is
- // closed. |mirroring_manager_| is a lazy instance, so passing it is safe.
+ // closed.
controller_->Close(base::BindOnce(
- [](AudioMirroringManager* mirroring_manager,
- std::unique_ptr<ControllerEventHandler> event_handler,
+ [](std::unique_ptr<ControllerEventHandler> event_handler,
std::unique_ptr<media::AudioSyncReader> reader,
scoped_refptr<media::AudioOutputController> controller) {
- // De-register the controller from the AudioMirroringManager now that
- // the controller has closed the AudioOutputStream and shut itself down.
- // This ensures that calling RemoveDiverter() here won't trigger the
- // controller to re-start the default AudioOutputStream and cause a
- // brief audio blip to come out the user's speakers.
- // http://crbug.com/474432
- //
- // It's fine if this task is canceled during shutdown, since the
- // mirroring manager doesn't require that all diverters are
- // removed.
- mirroring_manager->RemoveDiverter(controller.get());
+ // Objects pointed to by the arguments are deleted on out-of-scope here.
},
- mirroring_manager_, std::move(controller_event_handler_),
- std::move(reader_), controller_));
+ std::move(controller_event_handler_), std::move(reader_), controller_));
}
int AudioOutputDelegateImpl::GetStreamId() {
diff --git a/chromium/content/browser/renderer_host/media/audio_output_delegate_impl.h b/chromium/content/browser/renderer_host/media/audio_output_delegate_impl.h
index dae9af16270..824a99ce66b 100644
--- a/chromium/content/browser/renderer_host/media/audio_output_delegate_impl.h
+++ b/chromium/content/browser/renderer_host/media/audio_output_delegate_impl.h
@@ -16,7 +16,6 @@
#include "media/mojo/interfaces/audio_output_stream.mojom.h"
namespace content {
-class AudioMirroringManager;
class MediaObserver;
}
@@ -38,7 +37,6 @@ class CONTENT_EXPORT AudioOutputDelegateImpl
EventHandler* handler,
media::AudioManager* audio_manager,
media::mojom::AudioLogPtr audio_log,
- AudioMirroringManager* mirroring_manager,
MediaObserver* media_observer,
int stream_id,
int render_frame_id,
@@ -53,7 +51,6 @@ class CONTENT_EXPORT AudioOutputDelegateImpl
EventHandler* handler,
media::AudioManager* audio_manager,
media::mojom::AudioLogPtr audio_log,
- AudioMirroringManager* mirroring_manager,
MediaObserver* media_observer,
int stream_id,
int render_frame_id,
@@ -85,16 +82,13 @@ class CONTENT_EXPORT AudioOutputDelegateImpl
EventHandler* subscriber_;
const media::mojom::AudioLogPtr audio_log_;
// |controller_event_handler_| proxies events from controller to |this|.
- // |controller_event_handler_|, |reader_| and |mirroring_manager_| will
- // outlive |this|, see the destructor for details.
+ // |controller_event_handler_|, and |reader_| will outlive |this|, see the
+ // destructor for details.
std::unique_ptr<ControllerEventHandler> controller_event_handler_;
std::unique_ptr<media::AudioSyncReader> reader_;
std::unique_ptr<base::CancelableSyncSocket> foreign_socket_;
- AudioMirroringManager* mirroring_manager_;
scoped_refptr<media::AudioOutputController> controller_;
const int stream_id_;
- const int render_frame_id_;
- const int render_process_id_;
// This flag ensures that we only send OnStreamStateChanged notifications
// and (de)register with the stream monitor when the state actually changes.
diff --git a/chromium/content/browser/renderer_host/media/audio_output_delegate_impl_unittest.cc b/chromium/content/browser/renderer_host/media/audio_output_delegate_impl_unittest.cc
index f43a1499ebb..f474636086a 100644
--- a/chromium/content/browser/renderer_host/media/audio_output_delegate_impl_unittest.cc
+++ b/chromium/content/browser/renderer_host/media/audio_output_delegate_impl_unittest.cc
@@ -11,8 +11,6 @@
#include "base/bind.h"
#include "base/command_line.h"
-#include "base/memory/ptr_util.h"
-#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/sync_socket.h"
#include "content/browser/media/capture/audio_mirroring_manager.h"
@@ -157,6 +155,9 @@ class AudioOutputDelegateTest : public testing::Test {
audio_manager_.reset(new media::FakeAudioManager(
std::make_unique<media::AudioThreadImpl>(), &log_factory_));
+ audio_manager_->SetDiverterCallbacks(
+ mirroring_manager_.GetAddDiverterCallback(),
+ mirroring_manager_.GetRemoveDiverterCallback());
}
~AudioOutputDelegateTest() { audio_manager_->Shutdown(); }
@@ -194,16 +195,16 @@ class AudioOutputDelegateTest : public testing::Test {
Params(), socket.get());
AudioOutputDelegateImpl delegate(
std::move(reader), std::move(socket), &event_handler_,
- audio_manager_.get(), CreateDummyMojoAudioLog(), &mirroring_manager_,
- &media_observer_, kStreamId, kRenderFrameId, kRenderProcessId,
- Params(), std::move(observer_ptr), kDefaultDeviceId);
+ audio_manager_.get(), CreateDummyMojoAudioLog(), &media_observer_,
+ kStreamId, kRenderFrameId, kRenderProcessId, Params(),
+ std::move(observer_ptr), kDefaultDeviceId);
SyncWithAllThreads();
EXPECT_CALL(mirroring_manager_, RemoveDiverter(NotNull()));
}
SyncWithAllThreads();
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, done);
+ BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, std::move(done));
}
void PlayTest(base::Closure done, bool use_bound_observer) {
@@ -235,9 +236,9 @@ class AudioOutputDelegateTest : public testing::Test {
AudioOutputDelegateImpl delegate(
std::move(reader), std::move(socket), &event_handler_,
- audio_manager_.get(), CreateDummyMojoAudioLog(), &mirroring_manager_,
- &media_observer_, kStreamId, kRenderFrameId, kRenderProcessId,
- Params(), std::move(observer_ptr), kDefaultDeviceId);
+ audio_manager_.get(), CreateDummyMojoAudioLog(), &media_observer_,
+ kStreamId, kRenderFrameId, kRenderProcessId, Params(),
+ std::move(observer_ptr), kDefaultDeviceId);
if (!use_bound_observer)
observer_binding->Close();
@@ -249,7 +250,7 @@ class AudioOutputDelegateTest : public testing::Test {
EXPECT_CALL(mirroring_manager_, RemoveDiverter(NotNull()));
}
SyncWithAllThreads();
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, done);
+ BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, std::move(done));
}
void PauseTest(base::Closure done) {
@@ -269,9 +270,9 @@ class AudioOutputDelegateTest : public testing::Test {
Params(), socket.get());
AudioOutputDelegateImpl delegate(
std::move(reader), std::move(socket), &event_handler_,
- audio_manager_.get(), CreateDummyMojoAudioLog(), &mirroring_manager_,
- &media_observer_, kStreamId, kRenderFrameId, kRenderProcessId,
- Params(), std::move(observer_ptr), kDefaultDeviceId);
+ audio_manager_.get(), CreateDummyMojoAudioLog(), &media_observer_,
+ kStreamId, kRenderFrameId, kRenderProcessId, Params(),
+ std::move(observer_ptr), kDefaultDeviceId);
delegate.OnPauseStream();
@@ -280,7 +281,7 @@ class AudioOutputDelegateTest : public testing::Test {
EXPECT_CALL(mirroring_manager_, RemoveDiverter(NotNull()));
}
SyncWithAllThreads();
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, done);
+ BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, std::move(done));
}
void PlayPausePlayTest(base::Closure done) {
@@ -304,9 +305,9 @@ class AudioOutputDelegateTest : public testing::Test {
AudioOutputDelegateImpl delegate(
std::move(reader), std::move(socket), &event_handler_,
- audio_manager_.get(), CreateDummyMojoAudioLog(), &mirroring_manager_,
- &media_observer_, kStreamId, kRenderFrameId, kRenderProcessId,
- Params(), std::move(observer_ptr), kDefaultDeviceId);
+ audio_manager_.get(), CreateDummyMojoAudioLog(), &media_observer_,
+ kStreamId, kRenderFrameId, kRenderProcessId, Params(),
+ std::move(observer_ptr), kDefaultDeviceId);
delegate.OnPlayStream();
delegate.OnPauseStream();
@@ -317,7 +318,7 @@ class AudioOutputDelegateTest : public testing::Test {
EXPECT_CALL(mirroring_manager_, RemoveDiverter(NotNull()));
}
SyncWithAllThreads();
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, done);
+ BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, std::move(done));
}
void PlayPlayTest(base::Closure done) {
@@ -339,9 +340,9 @@ class AudioOutputDelegateTest : public testing::Test {
AudioOutputDelegateImpl delegate(
std::move(reader), std::move(socket), &event_handler_,
- audio_manager_.get(), CreateDummyMojoAudioLog(), &mirroring_manager_,
- &media_observer_, kStreamId, kRenderFrameId, kRenderProcessId,
- Params(), std::move(observer_ptr), kDefaultDeviceId);
+ audio_manager_.get(), CreateDummyMojoAudioLog(), &media_observer_,
+ kStreamId, kRenderFrameId, kRenderProcessId, Params(),
+ std::move(observer_ptr), kDefaultDeviceId);
delegate.OnPlayStream();
delegate.OnPlayStream();
@@ -351,7 +352,7 @@ class AudioOutputDelegateTest : public testing::Test {
EXPECT_CALL(mirroring_manager_, RemoveDiverter(NotNull()));
}
SyncWithAllThreads();
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, done);
+ BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, std::move(done));
}
void CreateDivertTest(base::Closure done) {
@@ -372,9 +373,9 @@ class AudioOutputDelegateTest : public testing::Test {
Params(), socket.get());
AudioOutputDelegateImpl delegate(
std::move(reader), std::move(socket), &event_handler_,
- audio_manager_.get(), CreateDummyMojoAudioLog(), &mirroring_manager_,
- &media_observer_, kStreamId, kRenderFrameId, kRenderProcessId,
- Params(), std::move(observer_ptr), kDefaultDeviceId);
+ audio_manager_.get(), CreateDummyMojoAudioLog(), &media_observer_,
+ kStreamId, kRenderFrameId, kRenderProcessId, Params(),
+ std::move(observer_ptr), kDefaultDeviceId);
delegate.GetControllerForTesting()->StartDiverting(&stream);
@@ -383,7 +384,7 @@ class AudioOutputDelegateTest : public testing::Test {
EXPECT_CALL(mirroring_manager_, RemoveDiverter(NotNull()));
}
SyncWithAllThreads();
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, done);
+ BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, std::move(done));
}
void CreateDivertPauseTest(base::Closure done) {
@@ -400,9 +401,9 @@ class AudioOutputDelegateTest : public testing::Test {
Params(), socket.get());
AudioOutputDelegateImpl delegate(
std::move(reader), std::move(socket), &event_handler_,
- audio_manager_.get(), CreateDummyMojoAudioLog(), &mirroring_manager_,
- &media_observer_, kStreamId, kRenderFrameId, kRenderProcessId,
- Params(), nullptr, kDefaultDeviceId);
+ audio_manager_.get(), CreateDummyMojoAudioLog(), &media_observer_,
+ kStreamId, kRenderFrameId, kRenderProcessId, Params(), nullptr,
+ kDefaultDeviceId);
delegate.GetControllerForTesting()->StartDiverting(&stream);
@@ -414,7 +415,7 @@ class AudioOutputDelegateTest : public testing::Test {
EXPECT_CALL(mirroring_manager_, RemoveDiverter(NotNull()));
}
SyncWithAllThreads();
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, done);
+ BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, std::move(done));
}
void PlayDivertTest(base::Closure done) {
@@ -436,9 +437,9 @@ class AudioOutputDelegateTest : public testing::Test {
Params(), socket.get());
AudioOutputDelegateImpl delegate(
std::move(reader), std::move(socket), &event_handler_,
- audio_manager_.get(), CreateDummyMojoAudioLog(), &mirroring_manager_,
- &media_observer_, kStreamId, kRenderFrameId, kRenderProcessId,
- Params(), std::move(observer_ptr), kDefaultDeviceId);
+ audio_manager_.get(), CreateDummyMojoAudioLog(), &media_observer_,
+ kStreamId, kRenderFrameId, kRenderProcessId, Params(),
+ std::move(observer_ptr), kDefaultDeviceId);
delegate.OnPlayStream();
delegate.GetControllerForTesting()->StartDiverting(&stream);
@@ -448,7 +449,7 @@ class AudioOutputDelegateTest : public testing::Test {
EXPECT_CALL(mirroring_manager_, RemoveDiverter(NotNull()));
}
SyncWithAllThreads();
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, done);
+ BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, std::move(done));
}
void TrampolineToUI(base::Closure done,
@@ -456,7 +457,7 @@ class AudioOutputDelegateTest : public testing::Test {
// Destruct and then sync since destruction will post some tasks.
delegate.reset();
SyncWithAllThreads();
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, done);
+ BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, std::move(done));
}
void ErrorTest(base::Closure done) {
@@ -476,8 +477,8 @@ class AudioOutputDelegateTest : public testing::Test {
Params(), socket.get());
auto delegate = std::make_unique<AudioOutputDelegateImpl>(
std::move(reader), std::move(socket), &event_handler_,
- audio_manager_.get(), CreateDummyMojoAudioLog(), &mirroring_manager_,
- &media_observer_, kStreamId, kRenderFrameId, kRenderProcessId, Params(),
+ audio_manager_.get(), CreateDummyMojoAudioLog(), &media_observer_,
+ kStreamId, kRenderFrameId, kRenderProcessId, Params(),
std::move(observer_ptr), kDefaultDeviceId);
delegate->OnPlayStream();
@@ -489,7 +490,7 @@ class AudioOutputDelegateTest : public testing::Test {
EXPECT_CALL(event_handler_, OnStreamError(kStreamId))
.WillOnce(media::RunClosure(media::BindToCurrentLoop(base::Bind(
&AudioOutputDelegateTest::TrampolineToUI, base::Unretained(this),
- done, base::Passed(&delegate)))));
+ std::move(done), base::Passed(&delegate)))));
}
void CreateAndDestroyTest(base::Closure done) {
@@ -509,12 +510,12 @@ class AudioOutputDelegateTest : public testing::Test {
Params(), socket.get());
AudioOutputDelegateImpl delegate(
std::move(reader), std::move(socket), &event_handler_,
- audio_manager_.get(), CreateDummyMojoAudioLog(), &mirroring_manager_,
- &media_observer_, kStreamId, kRenderFrameId, kRenderProcessId,
- Params(), std::move(observer_ptr), kDefaultDeviceId);
+ audio_manager_.get(), CreateDummyMojoAudioLog(), &media_observer_,
+ kStreamId, kRenderFrameId, kRenderProcessId, Params(),
+ std::move(observer_ptr), kDefaultDeviceId);
}
SyncWithAllThreads();
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, done);
+ BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, std::move(done));
}
void PlayAndDestroyTest(base::Closure done) {
@@ -535,16 +536,16 @@ class AudioOutputDelegateTest : public testing::Test {
Params(), socket.get());
AudioOutputDelegateImpl delegate(
std::move(reader), std::move(socket), &event_handler_,
- audio_manager_.get(), CreateDummyMojoAudioLog(), &mirroring_manager_,
- &media_observer_, kStreamId, kRenderFrameId, kRenderProcessId,
- Params(), std::move(observer_ptr), kDefaultDeviceId);
+ audio_manager_.get(), CreateDummyMojoAudioLog(), &media_observer_,
+ kStreamId, kRenderFrameId, kRenderProcessId, Params(),
+ std::move(observer_ptr), kDefaultDeviceId);
SyncWithAllThreads();
delegate.OnPlayStream();
}
SyncWithAllThreads();
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, done);
+ BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, std::move(done));
}
void ErrorAndDestroyTest(base::Closure done) {
@@ -565,15 +566,15 @@ class AudioOutputDelegateTest : public testing::Test {
Params(), socket.get());
AudioOutputDelegateImpl delegate(
std::move(reader), std::move(socket), &event_handler_,
- audio_manager_.get(), CreateDummyMojoAudioLog(), &mirroring_manager_,
- &media_observer_, kStreamId, kRenderFrameId, kRenderProcessId,
- Params(), std::move(observer_ptr), kDefaultDeviceId);
+ audio_manager_.get(), CreateDummyMojoAudioLog(), &media_observer_,
+ kStreamId, kRenderFrameId, kRenderProcessId, Params(),
+ std::move(observer_ptr), kDefaultDeviceId);
SyncWithAllThreads();
delegate.GetControllerForTesting()->OnError();
}
SyncWithAllThreads();
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, done);
+ BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, std::move(done));
}
protected:
@@ -590,11 +591,7 @@ class AudioOutputDelegateTest : public testing::Test {
// New tasks might be posted while we are syncing, but in every iteration at
// least one task will be run. 20 iterations should be enough for our code.
for (int i = 0; i < 20; ++i) {
- {
- base::MessageLoop::ScopedNestableTaskAllower allower(
- base::MessageLoop::current());
- base::RunLoop().RunUntilIdle();
- }
+ base::RunLoop(base::RunLoop::Type::kNestableTasksAllowed).RunUntilIdle();
SyncWith(BrowserThread::GetTaskRunnerForThread(BrowserThread::UI));
SyncWith(audio_manager_->GetWorkerTaskRunner());
}
diff --git a/chromium/content/browser/renderer_host/media/audio_renderer_host.cc b/chromium/content/browser/renderer_host/media/audio_renderer_host.cc
index 95603242cfe..6637ebf3354 100644
--- a/chromium/content/browser/renderer_host/media/audio_renderer_host.cc
+++ b/chromium/content/browser/renderer_host/media/audio_renderer_host.cc
@@ -14,7 +14,6 @@
#include "content/browser/bad_message.h"
#include "content/browser/browser_main_loop.h"
#include "content/browser/media/audio_stream_monitor.h"
-#include "content/browser/media/capture/audio_mirroring_manager.h"
#include "content/browser/media/media_internals.h"
#include "content/browser/renderer_host/media/audio_input_device_manager.h"
#include "content/browser/renderer_host/media/audio_output_authorization_handler.h"
@@ -22,6 +21,7 @@
#include "content/browser/renderer_host/media/audio_output_stream_observer_impl.h"
#include "content/browser/renderer_host/media/media_stream_manager.h"
#include "content/common/media/audio_messages.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/media_device_id.h"
#include "content/public/browser/media_observer.h"
@@ -61,12 +61,10 @@ void ValidateRenderFrameId(int render_process_id,
AudioRendererHost::AudioRendererHost(int render_process_id,
media::AudioManager* audio_manager,
media::AudioSystem* audio_system,
- AudioMirroringManager* mirroring_manager,
MediaStreamManager* media_stream_manager)
: BrowserMessageFilter(AudioMsgStart),
render_process_id_(render_process_id),
audio_manager_(audio_manager),
- mirroring_manager_(mirroring_manager),
media_stream_manager_(media_stream_manager),
authorization_handler_(audio_system,
media_stream_manager,
@@ -296,9 +294,9 @@ void AudioRendererHost::OnCreateStream(int stream_id,
mojo::MakeRequest(&observer_ptr));
auto delegate = AudioOutputDelegateImpl::Create(
- this, audio_manager_, std::move(audio_log_ptr), mirroring_manager_,
- media_observer, stream_id, render_frame_id, render_process_id_, params,
- std::move(observer_ptr), device_unique_id);
+ this, audio_manager_, std::move(audio_log_ptr), media_observer, stream_id,
+ render_frame_id, render_process_id_, params, std::move(observer_ptr),
+ device_unique_id);
if (delegate)
delegates_.push_back(std::move(delegate));
else
diff --git a/chromium/content/browser/renderer_host/media/audio_renderer_host.h b/chromium/content/browser/renderer_host/media/audio_renderer_host.h
index f9506bff573..d981ae8e014 100644
--- a/chromium/content/browser/renderer_host/media/audio_renderer_host.h
+++ b/chromium/content/browser/renderer_host/media/audio_renderer_host.h
@@ -65,7 +65,6 @@ class AudioSystem;
namespace content {
-class AudioMirroringManager;
class MediaStreamManager;
class CONTENT_EXPORT AudioRendererHost
@@ -76,7 +75,6 @@ class CONTENT_EXPORT AudioRendererHost
AudioRendererHost(int render_process_id,
media::AudioManager* audio_manager,
media::AudioSystem* audio_system,
- AudioMirroringManager* mirroring_manager,
MediaStreamManager* media_stream_manager);
// BrowserMessageFilter implementation.
@@ -186,7 +184,6 @@ class CONTENT_EXPORT AudioRendererHost
const int render_process_id_;
media::AudioManager* const audio_manager_;
- AudioMirroringManager* const mirroring_manager_;
// Used to access to AudioInputDeviceManager.
MediaStreamManager* media_stream_manager_;
diff --git a/chromium/content/browser/renderer_host/media/audio_renderer_host_unittest.cc b/chromium/content/browser/renderer_host/media/audio_renderer_host_unittest.cc
index 4518c1723a6..e60a118f507 100644
--- a/chromium/content/browser/renderer_host/media/audio_renderer_host_unittest.cc
+++ b/chromium/content/browser/renderer_host/media/audio_renderer_host_unittest.cc
@@ -11,7 +11,6 @@
#include "base/bind.h"
#include "base/command_line.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/sync_socket.h"
#include "base/synchronization/lock.h"
@@ -105,12 +104,10 @@ class MockAudioRendererHost : public AudioRendererHost {
int render_process_id,
media::AudioManager* audio_manager,
media::AudioSystem* audio_system,
- AudioMirroringManager* mirroring_manager,
MediaStreamManager* media_stream_manager)
: AudioRendererHost(render_process_id,
audio_manager,
audio_system,
- mirroring_manager,
media_stream_manager),
shared_memory_length_(0),
auth_run_loop_(auth_run_loop) {}
@@ -224,6 +221,9 @@ class AudioRendererHostTest : public RenderViewHostTestHarness {
RenderViewHostTestHarness::SetUp();
audio_manager_ =
std::make_unique<FakeAudioManagerWithAssociations>(&log_factory_);
+ audio_manager_->SetDiverterCallbacks(
+ mirroring_manager_.GetAddDiverterCallback(),
+ mirroring_manager_.GetRemoveDiverterCallback());
audio_system_ =
std::make_unique<media::AudioSystemImpl>(audio_manager_.get());
media_stream_manager_ = std::make_unique<MediaStreamManager>(
@@ -231,7 +231,7 @@ class AudioRendererHostTest : public RenderViewHostTestHarness {
auth_run_loop_ = std::make_unique<base::RunLoop>();
host_ = base::MakeRefCounted<MockAudioRendererHost>(
auth_run_loop_.get(), process()->GetID(), audio_manager_.get(),
- audio_system_.get(), &mirroring_manager_, media_stream_manager_.get());
+ audio_system_.get(), media_stream_manager_.get());
// Simulate IPC channel connected.
host_->set_peer_process_for_testing(base::Process::Current());
diff --git a/chromium/content/browser/renderer_host/media/fake_video_capture_device_launcher.cc b/chromium/content/browser/renderer_host/media/fake_video_capture_device_launcher.cc
index 6850c3a35bc..5874c901f67 100644
--- a/chromium/content/browser/renderer_host/media/fake_video_capture_device_launcher.cc
+++ b/chromium/content/browser/renderer_host/media/fake_video_capture_device_launcher.cc
@@ -80,7 +80,7 @@ void FakeVideoCaptureDeviceLauncher::LaunchDeviceAsync(
auto device_client = std::make_unique<media::VideoCaptureDeviceClient>(
std::make_unique<media::VideoFrameReceiverOnTaskRunner>(
receiver, base::ThreadTaskRunnerHandle::Get()),
- std::move(buffer_pool), empty_jpeg_decoder_factory_cb);
+ std::move(buffer_pool), std::move(empty_jpeg_decoder_factory_cb));
device->AllocateAndStart(params, std::move(device_client));
auto launched_device =
std::make_unique<FakeLaunchedVideoCaptureDevice>(std::move(device));
diff --git a/chromium/content/browser/renderer_host/media/in_process_video_capture_provider.h b/chromium/content/browser/renderer_host/media/in_process_video_capture_provider.h
index b713f0da494..fa45fbc7d00 100644
--- a/chromium/content/browser/renderer_host/media/in_process_video_capture_provider.h
+++ b/chromium/content/browser/renderer_host/media/in_process_video_capture_provider.h
@@ -5,7 +5,6 @@
#ifndef CONTENT_BROWSER_RENDERER_HOST_MEDIA_IN_PROCESS_VIDEO_CAPTURE_SYSTEM_H_
#define CONTENT_BROWSER_RENDERER_HOST_MEDIA_IN_PROCESS_VIDEO_CAPTURE_SYSTEM_H_
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/single_thread_task_runner.h"
#include "content/browser/renderer_host/media/video_capture_provider.h"
diff --git a/chromium/content/browser/renderer_host/media/media_devices_dispatcher_host.cc b/chromium/content/browser/renderer_host/media/media_devices_dispatcher_host.cc
index dbb2070499c..07bcb4cd97b 100644
--- a/chromium/content/browser/renderer_host/media/media_devices_dispatcher_host.cc
+++ b/chromium/content/browser/renderer_host/media/media_devices_dispatcher_host.cc
@@ -10,7 +10,6 @@
#include "base/bind_helpers.h"
#include "base/command_line.h"
-#include "base/memory/ptr_util.h"
#include "base/task_runner_util.h"
#include "content/browser/bad_message.h"
#include "content/browser/media/media_devices_permission_checker.h"
@@ -33,31 +32,6 @@ namespace content {
namespace {
-// Resolutions used if the source doesn't support capability enumeration.
-struct {
- int width;
- int height;
-} const kFallbackVideoResolutions[] = {{1920, 1080}, {1280, 720}, {960, 720},
- {640, 480}, {640, 360}, {320, 240},
- {320, 180}};
-
-// Frame rates for sources with no support for capability enumeration.
-const int kFallbackVideoFrameRates[] = {30, 60};
-
-blink::mojom::FacingMode ToFacingMode(media::VideoFacingMode facing_mode) {
- switch (facing_mode) {
- case media::MEDIA_VIDEO_FACING_NONE:
- return blink::mojom::FacingMode::NONE;
- case media::MEDIA_VIDEO_FACING_USER:
- return blink::mojom::FacingMode::USER;
- case media::MEDIA_VIDEO_FACING_ENVIRONMENT:
- return blink::mojom::FacingMode::ENVIRONMENT;
- default:
- NOTREACHED();
- return blink::mojom::FacingMode::NONE;
- }
-}
-
std::vector<blink::mojom::AudioInputDeviceCapabilitiesPtr>
ToVectorAudioInputDeviceCapabilitiesPtr(
const std::vector<blink::mojom::AudioInputDeviceCapabilities>&
@@ -122,6 +96,7 @@ void MediaDevicesDispatcherHost::EnumerateDevices(
bool request_audio_input,
bool request_video_input,
bool request_audio_output,
+ bool request_video_input_capabilities,
EnumerateDevicesCallback client_callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
@@ -138,7 +113,8 @@ void MediaDevicesDispatcherHost::EnumerateDevices(
media_stream_manager_->media_devices_manager()->EnumerateDevices(
render_process_id_, render_frame_id_, group_id_salt_base_,
- devices_to_enumerate, std::move(client_callback));
+ devices_to_enumerate, request_video_input_capabilities,
+ std::move(client_callback));
}
void MediaDevicesDispatcherHost::GetVideoInputCapabilities(
@@ -247,17 +223,18 @@ void MediaDevicesDispatcherHost::FinalizeGetVideoInputCapabilities(
blink::mojom::VideoInputDeviceCapabilities::New();
capabilities->device_id = std::move(hmac_device_id);
capabilities->formats =
- GetVideoInputFormats(descriptor.device_id, true /* try_in_use_first */);
- capabilities->facing_mode = ToFacingMode(descriptor.facing);
+ media_stream_manager_->media_devices_manager()->GetVideoInputFormats(
+ descriptor.device_id, true /* try_in_use_first */);
+ capabilities->facing_mode = descriptor.facing;
#if defined(OS_ANDROID)
// On Android, the facing mode is not available in the |facing| field,
// but is available as part of the label.
// TODO(guidou): Remove this code once the |facing| field is supported
// on Android. See http://crbug.com/672856.
if (descriptor.GetNameAndModel().find("front") != std::string::npos)
- capabilities->facing_mode = blink::mojom::FacingMode::USER;
+ capabilities->facing_mode = media::MEDIA_VIDEO_FACING_USER;
else if (descriptor.GetNameAndModel().find("back") != std::string::npos)
- capabilities->facing_mode = blink::mojom::FacingMode::ENVIRONMENT;
+ capabilities->facing_mode = media::MEDIA_VIDEO_FACING_ENVIRONMENT;
#endif
if (descriptor.device_id == default_device_id) {
video_input_capabilities.insert(video_input_capabilities.begin(),
@@ -310,53 +287,15 @@ void MediaDevicesDispatcherHost::FinalizeGetVideoInputDeviceFormats(
if (DoesMediaDeviceIDMatchHMAC(device_id_salt, security_origin, device_id,
descriptor.device_id)) {
std::move(client_callback)
- .Run(GetVideoInputFormats(descriptor.device_id, try_in_use_first));
+ .Run(media_stream_manager_->media_devices_manager()
+ ->GetVideoInputFormats(descriptor.device_id,
+ try_in_use_first));
return;
}
}
std::move(client_callback).Run(media::VideoCaptureFormats());
}
-media::VideoCaptureFormats MediaDevicesDispatcherHost::GetVideoInputFormats(
- const std::string& device_id,
- bool try_in_use_first) {
- DCHECK_CURRENTLY_ON(BrowserThread::IO);
- media::VideoCaptureFormats formats;
-
- if (try_in_use_first) {
- base::Optional<media::VideoCaptureFormat> format =
- media_stream_manager_->video_capture_manager()->GetDeviceFormatInUse(
- MEDIA_DEVICE_VIDEO_CAPTURE, device_id);
- if (format.has_value()) {
- formats.push_back(format.value());
- return formats;
- }
- }
-
- media_stream_manager_->video_capture_manager()->GetDeviceSupportedFormats(
- device_id, &formats);
- // Remove formats that have zero resolution.
- formats.erase(std::remove_if(formats.begin(), formats.end(),
- [](const media::VideoCaptureFormat& format) {
- return format.frame_size.GetArea() <= 0;
- }),
- formats.end());
-
- // If the device does not report any valid format, use a fallback list of
- // standard formats.
- if (formats.empty()) {
- for (const auto& resolution : kFallbackVideoResolutions) {
- for (const auto frame_rate : kFallbackVideoFrameRates) {
- formats.push_back(media::VideoCaptureFormat(
- gfx::Size(resolution.width, resolution.height), frame_rate,
- media::PIXEL_FORMAT_I420));
- }
- }
- }
-
- return formats;
-}
-
struct MediaDevicesDispatcherHost::AudioInputCapabilitiesRequest {
std::string device_id_salt;
url::Origin security_origin;
diff --git a/chromium/content/browser/renderer_host/media/media_devices_dispatcher_host.h b/chromium/content/browser/renderer_host/media/media_devices_dispatcher_host.h
index a605b18ac5d..6098e6167c8 100644
--- a/chromium/content/browser/renderer_host/media/media_devices_dispatcher_host.h
+++ b/chromium/content/browser/renderer_host/media/media_devices_dispatcher_host.h
@@ -15,11 +15,9 @@
#include "content/browser/renderer_host/media/media_devices_manager.h"
#include "content/common/content_export.h"
#include "media/capture/video/video_capture_device_descriptor.h"
-#include "third_party/WebKit/public/platform/modules/mediastream/media_devices.mojom.h"
+#include "third_party/blink/public/platform/modules/mediastream/media_devices.mojom.h"
#include "url/origin.h"
-using blink::mojom::MediaDeviceType;
-
namespace content {
class MediaStreamManager;
@@ -41,6 +39,7 @@ class CONTENT_EXPORT MediaDevicesDispatcherHost
void EnumerateDevices(bool request_audio_input,
bool request_video_input,
bool request_audio_output,
+ bool request_video_input_capabilities,
EnumerateDevicesCallback client_callback) override;
void GetVideoInputCapabilities(
GetVideoInputCapabilitiesCallback client_callback) override;
@@ -111,13 +110,6 @@ class CONTENT_EXPORT MediaDevicesDispatcherHost
const url::Origin& security_origin,
const media::VideoCaptureDeviceDescriptors& device_descriptors);
- // Returns the supported video formats for the given |device_id|.
- // If |try_in_use_first| is true and the device is being used, only the format
- // in use is returned. Otherwise, all formats supported by the device are
- // returned.
- media::VideoCaptureFormats GetVideoInputFormats(const std::string& device_id,
- bool try_in_use_first);
-
// The following const fields can be accessed on any thread.
const int render_process_id_;
const int render_frame_id_;
diff --git a/chromium/content/browser/renderer_host/media/media_devices_dispatcher_host_unittest.cc b/chromium/content/browser/renderer_host/media/media_devices_dispatcher_host_unittest.cc
index 231c7833544..0647a6d80eb 100644
--- a/chromium/content/browser/renderer_host/media/media_devices_dispatcher_host_unittest.cc
+++ b/chromium/content/browser/renderer_host/media/media_devices_dispatcher_host_unittest.cc
@@ -13,7 +13,6 @@
#include "base/bind.h"
#include "base/command_line.h"
-#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "base/threading/thread_task_runner_handle.h"
@@ -37,6 +36,7 @@
#include "testing/gtest/include/gtest/gtest.h"
#include "url/origin.h"
+using blink::mojom::MediaDeviceType;
using testing::_;
using testing::SaveArg;
using testing::InvokeWithoutArgs;
@@ -60,7 +60,7 @@ void PhysicalDevicesEnumerated(base::Closure quit_closure,
MediaDeviceEnumeration* out,
const MediaDeviceEnumeration& enumeration) {
*out = enumeration;
- quit_closure.Run();
+ std::move(quit_closure).Run();
}
class MockMediaDevicesListener : public blink::mojom::MediaDevicesListener {
@@ -233,7 +233,9 @@ class MediaDevicesDispatcherHostTest : public testing::TestWithParam<GURL> {
protected:
void DevicesEnumerated(
const base::Closure& closure,
- const std::vector<std::vector<MediaDeviceInfo>>& devices) {
+ const std::vector<std::vector<MediaDeviceInfo>>& devices,
+ std::vector<blink::mojom::VideoInputDeviceCapabilitiesPtr>
+ video_input_capabilities) {
enumerated_devices_ = devices;
closure.Run();
}
@@ -248,6 +250,7 @@ class MediaDevicesDispatcherHostTest : public testing::TestWithParam<GURL> {
base::RunLoop run_loop;
host_->EnumerateDevices(
enumerate_audio_input, enumerate_video_input, enumerate_audio_output,
+ false,
base::BindOnce(&MediaDevicesDispatcherHostTest::DevicesEnumerated,
base::Unretained(this), run_loop.QuitClosure()));
run_loop.Run();
diff --git a/chromium/content/browser/renderer_host/media/media_devices_manager.cc b/chromium/content/browser/renderer_host/media/media_devices_manager.cc
index d1eb9e92d9e..ff76d268e72 100644
--- a/chromium/content/browser/renderer_host/media/media_devices_manager.cc
+++ b/chromium/content/browser/renderer_host/media/media_devices_manager.cc
@@ -37,6 +37,17 @@ namespace content {
namespace {
+// Resolutions used if the source doesn't support capability enumeration.
+struct {
+ uint16_t width;
+ uint16_t height;
+} const kFallbackVideoResolutions[] = {{1920, 1080}, {1280, 720}, {960, 720},
+ {640, 480}, {640, 360}, {320, 240},
+ {320, 180}};
+
+// Frame rates for sources with no support for capability enumeration.
+const uint16_t kFallbackVideoFrameRates[] = {30, 60};
+
// Private helper method to generate a string for the log message that lists the
// human readable names of |devices|.
std::string GetLogMessageString(MediaDeviceType device_type,
@@ -84,6 +95,21 @@ std::string VideoLabelWithoutModelID(const std::string& label) {
return label.substr(0, idx - 1);
}
+bool LabelHasUSBModel(const std::string& label) {
+ return label.size() >= 11 && label[label.size() - 11] == '(' &&
+ label[label.size() - 6] == ':' && label[label.size() - 1] == ')';
+}
+
+std::string GetUSBModelFromLabel(const std::string& label) {
+ DCHECK(LabelHasUSBModel(label));
+ return label.substr(label.size() - 10, 9);
+}
+
+bool IsRealAudioDeviceID(const std::string& device_id) {
+ return !media::AudioDeviceDescription::IsDefaultDevice(device_id) &&
+ !media::AudioDeviceDescription::IsCommunicationsDevice(device_id);
+}
+
} // namespace
std::string GuessVideoGroupID(const MediaDeviceInfoArray& audio_infos,
@@ -95,25 +121,55 @@ std::string GuessVideoGroupID(const MediaDeviceInfoArray& audio_infos,
if (video_label.size() <= 3)
return video_info.device_id;
- auto equals_lambda = [&video_label](const MediaDeviceInfo& info) {
- return info.label.find(video_label) != std::string::npos;
- };
+ std::function<bool(const MediaDeviceInfo&)>
+ video_label_is_included_in_audio_label =
+ [&video_label](const MediaDeviceInfo& audio_info) {
+ return audio_info.label.find(video_label) != std::string::npos;
+ };
+
+ bool video_has_usb_model = LabelHasUSBModel(video_info.label);
+ std::string video_usb_model = video_has_usb_model
+ ? GetUSBModelFromLabel(video_info.label)
+ : std::string();
+ std::function<bool(const MediaDeviceInfo&)> usb_model_matches =
+ [video_has_usb_model,
+ &video_usb_model](const MediaDeviceInfo& audio_info) {
+ return video_has_usb_model && LabelHasUSBModel(audio_info.label)
+ ? video_usb_model == GetUSBModelFromLabel(audio_info.label)
+ : false;
+ };
+
+ for (auto* lambda :
+ {&video_label_is_included_in_audio_label, &usb_model_matches}) {
+ // The label for the default and communication audio devices may contain the
+ // same label as the real devices, so they should be ignored when trying to
+ // find unique matches.
+ auto real_device_matches = [lambda](const MediaDeviceInfo& audio_info) {
+ return IsRealAudioDeviceID(audio_info.device_id) && (*lambda)(audio_info);
+ };
+ auto it_first = std::find_if(audio_infos.begin(), audio_infos.end(),
+ real_device_matches);
+ if (it_first == audio_infos.end())
+ continue;
- auto it_first =
- std::find_if(audio_infos.begin(), audio_infos.end(), equals_lambda);
- if (it_first == audio_infos.end())
- return video_info.device_id;
+ auto it = it_first;
+ bool duplicate_found = false;
+ while ((it = std::find_if(it + 1, audio_infos.end(),
+ real_device_matches)) != audio_infos.end()) {
+ // If there is more than one match, it is impossible to know which group
+ // ID is the correct one. This may occur if multiple devices of the same
+ // model are installed.
+ if (it->group_id != it_first->group_id) {
+ duplicate_found = true;
+ break;
+ }
+ }
- auto it = it_first;
- while ((it = std::find_if(it + 1, audio_infos.end(), equals_lambda)) !=
- audio_infos.end()) {
- // If the label appears with more than one group ID, it is impossible to
- // know which group ID is the correct one.
- if (it->group_id != it_first->group_id)
- return video_info.device_id;
+ if (!duplicate_found)
+ return it_first->group_id;
}
- return it_first->group_id;
+ return video_info.device_id;
}
struct MediaDevicesManager::EnumerationRequest {
@@ -258,6 +314,7 @@ void MediaDevicesManager::EnumerateDevices(
int render_frame_id,
const std::string& group_id_salt_base,
const BoolDeviceTypes& requested_types,
+ bool request_video_input_capabilities,
EnumerateDevicesCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
@@ -268,7 +325,7 @@ void MediaDevicesManager::EnumerateDevices(
base::BindOnce(&MediaDevicesManager::CheckPermissionsForEnumerateDevices,
weak_factory_.GetWeakPtr(), render_process_id,
render_frame_id, group_id_salt_base, requested_types,
- std::move(callback)));
+ request_video_input_capabilities, std::move(callback)));
}
uint32_t MediaDevicesManager::SubscribeDeviceChangeNotifications(
@@ -387,6 +444,45 @@ void MediaDevicesManager::OnDevicesChanged(
}
}
+media::VideoCaptureFormats MediaDevicesManager::GetVideoInputFormats(
+ const std::string& device_id,
+ bool try_in_use_first) {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+ media::VideoCaptureFormats formats;
+
+ if (try_in_use_first) {
+ base::Optional<media::VideoCaptureFormat> format =
+ video_capture_manager_->GetDeviceFormatInUse(MEDIA_DEVICE_VIDEO_CAPTURE,
+ device_id);
+ if (format.has_value()) {
+ formats.push_back(format.value());
+ return formats;
+ }
+ }
+
+ video_capture_manager_->GetDeviceSupportedFormats(device_id, &formats);
+ // Remove formats that have zero resolution.
+ formats.erase(std::remove_if(formats.begin(), formats.end(),
+ [](const media::VideoCaptureFormat& format) {
+ return format.frame_size.GetArea() <= 0;
+ }),
+ formats.end());
+
+ // If the device does not report any valid format, use a fallback list of
+ // standard formats.
+ if (formats.empty()) {
+ for (const auto& resolution : kFallbackVideoResolutions) {
+ for (const auto frame_rate : kFallbackVideoFrameRates) {
+ formats.push_back(media::VideoCaptureFormat(
+ gfx::Size(resolution.width, resolution.height), frame_rate,
+ media::PIXEL_FORMAT_I420));
+ }
+ }
+ }
+
+ return formats;
+}
+
MediaDeviceInfoArray MediaDevicesManager::GetCachedDeviceInfo(
MediaDeviceType type) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
@@ -411,6 +507,7 @@ void MediaDevicesManager::CheckPermissionsForEnumerateDevices(
int render_frame_id,
const std::string& group_id_salt_base,
const BoolDeviceTypes& requested_types,
+ bool request_video_input_capabilities,
EnumerateDevicesCallback callback,
const std::pair<std::string, url::Origin>& salt_and_origin) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
@@ -418,13 +515,15 @@ void MediaDevicesManager::CheckPermissionsForEnumerateDevices(
requested_types, render_process_id, render_frame_id,
base::BindOnce(&MediaDevicesManager::OnPermissionsCheckDone,
weak_factory_.GetWeakPtr(), group_id_salt_base,
- requested_types, std::move(callback),
- salt_and_origin.first, salt_and_origin.second));
+ requested_types, request_video_input_capabilities,
+ std::move(callback), salt_and_origin.first,
+ salt_and_origin.second));
}
void MediaDevicesManager::OnPermissionsCheckDone(
const std::string& group_id_salt_base,
const MediaDevicesManager::BoolDeviceTypes& requested_types,
+ bool request_video_input_capabilities,
EnumerateDevicesCallback callback,
const std::string& device_id_salt,
const url::Origin& security_origin,
@@ -434,13 +533,15 @@ void MediaDevicesManager::OnPermissionsCheckDone(
requested_types,
base::BindRepeating(&MediaDevicesManager::OnDevicesEnumerated,
weak_factory_.GetWeakPtr(), group_id_salt_base,
- requested_types, base::Passed(&callback),
- device_id_salt, security_origin, has_permissions));
+ requested_types, request_video_input_capabilities,
+ base::Passed(&callback), device_id_salt,
+ security_origin, has_permissions));
}
void MediaDevicesManager::OnDevicesEnumerated(
const std::string& group_id_salt_base,
const MediaDevicesManager::BoolDeviceTypes& requested_types,
+ bool request_video_input_capabilities,
EnumerateDevicesCallback callback,
const std::string& device_id_salt,
const url::Origin& security_origin,
@@ -448,6 +549,9 @@ void MediaDevicesManager::OnDevicesEnumerated(
const MediaDeviceEnumeration& enumeration) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
std::string group_id_salt = group_id_salt_base + device_id_salt;
+ const bool video_input_capabilities_requested =
+ has_permissions[MEDIA_DEVICE_TYPE_VIDEO_INPUT] &&
+ request_video_input_capabilities;
MediaDeviceInfoArray video_device_infos =
enumeration[MEDIA_DEVICE_TYPE_VIDEO_INPUT];
@@ -461,16 +565,55 @@ void MediaDevicesManager::OnDevicesEnumerated(
if (!requested_types[i])
continue;
- const MediaDeviceInfoArray& device_infos =
- i == MEDIA_DEVICE_TYPE_VIDEO_INPUT ? video_device_infos
- : enumeration[i];
- for (const auto& device_info : device_infos) {
- result[i].push_back(TranslateMediaDeviceInfo(
- has_permissions[i], device_id_salt, group_id_salt, security_origin,
- device_info));
+ if (i == MEDIA_DEVICE_TYPE_VIDEO_INPUT) {
+ for (const auto& device_info : video_device_infos) {
+ MediaDeviceInfo translated_device_info = TranslateMediaDeviceInfo(
+ has_permissions[i], device_id_salt, group_id_salt, security_origin,
+ device_info);
+ if (video_input_capabilities_requested)
+ translated_device_info.video_facing = device_info.video_facing;
+ result[i].push_back(translated_device_info);
+ }
+ } else {
+ for (const auto& device_info : enumeration[i]) {
+ result[i].push_back(TranslateMediaDeviceInfo(
+ has_permissions[i], device_id_salt, group_id_salt, security_origin,
+ device_info));
+ }
}
}
- std::move(callback).Run(result);
+
+ std::move(callback).Run(
+ std::move(result),
+ video_input_capabilities_requested
+ ? ComputeVideoInputCapabilities(result[MEDIA_DEVICE_TYPE_VIDEO_INPUT])
+ : std::vector<VideoInputDeviceCapabilitiesPtr>());
+}
+
+std::vector<VideoInputDeviceCapabilitiesPtr>
+MediaDevicesManager::ComputeVideoInputCapabilities(
+ const MediaDeviceInfoArray& device_infos) {
+ std::vector<VideoInputDeviceCapabilitiesPtr> video_input_capabilities;
+ for (const auto& device_info : device_infos) {
+ VideoInputDeviceCapabilitiesPtr capabilities =
+ blink::mojom::VideoInputDeviceCapabilities::New();
+ capabilities->device_id = device_info.device_id;
+ capabilities->formats = GetVideoInputFormats(device_info.device_id,
+ false /* try_in_use_first */);
+ capabilities->facing_mode = device_info.video_facing;
+#if defined(OS_ANDROID)
+ // On Android, the facing mode is not available in the |facing| field,
+ // but is available as part of the label.
+ // TODO(guidou): Remove this code once the |facing| field is supported
+ // on Android. See http://crbug.com/672856.
+ if (device_info.label.find("front") != std::string::npos)
+ capabilities->facing_mode = media::MEDIA_VIDEO_FACING_USER;
+ else if (device_info.label.find("back") != std::string::npos)
+ capabilities->facing_mode = media::MEDIA_VIDEO_FACING_ENVIRONMENT;
+#endif
+ video_input_capabilities.push_back(std::move(capabilities));
+ }
+ return video_input_capabilities;
}
void MediaDevicesManager::DoEnumerateDevices(MediaDeviceType type) {
diff --git a/chromium/content/browser/renderer_host/media/media_devices_manager.h b/chromium/content/browser/renderer_host/media/media_devices_manager.h
index fbe0e048870..27eb038bbb9 100644
--- a/chromium/content/browser/renderer_host/media/media_devices_manager.h
+++ b/chromium/content/browser/renderer_host/media/media_devices_manager.h
@@ -21,7 +21,10 @@
#include "content/common/media/media_devices.h"
#include "media/audio/audio_device_description.h"
#include "media/capture/video/video_capture_device_descriptor.h"
-#include "third_party/WebKit/public/platform/modules/mediastream/media_devices.mojom.h"
+#include "media/capture/video_capture_types.h"
+#include "third_party/blink/public/platform/modules/mediastream/media_devices.mojom.h"
+
+using blink::mojom::VideoInputDeviceCapabilitiesPtr;
namespace media {
class AudioSystem;
@@ -55,7 +58,8 @@ class CONTENT_EXPORT MediaDevicesManager
using EnumerationCallback =
base::Callback<void(const MediaDeviceEnumeration&)>;
using EnumerateDevicesCallback =
- base::OnceCallback<void(const std::vector<MediaDeviceInfoArray>&)>;
+ base::OnceCallback<void(const std::vector<MediaDeviceInfoArray>&,
+ std::vector<VideoInputDeviceCapabilitiesPtr>)>;
MediaDevicesManager(
media::AudioSystem* audio_system,
@@ -83,6 +87,7 @@ class CONTENT_EXPORT MediaDevicesManager
int render_frame_id,
const std::string& group_id_salt_base,
const BoolDeviceTypes& requested_types,
+ bool request_video_input_capabilities,
EnumerateDevicesCallback callback);
uint32_t SubscribeDeviceChangeNotifications(
@@ -108,6 +113,13 @@ class CONTENT_EXPORT MediaDevicesManager
// changes.
void OnDevicesChanged(base::SystemMonitor::DeviceType device_type) override;
+ // Returns the supported video formats for the given |device_id|.
+ // If |try_in_use_first| is true and the device is being used, only the format
+ // in use is returned. Otherwise, all formats supported by the device are
+ // returned.
+ media::VideoCaptureFormats GetVideoInputFormats(const std::string& device_id,
+ bool try_in_use_first);
+
// TODO(guidou): Remove this function once content::GetMediaDeviceIDForHMAC
// is rewritten to receive devices via a callback.
// See http://crbug.com/648155.
@@ -169,11 +181,13 @@ class CONTENT_EXPORT MediaDevicesManager
int render_frame_id,
const std::string& group_id_salt_base,
const BoolDeviceTypes& requested_types,
+ bool request_video_input_capabilities,
EnumerateDevicesCallback callback,
const std::pair<std::string, url::Origin>& salt_and_origin);
void OnPermissionsCheckDone(
const std::string& group_id_salt_base,
const MediaDevicesManager::BoolDeviceTypes& requested_types,
+ bool request_video_input_capabilities,
EnumerateDevicesCallback callback,
const std::string& device_id_salt,
const url::Origin& security_origin,
@@ -181,12 +195,16 @@ class CONTENT_EXPORT MediaDevicesManager
void OnDevicesEnumerated(
const std::string& group_id_salt_base,
const MediaDevicesManager::BoolDeviceTypes& requested_types,
+ bool request_video_input_capabilities,
EnumerateDevicesCallback callback,
const std::string& device_id_salt,
const url::Origin& security_origin,
const MediaDevicesManager::BoolDeviceTypes& has_permissions,
const MediaDeviceEnumeration& enumeration);
+ std::vector<VideoInputDeviceCapabilitiesPtr> ComputeVideoInputCapabilities(
+ const MediaDeviceInfoArray& device_infos);
+
// Helpers to issue low-level device enumerations.
void DoEnumerateDevices(MediaDeviceType type);
void EnumerateAudioDevices(bool is_input);
diff --git a/chromium/content/browser/renderer_host/media/media_devices_manager_unittest.cc b/chromium/content/browser/renderer_host/media/media_devices_manager_unittest.cc
index 4418319b97b..79302f2c9a9 100644
--- a/chromium/content/browser/renderer_host/media/media_devices_manager_unittest.cc
+++ b/chromium/content/browser/renderer_host/media/media_devices_manager_unittest.cc
@@ -630,6 +630,10 @@ TEST_F(MediaDevicesManagerTest, SubscribeDeviceChanges) {
TEST_F(MediaDevicesManagerTest, GuessVideoGroupID) {
MediaDeviceInfoArray audio_devices = {
+ {media::AudioDeviceDescription::kDefaultDeviceId,
+ "Default - Unique USB Mic (1234:5678)", "group_1"},
+ {media::AudioDeviceDescription::kCommunicationsDeviceId,
+ "communications - Unique USB Mic (1234:5678)", "group_1"},
{"device_id_1", "Microphone (Logitech Webcam C930e)", "group_1"},
{"device_id_2", "HD Pro Webcam C920", "group_2"},
{"device_id_3", "Microsoft® LifeCam Cinema(TM)", "group_3"},
@@ -641,6 +645,16 @@ TEST_F(MediaDevicesManagerTest, GuessVideoGroupID) {
{"device_id_9", "Repeated dual-mic webcam device", "group_7"},
{"device_id_10", "Repeated dual-mic webcam device", "group_8"},
{"device_id_11", "Repeated dual-mic webcam device", "group_8"},
+ {"device_id_12", "Unique USB Mic (1234:5678)", "group_1"},
+ {"device_id_13", "Another Unique USB Mic (5678:9abc)", "group_9"},
+ {"device_id_14", "Repeated USB Mic (8765:4321)", "group_10"},
+ {"device_id_15", "Repeated USB Mic (8765:4321)", "group_11"},
+ // Extra entry for communications device added here just to make sure
+ // that it is not incorrectly detected as an extra real device. Real
+ // enumerations contain only the first entry for the communications
+ // device.
+ {media::AudioDeviceDescription::kCommunicationsDeviceId,
+ "communications - Unique USB Mic (1234:5678)", "group_1"},
};
MediaDeviceInfo logitech_video("logitech_video",
@@ -662,6 +676,14 @@ TEST_F(MediaDevicesManagerTest, GuessVideoGroupID) {
MediaDeviceInfo repeated_dual_mic2_video(
"repeated_dual_mic2_video", "Repeated dual-mic webcam device", "");
MediaDeviceInfo short_label_video("short_label_video", " ()", "");
+ MediaDeviceInfo unique_usb_video("unique_usb_video",
+ "Unique USB webcam (1234:5678)", "");
+ MediaDeviceInfo another_unique_usb_video(
+ "another_unique_usb_video", "Another Unique USB webcam (5678:9abc)", "");
+ MediaDeviceInfo repeated_usb1_video("repeated_usb1_video",
+ "Repeated USB webcam (8765:4321)", "");
+ MediaDeviceInfo repeated_usb2_video("repeated_usb2_video",
+ "Repeated USB webcam (8765:4321)", "");
EXPECT_EQ(GuessVideoGroupID(audio_devices, logitech_video), "group_1");
EXPECT_EQ(GuessVideoGroupID(audio_devices, hd_pro_video), "group_2");
@@ -679,6 +701,13 @@ TEST_F(MediaDevicesManagerTest, GuessVideoGroupID) {
repeated_dual_mic2_video.device_id);
EXPECT_EQ(GuessVideoGroupID(audio_devices, short_label_video),
short_label_video.device_id);
+ EXPECT_EQ(GuessVideoGroupID(audio_devices, unique_usb_video), "group_1");
+ EXPECT_EQ(GuessVideoGroupID(audio_devices, another_unique_usb_video),
+ "group_9");
+ EXPECT_EQ(GuessVideoGroupID(audio_devices, repeated_usb1_video),
+ repeated_usb1_video.device_id);
+ EXPECT_EQ(GuessVideoGroupID(audio_devices, repeated_usb2_video),
+ repeated_usb2_video.device_id);
}
} // namespace content
diff --git a/chromium/content/browser/renderer_host/media/media_stream_dispatcher_host_unittest.cc b/chromium/content/browser/renderer_host/media/media_stream_dispatcher_host_unittest.cc
index 4c0d08663a3..e7f85c17584 100644
--- a/chromium/content/browser/renderer_host/media/media_stream_dispatcher_host_unittest.cc
+++ b/chromium/content/browser/renderer_host/media/media_stream_dispatcher_host_unittest.cc
@@ -71,7 +71,7 @@ void AudioInputDevicesEnumerated(base::Closure quit_closure,
for (const auto& info : enumeration[MEDIA_DEVICE_TYPE_AUDIO_INPUT]) {
out->emplace_back(info.label, info.device_id, info.group_id);
}
- quit_closure.Run();
+ std::move(quit_closure).Run();
}
} // anonymous namespace
diff --git a/chromium/content/browser/renderer_host/media/media_stream_manager.cc b/chromium/content/browser/renderer_host/media/media_stream_manager.cc
index f42876a85b6..19a1e6b3e2e 100644
--- a/chromium/content/browser/renderer_host/media/media_stream_manager.cc
+++ b/chromium/content/browser/renderer_host/media/media_stream_manager.cc
@@ -112,6 +112,24 @@ void CreateJpegDecodeAccelerator(
std::move(request)));
}
+void CreateJpegEncodeAcceleratorOnIOThread(
+ media::mojom::JpegEncodeAcceleratorRequest request) {
+ auto* host =
+ GpuProcessHost::Get(GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED, false);
+ if (host) {
+ host->gpu_service()->CreateJpegEncodeAccelerator(std::move(request));
+ } else {
+ LOG(ERROR) << "No GpuProcessHost";
+ }
+}
+
+void CreateJpegEncodeAccelerator(
+ media::mojom::JpegEncodeAcceleratorRequest request) {
+ BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
+ base::BindOnce(&CreateJpegEncodeAcceleratorOnIOThread,
+ std::move(request)));
+}
+
void ParseStreamType(const StreamControls& controls,
MediaStreamType* audio_type,
MediaStreamType* video_type) {
@@ -183,7 +201,7 @@ bool CalledOnIOThread() {
// Check if this function call is on the IO thread, except for unittests where
// an IO thread might not have been created.
return BrowserThread::CurrentlyOn(BrowserThread::IO) ||
- !BrowserThread::IsMessageLoopValid(BrowserThread::IO);
+ !BrowserThread::IsThreadInitialized(BrowserThread::IO);
}
bool GetDeviceIDFromHMAC(const std::string& salt,
@@ -495,7 +513,8 @@ MediaStreamManager::MediaStreamManager(
media::VideoCaptureDeviceFactory::CreateFactory(
BrowserThread::GetTaskRunnerForThread(BrowserThread::UI),
BrowserGpuMemoryBufferManager::current(),
- base::BindRepeating(&CreateJpegDecodeAccelerator))),
+ base::BindRepeating(&CreateJpegDecodeAccelerator),
+ base::BindRepeating(&CreateJpegEncodeAccelerator))),
std::move(device_task_runner),
base::BindRepeating(&SendVideoCaptureLogMessage));
}
@@ -1495,7 +1514,7 @@ void MediaStreamManager::UseFakeUIFactoryForTests(
base::Callback<std::unique_ptr<FakeMediaStreamUIProxy>(void)>
fake_ui_factory) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
- fake_ui_factory_ = fake_ui_factory;
+ fake_ui_factory_ = std::move(fake_ui_factory);
}
// static
@@ -1837,7 +1856,7 @@ void MediaStreamManager::SetCapturingLinkSecured(int render_process_id,
void MediaStreamManager::SetGenerateStreamCallbackForTesting(
GenerateStreamTestCallback test_callback) {
- generate_stream_test_callback_ = test_callback;
+ generate_stream_test_callback_ = std::move(test_callback);
}
MediaStreamDevices MediaStreamManager::ConvertToMediaStreamDevices(
diff --git a/chromium/content/browser/renderer_host/media/media_stream_manager_unittest.cc b/chromium/content/browser/renderer_host/media/media_stream_manager_unittest.cc
index bf6e7af8254..3f169d3d485 100644
--- a/chromium/content/browser/renderer_host/media/media_stream_manager_unittest.cc
+++ b/chromium/content/browser/renderer_host/media/media_stream_manager_unittest.cc
@@ -15,7 +15,6 @@
#include "base/strings/string_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
-#include "content/browser/browser_thread_impl.h"
#include "content/browser/renderer_host/media/media_stream_manager.h"
#include "content/browser/renderer_host/media/media_stream_ui_proxy.h"
#include "content/browser/renderer_host/media/mock_video_capture_provider.h"
diff --git a/chromium/content/browser/renderer_host/media/media_stream_track_metrics_host.cc b/chromium/content/browser/renderer_host/media/media_stream_track_metrics_host.cc
index 441df83d73c..4d22fb1c51a 100644
--- a/chromium/content/browser/renderer_host/media/media_stream_track_metrics_host.cc
+++ b/chromium/content/browser/renderer_host/media/media_stream_track_metrics_host.cc
@@ -5,7 +5,6 @@
#include "content/browser/renderer_host/media/media_stream_track_metrics_host.h"
#include "base/metrics/histogram_macros.h"
-#include "content/common/media/media_stream_track_metrics_host_messages.h"
// We use a histogram with a maximum bucket of 16 hours to infinity
// for track durations.
@@ -17,9 +16,7 @@
namespace content {
-MediaStreamTrackMetricsHost::MediaStreamTrackMetricsHost()
- : BrowserMessageFilter(MediaStreamTrackMetricsHostMsgStart) {
-}
+MediaStreamTrackMetricsHost::MediaStreamTrackMetricsHost() {}
MediaStreamTrackMetricsHost::~MediaStreamTrackMetricsHost() {
// Our render process has exited. We won't receive any more IPC
@@ -33,22 +30,14 @@ MediaStreamTrackMetricsHost::~MediaStreamTrackMetricsHost() {
tracks_.clear();
}
-bool MediaStreamTrackMetricsHost::OnMessageReceived(
- const IPC::Message& message) {
- bool handled = true;
-
- IPC_BEGIN_MESSAGE_MAP(MediaStreamTrackMetricsHost, message)
- IPC_MESSAGE_HANDLER(MediaStreamTrackMetricsHost_AddTrack, OnAddTrack)
- IPC_MESSAGE_HANDLER(MediaStreamTrackMetricsHost_RemoveTrack, OnRemoveTrack)
- IPC_MESSAGE_UNHANDLED(handled = false)
- IPC_END_MESSAGE_MAP()
-
- return handled;
+void MediaStreamTrackMetricsHost::BindRequest(
+ mojom::MediaStreamTrackMetricsHostRequest request) {
+ bindings_.AddBinding(this, std::move(request));
}
-void MediaStreamTrackMetricsHost::OnAddTrack(uint64_t id,
- bool is_audio,
- bool is_remote) {
+void MediaStreamTrackMetricsHost::AddTrack(uint64_t id,
+ bool is_audio,
+ bool is_remote) {
if (tracks_.find(id) != tracks_.end())
return;
@@ -56,7 +45,7 @@ void MediaStreamTrackMetricsHost::OnAddTrack(uint64_t id,
tracks_[id] = info;
}
-void MediaStreamTrackMetricsHost::OnRemoveTrack(uint64_t id) {
+void MediaStreamTrackMetricsHost::RemoveTrack(uint64_t id) {
if (tracks_.find(id) == tracks_.end())
return;
diff --git a/chromium/content/browser/renderer_host/media/media_stream_track_metrics_host.h b/chromium/content/browser/renderer_host/media/media_stream_track_metrics_host.h
index c800f3a5824..aeed2325b5a 100644
--- a/chromium/content/browser/renderer_host/media/media_stream_track_metrics_host.h
+++ b/chromium/content/browser/renderer_host/media/media_stream_track_metrics_host.h
@@ -11,7 +11,8 @@
#include <string>
#include "base/time/time.h"
-#include "content/public/browser/browser_message_filter.h"
+#include "content/common/media/media_stream.mojom.h"
+#include "mojo/public/cpp/bindings/binding_set.h"
namespace content {
@@ -27,20 +28,16 @@ namespace content {
// If the renderer process goes away without sending messages that
// tracks were removed, this class instead infers that the tracks were
// removed.
-class MediaStreamTrackMetricsHost
- : public BrowserMessageFilter {
+class MediaStreamTrackMetricsHost : public mojom::MediaStreamTrackMetricsHost {
public:
explicit MediaStreamTrackMetricsHost();
- protected:
~MediaStreamTrackMetricsHost() override;
-
- // BrowserMessageFilter override.
- bool OnMessageReceived(const IPC::Message& message) override;
+ void BindRequest(mojom::MediaStreamTrackMetricsHostRequest request);
private:
- void OnAddTrack(uint64_t id, bool is_audio, bool is_remote);
- void OnRemoveTrack(uint64_t id);
+ void AddTrack(uint64_t id, bool is_audio, bool is_remote) override;
+ void RemoveTrack(uint64_t id) override;
// Information for a track we're keeping in |tracks_|. |is_audio|
// specifies whether it's an audio or video track, |is_remote|
@@ -58,6 +55,8 @@ class MediaStreamTrackMetricsHost
// Values are unique (per renderer) track IDs.
typedef std::map<uint64_t, TrackInfo> TrackMap;
TrackMap tracks_;
+
+ mojo::BindingSet<mojom::MediaStreamTrackMetricsHost> bindings_;
};
} // namespace content
diff --git a/chromium/content/browser/renderer_host/media/media_stream_ui_proxy.cc b/chromium/content/browser/renderer_host/media/media_stream_ui_proxy.cc
index 07a03018a91..2f13d1d2045 100644
--- a/chromium/content/browser/renderer_host/media/media_stream_ui_proxy.cc
+++ b/chromium/content/browser/renderer_host/media/media_stream_ui_proxy.cc
@@ -16,7 +16,7 @@
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "media/capture/video/fake_video_capture_device.h"
-#include "third_party/WebKit/public/mojom/feature_policy/feature_policy.mojom.h"
+#include "third_party/blink/public/mojom/feature_policy/feature_policy.mojom.h"
#include "url/gurl.h"
#include "url/origin.h"
diff --git a/chromium/content/browser/renderer_host/media/media_stream_ui_proxy_unittest.cc b/chromium/content/browser/renderer_host/media/media_stream_ui_proxy_unittest.cc
index 49fe89276bc..a9a89760950 100644
--- a/chromium/content/browser/renderer_host/media/media_stream_ui_proxy_unittest.cc
+++ b/chromium/content/browser/renderer_host/media/media_stream_ui_proxy_unittest.cc
@@ -10,6 +10,7 @@
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/test/scoped_feature_list.h"
+#include "build/build_config.h"
#include "content/browser/frame_host/render_frame_host_delegate.h"
#include "content/public/common/content_features.h"
#include "content/public/test/test_browser_thread.h"
@@ -32,8 +33,10 @@ class MockRenderFrameHostDelegate : public RenderFrameHostDelegate {
MOCK_METHOD2(RequestMediaAccessPermission,
void(const MediaStreamRequest& request,
const MediaResponseCallback& callback));
- MOCK_METHOD2(CheckMediaAccessPermission,
- bool(const url::Origin& security_origin, MediaStreamType type));
+ MOCK_METHOD3(CheckMediaAccessPermission,
+ bool(RenderFrameHost* render_frame_host,
+ const url::Origin& security_origin,
+ MediaStreamType type));
};
class MockResponseCallback {
@@ -93,7 +96,22 @@ MATCHER_P(SameRequest, expected, "") {
expected->video_type == arg.video_type;
}
-TEST_F(MediaStreamUIProxyTest, Deny) {
+// These tests are flaky on Linux. https://crbug.com/826483
+#if defined(OS_LINUX)
+#define MAYBE_DeleteBeforeAccepted DISABLED_DeleteBeforeAccepted
+#define MAYBE_Deny DISABLED_Deny
+#define MAYBE_AcceptAndStart DISABLED_AcceptAndStart
+#define MAYBE_StopFromUI DISABLED_StopFromUI
+#define MAYBE_WindowIdCallbackCalled DISABLED_WindowIdCallbackCalled
+#else
+#define MAYBE_DeleteBeforeAccepted DeleteBeforeAccepted
+#define MAYBE_Deny Deny
+#define MAYBE_AcceptAndStart AcceptAndStart
+#define MAYBE_StopFromUI StopFromUI
+#define MAYBE_WindowIdCallbackCalled WindowIdCallbackCalled
+#endif
+
+TEST_F(MediaStreamUIProxyTest, MAYBE_Deny) {
std::unique_ptr<MediaStreamRequest> request(new MediaStreamRequest(
0, 0, 0, GURL("http://origin/"), false, MEDIA_GENERATE_STREAM,
std::string(), std::string(), MEDIA_DEVICE_AUDIO_CAPTURE,
@@ -121,7 +139,7 @@ TEST_F(MediaStreamUIProxyTest, Deny) {
EXPECT_TRUE(response.empty());
}
-TEST_F(MediaStreamUIProxyTest, AcceptAndStart) {
+TEST_F(MediaStreamUIProxyTest, MAYBE_AcceptAndStart) {
std::unique_ptr<MediaStreamRequest> request(new MediaStreamRequest(
0, 0, 0, GURL("http://origin/"), false, MEDIA_GENERATE_STREAM,
std::string(), std::string(), MEDIA_DEVICE_AUDIO_CAPTURE,
@@ -157,7 +175,7 @@ TEST_F(MediaStreamUIProxyTest, AcceptAndStart) {
}
// Verify that the proxy can be deleted before the request is processed.
-TEST_F(MediaStreamUIProxyTest, DeleteBeforeAccepted) {
+TEST_F(MediaStreamUIProxyTest, MAYBE_DeleteBeforeAccepted) {
std::unique_ptr<MediaStreamRequest> request(new MediaStreamRequest(
0, 0, 0, GURL("http://origin/"), false, MEDIA_GENERATE_STREAM,
std::string(), std::string(), MEDIA_DEVICE_AUDIO_CAPTURE,
@@ -181,7 +199,7 @@ TEST_F(MediaStreamUIProxyTest, DeleteBeforeAccepted) {
callback.Run(devices, MEDIA_DEVICE_OK, std::move(ui));
}
-TEST_F(MediaStreamUIProxyTest, StopFromUI) {
+TEST_F(MediaStreamUIProxyTest, MAYBE_StopFromUI) {
std::unique_ptr<MediaStreamRequest> request(new MediaStreamRequest(
0, 0, 0, GURL("http://origin/"), false, MEDIA_GENERATE_STREAM,
std::string(), std::string(), MEDIA_DEVICE_AUDIO_CAPTURE,
@@ -227,7 +245,7 @@ TEST_F(MediaStreamUIProxyTest, StopFromUI) {
base::RunLoop().RunUntilIdle();
}
-TEST_F(MediaStreamUIProxyTest, WindowIdCallbackCalled) {
+TEST_F(MediaStreamUIProxyTest, MAYBE_WindowIdCallbackCalled) {
std::unique_ptr<MediaStreamRequest> request(new MediaStreamRequest(
0, 0, 0, GURL("http://origin/"), false, MEDIA_GENERATE_STREAM,
std::string(), std::string(), MEDIA_NO_SERVICE,
@@ -297,7 +315,7 @@ class MediaStreamUIProxyFeaturePolicyTest
BrowserThread::IO, FROM_HERE,
base::BindOnce(
&MediaStreamUIProxyFeaturePolicyTest::GetResultForRequestOnIOThread,
- base::Unretained(this), base::Passed(&request)));
+ base::Unretained(this), std::move(request)));
run_loop.Run();
*devices_out = devices_;
*result_out = result_;
diff --git a/chromium/content/browser/renderer_host/media/peer_connection_tracker_host.cc b/chromium/content/browser/renderer_host/media/peer_connection_tracker_host.cc
index 555760ac905..9dccd399f82 100644
--- a/chromium/content/browser/renderer_host/media/peer_connection_tracker_host.cc
+++ b/chromium/content/browser/renderer_host/media/peer_connection_tracker_host.cc
@@ -6,9 +6,9 @@
#include "base/power_monitor/power_monitor.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
-#include "content/browser/webrtc/webrtc_event_log_manager.h"
#include "content/browser/webrtc/webrtc_internals.h"
#include "content/common/media/peer_connection_tracker_messages.h"
+#include "content/public/browser/webrtc_event_logger.h"
namespace content {
@@ -68,8 +68,11 @@ void PeerConnectionTrackerHost::OnAddPeerConnection(
render_process_id_, peer_pid(), info.lid, info.url,
info.rtc_configuration, info.constraints);
}
- WebRtcEventLogManager::GetInstance()->PeerConnectionAdded(render_process_id_,
- info.lid);
+ WebRtcEventLogger* const logger = WebRtcEventLogger::Get();
+ if (logger) {
+ logger->PeerConnectionAdded(render_process_id_, info.lid,
+ info.peer_connection_id);
+ }
}
void PeerConnectionTrackerHost::RemovePeerConnection(int lid) {
@@ -84,8 +87,10 @@ void PeerConnectionTrackerHost::RemovePeerConnection(int lid) {
if (webrtc_internals) {
webrtc_internals->OnRemovePeerConnection(peer_pid(), lid);
}
- WebRtcEventLogManager::GetInstance()->PeerConnectionRemoved(
- render_process_id_, lid);
+ WebRtcEventLogger* const logger = WebRtcEventLogger::Get();
+ if (logger) {
+ logger->PeerConnectionRemoved(render_process_id_, lid);
+ }
}
void PeerConnectionTrackerHost::UpdatePeerConnection(int lid,
@@ -100,8 +105,10 @@ void PeerConnectionTrackerHost::UpdatePeerConnection(int lid,
}
// TODO(eladalon): Get rid of magic value. https://crbug.com/810383
if (type == "stop") {
- auto* manager = WebRtcEventLogManager::GetInstance();
- manager->PeerConnectionStopped(render_process_id_, lid);
+ WebRtcEventLogger* const logger = WebRtcEventLogger::Get();
+ if (logger) {
+ logger->PeerConnectionStopped(render_process_id_, lid);
+ }
}
WebRTCInternals* webrtc_internals = WebRTCInternals::GetInstance();
@@ -148,8 +155,10 @@ void PeerConnectionTrackerHost::WebRtcEventLogWrite(int lid,
lid, output));
return;
}
- auto* manager = WebRtcEventLogManager::GetInstance();
- manager->OnWebRtcEventLogWrite(render_process_id_, lid, output);
+ WebRtcEventLogger* const logger = WebRtcEventLogger::Get();
+ if (logger) {
+ logger->OnWebRtcEventLogWrite(render_process_id_, lid, output);
+ }
}
void PeerConnectionTrackerHost::OnSuspend() {
diff --git a/chromium/content/browser/renderer_host/media/peer_connection_tracker_host.h b/chromium/content/browser/renderer_host/media/peer_connection_tracker_host.h
index 5d6ca017c02..57559aaa08f 100644
--- a/chromium/content/browser/renderer_host/media/peer_connection_tracker_host.h
+++ b/chromium/content/browser/renderer_host/media/peer_connection_tracker_host.h
@@ -12,6 +12,7 @@
#include "content/common/media/peer_connection_tracker.mojom.h"
#include "content/public/browser/browser_associated_interface.h"
#include "content/public/browser/browser_message_filter.h"
+#include "content/public/browser/browser_thread.h"
struct PeerConnectionInfo;
diff --git a/chromium/content/browser/renderer_host/media/render_frame_audio_input_stream_factory_unittest.cc b/chromium/content/browser/renderer_host/media/render_frame_audio_input_stream_factory_unittest.cc
index 8e6d66b9b87..135e6c4bc90 100644
--- a/chromium/content/browser/renderer_host/media/render_frame_audio_input_stream_factory_unittest.cc
+++ b/chromium/content/browser/renderer_host/media/render_frame_audio_input_stream_factory_unittest.cc
@@ -120,13 +120,27 @@ class RenderFrameAudioInputStreamFactoryTest : public testing::Test {
~RenderFrameAudioInputStreamFactoryTest() override {
audio_manager_.Shutdown();
+
+ // UniqueAudioInputStreamFactoryPtr uses DeleteOnIOThread and must run
+ // before |thread_bundle_| tear down.
+ factory_handle_.reset();
+
+ // Shutdown BrowserThread::IO before tearing down members.
thread_bundle_.reset();
}
+ // |thread_bundle_| needs to be up before the members below (as they use
+ // BrowserThreads for their initialization) but then needs to be torn down
+ // before them as some verify they're town down in a single-threaded
+ // environment (while
+ // !BrowserThread::IsThreadInitiaslized(BrowserThread::IO)).
base::Optional<TestBrowserThreadBundle> thread_bundle_;
+
+ // These members need to be torn down after |thread_bundle_|.
media::MockAudioManager audio_manager_;
media::AudioSystemImpl audio_system_;
MediaStreamManager media_stream_manager_;
+
mojom::RendererAudioInputStreamFactoryPtr factory_ptr_;
media::mojom::AudioInputStreamPtr stream_ptr_;
MockRendererAudioInputStreamFactoryClient client_;
diff --git a/chromium/content/browser/renderer_host/media/renderer_audio_output_stream_factory_context_impl.cc b/chromium/content/browser/renderer_host/media/renderer_audio_output_stream_factory_context_impl.cc
index c1ea7314ef5..cd8ca99ea4c 100644
--- a/chromium/content/browser/renderer_host/media/renderer_audio_output_stream_factory_context_impl.cc
+++ b/chromium/content/browser/renderer_host/media/renderer_audio_output_stream_factory_context_impl.cc
@@ -6,8 +6,6 @@
#include <utility>
-#include "base/memory/ptr_util.h"
-#include "content/browser/media/capture/audio_mirroring_manager.h"
#include "content/browser/media/media_internals.h"
#include "content/browser/renderer_host/media/audio_output_delegate_impl.h"
#include "content/browser/renderer_host/media/media_stream_manager.h"
@@ -72,10 +70,9 @@ RendererAudioOutputStreamFactoryContextImpl::CreateDelegate(
audio_log_ptr->OnCreated(params, unique_device_id);
return AudioOutputDelegateImpl::Create(
- handler, audio_manager_, std::move(audio_log_ptr),
- AudioMirroringManager::GetInstance(), media_observer, stream_id,
- render_frame_id, render_process_id_, params, std::move(stream_observer),
- unique_device_id);
+ handler, audio_manager_, std::move(audio_log_ptr), media_observer,
+ stream_id, render_frame_id, render_process_id_, params,
+ std::move(stream_observer), unique_device_id);
}
// static
diff --git a/chromium/content/browser/renderer_host/media/video_capture_browsertest.cc b/chromium/content/browser/renderer_host/media/video_capture_browsertest.cc
index 4d921c5e391..c03c46d7d78 100644
--- a/chromium/content/browser/renderer_host/media/video_capture_browsertest.cc
+++ b/chromium/content/browser/renderer_host/media/video_capture_browsertest.cc
@@ -10,6 +10,7 @@
#include "content/browser/renderer_host/media/media_stream_manager.h"
#include "content/browser/renderer_host/media/video_capture_controller.h"
#include "content/browser/renderer_host/media/video_capture_manager.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/content_browser_test.h"
@@ -204,7 +205,7 @@ class VideoCaptureBrowserTest : public ContentBrowserTest,
controller_ = controller;
if (!continuation)
return;
- continuation.Run();
+ std::move(continuation).Run();
}
protected:
diff --git a/chromium/content/browser/renderer_host/media/video_capture_buffer_pool_unittest.cc b/chromium/content/browser/renderer_host/media/video_capture_buffer_pool_unittest.cc
index a378c018244..8ed10adda5c 100644
--- a/chromium/content/browser/renderer_host/media/video_capture_buffer_pool_unittest.cc
+++ b/chromium/content/browser/renderer_host/media/video_capture_buffer_pool_unittest.cc
@@ -16,7 +16,6 @@
#include "base/bind.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop/message_loop.h"
#include "build/build_config.h"
diff --git a/chromium/content/browser/renderer_host/media/video_capture_controller.cc b/chromium/content/browser/renderer_host/media/video_capture_controller.cc
index f132e622bb7..8d2cc05ab2c 100644
--- a/chromium/content/browser/renderer_host/media/video_capture_controller.cc
+++ b/chromium/content/browser/renderer_host/media/video_capture_controller.cc
@@ -12,7 +12,6 @@
#include "base/bind.h"
#include "base/command_line.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "build/build_config.h"
@@ -22,7 +21,7 @@
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "media/base/video_frame.h"
-#include "media/capture/mojo/video_capture_types.mojom.h"
+#include "media/capture/mojom/video_capture_types.mojom.h"
#include "media/capture/video/video_capture_buffer_pool.h"
#include "media/capture/video/video_capture_buffer_tracker_factory_impl.h"
#include "media/capture/video/video_capture_device_client.h"
@@ -458,7 +457,7 @@ void VideoCaptureController::OnFrameReadyInBuffer(
double frame_rate = 0.0f;
if (video_capture_format_) {
media::VideoFrameMetadata metadata;
- metadata.MergeInternalValuesFrom(*frame_info->metadata);
+ metadata.MergeInternalValuesFrom(frame_info->metadata);
if (!metadata.GetDouble(VideoFrameMetadata::FRAME_RATE, &frame_rate)) {
frame_rate = video_capture_format_->frame_rate;
}
diff --git a/chromium/content/browser/renderer_host/media/video_capture_controller_event_handler.h b/chromium/content/browser/renderer_host/media/video_capture_controller_event_handler.h
index a11d54fe2e3..674a8b5f534 100644
--- a/chromium/content/browser/renderer_host/media/video_capture_controller_event_handler.h
+++ b/chromium/content/browser/renderer_host/media/video_capture_controller_event_handler.h
@@ -9,7 +9,7 @@
#include "base/memory/shared_memory.h"
#include "content/common/content_export.h"
-#include "media/capture/mojo/video_capture_types.mojom.h"
+#include "media/capture/mojom/video_capture_types.mojom.h"
#include "mojo/public/cpp/system/buffer.h"
#include "ui/gfx/geometry/size.h"
diff --git a/chromium/content/browser/renderer_host/media/video_capture_controller_unittest.cc b/chromium/content/browser/renderer_host/media/video_capture_controller_unittest.cc
index b13a79c702e..f9f188c99c8 100644
--- a/chromium/content/browser/renderer_host/media/video_capture_controller_unittest.cc
+++ b/chromium/content/browser/renderer_host/media/video_capture_controller_unittest.cc
@@ -15,7 +15,6 @@
#include "base/bind_helpers.h"
#include "base/location.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
@@ -89,7 +88,7 @@ class MockVideoCaptureControllerEventHandler
const media::mojom::VideoFrameInfoPtr& frame_info) override {
EXPECT_EQ(expected_pixel_format_, frame_info->pixel_format);
media::VideoFrameMetadata metadata;
- metadata.MergeInternalValuesFrom(*frame_info->metadata);
+ metadata.MergeInternalValuesFrom(frame_info->metadata);
base::TimeTicks reference_time;
EXPECT_TRUE(metadata.GetTimeTicks(media::VideoFrameMetadata::REFERENCE_TIME,
&reference_time));
diff --git a/chromium/content/browser/renderer_host/media/video_capture_gpu_jpeg_decoder.cc b/chromium/content/browser/renderer_host/media/video_capture_gpu_jpeg_decoder.cc
index e354d9767f2..521eb91840e 100644
--- a/chromium/content/browser/renderer_host/media/video_capture_gpu_jpeg_decoder.cc
+++ b/chromium/content/browser/renderer_host/media/video_capture_gpu_jpeg_decoder.cc
@@ -179,7 +179,7 @@ void VideoCaptureGpuJpegDecoder::DecodeCapturedData(
out_frame_info->storage_type = media::VideoPixelStorage::CPU;
out_frame_info->coded_size = dimensions;
out_frame_info->visible_rect = gfx::Rect(dimensions);
- out_frame_info->metadata = out_frame->metadata()->CopyInternalValues();
+ out_frame_info->metadata = out_frame->metadata()->GetInternalValues().Clone();
{
base::AutoLock lock(lock_);
@@ -275,7 +275,7 @@ void VideoCaptureGpuJpegDecoder::DidReceiveGPUInfoOnIOThread(
task_runner->PostTask(
FROM_HERE,
base::BindOnce(&VideoCaptureGpuJpegDecoder::FinishInitialization,
- weak_this, base::Passed(remote_decoder.PassInterface())));
+ weak_this, remote_decoder.PassInterface()));
}
void VideoCaptureGpuJpegDecoder::FinishInitialization(
diff --git a/chromium/content/browser/renderer_host/media/video_capture_host.cc b/chromium/content/browser/renderer_host/media/video_capture_host.cc
index a7f9923f0da..c362c364707 100644
--- a/chromium/content/browser/renderer_host/media/video_capture_host.cc
+++ b/chromium/content/browser/renderer_host/media/video_capture_host.cc
@@ -8,10 +8,10 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
-#include "base/memory/ptr_util.h"
#include "content/browser/browser_main_loop.h"
#include "content/browser/renderer_host/media/media_stream_manager.h"
#include "content/browser/renderer_host/media/video_capture_manager.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_process_host.h"
#include "mojo/common/values_struct_traits.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
diff --git a/chromium/content/browser/renderer_host/media/video_capture_host.h b/chromium/content/browser/renderer_host/media/video_capture_host.h
index 5c422624fc5..6a9fe208d3b 100644
--- a/chromium/content/browser/renderer_host/media/video_capture_host.h
+++ b/chromium/content/browser/renderer_host/media/video_capture_host.h
@@ -14,7 +14,7 @@
#include "content/browser/renderer_host/media/video_capture_controller.h"
#include "content/browser/renderer_host/media/video_capture_controller_event_handler.h"
#include "content/common/content_export.h"
-#include "media/capture/mojo/video_capture.mojom.h"
+#include "media/capture/mojom/video_capture.mojom.h"
namespace content {
class MediaStreamManager;
diff --git a/chromium/content/browser/renderer_host/media/video_capture_manager.cc b/chromium/content/browser/renderer_host/media/video_capture_manager.cc
index 5cc7a0a10af..3cdff16e6ef 100644
--- a/chromium/content/browser/renderer_host/media/video_capture_manager.cc
+++ b/chromium/content/browser/renderer_host/media/video_capture_manager.cc
@@ -13,7 +13,6 @@
#include "base/command_line.h"
#include "base/location.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
diff --git a/chromium/content/browser/renderer_host/media/video_capture_manager_unittest.cc b/chromium/content/browser/renderer_host/media/video_capture_manager_unittest.cc
index 7e0186adfef..d02c7104d74 100644
--- a/chromium/content/browser/renderer_host/media/video_capture_manager_unittest.cc
+++ b/chromium/content/browser/renderer_host/media/video_capture_manager_unittest.cc
@@ -15,7 +15,6 @@
#include "base/bind.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/run_loop.h"
#include "base/threading/thread_task_runner_handle.h"
diff --git a/chromium/content/browser/renderer_host/media/video_capture_provider.h b/chromium/content/browser/renderer_host/media/video_capture_provider.h
index cdae54fd704..fc986c9fe8b 100644
--- a/chromium/content/browser/renderer_host/media/video_capture_provider.h
+++ b/chromium/content/browser/renderer_host/media/video_capture_provider.h
@@ -5,7 +5,6 @@
#ifndef CONTENT_BROWSER_RENDERER_HOST_MEDIA_BUILDABLE_VIDEO_CAPTURE_DEVICE_H_
#define CONTENT_BROWSER_RENDERER_HOST_MEDIA_BUILDABLE_VIDEO_CAPTURE_DEVICE_H_
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "content/common/content_export.h"
#include "content/public/common/media_stream_request.h"
diff --git a/chromium/content/browser/renderer_host/media/video_capture_unittest.cc b/chromium/content/browser/renderer_host/media/video_capture_unittest.cc
index 72eb952a241..3eb79dba90a 100644
--- a/chromium/content/browser/renderer_host/media/video_capture_unittest.cc
+++ b/chromium/content/browser/renderer_host/media/video_capture_unittest.cc
@@ -17,7 +17,6 @@
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
-#include "content/browser/browser_thread_impl.h"
#include "content/browser/renderer_host/media/fake_video_capture_provider.h"
#include "content/browser/renderer_host/media/media_stream_manager.h"
#include "content/browser/renderer_host/media/media_stream_ui_proxy.h"
@@ -62,7 +61,7 @@ void VideoInputDevicesEnumerated(base::Closure quit_closure,
salt, security_origin, info.device_id);
out->push_back(MediaDeviceInfo(device_id, info.label, std::string()));
}
- quit_closure.Run();
+ std::move(quit_closure).Run();
}
} // namespace
@@ -295,7 +294,7 @@ class VideoCaptureTest : public testing::Test,
opened_device_label_ = label;
opened_session_id_ = opened_device.session_id;
}
- quit_closure.Run();
+ std::move(quit_closure).Run();
}
// |media_stream_manager_| needs to outlive |thread_bundle_| because it is a
diff --git a/chromium/content/browser/renderer_host/offscreen_canvas_provider_impl.h b/chromium/content/browser/renderer_host/offscreen_canvas_provider_impl.h
index a96d4ce6b79..9248dfeabbb 100644
--- a/chromium/content/browser/renderer_host/offscreen_canvas_provider_impl.h
+++ b/chromium/content/browser/renderer_host/offscreen_canvas_provider_impl.h
@@ -11,7 +11,7 @@
#include "components/viz/common/surfaces/frame_sink_id.h"
#include "content/common/content_export.h"
#include "mojo/public/cpp/bindings/binding_set.h"
-#include "third_party/WebKit/public/platform/modules/offscreencanvas/offscreen_canvas_surface.mojom.h"
+#include "third_party/blink/public/platform/modules/offscreencanvas/offscreen_canvas_surface.mojom.h"
namespace viz {
class HostFrameSinkManager;
diff --git a/chromium/content/browser/renderer_host/offscreen_canvas_provider_impl_unittest.cc b/chromium/content/browser/renderer_host/offscreen_canvas_provider_impl_unittest.cc
index 935bdc2875c..eb896c946a4 100644
--- a/chromium/content/browser/renderer_host/offscreen_canvas_provider_impl_unittest.cc
+++ b/chromium/content/browser/renderer_host/offscreen_canvas_provider_impl_unittest.cc
@@ -8,7 +8,6 @@
#include <utility>
#include <vector>
-#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "components/viz/common/quads/compositor_frame.h"
@@ -22,7 +21,7 @@
#include "services/viz/public/interfaces/compositing/compositor_frame_sink.mojom.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/modules/offscreencanvas/offscreen_canvas_surface.mojom.h"
+#include "third_party/blink/public/platform/modules/offscreencanvas/offscreen_canvas_surface.mojom.h"
#include "ui/compositor/compositor.h"
#if !defined(OS_ANDROID)
@@ -128,9 +127,10 @@ class OffscreenCanvasProviderImplTest : public testing::Test {
&host_frame_sink_client_);
}
void TearDown() override {
+ host_frame_sink_manager_->InvalidateFrameSinkId(kFrameSinkParent);
provider_.reset();
- frame_sink_manager_.reset();
host_frame_sink_manager_.reset();
+ frame_sink_manager_.reset();
}
private:
diff --git a/chromium/content/browser/renderer_host/offscreen_canvas_surface_impl.cc b/chromium/content/browser/renderer_host/offscreen_canvas_surface_impl.cc
index 0265a0ae9fa..59d8e00e150 100644
--- a/chromium/content/browser/renderer_host/offscreen_canvas_surface_impl.cc
+++ b/chromium/content/browser/renderer_host/offscreen_canvas_surface_impl.cc
@@ -7,7 +7,6 @@
#include <memory>
#include <utility>
-#include "base/memory/ptr_util.h"
#include "components/viz/common/features.h"
#include "components/viz/host/host_frame_sink_manager.h"
#include "components/viz/service/surfaces/surface_manager.h"
diff --git a/chromium/content/browser/renderer_host/offscreen_canvas_surface_impl.h b/chromium/content/browser/renderer_host/offscreen_canvas_surface_impl.h
index 6f82d87b264..d098b8b1386 100644
--- a/chromium/content/browser/renderer_host/offscreen_canvas_surface_impl.h
+++ b/chromium/content/browser/renderer_host/offscreen_canvas_surface_impl.h
@@ -12,7 +12,7 @@
#include "components/viz/host/host_frame_sink_client.h"
#include "content/common/content_export.h"
#include "mojo/public/cpp/bindings/binding.h"
-#include "third_party/WebKit/public/platform/modules/offscreencanvas/offscreen_canvas_surface.mojom.h"
+#include "third_party/blink/public/platform/modules/offscreencanvas/offscreen_canvas_surface.mojom.h"
namespace viz {
class HostFrameSinkManager;
diff --git a/chromium/content/browser/renderer_host/overscroll_configuration.cc b/chromium/content/browser/renderer_host/overscroll_configuration.cc
index d7030f70867..51b4e0dbd72 100644
--- a/chromium/content/browser/renderer_host/overscroll_configuration.cc
+++ b/chromium/content/browser/renderer_host/overscroll_configuration.cc
@@ -7,13 +7,18 @@
#include "base/command_line.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
+#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
namespace {
-bool g_is_mode_initialized = false;
-content::OverscrollConfig::Mode g_mode =
- content::OverscrollConfig::Mode::kSimpleUi;
+bool g_is_history_navigation_mode_initialized = false;
+content::OverscrollConfig::HistoryNavigationMode g_history_navigation_mode =
+ content::OverscrollConfig::HistoryNavigationMode::kSimpleUi;
+
+bool g_is_ptr_mode_initialized = false;
+content::OverscrollConfig::PullToRefreshMode g_ptr_mode =
+ content::OverscrollConfig::PullToRefreshMode::kDisabled;
const float kThresholdCompleteTouchpad = 0.3f;
const float kThresholdCompleteTouchscreen = 0.25f;
@@ -21,6 +26,9 @@ const float kThresholdCompleteTouchscreen = 0.25f;
const float kThresholdStartTouchpad = 60.f;
const float kThresholdStartTouchscreen = 50.f;
+bool g_is_touchpad_overscroll_history_navigation_enabled_initialized = false;
+bool g_touchpad_overscroll_history_navigation_enabled = false;
+
float GetStartThresholdMultiplier() {
base::CommandLine* cmd = base::CommandLine::ForCurrentProcess();
if (!cmd->HasSwitch(switches::kOverscrollStartThreshold))
@@ -42,21 +50,36 @@ float GetStartThresholdMultiplier() {
namespace content {
// static
-OverscrollConfig::Mode OverscrollConfig::GetMode() {
- if (g_is_mode_initialized)
- return g_mode;
-
- g_is_mode_initialized = true;
+OverscrollConfig::HistoryNavigationMode
+OverscrollConfig::GetHistoryNavigationMode() {
+ if (g_is_history_navigation_mode_initialized)
+ return g_history_navigation_mode;
const std::string mode =
base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kOverscrollHistoryNavigation);
if (mode == "0")
- g_mode = Mode::kDisabled;
+ g_history_navigation_mode = HistoryNavigationMode::kDisabled;
else if (mode == "1")
- g_mode = Mode::kParallaxUi;
+ g_history_navigation_mode = HistoryNavigationMode::kParallaxUi;
+ g_is_history_navigation_mode_initialized = true;
+ return g_history_navigation_mode;
+}
+
+// static
+OverscrollConfig::PullToRefreshMode OverscrollConfig::GetPullToRefreshMode() {
+ if (g_is_ptr_mode_initialized)
+ return g_ptr_mode;
- return g_mode;
+ const std::string mode =
+ base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
+ switches::kPullToRefresh);
+ if (mode == "1")
+ g_ptr_mode = PullToRefreshMode::kEnabled;
+ else if (mode == "2")
+ g_ptr_mode = PullToRefreshMode::kEnabledTouchschreen;
+ g_is_ptr_mode_initialized = true;
+ return g_ptr_mode;
}
// static
@@ -84,15 +107,45 @@ float OverscrollConfig::GetThreshold(Threshold threshold) {
}
// static
-void OverscrollConfig::SetMode(Mode mode) {
- g_mode = mode;
- g_is_mode_initialized = true;
+void OverscrollConfig::SetHistoryNavigationMode(HistoryNavigationMode mode) {
+ g_history_navigation_mode = mode;
+ g_is_history_navigation_mode_initialized = true;
+}
+
+// static
+void OverscrollConfig::ResetHistoryNavigationMode() {
+ g_is_history_navigation_mode_initialized = false;
+ g_history_navigation_mode =
+ OverscrollConfig::HistoryNavigationMode::kSimpleUi;
+}
+
+// static
+void OverscrollConfig::SetPullToRefreshMode(PullToRefreshMode mode) {
+ g_ptr_mode = mode;
+ g_is_ptr_mode_initialized = true;
+}
+
+// static
+void OverscrollConfig::ResetPullToRefreshMode() {
+ g_is_ptr_mode_initialized = false;
+ g_ptr_mode = OverscrollConfig::PullToRefreshMode::kDisabled;
+}
+
+// static
+bool OverscrollConfig::TouchpadOverscrollHistoryNavigationEnabled() {
+ if (!g_is_touchpad_overscroll_history_navigation_enabled_initialized) {
+ g_is_touchpad_overscroll_history_navigation_enabled_initialized = true;
+ g_touchpad_overscroll_history_navigation_enabled =
+ base::FeatureList::IsEnabled(
+ features::kTouchpadOverscrollHistoryNavigation);
+ }
+
+ return g_touchpad_overscroll_history_navigation_enabled;
}
// static
-void OverscrollConfig::ResetMode() {
- g_is_mode_initialized = false;
- g_mode = OverscrollConfig::Mode::kSimpleUi;
+void OverscrollConfig::ResetTouchpadOverscrollHistoryNavigationEnabled() {
+ g_is_touchpad_overscroll_history_navigation_enabled_initialized = false;
}
} // namespace content
diff --git a/chromium/content/browser/renderer_host/overscroll_controller.cc b/chromium/content/browser/renderer_host/overscroll_controller.cc
index 18c0698e648..48656300248 100644
--- a/chromium/content/browser/renderer_host/overscroll_controller.cc
+++ b/chromium/content/browser/renderer_host/overscroll_controller.cc
@@ -17,16 +17,11 @@ namespace content {
namespace {
-bool IsPullToRefreshEnabled() {
- return base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
- switches::kPullToRefresh) == "1";
-}
-
bool IsGestureEventFromTouchpad(const blink::WebInputEvent& event) {
DCHECK(blink::WebInputEvent::IsGestureEventType(event.GetType()));
const blink::WebGestureEvent& gesture =
static_cast<const blink::WebGestureEvent&>(event);
- return gesture.source_device == blink::kWebGestureDeviceTouchpad;
+ return gesture.SourceDevice() == blink::kWebGestureDeviceTouchpad;
}
float ClampAbsoluteValue(float value, float max_abs) {
@@ -84,7 +79,23 @@ bool OverscrollController::ShouldProcessEvent(
return true;
}
+bool OverscrollController::ShouldIgnoreInertialEvent(
+ const blink::WebInputEvent& event) const {
+ if (!ignore_following_inertial_events_ ||
+ event.GetType() != blink::WebInputEvent::kGestureScrollUpdate) {
+ return false;
+ }
+
+ const blink::WebGestureEvent& gesture =
+ static_cast<const blink::WebGestureEvent&>(event);
+ return gesture.data.scroll_update.inertial_phase ==
+ blink::WebGestureEvent::kMomentumPhase;
+}
+
bool OverscrollController::WillHandleEvent(const blink::WebInputEvent& event) {
+ if (event.GetType() == blink::WebInputEvent::kGestureScrollBegin)
+ ignore_following_inertial_events_ = false;
+
if (!ShouldProcessEvent(event))
return false;
@@ -99,6 +110,11 @@ bool OverscrollController::WillHandleEvent(const blink::WebInputEvent& event) {
return false;
}
+ // Consume the scroll-update events if they are from a inertial scroll (fling)
+ // event that completed an overscroll gesture.
+ if (ShouldIgnoreInertialEvent(event))
+ return true;
+
bool reset_scroll_state = false;
if (scroll_state_ != ScrollState::NONE || overscroll_delta_x_ ||
overscroll_delta_y_) {
@@ -152,8 +168,7 @@ void OverscrollController::OnDidOverscroll(
const ui::DidOverscrollParams& params) {
// TODO(sunyunjia): We should also decide whether to trigger overscroll,
// update scroll_state_ here. See https://crbug.com/799467.
- if (delegate_)
- delegate_->OnOverscrollBehaviorUpdate(params.overscroll_behavior);
+ behavior_ = params.overscroll_behavior;
}
void OverscrollController::ReceivedEventACK(const blink::WebInputEvent& event,
@@ -161,6 +176,11 @@ void OverscrollController::ReceivedEventACK(const blink::WebInputEvent& event,
if (!ShouldProcessEvent(event))
return;
+ // An inertial scroll (fling) event from a completed overscroll gesture
+ // should not modify states below.
+ if (ShouldIgnoreInertialEvent(event))
+ return;
+
if (processed) {
// If a scroll event is consumed by the page, i.e. some content on the page
// has been scrolled, then there is not going to be an overscroll gesture,
@@ -200,7 +220,7 @@ void OverscrollController::Cancel() {
ResetScrollState();
}
-bool OverscrollController::DispatchEventCompletesAction (
+bool OverscrollController::DispatchEventCompletesAction(
const blink::WebInputEvent& event) const {
if (overscroll_mode_ == OVERSCROLL_NONE)
return false;
@@ -210,9 +230,23 @@ bool OverscrollController::DispatchEventCompletesAction (
// after the threshold.
if (event.GetType() != blink::WebInputEvent::kMouseMove &&
event.GetType() != blink::WebInputEvent::kGestureScrollEnd &&
- event.GetType() != blink::WebInputEvent::kGestureFlingStart)
+ event.GetType() != blink::WebInputEvent::kGestureFlingStart &&
+ event.GetType() != blink::WebInputEvent::kGestureScrollUpdate)
return false;
+ // Complete the overscroll gesture for inertial scroll (fling) event from
+ // touchpad.
+ if (event.GetType() == blink::WebInputEvent::kGestureScrollUpdate) {
+ if (overscroll_source_ != OverscrollSource::TOUCHPAD)
+ return false;
+ DCHECK(IsGestureEventFromTouchpad(event));
+ const blink::WebGestureEvent gesture_event =
+ static_cast<const blink::WebGestureEvent&>(event);
+ if (gesture_event.data.scroll_update.inertial_phase !=
+ blink::WebGestureEvent::kMomentumPhase)
+ return false;
+ }
+
if (event.GetType() == blink::WebInputEvent::kGestureScrollEnd &&
overscroll_source_ == OverscrollSource::TOUCHPAD) {
DCHECK(IsGestureEventFromTouchpad(event));
@@ -335,7 +369,7 @@ bool OverscrollController::ProcessEventForOverscroll(
event_processed = ProcessOverscroll(
gesture.data.scroll_update.delta_x,
gesture.data.scroll_update.delta_y,
- gesture.source_device == blink::kWebGestureDeviceTouchpad);
+ gesture.SourceDevice() == blink::kWebGestureDeviceTouchpad);
break;
}
case blink::WebInputEvent::kGestureFlingStart: {
@@ -424,11 +458,25 @@ bool OverscrollController::ProcessOverscroll(float delta_x,
fabs(overscroll_delta_y_) > fabs(overscroll_delta_x_) * kMinRatio)
new_mode = overscroll_delta_y_ > 0.f ? OVERSCROLL_SOUTH : OVERSCROLL_NORTH;
+ // The horizontal overscroll is used for history navigation. Enable it for
+ // touchpad only if TouchpadOverscrollHistoryNavigation is enabled.
+ if ((new_mode == OVERSCROLL_EAST || new_mode == OVERSCROLL_WEST) &&
+ is_touchpad &&
+ !OverscrollConfig::TouchpadOverscrollHistoryNavigationEnabled()) {
+ new_mode = OVERSCROLL_NONE;
+ }
+
// The vertical overscroll is used for pull-to-refresh. Enable it only if
// pull-to-refresh is enabled.
- if ((new_mode == OVERSCROLL_SOUTH || new_mode == OVERSCROLL_NORTH) &&
- !IsPullToRefreshEnabled())
- new_mode = OVERSCROLL_NONE;
+ if (new_mode == OVERSCROLL_SOUTH || new_mode == OVERSCROLL_NORTH) {
+ auto ptr_mode = OverscrollConfig::GetPullToRefreshMode();
+ if (ptr_mode == OverscrollConfig::PullToRefreshMode::kDisabled ||
+ (ptr_mode ==
+ OverscrollConfig::PullToRefreshMode::kEnabledTouchschreen &&
+ is_touchpad)) {
+ new_mode = OVERSCROLL_NONE;
+ }
+ }
if (overscroll_mode_ == OVERSCROLL_NONE) {
SetOverscrollMode(new_mode, is_touchpad ? OverscrollSource::TOUCHPAD
@@ -470,6 +518,7 @@ bool OverscrollController::ProcessOverscroll(float delta_x,
}
void OverscrollController::CompleteAction() {
+ ignore_following_inertial_events_ = true;
if (delegate_)
delegate_->OnOverscrollComplete(overscroll_mode_);
Reset();
@@ -499,8 +548,10 @@ void OverscrollController::SetOverscrollMode(OverscrollMode mode,
scroll_state_ = ScrollState::OVERSCROLLING;
locked_mode_ = overscroll_mode_;
}
- if (delegate_)
- delegate_->OnOverscrollModeChange(old_mode, overscroll_mode_, source);
+ if (delegate_) {
+ delegate_->OnOverscrollModeChange(old_mode, overscroll_mode_, source,
+ behavior_);
+ }
}
void OverscrollController::ResetScrollState() {
diff --git a/chromium/content/browser/renderer_host/overscroll_controller.h b/chromium/content/browser/renderer_host/overscroll_controller.h
index 48bf658e01d..a76a633aada 100644
--- a/chromium/content/browser/renderer_host/overscroll_controller.h
+++ b/chromium/content/browser/renderer_host/overscroll_controller.h
@@ -7,9 +7,10 @@
#include "base/compiler_specific.h"
#include "base/macros.h"
+#include "cc/input/overscroll_behavior.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebGestureEvent.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_gesture_event.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/events/blink/did_overscroll_params.h"
namespace content {
@@ -96,8 +97,7 @@ class CONTENT_EXPORT OverscrollController {
// Returns true if the event indicates that the in-progress overscroll gesture
// can now be completed.
- bool DispatchEventCompletesAction(
- const blink::WebInputEvent& event) const;
+ bool DispatchEventCompletesAction(const blink::WebInputEvent& event) const;
// Returns true to indicate that dispatching the event should reset the
// overscroll gesture status.
@@ -122,12 +122,19 @@ class CONTENT_EXPORT OverscrollController {
// triggered the overscroll gesture.
void SetOverscrollMode(OverscrollMode new_mode, OverscrollSource source);
+ // Whether this inertial event should be filtered out by the controller.
+ bool ShouldIgnoreInertialEvent(const blink::WebInputEvent& event) const;
+
// Whether this event should be processed or not handled by the controller.
bool ShouldProcessEvent(const blink::WebInputEvent& event);
// Helper function to reset |scroll_state_| and |locked_mode_|.
void ResetScrollState();
+ // Current value of overscroll-behavior CSS property for the root element of
+ // the page.
+ cc::OverscrollBehavior behavior_;
+
// The current state of overscroll gesture.
OverscrollMode overscroll_mode_ = OVERSCROLL_NONE;
@@ -153,6 +160,11 @@ class CONTENT_EXPORT OverscrollController {
bool wheel_scroll_latching_enabled_;
+ // A inertial scroll (fling) event may complete an overscroll gesture and
+ // navigate to a new page, but the inertial scroll can continue to generate
+ // scroll-update events. These events need to be ignored.
+ bool ignore_following_inertial_events_ = false;
+
DISALLOW_COPY_AND_ASSIGN(OverscrollController);
};
diff --git a/chromium/content/browser/renderer_host/overscroll_controller_delegate.h b/chromium/content/browser/renderer_host/overscroll_controller_delegate.h
index 3b8e09e3ca1..3ae6679573f 100644
--- a/chromium/content/browser/renderer_host/overscroll_controller_delegate.h
+++ b/chromium/content/browser/renderer_host/overscroll_controller_delegate.h
@@ -26,12 +26,6 @@ class CONTENT_EXPORT OverscrollControllerDelegate {
// delegate.
virtual gfx::Size GetDisplaySize() const = 0;
- // This is called whenever an overscroll event is generated on the renderer
- // side, and is called before OnOverscrollUpdate. The params contains an
- // OverscrollBehavior that can prevent overscroll navigation.
- virtual void OnOverscrollBehaviorUpdate(
- cc::OverscrollBehavior overscroll_behavior) = 0;
-
// This is called for each update in the overscroll amount. Returns true if
// the delegate consumed the event.
virtual bool OnOverscrollUpdate(float delta_x, float delta_y) = 0;
@@ -42,10 +36,12 @@ class CONTENT_EXPORT OverscrollControllerDelegate {
// This is called when the direction of the overscroll changes. When a new
// overscroll is started (i.e. when |new_mode| is not equal to
// OVERSCROLL_NONE), |source| will be set to the device that triggered the
- // overscroll gesture.
+ // overscroll gesture. |behavior| is the value of overscroll-behavior CSS
+ // property for the root element.
virtual void OnOverscrollModeChange(OverscrollMode old_mode,
OverscrollMode new_mode,
- OverscrollSource source) = 0;
+ OverscrollSource source,
+ cc::OverscrollBehavior behavior) = 0;
// Returns the optional maximum amount allowed for the absolute value of
// overscroll delta corresponding to the current overscroll mode.
diff --git a/chromium/content/browser/renderer_host/overscroll_controller_unittest.cc b/chromium/content/browser/renderer_host/overscroll_controller_unittest.cc
index db2f3d47f68..f69b0e29faf 100644
--- a/chromium/content/browser/renderer_host/overscroll_controller_unittest.cc
+++ b/chromium/content/browser/renderer_host/overscroll_controller_unittest.cc
@@ -7,10 +7,15 @@
#include <memory>
#include "base/containers/queue.h"
+#include "base/test/scoped_feature_list.h"
#include "content/browser/renderer_host/overscroll_controller_delegate.h"
#include "content/common/input/synthetic_web_input_event_builders.h"
+#include "content/public/browser/overscroll_configuration.h"
+#include "content/public/common/content_features.h"
+#include "content/public/test/scoped_overscroll_modes.h"
#include "content/test/test_overscroll_delegate.h"
#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/public/platform/web_input_event.h"
namespace content {
@@ -20,6 +25,9 @@ class OverscrollControllerTest : public ::testing::Test {
~OverscrollControllerTest() override {}
void SetUp() override {
+ OverscrollConfig::ResetTouchpadOverscrollHistoryNavigationEnabled();
+ scoped_feature_list_.InitAndEnableFeature(
+ features::kTouchpadOverscrollHistoryNavigation);
delegate_ = std::make_unique<TestOverscrollDelegate>(gfx::Size(400, 300));
controller_ = std::make_unique<OverscrollController>();
controller_->set_delegate(delegate_.get());
@@ -39,15 +47,43 @@ class OverscrollControllerTest : public ::testing::Test {
return controller_->WillHandleEvent(*current_event_);
}
+ // Creates and sends a gesture event to the overscroll controller. Returns
+ // |true| if the event is consumed by the overscroll controller.
+ bool SimulateGestureEvent(blink::WebInputEvent::Type type,
+ blink::WebGestureDevice source_device) {
+ DCHECK(!current_event_);
+ current_event_ = std::make_unique<blink::WebGestureEvent>(
+ SyntheticWebGestureEventBuilder::Build(type, source_device));
+ return controller_->WillHandleEvent(*current_event_);
+ }
+
// Creates and sends a gesture-scroll-update event to the overscroll
// controller. Returns |true| if the event is consumed by the overscroll
// controller.
bool SimulateGestureScrollUpdate(float dx,
float dy,
- blink::WebGestureDevice device) {
+ blink::WebGestureDevice device,
+ bool inertial_update) {
DCHECK(!current_event_);
- current_event_ = std::make_unique<blink::WebGestureEvent>(
+ auto event = std::make_unique<blink::WebGestureEvent>(
SyntheticWebGestureEventBuilder::BuildScrollUpdate(dx, dy, 0, device));
+ if (inertial_update) {
+ event->data.scroll_update.inertial_phase =
+ blink::WebGestureEvent::kMomentumPhase;
+ }
+ current_event_ = std::move(event);
+ return controller_->WillHandleEvent(*current_event_);
+ }
+
+ // Creates and sends a gesture-fling-start event to the overscroll controller.
+ // Returns |true| if the event is consumed by the overscroll controller.
+ bool SimulateGestureFlingStart(float velocity_x,
+ float velocity_y,
+ blink::WebGestureDevice device) {
+ DCHECK(!current_event_);
+ current_event_ = std::make_unique<blink::WebGestureEvent>(
+ SyntheticWebGestureEventBuilder::BuildFling(velocity_x, velocity_y,
+ device));
return controller_->WillHandleEvent(*current_event_);
}
@@ -77,6 +113,8 @@ class OverscrollControllerTest : public ::testing::Test {
// the last event is ACKed.
std::unique_ptr<blink::WebInputEvent> current_event_;
+ base::test::ScopedFeatureList scoped_feature_list_;
+
DISALLOW_COPY_AND_ASSIGN(OverscrollControllerTest);
};
@@ -84,12 +122,12 @@ class OverscrollControllerTest : public ::testing::Test {
// initiated, overscroll will not initiate anymore.
TEST_F(OverscrollControllerTest, MouseWheelConsumedPreventsOverscroll) {
// Simulate a mouse-wheel, ACK it as not processed, simulate the corresponding
- // gesture scroll-update event, and ACK it is not processed. Since it is not
+ // gesture scroll-update event, and ACK it as not processed. Since it is not
// passing the start threshold, no overscroll should happen.
EXPECT_FALSE(SimulateMouseWheel(10, 0));
SimulateAck(false);
- EXPECT_FALSE(
- SimulateGestureScrollUpdate(10, 0, blink::kWebGestureDeviceTouchpad));
+ EXPECT_FALSE(SimulateGestureScrollUpdate(
+ 10, 0, blink::kWebGestureDeviceTouchpad, false));
SimulateAck(false);
EXPECT_EQ(OVERSCROLL_NONE, controller_mode());
EXPECT_EQ(OverscrollSource::NONE, controller_source());
@@ -111,13 +149,204 @@ TEST_F(OverscrollControllerTest, MouseWheelConsumedPreventsOverscroll) {
// marked as processed.
EXPECT_FALSE(SimulateMouseWheel(100, 0));
SimulateAck(false);
+ EXPECT_FALSE(SimulateGestureScrollUpdate(
+ 100, 0, blink::kWebGestureDeviceTouchpad, false));
+ SimulateAck(false);
+ EXPECT_EQ(OVERSCROLL_NONE, controller_mode());
+ EXPECT_EQ(OverscrollSource::NONE, controller_source());
+ EXPECT_EQ(OVERSCROLL_NONE, delegate()->current_mode());
+ EXPECT_EQ(OVERSCROLL_NONE, delegate()->completed_mode());
+}
+
+// Verifying the inertial scroll event completes overscroll. After that we will
+// ignore the following inertial scroll events until new sequence start.
+TEST_F(OverscrollControllerTest,
+ InertialGestureScrollUpdateCompletesOverscroll) {
+ EXPECT_FALSE(SimulateGestureEvent(blink::WebInputEvent::kGestureScrollBegin,
+ blink::kWebGestureDeviceTouchpad));
+ SimulateAck(false);
+
+ EXPECT_FALSE(SimulateGestureScrollUpdate(
+ 200, 0, blink::kWebGestureDeviceTouchpad, false));
+ SimulateAck(false);
+ EXPECT_EQ(OVERSCROLL_EAST, controller_mode());
+ EXPECT_EQ(OverscrollSource::TOUCHPAD, controller_source());
+ EXPECT_EQ(OVERSCROLL_EAST, delegate()->current_mode());
+ EXPECT_EQ(OVERSCROLL_NONE, delegate()->completed_mode());
+
+ // Inertial update event complete the overscroll action.
+ EXPECT_FALSE(SimulateGestureScrollUpdate(
+ 100, 0, blink::kWebGestureDeviceTouchpad, true));
+ SimulateAck(false);
+ EXPECT_EQ(OVERSCROLL_NONE, controller_mode());
+ EXPECT_EQ(OverscrollSource::NONE, controller_source());
+ EXPECT_EQ(OVERSCROLL_NONE, delegate()->current_mode());
+ EXPECT_EQ(OVERSCROLL_EAST, delegate()->completed_mode());
+
+ // Next Inertial update event would be consumed by overscroll controller.
+ EXPECT_TRUE(SimulateGestureScrollUpdate(
+ 100, 0, blink::kWebGestureDeviceTouchpad, true));
+}
+
+// Verifies that when pull-to-refresh is disabled, it is not triggered for
+// neither touchpad nor touchscreen.
+TEST_F(OverscrollControllerTest, PullToRefreshDisabled) {
+ ScopedPullToRefreshMode scoped_mode(
+ OverscrollConfig::PullToRefreshMode::kDisabled);
+
+ // Simulate a touchpad gesture scroll-update event that passes the start
+ // threshold and ACK it as not processed. Pull-to-refresh should not be
+ // triggered.
+ EXPECT_FALSE(SimulateGestureScrollUpdate(
+ 0, 80, blink::kWebGestureDeviceTouchpad, false));
+ SimulateAck(false);
+ EXPECT_EQ(OVERSCROLL_NONE, controller_mode());
+ EXPECT_EQ(OverscrollSource::NONE, controller_source());
+ EXPECT_EQ(OVERSCROLL_NONE, delegate()->current_mode());
+ EXPECT_EQ(OVERSCROLL_NONE, delegate()->completed_mode());
+
+ // Simulate a touchpad zero-velocity fling-start which would normally end
+ // pull-to-refresh, and ACK it as not processed. Nothing should happen.
EXPECT_FALSE(
- SimulateGestureScrollUpdate(100, 0, blink::kWebGestureDeviceTouchpad));
+ SimulateGestureFlingStart(0, 0, blink::kWebGestureDeviceTouchpad));
SimulateAck(false);
EXPECT_EQ(OVERSCROLL_NONE, controller_mode());
EXPECT_EQ(OverscrollSource::NONE, controller_source());
EXPECT_EQ(OVERSCROLL_NONE, delegate()->current_mode());
EXPECT_EQ(OVERSCROLL_NONE, delegate()->completed_mode());
+
+ // Simulate a touchscreen gesture scroll-update event that passes the start
+ // threshold and ACK it as not processed. Pull-to-refresh should not be
+ // triggered.
+ EXPECT_FALSE(SimulateGestureScrollUpdate(
+ 0, 80, blink::kWebGestureDeviceTouchscreen, false));
+ SimulateAck(false);
+ EXPECT_EQ(OVERSCROLL_NONE, controller_mode());
+ EXPECT_EQ(OverscrollSource::NONE, controller_source());
+ EXPECT_EQ(OVERSCROLL_NONE, delegate()->current_mode());
+ EXPECT_EQ(OVERSCROLL_NONE, delegate()->completed_mode());
+
+ // Simulate a touchscreen gesture scroll-end which would normally end
+ // pull-to-refresh, and ACK it as not processed. Nothing should happen.
+ EXPECT_FALSE(SimulateGestureEvent(blink::WebInputEvent::kGestureScrollEnd,
+ blink::kWebGestureDeviceTouchscreen));
+ SimulateAck(false);
+ EXPECT_EQ(OVERSCROLL_NONE, controller_mode());
+ EXPECT_EQ(OverscrollSource::NONE, controller_source());
+ EXPECT_EQ(OVERSCROLL_NONE, delegate()->current_mode());
+ EXPECT_EQ(OVERSCROLL_NONE, delegate()->completed_mode());
+}
+
+// Verifies that when pull-to-refresh is enabled, it is triggered for both
+// touchpad and touchscreen.
+TEST_F(OverscrollControllerTest, PullToRefreshEnabled) {
+ ScopedPullToRefreshMode scoped_mode(
+ OverscrollConfig::PullToRefreshMode::kEnabled);
+
+ // Simulate a touchpad gesture scroll-update event that passes the start
+ // threshold and ACK it as not processed. Pull-to-refresh should be triggered.
+ EXPECT_FALSE(SimulateGestureScrollUpdate(
+ 0, 80, blink::kWebGestureDeviceTouchpad, false));
+ SimulateAck(false);
+ EXPECT_EQ(OVERSCROLL_SOUTH, controller_mode());
+ EXPECT_EQ(OverscrollSource::TOUCHPAD, controller_source());
+ EXPECT_EQ(OVERSCROLL_SOUTH, delegate()->current_mode());
+ EXPECT_EQ(OVERSCROLL_NONE, delegate()->completed_mode());
+
+ // Simulate a touchpad zero-velocity fling-start and ACK it as not processed..
+ // It should abort pull-to-refresh.
+ EXPECT_FALSE(
+ SimulateGestureFlingStart(0, 0, blink::kWebGestureDeviceTouchpad));
+ SimulateAck(false);
+ EXPECT_EQ(OVERSCROLL_NONE, controller_mode());
+ EXPECT_EQ(OverscrollSource::NONE, controller_source());
+ EXPECT_EQ(OVERSCROLL_NONE, delegate()->current_mode());
+ EXPECT_EQ(OVERSCROLL_NONE, delegate()->completed_mode());
+
+ // Simulate a touchscreen gesture scroll-update event that passes the start
+ // threshold and ACK it as not processed. Pull-to-refresh should be triggered.
+ EXPECT_FALSE(SimulateGestureScrollUpdate(
+ 0, 80, blink::kWebGestureDeviceTouchscreen, false));
+ SimulateAck(false);
+ EXPECT_EQ(OVERSCROLL_SOUTH, controller_mode());
+ EXPECT_EQ(OverscrollSource::TOUCHSCREEN, controller_source());
+ EXPECT_EQ(OVERSCROLL_SOUTH, delegate()->current_mode());
+ EXPECT_EQ(OVERSCROLL_NONE, delegate()->completed_mode());
+
+ // Simulate a touchscreen gesture scroll-end and ACK it as not processed. It
+ // should abort pull-to-refresh.
+ EXPECT_FALSE(SimulateGestureEvent(blink::WebInputEvent::kGestureScrollEnd,
+ blink::kWebGestureDeviceTouchscreen));
+ SimulateAck(false);
+ EXPECT_EQ(OVERSCROLL_NONE, controller_mode());
+ EXPECT_EQ(OverscrollSource::NONE, controller_source());
+ EXPECT_EQ(OVERSCROLL_NONE, delegate()->current_mode());
+ EXPECT_EQ(OVERSCROLL_NONE, delegate()->completed_mode());
+}
+
+// Verifies that when pull-to-refresh is enabled only for touchscreen, it is
+// triggered for touchscreen but not for touchpad.
+TEST_F(OverscrollControllerTest, PullToRefreshEnabledTouchscreen) {
+ ScopedPullToRefreshMode scoped_mode(
+ OverscrollConfig::PullToRefreshMode::kEnabledTouchschreen);
+
+ // Simulate a touchpad gesture scroll-update event that passes the start
+ // threshold and ACK it as not processed. Pull-to-refresh should not be
+ // triggered.
+ EXPECT_FALSE(SimulateGestureScrollUpdate(
+ 0, 80, blink::kWebGestureDeviceTouchpad, false));
+ SimulateAck(false);
+ EXPECT_EQ(OVERSCROLL_NONE, controller_mode());
+ EXPECT_EQ(OverscrollSource::NONE, controller_source());
+ EXPECT_EQ(OVERSCROLL_NONE, delegate()->current_mode());
+ EXPECT_EQ(OVERSCROLL_NONE, delegate()->completed_mode());
+
+ // Simulate a touchpad zero-velocity fling-start which would normally end
+ // pull-to-refresh, and ACK it as not processed. Nothing should happen.
+ EXPECT_FALSE(
+ SimulateGestureFlingStart(0, 0, blink::kWebGestureDeviceTouchpad));
+ SimulateAck(false);
+ EXPECT_EQ(OVERSCROLL_NONE, controller_mode());
+ EXPECT_EQ(OverscrollSource::NONE, controller_source());
+ EXPECT_EQ(OVERSCROLL_NONE, delegate()->current_mode());
+ EXPECT_EQ(OVERSCROLL_NONE, delegate()->completed_mode());
+
+ // Simulate a touchscreen gesture scroll-update event that passes the start
+ // threshold and ACK it as not processed. Pull-to-refresh should be triggered.
+ EXPECT_FALSE(SimulateGestureScrollUpdate(
+ 0, 80, blink::kWebGestureDeviceTouchscreen, false));
+ SimulateAck(false);
+ EXPECT_EQ(OVERSCROLL_SOUTH, controller_mode());
+ EXPECT_EQ(OverscrollSource::TOUCHSCREEN, controller_source());
+ EXPECT_EQ(OVERSCROLL_SOUTH, delegate()->current_mode());
+ EXPECT_EQ(OVERSCROLL_NONE, delegate()->completed_mode());
+
+ // Simulate a touchscreen gesture scroll-end and ACK it as not processed. It
+ // should abort pull-to-refresh.
+ EXPECT_FALSE(SimulateGestureEvent(blink::WebInputEvent::kGestureScrollEnd,
+ blink::kWebGestureDeviceTouchscreen));
+ SimulateAck(false);
+ EXPECT_EQ(OVERSCROLL_NONE, controller_mode());
+ EXPECT_EQ(OverscrollSource::NONE, controller_source());
+ EXPECT_EQ(OVERSCROLL_NONE, delegate()->current_mode());
+ EXPECT_EQ(OVERSCROLL_NONE, delegate()->completed_mode());
+}
+
+// Ensure disabling kTouchpadOverscrollHistoryNavigation will prevent overscroll
+// from touchpad.
+TEST_F(OverscrollControllerTest, DisableTouchpadOverscrollHistoryNavigation) {
+ base::test::ScopedFeatureList feature_list;
+ feature_list.InitAndDisableFeature(
+ features::kTouchpadOverscrollHistoryNavigation);
+ ASSERT_FALSE(OverscrollConfig::TouchpadOverscrollHistoryNavigationEnabled());
+ EXPECT_FALSE(SimulateGestureScrollUpdate(
+ 200, 0, blink::kWebGestureDeviceTouchpad, false));
+ SimulateAck(false);
+
+ EXPECT_EQ(OVERSCROLL_NONE, controller_mode());
+ EXPECT_EQ(OverscrollSource::NONE, controller_source());
+ EXPECT_EQ(OVERSCROLL_NONE, delegate()->current_mode());
+ EXPECT_EQ(OVERSCROLL_NONE, delegate()->completed_mode());
}
} // namespace content
diff --git a/chromium/content/browser/renderer_host/p2p/socket_dispatcher_host.cc b/chromium/content/browser/renderer_host/p2p/socket_dispatcher_host.cc
index 8e90556d683..c8bfe794b21 100644
--- a/chromium/content/browser/renderer_host/p2p/socket_dispatcher_host.cc
+++ b/chromium/content/browser/renderer_host/p2p/socket_dispatcher_host.cc
@@ -9,7 +9,6 @@
#include <algorithm>
#include "base/bind.h"
-#include "base/memory/ptr_util.h"
#include "base/task_scheduler/post_task.h"
#include "content/browser/bad_message.h"
#include "content/browser/renderer_host/p2p/socket_host.h"
@@ -44,6 +43,11 @@ const uint8_t kPublicIPv6Host[] = {
0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0, 0, 0, 0, 0, 0, 0, 0, 0x88, 0x88};
const int kPublicPort = 53; // DNS port.
+// Experimentation shows that creating too many sockets creates odd problems
+// because of resource exhaustion in the Unix sockets domain.
+// Trouble has been seen on Linux at 3479 sockets in test, so leave a margin.
+const int kMaxSimultaneousSockets = 3000;
+
} // namespace
const size_t kMaximumPacketSize = 32768;
@@ -268,6 +272,11 @@ void P2PSocketDispatcherHost::OnCreateSocket(
std::make_unique<network::ProxyResolvingClientSocketFactory>(
nullptr, url_context_->GetURLRequestContext());
}
+ if (sockets_.size() > kMaxSimultaneousSockets) {
+ LOG(ERROR) << "Too many sockets created";
+ Send(new P2PMsg_OnError(socket_id));
+ return;
+ }
std::unique_ptr<P2PSocketHost> socket(P2PSocketHost::Create(
this, socket_id, type, url_context_.get(),
proxy_resolving_socket_factory_.get(), &throttler_));
@@ -384,10 +393,9 @@ net::IPAddress P2PSocketDispatcherHost::GetDefaultLocalAddress(int family) {
// Creation and connection of a UDP socket might be janky.
DCHECK(network_list_task_runner_->RunsTasksInCurrentSequence());
- std::unique_ptr<net::DatagramClientSocket> socket(
+ auto socket =
net::ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
- net::DatagramSocket::DEFAULT_BIND, net::RandIntCallback(), nullptr,
- net::NetLogSource()));
+ net::DatagramSocket::DEFAULT_BIND, nullptr, net::NetLogSource());
net::IPAddress ip_address;
if (family == AF_INET) {
diff --git a/chromium/content/browser/renderer_host/p2p/socket_host_tcp.cc b/chromium/content/browser/renderer_host/p2p/socket_host_tcp.cc
index 83d8168d378..12ead42db0e 100644
--- a/chromium/content/browser/renderer_host/p2p/socket_host_tcp.cc
+++ b/chromium/content/browser/renderer_host/p2p/socket_host_tcp.cc
@@ -126,7 +126,8 @@ bool P2PSocketHostTcpBase::Init(const net::IPEndPoint& local_address,
// The default SSLConfig is good enough for us for now.
const net::SSLConfig ssl_config;
socket_ = proxy_resolving_socket_factory_->CreateSocket(
- ssl_config, GURL("https://" + dest_host_port_pair.ToString()));
+ ssl_config, GURL("https://" + dest_host_port_pair.ToString()),
+ false /*use_tls*/);
int status = socket_->Connect(
base::Bind(&P2PSocketHostTcpBase::OnConnected,
diff --git a/chromium/content/browser/renderer_host/p2p/socket_host_tcp_server_unittest.cc b/chromium/content/browser/renderer_host/p2p/socket_host_tcp_server_unittest.cc
index 06837d32af4..ca1ea46195c 100644
--- a/chromium/content/browser/renderer_host/p2p/socket_host_tcp_server_unittest.cc
+++ b/chromium/content/browser/renderer_host/p2p/socket_host_tcp_server_unittest.cc
@@ -40,7 +40,7 @@ class FakeServerSocket : public net::ServerSocket {
// callback.
net::CompletionCallback cb = accept_callback_;
accept_callback_.Reset();
- cb.Run(net::OK);
+ std::move(cb).Run(net::OK);
} else {
incoming_sockets_.push_back(socket);
}
diff --git a/chromium/content/browser/renderer_host/p2p/socket_host_test_utils.cc b/chromium/content/browser/renderer_host/p2p/socket_host_test_utils.cc
index 767bf7774a5..389ed2bfeec 100644
--- a/chromium/content/browser/renderer_host/p2p/socket_host_test_utils.cc
+++ b/chromium/content/browser/renderer_host/p2p/socket_host_test_utils.cc
@@ -46,7 +46,7 @@ void FakeSocket::AppendInputData(const char* data, int data_size) {
read_buffer_ = nullptr;
net::CompletionCallback cb = read_callback_;
read_callback_.Reset();
- cb.Run(result);
+ std::move(cb).Run(result);
}
}
diff --git a/chromium/content/browser/renderer_host/p2p/socket_host_throttler.cc b/chromium/content/browser/renderer_host/p2p/socket_host_throttler.cc
index 1cb6d424085..e54d190eee7 100644
--- a/chromium/content/browser/renderer_host/p2p/socket_host_throttler.cc
+++ b/chromium/content/browser/renderer_host/p2p/socket_host_throttler.cc
@@ -6,7 +6,7 @@
#include <utility>
-#include "third_party/webrtc/rtc_base/ratelimiter.h"
+#include "third_party/webrtc/rtc_base/data_rate_limiter.h"
#include "third_party/webrtc/rtc_base/timeutils.h"
namespace content {
@@ -17,16 +17,14 @@ const int kMaxIceMessageBandwidth = 256 * 1024;
} // namespace
-
P2PMessageThrottler::P2PMessageThrottler()
- : rate_limiter_(new rtc::RateLimiter(kMaxIceMessageBandwidth, 1.0)) {
-}
+ : rate_limiter_(new rtc::DataRateLimiter(kMaxIceMessageBandwidth, 1.0)) {}
P2PMessageThrottler::~P2PMessageThrottler() {
}
void P2PMessageThrottler::SetSendIceBandwidth(int bandwidth_kbps) {
- rate_limiter_.reset(new rtc::RateLimiter(bandwidth_kbps, 1.0));
+ rate_limiter_.reset(new rtc::DataRateLimiter(bandwidth_kbps, 1.0));
}
bool P2PMessageThrottler::DropNextPacket(size_t packet_len) {
diff --git a/chromium/content/browser/renderer_host/p2p/socket_host_throttler.h b/chromium/content/browser/renderer_host/p2p/socket_host_throttler.h
index 3715275f6a9..d8ad20c7dd3 100644
--- a/chromium/content/browser/renderer_host/p2p/socket_host_throttler.h
+++ b/chromium/content/browser/renderer_host/p2p/socket_host_throttler.h
@@ -13,7 +13,7 @@
#include "content/common/content_export.h"
namespace rtc {
-class RateLimiter;
+class DataRateLimiter;
}
namespace content {
@@ -31,7 +31,7 @@ class CONTENT_EXPORT P2PMessageThrottler {
void SetSendIceBandwidth(int bandwith_kbps);
private:
- std::unique_ptr<rtc::RateLimiter> rate_limiter_;
+ std::unique_ptr<rtc::DataRateLimiter> rate_limiter_;
DISALLOW_COPY_AND_ASSIGN(P2PMessageThrottler);
};
diff --git a/chromium/content/browser/renderer_host/p2p/socket_host_udp.cc b/chromium/content/browser/renderer_host/p2p/socket_host_udp.cc
index cc5e0d47403..318ed0bbd5a 100644
--- a/chromium/content/browser/renderer_host/p2p/socket_host_udp.cc
+++ b/chromium/content/browser/renderer_host/p2p/socket_host_udp.cc
@@ -317,7 +317,7 @@ void P2PSocketHostUdp::DoSend(const PendingPacket& packet) {
static_cast<net::DiffServCodePoint>(packet.packet_options.dscp);
if (dscp != net::DSCP_NO_CHANGE && last_dscp_ != dscp &&
last_dscp_ != net::DSCP_NO_CHANGE) {
- int result = socket_->SetDiffServCodePoint(dscp);
+ int result = SetSocketDiffServCodePointInternal(dscp);
if (result == net::OK) {
last_dscp_ = dscp;
} else if (!IsTransientError(result) && last_dscp_ != net::DSCP_CS0) {
@@ -346,7 +346,7 @@ void P2PSocketHostUdp::DoSend(const PendingPacket& packet) {
// and just drop it if it fails again.
if (IsTransientError(result)) {
result = socket_->SendTo(packet.data.get(), packet.size, packet.to,
- callback_binding);
+ std::move(callback_binding));
}
if (result == net::ERR_IO_PENDING) {
@@ -422,21 +422,31 @@ bool P2PSocketHostUdp::SetOption(P2PSocketOption option, int value) {
DCHECK_EQ(state_, STATE_ERROR);
return false;
}
-
switch (option) {
case P2P_SOCKET_OPT_RCVBUF:
return socket_->SetReceiveBufferSize(value) == net::OK;
case P2P_SOCKET_OPT_SNDBUF:
return socket_->SetSendBufferSize(value) == net::OK;
case P2P_SOCKET_OPT_DSCP:
- return (net::OK == socket_->SetDiffServCodePoint(
- static_cast<net::DiffServCodePoint>(value))) ? true : false;
+ return net::OK == SetSocketDiffServCodePointInternal(
+ static_cast<net::DiffServCodePoint>(value));
default:
NOTREACHED();
return false;
}
}
+// TODO(crbug.com/812137): We don't call SetDiffServCodePoint for the Windows
+// UDP socket, because this is known to cause a hanging thread.
+int P2PSocketHostUdp::SetSocketDiffServCodePointInternal(
+ net::DiffServCodePoint dscp) {
+#if defined(OS_WIN)
+ return net::OK;
+#else
+ return socket_->SetDiffServCodePoint(dscp);
+#endif
+}
+
// static
std::unique_ptr<net::DatagramServerSocket>
P2PSocketHostUdp::DefaultSocketFactory(net::NetLog* net_log) {
diff --git a/chromium/content/browser/renderer_host/p2p/socket_host_udp.h b/chromium/content/browser/renderer_host/p2p/socket_host_udp.h
index 1ceef05b09e..9ff284aef8d 100644
--- a/chromium/content/browser/renderer_host/p2p/socket_host_udp.h
+++ b/chromium/content/browser/renderer_host/p2p/socket_host_udp.h
@@ -102,6 +102,7 @@ class CONTENT_EXPORT P2PSocketHostUdp : public P2PSocketHost {
int32_t transport_sequence_number,
base::TimeTicks send_time,
int result);
+ int SetSocketDiffServCodePointInternal(net::DiffServCodePoint dscp);
static std::unique_ptr<net::DatagramServerSocket> DefaultSocketFactory(
net::NetLog* net_log);
diff --git a/chromium/content/browser/renderer_host/p2p/socket_host_udp_unittest.cc b/chromium/content/browser/renderer_host/p2p/socket_host_udp_unittest.cc
index e286adb596a..925e600eb16 100644
--- a/chromium/content/browser/renderer_host/p2p/socket_host_udp_unittest.cc
+++ b/chromium/content/browser/renderer_host/p2p/socket_host_udp_unittest.cc
@@ -10,7 +10,6 @@
#include "base/containers/circular_deque.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/sys_byteorder.h"
#include "content/browser/renderer_host/p2p/socket_host_test_utils.h"
#include "content/browser/renderer_host/p2p/socket_host_throttler.h"
@@ -126,6 +125,8 @@ class FakeDatagramServerSocket : public net::DatagramServerSocket {
int SetDoNotFragment() override { return net::OK; }
+ void SetMsgConfirm(bool confirm) override {}
+
void ReceivePacket(const net::IPEndPoint& address, std::vector<char> data) {
if (!recv_callback_.is_null()) {
int size = std::min(recv_size_, static_cast<int>(data.size()));
@@ -134,7 +135,7 @@ class FakeDatagramServerSocket : public net::DatagramServerSocket {
net::CompletionCallback cb = recv_callback_;
recv_callback_.Reset();
recv_buffer_ = nullptr;
- cb.Run(size);
+ std::move(cb).Run(size);
} else {
incoming_packets_.push_back(UDPPacket(address, data));
}
@@ -526,8 +527,9 @@ TEST_F(P2PSocketHostUdpTest, PortRangeImplicitPort) {
EXPECT_CALL(sender,
Send(MatchMessage(static_cast<uint32_t>(P2PMsg_OnError::ID))))
.WillOnce(DoAll(DeleteArg<0>(), Return(true)));
- std::unique_ptr<P2PSocketHostUdp> socket_host(new P2PSocketHostUdp(
- &sender, 0, &throttler, /*net_log=*/nullptr, fake_socket_factory));
+ std::unique_ptr<P2PSocketHostUdp> socket_host(
+ new P2PSocketHostUdp(&sender, 0, &throttler, /*net_log=*/nullptr,
+ std::move(fake_socket_factory)));
net::IPEndPoint local_address = ParseAddress(kTestLocalIpAddress, 0);
bool rv = socket_host->Init(local_address, min_port, max_port,
P2PHostAndIPEndPoint());
@@ -551,8 +553,9 @@ TEST_F(P2PSocketHostUdpTest, PortRangeExplictValidPort) {
Send(MatchMessage(static_cast<uint32_t>(P2PMsg_OnSocketCreated::ID))))
.WillOnce(DoAll(DeleteArg<0>(), Return(true)));
- std::unique_ptr<P2PSocketHostUdp> socket_host(new P2PSocketHostUdp(
- &sender, 0, &throttler, /*net_log=*/nullptr, fake_socket_factory));
+ std::unique_ptr<P2PSocketHostUdp> socket_host(
+ new P2PSocketHostUdp(&sender, 0, &throttler, /*net_log=*/nullptr,
+ std::move(fake_socket_factory)));
net::IPEndPoint local_address = ParseAddress(kTestLocalIpAddress, valid_port);
bool rv = socket_host->Init(local_address, min_port, max_port,
P2PHostAndIPEndPoint());
@@ -580,8 +583,9 @@ TEST_F(P2PSocketHostUdpTest, PortRangeExplictInvalidPort) {
Send(MatchMessage(static_cast<uint32_t>(P2PMsg_OnError::ID))))
.WillOnce(DoAll(DeleteArg<0>(), Return(true)));
- std::unique_ptr<P2PSocketHostUdp> socket_host(new P2PSocketHostUdp(
- &sender, 0, &throttler, /*net_log=*/nullptr, fake_socket_factory));
+ std::unique_ptr<P2PSocketHostUdp> socket_host(
+ new P2PSocketHostUdp(&sender, 0, &throttler, /*net_log=*/nullptr,
+ std::move(fake_socket_factory)));
net::IPEndPoint local_address =
ParseAddress(kTestLocalIpAddress, invalid_port);
bool rv = socket_host->Init(local_address, min_port, max_port,
diff --git a/chromium/content/browser/renderer_host/pepper/browser_ppapi_host_impl.cc b/chromium/content/browser/renderer_host/pepper/browser_ppapi_host_impl.cc
index 75124b4e10a..09c612c70a1 100644
--- a/chromium/content/browser/renderer_host/pepper/browser_ppapi_host_impl.cc
+++ b/chromium/content/browser/renderer_host/pepper/browser_ppapi_host_impl.cc
@@ -4,7 +4,6 @@
#include "content/browser/renderer_host/pepper/browser_ppapi_host_impl.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_functions.h"
#include "content/browser/renderer_host/pepper/pepper_message_filter.h"
#include "content/browser/tracing/trace_message_filter.h"
diff --git a/chromium/content/browser/renderer_host/pepper/browser_ppapi_host_impl.h b/chromium/content/browser/renderer_host/pepper/browser_ppapi_host_impl.h
index db48eac07f3..6f00768bc50 100644
--- a/chromium/content/browser/renderer_host/pepper/browser_ppapi_host_impl.h
+++ b/chromium/content/browser/renderer_host/pepper/browser_ppapi_host_impl.h
@@ -24,7 +24,7 @@
#include "content/public/browser/browser_ppapi_host.h"
#include "content/public/common/process_type.h"
#include "ipc/message_filter.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#include "ppapi/host/ppapi_host.h"
#if !BUILDFLAG(ENABLE_PLUGINS)
diff --git a/chromium/content/browser/renderer_host/pepper/content_browser_pepper_host_factory.cc b/chromium/content/browser/renderer_host/pepper/content_browser_pepper_host_factory.cc
index f0cd482cf3d..782cd8b785b 100644
--- a/chromium/content/browser/renderer_host/pepper/content_browser_pepper_host_factory.cc
+++ b/chromium/content/browser/renderer_host/pepper/content_browser_pepper_host_factory.cc
@@ -7,7 +7,6 @@
#include <stddef.h>
#include <utility>
-#include "base/memory/ptr_util.h"
#include "content/browser/renderer_host/pepper/browser_ppapi_host_impl.h"
#include "content/browser/renderer_host/pepper/pepper_browser_font_singleton_host.h"
#include "content/browser/renderer_host/pepper/pepper_file_io_host.h"
diff --git a/chromium/content/browser/renderer_host/pepper/pepper_external_file_ref_backend.cc b/chromium/content/browser/renderer_host/pepper/pepper_external_file_ref_backend.cc
index eb8e27d36c9..cdc4ab29cde 100644
--- a/chromium/content/browser/renderer_host/pepper/pepper_external_file_ref_backend.cc
+++ b/chromium/content/browser/renderer_host/pepper/pepper_external_file_ref_backend.cc
@@ -47,14 +47,10 @@ int32_t PepperExternalFileRefBackend::Touch(
PP_Time last_modified_time) {
IPC::Message reply_msg = PpapiPluginMsg_FileRef_TouchReply();
base::FileUtilProxy::Touch(
- task_runner_.get(),
- path_,
- ppapi::PPTimeToTime(last_access_time),
+ task_runner_.get(), path_, ppapi::PPTimeToTime(last_access_time),
ppapi::PPTimeToTime(last_modified_time),
- base::Bind(&PepperExternalFileRefBackend::DidFinish,
- weak_factory_.GetWeakPtr(),
- reply_context,
- reply_msg));
+ base::BindOnce(&PepperExternalFileRefBackend::DidFinish,
+ weak_factory_.GetWeakPtr(), reply_context, reply_msg));
return PP_OK_COMPLETIONPENDING;
}
@@ -74,11 +70,9 @@ int32_t PepperExternalFileRefBackend::Rename(
int32_t PepperExternalFileRefBackend::Query(
ppapi::host::ReplyMessageContext reply_context) {
bool ok = base::FileUtilProxy::GetFileInfo(
- task_runner_.get(),
- path_,
- base::Bind(&PepperExternalFileRefBackend::GetMetadataComplete,
- weak_factory_.GetWeakPtr(),
- reply_context));
+ task_runner_.get(), path_,
+ base::BindOnce(&PepperExternalFileRefBackend::GetMetadataComplete,
+ weak_factory_.GetWeakPtr(), reply_context));
DCHECK(ok);
return PP_OK_COMPLETIONPENDING;
}
diff --git a/chromium/content/browser/renderer_host/pepper/pepper_file_io_host.cc b/chromium/content/browser/renderer_host/pepper/pepper_file_io_host.cc
index 8cb0a384b41..259f1102674 100644
--- a/chromium/content/browser/renderer_host/pepper/pepper_file_io_host.cc
+++ b/chromium/content/browser/renderer_host/pepper/pepper_file_io_host.cc
@@ -94,7 +94,7 @@ void DidOpenFile(base::WeakPtr<PepperFileIOHost> file_host,
base::File file,
base::OnceClosure on_close_callback) {
if (file_host) {
- callback.Run(std::move(file), std::move(on_close_callback));
+ std::move(callback).Run(std::move(file), std::move(on_close_callback));
} else {
task_runner->PostTaskAndReply(
FROM_HERE, base::BindOnce(&FileCloser, std::move(file)),
@@ -295,8 +295,8 @@ void PepperFileIOHost::GotResolvedRenderProcessId(
DCHECK_CURRENTLY_ON(BrowserThread::IO);
resolved_render_process_id_ = resolved_render_process_id;
file_.CreateOrOpen(path, file_flags,
- base::Bind(&PepperFileIOHost::OnLocalFileOpened,
- AsWeakPtr(), reply_context, path));
+ base::BindOnce(&PepperFileIOHost::OnLocalFileOpened,
+ AsWeakPtr(), reply_context, path));
}
int32_t PepperFileIOHost::OnHostMsgTouch(
@@ -309,11 +309,9 @@ int32_t PepperFileIOHost::OnHostMsgTouch(
return rv;
if (!file_.SetTimes(
- PPTimeToTime(last_access_time),
- PPTimeToTime(last_modified_time),
- base::Bind(&PepperFileIOHost::ExecutePlatformGeneralCallback,
- AsWeakPtr(),
- context->MakeReplyMessageContext()))) {
+ PPTimeToTime(last_access_time), PPTimeToTime(last_modified_time),
+ base::BindOnce(&PepperFileIOHost::ExecutePlatformGeneralCallback,
+ AsWeakPtr(), context->MakeReplyMessageContext()))) {
return PP_ERROR_FAILED;
}
@@ -336,9 +334,8 @@ int32_t PepperFileIOHost::OnHostMsgSetLength(
if (!file_.SetLength(
length,
- base::Bind(&PepperFileIOHost::ExecutePlatformGeneralCallback,
- AsWeakPtr(),
- context->MakeReplyMessageContext()))) {
+ base::BindOnce(&PepperFileIOHost::ExecutePlatformGeneralCallback,
+ AsWeakPtr(), context->MakeReplyMessageContext()))) {
return PP_ERROR_FAILED;
}
@@ -354,9 +351,8 @@ int32_t PepperFileIOHost::OnHostMsgFlush(
return rv;
if (!file_.Flush(
- base::Bind(&PepperFileIOHost::ExecutePlatformGeneralCallback,
- AsWeakPtr(),
- context->MakeReplyMessageContext()))) {
+ base::BindOnce(&PepperFileIOHost::ExecutePlatformGeneralCallback,
+ AsWeakPtr(), context->MakeReplyMessageContext()))) {
return PP_ERROR_FAILED;
}
@@ -373,8 +369,7 @@ int32_t PepperFileIOHost::OnHostMsgClose(
}
if (file_.IsValid()) {
- file_.Close(base::Bind(&PepperFileIOHost::DidCloseFile,
- AsWeakPtr()));
+ file_.Close(base::BindOnce(&PepperFileIOHost::DidCloseFile, AsWeakPtr()));
}
return PP_OK;
}
diff --git a/chromium/content/browser/renderer_host/pepper/pepper_internal_file_ref_backend.cc b/chromium/content/browser/renderer_host/pepper/pepper_internal_file_ref_backend.cc
index ab1c3fc3d50..ea6cf498c36 100644
--- a/chromium/content/browser/renderer_host/pepper/pepper_internal_file_ref_backend.cc
+++ b/chromium/content/browser/renderer_host/pepper/pepper_internal_file_ref_backend.cc
@@ -7,6 +7,7 @@
#include <string.h>
#include <string>
+#include <vector>
#include "base/callback.h"
#include "base/files/file_util.h"
@@ -236,8 +237,9 @@ void PepperInternalFileRefBackend::ReadDirectoryComplete(
dir_path += '/';
for (const auto& it : *accumulated_file_list) {
- file_types.push_back(it.is_directory ? PP_FILETYPE_DIRECTORY
- : PP_FILETYPE_REGULAR);
+ file_types.push_back(it.type == filesystem::mojom::FsFileType::DIRECTORY
+ ? PP_FILETYPE_DIRECTORY
+ : PP_FILETYPE_REGULAR);
ppapi::FileRefCreateInfo info;
info.file_system_type = fs_type_;
diff --git a/chromium/content/browser/renderer_host/pepper/pepper_network_monitor_host.cc b/chromium/content/browser/renderer_host/pepper/pepper_network_monitor_host.cc
index 79e5e7f90e5..ed62e219f02 100644
--- a/chromium/content/browser/renderer_host/pepper/pepper_network_monitor_host.cc
+++ b/chromium/content/browser/renderer_host/pepper/pepper_network_monitor_host.cc
@@ -64,10 +64,14 @@ PepperNetworkMonitorHost::PepperNetworkMonitorHost(BrowserPpapiHostImpl* host,
}
PepperNetworkMonitorHost::~PepperNetworkMonitorHost() {
- net::NetworkChangeNotifier::RemoveIPAddressObserver(this);
+ net::NetworkChangeNotifier::RemoveNetworkChangeObserver(this);
}
-void PepperNetworkMonitorHost::OnIPAddressChanged() { GetAndSendNetworkList(); }
+void PepperNetworkMonitorHost::OnNetworkChanged(
+ net::NetworkChangeNotifier::ConnectionType type) {
+ if (type == net::NetworkChangeNotifier::GetConnectionType())
+ GetAndSendNetworkList();
+}
void PepperNetworkMonitorHost::OnPermissionCheckResult(
bool can_use_network_monitor) {
@@ -77,7 +81,7 @@ void PepperNetworkMonitorHost::OnPermissionCheckResult(
return;
}
- net::NetworkChangeNotifier::AddIPAddressObserver(this);
+ net::NetworkChangeNotifier::AddNetworkChangeObserver(this);
GetAndSendNetworkList();
}
diff --git a/chromium/content/browser/renderer_host/pepper/pepper_network_monitor_host.h b/chromium/content/browser/renderer_host/pepper/pepper_network_monitor_host.h
index c04d4993b69..5e61b20fe27 100644
--- a/chromium/content/browser/renderer_host/pepper/pepper_network_monitor_host.h
+++ b/chromium/content/browser/renderer_host/pepper/pepper_network_monitor_host.h
@@ -21,7 +21,7 @@ class BrowserPpapiHostImpl;
// The host for PPB_NetworkMonitor. This class lives on the IO thread.
class CONTENT_EXPORT PepperNetworkMonitorHost
: public ppapi::host::ResourceHost,
- public net::NetworkChangeNotifier::IPAddressObserver {
+ public net::NetworkChangeNotifier::NetworkChangeObserver {
public:
PepperNetworkMonitorHost(BrowserPpapiHostImpl* host,
PP_Instance instance,
@@ -29,8 +29,9 @@ class CONTENT_EXPORT PepperNetworkMonitorHost
~PepperNetworkMonitorHost() override;
- // net::NetworkChangeNotifier::IPAddressObserver interface.
- void OnIPAddressChanged() override;
+ // net::NetworkChangeNotifier::NetworkChangeObserver interface.
+ void OnNetworkChanged(
+ net::NetworkChangeNotifier::ConnectionType type) override;
private:
void OnPermissionCheckResult(bool can_use_network_monitor);
diff --git a/chromium/content/browser/renderer_host/pepper/pepper_network_proxy_host.cc b/chromium/content/browser/renderer_host/pepper/pepper_network_proxy_host.cc
index 4dcdf4d138a..3fcb804a5f8 100644
--- a/chromium/content/browser/renderer_host/pepper/pepper_network_proxy_host.cc
+++ b/chromium/content/browser/renderer_host/pepper/pepper_network_proxy_host.cc
@@ -152,7 +152,7 @@ void PepperNetworkProxyHost::TryToSendUnsentRequests() {
// If it was handled synchronously, we must run the callback now;
// proxy_resolution_service_ won't run it for us in this case.
if (result != net::ERR_IO_PENDING)
- callback.Run(result);
+ std::move(callback).Run(result);
}
unsent_requests_.pop();
}
diff --git a/chromium/content/browser/renderer_host/pepper/pepper_network_proxy_host.h b/chromium/content/browser/renderer_host/pepper/pepper_network_proxy_host.h
index 780af3e2df5..a3b9424aeba 100644
--- a/chromium/content/browser/renderer_host/pepper/pepper_network_proxy_host.h
+++ b/chromium/content/browser/renderer_host/pepper/pepper_network_proxy_host.h
@@ -15,7 +15,7 @@
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "content/common/content_export.h"
-#include "net/proxy_resolution/proxy_service.h"
+#include "net/proxy_resolution/proxy_resolution_service.h"
#include "ppapi/host/host_message_context.h"
#include "ppapi/host/resource_host.h"
diff --git a/chromium/content/browser/renderer_host/pepper/pepper_print_settings_manager.cc b/chromium/content/browser/renderer_host/pepper/pepper_print_settings_manager.cc
index 94d7951abf7..0a3c9da3d24 100644
--- a/chromium/content/browser/renderer_host/pepper/pepper_print_settings_manager.cc
+++ b/chromium/content/browser/renderer_host/pepper/pepper_print_settings_manager.cc
@@ -8,7 +8,7 @@
#include "content/public/browser/content_browser_client.h"
#include "content/public/common/content_client.h"
#include "ppapi/c/pp_errors.h"
-#include "printing/features/features.h"
+#include "printing/buildflags/buildflags.h"
#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
#include "printing/printing_context.h" // nogncheck
@@ -112,10 +112,8 @@ PepperPrintSettingsManager::Result ComputeDefaultPrintSettings() {
void PepperPrintSettingsManagerImpl::GetDefaultPrintSettings(
PepperPrintSettingsManager::Callback callback) {
BrowserThread::PostTaskAndReplyWithResult(
- BrowserThread::UI,
- FROM_HERE,
- base::Bind(ComputeDefaultPrintSettings),
- callback);
+ BrowserThread::UI, FROM_HERE, base::Bind(ComputeDefaultPrintSettings),
+ std::move(callback));
}
} // namespace content
diff --git a/chromium/content/browser/renderer_host/pepper/pepper_printing_host_unittest.cc b/chromium/content/browser/renderer_host/pepper/pepper_printing_host_unittest.cc
index 3ae9075a5cb..a1275661065 100644
--- a/chromium/content/browser/renderer_host/pepper/pepper_printing_host_unittest.cc
+++ b/chromium/content/browser/renderer_host/pepper/pepper_printing_host_unittest.cc
@@ -45,7 +45,7 @@ MockPepperPrintSettingsManager::MockPepperPrintSettingsManager(
void MockPepperPrintSettingsManager::GetDefaultPrintSettings(
PepperPrintSettingsManager::Callback callback) {
- callback.Run(PepperPrintSettingsManager::Result(settings_, PP_OK));
+ std::move(callback).Run(PepperPrintSettingsManager::Result(settings_, PP_OK));
}
class PepperPrintingHostTest : public testing::Test,
diff --git a/chromium/content/browser/renderer_host/pepper/pepper_renderer_connection.cc b/chromium/content/browser/renderer_host/pepper/pepper_renderer_connection.cc
index af880f7b0dc..62c9808e6a8 100644
--- a/chromium/content/browser/renderer_host/pepper/pepper_renderer_connection.cc
+++ b/chromium/content/browser/renderer_host/pepper/pepper_renderer_connection.cc
@@ -18,6 +18,7 @@
#include "content/browser/renderer_host/pepper/pepper_file_system_browser_host.h"
#include "content/common/frame_messages.h"
#include "content/common/pepper_renderer_instance_data.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/common/content_client.h"
#include "ipc/ipc_message_macros.h"
diff --git a/chromium/content/browser/renderer_host/pepper/pepper_socket_utils.cc b/chromium/content/browser/renderer_host/pepper/pepper_socket_utils.cc
index ab546731789..2050cf6f4d3 100644
--- a/chromium/content/browser/renderer_host/pepper/pepper_socket_utils.cc
+++ b/chromium/content/browser/renderer_host/pepper/pepper_socket_utils.cc
@@ -8,7 +8,6 @@
#include <vector>
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/strings/string_util.h"
#include "base/values.h"
diff --git a/chromium/content/browser/renderer_host/pepper/pepper_udp_socket_message_filter.cc b/chromium/content/browser/renderer_host/pepper/pepper_udp_socket_message_filter.cc
index ed3a9daea66..141d0b840a2 100644
--- a/chromium/content/browser/renderer_host/pepper/pepper_udp_socket_message_filter.cc
+++ b/chromium/content/browser/renderer_host/pepper/pepper_udp_socket_message_filter.cc
@@ -20,7 +20,6 @@
#include "ipc/ipc_message_macros.h"
#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/udp_socket.h"
#include "ppapi/c/pp_errors.h"
@@ -399,9 +398,8 @@ void PepperUDPSocketMessageFilter::DoBind(
return;
}
- std::unique_ptr<net::UDPSocket> socket(
- new net::UDPSocket(net::DatagramSocket::DEFAULT_BIND,
- net::RandIntCallback(), nullptr, net::NetLogSource()));
+ auto socket = std::make_unique<net::UDPSocket>(
+ net::DatagramSocket::DEFAULT_BIND, nullptr, net::NetLogSource());
net::IPAddressBytes address;
uint16_t port;
diff --git a/chromium/content/browser/renderer_host/pepper/pepper_vpn_provider_message_filter_chromeos.cc b/chromium/content/browser/renderer_host/pepper/pepper_vpn_provider_message_filter_chromeos.cc
index 5327e8d97bc..232ed55c4eb 100644
--- a/chromium/content/browser/renderer_host/pepper/pepper_vpn_provider_message_filter_chromeos.cc
+++ b/chromium/content/browser/renderer_host/pepper/pepper_vpn_provider_message_filter_chromeos.cc
@@ -4,7 +4,6 @@
#include "content/browser/renderer_host/pepper/pepper_vpn_provider_message_filter_chromeos.h"
-#include "base/memory/ptr_util.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/pepper_vpn_provider_resource_host_proxy.h"
diff --git a/chromium/content/browser/renderer_host/popup_window_mac.h b/chromium/content/browser/renderer_host/popup_window_mac.h
new file mode 100644
index 00000000000..424e75fa241
--- /dev/null
+++ b/chromium/content/browser/renderer_host/popup_window_mac.h
@@ -0,0 +1,41 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_BROWSER_RENDERER_HOST_POPUP_WINDOW_MAC_H_
+#define CONTENT_BROWSER_RENDERER_HOST_POPUP_WINDOW_MAC_H_
+
+#import "base/mac/scoped_nsobject.h"
+#include "base/macros.h"
+#include "third_party/blink/public/web/web_popup_type.h"
+#include "ui/gfx/geometry/rect.h"
+
+@class NSWindow;
+@class RenderWidgetHostViewCocoa;
+
+namespace content {
+
+// Helper class for RHWVMacs that are initialized using InitAsPopup. Note that
+// this refers to UI that creates its own NSWindow, and does not refer to JS
+// initiated popups. This can be tesed using <input type="datetime-local">.
+class PopupWindowMac {
+ public:
+ PopupWindowMac(const gfx::Rect& content_rect,
+ blink::WebPopupType popup_type,
+ RenderWidgetHostViewCocoa* cocoa_view);
+ ~PopupWindowMac();
+
+ NSWindow* window() { return popup_window_.get(); }
+
+ private:
+ base::scoped_nsobject<NSWindow> popup_window_;
+
+ // Weak.
+ RenderWidgetHostViewCocoa* cocoa_view_ = nil;
+
+ DISALLOW_COPY_AND_ASSIGN(PopupWindowMac);
+};
+
+} // namespace content
+
+#endif // CONTENT_BROWSER_RENDERER_HOST_POPUP_WINDOW_MAC_H_
diff --git a/chromium/content/browser/renderer_host/popup_window_mac.mm b/chromium/content/browser/renderer_host/popup_window_mac.mm
new file mode 100644
index 00000000000..c77d21aeecd
--- /dev/null
+++ b/chromium/content/browser/renderer_host/popup_window_mac.mm
@@ -0,0 +1,120 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#import "content/browser/renderer_host/popup_window_mac.h"
+
+#import "content/browser/renderer_host/render_widget_host_view_cocoa.h"
+#include "ui/gfx/mac/coordinate_conversion.h"
+
+@interface RenderWidgetPopupWindow : NSWindow {
+ // The event tap that allows monitoring of all events, to properly close with
+ // a click outside the bounds of the window.
+ id clickEventTap_;
+}
+@end
+
+@implementation RenderWidgetPopupWindow
+
+- (id)initWithContentRect:(NSRect)contentRect
+ styleMask:(NSUInteger)windowStyle
+ backing:(NSBackingStoreType)bufferingType
+ defer:(BOOL)deferCreation {
+ if (self = [super initWithContentRect:contentRect
+ styleMask:windowStyle
+ backing:bufferingType
+ defer:deferCreation]) {
+ [self setBackgroundColor:[NSColor clearColor]];
+ [self startObservingClicks];
+ }
+ return self;
+}
+
+- (void)close {
+ [self stopObservingClicks];
+ [super close];
+}
+
+// Gets called when the menubar is clicked.
+// Needed because the local event monitor doesn't see the click on the menubar.
+- (void)beganTracking:(NSNotification*)notification {
+ [self close];
+}
+
+// Install the callback.
+- (void)startObservingClicks {
+ clickEventTap_ = [NSEvent
+ addLocalMonitorForEventsMatchingMask:NSAnyEventMask
+ handler:^NSEvent*(NSEvent* event) {
+ if ([event window] == self)
+ return event;
+ NSEventType eventType = [event type];
+ if (eventType == NSLeftMouseDown ||
+ eventType == NSRightMouseDown)
+ [self close];
+ return event;
+ }];
+
+ NSNotificationCenter* notificationCenter =
+ [NSNotificationCenter defaultCenter];
+ [notificationCenter addObserver:self
+ selector:@selector(beganTracking:)
+ name:NSMenuDidBeginTrackingNotification
+ object:[NSApp mainMenu]];
+}
+
+// Remove the callback.
+- (void)stopObservingClicks {
+ if (!clickEventTap_)
+ return;
+
+ [NSEvent removeMonitor:clickEventTap_];
+ clickEventTap_ = nil;
+
+ NSNotificationCenter* notificationCenter =
+ [NSNotificationCenter defaultCenter];
+ [notificationCenter removeObserver:self
+ name:NSMenuDidBeginTrackingNotification
+ object:[NSApp mainMenu]];
+}
+
+@end
+
+namespace content {
+
+PopupWindowMac::PopupWindowMac(const gfx::Rect& content_rect,
+ blink::WebPopupType popup_type,
+ RenderWidgetHostViewCocoa* cocoa_view)
+ : cocoa_view_(cocoa_view) {
+ bool activatable = popup_type == blink::kWebPopupTypeNone;
+ [cocoa_view_ setCloseOnDeactivate:YES];
+ [cocoa_view_ setCanBeKeyView:activatable ? YES : NO];
+
+ popup_window_.reset([[RenderWidgetPopupWindow alloc]
+ initWithContentRect:gfx::ScreenRectToNSRect(content_rect)
+ styleMask:NSBorderlessWindowMask
+ backing:NSBackingStoreBuffered
+ defer:NO]);
+ [popup_window_ setLevel:NSPopUpMenuWindowLevel];
+ [popup_window_ setReleasedWhenClosed:NO];
+ [popup_window_ makeKeyAndOrderFront:nil];
+ [[popup_window_ contentView] addSubview:cocoa_view_];
+ [cocoa_view_ setFrame:[[popup_window_ contentView] bounds]];
+ [cocoa_view_ setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
+ [[NSNotificationCenter defaultCenter]
+ addObserver:cocoa_view_
+ selector:@selector(popupWindowWillClose:)
+ name:NSWindowWillCloseNotification
+ object:popup_window_];
+}
+
+PopupWindowMac::~PopupWindowMac() {
+ [[NSNotificationCenter defaultCenter]
+ removeObserver:cocoa_view_
+ name:NSWindowWillCloseNotification
+ object:popup_window_];
+ [popup_window_ close];
+ popup_window_.autorelease();
+}
+
+} // namespace content
diff --git a/chromium/content/browser/renderer_host/render_frame_metadata_provider_impl.cc b/chromium/content/browser/renderer_host/render_frame_metadata_provider_impl.cc
index ca87101b26c..d16a615e8ef 100644
--- a/chromium/content/browser/renderer_host/render_frame_metadata_provider_impl.cc
+++ b/chromium/content/browser/renderer_host/render_frame_metadata_provider_impl.cc
@@ -4,16 +4,16 @@
#include "content/browser/renderer_host/render_frame_metadata_provider_impl.h"
+#include "base/bind.h"
+#include "content/browser/renderer_host/frame_token_message_queue.h"
+
namespace content {
RenderFrameMetadataProviderImpl::RenderFrameMetadataProviderImpl(
- mojom::RenderFrameMetadataObserverClientRequest client_request,
- mojom::RenderFrameMetadataObserverPtr observer)
- : render_frame_metadata_observer_client_binding_(this),
- render_frame_metadata_observer_ptr_(std::move(observer)) {
- render_frame_metadata_observer_client_binding_.Bind(
- std::move(client_request));
-}
+ FrameTokenMessageQueue* frame_token_message_queue)
+ : frame_token_message_queue_(frame_token_message_queue),
+ render_frame_metadata_observer_client_binding_(this),
+ weak_factory_(this) {}
RenderFrameMetadataProviderImpl::~RenderFrameMetadataProviderImpl() = default;
@@ -25,8 +25,18 @@ void RenderFrameMetadataProviderImpl::RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
+void RenderFrameMetadataProviderImpl::Bind(
+ mojom::RenderFrameMetadataObserverClientRequest client_request,
+ mojom::RenderFrameMetadataObserverPtr observer) {
+ render_frame_metadata_observer_ptr_ = std::move(observer);
+ render_frame_metadata_observer_client_binding_.Close();
+ render_frame_metadata_observer_client_binding_.Bind(
+ std::move(client_request));
+}
+
void RenderFrameMetadataProviderImpl::ReportAllFrameSubmissionsForTesting(
bool enabled) {
+ DCHECK(render_frame_metadata_observer_ptr_);
render_frame_metadata_observer_ptr_->ReportAllFrameSubmissionsForTesting(
enabled);
}
@@ -36,16 +46,42 @@ RenderFrameMetadataProviderImpl::LastRenderFrameMetadata() const {
return last_render_frame_metadata_;
}
-void RenderFrameMetadataProviderImpl::OnRenderFrameMetadataChanged(
- const cc::RenderFrameMetadata& metadata) {
- last_render_frame_metadata_ = metadata;
+void RenderFrameMetadataProviderImpl::OnFrameTokenRenderFrameMetadataChanged(
+ cc::RenderFrameMetadata metadata) {
+ last_render_frame_metadata_ = std::move(metadata);
for (Observer& observer : observers_)
observer.OnRenderFrameMetadataChanged();
}
-void RenderFrameMetadataProviderImpl::OnFrameSubmissionForTesting() {
+void RenderFrameMetadataProviderImpl::OnFrameTokenFrameSubmissionForTesting() {
for (Observer& observer : observers_)
observer.OnRenderFrameSubmission();
}
+void RenderFrameMetadataProviderImpl::SetLastRenderFrameMetadataForTest(
+ cc::RenderFrameMetadata metadata) {
+ last_render_frame_metadata_ = metadata;
+}
+
+void RenderFrameMetadataProviderImpl::OnRenderFrameMetadataChanged(
+ uint32_t frame_token,
+ const cc::RenderFrameMetadata& metadata) {
+ // Both RenderFrameMetadataProviderImpl and FrameTokenMessageQueue are owned
+ // by the same RenderWidgetHostImpl. During shutdown the queue is cleared
+ // without running the callbacks.
+ frame_token_message_queue_->EnqueueOrRunFrameTokenCallback(
+ frame_token,
+ base::BindOnce(&RenderFrameMetadataProviderImpl::
+ OnFrameTokenRenderFrameMetadataChanged,
+ weak_factory_.GetWeakPtr(), std::move(metadata)));
+}
+
+void RenderFrameMetadataProviderImpl::OnFrameSubmissionForTesting(
+ uint32_t frame_token) {
+ frame_token_message_queue_->EnqueueOrRunFrameTokenCallback(
+ frame_token, base::BindOnce(&RenderFrameMetadataProviderImpl::
+ OnFrameTokenFrameSubmissionForTesting,
+ weak_factory_.GetWeakPtr()));
+}
+
} // namespace content
diff --git a/chromium/content/browser/renderer_host/render_frame_metadata_provider_impl.h b/chromium/content/browser/renderer_host/render_frame_metadata_provider_impl.h
index df57442bc41..48ab561549b 100644
--- a/chromium/content/browser/renderer_host/render_frame_metadata_provider_impl.h
+++ b/chromium/content/browser/renderer_host/render_frame_metadata_provider_impl.h
@@ -6,12 +6,14 @@
#define CONTENT_BROWSER_RENDERER_HOST_RENDER_FRAME_METADATA_PROVIDER_IMPL_H_
#include "base/macros.h"
+#include "base/memory/weak_ptr.h"
#include "base/observer_list.h"
#include "content/common/render_frame_metadata.mojom.h"
#include "content/public/browser/render_frame_metadata_provider.h"
#include "mojo/public/cpp/bindings/binding.h"
namespace content {
+class FrameTokenMessageQueue;
// Observes RenderFrameMetadata associated with the submission of a frame for a
// given RenderWidgetHost. The renderer will notify this when sumitting a
@@ -21,18 +23,20 @@ namespace content {
// notified of all frame submissions.
//
// All RenderFrameMetadataProvider::Observer will be notified.
-class RenderFrameMetadataProviderImpl
+class CONTENT_EXPORT RenderFrameMetadataProviderImpl
: public RenderFrameMetadataProvider,
public mojom::RenderFrameMetadataObserverClient {
public:
- RenderFrameMetadataProviderImpl(
- mojom::RenderFrameMetadataObserverClientRequest client_request,
- mojom::RenderFrameMetadataObserverPtr observer);
+ explicit RenderFrameMetadataProviderImpl(
+ FrameTokenMessageQueue* frame_token_message_queue);
~RenderFrameMetadataProviderImpl() override;
void AddObserver(Observer* observer) override;
void RemoveObserver(Observer* observer) override;
+ void Bind(mojom::RenderFrameMetadataObserverClientRequest client_request,
+ mojom::RenderFrameMetadataObserverPtr observer);
+
// Notifies the renderer to begin sending a notification on all frame
// submissions.
void ReportAllFrameSubmissionsForTesting(bool enabled) override;
@@ -40,19 +44,38 @@ class RenderFrameMetadataProviderImpl
const cc::RenderFrameMetadata& LastRenderFrameMetadata() const override;
private:
+ friend class FakeRenderWidgetHostViewAura;
+
+ // Paired with the mojom::RenderFrameMetadataObserverClient overrides, these
+ // methods are enqueued in |frame_token_message_queue_|. They are invoked when
+ // the browser process receives their associated frame tokens. These then
+ // notify any |observers_|.
+ void OnFrameTokenRenderFrameMetadataChanged(cc::RenderFrameMetadata metadata);
+ void OnFrameTokenFrameSubmissionForTesting();
+
+ // Set |last_render_frame_metadata_| to the given |metadata| for testing
+ // purpose.
+ void SetLastRenderFrameMetadataForTest(cc::RenderFrameMetadata metadata);
+
// mojom::RenderFrameMetadataObserverClient:
void OnRenderFrameMetadataChanged(
+ uint32_t frame_token,
const cc::RenderFrameMetadata& metadata) override;
- void OnFrameSubmissionForTesting() override;
+ void OnFrameSubmissionForTesting(uint32_t frame_token) override;
base::ObserverList<Observer> observers_;
cc::RenderFrameMetadata last_render_frame_metadata_;
+ // Not owned.
+ FrameTokenMessageQueue* const frame_token_message_queue_;
+
mojo::Binding<mojom::RenderFrameMetadataObserverClient>
render_frame_metadata_observer_client_binding_;
mojom::RenderFrameMetadataObserverPtr render_frame_metadata_observer_ptr_;
+ base::WeakPtrFactory<RenderFrameMetadataProviderImpl> weak_factory_;
+
DISALLOW_COPY_AND_ASSIGN(RenderFrameMetadataProviderImpl);
};
diff --git a/chromium/content/browser/renderer_host/render_message_filter.cc b/chromium/content/browser/renderer_host/render_message_filter.cc
index 5ef86142da3..c12556a65ba 100644
--- a/chromium/content/browser/renderer_host/render_message_filter.cc
+++ b/chromium/content/browser/renderer_host/render_message_filter.cc
@@ -46,13 +46,12 @@
#include "content/common/view_messages.h"
#include "content/public/browser/browser_child_process_host.h"
#include "content/public/browser/browser_context.h"
-#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/resource_context.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/context_menu_params.h"
#include "content/public/common/url_constants.h"
-#include "gpu/ipc/client/gpu_memory_buffer_impl.h"
+#include "gpu/ipc/common/gpu_memory_buffer_impl.h"
#include "ipc/ipc_channel_handle.h"
#include "ipc/ipc_platform_file.h"
#include "media/base/media_log_event.h"
@@ -75,7 +74,6 @@
#endif
#if defined(OS_MACOSX)
-#include "content/common/mac/font_loader.h"
#include "ui/accelerated_widget_mac/window_resize_helper_mac.h"
#endif
#if defined(OS_LINUX)
@@ -196,17 +194,6 @@ void RenderMessageFilter::CreateFullscreenWidget(
std::move(callback).Run(route_id);
}
-void RenderMessageFilter::LoadFont(const base::string16& font_name,
- float font_point_size,
- LoadFontCallback callback) {
-#if defined(OS_MACOSX)
- FontLoader::LoadFont(font_name, font_point_size, std::move(callback));
-#else
- // TODO(https://crbug.com/676224): remove this reporting.
- mojo::ReportBadMessage("LoadFont is OS_MACOSX only.");
-#endif // defined(OS_MACOSX)
-}
-
#if defined(OS_LINUX)
void RenderMessageFilter::SetThreadPriorityOnFileThread(
base::PlatformThreadId ns_tid,
@@ -228,9 +215,9 @@ void RenderMessageFilter::SetThreadPriorityOnFileThread(
}
#endif
+#if defined(OS_LINUX)
void RenderMessageFilter::SetThreadPriority(int32_t ns_tid,
base::ThreadPriority priority) {
-#if defined(OS_LINUX)
constexpr base::TaskTraits kTraits = {
base::MayBlock(), base::TaskPriority::USER_BLOCKING,
base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN};
@@ -238,10 +225,8 @@ void RenderMessageFilter::SetThreadPriority(int32_t ns_tid,
FROM_HERE, kTraits,
base::BindOnce(&RenderMessageFilter::SetThreadPriorityOnFileThread, this,
static_cast<base::PlatformThreadId>(ns_tid), priority));
-#else
- mojo::ReportBadMessage("SetThreadPriority is only supported on OS_LINUX");
-#endif
}
+#endif
void RenderMessageFilter::DidGenerateCacheableMetadata(
const GURL& url,
diff --git a/chromium/content/browser/renderer_host/render_message_filter.h b/chromium/content/browser/renderer_host/render_message_filter.h
index 0a42a5e14b6..d6dad3d8e72 100644
--- a/chromium/content/browser/renderer_host/render_message_filter.h
+++ b/chromium/content/browser/renderer_host/render_message_filter.h
@@ -23,10 +23,11 @@
#include "content/common/render_message_filter.mojom.h"
#include "content/public/browser/browser_associated_interface.h"
#include "content/public/browser/browser_message_filter.h"
+#include "content/public/browser/browser_thread.h"
#include "gpu/config/gpu_info.h"
#include "ipc/message_filter.h"
-#include "third_party/WebKit/public/platform/modules/cache_storage/cache_storage.mojom.h"
-#include "third_party/WebKit/public/web/WebPopupType.h"
+#include "third_party/blink/public/platform/modules/cache_storage/cache_storage.mojom.h"
+#include "third_party/blink/public/web/web_popup_type.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/gpu_memory_buffer.h"
#include "ui/gfx/native_widget_types.h"
@@ -113,12 +114,10 @@ class CONTENT_EXPORT RenderMessageFilter
const url::Origin& cache_storage_origin,
const std::string& cache_storage_cache_name) override;
void HasGpuProcess(HasGpuProcessCallback callback) override;
+#if defined(OS_LINUX)
void SetThreadPriority(int32_t ns_tid,
base::ThreadPriority priority) override;
- // Messages for OOP font loading. Only used for MACOSX.
- void LoadFont(const base::string16& font_to_load,
- float font_point_size,
- LoadFontCallback callback) override;
+#endif
void OnResolveProxy(const GURL& url, IPC::Message* reply_msg);
diff --git a/chromium/content/browser/renderer_host/render_process_host_browsertest.cc b/chromium/content/browser/renderer_host/render_process_host_browsertest.cc
index 19531ae570c..820687c3cb7 100644
--- a/chromium/content/browser/renderer_host/render_process_host_browsertest.cc
+++ b/chromium/content/browser/renderer_host/render_process_host_browsertest.cc
@@ -11,6 +11,8 @@
#include "build/build_config.h"
#include "content/browser/frame_host/render_frame_host_impl.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
+#include "content/public/browser/browser_thread.h"
+#include "content/public/browser/child_process_launcher_utils.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_process_host_observer.h"
@@ -31,7 +33,7 @@
#include "media/base/bind_to_current_loop.h"
#include "media/base/media_switches.h"
#include "media/base/test_data_util.h"
-#include "media/mojo/features.h"
+#include "media/mojo/buildflags.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"
@@ -43,17 +45,6 @@
namespace content {
namespace {
-int RenderProcessHostCount() {
- RenderProcessHost::iterator hosts = RenderProcessHost::AllHostsIterator();
- int count = 0;
- while (!hosts.IsAtEnd()) {
- if (hosts.GetCurrentValue()->HasConnection())
- count++;
- hosts.Advance();
- }
- return count;
-}
-
std::unique_ptr<net::test_server::HttpResponse> HandleBeacon(
const net::test_server::HttpRequest& request) {
if (request.relative_url != "/beacon")
@@ -77,10 +68,6 @@ class RenderProcessHostTest : public ContentBrowserTest,
command_line->AppendSwitchASCII(
switches::kAutoplayPolicy,
switches::autoplay::kNoUserGestureRequiredPolicy);
- // These flags are necessary to emulate camera input for getUserMedia()
- // tests.
- command_line->AppendSwitch(switches::kUseFakeDeviceForMediaStream);
- command_line->AppendSwitch(switches::kUseFakeUIForMediaStream);
}
protected:
@@ -127,6 +114,8 @@ class SpareRendererContentBrowserClient : public TestContentBrowserClient {
// suitable host, but otherwise tries to reuse processes.
class NonSpareRendererContentBrowserClient : public TestContentBrowserClient {
public:
+ NonSpareRendererContentBrowserClient() = default;
+
bool IsSuitableHost(RenderProcessHost* process_host,
const GURL& site_url) override {
return RenderProcessHostImpl::GetSpareRenderProcessHostForTesting() !=
@@ -137,24 +126,14 @@ class NonSpareRendererContentBrowserClient : public TestContentBrowserClient {
const GURL& url) override {
return true;
}
-};
-class RenderProcessHostWithKeepAliveOptionEnabledTest
- : public RenderProcessHostTest {
- public:
- void SetUp() override {
- feature_list_.InitAndEnableFeature(
- features::kKeepAliveRendererForKeepaliveRequests);
- RenderProcessHostTest::SetUp();
- }
-
- void SetUpCommandLine(base::CommandLine* command_line) override {
- command_line->AppendSwitch(
- switches::kEnableExperimentalWebPlatformFeatures);
+ bool ShouldUseSpareRenderProcessHost(BrowserContext* browser_context,
+ const GURL& site_url) override {
+ return false;
}
private:
- base::test::ScopedFeatureList feature_list_;
+ DISALLOW_COPY_AND_ASSIGN(NonSpareRendererContentBrowserClient);
};
// Sometimes the renderer process's ShutdownRequest (corresponding to the
@@ -203,7 +182,7 @@ IN_PROC_BROWSER_TEST_F(RenderProcessHostTest,
// Make it believe it's a guest.
reinterpret_cast<RenderProcessHostImpl*>(rph)->
set_is_for_guests_only_for_testing(true);
- EXPECT_EQ(1, RenderProcessHostCount());
+ EXPECT_EQ(1, RenderProcessHost::GetCurrentRenderProcessCountForTesting());
// Navigate to a different page.
GURL::Replacements replace_host;
@@ -213,7 +192,7 @@ IN_PROC_BROWSER_TEST_F(RenderProcessHostTest,
NavigateToURL(CreateBrowser(), another_url);
// Expect that we got another process (the guest renderer was not reused).
- EXPECT_EQ(2, RenderProcessHostCount());
+ EXPECT_EQ(2, RenderProcessHost::GetCurrentRenderProcessCountForTesting());
}
IN_PROC_BROWSER_TEST_F(RenderProcessHostTest, SpareRenderProcessHostTaken) {
@@ -232,9 +211,18 @@ IN_PROC_BROWSER_TEST_F(RenderProcessHostTest, SpareRenderProcessHostTaken) {
EXPECT_EQ(spare_renderer,
window->web_contents()->GetMainFrame()->GetProcess());
- // The spare render process host should no longer be available.
- EXPECT_EQ(nullptr,
+ // The old spare render process host should no longer be available.
+ EXPECT_NE(spare_renderer,
RenderProcessHostImpl::GetSpareRenderProcessHostForTesting());
+
+ // Check if a fresh spare is available (depending on the operating mode).
+ if (RenderProcessHostImpl::IsSpareProcessKeptAtAllTimes()) {
+ EXPECT_NE(nullptr,
+ RenderProcessHostImpl::GetSpareRenderProcessHostForTesting());
+ } else {
+ EXPECT_EQ(nullptr,
+ RenderProcessHostImpl::GetSpareRenderProcessHostForTesting());
+ }
}
IN_PROC_BROWSER_TEST_F(RenderProcessHostTest, SpareRenderProcessHostNotTaken) {
@@ -252,11 +240,16 @@ IN_PROC_BROWSER_TEST_F(RenderProcessHostTest, SpareRenderProcessHostNotTaken) {
EXPECT_NE(spare_renderer,
window->web_contents()->GetMainFrame()->GetProcess());
- // The spare RenderProcessHost should have been cleaned up. Note this
- // behavior is identical to what would have happened if the RenderProcessHost
- // were taken.
- EXPECT_EQ(nullptr,
- RenderProcessHostImpl::GetSpareRenderProcessHostForTesting());
+ // Check if a fresh spare is available (depending on the operating mode).
+ // Note this behavior is identical to what would have happened if the
+ // RenderProcessHost were taken.
+ if (RenderProcessHostImpl::IsSpareProcessKeptAtAllTimes()) {
+ EXPECT_NE(nullptr,
+ RenderProcessHostImpl::GetSpareRenderProcessHostForTesting());
+ } else {
+ EXPECT_EQ(nullptr,
+ RenderProcessHostImpl::GetSpareRenderProcessHostForTesting());
+ }
}
IN_PROC_BROWSER_TEST_F(RenderProcessHostTest, SpareRenderProcessHostKilled) {
@@ -315,8 +308,10 @@ IN_PROC_BROWSER_TEST_F(RenderProcessHostTest,
GURL test_url = embedded_test_server()->GetURL("/simple_page.html");
Shell* new_window = CreateBrowser();
NavigateToURL(new_window, test_url);
- // The spare RPH should have been dropped during CreateBrowser() and given to
- // the new window.
+ // Outside of RenderProcessHostImpl::IsSpareProcessKeptAtAllTimes mode, the
+ // spare RPH should have been dropped during CreateBrowser() and given to the
+ // new window. OTOH, even in the IsSpareProcessKeptAtAllTimes mode, the spare
+ // shouldn't be created because of the low process limit.
EXPECT_EQ(nullptr,
RenderProcessHostImpl::GetSpareRenderProcessHostForTesting());
EXPECT_EQ(spare_renderer,
@@ -341,23 +336,27 @@ IN_PROC_BROWSER_TEST_F(RenderProcessHostTest, SpareRendererOnProcessReuse) {
RenderProcessHostImpl::GetSpareRenderProcessHostForTesting();
EXPECT_NE(nullptr, spare_renderer);
- // This should resuse the existing process and cause the spare renderer to be
- // dropped.
+ // This should reuse the existing process.
Shell* new_browser = CreateBrowser();
EXPECT_EQ(shell()->web_contents()->GetMainFrame()->GetProcess(),
new_browser->web_contents()->GetMainFrame()->GetProcess());
EXPECT_NE(spare_renderer,
new_browser->web_contents()->GetMainFrame()->GetProcess());
- EXPECT_EQ(nullptr,
- RenderProcessHostImpl::GetSpareRenderProcessHostForTesting());
+ if (RenderProcessHostImpl::IsSpareProcessKeptAtAllTimes()) {
+ EXPECT_NE(nullptr,
+ RenderProcessHostImpl::GetSpareRenderProcessHostForTesting());
+ } else {
+ EXPECT_EQ(nullptr,
+ RenderProcessHostImpl::GetSpareRenderProcessHostForTesting());
+ }
// The launcher thread reads state from browser_client, need to wait for it to
// be done before resetting the browser client. crbug.com/742533.
base::WaitableEvent launcher_thread_done(
base::WaitableEvent::ResetPolicy::MANUAL,
base::WaitableEvent::InitialState::NOT_SIGNALED);
- BrowserThread::PostTask(
- BrowserThread::PROCESS_LAUNCHER, FROM_HERE,
+ GetProcessLauncherTaskRunner()->PostTask(
+ FROM_HERE,
base::BindOnce([](base::WaitableEvent* done) { done->Signal(); },
base::Unretained(&launcher_thread_done)));
ASSERT_TRUE(launcher_thread_done.TimedWait(TestTimeouts::action_timeout()));
@@ -365,6 +364,230 @@ IN_PROC_BROWSER_TEST_F(RenderProcessHostTest, SpareRendererOnProcessReuse) {
SetBrowserClientForTesting(old_client);
}
+// Verifies that the spare renderer maintained by SpareRenderProcessHostManager
+// is correctly destroyed during browser shutdown. This test is an analogue
+// to the //chrome-layer FastShutdown.SpareRenderProcessHost test.
+IN_PROC_BROWSER_TEST_F(RenderProcessHostTest,
+ SpareRenderProcessHostDuringShutdown) {
+ content::RenderProcessHost::WarmupSpareRenderProcessHost(
+ shell()->web_contents()->GetBrowserContext());
+
+ // The verification is that there are no DCHECKs anywhere during test tear
+ // down.
+}
+
+// Verifies that the spare renderer maintained by SpareRenderProcessHostManager
+// is correctly destroyed when closing the last content shell.
+IN_PROC_BROWSER_TEST_F(RenderProcessHostTest, SpareRendererDuringClosing) {
+ content::RenderProcessHost::WarmupSpareRenderProcessHost(
+ shell()->web_contents()->GetBrowserContext());
+ shell()->web_contents()->Close();
+
+ // The verification is that there are no DCHECKs or UaF anywhere during test
+ // tear down.
+}
+
+// Class that simulates the fact that some //content embedders (e.g. by
+// overriding ChromeContentBrowserClient::GetStoragePartitionConfigForSite) can
+// cause BrowserContext::GetDefaultStoragePartition(browser_context) to differ
+// from BrowserContext::GetStoragePartition(browser_context, site_instance) even
+// if |site_instance| is not for guests.
+class CustomStoragePartitionForSomeSites : public TestContentBrowserClient {
+ public:
+ explicit CustomStoragePartitionForSomeSites(const GURL& site_to_isolate)
+ : site_to_isolate_(site_to_isolate) {}
+
+ void GetStoragePartitionConfigForSite(BrowserContext* browser_context,
+ const GURL& site,
+ bool can_be_default,
+ std::string* partition_domain,
+ std::string* partition_name,
+ bool* in_memory) override {
+ // Default to the browser-wide storage partition and override based on
+ // |site| below.
+ partition_domain->clear();
+ partition_name->clear();
+ *in_memory = false;
+
+ // Override for |site_to_isolate_|.
+ if (site == site_to_isolate_) {
+ *partition_domain = "blah_isolated_storage";
+ *partition_name = "blah_isolated_storage";
+ *in_memory = false;
+ }
+ }
+
+ std::string GetStoragePartitionIdForSite(BrowserContext* browser_context,
+ const GURL& site) override {
+ if (site == site_to_isolate_)
+ return "custom";
+ return "";
+ }
+
+ bool IsValidStoragePartitionId(BrowserContext* browser_context,
+ const std::string& partition_id) override {
+ return partition_id == "" || partition_id == "custom";
+ }
+
+ private:
+ GURL site_to_isolate_;
+
+ DISALLOW_COPY_AND_ASSIGN(CustomStoragePartitionForSomeSites);
+};
+
+// This test verifies that SpareRenderProcessHostManager correctly accounts
+// for StoragePartition differences when handing out the spare process.
+IN_PROC_BROWSER_TEST_F(RenderProcessHostTest,
+ SpareProcessVsCustomStoragePartition) {
+ ASSERT_TRUE(embedded_test_server()->Start());
+
+ // Provide custom storage partition for test sites.
+ GURL test_url = embedded_test_server()->GetURL("/simple_page.html");
+ BrowserContext* browser_context =
+ ShellContentBrowserClient::Get()->browser_context();
+ GURL test_site = SiteInstance::GetSiteForURL(browser_context, test_url);
+ CustomStoragePartitionForSomeSites modified_client(test_site);
+ ContentBrowserClient* old_client =
+ SetBrowserClientForTesting(&modified_client);
+ StoragePartition* default_storage =
+ BrowserContext::GetDefaultStoragePartition(browser_context);
+ StoragePartition* custom_storage =
+ BrowserContext::GetStoragePartitionForSite(browser_context, test_site);
+ EXPECT_NE(default_storage, custom_storage);
+
+ // Open a test window - it should be associated with the default storage
+ // partition.
+ Shell* window = CreateBrowser();
+ RenderProcessHost* old_process =
+ window->web_contents()->GetMainFrame()->GetProcess();
+ EXPECT_EQ(default_storage, old_process->GetStoragePartition());
+
+ // Warm up the spare process - it should be associated with the default
+ // storage partition.
+ RenderProcessHost::WarmupSpareRenderProcessHost(browser_context);
+ RenderProcessHost* spare_renderer =
+ RenderProcessHostImpl::GetSpareRenderProcessHostForTesting();
+ ASSERT_TRUE(spare_renderer);
+ EXPECT_EQ(default_storage, spare_renderer->GetStoragePartition());
+
+ // Navigate to a URL that requires a custom storage partition.
+ EXPECT_TRUE(NavigateToURL(window, test_url));
+ RenderProcessHost* new_process =
+ window->web_contents()->GetMainFrame()->GetProcess();
+ // Requirement to use a custom storage partition should force a process swap.
+ EXPECT_NE(new_process, old_process);
+ // The new process should be associated with the custom storage partition.
+ EXPECT_EQ(custom_storage, new_process->GetStoragePartition());
+ // And consequently, the spare shouldn't have been used.
+ EXPECT_NE(spare_renderer, new_process);
+
+ // Restore the original ContentBrowserClient.
+ SetBrowserClientForTesting(old_client);
+}
+
+class RenderProcessHostObserverCounter : public RenderProcessHostObserver {
+ public:
+ explicit RenderProcessHostObserverCounter(RenderProcessHost* host) {
+ host->AddObserver(this);
+ observing_ = true;
+ observed_host_ = host;
+ }
+
+ ~RenderProcessHostObserverCounter() override {
+ if (observing_)
+ observed_host_->RemoveObserver(this);
+ }
+
+ void RenderProcessExited(RenderProcessHost* host,
+ base::TerminationStatus status,
+ int exit_code) override {
+ DCHECK(observing_);
+ DCHECK_EQ(host, observed_host_);
+ exited_count_++;
+ }
+
+ void RenderProcessHostDestroyed(RenderProcessHost* host) override {
+ DCHECK(observing_);
+ DCHECK_EQ(host, observed_host_);
+ destroyed_count_++;
+
+ host->RemoveObserver(this);
+ observing_ = false;
+ observed_host_ = nullptr;
+ }
+
+ int exited_count() const { return exited_count_; }
+ int destroyed_count() const { return destroyed_count_; }
+
+ private:
+ int exited_count_ = 0;
+ int destroyed_count_ = 0;
+ bool observing_ = false;
+ RenderProcessHost* observed_host_ = nullptr;
+
+ DISALLOW_COPY_AND_ASSIGN(RenderProcessHostObserverCounter);
+};
+
+// Check that the spare renderer is properly destroyed via
+// DisableKeepAliveRefCount.
+IN_PROC_BROWSER_TEST_F(RenderProcessHostTest, SpareVsDisableKeepAliveRefCount) {
+ RenderProcessHost::WarmupSpareRenderProcessHost(
+ ShellContentBrowserClient::Get()->browser_context());
+ base::RunLoop().RunUntilIdle();
+
+ RenderProcessHost* spare_renderer =
+ RenderProcessHostImpl::GetSpareRenderProcessHostForTesting();
+ RenderProcessHostObserverCounter counter(spare_renderer);
+
+ RenderProcessHostWatcher process_watcher(
+ spare_renderer, RenderProcessHostWatcher::WATCH_FOR_HOST_DESTRUCTION);
+
+ spare_renderer->DisableKeepAliveRefCount();
+
+ process_watcher.Wait();
+ EXPECT_TRUE(process_watcher.did_exit_normally());
+
+ // An important part of test verification is that UaF doesn't happen in the
+ // next revolution of the message pump - without extra care in the
+ // SpareRenderProcessHostManager RenderProcessHost::Cleanup could be called
+ // twice leading to a crash caused by double-free flavour of UaF in
+ // base::DeleteHelper<...>::DoDelete.
+ base::RunLoop().RunUntilIdle();
+
+ DCHECK_EQ(1, counter.exited_count());
+ DCHECK_EQ(1, counter.destroyed_count());
+}
+
+// Check that the spare renderer is properly destroyed via
+// DisableKeepAliveRefCount.
+IN_PROC_BROWSER_TEST_F(RenderProcessHostTest, SpareVsFastShutdown) {
+ RenderProcessHost::WarmupSpareRenderProcessHost(
+ ShellContentBrowserClient::Get()->browser_context());
+ base::RunLoop().RunUntilIdle();
+
+ RenderProcessHost* spare_renderer =
+ RenderProcessHostImpl::GetSpareRenderProcessHostForTesting();
+ RenderProcessHostObserverCounter counter(spare_renderer);
+
+ RenderProcessHostWatcher process_watcher(
+ spare_renderer, RenderProcessHostWatcher::WATCH_FOR_HOST_DESTRUCTION);
+
+ spare_renderer->FastShutdownIfPossible();
+
+ process_watcher.Wait();
+ EXPECT_FALSE(process_watcher.did_exit_normally());
+
+ // An important part of test verification is that UaF doesn't happen in the
+ // next revolution of the message pump - without extra care in the
+ // SpareRenderProcessHostManager RenderProcessHost::Cleanup could be called
+ // twice leading to a crash caused by double-free flavour of UaF in
+ // base::DeleteHelper<...>::DoDelete.
+ base::RunLoop().RunUntilIdle();
+
+ DCHECK_EQ(1, counter.exited_count());
+ DCHECK_EQ(1, counter.destroyed_count());
+}
+
class ShellCloser : public RenderProcessHostObserver {
public:
ShellCloser(Shell* shell, std::string* logging_string)
@@ -573,6 +796,25 @@ IN_PROC_BROWSER_TEST_F(RenderProcessHostTest, KillProcessZerosAudioStreams) {
rph->RemoveObserver(this);
}
+// Test class instance to run specific setup steps for capture streams.
+class CaptureStreamRenderProcessHostTest : public RenderProcessHostTest {
+ public:
+ void SetUp() override {
+ // Pixel output is needed when digging pixel values out of video tags for
+ // verification in VideoCaptureStream tests.
+ EnablePixelOutput();
+ RenderProcessHostTest::SetUp();
+ }
+
+ void SetUpCommandLine(base::CommandLine* command_line) override {
+ // These flags are necessary to emulate camera input for getUserMedia()
+ // tests.
+ command_line->AppendSwitch(switches::kUseFakeDeviceForMediaStream);
+ command_line->AppendSwitch(switches::kUseFakeUIForMediaStream);
+ RenderProcessHostTest::SetUpCommandLine(command_line);
+ }
+};
+
// These tests contain WebRTC calls and cannot be run when it isn't enabled.
#if !BUILDFLAG(ENABLE_WEBRTC)
#define GetUserMediaIncrementsVideoCaptureStreams \
@@ -588,7 +830,7 @@ IN_PROC_BROWSER_TEST_F(RenderProcessHostTest, KillProcessZerosAudioStreams) {
// Tests that video capture stream count increments when getUserMedia() is
// called.
-IN_PROC_BROWSER_TEST_F(RenderProcessHostTest,
+IN_PROC_BROWSER_TEST_F(CaptureStreamRenderProcessHostTest,
GetUserMediaIncrementsVideoCaptureStreams) {
ASSERT_TRUE(embedded_test_server()->Start());
NavigateToURL(shell(),
@@ -604,7 +846,8 @@ IN_PROC_BROWSER_TEST_F(RenderProcessHostTest,
// Tests that video capture stream count resets when getUserMedia() is called
// and stopped.
-IN_PROC_BROWSER_TEST_F(RenderProcessHostTest, StopResetsVideoCaptureStreams) {
+IN_PROC_BROWSER_TEST_F(CaptureStreamRenderProcessHostTest,
+ StopResetsVideoCaptureStreams) {
ASSERT_TRUE(embedded_test_server()->Start());
NavigateToURL(shell(),
embedded_test_server()->GetURL("/media/getusermedia.html"));
@@ -620,7 +863,7 @@ IN_PROC_BROWSER_TEST_F(RenderProcessHostTest, StopResetsVideoCaptureStreams) {
// Tests that video capture stream counts (used for process priority
// calculations) are properly set and cleared during media playback and renderer
// terminations.
-IN_PROC_BROWSER_TEST_F(RenderProcessHostTest,
+IN_PROC_BROWSER_TEST_F(CaptureStreamRenderProcessHostTest,
KillProcessZerosVideoCaptureStreams) {
ASSERT_TRUE(embedded_test_server()->Start());
NavigateToURL(shell(),
@@ -666,7 +909,7 @@ IN_PROC_BROWSER_TEST_F(RenderProcessHostTest,
// Tests that media stream count increments when getUserMedia() is
// called with audio only.
-IN_PROC_BROWSER_TEST_F(RenderProcessHostTest,
+IN_PROC_BROWSER_TEST_F(CaptureStreamRenderProcessHostTest,
GetUserMediaAudioOnlyIncrementsMediaStreams) {
ASSERT_TRUE(embedded_test_server()->Start());
NavigateToURL(shell(),
@@ -684,7 +927,7 @@ IN_PROC_BROWSER_TEST_F(RenderProcessHostTest,
// Tests that media stream counts (used for process priority
// calculations) are properly set and cleared during media playback and renderer
// terminations for audio only streams.
-IN_PROC_BROWSER_TEST_F(RenderProcessHostTest,
+IN_PROC_BROWSER_TEST_F(CaptureStreamRenderProcessHostTest,
KillProcessZerosAudioCaptureStreams) {
ASSERT_TRUE(embedded_test_server()->Start());
NavigateToURL(shell(),
@@ -729,8 +972,7 @@ IN_PROC_BROWSER_TEST_F(RenderProcessHostTest,
rph->RemoveObserver(this);
}
-IN_PROC_BROWSER_TEST_F(RenderProcessHostWithKeepAliveOptionEnabledTest,
- KeepAliveRendererProcess) {
+IN_PROC_BROWSER_TEST_F(RenderProcessHostTest, KeepAliveRendererProcess) {
embedded_test_server()->RegisterRequestHandler(
base::BindRepeating(HandleBeacon));
ASSERT_TRUE(embedded_test_server()->Start());
@@ -757,8 +999,7 @@ IN_PROC_BROWSER_TEST_F(RenderProcessHostWithKeepAliveOptionEnabledTest,
rph->RemoveObserver(this);
}
-IN_PROC_BROWSER_TEST_F(RenderProcessHostWithKeepAliveOptionEnabledTest,
- KeepAliveRendererProcess_Hung) {
+IN_PROC_BROWSER_TEST_F(RenderProcessHostTest, KeepAliveRendererProcess_Hung) {
embedded_test_server()->RegisterRequestHandler(
base::BindRepeating(HandleHungBeacon));
ASSERT_TRUE(embedded_test_server()->Start());
@@ -785,7 +1026,7 @@ IN_PROC_BROWSER_TEST_F(RenderProcessHostWithKeepAliveOptionEnabledTest,
rph->RemoveObserver(this);
}
-IN_PROC_BROWSER_TEST_F(RenderProcessHostWithKeepAliveOptionEnabledTest,
+IN_PROC_BROWSER_TEST_F(RenderProcessHostTest,
FetchKeepAliveRendererProcess_Hung) {
embedded_test_server()->RegisterRequestHandler(
base::BindRepeating(HandleHungBeacon));
@@ -814,5 +1055,14 @@ IN_PROC_BROWSER_TEST_F(RenderProcessHostWithKeepAliveOptionEnabledTest,
rph->RemoveObserver(this);
}
+// This test verifies that a fast shutdown is possible for a starting process.
+IN_PROC_BROWSER_TEST_F(RenderProcessHostTest, FastShutdownForStartingProcess) {
+ RenderProcessHost* process = RenderProcessHostImpl::CreateRenderProcessHost(
+ ShellContentBrowserClient::Get()->browser_context(), nullptr, nullptr,
+ false /* is_for_guests_only */);
+ process->Init();
+ EXPECT_TRUE(process->FastShutdownIfPossible());
+}
+
} // namespace
} // namespace content
diff --git a/chromium/content/browser/renderer_host/render_process_host_impl.cc b/chromium/content/browser/renderer_host/render_process_host_impl.cc
index 8c34d8e7af5..2a5c90e85c7 100644
--- a/chromium/content/browser/renderer_host/render_process_host_impl.cc
+++ b/chromium/content/browser/renderer_host/render_process_host_impl.cc
@@ -9,6 +9,7 @@
#include <algorithm>
#include <limits>
+#include <map>
#include <set>
#include <utility>
#include <vector>
@@ -54,6 +55,9 @@
#include "base/threading/thread_restrictions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
+#include "base/trace_event/memory_allocator_dump.h"
+#include "base/trace_event/memory_dump_manager.h"
+#include "base/trace_event/memory_dump_provider.h"
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
#include "cc/base/switches.h"
@@ -127,7 +131,6 @@
#include "content/browser/service_worker/service_worker_context_wrapper.h"
#include "content/browser/service_worker/service_worker_dispatcher_host.h"
#include "content/browser/site_instance_impl.h"
-#include "content/browser/site_isolation_policy.h"
#include "content/browser/speech/speech_recognition_dispatcher_host.h"
#include "content/browser/storage_partition_impl.h"
#include "content/browser/streams/stream_context.h"
@@ -138,13 +141,13 @@
#include "content/common/content_switches_internal.h"
#include "content/common/frame_messages.h"
#include "content/common/in_process_child_thread_params.h"
+#include "content/common/media/peer_connection_tracker_messages.h"
#include "content/common/navigation_subresource_loader_params.h"
#include "content/common/resource_messages.h"
#include "content/common/service_manager/child_connection.h"
#include "content/common/service_manager/service_manager_connection_impl.h"
#include "content/common/view_messages.h"
#include "content/public/browser/browser_context.h"
-#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_types.h"
@@ -153,6 +156,7 @@
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/render_widget_host_iterator.h"
#include "content/public/browser/resource_context.h"
+#include "content/public/browser/site_isolation_policy.h"
#include "content/public/common/bind_interface_helpers.h"
#include "content/public/common/child_process_host.h"
#include "content/public/common/connection_filter.h"
@@ -166,7 +170,7 @@
#include "content/public/common/sandboxed_process_launcher_delegate.h"
#include "content/public/common/service_names.mojom.h"
#include "content/public/common/url_constants.h"
-#include "content/public/common/zygote_features.h"
+#include "content/public/common/zygote_buildflags.h"
#include "device/gamepad/gamepad_haptics_manager.h"
#include "device/gamepad/gamepad_monitor.h"
#include "gpu/GLES2/gl2extchromium.h"
@@ -180,14 +184,14 @@
#include "ipc/ipc_logging.h"
#include "media/audio/audio_manager.h"
#include "media/base/media_switches.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "media/mojo/services/video_decode_perf_history.h"
#include "mojo/edk/embedder/embedder.h"
#include "mojo/public/cpp/bindings/associated_interface_ptr.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "mojo/public/cpp/system/platform_handle.h"
#include "net/url_request/url_request_context_getter.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#include "services/device/public/mojom/battery_monitor.mojom.h"
#include "services/device/public/mojom/constants.mojom.h"
#include "services/network/public/cpp/features.h"
@@ -203,8 +207,8 @@
#include "services/service_manager/runner/common/switches.h"
#include "services/service_manager/sandbox/switches.h"
#include "storage/browser/fileapi/sandbox_file_system_backend.h"
-#include "third_party/WebKit/public/common/page/launching_process_state.h"
-#include "third_party/WebKit/public/public_features.h"
+#include "third_party/blink/public/common/page/launching_process_state.h"
+#include "third_party/blink/public/public_buildflags.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/ui_base_features.h"
#include "ui/base/ui_base_switches.h"
@@ -276,6 +280,10 @@
#endif // BUILDFLAG(ENABLE_REPORTING)
namespace content {
+
+using CheckOriginLockResult =
+ ChildProcessSecurityPolicyImpl::CheckOriginLockResult;
+
namespace {
const RenderProcessHostFactory* g_render_process_host_factory_ = nullptr;
@@ -342,6 +350,57 @@ bool has_done_stun_trials = false;
#endif
+// Globally tracks all existing RenderProcessHostImpl instances.
+//
+// TODO(https://crbug.com/813045): Remove this.
+class RenderProcessMemoryDumpProvider
+ : public base::trace_event::MemoryDumpProvider {
+ public:
+ RenderProcessMemoryDumpProvider() {
+ base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
+ this, "RenderProcessHost", base::ThreadTaskRunnerHandle::Get());
+ }
+
+ ~RenderProcessMemoryDumpProvider() override {
+ base::trace_event::MemoryDumpManager::GetInstance()->UnregisterDumpProvider(
+ this);
+ }
+
+ void AddHost(RenderProcessHostImpl* host) {
+ hosts_.emplace(host, base::Time::Now());
+ }
+
+ void RemoveHost(RenderProcessHostImpl* host) { hosts_.erase(host); }
+
+ private:
+ // base::trace_event::MemoryDumpProvider:
+ bool OnMemoryDump(const base::trace_event::MemoryDumpArgs& args,
+ base::trace_event::ProcessMemoryDump* pmd) override {
+ for (auto& iter : hosts_) {
+ auto* host = iter.first;
+ base::trace_event::MemoryAllocatorDump* dump = pmd->CreateAllocatorDump(
+ base::StringPrintf("mojo/render_process_host/0x%" PRIxPTR,
+ reinterpret_cast<uintptr_t>(host)));
+ dump->AddScalar("is_initialized",
+ base::trace_event::MemoryAllocatorDump::kUnitsObjects,
+ host->is_initialized() ? 1 : 0);
+ dump->AddScalar("age",
+ base::trace_event::MemoryAllocatorDump::kUnitsObjects,
+ (base::Time::Now() - iter.second).InSeconds());
+ }
+ return true;
+ }
+
+ std::map<RenderProcessHostImpl*, base::Time> hosts_;
+
+ DISALLOW_COPY_AND_ASSIGN(RenderProcessMemoryDumpProvider);
+};
+
+RenderProcessMemoryDumpProvider& GetMemoryDumpProvider() {
+ static base::NoDestructor<RenderProcessMemoryDumpProvider> tracker;
+ return *tracker;
+}
+
// the global list of all renderer processes
base::LazyInstance<base::IDMap<RenderProcessHost*>>::Leaky g_all_hosts =
LAZY_INSTANCE_INITIALIZER;
@@ -486,11 +545,10 @@ class SessionStorageHolder : public base::SupportsUserData::Data {
// SpareRenderProcessHostManager::MaybeTakeSpareRenderProcessHost when creating
// a new RPH. In this implementation, the spare renderer is bound to a
// BrowserContext and its default StoragePartition. If
-// MaybeTakeSpareRenderProcessHost is called with a BrowserContext and
-// StoragePartition that does not match, the spare renderer is discarded. In
-// particular, only the default StoragePartition will be able to use a spare
-// renderer. The spare renderer will also not be used as a guest renderer
-// (is_for_guests_ == true).
+// MaybeTakeSpareRenderProcessHost is called with a BrowserContext that does not
+// match, the spare renderer is discarded. Only the default StoragePartition
+// will be able to use a spare renderer. The spare renderer will also not be
+// used as a guest renderer (is_for_guests_ == true).
//
// It is safe to call WarmupSpareRenderProcessHost multiple times, although if
// called in a context where the spare renderer is not likely to be used
@@ -500,14 +558,12 @@ class SpareRenderProcessHostManager : public RenderProcessHostObserver {
SpareRenderProcessHostManager() {}
void WarmupSpareRenderProcessHost(BrowserContext* browser_context) {
- StoragePartitionImpl* current_partition =
- static_cast<StoragePartitionImpl*>(
- BrowserContext::GetStoragePartition(browser_context, nullptr));
-
if (spare_render_process_host_ &&
- matching_browser_context_ == browser_context &&
- matching_storage_partition_ == current_partition)
+ spare_render_process_host_->GetBrowserContext() == browser_context) {
+ DCHECK_EQ(BrowserContext::GetDefaultStoragePartition(browser_context),
+ spare_render_process_host_->GetStoragePartition());
return; // Nothing to warm up.
+ }
CleanupSpareRenderProcessHost();
@@ -519,68 +575,93 @@ class SpareRenderProcessHostManager : public RenderProcessHostObserver {
RenderProcessHostImpl::GetMaxRendererProcessCount())
return;
- matching_browser_context_ = browser_context;
- matching_storage_partition_ = current_partition;
-
spare_render_process_host_ = RenderProcessHostImpl::CreateRenderProcessHost(
- browser_context, current_partition, nullptr,
- false /* is_for_guests_only */);
+ browser_context, nullptr /* storage_partition_impl */,
+ nullptr /* site_instance */, false /* is_for_guests_only */);
spare_render_process_host_->AddObserver(this);
spare_render_process_host_->Init();
}
- // If |partition| is null, this gets the default partition from the browser
- // context.
RenderProcessHost* MaybeTakeSpareRenderProcessHost(
BrowserContext* browser_context,
- StoragePartition* partition,
SiteInstance* site_instance,
bool is_for_guests_only) {
+ // Give embedder a chance to disable using a spare RenderProcessHost for
+ // certain SiteInstances. Some navigations, such as to NTP or extensions,
+ // require passing command-line flags to the renderer process at process
+ // launch time, but this cannot be done for spare RenderProcessHosts, which
+ // are started before it is known which navigation might use them. So, a
+ // spare RenderProcessHost should not be used in such cases.
+ bool should_use_spare =
+ GetContentClient()->browser()->ShouldUseSpareRenderProcessHost(
+ browser_context, site_instance->GetSiteURL());
+
+ // Get the StoragePartition for |site_instance|. Note that this might be
+ // different than the default StoragePartition for |browser_context|.
+ StoragePartition* site_storage =
+ BrowserContext::GetStoragePartition(browser_context, site_instance);
+
+ // Log UMA metrics.
+ using SpareProcessMaybeTakeAction =
+ RenderProcessHostImpl::SpareProcessMaybeTakeAction;
+ SpareProcessMaybeTakeAction action =
+ SpareProcessMaybeTakeAction::kNoSparePresent;
+ if (!spare_render_process_host_)
+ action = SpareProcessMaybeTakeAction::kNoSparePresent;
+ else if (browser_context != spare_render_process_host_->GetBrowserContext())
+ action = SpareProcessMaybeTakeAction::kMismatchedBrowserContext;
+ else if (site_storage != spare_render_process_host_->GetStoragePartition())
+ action = SpareProcessMaybeTakeAction::kMismatchedStoragePartition;
+ else if (!should_use_spare)
+ action = SpareProcessMaybeTakeAction::kRefusedByEmbedder;
+ else
+ action = SpareProcessMaybeTakeAction::kSpareTaken;
+ UMA_HISTOGRAM_ENUMERATION(
+ "BrowserRenderProcessHost.SpareProcessMaybeTakeAction", action);
+
+ // Decide whether to take or drop the spare process.
+ RenderProcessHost* returned_process = nullptr;
if (spare_render_process_host_ &&
- browser_context == matching_browser_context_ && !is_for_guests_only &&
- !partition) {
- // If the spare renderer matches for everything but possibly the storage
- // partition, and the passed-in partition is null, get the default storage
- // partition. If this is the case, the default storage partition will
- // already have been created and there is no possibility of breaking tests
- // by GetDefaultStoragePartition prematurely creating one.
- partition =
- BrowserContext::GetStoragePartition(browser_context, site_instance);
- }
-
- if (!spare_render_process_host_ ||
- browser_context != matching_browser_context_ ||
- partition != matching_storage_partition_ || is_for_guests_only) {
- // As a new RenderProcessHost will almost certainly be created, we cleanup
- // the non-matching one so as not to waste resources.
+ browser_context == spare_render_process_host_->GetBrowserContext() &&
+ site_storage == spare_render_process_host_->GetStoragePartition() &&
+ !is_for_guests_only && should_use_spare) {
+ CHECK(spare_render_process_host_->HostHasNotBeenUsed());
+
+ // If the spare process ends up getting killed, the spare manager should
+ // discard the spare RPH, so if one exists, it should always be live here.
+ CHECK(spare_render_process_host_->HasConnection());
+
+ DCHECK_EQ(SpareProcessMaybeTakeAction::kSpareTaken, action);
+ returned_process = spare_render_process_host_;
+ ReleaseSpareRenderProcessHost(spare_render_process_host_);
+ } else if (!RenderProcessHostImpl::IsSpareProcessKeptAtAllTimes()) {
+ // If the spare shouldn't be kept around, then discard it as soon as we
+ // find that the current spare was mismatched.
+ CleanupSpareRenderProcessHost();
+ } else if (g_all_hosts.Get().size() >=
+ RenderProcessHostImpl::GetMaxRendererProcessCount()) {
+ // Drop the spare if we are at a process limit and the spare wasn't taken.
+ // This helps avoid process reuse.
CleanupSpareRenderProcessHost();
- return nullptr;
}
- CHECK(spare_render_process_host_->HostHasNotBeenUsed());
- RenderProcessHost* rph = spare_render_process_host_;
- DropSpareRenderProcessHost(spare_render_process_host_);
- return rph;
+ return returned_process;
}
- // Remove |host| as a possible spare renderer. Does not shut it down cleanly;
- // the assumption is that the host was shutdown somewhere else and has
- // notifying the SpareRenderProcessHostManager.
- void DropSpareRenderProcessHost(RenderProcessHost* host) {
- if (spare_render_process_host_ && spare_render_process_host_ == host) {
- spare_render_process_host_->RemoveObserver(this);
- spare_render_process_host_ = nullptr;
- }
- }
-
- // Remove |host| as a possible spare renderer. If |host| is not the spare
- // renderer, then shut down the spare renderer. The idea is that a navigation
- // was just made to |host|, and we do not expect another immediate navigation,
- // so that the spare renderer can be dropped in order to free up resources.
- void DropSpareOnProcessCreation(RenderProcessHost* new_host) {
- if (spare_render_process_host_ == new_host) {
- DropSpareRenderProcessHost(new_host);
+ // Prepares for future requests (with an assumption that a future navigation
+ // might require a new process for |browser_context|).
+ //
+ // Note that depending on the caller PrepareForFutureRequests can be called
+ // after the spare_render_process_host_ has either been 1) matched and taken
+ // or 2) mismatched and ignored or 3) matched and ignored.
+ void PrepareForFutureRequests(BrowserContext* browser_context) {
+ if (RenderProcessHostImpl::IsSpareProcessKeptAtAllTimes()) {
+ // Always keep around a spare process for the most recently requested
+ // |browser_context|.
+ WarmupSpareRenderProcessHost(browser_context);
} else {
+ // Discard the ignored (probably non-matching) spare so as not to waste
+ // resources.
CleanupSpareRenderProcessHost();
}
}
@@ -588,8 +669,17 @@ class SpareRenderProcessHostManager : public RenderProcessHostObserver {
// Gracefully remove and cleanup a spare RenderProcessHost if it exists.
void CleanupSpareRenderProcessHost() {
if (spare_render_process_host_) {
- spare_render_process_host_->Cleanup();
- DropSpareRenderProcessHost(spare_render_process_host_);
+ // Stop observing the process, to avoid getting notifications as a
+ // consequence of the Cleanup call below - such notification could call
+ // back into CleanupSpareRenderProcessHost leading to stack overflow.
+ spare_render_process_host_->RemoveObserver(this);
+
+ // Make sure the RenderProcessHost object gets destroyed.
+ if (!spare_render_process_host_->IsKeepAliveRefCountDisabled())
+ spare_render_process_host_->Cleanup();
+
+ // Drop reference to the RenderProcessHost object.
+ spare_render_process_host_ = nullptr;
}
}
@@ -598,30 +688,37 @@ class SpareRenderProcessHostManager : public RenderProcessHostObserver {
}
private:
- // RenderProcessHostObserver
- void RenderProcessWillExit(RenderProcessHost* host) override {
- DropSpareRenderProcessHost(host);
+ // Release ownership of |host| as a possible spare renderer. Called when
+ // |host| has either been 1) claimed to be used in a navigation or 2) shutdown
+ // somewhere else.
+ void ReleaseSpareRenderProcessHost(RenderProcessHost* host) {
+ if (spare_render_process_host_ && spare_render_process_host_ == host) {
+ spare_render_process_host_->RemoveObserver(this);
+ spare_render_process_host_ = nullptr;
+ }
}
+ // RenderProcessHostObserver::RenderProcessWillExit is not overriden because:
+ // 1. This simplifies reasoning when Cleanup can be called.
+ // 2. In practice the spare shouldn't go through graceful shutdown.
+ // 3. Handling RenderProcessExited and RenderProcessHostDestroyed is
+ // sufficient from correctness perspective.
+
void RenderProcessExited(RenderProcessHost* host,
- base::TerminationStatus unused_status,
+ base::TerminationStatus status,
int unused_exit_code) override {
- DropSpareRenderProcessHost(host);
+ if (host == spare_render_process_host_)
+ CleanupSpareRenderProcessHost();
}
void RenderProcessHostDestroyed(RenderProcessHost* host) override {
- DropSpareRenderProcessHost(host);
+ ReleaseSpareRenderProcessHost(host);
}
// This is a bare pointer, because RenderProcessHost manages the lifetime of
// all its instances; see g_all_hosts, above.
RenderProcessHost* spare_render_process_host_ = nullptr;
- // Used only to check if a creation request matches the spare, and not
- // accessed.
- const BrowserContext* matching_browser_context_ = nullptr;
- const StoragePartition* matching_storage_partition_ = nullptr;
-
DISALLOW_COPY_AND_ASSIGN(SpareRenderProcessHostManager);
};
@@ -661,7 +758,7 @@ class DefaultSubframeProcessHostHolder : public base::SupportsUserData::Data,
if (host_)
return host_;
- host_ = RenderProcessHostImpl::CreateOrUseSpareRenderProcessHost(
+ host_ = RenderProcessHostImpl::CreateRenderProcessHost(
browser_context_, partition, site_instance,
false /* is for guests only */);
host_->SetIsNeverSuitableForReuse();
@@ -842,7 +939,7 @@ class SiteProcessCountTracker : public base::SupportsUserData::Data,
host, host->GetBrowserContext(), site_url))
continue;
- if (host->VisibleWidgetCount())
+ if (host->VisibleClientCount())
foreground_processes->insert(host);
else
background_processes->insert(host);
@@ -1235,6 +1332,24 @@ size_t RenderProcessHost::GetMaxRendererProcessCount() {
// static
void RenderProcessHost::SetMaxRendererProcessCount(size_t count) {
g_max_renderer_count_override = count;
+ if (g_all_hosts.Get().size() > count)
+ g_spare_render_process_host_manager.Get().CleanupSpareRenderProcessHost();
+}
+
+// static
+int RenderProcessHost::GetCurrentRenderProcessCountForTesting() {
+ content::RenderProcessHost::iterator it =
+ content::RenderProcessHost::AllHostsIterator();
+ int count = 0;
+ while (!it.IsAtEnd()) {
+ RenderProcessHost* host = it.GetCurrentValue();
+ if (host->HasConnection() &&
+ host != RenderProcessHostImpl::GetSpareRenderProcessHostForTesting()) {
+ count++;
+ }
+ it.Advance();
+ }
+ return count;
}
// static
@@ -1270,25 +1385,8 @@ RenderProcessHost* RenderProcessHostImpl::CreateRenderProcessHost(
}
// static
-RenderProcessHost* RenderProcessHostImpl::CreateOrUseSpareRenderProcessHost(
- BrowserContext* browser_context,
- StoragePartitionImpl* storage_partition_impl,
- SiteInstance* site_instance,
- bool is_for_guests_only) {
- RenderProcessHost* render_process_host =
- g_spare_render_process_host_manager.Get().MaybeTakeSpareRenderProcessHost(
- browser_context, storage_partition_impl, site_instance,
- is_for_guests_only);
-
- if (!render_process_host) {
- render_process_host =
- CreateRenderProcessHost(browser_context, storage_partition_impl,
- site_instance, is_for_guests_only);
- }
-
- DCHECK(render_process_host);
- return render_process_host;
-}
+const unsigned int RenderProcessHostImpl::kMaxFrameDepthForPriority =
+ std::numeric_limits<unsigned int>::max();
RenderProcessHostImpl::RenderProcessHostImpl(
BrowserContext* browser_context,
@@ -1303,9 +1401,9 @@ RenderProcessHostImpl::RenderProcessHostImpl(
keep_alive_ref_count_(0),
is_keep_alive_ref_count_disabled_(false),
route_provider_binding_(this),
- visible_widgets_(0),
+ visible_clients_(0),
priority_({
- blink::kLaunchingProcessIsBackgrounded,
+ blink::kLaunchingProcessIsBackgrounded, frame_depth_,
blink::kLaunchingProcessIsBoostedForPendingView,
#if defined(OS_ANDROID)
ChildProcessImportance::NORMAL,
@@ -1340,6 +1438,9 @@ RenderProcessHostImpl::RenderProcessHostImpl(
shared_bitmap_allocation_notifier_impl_(
viz::ServerSharedBitmapManager::current()),
weak_factory_(this) {
+ for (size_t i = 0; i < kNumKeepAliveClients; i++)
+ keep_alive_client_count_[i] = 0;
+
widget_helper_ = new RenderWidgetHelper();
ChildProcessSecurityPolicyImpl::GetInstance()->Add(GetID());
@@ -1362,11 +1463,16 @@ RenderProcessHostImpl::RenderProcessHostImpl(
GetID(), storage_partition_impl_->GetServiceWorkerContext()));
AddObserver(indexed_db_factory_.get());
+#if defined(OS_MACOSX)
+ AddObserver(MachBroker::GetInstance());
+#endif
InitializeChannelProxy();
if (!base::FeatureList::IsEnabled(features::kMash))
gpu_client_.reset(new GpuClient(GetID()));
+
+ GetMemoryDumpProvider().AddHost(this);
}
// static
@@ -1430,6 +1536,8 @@ RenderProcessHostImpl::~RenderProcessHostImpl() {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::BindOnce(&RemoveShaderInfo, GetID()));
}
+
+ GetMemoryDumpProvider().RemoveHost(this);
}
bool RenderProcessHostImpl::Init() {
@@ -1705,9 +1813,7 @@ void RenderProcessHostImpl::CreateMessageFilters() {
#else
nullptr,
#endif
- GetBrowserContext(),
- request_context.get(),
- widget_helper_.get());
+ GetBrowserContext(), storage_partition_impl_, widget_helper_.get());
AddFilter(render_frame_message_filter_.get());
BrowserContext* browser_context = GetBrowserContext();
@@ -1729,7 +1835,7 @@ void RenderProcessHostImpl::CreateMessageFilters() {
storage_partition_impl_->GetFileSystemContext(),
storage_partition_impl_->GetServiceWorkerContext(),
storage_partition_impl_->GetPrefetchURLLoaderService(),
- get_contexts_callback,
+ std::move(get_contexts_callback),
BrowserThread::GetTaskRunnerForThread(BrowserThread::IO));
AddFilter(resource_message_filter_.get());
@@ -1749,7 +1855,7 @@ void RenderProcessHostImpl::CreateMessageFilters() {
AddFilter(base::MakeRefCounted<AudioRendererHost>(
GetID(), audio_manager,
BrowserMainLoop::GetInstance()->audio_system(),
- AudioMirroringManager::GetInstance(), media_stream_manager)
+ media_stream_manager)
.get());
}
AddFilter(
@@ -1760,7 +1866,6 @@ void RenderProcessHostImpl::CreateMessageFilters() {
#if BUILDFLAG(ENABLE_WEBRTC)
peer_connection_tracker_host_ = new PeerConnectionTrackerHost(GetID());
AddFilter(peer_connection_tracker_host_.get());
- AddFilter(new MediaStreamTrackMetricsHost());
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
AddFilter(new PepperRendererConnection(GetID()));
@@ -1776,11 +1881,6 @@ void RenderProcessHostImpl::CreateMessageFilters() {
AddFilter(new TextInputClientMessageFilter());
#endif
- scoped_refptr<CacheStorageDispatcherHost> cache_storage_filter =
- new CacheStorageDispatcherHost();
- cache_storage_filter->Init(storage_partition_impl_->GetCacheStorageContext());
- AddFilter(cache_storage_filter.get());
-
scoped_refptr<ServiceWorkerDispatcherHost> service_worker_filter =
new ServiceWorkerDispatcherHost(GetID(), resource_context);
service_worker_filter->Init(
@@ -1813,6 +1913,26 @@ void RenderProcessHostImpl::CreateMessageFilters() {
#endif
}
+void RenderProcessHostImpl::BindCacheStorage(
+ blink::mojom::CacheStorageRequest request,
+ const url::Origin& origin) {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+
+ if (!cache_storage_dispatcher_host_) {
+ cache_storage_dispatcher_host_ =
+ base::MakeRefCounted<CacheStorageDispatcherHost>();
+ cache_storage_dispatcher_host_->Init(
+ storage_partition_impl_->GetCacheStorageContext());
+ }
+ // Send the binding to IO thread, because Cache Storage handles Mojo IPC on IO
+ // thread entirely.
+ BrowserThread::PostTask(
+ BrowserThread::IO, FROM_HERE,
+ base::BindOnce(&CacheStorageDispatcherHost::AddBinding,
+ cache_storage_dispatcher_host_, std::move(request),
+ origin));
+}
+
void RenderProcessHostImpl::RegisterMojoInterfaces() {
auto registry = std::make_unique<service_manager::BinderRegistry>();
@@ -1924,6 +2044,12 @@ void RenderProcessHostImpl::RegisterMojoInterfaces() {
base::CreateSequencedTaskRunnerWithTraits(
{base::MayBlock(), base::TaskPriority::USER_VISIBLE}));
+#if BUILDFLAG(ENABLE_WEBRTC)
+ registry->AddInterface(base::BindRepeating(
+ &RenderProcessHostImpl::CreateMediaStreamTrackMetricsHost,
+ base::Unretained(this)));
+#endif
+
registry->AddInterface(
base::Bind(&metrics::CreateSingleSampleMetricsProvider));
@@ -1966,6 +2092,11 @@ void RenderProcessHostImpl::RegisterMojoInterfaces() {
ServiceManagerConnection* service_manager_connection =
BrowserContext::GetServiceManagerConnectionFor(browser_context_);
+ if (connection_filter_id_ !=
+ ServiceManagerConnection::kInvalidConnectionFilterId) {
+ connection_filter_controller_->DisableFilter();
+ service_manager_connection->RemoveConnectionFilter(connection_filter_id_);
+ }
std::unique_ptr<ConnectionFilterImpl> connection_filter(
new ConnectionFilterImpl(child_connection_->child_identity(),
std::move(registry)));
@@ -2096,19 +2227,35 @@ bool RenderProcessHostImpl::IsProcessBackgrounded() const {
return priority_.background;
}
-void RenderProcessHostImpl::IncrementKeepAliveRefCount() {
+void RenderProcessHostImpl::IncrementKeepAliveRefCount(
+ RenderProcessHost::KeepAliveClientType client) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(!is_keep_alive_ref_count_disabled_);
+ base::TimeTicks now = base::TimeTicks::Now();
+ size_t client_type = static_cast<size_t>(client);
+ keep_alive_client_count_[client_type]++;
+ if (keep_alive_client_count_[client_type] == 1)
+ keep_alive_client_start_time_[client_type] = now;
+
++keep_alive_ref_count_;
- if (keep_alive_ref_count_ - 1 == 0) {
+ if (keep_alive_ref_count_ == 1) {
GetRendererInterface()->SetSchedulerKeepActive(true);
}
}
-void RenderProcessHostImpl::DecrementKeepAliveRefCount() {
+void RenderProcessHostImpl::DecrementKeepAliveRefCount(
+ RenderProcessHost::KeepAliveClientType client) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(!is_keep_alive_ref_count_disabled_);
DCHECK_GT(keep_alive_ref_count_, 0U);
+ base::TimeTicks now = base::TimeTicks::Now();
+ size_t client_type = static_cast<size_t>(client);
+ keep_alive_client_count_[client_type]--;
+ if (keep_alive_client_count_[client_type] == 0) {
+ RecordKeepAliveDuration(client, keep_alive_client_start_time_[client_type],
+ now);
+ }
+
--keep_alive_ref_count_;
if (keep_alive_ref_count_ == 0) {
Cleanup();
@@ -2116,13 +2263,48 @@ void RenderProcessHostImpl::DecrementKeepAliveRefCount() {
}
}
+void RenderProcessHostImpl::RecordKeepAliveDuration(
+ RenderProcessHost::KeepAliveClientType client,
+ base::TimeTicks start,
+ base::TimeTicks end) {
+ switch (client) {
+ case RenderProcessHost::KeepAliveClientType::kServiceWorker:
+ UMA_HISTOGRAM_LONG_TIMES(
+ "BrowserRenderProcessHost.KeepAliveDuration.ServiceWorker",
+ end - start);
+ break;
+ case RenderProcessHost::KeepAliveClientType::kSharedWorker:
+ UMA_HISTOGRAM_LONG_TIMES(
+ "BrowserRenderProcessHost.KeepAliveDuration.SharedWorker",
+ end - start);
+ break;
+ case RenderProcessHost::KeepAliveClientType::kFetch:
+ UMA_HISTOGRAM_LONG_TIMES(
+ "BrowserRenderProcessHost.KeepAliveDuration.Fetch", end - start);
+ break;
+ }
+}
+
void RenderProcessHostImpl::DisableKeepAliveRefCount() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
- is_keep_alive_ref_count_disabled_ = true;
- if (!keep_alive_ref_count_)
+
+ if (is_keep_alive_ref_count_disabled_)
return;
+ is_keep_alive_ref_count_disabled_ = true;
+
keep_alive_ref_count_ = 0;
+ base::TimeTicks now = base::TimeTicks::Now();
+ for (size_t i = 0; i < kNumKeepAliveClients; i++) {
+ if (keep_alive_client_count_[i] > 0) {
+ RecordKeepAliveDuration(
+ static_cast<RenderProcessHost::KeepAliveClientType>(i),
+ keep_alive_client_start_time_[i], now);
+ keep_alive_client_count_[i] = 0;
+ }
+ }
+
// Cleaning up will also remove this from the SpareRenderProcessHostManager.
+ // (in this case |keep_alive_ref_count_| would be 0 even before).
Cleanup();
}
@@ -2218,7 +2400,7 @@ void RenderProcessHostImpl::ShutdownForBadMessage(
// We kill the renderer but don't include a NOTREACHED, because we want the
// browser to try to survive when it gets illegal messages from the renderer.
- Shutdown(RESULT_CODE_KILLED_BAD_MESSAGE, false);
+ Shutdown(RESULT_CODE_KILLED_BAD_MESSAGE);
if (crash_report_mode == CrashReportMode::GENERATE_CRASH_DUMP) {
// Set crash keys to understand renderer kills related to site isolation.
@@ -2247,47 +2429,23 @@ void RenderProcessHostImpl::ShutdownForBadMessage(
PROCESS_TYPE_RENDERER);
}
-void RenderProcessHostImpl::WidgetRestored() {
- visible_widgets_++;
- UpdateProcessPriority();
+void RenderProcessHostImpl::UpdateClientPriority(PriorityClient* client) {
+ DCHECK(client);
+ DCHECK_EQ(1u, priority_clients_.count(client));
+ UpdateProcessPriorityInputs();
}
-void RenderProcessHostImpl::WidgetHidden() {
- // On startup, the browser will call Hide. We ignore this call.
- if (visible_widgets_ == 0)
- return;
-
- --visible_widgets_;
- if (visible_widgets_ == 0) {
- UpdateProcessPriority();
- }
+int RenderProcessHostImpl::VisibleClientCount() const {
+ return visible_clients_;
}
-int RenderProcessHostImpl::VisibleWidgetCount() const {
- return visible_widgets_;
+unsigned int RenderProcessHostImpl::GetFrameDepthForTesting() const {
+ return frame_depth_;
}
#if defined(OS_ANDROID)
-void RenderProcessHostImpl::UpdateWidgetImportance(
- ChildProcessImportance old_value,
- ChildProcessImportance new_value) {
- DCHECK_NE(old_value, new_value);
- DCHECK(widget_importance_counts_[static_cast<size_t>(old_value)]);
- widget_importance_counts_[static_cast<size_t>(old_value)]--;
- widget_importance_counts_[static_cast<size_t>(new_value)]++;
- UpdateProcessPriority();
-}
-
-ChildProcessImportance RenderProcessHostImpl::ComputeEffectiveImportance() {
- ChildProcessImportance importance = ChildProcessImportance::NORMAL;
- for (size_t i = 0u; i < arraysize(widget_importance_counts_); ++i) {
- DCHECK_GE(widget_importance_counts_[i], 0);
- if (widget_importance_counts_[i]) {
- // No early out. Highest importance wins.
- importance = static_cast<ChildProcessImportance>(i);
- }
- }
- return importance;
+ChildProcessImportance RenderProcessHostImpl::GetEffectiveImportance() {
+ return effective_importance_;
}
#endif
@@ -2318,6 +2476,7 @@ void RenderProcessHostImpl::OnMediaStreamRemoved() {
UpdateProcessPriority();
}
+// static
void RenderProcessHostImpl::set_render_process_host_factory(
const RenderProcessHostFactory* rph_factory) {
g_render_process_host_factory_ = rph_factory;
@@ -2400,8 +2559,10 @@ void RenderProcessHostImpl::RemoveExpectedNavigationToSite(
}
// static
-void RenderProcessHostImpl::CleanupSpareRenderProcessHost() {
- g_spare_render_process_host_manager.Get().CleanupSpareRenderProcessHost();
+void RenderProcessHostImpl::NotifySpareManagerAboutRecentlyUsedBrowserContext(
+ BrowserContext* browser_context) {
+ g_spare_render_process_host_manager.Get().PrepareForFutureRequests(
+ browser_context);
}
// static
@@ -2410,6 +2571,22 @@ RenderProcessHostImpl::GetSpareRenderProcessHostForTesting() {
return g_spare_render_process_host_manager.Get().spare_render_process_host();
}
+// static
+void RenderProcessHostImpl::DiscardSpareRenderProcessHostForTesting() {
+ g_spare_render_process_host_manager.Get().CleanupSpareRenderProcessHost();
+}
+
+// static
+bool RenderProcessHostImpl::IsSpareProcessKeptAtAllTimes() {
+ if (!SiteIsolationPolicy::UseDedicatedProcessesForAllSites())
+ return false;
+
+ if (!base::FeatureList::IsEnabled(features::kSpareRendererForSitePerProcess))
+ return false;
+
+ return true;
+}
+
bool RenderProcessHostImpl::HostHasNotBeenUsed() {
return IsUnused() && listeners_.IsEmpty() && keep_alive_ref_count_ == 0 &&
pending_views_ == 0;
@@ -2450,9 +2627,6 @@ static void AppendCompositorCommandLineFlags(base::CommandLine* command_line) {
if (IsCheckerImagingEnabled())
command_line->AppendSwitch(cc::switches::kEnableCheckerImaging);
- if (IsCompositorImageAnimationEnabled())
- command_line->AppendSwitch(switches::kEnableCompositorImageAnimations);
-
// Slimming Paint v2 implies layer lists in the renderer.
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableSlimmingPaintV2)) {
@@ -2525,15 +2699,16 @@ void RenderProcessHostImpl::PropagateBrowserCommandLineToRenderer(
switches::kDisable2dCanvasImageChromium,
switches::kDisableAcceleratedJpegDecoding,
switches::kDisableAcceleratedVideoDecode,
+ switches::kDisableBackgroundTasks,
switches::kDisableBackgroundTimerThrottling,
switches::kDisableBreakpad,
switches::kDisableCompositorUkmForTests,
switches::kDisablePreferCompositingToLCDText,
switches::kDisableDatabases,
- switches::kDisableDistanceFieldText,
switches::kDisableFileSystem,
switches::kDisableGpuMemoryBufferVideoFrames,
switches::kDisableGpuVsync,
+ switches::kDisableImageAnimationResync,
switches::kDisableLowResTiling,
switches::kDisableHistogramCustomizer,
switches::kDisableLCDText,
@@ -2557,8 +2732,6 @@ void RenderProcessHostImpl::PropagateBrowserCommandLineToRenderer(
switches::kDisableWebGLImageChromium,
switches::kDomAutomationController,
switches::kEnableAutomation,
- switches::kEnableDistanceFieldText,
- switches::kEnableExperimentalCanvasFeatures,
switches::kEnableExperimentalWebPlatformFeatures,
switches::kEnableHeapProfiling,
switches::kEnableGPUClientLogging,
@@ -2576,6 +2749,7 @@ void RenderProcessHostImpl::PropagateBrowserCommandLineToRenderer(
switches::kEnablePreciseMemoryInfo,
switches::kEnablePrintBrowser,
switches::kEnablePreferCompositingToLCDText,
+ switches::kEnableRasterDecoder,
switches::kEnableRGBA4444Textures,
switches::kEnableSkiaBenchmarking,
switches::kEnableSlimmingPaintV175,
@@ -2611,13 +2785,15 @@ void RenderProcessHostImpl::PropagateBrowserCommandLineToRenderer(
switches::kReducedReferrerGranularity,
switches::kRegisterPepperPlugins,
switches::kRendererStartupDialog,
+ switches::kReportVp9AsAnUnsupportedMimeType,
switches::kSamplingHeapProfiler,
switches::kShowPaintRects,
switches::kStatsCollectionController,
+ switches::kSkiaFontCacheLimitMb,
+ switches::kSkiaResourceCacheLimitMb,
switches::kTestType,
switches::kTouchEventFeatureDetection,
switches::kTouchTextSelectionStrategy,
- switches::kTraceConfigFile,
switches::kTraceToConsole,
switches::kUseFakeUIForMediaStream,
// This flag needs to be propagated to the renderer process for
@@ -2625,6 +2801,7 @@ void RenderProcessHostImpl::PropagateBrowserCommandLineToRenderer(
switches::kUseGL,
switches::kUseGpuInTests,
switches::kUseMobileUserAgent,
+ switches::kUseSkiaRenderer,
switches::kV,
switches::kVideoThreads,
switches::kVideoUnderflowThresholdMs,
@@ -2696,15 +2873,7 @@ void RenderProcessHostImpl::PropagateBrowserCommandLineToRenderer(
arraysize(kSwitchNames));
BrowserChildProcessHostImpl::CopyFeatureAndFieldTrialFlags(renderer_cmd);
-
- if (browser_cmd.HasSwitch(switches::kTraceStartup) &&
- BrowserMainLoop::GetInstance()->is_tracing_startup_for_duration()) {
- // Pass kTraceStartup switch to renderer only if startup tracing has not
- // finished.
- renderer_cmd->AppendSwitchASCII(
- switches::kTraceStartup,
- browser_cmd.GetSwitchValueASCII(switches::kTraceStartup));
- }
+ BrowserChildProcessHostImpl::CopyTraceStartupFlags(renderer_cmd);
#if BUILDFLAG(ENABLE_WEBRTC)
// Only run the Stun trials in the first renderer.
@@ -2785,14 +2954,14 @@ bool RenderProcessHostImpl::IsReady() const {
return GetHandle() && channel_connected_;
}
-bool RenderProcessHostImpl::Shutdown(int exit_code, bool wait) {
+bool RenderProcessHostImpl::Shutdown(int exit_code) {
if (run_renderer_in_process())
return false; // Single process mode never shuts down the renderer.
if (!child_process_launcher_.get())
return false;
- return child_process_launcher_->Terminate(exit_code, wait);
+ return child_process_launcher_->Terminate(exit_code);
}
bool RenderProcessHostImpl::FastShutdownIfPossible(size_t page_count,
@@ -2805,8 +2974,7 @@ bool RenderProcessHostImpl::FastShutdownIfPossible(size_t page_count,
if (run_renderer_in_process())
return false; // Single process mode never shuts down the renderer.
- if (!child_process_launcher_.get() || child_process_launcher_->IsStarting() ||
- !GetHandle())
+ if (!child_process_launcher_.get())
return false; // Render process hasn't started or is probably crashed.
// Test if there's an unload listener.
@@ -3061,12 +3229,9 @@ void RenderProcessHostImpl::Cleanup() {
base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this);
deleting_soon_ = true;
- // It's important not to wait for the DeleteTask to delete the channel
- // proxy. Kill it off now. That way, in case the profile is going away, the
- // rest of the objects attached to this RenderProcessHost start going
- // away first, since deleting the channel proxy will post a
- // OnChannelClosed() to IPC::ChannelProxy::Context on the IO thread.
- ResetChannelProxy();
+ // Destroy all mojo bindings and IPC channels that can cause calls to this
+ // object, to avoid method invocations that trigger usages of profile.
+ ResetIPC();
// Its important to remove the kSessionStorageHolder after the channel
// has been reset to avoid deleting the underlying namespaces prior
@@ -3097,10 +3262,10 @@ void RenderProcessHostImpl::AddWidget(RenderWidgetHost* widget) {
RenderWidgetHostImpl* widget_impl =
static_cast<RenderWidgetHostImpl*>(widget);
widgets_.insert(widget_impl);
-#if defined(OS_ANDROID)
- widget_importance_counts_[static_cast<size_t>(widget_impl->importance())]++;
- UpdateProcessPriority();
-#endif
+
+ DCHECK(!base::ContainsKey(priority_clients_, widget_impl));
+ priority_clients_.insert(widget_impl);
+ UpdateProcessPriorityInputs();
}
void RenderProcessHostImpl::RemoveWidget(RenderWidgetHost* widget) {
@@ -3108,12 +3273,9 @@ void RenderProcessHostImpl::RemoveWidget(RenderWidgetHost* widget) {
static_cast<RenderWidgetHostImpl*>(widget);
widgets_.erase(widget_impl);
-#if defined(OS_ANDROID)
- ChildProcessImportance importance = widget_impl->importance();
- DCHECK(widget_importance_counts_[static_cast<size_t>(importance)]);
- widget_importance_counts_[static_cast<size_t>(importance)]--;
- UpdateProcessPriority();
-#endif
+ DCHECK(base::ContainsKey(priority_clients_, widget_impl));
+ priority_clients_.erase(widget_impl);
+ UpdateProcessPriorityInputs();
}
void RenderProcessHostImpl::SetSuddenTerminationAllowed(bool enabled) {
@@ -3194,6 +3356,15 @@ RenderProcessHostImpl::StartRtpDump(
}
return stop_rtp_dump_callback_;
}
+
+void RenderProcessHostImpl::SetWebRtcEventLogOutput(int lid, bool enabled) {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ if (enabled) {
+ Send(new PeerConnectionTracker_StartEventLogOutput(lid));
+ } else {
+ Send(new PeerConnectionTracker_StopEventLog(lid));
+ }
+}
#endif // BUILDFLAG(ENABLE_WEBRTC)
IPC::ChannelProxy* RenderProcessHostImpl::GetChannel() {
@@ -3286,28 +3457,40 @@ bool RenderProcessHostImpl::IsSuitableHost(RenderProcessHost* host,
if (!host->InSameStoragePartition(dest_partition))
return false;
+ // Check WebUI bindings and origin locks.
auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
- if (policy->HasWebUIBindings(host->GetID()) !=
- WebUIControllerFactoryRegistry::GetInstance()->UseWebUIBindingsForURL(
- browser_context, site_url)) {
- return false;
- }
-
- // Sites requiring dedicated processes can only reuse a compatible process.
+ bool host_has_web_ui_bindings = policy->HasWebUIBindings(host->GetID());
auto lock_state = policy->CheckOriginLock(host->GetID(), site_url);
- if (lock_state !=
- ChildProcessSecurityPolicyImpl::CheckOriginLockResult::NO_LOCK) {
- // If the process is already dedicated to a site, only allow the destination
- // URL to reuse this process if the URL has the same site.
- if (lock_state !=
- ChildProcessSecurityPolicyImpl::CheckOriginLockResult::HAS_EQUAL_LOCK)
+ if (host->HostHasNotBeenUsed()) {
+ // If the host hasn't been used, it won't have the expected WebUI bindings
+ // or origin locks just *yet* - skip the checks in this case. One example
+ // where this case can happen is when the spare RenderProcessHost gets used.
+ CHECK(!host_has_web_ui_bindings);
+ CHECK_EQ(CheckOriginLockResult::NO_LOCK, lock_state);
+ } else {
+ // WebUI checks.
+ bool url_requires_web_ui_bindings =
+ WebUIControllerFactoryRegistry::GetInstance()->UseWebUIBindingsForURL(
+ browser_context, site_url);
+ if (host_has_web_ui_bindings != url_requires_web_ui_bindings)
return false;
- } else if (!host->IsUnused() && SiteInstanceImpl::ShouldLockToOrigin(
- browser_context, host, site_url)) {
- // Otherwise, if this process has been used to host any other content, it
- // cannot be reused if the destination site indeed requires a dedicated
- // process and can be locked to just that site.
- return false;
+
+ // Sites requiring dedicated processes can only reuse a compatible process.
+ switch (lock_state) {
+ case CheckOriginLockResult::HAS_EQUAL_LOCK:
+ break;
+ case CheckOriginLockResult::HAS_WRONG_LOCK:
+ return false;
+ case CheckOriginLockResult::NO_LOCK:
+ if (!host->IsUnused() && SiteInstanceImpl::ShouldLockToOrigin(
+ browser_context, host, site_url)) {
+ // If this process has been used to host any other content, it cannot
+ // be reused if the destination site requires a dedicated process and
+ // should use a process locked to just that site.
+ return false;
+ }
+ break;
+ }
}
return GetContentClient()->browser()->IsSuitableHost(host, site_url);
@@ -3390,7 +3573,7 @@ bool RenderProcessHost::ShouldTryToUseExistingProcessHost(
}
// static
-RenderProcessHost* RenderProcessHost::GetExistingProcessHost(
+RenderProcessHost* RenderProcessHostImpl::GetExistingProcessHost(
BrowserContext* browser_context,
const GURL& site_url) {
// First figure out which existing renderers we can use.
@@ -3402,6 +3585,11 @@ RenderProcessHost* RenderProcessHost::GetExistingProcessHost(
if (iter.GetCurrentValue()->MayReuseHost() &&
RenderProcessHostImpl::IsSuitableHost(iter.GetCurrentValue(),
browser_context, site_url)) {
+ // The spare is always considered before process reuse.
+ DCHECK_NE(iter.GetCurrentValue(),
+ g_spare_render_process_host_manager.Get()
+ .spare_render_process_host());
+
suitable_renderers.push_back(iter.GetCurrentValue());
}
iter.Advance();
@@ -3411,10 +3599,6 @@ RenderProcessHost* RenderProcessHost::GetExistingProcessHost(
if (!suitable_renderers.empty()) {
int suitable_count = static_cast<int>(suitable_renderers.size());
int random_index = base::RandInt(0, suitable_count - 1);
- // If the process chosen was the spare RenderProcessHost, ensure it won't be
- // used as a spare in the future, or drop the spare if it wasn't used.
- g_spare_render_process_host_manager.Get().DropSpareOnProcessCreation(
- suitable_renderers[random_index]);
return suitable_renderers[random_index];
}
@@ -3535,6 +3719,16 @@ RenderProcessHost* RenderProcessHostImpl::GetProcessHostForSiteInstance(
browser_context, site_url);
}
+ // See if the spare RenderProcessHost can be used.
+ SpareRenderProcessHostManager& spare_process_manager =
+ g_spare_render_process_host_manager.Get();
+ bool spare_was_taken = false;
+ if (!render_process_host) {
+ render_process_host = spare_process_manager.MaybeTakeSpareRenderProcessHost(
+ browser_context, site_instance, is_for_guests_only);
+ spare_was_taken = (render_process_host != nullptr);
+ }
+
// If not (or if none found), see if we should reuse an existing process.
if (!render_process_host &&
ShouldTryToUseExistingProcessHost(browser_context, site_url)) {
@@ -3558,16 +3752,28 @@ RenderProcessHost* RenderProcessHostImpl::GetProcessHostForSiteInstance(
CHECK(false) << "Unsuitable process reused for site " << site_url;
}
- // Otherwise, use the spare RenderProcessHost or create a new one.
+ // Otherwise, create a new RenderProcessHost.
if (!render_process_host) {
// Pass a null StoragePartition. Tests with TestBrowserContext using a
// RenderProcessHostFactory may not instantiate a StoragePartition, and
// creating one here with GetStoragePartition() can run into cross-thread
// issues as TestBrowserContext initialization is done on the main thread.
- render_process_host = CreateOrUseSpareRenderProcessHost(
+ render_process_host = CreateRenderProcessHost(
browser_context, nullptr, site_instance, is_for_guests_only);
}
+ // It is important to call PrepareForFutureRequests *after* potentially
+ // creating a process a few statements earlier - doing this avoids violating
+ // the process limit.
+ //
+ // We should not warm-up another spare if the spare was not taken, because in
+ // this case we might have created a new process - we want to avoid spawning
+ // two processes at the same time. In this case the call to
+ // PrepareForFutureRequests will be postponed until later (e.g. until the
+ // navigation commits or a cross-site redirect happens).
+ if (spare_was_taken)
+ spare_process_manager.PrepareForFutureRequests(browser_context);
+
if (is_unmatched_service_worker) {
UnmatchedServiceWorkerProcessTracker::Register(
browser_context, render_process_host, site_url);
@@ -3666,11 +3872,10 @@ void RenderProcessHostImpl::ProcessDied(bool already_dead,
child_process_launcher_.reset();
is_dead_ = true;
- if (route_provider_binding_.is_bound())
- route_provider_binding_.Close();
- associated_interfaces_.reset();
+ // Make sure no IPCs or mojo calls from the old process get dispatched after
+ // it has died.
+ ResetIPC();
process_resource_coordinator_.reset();
- ResetChannelProxy();
UpdateProcessPriority();
@@ -3703,13 +3908,6 @@ void RenderProcessHostImpl::ProcessDied(bool already_dead,
if (delayed_cleanup_needed_)
Cleanup();
- // If RenderProcessHostImpl is reused, the next renderer will send a new
- // request for FrameSinkProvider so make sure frame_sink_provider_ is ready
- // for that.
- frame_sink_provider_.Unbind();
- if (renderer_host_binding_.is_bound())
- renderer_host_binding_.Unbind();
-
compositing_mode_reporter_.reset();
shared_bitmap_allocation_notifier_impl_.ChildDied();
@@ -3719,6 +3917,27 @@ void RenderProcessHostImpl::ProcessDied(bool already_dead,
// TODO(darin): clean this up
}
+void RenderProcessHostImpl::ResetIPC() {
+ if (renderer_host_binding_.is_bound())
+ renderer_host_binding_.Unbind();
+ if (route_provider_binding_.is_bound())
+ route_provider_binding_.Close();
+ associated_interface_provider_bindings_.CloseAllBindings();
+ associated_interfaces_.reset();
+
+ // If RenderProcessHostImpl is reused, the next renderer will send a new
+ // request for FrameSinkProvider so make sure frame_sink_provider_ is ready
+ // for that.
+ frame_sink_provider_.Unbind();
+
+ // It's important not to wait for the DeleteTask to delete the channel
+ // proxy. Kill it off now. That way, in case the profile is going away, the
+ // rest of the objects attached to this RenderProcessHost start going
+ // away first, since deleting the channel proxy will post a
+ // OnChannelClosed() to IPC::ChannelProxy::Context on the IO thread.
+ ResetChannelProxy();
+}
+
size_t RenderProcessHost::GetActiveViewCount() {
size_t num_active_views = 0;
std::unique_ptr<RenderWidgetHostIterator> widgets(
@@ -3784,6 +4003,49 @@ void RenderProcessHostImpl::SuddenTerminationChanged(bool enabled) {
SetSuddenTerminationAllowed(enabled);
}
+void RenderProcessHostImpl::UpdateProcessPriorityInputs() {
+ int32_t new_visible_widgets_count = 0;
+ unsigned int new_frame_depth = kMaxFrameDepthForPriority;
+#if defined(OS_ANDROID)
+ ChildProcessImportance new_effective_importance =
+ ChildProcessImportance::NORMAL;
+#endif
+ for (auto* client : priority_clients_) {
+ Priority priority = client->GetPriority();
+
+ // Compute the lowest depth of widgets with highest visibility priority.
+ // See comment on |frame_depth_| for more details.
+ if (priority.is_hidden) {
+ if (!new_visible_widgets_count) {
+ new_frame_depth = std::min(new_frame_depth, priority.frame_depth);
+ }
+ } else {
+ if (new_visible_widgets_count) {
+ new_frame_depth = std::min(new_frame_depth, priority.frame_depth);
+ } else {
+ new_frame_depth = priority.frame_depth;
+ }
+ new_visible_widgets_count++;
+ }
+
+#if defined(OS_ANDROID)
+ new_effective_importance =
+ std::max(new_effective_importance, priority.importance);
+#endif
+ }
+
+ bool inputs_changed = new_visible_widgets_count != visible_clients_;
+ visible_clients_ = new_visible_widgets_count;
+ frame_depth_ = new_frame_depth;
+#if defined(OS_ANDROID)
+ inputs_changed =
+ inputs_changed || new_effective_importance != effective_importance_;
+ effective_importance_ = new_effective_importance;
+#endif
+ if (inputs_changed)
+ UpdateProcessPriority();
+}
+
void RenderProcessHostImpl::UpdateProcessPriority() {
if (!run_renderer_in_process() && (!child_process_launcher_.get() ||
child_process_launcher_->IsStarting())) {
@@ -3797,13 +4059,14 @@ void RenderProcessHostImpl::UpdateProcessPriority() {
// We background a process as soon as it hosts no active audio/video streams
// and no visible widgets -- the callers must call this function whenever we
// transition in/out of those states.
- visible_widgets_ == 0 && media_stream_count_ == 0 &&
+ visible_clients_ == 0 && media_stream_count_ == 0 &&
!base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableRendererBackgrounding),
+ frame_depth_,
// boost_for_pending_views
!!pending_views_,
#if defined(OS_ANDROID)
- ComputeEffectiveImportance(),
+ GetEffectiveImportance(),
#endif
};
@@ -4033,6 +4296,14 @@ RenderProcessHost* RenderProcessHostImpl::FindReusableProcessHostForSite(
}
#if BUILDFLAG(ENABLE_WEBRTC)
+void RenderProcessHostImpl::CreateMediaStreamTrackMetricsHost(
+ mojom::MediaStreamTrackMetricsHostRequest request) {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+ if (!media_stream_track_metrics_host_)
+ media_stream_track_metrics_host_.reset(new MediaStreamTrackMetricsHost());
+ media_stream_track_metrics_host_->BindRequest(std::move(request));
+}
+
void RenderProcessHostImpl::OnRegisterAecDumpConsumer(int id) {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
diff --git a/chromium/content/browser/renderer_host/render_process_host_impl.h b/chromium/content/browser/renderer_host/render_process_host_impl.h
index 51c2ff46b9a..5f6fd5d4c8c 100644
--- a/chromium/content/browser/renderer_host/render_process_host_impl.h
+++ b/chromium/content/browser/renderer_host/render_process_host_impl.h
@@ -13,7 +13,11 @@
#include <queue>
#include <set>
#include <string>
+#include <utility>
+#include <vector>
+#include "base/containers/flat_set.h"
+#include "base/gtest_prod_util.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/observer_list.h"
@@ -22,6 +26,7 @@
#include "base/synchronization/waitable_event.h"
#include "build/build_config.h"
#include "components/viz/service/display_embedder/shared_bitmap_allocation_notifier_impl.h"
+#include "content/browser/cache_storage/cache_storage_dispatcher_host.h"
#include "content/browser/child_process_launcher.h"
#include "content/browser/dom_storage/session_storage_namespace_impl.h"
#include "content/browser/renderer_host/frame_sink_provider_impl.h"
@@ -37,11 +42,12 @@
#include "content/common/renderer.mojom.h"
#include "content/common/renderer_host.mojom.h"
#include "content/common/storage_partition_service.mojom.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/service_manager_connection.h"
#include "ipc/ipc_channel_proxy.h"
#include "ipc/ipc_platform_file.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "mojo/edk/embedder/outgoing_broker_client_invitation.h"
#include "mojo/public/cpp/bindings/associated_binding.h"
#include "mojo/public/cpp/bindings/associated_binding_set.h"
@@ -86,6 +92,7 @@ class StoragePartition;
class StoragePartitionImpl;
#if BUILDFLAG(ENABLE_WEBRTC)
+class MediaStreamTrackMetricsHost;
class P2PSocketDispatcherHost;
#endif
@@ -119,19 +126,10 @@ class CONTENT_EXPORT RenderProcessHostImpl
public mojom::AssociatedInterfaceProvider,
public mojom::RendererHost {
public:
- // Use the spare RenderProcessHost if it exists, or create a new one. This
- // should be the usual way to get a new RenderProcessHost.
- // If |storage_partition_impl| is null, the default partition from the
- // browser_context is used, using |site_instance| (for which a null value is
- // legal).
- static RenderProcessHost* CreateOrUseSpareRenderProcessHost(
- BrowserContext* browser_context,
- StoragePartitionImpl* storage_partition_impl,
- SiteInstance* site_instance,
- bool is_for_guests_only);
+ // Special depth used when there are no PriorityClients.
+ static const unsigned int kMaxFrameDepthForPriority;
- // Create a new RenderProcessHost. In most cases
- // CreateOrUseSpareRenderProcessHost, above, should be used instead.
+ // Create a new RenderProcessHost.
// If |storage_partition_impl| is null, the default partition from the
// browser_context is used, using |site_instance| (for which a null value is
// legal). |site_instance| is not used if |storage_partition_impl| is not
@@ -153,12 +151,12 @@ class CONTENT_EXPORT RenderProcessHostImpl
void AddObserver(RenderProcessHostObserver* observer) override;
void RemoveObserver(RenderProcessHostObserver* observer) override;
void ShutdownForBadMessage(CrashReportMode crash_report_mode) override;
- void WidgetRestored() override;
- void WidgetHidden() override;
- int VisibleWidgetCount() const override;
+ void UpdateClientPriority(PriorityClient* client) override;
+ int VisibleClientCount() const override;
+ unsigned int GetFrameDepthForTesting() const override;
bool IsForGuestsOnly() const override;
StoragePartition* GetStoragePartition() const override;
- bool Shutdown(int exit_code, bool wait) override;
+ bool Shutdown(int exit_code) override;
bool FastShutdownIfPossible(size_t page_count = 0,
bool skip_unload_handlers = false) override;
base::ProcessHandle GetHandle() const override;
@@ -175,9 +173,7 @@ class CONTENT_EXPORT RenderProcessHostImpl
void AddWidget(RenderWidgetHost* widget) override;
void RemoveWidget(RenderWidgetHost* widget) override;
#if defined(OS_ANDROID)
- void UpdateWidgetImportance(ChildProcessImportance old_value,
- ChildProcessImportance new_value) override;
- ChildProcessImportance ComputeEffectiveImportance() override;
+ ChildProcessImportance GetEffectiveImportance() override;
#endif
void SetSuddenTerminationAllowed(bool enabled) override;
bool SuddenTerminationAllowed() const override;
@@ -196,6 +192,7 @@ class CONTENT_EXPORT RenderProcessHostImpl
bool incoming,
bool outgoing,
const WebRtcRtpPacketCallback& packet_callback) override;
+ void SetWebRtcEventLogOutput(int lid, bool enabled) override;
#endif
void ResumeDeferredNavigation(const GlobalRequestID& request_id) override;
void BindInterface(const std::string& interface_name,
@@ -205,8 +202,10 @@ class CONTENT_EXPORT RenderProcessHostImpl
override;
const base::TimeTicks& GetInitTimeForNavigationMetrics() const override;
bool IsProcessBackgrounded() const override;
- void IncrementKeepAliveRefCount() override;
- void DecrementKeepAliveRefCount() override;
+ void IncrementKeepAliveRefCount(
+ RenderProcessHost::KeepAliveClientType) override;
+ void DecrementKeepAliveRefCount(
+ RenderProcessHost::KeepAliveClientType) override;
void DisableKeepAliveRefCount() override;
bool IsKeepAliveRefCountDisabled() override;
void PurgeAndSuspend() override;
@@ -295,10 +294,25 @@ class CONTENT_EXPORT RenderProcessHostImpl
BrowserContext* browser_context,
SiteInstanceImpl* site_instance);
- // Cleanup and remove any spare renderer. This should be used when a
- // navigation has occurred or will be occurring that will not use the spare
- // renderer and resources should be cleaned up.
- static void CleanupSpareRenderProcessHost();
+ // Should be called when |browser_context| is used in a navigation.
+ //
+ // The SpareRenderProcessHostManager can decide how to respond (for example,
+ // by shutting down the spare process to conserve resources, or alternatively
+ // by making sure that the spare process belongs to the same BrowserContext as
+ // the most recent navigation).
+ static void NotifySpareManagerAboutRecentlyUsedBrowserContext(
+ BrowserContext* browser_context);
+
+ // This enum backs a histogram, so do not change the order of entries or
+ // remove entries and update enums.xml if adding new entries.
+ enum class SpareProcessMaybeTakeAction {
+ kNoSparePresent = 0,
+ kMismatchedBrowserContext = 1,
+ kMismatchedStoragePartition = 2,
+ kRefusedByEmbedder = 3,
+ kSpareTaken = 4,
+ kMaxValue = kSpareTaken
+ };
static base::MessageLoop* GetInProcessRendererThreadForTesting();
@@ -384,10 +398,24 @@ class CONTENT_EXPORT RenderProcessHostImpl
// globally-used spare RenderProcessHost at any time.
static RenderProcessHost* GetSpareRenderProcessHostForTesting();
+ // Discards the spare RenderProcessHost. After this call,
+ // GetSpareRenderProcessHostForTesting will return nullptr.
+ static void DiscardSpareRenderProcessHostForTesting();
+
+ // Returns true if a spare RenderProcessHost should be kept at all times.
+ static bool IsSpareProcessKeptAtAllTimes();
+
PermissionServiceContext& permission_service_context() {
return *permission_service_context_;
}
+ bool is_initialized() const { return is_initialized_; }
+
+ // Binds Mojo request to Mojo implementation CacheStorageDispatcherHost
+ // instance, binding is sent to IO thread.
+ void BindCacheStorage(blink::mojom::CacheStorageRequest request,
+ const url::Origin& origin);
+
protected:
// A proxy for our IPC::Channel that lives on the IO thread.
std::unique_ptr<IPC::ChannelProxy> channel_;
@@ -485,6 +513,10 @@ class CONTENT_EXPORT RenderProcessHostImpl
const base::CommandLine& browser_cmd,
base::CommandLine* renderer_cmd);
+ // Recompute |visible_clients_| and |effective_importance_| from
+ // |priority_clients_|.
+ void UpdateProcessPriorityInputs();
+
// Inspects the current object state and sets/removes background priority if
// appropriate. Should be called after any of the involved data members
// change.
@@ -499,15 +531,35 @@ class CONTENT_EXPORT RenderProcessHostImpl
// Handle termination of our process.
void ProcessDied(bool already_dead, RendererClosedDetails* known_details);
+ // Destroy all objects that can cause methods to be invoked on this object or
+ // any other that hang off it.
+ void ResetIPC();
+
// GpuSwitchingObserver implementation.
void OnGpuSwitched() override;
+ void RecordKeepAliveDuration(RenderProcessHost::KeepAliveClientType,
+ base::TimeTicks start,
+ base::TimeTicks end);
+
// Returns the default subframe RenderProcessHost to use for |site_instance|.
static RenderProcessHost* GetDefaultSubframeProcessHost(
BrowserContext* browser_context,
SiteInstanceImpl* site_instance,
bool is_for_guests_only);
+ // Get an existing RenderProcessHost associated with the given browser
+ // context, if possible. The renderer process is chosen randomly from
+ // suitable renderers that share the same context and type (determined by the
+ // site url).
+ // Returns nullptr if no suitable renderer process is available, in which case
+ // the caller is free to create a new renderer.
+ static RenderProcessHost* GetExistingProcessHost(
+ content::BrowserContext* browser_context,
+ const GURL& site_url);
+ FRIEND_TEST_ALL_PREFIXES(RenderProcessHostUnitTest,
+ GuestsAreNotSuitableHosts);
+
// Returns a RenderProcessHost that is rendering |site_url| in one of its
// frames, or that is expecting a navigation to |site_url|.
static RenderProcessHost* FindReusableProcessHostForSite(
@@ -518,6 +570,9 @@ class CONTENT_EXPORT RenderProcessHostImpl
void CreateMediaStreamDispatcherHost(
MediaStreamManager* media_stream_manager,
mojom::MediaStreamDispatcherHostRequest request);
+ void CreateMediaStreamTrackMetricsHost(
+ mojom::MediaStreamTrackMetricsHostRequest request);
+
void OnRegisterAecDumpConsumer(int id);
void OnUnregisterAecDumpConsumer(int id);
void RegisterAecDumpConsumerOnUIThread(int id);
@@ -576,6 +631,12 @@ class CONTENT_EXPORT RenderProcessHostImpl
size_t keep_alive_ref_count_;
+ // TODO(panicker): Remove these after investigation in
+ // https://crbug.com/823482.
+ static const size_t kNumKeepAliveClients = 3;
+ size_t keep_alive_client_count_[kNumKeepAliveClients];
+ base::TimeTicks keep_alive_client_start_time_[kNumKeepAliveClients];
+
// Set in DisableKeepAliveRefCount(). When true, |keep_alive_ref_count_| must
// no longer be modified.
bool is_keep_alive_ref_count_disabled_;
@@ -597,19 +658,24 @@ class CONTENT_EXPORT RenderProcessHostImpl
mojo::AssociatedBindingSet<mojom::AssociatedInterfaceProvider, int32_t>
associated_interface_provider_bindings_;
- // The count of currently visible widgets. Since the host can be a container
- // for multiple widgets, it uses this count to determine when it should be
- // backgrounded.
- int32_t visible_widgets_;
-
+ // These fields are cached values that are updated in
+ // UpdateProcessPriorityInputs, and are used to compute priority sent to
+ // ChildProcessLauncher.
+ // |visible_clients_| is the count of currently visible clients.
+ int32_t visible_clients_;
+ // |frame_depth_| can be used to rank processes of the same visibility, ie it
+ // is the lowest depth of all visible clients, or if there are no visible
+ // widgets the lowest depth of all hidden clients. Initialized to max depth
+ // when there are no clients.
+ unsigned int frame_depth_ = kMaxFrameDepthForPriority;
#if defined(OS_ANDROID)
- // Track count of number of widgets with each possible ChildProcessImportance
- // value.
- int32_t widget_importance_counts_[static_cast<size_t>(
- ChildProcessImportance::COUNT)] = {0};
-
+ // Highest importance of all clients that contribute priority.
+ ChildProcessImportance effective_importance_ = ChildProcessImportance::NORMAL;
#endif
+ // Clients that contribute priority to this proces.
+ base::flat_set<PriorityClient*> priority_clients_;
+
// The set of widgets in this RenderProcessHostImpl.
std::set<RenderWidgetHostImpl*> widgets_;
@@ -714,6 +780,9 @@ class CONTENT_EXPORT RenderProcessHostImpl
scoped_refptr<base::SequencedTaskRunner>
audio_debug_recordings_file_task_runner_;
+
+ std::unique_ptr<MediaStreamTrackMetricsHost, BrowserThread::DeleteOnIOThread>
+ media_stream_track_metrics_host_;
#endif
// Forwards messages between WebRTCInternals in the browser process
@@ -735,6 +804,8 @@ class CONTENT_EXPORT RenderProcessHostImpl
std::unique_ptr<IndexedDBDispatcherHost, BrowserThread::DeleteOnIOThread>
indexed_db_factory_;
+ scoped_refptr<CacheStorageDispatcherHost> cache_storage_dispatcher_host_;
+
bool channel_connected_;
bool sent_render_process_ready_;
diff --git a/chromium/content/browser/renderer_host/render_process_host_unittest.cc b/chromium/content/browser/renderer_host/render_process_host_unittest.cc
index 567ea5384c2..1ed8e6caccc 100644
--- a/chromium/content/browser/renderer_host/render_process_host_unittest.cc
+++ b/chromium/content/browser/renderer_host/render_process_host_unittest.cc
@@ -9,7 +9,9 @@
#include <vector>
#include "base/command_line.h"
-#include "base/memory/ptr_util.h"
+#include "base/macros.h"
+#include "base/run_loop.h"
+#include "base/test/histogram_tester.h"
#include "build/build_config.h"
#include "content/common/frame_messages.h"
#include "content/common/frame_owner_properties.h"
@@ -25,7 +27,8 @@
#include "content/test/test_render_frame_host.h"
#include "content/test/test_render_view_host.h"
#include "content/test/test_web_contents.h"
-#include "third_party/WebKit/public/common/frame/frame_policy.h"
+#include "testing/gmock/include/gmock/gmock.h"
+#include "third_party/blink/public/common/frame/frame_policy.h"
namespace content {
@@ -43,9 +46,8 @@ TEST_F(RenderProcessHostUnitTest, GuestsAreNotSuitableHosts) {
&guest_host, browser_context(), test_url));
EXPECT_TRUE(RenderProcessHostImpl::IsSuitableHost(
process(), browser_context(), test_url));
- EXPECT_EQ(
- process(),
- RenderProcessHost::GetExistingProcessHost(browser_context(), test_url));
+ EXPECT_EQ(process(), RenderProcessHostImpl::GetExistingProcessHost(
+ browser_context(), test_url));
}
#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
@@ -249,6 +251,9 @@ TEST_F(RenderProcessHostUnitTest,
ContentBrowserClient* regular_client =
SetBrowserClientForTesting(&modified_client);
+ // Discard the spare, so it cannot be considered by the GetProcess call below.
+ RenderProcessHostImpl::DiscardSpareRenderProcessHostForTesting();
+
// Now, getting a RenderProcessHost for a navigation to the same site should
// not reuse the unmatched service worker's process (i.e., |sw_host|), as
// it's unsuitable.
@@ -426,7 +431,8 @@ TEST_F(RenderProcessHostUnitTest, DoNotReuseHostThatIsNeverSuitableForReuse) {
}
// Tests that RenderProcessHost reuse considers navigations correctly.
-TEST_F(RenderProcessHostUnitTest, ReuseNavigationProcess) {
+// Disabled for flakiness: see https://crbug.com/826595
+TEST_F(RenderProcessHostUnitTest, DISABLED_ReuseNavigationProcess) {
const GURL kUrl1("http://foo.com");
const GURL kUrl2("http://bar.com");
@@ -883,19 +889,37 @@ TEST_F(RenderProcessHostUnitTest,
}
class SpareRenderProcessHostUnitTest : public RenderViewHostImplTestHarness {
+ public:
+ SpareRenderProcessHostUnitTest() {}
+
protected:
void SetUp() override {
SetRenderProcessHostFactory(&rph_factory_);
RenderViewHostImplTestHarness::SetUp();
SetContents(nullptr); // Start with no renderers.
+ RenderProcessHostImpl::DiscardSpareRenderProcessHostForTesting();
while (!rph_factory_.GetProcesses()->empty()) {
rph_factory_.Remove(rph_factory_.GetProcesses()->back().get());
}
}
MockRenderProcessHostFactory rph_factory_;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(SpareRenderProcessHostUnitTest);
};
+using SpareProcessMaybeTakeAction =
+ RenderProcessHostImpl::SpareProcessMaybeTakeAction;
+void ExpectSpareProcessMaybeTakeActionBucket(
+ const base::HistogramTester& histograms,
+ SpareProcessMaybeTakeAction expected_action) {
+ EXPECT_THAT(
+ histograms.GetAllSamples(
+ "BrowserRenderProcessHost.SpareProcessMaybeTakeAction"),
+ testing::ElementsAre(base::Bucket(static_cast<int>(expected_action), 1)));
+}
+
TEST_F(SpareRenderProcessHostUnitTest, TestRendererTaken) {
RenderProcessHost::WarmupSpareRenderProcessHost(browser_context());
ASSERT_EQ(1U, rph_factory_.GetProcesses()->size());
@@ -904,24 +928,183 @@ TEST_F(SpareRenderProcessHostUnitTest, TestRendererTaken) {
EXPECT_EQ(spare_rph, rph_factory_.GetProcesses()->at(0).get());
const GURL kUrl1("http://foo.com");
+ base::HistogramTester histograms;
SetContents(CreateTestWebContents());
NavigateAndCommit(kUrl1);
EXPECT_EQ(spare_rph, main_test_rfh()->GetProcess());
- ASSERT_EQ(1U, rph_factory_.GetProcesses()->size());
+ ExpectSpareProcessMaybeTakeActionBucket(
+ histograms, SpareProcessMaybeTakeAction::kSpareTaken);
+
+ EXPECT_NE(spare_rph,
+ RenderProcessHostImpl::GetSpareRenderProcessHostForTesting());
+ if (RenderProcessHostImpl::IsSpareProcessKeptAtAllTimes()) {
+ EXPECT_NE(nullptr,
+ RenderProcessHostImpl::GetSpareRenderProcessHostForTesting());
+ EXPECT_EQ(2U, rph_factory_.GetProcesses()->size());
+ } else {
+ EXPECT_EQ(nullptr,
+ RenderProcessHostImpl::GetSpareRenderProcessHostForTesting());
+ EXPECT_EQ(1U, rph_factory_.GetProcesses()->size());
+ }
}
TEST_F(SpareRenderProcessHostUnitTest, TestRendererNotTaken) {
std::unique_ptr<BrowserContext> alternate_context(new TestBrowserContext());
RenderProcessHost::WarmupSpareRenderProcessHost(alternate_context.get());
ASSERT_EQ(1U, rph_factory_.GetProcesses()->size());
+ RenderProcessHost* old_spare =
+ RenderProcessHostImpl::GetSpareRenderProcessHostForTesting();
+ EXPECT_EQ(alternate_context.get(), old_spare->GetBrowserContext());
+ EXPECT_EQ(old_spare, rph_factory_.GetProcesses()->at(0).get());
+
+ const GURL kUrl1("http://foo.com");
+ base::HistogramTester histograms;
+ SetContents(CreateTestWebContents());
+ NavigateAndCommit(kUrl1);
+ EXPECT_NE(old_spare, main_test_rfh()->GetProcess());
+ ExpectSpareProcessMaybeTakeActionBucket(
+ histograms, SpareProcessMaybeTakeAction::kMismatchedBrowserContext);
+
+ // Pumping the message loop here accounts for the delay between calling
+ // RPH::Cleanup on the spare and the time when the posted delete actually
+ // happens. Without pumping, the spare would still be present in
+ // rph_factory_.GetProcesses().
+ base::RunLoop().RunUntilIdle();
+
+ RenderProcessHost* new_spare =
+ RenderProcessHostImpl::GetSpareRenderProcessHostForTesting();
+ EXPECT_NE(old_spare, new_spare);
+ if (RenderProcessHostImpl::IsSpareProcessKeptAtAllTimes()) {
+ EXPECT_EQ(2U, rph_factory_.GetProcesses()->size());
+ ASSERT_NE(nullptr, new_spare);
+ EXPECT_EQ(GetBrowserContext(), new_spare->GetBrowserContext());
+ } else {
+ EXPECT_EQ(1U, rph_factory_.GetProcesses()->size());
+ EXPECT_EQ(nullptr, new_spare);
+ }
+}
+
+TEST_F(SpareRenderProcessHostUnitTest, SpareMissing) {
+ RenderProcessHostImpl::DiscardSpareRenderProcessHostForTesting();
+ ASSERT_EQ(0U, rph_factory_.GetProcesses()->size());
RenderProcessHost* spare_rph =
RenderProcessHostImpl::GetSpareRenderProcessHostForTesting();
- EXPECT_EQ(spare_rph, rph_factory_.GetProcesses()->at(0).get());
+ EXPECT_FALSE(spare_rph);
const GURL kUrl1("http://foo.com");
+ base::HistogramTester histograms;
SetContents(CreateTestWebContents());
NavigateAndCommit(kUrl1);
- EXPECT_NE(spare_rph, main_test_rfh()->GetProcess());
+ EXPECT_TRUE(main_test_rfh()->GetProcess());
+ ExpectSpareProcessMaybeTakeActionBucket(
+ histograms, SpareProcessMaybeTakeAction::kNoSparePresent);
+
+ spare_rph = RenderProcessHostImpl::GetSpareRenderProcessHostForTesting();
+ if (RenderProcessHostImpl::IsSpareProcessKeptAtAllTimes()) {
+ EXPECT_TRUE(spare_rph);
+ EXPECT_EQ(2U, rph_factory_.GetProcesses()->size());
+ } else {
+ EXPECT_FALSE(spare_rph);
+ EXPECT_EQ(1U, rph_factory_.GetProcesses()->size());
+ }
+}
+
+TEST_F(SpareRenderProcessHostUnitTest,
+ SpareShouldNotLaunchInParallelWithOtherProcess) {
+ std::unique_ptr<BrowserContext> alternate_context(new TestBrowserContext());
+ RenderProcessHost::WarmupSpareRenderProcessHost(alternate_context.get());
+ ASSERT_EQ(1U, rph_factory_.GetProcesses()->size());
+ RenderProcessHost* old_spare =
+ RenderProcessHostImpl::GetSpareRenderProcessHostForTesting();
+ EXPECT_EQ(alternate_context.get(), old_spare->GetBrowserContext());
+ EXPECT_EQ(old_spare, rph_factory_.GetProcesses()->at(0).get());
+
+ // When we try to get a process for foo.com, we won't be able to use the spare
+ // (because it is associated with the alternate, mismatched BrowserContext)
+ // and therefore we will have to spawn a new process. This test verifies that
+ // we don't at the same time try to warm-up a new spare (leading to
+ // unnecessary resource contention when 2 processes try to launch at the same
+ // time).
+ scoped_refptr<SiteInstanceImpl> site_instance =
+ SiteInstanceImpl::CreateForURL(browser_context(), GURL("http://foo.com"));
+ RenderProcessHost* site_instance_process = site_instance->GetProcess();
+ // We need to ensure the MockRenderProcessHost gets destroyed at the end of
+ // the test.
+ std::unique_ptr<MockRenderProcessHost> owned_mock_process(
+ static_cast<MockRenderProcessHost*>(site_instance_process));
+
+ // The SiteInstance shouldn't get the old spare, because of BrowserContext
+ // mismatch. The SiteInstance will get a new process instead.
+ EXPECT_NE(old_spare, site_instance_process);
+ EXPECT_FALSE(site_instance_process->IsReady());
+
+ // There should be no new spare at this point to avoid launching 2 processes
+ // at the same time. Note that the spare might still be created later during
+ // a navigation (e.g. after cross-site redirects or when committing).
+ RenderProcessHost* new_spare =
+ RenderProcessHostImpl::GetSpareRenderProcessHostForTesting();
+ if (new_spare != old_spare)
+ EXPECT_FALSE(new_spare);
+}
+
+// This unit test looks at the simplified equivalent of what
+// CtrlClickShouldEndUpInSameProcessTest.BlankTarget test would have
+// encountered. The test verifies that the spare RPH is not launched if 1) we
+// need to create another renderer process anyway (e.g. because the spare is
+// missing when MaybeTakeSpareRenderProcessHost is called) and 2) creating the
+// other renderer process will put as at the process limit. Launching the spare
+// in this scenario would put us over the process limit and is therefore
+// undesirable.
+TEST_F(SpareRenderProcessHostUnitTest, JustBelowProcessLimit) {
+ RenderProcessHostImpl::SetMaxRendererProcessCount(1);
+
+ // No spare or any other renderer process at the start of the test.
+ EXPECT_FALSE(RenderProcessHostImpl::GetSpareRenderProcessHostForTesting());
+ EXPECT_EQ(0U, rph_factory_.GetProcesses()->size());
+
+ // Navigation can't take a spare (none present) and needs to launch a new
+ // renderer process.
+ const GURL kUrl1("http://foo.com");
+ SetContents(CreateTestWebContents());
+ NavigateAndCommit(kUrl1);
+
+ // We should still be below the process limit.
+ EXPECT_EQ(1U, rph_factory_.GetProcesses()->size());
+
+ // There should be no spare - having one would put us over the process limit.
+ EXPECT_FALSE(RenderProcessHostImpl::GetSpareRenderProcessHostForTesting());
+}
+
+// This unit test verifies that a mismatched spare RenderProcessHost is dropped
+// before considering process reuse due to the process limit.
+TEST_F(SpareRenderProcessHostUnitTest, AtProcessLimit) {
+ RenderProcessHostImpl::SetMaxRendererProcessCount(2);
+
+ // Create and navigate the 1st WebContents.
+ const GURL kUrl1("http://foo.com");
+ std::unique_ptr<WebContents> contents1(CreateTestWebContents());
+ static_cast<TestWebContents*>(contents1.get())->NavigateAndCommit(kUrl1);
+ EXPECT_NE(RenderProcessHostImpl::GetSpareRenderProcessHostForTesting(),
+ contents1->GetMainFrame()->GetProcess());
+
+ // Warm up a mismatched spare.
+ std::unique_ptr<BrowserContext> alternate_context(new TestBrowserContext());
+ RenderProcessHost::WarmupSpareRenderProcessHost(alternate_context.get());
+ base::RunLoop().RunUntilIdle();
+ EXPECT_EQ(2U, rph_factory_.GetProcesses()->size());
+
+ // Create and navigate the 2nd WebContents.
+ const GURL kUrl2("http://bar.com");
+ std::unique_ptr<WebContents> contents2(CreateTestWebContents());
+ static_cast<TestWebContents*>(contents2.get())->NavigateAndCommit(kUrl2);
+ base::RunLoop().RunUntilIdle();
+
+ // Creating a 2nd WebContents shouldn't share a renderer process with the 1st
+ // one - instead the spare should be dropped to stay under the process limit.
+ EXPECT_EQ(2U, rph_factory_.GetProcesses()->size());
+ EXPECT_FALSE(RenderProcessHostImpl::GetSpareRenderProcessHostForTesting());
+ EXPECT_NE(contents1->GetMainFrame()->GetProcess(),
+ contents2->GetMainFrame()->GetProcess());
}
} // namespace content
diff --git a/chromium/content/browser/renderer_host/render_view_host_delegate.h b/chromium/content/browser/renderer_host/render_view_host_delegate.h
index 9b01a0dd1e0..cec02574757 100644
--- a/chromium/content/browser/renderer_host/render_view_host_delegate.h
+++ b/chromium/content/browser/renderer_host/render_view_host_delegate.h
@@ -16,7 +16,7 @@
#include "content/common/content_export.h"
#include "content/common/render_message_filter.mojom.h"
#include "net/base/load_states.h"
-#include "third_party/WebKit/public/web/WebPopupType.h"
+#include "third_party/blink/public/web/web_popup_type.h"
class GURL;
diff --git a/chromium/content/browser/renderer_host/render_view_host_delegate_view.h b/chromium/content/browser/renderer_host/render_view_host_delegate_view.h
index 2576982a65e..62e97446fb0 100644
--- a/chromium/content/browser/renderer_host/render_view_host_delegate_view.h
+++ b/chromium/content/browser/renderer_host/render_view_host_delegate_view.h
@@ -9,11 +9,11 @@
#include "base/callback.h"
#include "build/build_config.h"
+#include "content/common/buildflags.h"
#include "content/common/content_export.h"
#include "content/common/drag_event_source_info.h"
-#include "content/common/features.h"
#include "content/public/common/input_event_ack_state.h"
-#include "third_party/WebKit/public/platform/WebDragOperation.h"
+#include "third_party/blink/public/platform/web_drag_operation.h"
namespace blink {
class WebGestureEvent;
diff --git a/chromium/content/browser/renderer_host/render_view_host_impl.cc b/chromium/content/browser/renderer_host/render_view_host_impl.cc
index 8f51f51ebf7..ff1e068349c 100644
--- a/chromium/content/browser/renderer_host/render_view_host_impl.cc
+++ b/chromium/content/browser/renderer_host/render_view_host_impl.cc
@@ -58,6 +58,7 @@
#include "content/public/browser/browser_accessibility_state.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_message_filter.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "content/public/browser/notification_details.h"
@@ -228,6 +229,9 @@ RenderViewHostImpl::RenderViewHostImpl(
// make their way to the new renderer once its restarted.
GetProcess()->EnableSendQueue();
+ if (!is_active_)
+ GetWidget()->UpdatePriority();
+
if (ResourceDispatcherHostImpl::Get()) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
@@ -360,6 +364,13 @@ bool RenderViewHostImpl::CreateRenderView(
return true;
}
+void RenderViewHostImpl::SetIsActive(bool is_active) {
+ if (is_active_ == is_active)
+ return;
+ is_active_ = is_active;
+ GetWidget()->UpdatePriority();
+}
+
bool RenderViewHostImpl::IsRenderViewLive() const {
return GetProcess()->HasConnection() && GetWidget()->renderer_initialized();
}
@@ -425,6 +436,9 @@ WebPreferences RenderViewHostImpl::ComputeWebkitPrefs() {
prefs.history_entry_requires_user_gesture =
command_line.HasSwitch(switches::kHistoryEntryRequiresUserGesture);
+ prefs.disable_pushstate_throttle =
+ command_line.HasSwitch(switches::kDisablePushStateThrottle);
+
#if defined(OS_ANDROID)
prefs.use_solid_color_scrollbars = true;
#endif // defined(OS_ANDROID)
@@ -548,6 +562,11 @@ WebPreferences RenderViewHostImpl::ComputeWebkitPrefs() {
prefs.background_video_track_optimization_enabled =
base::FeatureList::IsEnabled(media::kBackgroundVideoTrackOptimization);
+ if (base::FeatureList::IsEnabled(media::kUseSurfaceLayerForVideo) &&
+ base::FeatureList::IsEnabled(media::kPictureInPicture)) {
+ prefs.picture_in_picture_enabled = true;
+ }
+
GetContentClient()->browser()->OverrideWebkitPrefs(this, &prefs);
return prefs;
}
@@ -891,6 +910,10 @@ bool RenderViewHostImpl::MayRenderWidgetForwardKeyboardEvent(
return true;
}
+bool RenderViewHostImpl::ShouldContributePriorityToProcess() {
+ return is_active_;
+}
+
WebPreferences RenderViewHostImpl::GetWebkitPreferences() {
if (!web_preferences_.get()) {
OnWebkitPreferencesChanged();
@@ -925,23 +948,6 @@ void RenderViewHostImpl::EnablePreferredSizeMode() {
Send(new ViewMsg_EnablePreferredSizeChangedMode(GetRoutingID()));
}
-void RenderViewHostImpl::EnableAutoResize(const gfx::Size& min_size,
- const gfx::Size& max_size) {
- GetWidget()->SetAutoResize(true, min_size, max_size);
- Send(new ViewMsg_EnableAutoResize(GetRoutingID(), min_size, max_size));
-}
-
-void RenderViewHostImpl::DisableAutoResize(const gfx::Size& new_size) {
- GetWidget()->SetAutoResize(false, gfx::Size(), gfx::Size());
- Send(new ViewMsg_DisableAutoResize(GetRoutingID(), new_size));
- if (!new_size.IsEmpty())
- GetWidget()->GetView()->SetSize(new_size);
- // This clears the cached value in the WebContents, so that OOPIFs will
- // stop using it.
- if (GetWidget()->delegate())
- GetWidget()->delegate()->ResetAutoResizeSize();
-}
-
void RenderViewHostImpl::ExecuteMediaPlayerActionAtLocation(
const gfx::Point& location, const blink::WebMediaPlayerAction& action) {
// TODO(wjmaclean): See if coordinate transforms need to be done for OOPIFs
diff --git a/chromium/content/browser/renderer_host/render_view_host_impl.h b/chromium/content/browser/renderer_host/render_view_host_impl.h
index 0acf0d44bfd..890215a944a 100644
--- a/chromium/content/browser/renderer_host/render_view_host_impl.h
+++ b/chromium/content/browser/renderer_host/render_view_host_impl.h
@@ -29,9 +29,9 @@
#include "content/public/browser/render_process_host_observer.h"
#include "content/public/browser/render_view_host.h"
#include "net/base/load_states.h"
-#include "third_party/WebKit/public/web/WebAXEnums.h"
-#include "third_party/WebKit/public/web/WebConsoleMessage.h"
-#include "third_party/WebKit/public/web/WebPopupType.h"
+#include "third_party/blink/public/web/web_ax_enums.h"
+#include "third_party/blink/public/web/web_console_message.h"
+#include "third_party/blink/public/web/web_popup_type.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/base/mojo/window_open_disposition.mojom.h"
@@ -92,9 +92,6 @@ class CONTENT_EXPORT RenderViewHostImpl : public RenderViewHost,
int request_id,
const std::vector<base::FilePath>& files) override;
void DisableScrollbarsForThreshold(const gfx::Size& size) override;
- void EnableAutoResize(const gfx::Size& min_size,
- const gfx::Size& max_size) override;
- void DisableAutoResize(const gfx::Size& new_size) override;
void EnablePreferredSizeMode() override;
void ExecuteMediaPlayerActionAtLocation(
const gfx::Point& location,
@@ -151,7 +148,7 @@ class CONTENT_EXPORT RenderViewHostImpl : public RenderViewHost,
// pending swap out or swapped out), according to its main frame
// RenderFrameHost.
bool is_active() const { return is_active_; }
- void set_is_active(bool is_active) { is_active_ = is_active; }
+ void SetIsActive(bool is_active);
// Tracks whether this RenderViewHost is swapped out, according to its main
// frame RenderFrameHost.
@@ -241,6 +238,7 @@ class CONTENT_EXPORT RenderViewHostImpl : public RenderViewHost,
const blink::WebMouseEvent& mouse_event) override;
bool MayRenderWidgetForwardKeyboardEvent(
const NativeWebKeyboardEvent& key_event) override;
+ bool ShouldContributePriorityToProcess() override;
// IPC message handlers.
void OnShowView(int route_id,
diff --git a/chromium/content/browser/renderer_host/render_view_host_unittest.cc b/chromium/content/browser/renderer_host/render_view_host_unittest.cc
index 56d2d7c0c2f..4127d8bdf82 100644
--- a/chromium/content/browser/renderer_host/render_view_host_unittest.cc
+++ b/chromium/content/browser/renderer_host/render_view_host_unittest.cc
@@ -27,7 +27,7 @@
#include "content/test/test_render_view_host.h"
#include "content/test/test_web_contents.h"
#include "net/base/filename_util.h"
-#include "third_party/WebKit/public/platform/WebDragOperation.h"
+#include "third_party/blink/public/platform/web_drag_operation.h"
#include "ui/base/page_transition_types.h"
namespace content {
@@ -237,7 +237,7 @@ TEST_F(RenderViewHostTest, NavigationWithBadHistoryItemFiles) {
main_test_rfh()->SendRendererInitiatedNavigationRequest(url, false);
main_test_rfh()->PrepareForCommit();
contents()->GetMainFrame()->SendNavigateWithModificationCallback(
- 2, true, url, set_bad_file_path_callback);
+ 2, true, url, std::move(set_bad_file_path_callback));
EXPECT_EQ(1, process()->bad_msg_count());
}
@@ -256,8 +256,7 @@ class TestSaveImageFromDataURL : public RenderFrameMessageFilter {
0,
nullptr,
context,
- BrowserContext::GetDefaultStoragePartition(context)
- ->GetURLRequestContext(),
+ BrowserContext::GetDefaultStoragePartition(context),
nullptr) {
Reset();
}
diff --git a/chromium/content/browser/renderer_host/render_widget_helper.h b/chromium/content/browser/renderer_host/render_widget_helper.h
index a6e185c121a..1fcb3097084 100644
--- a/chromium/content/browser/renderer_host/render_widget_helper.h
+++ b/chromium/content/browser/renderer_host/render_widget_helper.h
@@ -18,7 +18,7 @@
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/global_request_id.h"
-#include "third_party/WebKit/public/web/WebPopupType.h"
+#include "third_party/blink/public/web/web_popup_type.h"
#include "ui/gfx/native_widget_types.h"
namespace content {
diff --git a/chromium/content/browser/renderer_host/render_widget_host_delegate.cc b/chromium/content/browser/renderer_host/render_widget_host_delegate.cc
index 23afbb78a96..b41e5f828d2 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_delegate.cc
+++ b/chromium/content/browser/renderer_host/render_widget_host_delegate.cc
@@ -74,6 +74,15 @@ RenderWidgetHostImpl* RenderWidgetHostDelegate::GetMouseLockWidget() {
return nullptr;
}
+bool RenderWidgetHostDelegate::RequestKeyboardLock(RenderWidgetHostImpl* host,
+ bool esc_key_locked) {
+ return false;
+}
+
+RenderWidgetHostImpl* RenderWidgetHostDelegate::GetKeyboardLockWidget() {
+ return nullptr;
+}
+
TextInputManager* RenderWidgetHostDelegate::GetTextInputManager() {
return nullptr;
}
diff --git a/chromium/content/browser/renderer_host/render_widget_host_delegate.h b/chromium/content/browser/renderer_host/render_widget_host_delegate.h
index 4f6068ea17f..680b1e81320 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_delegate.h
+++ b/chromium/content/browser/renderer_host/render_widget_host_delegate.h
@@ -7,6 +7,7 @@
#include <stdint.h>
+#include <string>
#include <vector>
#include "build/build_config.h"
@@ -14,9 +15,9 @@
#include "content/common/drag_event_source_info.h"
#include "content/public/common/drop_data.h"
#include "services/metrics/public/cpp/ukm_recorder.h"
-#include "third_party/WebKit/public/platform/WebDisplayMode.h"
-#include "third_party/WebKit/public/platform/WebDragOperation.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_display_mode.h"
+#include "third_party/blink/public/platform/web_drag_operation.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/gfx/native_widget_types.h"
namespace blink {
@@ -95,12 +96,10 @@ class CONTENT_EXPORT RenderWidgetHostDelegate {
// the event itself.
virtual bool HandleWheelEvent(const blink::WebMouseWheelEvent& event);
- // Notification the user has performed a direct interaction (mouse down,
- // scroll, raw key down, gesture tap, or browser-initiated navigation) while
- // focus was on the page. Informs the delegate that a user is interacting with
- // a site.
- virtual void OnUserInteraction(RenderWidgetHostImpl* render_widget_host,
- const blink::WebInputEvent::Type type) {}
+ // Notification that an input event from the user was dispatched to the
+ // widget.
+ virtual void DidReceiveInputEvent(RenderWidgetHostImpl* render_widget_host,
+ const blink::WebInputEvent::Type type) {}
// Callback to give the browser a chance to handle the specified gesture
// event before sending it to the renderer.
@@ -193,6 +192,18 @@ class CONTENT_EXPORT RenderWidgetHostDelegate {
// locked.
virtual RenderWidgetHostImpl* GetMouseLockWidget();
+ // Requests to lock the keyboard. Once the request is approved or rejected,
+ // GotResponseToKeyboardLockRequest() will be called on the requesting render
+ // widget host.
+ virtual bool RequestKeyboardLock(RenderWidgetHostImpl* render_widget_host,
+ bool esc_key_locked);
+
+ // Cancels a previous keyboard lock request.
+ virtual void CancelKeyboardLock(RenderWidgetHostImpl* render_widget_host) {}
+
+ // Returns the widget that holds the keyboard lock or nullptr if not locked.
+ virtual RenderWidgetHostImpl* GetKeyboardLockWidget();
+
// Called when the visibility of the RenderFrameProxyHost in outer
// WebContents changes. This method is only called on an inner WebContents and
// will eventually notify all the RenderWidgetHostViews belonging to that
diff --git a/chromium/content/browser/renderer_host/render_widget_host_impl.cc b/chromium/content/browser/renderer_host/render_widget_host_impl.cc
index 77c870b8a07..97ca37d843b 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_impl.cc
+++ b/chromium/content/browser/renderer_host/render_widget_host_impl.cc
@@ -6,6 +6,7 @@
#include <math.h>
+#include <algorithm>
#include <set>
#include <tuple>
#include <utility>
@@ -19,7 +20,6 @@
#include "base/lazy_instance.h"
#include "base/location.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/shared_memory.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/field_trial.h"
@@ -29,6 +29,7 @@
#include "base/strings/utf_string_conversions.h"
#include "base/task_scheduler/post_task.h"
#include "base/threading/thread_task_runner_handle.h"
+#include "base/time/default_tick_clock.h"
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
#include "cc/base/switches.h"
@@ -57,8 +58,6 @@
#include "content/browser/renderer_host/input/synthetic_gesture_target.h"
#include "content/browser/renderer_host/input/timeout_monitor.h"
#include "content/browser/renderer_host/input/touch_emulator.h"
-#include "content/browser/renderer_host/render_frame_metadata_provider_impl.h"
-#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/renderer_host/render_view_host_delegate.h"
#include "content/browser/renderer_host/render_view_host_delegate_view.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
@@ -76,6 +75,7 @@
#include "content/common/text_input_state.h"
#include "content/common/view_messages.h"
#include "content/public/browser/browser_context.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/keyboard_event_processing_result.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "content/public/browser/notification_service.h"
@@ -97,13 +97,16 @@
#include "skia/ext/image_operations.h"
#include "skia/ext/platform_canvas.h"
#include "storage/browser/fileapi/isolated_context.h"
-#include "third_party/WebKit/public/web/WebImeTextSpan.h"
+#include "third_party/blink/public/web/web_ime_text_span.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/base/ui_base_switches.h"
#include "ui/display/display_switches.h"
#include "ui/display/screen.h"
#include "ui/events/blink/web_input_event_traits.h"
#include "ui/events/event.h"
+#include "ui/events/keycodes/dom/dom_code.h"
+#include "ui/events/keycodes/dom/keycode_converter.h"
+#include "ui/events/keycodes/keyboard_code_conversion.h"
#include "ui/events/keycodes/keyboard_codes.h"
#include "ui/gfx/color_space.h"
#include "ui/gfx/geometry/size_conversions.h"
@@ -189,8 +192,7 @@ inline blink::WebGestureEvent CreateScrollBeginForWrapping(
blink::WebGestureEvent wrap_gesture_scroll_begin(
blink::WebInputEvent::kGestureScrollBegin, gesture_event.GetModifiers(),
- gesture_event.TimeStampSeconds());
- wrap_gesture_scroll_begin.source_device = gesture_event.source_device;
+ gesture_event.TimeStampSeconds(), gesture_event.SourceDevice());
wrap_gesture_scroll_begin.data.scroll_begin.delta_x_hint = 0;
wrap_gesture_scroll_begin.data.scroll_begin.delta_y_hint = 0;
wrap_gesture_scroll_begin.resending_plugin_id =
@@ -207,8 +209,7 @@ inline blink::WebGestureEvent CreateScrollEndForWrapping(
blink::WebGestureEvent wrap_gesture_scroll_end(
blink::WebInputEvent::kGestureScrollEnd, gesture_event.GetModifiers(),
- gesture_event.TimeStampSeconds());
- wrap_gesture_scroll_end.source_device = gesture_event.source_device;
+ gesture_event.TimeStampSeconds(), gesture_event.SourceDevice());
wrap_gesture_scroll_end.resending_plugin_id =
gesture_event.resending_plugin_id;
wrap_gesture_scroll_end.data.scroll_end.delta_units =
@@ -338,6 +339,7 @@ RenderWidgetHostImpl::RenderWidgetHostImpl(RenderWidgetHostDelegate* delegate,
owner_delegate_(nullptr),
process_(process),
routing_id_(routing_id),
+ clock_(base::DefaultTickClock::GetInstance()),
is_loading_(false),
is_hidden_(hidden),
repaint_ack_pending_(false),
@@ -362,15 +364,15 @@ RenderWidgetHostImpl::RenderWidgetHostImpl(RenderWidgetHostDelegate* delegate,
next_browser_snapshot_id_(1),
owned_by_render_frame_host_(false),
is_focused_(false),
- hung_renderer_delay_(
- base::TimeDelta::FromMilliseconds(kHungRendererDelayMs)),
+ hung_renderer_delay_(TimeDelta::FromMilliseconds(kHungRendererDelayMs)),
new_content_rendering_delay_(
- base::TimeDelta::FromMilliseconds(kNewContentRenderingDelayMs)),
+ TimeDelta::FromMilliseconds(kNewContentRenderingDelayMs)),
current_content_source_id_(0),
monitoring_composition_info_(false),
compositor_frame_sink_binding_(this),
frame_token_message_queue_(
std::make_unique<FrameTokenMessageQueue>(this)),
+ render_frame_metadata_provider_(frame_token_message_queue_.get()),
frame_sink_id_(base::checked_cast<uint32_t>(process_->GetID()),
base::checked_cast<uint32_t>(routing_id_)),
weak_factory_(this) {
@@ -387,11 +389,6 @@ RenderWidgetHostImpl::RenderWidgetHostImpl(RenderWidgetHostDelegate* delegate,
process_->AddWidget(this);
process_->GetSharedBitmapAllocationNotifier()->AddObserver(this);
- // If we're initially visible, tell the process host that we're alive.
- // Otherwise we'll notify the process host when we are first shown.
- if (!hidden)
- process_->WidgetRestored();
-
latency_tracker_.Initialize(routing_id_, GetProcess()->GetID());
SetupInputRouter();
@@ -482,10 +479,8 @@ void RenderWidgetHostImpl::SetView(RenderWidgetHostViewBase* view) {
if (view) {
view_ = view->GetWeakPtr();
if (enable_viz_) {
- if (!create_frame_sink_callback_.is_null()) {
- view_->CreateCompositorFrameSink(
- std::move(create_frame_sink_callback_));
- }
+ if (!create_frame_sink_callback_.is_null())
+ std::move(create_frame_sink_callback_).Run(view_->GetFrameSinkId());
} else {
if (renderer_compositor_frame_sink_.is_bound()) {
view->DidCreateNewRendererCompositorFrameSink(
@@ -551,6 +546,19 @@ void RenderWidgetHostImpl::SendScreenRects() {
waiting_for_screen_rects_ack_ = true;
}
+void RenderWidgetHostImpl::SetFrameDepth(unsigned int depth) {
+ if (frame_depth_ == depth)
+ return;
+
+ frame_depth_ = depth;
+ UpdatePriority();
+}
+
+void RenderWidgetHostImpl::UpdatePriority() {
+ if (!destroyed_)
+ process_->UpdateClientPriority(this);
+}
+
void RenderWidgetHostImpl::Init() {
DCHECK(process_->HasConnection());
@@ -575,6 +583,7 @@ void RenderWidgetHostImpl::InitForFrame() {
}
void RenderWidgetHostImpl::ShutdownAndDestroyWidget(bool also_delete) {
+ CancelKeyboardLock();
RejectMouseLockOrUnlockIfNecessary();
if (process_->HasConnection()) {
@@ -677,7 +686,7 @@ void RenderWidgetHostImpl::WasHidden() {
Send(new ViewMsg_WasHidden(routing_id_));
// Tell the RenderProcessHost we were hidden.
- process_->WidgetHidden();
+ process_->UpdateClientPriority(this);
bool is_visible = false;
NotificationService::current()->Notify(
@@ -695,11 +704,7 @@ void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) {
// If we navigated in background, clear the displayed graphics of the
// previous page before going visible.
- if (new_content_rendering_timeout_ &&
- new_content_rendering_timeout_->IsRunning()) {
- new_content_rendering_timeout_->Stop();
- ClearDisplayedGraphics();
- }
+ ForceFirstFrameAfterNavigationTimeout();
SendScreenRects();
RestartHangMonitorTimeoutIfNecessary();
@@ -709,7 +714,7 @@ void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) {
needs_repainting_on_restore_ = false;
Send(new ViewMsg_WasShown(routing_id_, needs_repainting, latency_info));
- process_->WidgetRestored();
+ process_->UpdateClientPriority(this);
bool is_visible = true;
NotificationService::current()->Notify(
@@ -739,9 +744,8 @@ void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) {
void RenderWidgetHostImpl::SetImportance(ChildProcessImportance importance) {
if (importance_ == importance)
return;
- ChildProcessImportance old = importance_;
importance_ = importance;
- process_->UpdateWidgetImportance(old, importance_);
+ process_->UpdateClientPriority(this);
}
#endif
@@ -759,6 +763,12 @@ bool RenderWidgetHostImpl::GetResizeParams(ResizeParams* resize_params) {
resize_params->display_mode = blink::kWebDisplayModeBrowser;
}
+ resize_params->auto_resize_enabled = auto_resize_enabled_;
+ resize_params->min_size_for_auto_resize = min_size_for_auto_resize_;
+ resize_params->max_size_for_auto_resize = max_size_for_auto_resize_;
+ resize_params->auto_resize_sequence_number =
+ last_auto_resize_response_number_;
+
if (view_) {
resize_params->new_size = view_->GetRequestedRendererSize();
resize_params->compositor_viewport_pixel_size =
@@ -775,13 +785,7 @@ bool RenderWidgetHostImpl::GetResizeParams(ResizeParams* resize_params) {
resize_params->visible_viewport_size = view_->GetVisibleViewportSize();
// TODO(ccameron): GetLocalSurfaceId is not synchronized with the device
// scale factor of the surface. Fix this.
- // We can allocate a LocalSurfaceId on navigation prior to giving the widget
- // a size. We should only propagate a LocalSurfaceId here if the
- // compositor's viewport has a non-empty size.
- viz::LocalSurfaceId local_surface_id =
- resize_params->compositor_viewport_pixel_size.IsEmpty()
- ? viz::LocalSurfaceId()
- : view_->GetLocalSurfaceId();
+ viz::LocalSurfaceId local_surface_id = view_->GetLocalSurfaceId();
if (local_surface_id.is_valid())
resize_params->local_surface_id = local_surface_id;
}
@@ -800,9 +804,19 @@ bool RenderWidgetHostImpl::GetResizeParams(ResizeParams* resize_params) {
const bool size_changed =
!old_resize_params_ ||
- old_resize_params_->new_size != resize_params->new_size ||
- (old_resize_params_->compositor_viewport_pixel_size.IsEmpty() &&
- !resize_params->compositor_viewport_pixel_size.IsEmpty());
+ old_resize_params_->auto_resize_enabled !=
+ resize_params->auto_resize_enabled ||
+ (old_resize_params_->auto_resize_enabled &&
+ (old_resize_params_->min_size_for_auto_resize !=
+ resize_params->min_size_for_auto_resize ||
+ old_resize_params_->max_size_for_auto_resize !=
+ resize_params->max_size_for_auto_resize ||
+ old_resize_params_->auto_resize_sequence_number !=
+ resize_params->auto_resize_sequence_number)) ||
+ (!old_resize_params_->auto_resize_enabled &&
+ (old_resize_params_->new_size != resize_params->new_size ||
+ (old_resize_params_->compositor_viewport_pixel_size.IsEmpty() &&
+ !resize_params->compositor_viewport_pixel_size.IsEmpty())));
bool dirty =
size_changed ||
@@ -829,7 +843,8 @@ bool RenderWidgetHostImpl::GetResizeParams(ResizeParams* resize_params) {
// We don't expect to receive an ACK when the requested size or the physical
// backing size is empty, or when the main viewport size didn't change.
resize_params->needs_resize_ack =
- g_check_for_pending_resize_ack && !resize_params->new_size.IsEmpty() &&
+ !auto_resize_enabled_ && g_check_for_pending_resize_ack &&
+ !resize_params->new_size.IsEmpty() &&
!resize_params->compositor_viewport_pixel_size.IsEmpty() &&
(size_changed || next_resize_needs_resize_ack_) &&
(!enable_surface_synchronization_ ||
@@ -854,8 +869,8 @@ void RenderWidgetHostImpl::WasResized(bool scroll_focused_node_into_view) {
// Skip if the |delegate_| has already been detached because
// it's web contents is being deleted.
if (resize_ack_pending_ || !process_->HasConnection() || !view_ ||
- !view_->HasSize() || !renderer_initialized_ || auto_resize_enabled_ ||
- !delegate_) {
+ !view_->HasSize() || !renderer_initialized_ || !delegate_ ||
+ last_auto_resize_request_number_ != last_auto_resize_response_number_) {
return;
}
@@ -922,8 +937,13 @@ void RenderWidgetHostImpl::SetPageFocus(bool focused) {
if (IsMouseLocked())
view_->UnlockMouse();
+ if (IsKeyboardLocked())
+ UnlockKeyboard();
+
if (touch_emulator_)
touch_emulator_->CancelTouch();
+ } else if (keyboard_lock_allowed_) {
+ LockKeyboard();
}
GetWidgetInputHandler()->SetFocus(focused);
@@ -958,6 +978,7 @@ void RenderWidgetHostImpl::SendMouseLockLost() {
}
void RenderWidgetHostImpl::ViewDestroyed() {
+ CancelKeyboardLock();
RejectMouseLockOrUnlockIfNecessary();
// TODO(evanm): tracking this may no longer be necessary;
@@ -1012,7 +1033,7 @@ void RenderWidgetHostImpl::PauseForPendingResizeOrRepaints() {
// Pump a nested run loop until we time out or get a frame of the right
// size.
- TimeTicks start_time = TimeTicks::Now();
+ TimeTicks start_time = clock_->NowTicks();
TimeDelta time_left = TimeDelta::FromMilliseconds(kPaintMsgTimeoutMS);
TimeTicks timeout_time = start_time + time_left;
while (1) {
@@ -1021,7 +1042,7 @@ void RenderWidgetHostImpl::PauseForPendingResizeOrRepaints() {
if (!view_->ShouldContinueToPauseForFrame())
break;
}
- time_left = timeout_time - TimeTicks::Now();
+ time_left = timeout_time - clock_->NowTicks();
if (time_left <= TimeDelta::FromSeconds(0)) {
TRACE_EVENT0("renderer_host", "WaitForSurface::Timeout");
break;
@@ -1037,7 +1058,7 @@ bool RenderWidgetHostImpl::ScheduleComposite() {
}
// Send out a request to the renderer to paint the view if required.
- repaint_start_time_ = TimeTicks::Now();
+ repaint_start_time_ = clock_->NowTicks();
repaint_ack_pending_ = true;
TRACE_EVENT_ASYNC_BEGIN0(
"renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
@@ -1053,10 +1074,11 @@ void RenderWidgetHostImpl::ProcessIgnoreInputEventsChanged(
RestartHangMonitorTimeoutIfNecessary();
}
-void RenderWidgetHostImpl::StartHangMonitorTimeout(base::TimeDelta delay) {
+void RenderWidgetHostImpl::StartHangMonitorTimeout(TimeDelta delay) {
if (!hang_monitor_timeout_)
return;
hang_monitor_timeout_->Start(delay);
+ hang_monitor_start_time_ = clock_->NowTicks();
}
void RenderWidgetHostImpl::RestartHangMonitorTimeoutIfNecessary() {
@@ -1071,23 +1093,31 @@ bool RenderWidgetHostImpl::IsCurrentlyUnresponsive() const {
void RenderWidgetHostImpl::StopHangMonitorTimeout() {
if (hang_monitor_timeout_)
hang_monitor_timeout_->Stop();
+
+ if (!hang_monitor_start_time_.is_null()) {
+ base::TimeDelta elapsed = clock_->NowTicks() - hang_monitor_start_time_;
+ const base::TimeDelta kMinimumHangTimeToReport =
+ base::TimeDelta::FromSeconds(5);
+ if (elapsed >= kMinimumHangTimeToReport)
+ UMA_HISTOGRAM_LONG_TIMES("Renderer.Hung.Duration", elapsed);
+
+ hang_monitor_start_time_ = TimeTicks();
+ }
RendererIsResponsive();
}
void RenderWidgetHostImpl::DidNavigate(uint32_t next_source_id) {
current_content_source_id_ = next_source_id;
+ did_receive_first_frame_after_navigation_ = false;
if (enable_surface_synchronization_) {
- if (view_)
- view_->DidNavigate();
// Resize messages before navigation are not acked, so reset
// |resize_ack_pending_| and make sure the next resize will be acked if the
// last resize before navigation was supposed to be acked.
next_resize_needs_resize_ack_ = resize_ack_pending_;
resize_ack_pending_ = false;
- // If |view_| decides we need a new LocalSurfaceId, we should notify
- // RenderWidget.
- WasResized();
+ if (view_)
+ view_->DidNavigate();
} else {
// It is possible for a compositor frame to arrive before the browser is
// notified about the page being committed, in which case no timer is
@@ -1191,16 +1221,28 @@ void RenderWidgetHostImpl::ForwardGestureEventWithLatencyInfo(
bool scroll_update_needs_wrapping = false;
if (gesture_event.GetType() == blink::WebInputEvent::kGestureScrollBegin) {
- DCHECK(!is_in_gesture_scroll_[gesture_event.source_device]);
- is_in_gesture_scroll_[gesture_event.source_device] = true;
+ // When a user starts scrolling while a fling is active, the GSB will arrive
+ // when is_in_gesture_scroll_[gesture_event.SourceDevice()] is still true.
+ // This is because the fling controller defers handling the GFC event
+ // arrived before the GSB and doesn't send a GSE to end the fling; Instead,
+ // it waits for a second GFS to arrive and boost the current active fling if
+ // possible. While GFC handling is deferred the controller suppresses the
+ // GSB and GSU events instead of sending them to the renderer and continues
+ // to progress the fling. So, the renderer doesn't receive two GSB events
+ // without any GSE in between.
+ DCHECK(!is_in_gesture_scroll_[gesture_event.SourceDevice()] ||
+ FlingCancellationIsDeferred());
+ is_in_gesture_scroll_[gesture_event.SourceDevice()] = true;
} else if (gesture_event.GetType() ==
blink::WebInputEvent::kGestureScrollEnd) {
- DCHECK(is_in_gesture_scroll_[gesture_event.source_device]);
- is_in_gesture_scroll_[gesture_event.source_device] = false;
+ DCHECK(is_in_gesture_scroll_[gesture_event.SourceDevice()]);
+ is_in_gesture_scroll_[gesture_event.SourceDevice()] = false;
is_in_touchpad_gesture_fling_ = false;
+ if (view_)
+ view_->set_is_currently_scrolling_viewport(false);
} else if (gesture_event.GetType() ==
blink::WebInputEvent::kGestureFlingStart) {
- if (gesture_event.source_device ==
+ if (gesture_event.SourceDevice() ==
blink::WebGestureDevice::kWebGestureDeviceTouchpad) {
// TODO(sahel): Remove the VR specific case when motion events are used
// for Android VR event processing and VR touchpad scrolling is handled by
@@ -1209,18 +1251,21 @@ void RenderWidgetHostImpl::ForwardGestureEventWithLatencyInfo(
if (GetView()->IsInVR()) {
// Regardless of the state of the wheel scroll latching
// WebContentsEventForwarder doesn't inject any GSE events before GFS.
- DCHECK(is_in_gesture_scroll_[gesture_event.source_device]);
+ DCHECK(is_in_gesture_scroll_[gesture_event.SourceDevice()]);
// Reset the is_in_gesture_scroll since while scrolling in Android VR
// the first wheel event sent by the FlingController will cause a GSB
// generation in MouseWheelEventQueue. This is because GSU events before
// the GFS are directly injected to RWHI rather than being generated
// from wheel events in MouseWheelEventQueue.
- is_in_gesture_scroll_[gesture_event.source_device] = false;
+ is_in_gesture_scroll_[gesture_event.SourceDevice()] = false;
} else if (GetView()->wheel_scroll_latching_enabled()) {
// When wheel scroll latching is enabled, no GSE is sent before GFS, so
// is_in_gesture_scroll must be true.
- DCHECK(is_in_gesture_scroll_[gesture_event.source_device]);
+ // TODO(sahel): This often gets tripped on Debug builds in ChromeOS
+ // indicating some kind of gesture event ordering race.
+ // https://crbug.com/821237.
+ // DCHECK(is_in_gesture_scroll_[gesture_event.SourceDevice()]);
// The FlingController handles GFS with touchpad source and sends wheel
// events to progress the fling, the wheel events will get processed by
@@ -1235,14 +1280,18 @@ void RenderWidgetHostImpl::ForwardGestureEventWithLatencyInfo(
// When wheel scroll latching is disabled a GSE is sent before a GFS.
// The GSE has already finished the scroll sequence.
- DCHECK(!is_in_gesture_scroll_[gesture_event.source_device]);
+ DCHECK(!is_in_gesture_scroll_[gesture_event.SourceDevice()]);
}
is_in_touchpad_gesture_fling_ = true;
- } else { // gesture_event.source_device !=
- // blink::WebGestureDevice::kWebGestureDeviceTouchpad
- DCHECK(is_in_gesture_scroll_[gesture_event.source_device]);
- is_in_gesture_scroll_[gesture_event.source_device] = false;
+ } else {
+ DCHECK(is_in_gesture_scroll_[gesture_event.SourceDevice()]);
+
+ // The FlingController handles GFS with touchscreen source and sends GSU
+ // events with inertial state to the renderer to progress the fling.
+ // is_in_gesture_scroll must stay true till the fling progress is
+ // finished. Then the FlingController will generate and send a GSE which
+ // shows the end of a scroll sequence and resets is_in_gesture_scroll_.
}
}
@@ -1252,7 +1301,7 @@ void RenderWidgetHostImpl::ForwardGestureEventWithLatencyInfo(
scroll_update_needs_wrapping =
gesture_event.GetType() == blink::WebInputEvent::kGestureScrollUpdate &&
gesture_event.resending_plugin_id != -1 &&
- !is_in_gesture_scroll_[gesture_event.source_device];
+ !is_in_gesture_scroll_[gesture_event.SourceDevice()];
// TODO(crbug.com/544782): Fix WebViewGuestScrollTest.TestGuestWheelScrolls-
// Bubble to test the resending logic of gesture events.
@@ -1593,6 +1642,25 @@ void RenderWidgetHostImpl::SetCursor(const CursorInfo& cursor_info) {
SetCursor(cursor);
}
+RenderProcessHost::Priority RenderWidgetHostImpl::GetPriority() {
+ RenderProcessHost::Priority priority = {
+ is_hidden_,
+ frame_depth_,
+#if defined(OS_ANDROID)
+ importance_,
+#endif
+ };
+ if (owner_delegate_ &&
+ !owner_delegate_->ShouldContributePriorityToProcess()) {
+ priority.is_hidden = true;
+ priority.frame_depth = RenderProcessHostImpl::kMaxFrameDepthForPriority;
+#if defined(OS_ANDROID)
+ priority.importance = ChildProcessImportance::NORMAL;
+#endif
+ }
+ return priority;
+}
+
mojom::WidgetInputHandler* RenderWidgetHostImpl::GetWidgetInputHandler() {
if (associated_widget_input_handler_)
return associated_widget_input_handler_.get();
@@ -1710,7 +1778,7 @@ void RenderWidgetHostImpl::OnStartDragging(
}
void RenderWidgetHostImpl::OnUpdateDragCursor(WebDragOperation current_op) {
- if (delegate_ && delegate_->OnUpdateDragCursor())
+ if (delegate_->OnUpdateDragCursor())
return;
RenderViewHostDelegateView* view = delegate_->GetDelegateView();
@@ -1756,8 +1824,9 @@ void RenderWidgetHostImpl::RendererExited(base::TerminationStatus status,
// the |is_hidden_| change, so that the renderer will have correct visibility
// set when respawned.
if (!is_hidden_) {
- process_->WidgetHidden();
is_hidden_ = true;
+ if (!destroyed_)
+ process_->UpdateClientPriority(this);
}
// Reset this to ensure the hung renderer mechanism is working properly.
@@ -1839,6 +1908,19 @@ void RenderWidgetHostImpl::RejectMouseLockOrUnlockIfNecessary() {
}
}
+bool RenderWidgetHostImpl::IsKeyboardLocked() const {
+ return view_ ? view_->IsKeyboardLocked() : false;
+}
+
+void RenderWidgetHostImpl::GetContentRenderingTimeoutFrom(
+ RenderWidgetHostImpl* other) {
+ if (other->new_content_rendering_timeout_ &&
+ other->new_content_rendering_timeout_->IsRunning()) {
+ new_content_rendering_timeout_->Start(
+ other->new_content_rendering_timeout_->GetCurrentDelay());
+ }
+}
+
bool RenderWidgetHostImpl::IsMouseLocked() const {
return view_ ? view_->IsMouseLocked() : false;
}
@@ -1935,7 +2017,7 @@ void RenderWidgetHostImpl::OnGpuSwapBuffersCompletedInternal(
FROM_HERE,
base::Bind(&RenderWidgetHostImpl::WindowSnapshotReachedScreen,
weak_factory_.GetWeakPtr(), sequence_number),
- base::TimeDelta::FromSecondsD(1. / 6));
+ TimeDelta::FromSecondsD(1. / 6));
#else
WindowSnapshotReachedScreen(sequence_number);
#endif
@@ -2050,7 +2132,7 @@ void RenderWidgetHostImpl::DidDeleteSharedBitmap(
void RenderWidgetHostImpl::OnResizeOrRepaintACK(
const ViewHostMsg_ResizeOrRepaint_ACK_Params& params) {
TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::OnResizeOrRepaintACK");
- TimeTicks paint_start = TimeTicks::Now();
+ TimeTicks paint_start = clock_->NowTicks();
// Update our knowledge of the RenderWidget's size.
current_size_ = params.view_size;
@@ -2072,7 +2154,7 @@ void RenderWidgetHostImpl::OnResizeOrRepaintACK(
TRACE_EVENT_ASYNC_END0(
"renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
repaint_ack_pending_ = false;
- TimeDelta delta = TimeTicks::Now() - repaint_start_time_;
+ TimeDelta delta = clock_->NowTicks() - repaint_start_time_;
UMA_HISTOGRAM_TIMES("MPArch.RWH_RepaintDelta", delta);
}
@@ -2095,7 +2177,7 @@ void RenderWidgetHostImpl::OnResizeOrRepaintACK(
// Log the time delta for processing a paint message. On platforms that don't
// support asynchronous painting, this is equivalent to
// MPArch.RWH_TotalPaintTime.
- TimeDelta delta = TimeTicks::Now() - paint_start;
+ TimeDelta delta = clock_->NowTicks() - paint_start;
UMA_HISTOGRAM_TIMES("MPArch.RWH_OnMsgResizeOrRepaintACK", delta);
}
@@ -2130,12 +2212,16 @@ void RenderWidgetHostImpl::OnAutoscrollStart(const gfx::PointF& position) {
WebGestureEvent scroll_begin = SyntheticWebGestureEventBuilder::Build(
WebInputEvent::kGestureScrollBegin,
blink::kWebGestureDeviceSyntheticAutoscroll);
+ scroll_begin.SetPositionInWidget(position);
- scroll_begin.x = position.x();
- scroll_begin.y = position.y();
- scroll_begin.source_device = blink::kWebGestureDeviceSyntheticAutoscroll;
+ ForwardGestureEventWithLatencyInfo(
+ scroll_begin, ui::LatencyInfo(ui::SourceEventType::OTHER));
- input_router_->SendGestureEvent(GestureEventWithLatencyInfo(scroll_begin));
+ // Send a GFS event with zero velocity to make sure that the scroll sequence
+ // will end with the GFC generated in |OnAutoscrollEnd()|; Otherwise if the
+ // user cancels the autoscroll without moving the mouse, the GFC will get
+ // filtered since no GFS is sent in the sequence. https://crbug.com/829794
+ OnAutoscrollFling(gfx::Vector2dF());
}
void RenderWidgetHostImpl::OnAutoscrollFling(const gfx::Vector2dF& velocity) {
@@ -2144,9 +2230,9 @@ void RenderWidgetHostImpl::OnAutoscrollFling(const gfx::Vector2dF& velocity) {
blink::kWebGestureDeviceSyntheticAutoscroll);
event.data.fling_start.velocity_x = velocity.x();
event.data.fling_start.velocity_y = velocity.y();
- event.source_device = blink::kWebGestureDeviceSyntheticAutoscroll;
- input_router_->SendGestureEvent(GestureEventWithLatencyInfo(event));
+ ForwardGestureEventWithLatencyInfo(
+ event, ui::LatencyInfo(ui::SourceEventType::OTHER));
}
void RenderWidgetHostImpl::OnAutoscrollEnd() {
@@ -2154,12 +2240,9 @@ void RenderWidgetHostImpl::OnAutoscrollEnd() {
WebInputEvent::kGestureFlingCancel,
blink::kWebGestureDeviceSyntheticAutoscroll);
cancel_event.data.fling_cancel.prevent_boosting = true;
- input_router_->SendGestureEvent(GestureEventWithLatencyInfo(cancel_event));
- WebGestureEvent end_event = SyntheticWebGestureEventBuilder::Build(
- WebInputEvent::kGestureScrollEnd,
- blink::kWebGestureDeviceSyntheticAutoscroll);
- input_router_->SendGestureEvent(GestureEventWithLatencyInfo(end_event));
+ ForwardGestureEventWithLatencyInfo(
+ cancel_event, ui::LatencyInfo(ui::SourceEventType::OTHER));
}
TouchEmulator* RenderWidgetHostImpl::GetTouchEmulator() {
@@ -2239,6 +2322,38 @@ void RenderWidgetHostImpl::OnUnlockMouse() {
is_last_unlocked_by_target_ = true;
}
+void RenderWidgetHostImpl::RequestKeyboardLock(
+ base::Optional<base::flat_set<int>> keys_to_lock) {
+ if (!delegate_) {
+ CancelKeyboardLock();
+ return;
+ }
+
+ DCHECK(!keys_to_lock.has_value() || !keys_to_lock.value().empty());
+ keyboard_keys_to_lock_ = std::move(keys_to_lock);
+ keyboard_lock_requested_ = true;
+
+ const int esc_native_key_code =
+ ui::KeycodeConverter::DomCodeToNativeKeycode(ui::DomCode::ESCAPE);
+ const bool esc_requested =
+ !keyboard_keys_to_lock_.has_value() ||
+ base::ContainsKey(keyboard_keys_to_lock_.value(), esc_native_key_code);
+
+ if (!delegate_->RequestKeyboardLock(this, esc_requested))
+ CancelKeyboardLock();
+}
+
+void RenderWidgetHostImpl::CancelKeyboardLock() {
+ if (delegate_)
+ delegate_->CancelKeyboardLock(this);
+
+ UnlockKeyboard();
+
+ keyboard_lock_allowed_ = false;
+ keyboard_lock_requested_ = false;
+ keyboard_keys_to_lock_.reset();
+}
+
void RenderWidgetHostImpl::OnShowDisambiguationPopup(
const gfx::Rect& rect_pixels,
const gfx::Size& size,
@@ -2310,12 +2425,7 @@ InputEventAckState RenderWidgetHostImpl::FilterInputEvent(
event.GetType() == WebInputEvent::kTouchStart) {
delegate_->FocusOwningWebContents(this);
}
- if (event.GetType() == WebInputEvent::kMouseDown ||
- event.GetType() == WebInputEvent::kGestureScrollBegin ||
- event.GetType() == WebInputEvent::kTouchStart ||
- event.GetType() == WebInputEvent::kRawKeyDown) {
- delegate_->OnUserInteraction(this, event.GetType());
- }
+ delegate_->DidReceiveInputEvent(this, event.GetType());
}
return view_ ? view_->FilterInputEvent(event)
@@ -2358,7 +2468,12 @@ void RenderWidgetHostImpl::DidStopFlinging() {
view_->DidStopFlinging();
}
+void RenderWidgetHostImpl::DidStartScrollingViewport() {
+ if (view_)
+ view_->set_is_currently_scrolling_viewport(true);
+}
void RenderWidgetHostImpl::SetNeedsBeginFrameForFlingProgress() {
+ browser_fling_needs_begin_frame_ = true;
SetNeedsBeginFrame(true);
}
@@ -2492,6 +2607,16 @@ bool RenderWidgetHostImpl::GotResponseToLockMouseRequest(bool allowed) {
return true;
}
+void RenderWidgetHostImpl::GotResponseToKeyboardLockRequest(bool allowed) {
+ DCHECK(keyboard_lock_requested_);
+ keyboard_lock_allowed_ = allowed;
+
+ if (keyboard_lock_allowed_)
+ LockKeyboard();
+ else
+ UnlockKeyboard();
+}
+
void RenderWidgetHostImpl::DelayedAutoResized() {
gfx::Size new_size = new_auto_size_;
// Clear the new_auto_size_ since the empty value is used as a flag to
@@ -2501,9 +2626,15 @@ void RenderWidgetHostImpl::DelayedAutoResized() {
if (!auto_resize_enabled_)
return;
- if (delegate_) {
- delegate_->ResizeDueToAutoResize(this, new_size,
+ if (view_) {
+ viz::ScopedSurfaceIdAllocator scoped_allocator =
+ view_->ResizeDueToAutoResize(new_size,
last_auto_resize_request_number_);
+
+ if (delegate_) {
+ delegate_->ResizeDueToAutoResize(this, new_size,
+ last_auto_resize_request_number_);
+ }
}
}
@@ -2514,20 +2645,8 @@ void RenderWidgetHostImpl::DetachDelegate() {
void RenderWidgetHostImpl::DidAllocateLocalSurfaceIdForAutoResize(
uint64_t sequence_number) {
- if (!view_ || !sequence_number ||
- last_auto_resize_request_number_ != sequence_number) {
- return;
- }
-
- viz::LocalSurfaceId local_surface_id(view_->GetLocalSurfaceId());
- if (local_surface_id.is_valid()) {
- ScreenInfo screen_info;
- view_->GetScreenInfo(&screen_info);
- Send(new ViewMsg_SetLocalSurfaceIdForAutoResize(
- routing_id_, sequence_number, min_size_for_auto_resize_,
- max_size_for_auto_resize_, screen_info, current_content_source_id_,
- local_surface_id));
- }
+ last_auto_resize_response_number_ = sequence_number;
+ WasResized();
}
void RenderWidgetHostImpl::DidReceiveRendererFrame() {
@@ -2676,10 +2795,9 @@ void RenderWidgetHostImpl::RequestCompositorFrameSink(
mojom::RenderFrameMetadataObserverClientRequest
render_frame_metadata_observer_client_request,
mojom::RenderFrameMetadataObserverPtr render_frame_metadata_observer) {
- render_frame_metadata_provider_ =
- std::make_unique<RenderFrameMetadataProviderImpl>(
- std::move(render_frame_metadata_observer_client_request),
- std::move(render_frame_metadata_observer));
+ render_frame_metadata_provider_.Bind(
+ std::move(render_frame_metadata_observer_client_request),
+ std::move(render_frame_metadata_observer));
if (enable_viz_) {
// Connects the viz process end of CompositorFrameSink message pipes. The
// renderer compositor may request a new CompositorFrameSink on context
@@ -2697,7 +2815,7 @@ void RenderWidgetHostImpl::RequestCompositorFrameSink(
std::move(compositor_frame_sink_client));
if (view_)
- view_->CreateCompositorFrameSink(std::move(callback));
+ std::move(callback).Run(view_->GetFrameSinkId());
else
create_frame_sink_callback_ = std::move(callback);
@@ -2723,9 +2841,9 @@ void RenderWidgetHostImpl::SetNeedsBeginFrame(bool needs_begin_frames) {
if (needs_begin_frames_ == needs_begin_frames)
return;
- needs_begin_frames_ = needs_begin_frames;
+ needs_begin_frames_ = needs_begin_frames || browser_fling_needs_begin_frame_;
if (view_)
- view_->SetNeedsBeginFrames(needs_begin_frames);
+ view_->SetNeedsBeginFrames(needs_begin_frames_);
}
void RenderWidgetHostImpl::SetWantsAnimateOnlyBeginFrames() {
@@ -2738,7 +2856,6 @@ void RenderWidgetHostImpl::SubmitCompositorFrame(
viz::CompositorFrame frame,
viz::mojom::HitTestRegionListPtr hit_test_region_list,
uint64_t submit_time) {
- // TODO(gklassen): Route hit-test data to appropriate HitTestAggregator.
TRACE_EVENT_FLOW_END0(TRACE_DISABLED_BY_DEFAULT("cc.debug.ipc"),
"SubmitCompositorFrame", local_surface_id.hash());
@@ -2756,8 +2873,8 @@ void RenderWidgetHostImpl::SubmitCompositorFrame(
TRACE_EVENT_CATEGORY_GROUP_ENABLED(TRACE_DISABLED_BY_DEFAULT("cc.debug.ipc"),
&tracing_enabled);
if (tracing_enabled) {
- base::TimeDelta elapsed = base::TimeTicks::Now().since_origin() -
- base::TimeDelta::FromMicroseconds(submit_time);
+ TimeDelta elapsed = clock_->NowTicks().since_origin() -
+ TimeDelta::FromMicroseconds(submit_time);
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("cc.debug.ipc"),
"SubmitCompositorFrame::TimeElapsed",
TRACE_EVENT_SCOPE_THREAD,
@@ -2873,10 +2990,12 @@ void RenderWidgetHostImpl::SubmitCompositorFrame(
// After navigation, if a frame belonging to the new page is received, stop
// the timer that triggers clearing the graphics of the last page.
- if (new_content_rendering_timeout_ &&
- last_received_content_source_id_ >= current_content_source_id_ &&
- new_content_rendering_timeout_->IsRunning()) {
- new_content_rendering_timeout_->Stop();
+ if (last_received_content_source_id_ >= current_content_source_id_) {
+ did_receive_first_frame_after_navigation_ = true;
+ if (new_content_rendering_timeout_ &&
+ new_content_rendering_timeout_->IsRunning()) {
+ new_content_rendering_timeout_->Stop();
+ }
}
}
@@ -2922,7 +3041,7 @@ void RenderWidgetHostImpl::OnSharedBitmapAllocatedByChild(
SubmitCompositorFrame(
saved_frame_.local_surface_id, std::move(saved_frame_.frame),
std::move(saved_frame_.hit_test_region_list),
- tracing_enabled ? base::TimeTicks::Now().since_origin().InMicroseconds()
+ tracing_enabled ? clock_->NowTicks().since_origin().InMicroseconds()
: 0);
saved_frame_.local_surface_id = viz::LocalSurfaceId();
compositor_frame_sink_binding_.ResumeIncomingMethodCallProcessing();
@@ -2954,12 +3073,16 @@ void RenderWidgetHostImpl::SetupInputRouter() {
static_cast<LegacyInputRouterImpl*>(input_router_.get()));
}
+ // input_router_ recreated, need to update the force_enable_zoom_ state.
+ input_router_->SetForceEnableZoom(force_enable_zoom_);
+
if (IsUseZoomForDSFEnabled()) {
input_router_->SetDeviceScaleFactor(GetScaleFactorForView(view_.get()));
}
}
void RenderWidgetHostImpl::SetForceEnableZoom(bool enabled) {
+ force_enable_zoom_ = enabled;
input_router_->SetForceEnableZoom(enabled);
}
@@ -2992,13 +3115,15 @@ void RenderWidgetHostImpl::SetWidget(mojom::WidgetPtr widget) {
}
}
-void RenderWidgetHostImpl::ProgressFling(base::TimeTicks current_time) {
+void RenderWidgetHostImpl::ProgressFling(TimeTicks current_time) {
+ browser_fling_needs_begin_frame_ = false;
if (input_router_)
input_router_->ProgressFling(current_time);
}
void RenderWidgetHostImpl::DidReceiveFirstFrameAfterNavigation() {
DCHECK(enable_surface_synchronization_);
+ did_receive_first_frame_after_navigation_ = true;
if (!new_content_rendering_timeout_ ||
!new_content_rendering_timeout_->IsRunning()) {
return;
@@ -3006,11 +3131,26 @@ void RenderWidgetHostImpl::DidReceiveFirstFrameAfterNavigation() {
new_content_rendering_timeout_->Stop();
}
+void RenderWidgetHostImpl::ForceFirstFrameAfterNavigationTimeout() {
+ if (did_receive_first_frame_after_navigation_)
+ return;
+ if (new_content_rendering_timeout_)
+ new_content_rendering_timeout_->Stop();
+ ClearDisplayedGraphics();
+}
+
void RenderWidgetHostImpl::StopFling() {
if (input_router_)
input_router_->StopFling();
}
+bool RenderWidgetHostImpl::FlingCancellationIsDeferred() const {
+ if (input_router_)
+ return input_router_->FlingCancellationIsDeferred();
+
+ return false;
+}
+
void RenderWidgetHostImpl::SetScreenOrientationForTesting(
uint16_t angle,
ScreenOrientationValues type) {
@@ -3049,4 +3189,20 @@ bool RenderWidgetHostImpl::SurfacePropertiesMismatch(
return first != second;
}
+bool RenderWidgetHostImpl::LockKeyboard() {
+ if (!keyboard_lock_allowed_ || !is_focused_ || !view_)
+ return false;
+
+ // KeyboardLock can be activated and deactivated several times per request,
+ // for example when a fullscreen tab loses and gains focus multiple times,
+ // so we need to retain a copy of the keys requested.
+ base::Optional<base::flat_set<int>> copy_of_keys = keyboard_keys_to_lock_;
+ return view_->LockKeyboard(std::move(copy_of_keys));
+}
+
+void RenderWidgetHostImpl::UnlockKeyboard() {
+ if (IsKeyboardLocked())
+ view_->UnlockKeyboard();
+}
+
} // namespace content
diff --git a/chromium/content/browser/renderer_host/render_widget_host_impl.h b/chromium/content/browser/renderer_host/render_widget_host_impl.h
index e55683792a3..e3f95d8623a 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_impl.h
+++ b/chromium/content/browser/renderer_host/render_widget_host_impl.h
@@ -16,14 +16,17 @@
#include <vector>
#include "base/callback.h"
+#include "base/containers/flat_set.h"
#include "base/containers/queue.h"
#include "base/gtest_prod_util.h"
#include "base/macros.h"
#include "base/memory/shared_memory_handle.h"
#include "base/memory/weak_ptr.h"
#include "base/observer_list.h"
+#include "base/optional.h"
#include "base/process/kill.h"
#include "base/strings/string16.h"
+#include "base/time/tick_clock.h"
#include "base/time/time.h"
#include "base/timer/elapsed_timer.h"
#include "build/build_config.h"
@@ -38,6 +41,8 @@
#include "content/browser/renderer_host/input/synthetic_gesture.h"
#include "content/browser/renderer_host/input/synthetic_gesture_controller.h"
#include "content/browser/renderer_host/input/touch_emulator_client.h"
+#include "content/browser/renderer_host/render_frame_metadata_provider_impl.h"
+#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_delegate.h"
#include "content/browser/renderer_host/render_widget_host_view_base.h"
#include "content/common/drag_event_source_info.h"
@@ -54,7 +59,7 @@
#include "mojo/public/cpp/bindings/binding.h"
#include "services/viz/public/interfaces/compositing/compositor_frame_sink.mojom.h"
#include "services/viz/public/interfaces/hit_test/input_target_client.mojom.h"
-#include "third_party/WebKit/public/platform/WebDisplayMode.h"
+#include "third_party/blink/public/platform/web_display_mode.h"
#include "ui/base/ime/text_input_mode.h"
#include "ui/base/ime/text_input_type.h"
#include "ui/base/ui_base_types.h"
@@ -94,7 +99,6 @@ namespace content {
class BrowserAccessibilityManager;
class InputRouter;
class MockRenderWidgetHost;
-class RenderFrameMetadataProvider;
class RenderWidgetHostOwnerDelegate;
class SyntheticGestureController;
class TimeoutMonitor;
@@ -112,6 +116,7 @@ class CONTENT_EXPORT RenderWidgetHostImpl
public FrameTokenMessageQueue::Client,
public InputRouterImplClient,
public InputDispositionHandler,
+ public RenderProcessHostImpl::PriorityClient,
public TouchEmulatorClient,
public SyntheticGestureController::Delegate,
public viz::mojom::CompositorFrameSink,
@@ -162,6 +167,8 @@ class CONTENT_EXPORT RenderWidgetHostImpl
RenderWidgetHostOwnerDelegate* owner_delegate() { return owner_delegate_; }
+ void set_clock_for_testing(const base::TickClock* clock) { clock_ = clock; }
+
// Returns the viz::FrameSinkId that this object uses to put things on screen.
// This value is constant throughout the lifetime of this object. Note that
// until a RenderWidgetHostView is created, initialized, and assigned to this
@@ -229,6 +236,9 @@ class CONTENT_EXPORT RenderWidgetHostImpl
void FilterDropData(DropData* drop_data) override;
void SetCursor(const CursorInfo& cursor_info) override;
+ // RenderProcessHostImpl::PriorityClient implementation.
+ RenderProcessHost::Priority GetPriority() override;
+
// Notification that the screen info has changed.
void NotifyScreenInfoChanged();
@@ -270,6 +280,9 @@ class CONTENT_EXPORT RenderWidgetHostImpl
return owned_by_render_frame_host_;
}
+ void SetFrameDepth(unsigned int depth);
+ void UpdatePriority();
+
// Tells the renderer to die and optionally delete |this|.
void ShutdownAndDestroyWidget(bool also_delete);
@@ -478,6 +491,11 @@ class CONTENT_EXPORT RenderWidgetHostImpl
allow_privileged_mouse_lock_ = allow;
}
+ // Called when the response to a pending keyboard lock request has arrived.
+ // |allowed| should be true if the current tab is in tab initiated fullscreen
+ // mode.
+ void GotResponseToKeyboardLockRequest(bool allowed);
+
// Resets state variables related to tracking pending size and painting.
//
// We need to reset these flags when we want to repaint the contents of
@@ -601,8 +619,8 @@ class CONTENT_EXPORT RenderWidgetHostImpl
return last_auto_resize_request_number_;
}
- RenderFrameMetadataProvider* render_frame_metadata_provider() {
- return render_frame_metadata_provider_.get();
+ RenderFrameMetadataProviderImpl* render_frame_metadata_provider() {
+ return &render_frame_metadata_provider_;
}
bool HasGestureStopped() override;
@@ -654,14 +672,35 @@ class CONTENT_EXPORT RenderWidgetHostImpl
void ProgressFling(base::TimeTicks current_time);
void StopFling();
+ bool FlingCancellationIsDeferred() const;
void DidReceiveFirstFrameAfterNavigation();
+ // The RenderWidgetHostImpl will keep showing the old page (for a while) after
+ // navigation until the first frame of the new page arrives. This reduces
+ // flicker. However, if for some reason it is known that the frames won't be
+ // arriving, this call can be used for force a timeout, to avoid showing the
+ // content of the old page under UI from the new page.
+ void ForceFirstFrameAfterNavigationTimeout();
+
uint32_t current_content_source_id() { return current_content_source_id_; }
void SetScreenOrientationForTesting(uint16_t angle,
ScreenOrientationValues type);
+ // Requests Keyboard lock. Note: the lock may not take effect until later.
+ // If |keys_to_lock| has no value then all keys will be locked, otherwise only
+ // the keys specified will be intercepted and routed to the web page.
+ void RequestKeyboardLock(base::Optional<base::flat_set<int>> keys_to_lock);
+
+ // Cancels a previous keyboard lock request.
+ void CancelKeyboardLock();
+
+ // Indicates whether keyboard lock is active.
+ bool IsKeyboardLocked() const;
+
+ void GetContentRenderingTimeoutFrom(RenderWidgetHostImpl* other);
+
protected:
// ---------------------------------------------------------------------------
// The following method is overridden by RenderViewHost to send upwards to
@@ -789,6 +828,7 @@ class CONTENT_EXPORT RenderWidgetHostImpl
void OnHasTouchEventHandlers(bool has_handlers) override;
void DidOverscroll(const ui::DidOverscrollParams& params) override;
void DidStopFlinging() override;
+ void DidStartScrollingViewport() override;
void OnSetWhiteListedTouchAction(
cc::TouchAction white_listed_touch_action) override {}
void SetNeedsBeginFrameForFlingProgress() override;
@@ -833,6 +873,12 @@ class CONTENT_EXPORT RenderWidgetHostImpl
const RenderWidgetSurfaceProperties& first,
const RenderWidgetSurfaceProperties& second) const;
+ // Start intercepting system keyboard events.
+ bool LockKeyboard();
+
+ // Stop intercepting system keyboard events.
+ void UnlockKeyboard();
+
#if defined(OS_MACOSX)
device::mojom::WakeLock* GetWakeLock();
#endif
@@ -859,16 +905,22 @@ class CONTENT_EXPORT RenderWidgetHostImpl
// The ID of the corresponding object in the Renderer Instance.
const int routing_id_;
+ // The clock used; overridable for tests.
+ const base::TickClock* clock_;
+
// Indicates whether a page is loading or not.
bool is_loading_;
- // Indicates whether a page is hidden or not. It has to stay in sync with the
- // most recent call to process_->WidgetRestored() / WidgetHidden().
+ // Indicates whether a page is hidden or not. Need to call
+ // process_->UpdateClientPriority when this value changes.
bool is_hidden_;
+ // For a widget that does not have an associated RenderFrame/View, assume it
+ // is depth 1, ie just below the root widget.
+ unsigned int frame_depth_ = 1u;
+
#if defined(OS_ANDROID)
- // Tracks the current importance of widget, so the old value can be passed to
- // RenderProcessHost on changes.
+ // Tracks the current importance of widget.
ChildProcessImportance importance_ = ChildProcessImportance::NORMAL;
#endif
@@ -898,6 +950,7 @@ class CONTENT_EXPORT RenderWidgetHostImpl
gfx::Size max_size_for_auto_resize_;
uint64_t last_auto_resize_request_number_ = 0ul;
+ uint64_t last_auto_resize_response_number_ = 0ul;
bool waiting_for_screen_rects_ack_;
gfx::Rect last_view_screen_rect_;
@@ -961,6 +1014,11 @@ class CONTENT_EXPORT RenderWidgetHostImpl
bool pending_mouse_lock_request_;
bool allow_privileged_mouse_lock_;
+ // Stores the keyboard keys to lock while waiting for a pending lock request.
+ base::Optional<base::flat_set<int>> keyboard_keys_to_lock_;
+ bool keyboard_lock_requested_ = false;
+ bool keyboard_lock_allowed_ = false;
+
// Used when locking to indicate when a target application has voluntarily
// unlocked and desires to relock the mouse. If the mouse is unlocked due
// to ESC being pressed by the user, this will be false.
@@ -985,6 +1043,7 @@ class CONTENT_EXPORT RenderWidgetHostImpl
std::unique_ptr<InputRouter> input_router_;
std::unique_ptr<TimeoutMonitor> hang_monitor_timeout_;
+ base::TimeTicks hang_monitor_start_time_;
std::unique_ptr<TimeoutMonitor> new_content_rendering_timeout_;
@@ -1010,6 +1069,10 @@ class CONTENT_EXPORT RenderWidgetHostImpl
// consistent with the state in the renderer, so this host handles it.
bool needs_begin_frames_ = false;
+ // This is used to make sure that when the fling controller sets
+ // needs_begin_frames_ it doesn't get overriden by the renderer.
+ bool browser_fling_needs_begin_frame_ = false;
+
// This value indicates how long to wait before we consider a renderer hung.
base::TimeDelta hung_renderer_delay_;
@@ -1090,10 +1153,14 @@ class CONTENT_EXPORT RenderWidgetHostImpl
bool next_resize_needs_resize_ack_ = false;
- std::unique_ptr<RenderFrameMetadataProvider> render_frame_metadata_provider_;
+ bool force_enable_zoom_ = false;
+
+ RenderFrameMetadataProviderImpl render_frame_metadata_provider_;
const viz::FrameSinkId frame_sink_id_;
+ bool did_receive_first_frame_after_navigation_ = true;
+
base::WeakPtrFactory<RenderWidgetHostImpl> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostImpl);
diff --git a/chromium/content/browser/renderer_host/render_widget_host_input_event_router.cc b/chromium/content/browser/renderer_host/render_widget_host_input_event_router.cc
index 4e58b894e06..d9f001f9ff0 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_input_event_router.cc
+++ b/chromium/content/browser/renderer_host/render_widget_host_input_event_router.cc
@@ -9,6 +9,7 @@
#include "base/debug/crash_logging.h"
#include "base/debug/dump_without_crashing.h"
#include "base/metrics/histogram_macros.h"
+#include "base/strings/stringprintf.h"
#include "components/viz/common/features.h"
#include "components/viz/common/quads/surface_draw_quad.h"
#include "components/viz/host/host_frame_sink_manager.h"
@@ -21,7 +22,7 @@
#include "content/browser/renderer_host/render_widget_host_view_child_frame.h"
#include "content/common/frame_messages.h"
#include "services/viz/public/interfaces/hit_test/hit_test_region_list.mojom.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/base/layout.h"
#include "ui/gfx/geometry/dip_util.h"
@@ -200,10 +201,7 @@ RenderWidgetTargetResult RenderWidgetHostInputEventRouter::FindMouseEventTarget(
RenderWidgetHostViewBase* target = nullptr;
bool needs_transform_point = true;
if (root_view->IsMouseLocked()) {
- target = root_view->GetRenderWidgetHostImpl()
- ->delegate()
- ->GetMouseLockWidget()
- ->GetView();
+ target = root_view->host()->delegate()->GetMouseLockWidget()->GetView();
}
constexpr int mouse_button_modifiers =
@@ -249,10 +247,7 @@ RenderWidgetHostInputEventRouter::FindMouseWheelEventTarget(
RenderWidgetHostViewBase* target = nullptr;
gfx::PointF transformed_point;
if (root_view->IsMouseLocked()) {
- target = root_view->GetRenderWidgetHostImpl()
- ->delegate()
- ->GetMouseLockWidget()
- ->GetView();
+ target = root_view->host()->delegate()->GetMouseLockWidget()->GetView();
if (!TransformPointToTargetCoordSpace(
root_view, target, event.PositionInWidget(), &transformed_point,
viz::EventSource::MOUSE)) {
@@ -332,7 +327,14 @@ RenderWidgetTargetResult RenderWidgetHostInputEventRouter::FindViewAtLocation(
}
auto* view = FindViewFromFrameSinkId(frame_sink_id);
- return {view ? view : root_view, query_renderer, *transformed_point};
+ // Send the event to |root_view| if |view| is not in |root_view|'s sub-tree
+ // anymore.
+ if (!view || (RenderWidgetHostViewGuest::GetRootView(view) != root_view)) {
+ view = root_view;
+ *transformed_point = point;
+ }
+
+ return {view, query_renderer, *transformed_point};
}
void RenderWidgetHostInputEventRouter::RouteMouseEvent(
@@ -415,7 +417,7 @@ void RenderWidgetHostInputEventRouter::DispatchMouseWheelEvent(
// processed.
blink::WebGestureEvent fake_scroll_update =
DummyGestureScrollUpdate(mouse_wheel_event.TimeStampSeconds());
- fake_scroll_update.source_device = blink::kWebGestureDeviceTouchpad;
+ fake_scroll_update.SetSourceDevice(blink::kWebGestureDeviceTouchpad);
SendGestureScrollEnd(bubbling_gesture_scroll_target_.target,
fake_scroll_update);
bubbling_gesture_scroll_target_.target = nullptr;
@@ -458,7 +460,7 @@ void RenderWidgetHostInputEventRouter::RouteGestureEvent(
return;
}
- switch (event->source_device) {
+ switch (event->SourceDevice()) {
case blink::kWebGestureDeviceUninitialized:
case blink::kWebGestureDeviceCount:
NOTREACHED() << "Uninitialized device type is not allowed";
@@ -754,12 +756,10 @@ namespace {
blink::WebGestureEvent GestureEventInTarget(
const blink::WebGestureEvent& event,
RenderWidgetHostViewBase* target_view) {
- const gfx::Point point_in_target =
- gfx::ToRoundedPoint(target_view->TransformRootPointToViewCoordSpace(
- gfx::PointF(event.x, event.y)));
+ const gfx::PointF point_in_target =
+ target_view->TransformRootPointToViewCoordSpace(event.PositionInWidget());
blink::WebGestureEvent event_for_target(event);
- event_for_target.x = point_in_target.x();
- event_for_target.y = point_in_target.y();
+ event_for_target.SetPositionInWidget(point_in_target);
return event_for_target;
}
@@ -1052,9 +1052,8 @@ RenderWidgetHostInputEventRouter::FindTouchscreenGestureEventTarget(
// these we hit-test explicitly.
if (gesture_event.unique_touch_event_id == 0) {
gfx::PointF transformed_point;
- gfx::PointF original_point(gesture_event.x, gesture_event.y);
- gfx::PointF original_point_in_screen(gesture_event.global_x,
- gesture_event.global_y);
+ gfx::PointF original_point(gesture_event.PositionInWidget());
+ gfx::PointF original_point_in_screen(gesture_event.PositionInScreen());
return FindViewAtLocation(root_view, original_point,
original_point_in_screen, viz::EventSource::TOUCH,
&transformed_point);
@@ -1071,6 +1070,11 @@ void RenderWidgetHostInputEventRouter::DispatchTouchscreenGestureEvent(
const blink::WebGestureEvent& gesture_event,
const ui::LatencyInfo& latency,
const base::Optional<gfx::PointF>& target_location) {
+ // Temporary logging for https://crbug.com/824774.
+ static auto* target_source_key = base::debug::AllocateCrashKeyString(
+ "touchscreen-gesture-target-source", base::debug::CrashKeySize::Size32);
+ base::debug::SetCrashKeyString(target_source_key, "input");
+
if (gesture_event.GetType() == blink::WebInputEvent::kGesturePinchBegin) {
in_touchscreen_gesture_pinch_ = true;
// If the root view wasn't already receiving the gesture stream, then we
@@ -1085,8 +1089,26 @@ void RenderWidgetHostInputEventRouter::DispatchTouchscreenGestureEvent(
// should have been one.
if (root_view != touchscreen_gesture_target_.target &&
!rwhi->is_in_touchscreen_gesture_scroll()) {
- gesture_pinch_did_send_scroll_begin_ = true;
- SendGestureScrollBegin(root_view, gesture_event);
+ cc::TouchAction target_allowed_touch_action =
+ cc::TouchAction::kTouchActionAuto;
+ if (touchscreen_gesture_target_.target) {
+ target_allowed_touch_action =
+ (static_cast<RenderWidgetHostImpl*>(
+ touchscreen_gesture_target_.target->GetRenderWidgetHost()))
+ ->input_router()
+ ->AllowedTouchAction();
+ }
+ if (target_allowed_touch_action &
+ cc::TouchAction::kTouchActionPinchZoom) {
+ gesture_pinch_did_send_scroll_begin_ = true;
+ SendGestureScrollBegin(root_view, gesture_event);
+ } else {
+ // When target does not allow touch-action: pinch, instead of sending
+ // pinch gestures to the root frame, we send all gesture pinch events
+ // to the subframe target so the target can look after disposing of
+ // them.
+ in_touchscreen_gesture_pinch_ = false;
+ }
}
}
@@ -1128,9 +1150,11 @@ void RenderWidgetHostInputEventRouter::DispatchTouchscreenGestureEvent(
// RenderWidgetTargeter. These gesture events should always have a
// unique_touch_event_id of 0.
touchscreen_gesture_target_.target = target;
- DCHECK(target_location.has_value());
+ base::debug::SetCrashKeyString(target_source_key, "touch_id=0");
touchscreen_gesture_target_.delta =
- target_location.value() - gfx::PointF(gesture_event.x, gesture_event.y);
+ target_location.has_value()
+ ? target_location.value() - gesture_event.PositionInWidget()
+ : gfx::Vector2dF();
} else if (no_matching_id && is_gesture_start) {
// A long-standing Windows issues where occasionally a GestureStart is
// encountered with no targets in the event queue. We never had a repro for
@@ -1143,9 +1167,8 @@ void RenderWidgetHostInputEventRouter::DispatchTouchscreenGestureEvent(
LOG(ERROR) << "Gesture sequence start detected with no target available.";
// It is still safe to continue; we will recalculate the target.
gfx::PointF transformed_point;
- gfx::PointF original_point(gesture_event.x, gesture_event.y);
- gfx::PointF original_point_in_screen(gesture_event.global_x,
- gesture_event.global_y);
+ gfx::PointF original_point(gesture_event.PositionInWidget());
+ gfx::PointF original_point_in_screen(gesture_event.PositionInScreen());
auto result =
FindViewAtLocation(root_view, original_point, original_point_in_screen,
viz::EventSource::TOUCH, &transformed_point);
@@ -1153,6 +1176,7 @@ void RenderWidgetHostInputEventRouter::DispatchTouchscreenGestureEvent(
// don't worry about the fact we're ignoring |result.should_query_view|, as
// this is the best we can do until we fix https://crbug.com/595422.
touchscreen_gesture_target_.target = result.view;
+ base::debug::SetCrashKeyString(target_source_key, "no_matching_id");
touchscreen_gesture_target_.delta = transformed_point - original_point;
} else if (is_gesture_start) {
touchscreen_gesture_target_ = gesture_target_it->second;
@@ -1175,10 +1199,15 @@ void RenderWidgetHostInputEventRouter::DispatchTouchscreenGestureEvent(
return;
}
- // TODO(wjmaclean): Add SetPositionInWidget() to WebGestureEvent.
blink::WebGestureEvent event(gesture_event);
- event.x += touchscreen_gesture_target_.delta.x();
- event.y += touchscreen_gesture_target_.delta.y();
+ event.SetPositionInWidget(event.PositionInWidget() +
+ touchscreen_gesture_target_.delta);
+ // Temporary logging for https://crbug.com/824774.
+ static auto* target_ptr_key = base::debug::AllocateCrashKeyString(
+ "touchscreen-gesture-target-ptr", base::debug::CrashKeySize::Size64);
+ base::debug::SetCrashKeyString(
+ target_ptr_key,
+ base::StringPrintf("%p", touchscreen_gesture_target_.target));
touchscreen_gesture_target_.target->ProcessGestureEvent(event, latency);
}
@@ -1186,7 +1215,7 @@ void RenderWidgetHostInputEventRouter::RouteTouchscreenGestureEvent(
RenderWidgetHostViewBase* root_view,
blink::WebGestureEvent* event,
const ui::LatencyInfo& latency) {
- DCHECK_EQ(blink::kWebGestureDeviceTouchscreen, event->source_device);
+ DCHECK_EQ(blink::kWebGestureDeviceTouchscreen, event->SourceDevice());
event_targeter_->FindTargetAndDispatch(root_view, *event, latency);
}
@@ -1209,7 +1238,7 @@ void RenderWidgetHostInputEventRouter::RouteTouchpadGestureEvent(
RenderWidgetHostViewBase* root_view,
blink::WebGestureEvent* event,
const ui::LatencyInfo& latency) {
- DCHECK_EQ(blink::kWebGestureDeviceTouchpad, event->source_device);
+ DCHECK_EQ(blink::kWebGestureDeviceTouchpad, event->SourceDevice());
event_targeter_->FindTargetAndDispatch(root_view, *event, latency);
}
@@ -1249,8 +1278,8 @@ void RenderWidgetHostInputEventRouter::DispatchTouchpadGestureEvent(
blink::WebGestureEvent gesture_event = touchpad_gesture_event;
// TODO(mohsen): Add tests to check event location.
- gesture_event.x += touchpad_gesture_target_.delta.x();
- gesture_event.y += touchpad_gesture_target_.delta.y();
+ gesture_event.SetPositionInWidget(gesture_event.PositionInWidget() +
+ touchpad_gesture_target_.delta);
touchpad_gesture_target_.target->ProcessGestureEvent(gesture_event, latency);
}
@@ -1293,9 +1322,15 @@ bool RenderWidgetHostInputEventRouter::TransformPointToTargetCoordSpace(
target_ancestors.push_back(target->GetFrameSinkId());
RenderWidgetHostViewBase* cur_view = target;
while (cur_view->IsRenderWidgetHostViewChildFrame()) {
- cur_view =
- static_cast<RenderWidgetHostViewChildFrame*>(cur_view)->GetParentView();
- DCHECK(cur_view);
+ if (cur_view->IsRenderWidgetHostViewGuest()) {
+ cur_view = static_cast<RenderWidgetHostViewGuest*>(cur_view)
+ ->GetOwnerRenderWidgetHostView();
+ } else {
+ cur_view = static_cast<RenderWidgetHostViewChildFrame*>(cur_view)
+ ->GetParentView();
+ }
+ if (!cur_view)
+ return false;
target_ancestors.push_back(cur_view->GetFrameSinkId());
}
DCHECK_EQ(cur_view, root_view);
@@ -1333,11 +1368,11 @@ RenderWidgetHostInputEventRouter::FindTargetSynchronously(
}
if (blink::WebInputEvent::IsGestureEventType(event.GetType())) {
auto gesture_event = static_cast<const blink::WebGestureEvent&>(event);
- if (gesture_event.source_device ==
+ if (gesture_event.SourceDevice() ==
blink::WebGestureDevice::kWebGestureDeviceTouchscreen) {
return FindTouchscreenGestureEventTarget(root_view, gesture_event);
}
- if (gesture_event.source_device ==
+ if (gesture_event.SourceDevice() ==
blink::WebGestureDevice::kWebGestureDeviceTouchpad) {
return FindTouchpadGestureEventTarget(root_view, gesture_event);
}
@@ -1372,13 +1407,13 @@ void RenderWidgetHostInputEventRouter::DispatchEventToTarget(
}
if (blink::WebInputEvent::IsGestureEventType(event.GetType())) {
auto gesture_event = static_cast<const blink::WebGestureEvent&>(event);
- if (gesture_event.source_device ==
+ if (gesture_event.SourceDevice() ==
blink::WebGestureDevice::kWebGestureDeviceTouchscreen) {
DispatchTouchscreenGestureEvent(root_view, target, gesture_event, latency,
target_location);
return;
}
- if (gesture_event.source_device ==
+ if (gesture_event.SourceDevice() ==
blink::WebGestureDevice::kWebGestureDeviceTouchpad) {
DispatchTouchpadGestureEvent(root_view, target, gesture_event, latency,
target_location);
diff --git a/chromium/content/browser/renderer_host/render_widget_host_input_event_router.h b/chromium/content/browser/renderer_host/render_widget_host_input_event_router.h
index 06fe5aec917..415a6d5c36a 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_input_event_router.h
+++ b/chromium/content/browser/renderer_host/render_widget_host_input_event_router.h
@@ -283,6 +283,8 @@ class CONTENT_EXPORT RenderWidgetHostInputEventRouter
DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostInputEventRouter);
friend class RenderWidgetHostInputEventRouterTest;
FRIEND_TEST_ALL_PREFIXES(SitePerProcessHitTestBrowserTest,
+ HitTestStaleDataDeletedView);
+ FRIEND_TEST_ALL_PREFIXES(SitePerProcessHitTestBrowserTest,
InputEventRouterGestureTargetMapTest);
FRIEND_TEST_ALL_PREFIXES(SitePerProcessHitTestBrowserTest,
InputEventRouterGesturePreventDefaultTargetMapTest);
diff --git a/chromium/content/browser/renderer_host/render_widget_host_input_event_router_unittest.cc b/chromium/content/browser/renderer_host/render_widget_host_input_event_router_unittest.cc
index dae4aed17a5..78c2efb7792 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_input_event_router_unittest.cc
+++ b/chromium/content/browser/renderer_host/render_widget_host_input_event_router_unittest.cc
@@ -6,10 +6,15 @@
#include "base/run_loop.h"
#include "base/test/scoped_task_environment.h"
+#include "build/build_config.h"
+#include "content/browser/compositor/test/test_image_transport_factory.h"
+#include "content/browser/renderer_host/frame_connector_delegate.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
+#include "content/browser/renderer_host/render_widget_host_view_child_frame.h"
#include "content/browser/renderer_host/render_widget_targeter.h"
#include "content/public/test/mock_render_process_host.h"
#include "content/public/test/test_browser_context.h"
+#include "content/public/test/test_browser_thread_bundle.h"
#include "content/test/mock_render_widget_host_delegate.h"
#include "content/test/mock_widget_impl.h"
#include "content/test/test_render_view_host.h"
@@ -20,15 +25,36 @@ namespace content {
namespace {
+class MockFrameConnectorDelegate : public FrameConnectorDelegate {
+ public:
+ MockFrameConnectorDelegate(bool use_zoom_for_device_scale_factor)
+ : FrameConnectorDelegate(use_zoom_for_device_scale_factor) {}
+ ~MockFrameConnectorDelegate() override {}
+
+ RenderWidgetHostViewBase* GetRootRenderWidgetHostView() override {
+ return root_view_;
+ }
+
+ void set_root_view(RenderWidgetHostViewBase* root_view) {
+ root_view_ = root_view;
+ }
+
+ private:
+ RenderWidgetHostViewBase* root_view_;
+
+ DISALLOW_COPY_AND_ASSIGN(MockFrameConnectorDelegate);
+};
+
// Used as a target for the RenderWidgetHostInputEventRouter. We record what
// events were forwarded to us in order to verify that the events are being
// routed correctly.
-class MockRenderWidgetHostView : public TestRenderWidgetHostView {
+class TestRenderWidgetHostViewChildFrame
+ : public RenderWidgetHostViewChildFrame {
public:
- MockRenderWidgetHostView(RenderWidgetHost* rwh)
- : TestRenderWidgetHostView(rwh),
+ explicit TestRenderWidgetHostViewChildFrame(RenderWidgetHost* widget)
+ : RenderWidgetHostViewChildFrame(widget),
last_gesture_seen_(blink::WebInputEvent::kUndefined) {}
- ~MockRenderWidgetHostView() override {}
+ ~TestRenderWidgetHostViewChildFrame() override = default;
void ProcessGestureEvent(const blink::WebGestureEvent& event,
const ui::LatencyInfo&) override {
@@ -53,15 +79,16 @@ class MockRenderWidgetHostView : public TestRenderWidgetHostView {
// The RenderWidgetHostInputEventRouter uses the root RWHV for hittesting, so
// here we stub out the hittesting logic so we can control which RWHV will be
// the result of a hittest by the RWHIER.
-class MockRootRenderWidgetHostView : public MockRenderWidgetHostView {
+class MockRootRenderWidgetHostView : public TestRenderWidgetHostView {
public:
MockRootRenderWidgetHostView(
RenderWidgetHost* rwh,
- std::map<MockRenderWidgetHostView*, viz::FrameSinkId>& frame_sink_id_map)
- : MockRenderWidgetHostView(rwh),
+ std::map<RenderWidgetHostViewBase*, viz::FrameSinkId>& frame_sink_id_map)
+ : TestRenderWidgetHostView(rwh),
frame_sink_id_map_(frame_sink_id_map),
current_hittest_result_(nullptr),
- force_query_renderer_on_hit_test_(false) {}
+ force_query_renderer_on_hit_test_(false),
+ last_gesture_seen_(blink::WebInputEvent::kUndefined) {}
~MockRootRenderWidgetHostView() override {}
viz::FrameSinkId FrameSinkIdAtPoint(viz::SurfaceHittestDelegate*,
@@ -82,7 +109,20 @@ class MockRootRenderWidgetHostView : public MockRenderWidgetHostView {
return true;
}
- void SetHittestResult(MockRenderWidgetHostView* view) {
+ void ProcessGestureEvent(const blink::WebGestureEvent& event,
+ const ui::LatencyInfo&) override {
+ last_gesture_seen_ = event.GetType();
+ }
+
+ void ProcessAckedTouchEvent(const TouchEventWithLatencyInfo& touch,
+ InputEventAckState ack_result) override {
+ unique_id_for_last_touch_ack_ = touch.event.unique_touch_event_id;
+ }
+
+ blink::WebInputEvent::Type last_gesture_seen() { return last_gesture_seen_; }
+ uint32_t last_id_for_touch_ack() { return unique_id_for_last_touch_ack_; }
+
+ void SetHittestResult(RenderWidgetHostViewBase* view) {
current_hittest_result_ = view;
}
@@ -90,24 +130,34 @@ class MockRootRenderWidgetHostView : public MockRenderWidgetHostView {
force_query_renderer_on_hit_test_ = force;
}
+ void Reset() { last_gesture_seen_ = blink::WebInputEvent::kUndefined; }
+
private:
- std::map<MockRenderWidgetHostView*, viz::FrameSinkId>& frame_sink_id_map_;
- MockRenderWidgetHostView* current_hittest_result_;
+ std::map<RenderWidgetHostViewBase*, viz::FrameSinkId>& frame_sink_id_map_;
+ RenderWidgetHostViewBase* current_hittest_result_;
bool force_query_renderer_on_hit_test_;
+ blink::WebInputEvent::Type last_gesture_seen_;
+ uint32_t unique_id_for_last_touch_ack_ = 0;
};
} // namespace
class RenderWidgetHostInputEventRouterTest : public testing::Test {
public:
- RenderWidgetHostInputEventRouterTest()
- : scoped_task_environment_(
- base::test::ScopedTaskEnvironment::MainThreadType::UI) {}
+ RenderWidgetHostInputEventRouterTest() {}
protected:
// testing::Test:
void SetUp() override {
browser_context_ = std::make_unique<TestBrowserContext>();
+
+// ImageTransportFactory doesn't exist on Android. This is needed to create
+// a RenderWidgetHostViewChildFrame in the test.
+#if !defined(OS_ANDROID)
+ ImageTransportFactory::SetFactory(
+ std::make_unique<TestImageTransportFactory>());
+#endif
+
process_host1_ =
std::make_unique<MockRenderProcessHost>(browser_context_.get());
process_host2_ =
@@ -127,8 +177,14 @@ class RenderWidgetHostInputEventRouterTest : public testing::Test {
view_root_ = std::make_unique<MockRootRenderWidgetHostView>(
widget_host1_.get(), frame_sink_id_map_);
- view_other_ =
- std::make_unique<MockRenderWidgetHostView>(widget_host2_.get());
+ view_other_ = std::make_unique<TestRenderWidgetHostViewChildFrame>(
+ widget_host2_.get());
+
+ test_frame_connector_ = std::make_unique<MockFrameConnectorDelegate>(
+ false /* use_zoom_for_device_scale_factor */);
+ test_frame_connector_->set_root_view(view_root_.get());
+ test_frame_connector_->SetView(view_other_.get());
+ view_other_->SetFrameConnectorDelegate(test_frame_connector_.get());
// Set up the RWHIER's FrameSinkId to RWHV map so that we can control the
// result of RWHIER's hittesting.
@@ -140,7 +196,14 @@ class RenderWidgetHostInputEventRouterTest : public testing::Test {
view_other_.get());
}
- void TearDown() override { base::RunLoop().RunUntilIdle(); }
+ void TearDown() override {
+ view_root_.reset();
+ view_other_.reset();
+ base::RunLoop().RunUntilIdle();
+#if !defined(OS_ANDROID)
+ ImageTransportFactory::Terminate();
+#endif
+ }
RenderWidgetHostViewBase* touch_target() {
return rwhier_.touch_target_.target;
@@ -149,8 +212,7 @@ class RenderWidgetHostInputEventRouterTest : public testing::Test {
return rwhier_.touchscreen_gesture_target_.target;
}
- // Needed by RenderWidgetHostImpl constructor.
- base::test::ScopedTaskEnvironment scoped_task_environment_;
+ TestBrowserThreadBundle thread_bundle_;
MockRenderWidgetHostDelegate delegate_;
std::unique_ptr<BrowserContext> browser_context_;
@@ -162,12 +224,12 @@ class RenderWidgetHostInputEventRouterTest : public testing::Test {
std::unique_ptr<RenderWidgetHostImpl> widget_host2_;
std::unique_ptr<MockRootRenderWidgetHostView> view_root_;
- std::unique_ptr<MockRenderWidgetHostView> view_other_;
+ std::unique_ptr<TestRenderWidgetHostViewChildFrame> view_other_;
+ std::unique_ptr<MockFrameConnectorDelegate> test_frame_connector_;
- std::map<MockRenderWidgetHostView*, viz::FrameSinkId> frame_sink_id_map_;
+ std::map<RenderWidgetHostViewBase*, viz::FrameSinkId> frame_sink_id_map_;
RenderWidgetHostInputEventRouter rwhier_;
- TestBrowserThreadBundle thread_bundle_;
private:
DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostInputEventRouterTest);
@@ -198,8 +260,8 @@ TEST_F(RenderWidgetHostInputEventRouterTest,
blink::WebGestureEvent gesture_event(
blink::WebInputEvent::kGestureTapDown, blink::WebInputEvent::kNoModifiers,
- blink::WebInputEvent::GetStaticTimeStampForTests());
- gesture_event.source_device = blink::kWebGestureDeviceTouchscreen;
+ blink::WebInputEvent::GetStaticTimeStampForTests(),
+ blink::kWebGestureDeviceTouchscreen);
gesture_event.unique_touch_event_id = touch_event.unique_touch_event_id;
rwhier_.RouteGestureEvent(view_root_.get(), &gesture_event,
@@ -389,8 +451,8 @@ TEST_F(RenderWidgetHostInputEventRouterTest, DoNotCoalesceGestureEvents) {
blink::WebGestureEvent gesture_event(
blink::WebInputEvent::kGestureTapDown, blink::WebInputEvent::kNoModifiers,
- blink::WebInputEvent::GetStaticTimeStampForTests());
- gesture_event.source_device = blink::kWebGestureDeviceTouchscreen;
+ blink::WebInputEvent::GetStaticTimeStampForTests(),
+ blink::kWebGestureDeviceTouchscreen);
gesture_event.unique_touch_event_id = touch_event.unique_touch_event_id;
rwhier_.RouteGestureEvent(view_root_.get(), &gesture_event,
ui::LatencyInfo(ui::SourceEventType::TOUCH));
diff --git a/chromium/content/browser/renderer_host/render_widget_host_ns_view_bridge.h b/chromium/content/browser/renderer_host/render_widget_host_ns_view_bridge.h
new file mode 100644
index 00000000000..e0ffad96974
--- /dev/null
+++ b/chromium/content/browser/renderer_host/render_widget_host_ns_view_bridge.h
@@ -0,0 +1,101 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_NS_VIEW_BRIDGE_H_
+#define CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_NS_VIEW_BRIDGE_H_
+
+@class RenderWidgetHostViewCocoa;
+
+#include <memory>
+
+#include "base/macros.h"
+#include "base/strings/string16.h"
+#include "content/common/mac/attributed_string_coder.h"
+#include "third_party/blink/public/web/web_popup_type.h"
+#include "third_party/skia/include/core/SkColor.h"
+
+namespace gfx {
+class Point;
+class Range;
+class Rect;
+} // namespace gfx
+
+namespace content {
+
+class RenderWidgetHostNSViewClient;
+class WebCursor;
+
+// The interface through which RenderWidgetHostViewMac is to manipulate its
+// corresponding NSView (potentially in another process).
+class RenderWidgetHostNSViewBridge {
+ public:
+ RenderWidgetHostNSViewBridge() {}
+ virtual ~RenderWidgetHostNSViewBridge() {}
+
+ static std::unique_ptr<RenderWidgetHostNSViewBridge> Create(
+ RenderWidgetHostNSViewClient* client);
+
+ // TODO(ccameron): RenderWidgetHostViewMac and other functions currently use
+ // this method to communicate directly with RenderWidgetHostViewCocoa. The
+ // goal of this class is to eliminate this direct communication (so this
+ // method is expected to go away).
+ virtual RenderWidgetHostViewCocoa* GetRenderWidgetHostViewCocoa() = 0;
+
+ // Initialize the window as a popup (e.g, date/time picker).
+ virtual void InitAsPopup(const gfx::Rect& content_rect,
+ blink::WebPopupType popup_type) = 0;
+
+ // Make the NSView be the first responder of its NSWindow.
+ virtual void MakeFirstResponder() = 0;
+
+ // Set the bounds of the NSView or its enclosing NSWindow (depending on the
+ // window type).
+ virtual void SetBounds(const gfx::Rect& rect) = 0;
+
+ // Set the background color of the hosted CALayer.
+ virtual void SetBackgroundColor(SkColor color) = 0;
+
+ // Call the -[NSView setHidden:] method.
+ virtual void SetVisible(bool visible) = 0;
+
+ // Call the -[NSView setToolTipAtMousePoint] method.
+ virtual void SetTooltipText(const base::string16& display_text) = 0;
+
+ // Forward the TextInputManager::TextSelection from the renderer.
+ virtual void SetTextSelection(const base::string16& text,
+ size_t offset,
+ const gfx::Range& range) = 0;
+
+ // Forward the TextInputManager::CompositionRangeInfo from the renderer.
+ virtual void SetCompositionRangeInfo(const gfx::Range& range) = 0;
+
+ // Clear the marked range.
+ virtual void CancelComposition() = 0;
+
+ // Indicate if the WebContext is showing a context menu.
+ virtual void SetShowingContextMenu(bool showing) = 0;
+
+ // Set the cursor type to display.
+ virtual void DisplayCursor(const WebCursor& cursor) = 0;
+
+ // Lock or unlock the cursor.
+ virtual void SetCursorLocked(bool locked) = 0;
+
+ // Open the dictionary overlay for the currently selected string. This
+ // will roundtrip to the NSView to determine the selected range.
+ virtual void ShowDictionaryOverlayForSelection() = 0;
+
+ // Open the dictionary overlay for the specified string at the specified
+ // point.
+ virtual void ShowDictionaryOverlay(
+ const mac::AttributedStringCoder::EncodedString& encoded_string,
+ gfx::Point baseline_point) = 0;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostNSViewBridge);
+};
+
+} // namespace content
+
+#endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_NS_VIEW_BRIDGE_H_
diff --git a/chromium/content/browser/renderer_host/render_widget_host_ns_view_bridge.mm b/chromium/content/browser/renderer_host/render_widget_host_ns_view_bridge.mm
new file mode 100644
index 00000000000..ce3cc68af90
--- /dev/null
+++ b/chromium/content/browser/renderer_host/render_widget_host_ns_view_bridge.mm
@@ -0,0 +1,286 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#import "content/browser/renderer_host/render_widget_host_ns_view_bridge.h"
+
+#import <Cocoa/Cocoa.h>
+
+#include "base/mac/scoped_cftyperef.h"
+#import "base/mac/scoped_nsobject.h"
+#include "base/strings/sys_string_conversions.h"
+#import "content/browser/renderer_host/popup_window_mac.h"
+#import "content/browser/renderer_host/render_widget_host_view_cocoa.h"
+#include "content/common/cursors/webcursor.h"
+#import "skia/ext/skia_utils_mac.h"
+#import "ui/base/cocoa/animation_utils.h"
+#include "ui/display/display_observer.h"
+#include "ui/display/screen.h"
+#include "ui/gfx/mac/coordinate_conversion.h"
+
+namespace content {
+
+namespace {
+
+// Bridge to a locally-hosted NSView -- this is always instantiated in the same
+// process as the NSView. The caller of this interface may exist in another
+// process.
+class RenderWidgetHostViewNSViewBridgeLocal
+ : public RenderWidgetHostNSViewBridge,
+ public display::DisplayObserver {
+ public:
+ explicit RenderWidgetHostViewNSViewBridgeLocal(
+ RenderWidgetHostNSViewClient* client);
+ ~RenderWidgetHostViewNSViewBridgeLocal() override;
+ RenderWidgetHostViewCocoa* GetRenderWidgetHostViewCocoa() override;
+
+ void InitAsPopup(const gfx::Rect& content_rect,
+ blink::WebPopupType popup_type) override;
+ void MakeFirstResponder() override;
+ void SetBounds(const gfx::Rect& rect) override;
+ void SetBackgroundColor(SkColor color) override;
+ void SetVisible(bool visible) override;
+ void SetTooltipText(const base::string16& display_text) override;
+ void SetTextSelection(const base::string16& text,
+ size_t offset,
+ const gfx::Range& range) override;
+ void SetCompositionRangeInfo(const gfx::Range& range) override;
+ void CancelComposition() override;
+ void SetShowingContextMenu(bool showing) override;
+ void DisplayCursor(const WebCursor& cursor) override;
+ void SetCursorLocked(bool locked) override;
+ void ShowDictionaryOverlayForSelection() override;
+ void ShowDictionaryOverlay(
+ const mac::AttributedStringCoder::EncodedString& encoded_string,
+ gfx::Point baseline_point) override;
+
+ private:
+ bool IsPopup() const {
+ // TODO(ccameron): If this is not equivalent to |popup_window_| then
+ // there are bugs.
+ return popup_type_ != blink::kWebPopupTypeNone;
+ }
+
+ // display::DisplayObserver implementation.
+ void OnDisplayMetricsChanged(const display::Display& display,
+ uint32_t metrics) override;
+
+ // The NSView used for input and display.
+ base::scoped_nsobject<RenderWidgetHostViewCocoa> cocoa_view_;
+
+ // The window used for popup widgets, and its helper.
+ std::unique_ptr<PopupWindowMac> popup_window_;
+ blink::WebPopupType popup_type_ = blink::kWebPopupTypeNone;
+
+ // The background CoreAnimation layer which is hosted by |cocoa_view_|.
+ base::scoped_nsobject<CALayer> background_layer_;
+
+ // Cached copy of the tooltip text, to avoid redundant calls.
+ base::string16 tooltip_text_;
+
+ DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostViewNSViewBridgeLocal);
+};
+
+RenderWidgetHostViewNSViewBridgeLocal::RenderWidgetHostViewNSViewBridgeLocal(
+ RenderWidgetHostNSViewClient* client) {
+ display::Screen::GetScreen()->AddObserver(this);
+
+ cocoa_view_.reset([[RenderWidgetHostViewCocoa alloc] initWithClient:client]);
+
+ background_layer_.reset([[CALayer alloc] init]);
+ [cocoa_view_ setLayer:background_layer_];
+ [cocoa_view_ setWantsLayer:YES];
+}
+
+RenderWidgetHostViewNSViewBridgeLocal::
+ ~RenderWidgetHostViewNSViewBridgeLocal() {
+ [cocoa_view_ setClientDisconnected];
+ // Do not immediately remove |cocoa_view_| from the NSView heirarchy, because
+ // the call to -[NSView removeFromSuperview] may cause use to call into the
+ // RWHVMac during tear-down, via WebContentsImpl::UpdateWebContentsVisibility.
+ // https://crbug.com/834931
+ [cocoa_view_ performSelector:@selector(removeFromSuperview)
+ withObject:nil
+ afterDelay:0];
+ cocoa_view_.autorelease();
+ display::Screen::GetScreen()->RemoveObserver(this);
+ popup_window_.reset();
+}
+
+RenderWidgetHostViewCocoa*
+RenderWidgetHostViewNSViewBridgeLocal::GetRenderWidgetHostViewCocoa() {
+ return cocoa_view_;
+}
+
+void RenderWidgetHostViewNSViewBridgeLocal::InitAsPopup(
+ const gfx::Rect& content_rect,
+ blink::WebPopupType popup_type) {
+ popup_type_ = popup_type;
+ popup_window_ =
+ std::make_unique<PopupWindowMac>(content_rect, popup_type_, cocoa_view_);
+}
+
+void RenderWidgetHostViewNSViewBridgeLocal::MakeFirstResponder() {
+ [[cocoa_view_ window] makeFirstResponder:cocoa_view_];
+}
+
+void RenderWidgetHostViewNSViewBridgeLocal::SetBounds(const gfx::Rect& rect) {
+ // |rect.size()| is view coordinates, |rect.origin| is screen coordinates,
+ // TODO(thakis): fix, http://crbug.com/73362
+
+ // During the initial creation of the RenderWidgetHostView in
+ // WebContentsImpl::CreateRenderViewForRenderManager, SetSize is called with
+ // an empty size. In the Windows code flow, it is not ignored because
+ // subsequent sizing calls from the OS flow through TCVW::WasSized which calls
+ // SetSize() again. On Cocoa, we rely on the Cocoa view struture and resizer
+ // flags to keep things sized properly. On the other hand, if the size is not
+ // empty then this is a valid request for a pop-up.
+ if (rect.size().IsEmpty())
+ return;
+
+ // Ignore the position of |rect| for non-popup rwhvs. This is because
+ // background tabs do not have a window, but the window is required for the
+ // coordinate conversions. Popups are always for a visible tab.
+ //
+ // Note: If |cocoa_view_| has been removed from the view hierarchy, it's still
+ // valid for resizing to be requested (e.g., during tab capture, to size the
+ // view to screen-capture resolution). In this case, simply treat the view as
+ // relative to the screen.
+ BOOL isRelativeToScreen =
+ IsPopup() || ![[cocoa_view_ superview] isKindOfClass:[BaseView class]];
+ if (isRelativeToScreen) {
+ // The position of |rect| is screen coordinate system and we have to
+ // consider Cocoa coordinate system is upside-down and also multi-screen.
+ NSRect frame = gfx::ScreenRectToNSRect(rect);
+ if (IsPopup())
+ [popup_window_->window() setFrame:frame display:YES];
+ else
+ [cocoa_view_ setFrame:frame];
+ } else {
+ BaseView* superview = static_cast<BaseView*>([cocoa_view_ superview]);
+ gfx::Rect rect2 = [superview flipNSRectToRect:[cocoa_view_ frame]];
+ rect2.set_width(rect.width());
+ rect2.set_height(rect.height());
+ [cocoa_view_ setFrame:[superview flipRectToNSRect:rect2]];
+ }
+}
+
+void RenderWidgetHostViewNSViewBridgeLocal::SetBackgroundColor(SkColor color) {
+ ScopedCAActionDisabler disabler;
+ base::ScopedCFTypeRef<CGColorRef> cg_color(
+ skia::CGColorCreateFromSkColor(color));
+ [background_layer_ setBackgroundColor:cg_color];
+}
+
+void RenderWidgetHostViewNSViewBridgeLocal::SetVisible(bool visible) {
+ ScopedCAActionDisabler disabler;
+ [cocoa_view_ setHidden:!visible];
+}
+
+void RenderWidgetHostViewNSViewBridgeLocal::SetTooltipText(
+ const base::string16& tooltip_text) {
+ // Called from the renderer to tell us what the tooltip text should be. It
+ // calls us frequently so we need to cache the value to prevent doing a lot
+ // of repeat work.
+ if (tooltip_text == tooltip_text_ || ![[cocoa_view_ window] isKeyWindow])
+ return;
+ tooltip_text_ = tooltip_text;
+
+ // Maximum number of characters we allow in a tooltip.
+ const size_t kMaxTooltipLength = 1024;
+
+ // Clamp the tooltip length to kMaxTooltipLength. It's a DOS issue on
+ // Windows; we're just trying to be polite. Don't persist the trimmed
+ // string, as then the comparison above will always fail and we'll try to
+ // set it again every single time the mouse moves.
+ base::string16 display_text = tooltip_text_;
+ if (tooltip_text_.length() > kMaxTooltipLength)
+ display_text = tooltip_text_.substr(0, kMaxTooltipLength);
+
+ NSString* tooltip_nsstring = base::SysUTF16ToNSString(display_text);
+ [cocoa_view_ setToolTipAtMousePoint:tooltip_nsstring];
+}
+
+void RenderWidgetHostViewNSViewBridgeLocal::SetCompositionRangeInfo(
+ const gfx::Range& range) {
+ [cocoa_view_ setCompositionRange:range];
+ [cocoa_view_ setMarkedRange:range.ToNSRange()];
+}
+
+void RenderWidgetHostViewNSViewBridgeLocal::CancelComposition() {
+ [cocoa_view_ cancelComposition];
+}
+
+void RenderWidgetHostViewNSViewBridgeLocal::SetTextSelection(
+ const base::string16& text,
+ size_t offset,
+ const gfx::Range& range) {
+ [cocoa_view_ setTextSelectionText:text offset:offset range:range];
+ // Updates markedRange when there is no marked text so that retrieving
+ // markedRange immediately after calling setMarkdText: returns the current
+ // caret position.
+ if (![cocoa_view_ hasMarkedText]) {
+ [cocoa_view_ setMarkedRange:range.ToNSRange()];
+ }
+}
+
+void RenderWidgetHostViewNSViewBridgeLocal::SetShowingContextMenu(
+ bool showing) {
+ [cocoa_view_ setShowingContextMenu:showing];
+}
+
+void RenderWidgetHostViewNSViewBridgeLocal::OnDisplayMetricsChanged(
+ const display::Display& display,
+ uint32_t changed_metrics) {
+ // Note that -updateScreenProperties is also be called by the notification
+ // NSWindowDidChangeBackingPropertiesNotification (some of these calls
+ // will be redundant).
+ [cocoa_view_ updateScreenProperties];
+}
+
+void RenderWidgetHostViewNSViewBridgeLocal::DisplayCursor(
+ const WebCursor& cursor) {
+ WebCursor non_const_cursor = cursor;
+ [cocoa_view_ updateCursor:non_const_cursor.GetNativeCursor()];
+}
+
+void RenderWidgetHostViewNSViewBridgeLocal::SetCursorLocked(bool locked) {
+ if (locked) {
+ CGAssociateMouseAndMouseCursorPosition(NO);
+ [NSCursor hide];
+ } else {
+ // Unlock position of mouse cursor and unhide it.
+ CGAssociateMouseAndMouseCursorPosition(YES);
+ [NSCursor unhide];
+ }
+}
+
+void RenderWidgetHostViewNSViewBridgeLocal::
+ ShowDictionaryOverlayForSelection() {
+ NSRange selection_range = [cocoa_view_ selectedRange];
+ [cocoa_view_ showLookUpDictionaryOverlayFromRange:selection_range];
+}
+
+void RenderWidgetHostViewNSViewBridgeLocal::ShowDictionaryOverlay(
+ const mac::AttributedStringCoder::EncodedString& encoded_string,
+ gfx::Point baseline_point) {
+ NSAttributedString* string =
+ mac::AttributedStringCoder::Decode(&encoded_string);
+ if ([string length] == 0)
+ return;
+ NSPoint flipped_baseline_point = {
+ baseline_point.x(), [cocoa_view_ frame].size.height - baseline_point.y(),
+ };
+ [cocoa_view_ showDefinitionForAttributedString:string
+ atPoint:flipped_baseline_point];
+}
+
+} // namespace
+
+// static
+std::unique_ptr<RenderWidgetHostNSViewBridge>
+RenderWidgetHostNSViewBridge::Create(RenderWidgetHostNSViewClient* client) {
+ return std::make_unique<RenderWidgetHostViewNSViewBridgeLocal>(client);
+}
+
+} // namespace content
diff --git a/chromium/content/browser/renderer_host/render_widget_host_ns_view_client.h b/chromium/content/browser/renderer_host/render_widget_host_ns_view_client.h
new file mode 100644
index 00000000000..25c14510b94
--- /dev/null
+++ b/chromium/content/browser/renderer_host/render_widget_host_ns_view_client.h
@@ -0,0 +1,192 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_NS_VIEW_CLIENT_H_
+#define CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_NS_VIEW_CLIENT_H_
+
+#include "base/macros.h"
+#include "base/strings/string16.h"
+#include "content/common/edit_command.h"
+#include "content/common/mac/attributed_string_coder.h"
+#include "ui/base/ime/ime_text_span.h"
+#include "ui/base/ime/text_input_type.h"
+
+namespace blink {
+class WebGestureEvent;
+class WebMouseEvent;
+class WebMouseWheelEvent;
+} // namespace blink
+
+namespace display {
+class Display;
+} // namespace display
+
+namespace gfx {
+class PointF;
+class Range;
+class Rect;
+} // namespace gfx
+
+namespace ui {
+class LatencyInfo;
+} // namespace ui
+
+namespace content {
+
+class RenderWidgetHostViewMac;
+
+// The interface through which the NSView for a RenderWidgetHostViewMac is to
+// communicate with the RenderWidgetHostViewMac (potentially in another
+// process).
+class RenderWidgetHostNSViewClient {
+ public:
+ RenderWidgetHostNSViewClient() {}
+ virtual ~RenderWidgetHostNSViewClient() {}
+
+ // Return the RenderWidget's BrowserAccessibilityManager.
+ // TODO(ccameron): This returns nullptr for non-local NSViews. A scheme for
+ // non-local accessibility needs to be developed.
+ virtual BrowserAccessibilityManager* GetRootBrowserAccessibilityManager() = 0;
+
+ // Synchronously query if there exists a RenderViewHost for the corresponding
+ // RenderWidgetHostView's RenderWidgetHost, and store the result in
+ // |*is_render_view|.
+ virtual void OnNSViewSyncIsRenderViewHost(bool* is_render_view) = 0;
+
+ // Indicates that the RenderWidgetHost is to shut down.
+ virtual void OnNSViewRequestShutdown() = 0;
+
+ // Indicates whether or not the NSView is its NSWindow's first responder.
+ virtual void OnNSViewIsFirstResponderChanged(bool is_first_responder) = 0;
+
+ // Indicates whether or not the NSView's NSWindow is key.
+ virtual void OnNSViewWindowIsKeyChanged(bool is_key) = 0;
+
+ // Indicates the NSView's bounds in its NSWindow's DIP coordinate system (with
+ // the origin at the upper-left corner), and indicate if the the NSView is
+ // attached to an NSWindow (if it is not, then |view_bounds_in_window_dip|'s
+ // origin is meaningless, but its size is still relevant).
+ virtual void OnNSViewBoundsInWindowChanged(
+ const gfx::Rect& view_bounds_in_window_dip,
+ bool attached_to_window) = 0;
+
+ // Indicates the NSView's NSWindow's frame in the global display::Screen
+ // DIP coordinate system (where the origin the upper-left corner of
+ // Screen::GetPrimaryDisplay).
+ virtual void OnNSViewWindowFrameInScreenChanged(
+ const gfx::Rect& window_frame_in_screen_dip) = 0;
+
+ // Indicate the NSView's NSScreen's properties.
+ virtual void OnNSViewDisplayChanged(const display::Display& display) = 0;
+
+ // Indicate the begin and end block of a keyboard event. The beginning of this
+ // block will record the active RenderWidgetHost, and will forward all
+ // remaining keyboard and Ime messages to that RenderWidgetHost.
+ virtual void OnNSViewBeginKeyboardEvent() = 0;
+ virtual void OnNSViewEndKeyboardEvent() = 0;
+
+ // Forward a keyboard event to the RenderWidgetHost that is currently handling
+ // the key-down event.
+ virtual void OnNSViewForwardKeyboardEvent(
+ const NativeWebKeyboardEvent& key_event,
+ const ui::LatencyInfo& latency_info) = 0;
+ virtual void OnNSViewForwardKeyboardEventWithCommands(
+ const NativeWebKeyboardEvent& key_event,
+ const ui::LatencyInfo& latency_info,
+ const std::vector<EditCommand>& commands) = 0;
+
+ // Forward events to the renderer or the input router, as appropriate.
+ virtual void OnNSViewRouteOrProcessMouseEvent(
+ const blink::WebMouseEvent& web_event) = 0;
+ virtual void OnNSViewRouteOrProcessWheelEvent(
+ const blink::WebMouseWheelEvent& web_event) = 0;
+
+ // Special case forwarding of synthetic events to the renderer.
+ virtual void OnNSViewForwardMouseEvent(
+ const blink::WebMouseEvent& web_event) = 0;
+ virtual void OnNSViewForwardWheelEvent(
+ const blink::WebMouseWheelEvent& web_event) = 0;
+
+ // Handling pinch gesture events.
+ virtual void OnNSViewGestureBegin(blink::WebGestureEvent begin_event) = 0;
+ virtual void OnNSViewGestureUpdate(blink::WebGestureEvent update_event) = 0;
+ virtual void OnNSViewGestureEnd(blink::WebGestureEvent end_event) = 0;
+ virtual void OnNSViewSmartMagnify(
+ const blink::WebGestureEvent& smart_magnify_event) = 0;
+
+ // Forward the corresponding Ime commands to the appropriate RenderWidgetHost.
+ // Appropriate, has two meanings here. If this is during a key-down event,
+ // then the target is the RWH that is handling that key-down event. Otherwise,
+ // it is the result of GetActiveWidget.
+ virtual void OnNSViewImeSetComposition(
+ const base::string16& text,
+ const std::vector<ui::ImeTextSpan>& ime_text_spans,
+ const gfx::Range& replacement_range,
+ int selection_start,
+ int selection_end) = 0;
+ virtual void OnNSViewImeCommitText(const base::string16& text,
+ const gfx::Range& replacement_range) = 0;
+ virtual void OnNSViewImeFinishComposingText() = 0;
+ virtual void OnNSViewImeCancelComposition() = 0;
+
+ // Request an overlay dictionary be displayed for the text at the specified
+ // point.
+ virtual void OnNSViewLookUpDictionaryOverlayAtPoint(
+ const gfx::PointF& root_point) = 0;
+
+ // Request an overlay dictionary be displayed for the text in the the
+ // specified character range.
+ virtual void OnNSViewLookUpDictionaryOverlayFromRange(
+ const gfx::Range& range) = 0;
+
+ // Synchronously query the text input type from the
+ virtual void OnNSViewSyncGetTextInputType(
+ ui::TextInputType* text_input_type) = 0;
+
+ // Synchronously query the character index for |root_point| and return it in
+ // |*index|. Sets it to UINT32_MAX if the request fails or is not completed.
+ virtual void OnNSViewSyncGetCharacterIndexAtPoint(
+ const gfx::PointF& root_point,
+ uint32_t* index) = 0;
+
+ // Synchronously query the composition character boundary rectangle and return
+ // it in |*rect|. Set |*actual_range| to the range actually used for the
+ // returned rectangle. If there was no focused RenderWidgetHost to query,
+ // then set |*success| to false.
+ virtual void OnNSViewSyncGetFirstRectForRange(
+ const gfx::Range& requested_range,
+ gfx::Rect* rect,
+ gfx::Range* actual_range,
+ bool* success) = 0;
+
+ // Forward the corresponding edit menu command to the RenderWidgetHost's
+ // delegate.
+ virtual void OnNSViewExecuteEditCommand(const std::string& command) = 0;
+ virtual void OnNSViewUndo() = 0;
+ virtual void OnNSViewRedo() = 0;
+ virtual void OnNSViewCut() = 0;
+ virtual void OnNSViewCopy() = 0;
+ virtual void OnNSViewCopyToFindPboard() = 0;
+ virtual void OnNSViewPaste() = 0;
+ virtual void OnNSViewPasteAndMatchStyle() = 0;
+ virtual void OnNSViewSelectAll() = 0;
+
+ // Speak the selected text of the appropriate RenderWidgetHostView using
+ // TextServicesContextMenu.
+ virtual void OnNSViewSpeakSelection() = 0;
+
+ // Stop speaking using TextServicesContextMenu.
+ virtual void OnNSViewStopSpeaking() = 0;
+
+ // Synchronously query if TextServicesContextMenu is currently speaking and
+ // store the result in |*is_speaking|.
+ virtual void OnNSViewSyncIsSpeaking(bool* is_speaking) = 0;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostNSViewClient);
+};
+
+} // namespace content
+
+#endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_NS_VIEW_CLIENT_H_
diff --git a/chromium/content/browser/renderer_host/render_widget_host_owner_delegate.h b/chromium/content/browser/renderer_host/render_widget_host_owner_delegate.h
index 3878691b3ed..409e8efb2a7 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_owner_delegate.h
+++ b/chromium/content/browser/renderer_host/render_widget_host_owner_delegate.h
@@ -53,6 +53,10 @@ class CONTENT_EXPORT RenderWidgetHostOwnerDelegate {
virtual bool MayRenderWidgetForwardKeyboardEvent(
const NativeWebKeyboardEvent& key_event) = 0;
+ // Allow OwnerDelegate to control whether its RenderWidgetHost contributes
+ // priority to the RenderProcessHost.
+ virtual bool ShouldContributePriorityToProcess() = 0;
+
protected:
virtual ~RenderWidgetHostOwnerDelegate() {}
};
diff --git a/chromium/content/browser/renderer_host/render_widget_host_unittest.cc b/chromium/content/browser/renderer_host/render_widget_host_unittest.cc
index 430d49e981e..ec9145eab42 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_unittest.cc
+++ b/chromium/content/browser/renderer_host/render_widget_host_unittest.cc
@@ -15,7 +15,9 @@
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
+#include "base/test/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
+#include "base/test/simple_test_tick_clock.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/timer/timer.h"
#include "build/build_config.h"
@@ -131,6 +133,7 @@ class MockInputRouter : public InputRouter {
bool frame_handler) override {}
void ProgressFling(base::TimeTicks time) override {}
void StopFling() override {}
+ bool FlingCancellationIsDeferred() override { return false; }
// IPC::Listener
bool OnMessageReceived(const IPC::Message& message) override {
@@ -220,6 +223,20 @@ class MockRenderWidgetHost : public RenderWidgetHostImpl {
}
}
+ void ExpectForceEnableZoom(bool enable) {
+ EXPECT_EQ(enable, force_enable_zoom_);
+
+ if (base::FeatureList::IsEnabled(features::kMojoInputMessages)) {
+ InputRouterImpl* input_router =
+ static_cast<InputRouterImpl*>(input_router_.get());
+ EXPECT_EQ(enable, input_router->touch_action_filter_.force_enable_zoom_);
+ } else {
+ LegacyInputRouterImpl* input_router =
+ static_cast<LegacyInputRouterImpl*>(input_router_.get());
+ EXPECT_EQ(enable, input_router->touch_action_filter_.force_enable_zoom_);
+ }
+ }
+
WebInputEvent::Type acked_touch_event_type() const {
return acked_touch_event_type_;
}
@@ -3054,6 +3071,26 @@ TEST_F(RenderWidgetHostTest, InflightEventCountResetsAfterRebind) {
EXPECT_EQ(0u, host_->in_flight_event_count());
}
+TEST_F(RenderWidgetHostTest, ForceEnableZoomShouldUpdateAfterRebind) {
+ SCOPED_TRACE("force_enable_zoom is false at start.");
+ host_->ExpectForceEnableZoom(false);
+
+ // Set force_enable_zoom true.
+ host_->SetForceEnableZoom(true);
+
+ SCOPED_TRACE("force_enable_zoom is true after set.");
+ host_->ExpectForceEnableZoom(true);
+
+ // Rebind should also update to the latest force_enable_zoom state.
+ mojom::WidgetPtr widget;
+ std::unique_ptr<MockWidgetImpl> widget_impl =
+ std::make_unique<MockWidgetImpl>(mojo::MakeRequest(&widget));
+ host_->SetWidget(std::move(widget));
+
+ SCOPED_TRACE("force_enable_zoom is true after rebind.");
+ host_->ExpectForceEnableZoom(true);
+}
+
TEST_F(RenderWidgetHostTest, RenderWidgetSurfaceProperties) {
RenderWidgetSurfaceProperties prop1;
prop1.size = gfx::Size(200, 200);
@@ -3096,4 +3133,29 @@ TEST_F(RenderWidgetHostTest, NavigateInBackgroundShowsBlank) {
EXPECT_TRUE(host_->new_content_rendering_timeout_fired());
}
+TEST_F(RenderWidgetHostTest, RendererHangRecordsMetrics) {
+ base::SimpleTestTickClock clock;
+ host_->set_clock_for_testing(&clock);
+ base::HistogramTester tester;
+
+ // RenderWidgetHost makes private the methods it overrides from
+ // InputRouterClient. Call them through the base class.
+ InputRouterClient* input_router_client = host_.get();
+
+ // Do a 3s hang. This shouldn't affect metrics.
+ input_router_client->IncrementInFlightEventCount();
+ clock.Advance(base::TimeDelta::FromSeconds(3));
+ input_router_client->DecrementInFlightEventCount(
+ InputEventAckSource::UNKNOWN);
+ tester.ExpectTotalCount("Renderer.Hung.Duration", 0u);
+
+ // Do a 17s hang. This should affect metrics.
+ input_router_client->IncrementInFlightEventCount();
+ clock.Advance(base::TimeDelta::FromSeconds(17));
+ input_router_client->DecrementInFlightEventCount(
+ InputEventAckSource::UNKNOWN);
+ tester.ExpectTotalCount("Renderer.Hung.Duration", 1u);
+ tester.ExpectUniqueSample("Renderer.Hung.Duration", 17000, 1);
+}
+
} // namespace content
diff --git a/chromium/content/browser/renderer_host/render_widget_host_view_android.cc b/chromium/content/browser/renderer_host/render_widget_host_view_android.cc
index 7c1009ca006..71c81ed240a 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_view_android.cc
+++ b/chromium/content/browser/renderer_host/render_widget_host_view_android.cc
@@ -14,7 +14,6 @@
#include "base/location.h"
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/metrics/histogram_macros.h"
#include "base/single_thread_task_runner.h"
@@ -31,14 +30,15 @@
#include "components/viz/service/surfaces/surface_hittest.h"
#include "content/browser/accessibility/browser_accessibility_manager_android.h"
#include "content/browser/accessibility/web_contents_accessibility_android.h"
-#include "content/browser/android/content_view_core.h"
+#include "content/browser/android/content_feature_list.h"
#include "content/browser/android/gesture_listener_manager.h"
#include "content/browser/android/ime_adapter_android.h"
#include "content/browser/android/overscroll_controller_android.h"
-#include "content/browser/android/selection_popup_controller.h"
+#include "content/browser/android/selection/selection_popup_controller.h"
#include "content/browser/android/synchronous_compositor_host.h"
#include "content/browser/android/tap_disambiguator.h"
#include "content/browser/android/text_suggestion_host_android.h"
+#include "content/browser/bad_message.h"
#include "content/browser/compositor/surface_utils.h"
#include "content/browser/devtools/render_frame_devtools_agent_host.h"
#include "content/browser/gpu/gpu_process_host.h"
@@ -56,6 +56,7 @@
#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_input_event_router.h"
#include "content/browser/renderer_host/ui_events_helper.h"
+#include "content/common/content_switches_internal.h"
#include "content/common/input_messages.h"
#include "content/common/view_messages.h"
#include "content/public/browser/android/compositor.h"
@@ -101,9 +102,9 @@ static const float kClickCountRadiusSquaredDIP = 25;
std::unique_ptr<ui::TouchSelectionController> CreateSelectionController(
ui::TouchSelectionControllerClient* client,
- ContentViewCore* content_view_core) {
+ bool has_view_tree) {
DCHECK(client);
- DCHECK(content_view_core);
+ DCHECK(has_view_tree);
ui::TouchSelectionController::Config config;
config.max_tap_duration = base::TimeDelta::FromMilliseconds(
gfx::ViewConfiguration::GetLongPressTimeoutInMs());
@@ -114,6 +115,10 @@ std::unique_ptr<ui::TouchSelectionController> CreateSelectionController(
config.enable_longpress_drag_selection =
base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableLongpressDragSelection);
+ config.hide_active_handle =
+ base::FeatureList::IsEnabled(
+ content::android::kEnhancedSelectionInsertionHandle) &&
+ base::android::BuildInfo::GetInstance()->is_at_least_p();
return std::make_unique<ui::TouchSelectionController>(client, config);
}
@@ -164,15 +169,14 @@ void RenderWidgetHostViewAndroid::OnContextLost() {
RenderWidgetHostViewAndroid::RenderWidgetHostViewAndroid(
RenderWidgetHostImpl* widget_host,
- ContentViewCore* content_view_core)
- : host_(widget_host),
+ gfx::NativeView parent_native_view)
+ : RenderWidgetHostViewBase(widget_host),
begin_frame_source_(nullptr),
outstanding_begin_frame_requests_(0),
is_showing_(!widget_host->is_hidden()),
is_window_visible_(true),
is_window_activity_started_(true),
is_in_vr_(false),
- content_view_core_(nullptr),
ime_adapter_android_(nullptr),
tap_disambiguator_(nullptr),
selection_popup_controller_(nullptr),
@@ -190,11 +194,13 @@ RenderWidgetHostViewAndroid::RenderWidgetHostViewAndroid(
frame_evictor_(new viz::FrameEvictor(this)),
observing_root_window_(false),
prev_top_shown_pix_(0.f),
+ prev_top_controls_translate_(0.f),
prev_bottom_shown_pix_(0.f),
+ prev_bottom_controls_translate_(0.f),
page_scale_(1.f),
min_page_scale_(1.f),
max_page_scale_(1.f),
- mouse_wheel_phase_handler_(widget_host, this),
+ mouse_wheel_phase_handler_(this),
weak_ptr_factory_(this) {
// Set the layer which will hold the content layer for this view. The content
// layer is managed by the DelegatedFrameHost.
@@ -203,20 +209,20 @@ RenderWidgetHostViewAndroid::RenderWidgetHostViewAndroid(
if (using_browser_compositor_) {
delegated_frame_host_ = std::make_unique<ui::DelegatedFrameHostAndroid>(
&view_, CompositorImpl::GetHostFrameSinkManager(), this,
- host_->GetFrameSinkId());
+ host()->GetFrameSinkId());
// Let the page-level input event router know about our frame sink ID
// for surface-based hit testing.
- if (host_->delegate() && host_->delegate()->GetInputEventRouter()) {
- host_->delegate()->GetInputEventRouter()->AddFrameSinkIdOwner(
+ if (host()->delegate() && host()->delegate()->GetInputEventRouter()) {
+ host()->delegate()->GetInputEventRouter()->AddFrameSinkIdOwner(
GetFrameSinkId(), this);
}
}
- host_->SetView(this);
+ host()->SetView(this);
touch_selection_controller_client_manager_ =
std::make_unique<TouchSelectionControllerClientManagerAndroid>(this);
- SetContentViewCore(content_view_core);
+ UpdateNativeViewTree(parent_native_view);
CreateOverscrollControllerIfPossible();
@@ -225,7 +231,7 @@ RenderWidgetHostViewAndroid::RenderWidgetHostViewAndroid(
}
RenderWidgetHostViewAndroid::~RenderWidgetHostViewAndroid() {
- SetContentViewCore(NULL);
+ UpdateNativeViewTree(nullptr);
DCHECK(!ime_adapter_android_);
DCHECK(ack_callbacks_.empty());
DCHECK(!delegated_frame_host_);
@@ -248,8 +254,6 @@ bool RenderWidgetHostViewAndroid::OnMessageReceived(
}
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(RenderWidgetHostViewAndroid, message)
- IPC_MESSAGE_HANDLER(ViewHostMsg_ShowUnhandledTapUIIfNeeded,
- OnShowUnhandledTapUIIfNeeded)
IPC_MESSAGE_HANDLER(ViewHostMsg_SelectWordAroundCaretAck,
OnSelectWordAroundCaretAck)
IPC_MESSAGE_UNHANDLED(handled = false)
@@ -259,7 +263,7 @@ bool RenderWidgetHostViewAndroid::OnMessageReceived(
bool RenderWidgetHostViewAndroid::SyncCompositorOnMessageReceived(
const IPC::Message& message) {
- DCHECK(!content_view_core_ || sync_compositor_) << !!content_view_core_;
+ DCHECK(!view_.parent() || sync_compositor_) << !!view_.parent();
return sync_compositor_ && sync_compositor_->OnMessageReceived(message);
}
@@ -280,7 +284,7 @@ void RenderWidgetHostViewAndroid::InitAsFullscreen(
void RenderWidgetHostViewAndroid::WasResized() {
if (delegated_frame_host_)
delegated_frame_host_->WasResized();
- host_->WasResized();
+ host()->WasResized();
}
void RenderWidgetHostViewAndroid::SetSize(const gfx::Size& size) {
@@ -294,7 +298,7 @@ void RenderWidgetHostViewAndroid::SetBounds(const gfx::Rect& rect) {
}
bool RenderWidgetHostViewAndroid::HasValidFrame() const {
- if (!content_view_core_)
+ if (!view_.parent())
return false;
if (current_surface_size_.IsEmpty())
@@ -308,10 +312,6 @@ bool RenderWidgetHostViewAndroid::HasValidFrame() const {
return true;
}
-gfx::Vector2dF RenderWidgetHostViewAndroid::GetLastScrollOffset() const {
- return last_scroll_offset_;
-}
-
gfx::NativeView RenderWidgetHostViewAndroid::GetNativeView() const {
return &view_;
}
@@ -323,12 +323,12 @@ RenderWidgetHostViewAndroid::GetNativeViewAccessible() {
}
void RenderWidgetHostViewAndroid::GotFocus() {
- host_->GotFocus();
+ host()->GotFocus();
OnFocusInternal();
}
void RenderWidgetHostViewAndroid::LostFocus() {
- host_->LostFocus();
+ host()->LostFocus();
LostFocusInternal();
}
@@ -376,17 +376,9 @@ void RenderWidgetHostViewAndroid::Hide() {
}
bool RenderWidgetHostViewAndroid::IsShowing() {
- // ContentViewCore represents the native side of the Java
- // ContentViewCore. It being NULL means that it is not attached
+ // |view_.parent()| being NULL means that it is not attached
// to the View system yet, so we treat this RWHVA as hidden.
- return is_showing_ && content_view_core_;
-}
-
-void RenderWidgetHostViewAndroid::OnShowUnhandledTapUIIfNeeded(int x_px,
- int y_px) {
- if (!selection_popup_controller_ || !content_view_core_)
- return;
- selection_popup_controller_->OnShowUnhandledTapUIIfNeeded(x_px, y_px);
+ return is_showing_ && view_.parent();
}
void RenderWidgetHostViewAndroid::OnSelectWordAroundCaretAck(bool did_select,
@@ -399,7 +391,7 @@ void RenderWidgetHostViewAndroid::OnSelectWordAroundCaretAck(bool did_select,
}
gfx::Rect RenderWidgetHostViewAndroid::GetViewBounds() const {
- if (!content_view_core_)
+ if (!view_.parent())
return default_bounds_;
gfx::Size size(view_.GetSize());
@@ -412,14 +404,14 @@ gfx::Rect RenderWidgetHostViewAndroid::GetViewBounds() const {
}
gfx::Size RenderWidgetHostViewAndroid::GetVisibleViewportSize() const {
- if (!content_view_core_)
+ if (!view_.parent())
return default_bounds_.size();
return view_.GetSize();
}
gfx::Size RenderWidgetHostViewAndroid::GetCompositorViewportPixelSize() const {
- if (!content_view_core_) {
+ if (!view_.parent()) {
if (default_bounds_.IsEmpty()) return gfx::Size();
float scale_factor = view_.GetDipScale();
@@ -447,14 +439,15 @@ float RenderWidgetHostViewAndroid::GetBottomControlsHeight() const {
}
int RenderWidgetHostViewAndroid::GetMouseWheelMinimumGranularity() const {
- if (!content_view_core_)
+ auto* window = view_.GetWindowAndroid();
+ if (!window)
return 0;
// On Android, mouse wheel MotionEvents specify the number of ticks and how
// many pixels each tick scrolls. This multiplier is specified by device
- // metrics (See RenderCoordinates::mWheelScrollFactor) so the minimum
+ // metrics (See WindowAndroid.getMouseWheelScrollFactor) so the minimum
// granularity will be the size of this tick multiplier.
- return content_view_core_->GetMouseWheelMinimumGranularity();
+ return window->mouse_wheel_scroll_factor() / view_.GetDipScale();
}
void RenderWidgetHostViewAndroid::UpdateCursor(const WebCursor& cursor) {
@@ -651,10 +644,17 @@ bool RenderWidgetHostViewAndroid::OnTouchEvent(
const ui::MotionEventAndroid& event) {
RecordToolTypeForActionDown(event);
+ if (event.GetAction() == ui::MotionEventAndroid::Action::DOWN) {
+ if (ime_adapter_android_)
+ ime_adapter_android_->UpdateOnTouchDown();
+ if (gesture_listener_manager_)
+ gesture_listener_manager_->UpdateOnTouchDown();
+ }
+
if (event.for_touch_handle())
return OnTouchHandleEvent(event);
- if (!host_ || !host_->delegate())
+ if (!host() || !host()->delegate())
return false;
ComputeEventLatencyOSTouchHistograms(event);
@@ -690,11 +690,11 @@ bool RenderWidgetHostViewAndroid::OnTouchEvent(
ui::LatencyInfo latency_info(ui::SourceEventType::TOUCH);
latency_info.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_UI_COMPONENT, 0, 0);
- if (host_->delegate()->GetInputEventRouter()) {
- host_->delegate()->GetInputEventRouter()->RouteTouchEvent(this, &web_event,
- latency_info);
+ if (host()->delegate()->GetInputEventRouter()) {
+ host()->delegate()->GetInputEventRouter()->RouteTouchEvent(this, &web_event,
+ latency_info);
} else {
- host_->ForwardTouchEventWithLatencyInfo(web_event, latency_info);
+ host()->ForwardTouchEventWithLatencyInfo(web_event, latency_info);
}
// Send a proactive BeginFrame for this vsync to reduce scroll latency for
@@ -738,11 +738,11 @@ void RenderWidgetHostViewAndroid::ResetGestureDetection() {
blink::WebTouchEvent web_event = ui::CreateWebTouchEventFromMotionEvent(
*cancel_event, causes_scrolling /* may_cause_scrolling */,
false /* hovering */);
- if (host_->delegate()->GetInputEventRouter()) {
- host_->delegate()->GetInputEventRouter()->RouteTouchEvent(
+ if (host()->delegate()->GetInputEventRouter()) {
+ host()->delegate()->GetInputEventRouter()->RouteTouchEvent(
this, &web_event, latency_info);
} else {
- host_->ForwardTouchEventWithLatencyInfo(web_event, latency_info);
+ host()->ForwardTouchEventWithLatencyInfo(web_event, latency_info);
}
}
}
@@ -773,20 +773,17 @@ void RenderWidgetHostViewAndroid::RenderProcessGone(
}
void RenderWidgetHostViewAndroid::Destroy() {
- host_->ViewDestroyed();
- SetContentViewCore(NULL);
+ host()->ViewDestroyed();
+ UpdateNativeViewTree(nullptr);
delegated_frame_host_.reset();
- // The RenderWidgetHost's destruction led here, so don't call it.
- host_ = NULL;
-
if (GetTextInputManager() && GetTextInputManager()->HasObserver(this))
GetTextInputManager()->RemoveObserver(this);
for (auto& observer : destruction_observers_)
observer.RenderWidgetHostViewDestroyed(this);
destruction_observers_.Clear();
-
+ RenderWidgetHostViewBase::Destroy();
delete this;
}
@@ -800,7 +797,7 @@ void RenderWidgetHostViewAndroid::SetBackgroundColor(SkColor color) {
DCHECK(SkColorGetA(color) == SK_AlphaOPAQUE ||
SkColorGetA(color) == SK_AlphaTRANSPARENT);
- host_->SetBackgroundOpaque(SkColorGetA(color) == SK_AlphaOPAQUE);
+ host()->SetBackgroundOpaque(SkColorGetA(color) == SK_AlphaOPAQUE);
UpdateBackgroundColor(color);
}
@@ -853,12 +850,12 @@ void RenderWidgetHostViewAndroid::ShowDisambiguationPopup(
std::unique_ptr<SyntheticGestureTarget>
RenderWidgetHostViewAndroid::CreateSyntheticGestureTarget() {
return std::unique_ptr<SyntheticGestureTarget>(
- new SyntheticGestureTargetAndroid(host_, &view_));
+ new SyntheticGestureTargetAndroid(host(), &view_));
}
void RenderWidgetHostViewAndroid::SendReclaimCompositorResources(
bool is_swap_ack) {
- DCHECK(host_);
+ DCHECK(host());
if (is_swap_ack) {
renderer_compositor_frame_sink_->DidReceiveCompositorFrameAck(
surface_returned_resources_);
@@ -873,6 +870,23 @@ void RenderWidgetHostViewAndroid::DidReceiveCompositorFrameAck() {
RunAckCallbacks();
}
+void RenderWidgetHostViewAndroid::DidPresentCompositorFrame(
+ uint32_t presentation_token,
+ base::TimeTicks time,
+ base::TimeDelta refresh,
+ uint32_t flags) {
+ DCHECK(using_browser_compositor_);
+ renderer_compositor_frame_sink_->DidPresentCompositorFrame(
+ presentation_token, time, refresh, flags);
+}
+
+void RenderWidgetHostViewAndroid::DidDiscardCompositorFrame(
+ uint32_t presentation_token) {
+ DCHECK(using_browser_compositor_);
+ renderer_compositor_frame_sink_->DidDiscardCompositorFrame(
+ presentation_token);
+}
+
void RenderWidgetHostViewAndroid::ReclaimResources(
const std::vector<viz::ReturnedResource>& resources) {
if (resources.empty())
@@ -893,7 +907,7 @@ void RenderWidgetHostViewAndroid::DidCreateNewRendererCompositorFrameSink(
DCHECK(!using_browser_compositor_);
// We don't expect RendererCompositorFrameSink on Android WebView.
// (crbug.com/721102)
- bad_message::ReceivedBadMessage(host_->GetProcess(),
+ bad_message::ReceivedBadMessage(host()->GetProcess(),
bad_message::RWH_BAD_FRAME_SINK_REQUEST);
return;
}
@@ -905,15 +919,19 @@ void RenderWidgetHostViewAndroid::DidCreateNewRendererCompositorFrameSink(
}
void RenderWidgetHostViewAndroid::EvictFrameIfNecessary() {
- if (!base::FeatureList::IsEnabled(
+ if (!host()->delegate()->IsFullscreenForCurrentTab() ||
+ current_surface_size_ == view_.GetPhysicalBackingSize() ||
+ !base::FeatureList::IsEnabled(
features::kHideIncorrectlySizedFullscreenFrames)) {
return;
}
- if (host_->delegate()->IsFullscreenForCurrentTab() &&
- current_surface_size_ != view_.GetPhysicalBackingSize()) {
- // When we're in a fullscreen and the frame size doesn't match the view
- // size (e.g. during a fullscreen rotation), we show black instead of the
- // incorrectly-sized frame.
+ // When we're in a fullscreen and and doing a resize we show black
+ // instead of the incorrectly-sized frame. However when we are just
+ // adjusting the height we keep the frames because it is a less jarring
+ // experience for the user instead frames shown as black.
+ bool is_width_same =
+ current_surface_size_.width() == view_.GetPhysicalBackingSize().width();
+ if (!is_width_same) {
EvictDelegatedFrame();
UpdateBackgroundColor(SK_ColorBLACK);
}
@@ -928,7 +946,6 @@ void RenderWidgetHostViewAndroid::SubmitCompositorFrame(
return;
}
- last_scroll_offset_ = frame.metadata.root_scroll_offset;
DCHECK(!frame.render_pass_list.empty());
viz::RenderPass* root_pass = frame.render_pass_list.back().get();
@@ -954,11 +971,11 @@ void RenderWidgetHostViewAndroid::SubmitCompositorFrame(
} else {
delegated_frame_host_->SubmitCompositorFrame(
local_surface_id, std::move(frame), std::move(hit_test_region_list));
- frame_evictor_->SwappedFrame(!host_->is_hidden());
+ frame_evictor_->SwappedFrame(!host()->is_hidden());
AcknowledgeBeginFrame(ack);
}
- if (host_->is_hidden())
+ if (host()->is_hidden())
RunAckCallbacks();
// As the metadata update may trigger view invalidation, always call it after
@@ -967,18 +984,17 @@ void RenderWidgetHostViewAndroid::SubmitCompositorFrame(
}
void RenderWidgetHostViewAndroid::DestroyDelegatedContent() {
- DCHECK(!delegated_frame_host_ ||
- delegated_frame_host_->HasDelegatedContent() ==
- frame_evictor_->HasFrame());
-
if (!delegated_frame_host_)
return;
- if (!delegated_frame_host_->HasDelegatedContent())
- return;
+ DCHECK(delegated_frame_host_->HasDelegatedContent() ==
+ frame_evictor_->HasFrame());
- frame_evictor_->DiscardedFrame();
delegated_frame_host_->DestroyDelegatedContent();
+
+ if (frame_evictor_->HasFrame())
+ frame_evictor_->DiscardedFrame();
+
current_surface_size_.SetSize(0, 0);
}
@@ -1008,25 +1024,24 @@ void RenderWidgetHostViewAndroid::ClearCompositorFrame() {
void RenderWidgetHostViewAndroid::SynchronousFrameMetadata(
viz::CompositorFrameMetadata frame_metadata) {
- if (!content_view_core_)
+ if (!view_.parent())
return;
bool is_mobile_optimized = IsMobileOptimizedFrame(frame_metadata);
- if (host_ && host_->input_router()) {
- host_->input_router()->NotifySiteIsMobileOptimized(
- is_mobile_optimized);
+ if (host() && host()->input_router()) {
+ host()->input_router()->NotifySiteIsMobileOptimized(is_mobile_optimized);
}
- if (host_ && frame_metadata.frame_token)
- host_->DidProcessFrame(frame_metadata.frame_token);
+ if (host() && frame_metadata.frame_token)
+ host()->DidProcessFrame(frame_metadata.frame_token);
// This is a subset of OnSwapCompositorFrame() used in the synchronous
// compositor flow.
OnFrameMetadataUpdated(frame_metadata.Clone(), false);
// DevTools ScreenCast support for Android WebView.
- RenderFrameHost* frame_host = RenderViewHost::From(host_)->GetMainFrame();
+ RenderFrameHost* frame_host = RenderViewHost::From(host())->GetMainFrame();
if (frame_host) {
RenderFrameDevToolsAgentHost::SignalSynchronousSwapCompositorFrame(
frame_host,
@@ -1106,7 +1121,7 @@ void RenderWidgetHostViewAndroid::SetSelectionControllerClientForTesting(
touch_selection_controller_client_for_test_.swap(client);
touch_selection_controller_ = CreateSelectionController(
- touch_selection_controller_client_for_test_.get(), content_view_core_);
+ touch_selection_controller_client_for_test_.get(), !!view_.parent());
}
std::unique_ptr<ui::TouchHandleDrawable>
@@ -1206,7 +1221,7 @@ void RenderWidgetHostViewAndroid::OnFrameMetadataUpdated(
if (wcax)
wcax->UpdateFrameInfo();
- if (!content_view_core_)
+ if (!gesture_listener_manager_)
return;
if (overscroll_controller_)
@@ -1240,25 +1255,32 @@ void RenderWidgetHostViewAndroid::OnFrameMetadataUpdated(
bool top_changed = !FloatEquals(top_shown_pix, prev_top_shown_pix_);
// TODO(carlosil, https://crbug.com/825765): Remove the IsInVR() check here,
- // which is a temporary hack. When interstitial pages load they set the
- // top controls offset to 0, and if we don't ignore that hit targeting on
- // interstitial pages breaks. The fix is still crucial for VR as VR needs the
- // top controls to be initially hidden correctly.
+ // which is a temporary hack. Interstitial pages are not committed navigations
+ // and their metadata updates never leave the content layer, so Chrome and the
+ // content layer end up mismatched and hit testing is offset. They rely on the
+ // previous (erroneous) behavior of ignoring the initial control offset update
+ // if offset is 0. The fix is still crucial for VR as VR needs the top
+ // controls to be initially hidden correctly (so we don't want the offset of 0
+ // to get ignored. Tracking bug for the interstitial work to fix this by
+ // converting interstitials to committed navigations is
+ // https://crbug.com/755632.
+ float top_translate = top_shown_pix - top_controls_pix;
if (top_changed || (!controls_initialized_ && IsInVR())) {
- float translate = top_shown_pix - top_controls_pix;
- view_.OnTopControlsChanged(translate, top_shown_pix);
- prev_top_shown_pix_ = top_shown_pix;
+ view_.OnTopControlsChanged(top_translate, top_shown_pix);
}
+ prev_top_shown_pix_ = top_shown_pix;
+ prev_top_controls_translate_ = top_translate;
float bottom_controls_pix = frame_metadata.bottom_controls_height * to_pix;
float bottom_shown_pix =
bottom_controls_pix * frame_metadata.bottom_controls_shown_ratio;
bool bottom_changed = !FloatEquals(bottom_shown_pix, prev_bottom_shown_pix_);
+ float bottom_translate = bottom_controls_pix - bottom_shown_pix;
if (bottom_changed || (!controls_initialized_ && IsInVR())) {
- float translate = bottom_controls_pix - bottom_shown_pix;
- view_.OnBottomControlsChanged(translate, bottom_shown_pix);
- prev_bottom_shown_pix_ = bottom_shown_pix;
+ view_.OnBottomControlsChanged(bottom_translate, bottom_shown_pix);
}
+ prev_bottom_shown_pix_ = bottom_shown_pix;
+ prev_bottom_controls_translate_ = bottom_translate;
controls_initialized_ = true;
page_scale_ = frame_metadata.page_scale_factor;
@@ -1266,12 +1288,12 @@ void RenderWidgetHostViewAndroid::OnFrameMetadataUpdated(
max_page_scale_ = frame_metadata.max_page_scale_factor;
// All offsets and sizes except |top_shown_pix| are in CSS pixels.
- content_view_core_->UpdateFrameInfo(
+ gesture_listener_manager_->UpdateScrollInfo(
root_scroll_offset_dip, frame_metadata.page_scale_factor,
frame_metadata.min_page_scale_factor,
frame_metadata.max_page_scale_factor, root_layer_size_dip,
scrollable_viewport_size_dip, top_content_offset_dip, top_shown_pix,
- top_changed, is_mobile_optimized);
+ top_changed);
EvictFrameIfNecessary();
}
@@ -1281,7 +1303,7 @@ void RenderWidgetHostViewAndroid::ShowInternal() {
if (!show)
return;
- if (!host_ || !host_->is_hidden())
+ if (!host() || !host()->is_hidden())
return;
view_.GetLayer()->SetHideLayerAndSubtree(false);
@@ -1291,9 +1313,9 @@ void RenderWidgetHostViewAndroid::ShowInternal() {
if (overscroll_controller_)
overscroll_controller_->Enable();
- host_->WasShown(ui::LatencyInfo());
+ host()->WasShown(ui::LatencyInfo());
- if (content_view_core_ && view_.GetWindowAndroid()) {
+ if (view_.parent() && view_.GetWindowAndroid()) {
StartObservingRootWindow();
AddBeginFrameRequest(BEGIN_FRAME);
}
@@ -1323,7 +1345,7 @@ void RenderWidgetHostViewAndroid::HideInternal() {
StopObservingRootWindow();
}
- if (!host_ || host_->is_hidden())
+ if (!host() || host()->is_hidden())
return;
if (overscroll_controller_)
@@ -1333,7 +1355,7 @@ void RenderWidgetHostViewAndroid::HideInternal() {
// Inform the renderer that we are being hidden so it can reduce its resource
// utilization.
- host_->WasHidden();
+ host()->WasHidden();
}
void RenderWidgetHostViewAndroid::SetBeginFrameSource(
@@ -1372,7 +1394,7 @@ void RenderWidgetHostViewAndroid::ClearBeginFrameRequest(
}
void RenderWidgetHostViewAndroid::StartObservingRootWindow() {
- DCHECK(content_view_core_);
+ DCHECK(view_.parent());
DCHECK(view_.GetWindowAndroid());
DCHECK(is_showing_);
if (observing_root_window_)
@@ -1436,8 +1458,8 @@ void RenderWidgetHostViewAndroid::SendBeginFrame(viz::BeginFrameArgs args) {
bool RenderWidgetHostViewAndroid::Animate(base::TimeTicks frame_time) {
bool needs_animate = false;
if (overscroll_controller_ && !is_in_vr_) {
- needs_animate |= overscroll_controller_->Animate(
- frame_time, content_view_core_->GetViewAndroid()->GetLayer());
+ needs_animate |=
+ overscroll_controller_->Animate(frame_time, view_.parent()->GetLayer());
}
// TODO(wjmaclean): Investigate how animation here does or doesn't affect
// an OOPIF client.
@@ -1447,8 +1469,8 @@ bool RenderWidgetHostViewAndroid::Animate(base::TimeTicks frame_time) {
}
void RenderWidgetHostViewAndroid::RequestDisallowInterceptTouchEvent() {
- if (content_view_core_)
- content_view_core_->RequestDisallowInterceptTouchEvent();
+ if (view_.parent())
+ view_.RequestDisallowInterceptTouchEvent();
}
void RenderWidgetHostViewAndroid::EvictDelegatedFrame() {
@@ -1473,8 +1495,9 @@ void RenderWidgetHostViewAndroid::ProcessAckedTouchEvent(
touch.event.unique_touch_event_id, event_consumed,
InputEventAckStateIsSetNonBlocking(ack_result));
if (touch.event.touch_start_or_first_touch_move && event_consumed &&
- host_->delegate() && host_->delegate()->GetInputEventRouter()) {
- host_->delegate()
+ host()->delegate() && host()->delegate()->GetInputEventRouter()) {
+ host()
+ ->delegate()
->GetInputEventRouter()
->OnHandledTouchStartOrFirstTouchMove(
touch.event.unique_touch_event_id);
@@ -1495,23 +1518,38 @@ void RenderWidgetHostViewAndroid::GestureEventAck(
RenderViewHostDelegateView*
RenderWidgetHostViewAndroid::GetRenderViewHostDelegateView() const {
- RenderWidgetHostDelegate* delegate = host_->delegate();
+ RenderWidgetHostDelegate* delegate = host()->delegate();
return delegate ? delegate->GetDelegateView() : nullptr;
}
InputEventAckState RenderWidgetHostViewAndroid::FilterInputEvent(
const blink::WebInputEvent& input_event) {
if (overscroll_controller_ &&
- blink::WebInputEvent::IsGestureEventType(input_event.GetType()) &&
- overscroll_controller_->WillHandleGestureEvent(
- static_cast<const blink::WebGestureEvent&>(input_event))) {
- return INPUT_EVENT_ACK_STATE_CONSUMED;
+ blink::WebInputEvent::IsGestureEventType(input_event.GetType())) {
+ blink::WebGestureEvent gesture_event =
+ static_cast<const blink::WebGestureEvent&>(input_event);
+ if (overscroll_controller_->WillHandleGestureEvent(gesture_event)) {
+ // Terminate an active fling when a GSU generated from the fling progress
+ // (GSU with inertial state) is consumed by the overscroll_controller_ and
+ // overscrolling mode is not |OVERSCROLL_NONE|. The early fling
+ // termination generates a GSE which completes the overscroll action.
+ if (gesture_event.GetType() ==
+ blink::WebInputEvent::kGestureScrollUpdate &&
+ gesture_event.data.scroll_update.inertial_phase ==
+ blink::WebGestureEvent::kMomentumPhase) {
+ host_->StopFling();
+ }
+
+ return INPUT_EVENT_ACK_STATE_CONSUMED;
+ }
}
- if (content_view_core_ && content_view_core_->FilterInputEvent(input_event))
+ if (gesture_listener_manager_ &&
+ gesture_listener_manager_->FilterInputEvent(input_event)) {
return INPUT_EVENT_ACK_STATE_CONSUMED;
+ }
- if (!host_)
+ if (!host())
return INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
if (input_event.GetType() == blink::WebInputEvent::kGestureTapDown ||
@@ -1536,7 +1574,7 @@ BrowserAccessibilityManager*
BrowserAccessibilityDelegate* delegate, bool for_root_frame) {
return new BrowserAccessibilityManagerAndroid(
BrowserAccessibilityManagerAndroid::GetEmptyDocument(),
- for_root_frame && host_ ? GetWebContentsAccessibilityAndroid() : nullptr,
+ for_root_frame && host() ? GetWebContentsAccessibilityAndroid() : nullptr,
delegate);
}
@@ -1553,15 +1591,15 @@ void RenderWidgetHostViewAndroid::UnlockMouse() {
void RenderWidgetHostViewAndroid::SendKeyEvent(
const NativeWebKeyboardEvent& event) {
- if (!host_)
+ if (!host())
return;
- RenderWidgetHostImpl* target_host = host_;
+ RenderWidgetHostImpl* target_host = host();
// If there are multiple widgets on the page (such as when there are
// out-of-process iframes), pick the one that should process this event.
- if (host_->delegate())
- target_host = host_->delegate()->GetFocusedRenderWidgetHost(host_);
+ if (host()->delegate())
+ target_host = host()->delegate()->GetFocusedRenderWidgetHost(host());
if (!target_host)
return;
@@ -1602,14 +1640,14 @@ void RenderWidgetHostViewAndroid::SendMouseEvent(
blink::WebMouseEvent mouse_event = WebMouseEventBuilder::Build(
motion_event, webMouseEventType, click_count, action_button);
- if (!host_ || !host_->delegate())
+ if (!host() || !host()->delegate())
return;
- if (host_->delegate()->GetInputEventRouter()) {
- host_->delegate()->GetInputEventRouter()->RouteMouseEvent(
+ if (host()->delegate()->GetInputEventRouter()) {
+ host()->delegate()->GetInputEventRouter()->RouteMouseEvent(
this, &mouse_event, ui::LatencyInfo());
} else {
- host_->ForwardMouseEvent(mouse_event);
+ host()->ForwardMouseEvent(mouse_event);
}
}
@@ -1639,22 +1677,22 @@ void RenderWidgetHostViewAndroid::UpdateMouseState(int action_button,
void RenderWidgetHostViewAndroid::SendMouseWheelEvent(
const blink::WebMouseWheelEvent& event) {
- if (!host_ || !host_->delegate())
+ if (!host() || !host()->delegate())
return;
ui::LatencyInfo latency_info(ui::SourceEventType::WHEEL);
latency_info.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_UI_COMPONENT, 0, 0);
blink::WebMouseWheelEvent wheel_event(event);
- bool should_route_event = !!host_->delegate()->GetInputEventRouter();
+ bool should_route_event = !!host()->delegate()->GetInputEventRouter();
if (wheel_scroll_latching_enabled()) {
mouse_wheel_phase_handler_.AddPhaseIfNeededAndScheduleEndEvent(
wheel_event, should_route_event);
}
if (should_route_event) {
- host_->delegate()->GetInputEventRouter()->RouteMouseWheelEvent(
+ host()->delegate()->GetInputEventRouter()->RouteMouseWheelEvent(
this, &wheel_event, latency_info);
} else {
- host_->ForwardWheelEventWithLatencyInfo(wheel_event, latency_info);
+ host()->ForwardWheelEventWithLatencyInfo(wheel_event, latency_info);
}
}
@@ -1664,7 +1702,7 @@ void RenderWidgetHostViewAndroid::SendGestureEvent(
if (overscroll_controller_)
overscroll_controller_->Enable();
- if (!host_ || !host_->delegate() ||
+ if (!host() || !host()->delegate() ||
event.GetType() == blink::WebInputEvent::kUndefined) {
return;
}
@@ -1672,19 +1710,19 @@ void RenderWidgetHostViewAndroid::SendGestureEvent(
// We let the touch selection controller see gesture events here, since they
// may be routed and not make it to FilterInputEvent().
if (touch_selection_controller_ &&
- event.source_device ==
+ event.SourceDevice() ==
blink::WebGestureDevice::kWebGestureDeviceTouchscreen) {
switch (event.GetType()) {
case blink::WebInputEvent::kGestureLongPress:
touch_selection_controller_->HandleLongPressEvent(
base::TimeTicks() +
base::TimeDelta::FromSecondsD(event.TimeStampSeconds()),
- gfx::PointF(event.x, event.y));
+ event.PositionInWidget());
break;
case blink::WebInputEvent::kGestureTap:
- touch_selection_controller_->HandleTapEvent(
- gfx::PointF(event.x, event.y), event.data.tap.tap_count);
+ touch_selection_controller_->HandleTapEvent(event.PositionInWidget(),
+ event.data.tap.tap_count);
break;
case blink::WebInputEvent::kGestureScrollBegin:
@@ -1699,7 +1737,7 @@ void RenderWidgetHostViewAndroid::SendGestureEvent(
ui::LatencyInfo latency_info =
ui::WebInputEventTraits::CreateLatencyInfoForWebGestureEvent(event);
if (wheel_scroll_latching_enabled()) {
- if (event.source_device ==
+ if (event.SourceDevice() ==
blink::WebGestureDevice::kWebGestureDeviceTouchscreen) {
if (event.GetType() == blink::WebInputEvent::kGestureScrollBegin) {
// If there is a current scroll going on and a new scroll that isn't
@@ -1714,20 +1752,20 @@ void RenderWidgetHostViewAndroid::SendGestureEvent(
}
} else if (event.GetType() == blink::WebInputEvent::kGestureFlingStart &&
- event.source_device ==
+ event.SourceDevice() ==
blink::WebGestureDevice::kWebGestureDeviceTouchpad) {
// Ignore the pending wheel end event to avoid sending a wheel event with
// kPhaseEnded before a GFS.
mouse_wheel_phase_handler_.IgnorePendingWheelEndEvent();
}
}
- bool should_route_event = !!host_->delegate()->GetInputEventRouter();
+ bool should_route_event = !!host()->delegate()->GetInputEventRouter();
if (should_route_event) {
blink::WebGestureEvent gesture_event(event);
- host_->delegate()->GetInputEventRouter()->RouteGestureEvent(
+ host()->delegate()->GetInputEventRouter()->RouteGestureEvent(
this, &gesture_event, latency_info);
} else {
- host_->ForwardGestureEventWithLatencyInfo(event, latency_info);
+ host()->ForwardGestureEventWithLatencyInfo(event, latency_info);
}
}
@@ -1744,22 +1782,22 @@ void RenderWidgetHostViewAndroid::ResolveTapDisambiguation(
double timestamp_seconds,
gfx::Point tap_viewport_offset,
bool is_long_press) {
- DCHECK(host_);
- host_->Send(new ViewMsg_ResolveTapDisambiguation(
- host_->GetRoutingID(), timestamp_seconds, tap_viewport_offset,
+ DCHECK(host());
+ host()->Send(new ViewMsg_ResolveTapDisambiguation(
+ host()->GetRoutingID(), timestamp_seconds, tap_viewport_offset,
is_long_press));
}
void RenderWidgetHostViewAndroid::MoveCaret(const gfx::Point& point) {
- if (host_ && host_->delegate())
- host_->delegate()->MoveCaret(point);
+ if (host() && host()->delegate())
+ host()->delegate()->MoveCaret(point);
}
void RenderWidgetHostViewAndroid::ShowContextMenuAtPoint(
const gfx::Point& point,
ui::MenuSourceType source_type) {
- if (host_)
- host_->ShowContextMenuAtPoint(point, source_type);
+ if (host())
+ host()->ShowContextMenuAtPoint(point, source_type);
}
void RenderWidgetHostViewAndroid::DismissTextHandles() {
@@ -1767,9 +1805,14 @@ void RenderWidgetHostViewAndroid::DismissTextHandles() {
touch_selection_controller_->HideAndDisallowShowingAutomatically();
}
-void RenderWidgetHostViewAndroid::SetTextHandlesTemporarilyHidden(bool hidden) {
- if (touch_selection_controller_)
- touch_selection_controller_->SetTemporarilyHidden(hidden);
+void RenderWidgetHostViewAndroid::SetTextHandlesTemporarilyHidden(
+ bool hide_handles) {
+ if (!touch_selection_controller_ ||
+ handles_hidden_by_selection_ui_ == hide_handles)
+ return;
+ handles_hidden_by_selection_ui_ = hide_handles;
+ touch_selection_controller_->SetTemporarilyHidden(
+ handles_hidden_by_selection_ui_ || handles_hidden_by_stylus_);
}
SkColor RenderWidgetHostViewAndroid::GetCachedBackgroundColor() const {
@@ -1781,9 +1824,20 @@ void RenderWidgetHostViewAndroid::SetIsInVR(bool is_in_vr) {
// TODO(crbug.com/779126): support touch selection handles in VR.
if (is_in_vr) {
touch_selection_controller_.reset();
- } else if (content_view_core_) {
+ } else if (view_.parent()) {
touch_selection_controller_ = CreateSelectionController(
- touch_selection_controller_client_manager_.get(), content_view_core_);
+ touch_selection_controller_client_manager_.get(), view_.parent());
+ }
+
+ if (is_in_vr_ && controls_initialized_) {
+ // TODO(carlosil, https://crbug.com/825765): See the TODO in
+ // RenderWidgetHostViewAndroid::OnFrameMetadataUpdated. RWHVA isn't
+ // initialized with VR state so the initial frame metadata top controls
+ // height can be dropped when a new RWHVA is created.
+ view_.OnTopControlsChanged(prev_top_controls_translate_,
+ prev_top_shown_pix_);
+ view_.OnBottomControlsChanged(prev_bottom_controls_translate_,
+ prev_bottom_shown_pix_);
}
}
@@ -1796,7 +1850,7 @@ void RenderWidgetHostViewAndroid::DidOverscroll(
if (sync_compositor_)
sync_compositor_->DidOverscroll(params);
- if (!content_view_core_ || !is_showing_)
+ if (!view_.parent() || !is_showing_)
return;
if (overscroll_controller_)
@@ -1809,11 +1863,6 @@ void RenderWidgetHostViewAndroid::DidStopFlinging() {
gesture_listener_manager_->DidStopFlinging();
}
-RenderWidgetHostImpl* RenderWidgetHostViewAndroid::GetRenderWidgetHostImpl()
- const {
- return host_;
-}
-
viz::FrameSinkId RenderWidgetHostViewAndroid::GetFrameSinkId() {
if (!delegated_frame_host_)
return viz::FrameSinkId();
@@ -1821,38 +1870,43 @@ viz::FrameSinkId RenderWidgetHostViewAndroid::GetFrameSinkId() {
return delegated_frame_host_->GetFrameSinkId();
}
-void RenderWidgetHostViewAndroid::SetContentViewCore(
- ContentViewCore* content_view_core) {
- DCHECK(!content_view_core || !content_view_core_ ||
- (content_view_core_ == content_view_core));
+void RenderWidgetHostViewAndroid::UpdateNativeViewTree(
+ gfx::NativeView parent_native_view) {
+ bool will_build_tree = parent_native_view != nullptr;
+ bool has_view_tree = view_.parent() != nullptr;
+
+ // Allows same parent view to be set again.
+ DCHECK(!will_build_tree || !has_view_tree ||
+ parent_native_view == view_.parent());
+
StopObservingRootWindow();
bool resize = false;
- if (content_view_core != content_view_core_) {
+ if (will_build_tree != has_view_tree) {
touch_selection_controller_.reset();
RunAckCallbacks();
- if (content_view_core_) {
+ if (has_view_tree) {
view_.RemoveObserver(this);
view_.RemoveFromParent();
view_.GetLayer()->RemoveFromParent();
}
- if (content_view_core) {
+ if (will_build_tree) {
view_.AddObserver(this);
- ui::ViewAndroid* parent_view = content_view_core->GetViewAndroid();
- parent_view->AddChild(&view_);
- parent_view->GetLayer()->AddChild(view_.GetLayer());
+ parent_native_view->AddChild(&view_);
+ parent_native_view->GetLayer()->AddChild(view_.GetLayer());
}
+
// TODO(yusufo) : Get rid of the below conditions and have a better handling
// for resizing after crbug.com/628302 is handled.
- bool is_size_initialized = !content_view_core ||
+ bool is_size_initialized = !will_build_tree ||
view_.GetSize().width() != 0 ||
view_.GetSize().height() != 0;
- if (content_view_core_ || is_size_initialized)
+ if (has_view_tree || is_size_initialized)
resize = true;
- content_view_core_ = content_view_core;
+ has_view_tree = will_build_tree;
}
- if (!content_view_core_) {
+ if (!has_view_tree) {
sync_compositor_.reset();
return;
}
@@ -1869,12 +1923,10 @@ void RenderWidgetHostViewAndroid::SetContentViewCore(
if (touch_selection_controller_client_for_test_)
client = touch_selection_controller_client_for_test_.get();
- touch_selection_controller_ =
- CreateSelectionController(client, content_view_core_);
+ touch_selection_controller_ = CreateSelectionController(client, true);
}
- if (content_view_core_)
- CreateOverscrollControllerIfPossible();
+ CreateOverscrollControllerIfPossible();
}
void RenderWidgetHostViewAndroid::RunAckCallbacks() {
@@ -1915,6 +1967,13 @@ bool RenderWidgetHostViewAndroid::OnMouseWheelEvent(
void RenderWidgetHostViewAndroid::OnGestureEvent(
const ui::GestureEventData& gesture) {
+ if ((gesture.type() == ui::ET_GESTURE_PINCH_BEGIN ||
+ gesture.type() == ui::ET_GESTURE_PINCH_UPDATE ||
+ gesture.type() == ui::ET_GESTURE_PINCH_END) &&
+ !IsPinchToZoomEnabled()) {
+ return;
+ }
+
blink::WebGestureEvent web_gesture =
ui::CreateWebGestureEventFromGestureEventData(gesture);
// TODO(jdduke): Remove this workaround after Android fixes UiAutomator to
@@ -1940,11 +1999,6 @@ void RenderWidgetHostViewAndroid::OnPhysicalBackingSizeChanged() {
WasResized();
}
-void RenderWidgetHostViewAndroid::OnContentViewCoreDestroyed() {
- SetContentViewCore(NULL);
- overscroll_controller_.reset();
-}
-
void RenderWidgetHostViewAndroid::OnRootWindowVisibilityChanged(bool visible) {
TRACE_EVENT1("browser",
"RenderWidgetHostViewAndroid::OnRootWindowVisibilityChanged",
@@ -1962,7 +2016,7 @@ void RenderWidgetHostViewAndroid::OnRootWindowVisibilityChanged(bool visible) {
}
void RenderWidgetHostViewAndroid::OnAttachedToWindow() {
- if (!content_view_core_)
+ if (!view_.parent())
return;
if (is_showing_)
@@ -1978,9 +2032,9 @@ void RenderWidgetHostViewAndroid::OnDetachedFromWindow() {
}
void RenderWidgetHostViewAndroid::OnAttachCompositor() {
- DCHECK(content_view_core_);
+ DCHECK(view_.parent());
CreateOverscrollControllerIfPossible();
- if (observing_root_window_) {
+ if (observing_root_window_ && using_browser_compositor_) {
ui::WindowAndroidCompositor* compositor =
view_.GetWindowAndroid()->GetCompositor();
delegated_frame_host_->AttachToCompositor(compositor);
@@ -1988,17 +2042,17 @@ void RenderWidgetHostViewAndroid::OnAttachCompositor() {
}
void RenderWidgetHostViewAndroid::OnDetachCompositor() {
- DCHECK(content_view_core_);
- DCHECK(using_browser_compositor_);
+ DCHECK(view_.parent());
RunAckCallbacks();
overscroll_controller_.reset();
- delegated_frame_host_->DetachFromCompositor();
+ if (using_browser_compositor_)
+ delegated_frame_host_->DetachFromCompositor();
}
void RenderWidgetHostViewAndroid::OnBeginFrame(
const viz::BeginFrameArgs& args) {
TRACE_EVENT0("cc,benchmark", "RenderWidgetHostViewAndroid::OnBeginFrame");
- if (!host_) {
+ if (!host()) {
OnDidNotProduceFrame(
viz::BeginFrameAck(args.source_id, args.sequence_number, false));
return;
@@ -2013,6 +2067,16 @@ void RenderWidgetHostViewAndroid::OnBeginFrame(
return;
}
+ bool webview_fling = sync_compositor_ && is_currently_scrolling_viewport_;
+ if (!webview_fling) {
+ host_->ProgressFling(args.frame_time);
+ } else if (sync_compositor_->on_compute_scroll_called()) {
+ // On Android webview progress the fling only when |OnComputeScroll| is
+ // called since in some cases Apps override |OnComputeScroll| to cancel
+ // fling animation.
+ host_->ProgressFling(args.frame_time);
+ }
+
// Update |last_begin_frame_args_| before handling
// |outstanding_begin_frame_requests_| to prevent the BeginFrameSource from
// sending the same MISSED args in infinite recursion.
@@ -2026,7 +2090,6 @@ void RenderWidgetHostViewAndroid::OnBeginFrame(
OnDidNotProduceFrame(
viz::BeginFrameAck(args.source_id, args.sequence_number, false));
}
- host_->ProgressFling(args.frame_time);
}
const viz::BeginFrameArgs& RenderWidgetHostViewAndroid::LastUsedBeginFrameArgs()
@@ -2080,10 +2143,23 @@ void RenderWidgetHostViewAndroid::OnLostResources() {
DCHECK(ack_callbacks_.empty());
}
+void RenderWidgetHostViewAndroid::SetTextHandlesHiddenForStylus(
+ bool hide_handles) {
+ if (!touch_selection_controller_ || handles_hidden_by_stylus_ == hide_handles)
+ return;
+ handles_hidden_by_stylus_ = hide_handles;
+ touch_selection_controller_->SetTemporarilyHidden(
+ handles_hidden_by_stylus_ || handles_hidden_by_selection_ui_);
+}
+
void RenderWidgetHostViewAndroid::OnStylusSelectBegin(float x0,
float y0,
float x1,
float y1) {
+ SetTextHandlesHiddenForStylus(true);
+ // TODO(ajith.v) Refactor the event names as this is not really handle drag,
+ // but currently we use same for long press drag selection as well.
+ OnSelectionEvent(ui::SELECTION_HANDLE_DRAG_STARTED);
SelectBetweenCoordinates(gfx::PointF(x0, y0), gfx::PointF(x1, y1));
}
@@ -2092,7 +2168,10 @@ void RenderWidgetHostViewAndroid::OnStylusSelectUpdate(float x, float y) {
}
void RenderWidgetHostViewAndroid::OnStylusSelectEnd(float x, float y) {
- ShowContextMenuAtPoint(gfx::Point(x, y), ui::MENU_SOURCE_STYLUS);
+ SetTextHandlesHiddenForStylus(false);
+ // TODO(ajith.v) Refactor the event names as this is not really handle drag,
+ // but currently we use same for long press drag selection as well.
+ OnSelectionEvent(ui::SELECTION_HANDLE_DRAG_STOPPED);
}
void RenderWidgetHostViewAndroid::OnStylusSelectTap(base::TimeTicks time,
@@ -2135,7 +2214,7 @@ void RenderWidgetHostViewAndroid::CreateOverscrollControllerIfPossible() {
if (overscroll_controller_)
return;
- RenderWidgetHostDelegate* delegate = host_->delegate();
+ RenderWidgetHostDelegate* delegate = host()->delegate();
if (!delegate)
return;
@@ -2150,7 +2229,7 @@ void RenderWidgetHostViewAndroid::CreateOverscrollControllerIfPossible() {
if (!overscroll_refresh_handler)
return;
- if (!content_view_core_)
+ if (!view_.parent())
return;
// If window_android is null here, this is bad because we don't listen for it
@@ -2158,8 +2237,7 @@ void RenderWidgetHostViewAndroid::CreateOverscrollControllerIfPossible() {
// proper time.
// TODO(rlanday): once we get WindowAndroid from ViewAndroid instead of
// ContentViewCore, listen for WindowAndroid being set and create the
- // OverscrollController.
- ui::WindowAndroid* window_android = content_view_core_->GetWindowAndroid();
+ ui::WindowAndroid* window_android = view_.GetWindowAndroid();
if (!window_android)
return;
@@ -2178,4 +2256,20 @@ void RenderWidgetHostViewAndroid::SetOverscrollControllerForTesting(
view_.GetDipScale());
}
+void RenderWidgetHostViewAndroid::TakeFallbackContentFrom(
+ RenderWidgetHostView* view) {
+ DCHECK(!static_cast<RenderWidgetHostViewBase*>(view)
+ ->IsRenderWidgetHostViewChildFrame());
+ DCHECK(!static_cast<RenderWidgetHostViewBase*>(view)
+ ->IsRenderWidgetHostViewGuest());
+ SetBackgroundColor(view->background_color());
+ RenderWidgetHostViewAndroid* view_android =
+ static_cast<RenderWidgetHostViewAndroid*>(view);
+ if (!delegated_frame_host_ || !view_android->delegated_frame_host_)
+ return;
+ delegated_frame_host_->TakeFallbackContentFrom(
+ view_android->delegated_frame_host_.get());
+ host()->GetContentRenderingTimeoutFrom(view_android->host());
+}
+
} // namespace content
diff --git a/chromium/content/browser/renderer_host/render_widget_host_view_android.h b/chromium/content/browser/renderer_host/render_widget_host_view_android.h
index 21c45903563..4e9fef8bc8f 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_view_android.h
+++ b/chromium/content/browser/renderer_host/render_widget_host_view_android.h
@@ -47,11 +47,9 @@ struct DidOverscrollParams;
}
namespace content {
-class ContentViewCore;
class GestureListenerManager;
class ImeAdapterAndroid;
class OverscrollControllerAndroid;
-class RenderWidgetHostImpl;
class SelectionPopupController;
class SynchronousCompositorHost;
class SynchronousCompositorClient;
@@ -79,7 +77,7 @@ class CONTENT_EXPORT RenderWidgetHostViewAndroid
public viz::BeginFrameObserver {
public:
RenderWidgetHostViewAndroid(RenderWidgetHostImpl* widget,
- ContentViewCore* content_view_core);
+ gfx::NativeView parent_native_view);
~RenderWidgetHostViewAndroid() override;
// Interface used to observe the destruction of a RenderWidgetHostViewAndroid.
@@ -107,7 +105,6 @@ class CONTENT_EXPORT RenderWidgetHostViewAndroid
void InitAsFullscreen(RenderWidgetHostView* reference_host_view) override;
void SetSize(const gfx::Size& size) override;
void SetBounds(const gfx::Rect& rect) override;
- gfx::Vector2dF GetLastScrollOffset() const override;
gfx::NativeView GetNativeView() const override;
gfx::NativeViewAccessible GetNativeViewAccessible() override;
void Focus() override;
@@ -171,7 +168,6 @@ class CONTENT_EXPORT RenderWidgetHostViewAndroid
void OnDidNavigateMainFrameToNewPage() override;
void SetNeedsBeginFrames(bool needs_begin_frames) override;
void SetWantsAnimateOnlyBeginFrames() override;
- RenderWidgetHostImpl* GetRenderWidgetHostImpl() const override;
viz::FrameSinkId GetFrameSinkId() override;
bool TransformPointToLocalCoordSpace(const gfx::PointF& point,
const viz::SurfaceId& original_surface,
@@ -186,6 +182,7 @@ class CONTENT_EXPORT RenderWidgetHostViewAndroid
GetTouchSelectionControllerClientManager() override;
viz::LocalSurfaceId GetLocalSurfaceId() const override;
void OnRenderWidgetInit() override;
+ void TakeFallbackContentFrom(RenderWidgetHostView* view) override;
// ui::ViewClient implementation.
bool OnTouchEvent(const ui::MotionEventAndroid& m) override;
@@ -235,6 +232,11 @@ class CONTENT_EXPORT RenderWidgetHostViewAndroid
// DelegatedFrameHostAndroid::Client implementation.
void SetBeginFrameSource(viz::BeginFrameSource* begin_frame_source) override;
void DidReceiveCompositorFrameAck() override;
+ void DidPresentCompositorFrame(uint32_t presentation_token,
+ base::TimeTicks time,
+ base::TimeDelta refresh,
+ uint32_t flags) override;
+ void DidDiscardCompositorFrame(uint32_t presentation_token) override;
void ReclaimResources(
const std::vector<viz::ReturnedResource>& resources) override;
void OnFrameTokenChanged(uint32_t frame_token) override;
@@ -246,8 +248,7 @@ class CONTENT_EXPORT RenderWidgetHostViewAndroid
bool WantsAnimateOnlyBeginFrames() const override;
// Non-virtual methods
- void SetContentViewCore(ContentViewCore* content_view_core);
- void OnContentViewCoreDestroyed();
+ void UpdateNativeViewTree(gfx::NativeView parent_native_view);
SkColor GetCachedBackgroundColor() const;
void SendKeyEvent(const NativeWebKeyboardEvent& event);
void SendMouseEvent(const ui::MotionEventAndroid&, int action_button);
@@ -289,9 +290,7 @@ class CONTENT_EXPORT RenderWidgetHostViewAndroid
void MoveCaret(const gfx::Point& point);
void ShowContextMenuAtPoint(const gfx::Point& point, ui::MenuSourceType);
void DismissTextHandles();
- void SetTextHandlesTemporarilyHidden(bool hidden);
- // |x_px| and |y_px| are in physical pixel scale.
- void OnShowUnhandledTapUIIfNeeded(int x_px, int y_px);
+ void SetTextHandlesTemporarilyHidden(bool hide_handles);
void OnSelectWordAroundCaretAck(bool did_select,
int start_adjust,
int end_adjust);
@@ -390,8 +389,7 @@ class CONTENT_EXPORT RenderWidgetHostViewAndroid
void OnFocusInternal();
void LostFocusInternal();
- // The model object.
- RenderWidgetHostImpl* host_;
+ void SetTextHandlesHiddenForStylus(bool hide_handles);
// The begin frame source being observed. Null if none.
viz::BeginFrameSource* begin_frame_source_;
@@ -413,8 +411,11 @@ class CONTENT_EXPORT RenderWidgetHostViewAndroid
// appearance of overscroll glow and the keyboard.
bool is_in_vr_;
- // ContentViewCore is our interface to the view system.
- ContentViewCore* content_view_core_;
+ // Specifies whether touch selection handles are hidden due to stylus.
+ bool handles_hidden_by_stylus_ = false;
+
+ // Specifies whether touch selection handles are hidden due to text selection.
+ bool handles_hidden_by_selection_ui_ = false;
ImeAdapterAndroid* ime_adapter_android_;
TapDisambiguator* tap_disambiguator_;
@@ -472,12 +473,11 @@ class CONTENT_EXPORT RenderWidgetHostViewAndroid
bool observing_root_window_;
- // The last scroll offset of the view.
- gfx::Vector2dF last_scroll_offset_;
-
bool controls_initialized_ = false;
float prev_top_shown_pix_;
+ float prev_top_controls_translate_;
float prev_bottom_shown_pix_;
+ float prev_bottom_controls_translate_;
float page_scale_;
float min_page_scale_;
float max_page_scale_;
diff --git a/chromium/content/browser/renderer_host/render_widget_host_view_aura.cc b/chromium/content/browser/renderer_host/render_widget_host_view_aura.cc
index 00bcfa03587..ebf2d257e64 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_view_aura.cc
+++ b/chromium/content/browser/renderer_host/render_widget_host_view_aura.cc
@@ -14,7 +14,6 @@
#include "base/debug/stack_trace.h"
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/trace_event/trace_event.h"
@@ -59,8 +58,8 @@
#include "services/service_manager/public/cpp/interface_provider.h"
#include "services/ui/common/switches.h"
#include "services/ui/public/interfaces/window_manager_constants.mojom.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
-#include "third_party/WebKit/public/web/WebImeTextSpan.h"
+#include "third_party/blink/public/platform/web_input_event.h"
+#include "third_party/blink/public/web/web_ime_text_span.h"
#include "ui/accessibility/platform/aura_window_properties.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/client/cursor_client.h"
@@ -108,9 +107,9 @@
#include "content/browser/accessibility/browser_accessibility_manager_win.h"
#include "content/browser/accessibility/browser_accessibility_win.h"
#include "content/browser/renderer_host/legacy_render_widget_host_win.h"
+#include "ui/base/ime/win/osk_display_manager.h"
+#include "ui/base/ime/win/osk_display_observer.h"
#include "ui/base/win/hidden_window.h"
-#include "ui/base/win/osk_display_manager.h"
-#include "ui/base/win/osk_display_observer.h"
#include "ui/display/win/screen_win.h"
#include "ui/gfx/gdi_util.h"
#endif
@@ -148,14 +147,8 @@ namespace {
// is obscured by the on screen keyboard.
class WinScreenKeyboardObserver : public ui::OnScreenKeyboardObserver {
public:
- WinScreenKeyboardObserver(RenderWidgetHostViewAura* host_view,
- const gfx::Point& location_in_screen,
- float scale_factor,
- aura::Window* window)
- : host_view_(host_view),
- location_in_screen_(location_in_screen),
- device_scale_factor_(scale_factor),
- window_(window) {
+ WinScreenKeyboardObserver(RenderWidgetHostViewAura* host_view)
+ : host_view_(host_view) {
host_view_->SetInsets(gfx::Insets());
}
@@ -165,65 +158,18 @@ class WinScreenKeyboardObserver : public ui::OnScreenKeyboardObserver {
}
// base::win::OnScreenKeyboardObserver overrides.
- void OnKeyboardVisible(const gfx::Rect& keyboard_rect_pixels) override {
- gfx::Point location_in_pixels =
- gfx::ConvertPointToPixel(device_scale_factor_, location_in_screen_);
-
- // Restore the viewport.
- host_view_->SetInsets(gfx::Insets());
-
- if (keyboard_rect_pixels.Contains(location_in_pixels)) {
- aura::client::ScreenPositionClient* screen_position_client =
- aura::client::GetScreenPositionClient(window_->GetRootWindow());
- if (!screen_position_client)
- return;
-
- DVLOG(1) << "OSK covering focus point.";
- gfx::Rect keyboard_rect =
- gfx::ConvertRectToDIP(device_scale_factor_, keyboard_rect_pixels);
- gfx::Rect bounds_in_screen = window_->GetBoundsInScreen();
-
- DCHECK(bounds_in_screen.bottom() > keyboard_rect.y());
-
- // Set the viewport of the window to be just above the on screen
- // keyboard.
- int viewport_bottom = bounds_in_screen.bottom() - keyboard_rect.y();
-
- // If the viewport is bigger than the view, then we cannot handle it
- // with the current approach. Moving the window above the OSK is one way.
- // That for a later patchset.
- if (viewport_bottom > bounds_in_screen.height())
- return;
-
- host_view_->SetInsets(gfx::Insets(0, 0, viewport_bottom, 0));
-
- gfx::Point origin(location_in_screen_);
- screen_position_client->ConvertPointFromScreen(window_, &origin);
-
- // TODO(ekaramad): We should support the case where the focused node is
- // inside an OOPIF (https://crbug.com/676037).
- // We want to scroll the node into a rectangle which originates from
- // the touch point and a small offset (10) in either direction.
- gfx::Rect node_rect(origin.x(), origin.y(), 10, 10);
-
- host_view_->ScrollFocusedEditableNodeIntoRect(node_rect);
- }
+ void OnKeyboardVisible(const gfx::Rect& keyboard_rect) override {
+ host_view_->SetInsets(gfx::Insets(
+ 0, 0, keyboard_rect.IsEmpty() ? 0 : keyboard_rect.height(), 0));
}
- void OnKeyboardHidden(const gfx::Rect& keyboard_rect_pixels) override {
+ void OnKeyboardHidden() override {
// Restore the viewport.
host_view_->SetInsets(gfx::Insets());
}
private:
RenderWidgetHostViewAura* host_view_;
- // The location in DIPs where the touch occurred.
- gfx::Point location_in_screen_;
- // The current device scale factor.
- float device_scale_factor_;
-
- // The content Window.
- aura::Window* window_;
DISALLOW_COPY_AND_ASSIGN(WinScreenKeyboardObserver);
};
@@ -286,10 +232,10 @@ void RenderWidgetHostViewAura::ApplyEventFilterForPopupExit(
// of the fact that focus was lost for the host window by sending a Blur
// notification. We also set a flag in the view indicating that we need
// to force a Focus notification on the next mouse down.
- if (popup_parent_host_view_ && popup_parent_host_view_->host_) {
+ if (popup_parent_host_view_ && popup_parent_host_view_->host()) {
popup_parent_host_view_->event_handler()
->set_focus_on_mouse_down_or_key_event(true);
- popup_parent_host_view_->host_->Blur();
+ popup_parent_host_view_->host()->Blur();
}
// Note: popup_parent_host_view_ may be NULL when there are multiple
// popup children per view. See: RenderWidgetHostViewAura::InitAsPopup().
@@ -326,6 +272,11 @@ class RenderWidgetHostViewAura::WindowObserver : public aura::WindowObserver {
view_->ParentHierarchyChanged();
}
+ void OnWindowTitleChanged(aura::Window* window) override {
+ if (window == view_->window_)
+ view_->WindowTitleChanged();
+ }
+
private:
RenderWidgetHostViewAura* view_;
@@ -386,10 +337,10 @@ class RenderWidgetHostViewAura::WindowAncestorObserver
// RenderWidgetHostViewAura, public:
RenderWidgetHostViewAura::RenderWidgetHostViewAura(
- RenderWidgetHost* host,
+ RenderWidgetHost* widget_host,
bool is_guest_view_hack,
bool is_mus_browser_plugin_guest)
- : host_(RenderWidgetHostImpl::From(host)),
+ : RenderWidgetHostViewBase(widget_host),
is_mus_browser_plugin_guest_(is_mus_browser_plugin_guest),
window_(nullptr),
in_shutdown_(false),
@@ -410,15 +361,18 @@ RenderWidgetHostViewAura::RenderWidgetHostViewAura(
has_snapped_to_boundary_(false),
is_guest_view_hack_(is_guest_view_hack),
device_scale_factor_(0.0f),
- event_handler_(new RenderWidgetHostViewEventHandler(host_, this, this)),
+ event_handler_(new RenderWidgetHostViewEventHandler(host(), this, this)),
frame_sink_id_(base::FeatureList::IsEnabled(features::kMash)
? viz::FrameSinkId()
: is_guest_view_hack_
? AllocateFrameSinkIdForGuestViewHack()
- : host_->GetFrameSinkId()),
+ : host()->GetFrameSinkId()),
weak_ptr_factory_(this) {
+ if (!is_mus_browser_plugin_guest_)
+ CreateDelegatedFrameHostClient();
+
if (!is_guest_view_hack_)
- host_->SetView(this);
+ host()->SetView(this);
// We should start observing the TextInputManager for IME-related events as
// well as monitoring its lifetime.
@@ -427,14 +381,15 @@ RenderWidgetHostViewAura::RenderWidgetHostViewAura(
cursor_manager_.reset(new CursorManager(this));
- SetOverscrollControllerEnabled(OverscrollConfig::GetMode() !=
- OverscrollConfig::Mode::kDisabled);
+ SetOverscrollControllerEnabled(
+ OverscrollConfig::GetHistoryNavigationMode() !=
+ OverscrollConfig::HistoryNavigationMode::kDisabled);
selection_controller_client_.reset(
new TouchSelectionControllerClientAura(this));
CreateSelectionController();
- RenderViewHost* rvh = RenderViewHost::From(host_);
+ RenderViewHost* rvh = RenderViewHost::From(host());
if (rvh) {
// TODO(mostynb): actually use prefs. Landing this as a separate CL
// first to rebaseline some unreliable layout tests.
@@ -448,9 +403,6 @@ RenderWidgetHostViewAura::RenderWidgetHostViewAura(
void RenderWidgetHostViewAura::InitAsChild(gfx::NativeView parent_view) {
if (is_mus_browser_plugin_guest_)
return;
-
- CreateDelegatedFrameHostClient();
-
CreateAuraWindow(aura::client::WINDOW_TYPE_CONTROL);
if (parent_view)
@@ -464,7 +416,6 @@ void RenderWidgetHostViewAura::InitAsPopup(
const gfx::Rect& bounds_in_screen) {
// Popups never have |is_mus_browser_plugin_guest_| set to true.
DCHECK(!is_mus_browser_plugin_guest_);
- CreateDelegatedFrameHostClient();
popup_parent_host_view_ =
static_cast<RenderWidgetHostViewAura*>(parent_host_view);
@@ -516,7 +467,6 @@ void RenderWidgetHostViewAura::InitAsFullscreen(
// |is_mus_browser_plugin_guest_| is always false.
DCHECK(!is_mus_browser_plugin_guest_);
is_fullscreen_ = true;
- CreateDelegatedFrameHostClient();
CreateAuraWindow(aura::client::WINDOW_TYPE_NORMAL);
window_->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_FULLSCREEN);
@@ -581,10 +531,6 @@ void RenderWidgetHostViewAura::SetBounds(const gfx::Rect& rect) {
InternalSetBounds(gfx::Rect(relative_origin, rect.size()));
}
-gfx::Vector2dF RenderWidgetHostViewAura::GetLastScrollOffset() const {
- return last_scroll_offset_;
-}
-
gfx::NativeView RenderWidgetHostViewAura::GetNativeView() const {
DCHECK(!is_mus_browser_plugin_guest_);
return window_;
@@ -599,16 +545,16 @@ HWND RenderWidgetHostViewAura::GetHostWindowHWND() const {
gfx::NativeViewAccessible RenderWidgetHostViewAura::GetNativeViewAccessible() {
#if defined(OS_WIN)
- aura::WindowTreeHost* host = window_->GetHost();
- if (!host)
+ aura::WindowTreeHost* window_host = window_->GetHost();
+ if (!window_host)
return static_cast<gfx::NativeViewAccessible>(NULL);
BrowserAccessibilityManager* manager =
- host_->GetOrCreateRootBrowserAccessibilityManager();
+ host()->GetOrCreateRootBrowserAccessibilityManager();
if (manager)
return ToBrowserAccessibilityWin(manager->GetRoot())->GetCOM();
#elif defined(USE_X11)
BrowserAccessibilityManager* manager =
- host_->GetOrCreateRootBrowserAccessibilityManager();
+ host()->GetOrCreateRootBrowserAccessibilityManager();
if (manager && manager->GetRoot())
return manager->GetRoot()->GetNativeViewAccessible();
#endif
@@ -632,12 +578,12 @@ void RenderWidgetHostViewAura::SetWantsAnimateOnlyBeginFrames() {
}
void RenderWidgetHostViewAura::OnBeginFrame(base::TimeTicks frame_time) {
- host_->ProgressFling(frame_time);
+ host()->ProgressFling(frame_time);
UpdateNeedsBeginFramesInternal();
}
RenderFrameHostImpl* RenderWidgetHostViewAura::GetFocusedFrame() const {
- RenderViewHost* rvh = RenderViewHost::From(host_);
+ RenderViewHost* rvh = RenderViewHost::From(host());
if (!rvh)
return nullptr;
FrameTreeNode* focused_frame =
@@ -704,11 +650,11 @@ void RenderWidgetHostViewAura::WasUnOccluded() {
ui::LatencyInfo renderer_latency_info, browser_latency_info;
if (has_saved_frame) {
browser_latency_info.AddLatencyNumber(ui::TAB_SHOW_COMPONENT,
- host_->GetLatencyComponentId(), 0);
+ host()->GetLatencyComponentId(), 0);
browser_latency_info.set_trace_id(++tab_show_sequence_);
} else {
renderer_latency_info.AddLatencyNumber(ui::TAB_SHOW_COMPONENT,
- host_->GetLatencyComponentId(), 0);
+ host()->GetLatencyComponentId(), 0);
renderer_latency_info.set_trace_id(++tab_show_sequence_);
}
@@ -720,7 +666,7 @@ void RenderWidgetHostViewAura::WasUnOccluded() {
TRACE_EVENT_ASYNC_BEGIN0("latency", "TabSwitching::Latency",
tab_show_sequence_);
- host_->WasShown(renderer_latency_info);
+ host()->WasShown(renderer_latency_info);
aura::Window* root = window_->GetRootWindow();
if (root) {
@@ -742,8 +688,8 @@ void RenderWidgetHostViewAura::WasUnOccluded() {
}
void RenderWidgetHostViewAura::WasOccluded() {
- if (!host_->is_hidden()) {
- host_->WasHidden();
+ if (!host()->is_hidden()) {
+ host()->WasHidden();
if (delegated_frame_host_)
delegated_frame_host_->WasHidden();
@@ -775,7 +721,7 @@ void RenderWidgetHostViewAura::SetBackgroundColor(SkColor color) {
DCHECK(SkColorGetA(color) == SK_AlphaOPAQUE ||
SkColorGetA(color) == SK_AlphaTRANSPARENT);
- host_->SetBackgroundOpaque(SkColorGetA(color) == SK_AlphaOPAQUE);
+ host()->SetBackgroundOpaque(SkColorGetA(color) == SK_AlphaOPAQUE);
}
SkColor RenderWidgetHostViewAura::background_color() const {
@@ -793,6 +739,13 @@ void RenderWidgetHostViewAura::UpdateBackgroundColorFromRenderer(
window_->layer()->SetColor(color);
}
+void RenderWidgetHostViewAura::WindowTitleChanged() {
+ if (delegated_frame_host_) {
+ delegated_frame_host_->WindowTitleChanged(
+ base::UTF16ToUTF8(window_->GetTitle()));
+ }
+}
+
bool RenderWidgetHostViewAura::IsMouseLocked() {
return event_handler_->mouse_locked();
}
@@ -806,20 +759,18 @@ gfx::Size RenderWidgetHostViewAura::GetVisibleViewportSize() const {
void RenderWidgetHostViewAura::SetInsets(const gfx::Insets& insets) {
if (insets != insets_) {
insets_ = insets;
- host_->WasResized(!insets_.IsEmpty());
+ host()->WasResized(!insets_.IsEmpty());
}
}
void RenderWidgetHostViewAura::FocusedNodeTouched(
- const gfx::Point& location_dips_screen,
bool editable) {
#if defined(OS_WIN)
ui::OnScreenKeyboardDisplayManager* osk_display_manager =
ui::OnScreenKeyboardDisplayManager::GetInstance();
DCHECK(osk_display_manager);
- if (editable && host_->GetView() && host_->delegate()) {
- keyboard_observer_.reset(new WinScreenKeyboardObserver(
- this, location_dips_screen, device_scale_factor_, window_));
+ if (editable && host()->GetView() && host()->delegate()) {
+ keyboard_observer_.reset(new WinScreenKeyboardObserver(this));
if (!osk_display_manager->DisplayVirtualKeyboard(keyboard_observer_.get()))
keyboard_observer_.reset(nullptr);
virtual_keyboard_requested_ = keyboard_observer_.get();
@@ -872,6 +823,11 @@ void RenderWidgetHostViewAura::Destroy() {
void RenderWidgetHostViewAura::SetTooltipText(
const base::string16& tooltip_text) {
+ GetCursorManager()->SetTooltipTextForView(this, tooltip_text);
+}
+
+void RenderWidgetHostViewAura::DisplayTooltipText(
+ const base::string16& tooltip_text) {
tooltip_ = tooltip_text;
aura::Window* root_window = window_->GetRootWindow();
wm::TooltipClient* tooltip_client = wm::GetTooltipClient(root_window);
@@ -892,10 +848,6 @@ void RenderWidgetHostViewAura::CopyFromSurface(
const gfx::Rect& src_subrect,
const gfx::Size& dst_size,
base::OnceCallback<void(const SkBitmap&)> callback) {
- if (!IsSurfaceAvailableForCopy()) {
- std::move(callback).Run(SkBitmap());
- return;
- }
delegated_frame_host_->CopyFromCompositingSurface(src_subrect, dst_size,
std::move(callback));
}
@@ -919,16 +871,6 @@ void RenderWidgetHostViewAura::OnLegacyWindowDestroyed() {
}
#endif
-void RenderWidgetHostViewAura::CreateCompositorFrameSink(
- CreateCompositorFrameSinkCallback callback) {
- // DelegatedFrameHost registers the FrameSinkId, so we need to wait
- // for that to be created before creating a CompositorFrameSink.
- if (delegated_frame_host_)
- std::move(callback).Run(frame_sink_id_);
- else
- create_frame_sink_callback_ = std::move(callback);
-}
-
void RenderWidgetHostViewAura::DidCreateNewRendererCompositorFrameSink(
viz::mojom::CompositorFrameSinkClient* renderer_compositor_frame_sink) {
renderer_compositor_frame_sink_ = renderer_compositor_frame_sink;
@@ -949,26 +891,11 @@ void RenderWidgetHostViewAura::SubmitCompositorFrame(
// This allows us to, when navigating to a new page, transfer this color to
// that page. This allows us to pass this background color to new views on
// navigation.
+ // TODO(yiyix): Remove this line when https://crbug.com/830540 is fixed.
UpdateBackgroundColorFromRenderer(frame.metadata.root_background_color);
- last_scroll_offset_ = frame.metadata.root_scroll_offset;
- if (IsUseZoomForDSFEnabled()) {
- // With zoom-for-DSF Blink pixel coordinates are used and zoom is used to
- // adjusts for the device scale factor. That's why last_scroll_offset_
- // needs to be scaled to view coordinates.
- // Without zoom-for-DSF the values are already in view coordinates.
- last_scroll_offset_.Scale(1.0f / current_device_scale_factor_);
- }
-
delegated_frame_host_->SubmitCompositorFrame(
local_surface_id, std::move(frame), std::move(hit_test_region_list));
- if (frame.metadata.selection.start != selection_start_ ||
- frame.metadata.selection.end != selection_end_) {
- selection_start_ = frame.metadata.selection.start;
- selection_end_ = frame.metadata.selection.end;
- selection_controller_client_->UpdateClientSelectionBounds(selection_start_,
- selection_end_);
- }
}
void RenderWidgetHostViewAura::OnDidNotProduceFrame(
@@ -1061,7 +988,7 @@ void RenderWidgetHostViewAura::GestureEventAck(
event.data.scroll_update.inertial_phase ==
blink::WebGestureEvent::kMomentumPhase &&
overscroll_controller_->overscroll_mode() != OVERSCROLL_NONE) {
- host_->StopFling();
+ host()->StopFling();
}
}
event_handler_->GestureEventAck(event, ack_result);
@@ -1070,9 +997,9 @@ void RenderWidgetHostViewAura::GestureEventAck(
void RenderWidgetHostViewAura::ProcessAckedTouchEvent(
const TouchEventWithLatencyInfo& touch,
InputEventAckState ack_result) {
- aura::WindowTreeHost* host = window_->GetHost();
+ aura::WindowTreeHost* window_host = window_->GetHost();
// |host| is NULL during tests.
- if (!host)
+ if (!window_host)
return;
// The TouchScrollStarted event is generated & consumed downstream from the
@@ -1108,13 +1035,14 @@ void RenderWidgetHostViewAura::ProcessAckedTouchEvent(
for (size_t i = 0; i < touch.event.touches_length; ++i) {
if (touch.event.touches[i].state == required_state) {
DCHECK(!sent_ack);
- host->dispatcher()->ProcessedTouchEvent(
+ window_host->dispatcher()->ProcessedTouchEvent(
touch.event.unique_touch_event_id, window_, result,
InputEventAckStateIsSetNonBlocking(ack_result));
if (touch.event.touch_start_or_first_touch_move &&
- result == ui::ER_HANDLED && host_->delegate() &&
- host_->delegate()->GetInputEventRouter()) {
- host_->delegate()
+ result == ui::ER_HANDLED && host()->delegate() &&
+ host()->delegate()->GetInputEventRouter()) {
+ host()
+ ->delegate()
->GetInputEventRouter()
->OnHandledTouchStartOrFirstTouchMove(
touch.event.unique_touch_event_id);
@@ -1127,7 +1055,7 @@ void RenderWidgetHostViewAura::ProcessAckedTouchEvent(
std::unique_ptr<SyntheticGestureTarget>
RenderWidgetHostViewAura::CreateSyntheticGestureTarget() {
return std::unique_ptr<SyntheticGestureTarget>(
- new SyntheticGestureTargetAura(host_));
+ new SyntheticGestureTargetAura(host()));
}
InputEventAckState RenderWidgetHostViewAura::FilterInputEvent(
@@ -1138,7 +1066,7 @@ InputEventAckState RenderWidgetHostViewAura::FilterInputEvent(
static_cast<const WebGestureEvent&>(input_event);
// Zero-velocity touchpad flings are an Aura-specific signal that the
// touchpad scroll has ended, and should not be forwarded to the renderer.
- if (gesture_event.source_device == blink::kWebGestureDeviceTouchpad &&
+ if (gesture_event.SourceDevice() == blink::kWebGestureDeviceTouchpad &&
!gesture_event.data.fling_start.velocity_x &&
!gesture_event.data.fling_start.velocity_y) {
consumed = true;
@@ -1221,6 +1149,19 @@ void RenderWidgetHostViewAura::UnlockMouse() {
event_handler_->UnlockMouse();
}
+bool RenderWidgetHostViewAura::LockKeyboard(
+ base::Optional<base::flat_set<int>> keys) {
+ return event_handler_->LockKeyboard(std::move(keys));
+}
+
+void RenderWidgetHostViewAura::UnlockKeyboard() {
+ event_handler_->UnlockKeyboard();
+}
+
+bool RenderWidgetHostViewAura::IsKeyboardLocked() {
+ return event_handler_->IsKeyboardLocked();
+}
+
////////////////////////////////////////////////////////////////////////////////
// RenderWidgetHostViewAura, ui::TextInputClient implementation:
void RenderWidgetHostViewAura::SetCompositionText(
@@ -1446,7 +1387,7 @@ bool RenderWidgetHostViewAura::GetTextFromRange(
}
void RenderWidgetHostViewAura::OnInputMethodChanged() {
- // TODO(suzhe): implement the newly added “locale” property of HTML DOM
+ // TODO(suzhe): implement the newly added "locale" property of HTML DOM
// TextEvent.
}
@@ -1570,7 +1511,7 @@ bool RenderWidgetHostViewAura::CanFocus() {
}
void RenderWidgetHostViewAura::OnCaptureLost() {
- host_->LostCapture();
+ host()->LostCapture();
}
void RenderWidgetHostViewAura::OnPaint(const ui::PaintContext& context) {
@@ -1602,7 +1543,6 @@ void RenderWidgetHostViewAura::OnWindowDestroying(aura::Window* window) {
// RenderWidgetHostViewAura instance goes away etc. To avoid that we
// destroy the LegacyRenderWidgetHostHWND instance here.
if (legacy_render_widget_host_HWND_) {
- legacy_render_widget_host_HWND_->set_host(NULL);
legacy_render_widget_host_HWND_->Destroy();
// The Destroy call above will delete the LegacyRenderWidgetHostHWND
// instance.
@@ -1769,11 +1709,11 @@ void RenderWidgetHostViewAura::OnWindowFocused(aura::Window* gained_focus,
// We need to honor input bypass if the associated tab is does not want
// input. This gives the current focused window a chance to be the text
// input client and handle events.
- if (host_->ignore_input_events())
+ if (host()->ignore_input_events())
return;
- host_->GotFocus();
- host_->SetActive(true);
+ host()->GotFocus();
+ host()->SetActive(true);
ui::InputMethod* input_method = GetInputMethod();
if (input_method) {
@@ -1783,12 +1723,12 @@ void RenderWidgetHostViewAura::OnWindowFocused(aura::Window* gained_focus,
}
BrowserAccessibilityManager* manager =
- host_->GetRootBrowserAccessibilityManager();
+ host()->GetRootBrowserAccessibilityManager();
if (manager)
manager->OnWindowFocused();
} else if (window_ == lost_focus) {
- host_->SetActive(false);
- host_->LostFocus();
+ host()->SetActive(false);
+ host()->LostFocus();
DetachFromInputMethod();
@@ -1802,7 +1742,7 @@ void RenderWidgetHostViewAura::OnWindowFocused(aura::Window* gained_focus,
overscroll_controller_->Cancel();
BrowserAccessibilityManager* manager =
- host_->GetRootBrowserAccessibilityManager();
+ host()->GetRootBrowserAccessibilityManager();
if (manager)
manager->OnWindowBlurred();
@@ -1851,12 +1791,30 @@ void RenderWidgetHostViewAura::OnHostMovedInPixels(
}
////////////////////////////////////////////////////////////////////////////////
+// RenderWidgetHostViewAura, RenderFrameMetadataProvider::Observer
+// implementation:
+void RenderWidgetHostViewAura::OnRenderFrameMetadataChanged() {
+ RenderWidgetHostViewBase::OnRenderFrameMetadataChanged();
+ const cc::RenderFrameMetadata& metadata =
+ host()->render_frame_metadata_provider()->LastRenderFrameMetadata();
+ UpdateBackgroundColorFromRenderer(metadata.root_background_color);
+
+ if (metadata.selection.start != selection_start_ ||
+ metadata.selection.end != selection_end_) {
+ selection_start_ = metadata.selection.start;
+ selection_end_ = metadata.selection.end;
+ selection_controller_client_->UpdateClientSelectionBounds(selection_start_,
+ selection_end_);
+ }
+}
+
+////////////////////////////////////////////////////////////////////////////////
// RenderWidgetHostViewAura, private:
RenderWidgetHostViewAura::~RenderWidgetHostViewAura() {
// Ask the RWH to drop reference to us.
if (!is_guest_view_hack_)
- host_->ViewDestroyed();
+ host()->ViewDestroyed();
selection_controller_.reset();
selection_controller_client_.reset();
@@ -1933,38 +1891,26 @@ void RenderWidgetHostViewAura::CreateAuraWindow(aura::client::WindowType type) {
GetWindowTreeClientFromRenderer(),
ui::mojom::kEmbedFlagEmbedderInterceptsEvents |
ui::mojom::kEmbedFlagEmbedderControlsVisibility,
- base::Bind(&EmbedCallback));
+ base::BindOnce(&EmbedCallback));
}
void RenderWidgetHostViewAura::CreateDelegatedFrameHostClient() {
if (!frame_sink_id_.is_valid())
return;
- // Tests may set |delegated_frame_host_client_|.
- if (!delegated_frame_host_client_) {
- delegated_frame_host_client_ =
- std::make_unique<DelegatedFrameHostClientAura>(this);
- }
-
+ delegated_frame_host_client_ =
+ std::make_unique<DelegatedFrameHostClientAura>(this);
const bool enable_viz =
base::FeatureList::IsEnabled(features::kVizDisplayCompositor);
delegated_frame_host_ = std::make_unique<DelegatedFrameHost>(
frame_sink_id_, delegated_frame_host_client_.get(),
features::IsSurfaceSynchronizationEnabled(), enable_viz,
false /* should_register_frame_sink_id */);
- if (!create_frame_sink_callback_.is_null())
- std::move(create_frame_sink_callback_).Run(frame_sink_id_);
-
- if (renderer_compositor_frame_sink_) {
- delegated_frame_host_->DidCreateNewRendererCompositorFrameSink(
- renderer_compositor_frame_sink_);
- }
- UpdateNeedsBeginFramesInternal();
// Let the page-level input event router know about our surface ID
// namespace for surface-based hit testing.
- if (host_->delegate() && host_->delegate()->GetInputEventRouter()) {
- host_->delegate()->GetInputEventRouter()->AddFrameSinkIdOwner(
+ if (host()->delegate() && host()->delegate()->GetInputEventRouter()) {
+ host()->delegate()->GetInputEventRouter()->AddFrameSinkIdOwner(
GetFrameSinkId(), this);
}
}
@@ -1973,7 +1919,7 @@ void RenderWidgetHostViewAura::UpdateCursorIfOverSelf() {
if (is_mus_browser_plugin_guest_)
return;
- if (host_->GetProcess()->FastShutdownStarted())
+ if (host()->GetProcess()->FastShutdownStarted())
return;
aura::Window* root_window = window_->GetRootWindow();
@@ -2065,7 +2011,7 @@ RenderWidgetHostViewAura::GetFocusedViewForTextSelection() {
void RenderWidgetHostViewAura::Shutdown() {
if (!in_shutdown_) {
in_shutdown_ = true;
- host_->ShutdownAndDestroyWidget(true);
+ host()->ShutdownAndDestroyWidget(true);
}
}
@@ -2098,7 +2044,7 @@ void RenderWidgetHostViewAura::ShowContextMenu(
const ContextMenuParams& params) {
// Use RenderViewHostDelegate to get to the WebContentsViewAura, which will
// actually show the disambiguation popup.
- RenderViewHost* rvh = RenderViewHost::From(host_);
+ RenderViewHost* rvh = RenderViewHost::From(host());
if (!rvh)
return;
@@ -2114,13 +2060,13 @@ void RenderWidgetHostViewAura::ShowContextMenu(
void RenderWidgetHostViewAura::NotifyRendererOfCursorVisibilityState(
bool is_visible) {
- if (host_->is_hidden() ||
+ if (host()->is_hidden() ||
(cursor_visibility_state_in_renderer_ == VISIBLE && is_visible) ||
(cursor_visibility_state_in_renderer_ == NOT_VISIBLE && !is_visible))
return;
cursor_visibility_state_in_renderer_ = is_visible ? VISIBLE : NOT_VISIBLE;
- host_->SendCursorVisibilityState(is_visible);
+ host()->SendCursorVisibilityState(is_visible);
}
void RenderWidgetHostViewAura::SetOverscrollControllerEnabled(bool enabled) {
@@ -2153,16 +2099,6 @@ void RenderWidgetHostViewAura::SnapToPhysicalPixelBoundary() {
has_snapped_to_boundary_ = true;
}
-bool RenderWidgetHostViewAura::OnShowContextMenu(
- const ContextMenuParams& params) {
-#if defined(OS_WIN)
- event_handler_->SetContextMenuParams(params);
- return params.source_type != ui::MENU_SOURCE_LONG_PRESS;
-#else
- return true;
-#endif // defined(OS_WIN)
-}
-
void RenderWidgetHostViewAura::SetSelectionControllerClientForTest(
std::unique_ptr<TouchSelectionControllerClientAura> client) {
selection_controller_client_.swap(client);
@@ -2188,6 +2124,9 @@ void RenderWidgetHostViewAura::InternalSetBounds(const gfx::Rect& rect) {
void RenderWidgetHostViewAura::SyncSurfaceProperties(
const cc::DeadlinePolicy& deadline_policy) {
+ if (IsLocalSurfaceIdAllocationSuppressed())
+ return;
+
if (delegated_frame_host_) {
delegated_frame_host_->WasResized(window_->GetLocalSurfaceId(),
window_->bounds().size(),
@@ -2195,10 +2134,10 @@ void RenderWidgetHostViewAura::SyncSurfaceProperties(
}
// Note that |host_| will retrieve resize parameters from
// |delegated_frame_host_|, so it must have WasResized called after.
- host_->WasResized();
- if (host_->auto_resize_enabled()) {
- host_->DidAllocateLocalSurfaceIdForAutoResize(
- host_->last_auto_resize_request_number());
+ host()->WasResized();
+ if (host()->auto_resize_enabled()) {
+ host()->DidAllocateLocalSurfaceIdForAutoResize(
+ host()->last_auto_resize_request_number());
}
}
@@ -2221,7 +2160,7 @@ void RenderWidgetHostViewAura::UpdateLegacyWin() {
// the associated RenderWidget is also visible before the
// LegacyRenderWidgetHostHWND instace is created. Ensure that it is shown
// here.
- if (!host_->is_hidden())
+ if (!host()->is_hidden())
legacy_render_widget_host_HWND_->Show();
}
}
@@ -2297,12 +2236,12 @@ void RenderWidgetHostViewAura::ForwardKeyboardEventWithLatencyInfo(
const NativeWebKeyboardEvent& event,
const ui::LatencyInfo& latency,
bool* update_event) {
- RenderWidgetHostImpl* target_host = host_;
+ RenderWidgetHostImpl* target_host = host();
// If there are multiple widgets on the page (such as when there are
// out-of-process iframes), pick the one that should process this event.
- if (host_->delegate())
- target_host = host_->delegate()->GetFocusedRenderWidgetHost(host_);
+ if (host()->delegate())
+ target_host = host()->delegate()->GetFocusedRenderWidgetHost(host());
if (!target_host)
return;
@@ -2347,11 +2286,6 @@ void RenderWidgetHostViewAura::OnDidNavigateMainFrameToNewPage() {
ui::GestureRecognizer::Get()->CancelActiveTouches(window_);
}
-RenderWidgetHostImpl* RenderWidgetHostViewAura::GetRenderWidgetHostImpl()
- const {
- return host_;
-}
-
viz::FrameSinkId RenderWidgetHostViewAura::GetFrameSinkId() {
return frame_sink_id_;
}
@@ -2380,7 +2314,7 @@ void RenderWidgetHostViewAura::OnUpdateTextInputStateCalled(
GetInputMethod()->ShowImeIfNeeded();
}
- if (auto* render_widget_host = updated_view->GetRenderWidgetHostImpl()) {
+ if (auto* render_widget_host = updated_view->host()) {
// Monitor the composition information if there is a focused editable node.
render_widget_host->RequestCompositionUpdates(
false /* immediate_request */,
@@ -2489,15 +2423,31 @@ void RenderWidgetHostViewAura::OnSynchronizedDisplayPropertiesChanged() {
WasResized(cc::DeadlinePolicy::UseDefaultDeadline());
}
-void RenderWidgetHostViewAura::ResizeDueToAutoResize(const gfx::Size& new_size,
- uint64_t sequence_number) {
- WasResized(cc::DeadlinePolicy::UseDefaultDeadline());
+viz::ScopedSurfaceIdAllocator RenderWidgetHostViewAura::ResizeDueToAutoResize(
+ const gfx::Size& new_size,
+ uint64_t sequence_number) {
+ base::OnceCallback<void()> allocation_task = base::BindOnce(
+ &RenderWidgetHostViewAura::WasResized, weak_ptr_factory_.GetWeakPtr(),
+ cc::DeadlinePolicy::UseDefaultDeadline());
+ return window_->GetSurfaceIdAllocator(std::move(allocation_task));
+}
+
+bool RenderWidgetHostViewAura::IsLocalSurfaceIdAllocationSuppressed() const {
+ DCHECK(window_);
+ return window_->IsLocalSurfaceIdAllocationSuppressed();
}
void RenderWidgetHostViewAura::DidNavigate() {
- WasResized(cc::DeadlinePolicy::UseExistingDeadline());
+ // The first navigation does not need a new LocalSurfaceID. The renderer can
+ // use the ID that was already provided.
+ if (is_first_navigation_) {
+ SyncSurfaceProperties(cc::DeadlinePolicy::UseExistingDeadline());
+ } else {
+ WasResized(cc::DeadlinePolicy::UseExistingDeadline());
+ }
if (delegated_frame_host_)
delegated_frame_host_->DidNavigate();
+ is_first_navigation_ = false;
}
// static
@@ -2508,4 +2458,20 @@ RenderWidgetHostViewAura::AllocateFrameSinkIdForGuestViewHack() {
->AllocateFrameSinkId();
}
+void RenderWidgetHostViewAura::TakeFallbackContentFrom(
+ RenderWidgetHostView* view) {
+ DCHECK(!static_cast<RenderWidgetHostViewBase*>(view)
+ ->IsRenderWidgetHostViewChildFrame());
+ DCHECK(!static_cast<RenderWidgetHostViewBase*>(view)
+ ->IsRenderWidgetHostViewGuest());
+ RenderWidgetHostViewAura* view_aura =
+ static_cast<RenderWidgetHostViewAura*>(view);
+ SetBackgroundColor(view_aura->background_color());
+ if (delegated_frame_host_ && view_aura->delegated_frame_host_) {
+ delegated_frame_host_->TakeFallbackContentFrom(
+ view_aura->delegated_frame_host_.get());
+ }
+ host()->GetContentRenderingTimeoutFrom(view_aura->host());
+}
+
} // namespace content
diff --git a/chromium/content/browser/renderer_host/render_widget_host_view_aura.h b/chromium/content/browser/renderer_host/render_widget_host_view_aura.h
index 15ada2cfce1..bc92c58c5c0 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_view_aura.h
+++ b/chromium/content/browser/renderer_host/render_widget_host_view_aura.h
@@ -67,13 +67,13 @@ class OnScreenKeyboardObserver;
namespace content {
#if defined(OS_WIN)
class LegacyRenderWidgetHostHWND;
+class DirectManipulationBrowserTest;
#endif
class CursorManager;
class DelegatedFrameHost;
class DelegatedFrameHostClient;
class RenderFrameHostImpl;
-class RenderWidgetHostImpl;
class RenderWidgetHostView;
class TouchSelectionControllerClientAura;
@@ -104,7 +104,6 @@ class CONTENT_EXPORT RenderWidgetHostViewAura
void InitAsChild(gfx::NativeView parent_view) override;
void SetSize(const gfx::Size& size) override;
void SetBounds(const gfx::Rect& rect) override;
- gfx::Vector2dF GetLastScrollOffset() const override;
gfx::NativeView GetNativeView() const override;
gfx::NativeViewAccessible GetNativeViewAccessible() override;
ui::TextInputClient* GetTextInputClient() override;
@@ -120,8 +119,7 @@ class CONTENT_EXPORT RenderWidgetHostViewAura
bool IsMouseLocked() override;
gfx::Size GetVisibleViewportSize() const override;
void SetInsets(const gfx::Insets& insets) override;
- void FocusedNodeTouched(const gfx::Point& location_dips_screen,
- bool editable) override;
+ void FocusedNodeTouched(bool editable) override;
void SetNeedsBeginFrames(bool needs_begin_frames) override;
void SetWantsAnimateOnlyBeginFrames() override;
TouchSelectionControllerClientManager*
@@ -140,6 +138,7 @@ class CONTENT_EXPORT RenderWidgetHostViewAura
int error_code) override;
void Destroy() override;
void SetTooltipText(const base::string16& tooltip_text) override;
+ void DisplayTooltipText(const base::string16& tooltip_text) override;
gfx::Size GetRequestedRendererSize() const override;
bool IsSurfaceAvailableForCopy() const override;
void CopyFromSurface(
@@ -168,8 +167,9 @@ class CONTENT_EXPORT RenderWidgetHostViewAura
void SetMainFrameAXTreeID(ui::AXTreeIDRegistry::AXTreeID id) override;
bool LockMouse() override;
void UnlockMouse() override;
- void CreateCompositorFrameSink(
- CreateCompositorFrameSinkCallback callback) override;
+ bool LockKeyboard(base::Optional<base::flat_set<int>> keys) override;
+ void UnlockKeyboard() override;
+ bool IsKeyboardLocked() override;
void DidCreateNewRendererCompositorFrameSink(
viz::mojom::CompositorFrameSinkClient* renderer_compositor_frame_sink)
override;
@@ -181,7 +181,6 @@ class CONTENT_EXPORT RenderWidgetHostViewAura
void ClearCompositorFrame() override;
void DidStopFlinging() override;
void OnDidNavigateMainFrameToNewPage() override;
- RenderWidgetHostImpl* GetRenderWidgetHostImpl() const override;
viz::FrameSinkId GetFrameSinkId() override;
viz::LocalSurfaceId GetLocalSurfaceId() const override;
bool TransformPointToLocalCoordSpace(const gfx::PointF& point,
@@ -200,9 +199,14 @@ class CONTENT_EXPORT RenderWidgetHostViewAura
base::OnceCallback<void(const base::UnguessableToken&)>
callback) override;
void OnSynchronizedDisplayPropertiesChanged() override;
- void ResizeDueToAutoResize(const gfx::Size& new_size,
- uint64_t sequence_number) override;
+ viz::ScopedSurfaceIdAllocator ResizeDueToAutoResize(
+ const gfx::Size& new_size,
+ uint64_t sequence_number) override;
+
+ bool IsLocalSurfaceIdAllocationSuppressed() const override;
+
void DidNavigate() override;
+ void TakeFallbackContentFrom(RenderWidgetHostView* view) override;
// Overridden from ui::TextInputClient:
void SetCompositionText(const ui::CompositionText& composition) override;
@@ -283,6 +287,9 @@ class CONTENT_EXPORT RenderWidgetHostViewAura
void OnHostMovedInPixels(aura::WindowTreeHost* host,
const gfx::Point& new_origin_in_pixels) override;
+ // RenderFrameMetadataProvider::Observer
+ void OnRenderFrameMetadataChanged() override;
+
#if defined(OS_WIN)
// Gets the HWND of the host window.
HWND GetHostWindowHWND() const;
@@ -309,13 +316,6 @@ class CONTENT_EXPORT RenderWidgetHostViewAura
void SnapToPhysicalPixelBoundary();
- // Called when the context menu is about to be displayed.
- // Returns true if the context menu should be displayed. We only return false
- // on Windows if the context menu is being displayed in response to a long
- // press gesture. On Windows we should be consistent like other apps and
- // display the menu when the touch is released.
- bool OnShowContextMenu(const ContextMenuParams& params);
-
// Used in tests to set a mock client for touch selection controller. It will
// create a new touch selection controller for the new client.
void SetSelectionControllerClientForTest(
@@ -354,6 +354,9 @@ class CONTENT_EXPORT RenderWidgetHostViewAura
friend class RenderWidgetHostViewAuraTest;
friend class RenderWidgetHostViewAuraCopyRequestTest;
friend class TestInputMethodObserver;
+#if defined(OS_WIN)
+ friend class DirectManipulationBrowserTest;
+#endif
FRIEND_TEST_ALL_PREFIXES(InputMethodResultAuraTest,
FinishImeCompositionSession);
FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest,
@@ -413,6 +416,8 @@ class CONTENT_EXPORT RenderWidgetHostViewAura
AllocateLocalSurfaceIdOnEviction);
FRIEND_TEST_ALL_PREFIXES(WebContentsViewAuraTest,
WebContentsViewReparent);
+ FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraSurfaceSynchronizationTest,
+ TakeFallbackContent);
class WindowObserver;
friend class WindowObserver;
@@ -519,11 +524,13 @@ class CONTENT_EXPORT RenderWidgetHostViewAura
void UpdateNeedsBeginFramesInternal();
// Applies background color without notifying the RenderWidget about
- // opaqueness changes.
+ // opaqueness changes. This allows us to, when navigating to a new page,
+ // transfer this color to that page. This allows us to pass this background
+ // color to new views on navigation.
void UpdateBackgroundColorFromRenderer(SkColor color);
- // The model object.
- RenderWidgetHostImpl* const host_;
+ // Called when the window title is changed.
+ void WindowTitleChanged();
const bool is_mus_browser_plugin_guest_;
@@ -618,9 +625,6 @@ class CONTENT_EXPORT RenderWidgetHostViewAura
bool has_snapped_to_boundary_;
- // The last scroll offset of the view.
- gfx::Vector2dF last_scroll_offset_;
-
// The last selection bounds reported to the view.
gfx::SelectionBound selection_start_;
gfx::SelectionBound selection_end_;
@@ -651,10 +655,7 @@ class CONTENT_EXPORT RenderWidgetHostViewAura
std::unique_ptr<CursorManager> cursor_manager_;
int tab_show_sequence_ = 0;
- // Stashes a request to create a CompositorFrameSink if it arrives before
- // DelegatedFrameHost is created. This is only used with VizDisplayCompositor
- // feature.
- CreateCompositorFrameSinkCallback create_frame_sink_callback_;
+ bool is_first_navigation_ = true;
base::WeakPtrFactory<RenderWidgetHostViewAura> weak_ptr_factory_;
diff --git a/chromium/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc b/chromium/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc
index 720e8fbffab..c099868cabc 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc
+++ b/chromium/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc
@@ -25,6 +25,7 @@
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "build/build_config.h"
+#include "cc/trees/render_frame_metadata.h"
#include "components/viz/common/features.h"
#include "components/viz/common/frame_sinks/begin_frame_args.h"
#include "components/viz/common/quads/compositor_frame.h"
@@ -39,8 +40,8 @@
#include "components/viz/test/compositor_frame_helpers.h"
#include "components/viz/test/fake_external_begin_frame_source.h"
#include "components/viz/test/fake_surface_observer.h"
+#include "components/viz/test/test_latest_local_surface_id_lookup_delegate.h"
#include "content/browser/browser_main_loop.h"
-#include "content/browser/browser_thread_impl.h"
#include "content/browser/compositor/test/test_image_transport_factory.h"
#include "content/browser/frame_host/render_widget_host_view_guest.h"
#include "content/browser/gpu/compositor_util.h"
@@ -50,6 +51,7 @@
#include "content/browser/renderer_host/input/mouse_wheel_event_queue.h"
#include "content/browser/renderer_host/overscroll_controller.h"
#include "content/browser/renderer_host/overscroll_controller_delegate.h"
+#include "content/browser/renderer_host/render_frame_metadata_provider_impl.h"
#include "content/browser/renderer_host/render_view_host_factory.h"
#include "content/browser/renderer_host/render_widget_host_delegate.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
@@ -82,6 +84,7 @@
#include "ui/aura/client/window_parenting_client.h"
#include "ui/aura/env.h"
#include "ui/aura/layout_manager.h"
+#include "ui/aura/scoped_keyboard_hook.h"
#include "ui/aura/test/aura_test_helper.h"
#include "ui/aura/test/aura_test_utils.h"
#include "ui/aura/test/test_cursor_client.h"
@@ -109,6 +112,7 @@
#include "ui/events/gestures/motion_event_aura.h"
#include "ui/events/keycodes/dom/dom_code.h"
#include "ui/events/keycodes/dom/keycode_converter.h"
+#include "ui/events/keycodes/keyboard_code_conversion.h"
#include "ui/events/test/event_generator.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/selection_bound.h"
@@ -137,8 +141,6 @@ void InstallDelegatedFrameHostClient(
RenderWidgetHostViewAura* render_widget_host_view,
std::unique_ptr<DelegatedFrameHostClient> delegated_frame_host_client);
-namespace {
-
constexpr uint64_t kFrameIndexStart =
viz::CompositorFrameSinkSupport::kFrameIndexStart;
@@ -289,6 +291,7 @@ class FakeRenderWidgetHostViewAura : public RenderWidgetHostViewAura {
: RenderWidgetHostViewAura(widget,
is_guest_view_hack,
false /* is_mus_browser_plugin_guest */),
+ is_guest_view_hack_(is_guest_view_hack),
delegated_frame_host_client_(
new FakeDelegatedFrameHostClientAura(this)) {
InstallDelegatedFrameHostClient(
@@ -352,12 +355,18 @@ class FakeRenderWidgetHostViewAura : public RenderWidgetHostViewAura {
return event_handler()->pointer_state();
}
+ void SetRenderFrameMetadata(cc::RenderFrameMetadata metadata) {
+ host()->render_frame_metadata_provider()->SetLastRenderFrameMetadataForTest(
+ metadata);
+ }
+
bool resize_locked() const {
return delegated_frame_host_client_->resize_locked();
}
bool compositor_locked() const {
return delegated_frame_host_client_->compositor_locked();
}
+ bool is_guest_view_hack() { return is_guest_view_hack_; }
gfx::Size last_frame_size_;
FakeWindowEventDispatcher* dispatcher_;
@@ -365,6 +374,7 @@ class FakeRenderWidgetHostViewAura : public RenderWidgetHostViewAura {
renderer_compositor_frame_sink_;
private:
+ bool is_guest_view_hack_;
FakeDelegatedFrameHostClientAura* delegated_frame_host_client_;
viz::mojom::CompositorFrameSinkClientPtr renderer_compositor_frame_sink_ptr_;
@@ -473,14 +483,51 @@ class MockRenderWidgetHostImpl : public RenderWidgetHostImpl {
std::unique_ptr<MockWidgetImpl> widget_impl_;
};
+class TestScopedKeyboardHook : public aura::ScopedKeyboardHook {
+ public:
+ TestScopedKeyboardHook();
+ ~TestScopedKeyboardHook() override;
+
+ // aura::ScopedKeyboardHook override.
+ bool IsKeyLocked(int native_key_code) override;
+
+ // Set up the keys being locked for testing. One of these methods must be
+ // called before using an instance.
+ void LockAllKeys();
+ void LockSpecificKey(int new_key_to_lock);
+
+ private:
+ bool keyboard_lock_active_ = false;
+ base::Optional<int> locked_key_;
+
+ DISALLOW_COPY_AND_ASSIGN(TestScopedKeyboardHook);
+};
+
+TestScopedKeyboardHook::TestScopedKeyboardHook() = default;
+
+TestScopedKeyboardHook::~TestScopedKeyboardHook() = default;
+
+bool TestScopedKeyboardHook::IsKeyLocked(int native_key_code) {
+ DCHECK(keyboard_lock_active_) << "Did you forget to reserve keys to lock?";
+ return !locked_key_ || (locked_key_.value() == native_key_code);
+}
+
+void TestScopedKeyboardHook::LockAllKeys() {
+ keyboard_lock_active_ = true;
+ locked_key_.reset();
+}
+
+void TestScopedKeyboardHook::LockSpecificKey(int key_to_lock) {
+ keyboard_lock_active_ = true;
+ locked_key_ = key_to_lock;
+}
+
enum WheelScrollingMode {
kWheelScrollingModeNone,
kWheelScrollLatching,
kAsyncWheelEvents,
};
-} // namespace
-
class RenderWidgetHostViewAuraTest : public testing::Test {
public:
RenderWidgetHostViewAuraTest(
@@ -490,10 +537,42 @@ class RenderWidgetHostViewAuraTest : public testing::Test {
is_guest_view_hack_(false) {}
static void InstallDelegatedFrameHostClient(
- RenderWidgetHostViewAura* render_widget_host_view,
+ RenderWidgetHostViewAura* view,
std::unique_ptr<DelegatedFrameHostClient> delegated_frame_host_client) {
- render_widget_host_view->delegated_frame_host_client_ =
- std::move(delegated_frame_host_client);
+ view->delegated_frame_host_client_ = std::move(delegated_frame_host_client);
+ const bool enable_viz =
+ base::FeatureList::IsEnabled(features::kVizDisplayCompositor);
+ view->delegated_frame_host_ = nullptr;
+ view->delegated_frame_host_ = std::make_unique<DelegatedFrameHost>(
+ view->frame_sink_id_, view->delegated_frame_host_client_.get(),
+ features::IsSurfaceSynchronizationEnabled(), enable_viz,
+ false /* should_register_frame_sink_id */);
+ }
+
+ FakeRenderWidgetHostViewAura* CreateView(bool is_guest_view_hack) {
+ int32_t routing_id = process_host_->GetNextRoutingID();
+ delegates_.push_back(base::WrapUnique(new MockRenderWidgetHostDelegate));
+ auto* widget_host = MockRenderWidgetHostImpl::Create(
+ delegates_.back().get(), process_host_, routing_id);
+ delegates_.back()->set_widget_host(widget_host);
+ widget_host->Init();
+ return new FakeRenderWidgetHostViewAura(widget_host, is_guest_view_hack);
+ }
+
+ void DestroyView(FakeRenderWidgetHostViewAura* view) {
+ // For guest-views, |view_| is not the view used by |widget_host_|.
+ bool is_guest_view_hack = view->is_guest_view_hack();
+ RenderWidgetHostImpl* host = view->host();
+ if (!is_guest_view_hack)
+ EXPECT_EQ(view, host->GetView());
+ view->Destroy();
+ if (!is_guest_view_hack)
+ EXPECT_EQ(nullptr, host->GetView());
+
+ if (widget_host_uses_shutdown_to_destroy_)
+ host->ShutdownAndDestroyWidget(true);
+ else
+ delete host;
}
void SetUpEnvironment() {
@@ -524,14 +603,8 @@ class RenderWidgetHostViewAuraTest : public testing::Test {
aura::client::ParentWindowWithContext(parent_view_->GetNativeView(),
aura_test_helper_->root_window(),
gfx::Rect());
-
- routing_id = process_host_->GetNextRoutingID();
- delegates_.push_back(base::WrapUnique(new MockRenderWidgetHostDelegate));
- widget_host_ = MockRenderWidgetHostImpl::Create(delegates_.back().get(),
- process_host_, routing_id);
- delegates_.back()->set_widget_host(widget_host_);
- widget_host_->Init();
- view_ = new FakeRenderWidgetHostViewAura(widget_host_, is_guest_view_hack_);
+ view_ = CreateView(is_guest_view_hack_);
+ widget_host_ = static_cast<MockRenderWidgetHostImpl*>(view_->host());
// Set the mouse_wheel_phase_handler_ timer timeout to 100ms.
view_->event_handler()->set_mouse_wheel_wheel_phase_handler_timeout(
base::TimeDelta::FromMilliseconds(100));
@@ -541,21 +614,8 @@ class RenderWidgetHostViewAuraTest : public testing::Test {
void TearDownEnvironment() {
sink_ = nullptr;
process_host_ = nullptr;
- if (view_) {
- // For guest-views, |view_| is not the view used by |widget_host_|.
- if (!is_guest_view_hack_) {
- EXPECT_EQ(view_, widget_host_->GetView());
- }
- view_->Destroy();
- if (!is_guest_view_hack_) {
- EXPECT_EQ(nullptr, widget_host_->GetView());
- }
- }
-
- if (widget_host_uses_shutdown_to_destroy_)
- widget_host_->ShutdownAndDestroyWidget(true);
- else
- delete widget_host_;
+ if (view_)
+ DestroyView(view_);
parent_view_->Destroy();
delete parent_host_;
@@ -567,7 +627,10 @@ class RenderWidgetHostViewAuraTest : public testing::Test {
ImageTransportFactory::Terminate();
}
- void SetUp() override { SetUpEnvironment(); }
+ void SetUp() override {
+ SetFeatureList();
+ SetUpEnvironment();
+ }
void TearDown() override { TearDownEnvironment(); }
@@ -619,6 +682,7 @@ class RenderWidgetHostViewAuraTest : public testing::Test {
void TimerBasedWheelEventPhaseInfo();
void TimerBasedLatchingBreaksWithMouseMove();
+ void TimerBasedLatchingBreaksWithModifiersChange();
void TimerBasedLatchingBreaksWithDirectionChange();
void TouchpadFlingStartResetsWheelPhaseState();
void GSBWithTouchSourceStopsWheelScrollSequence();
@@ -641,8 +705,7 @@ class RenderWidgetHostViewAuraTest : public testing::Test {
// First mock-focus the widget if not already.
if (render_widget_host_delegate()->GetFocusedRenderWidgetHost(
widget_host_) != view->GetRenderWidgetHost()) {
- render_widget_host_delegate()->set_focused_widget(
- view->GetRenderWidgetHostImpl());
+ render_widget_host_delegate()->set_focused_widget(view->host());
}
TextInputManager* manager =
@@ -715,7 +778,7 @@ class RenderWidgetHostViewAuraWheelScrollLatchingEnabledTest
SetFeatureList();
ui::GestureConfiguration::GetInstance()->set_scroll_debounce_interval_in_ms(
0);
- RenderWidgetHostViewAuraTest::SetUp();
+ RenderWidgetHostViewAuraTest::SetUpEnvironment();
}
};
@@ -728,7 +791,7 @@ class RenderWidgetHostViewAuraAsyncWheelEventsEnabledTest
SetFeatureList();
ui::GestureConfiguration::GetInstance()->set_scroll_debounce_interval_in_ms(
0);
- RenderWidgetHostViewAuraTest::SetUp();
+ RenderWidgetHostViewAuraTest::SetUpEnvironment();
}
};
@@ -836,10 +899,13 @@ class RenderWidgetHostViewAuraOverscrollTest
void SetUpOverscrollEnvironmentImpl(int debounce_interval_in_ms) {
SetFeatureList();
+ scoped_feature_list_.InitAndEnableFeature(
+ features::kTouchpadOverscrollHistoryNavigation);
+
ui::GestureConfiguration::GetInstance()->set_scroll_debounce_interval_in_ms(
debounce_interval_in_ms);
- RenderWidgetHostViewAuraTest::SetUp();
+ RenderWidgetHostViewAuraTest::SetUpEnvironment();
view_->SetOverscrollControllerEnabled(true);
gfx::Size display_size = display::Screen::GetScreen()
@@ -1173,6 +1239,8 @@ class RenderWidgetHostViewAuraOverscrollTest
bool wheel_scroll_latching_enabled_;
private:
+ base::test::ScopedFeatureList scoped_feature_list_;
+
DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostViewAuraOverscrollTest);
};
@@ -1466,13 +1534,14 @@ TEST_F(RenderWidgetHostViewAuraTest, SetCompositionText) {
composition_text.text = base::ASCIIToUTF16("|a|b");
// Focused segment
- composition_text.ime_text_spans.push_back(ui::ImeTextSpan(
- ui::ImeTextSpan::Type::kComposition, 0, 3, 0xff000000, true, 0x78563412));
+ composition_text.ime_text_spans.push_back(
+ ui::ImeTextSpan(ui::ImeTextSpan::Type::kComposition, 0, 3,
+ ui::ImeTextSpan::Thickness::kThick, 0x78563412));
// Non-focused segment, with different background color.
composition_text.ime_text_spans.push_back(
- ui::ImeTextSpan(ui::ImeTextSpan::Type::kComposition, 3, 4, 0xff000000,
- false, 0xefcdab90));
+ ui::ImeTextSpan(ui::ImeTextSpan::Type::kComposition, 3, 4,
+ ui::ImeTextSpan::Thickness::kThin, 0xefcdab90));
const ui::ImeTextSpans& ime_text_spans = composition_text.ime_text_spans;
@@ -1523,13 +1592,14 @@ TEST_F(RenderWidgetHostViewAuraTest, FinishCompositionByMouse) {
composition_text.text = base::ASCIIToUTF16("|a|b");
// Focused segment
- composition_text.ime_text_spans.push_back(ui::ImeTextSpan(
- ui::ImeTextSpan::Type::kComposition, 0, 3, 0xff000000, true, 0x78563412));
+ composition_text.ime_text_spans.push_back(
+ ui::ImeTextSpan(ui::ImeTextSpan::Type::kComposition, 0, 3,
+ ui::ImeTextSpan::Thickness::kThick, 0x78563412));
// Non-focused segment, with different background color.
composition_text.ime_text_spans.push_back(
- ui::ImeTextSpan(ui::ImeTextSpan::Type::kComposition, 3, 4, 0xff000000,
- false, 0xefcdab90));
+ ui::ImeTextSpan(ui::ImeTextSpan::Type::kComposition, 3, 4,
+ ui::ImeTextSpan::Thickness::kThin, 0xefcdab90));
// Caret is at the end. (This emulates Japanese MSIME 2007 and later)
composition_text.selection = gfx::Range(4);
@@ -1694,6 +1764,293 @@ TEST_F(RenderWidgetHostViewAuraTest, TouchEventState) {
EXPECT_EQ(0U, events.size());
}
+// The DOM KeyCode map for Fuchsia maps all DomCodes to 0. This means that
+// tests which expect different behaviors for different keys will not work.
+// Tracked via crbug.com/829551
+#if defined(OS_FUCHSIA)
+#define MAYBE_KeyEventRoutingWithKeyboardLockActiveForOneKey \
+ DISABLED_KeyEventRoutingWithKeyboardLockActiveForOneKey
+#else
+#define MAYBE_KeyEventRoutingWithKeyboardLockActiveForOneKey \
+ KeyEventRoutingWithKeyboardLockActiveForOneKey
+#endif
+TEST_F(RenderWidgetHostViewAuraTest,
+ MAYBE_KeyEventRoutingWithKeyboardLockActiveForOneKey) {
+ view_->InitAsChild(nullptr);
+ view_->Show();
+
+ auto test_hook = std::make_unique<TestScopedKeyboardHook>();
+ test_hook->LockSpecificKey(
+ ui::KeycodeConverter::DomCodeToNativeKeycode(ui::DomCode::US_A));
+ view_->event_handler()->scoped_keyboard_hook_ = std::move(test_hook);
+
+ // This locked key will skip the prehandler and be sent to the input handler.
+ ui::KeyEvent key_event1(ui::ET_KEY_PRESSED,
+ ui::DomCodeToUsLayoutKeyboardCode(ui::DomCode::US_A),
+ ui::DomCode::US_A, ui::EF_NONE);
+ view_->OnKeyEvent(&key_event1);
+ const NativeWebKeyboardEvent* event1 =
+ render_widget_host_delegate()->last_event();
+ ASSERT_FALSE(event1);
+ // Run the runloop to ensure input messages are dispatched. Otherwise the
+ // result of GetAndResetDispatchedMessages() will not be valid.
+ base::RunLoop().RunUntilIdle();
+ auto events = GetAndResetDispatchedMessages();
+ ASSERT_FALSE(events.empty());
+ const NativeWebKeyboardEvent* native_key_event1 =
+ static_cast<const NativeWebKeyboardEvent*>(
+ events[0]->ToEvent()->Event()->web_event.get());
+ ASSERT_TRUE(native_key_event1);
+ ASSERT_EQ(key_event1.key_code(), native_key_event1->windows_key_code);
+ ASSERT_EQ(ui::KeycodeConverter::DomCodeToNativeKeycode(key_event1.code()),
+ native_key_event1->native_key_code);
+
+ // These keys will pass through the prehandler since they aren't locked.
+ std::vector<ui::DomCode> dom_codes = {
+ ui::DomCode::US_B, ui::DomCode::US_Z, ui::DomCode::TAB,
+ ui::DomCode::ALT_LEFT, ui::DomCode::ENTER, ui::DomCode::ESCAPE};
+ for (ui::DomCode dom_code : dom_codes) {
+ ui::KeyEvent key_event(ui::ET_KEY_PRESSED,
+ ui::DomCodeToUsLayoutKeyboardCode(dom_code),
+ dom_code, ui::EF_NONE);
+ view_->OnKeyEvent(&key_event);
+ const NativeWebKeyboardEvent* event =
+ render_widget_host_delegate()->last_event();
+ ASSERT_TRUE(event) << "Failed for DomCode: "
+ << ui::KeycodeConverter::DomCodeToCodeString(dom_code);
+ ASSERT_EQ(key_event.key_code(), event->windows_key_code);
+ ASSERT_EQ(ui::KeycodeConverter::DomCodeToNativeKeycode(key_event.code()),
+ event->native_key_code);
+ }
+}
+
+// The DOM KeyCode map for Fuchsia maps all DomCodes to 0. This means that
+// tests which expect different behaviors for different keys will not work.
+// Tracked via crbug.com/829551
+#if defined(OS_FUCHSIA)
+#define MAYBE_KeyEventRoutingWithKeyboardLockActiveForEscKey \
+ DISABLED_KeyEventRoutingWithKeyboardLockActiveForEscKey
+#else
+#define MAYBE_KeyEventRoutingWithKeyboardLockActiveForEscKey \
+ KeyEventRoutingWithKeyboardLockActiveForEscKey
+#endif
+TEST_F(RenderWidgetHostViewAuraTest,
+ MAYBE_KeyEventRoutingWithKeyboardLockActiveForEscKey) {
+ view_->InitAsChild(nullptr);
+ view_->Show();
+
+ auto test_hook = std::make_unique<TestScopedKeyboardHook>();
+ test_hook->LockSpecificKey(
+ ui::KeycodeConverter::DomCodeToNativeKeycode(ui::DomCode::ESCAPE));
+ view_->event_handler()->scoped_keyboard_hook_ = std::move(test_hook);
+
+ // Although this key was locked, it will still pass through the prehandler as
+ // we do not want to prevent ESC from being used to exit fullscreen.
+ ui::KeyEvent key_event1(
+ ui::ET_KEY_PRESSED,
+ ui::DomCodeToUsLayoutKeyboardCode(ui::DomCode::ESCAPE),
+ ui::DomCode::ESCAPE, ui::EF_NONE);
+ view_->OnKeyEvent(&key_event1);
+ const NativeWebKeyboardEvent* event1 =
+ render_widget_host_delegate()->last_event();
+ ASSERT_TRUE(event1);
+ ASSERT_EQ(key_event1.key_code(), event1->windows_key_code);
+ ASSERT_EQ(ui::KeycodeConverter::DomCodeToNativeKeycode(key_event1.code()),
+ event1->native_key_code);
+
+ // This event will pass through the prehandler since it isn't locked.
+ ui::KeyEvent key_event2(ui::ET_KEY_PRESSED,
+ ui::DomCodeToUsLayoutKeyboardCode(ui::DomCode::US_B),
+ ui::DomCode::US_B, ui::EF_NONE);
+ view_->OnKeyEvent(&key_event2);
+ const NativeWebKeyboardEvent* event2 =
+ render_widget_host_delegate()->last_event();
+ ASSERT_TRUE(event2);
+ ASSERT_EQ(key_event2.key_code(), event2->windows_key_code);
+ ASSERT_EQ(ui::KeycodeConverter::DomCodeToNativeKeycode(key_event2.code()),
+ event2->native_key_code);
+}
+
+TEST_F(RenderWidgetHostViewAuraTest,
+ KeyEventRoutingWithKeyboardLockActiveForAllKeys) {
+ view_->InitAsChild(nullptr);
+ view_->Show();
+
+ auto test_hook = std::make_unique<TestScopedKeyboardHook>();
+ test_hook->LockAllKeys();
+ view_->event_handler()->scoped_keyboard_hook_ = std::move(test_hook);
+
+ // These keys will skip the prehandler and be sent to the input handler.
+ std::vector<ui::DomCode> dom_codes = {ui::DomCode::US_A, ui::DomCode::US_B,
+ ui::DomCode::TAB, ui::DomCode::ALT_LEFT,
+ ui::DomCode::ENTER};
+ for (ui::DomCode dom_code : dom_codes) {
+ ui::KeyEvent key_event(ui::ET_KEY_PRESSED,
+ ui::DomCodeToUsLayoutKeyboardCode(dom_code),
+ dom_code, ui::EF_NONE);
+ view_->OnKeyEvent(&key_event);
+ const NativeWebKeyboardEvent* event =
+ render_widget_host_delegate()->last_event();
+ ASSERT_FALSE(event) << "Failed for DomCode: "
+ << ui::KeycodeConverter::DomCodeToCodeString(dom_code);
+ // Run the runloop to ensure input messages are dispatched. Otherwise the
+ // result of GetAndResetDispatchedMessages() will not be valid.
+ base::RunLoop().RunUntilIdle();
+ auto events = GetAndResetDispatchedMessages();
+ ASSERT_FALSE(events.empty())
+ << "Failed for DomCode: "
+ << ui::KeycodeConverter::DomCodeToCodeString(dom_code);
+ const NativeWebKeyboardEvent* native_key_event =
+ static_cast<const NativeWebKeyboardEvent*>(
+ events[0]->ToEvent()->Event()->web_event.get());
+ ASSERT_TRUE(native_key_event)
+ << "Failed for DomCode: "
+ << ui::KeycodeConverter::DomCodeToCodeString(dom_code);
+ ASSERT_EQ(key_event.key_code(), native_key_event->windows_key_code);
+ ASSERT_EQ(ui::KeycodeConverter::DomCodeToNativeKeycode(key_event.code()),
+ native_key_event->native_key_code);
+ }
+
+ // Although this key was locked, it will still pass through the prehandler as
+ // we do not want to prevent ESC from being used to exit fullscreen.
+ ui::KeyEvent esc_key_event(
+ ui::ET_KEY_PRESSED,
+ ui::DomCodeToUsLayoutKeyboardCode(ui::DomCode::ESCAPE),
+ ui::DomCode::ESCAPE, ui::EF_NONE);
+ view_->OnKeyEvent(&esc_key_event);
+ const NativeWebKeyboardEvent* esc_event =
+ render_widget_host_delegate()->last_event();
+ ASSERT_TRUE(esc_event);
+ ASSERT_EQ(esc_key_event.key_code(), esc_event->windows_key_code);
+ ASSERT_EQ(ui::KeycodeConverter::DomCodeToNativeKeycode(esc_key_event.code()),
+ esc_event->native_key_code);
+}
+
+TEST_F(RenderWidgetHostViewAuraTest,
+ KeyEventRoutingKeyboardLockAndChildPopupWithInputGrab) {
+ parent_view_->SetBounds(gfx::Rect(10, 10, 400, 400));
+ parent_view_->Focus();
+ ASSERT_TRUE(parent_view_->HasFocus());
+
+ // kWebPopupTypePage means the child view (popup) will receive input.
+ view_->SetPopupType(blink::kWebPopupTypePage);
+ view_->InitAsPopup(parent_view_, gfx::Rect(10, 10, 100, 100));
+ ASSERT_NE(nullptr, view_->GetNativeView());
+ view_->Show();
+
+ MockRenderWidgetHostImpl* parent_host =
+ static_cast<MockRenderWidgetHostImpl*>(parent_host_);
+ // Run the runloop to ensure input messages are dispatched. Otherwise the
+ // result of GetAndResetDispatchedMessages() will not be valid.
+ base::RunLoop().RunUntilIdle();
+ // A MouseCapture lost message is posted when the child gains focus, clear
+ // that message out so we can reliably test the number of messages
+ // dispatched later on in the test.
+ parent_host->input_handler()->GetAndResetDispatchedMessages();
+
+ // The parent view owns the KeyboardLock for this test.
+ auto test_hook = std::make_unique<TestScopedKeyboardHook>();
+ test_hook->LockAllKeys();
+ parent_view_->event_handler()->scoped_keyboard_hook_ = std::move(test_hook);
+
+ // These keys will not be processed by the parent view but will be handled in
+ // the child (popup) view.
+ std::vector<ui::DomCode> dom_codes = {
+ ui::DomCode::US_A, ui::DomCode::ENTER, ui::DomCode::TAB,
+ ui::DomCode::ALT_LEFT, ui::DomCode::US_Z, ui::DomCode::ESCAPE};
+ for (ui::DomCode dom_code : dom_codes) {
+ ui::KeyEvent key_event(ui::ET_KEY_PRESSED,
+ ui::DomCodeToUsLayoutKeyboardCode(dom_code),
+ dom_code, ui::EF_NONE);
+ parent_view_->OnKeyEvent(&key_event);
+ const NativeWebKeyboardEvent* parent_event = delegates_[0]->last_event();
+ ASSERT_FALSE(parent_event)
+ << "Failed for DomCode: "
+ << ui::KeycodeConverter::DomCodeToCodeString(dom_code);
+
+ const NativeWebKeyboardEvent* child_event =
+ render_widget_host_delegate()->last_event();
+ ASSERT_TRUE(child_event)
+ << "Failed for DomCode: "
+ << ui::KeycodeConverter::DomCodeToCodeString(dom_code);
+ ASSERT_EQ(key_event.key_code(), child_event->windows_key_code);
+ ASSERT_EQ(ui::KeycodeConverter::DomCodeToNativeKeycode(key_event.code()),
+ child_event->native_key_code);
+ // Run the runloop to ensure input messages are dispatched. Otherwise the
+ // result of GetAndResetDispatchedMessages() will not be valid.
+ base::RunLoop().RunUntilIdle();
+ auto parent_events =
+ parent_host->input_handler()->GetAndResetDispatchedMessages();
+ ASSERT_TRUE(parent_events.empty())
+ << "Failed for DomCode: "
+ << ui::KeycodeConverter::DomCodeToCodeString(dom_code);
+ auto child_events = GetAndResetDispatchedMessages();
+ ASSERT_FALSE(child_events.empty())
+ << "Failed for DomCode: "
+ << ui::KeycodeConverter::DomCodeToCodeString(dom_code);
+ }
+}
+
+TEST_F(RenderWidgetHostViewAuraTest,
+ KeyEventRoutingKeyboardLockAndChildPopupWithoutInputGrab) {
+ parent_view_->SetBounds(gfx::Rect(10, 10, 400, 400));
+ parent_view_->Focus();
+ ASSERT_TRUE(parent_view_->HasFocus());
+
+ // kWebPopupTypeNone means the child view (popup) will not receive input.
+ view_->SetPopupType(blink::kWebPopupTypeNone);
+ view_->InitAsPopup(parent_view_, gfx::Rect(10, 10, 100, 100));
+ ASSERT_NE(nullptr, view_->GetNativeView());
+ view_->Show();
+
+ // The parent view owns the KeyboardLock for this test.
+ auto test_hook = std::make_unique<TestScopedKeyboardHook>();
+ test_hook->LockAllKeys();
+ parent_view_->event_handler()->scoped_keyboard_hook_ = std::move(test_hook);
+
+ // These keys will be handled by the parent view and will not be sent through
+ // the prehandler input pipeline.
+ std::vector<ui::DomCode> dom_codes = {ui::DomCode::US_A, ui::DomCode::ENTER,
+ ui::DomCode::TAB, ui::DomCode::ALT_LEFT,
+ ui::DomCode::US_Z};
+ MockRenderWidgetHostImpl* parent_host =
+ static_cast<MockRenderWidgetHostImpl*>(parent_host_);
+ for (ui::DomCode dom_code : dom_codes) {
+ ui::KeyEvent key_event(ui::ET_KEY_PRESSED,
+ ui::DomCodeToUsLayoutKeyboardCode(dom_code),
+ dom_code, ui::EF_NONE);
+ parent_view_->OnKeyEvent(&key_event);
+ const NativeWebKeyboardEvent* child_event =
+ render_widget_host_delegate()->last_event();
+ ASSERT_FALSE(child_event)
+ << "Failed for DomCode: "
+ << ui::KeycodeConverter::DomCodeToCodeString(dom_code);
+ // Run the runloop to ensure input messages are dispatched. Otherwise the
+ // result of GetAndResetDispatchedMessages() will not be valid.
+ base::RunLoop().RunUntilIdle();
+ auto child_events = GetAndResetDispatchedMessages();
+ ASSERT_TRUE(child_events.empty())
+ << "Failed for DomCode: "
+ << ui::KeycodeConverter::DomCodeToCodeString(dom_code);
+
+ const NativeWebKeyboardEvent* parent_event = delegates_[0]->last_event();
+ ASSERT_FALSE(parent_event)
+ << "Failed for DomCode: "
+ << ui::KeycodeConverter::DomCodeToCodeString(dom_code);
+ auto events = parent_host->input_handler()->GetAndResetDispatchedMessages();
+ ASSERT_FALSE(events.empty());
+ const NativeWebKeyboardEvent* native_key_event =
+ static_cast<const NativeWebKeyboardEvent*>(
+ events.back()->ToEvent()->Event()->web_event.get());
+ ASSERT_TRUE(native_key_event)
+ << "Failed for DomCode: "
+ << ui::KeycodeConverter::DomCodeToCodeString(dom_code);
+ ASSERT_EQ(key_event.key_code(), native_key_event->windows_key_code);
+ ASSERT_EQ(ui::KeycodeConverter::DomCodeToNativeKeycode(key_event.code()),
+ native_key_event->native_key_code);
+ }
+}
+
void RenderWidgetHostViewAuraTest::TimerBasedWheelEventPhaseInfo() {
// The test is valid only when wheel scroll latching is enabled.
if (wheel_scrolling_mode_ == kWheelScrollingModeNone)
@@ -1871,6 +2228,84 @@ TEST_F(RenderWidgetHostViewAuraAsyncWheelEventsEnabledTest,
TimerBasedLatchingBreaksWithMouseMove();
}
+// Tests that latching breaks when the current wheel event has different
+// modifiers.
+void RenderWidgetHostViewAuraTest::
+ TimerBasedLatchingBreaksWithModifiersChange() {
+ // The test is valid only when wheel scroll latching is enabled.
+ if (wheel_scrolling_mode_ == kWheelScrollingModeNone)
+ return;
+
+ // Set the mouse_wheel_phase_handler_ timer timeout to a large value to make
+ // sure that the timer is still running when the wheel event with different
+ // modifiers is sent.
+ view_->event_handler()->set_mouse_wheel_wheel_phase_handler_timeout(
+ TestTimeouts::action_max_timeout());
+
+ view_->InitAsChild(nullptr);
+ view_->Show();
+ sink_->ClearMessages();
+
+ ui::MouseWheelEvent event(gfx::Vector2d(0, 5), gfx::Point(2, 2),
+ gfx::Point(2, 2), ui::EventTimeForNow(), 0, 0);
+ view_->OnMouseEvent(&event);
+ base::RunLoop().RunUntilIdle();
+ MockWidgetInputHandler::MessageVector events =
+ GetAndResetDispatchedMessages();
+
+ EXPECT_TRUE(events[0]->ToEvent());
+ const WebMouseWheelEvent* wheel_event =
+ static_cast<const WebMouseWheelEvent*>(
+ events[0]->ToEvent()->Event()->web_event.get());
+ EXPECT_EQ(WebMouseWheelEvent::kPhaseBegan, wheel_event->phase);
+ events[0]->ToEvent()->CallCallback(INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
+ events = GetAndResetDispatchedMessages();
+
+ // Send the second wheel event with the same modifiers. The second wheel event
+ // will still be part of the current scrolling sequence.
+ ui::MouseWheelEvent event2(gfx::Vector2d(0, 5), gfx::Point(2, 2),
+ gfx::Point(2, 2), ui::EventTimeForNow(), 0, 0);
+ view_->OnMouseEvent(&event2);
+ base::RunLoop().RunUntilIdle();
+ events = GetAndResetDispatchedMessages();
+ if (wheel_scrolling_mode_ == kWheelScrollLatching)
+ EXPECT_EQ("MouseWheel", GetMessageNames(events));
+ else
+ EXPECT_EQ("MouseWheel GestureScrollUpdate", GetMessageNames(events));
+
+ wheel_event = static_cast<const WebMouseWheelEvent*>(
+ events[0]->ToEvent()->Event()->web_event.get());
+ EXPECT_EQ(WebMouseWheelEvent::kPhaseChanged, wheel_event->phase);
+ if (wheel_scrolling_mode_ == kWheelScrollLatching)
+ events[0]->ToEvent()->CallCallback(INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
+ events = GetAndResetDispatchedMessages();
+
+ // Send the third wheel event with a ctrl key down. The third wheel event will
+ // break the latching since the event modifiers have changed.
+ ui::MouseWheelEvent event3(gfx::Vector2d(0, 5), gfx::Point(2, 2),
+ gfx::Point(2, 2), ui::EventTimeForNow(),
+ ui::EF_CONTROL_DOWN, 0);
+ view_->OnMouseEvent(&event3);
+ base::RunLoop().RunUntilIdle();
+ events = GetAndResetDispatchedMessages();
+ EXPECT_EQ("MouseWheel GestureScrollEnd MouseWheel", GetMessageNames(events));
+ wheel_event = static_cast<const WebMouseWheelEvent*>(
+ events[0]->ToEvent()->Event()->web_event.get());
+ EXPECT_EQ(WebMouseWheelEvent::kPhaseEnded, wheel_event->phase);
+
+ wheel_event = static_cast<const WebMouseWheelEvent*>(
+ events[2]->ToEvent()->Event()->web_event.get());
+ EXPECT_EQ(WebMouseWheelEvent::kPhaseBegan, wheel_event->phase);
+}
+TEST_F(RenderWidgetHostViewAuraWheelScrollLatchingEnabledTest,
+ TimerBasedLatchingBreaksWithModifiersChange) {
+ TimerBasedLatchingBreaksWithModifiersChange();
+}
+TEST_F(RenderWidgetHostViewAuraAsyncWheelEventsEnabledTest,
+ TimerBasedLatchingBreaksWithModifiersChange) {
+ TimerBasedLatchingBreaksWithModifiersChange();
+}
+
// Tests that latching breaks when the new wheel event goes a different
// direction from previous wheel events and the previous GSU events are not
// consumed.
@@ -2114,12 +2549,12 @@ void RenderWidgetHostViewAuraTest::
gesture_event = static_cast<const WebGestureEvent*>(
events[1]->ToEvent()->Event()->web_event.get());
EXPECT_EQ(WebInputEvent::kGestureScrollEnd, gesture_event->GetType());
- EXPECT_EQ(blink::kWebGestureDeviceTouchpad, gesture_event->source_device);
+ EXPECT_EQ(blink::kWebGestureDeviceTouchpad, gesture_event->SourceDevice());
gesture_event = static_cast<const WebGestureEvent*>(
events[2]->ToEvent()->Event()->web_event.get());
EXPECT_EQ(WebInputEvent::kGestureScrollBegin, gesture_event->GetType());
- EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, gesture_event->source_device);
+ EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, gesture_event->SourceDevice());
}
TEST_F(RenderWidgetHostViewAuraWheelScrollLatchingEnabledTest,
@@ -2326,18 +2761,18 @@ TEST_F(RenderWidgetHostViewAuraTest, CompositorViewportPixelSizeWithScale) {
}
// This test verifies that in AutoResize mode a new
-// ViewMsg_SetLocalSurfaceIdForAutoResize message is sent when ScreenInfo
+// ViewMsg_Resize message is sent when ScreenInfo
// changes and that message contains the latest ScreenInfo.
TEST_F(RenderWidgetHostViewAuraTest, AutoResizeWithScale) {
view_->InitAsChild(nullptr);
aura::client::ParentWindowWithContext(
view_->GetNativeView(), parent_view_->GetNativeView()->GetRootWindow(),
gfx::Rect());
- sink_->ClearMessages();
viz::LocalSurfaceId local_surface_id1(view_->GetLocalSurfaceId());
EXPECT_TRUE(local_surface_id1.is_valid());
- widget_host_->SetAutoResize(true, gfx::Size(50, 50), gfx::Size(100, 100));
+ view_->EnableAutoResize(gfx::Size(50, 50), gfx::Size(100, 100));
+ sink_->ClearMessages();
ViewHostMsg_ResizeOrRepaint_ACK_Params params;
params.view_size = gfx::Size(75, 75);
params.sequence_number = 1;
@@ -2354,16 +2789,19 @@ TEST_F(RenderWidgetHostViewAuraTest, AutoResizeWithScale) {
ASSERT_EQ(1u, sink_->message_count());
{
const IPC::Message* msg = sink_->GetMessageAt(0);
- EXPECT_EQ(static_cast<uint32_t>(ViewMsg_SetLocalSurfaceIdForAutoResize::ID),
- msg->type());
- ViewMsg_SetLocalSurfaceIdForAutoResize::Param params;
- ViewMsg_SetLocalSurfaceIdForAutoResize::Read(msg, &params);
- EXPECT_EQ(1u, std::get<0>(params)); // sequence_number
- EXPECT_EQ("50x50", std::get<1>(params).ToString());
- EXPECT_EQ("100x100", std::get<2>(params).ToString());
- EXPECT_EQ(1, std::get<3>(params).device_scale_factor);
- local_surface_id2 = std::get<5>(params);
+ EXPECT_EQ(static_cast<uint32_t>(ViewMsg_Resize::ID), msg->type());
+ ViewMsg_Resize::Param params;
+ ViewMsg_Resize::Read(msg, &params);
+ ResizeParams resize_params = std::get<0>(params);
+ EXPECT_EQ(1u,
+ resize_params.auto_resize_sequence_number); // sequence_number
+ EXPECT_EQ("50x50", resize_params.min_size_for_auto_resize.ToString());
+ EXPECT_EQ("100x100", resize_params.max_size_for_auto_resize.ToString());
+ EXPECT_EQ(1, resize_params.screen_info.device_scale_factor);
+ local_surface_id2 =
+ resize_params.local_surface_id.value_or(viz::LocalSurfaceId());
EXPECT_NE(local_surface_id1, local_surface_id2);
+ EXPECT_TRUE(local_surface_id2.is_valid());
}
sink_->ClearMessages();
@@ -2372,33 +2810,36 @@ TEST_F(RenderWidgetHostViewAuraTest, AutoResizeWithScale) {
{
// TODO(samans): There should be only one message in the sink, but some
// testers are seeing two (crrev.com/c/839580). Investigate why.
- const IPC::Message* msg = sink_->GetFirstMessageMatching(
- ViewMsg_SetLocalSurfaceIdForAutoResize::ID);
+ const IPC::Message* msg =
+ sink_->GetFirstMessageMatching(ViewMsg_Resize::ID);
ASSERT_TRUE(msg);
- ViewMsg_SetLocalSurfaceIdForAutoResize::Param params;
- ViewMsg_SetLocalSurfaceIdForAutoResize::Read(msg, &params);
- EXPECT_EQ(1u, std::get<0>(params)); // sequence_number
- EXPECT_EQ("50x50", std::get<1>(params).ToString());
- EXPECT_EQ("100x100", std::get<2>(params).ToString());
- EXPECT_EQ(2, std::get<3>(params).device_scale_factor);
- EXPECT_NE(local_surface_id1, std::get<5>(params));
- EXPECT_NE(local_surface_id2, std::get<5>(params));
+ ViewMsg_Resize::Param params;
+ ViewMsg_Resize::Read(msg, &params);
+ ResizeParams resize_params = std::get<0>(params);
+ EXPECT_EQ(1u,
+ resize_params.auto_resize_sequence_number); // sequence_number
+ EXPECT_EQ("50x50", resize_params.min_size_for_auto_resize.ToString());
+ EXPECT_EQ("100x100", resize_params.max_size_for_auto_resize.ToString());
+ EXPECT_EQ(2, resize_params.screen_info.device_scale_factor);
+ EXPECT_NE(local_surface_id1,
+ resize_params.local_surface_id.value_or(viz::LocalSurfaceId()));
+ EXPECT_NE(local_surface_id2,
+ resize_params.local_surface_id.value_or(viz::LocalSurfaceId()));
}
}
// This test verifies that in AutoResize mode a new
-// ViewMsg_SetLocalSurfaceIdForAutoResize message is sent when size
-// changes.
+// ViewMsg_Resize message is sent when size changes.
TEST_F(RenderWidgetHostViewAuraTest, AutoResizeWithBrowserInitiatedResize) {
view_->InitAsChild(nullptr);
aura::client::ParentWindowWithContext(
view_->GetNativeView(), parent_view_->GetNativeView()->GetRootWindow(),
gfx::Rect());
- sink_->ClearMessages();
viz::LocalSurfaceId local_surface_id1(view_->GetLocalSurfaceId());
EXPECT_TRUE(local_surface_id1.is_valid());
- widget_host_->SetAutoResize(true, gfx::Size(50, 50), gfx::Size(100, 100));
+ view_->EnableAutoResize(gfx::Size(50, 50), gfx::Size(100, 100));
+ sink_->ClearMessages();
ViewHostMsg_ResizeOrRepaint_ACK_Params params;
params.view_size = gfx::Size(75, 75);
params.sequence_number = 1;
@@ -2415,15 +2856,17 @@ TEST_F(RenderWidgetHostViewAuraTest, AutoResizeWithBrowserInitiatedResize) {
ASSERT_EQ(1u, sink_->message_count());
{
const IPC::Message* msg = sink_->GetMessageAt(0);
- EXPECT_EQ(static_cast<uint32_t>(ViewMsg_SetLocalSurfaceIdForAutoResize::ID),
- msg->type());
- ViewMsg_SetLocalSurfaceIdForAutoResize::Param params;
- ViewMsg_SetLocalSurfaceIdForAutoResize::Read(msg, &params);
- EXPECT_EQ(1u, std::get<0>(params)); // sequence_number
- EXPECT_EQ("50x50", std::get<1>(params).ToString());
- EXPECT_EQ("100x100", std::get<2>(params).ToString());
- EXPECT_EQ(1, std::get<3>(params).device_scale_factor);
- local_surface_id2 = std::get<5>(params);
+ EXPECT_EQ(static_cast<uint32_t>(ViewMsg_Resize::ID), msg->type());
+ ViewMsg_Resize::Param params;
+ ViewMsg_Resize::Read(msg, &params);
+ ResizeParams resize_params = std::get<0>(params);
+ EXPECT_EQ(1u, resize_params.auto_resize_sequence_number);
+ EXPECT_EQ("50x50", resize_params.min_size_for_auto_resize.ToString());
+ EXPECT_EQ("100x100", resize_params.max_size_for_auto_resize.ToString());
+ EXPECT_EQ(1, resize_params.screen_info.device_scale_factor);
+ local_surface_id2 =
+ resize_params.local_surface_id.value_or(viz::LocalSurfaceId());
+ EXPECT_TRUE(local_surface_id2.is_valid());
EXPECT_NE(local_surface_id1, local_surface_id2);
}
@@ -2431,19 +2874,20 @@ TEST_F(RenderWidgetHostViewAuraTest, AutoResizeWithBrowserInitiatedResize) {
view_->SetSize(gfx::Size(120, 120));
viz::LocalSurfaceId local_surface_id3;
- // Find out what the second IPC is.
- ASSERT_EQ(2u, sink_->message_count());
+ ASSERT_EQ(1u, sink_->message_count());
{
const IPC::Message* msg = sink_->GetMessageAt(0);
- EXPECT_EQ(static_cast<uint32_t>(ViewMsg_SetLocalSurfaceIdForAutoResize::ID),
- msg->type());
- ViewMsg_SetLocalSurfaceIdForAutoResize::Param params;
- ViewMsg_SetLocalSurfaceIdForAutoResize::Read(msg, &params);
- EXPECT_EQ(1u, std::get<0>(params)); // sequence_number
- EXPECT_EQ("50x50", std::get<1>(params).ToString());
- EXPECT_EQ("100x100", std::get<2>(params).ToString());
- EXPECT_EQ(1, std::get<3>(params).device_scale_factor);
- local_surface_id3 = std::get<5>(params);
+ EXPECT_EQ(static_cast<uint32_t>(ViewMsg_Resize::ID), msg->type());
+ ViewMsg_Resize::Param params;
+ ViewMsg_Resize::Read(msg, &params);
+ ResizeParams resize_params = std::get<0>(params);
+ EXPECT_EQ(1u, resize_params.auto_resize_sequence_number);
+ EXPECT_EQ("50x50", resize_params.min_size_for_auto_resize.ToString());
+ EXPECT_EQ("100x100", resize_params.max_size_for_auto_resize.ToString());
+ EXPECT_EQ(1, resize_params.screen_info.device_scale_factor);
+ local_surface_id3 =
+ resize_params.local_surface_id.value_or(viz::LocalSurfaceId());
+ EXPECT_TRUE(local_surface_id3.is_valid());
EXPECT_NE(local_surface_id1, local_surface_id3);
EXPECT_NE(local_surface_id2, local_surface_id3);
}
@@ -2769,6 +3213,11 @@ TEST_F(RenderWidgetHostViewAuraTest, DelegatedFrameGutter) {
viz::CompositorFrame frame =
MakeDelegatedFrame(1.f, small_size, gfx::Rect(small_size));
frame.metadata.root_background_color = SK_ColorRED;
+
+ cc::RenderFrameMetadata metadata;
+ metadata.root_background_color = SK_ColorRED;
+ view_->SetRenderFrameMetadata(metadata);
+ view_->OnRenderFrameMetadataChanged();
view_->SubmitCompositorFrame(small_id, std::move(frame), nullptr);
ui::Layer* parent_layer = view_->GetNativeView()->layer();
@@ -2802,6 +3251,35 @@ TEST_F(RenderWidgetHostViewAuraTest, DelegatedFrameGutter) {
ASSERT_EQ(0u, parent_layer->children().size());
}
+TEST_F(RenderWidgetHostViewAuraTest, ZeroSizeStillGetsLocalSurfaceId) {
+ gfx::Size frame_size;
+ viz::LocalSurfaceId local_surface_id =
+ parent_local_surface_id_allocator_.GenerateId();
+
+ // Prevent the DelegatedFrameHost from skipping frames.
+ view_->DisableResizeLock();
+
+ view_->InitAsChild(nullptr);
+ aura::client::ParentWindowWithContext(
+ view_->GetNativeView(), parent_view_->GetNativeView()->GetRootWindow(),
+ gfx::Rect());
+ view_->SetSize(frame_size);
+ view_->Show();
+
+ ui::Layer* parent_layer = view_->GetNativeView()->layer();
+ EXPECT_EQ(gfx::Rect(), parent_layer->bounds());
+ EXPECT_EQ(2u, sink_->message_count());
+ {
+ const IPC::Message* msg = sink_->GetMessageAt(1);
+ EXPECT_EQ(static_cast<uint32_t>(ViewMsg_Resize::ID), msg->type());
+ ViewMsg_Resize::Param params;
+ ViewMsg_Resize::Read(msg, &params);
+ EXPECT_EQ(frame_size.ToString(), std::get<0>(params).new_size.ToString());
+ ASSERT_TRUE(std::get<0>(params).local_surface_id.has_value());
+ EXPECT_TRUE(std::get<0>(params).local_surface_id->is_valid());
+ }
+}
+
TEST_F(RenderWidgetHostViewAuraTest, BackgroundColorMatchesCompositorFrame) {
// TODO: fix for mash.
if (base::FeatureList::IsEnabled(features::kMash))
@@ -2820,11 +3298,10 @@ TEST_F(RenderWidgetHostViewAuraTest, BackgroundColorMatchesCompositorFrame) {
gfx::Rect());
view_->SetSize(frame_size);
view_->Show();
- viz::CompositorFrame frame =
- MakeDelegatedFrame(1.f, frame_size, gfx::Rect(frame_size));
- frame.metadata.root_background_color = SK_ColorRED;
- view_->SubmitCompositorFrame(local_surface_id, std::move(frame), nullptr);
-
+ cc::RenderFrameMetadata metadata;
+ metadata.root_background_color = SK_ColorRED;
+ view_->SetRenderFrameMetadata(metadata);
+ view_->OnRenderFrameMetadataChanged();
ui::Layer* parent_layer = view_->GetNativeView()->layer();
EXPECT_EQ(gfx::Rect(0, 0, 100, 100), parent_layer->bounds());
@@ -4558,8 +5035,8 @@ TEST_F(RenderWidgetHostViewAuraOverscrollTest,
{
// Start over, except instead of ending the gesture with ScrollEnd, end it
// with a FlingStart, with velocity in the reverse direction. This should
- // initiate an overscroll, but it should be cancelled because of the fling
- // in the opposite direction.
+ // initiate an overscroll, the overscroll mode should get reset after the
+ // first GSU event generated by the fling controller.
overscroll_delegate()->Reset();
SimulateGestureEvent(WebInputEvent::kGestureScrollBegin,
blink::kWebGestureDeviceTouchscreen);
@@ -4576,8 +5053,17 @@ TEST_F(RenderWidgetHostViewAuraOverscrollTest,
SimulateGestureFlingStartEvent(100, 0, blink::kWebGestureDeviceTouchscreen);
events = GetAndResetDispatchedMessages();
- EXPECT_EQ("GestureFlingStart", GetMessageNames(events));
- EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->completed_mode());
+ // The fling start event is not sent to the renderer.
+ EXPECT_EQ(0U, events.size());
+ EXPECT_EQ(OVERSCROLL_WEST, overscroll_mode());
+ EXPECT_EQ(OverscrollSource::TOUCHSCREEN, overscroll_source());
+ EXPECT_EQ(OVERSCROLL_WEST, overscroll_delegate()->current_mode());
+
+ // The overscrolling mode will reset after the first GSU from fling
+ // progress.
+ base::TimeTicks progress_time =
+ base::TimeTicks::Now() + base::TimeDelta::FromMilliseconds(17);
+ widget_host_->ProgressFling(progress_time);
EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
}
}
@@ -5969,12 +6455,16 @@ TEST_F(RenderWidgetHostViewAuraTest, HitTestRegionListSubmitted) {
MakeDelegatedFrame(1.f, frame_size, view_rect),
std::move(hit_test_region_list));
- const viz::mojom::HitTestRegionList* active_hit_test_region_list =
+ viz::TestLatestLocalSurfaceIdLookupDelegate delegate;
+ delegate.SetSurfaceIdMap(
+ viz::SurfaceId(view_->GetFrameSinkId(), kArbitraryLocalSurfaceId));
+ viz::FrameSinkManagerImpl* frame_sink_manager =
view_->GetDelegatedFrameHost()
->GetCompositorFrameSinkSupportForTesting()
- ->frame_sink_manager()
- ->hit_test_manager()
- ->GetActiveHitTestRegionList(surface_id);
+ ->frame_sink_manager();
+ const viz::mojom::HitTestRegionList* active_hit_test_region_list =
+ frame_sink_manager->hit_test_manager()->GetActiveHitTestRegionList(
+ &delegate, surface_id.frame_sink_id());
EXPECT_EQ(active_hit_test_region_list->flags, viz::mojom::kHitTestMine);
EXPECT_EQ(active_hit_test_region_list->bounds, view_rect);
}
@@ -5987,16 +6477,31 @@ TEST_F(RenderWidgetHostViewAuraSurfaceSynchronizationTest,
if (base::FeatureList::IsEnabled(features::kMash))
return;
+ constexpr base::TimeDelta kTimeout = base::TimeDelta::FromMicroseconds(10);
+
view_->InitAsChild(nullptr);
aura::client::ParentWindowWithContext(
view_->GetNativeView(), parent_view_->GetNativeView()->GetRootWindow(),
gfx::Rect());
- viz::LocalSurfaceId id1 = view_->GetLocalSurfaceId();
- EXPECT_TRUE(id1.is_valid());
+ widget_host_->set_new_content_rendering_delay_for_testing(kTimeout);
+
+ viz::LocalSurfaceId id0 = view_->GetLocalSurfaceId();
+ EXPECT_TRUE(id0.is_valid());
- widget_host_->set_new_content_rendering_delay_for_testing(
- base::TimeDelta::FromMicroseconds(10));
+ // No new LocalSurfaceId should be allocated for the first navigation but the
+ // timer should fire.
+ widget_host_->DidNavigate(1);
+ viz::LocalSurfaceId id1 = view_->GetLocalSurfaceId();
+ EXPECT_EQ(id0, id1);
+ {
+ base::RunLoop run_loop;
+ base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
+ FROM_HERE, run_loop.QuitClosure(), 2 * kTimeout);
+ run_loop.Run();
+ }
+ EXPECT_TRUE(widget_host_->new_content_rendering_timeout_fired());
+ widget_host_->reset_new_content_rendering_timeout_fired();
// Start the timer. Verify that a new LocalSurfaceId is allocated.
widget_host_->DidNavigate(5);
@@ -6012,8 +6517,7 @@ TEST_F(RenderWidgetHostViewAuraSurfaceSynchronizationTest,
{
base::RunLoop run_loop;
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
- FROM_HERE, run_loop.QuitClosure(),
- base::TimeDelta::FromMicroseconds(20));
+ FROM_HERE, run_loop.QuitClosure(), 2 * kTimeout);
run_loop.Run();
}
EXPECT_TRUE(widget_host_->new_content_rendering_timeout_fired());
@@ -6030,8 +6534,7 @@ TEST_F(RenderWidgetHostViewAuraSurfaceSynchronizationTest,
{
base::RunLoop run_loop;
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
- FROM_HERE, run_loop.QuitClosure(),
- base::TimeDelta::FromMicroseconds(20));
+ FROM_HERE, run_loop.QuitClosure(), 2 * kTimeout);
run_loop.Run();
}
EXPECT_FALSE(widget_host_->new_content_rendering_timeout_fired());
@@ -6096,6 +6599,39 @@ TEST_F(RenderWidgetHostViewAuraSurfaceSynchronizationTest,
EXPECT_TRUE(view_->window_->layer()->GetFallbackSurfaceId()->is_valid());
}
+// Check that TakeFallbackContentFrom() copies the fallback SurfaceId and
+// background color from the previous view to the new view.
+TEST_F(RenderWidgetHostViewAuraSurfaceSynchronizationTest,
+ TakeFallbackContent) {
+ // Initialize the first view.
+ view_->InitAsChild(nullptr);
+ aura::client::ParentWindowWithContext(
+ view_->GetNativeView(), parent_view_->GetNativeView()->GetRootWindow(),
+ gfx::Rect());
+ view_->Show();
+
+ // Create and initialize the second view.
+ FakeRenderWidgetHostViewAura* view2 = CreateView(false);
+ view2->InitAsChild(nullptr);
+ aura::client::ParentWindowWithContext(
+ view2->GetNativeView(), parent_view_->GetNativeView()->GetRootWindow(),
+ gfx::Rect());
+
+ // Set fallback for the first view.
+ viz::LocalSurfaceId id = view_->GetLocalSurfaceId();
+ view_->delegated_frame_host_->OnFirstSurfaceActivation(viz::SurfaceInfo(
+ viz::SurfaceId(view_->GetFrameSinkId(), id), 1, gfx::Size(20, 20)));
+ EXPECT_TRUE(view_->window_->layer()->GetFallbackSurfaceId()->is_valid());
+
+ // Call TakeFallbackContentFrom(). The second view should now have the same
+ // fallback as the first view.
+ view2->TakeFallbackContentFrom(view_);
+ EXPECT_EQ(*view_->window_->layer()->GetFallbackSurfaceId(),
+ *view2->window_->layer()->GetFallbackSurfaceId());
+
+ DestroyView(view2);
+}
+
// This class provides functionality to test a RenderWidgetHostViewAura
// instance which has been hooked up to a test RenderViewHost instance and
// a WebContents instance.
@@ -6218,31 +6754,12 @@ TEST_F(RenderWidgetHostViewAuraWithViewHarnessTest,
// A context menu request with the MENU_SOURCE_LONG_PRESS source type should
// result in the MockWebContentsViewDelegate::ShowContextMenu method
// getting called on non Windows platforms. This means that the request
- // worked correctly. On Windows this should be blocked.
+ // worked correctly.
delegate->ClearState();
context_menu_params.source_type = ui::MENU_SOURCE_LONG_PRESS;
contents()->ShowContextMenu(contents()->GetRenderViewHost()->GetMainFrame(),
context_menu_params);
-#if defined(OS_WIN)
- EXPECT_FALSE(delegate->context_menu_request_received());
-#else
EXPECT_TRUE(delegate->context_menu_request_received());
-#endif
-
-#if defined(OS_WIN)
- // On Windows the context menu request blocked above should be received when
- // the ET_GESTURE_LONG_TAP gesture is sent to the RenderWidgetHostViewAura
- // instance. This means that the touch was released.
- delegate->ClearState();
-
- ui::GestureEventDetails event_details(ui::ET_GESTURE_LONG_TAP);
- ui::GestureEvent gesture_event(
- 100, 100, 0, ui::EventTimeForNow(), event_details);
- view()->OnGestureEvent(&gesture_event);
-
- EXPECT_TRUE(delegate->context_menu_request_received());
- EXPECT_EQ(delegate->context_menu_source_type(), ui::MENU_SOURCE_TOUCH);
-#endif
RenderViewHostFactory::set_is_real_render_view_host(false);
}
diff --git a/chromium/content/browser/renderer_host/render_widget_host_view_base.cc b/chromium/content/browser/renderer_host/render_widget_host_view_base.cc
index 09a37c1a2c7..7655a0fe3f5 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_view_base.cc
+++ b/chromium/content/browser/renderer_host/render_widget_host_view_base.cc
@@ -8,6 +8,7 @@
#include "base/logging.h"
#include "base/unguessable_token.h"
#include "build/build_config.h"
+#include "components/viz/host/host_frame_sink_manager.h"
#include "components/viz/service/frame_sinks/frame_sink_manager_impl.h"
#include "components/viz/service/surfaces/surface_hittest.h"
#include "content/browser/accessibility/browser_accessibility_manager.h"
@@ -38,20 +39,24 @@
namespace content {
-RenderWidgetHostViewBase::RenderWidgetHostViewBase()
- : is_fullscreen_(false),
+RenderWidgetHostViewBase::RenderWidgetHostViewBase(RenderWidgetHost* host)
+ : host_(RenderWidgetHostImpl::From(host)),
+ is_fullscreen_(false),
popup_type_(blink::kWebPopupTypeNone),
- mouse_locked_(false),
current_device_scale_factor_(0),
current_display_rotation_(display::Display::ROTATE_0),
text_input_manager_(nullptr),
wheel_scroll_latching_enabled_(base::FeatureList::IsEnabled(
features::kTouchpadAndWheelScrollLatching)),
web_contents_accessibility_(nullptr),
+ is_currently_scrolling_viewport_(false),
renderer_frame_number_(0),
- weak_factory_(this) {}
+ weak_factory_(this) {
+ host_->render_frame_metadata_provider()->AddObserver(this);
+}
RenderWidgetHostViewBase::~RenderWidgetHostViewBase() {
+ DCHECK(!keyboard_locked_);
DCHECK(!mouse_locked_);
// We call this here to guarantee that observers are notified before we go
// away. However, some subclasses may wish to call this earlier in their
@@ -65,17 +70,18 @@ RenderWidgetHostViewBase::~RenderWidgetHostViewBase() {
// so that the |text_input_manager_| will free its state.
if (text_input_manager_)
text_input_manager_->Unregister(this);
+ if (host_)
+ host_->render_frame_metadata_provider()->RemoveObserver(this);
}
RenderWidgetHostImpl* RenderWidgetHostViewBase::GetFocusedWidget() const {
- RenderWidgetHostImpl* host = GetRenderWidgetHostImpl();
- return host && host->delegate()
- ? host->delegate()->GetFocusedRenderWidgetHost(host)
+ return host() && host()->delegate()
+ ? host()->delegate()->GetFocusedRenderWidgetHost(host())
: nullptr;
}
RenderWidgetHost* RenderWidgetHostViewBase::GetRenderWidgetHost() const {
- return GetRenderWidgetHostImpl();
+ return host();
}
void RenderWidgetHostViewBase::NotifyObserversAboutShutdown() {
@@ -91,6 +97,14 @@ bool RenderWidgetHostViewBase::OnMessageReceived(const IPC::Message& msg){
return false;
}
+void RenderWidgetHostViewBase::OnRenderFrameMetadataChanged() {
+ is_scroll_offset_at_top_ = host_->render_frame_metadata_provider()
+ ->LastRenderFrameMetadata()
+ .is_scroll_offset_at_top;
+}
+
+void RenderWidgetHostViewBase::OnRenderFrameSubmission() {}
+
void RenderWidgetHostViewBase::SetBackgroundColorToDefault() {
SetBackgroundColor(SK_ColorWHITE);
}
@@ -169,6 +183,15 @@ void RenderWidgetHostViewBase::CopyFromSurface(
std::move(callback).Run(SkBitmap());
}
+viz::mojom::FrameSinkVideoCapturerPtr
+RenderWidgetHostViewBase::CreateVideoCapturer() {
+ viz::mojom::FrameSinkVideoCapturerPtr video_capturer;
+ GetHostFrameSinkManager()->CreateVideoCapturer(
+ mojo::MakeRequest(&video_capturer));
+ video_capturer->ChangeTarget(GetFrameSinkId());
+ return video_capturer;
+}
+
base::string16 RenderWidgetHostViewBase::GetSelectedText() {
if (!GetTextInputManager())
return base::string16();
@@ -179,6 +202,20 @@ bool RenderWidgetHostViewBase::IsMouseLocked() {
return mouse_locked_;
}
+bool RenderWidgetHostViewBase::LockKeyboard(
+ base::Optional<base::flat_set<int>> keys) {
+ NOTIMPLEMENTED();
+ return false;
+}
+
+void RenderWidgetHostViewBase::UnlockKeyboard() {
+ NOTIMPLEMENTED();
+}
+
+bool RenderWidgetHostViewBase::IsKeyboardLocked() {
+ return keyboard_locked_;
+}
+
InputEventAckState RenderWidgetHostViewBase::FilterInputEvent(
const blink::WebInputEvent& input_event) {
// By default, input events are simply forwarded to the renderer.
@@ -217,9 +254,8 @@ RenderWidgetHostViewBase::CreateBrowserAccessibilityManager(
}
void RenderWidgetHostViewBase::AccessibilityShowMenu(const gfx::Point& point) {
- RenderWidgetHostImpl* impl = GetRenderWidgetHostImpl();
- if (impl)
- impl->ShowContextMenuAtPoint(point, ui::MENU_SOURCE_NONE);
+ if (host())
+ host()->ShowContextMenuAtPoint(point, ui::MENU_SOURCE_NONE);
}
gfx::Point RenderWidgetHostViewBase::AccessibilityOriginInScreen(
@@ -237,21 +273,13 @@ gfx::NativeViewAccessible
return nullptr;
}
-void RenderWidgetHostViewBase::CreateCompositorFrameSink(
- CreateCompositorFrameSinkCallback callback) {
- DCHECK(GetFrameSinkId().is_valid());
- std::move(callback).Run(GetFrameSinkId());
-}
-
void RenderWidgetHostViewBase::UpdateScreenInfo(gfx::NativeView view) {
- RenderWidgetHostImpl* impl = GetRenderWidgetHostImpl();
+ if (host() && host()->delegate())
+ host()->delegate()->SendScreenRects();
- if (impl && impl->delegate())
- impl->delegate()->SendScreenRects();
-
- if (HasDisplayPropertyChanged(view) && impl) {
+ if (HasDisplayPropertyChanged(view) && host()) {
OnSynchronizedDisplayPropertiesChanged();
- impl->NotifyScreenInfoChanged();
+ host()->NotifyScreenInfoChanged();
}
}
@@ -279,10 +307,42 @@ void RenderWidgetHostViewBase::DidUnregisterFromTextInputManager(
text_input_manager_ = nullptr;
}
-void RenderWidgetHostViewBase::ResizeDueToAutoResize(const gfx::Size& new_size,
- uint64_t sequence_number) {
- RenderWidgetHostImpl* host = GetRenderWidgetHostImpl();
- host->DidAllocateLocalSurfaceIdForAutoResize(sequence_number);
+void RenderWidgetHostViewBase::EnableAutoResize(const gfx::Size& min_size,
+ const gfx::Size& max_size) {
+ host()->SetAutoResize(true, min_size, max_size);
+ host()->WasResized();
+}
+
+void RenderWidgetHostViewBase::DisableAutoResize(const gfx::Size& new_size) {
+ if (!new_size.IsEmpty())
+ SetSize(new_size);
+ // This clears the cached value in the WebContents, so that OOPIFs will
+ // stop using it.
+ if (host()->delegate())
+ host()->delegate()->ResetAutoResizeSize();
+ host()->SetAutoResize(false, gfx::Size(), gfx::Size());
+ host()->WasResized();
+}
+
+bool RenderWidgetHostViewBase::IsScrollOffsetAtTop() const {
+ return is_scroll_offset_at_top_;
+}
+
+viz::ScopedSurfaceIdAllocator RenderWidgetHostViewBase::ResizeDueToAutoResize(
+ const gfx::Size& new_size,
+ uint64_t sequence_number) {
+ // TODO(cblume): This doesn't currently suppress allocation.
+ // It maintains existing behavior while using the suppression style.
+ // This will be addressed in a follow-up patch.
+ // See https://crbug.com/805073
+ base::OnceCallback<void()> allocation_task =
+ base::BindOnce(&RenderWidgetHostViewBase::OnResizeDueToAutoResizeComplete,
+ weak_factory_.GetWeakPtr(), sequence_number);
+ return viz::ScopedSurfaceIdAllocator(std::move(allocation_task));
+}
+
+bool RenderWidgetHostViewBase::IsLocalSurfaceIdAllocationSuppressed() const {
+ return false;
}
base::WeakPtr<RenderWidgetHostViewBase> RenderWidgetHostViewBase::GetWeakPtr() {
@@ -291,13 +351,11 @@ base::WeakPtr<RenderWidgetHostViewBase> RenderWidgetHostViewBase::GetWeakPtr() {
std::unique_ptr<SyntheticGestureTarget>
RenderWidgetHostViewBase::CreateSyntheticGestureTarget() {
- RenderWidgetHostImpl* host = GetRenderWidgetHostImpl();
return std::unique_ptr<SyntheticGestureTarget>(
- new SyntheticGestureTargetBase(host));
+ new SyntheticGestureTargetBase(host()));
}
void RenderWidgetHostViewBase::FocusedNodeTouched(
- const gfx::Point& location_dips_screen,
bool editable) {
DVLOG(1) << "FocusedNodeTouched: " << editable;
}
@@ -345,16 +403,10 @@ CursorManager* RenderWidgetHostViewBase::GetCursorManager() {
void RenderWidgetHostViewBase::OnDidNavigateMainFrameToNewPage() {
}
-RenderWidgetHostImpl* RenderWidgetHostViewBase::GetRenderWidgetHostImpl()
- const {
- return nullptr;
-}
-
void RenderWidgetHostViewBase::OnFrameTokenChangedForView(
uint32_t frame_token) {
- RenderWidgetHostImpl* host = GetRenderWidgetHostImpl();
- if (host)
- host->DidProcessFrame(frame_token);
+ if (host())
+ host()->DidProcessFrame(frame_token);
}
viz::FrameSinkId RenderWidgetHostViewBase::GetFrameSinkId() {
@@ -403,30 +455,26 @@ void RenderWidgetHostViewBase::ProcessMouseEvent(
const blink::WebMouseEvent& event,
const ui::LatencyInfo& latency) {
PreProcessMouseEvent(event);
- auto* host = GetRenderWidgetHostImpl();
- host->ForwardMouseEventWithLatencyInfo(event, latency);
+ host()->ForwardMouseEventWithLatencyInfo(event, latency);
}
void RenderWidgetHostViewBase::ProcessMouseWheelEvent(
const blink::WebMouseWheelEvent& event,
const ui::LatencyInfo& latency) {
- auto* host = GetRenderWidgetHostImpl();
- host->ForwardWheelEventWithLatencyInfo(event, latency);
+ host()->ForwardWheelEventWithLatencyInfo(event, latency);
}
void RenderWidgetHostViewBase::ProcessTouchEvent(
const blink::WebTouchEvent& event,
const ui::LatencyInfo& latency) {
PreProcessTouchEvent(event);
- auto* host = GetRenderWidgetHostImpl();
- host->ForwardTouchEventWithLatencyInfo(event, latency);
+ host()->ForwardTouchEventWithLatencyInfo(event, latency);
}
void RenderWidgetHostViewBase::ProcessGestureEvent(
const blink::WebGestureEvent& event,
const ui::LatencyInfo& latency) {
- auto* host = GetRenderWidgetHostImpl();
- host->ForwardGestureEventWithLatencyInfo(event, latency);
+ host()->ForwardGestureEventWithLatencyInfo(event, latency);
}
gfx::PointF RenderWidgetHostViewBase::TransformPointToRootCoordSpaceF(
@@ -467,6 +515,13 @@ bool RenderWidgetHostViewBase::HasSize() const {
return true;
}
+void RenderWidgetHostViewBase::Destroy() {
+ if (host_) {
+ host_->render_frame_metadata_provider()->RemoveObserver(this);
+ host_ = nullptr;
+ }
+}
+
void RenderWidgetHostViewBase::TextInputStateChanged(
const TextInputState& text_input_state) {
if (GetTextInputManager())
@@ -491,13 +546,12 @@ TextInputManager* RenderWidgetHostViewBase::GetTextInputManager() {
if (text_input_manager_)
return text_input_manager_;
- RenderWidgetHostImpl* host = GetRenderWidgetHostImpl();
- if (!host || !host->delegate())
+ if (!host() || !host()->delegate())
return nullptr;
// This RWHV needs to be registered with the TextInputManager so that the
// TextInputManager starts tracking its state, and observing its lifetime.
- text_input_manager_ = host->delegate()->GetTextInputManager();
+ text_input_manager_ = host()->delegate()->GetTextInputManager();
if (text_input_manager_)
text_input_manager_->Register(this);
@@ -582,10 +636,21 @@ RenderWidgetHostViewBase::GetWindowTreeClientFromRenderer() {
#endif
+void RenderWidgetHostViewBase::OnResizeDueToAutoResizeComplete(
+ uint64_t sequence_number) {
+ if (host())
+ host()->DidAllocateLocalSurfaceIdForAutoResize(sequence_number);
+}
+
#if defined(OS_MACOSX)
bool RenderWidgetHostViewBase::ShouldContinueToPauseForFrame() {
return false;
}
#endif
+void RenderWidgetHostViewBase::DidNavigate() {
+ if (host())
+ host()->WasResized();
+}
+
} // namespace content
diff --git a/chromium/content/browser/renderer_host/render_widget_host_view_base.h b/chromium/content/browser/renderer_host/render_widget_host_view_base.h
index 17c07af5e63..1a93d91aeff 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_view_base.h
+++ b/chromium/content/browser/renderer_host/render_widget_host_view_base.h
@@ -9,7 +9,6 @@
#include <stdint.h>
#include <memory>
-#include <string>
#include <vector>
#include "base/callback_forward.h"
@@ -19,18 +18,20 @@
#include "base/strings/string16.h"
#include "build/build_config.h"
#include "components/viz/common/quads/compositor_frame.h"
+#include "components/viz/common/surfaces/scoped_surface_id_allocator.h"
#include "components/viz/common/surfaces/surface_id.h"
#include "content/browser/renderer_host/event_with_latency_info.h"
#include "content/common/content_export.h"
+#include "content/public/browser/render_frame_metadata_provider.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/common/input_event_ack_state.h"
#include "content/public/common/screen_info.h"
#include "ipc/ipc_listener.h"
#include "services/viz/public/interfaces/compositing/compositor_frame_sink.mojom.h"
#include "services/viz/public/interfaces/hit_test/hit_test_region_list.mojom.h"
-#include "third_party/WebKit/public/platform/modules/screen_orientation/WebScreenOrientationType.h"
-#include "third_party/WebKit/public/web/WebPopupType.h"
-#include "third_party/WebKit/public/web/WebTextDirection.h"
+#include "third_party/blink/public/platform/modules/screen_orientation/web_screen_orientation_type.h"
+#include "third_party/blink/public/web/web_popup_type.h"
+#include "third_party/blink/public/web/web_text_direction.h"
#include "third_party/skia/include/core/SkImageInfo.h"
#include "ui/accessibility/ax_tree_id_registry.h"
#include "ui/base/ime/text_input_mode.h"
@@ -87,8 +88,10 @@ class WebCursor;
struct TextInputState;
// Basic implementation shared by concrete RenderWidgetHostView subclasses.
-class CONTENT_EXPORT RenderWidgetHostViewBase : public RenderWidgetHostView,
- public IPC::Listener {
+class CONTENT_EXPORT RenderWidgetHostViewBase
+ : public RenderWidgetHostView,
+ public IPC::Listener,
+ public RenderFrameMetadataProvider::Observer {
public:
using CreateCompositorFrameSinkCallback =
base::OnceCallback<void(const viz::FrameSinkId&)>;
@@ -111,6 +114,9 @@ class CONTENT_EXPORT RenderWidgetHostViewBase : public RenderWidgetHostView,
void SetIsInVR(bool is_in_vr) override;
base::string16 GetSelectedText() override;
bool IsMouseLocked() override;
+ bool LockKeyboard(base::Optional<base::flat_set<int>> keys) override;
+ void UnlockKeyboard() override;
+ bool IsKeyboardLocked() override;
gfx::Size GetVisibleViewportSize() const override;
void SetInsets(const gfx::Insets& insets) override;
bool IsSurfaceAvailableForCopy() const override;
@@ -118,9 +124,13 @@ class CONTENT_EXPORT RenderWidgetHostViewBase : public RenderWidgetHostView,
const gfx::Rect& src_rect,
const gfx::Size& output_size,
base::OnceCallback<void(const SkBitmap&)> callback) override;
- void FocusedNodeTouched(const gfx::Point& location_dips_screen,
- bool editable) override;
+ viz::mojom::FrameSinkVideoCapturerPtr CreateVideoCapturer() override;
+ void FocusedNodeTouched(bool editable) override;
void GetScreenInfo(ScreenInfo* screen_info) const override;
+ void EnableAutoResize(const gfx::Size& min_size,
+ const gfx::Size& max_size) override;
+ void DisableAutoResize(const gfx::Size& new_size) override;
+ bool IsScrollOffsetAtTop() const override;
float GetDeviceScaleFactor() const final;
TouchSelectionControllerClientManager*
GetTouchSelectionControllerClientManager() override;
@@ -135,6 +145,10 @@ class CONTENT_EXPORT RenderWidgetHostViewBase : public RenderWidgetHostView,
// IPC::Listener implementation:
bool OnMessageReceived(const IPC::Message& msg) override;
+ // RenderFrameMetadataProvider::Observer
+ void OnRenderFrameMetadataChanged() override;
+ void OnRenderFrameSubmission() override;
+
void SetPopupType(blink::WebPopupType popup_type);
blink::WebPopupType GetPopupType();
@@ -162,8 +176,11 @@ class CONTENT_EXPORT RenderWidgetHostViewBase : public RenderWidgetHostView,
// Informs the view that the renderer has resized to |new_size| because auto-
// resize is enabled.
- virtual void ResizeDueToAutoResize(const gfx::Size& new_size,
- uint64_t sequence_number);
+ virtual viz::ScopedSurfaceIdAllocator ResizeDueToAutoResize(
+ const gfx::Size& new_size,
+ uint64_t sequence_number);
+
+ virtual bool IsLocalSurfaceIdAllocationSuppressed() const;
base::WeakPtr<RenderWidgetHostViewBase> GetWeakPtr();
@@ -238,13 +255,6 @@ class CONTENT_EXPORT RenderWidgetHostViewBase : public RenderWidgetHostView,
virtual void FocusedNodeChanged(bool is_editable_node,
const gfx::Rect& node_bounds_in_screen) {}
- // This method is called by RenderWidgetHostImpl when the renderer has
- // requested a CompositorFrameSink. The callback takes a FrameSinkId and
- // fullfills the request. The default implementation will immediately run the
- // callback with GetFrameSinkId().
- virtual void CreateCompositorFrameSink(
- CreateCompositorFrameSinkCallback callback);
-
// This method is called by RenderWidgetHostImpl when a new
// RendererCompositorFrameSink is created in the renderer. The view is
// expected not to return resources belonging to the old
@@ -432,12 +442,15 @@ class CONTENT_EXPORT RenderWidgetHostViewBase : public RenderWidgetHostView,
int error_code) = 0;
// Tells the View to destroy itself.
- virtual void Destroy() = 0;
+ virtual void Destroy();
// Tells the View that the tooltip text for the current mouse position over
// the page has changed.
virtual void SetTooltipText(const base::string16& tooltip_text) = 0;
+ // Displays the requested tooltip on the screen.
+ virtual void DisplayTooltipText(const base::string16& tooltip_text) {}
+
// Returns the offset of the view from the origin of the browser compositor's
// surface. This is in DIP.
virtual gfx::Vector2d GetOffsetFromRootSurface() = 0;
@@ -460,7 +473,7 @@ class CONTENT_EXPORT RenderWidgetHostViewBase : public RenderWidgetHostView,
virtual void SetShowingContextMenu(bool showing) {}
// Returns the associated RenderWidgetHostImpl.
- virtual RenderWidgetHostImpl* GetRenderWidgetHostImpl() const;
+ RenderWidgetHostImpl* host() const { return host_; }
// Process swap messages sent before |frame_token| in RenderWidgetHostImpl.
void OnFrameTokenChangedForView(uint32_t frame_token);
@@ -493,6 +506,14 @@ class CONTENT_EXPORT RenderWidgetHostViewBase : public RenderWidgetHostView,
web_contents_accessibility_ = wcax;
}
+ void set_is_currently_scrolling_viewport(
+ bool is_currently_scrolling_viewport) {
+ is_currently_scrolling_viewport_ = is_currently_scrolling_viewport;
+ }
+
+ bool is_currently_scrolling_viewport() {
+ return is_currently_scrolling_viewport_;
+ }
#if defined(USE_AURA)
void EmbedChildFrameRendererWindowTreeClient(
RenderWidgetHostViewBase* root_view,
@@ -507,14 +528,13 @@ class CONTENT_EXPORT RenderWidgetHostViewBase : public RenderWidgetHostView,
virtual bool ShouldContinueToPauseForFrame();
#endif
- virtual void DidNavigate() {}
+ virtual void DidNavigate();
// Called when the RenderWidgetHostImpl has be initialized.
virtual void OnRenderWidgetInit() {}
protected:
- // Interface class only, do not construct.
- RenderWidgetHostViewBase();
+ explicit RenderWidgetHostViewBase(RenderWidgetHost* host);
void NotifyObserversAboutShutdown();
@@ -526,6 +546,10 @@ class CONTENT_EXPORT RenderWidgetHostViewBase : public RenderWidgetHostView,
ui::mojom::WindowTreeClientPtr GetWindowTreeClientFromRenderer();
#endif
+ // The model object. Members will become private when
+ // RenderWidgetHostViewGuest is removed.
+ RenderWidgetHostImpl* host_;
+
// Is this a fullscreen view?
bool is_fullscreen_;
@@ -533,12 +557,19 @@ class CONTENT_EXPORT RenderWidgetHostViewBase : public RenderWidgetHostView,
// autofill...).
blink::WebPopupType popup_type_;
+ // Indicates whether keyboard lock is active for this view.
+ bool keyboard_locked_ = false;
+
// While the mouse is locked, the cursor is hidden from the user. Mouse events
// are still generated. However, the position they report is the last known
// mouse position just as mouse lock was entered; the movement they report
// indicates what the change in position of the mouse would be had it not been
// locked.
- bool mouse_locked_;
+ bool mouse_locked_ = false;
+
+ // Indicates whether the scroll offset of the root layer is at top, i.e.,
+ // whether scroll_offset.y() == 0.
+ bool is_scroll_offset_at_top_ = true;
// The scale factor of the display the renderer is currently on.
float current_device_scale_factor_;
@@ -559,6 +590,8 @@ class CONTENT_EXPORT RenderWidgetHostViewBase : public RenderWidgetHostView,
WebContentsAccessibility* web_contents_accessibility_;
+ bool is_currently_scrolling_viewport_;
+
private:
#if defined(USE_AURA)
void OnDidScheduleEmbed(int routing_id,
@@ -572,6 +605,8 @@ class CONTENT_EXPORT RenderWidgetHostViewBase : public RenderWidgetHostView,
// LocalSurfaceId.
virtual void OnSynchronizedDisplayPropertiesChanged() {}
+ void OnResizeDueToAutoResizeComplete(uint64_t sequence_number);
+
gfx::Rect current_display_area_;
uint32_t renderer_frame_number_;
diff --git a/chromium/content/browser/renderer_host/render_widget_host_view_base_unittest.cc b/chromium/content/browser/renderer_host/render_widget_host_view_base_unittest.cc
index de7a80264ac..47d80a3e04d 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_view_base_unittest.cc
+++ b/chromium/content/browser/renderer_host/render_widget_host_view_base_unittest.cc
@@ -6,7 +6,7 @@
#include "content/browser/renderer_host/display_util.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/modules/screen_orientation/WebScreenOrientationType.h"
+#include "third_party/blink/public/platform/modules/screen_orientation/web_screen_orientation_type.h"
#include "ui/display/display.h"
namespace content {
diff --git a/chromium/content/browser/renderer_host/render_widget_host_view_browsertest.cc b/chromium/content/browser/renderer_host/render_widget_host_view_browsertest.cc
index 26f9a5b1155..2e37ed47d72 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_view_browsertest.cc
+++ b/chromium/content/browser/renderer_host/render_widget_host_view_browsertest.cc
@@ -761,14 +761,14 @@ IN_PROC_BROWSER_TEST_P(CompositingRenderWidgetHostViewBrowserTestHiDPI,
kContentHeight, kScrollAmount));
SET_UP_SURFACE_OR_PASS_TEST("\"DONE\"");
+ RenderFrameSubmissionObserver observer_(
+ GetRenderWidgetHost()->render_frame_metadata_provider());
+ observer_.WaitForScrollOffsetAtTop(false);
+
if (!ShouldContinueAfterTestURLLoad())
return;
- RenderWidgetHostViewBase* rwhv = GetRenderWidgetHostView();
- gfx::Vector2dF scroll_offset = rwhv->GetLastScrollOffset();
-
- EXPECT_EQ(scroll_offset.x(), 0);
- EXPECT_EQ(scroll_offset.y(), kScrollAmount);
+ EXPECT_FALSE(GetRenderWidgetHostView()->IsScrollOffsetAtTop());
}
#if defined(OS_CHROMEOS)
diff --git a/chromium/content/browser/renderer_host/render_widget_host_view_child_frame.cc b/chromium/content/browser/renderer_host/render_widget_host_view_child_frame.cc
index 8ef70e762e4..0f78c03f686 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_view_child_frame.cc
+++ b/chromium/content/browser/renderer_host/render_widget_host_view_child_frame.cc
@@ -10,7 +10,6 @@
#include "base/debug/dump_without_crashing.h"
#include "base/location.h"
-#include "base/memory/ptr_util.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
@@ -25,6 +24,7 @@
#include "content/browser/browser_plugin/browser_plugin_guest.h"
#include "content/browser/compositor/surface_utils.h"
#include "content/browser/gpu/compositor_util.h"
+#include "content/browser/renderer_host/cursor_manager.h"
#include "content/browser/renderer_host/display_util.h"
#include "content/browser/renderer_host/frame_connector_delegate.h"
#include "content/browser/renderer_host/input/touch_selection_controller_client_child_frame.h"
@@ -40,7 +40,7 @@
#include "content/public/browser/render_process_host.h"
#include "gpu/ipc/common/gpu_messages.h"
#include "services/service_manager/runner/common/client_util.h"
-#include "third_party/WebKit/public/platform/WebTouchEvent.h"
+#include "third_party/blink/public/platform/web_touch_event.h"
#include "ui/base/ui_base_features.h"
#include "ui/gfx/geometry/dip_util.h"
#include "ui/gfx/geometry/size_conversions.h"
@@ -65,7 +65,7 @@ RenderWidgetHostViewChildFrame* RenderWidgetHostViewChildFrame::Create(
RenderWidgetHostViewChildFrame::RenderWidgetHostViewChildFrame(
RenderWidgetHost* widget_host)
- : host_(RenderWidgetHostImpl::From(widget_host)),
+ : RenderWidgetHostViewBase(widget_host),
frame_sink_id_(
base::checked_cast<uint32_t>(widget_host->GetProcess()->GetID()),
base::checked_cast<uint32_t>(widget_host->GetRoutingID())),
@@ -104,7 +104,7 @@ RenderWidgetHostViewChildFrame::~RenderWidgetHostViewChildFrame() {
void RenderWidgetHostViewChildFrame::Init() {
RegisterFrameSinkId();
- host_->SetView(this);
+ host()->SetView(this);
GetTextInputManager();
}
@@ -225,7 +225,7 @@ void RenderWidgetHostViewChildFrame::SetBounds(const gfx::Rect& rect) {
// Resizing happens in CrossProcessFrameConnector for child frames.
if (rect != last_screen_rect_) {
last_screen_rect_ = rect;
- host_->SendScreenRects();
+ host()->SendScreenRects();
}
}
@@ -242,29 +242,29 @@ bool RenderWidgetHostViewChildFrame::IsSurfaceAvailableForCopy() const {
}
void RenderWidgetHostViewChildFrame::Show() {
- if (!host_->is_hidden())
+ if (!host()->is_hidden())
return;
if (!CanBecomeVisible())
return;
- host_->WasShown(ui::LatencyInfo());
+ host()->WasShown(ui::LatencyInfo());
if (frame_connector_)
frame_connector_->SetVisibilityForChildViews(true);
}
void RenderWidgetHostViewChildFrame::Hide() {
- if (host_->is_hidden())
+ if (host()->is_hidden())
return;
- host_->WasHidden();
+ host()->WasHidden();
if (frame_connector_)
frame_connector_->SetVisibilityForChildViews(false);
}
bool RenderWidgetHostViewChildFrame::IsShowing() {
- return !host_->is_hidden();
+ return !host()->is_hidden();
}
gfx::Rect RenderWidgetHostViewChildFrame::GetViewBounds() const {
@@ -301,12 +301,13 @@ gfx::Size RenderWidgetHostViewChildFrame::GetVisibleViewportSize() const {
// is that Blink ends up using the visual viewport to calculate things like
// window.innerWidth/innerHeight for main frames, and a guest is considered
// to be a main frame. This should be cleaned up eventually.
- bool is_guest = BrowserPluginGuest::IsGuest(RenderViewHostImpl::From(host_));
+ bool is_guest = BrowserPluginGuest::IsGuest(RenderViewHostImpl::From(host()));
if (frame_connector_ && !is_guest) {
// An auto-resize set by the top-level frame overrides what would be
// reported by embedding RenderWidgetHostViews.
- if (host_->delegate() && !host_->delegate()->GetAutoResizeSize().IsEmpty())
- return host_->delegate()->GetAutoResizeSize();
+ if (host()->delegate() &&
+ !host()->delegate()->GetAutoResizeSize().IsEmpty())
+ return host()->delegate()->GetAutoResizeSize();
RenderWidgetHostView* parent_view =
frame_connector_->GetParentRenderWidgetHostView();
@@ -314,11 +315,22 @@ gfx::Size RenderWidgetHostViewChildFrame::GetVisibleViewportSize() const {
if (parent_view)
return parent_view->GetVisibleViewportSize();
}
- return GetViewBounds().size();
+
+ gfx::Rect bounds = GetViewBounds();
+
+ // It doesn't make sense to set insets on an OOP iframe. The only time this
+ // should happen is when the virtual keyboard comes up on a <webview>.
+ if (is_guest)
+ bounds.Inset(insets_);
+
+ return bounds.size();
}
-gfx::Vector2dF RenderWidgetHostViewChildFrame::GetLastScrollOffset() const {
- return last_scroll_offset_;
+void RenderWidgetHostViewChildFrame::SetInsets(const gfx::Insets& insets) {
+ // Insets are used only for <webview> and are used to let the UI know it's
+ // being obscured (for e.g. by the virtual keyboard).
+ insets_ = insets;
+ host()->WasResized(!insets_.IsEmpty());
}
gfx::NativeView RenderWidgetHostViewChildFrame::GetNativeView() const {
@@ -342,7 +354,7 @@ void RenderWidgetHostViewChildFrame::SetBackgroundColor(SkColor color) {
DCHECK(SkColorGetA(color) == SK_AlphaOPAQUE ||
SkColorGetA(color) == SK_AlphaTRANSPARENT);
- host_->SetBackgroundOpaque(SkColorGetA(color) == SK_AlphaOPAQUE);
+ host()->SetBackgroundOpaque(SkColorGetA(color) == SK_AlphaOPAQUE);
}
SkColor RenderWidgetHostViewChildFrame::background_color() const {
@@ -379,7 +391,7 @@ void RenderWidgetHostViewChildFrame::SetIsLoading(bool is_loading) {
// inner/outer WebContents, only subframe's RenderWidgetHostView can be a
// RenderWidgetHostViewChildFrame which do not get a SetIsLoading() call.
if (GuestMode::IsCrossProcessFrameGuest(
- WebContents::FromRenderViewHost(RenderViewHost::From(host_))))
+ WebContents::FromRenderViewHost(RenderViewHost::From(host()))))
return;
NOTREACHED();
@@ -407,15 +419,21 @@ void RenderWidgetHostViewChildFrame::Destroy() {
// RenderWidgetHostInputEventRouter afterwards.
NotifyObserversAboutShutdown();
- host_->SetView(nullptr);
- host_ = nullptr;
+ RenderWidgetHostViewBase::Destroy();
delete this;
}
void RenderWidgetHostViewChildFrame::SetTooltipText(
const base::string16& tooltip_text) {
- frame_connector_->GetRootRenderWidgetHostView()->SetTooltipText(tooltip_text);
+ if (!frame_connector_)
+ return;
+
+ auto* root_view = frame_connector_->GetRootRenderWidgetHostView();
+ if (!root_view)
+ return;
+
+ root_view->GetCursorManager()->SetTooltipTextForView(this, tooltip_text);
}
RenderWidgetHostViewBase* RenderWidgetHostViewChildFrame::GetParentView() {
@@ -426,41 +444,45 @@ RenderWidgetHostViewBase* RenderWidgetHostViewChildFrame::GetParentView() {
void RenderWidgetHostViewChildFrame::RegisterFrameSinkId() {
// If Destroy() has been called before we get here, host_ may be null.
- if (host_ && host_->delegate() && host_->delegate()->GetInputEventRouter()) {
+ if (host() && host()->delegate() &&
+ host()->delegate()->GetInputEventRouter()) {
RenderWidgetHostInputEventRouter* router =
- host_->delegate()->GetInputEventRouter();
+ host()->delegate()->GetInputEventRouter();
if (!router->is_registered(frame_sink_id_))
router->AddFrameSinkIdOwner(frame_sink_id_, this);
}
}
void RenderWidgetHostViewChildFrame::UnregisterFrameSinkId() {
- DCHECK(host_);
- if (host_->delegate() && host_->delegate()->GetInputEventRouter()) {
- host_->delegate()->GetInputEventRouter()->RemoveFrameSinkIdOwner(
+ DCHECK(host());
+ if (host()->delegate() && host()->delegate()->GetInputEventRouter()) {
+ host()->delegate()->GetInputEventRouter()->RemoveFrameSinkIdOwner(
frame_sink_id_);
DetachFromTouchSelectionClientManagerIfNecessary();
}
}
void RenderWidgetHostViewChildFrame::UpdateViewportIntersection(
- const gfx::Rect& viewport_intersection) {
- if (host_)
- host_->Send(new ViewMsg_SetViewportIntersection(host_->GetRoutingID(),
- viewport_intersection));
+ const gfx::Rect& viewport_intersection,
+ const gfx::Rect& compositor_visible_rect) {
+ if (host()) {
+ host()->Send(new ViewMsg_SetViewportIntersection(host()->GetRoutingID(),
+ viewport_intersection,
+ compositor_visible_rect));
+ }
}
void RenderWidgetHostViewChildFrame::SetIsInert() {
- if (host_ && frame_connector_) {
- host_->Send(new ViewMsg_SetIsInert(host_->GetRoutingID(),
- frame_connector_->IsInert()));
+ if (host() && frame_connector_) {
+ host()->Send(new ViewMsg_SetIsInert(host()->GetRoutingID(),
+ frame_connector_->IsInert()));
}
}
void RenderWidgetHostViewChildFrame::UpdateRenderThrottlingStatus() {
- if (host_ && frame_connector_) {
- host_->Send(new ViewMsg_UpdateRenderThrottlingStatus(
- host_->GetRoutingID(), frame_connector_->IsThrottled(),
+ if (host() && frame_connector_) {
+ host()->Send(new ViewMsg_UpdateRenderThrottlingStatus(
+ host()->GetRoutingID(), frame_connector_->IsThrottled(),
frame_connector_->IsSubtreeThrottled()));
}
}
@@ -579,31 +601,6 @@ void RenderWidgetHostViewChildFrame::SetParentFrameSinkId(
}
}
-void RenderWidgetHostViewChildFrame::ProcessCompositorFrame(
- const viz::LocalSurfaceId& local_surface_id,
- viz::CompositorFrame frame,
- viz::mojom::HitTestRegionListPtr hit_test_region_list) {
- current_surface_size_ = frame.size_in_pixels();
- current_surface_scale_factor_ = frame.device_scale_factor();
-
- support_->SubmitCompositorFrame(local_surface_id, std::move(frame),
- std::move(hit_test_region_list));
- has_frame_ = true;
-
- if (last_received_local_surface_id_ != local_surface_id ||
- HasEmbedderChanged()) {
- last_received_local_surface_id_ = local_surface_id;
- SendSurfaceInfoToEmbedder();
- }
-
- if (selection_controller_client_) {
- selection_controller_client_->UpdateSelectionBoundsIfNeeded(
- frame.metadata.selection, current_device_scale_factor_);
- }
-
- ProcessFrameSwappedCallbacks();
-}
-
void RenderWidgetHostViewChildFrame::SendSurfaceInfoToEmbedder() {
if (base::FeatureList::IsEnabled(features::kMash))
return;
@@ -626,11 +623,20 @@ void RenderWidgetHostViewChildFrame::SubmitCompositorFrame(
DCHECK(!enable_viz_);
TRACE_EVENT0("content",
"RenderWidgetHostViewChildFrame::OnSwapCompositorFrame");
- last_scroll_offset_ = frame.metadata.root_scroll_offset;
- if (!frame_connector_)
- return;
- ProcessCompositorFrame(local_surface_id, std::move(frame),
- std::move(hit_test_region_list));
+ current_surface_size_ = frame.size_in_pixels();
+ current_surface_scale_factor_ = frame.device_scale_factor();
+
+ support_->SubmitCompositorFrame(local_surface_id, std::move(frame),
+ std::move(hit_test_region_list));
+ has_frame_ = true;
+
+ if (last_received_local_surface_id_ != local_surface_id ||
+ HasEmbedderChanged()) {
+ last_received_local_surface_id_ = local_surface_id;
+ SendSurfaceInfoToEmbedder();
+ }
+
+ ProcessFrameSwappedCallbacks();
}
void RenderWidgetHostViewChildFrame::OnDidNotProduceFrame(
@@ -689,21 +695,16 @@ bool RenderWidgetHostViewChildFrame::LockMouse() {
}
void RenderWidgetHostViewChildFrame::UnlockMouse() {
- if (host_->delegate() && host_->delegate()->HasMouseLock(host_) &&
+ if (host()->delegate() && host()->delegate()->HasMouseLock(host()) &&
frame_connector_)
frame_connector_->UnlockMouse();
}
bool RenderWidgetHostViewChildFrame::IsMouseLocked() {
- if (!host_->delegate())
+ if (!host()->delegate())
return false;
- return host_->delegate()->HasMouseLock(host_);
-}
-
-RenderWidgetHostImpl* RenderWidgetHostViewChildFrame::GetRenderWidgetHostImpl()
- const {
- return host_;
+ return host()->delegate()->HasMouseLock(host());
}
viz::FrameSinkId RenderWidgetHostViewChildFrame::GetFrameSinkId() {
@@ -805,7 +806,8 @@ void RenderWidgetHostViewChildFrame::WillSendScreenRects() {
// spammy way to do this, but triggering on SendScreenRects() is reasonable
// until somebody figures that out. RWHVCF::Init() is too early.
if (frame_connector_) {
- UpdateViewportIntersection(frame_connector_->ViewportIntersection());
+ UpdateViewportIntersection(frame_connector_->viewport_intersection_rect(),
+ frame_connector_->compositor_visible_rect());
SetIsInert();
UpdateRenderThrottlingStatus();
}
@@ -821,17 +823,7 @@ void RenderWidgetHostViewChildFrame::ShowDefinitionForSelection() {
}
}
-bool RenderWidgetHostViewChildFrame::SupportsSpeech() const {
- return false;
-}
-
void RenderWidgetHostViewChildFrame::SpeakSelection() {}
-
-bool RenderWidgetHostViewChildFrame::IsSpeaking() const {
- return false;
-}
-
-void RenderWidgetHostViewChildFrame::StopSpeaking() {}
#endif // defined(OS_MACOSX)
void RenderWidgetHostViewChildFrame::RegisterFrameSwappedCallback(
@@ -883,7 +875,9 @@ void RenderWidgetHostViewChildFrame::CopyFromSurface(
gfx::Vector2d(output_size.width(), output_size.height()));
}
- support_->RequestCopyOfSurface(std::move(request));
+ GetHostFrameSinkManager()->RequestCopyOfOutput(
+ viz::SurfaceId(frame_sink_id_, last_received_local_surface_id_),
+ std::move(request));
}
void RenderWidgetHostViewChildFrame::ReclaimResources(
@@ -894,6 +888,7 @@ void RenderWidgetHostViewChildFrame::ReclaimResources(
void RenderWidgetHostViewChildFrame::OnBeginFrame(
const viz::BeginFrameArgs& args) {
+ host_->ProgressFling(args.frame_time);
if (renderer_compositor_frame_sink_)
renderer_compositor_frame_sink_->OnBeginFrame(args);
}
@@ -928,11 +923,26 @@ RenderWidgetHostViewChildFrame::GetTouchSelectionControllerClientManager() {
return root_view->GetTouchSelectionControllerClientManager();
}
+void RenderWidgetHostViewChildFrame::OnRenderFrameMetadataChanged() {
+ RenderWidgetHostViewBase::OnRenderFrameMetadataChanged();
+ if (selection_controller_client_) {
+ const cc::RenderFrameMetadata& metadata =
+ host()->render_frame_metadata_provider()->LastRenderFrameMetadata();
+ selection_controller_client_->UpdateSelectionBoundsIfNeeded(
+ metadata.selection, current_device_scale_factor_);
+ }
+}
+
void RenderWidgetHostViewChildFrame::SetWantsAnimateOnlyBeginFrames() {
if (support_)
support_->SetWantsAnimateOnlyBeginFrames();
}
+void RenderWidgetHostViewChildFrame::TakeFallbackContentFrom(
+ RenderWidgetHostView* view) {
+ // This method only makes sense for top-level views.
+}
+
InputEventAckState RenderWidgetHostViewChildFrame::FilterInputEvent(
const blink::WebInputEvent& input_event) {
if (input_event.GetType() == blink::WebInputEvent::kGestureFlingStart) {
@@ -940,7 +950,7 @@ InputEventAckState RenderWidgetHostViewChildFrame::FilterInputEvent(
static_cast<const blink::WebGestureEvent&>(input_event);
// Zero-velocity touchpad flings are an Aura-specific signal that the
// touchpad scroll has ended, and should not be forwarded to the renderer.
- if (gesture_event.source_device == blink::kWebGestureDeviceTouchpad &&
+ if (gesture_event.SourceDevice() == blink::kWebGestureDeviceTouchpad &&
!gesture_event.data.fling_start.velocity_x &&
!gesture_event.data.fling_start.velocity_y) {
// Here we indicate that there was no consumer for this event, as
@@ -1014,18 +1024,33 @@ void RenderWidgetHostViewChildFrame::GetScreenInfo(
DisplayUtil::GetDefaultScreenInfo(screen_info);
}
-void RenderWidgetHostViewChildFrame::ResizeDueToAutoResize(
- const gfx::Size& new_size,
- uint64_t sequence_number) {
+void RenderWidgetHostViewChildFrame::EnableAutoResize(
+ const gfx::Size& min_size,
+ const gfx::Size& max_size) {
if (frame_connector_)
- frame_connector_->ResizeDueToAutoResize(new_size, sequence_number);
+ frame_connector_->EnableAutoResize(min_size, max_size);
}
-void RenderWidgetHostViewChildFrame::ClearCompositorSurfaceIfNecessary() {
- if (!support_)
- return;
- support_->EvictLastActivatedSurface();
- has_frame_ = false;
+void RenderWidgetHostViewChildFrame::DisableAutoResize(
+ const gfx::Size& new_size) {
+ // For child frames, the size comes from the parent when auto-resize is
+ // disabled so we ignore |new_size| here.
+ if (frame_connector_)
+ frame_connector_->DisableAutoResize();
+}
+
+viz::ScopedSurfaceIdAllocator
+RenderWidgetHostViewChildFrame::ResizeDueToAutoResize(
+ const gfx::Size& new_size,
+ uint64_t sequence_number) {
+ // TODO(cblume): This doesn't currently suppress allocation.
+ // It maintains existing behavior while using the suppression style.
+ // This will be addressed in a follow-up patch.
+ // See https://crbug.com/805073
+ base::OnceCallback<void()> allocation_task = base::BindOnce(
+ &RenderWidgetHostViewChildFrame::OnResizeDueToAutoResizeComplete,
+ weak_factory_.GetWeakPtr(), new_size, sequence_number);
+ return viz::ScopedSurfaceIdAllocator(std::move(allocation_task));
}
void RenderWidgetHostViewChildFrame::CreateCompositorFrameSinkSupport() {
@@ -1041,7 +1066,7 @@ void RenderWidgetHostViewChildFrame::CreateCompositorFrameSinkSupport() {
GetHostFrameSinkManager()->RegisterFrameSinkHierarchy(parent_frame_sink_id_,
frame_sink_id_);
}
- if (host_->needs_begin_frames())
+ if (host()->needs_begin_frames())
support_->SetNeedsBeginFrame(true);
}
@@ -1107,10 +1132,18 @@ bool RenderWidgetHostViewChildFrame::CanBecomeVisible() {
->CanBecomeVisible();
}
+void RenderWidgetHostViewChildFrame::OnResizeDueToAutoResizeComplete(
+ const gfx::Size& new_size,
+ uint64_t sequence_number) {
+ if (frame_connector_)
+ frame_connector_->ResizeDueToAutoResize(new_size, sequence_number);
+}
+
void RenderWidgetHostViewChildFrame::DidNavigate() {
- if (host_->auto_resize_enabled()) {
- host_->DidAllocateLocalSurfaceIdForAutoResize(
- host_->last_auto_resize_request_number());
+ host()->WasResized();
+ if (host()->auto_resize_enabled()) {
+ host()->DidAllocateLocalSurfaceIdForAutoResize(
+ host()->last_auto_resize_request_number());
}
}
diff --git a/chromium/content/browser/renderer_host/render_widget_host_view_child_frame.h b/chromium/content/browser/renderer_host/render_widget_host_view_child_frame.h
index 26bc82812db..a004195a306 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_view_child_frame.h
+++ b/chromium/content/browser/renderer_host/render_widget_host_view_child_frame.h
@@ -26,7 +26,7 @@
#include "content/public/browser/touch_selection_controller_client_manager.h"
#include "content/public/common/input_event_ack_state.h"
#include "services/viz/public/interfaces/compositing/compositor_frame_sink.mojom.h"
-#include "third_party/WebKit/public/platform/WebIntrinsicSizingInfo.h"
+#include "third_party/blink/public/platform/web_intrinsic_sizing_info.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/native_widget_types.h"
@@ -37,7 +37,6 @@ class CompositorFrameSinkSupport;
namespace content {
class FrameConnectorDelegate;
class RenderWidgetHost;
-class RenderWidgetHostImpl;
class RenderWidgetHostViewChildFrameTest;
class RenderWidgetHostViewGuestSurfaceTest;
class TouchSelectionControllerClientChildFrame;
@@ -73,7 +72,7 @@ class CONTENT_EXPORT RenderWidgetHostViewChildFrame
// This functions registers single-use callbacks that want to be notified when
// the next frame is swapped. The callback is triggered by
- // ProcessCompositorFrame, which is the appropriate time to request pixel
+ // SubmitCompositorFrame, which is the appropriate time to request pixel
// readback for the frame that is about to be drawn. Once called, the callback
// pointer is released.
// TODO(crbug.com/787941): This should be removed because it doesn't work when
@@ -102,7 +101,7 @@ class CONTENT_EXPORT RenderWidgetHostViewChildFrame
bool IsShowing() override;
gfx::Rect GetViewBounds() const override;
gfx::Size GetVisibleViewportSize() const override;
- gfx::Vector2dF GetLastScrollOffset() const override;
+ void SetInsets(const gfx::Insets& insets) override;
gfx::NativeView GetNativeView() const override;
gfx::NativeViewAccessible GetNativeViewAccessible() override;
void SetBackgroundColor(SkColor color) override;
@@ -111,6 +110,7 @@ class CONTENT_EXPORT RenderWidgetHostViewChildFrame
bool IsMouseLocked() override;
void SetNeedsBeginFrames(bool needs_begin_frames) override;
void SetWantsAnimateOnlyBeginFrames() override;
+ void TakeFallbackContentFrom(RenderWidgetHostView* view) override;
// RenderWidgetHostViewBase implementation.
void InitAsPopup(RenderWidgetHostView* parent_host_view,
@@ -142,7 +142,6 @@ class CONTENT_EXPORT RenderWidgetHostViewChildFrame
void DidStopFlinging() override;
bool LockMouse() override;
void UnlockMouse() override;
- RenderWidgetHostImpl* GetRenderWidgetHostImpl() const override;
viz::FrameSinkId GetFrameSinkId() override;
viz::LocalSurfaceId GetLocalSurfaceId() const override;
void PreProcessTouchEvent(const blink::WebTouchEvent& event) override;
@@ -162,6 +161,7 @@ class CONTENT_EXPORT RenderWidgetHostViewChildFrame
const gfx::PointF& point) override;
TouchSelectionControllerClientManager*
GetTouchSelectionControllerClientManager() override;
+ void OnRenderFrameMetadataChanged() override;
bool IsRenderWidgetHostViewChildFrame() override;
@@ -171,10 +171,7 @@ class CONTENT_EXPORT RenderWidgetHostViewChildFrame
// RenderWidgetHostView implementation.
void SetActive(bool active) override;
void ShowDefinitionForSelection() override;
- bool SupportsSpeech() const override;
void SpeakSelection() override;
- bool IsSpeaking() const override;
- void StopSpeaking() override;
#endif // defined(OS_MACOSX)
InputEventAckState FilterInputEvent(
@@ -185,8 +182,12 @@ class CONTENT_EXPORT RenderWidgetHostViewChildFrame
BrowserAccessibilityDelegate* delegate,
bool for_root_frame) override;
void GetScreenInfo(ScreenInfo* screen_info) const override;
- void ResizeDueToAutoResize(const gfx::Size& new_size,
- uint64_t sequence_number) override;
+ void EnableAutoResize(const gfx::Size& min_size,
+ const gfx::Size& max_size) override;
+ void DisableAutoResize(const gfx::Size& new_size) override;
+ viz::ScopedSurfaceIdAllocator ResizeDueToAutoResize(
+ const gfx::Size& new_size,
+ uint64_t sequence_number) override;
// viz::mojom::CompositorFrameSinkClient implementation.
void DidReceiveCompositorFrameAck(
@@ -220,7 +221,8 @@ class CONTENT_EXPORT RenderWidgetHostViewChildFrame
void RegisterFrameSinkId();
void UnregisterFrameSinkId();
- void UpdateViewportIntersection(const gfx::Rect& viewport_intersection);
+ void UpdateViewportIntersection(const gfx::Rect& viewport_intersection,
+ const gfx::Rect& compositor_visible_rect);
void SetIsInert();
@@ -247,11 +249,6 @@ class CONTENT_EXPORT RenderWidgetHostViewChildFrame
// parent was already set then it also unregisters hierarchy.
void SetParentFrameSinkId(const viz::FrameSinkId& parent_frame_sink_id);
- void ProcessCompositorFrame(
- const viz::LocalSurfaceId& local_surface_id,
- viz::CompositorFrame frame,
- viz::mojom::HitTestRegionListPtr hit_test_region_list);
-
void SendSurfaceInfoToEmbedder();
// Clears current compositor surface, if one is in use.
@@ -259,13 +256,6 @@ class CONTENT_EXPORT RenderWidgetHostViewChildFrame
void ProcessFrameSwappedCallbacks();
- // The last scroll offset of the view.
- gfx::Vector2dF last_scroll_offset_;
-
- // Members will become private when RenderWidgetHostViewGuest is removed.
- // The model object.
- RenderWidgetHostImpl* host_;
-
// The ID for FrameSink associated with this view.
viz::FrameSinkId frame_sink_id_;
@@ -305,6 +295,9 @@ class CONTENT_EXPORT RenderWidgetHostViewChildFrame
// using CSS.
bool CanBecomeVisible();
+ void OnResizeDueToAutoResizeComplete(const gfx::Size& new_size,
+ uint64_t sequence_number);
+
std::vector<base::OnceClosure> frame_swapped_callbacks_;
// The surface client ID of the parent RenderWidgetHostView. 0 if none.
@@ -318,6 +311,8 @@ class CONTENT_EXPORT RenderWidgetHostViewChildFrame
// The background color of the widget.
SkColor background_color_;
+ gfx::Insets insets_;
+
std::unique_ptr<TouchSelectionControllerClientChildFrame>
selection_controller_client_;
diff --git a/chromium/content/browser/renderer_host/render_widget_host_view_child_frame_browsertest.cc b/chromium/content/browser/renderer_host/render_widget_host_view_child_frame_browsertest.cc
index fcc9890cc8a..a568705e47a 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_view_child_frame_browsertest.cc
+++ b/chromium/content/browser/renderer_host/render_widget_host_view_child_frame_browsertest.cc
@@ -125,8 +125,10 @@ IN_PROC_BROWSER_TEST_F(RenderWidgetHostViewChildFrameTest,
FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
->GetFrameTree()
->root();
- root->current_frame_host()->render_view_host()->EnableAutoResize(
- gfx::Size(0, 0), gfx::Size(100, 100));
+ root->current_frame_host()
+ ->GetRenderWidgetHost()
+ ->GetView()
+ ->EnableAutoResize(gfx::Size(0, 0), gfx::Size(100, 100));
RenderWidgetHostView* rwhv =
root->child_at(0)->current_frame_host()->GetRenderWidgetHost()->GetView();
diff --git a/chromium/content/browser/renderer_host/render_widget_host_view_child_frame_unittest.cc b/chromium/content/browser/renderer_host/render_widget_host_view_child_frame_unittest.cc
index 33414fd5117..7a55f9227b7 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_view_child_frame_unittest.cc
+++ b/chromium/content/browser/renderer_host/render_widget_host_view_child_frame_unittest.cc
@@ -9,7 +9,6 @@
#include <utility>
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/test/scoped_feature_list.h"
@@ -28,11 +27,13 @@
#include "content/browser/renderer_host/frame_connector_delegate.h"
#include "content/browser/renderer_host/render_widget_host_delegate.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
+#include "content/common/frame_resize_params.h"
#include "content/common/view_messages.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/common/content_features.h"
#include "content/public/test/mock_render_process_host.h"
#include "content/public/test/test_browser_context.h"
+#include "content/public/test/test_browser_thread_bundle.h"
#include "content/test/fake_renderer_compositor_frame_sink.h"
#include "content/test/mock_render_widget_host_delegate.h"
#include "content/test/mock_widget_impl.h"
@@ -60,8 +61,10 @@ class MockFrameConnectorDelegate : public FrameConnectorDelegate {
last_surface_info_ = surface_info;
}
- void SetViewportIntersection(const gfx::Rect& intersection) {
+ void SetViewportIntersection(const gfx::Rect& intersection,
+ const gfx::Rect& compositor_visible_rect) {
viewport_intersection_rect_ = intersection;
+ compositor_visible_rect_ = compositor_visible_rect;
}
RenderWidgetHostViewBase* GetParentRenderWidgetHostView() override {
@@ -79,9 +82,7 @@ class MockFrameConnectorDelegate : public FrameConnectorDelegate {
class RenderWidgetHostViewChildFrameTest : public testing::Test {
public:
- RenderWidgetHostViewChildFrameTest()
- : scoped_task_environment_(
- base::test::ScopedTaskEnvironment::MainThreadType::UI) {}
+ RenderWidgetHostViewChildFrameTest() {}
void SetUp() override {
SetUpEnvironment(false /* use_zoom_for_device_scale_factor */);
@@ -147,12 +148,8 @@ class RenderWidgetHostViewChildFrameTest : public testing::Test {
return view_->last_received_local_surface_id_;
}
- void ClearCompositorSurfaceIfNecessary() {
- view_->ClearCompositorSurfaceIfNecessary();
- }
-
protected:
- base::test::ScopedTaskEnvironment scoped_task_environment_;
+ TestBrowserThreadBundle thread_bundle_;
std::unique_ptr<BrowserContext> browser_context_;
MockRenderWidgetHostDelegate delegate_;
@@ -236,46 +233,12 @@ TEST_F(RenderWidgetHostViewChildFrameTest, SwapCompositorFrame) {
}
}
-// Check that the same local surface id can be used after frame eviction.
-TEST_F(RenderWidgetHostViewChildFrameTest, FrameEviction) {
- // TODO: fix for mash.
- if (base::FeatureList::IsEnabled(features::kMash))
- return;
-
- gfx::Size view_size(100, 100);
- gfx::Rect view_rect(view_size);
- float scale_factor = 1.f;
-
- view_->SetSize(view_size);
- view_->Show();
-
- // Submit a frame.
- view_->SubmitCompositorFrame(
- kArbitraryLocalSurfaceId,
- CreateDelegatedFrame(scale_factor, view_size, view_rect), nullptr);
-
- EXPECT_EQ(kArbitraryLocalSurfaceId, GetLocalSurfaceId());
- EXPECT_TRUE(view_->has_frame());
-
- // Evict the frame. has_frame() should return false.
- ClearCompositorSurfaceIfNecessary();
- EXPECT_EQ(kArbitraryLocalSurfaceId, GetLocalSurfaceId());
- EXPECT_FALSE(view_->has_frame());
-
- // Submit another frame with the same local surface id. The same id should be
- // usable.
- view_->SubmitCompositorFrame(
- kArbitraryLocalSurfaceId,
- CreateDelegatedFrame(scale_factor, view_size, view_rect), nullptr);
- EXPECT_EQ(kArbitraryLocalSurfaceId, GetLocalSurfaceId());
- EXPECT_TRUE(view_->has_frame());
-}
-
// Tests that the viewport intersection rect is dispatched to the RenderWidget
// whenever screen rects are updated.
TEST_F(RenderWidgetHostViewChildFrameTest, ViewportIntersectionUpdated) {
gfx::Rect intersection_rect(5, 5, 100, 80);
- test_frame_connector_->SetViewportIntersection(intersection_rect);
+ test_frame_connector_->SetViewportIntersection(intersection_rect,
+ intersection_rect);
MockRenderProcessHost* process =
static_cast<MockRenderProcessHost*>(widget_host_->GetProcess());
@@ -287,9 +250,11 @@ TEST_F(RenderWidgetHostViewChildFrameTest, ViewportIntersectionUpdated) {
process->sink().GetUniqueMessageMatching(
ViewMsg_SetViewportIntersection::ID);
ASSERT_TRUE(intersection_update);
- std::tuple<gfx::Rect> sent_rect;
- ViewMsg_SetViewportIntersection::Read(intersection_update, &sent_rect);
- EXPECT_EQ(intersection_rect, std::get<0>(sent_rect));
+ std::tuple<gfx::Rect, gfx::Rect> sent_rects;
+
+ ViewMsg_SetViewportIntersection::Read(intersection_update, &sent_rects);
+ EXPECT_EQ(intersection_rect, std::get<0>(sent_rects));
+ EXPECT_EQ(intersection_rect, std::get<1>(sent_rects));
}
// Tests specific to non-scroll-latching behaviour.
@@ -386,9 +351,11 @@ TEST_F(RenderWidgetHostViewChildFrameTest, WasResizedOncePerChange) {
process->sink().ClearMessages();
- test_frame_connector_->UpdateResizeParams(screen_space_rect,
- compositor_viewport_pixel_size,
- ScreenInfo(), 1u, surface_id);
+ FrameResizeParams resize_params;
+ resize_params.screen_space_rect = screen_space_rect;
+ resize_params.local_frame_size = compositor_viewport_pixel_size;
+ resize_params.auto_resize_sequence_number = 1u;
+ test_frame_connector_->UpdateResizeParams(surface_id, resize_params);
ASSERT_EQ(1u, process->sink().message_count());
diff --git a/chromium/content/browser/renderer_host/render_widget_host_view_cocoa.h b/chromium/content/browser/renderer_host/render_widget_host_view_cocoa.h
new file mode 100644
index 00000000000..acdb2fd0ae6
--- /dev/null
+++ b/chromium/content/browser/renderer_host/render_widget_host_view_cocoa.h
@@ -0,0 +1,225 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_VIEW_COCOA_H_
+#define CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_VIEW_COCOA_H_
+
+#import <Cocoa/Cocoa.h>
+
+#include <set>
+#include <vector>
+
+#include "base/mac/scoped_nsobject.h"
+#include "content/browser/renderer_host/input/mouse_wheel_rails_filter_mac.h"
+#include "content/common/edit_command.h"
+#import "ui/base/cocoa/command_dispatcher.h"
+#import "ui/base/cocoa/tool_tip_base_view.h"
+#include "ui/base/ime/ime_text_span.h"
+#include "ui/gfx/range/range.h"
+
+namespace blink {
+class WebGestureEvent;
+}
+
+namespace content {
+class RenderWidgetHostNSViewClient;
+class RenderWidgetHostViewMac;
+class RenderWidgetHostViewMacEditCommandHelper;
+}
+
+namespace ui {
+struct DidOverscrollParams;
+}
+
+@protocol RenderWidgetHostViewMacDelegate;
+
+@protocol RenderWidgetHostNSViewClientOwner
+- (content::RenderWidgetHostNSViewClient*)renderWidgetHostNSViewClient;
+@end
+
+// This is the view that lives in the Cocoa view hierarchy. In Windows-land,
+// RenderWidgetHostViewWin is both the view and the delegate. We split the roles
+// but that means that the view needs to own the delegate and will dispose of it
+// when it's removed from the view system.
+// TODO(ccameron): Hide this interface behind RenderWidgetHostNSViewBridge.
+@interface RenderWidgetHostViewCocoa
+ : ToolTipBaseView<CommandDispatcherTarget,
+ RenderWidgetHostNSViewClientOwner,
+ NSTextInputClient> {
+ @private
+ // The communications channel to the RenderWidgetHostViewMac. This pointer is
+ // always valid. When the original client disconnects, |client_| is changed to
+ // point to |noopClient_|, to avoid having to preface every dereference with
+ // a nullptr check.
+ content::RenderWidgetHostNSViewClient* client_;
+
+ // Dummy client that is always valid (see above).
+ std::unique_ptr<content::RenderWidgetHostNSViewClient> noopClient_;
+
+ // This ivar is the cocoa delegate of the NSResponder.
+ base::scoped_nsobject<NSObject<RenderWidgetHostViewMacDelegate>>
+ responderDelegate_;
+ BOOL canBeKeyView_;
+ BOOL closeOnDeactivate_;
+ std::unique_ptr<content::RenderWidgetHostViewMacEditCommandHelper>
+ editCommandHelper_;
+
+ // Is YES if there was a mouse-down as yet unbalanced with a mouse-up.
+ BOOL hasOpenMouseDown_;
+
+ // The cursor for the page. This is passed up from the renderer.
+ base::scoped_nsobject<NSCursor> currentCursor_;
+
+ // Is YES if the cursor is hidden by key events.
+ BOOL cursorHidden_;
+
+ // Controlled by setShowingContextMenu.
+ BOOL showingContextMenu_;
+
+ // Set during -setFrame to avoid spamming client_ with origin and size
+ // changes.
+ BOOL inSetFrame_;
+
+ // Variables used by our implementaion of the NSTextInput protocol.
+ // An input method of Mac calls the methods of this protocol not only to
+ // notify an application of its status, but also to retrieve the status of
+ // the application. That is, an application cannot control an input method
+ // directly.
+ // This object keeps the status of a composition of the renderer and returns
+ // it when an input method asks for it.
+ // We need to implement Objective-C methods for the NSTextInput protocol. On
+ // the other hand, we need to implement a C++ method for an IPC-message
+ // handler which receives input-method events from the renderer.
+
+ // Represents the input-method attributes supported by this object.
+ base::scoped_nsobject<NSArray> validAttributesForMarkedText_;
+
+ // Indicates if we are currently handling a key down event.
+ BOOL handlingKeyDown_;
+
+ // Indicates if there is any marked text.
+ BOOL hasMarkedText_;
+
+ // Indicates if unmarkText is called or not when handling a keyboard
+ // event.
+ BOOL unmarkTextCalled_;
+
+ // The range of current marked text inside the whole content of the DOM node
+ // being edited.
+ // TODO(suzhe): This is currently a fake value, as we do not support accessing
+ // the whole content yet.
+ NSRange markedRange_;
+
+ // The text selection, cached from the RenderWidgetHostView. This is only ever
+ // updated from the renderer.
+ base::string16 textSelectionText_;
+ size_t textSelectionOffset_;
+ gfx::Range textSelectionRange_;
+
+ // The composition range, cached from the RenderWidgetHostView. This is only
+ // ever updated from the renderer (unlike |markedRange_|, which sometimes but
+ // not always coincides with |compositionRange_|).
+ bool hasCompositionRange_;
+ gfx::Range compositionRange_;
+
+ // Text to be inserted which was generated by handling a key down event.
+ base::string16 textToBeInserted_;
+
+ // Marked text which was generated by handling a key down event.
+ base::string16 markedText_;
+
+ // Selected range of |markedText_|.
+ NSRange markedTextSelectedRange_;
+
+ // Underline information of the |markedText_|.
+ std::vector<ui::ImeTextSpan> ime_text_spans_;
+
+ // Replacement range information received from |setMarkedText:|.
+ gfx::Range setMarkedTextReplacementRange_;
+
+ // Indicates if doCommandBySelector method receives any edit command when
+ // handling a key down event.
+ BOOL hasEditCommands_;
+
+ // Contains edit commands received by the -doCommandBySelector: method when
+ // handling a key down event, not including inserting commands, eg. insertTab,
+ // etc.
+ content::EditCommands editCommands_;
+
+ // Whether the previous mouse event was ignored due to hitTest check.
+ BOOL mouseEventWasIgnored_;
+
+ // Event monitor for scroll wheel end event.
+ id endWheelMonitor_;
+
+ // This is used to indicate if a stylus is currently in the proximity of the
+ // tablet.
+ bool isStylusEnteringProximity_;
+ blink::WebPointerProperties::PointerType pointerType_;
+
+ // The set of key codes from key down events that we haven't seen the matching
+ // key up events yet.
+ // Used for filtering out non-matching NSKeyUp events.
+ std::set<unsigned short> keyDownCodes_;
+
+ // The filter used to guide touch events towards a horizontal or vertical
+ // orientation.
+ content::MouseWheelRailsFilterMac mouseWheelFilter_;
+}
+
+@property(nonatomic, assign) NSRange markedRange;
+
+// Common code path for handling begin gesture events. This helper method is
+// called via different codepaths based on OS version and SDK:
+// - On 10.11 and later, when linking with the 10.11 SDK, it is called from
+// |magnifyWithEvent:| when the given event's phase is NSEventPhaseBegin.
+// - On 10.10 and earlier, or when linking with an earlier SDK, it is called
+// by |beginGestureWithEvent:| when a gesture begins.
+- (void)handleBeginGestureWithEvent:(NSEvent*)event;
+
+// Common code path for handling end gesture events. This helper method is
+// called via different codepaths based on OS version and SDK:
+// - On 10.11 and later, when linking with the 10.11 SDK, it is called from
+// |magnifyWithEvent:| when the given event's phase is NSEventPhaseEnded.
+// - On 10.10 and earlier, or when linking with an earlier SDK, it is called
+// by |endGestureWithEvent:| when a gesture ends.
+- (void)handleEndGestureWithEvent:(NSEvent*)event;
+
+- (void)setCanBeKeyView:(BOOL)can;
+- (void)setCloseOnDeactivate:(BOOL)b;
+// Inidicate that the client was destroyed and can't be called back into.
+- (void)setClientDisconnected;
+// True for always-on-top special windows (e.g. Balloons and Panels).
+- (BOOL)acceptsMouseEventsWhenInactive;
+// Cancel ongoing composition (abandon the marked text).
+- (void)cancelComposition;
+// Confirm ongoing composition.
+- (void)finishComposingText;
+- (void)updateCursor:(NSCursor*)cursor;
+- (void)tabletEvent:(NSEvent*)theEvent;
+- (void)quickLookWithEvent:(NSEvent*)event;
+- (void)showLookUpDictionaryOverlayFromRange:(NSRange)range;
+- (BOOL)suppressNextKeyUpForTesting:(int)keyCode;
+// Query the display::Display from the view's NSWindow's NSScreen and forward
+// it to the RenderWidgetHostNSViewClient (only if the screen is non-nil).
+- (void)updateScreenProperties;
+// Indicate if the embedding WebContents is showing a web content context menu.
+- (void)setShowingContextMenu:(BOOL)showing;
+// Set the current TextInputManager::TextSelection from the renderer.
+- (void)setTextSelectionText:(base::string16)text
+ offset:(size_t)offset
+ range:(gfx::Range)range;
+- (base::string16)selectedText;
+// Set the current TextInputManager::CompositionRangeInfo from the renderer.
+- (void)setCompositionRange:(gfx::Range)range;
+// Methods previously marked as private.
+- (id)initWithClient:(content::RenderWidgetHostNSViewClient*)client;
+- (void)setResponderDelegate:
+ (NSObject<RenderWidgetHostViewMacDelegate>*)delegate;
+- (void)processedGestureScrollEvent:(const blink::WebGestureEvent&)event
+ consumed:(BOOL)consumed;
+- (void)processedOverscroll:(const ui::DidOverscrollParams&)params;
+@end
+
+#endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_VIEW_COCOA_H_
diff --git a/chromium/content/browser/renderer_host/render_widget_host_view_cocoa.mm b/chromium/content/browser/renderer_host/render_widget_host_view_cocoa.mm
new file mode 100644
index 00000000000..8ee84cdafbd
--- /dev/null
+++ b/chromium/content/browser/renderer_host/render_widget_host_view_cocoa.mm
@@ -0,0 +1,1878 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#import "content/browser/renderer_host/render_widget_host_view_cocoa.h"
+
+#include <limits>
+#include <utility>
+
+#include "base/debug/crash_logging.h"
+#include "base/mac/bind_objc_block.h"
+#include "base/mac/mac_util.h"
+#include "base/strings/sys_string_conversions.h"
+#import "content/browser/accessibility/browser_accessibility_cocoa.h"
+#import "content/browser/accessibility/browser_accessibility_mac.h"
+#include "content/browser/accessibility/browser_accessibility_manager_mac.h"
+#import "content/browser/cocoa/system_hotkey_helper_mac.h"
+#import "content/browser/cocoa/system_hotkey_map.h"
+#include "content/browser/renderer_host/input/web_input_event_builders_mac.h"
+#include "content/browser/renderer_host/render_widget_host_view_mac.h"
+#import "content/browser/renderer_host/render_widget_host_view_mac_editcommand_helper.h"
+#import "content/public/browser/render_widget_host_view_mac_delegate.h"
+#import "ui/base/clipboard/clipboard_util_mac.h"
+#import "ui/base/cocoa/appkit_utils.h"
+#include "ui/base/cocoa/cocoa_base_utils.h"
+#include "ui/display/screen.h"
+#include "ui/events/event_utils.h"
+#include "ui/gfx/mac/coordinate_conversion.h"
+
+using content::BrowserAccessibility;
+using content::BrowserAccessibilityManager;
+using content::EditCommand;
+using content::NativeWebKeyboardEvent;
+using content::RenderWidgetHostNSViewClient;
+using content::RenderWidgetHostViewMacEditCommandHelper;
+using content::WebGestureEventBuilder;
+using content::WebMouseEventBuilder;
+using content::WebMouseWheelEventBuilder;
+using blink::WebInputEvent;
+using blink::WebMouseEvent;
+using blink::WebMouseWheelEvent;
+using blink::WebGestureEvent;
+
+namespace {
+
+// No-op client used to avoid scattering of nullptr checks (see comments in
+// the client_ member of RenderWidgetHostViewCocoa).
+class NoopClient : public RenderWidgetHostNSViewClient {
+ public:
+ NoopClient() {}
+ ~NoopClient() override{};
+
+ // RenderWidgetHostNSViewClient implementation:
+ BrowserAccessibilityManager* GetRootBrowserAccessibilityManager() override {
+ return nullptr;
+ }
+ void OnNSViewSyncIsRenderViewHost(bool* is_render_view) override {}
+ void OnNSViewRequestShutdown() override {}
+ void OnNSViewIsFirstResponderChanged(bool is_first_responder) override {}
+ void OnNSViewWindowIsKeyChanged(bool is_key) override {}
+ void OnNSViewBoundsInWindowChanged(const gfx::Rect& view_bounds_in_window_dip,
+ bool attached_to_window) override {}
+ void OnNSViewWindowFrameInScreenChanged(
+ const gfx::Rect& window_frame_in_screen_dip) override {}
+ void OnNSViewDisplayChanged(const display::Display& display) override {}
+ void OnNSViewBeginKeyboardEvent() override {}
+ void OnNSViewEndKeyboardEvent() override {}
+ void OnNSViewForwardKeyboardEvent(
+ const NativeWebKeyboardEvent& key_event,
+ const ui::LatencyInfo& latency_info) override {}
+ void OnNSViewForwardKeyboardEventWithCommands(
+ const NativeWebKeyboardEvent& key_event,
+ const ui::LatencyInfo& latency_info,
+ const std::vector<EditCommand>& commands) override {}
+ void OnNSViewRouteOrProcessMouseEvent(
+ const blink::WebMouseEvent& web_event) override {}
+ void OnNSViewRouteOrProcessWheelEvent(
+ const blink::WebMouseWheelEvent& web_event) override {}
+ void OnNSViewForwardMouseEvent(
+ const blink::WebMouseEvent& web_event) override {}
+ void OnNSViewForwardWheelEvent(
+ const blink::WebMouseWheelEvent& web_event) override {}
+ void OnNSViewGestureBegin(blink::WebGestureEvent begin_event) override {}
+ void OnNSViewGestureUpdate(blink::WebGestureEvent update_event) override {}
+ void OnNSViewGestureEnd(blink::WebGestureEvent end_event) override {}
+ void OnNSViewSmartMagnify(
+ const blink::WebGestureEvent& smart_magnify_event) override {}
+ void OnNSViewImeSetComposition(
+ const base::string16& text,
+ const std::vector<ui::ImeTextSpan>& ime_text_spans,
+ const gfx::Range& replacement_range,
+ int selection_start,
+ int selection_end) override {}
+ void OnNSViewImeCommitText(const base::string16& text,
+ const gfx::Range& replacement_range) override {}
+ void OnNSViewImeFinishComposingText() override {}
+ void OnNSViewImeCancelComposition() override {}
+ void OnNSViewLookUpDictionaryOverlayAtPoint(
+ const gfx::PointF& root_point) override {}
+ void OnNSViewLookUpDictionaryOverlayFromRange(
+ const gfx::Range& range) override {}
+ void OnNSViewSyncGetTextInputType(
+ ui::TextInputType* text_input_type) override {}
+ void OnNSViewSyncGetCharacterIndexAtPoint(const gfx::PointF& root_point,
+ uint32_t* index) override {}
+ void OnNSViewSyncGetFirstRectForRange(const gfx::Range& requested_range,
+ gfx::Rect* rect,
+ gfx::Range* actual_range,
+ bool* success) override {}
+ void OnNSViewExecuteEditCommand(const std::string& command) override {}
+ void OnNSViewUndo() override {}
+ void OnNSViewRedo() override {}
+ void OnNSViewCut() override {}
+ void OnNSViewCopy() override {}
+ void OnNSViewCopyToFindPboard() override {}
+ void OnNSViewPaste() override {}
+ void OnNSViewPasteAndMatchStyle() override {}
+ void OnNSViewSelectAll() override {}
+ void OnNSViewSpeakSelection() override {}
+ void OnNSViewStopSpeaking() override {}
+ void OnNSViewSyncIsSpeaking(bool* is_speaking) override {}
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(NoopClient);
+};
+
+// Whether a keyboard event has been reserved by OSX.
+BOOL EventIsReservedBySystem(NSEvent* event) {
+ content::SystemHotkeyHelperMac* helper =
+ content::SystemHotkeyHelperMac::GetInstance();
+ return helper->map()->IsEventReserved(event);
+}
+
+// TODO(suzhe): Upstream this function.
+blink::WebColor WebColorFromNSColor(NSColor* color) {
+ CGFloat r, g, b, a;
+ [color getRed:&r green:&g blue:&b alpha:&a];
+
+ return std::max(0, std::min(static_cast<int>(lroundf(255.0f * a)), 255))
+ << 24 |
+ std::max(0, std::min(static_cast<int>(lroundf(255.0f * r)), 255))
+ << 16 |
+ std::max(0, std::min(static_cast<int>(lroundf(255.0f * g)), 255))
+ << 8 |
+ std::max(0, std::min(static_cast<int>(lroundf(255.0f * b)), 255));
+}
+
+// Extract underline information from an attributed string. Mostly copied from
+// third_party/WebKit/Source/WebKit/mac/WebView/WebHTMLView.mm
+void ExtractUnderlines(NSAttributedString* string,
+ std::vector<ui::ImeTextSpan>* ime_text_spans) {
+ int length = [[string string] length];
+ int i = 0;
+ while (i < length) {
+ NSRange range;
+ NSDictionary* attrs = [string attributesAtIndex:i
+ longestEffectiveRange:&range
+ inRange:NSMakeRange(i, length - i)];
+ if (NSNumber* style = [attrs objectForKey:NSUnderlineStyleAttributeName]) {
+ blink::WebColor color = SK_ColorBLACK;
+ if (NSColor* colorAttr =
+ [attrs objectForKey:NSUnderlineColorAttributeName]) {
+ color = WebColorFromNSColor(
+ [colorAttr colorUsingColorSpaceName:NSDeviceRGBColorSpace]);
+ }
+ ui::ImeTextSpan::Thickness thickness =
+ [style intValue] > 1 ? ui::ImeTextSpan::Thickness::kThick
+ : ui::ImeTextSpan::Thickness::kThin;
+ ui::ImeTextSpan ui_ime_text_span =
+ ui::ImeTextSpan(ui::ImeTextSpan::Type::kComposition, range.location,
+ NSMaxRange(range), thickness, SK_ColorTRANSPARENT);
+ ui_ime_text_span.underline_color = color;
+ ime_text_spans->push_back(ui_ime_text_span);
+ }
+ i = range.location + range.length;
+ }
+}
+
+} // namespace
+
+// These are not documented, so use only after checking -respondsToSelector:.
+@interface NSApplication (UndocumentedSpeechMethods)
+- (void)speakString:(NSString*)string;
+- (void)stopSpeaking:(id)sender;
+- (BOOL)isSpeaking;
+@end
+
+// RenderWidgetHostViewCocoa ---------------------------------------------------
+
+// Private methods:
+@interface RenderWidgetHostViewCocoa ()
+- (void)processedWheelEvent:(const blink::WebMouseWheelEvent&)event
+ consumed:(BOOL)consumed;
+- (void)keyEvent:(NSEvent*)theEvent wasKeyEquivalent:(BOOL)equiv;
+- (void)windowDidChangeBackingProperties:(NSNotification*)notification;
+- (void)windowChangedGlobalFrame:(NSNotification*)notification;
+- (void)windowDidBecomeKey:(NSNotification*)notification;
+- (void)windowDidResignKey:(NSNotification*)notification;
+- (void)sendViewBoundsInWindowToClient;
+- (void)sendWindowFrameInScreenToClient;
+- (bool)clientIsDisconnected;
+@end
+
+@implementation RenderWidgetHostViewCocoa
+@synthesize markedRange = markedRange_;
+
+- (id)initWithClient:(RenderWidgetHostNSViewClient*)client {
+ self = [super initWithFrame:NSZeroRect];
+ if (self) {
+ self.acceptsTouchEvents = YES;
+ editCommandHelper_.reset(new RenderWidgetHostViewMacEditCommandHelper);
+ editCommandHelper_->AddEditingSelectorsToClass([self class]);
+
+ noopClient_ = std::make_unique<NoopClient>();
+ client_ = client;
+ canBeKeyView_ = YES;
+ isStylusEnteringProximity_ = false;
+ }
+ return self;
+}
+
+- (void)dealloc {
+ DCHECK([self clientIsDisconnected]);
+ [[NSNotificationCenter defaultCenter] removeObserver:self];
+
+ // Update and cache the new input context. Otherwise,
+ // [NSTextInputContext currentInputContext] might still hold on to this
+ // view's NSTextInputContext even after it's deallocated.
+ // See http://crbug.com/684388.
+ [[self window] makeFirstResponder:nil];
+ [NSApp updateWindows];
+
+ // Debug key to check if the current input context still holds onto the view.
+ NSTextInputContext* currentContext = [NSTextInputContext currentInputContext];
+ auto* crashKey = base::debug::AllocateCrashKeyString(
+ "text-input-context-client", base::debug::CrashKeySize::Size32);
+ base::debug::ScopedCrashKeyString textInputContextCrashKey(
+ crashKey, currentContext && [currentContext client] == self
+ ? "text input still held on"
+ : "text input no longer held on");
+
+ [super dealloc];
+}
+
+- (void)sendViewBoundsInWindowToClient {
+ TRACE_EVENT0("browser",
+ "RenderWidgetHostViewCocoa::sendViewBoundsInWindowToClient");
+ if (inSetFrame_)
+ return;
+
+ NSRect viewBoundsInView = [self bounds];
+ NSWindow* enclosingWindow = [self window];
+ if (!enclosingWindow) {
+ client_->OnNSViewBoundsInWindowChanged(gfx::Rect(viewBoundsInView), false);
+ return;
+ }
+
+ NSRect viewBoundsInWindow = [self convertRect:viewBoundsInView toView:nil];
+ gfx::Rect gfxViewBoundsInWindow(viewBoundsInWindow);
+ gfxViewBoundsInWindow.set_y(NSHeight([enclosingWindow frame]) -
+ NSMaxY(viewBoundsInWindow));
+ client_->OnNSViewBoundsInWindowChanged(gfxViewBoundsInWindow, true);
+}
+
+- (void)setTextSelectionText:(base::string16)text
+ offset:(size_t)offset
+ range:(gfx::Range)range {
+ textSelectionText_ = text;
+ textSelectionOffset_ = offset;
+ textSelectionRange_ = range;
+}
+
+- (base::string16)selectedText {
+ gfx::Range textRange(textSelectionOffset_,
+ textSelectionOffset_ + textSelectionText_.size());
+ gfx::Range intersectionRange = textRange.Intersect(textSelectionRange_);
+ if (intersectionRange.is_empty())
+ return base::string16();
+ return textSelectionText_.substr(
+ intersectionRange.start() - textSelectionOffset_,
+ intersectionRange.length());
+}
+
+- (void)setCompositionRange:(gfx::Range)range {
+ compositionRange_ = range;
+}
+
+- (void)sendWindowFrameInScreenToClient {
+ TRACE_EVENT0("browser",
+ "RenderWidgetHostViewCocoa::sendWindowFrameInScreenToClient");
+ NSWindow* enclosingWindow = [self window];
+ if (!enclosingWindow)
+ return;
+ client_->OnNSViewWindowFrameInScreenChanged(
+ gfx::ScreenRectFromNSRect([enclosingWindow frame]));
+}
+
+- (void)setResponderDelegate:
+ (NSObject<RenderWidgetHostViewMacDelegate>*)delegate {
+ DCHECK(!responderDelegate_);
+ responderDelegate_.reset([delegate retain]);
+}
+
+- (void)resetCursorRects {
+ if (currentCursor_) {
+ [self addCursorRect:[self visibleRect] cursor:currentCursor_];
+ [currentCursor_ setOnMouseEntered:YES];
+ }
+}
+
+- (void)processedWheelEvent:(const blink::WebMouseWheelEvent&)event
+ consumed:(BOOL)consumed {
+ [responderDelegate_ rendererHandledWheelEvent:event consumed:consumed];
+}
+
+- (void)processedGestureScrollEvent:(const blink::WebGestureEvent&)event
+ consumed:(BOOL)consumed {
+ [responderDelegate_ rendererHandledGestureScrollEvent:event
+ consumed:consumed];
+}
+
+- (void)processedOverscroll:(const ui::DidOverscrollParams&)params {
+ [responderDelegate_ rendererHandledOverscrollEvent:params];
+}
+
+- (BOOL)respondsToSelector:(SEL)selector {
+ // Trickiness: this doesn't mean "does this object's superclass respond to
+ // this selector" but rather "does the -respondsToSelector impl from the
+ // superclass say that this class responds to the selector".
+ if ([super respondsToSelector:selector])
+ return YES;
+
+ if (responderDelegate_)
+ return [responderDelegate_ respondsToSelector:selector];
+
+ return NO;
+}
+
+- (id)forwardingTargetForSelector:(SEL)selector {
+ if ([responderDelegate_ respondsToSelector:selector])
+ return responderDelegate_.get();
+
+ return [super forwardingTargetForSelector:selector];
+}
+
+- (void)setCanBeKeyView:(BOOL)can {
+ canBeKeyView_ = can;
+}
+
+- (BOOL)acceptsMouseEventsWhenInactive {
+ // Some types of windows (balloons, always-on-top panels) want to accept mouse
+ // clicks w/o the first click being treated as 'activation'. Same applies to
+ // mouse move events.
+ return [[self window] level] > NSNormalWindowLevel;
+}
+
+- (BOOL)acceptsFirstMouse:(NSEvent*)theEvent {
+ return [self acceptsMouseEventsWhenInactive];
+}
+
+- (void)setCloseOnDeactivate:(BOOL)b {
+ closeOnDeactivate_ = b;
+}
+
+- (void)setClientDisconnected {
+ client_ = noopClient_.get();
+
+ // |responderDelegate_| may attempt to access the RenderWidgetHostViewMac
+ // through its internal pointers, so detach it here.
+ // TODO(ccameron): Force |responderDelegate_| to use the |client_| as well,
+ // and the viewGone method to clientGone.
+ if (responderDelegate_ &&
+ [responderDelegate_ respondsToSelector:@selector(viewGone:)])
+ [responderDelegate_ viewGone:self];
+ responderDelegate_.reset();
+}
+
+- (bool)clientIsDisconnected {
+ return client_ == noopClient_.get();
+}
+
+- (void)setShowingContextMenu:(BOOL)showing {
+ showingContextMenu_ = showing;
+
+ // Create a fake mouse event to inform the render widget that the mouse
+ // left or entered.
+ NSWindow* window = [self window];
+ int window_number = window ? [window windowNumber] : -1;
+
+ // TODO(asvitkine): If the location outside of the event stream doesn't
+ // correspond to the current event (due to delayed event processing), then
+ // this may result in a cursor flicker if there are later mouse move events
+ // in the pipeline. Find a way to use the mouse location from the event that
+ // dismissed the context menu.
+ NSPoint location = [window mouseLocationOutsideOfEventStream];
+ NSTimeInterval event_time = [[NSApp currentEvent] timestamp];
+ NSEvent* event = [NSEvent mouseEventWithType:NSMouseMoved
+ location:location
+ modifierFlags:0
+ timestamp:event_time
+ windowNumber:window_number
+ context:nil
+ eventNumber:0
+ clickCount:0
+ pressure:0];
+ WebMouseEvent web_event = WebMouseEventBuilder::Build(event, self);
+ web_event.SetModifiers(web_event.GetModifiers() |
+ WebInputEvent::kRelativeMotionEvent);
+ client_->OnNSViewForwardMouseEvent(web_event);
+}
+
+- (BOOL)shouldIgnoreMouseEvent:(NSEvent*)theEvent {
+ NSWindow* window = [self window];
+ // If this is a background window, don't handle mouse movement events. This
+ // is the expected behavior on the Mac as evidenced by other applications.
+ if ([theEvent type] == NSMouseMoved &&
+ ![self acceptsMouseEventsWhenInactive] && ![window isKeyWindow]) {
+ return YES;
+ }
+
+ // Use hitTest to check whether the mouse is over a nonWebContentView - in
+ // which case the mouse event should not be handled by the render host.
+ const SEL nonWebContentViewSelector = @selector(nonWebContentView);
+ NSView* contentView = [window contentView];
+ NSView* view = [contentView hitTest:[theEvent locationInWindow]];
+ // Traverse the superview hierarchy as the hitTest will return the frontmost
+ // view, such as an NSTextView, while nonWebContentView may be specified by
+ // its parent view.
+ while (view) {
+ if ([view respondsToSelector:nonWebContentViewSelector] &&
+ [view performSelector:nonWebContentViewSelector]) {
+ // The cursor is over a nonWebContentView - ignore this mouse event.
+ return YES;
+ }
+ if ([view isKindOfClass:[self class]] && ![view isEqual:self] &&
+ !hasOpenMouseDown_) {
+ // The cursor is over an overlapping render widget. This check is done by
+ // both views so the one that's returned by -hitTest: will end up
+ // processing the event.
+ // Note that while dragging, we only get events for the render view where
+ // drag started, even if mouse is actually over another view or outside
+ // the window. Cocoa does this for us. We should handle these events and
+ // not ignore (since there is no other render view to handle them). Thus
+ // the |!hasOpenMouseDown_| check above.
+ return YES;
+ }
+ view = [view superview];
+ }
+ return NO;
+}
+
+- (void)mouseEvent:(NSEvent*)theEvent {
+ TRACE_EVENT0("browser", "RenderWidgetHostViewCocoa::mouseEvent");
+ if (responderDelegate_ &&
+ [responderDelegate_ respondsToSelector:@selector(handleEvent:)]) {
+ BOOL handled = [responderDelegate_ handleEvent:theEvent];
+ if (handled)
+ return;
+ }
+
+ // Set the pointer type when we are receiving a NSMouseEntered event and the
+ // following NSMouseExited event should have the same pointer type.
+ // For NSMouseExited and NSMouseEntered events, they do not have a subtype.
+ // We decide their pointer types by checking if we recevied a
+ // NSTabletProximity event.
+ NSEventType type = [theEvent type];
+ if (type == NSMouseEntered || type == NSMouseExited) {
+ pointerType_ = isStylusEnteringProximity_
+ ? pointerType_
+ : blink::WebPointerProperties::PointerType::kMouse;
+ } else {
+ NSEventSubtype subtype = [theEvent subtype];
+ // For other mouse events and touchpad events, the pointer type is mouse.
+ if (subtype != NSTabletPointEventSubtype &&
+ subtype != NSTabletProximityEventSubtype) {
+ pointerType_ = blink::WebPointerProperties::PointerType::kMouse;
+ }
+ }
+
+ if ([self shouldIgnoreMouseEvent:theEvent]) {
+ // If this is the first such event, send a mouse exit to the host view.
+ if (!mouseEventWasIgnored_) {
+ WebMouseEvent exitEvent =
+ WebMouseEventBuilder::Build(theEvent, self, pointerType_);
+ exitEvent.SetType(WebInputEvent::kMouseLeave);
+ exitEvent.button = WebMouseEvent::Button::kNoButton;
+ client_->OnNSViewForwardMouseEvent(exitEvent);
+ }
+ mouseEventWasIgnored_ = YES;
+ return;
+ }
+
+ if (mouseEventWasIgnored_) {
+ // If this is the first mouse event after a previous event that was ignored
+ // due to the hitTest, send a mouse enter event to the host view.
+ WebMouseEvent enterEvent =
+ WebMouseEventBuilder::Build(theEvent, self, pointerType_);
+ enterEvent.SetType(WebInputEvent::kMouseMove);
+ enterEvent.button = WebMouseEvent::Button::kNoButton;
+ client_->OnNSViewRouteOrProcessMouseEvent(enterEvent);
+ }
+ mouseEventWasIgnored_ = NO;
+
+ // Don't cancel child popups; killing them on a mouse click would prevent the
+ // user from positioning the insertion point in the text field spawning the
+ // popup. A click outside the text field would cause the text field to drop
+ // the focus, and then EditorClientImpl::textFieldDidEndEditing() would cancel
+ // the popup anyway, so we're OK.
+ if (type == NSLeftMouseDown)
+ hasOpenMouseDown_ = YES;
+ else if (type == NSLeftMouseUp)
+ hasOpenMouseDown_ = NO;
+
+ // TODO(suzhe): We should send mouse events to the input method first if it
+ // wants to handle them. But it won't work without implementing method
+ // - (NSUInteger)characterIndexForPoint:.
+ // See: http://code.google.com/p/chromium/issues/detail?id=47141
+ // Instead of sending mouse events to the input method first, we now just
+ // simply confirm all ongoing composition here.
+ if (type == NSLeftMouseDown || type == NSRightMouseDown ||
+ type == NSOtherMouseDown) {
+ [self finishComposingText];
+ }
+
+ if (type == NSMouseMoved)
+ cursorHidden_ = NO;
+
+ WebMouseEvent event =
+ WebMouseEventBuilder::Build(theEvent, self, pointerType_);
+ client_->OnNSViewRouteOrProcessMouseEvent(event);
+}
+
+- (void)tabletEvent:(NSEvent*)theEvent {
+ if ([theEvent type] == NSTabletProximity) {
+ isStylusEnteringProximity_ = [theEvent isEnteringProximity];
+ NSPointingDeviceType deviceType = [theEvent pointingDeviceType];
+ // For all tablet events, the pointer type will be pen or eraser.
+ pointerType_ = deviceType == NSEraserPointingDevice
+ ? blink::WebPointerProperties::PointerType::kEraser
+ : blink::WebPointerProperties::PointerType::kPen;
+ }
+}
+
+- (BOOL)performKeyEquivalent:(NSEvent*)theEvent {
+ // |performKeyEquivalent:| is sent to all views of a window, not only down the
+ // responder chain (cf. "Handling Key Equivalents" in
+ // http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/EventOverview/HandlingKeyEvents/HandlingKeyEvents.html
+ // ). A |performKeyEquivalent:| may also bubble up from a dialog child window
+ // to perform browser commands such as switching tabs. We only want to handle
+ // key equivalents if we're first responder in the keyWindow.
+ if (![[self window] isKeyWindow] || [[self window] firstResponder] != self)
+ return NO;
+
+ // If the event is reserved by the system, then do not pass it to web content.
+ if (EventIsReservedBySystem(theEvent))
+ return NO;
+
+ // If we return |NO| from this function, cocoa will send the key event to
+ // the menu and only if the menu does not process the event to |keyDown:|. We
+ // want to send the event to a renderer _before_ sending it to the menu, so
+ // we need to return |YES| for all events that might be swallowed by the menu.
+ // We do not return |YES| for every keypress because we don't get |keyDown:|
+ // events for keys that we handle this way.
+ NSUInteger modifierFlags = [theEvent modifierFlags];
+ if ((modifierFlags & NSCommandKeyMask) == 0) {
+ // Make sure the menu does not contain key equivalents that don't
+ // contain cmd.
+ DCHECK(![[NSApp mainMenu] performKeyEquivalent:theEvent]);
+ return NO;
+ }
+
+ // Command key combinations are sent via performKeyEquivalent rather than
+ // keyDown:. We just forward this on and if WebCore doesn't want to handle
+ // it, we let the WebContentsView figure out how to reinject it.
+ [self keyEvent:theEvent wasKeyEquivalent:YES];
+ return YES;
+}
+
+- (BOOL)_wantsKeyDownForEvent:(NSEvent*)event {
+ // This is a SPI that AppKit apparently calls after |performKeyEquivalent:|
+ // returned NO. If this function returns |YES|, Cocoa sends the event to
+ // |keyDown:| instead of doing other things with it. Ctrl-tab will be sent
+ // to us instead of doing key view loop control, ctrl-left/right get handled
+ // correctly, etc.
+ // (However, there are still some keys that Cocoa swallows, e.g. the key
+ // equivalent that Cocoa uses for toggling the input language. In this case,
+ // that's actually a good thing, though -- see http://crbug.com/26115 .)
+ return YES;
+}
+
+- (EventHandled)keyEvent:(NSEvent*)theEvent {
+ if (responderDelegate_ &&
+ [responderDelegate_ respondsToSelector:@selector(handleEvent:)]) {
+ BOOL handled = [responderDelegate_ handleEvent:theEvent];
+ if (handled)
+ return kEventHandled;
+ }
+
+ [self keyEvent:theEvent wasKeyEquivalent:NO];
+ return kEventHandled;
+}
+
+- (void)keyEvent:(NSEvent*)theEvent wasKeyEquivalent:(BOOL)equiv {
+ TRACE_EVENT0("browser", "RenderWidgetHostViewCocoa::keyEvent");
+ NSEventType eventType = [theEvent type];
+ NSEventModifierFlags modifierFlags = [theEvent modifierFlags];
+ int keyCode = [theEvent keyCode];
+
+ // If the user changes the system hotkey mapping after Chrome has been
+ // launched, then it is possible that a formerly reserved system hotkey is no
+ // longer reserved. The hotkey would have skipped the renderer, but would
+ // also have not been handled by the system. If this is the case, immediately
+ // return.
+ // TODO(erikchen): SystemHotkeyHelperMac should use the File System Events
+ // api to monitor changes to system hotkeys. This logic will have to be
+ // updated.
+ // http://crbug.com/383558.
+ if (EventIsReservedBySystem(theEvent))
+ return;
+
+ DCHECK(eventType != NSKeyDown ||
+ !equiv == !(modifierFlags & NSCommandKeyMask));
+
+ if (eventType == NSFlagsChanged) {
+ // Ignore NSFlagsChanged events from the NumLock and Fn keys as
+ // Safari does in -[WebHTMLView flagsChanged:] (of "WebHTMLView.mm").
+ // Also ignore unsupported |keyCode| (255) generated by Convert, NonConvert
+ // and KanaMode from JIS PC keyboard.
+ if (!keyCode || keyCode == 10 || keyCode == 63 || keyCode == 255)
+ return;
+ }
+
+ // Don't cancel child popups; the key events are probably what's triggering
+ // the popup in the first place.
+
+
+ NativeWebKeyboardEvent event(theEvent);
+ ui::LatencyInfo latency_info;
+ if (event.GetType() == blink::WebInputEvent::kRawKeyDown ||
+ event.GetType() == blink::WebInputEvent::kChar) {
+ latency_info.set_source_event_type(ui::SourceEventType::KEY_PRESS);
+ }
+
+ latency_info.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_UI_COMPONENT, 0, 0);
+
+ // Do not forward key up events unless preceded by a matching key down,
+ // otherwise we might get an event from releasing the return key in the
+ // omnibox (https://crbug.com/338736) or from closing another window
+ // (https://crbug.com/155492).
+ if (eventType == NSKeyUp) {
+ auto numErased = keyDownCodes_.erase(keyCode);
+ if (numErased < 1)
+ return;
+ }
+
+ // Tell the client that we are beginning a keyboard event. This ensures that
+ // all event and Ime messages target the same RenderWidgetHost throughout this
+ // function call.
+ client_->OnNSViewBeginKeyboardEvent();
+
+ ui::TextInputType textInputType = ui::TEXT_INPUT_TYPE_NONE;
+ client_->OnNSViewSyncGetTextInputType(&textInputType);
+ bool shouldAutohideCursor = textInputType != ui::TEXT_INPUT_TYPE_NONE &&
+ eventType == NSKeyDown &&
+ !(modifierFlags & NSCommandKeyMask);
+
+ // We only handle key down events and just simply forward other events.
+ if (eventType != NSKeyDown) {
+ client_->OnNSViewForwardKeyboardEvent(event, latency_info);
+
+ // Possibly autohide the cursor.
+ if (shouldAutohideCursor) {
+ [NSCursor setHiddenUntilMouseMoves:YES];
+ cursorHidden_ = YES;
+ }
+
+ client_->OnNSViewEndKeyboardEvent();
+ return;
+ }
+
+ keyDownCodes_.insert(keyCode);
+
+ base::scoped_nsobject<RenderWidgetHostViewCocoa> keepSelfAlive([self retain]);
+
+ // Records the current marked text state, so that we can know if the marked
+ // text was deleted or not after handling the key down event.
+ BOOL oldHasMarkedText = hasMarkedText_;
+
+ // This method should not be called recursively.
+ DCHECK(!handlingKeyDown_);
+
+ // Tells insertText: and doCommandBySelector: that we are handling a key
+ // down event.
+ handlingKeyDown_ = YES;
+
+ // These variables might be set when handling the keyboard event.
+ // Clear them here so that we can know whether they have changed afterwards.
+ textToBeInserted_.clear();
+ markedText_.clear();
+ markedTextSelectedRange_ = NSMakeRange(NSNotFound, 0);
+ ime_text_spans_.clear();
+ setMarkedTextReplacementRange_ = gfx::Range::InvalidRange();
+ unmarkTextCalled_ = NO;
+ hasEditCommands_ = NO;
+ editCommands_.clear();
+
+ // Sends key down events to input method first, then we can decide what should
+ // be done according to input method's feedback.
+ [self interpretKeyEvents:[NSArray arrayWithObject:theEvent]];
+
+ handlingKeyDown_ = NO;
+
+ // Indicates if we should send the key event and corresponding editor commands
+ // after processing the input method result.
+ BOOL delayEventUntilAfterImeCompostion = NO;
+
+ // To emulate Windows, over-write |event.windowsKeyCode| to VK_PROCESSKEY
+ // while an input method is composing or inserting a text.
+ // Gmail checks this code in its onkeydown handler to stop auto-completing
+ // e-mail addresses while composing a CJK text.
+ // If the text to be inserted has only one character, then we don't need this
+ // trick, because we'll send the text as a key press event instead.
+ if (hasMarkedText_ || oldHasMarkedText || textToBeInserted_.length() > 1) {
+ NativeWebKeyboardEvent fakeEvent = event;
+ fakeEvent.windows_key_code = 0xE5; // VKEY_PROCESSKEY
+ fakeEvent.skip_in_browser = true;
+ client_->OnNSViewForwardKeyboardEvent(fakeEvent, latency_info);
+ // If this key event was handled by the input method, but
+ // -doCommandBySelector: (invoked by the call to -interpretKeyEvents: above)
+ // enqueued edit commands, then in order to let webkit handle them
+ // correctly, we need to send the real key event and corresponding edit
+ // commands after processing the input method result.
+ // We shouldn't do this if a new marked text was set by the input method,
+ // otherwise the new marked text might be cancelled by webkit.
+ if (hasEditCommands_ && !hasMarkedText_)
+ delayEventUntilAfterImeCompostion = YES;
+ } else {
+ client_->OnNSViewForwardKeyboardEventWithCommands(event, latency_info,
+ editCommands_);
+ }
+
+ // Then send keypress and/or composition related events.
+ // If there was a marked text or the text to be inserted is longer than 1
+ // character, then we send the text by calling FinishComposingText().
+ // Otherwise, if the text to be inserted only contains 1 character, then we
+ // can just send a keypress event which is fabricated by changing the type of
+ // the keydown event, so that we can retain all necessary informations, such
+ // as unmodifiedText, etc. And we need to set event.skip_in_browser to true to
+ // prevent the browser from handling it again.
+ // Note that, |textToBeInserted_| is a UTF-16 string, but it's fine to only
+ // handle BMP characters here, as we can always insert non-BMP characters as
+ // text.
+ BOOL textInserted = NO;
+ if (textToBeInserted_.length() >
+ ((hasMarkedText_ || oldHasMarkedText) ? 0u : 1u)) {
+ client_->OnNSViewImeCommitText(textToBeInserted_,
+ gfx::Range::InvalidRange());
+ textInserted = YES;
+ }
+
+ // Updates or cancels the composition. If some text has been inserted, then
+ // we don't need to cancel the composition explicitly.
+ if (hasMarkedText_ && markedText_.length()) {
+ // Sends the updated marked text to the renderer so it can update the
+ // composition node in WebKit.
+ // When marked text is available, |markedTextSelectedRange_| will be the
+ // range being selected inside the marked text.
+ client_->OnNSViewImeSetComposition(markedText_, ime_text_spans_,
+ setMarkedTextReplacementRange_,
+ markedTextSelectedRange_.location,
+ NSMaxRange(markedTextSelectedRange_));
+ } else if (oldHasMarkedText && !hasMarkedText_ && !textInserted) {
+ if (unmarkTextCalled_) {
+ client_->OnNSViewImeFinishComposingText();
+ } else {
+ client_->OnNSViewImeCancelComposition();
+ }
+ }
+
+ // Clear information from |interpretKeyEvents:|
+ setMarkedTextReplacementRange_ = gfx::Range::InvalidRange();
+
+ // If the key event was handled by the input method but it also generated some
+ // edit commands, then we need to send the real key event and corresponding
+ // edit commands here. This usually occurs when the input method wants to
+ // finish current composition session but still wants the application to
+ // handle the key event. See http://crbug.com/48161 for reference.
+ if (delayEventUntilAfterImeCompostion) {
+ // If |delayEventUntilAfterImeCompostion| is YES, then a fake key down event
+ // with windowsKeyCode == 0xE5 has already been sent to webkit.
+ // So before sending the real key down event, we need to send a fake key up
+ // event to balance it.
+ NativeWebKeyboardEvent fakeEvent = event;
+ fakeEvent.SetType(blink::WebInputEvent::kKeyUp);
+ fakeEvent.skip_in_browser = true;
+ ui::LatencyInfo fake_event_latency_info = latency_info;
+ fake_event_latency_info.set_source_event_type(ui::SourceEventType::OTHER);
+ client_->OnNSViewForwardKeyboardEvent(fakeEvent, fake_event_latency_info);
+ client_->OnNSViewForwardKeyboardEventWithCommands(
+ event, fake_event_latency_info, editCommands_);
+ }
+
+ const NSUInteger kCtrlCmdKeyMask = NSControlKeyMask | NSCommandKeyMask;
+ // Only send a corresponding key press event if there is no marked text.
+ if (!hasMarkedText_) {
+ if (!textInserted && textToBeInserted_.length() == 1) {
+ // If a single character was inserted, then we just send it as a keypress
+ // event.
+ event.SetType(blink::WebInputEvent::kChar);
+ event.text[0] = textToBeInserted_[0];
+ event.text[1] = 0;
+ event.skip_in_browser = true;
+ client_->OnNSViewForwardKeyboardEvent(event, latency_info);
+ } else if ((!textInserted || delayEventUntilAfterImeCompostion) &&
+ event.text[0] != '\0' &&
+ ((modifierFlags & kCtrlCmdKeyMask) ||
+ (hasEditCommands_ && editCommands_.empty()))) {
+ // We don't get insertText: calls if ctrl or cmd is down, or the key event
+ // generates an insert command. So synthesize a keypress event for these
+ // cases, unless the key event generated any other command.
+ event.SetType(blink::WebInputEvent::kChar);
+ event.skip_in_browser = true;
+ client_->OnNSViewForwardKeyboardEvent(event, latency_info);
+ }
+ }
+
+ // Possibly autohide the cursor.
+ if (shouldAutohideCursor) {
+ [NSCursor setHiddenUntilMouseMoves:YES];
+ cursorHidden_ = YES;
+ }
+
+ client_->OnNSViewEndKeyboardEvent();
+}
+
+- (BOOL)suppressNextKeyUpForTesting:(int)keyCode {
+ return keyDownCodes_.count(keyCode) == 0;
+}
+
+- (void)forceTouchEvent:(NSEvent*)theEvent {
+ if (ui::ForceClickInvokesQuickLook())
+ [self quickLookWithEvent:theEvent];
+}
+
+- (void)shortCircuitScrollWheelEvent:(NSEvent*)event {
+ if ([event phase] != NSEventPhaseEnded &&
+ [event phase] != NSEventPhaseCancelled) {
+ return;
+ }
+
+ // History-swiping is not possible if the logic reaches this point.
+ WebMouseWheelEvent webEvent = WebMouseWheelEventBuilder::Build(event, self);
+ webEvent.rails_mode = mouseWheelFilter_.UpdateRailsMode(webEvent);
+ client_->OnNSViewForwardWheelEvent(webEvent);
+
+ if (endWheelMonitor_) {
+ [NSEvent removeMonitor:endWheelMonitor_];
+ endWheelMonitor_ = nil;
+ }
+}
+
+- (void)handleBeginGestureWithEvent:(NSEvent*)event {
+ [responderDelegate_ beginGestureWithEvent:event];
+
+ WebGestureEvent gestureBeginEvent(WebGestureEventBuilder::Build(event, self));
+
+ client_->OnNSViewGestureBegin(gestureBeginEvent);
+}
+
+- (void)handleEndGestureWithEvent:(NSEvent*)event {
+ [responderDelegate_ endGestureWithEvent:event];
+
+ // On macOS 10.11+, the end event has type = NSEventTypeMagnify and phase =
+ // NSEventPhaseEnded. On macOS 10.10 and older, the event has type =
+ // NSEventTypeEndGesture.
+ if ([event type] == NSEventTypeMagnify ||
+ [event type] == NSEventTypeEndGesture) {
+ WebGestureEvent endEvent(WebGestureEventBuilder::Build(event, self));
+ endEvent.SetType(WebInputEvent::kGesturePinchEnd);
+ endEvent.SetSourceDevice(
+ blink::WebGestureDevice::kWebGestureDeviceTouchpad);
+ client_->OnNSViewGestureEnd(endEvent);
+ }
+}
+
+- (void)beginGestureWithEvent:(NSEvent*)event {
+ // This method must be handled when linking with the 10.10 SDK or earlier, or
+ // when the app is running on 10.10 or earlier. In other circumstances, the
+ // event will be handled by |magnifyWithEvent:|, so this method should do
+ // nothing.
+ bool shouldHandle = true;
+#if defined(MAC_OS_X_VERSION_10_11) && \
+ MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_11
+ shouldHandle = base::mac::IsAtMostOS10_10();
+#endif
+
+ if (shouldHandle) {
+ [self handleBeginGestureWithEvent:event];
+ }
+}
+
+- (void)endGestureWithEvent:(NSEvent*)event {
+ // This method must be handled when linking with the 10.10 SDK or earlier, or
+ // when the app is running on 10.10 or earlier. In other circumstances, the
+ // event will be handled by |magnifyWithEvent:|, so this method should do
+ // nothing.
+ bool shouldHandle = true;
+#if defined(MAC_OS_X_VERSION_10_11) && \
+ MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_11
+ shouldHandle = base::mac::IsAtMostOS10_10();
+#endif
+
+ if (shouldHandle) {
+ [self handleEndGestureWithEvent:event];
+ }
+}
+
+- (void)touchesMovedWithEvent:(NSEvent*)event {
+ [responderDelegate_ touchesMovedWithEvent:event];
+}
+
+- (void)touchesBeganWithEvent:(NSEvent*)event {
+ [responderDelegate_ touchesBeganWithEvent:event];
+}
+
+- (void)touchesCancelledWithEvent:(NSEvent*)event {
+ [responderDelegate_ touchesCancelledWithEvent:event];
+}
+
+- (void)touchesEndedWithEvent:(NSEvent*)event {
+ [responderDelegate_ touchesEndedWithEvent:event];
+}
+
+- (void)smartMagnifyWithEvent:(NSEvent*)event {
+ const WebGestureEvent& smartMagnifyEvent =
+ WebGestureEventBuilder::Build(event, self);
+ client_->OnNSViewSmartMagnify(smartMagnifyEvent);
+}
+
+- (void)showLookUpDictionaryOverlayFromRange:(NSRange)range {
+ client_->OnNSViewLookUpDictionaryOverlayFromRange(gfx::Range(range));
+}
+
+// This is invoked only on 10.8 or newer when the user taps a word using
+// three fingers.
+- (void)quickLookWithEvent:(NSEvent*)event {
+ NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
+ gfx::PointF rootPoint(point.x, NSHeight([self frame]) - point.y);
+ client_->OnNSViewLookUpDictionaryOverlayAtPoint(rootPoint);
+}
+
+// This method handles 2 different types of hardware events.
+// (Apple does not distinguish between them).
+// a. Scrolling the middle wheel of a mouse.
+// b. Swiping on the track pad.
+//
+// This method is responsible for 2 types of behavior:
+// a. Scrolling the content of window.
+// b. Navigating forwards/backwards in history.
+//
+// This is a brief description of the logic:
+// 1. If the content can be scrolled, scroll the content.
+// (This requires a roundtrip to blink to determine whether the content
+// can be scrolled.)
+// Once this logic is triggered, the navigate logic cannot be triggered
+// until the gesture finishes.
+// 2. If the user is making a horizontal swipe, start the navigate
+// forward/backwards UI.
+// Once this logic is triggered, the user can either cancel or complete
+// the gesture. If the user completes the gesture, all remaining touches
+// are swallowed, and not allowed to scroll the content. If the user
+// cancels the gesture, all remaining touches are forwarded to the content
+// scroll logic. The user cannot trigger the navigation logic again.
+- (void)scrollWheel:(NSEvent*)event {
+#if defined(MAC_OS_X_VERSION_10_11) && \
+ MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_11
+ // When linking against the 10.11 (or later) SDK and running on 10.11 or
+ // later, check the phase of the event and specially handle the "begin" and
+ // "end" phases.
+ if (base::mac::IsAtLeastOS10_11()) {
+ if (event.phase == NSEventPhaseBegan) {
+ [self handleBeginGestureWithEvent:event];
+ }
+
+ if (event.phase == NSEventPhaseEnded ||
+ event.phase == NSEventPhaseCancelled) {
+ [self handleEndGestureWithEvent:event];
+ }
+ }
+#endif
+
+ if (responderDelegate_ &&
+ [responderDelegate_ respondsToSelector:@selector(handleEvent:)]) {
+ BOOL handled = [responderDelegate_ handleEvent:event];
+ if (handled)
+ return;
+ }
+
+ // Compute Event.Latency.OS.MOUSE_WHEEL histogram.
+ ui::ComputeEventLatencyOS(event);
+
+ // Use an NSEvent monitor to listen for the wheel-end end. This ensures that
+ // the event is received even when the mouse cursor is no longer over the view
+ // when the scrolling ends (e.g. if the tab was switched). This is necessary
+ // for ending rubber-banding in such cases.
+ if ([event phase] == NSEventPhaseBegan && !endWheelMonitor_) {
+ endWheelMonitor_ = [NSEvent
+ addLocalMonitorForEventsMatchingMask:NSScrollWheelMask
+ handler:^(NSEvent* blockEvent) {
+ [self shortCircuitScrollWheelEvent:
+ blockEvent];
+ return blockEvent;
+ }];
+ }
+
+ // This is responsible for content scrolling!
+ WebMouseWheelEvent webEvent = WebMouseWheelEventBuilder::Build(event, self);
+ webEvent.rails_mode = mouseWheelFilter_.UpdateRailsMode(webEvent);
+ client_->OnNSViewRouteOrProcessWheelEvent(webEvent);
+}
+
+// Called repeatedly during a pinch gesture, with incremental change values.
+- (void)magnifyWithEvent:(NSEvent*)event {
+#if defined(MAC_OS_X_VERSION_10_11) && \
+ MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_11
+ // When linking against the 10.11 (or later) SDK and running on 10.11 or
+ // later, check the phase of the event and specially handle the "begin" and
+ // "end" phases.
+ if (base::mac::IsAtLeastOS10_11()) {
+ if (event.phase == NSEventPhaseBegan) {
+ [self handleBeginGestureWithEvent:event];
+ return;
+ }
+
+ if (event.phase == NSEventPhaseEnded ||
+ event.phase == NSEventPhaseCancelled) {
+ [self handleEndGestureWithEvent:event];
+ return;
+ }
+ }
+#endif
+
+ // If this conditional evalutes to true, and the function has not
+ // short-circuited from the previous block, then this event is a duplicate of
+ // a gesture event, and should be ignored.
+ if (event.phase == NSEventPhaseBegan || event.phase == NSEventPhaseEnded ||
+ event.phase == NSEventPhaseCancelled) {
+ return;
+ }
+
+ WebGestureEvent updateEvent = WebGestureEventBuilder::Build(event, self);
+ client_->OnNSViewGestureUpdate(updateEvent);
+}
+
+- (void)viewWillMoveToWindow:(NSWindow*)newWindow {
+ NSWindow* oldWindow = [self window];
+
+ NSNotificationCenter* notificationCenter =
+ [NSNotificationCenter defaultCenter];
+
+ if (oldWindow) {
+ [notificationCenter
+ removeObserver:self
+ name:NSWindowDidChangeBackingPropertiesNotification
+ object:oldWindow];
+ [notificationCenter removeObserver:self
+ name:NSWindowDidMoveNotification
+ object:oldWindow];
+ [notificationCenter removeObserver:self
+ name:NSWindowDidResizeNotification
+ object:oldWindow];
+ [notificationCenter removeObserver:self
+ name:NSWindowDidBecomeKeyNotification
+ object:oldWindow];
+ [notificationCenter removeObserver:self
+ name:NSWindowDidResignKeyNotification
+ object:oldWindow];
+ }
+ if (newWindow) {
+ [notificationCenter
+ addObserver:self
+ selector:@selector(windowDidChangeBackingProperties:)
+ name:NSWindowDidChangeBackingPropertiesNotification
+ object:newWindow];
+ [notificationCenter addObserver:self
+ selector:@selector(windowChangedGlobalFrame:)
+ name:NSWindowDidMoveNotification
+ object:newWindow];
+ [notificationCenter addObserver:self
+ selector:@selector(windowChangedGlobalFrame:)
+ name:NSWindowDidResizeNotification
+ object:newWindow];
+ [notificationCenter addObserver:self
+ selector:@selector(windowDidBecomeKey:)
+ name:NSWindowDidBecomeKeyNotification
+ object:newWindow];
+ [notificationCenter addObserver:self
+ selector:@selector(windowDidResignKey:)
+ name:NSWindowDidResignKeyNotification
+ object:newWindow];
+ }
+
+ [self sendWindowFrameInScreenToClient];
+}
+
+- (void)updateScreenProperties {
+ NSWindow* enclosingWindow = [self window];
+ if (!enclosingWindow)
+ return;
+
+ // TODO(ccameron): This will call [enclosingWindow screen], which may return
+ // nil. Do that call here to avoid sending bogus display info to the client.
+ display::Display display =
+ display::Screen::GetScreen()->GetDisplayNearestView(self);
+ client_->OnNSViewDisplayChanged(display);
+}
+
+// This will be called when the NSView's NSWindow moves from one NSScreen to
+// another, and makes note of the new screen's color space, scale factor, etc.
+// It is also called when the current NSScreen's properties change (which is
+// redundant with display::DisplayObserver::OnDisplayMetricsChanged).
+- (void)windowDidChangeBackingProperties:(NSNotification*)notification {
+ // Delay calling updateScreenProperties so that display::ScreenMac can
+ // update our display::Displays first (if applicable).
+ [self performSelector:@selector(updateScreenProperties)
+ withObject:nil
+ afterDelay:0];
+}
+
+- (void)windowChangedGlobalFrame:(NSNotification*)notification {
+ [self sendWindowFrameInScreenToClient];
+ // Update the view bounds relative to the window, as they may have changed
+ // during layout, and we don't explicitly listen for re-layout of parent
+ // views.
+ [self sendViewBoundsInWindowToClient];
+}
+
+- (void)setFrame:(NSRect)r {
+ // Note that -setFrame: calls through -setFrameSize: and -setFrameOrigin. To
+ // avoid spamming the client with transiently invalid states, only send one
+ // message at the end.
+ inSetFrame_ = YES;
+ [super setFrame:r];
+ inSetFrame_ = NO;
+ [self sendViewBoundsInWindowToClient];
+}
+
+- (void)setFrameOrigin:(NSPoint)newOrigin {
+ [super setFrameOrigin:newOrigin];
+ [self sendViewBoundsInWindowToClient];
+}
+
+- (void)setFrameSize:(NSSize)newSize {
+ [super setFrameSize:newSize];
+ [self sendViewBoundsInWindowToClient];
+}
+
+- (BOOL)canBecomeKeyView {
+ if ([self clientIsDisconnected])
+ return NO;
+
+ return canBeKeyView_;
+}
+
+- (BOOL)acceptsFirstResponder {
+ if ([self clientIsDisconnected])
+ return NO;
+
+ return canBeKeyView_;
+}
+
+- (void)windowDidBecomeKey:(NSNotification*)notification {
+ DCHECK([self window]);
+ DCHECK_EQ([self window], [notification object]);
+ if ([responderDelegate_ respondsToSelector:@selector(windowDidBecomeKey)])
+ [responderDelegate_ windowDidBecomeKey];
+ if ([self window].isKeyWindow && [[self window] firstResponder] == self)
+ client_->OnNSViewWindowIsKeyChanged(true);
+}
+
+- (void)windowDidResignKey:(NSNotification*)notification {
+ DCHECK([self window]);
+ DCHECK_EQ([self window], [notification object]);
+
+ // If our app is still active and we're still the key window, ignore this
+ // message, since it just means that a menu extra (on the "system status bar")
+ // was activated; we'll get another |-windowDidResignKey| if we ever really
+ // lose key window status.
+ if ([NSApp isActive] && ([NSApp keyWindow] == [self window]))
+ return;
+
+ if ([[self window] firstResponder] == self)
+ client_->OnNSViewWindowIsKeyChanged(false);
+}
+
+- (BOOL)becomeFirstResponder {
+ if ([self clientIsDisconnected])
+ return NO;
+ if ([responderDelegate_ respondsToSelector:@selector(becomeFirstResponder)])
+ [responderDelegate_ becomeFirstResponder];
+
+ client_->OnNSViewIsFirstResponderChanged(true);
+
+ // Cancel any onging composition text which was left before we lost focus.
+ // TODO(suzhe): We should do it in -resignFirstResponder: method, but
+ // somehow that method won't be called when switching among different tabs.
+ // See http://crbug.com/47209
+ [self cancelComposition];
+
+ NSNumber* direction = [NSNumber
+ numberWithUnsignedInteger:[[self window] keyViewSelectionDirection]];
+ NSDictionary* userInfo =
+ [NSDictionary dictionaryWithObject:direction forKey:kSelectionDirection];
+ [[NSNotificationCenter defaultCenter]
+ postNotificationName:kViewDidBecomeFirstResponder
+ object:self
+ userInfo:userInfo];
+
+ return YES;
+}
+
+- (BOOL)resignFirstResponder {
+ if ([responderDelegate_ respondsToSelector:@selector(resignFirstResponder)])
+ [responderDelegate_ resignFirstResponder];
+
+ client_->OnNSViewIsFirstResponderChanged(false);
+ if (closeOnDeactivate_) {
+ [self setHidden:YES];
+ client_->OnNSViewRequestShutdown();
+ }
+
+ // We should cancel any onging composition whenever RWH's Blur() method gets
+ // called, because in this case, webkit will confirm the ongoing composition
+ // internally.
+ [self cancelComposition];
+
+ return YES;
+}
+
+- (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
+ if (responderDelegate_ &&
+ [responderDelegate_ respondsToSelector:@selector
+ (validateUserInterfaceItem:isValidItem:)]) {
+ BOOL valid;
+ BOOL known =
+ [responderDelegate_ validateUserInterfaceItem:item isValidItem:&valid];
+ if (known)
+ return valid;
+ }
+
+ bool is_render_view = false;
+ client_->OnNSViewSyncIsRenderViewHost(&is_render_view);
+
+ bool is_speaking = false;
+ client_->OnNSViewSyncIsSpeaking(&is_speaking);
+
+ SEL action = [item action];
+
+ if (action == @selector(stopSpeaking:))
+ return is_render_view && is_speaking;
+
+ if (action == @selector(startSpeaking:))
+ return is_render_view;
+
+ // For now, these actions are always enabled for render view,
+ // this is sub-optimal.
+ // TODO(suzhe): Plumb the "can*" methods up from WebCore.
+ if (action == @selector(undo:) || action == @selector(redo:) ||
+ action == @selector(cut:) || action == @selector(copy:) ||
+ action == @selector(copyToFindPboard:) || action == @selector(paste:) ||
+ action == @selector(pasteAndMatchStyle:)) {
+ return is_render_view;
+ }
+
+ return editCommandHelper_->IsMenuItemEnabled(action, self);
+}
+
+- (RenderWidgetHostNSViewClient*)renderWidgetHostNSViewClient {
+ return client_;
+}
+
+- (NSArray*)accessibilityArrayAttributeValues:(NSString*)attribute
+ index:(NSUInteger)index
+ maxCount:(NSUInteger)maxCount {
+ NSArray* fullArray = [self accessibilityAttributeValue:attribute];
+ NSUInteger totalLength = [fullArray count];
+ if (index >= totalLength)
+ return nil;
+ NSUInteger length = MIN(totalLength - index, maxCount);
+ return [fullArray subarrayWithRange:NSMakeRange(index, length)];
+}
+
+- (NSUInteger)accessibilityArrayAttributeCount:(NSString*)attribute {
+ NSArray* fullArray = [self accessibilityAttributeValue:attribute];
+ return [fullArray count];
+}
+
+- (id)accessibilityAttributeValue:(NSString*)attribute {
+ BrowserAccessibilityManager* manager =
+ client_->GetRootBrowserAccessibilityManager();
+
+ // Contents specifies document view of RenderWidgetHostViewCocoa provided by
+ // BrowserAccessibilityManager. Children includes all subviews in addition to
+ // contents. Currently we do not have subviews besides the document view.
+ if (([attribute isEqualToString:NSAccessibilityChildrenAttribute] ||
+ [attribute isEqualToString:NSAccessibilityContentsAttribute]) &&
+ manager) {
+ return [NSArray
+ arrayWithObjects:ToBrowserAccessibilityCocoa(manager->GetRoot()), nil];
+ } else if ([attribute isEqualToString:NSAccessibilityRoleAttribute]) {
+ return NSAccessibilityScrollAreaRole;
+ }
+ id ret = [super accessibilityAttributeValue:attribute];
+ return ret;
+}
+
+- (NSArray*)accessibilityAttributeNames {
+ NSMutableArray* ret = [[[NSMutableArray alloc] init] autorelease];
+ [ret addObject:NSAccessibilityContentsAttribute];
+ [ret addObjectsFromArray:[super accessibilityAttributeNames]];
+ return ret;
+}
+
+- (id)accessibilityHitTest:(NSPoint)point {
+ BrowserAccessibilityManager* manager =
+ client_->GetRootBrowserAccessibilityManager();
+ if (!manager)
+ return self;
+ NSPoint pointInWindow =
+ ui::ConvertPointFromScreenToWindow([self window], point);
+ NSPoint localPoint = [self convertPoint:pointInWindow fromView:nil];
+ localPoint.y = NSHeight([self bounds]) - localPoint.y;
+ BrowserAccessibilityCocoa* root =
+ ToBrowserAccessibilityCocoa(manager->GetRoot());
+ id obj = [root accessibilityHitTest:localPoint];
+ return obj;
+}
+
+- (BOOL)accessibilityIsIgnored {
+ BrowserAccessibilityManager* manager =
+ client_->GetRootBrowserAccessibilityManager();
+ return !manager;
+}
+
+- (NSUInteger)accessibilityGetIndexOf:(id)child {
+ BrowserAccessibilityManager* manager =
+ client_->GetRootBrowserAccessibilityManager();
+ // Only child is root.
+ if (manager && ToBrowserAccessibilityCocoa(manager->GetRoot()) == child) {
+ return 0;
+ } else {
+ return NSNotFound;
+ }
+}
+
+- (id)accessibilityFocusedUIElement {
+ BrowserAccessibilityManager* manager =
+ client_->GetRootBrowserAccessibilityManager();
+ if (manager) {
+ BrowserAccessibility* focused_item = manager->GetFocus();
+ DCHECK(focused_item);
+ if (focused_item) {
+ BrowserAccessibilityCocoa* focused_item_cocoa =
+ ToBrowserAccessibilityCocoa(focused_item);
+ DCHECK(focused_item_cocoa);
+ if (focused_item_cocoa)
+ return focused_item_cocoa;
+ }
+ }
+ return [super accessibilityFocusedUIElement];
+}
+
+// Below is our NSTextInputClient implementation.
+//
+// When WebHTMLView receives a NSKeyDown event, WebHTMLView calls the following
+// functions to process this event.
+//
+// [WebHTMLView keyDown] ->
+// EventHandler::keyEvent() ->
+// ...
+// [WebEditorClient handleKeyboardEvent] ->
+// [WebHTMLView _interceptEditingKeyEvent] ->
+// [NSResponder interpretKeyEvents] ->
+// [WebHTMLView insertText] ->
+// Editor::insertText()
+//
+// Unfortunately, it is hard for Chromium to use this implementation because
+// it causes key-typing jank.
+// RenderWidgetHostViewMac is running in a browser process. On the other
+// hand, Editor and EventHandler are running in a renderer process.
+// So, if we used this implementation, a NSKeyDown event is dispatched to
+// the following functions of Chromium.
+//
+// [RenderWidgetHostViewMac keyEvent] (browser) ->
+// |Sync IPC (KeyDown)| (*1) ->
+// EventHandler::keyEvent() (renderer) ->
+// ...
+// EditorClientImpl::handleKeyboardEvent() (renderer) ->
+// |Sync IPC| (*2) ->
+// [RenderWidgetHostViewMac _interceptEditingKeyEvent] (browser) ->
+// [self interpretKeyEvents] ->
+// [RenderWidgetHostViewMac insertText] (browser) ->
+// |Async IPC| ->
+// Editor::insertText() (renderer)
+//
+// (*1) we need to wait until this call finishes since WebHTMLView uses the
+// result of EventHandler::keyEvent().
+// (*2) we need to wait until this call finishes since WebEditorClient uses
+// the result of [WebHTMLView _interceptEditingKeyEvent].
+//
+// This needs many sync IPC messages sent between a browser and a renderer for
+// each key event, which would probably result in key-typing jank.
+// To avoid this problem, this implementation processes key events (and input
+// method events) totally in a browser process and sends asynchronous input
+// events, almost same as KeyboardEvents (and TextEvents) of DOM Level 3, to a
+// renderer process.
+//
+// [RenderWidgetHostViewMac keyEvent] (browser) ->
+// |Async IPC (RawKeyDown)| ->
+// [self interpretKeyEvents] ->
+// [RenderWidgetHostViewMac insertText] (browser) ->
+// |Async IPC (Char)| ->
+// Editor::insertText() (renderer)
+//
+// Since this implementation doesn't have to wait any IPC calls, this doesn't
+// make any key-typing jank. --hbono 7/23/09
+//
+extern "C" {
+extern NSString* NSTextInputReplacementRangeAttributeName;
+}
+
+- (NSArray*)validAttributesForMarkedText {
+ // This code is just copied from WebKit except renaming variables.
+ if (!validAttributesForMarkedText_) {
+ validAttributesForMarkedText_.reset([[NSArray alloc]
+ initWithObjects:NSUnderlineStyleAttributeName,
+ NSUnderlineColorAttributeName,
+ NSMarkedClauseSegmentAttributeName,
+ NSTextInputReplacementRangeAttributeName, nil]);
+ }
+ return validAttributesForMarkedText_.get();
+}
+
+- (NSUInteger)characterIndexForPoint:(NSPoint)thePoint {
+ DCHECK([self window]);
+ // |thePoint| is in screen coordinates, but needs to be converted to WebKit
+ // coordinates (upper left origin). Scroll offsets will be taken care of in
+ // the renderer.
+ thePoint = ui::ConvertPointFromScreenToWindow([self window], thePoint);
+ thePoint = [self convertPoint:thePoint fromView:nil];
+ thePoint.y = NSHeight([self frame]) - thePoint.y;
+ gfx::PointF rootPoint(thePoint.x, thePoint.y);
+
+ uint32_t index = UINT32_MAX;
+ client_->OnNSViewSyncGetCharacterIndexAtPoint(rootPoint, &index);
+ // |index| could be WTF::notFound (-1) and its value is different from
+ // NSNotFound so we need to convert it.
+ if (index == UINT32_MAX)
+ return NSNotFound;
+ size_t char_index = index;
+ return NSUInteger(char_index);
+}
+
+- (NSRect)firstRectForCharacterRange:(NSRange)theRange
+ actualRange:(NSRangePointer)actualRange {
+ gfx::Rect gfxRect;
+ gfx::Range gfxActualRange;
+ bool success = false;
+ if (actualRange)
+ gfxActualRange = gfx::Range(*actualRange);
+ client_->OnNSViewSyncGetFirstRectForRange(gfx::Range(theRange), &gfxRect,
+ &gfxActualRange, &success);
+ if (!success) {
+ // The call to cancelComposition comes from https://crrev.com/350261.
+ [self cancelComposition];
+ return NSZeroRect;
+ }
+ if (actualRange)
+ *actualRange = gfxActualRange.ToNSRange();
+
+ // The returned rectangle is in WebKit coordinates (upper left origin), so
+ // flip the coordinate system.
+ NSRect viewFrame = [self frame];
+ NSRect rect = NSRectFromCGRect(gfxRect.ToCGRect());
+ rect.origin.y = NSHeight(viewFrame) - NSMaxY(rect);
+
+ // Convert into screen coordinates for return.
+ rect = [self convertRect:rect toView:nil];
+ rect = [[self window] convertRectToScreen:rect];
+ return rect;
+}
+
+- (NSRange)selectedRange {
+ return textSelectionRange_.ToNSRange();
+}
+
+- (NSRange)markedRange {
+ // An input method calls this method to check if an application really has
+ // a text being composed when hasMarkedText call returns true.
+ // Returns the range saved in the setMarkedText method so the input method
+ // calls the setMarkedText method and we can update the composition node
+ // there. (When this method returns an empty range, the input method doesn't
+ // call the setMarkedText method.)
+ return hasMarkedText_ ? markedRange_ : NSMakeRange(NSNotFound, 0);
+}
+
+- (NSAttributedString*)attributedSubstringForProposedRange:(NSRange)range
+ actualRange:
+ (NSRangePointer)actualRange {
+ // Prepare |actualRange| as if the proposed range is invalid. If it is valid,
+ // then |actualRange| will be updated again.
+ if (actualRange)
+ *actualRange = NSMakeRange(NSNotFound, 0);
+
+ // The caller of this method is allowed to pass nonsensical ranges. These
+ // can't even be converted into gfx::Ranges.
+ if (range.location == NSNotFound || range.length == 0)
+ return nil;
+ if (range.length >= std::numeric_limits<NSUInteger>::max() - range.location)
+ return nil;
+
+ const gfx::Range requestedRange(range);
+ if (requestedRange.is_reversed())
+ return nil;
+
+ gfx::Range expectedRange;
+ const base::string16* expectedText;
+
+ if (!compositionRange_.is_empty()) {
+ // This method might get called after TextInputState.type is reset to none,
+ // in which case there will be no composition range information
+ // https://crbug.com/698672
+ expectedText = &markedText_;
+ expectedRange = compositionRange_.Intersect(
+ gfx::Range(compositionRange_.start(),
+ compositionRange_.start() + expectedText->length()));
+ } else {
+ expectedText = &textSelectionText_;
+ size_t offset = textSelectionOffset_;
+ expectedRange = gfx::Range(offset, offset + expectedText->size());
+ }
+
+ gfx::Range gfxActualRange = expectedRange.Intersect(requestedRange);
+ if (!gfxActualRange.IsValid())
+ return nil;
+ if (actualRange)
+ *actualRange = gfxActualRange.ToNSRange();
+
+ base::string16 string = expectedText->substr(
+ gfxActualRange.start() - expectedRange.start(), gfxActualRange.length());
+ return [[[NSAttributedString alloc]
+ initWithString:base::SysUTF16ToNSString(string)] autorelease];
+}
+
+- (NSInteger)conversationIdentifier {
+ return reinterpret_cast<NSInteger>(self);
+}
+
+// Each RenderWidgetHostViewCocoa has its own input context, but we return
+// nil when the caret is in non-editable content or password box to avoid
+// making input methods do their work.
+- (NSTextInputContext*)inputContext {
+ ui::TextInputType textInputType = ui::TEXT_INPUT_TYPE_NONE;
+ client_->OnNSViewSyncGetTextInputType(&textInputType);
+ switch (textInputType) {
+ case ui::TEXT_INPUT_TYPE_NONE:
+ case ui::TEXT_INPUT_TYPE_PASSWORD:
+ return nil;
+ default:
+ return [super inputContext];
+ }
+}
+
+- (BOOL)hasMarkedText {
+ // An input method calls this function to figure out whether or not an
+ // application is really composing a text. If it is composing, it calls
+ // the markedRange method, and maybe calls the setMarkedText method.
+ // It seems an input method usually calls this function when it is about to
+ // cancel an ongoing composition. If an application has a non-empty marked
+ // range, it calls the setMarkedText method to delete the range.
+ return hasMarkedText_;
+}
+
+- (void)unmarkText {
+ // Delete the composition node of the renderer and finish an ongoing
+ // composition.
+ // It seems an input method calls the setMarkedText method and set an empty
+ // text when it cancels an ongoing composition, i.e. I have never seen an
+ // input method calls this method.
+ hasMarkedText_ = NO;
+ markedText_.clear();
+ markedTextSelectedRange_ = NSMakeRange(NSNotFound, 0);
+ ime_text_spans_.clear();
+
+ // If we are handling a key down event, then FinishComposingText() will be
+ // called in keyEvent: method.
+ if (!handlingKeyDown_) {
+ client_->OnNSViewImeFinishComposingText();
+ } else {
+ unmarkTextCalled_ = YES;
+ }
+}
+
+- (void)setMarkedText:(id)string
+ selectedRange:(NSRange)newSelRange
+ replacementRange:(NSRange)replacementRange {
+ // An input method updates the composition string.
+ // We send the given text and range to the renderer so it can update the
+ // composition node of WebKit.
+ // TODO(suzhe): It's hard for us to support replacementRange without accessing
+ // the full web content.
+ BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
+ NSString* im_text = isAttributedString ? [string string] : string;
+ int length = [im_text length];
+
+ // |markedRange_| will get set on a callback from ImeSetComposition().
+ markedTextSelectedRange_ = newSelRange;
+ markedText_ = base::SysNSStringToUTF16(im_text);
+ hasMarkedText_ = (length > 0);
+
+ ime_text_spans_.clear();
+ if (isAttributedString) {
+ ExtractUnderlines(string, &ime_text_spans_);
+ } else {
+ // Use a thin black underline by default.
+ ime_text_spans_.push_back(ui::ImeTextSpan(
+ ui::ImeTextSpan::Type::kComposition, 0, length,
+ ui::ImeTextSpan::Thickness::kThin, SK_ColorTRANSPARENT));
+ }
+
+ // If we are handling a key down event, then SetComposition() will be
+ // called in keyEvent: method.
+ // Input methods of Mac use setMarkedText calls with an empty text to cancel
+ // an ongoing composition. So, we should check whether or not the given text
+ // is empty to update the input method state. (Our input method backend
+ // automatically cancels an ongoing composition when we send an empty text.
+ // So, it is OK to send an empty text to the renderer.)
+ if (handlingKeyDown_) {
+ setMarkedTextReplacementRange_ = gfx::Range(replacementRange);
+ } else {
+ client_->OnNSViewImeSetComposition(
+ markedText_, ime_text_spans_, gfx::Range(replacementRange),
+ newSelRange.location, NSMaxRange(newSelRange));
+ }
+}
+
+- (void)doCommandBySelector:(SEL)selector {
+ // An input method calls this function to dispatch an editing command to be
+ // handled by this view.
+ if (selector == @selector(noop:))
+ return;
+
+ std::string command(base::SysNSStringToUTF8(
+ RenderWidgetHostViewMacEditCommandHelper::CommandNameForSelector(
+ selector)));
+
+ // If this method is called when handling a key down event, then we need to
+ // handle the command in the key event handler. Otherwise we can just handle
+ // it here.
+ if (handlingKeyDown_) {
+ hasEditCommands_ = YES;
+ // We ignore commands that insert characters, because this was causing
+ // strange behavior (e.g. tab always inserted a tab rather than moving to
+ // the next field on the page).
+ if (!base::StartsWith(command, "insert",
+ base::CompareCase::INSENSITIVE_ASCII))
+ editCommands_.push_back(EditCommand(command, ""));
+ } else {
+ client_->OnNSViewExecuteEditCommand(command);
+ }
+}
+
+- (void)insertText:(id)string replacementRange:(NSRange)replacementRange {
+ // An input method has characters to be inserted.
+ // Same as Linux, Mac calls this method not only:
+ // * when an input method finishes composing text, but also;
+ // * when we type an ASCII character (without using input methods).
+ // When we aren't using input methods, we should send the given character as
+ // a Char event so it is dispatched to an onkeypress() event handler of
+ // JavaScript.
+ // On the other hand, when we are using input methods, we should send the
+ // given characters as an input method event and prevent the characters from
+ // being dispatched to onkeypress() event handlers.
+ // Text inserting might be initiated by other source instead of keyboard
+ // events, such as the Characters dialog. In this case the text should be
+ // sent as an input method event as well.
+ // TODO(suzhe): It's hard for us to support replacementRange without accessing
+ // the full web content.
+ BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
+ NSString* im_text = isAttributedString ? [string string] : string;
+ if (handlingKeyDown_) {
+ textToBeInserted_.append(base::SysNSStringToUTF16(im_text));
+ } else {
+ gfx::Range replacement_range(replacementRange);
+ client_->OnNSViewImeCommitText(base::SysNSStringToUTF16(im_text),
+ replacement_range);
+ }
+
+ // Inserting text will delete all marked text automatically.
+ hasMarkedText_ = NO;
+}
+
+- (void)insertText:(id)string {
+ [self insertText:string replacementRange:NSMakeRange(NSNotFound, 0)];
+}
+
+- (void)viewDidMoveToWindow {
+ // Update the window's frame, the view's bounds, focus, and the display info,
+ // as they have not been updated while unattached to a window.
+ [self sendWindowFrameInScreenToClient];
+ [self sendViewBoundsInWindowToClient];
+ [self updateScreenProperties];
+ client_->OnNSViewIsFirstResponderChanged([[self window] firstResponder] ==
+ self);
+
+ // If we switch windows (or are removed from the view hierarchy), cancel any
+ // open mouse-downs.
+ if (hasOpenMouseDown_) {
+ WebMouseEvent event(WebInputEvent::kMouseUp, WebInputEvent::kNoModifiers,
+ ui::EventTimeStampToSeconds(ui::EventTimeForNow()));
+ event.button = WebMouseEvent::Button::kLeft;
+ client_->OnNSViewForwardMouseEvent(event);
+ hasOpenMouseDown_ = NO;
+ }
+}
+
+- (void)undo:(id)sender {
+ client_->OnNSViewUndo();
+}
+
+- (void)redo:(id)sender {
+ client_->OnNSViewRedo();
+}
+
+- (void)cut:(id)sender {
+ client_->OnNSViewCut();
+}
+
+- (void)copy:(id)sender {
+ client_->OnNSViewCopy();
+}
+
+- (void)copyToFindPboard:(id)sender {
+ client_->OnNSViewCopyToFindPboard();
+}
+
+- (void)paste:(id)sender {
+ client_->OnNSViewPaste();
+}
+
+- (void)pasteAndMatchStyle:(id)sender {
+ client_->OnNSViewPasteAndMatchStyle();
+}
+
+- (void)selectAll:(id)sender {
+ // editCommandHelper_ adds implementations for most NSResponder methods
+ // dynamically. But the renderer side only sends selection results back to
+ // the browser if they were triggered by a keyboard event or went through
+ // one of the Select methods on RWH. Since selectAll: is called from the
+ // menu handler, neither is true.
+ // Explicitly call SelectAll() here to make sure the renderer returns
+ // selection results.
+ client_->OnNSViewSelectAll();
+}
+
+- (void)startSpeaking:(id)sender {
+ client_->OnNSViewSpeakSelection();
+}
+
+- (void)stopSpeaking:(id)sender {
+ client_->OnNSViewStopSpeaking();
+}
+
+- (void)cancelComposition {
+ if (!hasMarkedText_)
+ return;
+
+ NSTextInputContext* inputContext = [self inputContext];
+ [inputContext discardMarkedText];
+
+ hasMarkedText_ = NO;
+ // Should not call [self unmarkText] here, because it'll send unnecessary
+ // cancel composition IPC message to the renderer.
+}
+
+- (void)finishComposingText {
+ if (!hasMarkedText_)
+ return;
+
+ client_->OnNSViewImeFinishComposingText();
+ [self cancelComposition];
+}
+
+// Overriding a NSResponder method to support application services.
+
+- (id)validRequestorForSendType:(NSString*)sendType
+ returnType:(NSString*)returnType {
+ ui::TextInputType textInputType = ui::TEXT_INPUT_TYPE_NONE;
+ client_->OnNSViewSyncGetTextInputType(&textInputType);
+
+ id requestor = nil;
+ BOOL sendTypeIsString = [sendType isEqual:NSStringPboardType];
+ BOOL returnTypeIsString = [returnType isEqual:NSStringPboardType];
+ BOOL hasText = !textSelectionRange_.is_empty();
+ BOOL takesText = textInputType != ui::TEXT_INPUT_TYPE_NONE;
+
+ if (sendTypeIsString && hasText && !returnType) {
+ requestor = self;
+ } else if (!sendType && returnTypeIsString && takesText) {
+ requestor = self;
+ } else if (sendTypeIsString && returnTypeIsString && hasText && takesText) {
+ requestor = self;
+ } else {
+ requestor =
+ [super validRequestorForSendType:sendType returnType:returnType];
+ }
+ return requestor;
+}
+
+- (void)updateCursor:(NSCursor*)cursor {
+ if (currentCursor_ == cursor)
+ return;
+
+ currentCursor_.reset([cursor retain]);
+ [[self window] invalidateCursorRectsForView:self];
+
+ // NSWindow's invalidateCursorRectsForView: resets cursor rects but does not
+ // update the cursor instantly. The cursor is updated when the mouse moves.
+ // Update the cursor by setting the current cursor if not hidden.
+ if (!cursorHidden_ && !showingContextMenu_)
+ [currentCursor_ set];
+}
+
+- (void)popupWindowWillClose:(NSNotification*)notification {
+ [self setHidden:YES];
+ client_->OnNSViewRequestShutdown();
+}
+
+@end
+
+//
+// Supporting application services
+//
+@implementation RenderWidgetHostViewCocoa (NSServicesRequests)
+
+- (BOOL)writeSelectionToPasteboard:(NSPasteboard*)pboard types:(NSArray*)types {
+ if (textSelectionRange_.is_empty() ||
+ ![types containsObject:NSStringPboardType]) {
+ return NO;
+ }
+
+ NSString* text = base::SysUTF16ToNSString([self selectedText]);
+ NSArray* toDeclare = [NSArray arrayWithObject:NSStringPboardType];
+ [pboard declareTypes:toDeclare owner:nil];
+ return [pboard setString:text forType:NSStringPboardType];
+}
+
+- (BOOL)readSelectionFromPasteboard:(NSPasteboard*)pboard {
+ NSString* string = [pboard stringForType:NSStringPboardType];
+ if (!string)
+ return NO;
+
+ // If the user is currently using an IME, confirm the IME input,
+ // and then insert the text from the service, the same as TextEdit and Safari.
+ [self finishComposingText];
+ [self insertText:string];
+ return YES;
+}
+
+// "-webkit-app-region: drag | no-drag" is implemented on Mac by excluding
+// regions that are not draggable. (See ControlRegionView in
+// native_app_window_cocoa.mm). This requires the render host view to be
+// draggable by default.
+- (BOOL)mouseDownCanMoveWindow {
+ return YES;
+}
+
+@end
diff --git a/chromium/content/browser/renderer_host/render_widget_host_view_event_handler.cc b/chromium/content/browser/renderer_host/render_widget_host_view_event_handler.cc
index d7bb2f78dd6..e046d3a5e23 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_view_event_handler.cc
+++ b/chromium/content/browser/renderer_host/render_widget_host_view_event_handler.cc
@@ -21,11 +21,13 @@
#include "ui/aura/client/cursor_client.h"
#include "ui/aura/client/focus_client.h"
#include "ui/aura/client/screen_position_client.h"
+#include "ui/aura/scoped_keyboard_hook.h"
#include "ui/aura/window.h"
#include "ui/aura/window_delegate.h"
#include "ui/base/ime/text_input_client.h"
#include "ui/events/blink/blink_event_util.h"
#include "ui/events/blink/web_input_event.h"
+#include "ui/events/keycodes/dom/keycode_converter.h"
#include "ui/touch_selection/touch_selection_controller.h"
#if defined(OS_WIN)
@@ -140,7 +142,7 @@ RenderWidgetHostViewEventHandler::RenderWidgetHostViewEventHandler(
popup_child_event_handler_(nullptr),
delegate_(delegate),
window_(nullptr),
- mouse_wheel_phase_handler_(host, host_view) {}
+ mouse_wheel_phase_handler_(host_view) {}
RenderWidgetHostViewEventHandler::~RenderWidgetHostViewEventHandler() {}
@@ -161,15 +163,6 @@ void RenderWidgetHostViewEventHandler::TrackHost(
}
#if defined(OS_WIN)
-void RenderWidgetHostViewEventHandler::SetContextMenuParams(
- const ContextMenuParams& params) {
- last_context_menu_params_.reset();
- if (params.source_type == ui::MENU_SOURCE_LONG_PRESS) {
- last_context_menu_params_.reset(new ContextMenuParams);
- *last_context_menu_params_ = params;
- }
-}
-
void RenderWidgetHostViewEventHandler::UpdateMouseLockRegion() {
RECT window_rect =
display::Screen::GetScreen()
@@ -240,6 +233,27 @@ void RenderWidgetHostViewEventHandler::UnlockMouse() {
host_->LostMouseLock();
}
+bool RenderWidgetHostViewEventHandler::LockKeyboard(
+ base::Optional<base::flat_set<int>> keys) {
+ aura::Window* root_window = window_->GetRootWindow();
+ if (!root_window)
+ return false;
+
+ // Remove existing hook, if registered.
+ UnlockKeyboard();
+ scoped_keyboard_hook_ = root_window->CaptureSystemKeyEvents(std::move(keys));
+
+ return IsKeyboardLocked();
+}
+
+void RenderWidgetHostViewEventHandler::UnlockKeyboard() {
+ scoped_keyboard_hook_.reset();
+}
+
+bool RenderWidgetHostViewEventHandler::IsKeyboardLocked() const {
+ return scoped_keyboard_hook_ != nullptr;
+}
+
void RenderWidgetHostViewEventHandler::OnKeyEvent(ui::KeyEvent* event) {
TRACE_EVENT0("input", "RenderWidgetHostViewBase::OnKeyEvent");
@@ -285,6 +299,12 @@ void RenderWidgetHostViewEventHandler::OnKeyEvent(ui::KeyEvent* event) {
SetKeyboardFocus();
// We don't have to communicate with an input method here.
NativeWebKeyboardEvent webkit_event(*event);
+
+ // If the key has been reserved as part of the active KeyboardLock request,
+ // then we want to mark it as such so it is not intercepted by the browser.
+ if (IsKeyLocked(*event))
+ webkit_event.skip_in_browser = true;
+
delegate_->ForwardKeyboardEventWithLatencyInfo(
webkit_event, *event->latency(), &mark_event_as_handled);
}
@@ -414,8 +434,7 @@ void RenderWidgetHostViewEventHandler::OnScrollEvent(ui::ScrollEvent* event) {
// Coordinates need to be transferred to the fling cancel gesture only
// for Surface-targeting to ensure that it is targeted to the correct
// RenderWidgetHost.
- gesture_event.x = event->x();
- gesture_event.y = event->y();
+ gesture_event.SetPositionInWidget(event->location_f());
blink::WebMouseWheelEvent mouse_wheel_event = ui::MakeWebMouseWheelEvent(
*event, base::Bind(&GetScreenLocationFromEvent));
if (host_view_->wheel_scroll_latching_enabled())
@@ -449,7 +468,7 @@ void RenderWidgetHostViewEventHandler::OnScrollEvent(ui::ScrollEvent* event) {
mouse_wheel_phase_handler_.ResetScrollSequence();
} else if (event->type() == ui::ET_SCROLL_FLING_CANCEL) {
// The user has put their fingers down.
- DCHECK_EQ(blink::kWebGestureDeviceTouchpad, gesture_event.source_device);
+ DCHECK_EQ(blink::kWebGestureDeviceTouchpad, gesture_event.SourceDevice());
mouse_wheel_phase_handler_.ScrollingMayBegin();
}
}
@@ -532,7 +551,7 @@ void RenderWidgetHostViewEventHandler::OnGestureEvent(ui::GestureEvent* event) {
// event to stop any in-progress flings.
blink::WebGestureEvent fling_cancel = gesture;
fling_cancel.SetType(blink::WebInputEvent::kGestureFlingCancel);
- fling_cancel.source_device = blink::kWebGestureDeviceTouchscreen;
+ fling_cancel.SetSourceDevice(blink::kWebGestureDeviceTouchscreen);
if (ShouldRouteEvent(event)) {
host_->delegate()->GetInputEventRouter()->RouteGestureEvent(
host_view_, &fling_cancel,
@@ -701,29 +720,6 @@ void RenderWidgetHostViewEventHandler::HandleGestureForTouchSelection(
case ui::ET_GESTURE_SCROLL_END:
delegate_->selection_controller_client()->OnScrollCompleted();
break;
-#if defined(OS_WIN)
- case ui::ET_GESTURE_LONG_TAP: {
- if (!last_context_menu_params_)
- break;
-
- std::unique_ptr<ContextMenuParams> context_menu_params =
- std::move(last_context_menu_params_);
-
- // On Windows we want to display the context menu when the long press
- // gesture is released. To achieve that, we switch the saved context
- // menu params source type to MENU_SOURCE_TOUCH. This is to ensure that
- // the RenderWidgetHostViewBase::OnShowContextMenu function which is
- // called from the ShowContextMenu call below, does not treat it as
- // a context menu request coming in from the long press gesture.
- DCHECK(context_menu_params->source_type == ui::MENU_SOURCE_LONG_PRESS);
- context_menu_params->source_type = ui::MENU_SOURCE_TOUCH;
-
- delegate_->ShowContextMenu(*context_menu_params);
- event->SetHandled();
- // WARNING: we may have been deleted during the call to ShowContextMenu().
- break;
- }
-#endif
default:
break;
}
@@ -948,4 +944,15 @@ void RenderWidgetHostViewEventHandler::ProcessTouchEvent(
host_->ForwardTouchEventWithLatencyInfo(event, latency);
}
+bool RenderWidgetHostViewEventHandler::IsKeyLocked(const ui::KeyEvent& event) {
+ // Note: We never consider 'ESC' to be locked as we don't want to prevent it
+ // from being handled by the browser. Doing so would have adverse effects
+ // such as the user being unable to exit fullscreen mode.
+ if (!IsKeyboardLocked() || event.key_code() == ui::VKEY_ESCAPE)
+ return false;
+
+ int key_code = ui::KeycodeConverter::DomCodeToNativeKeycode(event.code());
+ return scoped_keyboard_hook_->IsKeyLocked(key_code);
+}
+
} // namespace content
diff --git a/chromium/content/browser/renderer_host/render_widget_host_view_event_handler.h b/chromium/content/browser/renderer_host/render_widget_host_view_event_handler.h
index 6d76d39d74a..410e6e2f209 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_view_event_handler.h
+++ b/chromium/content/browser/renderer_host/render_widget_host_view_event_handler.h
@@ -7,10 +7,13 @@
#include <memory>
+#include "base/containers/flat_set.h"
#include "base/macros.h"
+#include "base/optional.h"
#include "content/browser/renderer_host/input/mouse_wheel_phase_handler.h"
#include "content/common/content_export.h"
#include "content/public/browser/native_web_keyboard_event.h"
+#include "ui/aura/scoped_keyboard_hook.h"
#include "ui/aura/window_tracker.h"
#include "ui/events/event_handler.h"
#include "ui/events/gestures/motion_event_aura.h"
@@ -140,6 +143,11 @@ class CONTENT_EXPORT RenderWidgetHostViewEventHandler
bool LockMouse();
void UnlockMouse();
+ // Start/Stop processing of future system keyboard events.
+ bool LockKeyboard(base::Optional<base::flat_set<int>> keys);
+ void UnlockKeyboard();
+ bool IsKeyboardLocked() const;
+
// ui::EventHandler:
void OnKeyEvent(ui::KeyEvent* event) override;
void OnMouseEvent(ui::MouseEvent* event) override;
@@ -158,6 +166,18 @@ class CONTENT_EXPORT RenderWidgetHostViewEventHandler
private:
FRIEND_TEST_ALL_PREFIXES(InputMethodResultAuraTest,
FinishImeCompositionSession);
+ FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest,
+ KeyEventRoutingWithKeyboardLockActiveForOneKey);
+ FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest,
+ KeyEventRoutingWithKeyboardLockActiveForEscKey);
+ FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest,
+ KeyEventRoutingWithKeyboardLockActiveForAllKeys);
+ FRIEND_TEST_ALL_PREFIXES(
+ RenderWidgetHostViewAuraTest,
+ KeyEventRoutingKeyboardLockAndChildPopupWithInputGrab);
+ FRIEND_TEST_ALL_PREFIXES(
+ RenderWidgetHostViewAuraTest,
+ KeyEventRoutingKeyboardLockAndChildPopupWithoutInputGrab);
// Returns true if the |event| passed in can be forwarded to the renderer.
bool CanRendererHandleEvent(const ui::MouseEvent* event,
bool mouse_locked,
@@ -205,6 +225,9 @@ class CONTENT_EXPORT RenderWidgetHostViewEventHandler
void ProcessTouchEvent(const blink::WebTouchEvent& event,
const ui::LatencyInfo& latency);
+ // Returns true if event is a reserved key for an active KeyboardLock request.
+ bool IsKeyLocked(const ui::KeyEvent& event);
+
// Whether return characters should be passed on to the RenderWidgetHostImpl.
bool accept_return_character_;
@@ -213,6 +236,9 @@ class CONTENT_EXPORT RenderWidgetHostViewEventHandler
// RenderWidgetHostInputEventRouter.
bool disable_input_event_router_for_testing_;
+ // Deactivates keyboard lock when destroyed.
+ std::unique_ptr<aura::ScopedKeyboardHook> scoped_keyboard_hook_;
+
// While the mouse is locked, the cursor is hidden from the user. Mouse events
// are still generated. However, the position they report is the last known
// mouse position just as mouse lock was entered; the movement they report
@@ -250,12 +276,6 @@ class CONTENT_EXPORT RenderWidgetHostViewEventHandler
// object.
ui::MotionEventAura pointer_state_;
-#if defined(OS_WIN)
- // Contains a copy of the last context menu request parameters. Only set when
- // we receive a request to show the context menu on a long press.
- std::unique_ptr<ContextMenuParams> last_context_menu_params_;
-#endif // defined(OS_WIN)
-
// The following are not owned. They should outlive |this|
RenderWidgetHostImpl* const host_;
// Should create |this| and own it.
diff --git a/chromium/content/browser/renderer_host/render_widget_host_view_mac.h b/chromium/content/browser/renderer_host/render_widget_host_view_mac.h
index d24194d68cb..d4b8dadb129 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_view_mac.h
+++ b/chromium/content/browser/renderer_host/render_widget_host_view_mac.h
@@ -6,16 +6,8 @@
#define CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_VIEW_MAC_H_
#import <Cocoa/Cocoa.h>
-#include <IOSurface/IOSurface.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include <list>
-#include <map>
-#include <memory>
-#include <set>
+
#include <string>
-#include <utility>
#include <vector>
#include "base/mac/scoped_nsobject.h"
@@ -25,206 +17,31 @@
#include "components/viz/common/surfaces/surface_id.h"
#include "content/browser/renderer_host/browser_compositor_view_mac.h"
#include "content/browser/renderer_host/input/mouse_wheel_phase_handler.h"
-#include "content/browser/renderer_host/input/mouse_wheel_rails_filter_mac.h"
+#include "content/browser/renderer_host/render_widget_host_ns_view_client.h"
#include "content/browser/renderer_host/render_widget_host_view_base.h"
#include "content/browser/renderer_host/text_input_manager.h"
#include "content/common/content_export.h"
-#include "content/common/cursors/webcursor.h"
-#include "content/common/edit_command.h"
#include "ipc/ipc_sender.h"
#include "ui/accelerated_widget_mac/accelerated_widget_mac.h"
#include "ui/accelerated_widget_mac/display_link_mac.h"
-#import "ui/base/cocoa/command_dispatcher.h"
#include "ui/base/cocoa/remote_layer_api.h"
-#import "ui/base/cocoa/tool_tip_base_view.h"
-#include "ui/base/ime/ime_text_span.h"
-#include "ui/display/display_observer.h"
namespace content {
class CursorManager;
class RenderWidgetHost;
-class RenderWidgetHostImpl;
+class RenderWidgetHostNSViewBridge;
class RenderWidgetHostViewMac;
-class RenderWidgetHostViewMacEditCommandHelper;
class WebContents;
-struct TextInputState;
+class WebCursor;
}
-@class FullscreenWindowManager;
-@protocol RenderWidgetHostViewMacDelegate;
-
-@protocol RenderWidgetHostViewMacOwner
-- (content::RenderWidgetHostViewMac*)renderWidgetHostViewMac;
-@end
-
-// This is the view that lives in the Cocoa view hierarchy. In Windows-land,
-// RenderWidgetHostViewWin is both the view and the delegate. We split the roles
-// but that means that the view needs to own the delegate and will dispose of it
-// when it's removed from the view system.
-@interface RenderWidgetHostViewCocoa
- : ToolTipBaseView<CommandDispatcherTarget,
- RenderWidgetHostViewMacOwner,
- NSTextInputClient> {
- @private
- std::unique_ptr<content::RenderWidgetHostViewMac> renderWidgetHostView_;
- // This ivar is the cocoa delegate of the NSResponder.
- base::scoped_nsobject<NSObject<RenderWidgetHostViewMacDelegate>>
- responderDelegate_;
- BOOL canBeKeyView_;
- BOOL closeOnDeactivate_;
- std::unique_ptr<content::RenderWidgetHostViewMacEditCommandHelper>
- editCommand_helper_;
-
- // Is YES if there was a mouse-down as yet unbalanced with a mouse-up.
- BOOL hasOpenMouseDown_;
-
- // The cursor for the page. This is passed up from the renderer.
- base::scoped_nsobject<NSCursor> currentCursor_;
-
- // Is YES if the cursor is hidden by key events.
- BOOL cursorHidden_;
-
- // Variables used by our implementaion of the NSTextInput protocol.
- // An input method of Mac calls the methods of this protocol not only to
- // notify an application of its status, but also to retrieve the status of
- // the application. That is, an application cannot control an input method
- // directly.
- // This object keeps the status of a composition of the renderer and returns
- // it when an input method asks for it.
- // We need to implement Objective-C methods for the NSTextInput protocol. On
- // the other hand, we need to implement a C++ method for an IPC-message
- // handler which receives input-method events from the renderer.
-
- // Represents the input-method attributes supported by this object.
- base::scoped_nsobject<NSArray> validAttributesForMarkedText_;
-
- // Indicates if we are currently handling a key down event.
- BOOL handlingKeyDown_;
-
- // Indicates if there is any marked text.
- BOOL hasMarkedText_;
-
- // Indicates if unmarkText is called or not when handling a keyboard
- // event.
- BOOL unmarkTextCalled_;
-
- // The range of current marked text inside the whole content of the DOM node
- // being edited.
- // TODO(suzhe): This is currently a fake value, as we do not support accessing
- // the whole content yet.
- NSRange markedRange_;
-
- // The selected range, cached from a message sent by the renderer.
- NSRange selectedRange_;
-
- // Text to be inserted which was generated by handling a key down event.
- base::string16 textToBeInserted_;
-
- // Marked text which was generated by handling a key down event.
- base::string16 markedText_;
-
- // Selected range of |markedText_|.
- NSRange markedTextSelectedRange_;
-
- // Underline information of the |markedText_|.
- std::vector<ui::ImeTextSpan> ime_text_spans_;
-
- // Replacement range information received from |setMarkedText:|.
- gfx::Range setMarkedTextReplacementRange_;
-
- // Indicates if doCommandBySelector method receives any edit command when
- // handling a key down event.
- BOOL hasEditCommands_;
-
- // Contains edit commands received by the -doCommandBySelector: method when
- // handling a key down event, not including inserting commands, eg. insertTab,
- // etc.
- content::EditCommands editCommands_;
-
- // Whether the previous mouse event was ignored due to hitTest check.
- BOOL mouseEventWasIgnored_;
-
- // Event monitor for scroll wheel end event.
- id endWheelMonitor_;
-
- // When a gesture starts, the system does not inform the view of which type
- // of gesture is happening (magnify, rotate, etc), rather, it just informs
- // the view that some as-yet-undefined gesture is starting. Capture the
- // information about the gesture's beginning event here. It will be used to
- // create a specific gesture begin event later.
- std::unique_ptr<blink::WebGestureEvent> gestureBeginEvent_;
-
- // To avoid accidental pinches, require that a certain zoom threshold be
- // reached before forwarding it to the browser. Use |pinchUnusedAmount_| to
- // hold this value. If the user reaches this value, don't re-require the
- // threshold be reached until the page has been zoomed back to page scale of
- // one.
- bool pinchHasReachedZoomThreshold_;
- float pinchUnusedAmount_;
- NSTimeInterval pinchLastGestureTimestamp_;
-
- // This is set if a GesturePinchBegin event has been sent in the lifetime of
- // |gestureBeginEvent_|. If set, a GesturePinchEnd will be sent when the
- // gesture ends.
- BOOL gestureBeginPinchSent_;
-
- // If true then escape key down events are suppressed until the first escape
- // key up event. (The up event is suppressed as well). This is used by the
- // flash fullscreen code to avoid sending a key up event without a matching
- // key down event.
- BOOL suppressNextEscapeKeyUp_;
-
- // This is used to indicate if a stylus is currently in the proximity of the
- // tablet.
- bool isStylusEnteringProximity_;
- blink::WebPointerProperties::PointerType pointerType_;
-
- // The set of key codes from key down events that we haven't seen the matching
- // key up events yet.
- // Used for filtering out non-matching NSKeyUp events.
- std::set<unsigned short> keyDownCodes_;
-
- // The filter used to guide touch events towards a horizontal or vertical
- // orientation.
- content::MouseWheelRailsFilterMac mouseWheelFilter_;
+namespace ui {
+class ScopedPasswordInputEnabler;
}
-@property(nonatomic, readonly) NSRange selectedRange;
-@property(nonatomic, readonly) BOOL suppressNextEscapeKeyUp;
-
-// Common code path for handling begin gesture events. This helper method is
-// called via different codepaths based on OS version and SDK:
-// - On 10.11 and later, when linking with the 10.11 SDK, it is called from
-// |magnifyWithEvent:| when the given event's phase is NSEventPhaseBegin.
-// - On 10.10 and earlier, or when linking with an earlier SDK, it is called
-// by |beginGestureWithEvent:| when a gesture begins.
-- (void)handleBeginGestureWithEvent:(NSEvent*)event;
-
-// Common code path for handling end gesture events. This helper method is
-// called via different codepaths based on OS version and SDK:
-// - On 10.11 and later, when linking with the 10.11 SDK, it is called from
-// |magnifyWithEvent:| when the given event's phase is NSEventPhaseEnded.
-// - On 10.10 and earlier, or when linking with an earlier SDK, it is called
-// by |endGestureWithEvent:| when a gesture ends.
-- (void)handleEndGestureWithEvent:(NSEvent*)event;
-
-- (void)setCanBeKeyView:(BOOL)can;
-- (void)setCloseOnDeactivate:(BOOL)b;
-// True for always-on-top special windows (e.g. Balloons and Panels).
-- (BOOL)acceptsMouseEventsWhenInactive;
-// Cancel ongoing composition (abandon the marked text).
-- (void)cancelComposition;
-// Confirm ongoing composition.
-- (void)finishComposingText;
-- (void)updateCursor:(NSCursor*)cursor;
-- (NSRect)firstViewRectForCharacterRange:(NSRange)theRange
- actualRange:(NSRangePointer)actualRange;
-- (void)tabletEvent:(NSEvent*)theEvent;
-- (void)quickLookWithEvent:(NSEvent*)event;
-- (void)showLookUpDictionaryOverlayAtPoint:(NSPoint)point;
-- (void)showLookUpDictionaryOverlayFromRange:(NSRange)range
- targetView:(NSView*)targetView;
-@end
+@protocol RenderWidgetHostViewMacDelegate;
+
+@class RenderWidgetHostViewCocoa;
namespace content {
@@ -246,11 +63,11 @@ namespace content {
// RenderWidgetHostView class hierarchy described in render_widget_host_view.h.
class CONTENT_EXPORT RenderWidgetHostViewMac
: public RenderWidgetHostViewBase,
+ public RenderWidgetHostNSViewClient,
public BrowserCompositorMacClient,
public TextInputManager::Observer,
public ui::AcceleratedWidgetMacNSView,
- public IPC::Sender,
- public display::DisplayObserver {
+ public IPC::Sender {
public:
// The view will associate itself with the given widget. The native view must
// be hooked up immediately to the view hierarchy, or else when it is
@@ -261,9 +78,8 @@ class CONTENT_EXPORT RenderWidgetHostViewMac
// TODO(lazyboy): Remove |is_guest_view_hack| once BrowserPlugin has migrated
// to use RWHVChildFrame (http://crbug.com/330264).
RenderWidgetHostViewMac(RenderWidgetHost* widget, bool is_guest_view_hack);
- ~RenderWidgetHostViewMac() override;
- RenderWidgetHostViewCocoa* cocoa_view() const { return cocoa_view_; }
+ RenderWidgetHostViewCocoa* cocoa_view() const;
// |delegate| is used to separate out the logic from the NSResponder delegate.
// |delegate| is retained by this class.
@@ -273,11 +89,9 @@ class CONTENT_EXPORT RenderWidgetHostViewMac
void SetAllowPauseForResizeOrRepaint(bool allow);
// RenderWidgetHostView implementation.
- bool OnMessageReceived(const IPC::Message& msg) override;
void InitAsChild(gfx::NativeView parent_view) override;
void SetSize(const gfx::Size& size) override;
void SetBounds(const gfx::Rect& rect) override;
- gfx::Vector2dF GetLastScrollOffset() const override;
gfx::NativeView GetNativeView() const override;
gfx::NativeViewAccessible GetNativeViewAccessible() override;
bool HasFocus() const override;
@@ -289,15 +103,13 @@ class CONTENT_EXPORT RenderWidgetHostViewMac
gfx::Rect GetViewBounds() const override;
void SetActive(bool active) override;
void ShowDefinitionForSelection() override;
- bool SupportsSpeech() const override;
void SpeakSelection() override;
- bool IsSpeaking() const override;
- void StopSpeaking() override;
void SetBackgroundColor(SkColor color) override;
SkColor background_color() const override;
void SetNeedsBeginFrames(bool needs_begin_frames) override;
void GetScreenInfo(ScreenInfo* screen_info) const override;
void SetWantsAnimateOnlyBeginFrames() override;
+ void TakeFallbackContentFrom(RenderWidgetHostView* view) override;
// Implementation of RenderWidgetHostViewBase.
void InitAsPopup(RenderWidgetHostView* parent_host_view,
@@ -312,6 +124,7 @@ class CONTENT_EXPORT RenderWidgetHostViewMac
int error_code) override;
void Destroy() override;
void SetTooltipText(const base::string16& tooltip_text) override;
+ void DisplayTooltipText(const base::string16& tooltip_text) override;
gfx::Size GetRequestedRendererSize() const override;
bool IsSurfaceAvailableForCopy() const override;
void CopyFromSurface(
@@ -337,8 +150,9 @@ class CONTENT_EXPORT RenderWidgetHostViewMac
bool ShouldContinueToPauseForFrame() override;
gfx::Vector2d GetOffsetFromRootSurface() override;
gfx::Rect GetBoundsInRootWindow() override;
- void ResizeDueToAutoResize(const gfx::Size& new_size,
- uint64_t sequence_number) override;
+ viz::ScopedSurfaceIdAllocator ResizeDueToAutoResize(
+ const gfx::Size& new_size,
+ uint64_t sequence_number) override;
void DidNavigate() override;
bool LockMouse() override;
@@ -351,7 +165,6 @@ class CONTENT_EXPORT RenderWidgetHostViewMac
std::unique_ptr<SyntheticGestureTarget> CreateSyntheticGestureTarget()
override;
- RenderWidgetHostImpl* GetRenderWidgetHostImpl() const override;
viz::FrameSinkId GetFrameSinkId() override;
viz::LocalSurfaceId GetLocalSurfaceId() const override;
// Returns true when we can do SurfaceHitTesting for the event type.
@@ -388,27 +201,25 @@ class CONTENT_EXPORT RenderWidgetHostViewMac
RenderWidgetHostViewBase* updated_view) override;
void OnTextSelectionChanged(TextInputManager* text_input_manager,
RenderWidgetHostViewBase* updated_view) override;
+
+ // RenderFrameMetadataProvider::Observer
+ void OnRenderFrameMetadataChanged() override;
+
// IPC::Sender implementation.
bool Send(IPC::Message* message) override;
- // display::DisplayObserver implementation.
- void OnDisplayAdded(const display::Display& new_display) override;
- void OnDisplayRemoved(const display::Display& old_display) override;
- void OnDisplayMetricsChanged(const display::Display& display,
- uint32_t metrics) override;
-
// Forwards the mouse event to the renderer.
void ForwardMouseEvent(const blink::WebMouseEvent& event);
- void KillSelf();
-
void SetTextInputActive(bool active);
// Returns true and stores first rectangle for character range if the
// requested |range| is already cached, otherwise returns false.
// Exposed for testing.
CONTENT_EXPORT bool GetCachedFirstRectForCharacterRange(
- NSRange range, NSRect* rect, NSRange* actual_range);
+ const gfx::Range& requested_range,
+ gfx::Rect* rect,
+ gfx::Range* actual_range);
// Returns true if there is line break in |range| and stores line breaking
// point to |line_breaking_point|. The |line_break_point| is valid only if
@@ -441,13 +252,6 @@ class CONTENT_EXPORT RenderWidgetHostViewMac
// These member variables should be private, but the associated ObjC class
// needs access to them and can't be made a friend.
- // The associated Model. Can be NULL if Destroy() is called when
- // someone (other than superview) has retained |cocoa_view_|.
- RenderWidgetHostImpl* render_widget_host_;
-
- // The background CoreAnimation layer which is hosted by |cocoa_view_|.
- base::scoped_nsobject<CALayer> background_layer_;
-
// Delegated frame management and compositor interface.
std::unique_ptr<BrowserCompositorMac> browser_compositor_;
BrowserCompositorMac* BrowserCompositorForTesting() const {
@@ -465,34 +269,88 @@ class CONTENT_EXPORT RenderWidgetHostViewMac
mouse_wheel_phase_handler_.set_mouse_wheel_end_dispatch_timeout(timeout);
}
- NSWindow* pepper_fullscreen_window() const {
- return pepper_fullscreen_window_;
- }
-
- CONTENT_EXPORT void release_pepper_fullscreen_window_for_testing();
-
- RenderWidgetHostViewMac* fullscreen_parent_host_view() const {
- return fullscreen_parent_host_view_;
- }
-
- int window_number() const;
-
- // Update the size, scale factor, color profile, and any other properties
- // of the NSView or its NSScreen. Propagate these to the RenderWidgetHostImpl
- // as well.
+ // Update the size, scale factor, color profile, vsync parameters, and any
+ // other properties of the NSView or its NSScreen. Propagate these to the
+ // RenderWidgetHostImpl as well.
void UpdateNSViewAndDisplayProperties();
- // Ensure that the display link is associated with the correct display.
- void UpdateDisplayLink();
-
void PauseForPendingResizeOrRepaintsAndDraw();
+ // RenderWidgetHostNSViewClient implementation.
+ BrowserAccessibilityManager* GetRootBrowserAccessibilityManager() override;
+ void OnNSViewSyncIsRenderViewHost(bool* is_render_view) override;
+ void OnNSViewRequestShutdown() override;
+ void OnNSViewIsFirstResponderChanged(bool is_first_responder) override;
+ void OnNSViewWindowIsKeyChanged(bool is_key) override;
+ void OnNSViewBoundsInWindowChanged(const gfx::Rect& view_bounds_in_window_dip,
+ bool attached_to_window) override;
+ void OnNSViewWindowFrameInScreenChanged(
+ const gfx::Rect& window_frame_in_screen_dip) override;
+ void OnNSViewDisplayChanged(const display::Display& display) override;
+ void OnNSViewBeginKeyboardEvent() override;
+ void OnNSViewEndKeyboardEvent() override;
+ void OnNSViewForwardKeyboardEvent(
+ const NativeWebKeyboardEvent& key_event,
+ const ui::LatencyInfo& latency_info) override;
+ void OnNSViewForwardKeyboardEventWithCommands(
+ const NativeWebKeyboardEvent& key_event,
+ const ui::LatencyInfo& latency_info,
+ const std::vector<EditCommand>& commands) override;
+ void OnNSViewRouteOrProcessMouseEvent(
+ const blink::WebMouseEvent& web_event) override;
+ void OnNSViewRouteOrProcessWheelEvent(
+ const blink::WebMouseWheelEvent& web_event) override;
+ void OnNSViewForwardMouseEvent(
+ const blink::WebMouseEvent& web_event) override;
+ void OnNSViewForwardWheelEvent(
+ const blink::WebMouseWheelEvent& web_event) override;
+ void OnNSViewGestureBegin(blink::WebGestureEvent begin_event) override;
+ void OnNSViewGestureUpdate(blink::WebGestureEvent update_event) override;
+ void OnNSViewGestureEnd(blink::WebGestureEvent end_event) override;
+ void OnNSViewSmartMagnify(
+ const blink::WebGestureEvent& smart_magnify_event) override;
+ void OnNSViewImeSetComposition(
+ const base::string16& text,
+ const std::vector<ui::ImeTextSpan>& ime_text_spans,
+ const gfx::Range& replacement_range,
+ int selection_start,
+ int selection_end) override;
+ void OnNSViewImeCommitText(const base::string16& text,
+ const gfx::Range& replacement_range) override;
+ void OnNSViewImeFinishComposingText() override;
+ void OnNSViewImeCancelComposition() override;
+ void OnNSViewLookUpDictionaryOverlayAtPoint(
+ const gfx::PointF& root_point) override;
+ void OnNSViewLookUpDictionaryOverlayFromRange(
+ const gfx::Range& range) override;
+ void OnNSViewSyncGetTextInputType(
+ ui::TextInputType* text_input_type) override;
+ void OnNSViewSyncGetCharacterIndexAtPoint(const gfx::PointF& root_point,
+ uint32_t* index) override;
+ void OnNSViewSyncGetFirstRectForRange(const gfx::Range& requested_range,
+ gfx::Rect* rect,
+ gfx::Range* actual_range,
+ bool* success) override;
+ void OnNSViewExecuteEditCommand(const std::string& command) override;
+ void OnNSViewUndo() override;
+ void OnNSViewRedo() override;
+ void OnNSViewCut() override;
+ void OnNSViewCopy() override;
+ void OnNSViewCopyToFindPboard() override;
+ void OnNSViewPaste() override;
+ void OnNSViewPasteAndMatchStyle() override;
+ void OnNSViewSelectAll() override;
+ void OnNSViewSpeakSelection() override;
+ void OnNSViewStopSpeaking() override;
+ void OnNSViewSyncIsSpeaking(bool* is_speaking) override;
+
// BrowserCompositorMacClient implementation.
SkColor BrowserCompositorMacGetGutterColor() const override;
- void BrowserCompositorMacOnBeginFrame() override;
+ void BrowserCompositorMacOnBeginFrame(base::TimeTicks frame_time) override;
void OnFrameTokenChanged(uint32_t frame_token) override;
void DidReceiveFirstFrameAfterNavigation() override;
void DestroyCompositorForShutdown() override;
+ void WasResized() override;
// AcceleratedWidgetMacNSView implementation.
NSView* AcceleratedWidgetGetNSView() const override;
@@ -531,8 +389,26 @@ class CONTENT_EXPORT RenderWidgetHostViewMac
// in the destruction path of the WebContentsImpl.
RenderWidgetHostDelegate* GetFocusedRenderWidgetHostDelegate();
+ // Returns the RenderWidgetHostImpl to which Ime messages from the NSView
+ // should be targeted. This exists to preserve historical behavior, and may
+ // not be the desired behavior.
+ // https://crbug.com/831843
+ RenderWidgetHostImpl* GetWidgetForIme();
+
+ // When inside a block of handling a keyboard event, returns the
+ // RenderWidgetHostImpl to which all keyboard and Ime messages from the NSView
+ // should be fowarded. This exists to preserve historical behavior, and may
+ // not be the desired behavior.
+ // https://crbug.com/831843
+ RenderWidgetHostImpl* GetWidgetForKeyboardEvent();
+
+ protected:
+ // This class is to be deleted through the Destroy method.
+ ~RenderWidgetHostViewMac() override;
+
private:
friend class RenderWidgetHostViewMacTest;
+ FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewMacTest, GetPageTextForSpeech);
// Allocate a new FrameSinkId if this object is the platform view of a
// RenderWidgetHostViewGuest. This FrameSinkId will not be actually used in
@@ -541,22 +417,13 @@ class CONTENT_EXPORT RenderWidgetHostViewMac
// collide with FrameSinkIds used by RenderWidgetHostImpls.
static viz::FrameSinkId AllocateFrameSinkIdForGuestViewHack();
- // Returns whether this render view is a popup (autocomplete window).
- bool IsPopup() const;
-
// Shuts down the render_widget_host_. This is a separate function so we can
// invoke it from the message loop.
void ShutdownHost();
- // IPC message handlers.
- void OnGetRenderedTextCompleted(const std::string& text);
-
// Send updated vsync parameters to the top level display.
void UpdateDisplayVSyncParameters();
- // Dispatches a TTS session.
- void SpeakText(const std::string& text);
-
// Adds/Removes frame observer based on state.
void UpdateNeedsBeginFramesInternal();
@@ -564,10 +431,39 @@ class CONTENT_EXPORT RenderWidgetHostViewMac
blink::WebMouseWheelEvent wheel_event,
bool should_route_event);
- // The associated view. This is weak and is inserted into the view hierarchy
- // to own this RenderWidgetHostViewMac object. Set to nil at the start of the
- // destructor.
- RenderWidgetHostViewCocoa* cocoa_view_;
+ void OnResizeDueToAutoResizeComplete(const gfx::Size& new_size,
+ uint64_t sequence_number);
+
+ void OnGotStringForDictionaryOverlay(
+ int32_t targetWidgetProcessId,
+ int32_t targetWidgetRoutingId,
+ const mac::AttributedStringCoder::EncodedString& encodedString,
+ gfx::Point baselinePoint);
+
+ // Gets a textual view of the page's contents, and passes it to the callback
+ // provided.
+ using SpeechCallback = base::OnceCallback<void(const base::string16&)>;
+ void GetPageTextForSpeech(SpeechCallback callback);
+
+ // Interface through which the NSView is to be manipulated.
+ std::unique_ptr<RenderWidgetHostNSViewBridge> ns_view_bridge_;
+
+ // State tracked by Show/Hide/IsShowing.
+ bool is_visible_ = false;
+
+ // The bounds of the view in its NSWindow's coordinate system (with origin
+ // in the upper-left).
+ gfx::Rect view_bounds_in_window_dip_;
+
+ // The frame of the window in the global display::Screen coordinate system
+ // (where the origin is the upper-left corner of Screen::GetPrimaryDisplay).
+ gfx::Rect window_frame_in_screen_dip_;
+
+ // Cached copy of the display information pushed to us from the NSView.
+ display::Display display_;
+
+ // Whether or not the NSView is first responder.
+ bool is_first_responder_ = false;
// Indicates if the page is loading.
bool is_loading_;
@@ -575,25 +471,10 @@ class CONTENT_EXPORT RenderWidgetHostViewMac
// Whether it's allowed to pause waiting for a new frame.
bool allow_pause_for_resize_or_repaint_;
- // The last scroll offset of the view.
- gfx::Vector2dF last_scroll_offset_;
-
- // The text to be shown in the tooltip, supplied by the renderer.
- base::string16 tooltip_text_;
-
// True when this view acts as a platform view hack for a
// RenderWidgetHostViewGuest.
bool is_guest_view_hack_;
- // The window used for popup widgets.
- base::scoped_nsobject<NSWindow> popup_window_;
-
- // The fullscreen window used for pepper flash.
- base::scoped_nsobject<NSWindow> pepper_fullscreen_window_;
- base::scoped_nsobject<FullscreenWindowManager> fullscreen_window_manager_;
- // Our parent host view, if this is fullscreen. NULL otherwise.
- RenderWidgetHostViewMac* fullscreen_parent_host_view_;
-
// Display link for getting vsync info.
scoped_refptr<ui::DisplayLinkMac> display_link_;
@@ -623,6 +504,35 @@ class CONTENT_EXPORT RenderWidgetHostViewMac
std::unique_ptr<CursorManager> cursor_manager_;
+ // Used to track active password input sessions.
+ std::unique_ptr<ui::ScopedPasswordInputEnabler> password_input_enabler_;
+
+ // Used to ensure that a consistent RenderWidgetHost is targeted throughout
+ // the duration of a keyboard event.
+ bool in_keyboard_event_ = false;
+ int32_t keyboard_event_widget_process_id_ = 0;
+ int32_t keyboard_event_widget_routing_id_ = 0;
+
+ // When a gesture starts, the system does not inform the view of which type
+ // of gesture is happening (magnify, rotate, etc), rather, it just informs
+ // the view that some as-yet-undefined gesture is starting. Capture the
+ // information about the gesture's beginning event here. It will be used to
+ // create a specific gesture begin event later.
+ std::unique_ptr<blink::WebGestureEvent> gesture_begin_event_;
+
+ // This is set if a GesturePinchBegin event has been sent in the lifetime of
+ // |gesture_begin_event__|. If set, a GesturePinchEnd will be sent when the
+ // gesture ends.
+ bool gesture_begin_pinch_sent_ = false;
+
+ // To avoid accidental pinches, require that a certain zoom threshold be
+ // reached before forwarding it to the browser. Use |pinch_unused_amount_| to
+ // hold this value. If the user reaches this value, don't re-require the
+ // threshold be reached until the page has been zoomed back to page scale of
+ // one.
+ bool pinch_has_reached_zoom_threshold_ = false;
+ float pinch_unused_amount_ = 1.f;
+
// Factory used to safely scope delayed calls to ShutdownHost().
base::WeakPtrFactory<RenderWidgetHostViewMac> weak_factory_;
diff --git a/chromium/content/browser/renderer_host/render_widget_host_view_mac.mm b/chromium/content/browser/renderer_host/render_widget_host_view_mac.mm
index 6e947778990..6a161f0f36c 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_view_mac.mm
+++ b/chromium/content/browser/renderer_host/render_widget_host_view_mac.mm
@@ -5,374 +5,54 @@
#include "content/browser/renderer_host/render_widget_host_view_mac.h"
#import <Carbon/Carbon.h>
-#import <objc/runtime.h>
-#include <OpenGL/gl.h>
-#include <QuartzCore/QuartzCore.h>
-#include <stdint.h>
#include <limits>
#include <utility>
#include "base/bind.h"
-#include "base/callback_helpers.h"
#include "base/command_line.h"
-#include "base/debug/crash_logging.h"
#include "base/logging.h"
#include "base/mac/mac_util.h"
#include "base/mac/scoped_cftyperef.h"
-#import "base/mac/scoped_nsobject.h"
-#include "base/mac/sdk_forward_declarations.h"
#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/metrics/histogram_macros.h"
-#include "base/numerics/safe_conversions.h"
-#include "base/strings/string_util.h"
-#include "base/strings/stringprintf.h"
#include "base/strings/sys_string_conversions.h"
#include "base/strings/utf_string_conversions.h"
-#include "base/sys_info.h"
-#include "base/threading/thread_task_runner_handle.h"
-#include "base/trace_event/trace_event.h"
-#import "content/browser/accessibility/browser_accessibility_cocoa.h"
-#import "content/browser/accessibility/browser_accessibility_mac.h"
#include "content/browser/accessibility/browser_accessibility_manager_mac.h"
-#import "content/browser/cocoa/system_hotkey_helper_mac.h"
-#import "content/browser/cocoa/system_hotkey_map.h"
-#include "content/browser/frame_host/frame_tree.h"
-#include "content/browser/frame_host/frame_tree_node.h"
-#include "content/browser/frame_host/render_frame_host_impl.h"
-#include "content/browser/gpu/compositor_util.h"
#include "content/browser/renderer_host/cursor_manager.h"
#import "content/browser/renderer_host/input/synthetic_gesture_target_mac.h"
#include "content/browser/renderer_host/input/web_input_event_builders_mac.h"
+#include "content/browser/renderer_host/render_view_host_delegate.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/renderer_host/render_widget_helper.h"
-#include "content/browser/renderer_host/render_widget_host_delegate.h"
#include "content/browser/renderer_host/render_widget_host_input_event_router.h"
-#import "content/browser/renderer_host/render_widget_host_view_mac_dictionary_helper.h"
-#import "content/browser/renderer_host/render_widget_host_view_mac_editcommand_helper.h"
+#import "content/browser/renderer_host/render_widget_host_ns_view_bridge.h"
+#import "content/browser/renderer_host/render_widget_host_view_cocoa.h"
#import "content/browser/renderer_host/text_input_client_mac.h"
-#include "content/common/accessibility_messages.h"
-#include "content/common/edit_command.h"
-#include "content/common/input_messages.h"
#include "content/common/text_input_state.h"
#include "content/common/view_messages.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_plugin_guest_manager.h"
-#include "content/public/browser/browser_thread.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "content/public/browser/render_widget_host.h"
-#import "content/public/browser/render_widget_host_view_mac_delegate.h"
#include "content/public/browser/web_contents.h"
-#include "gpu/ipc/common/gpu_messages.h"
#include "skia/ext/platform_canvas.h"
#include "skia/ext/skia_utils_mac.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#import "ui/base/clipboard/clipboard_util_mac.h"
#include "ui/base/cocoa/animation_utils.h"
-#import "ui/base/cocoa/appkit_utils.h"
#include "ui/base/cocoa/cocoa_base_utils.h"
-#import "ui/base/cocoa/fullscreen_window_manager.h"
-#import "ui/base/cocoa/underlay_opengl_hosting_window.h"
-#include "ui/compositor/compositor.h"
-#include "ui/compositor/layer.h"
+#import "ui/base/cocoa/secure_password_input.h"
+#include "ui/base/cocoa/text_services_context_menu.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
-#include "ui/events/base_event_utils.h"
-#include "ui/events/event_utils.h"
-#include "ui/events/keycodes/keyboard_codes.h"
#include "ui/gfx/geometry/dip_util.h"
-#include "ui/gfx/geometry/point.h"
-#include "ui/gfx/geometry/rect_conversions.h"
-#include "ui/gfx/geometry/size_conversions.h"
-#include "ui/gfx/scoped_ns_graphics_context_save_gstate_mac.h"
+#include "ui/gfx/mac/coordinate_conversion.h"
#include "ui/gl/gl_switches.h"
-using content::BrowserAccessibility;
-using content::BrowserAccessibilityManager;
-using content::EditCommand;
-using content::FrameTreeNode;
-using content::NativeWebKeyboardEvent;
-using content::RenderFrameHost;
-using content::RenderViewHost;
-using content::RenderViewHostImpl;
-using content::RenderWidgetHostImpl;
-using content::RenderWidgetHostView;
-using content::RenderWidgetHostViewMac;
-using content::RenderWidgetHostViewMacEditCommandHelper;
-using content::TextInputClientMac;
-using content::WebContents;
-using content::WebGestureEventBuilder;
-using content::WebMouseEventBuilder;
-using content::WebMouseWheelEventBuilder;
using blink::WebInputEvent;
using blink::WebMouseEvent;
-using blink::WebMouseWheelEvent;
using blink::WebGestureEvent;
-namespace {
-
-// Whether a keyboard event has been reserved by OSX.
-BOOL EventIsReservedBySystem(NSEvent* event) {
- content::SystemHotkeyHelperMac* helper =
- content::SystemHotkeyHelperMac::GetInstance();
- return helper->map()->IsEventReserved(event);
-}
-
-RenderWidgetHostView* GetRenderWidgetHostViewToUse(
- RenderWidgetHostViewMac* render_widget_host_view) {
- WebContents* web_contents = render_widget_host_view->GetWebContents();
- if (!web_contents)
- return render_widget_host_view;
- content::BrowserPluginGuestManager* guest_manager =
- web_contents->GetBrowserContext()->GetGuestManager();
- if (!guest_manager)
- return render_widget_host_view;
- content::WebContents* guest =
- guest_manager->GetFullPageGuest(web_contents);
- if (!guest)
- return render_widget_host_view;
- return guest->GetRenderWidgetHostView();
-}
-
-} // namespace
-
-// These are not documented, so use only after checking -respondsToSelector:.
-@interface NSApplication (UndocumentedSpeechMethods)
-- (void)speakString:(NSString*)string;
-- (void)stopSpeaking:(id)sender;
-- (BOOL)isSpeaking;
-@end
-
-// Private methods:
-@interface RenderWidgetHostViewCocoa ()
-@property(nonatomic, assign) NSRange selectedRange;
-@property(nonatomic, assign) NSRange markedRange;
-
-- (BOOL)shouldAutohideCursorForEvent:(NSEvent*)event;
-- (id)initWithRenderWidgetHostViewMac:(RenderWidgetHostViewMac*)r;
-- (void)processedWheelEvent:(const blink::WebMouseWheelEvent&)event
- consumed:(BOOL)consumed;
-- (void)processedGestureScrollEvent:(const blink::WebGestureEvent&)event
- consumed:(BOOL)consumed;
-- (void)processedOverscroll:(const ui::DidOverscrollParams&)params;
-- (void)keyEvent:(NSEvent*)theEvent wasKeyEquivalent:(BOOL)equiv;
-- (void)windowDidChangeBackingProperties:(NSNotification*)notification;
-- (void)windowChangedGlobalFrame:(NSNotification*)notification;
-- (void)windowDidBecomeKey:(NSNotification*)notification;
-- (void)windowDidResignKey:(NSNotification*)notification;
-- (void)updateScreenProperties;
-- (void)setResponderDelegate:
- (NSObject<RenderWidgetHostViewMacDelegate>*)delegate;
-- (void)showLookUpDictionaryOverlayInternal:(NSAttributedString*) string
- baselinePoint:(NSPoint) baselinePoint
- targetView:(NSView*) view;
-@end
-
-// A window subclass that allows the fullscreen window to become main and gain
-// keyboard focus. This is only used for pepper flash. Normal fullscreen is
-// handled by the browser.
-@interface PepperFlashFullscreenWindow : UnderlayOpenGLHostingWindow
-@end
-
-@implementation PepperFlashFullscreenWindow
-
-- (BOOL)canBecomeKeyWindow {
- return YES;
-}
-
-- (BOOL)canBecomeMainWindow {
- return YES;
-}
-
-@end
-
-@interface RenderWidgetPopupWindow : NSWindow {
- // The event tap that allows monitoring of all events, to properly close with
- // a click outside the bounds of the window.
- id clickEventTap_;
-}
-@end
-
-@implementation RenderWidgetPopupWindow
-
-- (id)initWithContentRect:(NSRect)contentRect
- styleMask:(NSUInteger)windowStyle
- backing:(NSBackingStoreType)bufferingType
- defer:(BOOL)deferCreation {
- if (self = [super initWithContentRect:contentRect
- styleMask:windowStyle
- backing:bufferingType
- defer:deferCreation]) {
- [self setBackgroundColor:[NSColor clearColor]];
- [self startObservingClicks];
- }
- return self;
-}
-
-- (void)close {
- [self stopObservingClicks];
- [super close];
-}
-
-// Gets called when the menubar is clicked.
-// Needed because the local event monitor doesn't see the click on the menubar.
-- (void)beganTracking:(NSNotification*)notification {
- [self close];
-}
-
-// Install the callback.
-- (void)startObservingClicks {
- clickEventTap_ = [NSEvent addLocalMonitorForEventsMatchingMask:NSAnyEventMask
- handler:^NSEvent* (NSEvent* event) {
- if ([event window] == self)
- return event;
- NSEventType eventType = [event type];
- if (eventType == NSLeftMouseDown || eventType == NSRightMouseDown)
- [self close];
- return event;
- }];
-
- NSNotificationCenter* notificationCenter =
- [NSNotificationCenter defaultCenter];
- [notificationCenter addObserver:self
- selector:@selector(beganTracking:)
- name:NSMenuDidBeginTrackingNotification
- object:[NSApp mainMenu]];
-}
-
-// Remove the callback.
-- (void)stopObservingClicks {
- if (!clickEventTap_)
- return;
-
- [NSEvent removeMonitor:clickEventTap_];
- clickEventTap_ = nil;
-
- NSNotificationCenter* notificationCenter =
- [NSNotificationCenter defaultCenter];
- [notificationCenter removeObserver:self
- name:NSMenuDidBeginTrackingNotification
- object:[NSApp mainMenu]];
-}
-
-@end
-
-namespace {
-
-// Maximum number of characters we allow in a tooltip.
-const size_t kMaxTooltipLength = 1024;
-
-// TODO(suzhe): Upstream this function.
-blink::WebColor WebColorFromNSColor(NSColor *color) {
- CGFloat r, g, b, a;
- [color getRed:&r green:&g blue:&b alpha:&a];
-
- return
- std::max(0, std::min(static_cast<int>(lroundf(255.0f * a)), 255)) << 24 |
- std::max(0, std::min(static_cast<int>(lroundf(255.0f * r)), 255)) << 16 |
- std::max(0, std::min(static_cast<int>(lroundf(255.0f * g)), 255)) << 8 |
- std::max(0, std::min(static_cast<int>(lroundf(255.0f * b)), 255));
-}
-
-// Extract underline information from an attributed string. Mostly copied from
-// third_party/WebKit/Source/WebKit/mac/WebView/WebHTMLView.mm
-void ExtractUnderlines(NSAttributedString* string,
- std::vector<ui::ImeTextSpan>* ime_text_spans) {
- int length = [[string string] length];
- int i = 0;
- while (i < length) {
- NSRange range;
- NSDictionary* attrs = [string attributesAtIndex:i
- longestEffectiveRange:&range
- inRange:NSMakeRange(i, length - i)];
- if (NSNumber *style = [attrs objectForKey:NSUnderlineStyleAttributeName]) {
- blink::WebColor color = SK_ColorBLACK;
- if (NSColor *colorAttr =
- [attrs objectForKey:NSUnderlineColorAttributeName]) {
- color = WebColorFromNSColor(
- [colorAttr colorUsingColorSpaceName:NSDeviceRGBColorSpace]);
- }
- ime_text_spans->push_back(ui::ImeTextSpan(
- ui::ImeTextSpan::Type::kComposition, range.location,
- NSMaxRange(range), color, [style intValue] > 1, SK_ColorTRANSPARENT));
- }
- i = range.location + range.length;
- }
-}
-
-// EnablePasswordInput() and DisablePasswordInput() are copied from
-// enableSecureTextInput() and disableSecureTextInput() functions in
-// third_party/WebKit/WebCore/platform/SecureTextInput.cpp
-// But we don't call EnableSecureEventInput() and DisableSecureEventInput()
-// here, because they are already called in webkit and they are system wide
-// functions.
-void EnablePasswordInput() {
- CFArrayRef inputSources = TISCreateASCIICapableInputSourceList();
- TSMSetDocumentProperty(0, kTSMDocumentEnabledInputSourcesPropertyTag,
- sizeof(CFArrayRef), &inputSources);
- CFRelease(inputSources);
-}
-
-void DisablePasswordInput() {
- TSMRemoveDocumentProperty(0, kTSMDocumentEnabledInputSourcesPropertyTag);
-}
-
-// Calls to [NSScreen screens], required by FlipYFromRectToScreen and
-// FlipNSRectToRectScreen, can take several milliseconds. Only re-compute this
-// value when screen info changes.
-// TODO(ccameron): An observer on every RWHVCocoa will set this to false
-// on NSApplicationDidChangeScreenParametersNotification. Only one observer
-// is necessary.
-bool g_screen_info_up_to_date = false;
-
-float FlipYFromRectToScreen(float y, float rect_height) {
- TRACE_EVENT0("browser", "FlipYFromRectToScreen");
- static CGFloat screen_zero_height = 0;
- if (!g_screen_info_up_to_date) {
- if ([[NSScreen screens] count] > 0) {
- screen_zero_height =
- [[[NSScreen screens] firstObject] frame].size.height;
- g_screen_info_up_to_date = true;
- } else {
- return y;
- }
- }
- return screen_zero_height - y - rect_height;
-}
-
-// Adjusts an NSRect in Cocoa screen coordinates to have an origin in the upper
-// left of the primary screen (Carbon coordinates), and stuffs it into a
-// gfx::Rect.
-gfx::Rect FlipNSRectToRectScreen(const NSRect& rect) {
- gfx::Rect new_rect(NSRectToCGRect(rect));
- new_rect.set_y(FlipYFromRectToScreen(new_rect.y(), new_rect.height()));
- return new_rect;
-}
-
-// Returns the window that visually contains the given view. This is different
-// from [view window] in the case of tab dragging, where the view's owning
-// window is a floating panel attached to the actual browser window that the tab
-// is visually part of.
-NSWindow* ApparentWindowForView(NSView* view) {
- // TODO(shess): In case of !window, the view has been removed from
- // the view hierarchy because the tab isn't main. Could retrieve
- // the information from the main tab for our window.
- NSWindow* enclosing_window = [view window];
-
- // See if this is a tab drag window. The width check is to distinguish that
- // case from extension popup windows.
- NSWindow* ancestor_window = [enclosing_window parentWindow];
- if (ancestor_window && (NSWidth([enclosing_window frame]) ==
- NSWidth([ancestor_window frame]))) {
- enclosing_window = ancestor_window;
- }
-
- return enclosing_window;
-}
-
-} // namespace
-
namespace content {
////////////////////////////////////////////////////////////////////////////////
@@ -382,14 +62,17 @@ SkColor RenderWidgetHostViewMac::BrowserCompositorMacGetGutterColor() const {
// When making an element on the page fullscreen the element's background
// may not match the page's, so use black as the gutter color to avoid
// flashes of brighter colors during the transition.
- if (render_widget_host_->delegate() &&
- render_widget_host_->delegate()->IsFullscreenForCurrentTab()) {
+ if (host()->delegate() && host()->delegate()->IsFullscreenForCurrentTab()) {
return SK_ColorBLACK;
}
return last_frame_root_background_color_;
}
-void RenderWidgetHostViewMac::BrowserCompositorMacOnBeginFrame() {
+void RenderWidgetHostViewMac::BrowserCompositorMacOnBeginFrame(
+ base::TimeTicks frame_time) {
+ // ProgressFling must get called for middle click autoscroll fling on Mac.
+ if (host())
+ host()->ProgressFling(frame_time);
UpdateNeedsBeginFramesInternal();
}
@@ -398,18 +81,26 @@ void RenderWidgetHostViewMac::OnFrameTokenChanged(uint32_t frame_token) {
}
void RenderWidgetHostViewMac::DidReceiveFirstFrameAfterNavigation() {
- render_widget_host_->DidReceiveFirstFrameAfterNavigation();
+ host()->DidReceiveFirstFrameAfterNavigation();
}
void RenderWidgetHostViewMac::DestroyCompositorForShutdown() {
- browser_compositor_.reset();
+ // When RenderWidgetHostViewMac was owned by an NSView, this function was
+ // necessary to ensure that the ui::Compositor did not outlive the
+ // infrastructure that was needed to support it.
+ // https://crbug.com/805726
+ Destroy();
+}
+
+void RenderWidgetHostViewMac::WasResized() {
+ host()->WasResized();
}
////////////////////////////////////////////////////////////////////////////////
// AcceleratedWidgetMacNSView, public:
NSView* RenderWidgetHostViewMac::AcceleratedWidgetGetNSView() const {
- return cocoa_view_;
+ return cocoa_view();
}
void RenderWidgetHostViewMac::AcceleratedWidgetGetVSyncParameters(
@@ -437,46 +128,41 @@ void RenderWidgetHostViewMac::AcceleratedWidgetSwapCompleted() {
RenderWidgetHostViewMac::RenderWidgetHostViewMac(RenderWidgetHost* widget,
bool is_guest_view_hack)
- : render_widget_host_(RenderWidgetHostImpl::From(widget)),
+ : RenderWidgetHostViewBase(widget),
page_at_minimum_scale_(true),
- mouse_wheel_phase_handler_(RenderWidgetHostImpl::From(widget), this),
+ mouse_wheel_phase_handler_(this),
is_loading_(false),
allow_pause_for_resize_or_repaint_(true),
is_guest_view_hack_(is_guest_view_hack),
- fullscreen_parent_host_view_(nullptr),
weak_factory_(this) {
- // |cocoa_view_| owns us and we will be deleted when |cocoa_view_|
- // goes away. Since we autorelease it, our caller must put
- // |GetNativeView()| into the view hierarchy right after calling us.
- cocoa_view_ = [[[RenderWidgetHostViewCocoa alloc]
- initWithRenderWidgetHostViewMac:this] autorelease];
+ // The NSView is on the other side of |ns_view_bridge_|.
+ ns_view_bridge_ = RenderWidgetHostNSViewBridge::Create(this);
- background_layer_.reset([[CALayer alloc] init]);
- [cocoa_view_ setLayer:background_layer_];
- [cocoa_view_ setWantsLayer:YES];
+ // Guess that the initial screen we will be on is the screen of the current
+ // window (since that's the best guess that we have, and is usually right).
+ // https://crbug.com/357443
+ display_ =
+ display::Screen::GetScreen()->GetDisplayNearestWindow([NSApp keyWindow]);
viz::FrameSinkId frame_sink_id = is_guest_view_hack_
? AllocateFrameSinkIdForGuestViewHack()
- : render_widget_host_->GetFrameSinkId();
+ : host()->GetFrameSinkId();
browser_compositor_.reset(
- new BrowserCompositorMac(this, this, render_widget_host_->is_hidden(),
- [cocoa_view_ window], frame_sink_id));
-
- display::Screen::GetScreen()->AddObserver(this);
+ new BrowserCompositorMac(this, this, host()->is_hidden(),
+ [cocoa_view() window], display_, frame_sink_id));
if (!is_guest_view_hack_)
- render_widget_host_->SetView(this);
+ host()->SetView(this);
// Let the page-level input event router know about our surface ID
// namespace for surface-based hit testing.
- if (render_widget_host_->delegate() &&
- render_widget_host_->delegate()->GetInputEventRouter()) {
- render_widget_host_->delegate()->GetInputEventRouter()->AddFrameSinkIdOwner(
+ if (host()->delegate() && host()->delegate()->GetInputEventRouter()) {
+ host()->delegate()->GetInputEventRouter()->AddFrameSinkIdOwner(
GetFrameSinkId(), this);
}
- RenderViewHost* rvh = RenderViewHost::From(render_widget_host_);
+ RenderViewHost* rvh = RenderViewHost::From(host());
bool needs_begin_frames = true;
if (rvh) {
@@ -491,11 +177,10 @@ RenderWidgetHostViewMac::RenderWidgetHostViewMac(RenderWidgetHost* widget,
if (GetTextInputManager())
GetTextInputManager()->AddObserver(this);
- // Because of the way Mac pumps messages during resize, (see the code
- // in RenderMessageFilter::OnMessageReceived), SetNeedsBeginFrame
- // messages are not delayed on Mac. This leads to creation-time
- // raciness where renderer sends a SetNeedsBeginFrame(true) before
- // the renderer host is created to recieve it.
+ // Because of the way Mac pumps messages during resize, SetNeedsBeginFrame
+ // messages are not delayed on Mac. This leads to creation-time raciness
+ // where renderer sends a SetNeedsBeginFrame(true) before the renderer host is
+ // created to receive it.
//
// Any renderer that will produce frames needs to have begin frames sent to
// it. So unless it is never visible, start this value at true here to avoid
@@ -505,36 +190,15 @@ RenderWidgetHostViewMac::RenderWidgetHostViewMac(RenderWidgetHost* widget,
}
RenderWidgetHostViewMac::~RenderWidgetHostViewMac() {
- display::Screen::GetScreen()->RemoveObserver(this);
-
- // This is being called from |cocoa_view_|'s destructor, so invalidate the
- // pointer.
- cocoa_view_ = nil;
-
- UnlockMouse();
-
- browser_compositor_.reset();
-
- // We are owned by RenderWidgetHostViewCocoa, so if we go away before the
- // RenderWidgetHost does we need to tell it not to hold a stale pointer to
- // us.
- if (render_widget_host_) {
- // If this is a RenderWidgetHostViewGuest's platform_view_, we're not the
- // RWH's view, the RenderWidgetHostViewGuest is. So don't reset the RWH's
- // view, the RenderWidgetHostViewGuest will do it.
- if (!is_guest_view_hack_)
- render_widget_host_->SetView(NULL);
- }
+}
- // In case the view is deleted (by cocoa view) before calling destroy, we need
- // to remove this view from the observer list of TextInputManager.
- if (text_input_manager_ && text_input_manager_->HasObserver(this))
- text_input_manager_->RemoveObserver(this);
+RenderWidgetHostViewCocoa* RenderWidgetHostViewMac::cocoa_view() const {
+ return ns_view_bridge_->GetRenderWidgetHostViewCocoa();
}
void RenderWidgetHostViewMac::SetDelegate(
NSObject<RenderWidgetHostViewMacDelegate>* delegate) {
- [cocoa_view_ setResponderDelegate:delegate];
+ [cocoa_view() setResponderDelegate:delegate];
}
void RenderWidgetHostViewMac::SetAllowPauseForResizeOrRepaint(bool allow) {
@@ -567,16 +231,6 @@ RenderWidgetHostViewMac::GetTextSelection() {
///////////////////////////////////////////////////////////////////////////////
// RenderWidgetHostViewMac, RenderWidgetHostView implementation:
-bool RenderWidgetHostViewMac::OnMessageReceived(const IPC::Message& message) {
- bool handled = true;
- IPC_BEGIN_MESSAGE_MAP(RenderWidgetHostViewMac, message)
- IPC_MESSAGE_HANDLER(ViewMsg_GetRenderedTextCompleted,
- OnGetRenderedTextCompleted)
- IPC_MESSAGE_UNHANDLED(handled = false)
- IPC_END_MESSAGE_MAP()
- return handled;
-}
-
void RenderWidgetHostViewMac::InitAsChild(
gfx::NativeView parent_view) {
}
@@ -584,120 +238,18 @@ void RenderWidgetHostViewMac::InitAsChild(
void RenderWidgetHostViewMac::InitAsPopup(
RenderWidgetHostView* parent_host_view,
const gfx::Rect& pos) {
- bool activatable = popup_type_ == blink::kWebPopupTypeNone;
- [cocoa_view_ setCloseOnDeactivate:YES];
- [cocoa_view_ setCanBeKeyView:activatable ? YES : NO];
-
- NSPoint origin_global = NSPointFromCGPoint(pos.origin().ToCGPoint());
- origin_global.y = FlipYFromRectToScreen(origin_global.y, pos.height());
-
- popup_window_.reset([[RenderWidgetPopupWindow alloc]
- initWithContentRect:NSMakeRect(origin_global.x, origin_global.y,
- pos.width(), pos.height())
- styleMask:NSBorderlessWindowMask
- backing:NSBackingStoreBuffered
- defer:NO]);
- [popup_window_ setLevel:NSPopUpMenuWindowLevel];
- [popup_window_ setReleasedWhenClosed:NO];
- [popup_window_ makeKeyAndOrderFront:nil];
- [[popup_window_ contentView] addSubview:cocoa_view_];
- [cocoa_view_ setFrame:[[popup_window_ contentView] bounds]];
- [cocoa_view_ setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
- [[NSNotificationCenter defaultCenter]
- addObserver:cocoa_view_
- selector:@selector(popupWindowWillClose:)
- name:NSWindowWillCloseNotification
- object:popup_window_];
-}
-
-// This function creates the fullscreen window and hides the dock and menubar if
-// necessary. Note, this codepath is only used for pepper flash when
-// pp::FlashFullScreen::SetFullscreen() is called. If
-// pp::FullScreen::SetFullscreen() is called then the entire browser window
-// will enter fullscreen instead.
+ // This path is used by the time/date picker.
+ ns_view_bridge_->InitAsPopup(pos, popup_type_);
+}
+
void RenderWidgetHostViewMac::InitAsFullscreen(
RenderWidgetHostView* reference_host_view) {
- fullscreen_parent_host_view_ =
- static_cast<RenderWidgetHostViewMac*>(reference_host_view);
- NSWindow* parent_window = nil;
- if (reference_host_view)
- parent_window = [reference_host_view->GetNativeView() window];
- NSScreen* screen = [parent_window screen];
- if (!screen)
- screen = [NSScreen mainScreen];
-
- pepper_fullscreen_window_.reset([[PepperFlashFullscreenWindow alloc]
- initWithContentRect:[screen frame]
- styleMask:NSBorderlessWindowMask
- backing:NSBackingStoreBuffered
- defer:NO]);
- [pepper_fullscreen_window_ setLevel:NSFloatingWindowLevel];
- [pepper_fullscreen_window_ setReleasedWhenClosed:NO];
- [cocoa_view_ setCanBeKeyView:YES];
- [cocoa_view_ setFrame:[[pepper_fullscreen_window_ contentView] bounds]];
- [cocoa_view_ setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
- // If the pepper fullscreen window isn't opaque then there are performance
- // issues when it's on the discrete GPU and the Chrome window is being drawn
- // to. http://crbug.com/171911
- [pepper_fullscreen_window_ setOpaque:YES];
-
- // Note that this forms a reference cycle between the fullscreen window and
- // the rwhvmac: The PepperFlashFullscreenWindow retains cocoa_view_,
- // but cocoa_view_ keeps pepper_fullscreen_window_ in an instance variable.
- // This cycle is normally broken when -keyEvent: receives an <esc> key, which
- // explicitly calls Shutdown on the render_widget_host_, which calls
- // Destroy() on RWHVMac, which drops the reference to
- // pepper_fullscreen_window_.
- [[pepper_fullscreen_window_ contentView] addSubview:cocoa_view_];
-
- // Note that this keeps another reference to pepper_fullscreen_window_.
- fullscreen_window_manager_.reset([[FullscreenWindowManager alloc]
- initWithWindow:pepper_fullscreen_window_.get()
- desiredScreen:screen]);
- [fullscreen_window_manager_ enterFullscreenMode];
- [pepper_fullscreen_window_ makeKeyAndOrderFront:nil];
-}
-
-void RenderWidgetHostViewMac::release_pepper_fullscreen_window_for_testing() {
- // See comment in InitAsFullscreen(): There is a reference cycle between
- // rwhvmac and fullscreen window, which is usually broken by hitting <esc>.
- // Tests that test pepper fullscreen mode without sending an <esc> event
- // need to call this method to break the reference cycle.
- [fullscreen_window_manager_ exitFullscreenMode];
- fullscreen_window_manager_.reset();
- [pepper_fullscreen_window_ close];
- pepper_fullscreen_window_.reset();
-}
-
-int RenderWidgetHostViewMac::window_number() const {
- NSWindow* window = [cocoa_view_ window];
- if (!window)
- return -1;
- return [window windowNumber];
-}
-
-void RenderWidgetHostViewMac::UpdateDisplayLink() {
- static bool is_vsync_disabled =
- base::CommandLine::ForCurrentProcess()->HasSwitch(
- switches::kDisableGpuVsync);
- if (is_vsync_disabled)
- return;
-
- NSScreen* screen = [[cocoa_view_ window] screen];
- NSDictionary* screen_description = [screen deviceDescription];
- NSNumber* screen_number = [screen_description objectForKey:@"NSScreenNumber"];
- CGDirectDisplayID display_id = [screen_number unsignedIntValue];
-
- display_link_ = ui::DisplayLinkMac::GetForDisplay(display_id);
- if (!display_link_.get()) {
- // Note that on some headless systems, the display link will fail to be
- // created, so this should not be a fatal error.
- LOG(ERROR) << "Failed to create display link.";
- }
+ // This path appears never to be reached.
+ NOTREACHED();
}
void RenderWidgetHostViewMac::UpdateDisplayVSyncParameters() {
- if (!render_widget_host_ || !display_link_.get())
+ if (!host() || !display_link_.get())
return;
if (!display_link_->GetVSyncParameters(&vsync_timebase_, &vsync_interval_)) {
@@ -709,10 +261,6 @@ void RenderWidgetHostViewMac::UpdateDisplayVSyncParameters() {
browser_compositor_->UpdateVSyncParameters(vsync_timebase_, vsync_interval_);
}
-void RenderWidgetHostViewMac::SpeakText(const std::string& text) {
- [NSApp speakString:base::SysUTF8ToNSString(text)];
-}
-
RenderWidgetHostViewBase*
RenderWidgetHostViewMac::GetFocusedViewForTextSelection() {
// We obtain the TextSelection from focused RWH which is obtained from the
@@ -729,29 +277,52 @@ RenderWidgetHostDelegate*
RenderWidgetHostViewMac::GetFocusedRenderWidgetHostDelegate() {
if (auto* focused_widget = GetFocusedWidget())
return focused_widget->delegate();
- return render_widget_host_->delegate();
+ return host()->delegate();
+}
+
+RenderWidgetHostImpl* RenderWidgetHostViewMac::GetWidgetForKeyboardEvent() {
+ DCHECK(in_keyboard_event_);
+ return RenderWidgetHostImpl::FromID(keyboard_event_widget_process_id_,
+ keyboard_event_widget_routing_id_);
+}
+
+RenderWidgetHostImpl* RenderWidgetHostViewMac::GetWidgetForIme() {
+ if (in_keyboard_event_)
+ return GetWidgetForKeyboardEvent();
+ return GetActiveWidget();
}
void RenderWidgetHostViewMac::UpdateNSViewAndDisplayProperties() {
- if (!browser_compositor_)
- return;
+ static bool is_vsync_disabled =
+ base::CommandLine::ForCurrentProcess()->HasSwitch(
+ switches::kDisableGpuVsync);
+ if (!is_vsync_disabled) {
+ display_link_ = ui::DisplayLinkMac::GetForDisplay(display_.id());
+ if (!display_link_.get()) {
+ // Note that on some headless systems, the display link will fail to be
+ // created, so this should not be a fatal error.
+ LOG(ERROR) << "Failed to create display link.";
+ }
+ }
// During auto-resize it is the responsibility of the caller to ensure that
// the NSView and RenderWidgetHostImpl are kept in sync.
- if (render_widget_host_->auto_resize_enabled())
+ if (host()->auto_resize_enabled())
return;
- if (render_widget_host_->delegate())
- render_widget_host_->delegate()->SendScreenRects();
+ if (host()->delegate())
+ host()->delegate()->SendScreenRects();
else
- render_widget_host_->SendScreenRects();
+ host()->SendScreenRects();
// RenderWidgetHostImpl will query BrowserCompositorMac for the dimensions
// to send to the renderer, so it is required that BrowserCompositorMac be
// updated first. Only notify RenderWidgetHostImpl of the update if any
// properties it will query have changed.
- if (browser_compositor_->UpdateNSViewAndDisplay())
- render_widget_host_->NotifyScreenInfoChanged();
+ if (browser_compositor_->UpdateNSViewAndDisplay(
+ view_bounds_in_window_dip_.size(), display_)) {
+ host()->NotifyScreenInfoChanged();
+ }
}
void RenderWidgetHostViewMac::GetScreenInfo(ScreenInfo* screen_info) const {
@@ -759,49 +330,38 @@ void RenderWidgetHostViewMac::GetScreenInfo(ScreenInfo* screen_info) const {
}
void RenderWidgetHostViewMac::Show() {
- ScopedCAActionDisabler disabler;
- [cocoa_view_ setHidden:NO];
-
+ is_visible_ = true;
+ ns_view_bridge_->SetVisible(is_visible_);
browser_compositor_->SetRenderWidgetHostIsHidden(false);
ui::LatencyInfo renderer_latency_info;
- renderer_latency_info.AddLatencyNumber(
- ui::TAB_SHOW_COMPONENT, render_widget_host_->GetLatencyComponentId(), 0);
+ renderer_latency_info.AddLatencyNumber(ui::TAB_SHOW_COMPONENT,
+ host()->GetLatencyComponentId(), 0);
renderer_latency_info.set_trace_id(++tab_show_sequence_);
- render_widget_host_->WasShown(renderer_latency_info);
+ host()->WasShown(renderer_latency_info);
TRACE_EVENT_ASYNC_BEGIN0("latency", "TabSwitching::Latency",
tab_show_sequence_);
// If there is not a frame being currently drawn, kick one, so that the below
// pause will have a frame to wait on.
- render_widget_host_->ScheduleComposite();
+ host()->ScheduleComposite();
PauseForPendingResizeOrRepaintsAndDraw();
}
void RenderWidgetHostViewMac::Hide() {
- if (!browser_compositor_)
- return;
-
- ScopedCAActionDisabler disabler;
- [cocoa_view_ setHidden:YES];
-
- render_widget_host_->WasHidden();
+ is_visible_ = false;
+ ns_view_bridge_->SetVisible(is_visible_);
+ host()->WasHidden();
browser_compositor_->SetRenderWidgetHostIsHidden(true);
}
void RenderWidgetHostViewMac::WasUnOccluded() {
- if (!browser_compositor_)
- return;
-
browser_compositor_->SetRenderWidgetHostIsHidden(false);
- render_widget_host_->WasShown(ui::LatencyInfo());
+ host()->WasShown(ui::LatencyInfo());
}
void RenderWidgetHostViewMac::WasOccluded() {
- if (!browser_compositor_)
- return;
-
- render_widget_host_->WasHidden();
+ host()->WasHidden();
browser_compositor_->SetRenderWidgetHostIsHidden(true);
}
@@ -812,69 +372,23 @@ void RenderWidgetHostViewMac::SetSize(const gfx::Size& size) {
}
void RenderWidgetHostViewMac::SetBounds(const gfx::Rect& rect) {
- // |rect.size()| is view coordinates, |rect.origin| is screen coordinates,
- // TODO(thakis): fix, http://crbug.com/73362
-
- // During the initial creation of the RenderWidgetHostView in
- // WebContentsImpl::CreateRenderViewForRenderManager, SetSize is called with
- // an empty size. In the Windows code flow, it is not ignored because
- // subsequent sizing calls from the OS flow through TCVW::WasSized which calls
- // SetSize() again. On Cocoa, we rely on the Cocoa view struture and resizer
- // flags to keep things sized properly. On the other hand, if the size is not
- // empty then this is a valid request for a pop-up.
- if (rect.size().IsEmpty())
- return;
-
- // Ignore the position of |rect| for non-popup rwhvs. This is because
- // background tabs do not have a window, but the window is required for the
- // coordinate conversions. Popups are always for a visible tab.
- //
- // Note: If |cocoa_view_| has been removed from the view hierarchy, it's still
- // valid for resizing to be requested (e.g., during tab capture, to size the
- // view to screen-capture resolution). In this case, simply treat the view as
- // relative to the screen.
- BOOL isRelativeToScreen = IsPopup() ||
- ![[cocoa_view_ superview] isKindOfClass:[BaseView class]];
- if (isRelativeToScreen) {
- // The position of |rect| is screen coordinate system and we have to
- // consider Cocoa coordinate system is upside-down and also multi-screen.
- NSPoint origin_global = NSPointFromCGPoint(rect.origin().ToCGPoint());
- NSSize size = NSMakeSize(rect.width(), rect.height());
- size = [cocoa_view_ convertSize:size toView:nil];
- origin_global.y = FlipYFromRectToScreen(origin_global.y, size.height);
- NSRect frame = NSMakeRect(origin_global.x, origin_global.y,
- size.width, size.height);
- if (IsPopup())
- [popup_window_ setFrame:frame display:YES];
- else
- [cocoa_view_ setFrame:frame];
- } else {
- BaseView* superview = static_cast<BaseView*>([cocoa_view_ superview]);
- gfx::Rect rect2 = [superview flipNSRectToRect:[cocoa_view_ frame]];
- rect2.set_width(rect.width());
- rect2.set_height(rect.height());
- [cocoa_view_ setFrame:[superview flipRectToNSRect:rect2]];
- }
-}
-
-gfx::Vector2dF RenderWidgetHostViewMac::GetLastScrollOffset() const {
- return last_scroll_offset_;
+ ns_view_bridge_->SetBounds(rect);
}
gfx::NativeView RenderWidgetHostViewMac::GetNativeView() const {
- return cocoa_view_;
+ return cocoa_view();
}
gfx::NativeViewAccessible RenderWidgetHostViewMac::GetNativeViewAccessible() {
- return cocoa_view_;
+ return cocoa_view();
}
void RenderWidgetHostViewMac::Focus() {
- [[cocoa_view_ window] makeFirstResponder:cocoa_view_];
+ ns_view_bridge_->MakeFirstResponder();
}
bool RenderWidgetHostViewMac::HasFocus() const {
- return [[cocoa_view_ window] firstResponder] == cocoa_view_;
+ return is_first_responder_;
}
bool RenderWidgetHostViewMac::IsSurfaceAvailableForCopy() const {
@@ -883,21 +397,12 @@ bool RenderWidgetHostViewMac::IsSurfaceAvailableForCopy() const {
}
bool RenderWidgetHostViewMac::IsShowing() {
- return ![cocoa_view_ isHidden];
+ return is_visible_;
}
gfx::Rect RenderWidgetHostViewMac::GetViewBounds() const {
- NSRect bounds = [cocoa_view_ bounds];
- // TODO(shess): In case of !window, the view has been removed from
- // the view hierarchy because the tab isn't main. Could retrieve
- // the information from the main tab for our window.
- NSWindow* enclosing_window = ApparentWindowForView(cocoa_view_);
- if (!enclosing_window)
- return gfx::Rect(gfx::Size(NSWidth(bounds), NSHeight(bounds)));
-
- bounds = [cocoa_view_ convertRect:bounds toView:nil];
- bounds = [enclosing_window convertRectToScreen:bounds];
- return FlipNSRectToRectScreen(bounds);
+ return view_bounds_in_window_dip_ +
+ window_frame_in_screen_dip_.OffsetFromOrigin();
}
void RenderWidgetHostViewMac::UpdateCursor(const WebCursor& cursor) {
@@ -905,8 +410,7 @@ void RenderWidgetHostViewMac::UpdateCursor(const WebCursor& cursor) {
}
void RenderWidgetHostViewMac::DisplayCursor(const WebCursor& cursor) {
- WebCursor web_cursor = cursor;
- [cocoa_view_ updateCursor:web_cursor.GetNativeCursor()];
+ ns_view_bridge_->DisplayCursor(cursor);
}
CursorManager* RenderWidgetHostViewMac::GetCursorManager() {
@@ -929,13 +433,13 @@ void RenderWidgetHostViewMac::OnUpdateTextInputStateCalled(
// |updated_view| is the last view to change its TextInputState which can be
// used to start/stop monitoring composition info when it has a focused
// editable text input field.
- RenderWidgetHostImpl* widgetHost =
+ RenderWidgetHostImpl* widget_host =
RenderWidgetHostImpl::From(updated_view->GetRenderWidgetHost());
// We might end up here when |updated_view| has had active TextInputState and
// then got destroyed. In that case, |updated_view->GetRenderWidgetHost()|
// returns nullptr.
- if (!widgetHost)
+ if (!widget_host)
return;
// Set the monitor state based on the text input focus state.
@@ -944,8 +448,8 @@ void RenderWidgetHostViewMac::OnUpdateTextInputStateCalled(
bool need_monitor_composition =
has_focus && state && state->type != ui::TEXT_INPUT_TYPE_NONE;
- widgetHost->RequestCompositionUpdates(false /* immediate_request */,
- need_monitor_composition);
+ widget_host->RequestCompositionUpdates(false /* immediate_request */,
+ need_monitor_composition);
if (has_focus) {
SetTextInputActive(true);
@@ -967,7 +471,7 @@ void RenderWidgetHostViewMac::OnUpdateTextInputStateCalled(
void RenderWidgetHostViewMac::OnImeCancelComposition(
TextInputManager* text_input_manager,
RenderWidgetHostViewBase* updated_view) {
- [cocoa_view_ cancelComposition];
+ ns_view_bridge_->CancelComposition();
}
void RenderWidgetHostViewMac::OnImeCompositionRangeChanged(
@@ -979,7 +483,7 @@ void RenderWidgetHostViewMac::OnImeCompositionRangeChanged(
return;
// The RangeChanged message is only sent with valid values. The current
// caret position (start == end) will be sent if there is no IME range.
- [cocoa_view_ setMarkedRange:info->range.ToNSRange()];
+ ns_view_bridge_->SetCompositionRangeInfo(info->range);
}
void RenderWidgetHostViewMac::OnSelectionBoundsChanged(
@@ -1001,30 +505,17 @@ void RenderWidgetHostViewMac::OnSelectionBoundsChanged(
if (!region)
return;
- NSWindow* enclosing_window = ApparentWindowForView(cocoa_view_);
- if (!enclosing_window)
- return;
-
// Create a rectangle for the edge of the selection focus, which will be
// the same as the caret position if the selection is collapsed. That's
// what we want to try to keep centered on-screen if possible.
gfx::Rect gfx_caret_rect(region->focus.edge_top_rounded().x(),
region->focus.edge_top_rounded().y(),
1, region->focus.GetHeight());
+ gfx_caret_rect += view_bounds_in_window_dip_.OffsetFromOrigin();
+ gfx_caret_rect += window_frame_in_screen_dip_.OffsetFromOrigin();
- // Convert the caret rect to CG-style flipped widget-relative coordinates.
+ // Note that UAZoomChangeFocus wants unflipped screen coordinates.
NSRect caret_rect = NSRectFromCGRect(gfx_caret_rect.ToCGRect());
- caret_rect.origin.y = NSHeight([cocoa_view_ bounds]) -
- (caret_rect.origin.y + caret_rect.size.height);
-
- // Now convert that to screen coordinates.
- caret_rect = [cocoa_view_ convertRect:caret_rect toView:nil];
- caret_rect = [enclosing_window convertRectToScreen:caret_rect];
-
- // Finally, flip it again because UAZoomChangeFocus wants unflipped screen
- // coordinates, and call UAZoomChangeFocus to initiate the scroll.
- caret_rect.origin.y = FlipYFromRectToScreen(
- caret_rect.origin.y, caret_rect.size.height);
UAZoomChangeFocus(&caret_rect, &caret_rect, kUAZoomFocusTypeInsertionPoint);
}
@@ -1036,14 +527,16 @@ void RenderWidgetHostViewMac::OnTextSelectionChanged(
const TextInputManager::TextSelection* selection = GetTextSelection();
if (!selection)
return;
+ ns_view_bridge_->SetTextSelection(selection->text(), selection->offset(),
+ selection->range());
+}
- [cocoa_view_ setSelectedRange:selection->range().ToNSRange()];
- // Updates markedRange when there is no marked text so that retrieving
- // markedRange immediately after calling setMarkdText: returns the current
- // caret position.
- if (![cocoa_view_ hasMarkedText]) {
- [cocoa_view_ setMarkedRange:selection->range().ToNSRange()];
- }
+void RenderWidgetHostViewMac::OnRenderFrameMetadataChanged() {
+ last_frame_root_background_color_ = host()
+ ->render_frame_metadata_provider()
+ ->LastRenderFrameMetadata()
+ .root_background_color;
+ RenderWidgetHostViewBase::OnRenderFrameMetadataChanged();
}
void RenderWidgetHostViewMac::RenderProcessGone(base::TerminationStatus status,
@@ -1052,37 +545,23 @@ void RenderWidgetHostViewMac::RenderProcessGone(base::TerminationStatus status,
}
void RenderWidgetHostViewMac::Destroy() {
- // FrameSinkIds registered with RenderWidgetHostInputEventRouter
- // have already been cleared when RenderWidgetHostViewBase notified its
- // observers of our impending destruction.
- [[NSNotificationCenter defaultCenter]
- removeObserver:cocoa_view_
- name:NSWindowWillCloseNotification
- object:popup_window_];
-
- // We've been told to destroy.
- [cocoa_view_ retain];
- [cocoa_view_ removeFromSuperview];
- [cocoa_view_ autorelease];
-
- [popup_window_ close];
- popup_window_.autorelease();
-
- [fullscreen_window_manager_ exitFullscreenMode];
- fullscreen_window_manager_.reset();
- [pepper_fullscreen_window_ close];
-
- // This can be called as part of processing the window's responder
- // chain, for instance |-performKeyEquivalent:|. In that case the
- // object needs to survive until the stack unwinds.
- pepper_fullscreen_window_.autorelease();
+ // Unlock the mouse in the NSView's process before destroying our bridge to
+ // it.
+ if (mouse_locked_) {
+ mouse_locked_ = false;
+ ns_view_bridge_->SetCursorLocked(false);
+ }
+
+ // Destroy the brige to the NSView. Note that the NSView on the other side
+ // of |ns_view_bridge_| may outlive us due to other retains.
+ ns_view_bridge_.reset();
// Delete the delegated frame state, which will reach back into
- // render_widget_host_.
+ // host().
browser_compositor_.reset();
// Make sure none of our observers send events for us to process after
- // we release render_widget_host_.
+ // we release host().
NotifyObserversAboutShutdown();
if (text_input_manager_)
@@ -1090,39 +569,33 @@ void RenderWidgetHostViewMac::Destroy() {
mouse_wheel_phase_handler_.IgnorePendingWheelEndEvent();
- // We get this call just before |render_widget_host_| deletes
- // itself. But we are owned by |cocoa_view_|, which may be retained
- // by some other code. Examples are WebContentsViewMac's
- // |latent_focus_view_| and TabWindowController's
- // |cachedContentView_|.
- render_widget_host_ = NULL;
+ // The call to the base class will set host() to nullptr.
+ RenderWidgetHostViewBase::Destroy();
+
+ delete this;
}
-// Called from the renderer to tell us what the tooltip text should be. It
-// calls us frequently so we need to cache the value to prevent doing a lot
-// of repeat work.
void RenderWidgetHostViewMac::SetTooltipText(
const base::string16& tooltip_text) {
- if (tooltip_text != tooltip_text_ && [[cocoa_view_ window] isKeyWindow]) {
- tooltip_text_ = tooltip_text;
-
- // Clamp the tooltip length to kMaxTooltipLength. It's a DOS issue on
- // Windows; we're just trying to be polite. Don't persist the trimmed
- // string, as then the comparison above will always fail and we'll try to
- // set it again every single time the mouse moves.
- base::string16 display_text = tooltip_text_;
- if (tooltip_text_.length() > kMaxTooltipLength)
- display_text = tooltip_text_.substr(0, kMaxTooltipLength);
-
- NSString* tooltip_nsstring = base::SysUTF16ToNSString(display_text);
- [cocoa_view_ setToolTipAtMousePoint:tooltip_nsstring];
- }
+ GetCursorManager()->SetTooltipTextForView(this, tooltip_text);
}
-void RenderWidgetHostViewMac::ResizeDueToAutoResize(const gfx::Size& new_size,
- uint64_t sequence_number) {
- browser_compositor_->UpdateForAutoResize(new_size);
- RenderWidgetHostViewBase::ResizeDueToAutoResize(new_size, sequence_number);
+void RenderWidgetHostViewMac::DisplayTooltipText(
+ const base::string16& tooltip_text) {
+ ns_view_bridge_->SetTooltipText(tooltip_text);
+}
+
+viz::ScopedSurfaceIdAllocator RenderWidgetHostViewMac::ResizeDueToAutoResize(
+ const gfx::Size& new_size,
+ uint64_t sequence_number) {
+ // TODO(cblume): This doesn't currently suppress allocation.
+ // It maintains existing behavior while using the suppression style.
+ // This will be addressed in a follow-up patch.
+ // See https://crbug.com/805073
+ base::OnceCallback<void()> allocation_task =
+ base::BindOnce(&RenderWidgetHostViewMac::OnResizeDueToAutoResizeComplete,
+ weak_factory_.GetWeakPtr(), new_size, sequence_number);
+ return viz::ScopedSurfaceIdAllocator(std::move(allocation_task));
}
void RenderWidgetHostViewMac::DidNavigate() {
@@ -1133,39 +606,73 @@ gfx::Size RenderWidgetHostViewMac::GetRequestedRendererSize() const {
return browser_compositor_->GetRendererSize();
}
-bool RenderWidgetHostViewMac::SupportsSpeech() const {
- return [NSApp respondsToSelector:@selector(speakString:)] &&
- [NSApp respondsToSelector:@selector(stopSpeaking:)];
-}
+namespace {
-void RenderWidgetHostViewMac::SpeakSelection() {
- if (![NSApp respondsToSelector:@selector(speakString:)])
+// A helper function for CombineTextNodesAndMakeCallback() below. It would
+// ordinarily be a helper lambda in that class method, but it processes a tree
+// and needs to be recursive, and that's crazy difficult to do with a lambda.
+// TODO(avi): Move this to be a lambda when P0839R0 lands in C++.
+void AddTextNodesToVector(const ui::AXNode* node,
+ std::vector<base::string16>* strings) {
+ const ui::AXNodeData& node_data = node->data();
+
+ if (node_data.role == ax::mojom::Role::kStaticText) {
+ if (node_data.HasStringAttribute(ax::mojom::StringAttribute::kName)) {
+ strings->emplace_back(
+ node_data.GetString16Attribute(ax::mojom::StringAttribute::kName));
+ }
return;
+ }
- const TextInputManager::TextSelection* selection = GetTextSelection();
- if (!selection)
- return;
+ for (const auto* child : node->children())
+ AddTextNodesToVector(child, strings);
+}
- if (selection->selected_text().empty() && render_widget_host_) {
- // TODO: This will not work with OOPIFs (https://crbug.com/659753).
- // If there's no selection, speak all text. Send an asynchronous IPC
- // request for fetching all the text for a webcontent.
- // ViewMsg_GetRenderedTextCompleted is sent back to IPC Message receiver.
- render_widget_host_->Send(
- new ViewMsg_GetRenderedText(render_widget_host_->GetRoutingID()));
- return;
- }
+using SpeechCallback = base::OnceCallback<void(const base::string16&)>;
+void CombineTextNodesAndMakeCallback(SpeechCallback callback,
+ const ui::AXTreeUpdate& update) {
+ std::vector<base::string16> text_node_contents;
+ text_node_contents.reserve(update.nodes.size());
+
+ ui::AXTree tree(update);
- SpeakText(base::UTF16ToUTF8(selection->selected_text()));
+ AddTextNodesToVector(tree.root(), &text_node_contents);
+
+ std::move(callback).Run(
+ base::JoinString(text_node_contents, base::ASCIIToUTF16("\n")));
}
-bool RenderWidgetHostViewMac::IsSpeaking() const {
- return [NSApp respondsToSelector:@selector(isSpeaking)] && [NSApp isSpeaking];
+} // namespace
+
+void RenderWidgetHostViewMac::GetPageTextForSpeech(SpeechCallback callback) {
+ // Note that the WebContents::RequestAXTreeSnapshot() call has a limit on the
+ // number of nodes returned. For large pages, this call might hit that limit.
+ // This is a reasonable thing. The "Start Speaking" call dates back to the
+ // earliest days of the Mac, before accessibility. It was designed to show off
+ // the speech capabilities of the Mac, which is fine, but is mostly
+ // inapplicable nowadays. Is it useful to have the Mac read megabytes of text
+ // with zero control over positioning, with no fast-forward or rewind? What
+ // does it even mean to read a Web 2.0 dynamic, AJAXy page aloud from
+ // beginning to end?
+ //
+ // If this is an issue, please file a bug explaining the situation and how the
+ // limits of this feature affect you in the real world.
+
+ GetWebContents()->RequestAXTreeSnapshot(
+ base::BindOnce(CombineTextNodesAndMakeCallback, std::move(callback)),
+ ui::AXMode::kWebContents);
}
-void RenderWidgetHostViewMac::StopSpeaking() {
- if ([NSApp respondsToSelector:@selector(stopSpeaking:)])
- [NSApp stopSpeaking:cocoa_view_];
+void RenderWidgetHostViewMac::SpeakSelection() {
+ const TextInputManager::TextSelection* selection = GetTextSelection();
+ if (selection && !selection->selected_text().empty()) {
+ ui::TextServicesContextMenu::SpeakText(selection->selected_text());
+ return;
+ }
+
+ // With no selection, speak an approximation of the entire contents of the
+ // page.
+ GetPageTextForSpeech(base::BindOnce(ui::TextServicesContextMenu::SpeakText));
}
//
@@ -1174,33 +681,7 @@ void RenderWidgetHostViewMac::StopSpeaking() {
//
void RenderWidgetHostViewMac::SetShowingContextMenu(bool showing) {
- // Create a fake mouse event to inform the render widget that the mouse
- // left or entered.
- NSWindow* window = [cocoa_view_ window];
- // TODO(asvitkine): If the location outside of the event stream doesn't
- // correspond to the current event (due to delayed event processing), then
- // this may result in a cursor flicker if there are later mouse move events
- // in the pipeline. Find a way to use the mouse location from the event that
- // dismissed the context menu.
- NSPoint location = [window mouseLocationOutsideOfEventStream];
- NSTimeInterval event_time = [[NSApp currentEvent] timestamp];
- NSEvent* event = [NSEvent mouseEventWithType:NSMouseMoved
- location:location
- modifierFlags:0
- timestamp:event_time
- windowNumber:window_number()
- context:nil
- eventNumber:0
- clickCount:0
- pressure:0];
- WebMouseEvent web_event = WebMouseEventBuilder::Build(event, cocoa_view_);
- web_event.SetModifiers(web_event.GetModifiers() |
- WebInputEvent::kRelativeMotionEvent);
- ForwardMouseEvent(web_event);
-}
-
-bool RenderWidgetHostViewMac::IsPopup() const {
- return popup_type_ != blink::kWebPopupTypeNone;
+ ns_view_bridge_->SetShowingContextMenu(showing);
}
void RenderWidgetHostViewMac::CopyFromSurface(
@@ -1211,16 +692,6 @@ void RenderWidgetHostViewMac::CopyFromSurface(
src_subrect, dst_size, std::move(callback));
}
-void RenderWidgetHostViewMac::ForwardMouseEvent(const WebMouseEvent& event) {
- if (render_widget_host_)
- render_widget_host_->ForwardMouseEvent(event);
-
- if (event.GetType() == WebInputEvent::kMouseLeave) {
- [cocoa_view_ setToolTipAtMousePoint:nil];
- tooltip_text_.clear();
- }
-}
-
void RenderWidgetHostViewMac::SetNeedsBeginFrames(bool needs_begin_frames) {
needs_begin_frames_ = needs_begin_frames;
UpdateNeedsBeginFramesInternal();
@@ -1230,17 +701,29 @@ void RenderWidgetHostViewMac::UpdateNeedsBeginFramesInternal() {
browser_compositor_->SetNeedsBeginFrames(needs_begin_frames_);
}
+void RenderWidgetHostViewMac::OnResizeDueToAutoResizeComplete(
+ const gfx::Size& new_size,
+ uint64_t sequence_number) {
+ browser_compositor_->UpdateForAutoResize(new_size);
+ host()->DidAllocateLocalSurfaceIdForAutoResize(sequence_number);
+}
+
void RenderWidgetHostViewMac::SetWantsAnimateOnlyBeginFrames() {
browser_compositor_->SetWantsAnimateOnlyBeginFrames();
}
-void RenderWidgetHostViewMac::KillSelf() {
- if (!weak_factory_.HasWeakPtrs()) {
- [cocoa_view_ setHidden:YES];
- base::ThreadTaskRunnerHandle::Get()->PostTask(
- FROM_HERE, base::Bind(&RenderWidgetHostViewMac::ShutdownHost,
- weak_factory_.GetWeakPtr()));
- }
+void RenderWidgetHostViewMac::TakeFallbackContentFrom(
+ RenderWidgetHostView* view) {
+ DCHECK(!static_cast<RenderWidgetHostViewBase*>(view)
+ ->IsRenderWidgetHostViewChildFrame());
+ DCHECK(!static_cast<RenderWidgetHostViewBase*>(view)
+ ->IsRenderWidgetHostViewGuest());
+ RenderWidgetHostViewMac* view_mac =
+ static_cast<RenderWidgetHostViewMac*>(view);
+ ScopedCAActionDisabler disabler;
+ SetBackgroundColor(view_mac->background_color());
+ browser_compositor_->TakeFallbackContentFrom(
+ view_mac->browser_compositor_.get());
}
bool RenderWidgetHostViewMac::GetLineBreakIndex(
@@ -1339,14 +822,13 @@ gfx::Range RenderWidgetHostViewMac::ConvertCharacterRangeToCompositionRange(
}
WebContents* RenderWidgetHostViewMac::GetWebContents() {
- return WebContents::FromRenderViewHost(
- RenderViewHost::From(render_widget_host_));
+ return WebContents::FromRenderViewHost(RenderViewHost::From(host()));
}
bool RenderWidgetHostViewMac::GetCachedFirstRectForCharacterRange(
- NSRange range,
- NSRect* rect,
- NSRange* actual_range) {
+ const gfx::Range& requested_range,
+ gfx::Rect* rect,
+ gfx::Range* actual_range) {
if (!GetTextInputManager())
return false;
@@ -1359,16 +841,14 @@ bool RenderWidgetHostViewMac::GetCachedFirstRectForCharacterRange(
if (!selection)
return false;
- const gfx::Range requested_range(range);
// If requested range is same as caret location, we can just return it.
if (selection->range().is_empty() && requested_range == selection->range()) {
DCHECK(GetFocusedWidget());
if (actual_range)
- *actual_range = range;
- *rect =
- NSRectFromCGRect(GetTextInputManager()
- ->GetSelectionRegion(GetFocusedWidget()->GetView())
- ->caret_rect.ToCGRect());
+ *actual_range = requested_range;
+ *rect = GetTextInputManager()
+ ->GetSelectionRegion(GetFocusedWidget()->GetView())
+ ->caret_rect;
return true;
}
@@ -1379,11 +859,10 @@ bool RenderWidgetHostViewMac::GetCachedFirstRectForCharacterRange(
return false;
DCHECK(GetFocusedWidget());
if (actual_range)
- *actual_range = selection->range().ToNSRange();
- *rect =
- NSRectFromCGRect(GetTextInputManager()
- ->GetSelectionRegion(GetFocusedWidget()->GetView())
- ->first_selection_rect.ToCGRect());
+ *actual_range = selection->range();
+ *rect = GetTextInputManager()
+ ->GetSelectionRegion(GetFocusedWidget()->GetView())
+ ->first_selection_rect;
return true;
}
@@ -1400,14 +879,12 @@ bool RenderWidgetHostViewMac::GetCachedFirstRectForCharacterRange(
composition_info->range.length());
gfx::Range ui_actual_range;
- *rect = NSRectFromCGRect(GetFirstRectForCompositionRange(
- request_range_in_composition,
- &ui_actual_range).ToCGRect());
+ *rect = GetFirstRectForCompositionRange(request_range_in_composition,
+ &ui_actual_range);
if (actual_range) {
*actual_range =
gfx::Range(composition_info->range.start() + ui_actual_range.start(),
- composition_info->range.start() + ui_actual_range.end())
- .ToNSRange();
+ composition_info->range.start() + ui_actual_range.end());
}
return true;
}
@@ -1419,7 +896,7 @@ bool RenderWidgetHostViewMac::ShouldContinueToPauseForFrame() {
void RenderWidgetHostViewMac::FocusedNodeChanged(
bool is_editable_node,
const gfx::Rect& node_bounds_in_screen) {
- [cocoa_view_ cancelComposition];
+ ns_view_bridge_->CancelComposition();
// If the Mac Zoom feature is enabled, update it with the bounds of the
// current focused node so that it can ensure that it's scrolled into view.
@@ -1443,9 +920,6 @@ void RenderWidgetHostViewMac::SubmitCompositorFrame(
viz::mojom::HitTestRegionListPtr hit_test_region_list) {
TRACE_EVENT0("browser", "RenderWidgetHostViewMac::OnSwapCompositorFrame");
- last_frame_root_background_color_ = frame.metadata.root_background_color;
- last_scroll_offset_ = frame.metadata.root_scroll_offset;
-
page_at_minimum_scale_ =
frame.metadata.page_scale_factor == frame.metadata.min_page_scale_factor;
@@ -1469,15 +943,7 @@ gfx::Vector2d RenderWidgetHostViewMac::GetOffsetFromRootSurface() {
}
gfx::Rect RenderWidgetHostViewMac::GetBoundsInRootWindow() {
- // TODO(shess): In case of !window, the view has been removed from
- // the view hierarchy because the tab isn't main. Could retrieve
- // the information from the main tab for our window.
- NSWindow* enclosing_window = ApparentWindowForView(cocoa_view_);
- if (!enclosing_window)
- return gfx::Rect();
-
- NSRect bounds = [enclosing_window frame];
- return FlipNSRectToRectScreen(bounds);
+ return window_frame_in_screen_dip_;
}
bool RenderWidgetHostViewMac::LockMouse() {
@@ -1487,11 +953,10 @@ bool RenderWidgetHostViewMac::LockMouse() {
mouse_locked_ = true;
// Lock position of mouse cursor and hide it.
- CGAssociateMouseAndMouseCursorPosition(NO);
- [NSCursor hide];
+ ns_view_bridge_->SetCursorLocked(true);
// Clear the tooltip window.
- SetTooltipText(base::string16());
+ ns_view_bridge_->SetTooltipText(base::string16());
return true;
}
@@ -1500,24 +965,20 @@ void RenderWidgetHostViewMac::UnlockMouse() {
if (!mouse_locked_)
return;
mouse_locked_ = false;
+ ns_view_bridge_->SetCursorLocked(false);
- // Unlock position of mouse cursor and unhide it.
- CGAssociateMouseAndMouseCursorPosition(YES);
- [NSCursor unhide];
-
- if (render_widget_host_)
- render_widget_host_->LostMouseLock();
+ if (host())
+ host()->LostMouseLock();
}
-void RenderWidgetHostViewMac::GestureEventAck(
- const blink::WebGestureEvent& event,
- InputEventAckState ack_result) {
+void RenderWidgetHostViewMac::GestureEventAck(const WebGestureEvent& event,
+ InputEventAckState ack_result) {
bool consumed = ack_result == INPUT_EVENT_ACK_STATE_CONSUMED;
switch (event.GetType()) {
- case blink::WebInputEvent::kGestureScrollBegin:
- case blink::WebInputEvent::kGestureScrollUpdate:
- case blink::WebInputEvent::kGestureScrollEnd:
- [cocoa_view_ processedGestureScrollEvent:event consumed:consumed];
+ case WebInputEvent::kGestureScrollBegin:
+ case WebInputEvent::kGestureScrollUpdate:
+ case WebInputEvent::kGestureScrollEnd:
+ [cocoa_view() processedGestureScrollEvent:event consumed:consumed];
return;
default:
break;
@@ -1527,7 +988,7 @@ void RenderWidgetHostViewMac::GestureEventAck(
void RenderWidgetHostViewMac::DidOverscroll(
const ui::DidOverscrollParams& params) {
- [cocoa_view_ processedOverscroll:params];
+ [cocoa_view() processedOverscroll:params];
}
std::unique_ptr<SyntheticGestureTarget>
@@ -1535,22 +996,14 @@ RenderWidgetHostViewMac::CreateSyntheticGestureTarget() {
RenderWidgetHostImpl* host =
RenderWidgetHostImpl::From(GetRenderWidgetHost());
return std::unique_ptr<SyntheticGestureTarget>(
- new SyntheticGestureTargetMac(host, cocoa_view_));
-}
-
-RenderWidgetHostImpl* RenderWidgetHostViewMac::GetRenderWidgetHostImpl() const {
- return render_widget_host_;
+ new SyntheticGestureTargetMac(host, cocoa_view()));
}
viz::LocalSurfaceId RenderWidgetHostViewMac::GetLocalSurfaceId() const {
- if (!browser_compositor_)
- return viz::LocalSurfaceId();
return browser_compositor_->GetRendererLocalSurfaceId();
}
viz::FrameSinkId RenderWidgetHostViewMac::GetFrameSinkId() {
- if (!browser_compositor_)
- return viz::FrameSinkId();
return browser_compositor_->GetDelegatedFrameHost()->frame_sink_id();
}
@@ -1562,20 +1015,19 @@ bool RenderWidgetHostViewMac::ShouldRouteEvent(
DCHECK(WebInputEvent::IsMouseEventType(event.GetType()) ||
event.GetType() == WebInputEvent::kMouseWheel ||
WebInputEvent::IsPinchGestureEventType(event.GetType()));
- return render_widget_host_->delegate() &&
- render_widget_host_->delegate()->GetInputEventRouter();
+ return host()->delegate() && host()->delegate()->GetInputEventRouter();
}
void RenderWidgetHostViewMac::SendGesturePinchEvent(WebGestureEvent* event) {
DCHECK(WebInputEvent::IsPinchGestureEventType(event->GetType()));
if (ShouldRouteEvent(*event)) {
- DCHECK(event->source_device ==
+ DCHECK(event->SourceDevice() ==
blink::WebGestureDevice::kWebGestureDeviceTouchpad);
- render_widget_host_->delegate()->GetInputEventRouter()->RouteGestureEvent(
+ host()->delegate()->GetInputEventRouter()->RouteGestureEvent(
this, event, ui::LatencyInfo(ui::SourceEventType::WHEEL));
return;
}
- render_widget_host_->ForwardGestureEvent(*event);
+ host()->ForwardGestureEvent(*event);
}
bool RenderWidgetHostViewMac::TransformPointToLocalCoordSpace(
@@ -1584,7 +1036,7 @@ bool RenderWidgetHostViewMac::TransformPointToLocalCoordSpace(
gfx::PointF* transformed_point) {
// Transformations use physical pixels rather than DIP, so conversion
// is necessary.
- float scale_factor = ui::GetScaleFactorForNativeView(cocoa_view_);
+ float scale_factor = display_.device_scale_factor();
gfx::PointF point_in_pixels = gfx::ConvertPointToPixel(scale_factor, point);
if (!browser_compositor_->GetDelegatedFrameHost()
->TransformPointToLocalCoordSpace(point_in_pixels, original_surface,
@@ -1609,38 +1061,34 @@ bool RenderWidgetHostViewMac::TransformPointToCoordSpaceForView(
}
viz::FrameSinkId RenderWidgetHostViewMac::GetRootFrameSinkId() {
- if (!browser_compositor_)
- return viz::FrameSinkId();
return browser_compositor_->GetRootFrameSinkId();
}
viz::SurfaceId RenderWidgetHostViewMac::GetCurrentSurfaceId() const {
- if (!browser_compositor_)
- return viz::SurfaceId();
return browser_compositor_->GetDelegatedFrameHost()->GetCurrentSurfaceId();
}
bool RenderWidgetHostViewMac::Send(IPC::Message* message) {
- if (render_widget_host_)
- return render_widget_host_->Send(message);
+ if (host())
+ return host()->Send(message);
delete message;
return false;
}
void RenderWidgetHostViewMac::ShutdownHost() {
weak_factory_.InvalidateWeakPtrs();
- render_widget_host_->ShutdownAndDestroyWidget(true);
+ host()->ShutdownAndDestroyWidget(true);
// Do not touch any members at this point, |this| has been deleted.
}
void RenderWidgetHostViewMac::SetActive(bool active) {
- if (render_widget_host_) {
- render_widget_host_->SetActive(active);
+ if (host()) {
+ host()->SetActive(active);
if (active) {
if (HasFocus())
- render_widget_host_->Focus();
+ host()->Focus();
} else {
- render_widget_host_->Blur();
+ host()->Blur();
}
}
if (HasFocus())
@@ -1650,8 +1098,8 @@ void RenderWidgetHostViewMac::SetActive(bool active) {
}
void RenderWidgetHostViewMac::ShowDefinitionForSelection() {
- RenderWidgetHostViewMacDictionaryHelper helper(this);
- helper.ShowDefinitionForSelection();
+ // This will round-trip to the NSView to determine the selection range.
+ ns_view_bridge_->ShowDictionaryOverlayForSelection();
}
void RenderWidgetHostViewMac::SetBackgroundColor(SkColor color) {
@@ -1666,8 +1114,8 @@ void RenderWidgetHostViewMac::SetBackgroundColor(SkColor color) {
bool opaque = SkColorGetA(color) == SK_AlphaOPAQUE;
if (background_is_opaque_ != opaque) {
background_is_opaque_ = opaque;
- if (render_widget_host_)
- render_widget_host_->SetBackgroundOpaque(opaque);
+ if (host())
+ host()->SetBackgroundOpaque(opaque);
}
}
@@ -1686,11 +1134,7 @@ void RenderWidgetHostViewMac::SetBackgroundLayerColor(SkColor color) {
if (color == background_layer_color_)
return;
background_layer_color_ = color;
-
- ScopedCAActionDisabler disabler;
- base::ScopedCFTypeRef<CGColorRef> cg_color(
- skia::CGColorCreateFromSkColor(color));
- [background_layer_ setBackgroundColor:cg_color];
+ ns_view_bridge_->SetBackgroundColor(color);
}
BrowserAccessibilityManager*
@@ -1704,41 +1148,30 @@ gfx::Point RenderWidgetHostViewMac::AccessibilityOriginInScreen(
const gfx::Rect& bounds) {
NSPoint origin = NSMakePoint(bounds.x(), bounds.y());
NSSize size = NSMakeSize(bounds.width(), bounds.height());
- origin.y = NSHeight([cocoa_view_ bounds]) - origin.y;
- NSPoint originInWindow = [cocoa_view_ convertPoint:origin toView:nil];
+ origin.y = NSHeight([cocoa_view() bounds]) - origin.y;
+ NSPoint originInWindow = [cocoa_view() convertPoint:origin toView:nil];
NSPoint originInScreen =
- ui::ConvertPointFromWindowToScreen([cocoa_view_ window], originInWindow);
+ ui::ConvertPointFromWindowToScreen([cocoa_view() window], originInWindow);
originInScreen.y = originInScreen.y - size.height;
return gfx::Point(originInScreen.x, originInScreen.y);
}
gfx::AcceleratedWidget
RenderWidgetHostViewMac::AccessibilityGetAcceleratedWidget() {
- if (browser_compositor_)
- return browser_compositor_->GetAcceleratedWidget();
- return gfx::kNullAcceleratedWidget;
+ return browser_compositor_->GetAcceleratedWidget();
}
void RenderWidgetHostViewMac::SetTextInputActive(bool active) {
- if (active) {
- if (GetTextInputType() == ui::TEXT_INPUT_TYPE_PASSWORD)
- EnablePasswordInput();
- else
- DisablePasswordInput();
- } else {
- if (GetTextInputType() == ui::TEXT_INPUT_TYPE_PASSWORD)
- DisablePasswordInput();
- }
-}
-
-void RenderWidgetHostViewMac::OnGetRenderedTextCompleted(
- const std::string& text) {
- SpeakText(text);
+ const bool should_enable_password_input =
+ active && GetTextInputType() == ui::TEXT_INPUT_TYPE_PASSWORD;
+ if (should_enable_password_input)
+ password_input_enabler_.reset(new ui::ScopedPasswordInputEnabler());
+ else
+ password_input_enabler_.reset();
}
void RenderWidgetHostViewMac::PauseForPendingResizeOrRepaintsAndDraw() {
- if (!render_widget_host_ || !browser_compositor_ ||
- render_widget_host_->is_hidden()) {
+ if (!host() || !browser_compositor_ || host()->is_hidden()) {
return;
}
@@ -1748,9 +1181,8 @@ void RenderWidgetHostViewMac::PauseForPendingResizeOrRepaintsAndDraw() {
return;
// Wait for a frame of the right size to come in.
- browser_compositor_->BeginPauseForFrame(
- render_widget_host_->auto_resize_enabled());
- render_widget_host_->PauseForPendingResizeOrRepaints();
+ browser_compositor_->BeginPauseForFrame(host()->auto_resize_enabled());
+ host()->PauseForPendingResizeOrRepaints();
browser_compositor_->EndPauseForFrame();
}
@@ -1762,1936 +1194,484 @@ RenderWidgetHostViewMac::AllocateFrameSinkIdForGuestViewHack() {
->AllocateFrameSinkId();
}
-////////////////////////////////////////////////////////////////////////////////
-// display::DisplayObserver, public:
-
-void RenderWidgetHostViewMac::OnDisplayAdded(const display::Display& display) {}
-
-void RenderWidgetHostViewMac::OnDisplayRemoved(
- const display::Display& display) {}
+///////////////////////////////////////////////////////////////////////////////
+// RenderWidgetHostNSViewClient implementation:
-void RenderWidgetHostViewMac::OnDisplayMetricsChanged(
- const display::Display& display,
- uint32_t changed_metrics) {
- display::Screen* screen = display::Screen::GetScreen();
- if (display.id() != screen->GetDisplayNearestView(cocoa_view_).id())
- return;
- UpdateNSViewAndDisplayProperties();
+BrowserAccessibilityManager*
+RenderWidgetHostViewMac::GetRootBrowserAccessibilityManager() {
+ return host()->GetRootBrowserAccessibilityManager();
}
-Class GetRenderWidgetHostViewCocoaClassForTesting() {
- return [RenderWidgetHostViewCocoa class];
+void RenderWidgetHostViewMac::OnNSViewSyncIsRenderViewHost(
+ bool* is_render_view) {
+ *is_render_view = RenderViewHost::From(host()) != nullptr;
}
-} // namespace content
-
-// RenderWidgetHostViewCocoa ---------------------------------------------------
-
-@implementation RenderWidgetHostViewCocoa
-@synthesize selectedRange = selectedRange_;
-@synthesize suppressNextEscapeKeyUp = suppressNextEscapeKeyUp_;
-@synthesize markedRange = markedRange_;
-
-- (id)initWithRenderWidgetHostViewMac:(RenderWidgetHostViewMac*)r {
- self = [super initWithFrame:NSZeroRect];
- if (self) {
- self.acceptsTouchEvents = YES;
- editCommand_helper_.reset(new RenderWidgetHostViewMacEditCommandHelper);
- editCommand_helper_->AddEditingSelectorsToClass([self class]);
-
- renderWidgetHostView_.reset(r);
- canBeKeyView_ = YES;
- pinchHasReachedZoomThreshold_ = false;
- isStylusEnteringProximity_ = false;
-
- // OpenGL support:
- if ([self respondsToSelector:
- @selector(setWantsBestResolutionOpenGLSurface:)]) {
- [self setWantsBestResolutionOpenGLSurface:YES];
- }
- [[NSNotificationCenter defaultCenter]
- addObserver:self
- selector:@selector(didChangeScreenParameters:)
- name:NSApplicationDidChangeScreenParametersNotification
- object:nil];
+void RenderWidgetHostViewMac::OnNSViewRequestShutdown() {
+ if (!weak_factory_.HasWeakPtrs()) {
+ base::ThreadTaskRunnerHandle::Get()->PostTask(
+ FROM_HERE, base::BindOnce(&RenderWidgetHostViewMac::ShutdownHost,
+ weak_factory_.GetWeakPtr()));
}
- return self;
-}
-
-- (void)dealloc {
- if (responderDelegate_ &&
- [responderDelegate_ respondsToSelector:@selector(viewGone:)])
- [responderDelegate_ viewGone:self];
- responderDelegate_.reset();
-
- [[NSNotificationCenter defaultCenter] removeObserver:self];
-
- // Update and cache the new input context. Otherwise,
- // [NSTextInputContext currentInputContext] might still hold on to this
- // view's NSTextInputContext even after it's deallocated.
- // See http://crbug.com/684388.
- [[self window] makeFirstResponder:nil];
- [NSApp updateWindows];
-
- // Debug key to check if the current input context still holds onto the view.
- NSTextInputContext* currentContext = [NSTextInputContext currentInputContext];
- auto* crashKey = base::debug::AllocateCrashKeyString(
- "text-input-context-client", base::debug::CrashKeySize::Size32);
- base::debug::ScopedCrashKeyString textInputContextCrashKey(
- crashKey, currentContext && [currentContext client] == self
- ? "text input still held on"
- : "text input no longer held on");
-
- [super dealloc];
}
-- (void)didChangeScreenParameters:(NSNotification*)notify {
- g_screen_info_up_to_date = false;
-}
-
-- (void)setResponderDelegate:
- (NSObject<RenderWidgetHostViewMacDelegate>*)delegate {
- DCHECK(!responderDelegate_);
- responderDelegate_.reset([delegate retain]);
-}
-
-- (void)resetCursorRects {
- if (currentCursor_) {
- [self addCursorRect:[self visibleRect] cursor:currentCursor_];
- [currentCursor_ setOnMouseEntered:YES];
+void RenderWidgetHostViewMac::OnNSViewIsFirstResponderChanged(
+ bool is_first_responder) {
+ if (is_first_responder_ == is_first_responder)
+ return;
+ is_first_responder_ = is_first_responder;
+ if (is_first_responder_) {
+ host()->GotFocus();
+ SetTextInputActive(true);
+ } else {
+ SetTextInputActive(false);
+ host()->LostFocus();
}
}
-- (void)processedWheelEvent:(const blink::WebMouseWheelEvent&)event
- consumed:(BOOL)consumed {
- [responderDelegate_ rendererHandledWheelEvent:event consumed:consumed];
-}
-
-- (void)processedGestureScrollEvent:(const blink::WebGestureEvent&)event
- consumed:(BOOL)consumed {
- [responderDelegate_ rendererHandledGestureScrollEvent:event
- consumed:consumed];
-}
-
-- (void)processedOverscroll:(const ui::DidOverscrollParams&)params {
- [responderDelegate_ rendererHandledOverscrollEvent:params];
-}
-
-- (BOOL)respondsToSelector:(SEL)selector {
- // Trickiness: this doesn't mean "does this object's superclass respond to
- // this selector" but rather "does the -respondsToSelector impl from the
- // superclass say that this class responds to the selector".
- if ([super respondsToSelector:selector])
- return YES;
-
- if (responderDelegate_)
- return [responderDelegate_ respondsToSelector:selector];
-
- return NO;
+void RenderWidgetHostViewMac::OnNSViewWindowIsKeyChanged(bool is_key) {
+ SetActive(is_key);
}
-- (id)forwardingTargetForSelector:(SEL)selector {
- if ([responderDelegate_ respondsToSelector:selector])
- return responderDelegate_.get();
+void RenderWidgetHostViewMac::OnNSViewBoundsInWindowChanged(
+ const gfx::Rect& view_bounds_in_window_dip,
+ bool attached_to_window) {
+ bool view_size_changed =
+ view_bounds_in_window_dip_.size() != view_bounds_in_window_dip.size();
- return [super forwardingTargetForSelector:selector];
-}
+ browser_compositor_->SetNSViewAttachedToWindow(attached_to_window);
-- (void)setCanBeKeyView:(BOOL)can {
- canBeKeyView_ = can;
-}
-
-- (BOOL)acceptsMouseEventsWhenInactive {
- // Some types of windows (balloons, always-on-top panels) want to accept mouse
- // clicks w/o the first click being treated as 'activation'. Same applies to
- // mouse move events.
- return [[self window] level] > NSNormalWindowLevel;
-}
-
-- (BOOL)acceptsFirstMouse:(NSEvent*)theEvent {
- return [self acceptsMouseEventsWhenInactive];
-}
-
-- (void)setCloseOnDeactivate:(BOOL)b {
- closeOnDeactivate_ = b;
-}
-
-- (BOOL)shouldIgnoreMouseEvent:(NSEvent*)theEvent {
- NSWindow* window = [self window];
- // If this is a background window, don't handle mouse movement events. This
- // is the expected behavior on the Mac as evidenced by other applications.
- if ([theEvent type] == NSMouseMoved &&
- ![self acceptsMouseEventsWhenInactive] &&
- ![window isKeyWindow]) {
- return YES;
- }
-
- // Use hitTest to check whether the mouse is over a nonWebContentView - in
- // which case the mouse event should not be handled by the render host.
- const SEL nonWebContentViewSelector = @selector(nonWebContentView);
- NSView* contentView = [window contentView];
- NSView* view = [contentView hitTest:[theEvent locationInWindow]];
- // Traverse the superview hierarchy as the hitTest will return the frontmost
- // view, such as an NSTextView, while nonWebContentView may be specified by
- // its parent view.
- while (view) {
- if ([view respondsToSelector:nonWebContentViewSelector] &&
- [view performSelector:nonWebContentViewSelector]) {
- // The cursor is over a nonWebContentView - ignore this mouse event.
- return YES;
- }
- if ([view isKindOfClass:[self class]] && ![view isEqual:self] &&
- !hasOpenMouseDown_) {
- // The cursor is over an overlapping render widget. This check is done by
- // both views so the one that's returned by -hitTest: will end up
- // processing the event.
- // Note that while dragging, we only get events for the render view where
- // drag started, even if mouse is actually over another view or outside
- // the window. Cocoa does this for us. We should handle these events and
- // not ignore (since there is no other render view to handle them). Thus
- // the |!hasOpenMouseDown_| check above.
- return YES;
- }
- view = [view superview];
- }
- return NO;
-}
-
-- (void)mouseEvent:(NSEvent*)theEvent {
- TRACE_EVENT0("browser", "RenderWidgetHostViewCocoa::mouseEvent");
- if (responderDelegate_ &&
- [responderDelegate_ respondsToSelector:@selector(handleEvent:)]) {
- BOOL handled = [responderDelegate_ handleEvent:theEvent];
- if (handled)
- return;
- }
-
- // Set the pointer type when we are receiving a NSMouseEntered event and the
- // following NSMouseExited event should have the same pointer type.
- // For NSMouseExited and NSMouseEntered events, they do not have a subtype.
- // We decide their pointer types by checking if we recevied a
- // NSTabletProximity event.
- NSEventType type = [theEvent type];
- if (type == NSMouseEntered || type == NSMouseExited) {
- pointerType_ = isStylusEnteringProximity_
- ? pointerType_
- : blink::WebPointerProperties::PointerType::kMouse;
+ if (attached_to_window) {
+ view_bounds_in_window_dip_ = view_bounds_in_window_dip;
} else {
- NSEventSubtype subtype = [theEvent subtype];
- // For other mouse events and touchpad events, the pointer type is mouse.
- if (subtype != NSTabletPointEventSubtype &&
- subtype != NSTabletProximityEventSubtype) {
- pointerType_ = blink::WebPointerProperties::PointerType::kMouse;
- }
- }
-
- if ([self shouldIgnoreMouseEvent:theEvent]) {
- // If this is the first such event, send a mouse exit to the host view.
- if (!mouseEventWasIgnored_ && renderWidgetHostView_->render_widget_host_) {
- WebMouseEvent exitEvent =
- WebMouseEventBuilder::Build(theEvent, self, pointerType_);
- exitEvent.SetType(WebInputEvent::kMouseLeave);
- exitEvent.button = WebMouseEvent::Button::kNoButton;
- renderWidgetHostView_->ForwardMouseEvent(exitEvent);
- }
- mouseEventWasIgnored_ = YES;
- return;
- }
-
- if (mouseEventWasIgnored_) {
- // If this is the first mouse event after a previous event that was ignored
- // due to the hitTest, send a mouse enter event to the host view.
- if (renderWidgetHostView_->render_widget_host_) {
- WebMouseEvent enterEvent =
- WebMouseEventBuilder::Build(theEvent, self, pointerType_);
- enterEvent.SetType(WebInputEvent::kMouseMove);
- enterEvent.button = WebMouseEvent::Button::kNoButton;
- ui::LatencyInfo latency_info(ui::SourceEventType::OTHER);
- latency_info.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_UI_COMPONENT, 0, 0);
- if (renderWidgetHostView_->ShouldRouteEvent(enterEvent)) {
- renderWidgetHostView_->render_widget_host_->delegate()
- ->GetInputEventRouter()
- ->RouteMouseEvent(renderWidgetHostView_.get(), &enterEvent,
- latency_info);
- } else {
- renderWidgetHostView_->ProcessMouseEvent(enterEvent, latency_info);
- }
- }
- }
- mouseEventWasIgnored_ = NO;
-
- // Don't cancel child popups; killing them on a mouse click would prevent the
- // user from positioning the insertion point in the text field spawning the
- // popup. A click outside the text field would cause the text field to drop
- // the focus, and then EditorClientImpl::textFieldDidEndEditing() would cancel
- // the popup anyway, so we're OK.
- if (type == NSLeftMouseDown)
- hasOpenMouseDown_ = YES;
- else if (type == NSLeftMouseUp)
- hasOpenMouseDown_ = NO;
-
- // TODO(suzhe): We should send mouse events to the input method first if it
- // wants to handle them. But it won't work without implementing method
- // - (NSUInteger)characterIndexForPoint:.
- // See: http://code.google.com/p/chromium/issues/detail?id=47141
- // Instead of sending mouse events to the input method first, we now just
- // simply confirm all ongoing composition here.
- if (type == NSLeftMouseDown || type == NSRightMouseDown ||
- type == NSOtherMouseDown) {
- [self finishComposingText];
+ // If not attached to a window, do not update the bounds origin (since it is
+ // meaningless, and the last value is the best guess at the next meaningful
+ // value).
+ view_bounds_in_window_dip_.set_size(view_bounds_in_window_dip.size());
}
- if (type == NSMouseMoved)
- cursorHidden_ = NO;
-
- WebMouseEvent event =
- WebMouseEventBuilder::Build(theEvent, self, pointerType_);
- ui::LatencyInfo latency_info(ui::SourceEventType::OTHER);
- latency_info.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_UI_COMPONENT, 0, 0);
- if (renderWidgetHostView_->ShouldRouteEvent(event)) {
- renderWidgetHostView_->render_widget_host_->delegate()
- ->GetInputEventRouter()
- ->RouteMouseEvent(renderWidgetHostView_.get(), &event, latency_info);
- } else {
- renderWidgetHostView_->ProcessMouseEvent(event, latency_info);
+ if (view_size_changed) {
+ UpdateNSViewAndDisplayProperties();
+ // Wait for the frame that WasResize might have requested. If the view is
+ // being made visible at a new size, then this call will have no effect
+ // because the view widget is still hidden, and the pause call in WasShown
+ // will have this effect for us.
+ PauseForPendingResizeOrRepaintsAndDraw();
}
}
-- (void)tabletEvent:(NSEvent*)theEvent {
- if ([theEvent type] == NSTabletProximity) {
- isStylusEnteringProximity_ = [theEvent isEnteringProximity];
- NSPointingDeviceType deviceType = [theEvent pointingDeviceType];
- // For all tablet events, the pointer type will be pen or eraser.
- pointerType_ = deviceType == NSEraserPointingDevice
- ? blink::WebPointerProperties::PointerType::kEraser
- : blink::WebPointerProperties::PointerType::kPen;
- }
+void RenderWidgetHostViewMac::OnNSViewWindowFrameInScreenChanged(
+ const gfx::Rect& window_frame_in_screen_dip) {
+ window_frame_in_screen_dip_ = window_frame_in_screen_dip;
}
-- (BOOL)performKeyEquivalent:(NSEvent*)theEvent {
- // |performKeyEquivalent:| is sent to all views of a window, not only down the
- // responder chain (cf. "Handling Key Equivalents" in
- // http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/EventOverview/HandlingKeyEvents/HandlingKeyEvents.html
- // ). A |performKeyEquivalent:| may also bubble up from a dialog child window
- // to perform browser commands such as switching tabs. We only want to handle
- // key equivalents if we're first responder in the keyWindow.
- if (![[self window] isKeyWindow] || [[self window] firstResponder] != self)
- return NO;
-
- // If the event is reserved by the system, then do not pass it to web content.
- if (EventIsReservedBySystem(theEvent))
- return NO;
-
- // If we return |NO| from this function, cocoa will send the key event to
- // the menu and only if the menu does not process the event to |keyDown:|. We
- // want to send the event to a renderer _before_ sending it to the menu, so
- // we need to return |YES| for all events that might be swallowed by the menu.
- // We do not return |YES| for every keypress because we don't get |keyDown:|
- // events for keys that we handle this way.
- NSUInteger modifierFlags = [theEvent modifierFlags];
- if ((modifierFlags & NSCommandKeyMask) == 0) {
- // Make sure the menu does not contain key equivalents that don't
- // contain cmd.
- DCHECK(![[NSApp mainMenu] performKeyEquivalent:theEvent]);
- return NO;
- }
-
- // Command key combinations are sent via performKeyEquivalent rather than
- // keyDown:. We just forward this on and if WebCore doesn't want to handle
- // it, we let the WebContentsView figure out how to reinject it.
- [self keyEvent:theEvent wasKeyEquivalent:YES];
- return YES;
-}
-
-- (BOOL)_wantsKeyDownForEvent:(NSEvent*)event {
- // This is a SPI that AppKit apparently calls after |performKeyEquivalent:|
- // returned NO. If this function returns |YES|, Cocoa sends the event to
- // |keyDown:| instead of doing other things with it. Ctrl-tab will be sent
- // to us instead of doing key view loop control, ctrl-left/right get handled
- // correctly, etc.
- // (However, there are still some keys that Cocoa swallows, e.g. the key
- // equivalent that Cocoa uses for toggling the input language. In this case,
- // that's actually a good thing, though -- see http://crbug.com/26115 .)
- return YES;
-}
-
-- (EventHandled)keyEvent:(NSEvent*)theEvent {
- if (responderDelegate_ &&
- [responderDelegate_ respondsToSelector:@selector(handleEvent:)]) {
- BOOL handled = [responderDelegate_ handleEvent:theEvent];
- if (handled)
- return kEventHandled;
- }
-
- [self keyEvent:theEvent wasKeyEquivalent:NO];
- return kEventHandled;
+void RenderWidgetHostViewMac::OnNSViewDisplayChanged(
+ const display::Display& display) {
+ display_ = display;
+ UpdateNSViewAndDisplayProperties();
}
-- (void)keyEvent:(NSEvent*)theEvent wasKeyEquivalent:(BOOL)equiv {
- TRACE_EVENT0("browser", "RenderWidgetHostViewCocoa::keyEvent");
-
- // If the user changes the system hotkey mapping after Chrome has been
- // launched, then it is possible that a formerly reserved system hotkey is no
- // longer reserved. The hotkey would have skipped the renderer, but would
- // also have not been handled by the system. If this is the case, immediately
- // return.
- // TODO(erikchen): SystemHotkeyHelperMac should use the File System Events
- // api to monitor changes to system hotkeys. This logic will have to be
- // updated.
- // http://crbug.com/383558.
- if (EventIsReservedBySystem(theEvent))
- return;
-
- DCHECK([theEvent type] != NSKeyDown ||
- !equiv == !([theEvent modifierFlags] & NSCommandKeyMask));
-
- if ([theEvent type] == NSFlagsChanged) {
- // Ignore NSFlagsChanged events from the NumLock and Fn keys as
- // Safari does in -[WebHTMLView flagsChanged:] (of "WebHTMLView.mm").
- // Also ignore unsupported |keyCode| (255) generated by Convert, NonConvert
- // and KanaMode from JIS PC keyboard.
- int keyCode = [theEvent keyCode];
- if (!keyCode || keyCode == 10 || keyCode == 63 || keyCode == 255)
- return;
- }
-
- // Don't cancel child popups; the key events are probably what's triggering
- // the popup in the first place.
-
- RenderWidgetHostImpl* widgetHost = renderWidgetHostView_->render_widget_host_;
- DCHECK(widgetHost);
-
- NativeWebKeyboardEvent event(theEvent);
- ui::LatencyInfo latency_info;
- if (event.GetType() == blink::WebInputEvent::kRawKeyDown ||
- event.GetType() == blink::WebInputEvent::kChar) {
- latency_info.set_source_event_type(ui::SourceEventType::KEY_PRESS);
- }
-
- latency_info.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_UI_COMPONENT, 0, 0);
-
- // Force fullscreen windows to close on Escape so they won't keep the keyboard
- // grabbed or be stuck onscreen if the renderer is hanging.
- if (event.GetType() == NativeWebKeyboardEvent::kRawKeyDown &&
- event.windows_key_code == ui::VKEY_ESCAPE &&
- renderWidgetHostView_->pepper_fullscreen_window()) {
- RenderWidgetHostViewMac* parent =
- renderWidgetHostView_->fullscreen_parent_host_view();
- if (parent)
- parent->cocoa_view()->suppressNextEscapeKeyUp_ = YES;
- widgetHost->ShutdownAndDestroyWidget(true);
- return;
- }
-
- // If there are multiple widgets on the page (such as when there are
- // out-of-process iframes), pick the one that should process this event.
- if (widgetHost->delegate())
- widgetHost = widgetHost->delegate()->GetFocusedRenderWidgetHost(widgetHost);
- if (!widgetHost)
- return;
-
- // Suppress the escape key up event if necessary.
- if (event.windows_key_code == ui::VKEY_ESCAPE && suppressNextEscapeKeyUp_) {
- if (event.GetType() == NativeWebKeyboardEvent::kKeyUp)
- suppressNextEscapeKeyUp_ = NO;
- return;
- }
-
- // Do not forward key up events unless preceded by a matching key down,
- // otherwise we might get an event from releasing the return key in the
- // omnibox (http://crbug.com/338736).
- if ([theEvent type] == NSKeyUp) {
- auto numErased = keyDownCodes_.erase([theEvent keyCode]);
- if (numErased < 1)
- return;
- }
-
- // We only handle key down events and just simply forward other events.
- if ([theEvent type] != NSKeyDown) {
- widgetHost->ForwardKeyboardEventWithLatencyInfo(event, latency_info);
-
- // Possibly autohide the cursor.
- if ([self shouldAutohideCursorForEvent:theEvent]) {
- [NSCursor setHiddenUntilMouseMoves:YES];
- cursorHidden_ = YES;
- }
-
- return;
- }
-
- keyDownCodes_.insert([theEvent keyCode]);
-
- base::scoped_nsobject<RenderWidgetHostViewCocoa> keepSelfAlive([self retain]);
-
- // Records the current marked text state, so that we can know if the marked
- // text was deleted or not after handling the key down event.
- BOOL oldHasMarkedText = hasMarkedText_;
-
- // This method should not be called recursively.
- DCHECK(!handlingKeyDown_);
-
- // Tells insertText: and doCommandBySelector: that we are handling a key
- // down event.
- handlingKeyDown_ = YES;
-
- // These variables might be set when handling the keyboard event.
- // Clear them here so that we can know whether they have changed afterwards.
- textToBeInserted_.clear();
- markedText_.clear();
- markedTextSelectedRange_ = NSMakeRange(NSNotFound, 0);
- ime_text_spans_.clear();
- setMarkedTextReplacementRange_ = gfx::Range::InvalidRange();
- unmarkTextCalled_ = NO;
- hasEditCommands_ = NO;
- editCommands_.clear();
-
- // Sends key down events to input method first, then we can decide what should
- // be done according to input method's feedback.
- [self interpretKeyEvents:[NSArray arrayWithObject:theEvent]];
-
- handlingKeyDown_ = NO;
-
- // Indicates if we should send the key event and corresponding editor commands
- // after processing the input method result.
- BOOL delayEventUntilAfterImeCompostion = NO;
-
- // To emulate Windows, over-write |event.windowsKeyCode| to VK_PROCESSKEY
- // while an input method is composing or inserting a text.
- // Gmail checks this code in its onkeydown handler to stop auto-completing
- // e-mail addresses while composing a CJK text.
- // If the text to be inserted has only one character, then we don't need this
- // trick, because we'll send the text as a key press event instead.
- if (hasMarkedText_ || oldHasMarkedText || textToBeInserted_.length() > 1) {
- NativeWebKeyboardEvent fakeEvent = event;
- fakeEvent.windows_key_code = 0xE5; // VKEY_PROCESSKEY
- fakeEvent.skip_in_browser = true;
- widgetHost->ForwardKeyboardEventWithLatencyInfo(fakeEvent, latency_info);
- // If this key event was handled by the input method, but
- // -doCommandBySelector: (invoked by the call to -interpretKeyEvents: above)
- // enqueued edit commands, then in order to let webkit handle them
- // correctly, we need to send the real key event and corresponding edit
- // commands after processing the input method result.
- // We shouldn't do this if a new marked text was set by the input method,
- // otherwise the new marked text might be cancelled by webkit.
- if (hasEditCommands_ && !hasMarkedText_)
- delayEventUntilAfterImeCompostion = YES;
- } else {
- widgetHost->ForwardKeyboardEventWithCommands(event, latency_info,
- &editCommands_);
- }
-
- // Calling ForwardKeyboardEventWithCommands() could have destroyed the
- // widget. When the widget was destroyed,
- // |renderWidgetHostView_->render_widget_host_| will be set to NULL. So we
- // check it here and return immediately if it's NULL.
- if (!renderWidgetHostView_->render_widget_host_)
- return;
-
- // Then send keypress and/or composition related events.
- // If there was a marked text or the text to be inserted is longer than 1
- // character, then we send the text by calling FinishComposingText().
- // Otherwise, if the text to be inserted only contains 1 character, then we
- // can just send a keypress event which is fabricated by changing the type of
- // the keydown event, so that we can retain all necessary informations, such
- // as unmodifiedText, etc. And we need to set event.skip_in_browser to true to
- // prevent the browser from handling it again.
- // Note that, |textToBeInserted_| is a UTF-16 string, but it's fine to only
- // handle BMP characters here, as we can always insert non-BMP characters as
- // text.
- BOOL textInserted = NO;
- if (textToBeInserted_.length() >
- ((hasMarkedText_ || oldHasMarkedText) ? 0u : 1u)) {
- widgetHost->ImeCommitText(textToBeInserted_, std::vector<ui::ImeTextSpan>(),
- gfx::Range::InvalidRange(), 0);
- textInserted = YES;
- }
-
- // Updates or cancels the composition. If some text has been inserted, then
- // we don't need to cancel the composition explicitly.
- if (hasMarkedText_ && markedText_.length()) {
- // Sends the updated marked text to the renderer so it can update the
- // composition node in WebKit.
- // When marked text is available, |markedTextSelectedRange_| will be the
- // range being selected inside the marked text.
- widgetHost->ImeSetComposition(markedText_, ime_text_spans_,
- setMarkedTextReplacementRange_,
- markedTextSelectedRange_.location,
- NSMaxRange(markedTextSelectedRange_));
- } else if (oldHasMarkedText && !hasMarkedText_ && !textInserted) {
- if (unmarkTextCalled_) {
- widgetHost->ImeFinishComposingText(false);
- } else {
- widgetHost->ImeCancelComposition();
- }
- }
-
- // Clear information from |interpretKeyEvents:|
- setMarkedTextReplacementRange_ = gfx::Range::InvalidRange();
-
- // If the key event was handled by the input method but it also generated some
- // edit commands, then we need to send the real key event and corresponding
- // edit commands here. This usually occurs when the input method wants to
- // finish current composition session but still wants the application to
- // handle the key event. See http://crbug.com/48161 for reference.
- if (delayEventUntilAfterImeCompostion) {
- // If |delayEventUntilAfterImeCompostion| is YES, then a fake key down event
- // with windowsKeyCode == 0xE5 has already been sent to webkit.
- // So before sending the real key down event, we need to send a fake key up
- // event to balance it.
- NativeWebKeyboardEvent fakeEvent = event;
- fakeEvent.SetType(blink::WebInputEvent::kKeyUp);
- fakeEvent.skip_in_browser = true;
- ui::LatencyInfo fake_event_latency_info = latency_info;
- fake_event_latency_info.set_source_event_type(ui::SourceEventType::OTHER);
- widgetHost->ForwardKeyboardEventWithLatencyInfo(fakeEvent,
- fake_event_latency_info);
- // Not checking |renderWidgetHostView_->render_widget_host_| here because
- // a key event with |skip_in_browser| == true won't be handled by browser,
- // thus it won't destroy the widget.
-
- widgetHost->ForwardKeyboardEventWithCommands(event, fake_event_latency_info,
- &editCommands_);
-
- // Calling ForwardKeyboardEventWithCommands() could have destroyed the
- // widget. When the widget was destroyed,
- // |renderWidgetHostView_->render_widget_host_| will be set to NULL. So we
- // check it here and return immediately if it's NULL.
- if (!renderWidgetHostView_->render_widget_host_)
- return;
- }
-
- const NSUInteger kCtrlCmdKeyMask = NSControlKeyMask | NSCommandKeyMask;
- // Only send a corresponding key press event if there is no marked text.
- if (!hasMarkedText_) {
- if (!textInserted && textToBeInserted_.length() == 1) {
- // If a single character was inserted, then we just send it as a keypress
- // event.
- event.SetType(blink::WebInputEvent::kChar);
- event.text[0] = textToBeInserted_[0];
- event.text[1] = 0;
- event.skip_in_browser = true;
- widgetHost->ForwardKeyboardEventWithLatencyInfo(event, latency_info);
- } else if ((!textInserted || delayEventUntilAfterImeCompostion) &&
- event.text[0] != '\0' &&
- (([theEvent modifierFlags] & kCtrlCmdKeyMask) ||
- (hasEditCommands_ && editCommands_.empty()))) {
- // We don't get insertText: calls if ctrl or cmd is down, or the key event
- // generates an insert command. So synthesize a keypress event for these
- // cases, unless the key event generated any other command.
- event.SetType(blink::WebInputEvent::kChar);
- event.skip_in_browser = true;
- widgetHost->ForwardKeyboardEventWithLatencyInfo(event, latency_info);
- }
+void RenderWidgetHostViewMac::OnNSViewBeginKeyboardEvent() {
+ DCHECK(!in_keyboard_event_);
+ in_keyboard_event_ = true;
+ RenderWidgetHostImpl* widget_host = host();
+ if (widget_host && widget_host->delegate()) {
+ widget_host =
+ widget_host->delegate()->GetFocusedRenderWidgetHost(widget_host);
}
-
- // Possibly autohide the cursor.
- if ([self shouldAutohideCursorForEvent:theEvent]) {
- [NSCursor setHiddenUntilMouseMoves:YES];
- cursorHidden_ = YES;
+ if (widget_host) {
+ keyboard_event_widget_process_id_ = widget_host->GetProcess()->GetID();
+ keyboard_event_widget_routing_id_ = widget_host->GetRoutingID();
}
}
-- (void)forceTouchEvent:(NSEvent*)theEvent {
- if (ui::ForceClickInvokesQuickLook())
- [self quickLookWithEvent:theEvent];
+void RenderWidgetHostViewMac::OnNSViewEndKeyboardEvent() {
+ in_keyboard_event_ = false;
+ keyboard_event_widget_process_id_ = 0;
+ keyboard_event_widget_routing_id_ = 0;
}
-- (void)shortCircuitScrollWheelEvent:(NSEvent*)event {
- if ([event phase] != NSEventPhaseEnded &&
- [event phase] != NSEventPhaseCancelled) {
- return;
- }
-
- if (renderWidgetHostView_->render_widget_host_) {
- // History-swiping is not possible if the logic reaches this point.
- WebMouseWheelEvent webEvent = WebMouseWheelEventBuilder::Build(
- event, self);
- webEvent.rails_mode = mouseWheelFilter_.UpdateRailsMode(webEvent);
- if (renderWidgetHostView_->wheel_scroll_latching_enabled()) {
- renderWidgetHostView_->mouse_wheel_phase_handler_
- .AddPhaseIfNeededAndScheduleEndEvent(webEvent, false);
- } else {
- ui::LatencyInfo latency_info(ui::SourceEventType::WHEEL);
- latency_info.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_UI_COMPONENT, 0, 0);
- renderWidgetHostView_->render_widget_host_
- ->ForwardWheelEventWithLatencyInfo(webEvent, latency_info);
- }
+void RenderWidgetHostViewMac::OnNSViewForwardKeyboardEvent(
+ const NativeWebKeyboardEvent& key_event,
+ const ui::LatencyInfo& latency_info) {
+ if (auto* widget_host = GetWidgetForKeyboardEvent()) {
+ widget_host->ForwardKeyboardEventWithLatencyInfo(key_event, latency_info);
}
+}
- if (endWheelMonitor_) {
- [NSEvent removeMonitor:endWheelMonitor_];
- endWheelMonitor_ = nil;
+void RenderWidgetHostViewMac::OnNSViewForwardKeyboardEventWithCommands(
+ const NativeWebKeyboardEvent& key_event,
+ const ui::LatencyInfo& latency_info,
+ const std::vector<EditCommand>& commands) {
+ if (auto* widget_host = GetWidgetForKeyboardEvent()) {
+ widget_host->ForwardKeyboardEventWithCommands(key_event, latency_info,
+ &commands);
}
}
-- (void)handleBeginGestureWithEvent:(NSEvent*)event {
- [responderDelegate_ beginGestureWithEvent:event];
- gestureBeginEvent_.reset(
- new WebGestureEvent(WebGestureEventBuilder::Build(event, self)));
-
- // If the page is at the minimum zoom level, require a threshold be reached
- // before the pinch has an effect.
- if (renderWidgetHostView_->page_at_minimum_scale_) {
- pinchHasReachedZoomThreshold_ = false;
- pinchUnusedAmount_ = 1;
+void RenderWidgetHostViewMac::OnNSViewRouteOrProcessMouseEvent(
+ const blink::WebMouseEvent& const_web_event) {
+ blink::WebMouseEvent web_event = const_web_event;
+ ui::LatencyInfo latency_info(ui::SourceEventType::OTHER);
+ latency_info.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_UI_COMPONENT, 0, 0);
+ if (ShouldRouteEvent(web_event)) {
+ host()->delegate()->GetInputEventRouter()->RouteMouseEvent(this, &web_event,
+ latency_info);
+ } else {
+ ProcessMouseEvent(web_event, latency_info);
}
}
-- (void)handleEndGestureWithEvent:(NSEvent*)event {
- [responderDelegate_ endGestureWithEvent:event];
-
- // On macOS 10.11+, the end event has type = NSEventTypeMagnify and phase =
- // NSEventPhaseEnded. On macOS 10.10 and older, the event has type =
- // NSEventTypeEndGesture.
- if ([event type] == NSEventTypeMagnify ||
- [event type] == NSEventTypeEndGesture) {
- gestureBeginEvent_.reset();
-
- if (!renderWidgetHostView_->render_widget_host_)
+void RenderWidgetHostViewMac::OnNSViewRouteOrProcessWheelEvent(
+ const blink::WebMouseWheelEvent& const_web_event) {
+ blink::WebMouseWheelEvent web_event = const_web_event;
+ ui::LatencyInfo latency_info(ui::SourceEventType::WHEEL);
+ latency_info.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_UI_COMPONENT, 0, 0);
+ if (wheel_scroll_latching_enabled()) {
+ mouse_wheel_phase_handler_.AddPhaseIfNeededAndScheduleEndEvent(
+ web_event, ShouldRouteEvent(web_event));
+ if (web_event.phase == blink::WebMouseWheelEvent::kPhaseEnded) {
+ // A wheel end event is scheduled and will get dispatched if momentum
+ // phase doesn't start in 100ms. Don't sent the wheel end event
+ // immediately.
return;
-
- if (gestureBeginPinchSent_) {
- WebGestureEvent endEvent(WebGestureEventBuilder::Build(event, self));
- endEvent.SetType(WebInputEvent::kGesturePinchEnd);
- endEvent.source_device =
- blink::WebGestureDevice::kWebGestureDeviceTouchpad;
- renderWidgetHostView_->SendGesturePinchEvent(&endEvent);
- gestureBeginPinchSent_ = NO;
}
}
-}
-
-- (void)beginGestureWithEvent:(NSEvent*)event {
- // This method must be handled when linking with the 10.10 SDK or earlier, or
- // when the app is running on 10.10 or earlier. In other circumstances, the
- // event will be handled by |magnifyWithEvent:|, so this method should do
- // nothing.
- bool shouldHandle = true;
-#if defined(MAC_OS_X_VERSION_10_11) && \
- MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_11
- shouldHandle = base::mac::IsAtMostOS10_10();
-#endif
-
- if (shouldHandle) {
- [self handleBeginGestureWithEvent:event];
- }
-}
-
-- (void)endGestureWithEvent:(NSEvent*)event {
- // This method must be handled when linking with the 10.10 SDK or earlier, or
- // when the app is running on 10.10 or earlier. In other circumstances, the
- // event will be handled by |magnifyWithEvent:|, so this method should do
- // nothing.
- bool shouldHandle = true;
-#if defined(MAC_OS_X_VERSION_10_11) && \
- MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_11
- shouldHandle = base::mac::IsAtMostOS10_10();
-#endif
-
- if (shouldHandle) {
- [self handleEndGestureWithEvent:event];
- }
-}
-
-- (void)touchesMovedWithEvent:(NSEvent*)event {
- [responderDelegate_ touchesMovedWithEvent:event];
-}
-
-- (void)touchesBeganWithEvent:(NSEvent*)event {
- [responderDelegate_ touchesBeganWithEvent:event];
-}
-
-- (void)touchesCancelledWithEvent:(NSEvent*)event {
- [responderDelegate_ touchesCancelledWithEvent:event];
-}
-
-- (void)touchesEndedWithEvent:(NSEvent*)event {
- [responderDelegate_ touchesEndedWithEvent:event];
-}
-
-- (void)smartMagnifyWithEvent:(NSEvent*)event {
- const WebGestureEvent& smartMagnifyEvent =
- WebGestureEventBuilder::Build(event, self);
- if (renderWidgetHostView_ && renderWidgetHostView_->render_widget_host_) {
- renderWidgetHostView_->render_widget_host_->ForwardGestureEvent(
- smartMagnifyEvent);
+ if (ShouldRouteEvent(web_event)) {
+ host()->delegate()->GetInputEventRouter()->RouteMouseWheelEvent(
+ this, &web_event, latency_info);
+ } else {
+ ProcessMouseWheelEvent(web_event, latency_info);
}
}
-- (void)showLookUpDictionaryOverlayInternal:(NSAttributedString*) string
- baselinePoint:(NSPoint) baselinePoint
- targetView:(NSView*) view {
- if ([string length] == 0) {
- // The PDF plugin does not support getting the attributed string at point.
- // Until it does, use NSPerformService(), which opens Dictionary.app.
- // TODO(shuchen): Support GetStringAtPoint() & GetStringFromRange() for PDF.
- // See crbug.com/152438.
- NSString* text = nil;
- if (auto* selection = renderWidgetHostView_->GetTextSelection())
- text = base::SysUTF16ToNSString(selection->selected_text());
+void RenderWidgetHostViewMac::OnNSViewForwardMouseEvent(
+ const blink::WebMouseEvent& web_event) {
+ if (host())
+ host()->ForwardMouseEvent(web_event);
- if ([text length] == 0)
- return;
- scoped_refptr<ui::UniquePasteboard> pasteboard = new ui::UniquePasteboard;
- NSArray* types = [NSArray arrayWithObject:NSStringPboardType];
- [pasteboard->get() declareTypes:types owner:nil];
- if ([pasteboard->get() setString:text forType:NSStringPboardType])
- NSPerformService(@"Look Up in Dictionary", pasteboard->get());
- return;
- }
- NSPoint flippedBaselinePoint = {
- baselinePoint.x, [view frame].size.height - baselinePoint.y,
- };
- [view showDefinitionForAttributedString:string atPoint:flippedBaselinePoint];
+ if (web_event.GetType() == WebInputEvent::kMouseLeave)
+ ns_view_bridge_->SetTooltipText(base::string16());
}
-- (void)showLookUpDictionaryOverlayFromRange:(NSRange)range
- targetView:(NSView*)targetView {
- content::RenderWidgetHostViewBase* focusedView =
- renderWidgetHostView_->GetFocusedViewForTextSelection();
- if (!focusedView)
- return;
-
- RenderWidgetHostImpl* widgetHost =
- RenderWidgetHostImpl::From(focusedView->GetRenderWidgetHost());
- if (!widgetHost)
- return;
-
- int32_t targetWidgetProcessId = widgetHost->GetProcess()->GetID();
- int32_t targetWidgetRoutingId = widgetHost->GetRoutingID();
- TextInputClientMac::GetInstance()->GetStringFromRange(
- widgetHost, range, ^(NSAttributedString* string, NSPoint baselinePoint) {
- if (!content::RenderWidgetHost::FromID(targetWidgetProcessId,
- targetWidgetRoutingId)) {
- // By the time we get here |widgetHost| might have been destroyed.
- // (See https://crbug.com/737032).
- return;
- }
-
- if (auto* rwhv = widgetHost->GetView()) {
- gfx::Point pointInRootView = rwhv->TransformPointToRootCoordSpace(
- gfx::Point(baselinePoint.x, baselinePoint.y));
- baselinePoint.x = pointInRootView.x();
- baselinePoint.y = pointInRootView.y();
- }
- [self showLookUpDictionaryOverlayInternal:string
- baselinePoint:baselinePoint
- targetView:targetView];
- });
-}
-
-- (void)showLookUpDictionaryOverlayAtPoint:(NSPoint)point {
- gfx::PointF rootPoint(point.x, NSHeight([self frame]) - point.y);
- gfx::PointF transformedPoint;
- if (!renderWidgetHostView_->render_widget_host_ ||
- !renderWidgetHostView_->render_widget_host_->delegate() ||
- !renderWidgetHostView_->render_widget_host_->delegate()
- ->GetInputEventRouter())
- return;
-
- RenderWidgetHostImpl* widgetHost =
- renderWidgetHostView_->render_widget_host_->delegate()
- ->GetInputEventRouter()
- ->GetRenderWidgetHostAtPoint(renderWidgetHostView_.get(), rootPoint,
- &transformedPoint);
- if (!widgetHost)
- return;
-
- int32_t targetWidgetProcessId = widgetHost->GetProcess()->GetID();
- int32_t targetWidgetRoutingId = widgetHost->GetRoutingID();
- TextInputClientMac::GetInstance()->GetStringAtPoint(
- widgetHost, gfx::ToFlooredPoint(transformedPoint),
- ^(NSAttributedString* string, NSPoint baselinePoint) {
- if (!content::RenderWidgetHost::FromID(targetWidgetProcessId,
- targetWidgetRoutingId)) {
- // By the time we get here |widgetHost| might have been destroyed.
- // (See https://crbug.com/737032).
- return;
- }
-
- if (auto* rwhv = widgetHost->GetView()) {
- gfx::Point pointInRootView = rwhv->TransformPointToRootCoordSpace(
- gfx::Point(baselinePoint.x, baselinePoint.y));
- baselinePoint.x = pointInRootView.x();
- baselinePoint.y = pointInRootView.y();
- }
- [self showLookUpDictionaryOverlayInternal:string
- baselinePoint:baselinePoint
- targetView:self];
- });
-}
-
-// This is invoked only on 10.8 or newer when the user taps a word using
-// three fingers.
-- (void)quickLookWithEvent:(NSEvent*)event {
- NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
- [self showLookUpDictionaryOverlayAtPoint:point];
-}
-
-// This method handles 2 different types of hardware events.
-// (Apple does not distinguish between them).
-// a. Scrolling the middle wheel of a mouse.
-// b. Swiping on the track pad.
-//
-// This method is responsible for 2 types of behavior:
-// a. Scrolling the content of window.
-// b. Navigating forwards/backwards in history.
-//
-// This is a brief description of the logic:
-// 1. If the content can be scrolled, scroll the content.
-// (This requires a roundtrip to blink to determine whether the content
-// can be scrolled.)
-// Once this logic is triggered, the navigate logic cannot be triggered
-// until the gesture finishes.
-// 2. If the user is making a horizontal swipe, start the navigate
-// forward/backwards UI.
-// Once this logic is triggered, the user can either cancel or complete
-// the gesture. If the user completes the gesture, all remaining touches
-// are swallowed, and not allowed to scroll the content. If the user
-// cancels the gesture, all remaining touches are forwarded to the content
-// scroll logic. The user cannot trigger the navigation logic again.
-- (void)scrollWheel:(NSEvent*)event {
-#if defined(MAC_OS_X_VERSION_10_11) && \
- MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_11
- // When linking against the 10.11 (or later) SDK and running on 10.11 or
- // later, check the phase of the event and specially handle the "begin" and
- // "end" phases.
- if (base::mac::IsAtLeastOS10_11()) {
- if (event.phase == NSEventPhaseBegan) {
- [self handleBeginGestureWithEvent:event];
- }
-
- if (event.phase == NSEventPhaseEnded ||
- event.phase == NSEventPhaseCancelled) {
- [self handleEndGestureWithEvent:event];
- }
- }
-#endif
-
- if (responderDelegate_ &&
- [responderDelegate_ respondsToSelector:@selector(handleEvent:)]) {
- BOOL handled = [responderDelegate_ handleEvent:event];
- if (handled)
- return;
- }
-
- // Compute Event.Latency.OS.MOUSE_WHEEL histogram.
- ui::ComputeEventLatencyOS(event);
-
- // Use an NSEvent monitor to listen for the wheel-end end. This ensures that
- // the event is received even when the mouse cursor is no longer over the view
- // when the scrolling ends (e.g. if the tab was switched). This is necessary
- // for ending rubber-banding in such cases.
- if ([event phase] == NSEventPhaseBegan && !endWheelMonitor_) {
- endWheelMonitor_ =
- [NSEvent addLocalMonitorForEventsMatchingMask:NSScrollWheelMask
- handler:^(NSEvent* blockEvent) {
- [self shortCircuitScrollWheelEvent:blockEvent];
- return blockEvent;
- }];
- }
-
- // This is responsible for content scrolling!
- if (renderWidgetHostView_->render_widget_host_) {
- WebMouseWheelEvent webEvent = WebMouseWheelEventBuilder::Build(event, self);
- webEvent.rails_mode = mouseWheelFilter_.UpdateRailsMode(webEvent);
+void RenderWidgetHostViewMac::OnNSViewForwardWheelEvent(
+ const blink::WebMouseWheelEvent& const_web_event) {
+ blink::WebMouseWheelEvent web_event = const_web_event;
+ if (wheel_scroll_latching_enabled()) {
+ mouse_wheel_phase_handler_.AddPhaseIfNeededAndScheduleEndEvent(web_event,
+ false);
+ } else {
ui::LatencyInfo latency_info(ui::SourceEventType::WHEEL);
latency_info.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_UI_COMPONENT, 0, 0);
- if (renderWidgetHostView_->wheel_scroll_latching_enabled()) {
- renderWidgetHostView_->mouse_wheel_phase_handler_
- .AddPhaseIfNeededAndScheduleEndEvent(
- webEvent, renderWidgetHostView_->ShouldRouteEvent(webEvent));
- if (webEvent.phase == blink::WebMouseWheelEvent::kPhaseEnded) {
- // A wheel end event is scheduled and will get dispatched if momentum
- // phase doesn't start in 100ms. Don't sent the wheel end event
- // immediately.
- return;
- }
- }
-
- if (renderWidgetHostView_->ShouldRouteEvent(webEvent)) {
- renderWidgetHostView_->render_widget_host_->delegate()
- ->GetInputEventRouter()
- ->RouteMouseWheelEvent(renderWidgetHostView_.get(), &webEvent,
- latency_info);
- } else {
- renderWidgetHostView_->ProcessMouseWheelEvent(webEvent, latency_info);
- }
+ host()->ForwardWheelEventWithLatencyInfo(web_event, latency_info);
}
}
-// Called repeatedly during a pinch gesture, with incremental change values.
-- (void)magnifyWithEvent:(NSEvent*)event {
- if (!renderWidgetHostView_->render_widget_host_)
- return;
+void RenderWidgetHostViewMac::OnNSViewGestureBegin(
+ blink::WebGestureEvent begin_event) {
+ gesture_begin_event_.reset(new WebGestureEvent(begin_event));
-#if defined(MAC_OS_X_VERSION_10_11) && \
- MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_11
- // When linking against the 10.11 (or later) SDK and running on 10.11 or
- // later, check the phase of the event and specially handle the "begin" and
- // "end" phases.
- if (base::mac::IsAtLeastOS10_11()) {
- if (event.phase == NSEventPhaseBegan) {
- [self handleBeginGestureWithEvent:event];
- return;
- }
-
- if (event.phase == NSEventPhaseEnded ||
- event.phase == NSEventPhaseCancelled) {
- [self handleEndGestureWithEvent:event];
- return;
- }
- }
-#endif
-
- // If this conditional evalutes to true, and the function has not
- // short-circuited from the previous block, then this event is a duplicate of
- // a gesture event, and should be ignored.
- if (event.phase == NSEventPhaseBegan || event.phase == NSEventPhaseEnded ||
- event.phase == NSEventPhaseCancelled) {
- return;
+ // If the page is at the minimum zoom level, require a threshold be reached
+ // before the pinch has an effect.
+ if (page_at_minimum_scale_) {
+ pinch_has_reached_zoom_threshold_ = false;
+ pinch_unused_amount_ = 1;
}
+}
+void RenderWidgetHostViewMac::OnNSViewGestureUpdate(
+ blink::WebGestureEvent update_event) {
// If, due to nesting of multiple gestures (e.g, from multiple touch
// devices), the beginning of the gesture has been lost, skip the remainder
// of the gesture.
- if (!gestureBeginEvent_)
+ if (!gesture_begin_event_)
return;
- if (!pinchHasReachedZoomThreshold_) {
- pinchUnusedAmount_ *= (1 + [event magnification]);
- if (pinchUnusedAmount_ < 0.667 || pinchUnusedAmount_ > 1.5)
- pinchHasReachedZoomThreshold_ = true;
+ if (!pinch_has_reached_zoom_threshold_) {
+ pinch_unused_amount_ *= update_event.data.pinch_update.scale;
+ if (pinch_unused_amount_ < 0.667 || pinch_unused_amount_ > 1.5)
+ pinch_has_reached_zoom_threshold_ = true;
}
// Send a GesturePinchBegin event if none has been sent yet.
- if (!gestureBeginPinchSent_) {
- if (renderWidgetHostView_->wheel_scroll_latching_enabled()) {
+ if (!gesture_begin_pinch_sent_) {
+ if (wheel_scroll_latching_enabled()) {
// Before starting a pinch sequence, send the pending wheel end event to
// finish scrolling.
- renderWidgetHostView_->mouse_wheel_phase_handler_
- .DispatchPendingWheelEndEvent();
+ mouse_wheel_phase_handler_.DispatchPendingWheelEndEvent();
}
- WebGestureEvent beginEvent(*gestureBeginEvent_);
- beginEvent.SetType(WebInputEvent::kGesturePinchBegin);
- beginEvent.source_device =
- blink::WebGestureDevice::kWebGestureDeviceTouchpad;
- renderWidgetHostView_->SendGesturePinchEvent(&beginEvent);
- gestureBeginPinchSent_ = YES;
+ WebGestureEvent begin_event(*gesture_begin_event_);
+ begin_event.SetType(WebInputEvent::kGesturePinchBegin);
+ begin_event.SetSourceDevice(
+ blink::WebGestureDevice::kWebGestureDeviceTouchpad);
+ SendGesturePinchEvent(&begin_event);
+ gesture_begin_pinch_sent_ = YES;
}
// Send a GesturePinchUpdate event.
- WebGestureEvent updateEvent = WebGestureEventBuilder::Build(event, self);
- updateEvent.data.pinch_update.zoom_disabled = !pinchHasReachedZoomThreshold_;
- renderWidgetHostView_->SendGesturePinchEvent(&updateEvent);
-}
-
-- (void)viewWillMoveToWindow:(NSWindow*)newWindow {
- NSWindow* oldWindow = [self window];
-
- NSNotificationCenter* notificationCenter =
- [NSNotificationCenter defaultCenter];
-
- if (oldWindow) {
- [notificationCenter
- removeObserver:self
- name:NSWindowDidChangeBackingPropertiesNotification
- object:oldWindow];
- [notificationCenter
- removeObserver:self
- name:NSWindowDidMoveNotification
- object:oldWindow];
- [notificationCenter
- removeObserver:self
- name:NSWindowDidEndLiveResizeNotification
- object:oldWindow];
- [notificationCenter
- removeObserver:self
- name:NSWindowDidBecomeKeyNotification
- object:oldWindow];
- [notificationCenter
- removeObserver:self
- name:NSWindowDidResignKeyNotification
- object:oldWindow];
- }
- if (newWindow) {
- [notificationCenter
- addObserver:self
- selector:@selector(windowDidChangeBackingProperties:)
- name:NSWindowDidChangeBackingPropertiesNotification
- object:newWindow];
- [notificationCenter
- addObserver:self
- selector:@selector(windowChangedGlobalFrame:)
- name:NSWindowDidMoveNotification
- object:newWindow];
- [notificationCenter
- addObserver:self
- selector:@selector(windowChangedGlobalFrame:)
- name:NSWindowDidEndLiveResizeNotification
- object:newWindow];
- [notificationCenter addObserver:self
- selector:@selector(windowDidBecomeKey:)
- name:NSWindowDidBecomeKeyNotification
- object:newWindow];
- [notificationCenter addObserver:self
- selector:@selector(windowDidResignKey:)
- name:NSWindowDidResignKeyNotification
- object:newWindow];
- }
-}
-
-- (void)updateScreenProperties{
- renderWidgetHostView_->UpdateNSViewAndDisplayProperties();
- renderWidgetHostView_->UpdateDisplayLink();
-}
-
-// http://developer.apple.com/library/mac/#documentation/GraphicsAnimation/Conceptual/HighResolutionOSX/CapturingScreenContents/CapturingScreenContents.html#//apple_ref/doc/uid/TP40012302-CH10-SW4
-- (void)windowDidChangeBackingProperties:(NSNotification*)notification {
- // Background tabs check if their screen scale factor, color profile, and
- // vsync properties changed when they are added to a window.
-
- // Allocating a CGLayerRef with the current scale factor immediately from
- // this handler doesn't work. Schedule the backing store update on the
- // next runloop cycle, then things are read for CGLayerRef allocations to
- // work.
- [self performSelector:@selector(updateScreenProperties)
- withObject:nil
- afterDelay:0];
-}
-
-- (void)windowChangedGlobalFrame:(NSNotification*)notification {
- renderWidgetHostView_->UpdateNSViewAndDisplayProperties();
-}
-
-- (void)setFrameSize:(NSSize)newSize {
- TRACE_EVENT0("browser", "RenderWidgetHostViewCocoa::setFrameSize");
-
- // NB: -[NSView setFrame:] calls through -setFrameSize:, so overriding
- // -setFrame: isn't neccessary.
- [super setFrameSize:newSize];
-
- renderWidgetHostView_->UpdateNSViewAndDisplayProperties();
-
- // Wait for the frame that WasResize might have requested. If the view is
- // being made visible at a new size, then this call will have no effect
- // because the view widget is still hidden, and the pause call in WasShown
- // will have this effect for us.
- renderWidgetHostView_->PauseForPendingResizeOrRepaintsAndDraw();
-}
-
-- (BOOL)canBecomeKeyView {
- if (!renderWidgetHostView_->render_widget_host_)
- return NO;
-
- return canBeKeyView_;
-}
-
-- (BOOL)acceptsFirstResponder {
- if (!renderWidgetHostView_->render_widget_host_)
- return NO;
-
- return canBeKeyView_;
+ update_event.data.pinch_update.zoom_disabled =
+ !pinch_has_reached_zoom_threshold_;
+ SendGesturePinchEvent(&update_event);
}
-- (void)windowDidBecomeKey:(NSNotification*)notification {
- DCHECK([self window]);
- DCHECK_EQ([self window], [notification object]);
- if ([[self window] firstResponder] == self)
- renderWidgetHostView_->SetActive(true);
-}
-
-- (void)windowDidResignKey:(NSNotification*)notification {
- DCHECK([self window]);
- DCHECK_EQ([self window], [notification object]);
-
- // If our app is still active and we're still the key window, ignore this
- // message, since it just means that a menu extra (on the "system status bar")
- // was activated; we'll get another |-windowDidResignKey| if we ever really
- // lose key window status.
- if ([NSApp isActive] && ([NSApp keyWindow] == [self window]))
- return;
-
- if ([[self window] firstResponder] == self)
- renderWidgetHostView_->SetActive(false);
-}
-
-- (BOOL)becomeFirstResponder {
- if (!renderWidgetHostView_->render_widget_host_)
- return NO;
-
- renderWidgetHostView_->render_widget_host_->GotFocus();
- renderWidgetHostView_->SetTextInputActive(true);
-
- // Cancel any onging composition text which was left before we lost focus.
- // TODO(suzhe): We should do it in -resignFirstResponder: method, but
- // somehow that method won't be called when switching among different tabs.
- // See http://crbug.com/47209
- [self cancelComposition];
-
- NSNumber* direction = [NSNumber numberWithUnsignedInteger:
- [[self window] keyViewSelectionDirection]];
- NSDictionary* userInfo =
- [NSDictionary dictionaryWithObject:direction
- forKey:kSelectionDirection];
- [[NSNotificationCenter defaultCenter]
- postNotificationName:kViewDidBecomeFirstResponder
- object:self
- userInfo:userInfo];
-
- return YES;
-}
-
-- (BOOL)resignFirstResponder {
- renderWidgetHostView_->SetTextInputActive(false);
- if (!renderWidgetHostView_->render_widget_host_)
- return YES;
-
- if (closeOnDeactivate_)
- renderWidgetHostView_->KillSelf();
-
- renderWidgetHostView_->render_widget_host_->LostFocus();
-
- // We should cancel any onging composition whenever RWH's Blur() method gets
- // called, because in this case, webkit will confirm the ongoing composition
- // internally.
- [self cancelComposition];
-
- return YES;
-}
-
-- (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
- if (responderDelegate_ &&
- [responderDelegate_
- respondsToSelector:@selector(validateUserInterfaceItem:
- isValidItem:)]) {
- BOOL valid;
- BOOL known =
- [responderDelegate_ validateUserInterfaceItem:item isValidItem:&valid];
- if (known)
- return valid;
- }
-
- SEL action = [item action];
- BOOL is_render_view =
- RenderViewHost::From(renderWidgetHostView_->render_widget_host_) !=
- nullptr;
-
- if (action == @selector(stopSpeaking:))
- return is_render_view && renderWidgetHostView_->IsSpeaking();
-
- if (action == @selector(startSpeaking:))
- return is_render_view && renderWidgetHostView_->SupportsSpeech();
-
- // For now, these actions are always enabled for render view,
- // this is sub-optimal.
- // TODO(suzhe): Plumb the "can*" methods up from WebCore.
- if (action == @selector(undo:) ||
- action == @selector(redo:) ||
- action == @selector(cut:) ||
- action == @selector(copy:) ||
- action == @selector(copyToFindPboard:) ||
- action == @selector(paste:) ||
- action == @selector(pasteAndMatchStyle:)) {
- return is_render_view;
+void RenderWidgetHostViewMac::OnNSViewGestureEnd(
+ blink::WebGestureEvent end_event) {
+ gesture_begin_event_.reset();
+ if (gesture_begin_pinch_sent_) {
+ SendGesturePinchEvent(&end_event);
+ gesture_begin_pinch_sent_ = false;
}
-
- return editCommand_helper_->IsMenuItemEnabled(action, self);
-}
-
-- (RenderWidgetHostViewMac*)renderWidgetHostViewMac {
- return renderWidgetHostView_.get();
}
-// Determine whether we should autohide the cursor (i.e., hide it until mouse
-// move) for the given event. Customize here to be more selective about which
-// key presses to autohide on.
-- (BOOL)shouldAutohideCursorForEvent:(NSEvent*)event {
- return (renderWidgetHostView_->GetTextInputType() !=
- ui::TEXT_INPUT_TYPE_NONE &&
- [event type] == NSKeyDown &&
- !([event modifierFlags] & NSCommandKeyMask))
- ? YES
- : NO;
+void RenderWidgetHostViewMac::OnNSViewSmartMagnify(
+ const blink::WebGestureEvent& smart_magnify_event) {
+ host()->ForwardGestureEvent(smart_magnify_event);
}
-- (NSArray *)accessibilityArrayAttributeValues:(NSString *)attribute
- index:(NSUInteger)index
- maxCount:(NSUInteger)maxCount {
- NSArray* fullArray = [self accessibilityAttributeValue:attribute];
- NSUInteger totalLength = [fullArray count];
- if (index >= totalLength)
- return nil;
- NSUInteger length = MIN(totalLength - index, maxCount);
- return [fullArray subarrayWithRange:NSMakeRange(index, length)];
+void RenderWidgetHostViewMac::OnNSViewImeSetComposition(
+ const base::string16& text,
+ const std::vector<ui::ImeTextSpan>& ime_text_spans,
+ const gfx::Range& replacement_range,
+ int selection_start,
+ int selection_end) {
+ if (auto* widget_host = GetWidgetForIme()) {
+ widget_host->ImeSetComposition(text, ime_text_spans, replacement_range,
+ selection_start, selection_end);
+ }
}
-- (NSUInteger)accessibilityArrayAttributeCount:(NSString *)attribute {
- NSArray* fullArray = [self accessibilityAttributeValue:attribute];
- return [fullArray count];
+void RenderWidgetHostViewMac::OnNSViewImeCommitText(
+ const base::string16& text,
+ const gfx::Range& replacement_range) {
+ if (auto* widget_host = GetWidgetForIme()) {
+ widget_host->ImeCommitText(text, std::vector<ui::ImeTextSpan>(),
+ replacement_range, 0);
+ }
}
-- (id)accessibilityAttributeValue:(NSString *)attribute {
- BrowserAccessibilityManager* manager =
- renderWidgetHostView_->render_widget_host_
- ->GetRootBrowserAccessibilityManager();
-
- // Contents specifies document view of RenderWidgetHostViewCocoa provided by
- // BrowserAccessibilityManager. Children includes all subviews in addition to
- // contents. Currently we do not have subviews besides the document view.
- if (([attribute isEqualToString:NSAccessibilityChildrenAttribute] ||
- [attribute isEqualToString:NSAccessibilityContentsAttribute]) &&
- manager) {
- return [NSArray arrayWithObjects:ToBrowserAccessibilityCocoa(
- manager->GetRoot()), nil];
- } else if ([attribute isEqualToString:NSAccessibilityRoleAttribute]) {
- return NSAccessibilityScrollAreaRole;
- }
- id ret = [super accessibilityAttributeValue:attribute];
- return ret;
-}
-
-- (NSArray*)accessibilityAttributeNames {
- NSMutableArray* ret = [[[NSMutableArray alloc] init] autorelease];
- [ret addObject:NSAccessibilityContentsAttribute];
- [ret addObjectsFromArray:[super accessibilityAttributeNames]];
- return ret;
-}
-
-- (id)accessibilityHitTest:(NSPoint)point {
- BrowserAccessibilityManager* manager =
- renderWidgetHostView_->render_widget_host_
- ->GetRootBrowserAccessibilityManager();
- if (!manager)
- return self;
- NSPoint pointInWindow =
- ui::ConvertPointFromScreenToWindow([self window], point);
- NSPoint localPoint = [self convertPoint:pointInWindow fromView:nil];
- localPoint.y = NSHeight([self bounds]) - localPoint.y;
- BrowserAccessibilityCocoa* root =
- ToBrowserAccessibilityCocoa(manager->GetRoot());
- id obj = [root accessibilityHitTest:localPoint];
- return obj;
-}
-
-- (BOOL)accessibilityIsIgnored {
- BrowserAccessibilityManager* manager =
- renderWidgetHostView_->render_widget_host_
- ->GetRootBrowserAccessibilityManager();
- return !manager;
-}
-
-- (NSUInteger)accessibilityGetIndexOf:(id)child {
- BrowserAccessibilityManager* manager =
- renderWidgetHostView_->render_widget_host_
- ->GetRootBrowserAccessibilityManager();
- // Only child is root.
- if (manager &&
- ToBrowserAccessibilityCocoa(manager->GetRoot()) == child) {
- return 0;
- } else {
- return NSNotFound;
+void RenderWidgetHostViewMac::OnNSViewImeFinishComposingText() {
+ if (auto* widget_host = GetWidgetForIme()) {
+ widget_host->ImeFinishComposingText(false);
}
}
-- (id)accessibilityFocusedUIElement {
- BrowserAccessibilityManager* manager =
- renderWidgetHostView_->render_widget_host_
- ->GetRootBrowserAccessibilityManager();
- if (manager) {
- BrowserAccessibility* focused_item = manager->GetFocus();
- DCHECK(focused_item);
- if (focused_item) {
- BrowserAccessibilityCocoa* focused_item_cocoa =
- ToBrowserAccessibilityCocoa(focused_item);
- DCHECK(focused_item_cocoa);
- if (focused_item_cocoa)
- return focused_item_cocoa;
- }
+void RenderWidgetHostViewMac::OnNSViewImeCancelComposition() {
+ if (auto* widget_host = GetWidgetForIme()) {
+ widget_host->ImeCancelComposition();
}
- return [super accessibilityFocusedUIElement];
}
-// Below is our NSTextInputClient implementation.
-//
-// When WebHTMLView receives a NSKeyDown event, WebHTMLView calls the following
-// functions to process this event.
-//
-// [WebHTMLView keyDown] ->
-// EventHandler::keyEvent() ->
-// ...
-// [WebEditorClient handleKeyboardEvent] ->
-// [WebHTMLView _interceptEditingKeyEvent] ->
-// [NSResponder interpretKeyEvents] ->
-// [WebHTMLView insertText] ->
-// Editor::insertText()
-//
-// Unfortunately, it is hard for Chromium to use this implementation because
-// it causes key-typing jank.
-// RenderWidgetHostViewMac is running in a browser process. On the other
-// hand, Editor and EventHandler are running in a renderer process.
-// So, if we used this implementation, a NSKeyDown event is dispatched to
-// the following functions of Chromium.
-//
-// [RenderWidgetHostViewMac keyEvent] (browser) ->
-// |Sync IPC (KeyDown)| (*1) ->
-// EventHandler::keyEvent() (renderer) ->
-// ...
-// EditorClientImpl::handleKeyboardEvent() (renderer) ->
-// |Sync IPC| (*2) ->
-// [RenderWidgetHostViewMac _interceptEditingKeyEvent] (browser) ->
-// [self interpretKeyEvents] ->
-// [RenderWidgetHostViewMac insertText] (browser) ->
-// |Async IPC| ->
-// Editor::insertText() (renderer)
-//
-// (*1) we need to wait until this call finishes since WebHTMLView uses the
-// result of EventHandler::keyEvent().
-// (*2) we need to wait until this call finishes since WebEditorClient uses
-// the result of [WebHTMLView _interceptEditingKeyEvent].
-//
-// This needs many sync IPC messages sent between a browser and a renderer for
-// each key event, which would probably result in key-typing jank.
-// To avoid this problem, this implementation processes key events (and input
-// method events) totally in a browser process and sends asynchronous input
-// events, almost same as KeyboardEvents (and TextEvents) of DOM Level 3, to a
-// renderer process.
-//
-// [RenderWidgetHostViewMac keyEvent] (browser) ->
-// |Async IPC (RawKeyDown)| ->
-// [self interpretKeyEvents] ->
-// [RenderWidgetHostViewMac insertText] (browser) ->
-// |Async IPC (Char)| ->
-// Editor::insertText() (renderer)
-//
-// Since this implementation doesn't have to wait any IPC calls, this doesn't
-// make any key-typing jank. --hbono 7/23/09
-//
-extern "C" {
-extern NSString *NSTextInputReplacementRangeAttributeName;
-}
-
-- (NSArray *)validAttributesForMarkedText {
- // This code is just copied from WebKit except renaming variables.
- if (!validAttributesForMarkedText_) {
- validAttributesForMarkedText_.reset([[NSArray alloc] initWithObjects:
- NSUnderlineStyleAttributeName,
- NSUnderlineColorAttributeName,
- NSMarkedClauseSegmentAttributeName,
- NSTextInputReplacementRangeAttributeName,
- nil]);
- }
- return validAttributesForMarkedText_.get();
-}
-
-- (NSUInteger)characterIndexForPoint:(NSPoint)thePoint {
- DCHECK([self window]);
- // |thePoint| is in screen coordinates, but needs to be converted to WebKit
- // coordinates (upper left origin). Scroll offsets will be taken care of in
- // the renderer.
- thePoint = ui::ConvertPointFromScreenToWindow([self window], thePoint);
- thePoint = [self convertPoint:thePoint fromView:nil];
- thePoint.y = NSHeight([self frame]) - thePoint.y;
-
- if (!renderWidgetHostView_->render_widget_host_ ||
- !renderWidgetHostView_->render_widget_host_->delegate() ||
- !renderWidgetHostView_->render_widget_host_->delegate()
- ->GetInputEventRouter())
- return NSNotFound;
-
- gfx::PointF rootPoint(thePoint.x, thePoint.y);
- gfx::PointF transformedPoint;
- RenderWidgetHostImpl* widgetHost =
- renderWidgetHostView_->render_widget_host_->delegate()
- ->GetInputEventRouter()
- ->GetRenderWidgetHostAtPoint(renderWidgetHostView_.get(), rootPoint,
- &transformedPoint);
- if (!widgetHost)
- return NSNotFound;
-
- NSUInteger index =
- TextInputClientMac::GetInstance()->GetCharacterIndexAtPoint(
- widgetHost, gfx::ToFlooredPoint(transformedPoint));
- return index;
-}
-
-- (NSRect)firstViewRectForCharacterRange:(NSRange)theRange
- actualRange:(NSRangePointer)actualRange {
- NSRect rect;
- if (!renderWidgetHostView_->GetCachedFirstRectForCharacterRange(
- theRange,
- &rect,
- actualRange)) {
- rect = TextInputClientMac::GetInstance()->GetFirstRectForRange(
- renderWidgetHostView_->GetFocusedWidget(), theRange);
+void RenderWidgetHostViewMac::OnNSViewLookUpDictionaryOverlayFromRange(
+ const gfx::Range& range) {
+ content::RenderWidgetHostViewBase* focused_view =
+ GetFocusedViewForTextSelection();
+ if (!focused_view)
+ return;
- // TODO(thakis): Pipe |actualRange| through TextInputClientMac machinery.
- if (actualRange)
- *actualRange = theRange;
- }
+ RenderWidgetHostImpl* widget_host =
+ RenderWidgetHostImpl::From(focused_view->GetRenderWidgetHost());
+ if (!widget_host)
+ return;
- // The returned rectangle is in WebKit coordinates (upper left origin), so
- // flip the coordinate system.
- NSRect viewFrame = [self frame];
- rect.origin.y = NSHeight(viewFrame) - NSMaxY(rect);
- return rect;
+ int32_t target_widget_process_id = widget_host->GetProcess()->GetID();
+ int32_t target_widget_routing_id = widget_host->GetRoutingID();
+ TextInputClientMac::GetInstance()->GetStringFromRange(
+ widget_host, range,
+ base::BindOnce(&RenderWidgetHostViewMac::OnGotStringForDictionaryOverlay,
+ weak_factory_.GetWeakPtr(), target_widget_process_id,
+ target_widget_routing_id));
}
-- (NSRect)firstRectForCharacterRange:(NSRange)theRange
- actualRange:(NSRangePointer)actualRange {
- // During tab closure, events can arrive after RenderWidgetHostViewMac::
- // Destroy() is called, which will have set |render_widget_host_| to null.
- if (!renderWidgetHostView_->GetFocusedWidget()) {
- [self cancelComposition];
- return NSZeroRect;
- }
+void RenderWidgetHostViewMac::OnNSViewLookUpDictionaryOverlayAtPoint(
+ const gfx::PointF& root_point) {
+ if (!host() || !host()->delegate() ||
+ !host()->delegate()->GetInputEventRouter())
+ return;
- NSRect rect = [self firstViewRectForCharacterRange:theRange
- actualRange:actualRange];
+ gfx::PointF transformed_point;
+ RenderWidgetHostImpl* widget_host =
+ host()->delegate()->GetInputEventRouter()->GetRenderWidgetHostAtPoint(
+ this, root_point, &transformed_point);
+ if (!widget_host)
+ return;
- // Convert into screen coordinates for return.
- rect = [self convertRect:rect toView:nil];
- rect = [[self window] convertRectToScreen:rect];
- return rect;
+ int32_t target_widget_process_id = widget_host->GetProcess()->GetID();
+ int32_t target_widget_routing_id = widget_host->GetRoutingID();
+ TextInputClientMac::GetInstance()->GetStringAtPoint(
+ widget_host, gfx::ToFlooredPoint(transformed_point),
+ base::BindOnce(&RenderWidgetHostViewMac::OnGotStringForDictionaryOverlay,
+ weak_factory_.GetWeakPtr(), target_widget_process_id,
+ target_widget_routing_id));
}
-- (NSRange)selectedRange {
- if (selectedRange_.location == NSNotFound)
- return NSMakeRange(NSNotFound, 0);
- return selectedRange_;
-}
-
-- (NSRange)markedRange {
- // An input method calls this method to check if an application really has
- // a text being composed when hasMarkedText call returns true.
- // Returns the range saved in the setMarkedText method so the input method
- // calls the setMarkedText method and we can update the composition node
- // there. (When this method returns an empty range, the input method doesn't
- // call the setMarkedText method.)
- return hasMarkedText_ ? markedRange_ : NSMakeRange(NSNotFound, 0);
-}
-
-- (NSAttributedString*)attributedSubstringForProposedRange:(NSRange)range
- actualRange:(NSRangePointer)actualRange {
- // Prepare |actualRange| as if the proposed range is invalid. If it is valid,
- // then |actualRange| will be updated again.
- if (actualRange)
- *actualRange = NSMakeRange(NSNotFound, 0);
-
- // The caller of this method is allowed to pass nonsensical ranges. These
- // can't even be converted into gfx::Ranges.
- if (range.location == NSNotFound || range.length == 0)
- return nil;
- if (range.length >= std::numeric_limits<NSUInteger>::max() - range.location)
- return nil;
-
- const gfx::Range requested_range(range);
- if (requested_range.is_reversed())
- return nil;
-
- gfx::Range expected_range;
- const base::string16* expected_text;
- const content::TextInputManager::CompositionRangeInfo* compositionInfo =
- renderWidgetHostView_->GetCompositionRangeInfo();
- const content::TextInputManager::TextSelection* selection =
- renderWidgetHostView_->GetTextSelection();
- if (!selection)
- return nil;
-
- if (compositionInfo && !compositionInfo->range.is_empty()) {
- // This method might get called after TextInputState.type is reset to none,
- // in which case there will be no composition range information
- // (https://crbug.com/698672).
- expected_text = &markedText_;
- expected_range = compositionInfo->range;
- } else {
- expected_text = &selection->text();
- size_t offset = selection->offset();
- expected_range = gfx::Range(offset, offset + expected_text->size());
- }
-
- gfx::Range actual_range = expected_range.Intersect(requested_range);
- if (!actual_range.IsValid())
- return nil;
-
- // Gets the raw bytes to avoid unnecessary string copies for generating
- // NSString.
- const base::char16* bytes =
- &(*expected_text)[actual_range.start() - expected_range.start()];
- // Avoid integer overflow.
- base::CheckedNumeric<size_t> requested_len = actual_range.length();
- requested_len *= sizeof(base::char16);
- NSUInteger bytes_len = base::strict_cast<NSUInteger, size_t>(
- requested_len.ValueOrDefault(0));
- base::scoped_nsobject<NSString> ns_string(
- [[NSString alloc] initWithBytes:bytes
- length:bytes_len
- encoding:NSUTF16LittleEndianStringEncoding]);
- if (actualRange)
- *actualRange = actual_range.ToNSRange();
-
- return [[[NSAttributedString alloc] initWithString:ns_string] autorelease];
-}
-
-- (NSInteger)conversationIdentifier {
- return reinterpret_cast<NSInteger>(self);
-}
-
-// Each RenderWidgetHostViewCocoa has its own input context, but we return
-// nil when the caret is in non-editable content or password box to avoid
-// making input methods do their work.
-- (NSTextInputContext *)inputContext {
- switch (renderWidgetHostView_->GetTextInputType()) {
- case ui::TEXT_INPUT_TYPE_NONE:
- case ui::TEXT_INPUT_TYPE_PASSWORD:
- return nil;
- default:
- return [super inputContext];
- }
+void RenderWidgetHostViewMac::OnNSViewSyncGetTextInputType(
+ ui::TextInputType* text_input_type) {
+ *text_input_type = GetTextInputType();
}
-- (BOOL)hasMarkedText {
- // An input method calls this function to figure out whether or not an
- // application is really composing a text. If it is composing, it calls
- // the markedRange method, and maybe calls the setMarkedText method.
- // It seems an input method usually calls this function when it is about to
- // cancel an ongoing composition. If an application has a non-empty marked
- // range, it calls the setMarkedText method to delete the range.
- return hasMarkedText_;
-}
-
-- (void)unmarkText {
- // Delete the composition node of the renderer and finish an ongoing
- // composition.
- // It seems an input method calls the setMarkedText method and set an empty
- // text when it cancels an ongoing composition, i.e. I have never seen an
- // input method calls this method.
- hasMarkedText_ = NO;
- markedText_.clear();
- markedTextSelectedRange_ = NSMakeRange(NSNotFound, 0);
- ime_text_spans_.clear();
-
- // If we are handling a key down event, then FinishComposingText() will be
- // called in keyEvent: method.
- if (!handlingKeyDown_) {
- if (renderWidgetHostView_->GetActiveWidget()) {
- renderWidgetHostView_->GetActiveWidget()->ImeFinishComposingText(false);
- }
- } else {
- unmarkTextCalled_ = YES;
- }
-}
+void RenderWidgetHostViewMac::OnNSViewSyncGetCharacterIndexAtPoint(
+ const gfx::PointF& root_point,
+ uint32_t* index) {
+ *index = UINT32_MAX;
-- (void)setMarkedText:(id)string selectedRange:(NSRange)newSelRange
- replacementRange:(NSRange)replacementRange {
- // An input method updates the composition string.
- // We send the given text and range to the renderer so it can update the
- // composition node of WebKit.
- // TODO(suzhe): It's hard for us to support replacementRange without accessing
- // the full web content.
- BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
- NSString* im_text = isAttributedString ? [string string] : string;
- int length = [im_text length];
-
- // |markedRange_| will get set on a callback from ImeSetComposition().
- markedTextSelectedRange_ = newSelRange;
- markedText_ = base::SysNSStringToUTF16(im_text);
- hasMarkedText_ = (length > 0);
-
- ime_text_spans_.clear();
- if (isAttributedString) {
- ExtractUnderlines(string, &ime_text_spans_);
- } else {
- // Use a thin black underline by default.
- ime_text_spans_.push_back(
- ui::ImeTextSpan(ui::ImeTextSpan::Type::kComposition, 0, length,
- SK_ColorBLACK, false, SK_ColorTRANSPARENT));
- }
-
- // If we are handling a key down event, then SetComposition() will be
- // called in keyEvent: method.
- // Input methods of Mac use setMarkedText calls with an empty text to cancel
- // an ongoing composition. So, we should check whether or not the given text
- // is empty to update the input method state. (Our input method backend
- // automatically cancels an ongoing composition when we send an empty text.
- // So, it is OK to send an empty text to the renderer.)
- if (handlingKeyDown_) {
- setMarkedTextReplacementRange_ = gfx::Range(replacementRange);
- } else {
- if (renderWidgetHostView_->GetActiveWidget()) {
- renderWidgetHostView_->GetActiveWidget()->ImeSetComposition(
- markedText_, ime_text_spans_, gfx::Range(replacementRange),
- newSelRange.location, NSMaxRange(newSelRange));
- }
- }
-}
+ if (!host() || !host()->delegate() ||
+ !host()->delegate()->GetInputEventRouter())
+ return;
-- (void)doCommandBySelector:(SEL)selector {
- // An input method calls this function to dispatch an editing command to be
- // handled by this view.
- if (selector == @selector(noop:))
+ gfx::PointF transformed_point;
+ RenderWidgetHostImpl* widget_host =
+ host()->delegate()->GetInputEventRouter()->GetRenderWidgetHostAtPoint(
+ this, root_point, &transformed_point);
+ if (!widget_host)
return;
- std::string command(
- [RenderWidgetHostViewMacEditCommandHelper::
- CommandNameForSelector(selector) UTF8String]);
-
- // If this method is called when handling a key down event, then we need to
- // handle the command in the key event handler. Otherwise we can just handle
- // it here.
- if (handlingKeyDown_) {
- hasEditCommands_ = YES;
- // We ignore commands that insert characters, because this was causing
- // strange behavior (e.g. tab always inserted a tab rather than moving to
- // the next field on the page).
- if (!base::StartsWith(command, "insert",
- base::CompareCase::INSENSITIVE_ASCII))
- editCommands_.push_back(EditCommand(command, ""));
- } else {
- if (renderWidgetHostView_->render_widget_host_->delegate()) {
- renderWidgetHostView_->render_widget_host_->delegate()
- ->ExecuteEditCommand(command, base::nullopt);
- }
- }
+ *index = TextInputClientMac::GetInstance()->GetCharacterIndexAtPoint(
+ widget_host, gfx::ToFlooredPoint(transformed_point));
}
-- (void)insertText:(id)string replacementRange:(NSRange)replacementRange {
- // An input method has characters to be inserted.
- // Same as Linux, Mac calls this method not only:
- // * when an input method finishes composing text, but also;
- // * when we type an ASCII character (without using input methods).
- // When we aren't using input methods, we should send the given character as
- // a Char event so it is dispatched to an onkeypress() event handler of
- // JavaScript.
- // On the other hand, when we are using input methods, we should send the
- // given characters as an input method event and prevent the characters from
- // being dispatched to onkeypress() event handlers.
- // Text inserting might be initiated by other source instead of keyboard
- // events, such as the Characters dialog. In this case the text should be
- // sent as an input method event as well.
- // TODO(suzhe): It's hard for us to support replacementRange without accessing
- // the full web content.
- BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
- NSString* im_text = isAttributedString ? [string string] : string;
- if (handlingKeyDown_) {
- textToBeInserted_.append(base::SysNSStringToUTF16(im_text));
- } else {
- gfx::Range replacement_range(replacementRange);
- if (renderWidgetHostView_->GetActiveWidget()) {
- renderWidgetHostView_->GetActiveWidget()->ImeCommitText(
- base::SysNSStringToUTF16(im_text), std::vector<ui::ImeTextSpan>(),
- replacement_range, 0);
- }
+void RenderWidgetHostViewMac::OnNSViewSyncGetFirstRectForRange(
+ const gfx::Range& requested_range,
+ gfx::Rect* rect,
+ gfx::Range* actual_range,
+ bool* success) {
+ if (!GetFocusedWidget()) {
+ *success = false;
+ return;
+ }
+ *success = true;
+ if (!GetCachedFirstRectForCharacterRange(requested_range, rect,
+ actual_range)) {
+ *rect = TextInputClientMac::GetInstance()->GetFirstRectForRange(
+ GetFocusedWidget(), requested_range);
+ // TODO(thakis): Pipe |actualRange| through TextInputClientMac machinery.
+ *actual_range = requested_range;
}
-
- // Inserting text will delete all marked text automatically.
- hasMarkedText_ = NO;
-}
-
-- (void)insertText:(id)string {
- [self insertText:string replacementRange:NSMakeRange(NSNotFound, 0)];
}
-- (void)viewDidMoveToWindow {
- // This can be called very late during shutdown, so it needs to be guarded by
- // a check that DestroyCompositorForShutdown has not yet been called.
- // https://crbug.com/805726
- if (!renderWidgetHostView_->browser_compositor_)
- return;
-
- if ([self window])
- [self updateScreenProperties];
- renderWidgetHostView_->browser_compositor_->SetNSViewAttachedToWindow(
- [self window]);
-
- // If we switch windows (or are removed from the view hierarchy), cancel any
- // open mouse-downs.
- if (hasOpenMouseDown_) {
- WebMouseEvent event(WebInputEvent::kMouseUp, WebInputEvent::kNoModifiers,
- ui::EventTimeStampToSeconds(ui::EventTimeForNow()));
- event.button = WebMouseEvent::Button::kLeft;
- renderWidgetHostView_->ForwardMouseEvent(event);
-
- hasOpenMouseDown_ = NO;
+void RenderWidgetHostViewMac::OnNSViewExecuteEditCommand(
+ const std::string& command) {
+ if (host()->delegate()) {
+ host()->delegate()->ExecuteEditCommand(command, base::nullopt);
}
}
-- (void)undo:(id)sender {
- WebContents* web_contents = renderWidgetHostView_->GetWebContents();
+void RenderWidgetHostViewMac::OnNSViewUndo() {
+ WebContents* web_contents = GetWebContents();
if (web_contents)
web_contents->Undo();
}
-- (void)redo:(id)sender {
- WebContents* web_contents = renderWidgetHostView_->GetWebContents();
+void RenderWidgetHostViewMac::OnNSViewRedo() {
+ WebContents* web_contents = GetWebContents();
if (web_contents)
web_contents->Redo();
}
-- (void)cut:(id)sender {
- if (auto* delegate =
- renderWidgetHostView_->GetFocusedRenderWidgetHostDelegate()) {
+void RenderWidgetHostViewMac::OnNSViewCut() {
+ if (auto* delegate = GetFocusedRenderWidgetHostDelegate()) {
delegate->Cut();
}
}
-- (void)copy:(id)sender {
- if (auto* delegate =
- renderWidgetHostView_->GetFocusedRenderWidgetHostDelegate()) {
+void RenderWidgetHostViewMac::OnNSViewCopy() {
+ if (auto* delegate = GetFocusedRenderWidgetHostDelegate()) {
delegate->Copy();
}
}
-- (void)copyToFindPboard:(id)sender {
- WebContents* web_contents = renderWidgetHostView_->GetWebContents();
+void RenderWidgetHostViewMac::OnNSViewCopyToFindPboard() {
+ WebContents* web_contents = GetWebContents();
if (web_contents)
web_contents->CopyToFindPboard();
}
-- (void)paste:(id)sender {
- if (auto* delegate =
- renderWidgetHostView_->GetFocusedRenderWidgetHostDelegate()) {
+void RenderWidgetHostViewMac::OnNSViewPaste() {
+ if (auto* delegate = GetFocusedRenderWidgetHostDelegate()) {
delegate->Paste();
}
}
-- (void)pasteAndMatchStyle:(id)sender {
- WebContents* web_contents = renderWidgetHostView_->GetWebContents();
+void RenderWidgetHostViewMac::OnNSViewPasteAndMatchStyle() {
+ WebContents* web_contents = GetWebContents();
if (web_contents)
web_contents->PasteAndMatchStyle();
}
-- (void)selectAll:(id)sender {
- // editCommand_helper_ adds implementations for most NSResponder methods
- // dynamically. But the renderer side only sends selection results back to
- // the browser if they were triggered by a keyboard event or went through
- // one of the Select methods on RWH. Since selectAll: is called from the
- // menu handler, neither is true.
- // Explicitly call SelectAll() here to make sure the renderer returns
- // selection results.
- if (auto* delegate =
- renderWidgetHostView_->GetFocusedRenderWidgetHostDelegate()) {
+void RenderWidgetHostViewMac::OnNSViewSelectAll() {
+ if (auto* delegate = GetFocusedRenderWidgetHostDelegate()) {
delegate->SelectAll();
}
}
-- (void)startSpeaking:(id)sender {
- GetRenderWidgetHostViewToUse(renderWidgetHostView_.get())->SpeakSelection();
-}
-
-- (void)stopSpeaking:(id)sender {
- GetRenderWidgetHostViewToUse(renderWidgetHostView_.get())->StopSpeaking();
+void RenderWidgetHostViewMac::OnNSViewSyncIsSpeaking(bool* is_speaking) {
+ *is_speaking = ui::TextServicesContextMenu::IsSpeaking();
}
-- (void)cancelComposition {
- if (!hasMarkedText_)
- return;
-
- NSTextInputContext* inputContext = [self inputContext];
- [inputContext discardMarkedText];
-
- hasMarkedText_ = NO;
- // Should not call [self unmarkText] here, because it'll send unnecessary
- // cancel composition IPC message to the renderer.
-}
-
-- (void)finishComposingText {
- if (!hasMarkedText_)
- return;
-
- if (renderWidgetHostView_->GetActiveWidget()) {
- renderWidgetHostView_->GetActiveWidget()->ImeFinishComposingText(false);
- }
-
- [self cancelComposition];
-}
-
-// Overriding a NSResponder method to support application services.
-
-- (id)validRequestorForSendType:(NSString*)sendType
- returnType:(NSString*)returnType {
- id requestor = nil;
- BOOL sendTypeIsString = [sendType isEqual:NSStringPboardType];
- BOOL returnTypeIsString = [returnType isEqual:NSStringPboardType];
- const content::TextInputManager::TextSelection* selection =
- renderWidgetHostView_->GetTextSelection();
- BOOL hasText = selection && !selection->selected_text().empty();
- BOOL takesText =
- renderWidgetHostView_->GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE;
-
- if (sendTypeIsString && hasText && !returnType) {
- requestor = self;
- } else if (!sendType && returnTypeIsString && takesText) {
- requestor = self;
- } else if (sendTypeIsString && returnTypeIsString && hasText && takesText) {
- requestor = self;
- } else {
- requestor = [super validRequestorForSendType:sendType
- returnType:returnType];
+void RenderWidgetHostViewMac::OnNSViewSpeakSelection() {
+ RenderWidgetHostView* target = this;
+ WebContents* web_contents = GetWebContents();
+ if (web_contents) {
+ content::BrowserPluginGuestManager* guest_manager =
+ web_contents->GetBrowserContext()->GetGuestManager();
+ if (guest_manager) {
+ content::WebContents* guest =
+ guest_manager->GetFullPageGuest(web_contents);
+ if (guest) {
+ target = guest->GetRenderWidgetHostView();
+ }
+ }
}
- return requestor;
+ target->SpeakSelection();
}
-- (void)updateCursor:(NSCursor*)cursor {
- if (currentCursor_ == cursor)
- return;
-
- currentCursor_.reset([cursor retain]);
- [[self window] invalidateCursorRectsForView:self];
-
- // NSWindow's invalidateCursorRectsForView: resets cursor rects but does not
- // update the cursor instantly. The cursor is updated when the mouse moves.
- // Update the cursor by setting the current cursor if not hidden.
- WebContents* web_contents = renderWidgetHostView_->GetWebContents();
- if (!cursorHidden_ && web_contents && !web_contents->IsShowingContextMenu())
- [currentCursor_ set];
-}
-
-- (void)popupWindowWillClose:(NSNotification *)notification {
- renderWidgetHostView_->KillSelf();
+void RenderWidgetHostViewMac::OnNSViewStopSpeaking() {
+ ui::TextServicesContextMenu::StopSpeaking();
}
-@end
-
-//
-// Supporting application services
-//
-@implementation RenderWidgetHostViewCocoa(NSServicesRequests)
-
-- (BOOL)writeSelectionToPasteboard:(NSPasteboard*)pboard
- types:(NSArray*)types {
- const content::TextInputManager::TextSelection* selection =
- renderWidgetHostView_->GetTextSelection();
- if (!selection || selection->selected_text().empty() ||
- ![types containsObject:NSStringPboardType]) {
- return NO;
+void RenderWidgetHostViewMac::OnGotStringForDictionaryOverlay(
+ int32_t target_widget_process_id,
+ int32_t target_widget_routing_id,
+ const mac::AttributedStringCoder::EncodedString& encoded_string,
+ gfx::Point baseline_point) {
+ if (encoded_string.string().empty()) {
+ // The PDF plugin does not support getting the attributed string at point.
+ // Until it does, use NSPerformService(), which opens Dictionary.app.
+ // TODO(shuchen): Support GetStringAtPoint() & GetStringFromRange() for PDF.
+ // https://crbug.com/152438
+ // This often just opens a blank dictionary, not the definition of |string|.
+ // https://crbug.com/830047
+ // This path will be taken, inappropriately, when a lookup gesture was
+ // performed at a location that doesn't have text, but some text is
+ // selected.
+ // https://crbug.com/830906
+ if (auto* selection = GetTextSelection()) {
+ const base::string16& selected_text = selection->selected_text();
+ NSString* ns_selected_text = base::SysUTF16ToNSString(selected_text);
+ if ([ns_selected_text length] == 0)
+ return;
+ scoped_refptr<ui::UniquePasteboard> pasteboard = new ui::UniquePasteboard;
+ NSArray* types = [NSArray arrayWithObject:NSStringPboardType];
+ [pasteboard->get() declareTypes:types owner:nil];
+ if ([pasteboard->get() setString:ns_selected_text
+ forType:NSStringPboardType]) {
+ NSPerformService(@"Look Up in Dictionary", pasteboard->get());
+ }
+ }
+ } else {
+ // By the time we get here |widget_host| might have been destroyed.
+ // https://crbug.com/737032
+ auto* widget_host = content::RenderWidgetHost::FromID(
+ target_widget_process_id, target_widget_routing_id);
+ if (widget_host) {
+ if (auto* rwhv = widget_host->GetView())
+ baseline_point = rwhv->TransformPointToRootCoordSpace(baseline_point);
+ }
+ ns_view_bridge_->ShowDictionaryOverlay(encoded_string, baseline_point);
}
-
- base::scoped_nsobject<NSString> text([[NSString alloc]
- initWithUTF8String:base::UTF16ToUTF8(selection->selected_text())
- .c_str()]);
- NSArray* toDeclare = [NSArray arrayWithObject:NSStringPboardType];
- [pboard declareTypes:toDeclare owner:nil];
- return [pboard setString:text forType:NSStringPboardType];
-}
-
-- (BOOL)readSelectionFromPasteboard:(NSPasteboard*)pboard {
- NSString *string = [pboard stringForType:NSStringPboardType];
- if (!string) return NO;
-
- // If the user is currently using an IME, confirm the IME input,
- // and then insert the text from the service, the same as TextEdit and Safari.
- [self finishComposingText];
- [self insertText:string];
- return YES;
}
-// "-webkit-app-region: drag | no-drag" is implemented on Mac by excluding
-// regions that are not draggable. (See ControlRegionView in
-// native_app_window_cocoa.mm). This requires the render host view to be
-// draggable by default.
-- (BOOL)mouseDownCanMoveWindow {
- return YES;
+Class GetRenderWidgetHostViewCocoaClassForTesting() {
+ return [RenderWidgetHostViewCocoa class];
}
-@end
+} // namespace content
diff --git a/chromium/content/browser/renderer_host/render_widget_host_view_mac_browsertest.mm b/chromium/content/browser/renderer_host/render_widget_host_view_mac_browsertest.mm
new file mode 100644
index 00000000000..a3a0186754d
--- /dev/null
+++ b/chromium/content/browser/renderer_host/render_widget_host_view_mac_browsertest.mm
@@ -0,0 +1,66 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/renderer_host/render_widget_host_view_mac.h"
+
+#include "base/bind.h"
+#include "base/macros.h"
+#include "base/run_loop.h"
+#include "base/strings/string16.h"
+#include "base/strings/utf_string_conversions.h"
+#include "content/public/browser/render_frame_host.h"
+#include "content/public/browser/web_contents.h"
+#include "content/public/test/content_browser_test.h"
+#include "content/public/test/content_browser_test_utils.h"
+#include "content/shell/browser/shell.h"
+
+namespace content {
+
+namespace {
+
+class TextCallbackWaiter {
+ public:
+ TextCallbackWaiter() {}
+
+ void Wait() { run_loop_.Run(); }
+
+ const base::string16& text() const { return text_; }
+
+ void GetText(const base::string16& text) {
+ text_ = text;
+ run_loop_.Quit();
+ }
+
+ private:
+ base::string16 text_;
+ base::RunLoop run_loop_;
+
+ DISALLOW_COPY_AND_ASSIGN(TextCallbackWaiter);
+};
+
+} // namespace
+
+class RenderWidgetHostViewMacTest : public ContentBrowserTest {};
+
+IN_PROC_BROWSER_TEST_F(RenderWidgetHostViewMacTest, GetPageTextForSpeech) {
+ GURL url(
+ "data:text/html,<span>Hello</span>"
+ "<span style='display:none'>Goodbye</span>"
+ "<span>World</span>");
+ EXPECT_TRUE(NavigateToURL(shell(), url));
+
+ RenderWidgetHostView* rwhv =
+ shell()->web_contents()->GetMainFrame()->GetView();
+ RenderWidgetHostViewMac* rwhv_mac =
+ static_cast<RenderWidgetHostViewMac*>(rwhv);
+
+ TextCallbackWaiter waiter;
+ rwhv_mac->GetPageTextForSpeech(
+ base::BindOnce(&TextCallbackWaiter::GetText, base::Unretained(&waiter)));
+ waiter.Wait();
+
+ EXPECT_EQ(base::ASCIIToUTF16("Hello\nWorld"), waiter.text());
+}
+
+} // namespace content
diff --git a/chromium/content/browser/renderer_host/render_widget_host_view_mac_dictionary_helper.h b/chromium/content/browser/renderer_host/render_widget_host_view_mac_dictionary_helper.h
deleted file mode 100644
index 71deadbfcb5..00000000000
--- a/chromium/content/browser/renderer_host/render_widget_host_view_mac_dictionary_helper.h
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_VIEW_MAC_DICTIONARY_HELPER_H_
-#define CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_VIEW_MAC_DICTIONARY_HELPER_H_
-
-#include "base/macros.h"
-#include "ui/gfx/geometry/vector2d.h"
-
-namespace content {
-
-class RenderWidgetHostView;
-class RenderWidgetHostViewMac;
-
-// A helper class to bring up definition of word for a RWHV.
-//
-// This is triggered by "Lookup in Dictionary" context menu item.
-// Either uses Dictionary.app or a light-weight dictionary panel, based on
-// system settings.
-class RenderWidgetHostViewMacDictionaryHelper {
- public:
- explicit RenderWidgetHostViewMacDictionaryHelper(RenderWidgetHostView* view);
-
- // Overrides the view to use to bring up dictionary panel.
- // This |target_view| can be different from |view_|, |view_| is used to get
- // the current selection value where |target_view| is used to bring up the
- // cocoa dictionary panel.
- void SetTargetView(RenderWidgetHostView* target_view);
- void set_offset(const gfx::Vector2d& offset) { offset_ = offset; }
-
- // Brings up either Dictionary.app or a light-weight dictionary panel,
- // depending on system settings.
- void ShowDefinitionForSelection();
-
- private:
- // This class shows definition for this view.
- RenderWidgetHostViewMac* view_;
- // This view is use to bring up the dictionary panel. Generally this is the
- // same as |view_|. One can override the view to use via SetTargetView().
- RenderWidgetHostViewMac* target_view_;
- // The extra offset to use while positioning the dicitonary panel.
- gfx::Vector2d offset_;
-
- DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostViewMacDictionaryHelper);
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_VIEW_MAC_DICTIONARY_HELPER_H_
diff --git a/chromium/content/browser/renderer_host/render_widget_host_view_mac_dictionary_helper.mm b/chromium/content/browser/renderer_host/render_widget_host_view_mac_dictionary_helper.mm
deleted file mode 100644
index 4e5849d3661..00000000000
--- a/chromium/content/browser/renderer_host/render_widget_host_view_mac_dictionary_helper.mm
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#import "content/browser/renderer_host/render_widget_host_view_mac_dictionary_helper.h"
-
-#include "base/strings/sys_string_conversions.h"
-#import "content/browser/renderer_host/render_widget_host_view_mac.h"
-
-namespace content {
-
-RenderWidgetHostViewMacDictionaryHelper::
- RenderWidgetHostViewMacDictionaryHelper(RenderWidgetHostView* view)
- : view_(static_cast<RenderWidgetHostViewMac*>(view)),
- target_view_(static_cast<RenderWidgetHostViewMac*>(view)) {
-}
-
-void RenderWidgetHostViewMacDictionaryHelper::SetTargetView(
- RenderWidgetHostView* target_view) {
- target_view_ = static_cast<RenderWidgetHostViewMac*>(target_view);
-}
-
-void RenderWidgetHostViewMacDictionaryHelper::ShowDefinitionForSelection() {
- NSRange selection_range = [view_->cocoa_view() selectedRange];
- NSView* view = target_view_->cocoa_view();
- [view_->cocoa_view() showLookUpDictionaryOverlayFromRange:selection_range
- targetView:view];
-}
-
-} // namespace content
diff --git a/chromium/content/browser/renderer_host/render_widget_host_view_mac_editcommand_helper.h b/chromium/content/browser/renderer_host/render_widget_host_view_mac_editcommand_helper.h
index bf9a5c8bbe8..99b67518acd 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_view_mac_editcommand_helper.h
+++ b/chromium/content/browser/renderer_host/render_widget_host_view_mac_editcommand_helper.h
@@ -10,6 +10,7 @@
#include "base/containers/hash_tables.h"
#include "base/gtest_prod_util.h"
#include "base/macros.h"
+#import "content/browser/renderer_host/render_widget_host_view_cocoa.h"
#include "content/browser/renderer_host/render_widget_host_view_mac.h"
namespace content {
@@ -43,7 +44,7 @@ class CONTENT_EXPORT RenderWidgetHostViewMacEditCommandHelper {
// Each selector is connected to a single c method which forwards the message
// to WebCore's ExecuteEditCommand() function.
// This method is idempotent.
- // The class passed in must conform to the RenderWidgetHostViewMacOwner
+ // The class passed in must conform to the RenderWidgetHostNSViewClientOwner
// protocol.
void AddEditingSelectorsToClass(Class klass);
@@ -52,7 +53,7 @@ class CONTENT_EXPORT RenderWidgetHostViewMacEditCommandHelper {
// owner - An object we can retrieve a RenderWidgetHostViewMac from to
// determine the command states.
bool IsMenuItemEnabled(SEL item_action,
- id<RenderWidgetHostViewMacOwner> owner);
+ id<RenderWidgetHostNSViewClientOwner> owner);
// Converts an editing selector into a command name that can be sent to
// webkit.
diff --git a/chromium/content/browser/renderer_host/render_widget_host_view_mac_editcommand_helper.mm b/chromium/content/browser/renderer_host/render_widget_host_view_mac_editcommand_helper.mm
index 02b3c10a70d..f4e2439c495 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_view_mac_editcommand_helper.mm
+++ b/chromium/content/browser/renderer_host/render_widget_host_view_mac_editcommand_helper.mm
@@ -110,14 +110,13 @@ const char* const kEditCommands[] = {
"yankAndSelect"
};
-
// This function is installed via the objc runtime as the implementation of all
// the various editing selectors.
// The objc runtime hookup occurs in
// RenderWidgetHostViewMacEditCommandHelper::AddEditingSelectorsToClass().
//
// self - the object we're attached to; it must implement the
-// RenderWidgetHostViewMacOwner protocol.
+// RenderWidgetHostNSViewClientOwner protocol.
// _cmd - the selector that fired.
// sender - the id of the object that sent the message.
//
@@ -130,7 +129,8 @@ const char* const kEditCommands[] = {
// The WebFrame is in the Chrome glue layer and forwards the message to WebCore.
void EditCommandImp(id self, SEL _cmd, id sender) {
// Make sure |self| is the right type.
- DCHECK([self conformsToProtocol:@protocol(RenderWidgetHostViewMacOwner)]);
+ DCHECK(
+ [self conformsToProtocol:@protocol(RenderWidgetHostNSViewClientOwner)]);
// SEL -> command name string.
NSString* command_name_ns =
@@ -138,14 +138,10 @@ void EditCommandImp(id self, SEL _cmd, id sender) {
std::string command([command_name_ns UTF8String]);
// Forward the edit command string down the pipeline.
- RenderWidgetHostViewMac* rwhv = [(id<RenderWidgetHostViewMacOwner>)self
- renderWidgetHostViewMac];
- DCHECK(rwhv);
-
- RenderWidgetHostDelegate* host_delegate =
- RenderWidgetHostImpl::From(rwhv->GetRenderWidgetHost())->delegate();
- if (host_delegate)
- host_delegate->ExecuteEditCommand(command, base::nullopt);
+ RenderWidgetHostNSViewClient* client = [(
+ id<RenderWidgetHostNSViewClientOwner>)self renderWidgetHostNSViewClient];
+ DCHECK(client);
+ client->OnNSViewExecuteEditCommand(command);
}
} // namespace
@@ -212,7 +208,7 @@ void RenderWidgetHostViewMacEditCommandHelper::AddEditingSelectorsToClass(
bool RenderWidgetHostViewMacEditCommandHelper::IsMenuItemEnabled(
SEL item_action,
- id<RenderWidgetHostViewMacOwner> owner) {
+ id<RenderWidgetHostNSViewClientOwner> owner) {
const char* selector_name = sel_getName(item_action);
// TODO(jeremy): The final form of this function will check state
// associated with the Browser.
diff --git a/chromium/content/browser/renderer_host/render_widget_host_view_mac_editcommand_helper_unittest.mm b/chromium/content/browser/renderer_host/render_widget_host_view_mac_editcommand_helper_unittest.mm
index ca82d54938e..701da35330e 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_view_mac_editcommand_helper_unittest.mm
+++ b/chromium/content/browser/renderer_host/render_widget_host_view_mac_editcommand_helper_unittest.mm
@@ -10,7 +10,6 @@
#include "base/mac/scoped_nsautorelease_pool.h"
#include "base/message_loop/message_loop.h"
-#include "base/test/scoped_task_environment.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/browser/compositor/test/test_image_transport_factory.h"
#include "content/browser/gpu/compositor_util.h"
@@ -19,6 +18,7 @@
#include "content/common/input_messages.h"
#include "content/public/test/mock_render_process_host.h"
#include "content/public/test/test_browser_context.h"
+#include "content/public/test/test_browser_thread_bundle.h"
#include "content/test/mock_widget_impl.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -36,15 +36,15 @@ using content::RenderWidgetHostViewMac;
@end
// Class that owns a RenderWidgetHostViewMac.
-@interface RenderWidgetHostViewMacOwner :
- NSObject<RenderWidgetHostViewMacOwner> {
+@interface RenderWidgetHostNSViewClientOwner
+ : NSObject<RenderWidgetHostNSViewClientOwner> {
RenderWidgetHostViewMac* rwhvm_;
}
- (id)initWithRenderWidgetHostViewMac:(RenderWidgetHostViewMac*)rwhvm;
@end
-@implementation RenderWidgetHostViewMacOwner
+@implementation RenderWidgetHostNSViewClientOwner
- (id)initWithRenderWidgetHostViewMac:(RenderWidgetHostViewMac*)rwhvm {
if ((self = [super init])) {
@@ -53,7 +53,7 @@ using content::RenderWidgetHostViewMac;
return self;
}
-- (RenderWidgetHostViewMac*)renderWidgetHostViewMac {
+- (content::RenderWidgetHostNSViewClient*)renderWidgetHostNSViewClient {
return rwhvm_;
}
@@ -117,8 +117,10 @@ class RenderWidgetHostViewMacEditCommandHelperWithTaskEnvTest
void TearDown() override { ImageTransportFactory::Terminate(); }
private:
- // This has a MessageLoop for ImageTransportFactory.
- base::test::ScopedTaskEnvironment scoped_task_environment_;
+ // This has a MessageLoop for ImageTransportFactory and enables
+ // BrowserThread::UI for RecyclableCompositorMac used by
+ // RenderWidgetHostViewMac.
+ content::TestBrowserThreadBundle thread_bundle_;
};
} // namespace
@@ -158,8 +160,8 @@ TEST_F(RenderWidgetHostViewMacEditCommandHelperWithTaskEnvTest,
RenderWidgetHostViewMacEditCommandHelper helper;
NSArray* edit_command_strings = helper.GetEditSelectorNames();
- RenderWidgetHostViewMacOwner* rwhwvm_owner =
- [[[RenderWidgetHostViewMacOwner alloc]
+ RenderWidgetHostNSViewClientOwner* rwhwvm_owner =
+ [[[RenderWidgetHostNSViewClientOwner alloc]
initWithRenderWidgetHostViewMac:rwhv_mac] autorelease];
helper.AddEditingSelectorsToClass([rwhwvm_owner class]);
@@ -213,8 +215,8 @@ TEST_F(RenderWidgetHostViewMacEditCommandHelperTest,
// Test RenderWidgetHostViewMacEditCommandHelper::IsMenuItemEnabled.
TEST_F(RenderWidgetHostViewMacEditCommandHelperTest, TestMenuItemEnabling) {
RenderWidgetHostViewMacEditCommandHelper helper;
- RenderWidgetHostViewMacOwner* rwhvm_owner =
- [[[RenderWidgetHostViewMacOwner alloc] init] autorelease];
+ RenderWidgetHostNSViewClientOwner* rwhvm_owner =
+ [[[RenderWidgetHostNSViewClientOwner alloc] init] autorelease];
// The select all menu should always be enabled.
SEL select_all = NSSelectorFromString(@"selectAll:");
diff --git a/chromium/content/browser/renderer_host/render_widget_host_view_mac_unittest.mm b/chromium/content/browser/renderer_host/render_widget_host_view_mac_unittest.mm
index 2ef69acae40..84029bb39e9 100644
--- a/chromium/content/browser/renderer_host/render_widget_host_view_mac_unittest.mm
+++ b/chromium/content/browser/renderer_host/render_widget_host_view_mac_unittest.mm
@@ -21,14 +21,15 @@
#include "base/test/scoped_feature_list.h"
#include "base/test/simple_test_tick_clock.h"
#include "base/threading/thread_task_runner_handle.h"
-#include "content/browser/browser_thread_impl.h"
#include "content/browser/frame_host/render_widget_host_view_guest.h"
#include "content/browser/gpu/compositor_util.h"
#include "content/browser/renderer_host/render_widget_host_delegate.h"
+#import "content/browser/renderer_host/render_widget_host_view_cocoa.h"
#include "content/browser/renderer_host/text_input_manager.h"
#include "content/common/input_messages.h"
#include "content/common/text_input_state.h"
#include "content/common/view_messages.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_widget_host_view_mac_delegate.h"
#include "content/public/common/content_features.h"
@@ -46,6 +47,7 @@
#include "testing/gtest_mac.h"
#import "third_party/ocmock/OCMock/OCMock.h"
#import "third_party/ocmock/ocmock_extensions.h"
+#include "ui/base/cocoa/secure_password_input.h"
#import "ui/base/test/cocoa_helper.h"
#import "ui/base/test/scoped_fake_nswindow_focus.h"
#include "ui/events/base_event_utils.h"
@@ -366,6 +368,9 @@ class RenderWidgetHostViewMacTest : public RenderViewHostImplTestHarness {
RenderViewHostImplTestHarness::SetUp();
gpu::ImageTransportSurface::SetAllowOSMesaForTesting(true);
+ browser_context_ = std::make_unique<TestBrowserContext>();
+ process_host_ =
+ std::make_unique<MockRenderProcessHost>(browser_context_.get());
process_host_->Init();
host_ = MockRenderWidgetHostImpl::Create(&delegate_, process_host_.get(),
process_host_->GetNextRoutingID());
@@ -380,6 +385,7 @@ class RenderWidgetHostViewMacTest : public RenderViewHostImplTestHarness {
rwhv_cocoa_.reset();
host_->ShutdownAndDestroyWidget(true);
process_host_.reset();
+ browser_context_.reset();
RecycleAndWait();
RenderViewHostImplTestHarness::TearDown();
}
@@ -432,9 +438,8 @@ class RenderWidgetHostViewMacTest : public RenderViewHostImplTestHarness {
MockRenderWidgetHostDelegate delegate_;
- TestBrowserContext browser_context_;
- std::unique_ptr<MockRenderProcessHost> process_host_ =
- std::make_unique<MockRenderProcessHost>(&browser_context_);
+ std::unique_ptr<TestBrowserContext> browser_context_;
+ std::unique_ptr<MockRenderProcessHost> process_host_;
MockRenderWidgetHostImpl* host_ = nullptr;
RenderWidgetHostViewMac* rwhv_mac_ = nullptr;
base::scoped_nsobject<RenderWidgetHostViewCocoa> rwhv_cocoa_;
@@ -486,78 +491,6 @@ TEST_F(RenderWidgetHostViewMacTest, NSTextInputClientConformance) {
EXPECT_EQ(0u, actualRange.length);
}
-TEST_F(RenderWidgetHostViewMacTest, Fullscreen) {
- rwhv_mac_->InitAsFullscreen(nullptr);
- EXPECT_TRUE(rwhv_mac_->pepper_fullscreen_window());
-
- // Break the reference cycle caused by pepper_fullscreen_window() without
- // an <esc> event. See comment in
- // release_pepper_fullscreen_window_for_testing().
- rwhv_mac_->release_pepper_fullscreen_window_for_testing();
-}
-
-// Verify that escape key down in fullscreen mode suppressed the keyup event on
-// the parent.
-TEST_F(RenderWidgetHostViewMacTest, FullscreenCloseOnEscape) {
- // Use our own RWH since we need to destroy it.
- MockRenderWidgetHostDelegate delegate;
- int32_t routing_id = process_host_->GetNextRoutingID();
- // Owned by its |cocoa_view()|.
- MockRenderWidgetHostImpl* rwh = MockRenderWidgetHostImpl::Create(
- &delegate, process_host_.get(), routing_id);
- RenderWidgetHostViewMac* view = new RenderWidgetHostViewMac(rwh, false);
-
- view->InitAsFullscreen(rwhv_mac_);
-
- WindowedNotificationObserver observer(
- NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
- Source<RenderWidgetHost>(rwh));
- EXPECT_FALSE([rwhv_mac_->cocoa_view() suppressNextEscapeKeyUp]);
-
- // Escape key down. Should close window and set |suppressNextEscapeKeyUp| on
- // the parent.
- [view->cocoa_view() keyEvent:
- cocoa_test_event_utils::KeyEventWithKeyCode(53, 27, NSKeyDown, 0)];
- observer.Wait();
- EXPECT_TRUE([rwhv_mac_->cocoa_view() suppressNextEscapeKeyUp]);
-
- // Escape key up on the parent should clear |suppressNextEscapeKeyUp|.
- [rwhv_mac_->cocoa_view() keyEvent:
- cocoa_test_event_utils::KeyEventWithKeyCode(53, 27, NSKeyUp, 0)];
- EXPECT_FALSE([rwhv_mac_->cocoa_view() suppressNextEscapeKeyUp]);
-}
-
-// Test that command accelerators which destroy the fullscreen window
-// don't crash when forwarded via the window's responder machinery.
-TEST_F(RenderWidgetHostViewMacTest, AcceleratorDestroy) {
- // Use our own RWH since we need to destroy it.
- MockRenderWidgetHostDelegate delegate;
- TestBrowserContext browser_context;
- int32_t routing_id = process_host_->GetNextRoutingID();
- // Owned by its |cocoa_view()|.
- MockRenderWidgetHostImpl* rwh = MockRenderWidgetHostImpl::Create(
- &delegate, process_host_.get(), routing_id);
- RenderWidgetHostViewMac* view = new RenderWidgetHostViewMac(rwh, false);
-
- view->InitAsFullscreen(rwhv_mac_);
-
- WindowedNotificationObserver observer(
- NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
- Source<RenderWidgetHost>(rwh));
-
- // Key equivalents are only sent to the renderer if the window is key.
- ui::test::ScopedFakeNSWindowFocus key_window_faker;
- [[view->cocoa_view() window] makeKeyWindow];
-
- // Command-ESC will destroy the view, while the window is still in
- // |-performKeyEquivalent:|. There are other cases where this can
- // happen, Command-ESC is the easiest to trigger.
- [[view->cocoa_view() window] performKeyEquivalent:
- cocoa_test_event_utils::KeyEventWithKeyCode(
- 53, 27, NSKeyDown, NSCommandKeyMask)];
- observer.Wait();
-}
-
// Test that NSEvent of private use character won't generate keypress event
// http://crbug.com/459089
TEST_F(RenderWidgetHostViewMacTest, FilterNonPrintableCharacter) {
@@ -614,31 +547,23 @@ TEST_F(RenderWidgetHostViewMacTest, GetFirstRectForCharacterRangeCaretCase) {
gfx::Range caret_range(0, 0);
ViewHostMsg_SelectionBounds_Params params;
- NSRect rect;
- NSRange actual_range;
+ gfx::Rect rect;
+ gfx::Range actual_range;
rwhv_mac_->SelectionChanged(kDummyString, kDummyOffset, caret_range);
params.anchor_rect = params.focus_rect = caret_rect;
params.anchor_dir = params.focus_dir = blink::kWebTextDirectionLeftToRight;
rwhv_mac_->SelectionBoundsChanged(params);
- EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
- caret_range.ToNSRange(),
- &rect,
- &actual_range));
- EXPECT_EQ(caret_rect, gfx::Rect(NSRectToCGRect(rect)));
+ EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(caret_range, &rect,
+ &actual_range));
+ EXPECT_EQ(caret_rect, rect);
EXPECT_EQ(caret_range, gfx::Range(actual_range));
EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
- gfx::Range(0, 1).ToNSRange(),
- &rect,
- &actual_range));
+ gfx::Range(0, 1), &rect, &actual_range));
EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
- gfx::Range(1, 1).ToNSRange(),
- &rect,
- &actual_range));
+ gfx::Range(1, 1), &rect, &actual_range));
EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
- gfx::Range(2, 3).ToNSRange(),
- &rect,
- &actual_range));
+ gfx::Range(2, 3), &rect, &actual_range));
// Caret moved.
caret_rect = gfx::Rect(20, 11, 0, 10);
@@ -646,25 +571,17 @@ TEST_F(RenderWidgetHostViewMacTest, GetFirstRectForCharacterRangeCaretCase) {
params.anchor_rect = params.focus_rect = caret_rect;
rwhv_mac_->SelectionChanged(kDummyString, kDummyOffset, caret_range);
rwhv_mac_->SelectionBoundsChanged(params);
- EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
- caret_range.ToNSRange(),
- &rect,
- &actual_range));
- EXPECT_EQ(caret_rect, gfx::Rect(NSRectToCGRect(rect)));
- EXPECT_EQ(caret_range, gfx::Range(actual_range));
+ EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(caret_range, &rect,
+ &actual_range));
+ EXPECT_EQ(caret_rect, rect);
+ EXPECT_EQ(caret_range, actual_range);
EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
- gfx::Range(0, 0).ToNSRange(),
- &rect,
- &actual_range));
+ gfx::Range(0, 0), &rect, &actual_range));
EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
- gfx::Range(1, 2).ToNSRange(),
- &rect,
- &actual_range));
+ gfx::Range(1, 2), &rect, &actual_range));
EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
- gfx::Range(2, 3).ToNSRange(),
- &rect,
- &actual_range));
+ gfx::Range(2, 3), &rect, &actual_range));
// No caret.
caret_range = gfx::Range(1, 2);
@@ -673,25 +590,15 @@ TEST_F(RenderWidgetHostViewMacTest, GetFirstRectForCharacterRangeCaretCase) {
params.focus_rect = gfx::Rect(30, 11, 0, 10);
rwhv_mac_->SelectionBoundsChanged(params);
EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
- gfx::Range(0, 0).ToNSRange(),
- &rect,
- &actual_range));
+ gfx::Range(0, 0), &rect, &actual_range));
EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
- gfx::Range(0, 1).ToNSRange(),
- &rect,
- &actual_range));
+ gfx::Range(0, 1), &rect, &actual_range));
EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
- gfx::Range(1, 1).ToNSRange(),
- &rect,
- &actual_range));
+ gfx::Range(1, 1), &rect, &actual_range));
EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
- gfx::Range(1, 2).ToNSRange(),
- &rect,
- &actual_range));
+ gfx::Range(1, 2), &rect, &actual_range));
EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
- gfx::Range(2, 2).ToNSRange(),
- &rect,
- &actual_range));
+ gfx::Range(2, 2), &rect, &actual_range));
}
TEST_F(RenderWidgetHostViewMacTest, UpdateCompositionSinglelineCase) {
@@ -699,41 +606,31 @@ TEST_F(RenderWidgetHostViewMacTest, UpdateCompositionSinglelineCase) {
const gfx::Point kOrigin(10, 11);
const gfx::Size kBoundsUnit(10, 20);
- NSRect rect;
+ gfx::Rect rect;
// Make sure not crashing by passing nullptr pointer instead of
// |actual_range|.
- EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
- gfx::Range(0, 0).ToNSRange(), &rect, nullptr));
+ EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(gfx::Range(0, 0),
+ &rect, nullptr));
// If there are no update from renderer, always returned caret position.
- NSRange actual_range;
+ gfx::Range actual_range;
EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
- gfx::Range(0, 0).ToNSRange(),
- &rect,
- &actual_range));
+ gfx::Range(0, 0), &rect, &actual_range));
EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
- gfx::Range(0, 1).ToNSRange(),
- &rect,
- &actual_range));
+ gfx::Range(0, 1), &rect, &actual_range));
EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
- gfx::Range(1, 0).ToNSRange(),
- &rect,
- &actual_range));
+ gfx::Range(1, 0), &rect, &actual_range));
EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
- gfx::Range(1, 1).ToNSRange(),
- &rect,
- &actual_range));
+ gfx::Range(1, 1), &rect, &actual_range));
EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
- gfx::Range(1, 2).ToNSRange(),
- &rect,
- &actual_range));
+ gfx::Range(1, 2), &rect, &actual_range));
// If the firstRectForCharacterRange is failed in renderer, empty rect vector
// is sent. Make sure this does not crash.
rwhv_mac_->ImeCompositionRangeChanged(gfx::Range(10, 12),
std::vector<gfx::Rect>());
EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
- gfx::Range(10, 11).ToNSRange(), &rect, nullptr));
+ gfx::Range(10, 11), &rect, nullptr));
const int kCompositionLength = 10;
std::vector<gfx::Rect> composition_bounds;
@@ -749,29 +646,17 @@ TEST_F(RenderWidgetHostViewMacTest, UpdateCompositionSinglelineCase) {
// Out of range requests will return caret position.
EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
- gfx::Range(0, 0).ToNSRange(),
- &rect,
- &actual_range));
+ gfx::Range(0, 0), &rect, &actual_range));
EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
- gfx::Range(1, 1).ToNSRange(),
- &rect,
- &actual_range));
+ gfx::Range(1, 1), &rect, &actual_range));
EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
- gfx::Range(1, 2).ToNSRange(),
- &rect,
- &actual_range));
+ gfx::Range(1, 2), &rect, &actual_range));
EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
- gfx::Range(2, 2).ToNSRange(),
- &rect,
- &actual_range));
+ gfx::Range(2, 2), &rect, &actual_range));
EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
- gfx::Range(13, 14).ToNSRange(),
- &rect,
- &actual_range));
+ gfx::Range(13, 14), &rect, &actual_range));
EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
- gfx::Range(14, 15).ToNSRange(),
- &rect,
- &actual_range));
+ gfx::Range(14, 15), &rect, &actual_range));
for (int i = 0; i <= kCompositionLength; ++i) {
for (int j = 0; j <= kCompositionLength - i; ++j) {
@@ -780,15 +665,14 @@ TEST_F(RenderWidgetHostViewMacTest, UpdateCompositionSinglelineCase) {
kBoundsUnit,
range,
0);
- const NSRange request_range = gfx::Range(
- kCompositionStart + range.start(),
- kCompositionStart + range.end()).ToNSRange();
+ const gfx::Range request_range = gfx::Range(
+ kCompositionStart + range.start(), kCompositionStart + range.end());
EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
request_range,
&rect,
&actual_range));
- EXPECT_EQ(gfx::Range(request_range), gfx::Range(actual_range));
- EXPECT_EQ(expected_rect, gfx::Rect(NSRectToCGRect(rect)));
+ EXPECT_EQ(request_range, actual_range);
+ EXPECT_EQ(expected_rect, rect);
// Make sure not crashing by passing nullptr pointer instead of
// |actual_range|.
@@ -802,7 +686,7 @@ TEST_F(RenderWidgetHostViewMacTest, UpdateCompositionMultilineCase) {
ActivateViewWithTextInputManager(rwhv_mac_, ui::TEXT_INPUT_TYPE_TEXT);
const gfx::Point kOrigin(10, 11);
const gfx::Size kBoundsUnit(10, 20);
- NSRect rect;
+ gfx::Rect rect;
const int kCompositionLength = 30;
std::vector<gfx::Rect> composition_bounds;
@@ -821,112 +705,76 @@ TEST_F(RenderWidgetHostViewMacTest, UpdateCompositionMultilineCase) {
// Range doesn't contain line breaking point.
gfx::Range range;
range = gfx::Range(5, 8);
- NSRange actual_range;
- EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range.ToNSRange(),
- &rect,
+ gfx::Range actual_range;
+ EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range, &rect,
&actual_range));
- EXPECT_EQ(range, gfx::Range(actual_range));
- EXPECT_EQ(
- GetExpectedRect(kOrigin, kBoundsUnit, range, 0),
- gfx::Rect(NSRectToCGRect(rect)));
+ EXPECT_EQ(range, actual_range);
+ EXPECT_EQ(GetExpectedRect(kOrigin, kBoundsUnit, range, 0), rect);
range = gfx::Range(15, 18);
- EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range.ToNSRange(),
- &rect,
+ EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range, &rect,
&actual_range));
- EXPECT_EQ(range, gfx::Range(actual_range));
- EXPECT_EQ(
- GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(5, 8), 1),
- gfx::Rect(NSRectToCGRect(rect)));
+ EXPECT_EQ(range, actual_range);
+ EXPECT_EQ(GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(5, 8), 1), rect);
range = gfx::Range(25, 28);
- EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range.ToNSRange(),
- &rect,
+ EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range, &rect,
&actual_range));
- EXPECT_EQ(range, gfx::Range(actual_range));
- EXPECT_EQ(
- GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(5, 8), 2),
- gfx::Rect(NSRectToCGRect(rect)));
+ EXPECT_EQ(range, actual_range);
+ EXPECT_EQ(GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(5, 8), 2), rect);
// Range contains line breaking point.
range = gfx::Range(8, 12);
- EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range.ToNSRange(),
- &rect,
+ EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range, &rect,
&actual_range));
- EXPECT_EQ(gfx::Range(8, 10), gfx::Range(actual_range));
- EXPECT_EQ(
- GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(8, 10), 0),
- gfx::Rect(NSRectToCGRect(rect)));
+ EXPECT_EQ(gfx::Range(8, 10), actual_range);
+ EXPECT_EQ(GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(8, 10), 0), rect);
range = gfx::Range(18, 22);
- EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range.ToNSRange(),
- &rect,
+ EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range, &rect,
&actual_range));
- EXPECT_EQ(gfx::Range(18, 20), gfx::Range(actual_range));
- EXPECT_EQ(
- GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(8, 10), 1),
- gfx::Rect(NSRectToCGRect(rect)));
+ EXPECT_EQ(gfx::Range(18, 20), actual_range);
+ EXPECT_EQ(GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(8, 10), 1), rect);
// Start point is line breaking point.
range = gfx::Range(10, 12);
- EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range.ToNSRange(),
- &rect,
+ EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range, &rect,
&actual_range));
- EXPECT_EQ(gfx::Range(10, 12), gfx::Range(actual_range));
- EXPECT_EQ(
- GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(0, 2), 1),
- gfx::Rect(NSRectToCGRect(rect)));
+ EXPECT_EQ(gfx::Range(10, 12), actual_range);
+ EXPECT_EQ(GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(0, 2), 1), rect);
range = gfx::Range(20, 22);
- EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range.ToNSRange(),
- &rect,
+ EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range, &rect,
&actual_range));
- EXPECT_EQ(gfx::Range(20, 22), gfx::Range(actual_range));
- EXPECT_EQ(
- GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(0, 2), 2),
- gfx::Rect(NSRectToCGRect(rect)));
+ EXPECT_EQ(gfx::Range(20, 22), actual_range);
+ EXPECT_EQ(GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(0, 2), 2), rect);
// End point is line breaking point.
range = gfx::Range(5, 10);
- EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range.ToNSRange(),
- &rect,
+ EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range, &rect,
&actual_range));
- EXPECT_EQ(gfx::Range(5, 10), gfx::Range(actual_range));
- EXPECT_EQ(
- GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(5, 10), 0),
- gfx::Rect(NSRectToCGRect(rect)));
+ EXPECT_EQ(gfx::Range(5, 10), actual_range);
+ EXPECT_EQ(GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(5, 10), 0), rect);
range = gfx::Range(15, 20);
- EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range.ToNSRange(),
- &rect,
+ EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range, &rect,
&actual_range));
- EXPECT_EQ(gfx::Range(15, 20), gfx::Range(actual_range));
- EXPECT_EQ(
- GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(5, 10), 1),
- gfx::Rect(NSRectToCGRect(rect)));
+ EXPECT_EQ(gfx::Range(15, 20), actual_range);
+ EXPECT_EQ(GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(5, 10), 1), rect);
// Start and end point are same line breaking point.
range = gfx::Range(10, 10);
- EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range.ToNSRange(),
- &rect,
+ EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range, &rect,
&actual_range));
- EXPECT_EQ(gfx::Range(10, 10), gfx::Range(actual_range));
- EXPECT_EQ(
- GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(0, 0), 1),
- gfx::Rect(NSRectToCGRect(rect)));
+ EXPECT_EQ(gfx::Range(10, 10), actual_range);
+ EXPECT_EQ(GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(0, 0), 1), rect);
range = gfx::Range(20, 20);
- EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range.ToNSRange(),
- &rect,
+ EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range, &rect,
&actual_range));
- EXPECT_EQ(gfx::Range(20, 20), gfx::Range(actual_range));
- EXPECT_EQ(
- GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(0, 0), 2),
- gfx::Rect(NSRectToCGRect(rect)));
+ EXPECT_EQ(gfx::Range(20, 20), actual_range);
+ EXPECT_EQ(GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(0, 0), 2), rect);
// Start and end point are different line breaking point.
range = gfx::Range(10, 20);
- EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range.ToNSRange(),
- &rect,
+ EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range, &rect,
&actual_range));
- EXPECT_EQ(gfx::Range(10, 20), gfx::Range(actual_range));
- EXPECT_EQ(
- GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(0, 10), 1),
- gfx::Rect(NSRectToCGRect(rect)));
+ EXPECT_EQ(gfx::Range(10, 20), actual_range);
+ EXPECT_EQ(GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(0, 10), 1), rect);
}
// Check that events coming from AppKit via -[NSTextInputClient
@@ -1754,14 +1602,18 @@ class InputMethodMacTest : public RenderWidgetHostViewMacTest {
void SetUp() override {
RenderWidgetHostViewMacTest::SetUp();
- process_host_ = new MockRenderProcessHost(&browser_context_);
+
+ browser_context_ = std::make_unique<TestBrowserContext>();
+ process_host_ = new MockRenderProcessHost(browser_context_.get());
process_host_->Init();
widget_ = MockRenderWidgetHostImpl::Create(
&delegate_, process_host_, process_host_->GetNextRoutingID());
view_ = new RenderWidgetHostViewMac(widget_, false);
// Initializing a child frame's view.
- child_process_host_ = new MockRenderProcessHost(&child_browser_context_);
+ child_browser_context_ = std::make_unique<TestBrowserContext>();
+ child_process_host_ =
+ new MockRenderProcessHost(child_browser_context_.get());
child_process_host_->Init();
child_widget_ = MockRenderWidgetHostImpl::Create(
&delegate_, child_process_host_,
@@ -1774,6 +1626,9 @@ class InputMethodMacTest : public RenderWidgetHostViewMacTest {
widget_->ShutdownAndDestroyWidget(true);
child_widget_->ShutdownAndDestroyWidget(true);
+ child_browser_context_.reset();
+ browser_context_.reset();
+
RenderWidgetHostViewMacTest::TearDown();
}
@@ -1804,8 +1659,8 @@ class InputMethodMacTest : public RenderWidgetHostViewMacTest {
TestRenderWidgetHostView* child_view_;
private:
- TestBrowserContext browser_context_;
- TestBrowserContext child_browser_context_;
+ std::unique_ptr<TestBrowserContext> browser_context_;
+ std::unique_ptr<TestBrowserContext> child_browser_context_;
DISALLOW_COPY_AND_ASSIGN(InputMethodMacTest);
};
@@ -1931,6 +1786,38 @@ TEST_F(InputMethodMacTest, FinishComposingText) {
EXPECT_EQ("SetComposition FinishComposingText", GetMessageNames(events));
}
+TEST_F(InputMethodMacTest, SecurePasswordInput) {
+ ASSERT_FALSE(ui::ScopedPasswordInputEnabler::IsPasswordInputEnabled());
+ ASSERT_EQ(text_input_manager(), view_->GetTextInputManager());
+
+ base::scoped_nsobject<CocoaTestHelperWindow> window(
+ [[CocoaTestHelperWindow alloc] init]);
+ [[window contentView] addSubview:view_->cocoa_view()];
+
+ // RenderWidgetHostViewMacTest.BlurAndFocusOnSetActive checks the
+ // Focus()/Blur() rules, just silence the warnings here.
+ EXPECT_CALL(*widget_, Focus()).Times(::testing::AnyNumber());
+ EXPECT_CALL(*widget_, Blur()).Times(::testing::AnyNumber());
+
+ [window makeFirstResponder:view_->cocoa_view()];
+
+ // Shouldn't enable secure input if it's not a password textfield.
+ view_->SetActive(true);
+ EXPECT_FALSE(ui::ScopedPasswordInputEnabler::IsPasswordInputEnabled());
+
+ SetTextInputType(child_view_, ui::TEXT_INPUT_TYPE_PASSWORD);
+ ASSERT_EQ(child_widget_, text_input_manager()->GetActiveWidget());
+ ASSERT_EQ(text_input_manager(), view_->GetTextInputManager());
+ ASSERT_EQ(ui::TEXT_INPUT_TYPE_PASSWORD, view_->GetTextInputType());
+
+ // Single matched calls immediately update IsPasswordInputEnabled().
+ view_->SetActive(true);
+ EXPECT_TRUE(ui::ScopedPasswordInputEnabler::IsPasswordInputEnabled());
+
+ view_->SetActive(false);
+ EXPECT_FALSE(ui::ScopedPasswordInputEnabler::IsPasswordInputEnabled());
+}
+
// This test creates a test view to mimic a child frame's view and verifies that
// calling ImeCancelComposition on either the child view or the tab's view will
// always lead to a call to cancelComposition on the cocoa view.
@@ -2047,68 +1934,6 @@ TEST_F(InputMethodMacTest, MonitorCompositionRangeForActiveWidget) {
EXPECT_FALSE(message->monitor_request());
}
-// Ensure RenderWidgetHostViewMac claims hotkeys when AppKit spams the UI with
-// -performKeyEquivalent:, but only when the window is key.
-// Flaky: https://crbug.com/792907
-TEST_F(RenderWidgetHostViewMacTest, DISABLED_ForwardKeyEquivalentsOnlyIfKey) {
- int32_t routing_id = process_host_->GetNextRoutingID();
- // Owned by its |cocoa_view()|.
- MockRenderWidgetHostImpl* host = MockRenderWidgetHostImpl::Create(
- &delegate_, process_host_.get(), routing_id);
- RenderWidgetHostViewMac* view = new RenderWidgetHostViewMac(host, false);
-
- EXPECT_CALL(*host, Focus()).Times(2);
- EXPECT_CALL(*host, Blur());
-
- // This test needs an NSWindow. |rwhv_cocoa_| isn't in one, but going
- // fullscreen conveniently puts it in one.
- EXPECT_FALSE([view->cocoa_view() window]);
- view->InitAsFullscreen(nullptr);
- NSWindow* window = [view->cocoa_view() window];
- EXPECT_TRUE(window);
- base::RunLoop().RunUntilIdle();
- MockWidgetInputHandler::MessageVector events =
- host->GetAndResetDispatchedMessages();
-
- ui::test::ScopedFakeNSWindowFocus key_window_faker;
- EXPECT_FALSE([window isKeyWindow]);
- base::RunLoop().RunUntilIdle();
- events = host->GetAndResetDispatchedMessages();
-
- EXPECT_EQ(0U, events.size());
-
- // Cmd+x.
- NSEvent* key_down =
- cocoa_test_event_utils::KeyEventWithType(NSKeyDown, NSCommandKeyMask);
-
- // Sending while not key should forward along the responder chain (e.g. to the
- // mainMenu). Note the event is being sent to the NSWindow, which may also ask
- // other parts of the UI to handle it, but in the test they should all say
- // "NO" as well.
- EXPECT_FALSE([window performKeyEquivalent:key_down]);
- base::RunLoop().RunUntilIdle();
- events = host->GetAndResetDispatchedMessages();
- EXPECT_EQ(0U, events.size());
-
- // Make key and send again. Event should be seen.
- [window makeKeyWindow];
- EXPECT_TRUE([window isKeyWindow]);
- base::RunLoop().RunUntilIdle();
- events = host->GetAndResetDispatchedMessages();
-
- // -performKeyEquivalent: now returns YES to prevent further propagation, and
- // the event is sent to the renderer.
- EXPECT_TRUE([window performKeyEquivalent:key_down]);
- base::RunLoop().RunUntilIdle();
- events = host->GetAndResetDispatchedMessages();
- EXPECT_EQ("RawKeyDown Char", GetMessageNames(events));
-
- view->release_pepper_fullscreen_window_for_testing();
-
- // Clean up.
- host->ShutdownAndDestroyWidget(true);
-}
-
TEST_F(RenderWidgetHostViewMacTest, ClearCompositorFrame) {
BrowserCompositorMac* browser_compositor =
rwhv_mac_->BrowserCompositorForTesting();
diff --git a/chromium/content/browser/renderer_host/render_widget_targeter.cc b/chromium/content/browser/renderer_host/render_widget_targeter.cc
index 2282465f5cc..9e0e5b96b8e 100644
--- a/chromium/content/browser/renderer_host/render_widget_targeter.cc
+++ b/chromium/content/browser/renderer_host/render_widget_targeter.cc
@@ -8,7 +8,7 @@
#include "content/browser/renderer_host/input/one_shot_timeout_monitor.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_view_base.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/events/blink/blink_event_util.h"
namespace content {
@@ -120,9 +120,9 @@ void RenderWidgetTargeter::FindTargetAndDispatch(
event.GetType() == blink::WebInputEvent::kMouseWheel ||
blink::WebInputEvent::IsTouchEventType(event.GetType()) ||
(blink::WebInputEvent::IsGestureEventType(event.GetType()) &&
- (static_cast<const blink::WebGestureEvent&>(event).source_device ==
+ (static_cast<const blink::WebGestureEvent&>(event).SourceDevice() ==
blink::WebGestureDevice::kWebGestureDeviceTouchscreen ||
- static_cast<const blink::WebGestureEvent&>(event).source_device ==
+ static_cast<const blink::WebGestureEvent&>(event).SourceDevice() ==
blink::WebGestureDevice::kWebGestureDeviceTouchpad)));
if (request_in_flight_) {
@@ -178,8 +178,7 @@ void RenderWidgetTargeter::QueryClient(
DCHECK(!request_in_flight_);
request_in_flight_ = true;
- auto* target_client =
- target->GetRenderWidgetHostImpl()->input_target_client();
+ auto* target_client = target->host()->input_target_client();
TracingUmaTracker tracker("Event.AsyncTargeting.ResponseTime",
"input,latency");
async_hit_test_timeout_.reset(new OneShotTimeoutMonitor(
diff --git a/chromium/content/browser/renderer_host/render_widget_targeter.h b/chromium/content/browser/renderer_host/render_widget_targeter.h
index 7aac783ab05..899c37f20bc 100644
--- a/chromium/content/browser/renderer_host/render_widget_targeter.h
+++ b/chromium/content/browser/renderer_host/render_widget_targeter.h
@@ -12,6 +12,7 @@
#include "base/optional.h"
#include "base/time/time.h"
#include "content/common/content_constants_internal.h"
+#include "content/common/content_export.h"
#include "ui/events/blink/web_input_event_traits.h"
#include "ui/latency/latency_info.h"
@@ -32,7 +33,7 @@ namespace content {
class RenderWidgetHostViewBase;
class OneShotTimeoutMonitor;
-struct RenderWidgetTargetResult {
+struct CONTENT_EXPORT RenderWidgetTargetResult {
RenderWidgetTargetResult();
RenderWidgetTargetResult(const RenderWidgetTargetResult&);
RenderWidgetTargetResult(RenderWidgetHostViewBase* view,
diff --git a/chromium/content/browser/renderer_host/text_input_client_mac.h b/chromium/content/browser/renderer_host/text_input_client_mac.h
index eeb48a81595..8165445841d 100644
--- a/chromium/content/browser/renderer_host/text_input_client_mac.h
+++ b/chromium/content/browser/renderer_host/text_input_client_mac.h
@@ -13,13 +13,19 @@
#include "base/synchronization/condition_variable.h"
#include "base/synchronization/lock.h"
#include "content/common/content_export.h"
+#include "content/common/mac/attributed_string_coder.h"
#include "ui/gfx/geometry/point.h"
+#include "ui/gfx/geometry/rect.h"
namespace base {
template <typename T>
struct DefaultSingletonTraits;
} // namespace base
+namespace gfx {
+class Range;
+}
+
namespace content {
class RenderWidgetHost;
@@ -56,17 +62,23 @@ class CONTENT_EXPORT TextInputClientMac {
// this service and signal the condition to allow the Get*() methods to
// unlock and return that stored value.
//
- // Returns NSNotFound if the request times out or is not completed.
- NSUInteger GetCharacterIndexAtPoint(RenderWidgetHost* rwh, gfx::Point point);
+ // Returns UINT32_MAX if the request times out or is not completed.
+ uint32_t GetCharacterIndexAtPoint(RenderWidgetHost* rwh,
+ const gfx::Point& point);
// Returns NSZeroRect if the request times out or is not completed. The result
// is in WebKit coordinates.
- NSRect GetFirstRectForRange(RenderWidgetHost* rwh, NSRange range);
+ gfx::Rect GetFirstRectForRange(RenderWidgetHost* rwh,
+ const gfx::Range& range);
// When the renderer sends the ViewHostMsg reply, the RenderMessageFilter will
// call the corresponding method on the IO thread to unlock the condition and
// allow the Get*() methods to continue/return.
- void SetCharacterIndexAndSignal(NSUInteger index);
- void SetFirstRectAndSignal(NSRect first_rect);
+ void SetCharacterIndexAndSignal(uint32_t index);
+ void SetFirstRectAndSignal(const gfx::Rect& first_rect);
+
+ typedef base::OnceCallback<
+ void(const mac::AttributedStringCoder::EncodedString&, gfx::Point)>
+ GetStringCallback;
// This async method is invoked from RenderWidgetHostViewCocoa's
// -quickLookWithEvent:, when the user taps a word using 3 fingers.
@@ -75,12 +87,14 @@ class CONTENT_EXPORT TextInputClientMac {
// The callback parameters provide the attributed word under the point and
// the lower left baseline point of the text.
void GetStringAtPoint(RenderWidgetHost* rwh,
- gfx::Point point,
- void (^reply_handler)(NSAttributedString*, NSPoint));
+ const gfx::Point& point,
+ GetStringCallback callback);
// This is called on the IO thread when we get the renderer's reply for
// GetStringAtPoint.
- void GetStringAtPointReply(NSAttributedString* string, NSPoint point);
+ void GetStringAtPointReply(
+ const mac::AttributedStringCoder::EncodedString& string,
+ const gfx::Point& point);
// This async method is invoked when browser tries to retreive the text for
// certain range and doesn't want to wait for the reply from blink.
@@ -89,12 +103,14 @@ class CONTENT_EXPORT TextInputClientMac {
// The callback parameters provide the attributed word under the point and
// the lower left baseline point of the text.
void GetStringFromRange(RenderWidgetHost* rwh,
- NSRange range,
- void (^reply_handler)(NSAttributedString*, NSPoint));
+ const gfx::Range& range,
+ GetStringCallback callback);
// This is called on the IO thread when we get the renderer's reply for
// GetStringFromRange.
- void GetStringFromRangeReply(NSAttributedString* string, NSPoint point);
+ void GetStringFromRangeReply(
+ const mac::AttributedStringCoder::EncodedString& string,
+ const gfx::Point& point);
private:
friend struct base::DefaultSingletonTraits<TextInputClientMac>;
@@ -110,19 +126,17 @@ class CONTENT_EXPORT TextInputClientMac {
// condition.
void AfterRequest();
- NSUInteger character_index_;
- NSRect first_rect_;
+ uint32_t character_index_;
+ gfx::Rect first_rect_;
base::Lock lock_;
base::ConditionVariable condition_;
// The callback when received IPC TextInputClientReplyMsg_GotStringAtPoint.
- base::mac::ScopedBlock<void(^)(NSAttributedString*, NSPoint)>
- replyForPointHandler_;
+ GetStringCallback replyForPointHandler_;
// The callback when received IPC TextInputClientReplyMsg_GotStringForRange.
- base::mac::ScopedBlock<void(^)(NSAttributedString*, NSPoint)>
- replyForRangeHandler_;
+ GetStringCallback replyForRangeHandler_;
DISALLOW_COPY_AND_ASSIGN(TextInputClientMac);
};
diff --git a/chromium/content/browser/renderer_host/text_input_client_mac.mm b/chromium/content/browser/renderer_host/text_input_client_mac.mm
index 46553dfb8c0..3a6bcfb56d2 100644
--- a/chromium/content/browser/renderer_host/text_input_client_mac.mm
+++ b/chromium/content/browser/renderer_host/text_input_client_mac.mm
@@ -42,10 +42,7 @@ bool SendMessageToRenderWidget(RenderWidgetHostImpl* widget,
const float kWaitTimeout = 1500;
TextInputClientMac::TextInputClientMac()
- : character_index_(NSNotFound),
- lock_(),
- condition_(&lock_) {
-}
+ : character_index_(UINT32_MAX), lock_(), condition_(&lock_) {}
TextInputClientMac::~TextInputClientMac() {
}
@@ -55,55 +52,53 @@ TextInputClientMac* TextInputClientMac::GetInstance() {
return base::Singleton<TextInputClientMac>::get();
}
-void TextInputClientMac::GetStringAtPoint(
- RenderWidgetHost* rwh,
- gfx::Point point,
- void (^reply_handler)(NSAttributedString*, NSPoint)) {
+void TextInputClientMac::GetStringAtPoint(RenderWidgetHost* rwh,
+ const gfx::Point& point,
+ GetStringCallback callback) {
// TODO(ekaramad): In principle, we are using the same handler regardless of
// the |rwh| which requested this. We should track the callbacks for each
// |rwh| individually so that one slow RWH will not end up clearing the
// callback for another (https://crbug.com/643233).
- DCHECK(replyForPointHandler_.get() == nil);
- replyForPointHandler_.reset(reply_handler, base::scoped_policy::RETAIN);
+ DCHECK(!replyForPointHandler_);
+ replyForPointHandler_ = std::move(callback);
RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(rwh);
SendMessageToRenderWidget(
rwhi, new TextInputClientMsg_StringAtPoint(rwhi->GetRoutingID(), point));
}
-void TextInputClientMac::GetStringAtPointReply(NSAttributedString* string,
- NSPoint point) {
- if (replyForPointHandler_.get()) {
- replyForPointHandler_.get()(string, point);
- replyForPointHandler_.reset();
+void TextInputClientMac::GetStringAtPointReply(
+ const mac::AttributedStringCoder::EncodedString& string,
+ const gfx::Point& point) {
+ if (replyForPointHandler_) {
+ std::move(replyForPointHandler_).Run(string, point);
}
}
-void TextInputClientMac::GetStringFromRange(
- RenderWidgetHost* rwh,
- NSRange range,
- void (^reply_handler)(NSAttributedString*, NSPoint)) {
- DCHECK(replyForRangeHandler_.get() == nil);
- replyForRangeHandler_.reset(reply_handler, base::scoped_policy::RETAIN);
+void TextInputClientMac::GetStringFromRange(RenderWidgetHost* rwh,
+ const gfx::Range& range,
+ GetStringCallback callback) {
+ DCHECK(!replyForRangeHandler_);
+ replyForRangeHandler_ = std::move(callback);
RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(rwh);
- SendMessageToRenderWidget(rwhi, new TextInputClientMsg_StringForRange(
- rwhi->GetRoutingID(), gfx::Range(range)));
+ SendMessageToRenderWidget(
+ rwhi, new TextInputClientMsg_StringForRange(rwhi->GetRoutingID(), range));
}
-void TextInputClientMac::GetStringFromRangeReply(NSAttributedString* string,
- NSPoint point) {
- if (replyForRangeHandler_.get()) {
- replyForRangeHandler_.get()(string, point);
- replyForRangeHandler_.reset();
+void TextInputClientMac::GetStringFromRangeReply(
+ const mac::AttributedStringCoder::EncodedString& string,
+ const gfx::Point& point) {
+ if (replyForRangeHandler_) {
+ std::move(replyForRangeHandler_).Run(string, point);
}
}
-NSUInteger TextInputClientMac::GetCharacterIndexAtPoint(RenderWidgetHost* rwh,
- gfx::Point point) {
+uint32_t TextInputClientMac::GetCharacterIndexAtPoint(RenderWidgetHost* rwh,
+ const gfx::Point& point) {
RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(rwh);
if (!SendMessageToRenderWidget(rwhi,
new TextInputClientMsg_CharacterIndexForPoint(
rwhi->GetRoutingID(), point))) {
- return NSNotFound;
+ return UINT32_MAX;
}
base::TimeTicks start = base::TimeTicks::Now();
@@ -122,13 +117,13 @@ NSUInteger TextInputClientMac::GetCharacterIndexAtPoint(RenderWidgetHost* rwh,
return character_index_;
}
-NSRect TextInputClientMac::GetFirstRectForRange(RenderWidgetHost* rwh,
- NSRange range) {
+gfx::Rect TextInputClientMac::GetFirstRectForRange(RenderWidgetHost* rwh,
+ const gfx::Range& range) {
RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(rwh);
if (!SendMessageToRenderWidget(
rwhi, new TextInputClientMsg_FirstRectForCharacterRange(
- rwhi->GetRoutingID(), gfx::Range(range)))) {
- return NSRect();
+ rwhi->GetRoutingID(), range))) {
+ return gfx::Rect();
}
base::TimeTicks start = base::TimeTicks::Now();
@@ -147,14 +142,14 @@ NSRect TextInputClientMac::GetFirstRectForRange(RenderWidgetHost* rwh,
return first_rect_;
}
-void TextInputClientMac::SetCharacterIndexAndSignal(NSUInteger index) {
+void TextInputClientMac::SetCharacterIndexAndSignal(uint32_t index) {
lock_.Acquire();
character_index_ = index;
lock_.Release();
condition_.Signal();
}
-void TextInputClientMac::SetFirstRectAndSignal(NSRect first_rect) {
+void TextInputClientMac::SetFirstRectAndSignal(const gfx::Rect& first_rect) {
lock_.Acquire();
first_rect_ = first_rect;
lock_.Release();
@@ -170,8 +165,8 @@ void TextInputClientMac::BeforeRequest() {
UMA_HISTOGRAM_LONG_TIMES("TextInputClient.LockWait",
delta * base::Time::kMicrosecondsPerMillisecond);
- character_index_ = NSNotFound;
- first_rect_ = NSZeroRect;
+ character_index_ = UINT32_MAX;
+ first_rect_ = gfx::Rect();
}
void TextInputClientMac::AfterRequest() {
diff --git a/chromium/content/browser/renderer_host/text_input_client_mac_unittest.mm b/chromium/content/browser/renderer_host/text_input_client_mac_unittest.mm
index 91fe5b76b06..8b752c7b793 100644
--- a/chromium/content/browser/renderer_host/text_input_client_mac_unittest.mm
+++ b/chromium/content/browser/renderer_host/text_input_client_mac_unittest.mm
@@ -10,7 +10,6 @@
#include "base/bind.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
-#include "base/test/scoped_task_environment.h"
#include "base/threading/thread.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_delegate.h"
@@ -19,6 +18,7 @@
#include "content/common/text_input_client_messages.h"
#include "content/public/test/mock_render_process_host.h"
#include "content/public/test/test_browser_context.h"
+#include "content/public/test/test_browser_thread_bundle.h"
#include "content/test/mock_widget_impl.h"
#include "ipc/ipc_test_sink.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -50,9 +50,7 @@ class MockRenderWidgetHostDelegate : public RenderWidgetHostDelegate {
class TextInputClientMacTest : public testing::Test {
public:
TextInputClientMacTest()
- : scoped_task_environment_(
- base::test::ScopedTaskEnvironment::MainThreadType::UI),
- browser_context_(),
+ : browser_context_(),
process_factory_(),
delegate_(),
thread_("TextInputClientMacTestThread") {
@@ -103,7 +101,7 @@ class TextInputClientMacTest : public testing::Test {
friend class ScopedTestingThread;
// TaskScheduler is used by RenderWidgetHostImpl constructor.
- base::test::ScopedTaskEnvironment scoped_task_environment_;
+ TestBrowserThreadBundle thread_bundle_;
TestBrowserContext browser_context_;
@@ -161,12 +159,12 @@ TEST_F(TextInputClientMacTest, GetCharacterIndex) {
}
TEST_F(TextInputClientMacTest, TimeoutCharacterIndex) {
- NSUInteger index = service()->GetCharacterIndexAtPoint(
- widget(), gfx::Point(2, 2));
+ uint32_t index =
+ service()->GetCharacterIndexAtPoint(widget(), gfx::Point(2, 2));
EXPECT_EQ(1U, ipc_sink().message_count());
EXPECT_TRUE(ipc_sink().GetUniqueMessageMatching(
TextInputClientMsg_CharacterIndexForPoint::ID));
- EXPECT_EQ(static_cast<NSUInteger>(NSNotFound), index);
+ EXPECT_EQ(UINT32_MAX, index);
}
TEST_F(TextInputClientMacTest, NotFoundCharacterIndex) {
@@ -189,11 +187,11 @@ TEST_F(TextInputClientMacTest, NotFoundCharacterIndex) {
base::Bind(&CallOnMessageReceived, filter, *message),
base::TimeDelta::FromMilliseconds(kTaskDelayMs) * 2);
- NSUInteger index = service()->GetCharacterIndexAtPoint(
- widget(), gfx::Point(2, 2));
+ uint32_t index =
+ service()->GetCharacterIndexAtPoint(widget(), gfx::Point(2, 2));
EXPECT_EQ(kPreviousValue, index);
index = service()->GetCharacterIndexAtPoint(widget(), gfx::Point(2, 2));
- EXPECT_EQ(static_cast<NSUInteger>(NSNotFound), index);
+ EXPECT_EQ(UINT32_MAX, index);
EXPECT_EQ(2U, ipc_sink().message_count());
for (size_t i = 0; i < ipc_sink().message_count(); ++i) {
@@ -205,25 +203,27 @@ TEST_F(TextInputClientMacTest, NotFoundCharacterIndex) {
TEST_F(TextInputClientMacTest, GetRectForRange) {
ScopedTestingThread thread(this);
- const NSRect kSuccessValue = NSMakeRect(42, 43, 44, 45);
+ const gfx::Rect kSuccessValue(42, 43, 44, 45);
PostTask(FROM_HERE,
base::Bind(&TextInputClientMac::SetFirstRectAndSignal,
base::Unretained(service()), kSuccessValue));
- NSRect rect = service()->GetFirstRectForRange(widget(), NSMakeRange(0, 32));
+ gfx::Rect rect =
+ service()->GetFirstRectForRange(widget(), gfx::Range(NSMakeRange(0, 32)));
EXPECT_EQ(1U, ipc_sink().message_count());
EXPECT_TRUE(ipc_sink().GetUniqueMessageMatching(
TextInputClientMsg_FirstRectForCharacterRange::ID));
- EXPECT_NSEQ(kSuccessValue, rect);
+ EXPECT_EQ(kSuccessValue, rect);
}
TEST_F(TextInputClientMacTest, TimeoutRectForRange) {
- NSRect rect = service()->GetFirstRectForRange(widget(), NSMakeRange(0, 32));
+ gfx::Rect rect =
+ service()->GetFirstRectForRange(widget(), gfx::Range(NSMakeRange(0, 32)));
EXPECT_EQ(1U, ipc_sink().message_count());
EXPECT_TRUE(ipc_sink().GetUniqueMessageMatching(
TextInputClientMsg_FirstRectForCharacterRange::ID));
- EXPECT_NSEQ(NSZeroRect, rect);
+ EXPECT_EQ(gfx::Rect(), rect);
}
} // namespace content
diff --git a/chromium/content/browser/renderer_host/text_input_client_message_filter.h b/chromium/content/browser/renderer_host/text_input_client_message_filter.h
index 4ded7f33f34..3dd6ab98135 100644
--- a/chromium/content/browser/renderer_host/text_input_client_message_filter.h
+++ b/chromium/content/browser/renderer_host/text_input_client_message_filter.h
@@ -10,6 +10,7 @@
#include "base/macros.h"
#include "content/common/mac/attributed_string_coder.h"
#include "content/public/browser/browser_message_filter.h"
+#include "content/public/browser/browser_thread.h"
namespace gfx {
class Point;
diff --git a/chromium/content/browser/renderer_host/text_input_client_message_filter.mm b/chromium/content/browser/renderer_host/text_input_client_message_filter.mm
index 35d430004b3..cb4db8bc7a1 100644
--- a/chromium/content/browser/renderer_host/text_input_client_message_filter.mm
+++ b/chromium/content/browser/renderer_host/text_input_client_message_filter.mm
@@ -52,38 +52,25 @@ void TextInputClientMessageFilter::OnGotStringAtPoint(
const mac::AttributedStringCoder::EncodedString& encoded_string,
const gfx::Point& point) {
TextInputClientMac* service = TextInputClientMac::GetInstance();
- NSAttributedString* string =
- mac::AttributedStringCoder::Decode(&encoded_string);
- service->GetStringAtPointReply(string, NSPointFromCGPoint(point.ToCGPoint()));
+ service->GetStringAtPointReply(encoded_string, point);
}
void TextInputClientMessageFilter::OnGotCharacterIndexForPoint(uint32_t index) {
TextInputClientMac* service = TextInputClientMac::GetInstance();
- // |index| could be WTF::notFound (-1) and its value is different from
- // NSNotFound so we need to convert it.
- size_t char_index;
- if (index == UINT32_MAX) {
- char_index = NSNotFound;
- } else {
- char_index = index;
- }
- service->SetCharacterIndexAndSignal(char_index);
+ service->SetCharacterIndexAndSignal(index);
}
void TextInputClientMessageFilter::OnGotFirstRectForRange(
const gfx::Rect& rect) {
TextInputClientMac* service = TextInputClientMac::GetInstance();
- service->SetFirstRectAndSignal(NSRectFromCGRect(rect.ToCGRect()));
+ service->SetFirstRectAndSignal(rect);
}
void TextInputClientMessageFilter::OnGotStringFromRange(
const mac::AttributedStringCoder::EncodedString& encoded_string,
const gfx::Point& point) {
TextInputClientMac* service = TextInputClientMac::GetInstance();
- NSAttributedString* string =
- mac::AttributedStringCoder::Decode(&encoded_string);
- service->GetStringFromRangeReply(
- string, NSPointFromCGPoint(point.ToCGPoint()));
+ service->GetStringFromRangeReply(encoded_string, point);
}
} // namespace content
diff --git a/chromium/content/browser/renderer_host/ui_events_helper.cc b/chromium/content/browser/renderer_host/ui_events_helper.cc
index 5e4c6f96377..a958b79e8c8 100644
--- a/chromium/content/browser/renderer_host/ui_events_helper.cc
+++ b/chromium/content/browser/renderer_host/ui_events_helper.cc
@@ -6,9 +6,8 @@
#include <stdint.h>
-#include "base/memory/ptr_util.h"
#include "content/common/input/web_touch_event_traits.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/events/base_event_utils.h"
#include "ui/events/blink/blink_event_util.h"
#include "ui/events/event.h"
diff --git a/chromium/content/browser/renderer_host/web_database_host_impl.cc b/chromium/content/browser/renderer_host/web_database_host_impl.cc
index 2383892cc38..a27dfea1f3e 100644
--- a/chromium/content/browser/renderer_host/web_database_host_impl.cc
+++ b/chromium/content/browser/renderer_host/web_database_host_impl.cc
@@ -18,7 +18,7 @@
#include "storage/browser/quota/quota_manager.h"
#include "storage/browser/quota/quota_manager_proxy.h"
#include "storage/common/database/database_identifier.h"
-#include "third_party/WebKit/public/mojom/quota/quota_types.mojom.h"
+#include "third_party/blink/public/mojom/quota/quota_types.mojom.h"
#include "third_party/sqlite/sqlite3.h"
#include "url/origin.h"
@@ -186,7 +186,7 @@ void WebDatabaseHostImpl::GetSpaceAvailable(
db_tracker_->quota_manager_proxy()->GetUsageAndQuota(
db_tracker_->task_runner(), origin, blink::mojom::StorageType::kTemporary,
- base::Bind(
+ base::BindOnce(
[](GetSpaceAvailableCallback callback,
blink::mojom::QuotaStatusCode status, int64_t usage,
int64_t quota) {
@@ -197,7 +197,7 @@ void WebDatabaseHostImpl::GetSpaceAvailable(
}
std::move(callback).Run(available);
},
- base::Passed(std::move(callback))));
+ std::move(callback)));
}
void WebDatabaseHostImpl::DatabaseDeleteFile(
diff --git a/chromium/content/browser/renderer_host/web_database_host_impl.h b/chromium/content/browser/renderer_host/web_database_host_impl.h
index 52d636704e5..21bf6dc9b23 100644
--- a/chromium/content/browser/renderer_host/web_database_host_impl.h
+++ b/chromium/content/browser/renderer_host/web_database_host_impl.h
@@ -10,7 +10,7 @@
#include "base/strings/string16.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "storage/browser/database/database_tracker.h"
-#include "third_party/WebKit/public/platform/modules/webdatabase/web_database.mojom.h"
+#include "third_party/blink/public/platform/modules/webdatabase/web_database.mojom.h"
namespace url {
class Origin;
diff --git a/chromium/content/browser/renderer_host/webmenurunner_mac.mm b/chromium/content/browser/renderer_host/webmenurunner_mac.mm
index 9527145b7d9..e57cfae2c59 100644
--- a/chromium/content/browser/renderer_host/webmenurunner_mac.mm
+++ b/chromium/content/browser/renderer_host/webmenurunner_mac.mm
@@ -6,7 +6,6 @@
#include <stddef.h>
-#import "base/message_loop/message_pump_mac.h"
#include "base/strings/sys_string_conversions.h"
@interface WebMenuRunner (PrivateAPI)
@@ -156,11 +155,7 @@
// Display the menu, and set a flag if a menu item was chosen.
[cell attachPopUpWithFrame:[dummyView bounds] inView:dummyView];
- {
- // Ensure the UI can update while the menu is fading out.
- base::ScopedPumpMessagesInPrivateModes pump_private;
- [cell performClickWithFrame:[dummyView bounds] inView:dummyView];
- }
+ [cell performClickWithFrame:[dummyView bounds] inView:dummyView];
[dummyView removeFromSuperview];
diff --git a/chromium/content/browser/renderer_interface_binders.cc b/chromium/content/browser/renderer_interface_binders.cc
index 9b1c71bdb19..24bd8c4e1e2 100644
--- a/chromium/content/browser/renderer_interface_binders.cc
+++ b/chromium/content/browser/renderer_interface_binders.cc
@@ -7,6 +7,7 @@
#include <utility>
#include "base/bind.h"
+#include "base/feature_list.h"
#include "content/browser/background_fetch/background_fetch_service_impl.h"
#include "content/browser/dedicated_worker/dedicated_worker_host.h"
#include "content/browser/locks/lock_manager.h"
@@ -25,6 +26,7 @@
#include "content/public/common/content_switches.h"
#include "services/device/public/mojom/constants.mojom.h"
#include "services/device/public/mojom/vibration_manager.mojom.h"
+#include "services/network/public/cpp/features.h"
#include "services/network/restricted_cookie_manager.h"
#include "services/service_manager/public/cpp/binder_registry.h"
#include "services/service_manager/public/cpp/connector.h"
@@ -32,7 +34,8 @@
#include "services/shape_detection/public/mojom/constants.mojom.h"
#include "services/shape_detection/public/mojom/facedetection_provider.mojom.h"
#include "services/shape_detection/public/mojom/textdetection.mojom.h"
-#include "third_party/WebKit/public/platform/modules/notifications/notification_service.mojom.h"
+#include "third_party/blink/public/platform/modules/cache_storage/cache_storage.mojom.h"
+#include "third_party/blink/public/platform/modules/notifications/notification_service.mojom.h"
#include "url/origin.h"
namespace content {
@@ -72,6 +75,10 @@ class RendererInterfaceBinders {
private:
void InitializeParameterizedBinderRegistry();
+ static void CreateWebSocket(network::mojom::WebSocketRequest request,
+ RenderProcessHost* host,
+ const url::Origin& origin);
+
service_manager::BinderRegistryWithArgs<RenderProcessHost*,
const url::Origin&>
parameterized_binder_registry_;
@@ -126,11 +133,7 @@ void RendererInterfaceBinders::InitializeParameterizedBinderRegistry() {
base::Bind(&ForwardServiceRequest<device::mojom::VibrationManager>,
device::mojom::kServiceName));
parameterized_binder_registry_.AddInterface(
- base::Bind([](blink::mojom::WebSocketRequest request,
- RenderProcessHost* host, const url::Origin& origin) {
- WebSocketManager::CreateWebSocketWithOrigin(
- host->GetID(), origin, std::move(request), MSG_ROUTING_NONE);
- }));
+ base::BindRepeating(CreateWebSocket));
parameterized_binder_registry_.AddInterface(
base::Bind([](payments::mojom::PaymentManagerRequest request,
RenderProcessHost* host, const url::Origin& origin) {
@@ -138,6 +141,12 @@ void RendererInterfaceBinders::InitializeParameterizedBinderRegistry() {
->GetPaymentAppContext()
->CreatePaymentManager(std::move(request));
}));
+ parameterized_binder_registry_.AddInterface(base::BindRepeating(
+ [](blink::mojom::CacheStorageRequest request, RenderProcessHost* host,
+ const url::Origin& origin) {
+ static_cast<RenderProcessHostImpl*>(host)->BindCacheStorage(
+ std::move(request), origin);
+ }));
parameterized_binder_registry_.AddInterface(
base::Bind([](blink::mojom::PermissionServiceRequest request,
RenderProcessHost* host, const url::Origin& origin) {
@@ -174,6 +183,22 @@ RendererInterfaceBinders& GetRendererInterfaceBinders() {
return binders;
}
+void RendererInterfaceBinders::CreateWebSocket(
+ network::mojom::WebSocketRequest request,
+ RenderProcessHost* host,
+ const url::Origin& origin) {
+ if (base::FeatureList::IsEnabled(network::features::kNetworkService)) {
+ StoragePartition* storage_partition = host->GetStoragePartition();
+ network::mojom::NetworkContext* network_context =
+ storage_partition->GetNetworkContext();
+ network_context->CreateWebSocket(std::move(request), host->GetID(),
+ MSG_ROUTING_NONE, origin);
+ } else {
+ WebSocketManager::CreateWebSocketWithOrigin(
+ host->GetID(), origin, std::move(request), MSG_ROUTING_NONE);
+ }
+}
+
} // namespace
void BindWorkerInterface(const std::string& interface_name,
diff --git a/chromium/content/browser/resolve_proxy_msg_helper.h b/chromium/content/browser/resolve_proxy_msg_helper.h
index 8a59d1322e1..8eacab90e7d 100644
--- a/chromium/content/browser/resolve_proxy_msg_helper.h
+++ b/chromium/content/browser/resolve_proxy_msg_helper.h
@@ -12,7 +12,7 @@
#include "content/common/content_export.h"
#include "content/public/browser/browser_message_filter.h"
#include "net/base/completion_callback.h"
-#include "net/proxy_resolution/proxy_service.h"
+#include "net/proxy_resolution/proxy_resolution_service.h"
#include "url/gurl.h"
namespace net {
diff --git a/chromium/content/browser/resolve_proxy_msg_helper_unittest.cc b/chromium/content/browser/resolve_proxy_msg_helper_unittest.cc
index ec1d86bef1b..d9e5b3e3f90 100644
--- a/chromium/content/browser/resolve_proxy_msg_helper_unittest.cc
+++ b/chromium/content/browser/resolve_proxy_msg_helper_unittest.cc
@@ -13,7 +13,8 @@
#include "net/base/net_errors.h"
#include "net/proxy_resolution/mock_proxy_resolver.h"
#include "net/proxy_resolution/proxy_config_service.h"
-#include "net/proxy_resolution/proxy_service.h"
+#include "net/proxy_resolution/proxy_resolution_service.h"
+#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace content {
@@ -23,8 +24,11 @@ class MockProxyConfigService : public net::ProxyConfigService {
public:
void AddObserver(Observer* observer) override {}
void RemoveObserver(Observer* observer) override {}
- ConfigAvailability GetLatestProxyConfig(net::ProxyConfig* results) override {
- *results = net::ProxyConfig::CreateFromCustomPacURL(GURL("http://pac"));
+ ConfigAvailability GetLatestProxyConfig(
+ net::ProxyConfigWithAnnotation* results) override {
+ *results = net::ProxyConfigWithAnnotation(
+ net::ProxyConfig::CreateFromCustomPacURL(GURL("http://pac")),
+ TRAFFIC_ANNOTATION_FOR_TESTS);
return CONFIG_VALID;
}
};
diff --git a/chromium/content/browser/resource_context_impl.cc b/chromium/content/browser/resource_context_impl.cc
index 895a9367b85..261e9343b8a 100644
--- a/chromium/content/browser/resource_context_impl.cc
+++ b/chromium/content/browser/resource_context_impl.cc
@@ -8,7 +8,6 @@
#include "base/bind.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "content/browser/blob_storage/chrome_blob_storage_context.h"
#include "content/browser/loader/resource_dispatcher_host_impl.h"
#include "content/browser/loader/resource_request_info_impl.h"
diff --git a/chromium/content/browser/resources/gpu/info_view.js b/chromium/content/browser/resources/gpu/info_view.js
index c9fb6bcfe33..eca2b71095f 100644
--- a/chromium/content/browser/resources/gpu/info_view.js
+++ b/chromium/content/browser/resources/gpu/info_view.js
@@ -117,6 +117,7 @@ cr.define('gpu', function() {
'vpx_decode': 'VPx Video Decode',
'webgl2': 'WebGL2',
'checker_imaging': 'CheckerImaging',
+ 'viz_display_compositor': 'Viz Service Display Compositor',
};
var statusMap = {
diff --git a/chromium/content/browser/resources/media/peer_connection_update_table.js b/chromium/content/browser/resources/media/peer_connection_update_table.js
index 208d11fde7e..4dcc476e90b 100644
--- a/chromium/content/browser/resources/media/peer_connection_update_table.js
+++ b/chromium/content/browser/resources/media/peer_connection_update_table.js
@@ -103,9 +103,9 @@ var PeerConnectionUpdateTable = (function() {
update.type === 'addIceCandidate') {
// extract ICE candidate type from the field following typ.
var candidateType = update.value.match(
- /(?: typ )(host|srflx|relay)/)[1];
+ /(?: typ )(host|srflx|relay)/);
if (candidateType) {
- type += ' (' + candidateType + ')';
+ type += ' (' + candidateType[1] + ')';
}
}
row.innerHTML += '<td><details><summary>' + type +
diff --git a/chromium/content/browser/sandbox_host_linux.h b/chromium/content/browser/sandbox_host_linux.h
index 10248baedea..cbaaaa6b30a 100644
--- a/chromium/content/browser/sandbox_host_linux.h
+++ b/chromium/content/browser/sandbox_host_linux.h
@@ -38,6 +38,8 @@ class CONTENT_EXPORT SandboxHostLinux {
}
void Init();
+ bool IsInitialized() const { return initialized_; }
+
private:
friend struct base::DefaultSingletonTraits<SandboxHostLinux>;
// This object must be constructed on the main thread.
diff --git a/chromium/content/browser/sandbox_ipc_linux.cc b/chromium/content/browser/sandbox_ipc_linux.cc
index 930fa23bfec..3206764895c 100644
--- a/chromium/content/browser/sandbox_ipc_linux.cc
+++ b/chromium/content/browser/sandbox_ipc_linux.cc
@@ -144,7 +144,13 @@ void SandboxIPCHandler::HandleRequestFromChild(int fd) {
base::UnixDomainSocket::RecvMsg(fd, buf, sizeof(buf), &fds);
if (len == -1) {
// TODO: should send an error reply, or the sender might block forever.
- NOTREACHED() << "Sandbox host message is larger than kMaxFontFamilyLength";
+ if (errno == EMSGSIZE) {
+ NOTREACHED()
+ << "Sandbox host message is larger than kMaxFontFamilyLength";
+ } else {
+ PLOG(ERROR) << "Recvmsg failed";
+ NOTREACHED();
+ }
return;
}
if (fds.empty())
diff --git a/chromium/content/browser/sandbox_parameters_mac.mm b/chromium/content/browser/sandbox_parameters_mac.mm
index 36bf6e2da42..a87788c2820 100644
--- a/chromium/content/browser/sandbox_parameters_mac.mm
+++ b/chromium/content/browser/sandbox_parameters_mac.mm
@@ -134,17 +134,6 @@ void SetupCDMSandboxParameters(sandbox::SeatbeltExecClient* client) {
void SetupUtilitySandboxParameters(sandbox::SeatbeltExecClient* client,
const base::CommandLine& command_line) {
SetupCommonSandboxParameters(client);
-
- base::FilePath permitted_dir =
- command_line.GetSwitchValuePath(switches::kUtilityProcessAllowedDir);
-
- if (!permitted_dir.empty()) {
- std::string permitted_dir_canonical =
- service_manager::SandboxMac::GetCanonicalPath(permitted_dir).value();
- CHECK(
- client->SetParameter(service_manager::SandboxMac::kSandboxPermittedDir,
- permitted_dir_canonical));
- }
}
} // namespace content
diff --git a/chromium/content/browser/screen_orientation/OWNERS b/chromium/content/browser/screen_orientation/OWNERS
index 20b13b92a47..5be0ec7c295 100644
--- a/chromium/content/browser/screen_orientation/OWNERS
+++ b/chromium/content/browser/screen_orientation/OWNERS
@@ -1,2 +1,2 @@
-file://third_party/WebKit/Source/modules/screen_orientation/OWNERS
+file://third_party/blink/renderer/modules/screen_orientation/OWNERS
diff --git a/chromium/content/browser/screen_orientation/screen_orientation_delegate_android.h b/chromium/content/browser/screen_orientation/screen_orientation_delegate_android.h
index e9da0fbefce..bf9d91c31b5 100644
--- a/chromium/content/browser/screen_orientation/screen_orientation_delegate_android.h
+++ b/chromium/content/browser/screen_orientation/screen_orientation_delegate_android.h
@@ -9,7 +9,7 @@
#include "base/macros.h"
#include "content/public/browser/screen_orientation_delegate.h"
-#include "third_party/WebKit/public/platform/modules/screen_orientation/WebScreenOrientationLockType.h"
+#include "third_party/blink/public/platform/modules/screen_orientation/web_screen_orientation_lock_type.h"
namespace content {
diff --git a/chromium/content/browser/screen_orientation/screen_orientation_provider.cc b/chromium/content/browser/screen_orientation/screen_orientation_provider.cc
index c9f4a867eb2..5d96c58eddc 100644
--- a/chromium/content/browser/screen_orientation/screen_orientation_provider.cc
+++ b/chromium/content/browser/screen_orientation/screen_orientation_provider.cc
@@ -13,7 +13,7 @@
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/screen_orientation_delegate.h"
#include "content/public/browser/web_contents.h"
-#include "third_party/WebKit/public/platform/modules/screen_orientation/WebLockOrientationError.h"
+#include "third_party/blink/public/platform/modules/screen_orientation/web_lock_orientation_error.h"
namespace content {
diff --git a/chromium/content/browser/screen_orientation/screen_orientation_provider.h b/chromium/content/browser/screen_orientation/screen_orientation_provider.h
index 35cd939bdf5..6ff35095bc1 100644
--- a/chromium/content/browser/screen_orientation/screen_orientation_provider.h
+++ b/chromium/content/browser/screen_orientation/screen_orientation_provider.h
@@ -14,7 +14,7 @@
#include "content/public/browser/web_contents_observer.h"
#include "services/device/public/mojom/screen_orientation.mojom.h"
#include "services/device/public/mojom/screen_orientation_lock_types.mojom.h"
-#include "third_party/WebKit/public/platform/modules/screen_orientation/WebScreenOrientationLockType.h"
+#include "third_party/blink/public/platform/modules/screen_orientation/web_screen_orientation_lock_type.h"
namespace content {
diff --git a/chromium/content/browser/screen_orientation/screen_orientation_provider_unittest.cc b/chromium/content/browser/screen_orientation/screen_orientation_provider_unittest.cc
index 888687a8b7f..97e3b3ecf6a 100644
--- a/chromium/content/browser/screen_orientation/screen_orientation_provider_unittest.cc
+++ b/chromium/content/browser/screen_orientation/screen_orientation_provider_unittest.cc
@@ -11,7 +11,7 @@
#include "content/public/browser/web_contents_delegate.h"
#include "content/test/test_render_view_host.h"
#include "content/test/test_web_contents.h"
-#include "third_party/WebKit/public/platform/modules/screen_orientation/WebScreenOrientationLockType.h"
+#include "third_party/blink/public/platform/modules/screen_orientation/web_screen_orientation_lock_type.h"
namespace content {
diff --git a/chromium/content/browser/security_exploit_browsertest.cc b/chromium/content/browser/security_exploit_browsertest.cc
index 0a1f363a673..637fae1bf91 100644
--- a/chromium/content/browser/security_exploit_browsertest.cc
+++ b/chromium/content/browser/security_exploit_browsertest.cc
@@ -7,7 +7,6 @@
#include "base/command_line.h"
#include "base/containers/hash_tables.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "content/browser/bad_message.h"
@@ -25,6 +24,7 @@
#include "content/common/render_message_filter.mojom.h"
#include "content/common/view_messages.h"
#include "content/public/browser/browser_context.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/interstitial_page.h"
#include "content/public/browser/interstitial_page_delegate.h"
@@ -54,7 +54,7 @@
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/mojom/url_loader.mojom.h"
#include "services/network/test/test_url_loader_client.h"
-#include "third_party/WebKit/public/web/WebTriggeringEventInfo.h"
+#include "third_party/blink/public/web/web_triggering_event_info.h"
using IPC::IpcSecurityTestUtil;
@@ -128,7 +128,6 @@ network::ResourceRequest CreateXHRRequest(const char* url) {
request.load_flags = 0;
request.plugin_child_id = -1;
request.resource_type = RESOURCE_TYPE_XHR;
- request.request_context = 0;
request.appcache_host_id = kAppCacheNoHostId;
request.download_to_file = false;
request.should_reset_appcache = false;
@@ -442,7 +441,7 @@ void OnHttpHeaderReceived(const std::string& header,
int child_process_id,
content::ResourceContext* resource_context,
OnHeaderProcessedCallback callback) {
- callback.Run(HeaderInterceptorResult::KILL);
+ std::move(callback).Run(HeaderInterceptorResult::KILL);
}
// Renderer processes should not be able to spoof Origin HTTP headers.
diff --git a/chromium/content/browser/service_manager/common_browser_interfaces.cc b/chromium/content/browser/service_manager/common_browser_interfaces.cc
index 282e036d2ed..55e52930552 100644
--- a/chromium/content/browser/service_manager/common_browser_interfaces.cc
+++ b/chromium/content/browser/service_manager/common_browser_interfaces.cc
@@ -9,7 +9,6 @@
#include "base/callback.h"
#include "base/command_line.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/task_runner.h"
#include "base/task_scheduler/post_task.h"
@@ -25,6 +24,8 @@
#if defined(OS_WIN)
#include "content/browser/renderer_host/dwrite_font_proxy_message_filter_win.h"
#include "content/public/common/font_cache_dispatcher_win.h"
+#elif defined(OS_MACOSX)
+#include "content/common/font_loader_dispatcher_mac.h"
#endif
namespace content {
@@ -40,6 +41,8 @@ class ConnectionFilterImpl : public ConnectionFilter {
base::BindRepeating(&DWriteFontProxyImpl::Create),
base::CreateSequencedTaskRunnerWithTraits(
{base::TaskPriority::USER_BLOCKING, base::MayBlock()}));
+#elif defined(OS_MACOSX)
+ registry_.AddInterface(base::BindRepeating(&FontLoaderDispatcher::Create));
#endif
if (!features::IsMusEnabled()) {
// For mus, the mojom::discardable_memory::DiscardableSharedMemoryManager
diff --git a/chromium/content/browser/service_manager/service_manager_context.cc b/chromium/content/browser/service_manager/service_manager_context.cc
index d8f30b7b62b..cc276364172 100644
--- a/chromium/content/browser/service_manager/service_manager_context.cc
+++ b/chromium/content/browser/service_manager/service_manager_context.cc
@@ -26,7 +26,8 @@
#include "content/browser/child_process_launcher.h"
#include "content/browser/gpu/gpu_process_host.h"
#include "content/browser/service_manager/common_browser_interfaces.h"
-#include "content/browser/utility_process_host_impl.h"
+#include "content/browser/utility_process_host.h"
+#include "content/browser/utility_process_host_client.h"
#include "content/browser/wake_lock/wake_lock_context_host.h"
#include "content/common/service_manager/service_manager_connection_impl.h"
#include "content/grit/content_resources.h"
@@ -35,15 +36,14 @@
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/gpu_service_registry.h"
#include "content/public/browser/network_service_instance.h"
-#include "content/public/browser/utility_process_host_client.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/service_manager_connection.h"
#include "content/public/common/service_names.mojom.h"
#include "media/audio/audio_manager.h"
-#include "media/media_features.h"
-#include "media/mojo/features.h"
+#include "media/media_buildflags.h"
+#include "media/mojo/buildflags.h"
#include "media/mojo/interfaces/constants.mojom.h"
#include "mojo/edk/embedder/embedder.h"
#include "mojo/edk/embedder/incoming_broker_client_invitation.h"
@@ -135,7 +135,7 @@ void StartServiceInUtilityProcess(
process_host = weak_host->get();
} else {
// Start a new process for this service.
- UtilityProcessHostImpl* impl = new UtilityProcessHostImpl(nullptr, nullptr);
+ UtilityProcessHost* impl = new UtilityProcessHost(nullptr, nullptr);
impl->SetName(process_name);
impl->SetServiceIdentity(service_manager::Identity(service_name));
impl->SetSandboxType(sandbox_type);
diff --git a/chromium/content/browser/service_worker/DEPS b/chromium/content/browser/service_worker/DEPS
index b85fe4e879a..b90ca0945bd 100644
--- a/chromium/content/browser/service_worker/DEPS
+++ b/chromium/content/browser/service_worker/DEPS
@@ -1,4 +1,4 @@
include_rules = [
"+third_party/leveldatabase",
- "+third_party/WebKit/public/web/worker_content_settings_proxy.mojom.h",
+ "+third_party/blink/public/web/worker_content_settings_proxy.mojom.h",
]
diff --git a/chromium/content/browser/service_worker/OWNERS b/chromium/content/browser/service_worker/OWNERS
index 53c92bc6fce..c19a2565fc3 100644
--- a/chromium/content/browser/service_worker/OWNERS
+++ b/chromium/content/browser/service_worker/OWNERS
@@ -5,11 +5,11 @@
# //content/browser/resources/service_worker/
# //content/common/service_worker/
# //content/renderer/service_worker/
-# //third_party/WebKit/public/mojom/service_worker/
-# //third_party/WebKit/public/web/modules/serviceworker/
-# //third_party/WebKit/public/platform/modules/serviceworker/
+# //third_party/blink/public/mojom/service_worker/
+# //third_party/blink/public/web/modules/serviceworker/
+# //third_party/blink/public/platform/modules/serviceworker/
# //third_party/WebKit/LayoutTests/external/wpt/service-workers/
-# //third_party/WebKit/Source/modules/serviceworkers/
+# //third_party/blink/renderer/modules/serviceworkers/
falken@chromium.org
horo@chromium.org
diff --git a/chromium/content/browser/service_worker/embedded_worker_instance.cc b/chromium/content/browser/service_worker/embedded_worker_instance.cc
index 754f001c315..19d8459d972 100644
--- a/chromium/content/browser/service_worker/embedded_worker_instance.cc
+++ b/chromium/content/browser/service_worker/embedded_worker_instance.cc
@@ -8,7 +8,6 @@
#include "base/bind_helpers.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/trace_event/trace_event.h"
#include "content/browser/bad_message.h"
@@ -19,7 +18,6 @@
#include "content/browser/service_worker/service_worker_context_core.h"
#include "content/common/content_switches_internal.h"
#include "content/common/renderer.mojom.h"
-#include "content/common/service_worker/embedded_worker_messages.h"
#include "content/common/service_worker/service_worker_types.h"
#include "content/common/service_worker/service_worker_utils.h"
#include "content/public/browser/browser_thread.h"
@@ -29,8 +27,8 @@
#include "content/public/common/content_client.h"
#include "content/public/common/content_switches.h"
#include "ipc/ipc_message.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
-#include "third_party/WebKit/public/web/WebConsoleMessage.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/web/web_console_message.h"
#include "url/gurl.h"
namespace content {
@@ -460,11 +458,6 @@ class EmbeddedWorkerInstance::StartTask {
DISALLOW_COPY_AND_ASSIGN(StartTask);
};
-bool EmbeddedWorkerInstance::Listener::OnMessageReceived(
- const IPC::Message& message) {
- return false;
-}
-
EmbeddedWorkerInstance::~EmbeddedWorkerInstance() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DCHECK(status_ == EmbeddedWorkerStatus::STOPPING ||
@@ -682,6 +675,10 @@ void EmbeddedWorkerInstance::RequestTermination() {
owner_version_->StopWorkerIfIdle(true /* requested_from_renderer */);
}
+void EmbeddedWorkerInstance::CountFeature(blink::mojom::WebFeature feature) {
+ owner_version_->CountFeature(feature);
+}
+
void EmbeddedWorkerInstance::OnReadyForInspection() {
if (devtools_proxy_) {
blink::mojom::DevToolsAgentAssociatedPtrInfo devtools_agent_ptr_info;
@@ -827,8 +824,7 @@ void EmbeddedWorkerInstance::OnStopped() {
}
void EmbeddedWorkerInstance::Detach() {
- // Temporary CHECK for debugging https://crbug.com/750267.
- CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
+ DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
if (status() == EmbeddedWorkerStatus::STOPPED)
return;
registry_->DetachWorker(process_id(), embedded_worker_id());
@@ -843,14 +839,6 @@ base::WeakPtr<EmbeddedWorkerInstance> EmbeddedWorkerInstance::AsWeakPtr() {
return weak_factory_.GetWeakPtr();
}
-bool EmbeddedWorkerInstance::OnMessageReceived(const IPC::Message& message) {
- for (auto& listener : listener_list_) {
- if (listener.OnMessageReceived(message))
- return true;
- }
- return false;
-}
-
void EmbeddedWorkerInstance::OnReportException(
const base::string16& error_message,
int line_number,
diff --git a/chromium/content/browser/service_worker/embedded_worker_instance.h b/chromium/content/browser/service_worker/embedded_worker_instance.h
index 01bc2122e61..5b6566ecb6d 100644
--- a/chromium/content/browser/service_worker/embedded_worker_instance.h
+++ b/chromium/content/browser/service_worker/embedded_worker_instance.h
@@ -29,14 +29,10 @@
#include "content/common/service_worker/service_worker_event_dispatcher.mojom.h"
#include "content/common/service_worker/service_worker_status_code.h"
#include "mojo/public/cpp/bindings/associated_binding.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_installed_scripts_manager.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_installed_scripts_manager.mojom.h"
#include "url/gurl.h"
-namespace IPC {
-class Message;
-}
-
namespace content {
class EmbeddedWorkerRegistry;
@@ -117,8 +113,6 @@ class CONTENT_EXPORT EmbeddedWorkerInstance
const base::string16& message,
int line_number,
const GURL& source_url) {}
- // Returns false if the message is not handled by this listener.
- CONTENT_EXPORT virtual bool OnMessageReceived(const IPC::Message& message);
};
~EmbeddedWorkerInstance() override;
@@ -252,6 +246,7 @@ class CONTENT_EXPORT EmbeddedWorkerInstance
// Implements mojom::EmbeddedWorkerInstanceHost.
// These functions all run on the IO thread.
void RequestTermination() override;
+ void CountFeature(blink::mojom::WebFeature feature) override;
void OnReadyForInspection() override;
void OnScriptLoaded() override;
// Notifies the corresponding provider host that the thread has started and is
@@ -275,11 +270,6 @@ class CONTENT_EXPORT EmbeddedWorkerInstance
int line_number,
const GURL& source_url) override;
- // Called back from Registry when the worker instance sends message
- // to the browser (i.e. EmbeddedWorker observers).
- // Returns false if the message is not handled.
- bool OnMessageReceived(const IPC::Message& message);
-
// Resets all running state. After this function is called, |status_| is
// STOPPED.
void ReleaseProcess();
diff --git a/chromium/content/browser/service_worker/embedded_worker_instance_unittest.cc b/chromium/content/browser/service_worker/embedded_worker_instance_unittest.cc
index 82e5fed9caf..b77c0716f69 100644
--- a/chromium/content/browser/service_worker/embedded_worker_instance_unittest.cc
+++ b/chromium/content/browser/service_worker/embedded_worker_instance_unittest.cc
@@ -10,7 +10,6 @@
#include "base/command_line.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/stl_util.h"
#include "content/browser/service_worker/embedded_worker_registry.h"
@@ -22,7 +21,6 @@
#include "content/browser/service_worker/service_worker_test_utils.h"
#include "content/browser/service_worker/service_worker_version.h"
#include "content/common/service_worker/embedded_worker.mojom.h"
-#include "content/common/service_worker/embedded_worker_messages.h"
#include "content/common/service_worker/service_worker_event_dispatcher.mojom.h"
#include "content/public/common/child_process_host.h"
#include "content/public/common/content_switches.h"
@@ -30,8 +28,8 @@
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
@@ -88,14 +86,16 @@ class ProviderHostEndpoints : public mojom::ServiceWorkerContainerHost {
GetRegistrationForReadyCallback callback) override {
NOTIMPLEMENTED();
}
- void GetControllerServiceWorker(
- mojom::ControllerServiceWorkerRequest request) override {
+ void EnsureControllerServiceWorker(
+ mojom::ControllerServiceWorkerRequest request,
+ mojom::ControllerServiceWorkerPurpose purpose) override {
NOTIMPLEMENTED();
}
void CloneForWorker(
mojom::ServiceWorkerContainerHostRequest request) override {
NOTIMPLEMENTED();
}
+ void Ping(PingCallback callback) override { NOTIMPLEMENTED(); }
mojom::ServiceWorkerContainerAssociatedPtr client_;
mojo::AssociatedBinding<mojom::ServiceWorkerContainerHost> binding_;
@@ -143,8 +143,6 @@ class EmbeddedWorkerInstanceTest : public testing::Test,
RecordEvent(DETACHED, old_status);
}
- bool OnMessageReceived(const IPC::Message&) override { return false; }
-
void SetUp() override {
helper_.reset(new EmbeddedWorkerTestHelper(base::FilePath()));
}
diff --git a/chromium/content/browser/service_worker/embedded_worker_registry.cc b/chromium/content/browser/service_worker/embedded_worker_registry.cc
index 16daab86fa5..c63e6333f45 100644
--- a/chromium/content/browser/service_worker/embedded_worker_registry.cc
+++ b/chromium/content/browser/service_worker/embedded_worker_registry.cc
@@ -12,7 +12,6 @@
#include "content/browser/service_worker/service_worker_context_core.h"
#include "content/browser/service_worker/service_worker_context_wrapper.h"
#include "content/browser/service_worker/service_worker_dispatcher_host.h"
-#include "content/common/service_worker/embedded_worker_messages.h"
#include "content/public/browser/browser_thread.h"
#include "ipc/ipc_message.h"
#include "ipc/ipc_sender.h"
@@ -44,28 +43,6 @@ std::unique_ptr<EmbeddedWorkerInstance> EmbeddedWorkerRegistry::CreateWorker(
return worker;
}
-bool EmbeddedWorkerRegistry::OnMessageReceived(const IPC::Message& message,
- int process_id) {
- // TODO(kinuko): Move all EmbeddedWorker message handling from
- // ServiceWorkerDispatcherHost.
-
- EmbeddedWorkerInstance* worker =
- GetWorkerForMessage(process_id, message.routing_id());
- if (!worker) {
- // Assume this is from a detached worker, return true to indicate we're
- // purposely handling the message as no-op.
- return true;
- }
- bool handled = worker->OnMessageReceived(message);
-
- // Assume an unhandled message for a stopping worker is because the message
- // was timed out and its handler removed prior to stopping.
- // We might be more precise and record timed out request ids, but some
- // cumbersome bookkeeping is needed and the IPC messaging will soon migrate
- // to Mojo anyway.
- return handled || worker->status() == EmbeddedWorkerStatus::STOPPING;
-}
-
void EmbeddedWorkerRegistry::Shutdown() {
for (WorkerInstanceMap::iterator it = worker_map_.begin();
it != worker_map_.end();
@@ -152,16 +129,4 @@ void EmbeddedWorkerRegistry::DetachWorker(int process_id,
lifetime_tracker_.StopTiming(embedded_worker_id);
}
-EmbeddedWorkerInstance* EmbeddedWorkerRegistry::GetWorkerForMessage(
- int process_id,
- int embedded_worker_id) {
- EmbeddedWorkerInstance* worker = GetWorker(embedded_worker_id);
- if (!worker || worker->process_id() != process_id) {
- UMA_HISTOGRAM_BOOLEAN("ServiceWorker.WorkerForMessageFound", false);
- return nullptr;
- }
- UMA_HISTOGRAM_BOOLEAN("ServiceWorker.WorkerForMessageFound", true);
- return worker;
-}
-
} // namespace content
diff --git a/chromium/content/browser/service_worker/embedded_worker_registry.h b/chromium/content/browser/service_worker/embedded_worker_registry.h
index deab4b367fd..c4e25c4b695 100644
--- a/chromium/content/browser/service_worker/embedded_worker_registry.h
+++ b/chromium/content/browser/service_worker/embedded_worker_registry.h
@@ -19,10 +19,6 @@
#include "content/common/content_export.h"
#include "content/common/service_worker/service_worker_status_code.h"
-namespace IPC {
-class Message;
-}
-
namespace content {
class EmbeddedWorkerInstance;
@@ -46,8 +42,6 @@ class CONTENT_EXPORT EmbeddedWorkerRegistry
const base::WeakPtr<ServiceWorkerContextCore>& context,
EmbeddedWorkerRegistry* old_registry);
- bool OnMessageReceived(const IPC::Message& message, int process_id);
-
// Creates and removes a new worker instance entry for bookkeeping.
// This doesn't actually start or stop the worker.
std::unique_ptr<EmbeddedWorkerInstance> CreateWorker(
@@ -101,9 +95,6 @@ class CONTENT_EXPORT EmbeddedWorkerRegistry
// cleanly stopped, e.g., because connection with the renderer was lost.
void DetachWorker(int process_id, int embedded_worker_id);
- EmbeddedWorkerInstance* GetWorkerForMessage(int process_id,
- int embedded_worker_id);
-
base::WeakPtr<ServiceWorkerContextCore> context_;
WorkerInstanceMap worker_map_;
diff --git a/chromium/content/browser/service_worker/embedded_worker_test_helper.cc b/chromium/content/browser/service_worker/embedded_worker_test_helper.cc
index a7a6575e0ee..963ff792cd5 100644
--- a/chromium/content/browser/service_worker/embedded_worker_test_helper.cc
+++ b/chromium/content/browser/service_worker/embedded_worker_test_helper.cc
@@ -12,7 +12,6 @@
#include "base/atomic_sequence_num.h"
#include "base/bind.h"
-#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/threading/thread_task_runner_handle.h"
@@ -26,7 +25,6 @@
#include "content/browser/service_worker/service_worker_test_utils.h"
#include "content/common/background_fetch/background_fetch_types.h"
#include "content/common/renderer.mojom.h"
-#include "content/common/service_worker/embedded_worker_messages.h"
#include "content/common/service_worker/service_worker_event_dispatcher.mojom.h"
#include "content/common/service_worker/service_worker_messages.h"
#include "content/common/service_worker/service_worker_utils.h"
@@ -39,7 +37,7 @@
#include "services/network/public/mojom/fetch_api.mojom.h"
#include "storage/common/blob_storage/blob_handle.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_event_status.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_event_status.mojom.h"
namespace content {
@@ -780,11 +778,6 @@ void EmbeddedWorkerTestHelper::SimulateWorkerStopped(int embedded_worker_id) {
}
}
-void EmbeddedWorkerTestHelper::SimulateSend(IPC::Message* message) {
- registry()->OnMessageReceived(*message, mock_render_process_id_);
- delete message;
-}
-
void EmbeddedWorkerTestHelper::OnStartWorkerStub(
mojom::EmbeddedWorkerStartParamsPtr params) {
EmbeddedWorkerInstance* worker =
diff --git a/chromium/content/browser/service_worker/embedded_worker_test_helper.h b/chromium/content/browser/service_worker/embedded_worker_test_helper.h
index 0a3369c66c7..c0cd7275d30 100644
--- a/chromium/content/browser/service_worker/embedded_worker_test_helper.h
+++ b/chromium/content/browser/service_worker/embedded_worker_test_helper.h
@@ -14,7 +14,6 @@
#include "base/callback.h"
#include "base/containers/hash_tables.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/weak_ptr.h"
#include "base/optional.h"
#include "base/time/time.h"
@@ -27,8 +26,8 @@
#include "ipc/ipc_test_sink.h"
#include "mojo/public/cpp/bindings/associated_binding.h"
#include "net/http/http_response_info.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_installed_scripts_manager.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_installed_scripts_manager.mojom.h"
#include "url/gurl.h"
class GURL;
@@ -275,7 +274,6 @@ class EmbeddedWorkerTestHelper : public IPC::Sender,
void SimulateWorkerScriptEvaluated(int embedded_worker_id, bool success);
void SimulateWorkerStarted(int embedded_worker_id);
void SimulateWorkerStopped(int embedded_worker_id);
- void SimulateSend(IPC::Message* message);
EmbeddedWorkerRegistry* registry();
diff --git a/chromium/content/browser/service_worker/payment_handler_support.h b/chromium/content/browser/service_worker/payment_handler_support.h
index 4e74d28c527..34ae62d2b71 100644
--- a/chromium/content/browser/service_worker/payment_handler_support.h
+++ b/chromium/content/browser/service_worker/payment_handler_support.h
@@ -6,7 +6,7 @@
#define CONTENT_BROWSER_SERVICE_WORKER_PAYMENT_HANDLER_SUPPORT_H_
#include "base/callback.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker.mojom.h"
class GURL;
diff --git a/chromium/content/browser/service_worker/service_worker_browsertest.cc b/chromium/content/browser/service_worker/service_worker_browsertest.cc
index 0d7a6c42b25..baf6eb5e6ab 100644
--- a/chromium/content/browser/service_worker/service_worker_browsertest.cc
+++ b/chromium/content/browser/service_worker/service_worker_browsertest.cc
@@ -14,7 +14,6 @@
#include "base/command_line.h"
#include "base/json/json_reader.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/metrics/statistics_recorder.h"
#include "base/run_loop.h"
@@ -25,6 +24,7 @@
#include "base/strings/utf_string_conversions.h"
#include "base/task_scheduler/post_task.h"
#include "base/task_scheduler/task_traits.h"
+#include "base/test/bind_test_util.h"
#include "base/test/scoped_feature_list.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
@@ -88,9 +88,9 @@
#include "storage/browser/blob/blob_data_snapshot.h"
#include "storage/browser/blob/blob_reader.h"
#include "storage/browser/blob/blob_storage_context.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_event_status.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_event_status.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
using blink::mojom::CacheStorageError;
@@ -98,8 +98,10 @@ namespace content {
namespace {
-// V8ScriptRunner::setCacheTimeStamp() stores 12 byte data (tag + timestamp).
-const int kV8CacheTimeStampDataSize = sizeof(unsigned) + sizeof(double);
+// V8ScriptRunner::setCacheTimeStamp() stores 16 byte data (marker + tag +
+// timestamp).
+const int kV8CacheTimeStampDataSize =
+ sizeof(uint32_t) + sizeof(uint32_t) + sizeof(double);
struct FetchResult {
ServiceWorkerStatusCode status;
@@ -108,26 +110,25 @@ struct FetchResult {
std::unique_ptr<storage::BlobDataHandle> blob_data_handle;
};
-void RunAndQuit(const base::Closure& closure,
- const base::Closure& quit,
+void RunAndQuit(base::OnceClosure closure,
+ base::OnceClosure quit,
base::SingleThreadTaskRunner* original_message_loop) {
- closure.Run();
- original_message_loop->PostTask(FROM_HERE, quit);
+ std::move(closure).Run();
+ original_message_loop->PostTask(FROM_HERE, std::move(quit));
}
-void RunOnIOThreadWithDelay(const base::Closure& closure,
- base::TimeDelta delay) {
+void RunOnIOThreadWithDelay(base::OnceClosure closure, base::TimeDelta delay) {
base::RunLoop run_loop;
BrowserThread::PostDelayedTask(
BrowserThread::IO, FROM_HERE,
- base::BindOnce(&RunAndQuit, closure, run_loop.QuitClosure(),
+ base::BindOnce(&RunAndQuit, std::move(closure), run_loop.QuitClosure(),
base::RetainedRef(base::ThreadTaskRunnerHandle::Get())),
delay);
run_loop.Run();
}
-void RunOnIOThread(const base::Closure& closure) {
- RunOnIOThreadWithDelay(closure, base::TimeDelta());
+void RunOnIOThread(base::OnceClosure closure) {
+ RunOnIOThreadWithDelay(std::move(closure), base::TimeDelta());
}
void RunOnIOThread(
@@ -138,8 +139,9 @@ void RunOnIOThread(
base::ThreadTaskRunnerHandle::Get().get(),
FROM_HERE,
run_loop.QuitClosure());
- BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
- base::BindOnce(closure, quit_on_original_thread));
+ BrowserThread::PostTask(
+ BrowserThread::IO, FROM_HERE,
+ base::BindOnce(closure, std::move(quit_on_original_thread)));
run_loop.Run();
}
@@ -181,7 +183,7 @@ void ReadResponseBody(std::string* body,
}
void ExpectResultAndRun(bool expected,
- const base::Closure& continuation,
+ base::RepeatingClosure continuation,
bool actual) {
EXPECT_EQ(expected, actual);
continuation.Run();
@@ -194,7 +196,8 @@ class WorkerActivatedObserver
explicit WorkerActivatedObserver(ServiceWorkerContextWrapper* context)
: context_(context) {}
void Init() {
- RunOnIOThread(base::Bind(&WorkerActivatedObserver::InitOnIOThread, this));
+ RunOnIOThread(
+ base::BindOnce(&WorkerActivatedObserver::InitOnIOThread, this));
}
// ServiceWorkerContextCoreObserver overrides.
void OnVersionStateChanged(int64_t version_id,
@@ -358,10 +361,10 @@ void CountScriptResources(
}
void StoreString(std::string* result,
- const base::Closure& callback,
+ base::OnceClosure callback,
const base::Value* value) {
value->GetAsString(result);
- callback.Run();
+ std::move(callback).Run();
}
int GetInt(const base::DictionaryValue& dict, base::StringPiece path) {
@@ -450,12 +453,13 @@ class ServiceWorkerBrowserTest : public ContentBrowserTest {
wrapper_ = static_cast<ServiceWorkerContextWrapper*>(
partition->GetServiceWorkerContext());
- RunOnIOThread(base::Bind(&self::SetUpOnIOThread, base::Unretained(this)));
+ RunOnIOThread(
+ base::BindOnce(&self::SetUpOnIOThread, base::Unretained(this)));
}
void TearDownOnMainThread() override {
RunOnIOThread(
- base::Bind(&self::TearDownOnIOThread, base::Unretained(this)));
+ base::BindOnce(&self::TearDownOnIOThread, base::Unretained(this)));
wrapper_ = nullptr;
}
@@ -510,7 +514,6 @@ class ConsoleListener : public EmbeddedWorkerInstance::Listener {
ASSERT_EQ(messages_.size(), expected_message_count);
}
- bool OnMessageReceived(const IPC::Message& message) override { return false; }
const std::vector<base::string16>& messages() const { return messages_; }
private:
@@ -587,8 +590,8 @@ class ServiceWorkerVersionBrowserTest : public ServiceWorkerBrowserTest {
void InstallTestHelper(const std::string& worker_url,
ServiceWorkerStatusCode expected_status) {
- RunOnIOThread(base::Bind(&self::SetUpRegistrationOnIOThread,
- base::Unretained(this), worker_url));
+ RunOnIOThread(base::BindOnce(&self::SetUpRegistrationOnIOThread,
+ base::Unretained(this), worker_url));
// Dispatch install on a worker.
ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_FAILED;
@@ -737,8 +740,9 @@ class ServiceWorkerVersionBrowserTest : public ServiceWorkerBrowserTest {
store_run_loop.Run();
ASSERT_EQ(expected_status, status);
- RunOnIOThread(base::Bind(&self::NotifyDoneInstallingRegistrationOnIOThread,
- base::Unretained(this), status));
+ RunOnIOThread(
+ base::BindOnce(&self::NotifyDoneInstallingRegistrationOnIOThread,
+ base::Unretained(this), status));
}
void FindRegistrationForId(int64_t id,
@@ -940,9 +944,9 @@ class ServiceWorkerVersionBrowserTest : public ServiceWorkerBrowserTest {
IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest, StartAndStop) {
StartServerAndNavigateToSetup();
- RunOnIOThread(base::Bind(&self::SetUpRegistrationOnIOThread,
- base::Unretained(this),
- "/service_worker/worker.js"));
+ RunOnIOThread(base::BindOnce(&self::SetUpRegistrationOnIOThread,
+ base::Unretained(this),
+ "/service_worker/worker.js"));
// Start a worker.
ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_FAILED;
@@ -963,12 +967,14 @@ IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest, StartAndStop) {
stop_run_loop.Run();
}
+// TODO(lunalu): remove this test when blink side use counter is removed
+// (crbug.com/811948).
IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest,
DropCountsOnBlinkUseCounter) {
StartServerAndNavigateToSetup();
- RunOnIOThread(base::Bind(&self::SetUpRegistrationOnIOThread,
- base::Unretained(this),
- "/service_worker/worker.js"));
+ RunOnIOThread(base::BindOnce(&self::SetUpRegistrationOnIOThread,
+ base::Unretained(this),
+ "/service_worker/worker.js"));
// Start a worker.
ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_FAILED;
base::RunLoop start_run_loop;
@@ -981,7 +987,7 @@ IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest,
// Expect no PageVisits count.
EXPECT_EQ(nullptr, base::StatisticsRecorder::FindHistogram(
- "Blink.UseCounter.Features"));
+ "Blink.UseCounter.Features_Legacy"));
// Stop the worker.
base::RunLoop stop_run_loop;
@@ -992,14 +998,14 @@ IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest,
stop_run_loop.Run();
// Expect no PageVisits count.
EXPECT_EQ(nullptr, base::StatisticsRecorder::FindHistogram(
- "Blink.UseCounter.Features"));
+ "Blink.UseCounter.Features_Legacy"));
}
IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest, StartNotFound) {
StartServerAndNavigateToSetup();
- RunOnIOThread(base::Bind(&self::SetUpRegistrationOnIOThread,
- base::Unretained(this),
- "/service_worker/nonexistent.js"));
+ RunOnIOThread(base::BindOnce(&self::SetUpRegistrationOnIOThread,
+ base::Unretained(this),
+ "/service_worker/nonexistent.js"));
// Start a worker for nonexistent URL.
StartWorker(SERVICE_WORKER_ERROR_NETWORK);
@@ -1015,9 +1021,9 @@ IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest,
MAYBE_ReadResourceFailure) {
StartServerAndNavigateToSetup();
// Create a registration.
- RunOnIOThread(base::Bind(&self::SetUpRegistrationOnIOThread,
- base::Unretained(this),
- "/service_worker/worker.js"));
+ RunOnIOThread(base::BindOnce(&self::SetUpRegistrationOnIOThread,
+ base::Unretained(this),
+ "/service_worker/worker.js"));
version_->set_fetch_handler_existence(
ServiceWorkerVersion::FetchHandlerExistence::EXISTS);
version_->SetStatus(ServiceWorkerVersion::ACTIVATED);
@@ -1037,8 +1043,8 @@ IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest,
// The registration should be deleted from storage since the broken worker was
// the stored one.
- RunOnIOThread(base::Bind(&self::RemoveLiveRegistrationOnIOThread,
- base::Unretained(this), registration_->id()));
+ RunOnIOThread(base::BindOnce(&self::RemoveLiveRegistrationOnIOThread,
+ base::Unretained(this), registration_->id()));
FindRegistrationForId(registration_->id(),
registration_->pattern().GetOrigin(),
SERVICE_WORKER_ERROR_NOT_FOUND);
@@ -1054,16 +1060,16 @@ IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest,
// Give the version a controllee.
RunOnIOThread(
- base::Bind(&self::AddControlleeOnIOThread, base::Unretained(this)));
+ base::BindOnce(&self::AddControlleeOnIOThread, base::Unretained(this)));
// Add a non-existent resource to the version.
version_->script_cache_map()->resource_map_[version_->script_url()] =
ServiceWorkerDatabase::ResourceRecord(30, version_->script_url(), 100);
// Make a waiting version and store it.
- RunOnIOThread(base::Bind(&self::AddWaitingWorkerOnIOThread,
- base::Unretained(this),
- "/service_worker/worker.js"));
+ RunOnIOThread(base::BindOnce(&self::AddWaitingWorkerOnIOThread,
+ base::Unretained(this),
+ "/service_worker/worker.js"));
std::vector<ServiceWorkerDatabase::ResourceRecord> records = {
ServiceWorkerDatabase::ResourceRecord(31, version_->script_url(), 100)};
registration_->waiting_version()->script_cache_map()->SetResources(records);
@@ -1078,8 +1084,8 @@ IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest,
// The registration should still be in storage since the waiting worker was
// the stored one.
- RunOnIOThread(base::Bind(&self::RemoveLiveRegistrationOnIOThread,
- base::Unretained(this), registration_->id()));
+ RunOnIOThread(base::BindOnce(&self::RemoveLiveRegistrationOnIOThread,
+ base::Unretained(this), registration_->id()));
FindRegistrationForId(registration_->id(),
registration_->pattern().GetOrigin(),
SERVICE_WORKER_OK);
@@ -1149,14 +1155,14 @@ IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest,
IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest,
InstallWithWaitUntil_RejectConsoleMessage) {
StartServerAndNavigateToSetup();
- RunOnIOThread(base::Bind(&self::SetUpRegistrationOnIOThread,
- base::Unretained(this),
- "/service_worker/worker_install_rejected.js"));
+ RunOnIOThread(base::BindOnce(&self::SetUpRegistrationOnIOThread,
+ base::Unretained(this),
+ "/service_worker/worker_install_rejected.js"));
ConsoleListener console_listener;
- RunOnIOThread(base::Bind(&EmbeddedWorkerInstance::AddListener,
- base::Unretained(version_->embedded_worker()),
- &console_listener));
+ RunOnIOThread(base::BindOnce(&EmbeddedWorkerInstance::AddListener,
+ base::Unretained(version_->embedded_worker()),
+ &console_listener));
// Dispatch install on a worker.
ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_FAILED;
@@ -1173,9 +1179,9 @@ IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest,
console_listener.WaitForConsoleMessages(1);
ASSERT_NE(base::string16::npos,
console_listener.messages()[0].find(expected));
- RunOnIOThread(base::Bind(&EmbeddedWorkerInstance::RemoveListener,
- base::Unretained(version_->embedded_worker()),
- &console_listener));
+ RunOnIOThread(base::BindOnce(&EmbeddedWorkerInstance::RemoveListener,
+ base::Unretained(version_->embedded_worker()),
+ &console_listener));
}
class WaitForLoaded : public EmbeddedWorkerInstance::Listener {
@@ -1186,7 +1192,6 @@ class WaitForLoaded : public EmbeddedWorkerInstance::Listener {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, quit_);
}
- bool OnMessageReceived(const IPC::Message& message) override { return false; }
private:
base::Closure quit_;
@@ -1194,26 +1199,26 @@ class WaitForLoaded : public EmbeddedWorkerInstance::Listener {
IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest, TimeoutStartingWorker) {
StartServerAndNavigateToSetup();
- RunOnIOThread(base::Bind(&self::SetUpRegistrationOnIOThread,
- base::Unretained(this),
- "/service_worker/while_true_worker.js"));
+ RunOnIOThread(base::BindOnce(&self::SetUpRegistrationOnIOThread,
+ base::Unretained(this),
+ "/service_worker/while_true_worker.js"));
// Start a worker, waiting until the script is loaded.
ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_FAILED;
base::RunLoop start_run_loop;
base::RunLoop load_run_loop;
WaitForLoaded wait_for_load(load_run_loop.QuitClosure());
- RunOnIOThread(base::Bind(&EmbeddedWorkerInstance::AddListener,
- base::Unretained(version_->embedded_worker()),
- &wait_for_load));
+ RunOnIOThread(base::BindOnce(&EmbeddedWorkerInstance::AddListener,
+ base::Unretained(version_->embedded_worker()),
+ &wait_for_load));
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&self::StartOnIOThread, base::Unretained(this),
start_run_loop.QuitClosure(), &status));
load_run_loop.Run();
- RunOnIOThread(base::Bind(&EmbeddedWorkerInstance::RemoveListener,
- base::Unretained(version_->embedded_worker()),
- &wait_for_load));
+ RunOnIOThread(base::BindOnce(&EmbeddedWorkerInstance::RemoveListener,
+ base::Unretained(version_->embedded_worker()),
+ &wait_for_load));
// The script has loaded but start has not completed yet.
ASSERT_EQ(SERVICE_WORKER_ERROR_FAILED, status);
@@ -1222,7 +1227,7 @@ IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest, TimeoutStartingWorker) {
// Simulate execution timeout. Use a delay to prevent killing the worker
// before it's started execution.
RunOnIOThreadWithDelay(
- base::Bind(&self::TimeoutWorkerOnIOThread, base::Unretained(this)),
+ base::BindOnce(&self::TimeoutWorkerOnIOThread, base::Unretained(this)),
base::TimeDelta::FromMilliseconds(100));
start_run_loop.Run();
@@ -1231,9 +1236,9 @@ IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest, TimeoutStartingWorker) {
IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest, TimeoutWorkerInEvent) {
StartServerAndNavigateToSetup();
- RunOnIOThread(base::Bind(&self::SetUpRegistrationOnIOThread,
- base::Unretained(this),
- "/service_worker/while_true_in_install_worker.js"));
+ RunOnIOThread(
+ base::BindOnce(&self::SetUpRegistrationOnIOThread, base::Unretained(this),
+ "/service_worker/while_true_in_install_worker.js"));
// Start a worker.
ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_FAILED;
@@ -1255,7 +1260,7 @@ IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest, TimeoutWorkerInEvent) {
// Simulate execution timeout. Use a delay to prevent killing the worker
// before it's started execution.
RunOnIOThreadWithDelay(
- base::Bind(&self::TimeoutWorkerOnIOThread, base::Unretained(this)),
+ base::BindOnce(&self::TimeoutWorkerOnIOThread, base::Unretained(this)),
base::TimeDelta::FromMilliseconds(100));
install_run_loop.Run();
@@ -1283,9 +1288,8 @@ IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest, FetchEvent_Response) {
EXPECT_EQ(expected_headers, response.headers);
std::string body;
- RunOnIOThread(
- base::Bind(&ReadResponseBody,
- &body, base::Owned(blob_data_handle.release())));
+ RunOnIOThread(base::BindOnce(&ReadResponseBody, &body,
+ base::Owned(blob_data_handle.release())));
EXPECT_EQ("This resource is gone. Gone, gone, gone.", body);
}
@@ -1333,9 +1337,9 @@ IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest,
SERVICE_WORKER_OK);
ConsoleListener console_listener;
- RunOnIOThread(base::Bind(&EmbeddedWorkerInstance::AddListener,
- base::Unretained(version_->embedded_worker()),
- &console_listener));
+ RunOnIOThread(base::BindOnce(&EmbeddedWorkerInstance::AddListener,
+ base::Unretained(version_->embedded_worker()),
+ &console_listener));
FetchOnRegisteredWorker(&result, &response, &blob_data_handle);
const base::string16 expected1 = base::ASCIIToUTF16(
@@ -1346,9 +1350,9 @@ IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest,
ASSERT_NE(base::string16::npos,
console_listener.messages()[0].find(expected1));
ASSERT_EQ(0u, console_listener.messages()[1].find(expected2));
- RunOnIOThread(base::Bind(&EmbeddedWorkerInstance::RemoveListener,
- base::Unretained(version_->embedded_worker()),
- &console_listener));
+ RunOnIOThread(base::BindOnce(&EmbeddedWorkerInstance::RemoveListener,
+ base::Unretained(version_->embedded_worker()),
+ &console_listener));
ASSERT_EQ(ServiceWorkerFetchDispatcher::FetchEventResult::kGotResponse,
result);
@@ -1609,7 +1613,7 @@ class ServiceWorkerNavigationPreloadTest : public ServiceWorkerBrowserTest {
content::ResourceContext* resource_context,
OnHeaderProcessedCallback callback) {
DCHECK_EQ(kNavigationPreloadHeaderName, header);
- callback.Run(HeaderInterceptorResult::KILL);
+ std::move(callback).Run(HeaderInterceptorResult::KILL);
}
void SetupForNavigationPreloadTest(const GURL& scope,
@@ -2401,10 +2405,9 @@ IN_PROC_BROWSER_TEST_F(ServiceWorkerBrowserTest, ImportsBustMemcache) {
const base::string16 kOKTitle(base::ASCIIToUTF16("OK"));
const base::string16 kFailTitle(base::ASCIIToUTF16("FAIL"));
- RunOnIOThread(
- base::Bind(&CreateLongLivedResourceInterceptors,
- embedded_test_server()->GetURL(kScriptUrl),
- embedded_test_server()->GetURL(kImportUrl)));
+ RunOnIOThread(base::BindOnce(&CreateLongLivedResourceInterceptors,
+ embedded_test_server()->GetURL(kScriptUrl),
+ embedded_test_server()->GetURL(kImportUrl)));
TitleWatcher title_watcher(shell()->web_contents(), kOKTitle);
title_watcher.AlsoWaitForTitle(kFailTitle);
@@ -2415,11 +2418,9 @@ IN_PROC_BROWSER_TEST_F(ServiceWorkerBrowserTest, ImportsBustMemcache) {
// Verify the number of resources in the implicit script cache is correct.
const int kExpectedNumResources = 2;
int num_resources = 0;
- RunOnIOThread(
- base::Bind(&CountScriptResources,
- base::Unretained(wrapper()),
- embedded_test_server()->GetURL(kScopeUrl),
- &num_resources));
+ RunOnIOThread(base::BindOnce(
+ &CountScriptResources, base::Unretained(wrapper()),
+ embedded_test_server()->GetURL(kScopeUrl), &num_resources));
EXPECT_EQ(kExpectedNumResources, num_resources);
}
@@ -2441,23 +2442,23 @@ class StopObserver : public ServiceWorkerVersion::Listener {
IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest, RendererCrash) {
// Start a worker.
StartServerAndNavigateToSetup();
- RunOnIOThread(base::Bind(&self::SetUpRegistrationOnIOThread,
- base::Unretained(this),
- "/service_worker/worker.js"));
+ RunOnIOThread(base::BindOnce(&self::SetUpRegistrationOnIOThread,
+ base::Unretained(this),
+ "/service_worker/worker.js"));
StartWorker(SERVICE_WORKER_OK);
// Crash the renderer process. The version should stop.
base::RunLoop run_loop;
StopObserver observer(run_loop.QuitClosure());
- RunOnIOThread(base::Bind(&ServiceWorkerVersion::AddListener,
- base::Unretained(version_.get()), &observer));
+ RunOnIOThread(base::BindOnce(&ServiceWorkerVersion::AddListener,
+ base::Unretained(version_.get()), &observer));
shell()->web_contents()->GetMainFrame()->GetProcess()->Shutdown(
- content::RESULT_CODE_KILLED, false /* wait */);
+ content::RESULT_CODE_KILLED);
run_loop.Run();
EXPECT_EQ(EmbeddedWorkerStatus::STOPPED, version_->running_status());
- RunOnIOThread(base::Bind(&ServiceWorkerVersion::RemoveListener,
- base::Unretained(version_.get()), &observer));
+ RunOnIOThread(base::BindOnce(&ServiceWorkerVersion::RemoveListener,
+ base::Unretained(version_.get()), &observer));
}
class ServiceWorkerBlackBoxBrowserTest : public ServiceWorkerBrowserTest {
@@ -2486,13 +2487,7 @@ class ServiceWorkerBlackBoxBrowserTest : public ServiceWorkerBrowserTest {
};
static int CountRenderProcessHosts() {
- int result = 0;
- for (RenderProcessHost::iterator iter(RenderProcessHost::AllHostsIterator());
- !iter.IsAtEnd();
- iter.Advance()) {
- result++;
- }
- return result;
+ return RenderProcessHost::GetCurrentRenderProcessCountForTesting();
}
IN_PROC_BROWSER_TEST_F(ServiceWorkerBlackBoxBrowserTest, Registration) {
@@ -2629,6 +2624,10 @@ class ServiceWorkerVersionBrowserV8CacheTest
public ServiceWorkerVersion::Listener {
public:
using self = ServiceWorkerVersionBrowserV8CacheTest;
+ ServiceWorkerVersionBrowserV8CacheTest() {
+ scoped_feature_list_.InitAndDisableFeature(
+ features::kServiceWorkerScriptFullCodeCache);
+ }
~ServiceWorkerVersionBrowserV8CacheTest() override {
if (version_)
version_->RemoveListener(this);
@@ -2652,13 +2651,16 @@ class ServiceWorkerVersionBrowserV8CacheTest
base::Closure cache_updated_closure_;
size_t metadata_size_ = 0;
+
+ private:
+ base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserV8CacheTest, Restart) {
StartServerAndNavigateToSetup();
- RunOnIOThread(base::Bind(&self::SetUpRegistrationAndListenerOnIOThread,
- base::Unretained(this),
- "/service_worker/worker.js"));
+ RunOnIOThread(base::BindOnce(&self::SetUpRegistrationAndListenerOnIOThread,
+ base::Unretained(this),
+ "/service_worker/worker.js"));
{
base::RunLoop cached_metadata_run_loop;
cache_updated_closure_ = cached_metadata_run_loop.QuitClosure();
@@ -2732,9 +2734,9 @@ class ServiceWorkerVersionBrowserV8FullCodeCacheTest
IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserV8FullCodeCacheTest,
FullCode) {
StartServerAndNavigateToSetup();
- RunOnIOThread(base::Bind(&self::SetUpRegistrationAndListenerOnIOThread,
- base::Unretained(this),
- "/service_worker/worker.js"));
+ RunOnIOThread(base::BindOnce(&self::SetUpRegistrationAndListenerOnIOThread,
+ base::Unretained(this),
+ "/service_worker/worker.js"));
base::RunLoop cached_metadata_run_loop;
cache_updated_closure_ = cached_metadata_run_loop.QuitClosure();
@@ -2818,46 +2820,17 @@ class CacheStorageSideDataSizeChecker
const base::Closure& continuation,
CacheStorageCacheHandle cache_handle,
CacheStorageError error,
- std::unique_ptr<ServiceWorkerResponse> response,
- std::unique_ptr<storage::BlobDataHandle> blob_data_handle) {
+ std::unique_ptr<ServiceWorkerResponse> response) {
ASSERT_EQ(CacheStorageError::kSuccess, error);
- blob_data_handle_ = std::move(blob_data_handle);
- blob_reader_ = blob_data_handle_->CreateReader();
- const storage::BlobReader::Status status = blob_reader_->CalculateSize(
- base::BindOnce(&self::OnBlobReaderCalculateSizeCallback, this, result,
- continuation));
-
- ASSERT_NE(storage::BlobReader::Status::NET_ERROR, status);
- if (status == storage::BlobReader::Status::DONE)
- OnBlobReaderCalculateSizeCallback(result, continuation, net::OK);
- }
-
- void OnBlobReaderCalculateSizeCallback(int* result,
- const base::Closure& continuation,
- int size_result) {
- ASSERT_EQ(net::OK, size_result);
- if (!blob_reader_->has_side_data()) {
- blob_reader_ = nullptr;
- continuation.Run();
- return;
- }
- const storage::BlobReader::Status status = blob_reader_->ReadSideData(
- base::Bind(&self::OnBlobReaderReadSideDataCallback, this, result,
- continuation));
- ASSERT_NE(storage::BlobReader::Status::NET_ERROR, status);
- if (status == storage::BlobReader::Status::DONE) {
- OnBlobReaderReadSideDataCallback(result, continuation,
- storage::BlobReader::Status::DONE);
- }
- }
-
- void OnBlobReaderReadSideDataCallback(int* result,
- const base::Closure& continuation,
- storage::BlobReader::Status status) {
- ASSERT_NE(storage::BlobReader::Status::NET_ERROR, status);
- *result = blob_reader_->side_data()->size();
- blob_reader_ = nullptr;
- continuation.Run();
+ ASSERT_TRUE(response->blob);
+ auto blob = response->blob;
+ response->blob->get()->ReadSideData(base::BindLambdaForTesting(
+ [blob, result,
+ continuation](const base::Optional<std::vector<uint8_t>>& data) {
+ if (data)
+ *result = data->size();
+ continuation.Run();
+ }));
}
CacheStorageContextImpl* cache_storage_context_;
@@ -2865,8 +2838,6 @@ class CacheStorageSideDataSizeChecker
const GURL origin_;
const std::string cache_name_;
const GURL url_;
- std::unique_ptr<storage::BlobDataHandle> blob_data_handle_;
- std::unique_ptr<storage::BlobReader> blob_reader_;
DISALLOW_COPY_AND_ASSIGN(CacheStorageSideDataSizeChecker);
};
diff --git a/chromium/content/browser/service_worker/service_worker_cache_writer.cc b/chromium/content/browser/service_worker/service_worker_cache_writer.cc
index dceaa6117d7..b58e6db84b0 100644
--- a/chromium/content/browser/service_worker/service_worker_cache_writer.cc
+++ b/chromium/content/browser/service_worker/service_worker_cache_writer.cc
@@ -433,7 +433,7 @@ int ServiceWorkerCacheWriter::ReadInfoHelper(
net::CompletionCallback run_callback = base::Bind(
&ServiceWorkerCacheWriter::AsyncDoLoop, weak_factory_.GetWeakPtr());
scoped_refptr<AsyncOnlyCompletionCallbackAdaptor> adaptor(
- new AsyncOnlyCompletionCallbackAdaptor(run_callback));
+ new AsyncOnlyCompletionCallbackAdaptor(std::move(run_callback)));
reader->ReadInfo(
buf, base::BindOnce(&AsyncOnlyCompletionCallbackAdaptor::WrappedCallback,
adaptor));
@@ -448,7 +448,7 @@ int ServiceWorkerCacheWriter::ReadDataHelper(
net::CompletionCallback run_callback = base::Bind(
&ServiceWorkerCacheWriter::AsyncDoLoop, weak_factory_.GetWeakPtr());
scoped_refptr<AsyncOnlyCompletionCallbackAdaptor> adaptor(
- new AsyncOnlyCompletionCallbackAdaptor(run_callback));
+ new AsyncOnlyCompletionCallbackAdaptor(std::move(run_callback)));
reader->ReadData(
buf, buf_len,
base::BindOnce(&AsyncOnlyCompletionCallbackAdaptor::WrappedCallback,
@@ -464,7 +464,7 @@ int ServiceWorkerCacheWriter::WriteInfoHelper(
net::CompletionCallback run_callback = base::Bind(
&ServiceWorkerCacheWriter::AsyncDoLoop, weak_factory_.GetWeakPtr());
scoped_refptr<AsyncOnlyCompletionCallbackAdaptor> adaptor(
- new AsyncOnlyCompletionCallbackAdaptor(run_callback));
+ new AsyncOnlyCompletionCallbackAdaptor(std::move(run_callback)));
writer->WriteInfo(
buf, base::BindOnce(&AsyncOnlyCompletionCallbackAdaptor::WrappedCallback,
adaptor));
@@ -479,7 +479,7 @@ int ServiceWorkerCacheWriter::WriteDataHelper(
net::CompletionCallback run_callback = base::Bind(
&ServiceWorkerCacheWriter::AsyncDoLoop, weak_factory_.GetWeakPtr());
scoped_refptr<AsyncOnlyCompletionCallbackAdaptor> adaptor(
- new AsyncOnlyCompletionCallbackAdaptor(run_callback));
+ new AsyncOnlyCompletionCallbackAdaptor(std::move(run_callback)));
writer->WriteData(
buf, buf_len,
base::BindOnce(&AsyncOnlyCompletionCallbackAdaptor::WrappedCallback,
diff --git a/chromium/content/browser/service_worker/service_worker_client_utils.cc b/chromium/content/browser/service_worker/service_worker_client_utils.cc
index fdf5de6526d..b27c2d353f7 100644
--- a/chromium/content/browser/service_worker/service_worker_client_utils.cc
+++ b/chromium/content/browser/service_worker/service_worker_client_utils.cc
@@ -9,7 +9,6 @@
#include "base/location.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/browser/frame_host/frame_tree_node.h"
@@ -25,13 +24,15 @@
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/page_navigator.h"
+#include "content/public/browser/payment_app_provider.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/common/child_process_host.h"
#include "services/network/public/mojom/request_context_frame_type.mojom.h"
-#include "third_party/WebKit/public/mojom/page/page_visibility_state.mojom.h"
+#include "third_party/blink/public/mojom/page/page_visibility_state.mojom.h"
+#include "ui/base/mojo/window_open_disposition.mojom.h"
#include "url/gurl.h"
namespace content {
@@ -160,7 +161,9 @@ blink::mojom::ServiceWorkerClientInfoPtr FocusOnUI(
}
// This is only called for main frame navigations in OpenWindowOnUI().
-void DidOpenURLOnUI(OpenURLCallback callback, WebContents* web_contents) {
+void DidOpenURLOnUI(WindowType type,
+ OpenURLCallback callback,
+ WebContents* web_contents) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!web_contents) {
@@ -183,6 +186,12 @@ void DidOpenURLOnUI(OpenURLCallback callback, WebContents* web_contents) {
new OpenURLObserver(web_contents,
rfhi->frame_tree_node()->frame_tree_node_id(),
std::move(callback));
+
+ if (type == WindowType::PAYMENT_HANDLER_WINDOW) {
+ // Set the opened web_contents to payment app provider to manage its life
+ // cycle.
+ PaymentAppProvider::GetInstance()->SetOpenedWindow(web_contents);
+ }
}
void OpenWindowOnUI(
@@ -190,7 +199,7 @@ void OpenWindowOnUI(
const GURL& script_url,
int worker_process_id,
const scoped_refptr<ServiceWorkerContextWrapper>& context_wrapper,
- WindowOpenDisposition disposition,
+ WindowType type,
OpenURLCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
@@ -216,13 +225,16 @@ void OpenWindowOnUI(
url,
Referrer::SanitizeForRequest(
url, Referrer(script_url, blink::kWebReferrerPolicyDefault)),
- disposition, ui::PAGE_TRANSITION_AUTO_TOPLEVEL,
- true /* is_renderer_initiated */);
+ type == WindowType::PAYMENT_HANDLER_WINDOW
+ ? WindowOpenDisposition::NEW_POPUP
+ : WindowOpenDisposition::NEW_FOREGROUND_TAB,
+ ui::PAGE_TRANSITION_AUTO_TOPLEVEL, true /* is_renderer_initiated */);
+ params.open_app_window_if_possible = type == WindowType::NEW_TAB_WINDOW;
GetContentClient()->browser()->OpenURL(
browser_context, params,
base::AdaptCallbackForRepeating(
- base::BindOnce(&DidOpenURLOnUI, std::move(callback))));
+ base::BindOnce(&DidOpenURLOnUI, type, std::move(callback))));
}
void NavigateClientOnUI(const GURL& url,
@@ -446,14 +458,14 @@ void OpenWindow(const GURL& url,
const GURL& script_url,
int worker_process_id,
const base::WeakPtr<ServiceWorkerContextCore>& context,
- WindowOpenDisposition disposition,
+ WindowType type,
NavigationCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::BindOnce(
&OpenWindowOnUI, url, script_url, worker_process_id,
- base::WrapRefCounted(context->wrapper()), disposition,
+ base::WrapRefCounted(context->wrapper()), type,
base::BindOnce(&DidNavigate, context, script_url.GetOrigin(),
std::move(callback))));
}
diff --git a/chromium/content/browser/service_worker/service_worker_client_utils.h b/chromium/content/browser/service_worker/service_worker_client_utils.h
index 74d5cefff90..93ac4aba752 100644
--- a/chromium/content/browser/service_worker/service_worker_client_utils.h
+++ b/chromium/content/browser/service_worker/service_worker_client_utils.h
@@ -11,8 +11,7 @@
#include "base/callback.h"
#include "base/memory/weak_ptr.h"
#include "content/common/service_worker/service_worker_status_code.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_client.mojom.h"
-#include "ui/base/mojo/window_open_disposition.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_client.mojom.h"
class GURL;
@@ -34,18 +33,28 @@ using ServiceWorkerClientPtrs =
using ClientsCallback =
base::OnceCallback<void(std::unique_ptr<ServiceWorkerClientPtrs> clients)>;
+// The type of an opened window.
+enum class WindowType {
+ NEW_TAB_WINDOW = 0,
+ PAYMENT_HANDLER_WINDOW,
+};
+
// Focuses the window client associated with |provider_host|. |callback| is
// called with the client information on completion.
void FocusWindowClient(ServiceWorkerProviderHost* provider_host,
ClientCallback callback);
// Opens a new window and navigates it to |url|. |callback| is called with the
-// window's client information on completion.
+// window's client information on completion. If |type| is NEW_TAB_WINDOW, we
+// will open a new app window, if there is an app installed that has |url| in
+// its scope. What an "installed app" is depends on the embedder of content. In
+// Chrome's case, it is an installed Progressive Web App. If there is no such
+// app, we will open a new foreground tab instead.
void OpenWindow(const GURL& url,
const GURL& script_url,
int worker_process_id,
const base::WeakPtr<ServiceWorkerContextCore>& context,
- WindowOpenDisposition disposition,
+ WindowType type,
NavigationCallback callback);
// Navigates the client specified by |process_id| and |frame_id| to |url|.
diff --git a/chromium/content/browser/service_worker/service_worker_content_settings_proxy_impl.h b/chromium/content/browser/service_worker/service_worker_content_settings_proxy_impl.h
index ac195dff926..d519ce707d8 100644
--- a/chromium/content/browser/service_worker/service_worker_content_settings_proxy_impl.h
+++ b/chromium/content/browser/service_worker/service_worker_content_settings_proxy_impl.h
@@ -9,7 +9,7 @@
#include "content/browser/service_worker/service_worker_context_wrapper.h"
#include "content/common/content_export.h"
#include "mojo/public/cpp/bindings/binding.h"
-#include "third_party/WebKit/public/web/worker_content_settings_proxy.mojom.h"
+#include "third_party/blink/public/web/worker_content_settings_proxy.mojom.h"
#include "url/origin.h"
namespace content {
diff --git a/chromium/content/browser/service_worker/service_worker_context_core.cc b/chromium/content/browser/service_worker/service_worker_context_core.cc
index a7ce9eae6a9..d5b665ca761 100644
--- a/chromium/content/browser/service_worker/service_worker_context_core.cc
+++ b/chromium/content/browser/service_worker/service_worker_context_core.cc
@@ -39,8 +39,8 @@
#include "net/http/http_response_headers.h"
#include "net/http/http_response_info.h"
#include "storage/browser/quota/quota_manager_proxy.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_provider_type.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_provider_type.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
#include "url/gurl.h"
namespace content {
@@ -89,7 +89,10 @@ void SuccessReportingCallback(
bool IsSameOriginClientProviderHost(const GURL& origin,
ServiceWorkerProviderHost* host) {
return host->IsProviderForClient() &&
- host->document_url().GetOrigin() == origin;
+ host->document_url().GetOrigin() == origin &&
+ // Don't expose "reserved" clients (clients that are not yet execution
+ // ready) to the Clients API.
+ host->is_execution_ready();
}
bool IsSameOriginWindowProviderHost(const GURL& origin,
@@ -150,7 +153,7 @@ class ClearAllServiceWorkersHelper
for (const auto& registration_info : registrations) {
context->UnregisterServiceWorker(
registration_info.pattern,
- base::Bind(&ClearAllServiceWorkersHelper::OnResult, this));
+ base::BindOnce(&ClearAllServiceWorkersHelper::OnResult, this));
}
}
@@ -340,8 +343,7 @@ ServiceWorkerDispatcherHost* ServiceWorkerContextCore::GetDispatcherHost(
}
void ServiceWorkerContextCore::RemoveDispatcherHost(int process_id) {
- // Temporary CHECK for debugging https://crbug.com/750267.
- CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
+ DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
// TODO(falken) Try to remove this call. It should be unnecessary because
// provider hosts remove themselves when their Mojo connection to the renderer
// is destroyed. But if we don't remove the hosts immediately here, collisions
@@ -353,8 +355,7 @@ void ServiceWorkerContextCore::RemoveDispatcherHost(int process_id) {
void ServiceWorkerContextCore::AddProviderHost(
std::unique_ptr<ServiceWorkerProviderHost> host) {
- // Temporary CHECK for debugging https://crbug.com/750267.
- CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
+ DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
int process_id = host->process_id();
int provider_id = host->provider_id();
ProviderMap* map = GetProviderMapForProcess(process_id);
@@ -368,6 +369,7 @@ void ServiceWorkerContextCore::AddProviderHost(
ServiceWorkerProviderHost* ServiceWorkerContextCore::GetProviderHost(
int process_id,
int provider_id) {
+ DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
ProviderMap* map = GetProviderMapForProcess(process_id);
if (!map)
return nullptr;
@@ -376,8 +378,7 @@ ServiceWorkerProviderHost* ServiceWorkerContextCore::GetProviderHost(
void ServiceWorkerContextCore::RemoveProviderHost(
int process_id, int provider_id) {
- // Temporary CHECK for debugging https://crbug.com/750267.
- CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
+ DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
ProviderMap* map = GetProviderMapForProcess(process_id);
DCHECK(map);
map->Remove(provider_id);
@@ -385,38 +386,28 @@ void ServiceWorkerContextCore::RemoveProviderHost(
void ServiceWorkerContextCore::RemoveAllProviderHostsForProcess(
int process_id) {
- // Temporary CHECK for debugging https://crbug.com/750267.
- CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
+ DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
if (providers_->Lookup(process_id))
providers_->Remove(process_id);
}
std::unique_ptr<ServiceWorkerContextCore::ProviderHostIterator>
-ServiceWorkerContextCore::GetProviderHostIterator() {
- // Temporary CHECK for debugging https://crbug.com/750267.
- CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
- return base::WrapUnique(new ProviderHostIterator(
- providers_.get(), ProviderHostIterator::ProviderHostPredicate()));
-}
-
-std::unique_ptr<ServiceWorkerContextCore::ProviderHostIterator>
ServiceWorkerContextCore::GetClientProviderHostIterator(const GURL& origin) {
- // Temporary CHECK for debugging https://crbug.com/750267.
- CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
+ DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
return base::WrapUnique(new ProviderHostIterator(
providers_.get(), base::Bind(IsSameOriginClientProviderHost, origin)));
}
void ServiceWorkerContextCore::HasMainFrameProviderHost(
const GURL& origin,
- const BoolCallback& callback) const {
+ BoolCallback callback) const {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
ProviderHostIterator provider_host_iterator(
providers_.get(), base::Bind(IsSameOriginWindowProviderHost, origin));
if (provider_host_iterator.IsAtEnd()) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
- FROM_HERE, base::BindOnce(callback, false));
+ FROM_HERE, base::BindOnce(std::move(callback), false));
return;
}
@@ -433,9 +424,8 @@ void ServiceWorkerContextCore::HasMainFrameProviderHost(
BrowserThread::PostTaskAndReplyWithResult(
BrowserThread::UI, FROM_HERE,
- base::Bind(&FrameListContainsMainFrameOnUI,
- base::Passed(std::move(render_frames))),
- callback);
+ base::BindOnce(&FrameListContainsMainFrameOnUI, std::move(render_frames)),
+ std::move(callback));
}
void ServiceWorkerContextCore::RegisterProviderHostByClientID(
@@ -462,13 +452,13 @@ ServiceWorkerProviderHost* ServiceWorkerContextCore::GetProviderHostByClientID(
void ServiceWorkerContextCore::RegisterServiceWorker(
const GURL& script_url,
const blink::mojom::ServiceWorkerRegistrationOptions& options,
- const RegistrationCallback& callback) {
+ RegistrationCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
was_service_worker_registered_ = true;
job_coordinator_->Register(
script_url, options,
- base::Bind(&ServiceWorkerContextCore::RegistrationComplete, AsWeakPtr(),
- options.scope, callback));
+ base::BindOnce(&ServiceWorkerContextCore::RegistrationComplete,
+ AsWeakPtr(), options.scope, std::move(callback)));
}
void ServiceWorkerContextCore::UpdateServiceWorker(
@@ -482,29 +472,25 @@ void ServiceWorkerContextCore::UpdateServiceWorker(
ServiceWorkerRegistration* registration,
bool force_bypass_cache,
bool skip_script_comparison,
- const UpdateCallback& callback) {
+ UpdateCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
- job_coordinator_->Update(registration, force_bypass_cache,
- skip_script_comparison,
- base::Bind(&ServiceWorkerContextCore::UpdateComplete,
- AsWeakPtr(), callback));
+ job_coordinator_->Update(
+ registration, force_bypass_cache, skip_script_comparison,
+ base::BindOnce(&ServiceWorkerContextCore::UpdateComplete, AsWeakPtr(),
+ std::move(callback)));
}
void ServiceWorkerContextCore::UnregisterServiceWorker(
const GURL& pattern,
- const UnregistrationCallback& callback) {
+ UnregistrationCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
job_coordinator_->Unregister(
- pattern,
- base::Bind(&ServiceWorkerContextCore::UnregistrationComplete,
- AsWeakPtr(),
- pattern,
- callback));
+ pattern, base::BindOnce(&ServiceWorkerContextCore::UnregistrationComplete,
+ AsWeakPtr(), pattern, std::move(callback)));
}
-void ServiceWorkerContextCore::DeleteForOrigin(
- const GURL& origin,
- base::OnceCallback<void(ServiceWorkerStatusCode)> callback) {
+void ServiceWorkerContextCore::DeleteForOrigin(const GURL& origin,
+ StatusCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
storage()->GetRegistrationsForOrigin(
origin,
@@ -545,26 +531,25 @@ void ServiceWorkerContextCore::DidGetRegistrationsForDeleteForOrigin(
ServiceWorkerContextCore::ProviderMap*
ServiceWorkerContextCore::GetProviderMapForProcess(int process_id) {
- // Temporary CHECK for debugging https://crbug.com/750267.
- CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
+ DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
return providers_->Lookup(process_id);
}
void ServiceWorkerContextCore::RegistrationComplete(
const GURL& pattern,
- const ServiceWorkerContextCore::RegistrationCallback& callback,
+ ServiceWorkerContextCore::RegistrationCallback callback,
ServiceWorkerStatusCode status,
const std::string& status_message,
ServiceWorkerRegistration* registration) {
if (status != SERVICE_WORKER_OK) {
DCHECK(!registration);
- callback.Run(status, status_message,
- blink::mojom::kInvalidServiceWorkerRegistrationId);
+ std::move(callback).Run(status, status_message,
+ blink::mojom::kInvalidServiceWorkerRegistrationId);
return;
}
DCHECK(registration);
- callback.Run(status, status_message, registration->id());
+ std::move(callback).Run(status, status_message, registration->id());
// TODO(falken): At this point the registration promise is resolved, but we
// haven't persisted anything to storage yet. So we should either call
// OnRegistrationStored somewhere else or change its name.
@@ -576,27 +561,27 @@ void ServiceWorkerContextCore::RegistrationComplete(
}
void ServiceWorkerContextCore::UpdateComplete(
- const ServiceWorkerContextCore::UpdateCallback& callback,
+ ServiceWorkerContextCore::UpdateCallback callback,
ServiceWorkerStatusCode status,
const std::string& status_message,
ServiceWorkerRegistration* registration) {
if (status != SERVICE_WORKER_OK) {
DCHECK(!registration);
- callback.Run(status, status_message,
- blink::mojom::kInvalidServiceWorkerRegistrationId);
+ std::move(callback).Run(status, status_message,
+ blink::mojom::kInvalidServiceWorkerRegistrationId);
return;
}
DCHECK(registration);
- callback.Run(status, status_message, registration->id());
+ std::move(callback).Run(status, status_message, registration->id());
}
void ServiceWorkerContextCore::UnregistrationComplete(
const GURL& pattern,
- const ServiceWorkerContextCore::UnregistrationCallback& callback,
+ ServiceWorkerContextCore::UnregistrationCallback callback,
int64_t registration_id,
ServiceWorkerStatusCode status) {
- callback.Run(status);
+ std::move(callback).Run(status);
if (status == SERVICE_WORKER_OK && observer_list_.get()) {
observer_list_->Notify(
FROM_HERE, &ServiceWorkerContextCoreObserver::OnRegistrationDeleted,
@@ -721,10 +706,9 @@ void ServiceWorkerContextCore::ScheduleDeleteAndStartOver() const {
wrapper_));
}
-void ServiceWorkerContextCore::DeleteAndStartOver(
- const StatusCallback& callback) {
+void ServiceWorkerContextCore::DeleteAndStartOver(StatusCallback callback) {
job_coordinator_->AbortAll();
- storage_->DeleteAndStartOver(callback);
+ storage_->DeleteAndStartOver(std::move(callback));
}
void ServiceWorkerContextCore::ClearAllServiceWorkersForTest(
@@ -748,8 +732,7 @@ void ServiceWorkerContextCore::CheckHasServiceWorker(
storage()->FindRegistrationForDocument(
url, base::BindOnce(&ServiceWorkerContextCore::
DidFindRegistrationForCheckHasServiceWorker,
- AsWeakPtr(), other_url,
- base::Passed(std::move(callback))));
+ AsWeakPtr(), other_url, std::move(callback)));
}
void ServiceWorkerContextCore::UpdateVersionFailureCount(
diff --git a/chromium/content/browser/service_worker/service_worker_context_core.h b/chromium/content/browser/service_worker/service_worker_context_core.h
index 892c3950941..18389af21fb 100644
--- a/chromium/content/browser/service_worker/service_worker_context_core.h
+++ b/chromium/content/browser/service_worker/service_worker_context_core.h
@@ -25,7 +25,7 @@
#include "content/browser/service_worker/service_worker_storage.h"
#include "content/common/content_export.h"
#include "content/public/browser/service_worker_context.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
class GURL;
@@ -59,17 +59,19 @@ class URLLoaderFactoryGetter;
class CONTENT_EXPORT ServiceWorkerContextCore
: public ServiceWorkerVersion::Listener {
public:
- using BoolCallback = base::Callback<void(bool)>;
- using StatusCallback = base::Callback<void(ServiceWorkerStatusCode status)>;
+ using BoolCallback = base::OnceCallback<void(bool)>;
+ using StatusCallback =
+ base::OnceCallback<void(ServiceWorkerStatusCode status)>;
using RegistrationCallback =
- base::Callback<void(ServiceWorkerStatusCode status,
- const std::string& status_message,
- int64_t registration_id)>;
- using UpdateCallback = base::Callback<void(ServiceWorkerStatusCode status,
- const std::string& status_message,
- int64_t registration_id)>;
+ base::OnceCallback<void(ServiceWorkerStatusCode status,
+ const std::string& status_message,
+ int64_t registration_id)>;
+ using UpdateCallback =
+ base::OnceCallback<void(ServiceWorkerStatusCode status,
+ const std::string& status_message,
+ int64_t registration_id)>;
using UnregistrationCallback =
- base::Callback<void(ServiceWorkerStatusCode status)>;
+ base::OnceCallback<void(ServiceWorkerStatusCode status)>;
using ProviderMap = base::IDMap<std::unique_ptr<ServiceWorkerProviderHost>>;
using ProcessToProviderMap = base::IDMap<std::unique_ptr<ProviderMap>>;
@@ -172,11 +174,11 @@ class CONTENT_EXPORT ServiceWorkerContextCore
ServiceWorkerProviderHost* GetProviderHost(int process_id, int provider_id);
void RemoveProviderHost(int process_id, int provider_id);
void RemoveAllProviderHostsForProcess(int process_id);
- std::unique_ptr<ProviderHostIterator> GetProviderHostIterator();
- // Returns a ProviderHost iterator for all ServiceWorker clients for
- // the |origin|. This only returns ProviderHosts that are of CONTROLLEE
- // and belong to the |origin|.
+ // Returns a ProviderHost iterator for all service worker clients for the
+ // |origin|. This only returns clients that are execution ready (i.e., for
+ // windows, the navigation has been committed and for workers, the final
+ // response after redirects has been delivered).
std::unique_ptr<ProviderHostIterator> GetClientProviderHostIterator(
const GURL& origin);
@@ -184,7 +186,7 @@ class CONTENT_EXPORT ServiceWorkerContextCore
// blink::mojom::ServiceWorkerProviderType::kForWindow which is a main
// (top-level) frame.
void HasMainFrameProviderHost(const GURL& origin,
- const BoolCallback& callback) const;
+ BoolCallback callback) const;
// Maintains a map from Client UUID to ProviderHost.
// (Note: instead of maintaining 2 maps we might be able to uniformly use
@@ -199,16 +201,14 @@ class CONTENT_EXPORT ServiceWorkerContextCore
void RegisterServiceWorker(
const GURL& script_url,
const blink::mojom::ServiceWorkerRegistrationOptions& options,
- const RegistrationCallback& callback);
+ RegistrationCallback callback);
void UnregisterServiceWorker(const GURL& pattern,
- const UnregistrationCallback& callback);
+ UnregistrationCallback callback);
// Callback is called after all deletions occured. The status code is
// SERVICE_WORKER_OK if all succeed, or SERVICE_WORKER_FAILED
// if any did not succeed.
- void DeleteForOrigin(
- const GURL& origin,
- base::OnceCallback<void(ServiceWorkerStatusCode)> callback);
+ void DeleteForOrigin(const GURL& origin, StatusCallback callback);
// Updates the service worker. If |force_bypass_cache| is true or 24 hours
// have passed since the last update, bypasses the browser cache.
@@ -217,7 +217,7 @@ class CONTENT_EXPORT ServiceWorkerContextCore
void UpdateServiceWorker(ServiceWorkerRegistration* registration,
bool force_bypass_cache,
bool skip_script_comparison,
- const UpdateCallback& callback);
+ UpdateCallback callback);
// Used in DevTools to update the service worker registrations without
// consulting the browser cache while loading the controlled page. The
@@ -269,7 +269,7 @@ class CONTENT_EXPORT ServiceWorkerContextCore
// Deletes all files on disk and restarts the system. This leaves the system
// in a disabled state until it's done.
- void DeleteAndStartOver(const StatusCallback& callback);
+ void DeleteAndStartOver(StatusCallback callback);
void ClearAllServiceWorkersForTest(base::OnceClosure callback);
@@ -310,18 +310,18 @@ class CONTENT_EXPORT ServiceWorkerContextCore
ProviderMap* GetProviderMapForProcess(int process_id);
void RegistrationComplete(const GURL& pattern,
- const RegistrationCallback& callback,
+ RegistrationCallback callback,
ServiceWorkerStatusCode status,
const std::string& status_message,
ServiceWorkerRegistration* registration);
- void UpdateComplete(const UpdateCallback& callback,
+ void UpdateComplete(UpdateCallback callback,
ServiceWorkerStatusCode status,
const std::string& status_message,
ServiceWorkerRegistration* registration);
void UnregistrationComplete(const GURL& pattern,
- const UnregistrationCallback& callback,
+ UnregistrationCallback callback,
int64_t registration_id,
ServiceWorkerStatusCode status);
@@ -333,11 +333,11 @@ class CONTENT_EXPORT ServiceWorkerContextCore
void DidFindRegistrationForCheckHasServiceWorker(
const GURL& other_url,
- const ServiceWorkerContext::CheckHasServiceWorkerCallback callback,
+ ServiceWorkerContext::CheckHasServiceWorkerCallback callback,
ServiceWorkerStatusCode status,
scoped_refptr<ServiceWorkerRegistration> registration);
void OnRegistrationFinishedForCheckHasServiceWorker(
- const ServiceWorkerContext::CheckHasServiceWorkerCallback callback,
+ ServiceWorkerContext::CheckHasServiceWorkerCallback callback,
scoped_refptr<ServiceWorkerRegistration> registration);
// It's safe to store a raw pointer instead of a scoped_refptr to |wrapper_|
diff --git a/chromium/content/browser/service_worker/service_worker_context_core_observer.h b/chromium/content/browser/service_worker/service_worker_context_core_observer.h
index f664aa2ba34..1453739b55a 100644
--- a/chromium/content/browser/service_worker/service_worker_context_core_observer.h
+++ b/chromium/content/browser/service_worker/service_worker_context_core_observer.h
@@ -12,7 +12,7 @@
#include "base/time/time.h"
#include "content/browser/service_worker/service_worker_info.h"
#include "content/browser/service_worker/service_worker_version.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_provider_type.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_provider_type.mojom.h"
#include "url/gurl.h"
namespace content {
diff --git a/chromium/content/browser/service_worker/service_worker_context_request_handler.cc b/chromium/content/browser/service_worker/service_worker_context_request_handler.cc
index 8c21ad6e5be..eaf2f2b0759 100644
--- a/chromium/content/browser/service_worker/service_worker_context_request_handler.cc
+++ b/chromium/content/browser/service_worker/service_worker_context_request_handler.cc
@@ -58,7 +58,8 @@ ServiceWorkerContextRequestHandler::ServiceWorkerContextRequestHandler(
blob_storage_context,
resource_type),
version_(provider_host_->running_hosted_version()) {
- DCHECK(provider_host_->IsHostToRunningServiceWorker());
+ DCHECK(provider_host_->IsProviderForServiceWorker());
+ DCHECK(version_);
}
ServiceWorkerContextRequestHandler::~ServiceWorkerContextRequestHandler() {
diff --git a/chromium/content/browser/service_worker/service_worker_context_request_handler_unittest.cc b/chromium/content/browser/service_worker/service_worker_context_request_handler_unittest.cc
index d9a6ff06d64..c7e1e2194f7 100644
--- a/chromium/content/browser/service_worker/service_worker_context_request_handler_unittest.cc
+++ b/chromium/content/browser/service_worker/service_worker_context_request_handler_unittest.cc
@@ -11,7 +11,6 @@
#include "base/run_loop.h"
#include "base/test/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
-#include "content/browser/browser_thread_impl.h"
#include "content/browser/service_worker/embedded_worker_test_helper.h"
#include "content/browser/service_worker/service_worker_context_core.h"
#include "content/browser/service_worker/service_worker_provider_host.h"
@@ -32,7 +31,7 @@
#include "services/network/public/mojom/request_context_frame_type.mojom.h"
#include "storage/browser/blob/blob_storage_context.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
diff --git a/chromium/content/browser/service_worker/service_worker_context_unittest.cc b/chromium/content/browser/service_worker/service_worker_context_unittest.cc
index 10f0068b562..06decdcd47b 100644
--- a/chromium/content/browser/service_worker/service_worker_context_unittest.cc
+++ b/chromium/content/browser/service_worker/service_worker_context_unittest.cc
@@ -8,11 +8,9 @@
#include "base/files/scoped_temp_dir.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/time/time.h"
-#include "content/browser/browser_thread_impl.h"
#include "content/browser/service_worker/embedded_worker_registry.h"
#include "content/browser/service_worker/embedded_worker_test_helper.h"
#include "content/browser/service_worker/service_worker_context_core.h"
@@ -23,13 +21,12 @@
#include "content/browser/service_worker/service_worker_storage.h"
#include "content/browser/service_worker/service_worker_test_utils.h"
#include "content/browser/service_worker/service_worker_version.h"
-#include "content/common/service_worker/embedded_worker_messages.h"
#include "content/common/service_worker/service_worker_messages.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "content/public/test/test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_event_status.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_event_status.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
@@ -48,7 +45,7 @@ void SaveResponseCallback(bool* called,
ServiceWorkerContextCore::RegistrationCallback MakeRegisteredCallback(
bool* called,
int64_t* store_registration_id) {
- return base::Bind(&SaveResponseCallback, called, store_registration_id);
+ return base::BindOnce(&SaveResponseCallback, called, store_registration_id);
}
void CallCompletedCallback(bool* called, ServiceWorkerStatusCode) {
@@ -57,7 +54,7 @@ void CallCompletedCallback(bool* called, ServiceWorkerStatusCode) {
ServiceWorkerContextCore::UnregistrationCallback MakeUnregisteredCallback(
bool* called) {
- return base::Bind(&CallCompletedCallback, called);
+ return base::BindOnce(&CallCompletedCallback, called);
}
void ExpectRegisteredWorkers(
@@ -645,26 +642,13 @@ TEST_F(ServiceWorkerContextTest, ProviderHostIterator) {
ServiceWorkerProviderHost* host1_raw = host1.get();
ServiceWorkerProviderHost* host2_raw = host2.get();
ServiceWorkerProviderHost* host3_raw = host3.get();
- ServiceWorkerProviderHost* host4_raw = host4.get();
context()->AddProviderHost(std::move(host1));
context()->AddProviderHost(std::move(host2));
context()->AddProviderHost(std::move(host3));
context()->AddProviderHost(std::move(host4));
- // Iterate over all provider hosts.
- std::set<ServiceWorkerProviderHost*> results;
- for (auto it = context()->GetProviderHostIterator(); !it->IsAtEnd();
- it->Advance()) {
- results.insert(it->GetProviderHost());
- }
- EXPECT_EQ(4u, results.size());
- EXPECT_TRUE(ContainsKey(results, host1_raw));
- EXPECT_TRUE(ContainsKey(results, host2_raw));
- EXPECT_TRUE(ContainsKey(results, host3_raw));
- EXPECT_TRUE(ContainsKey(results, host4_raw));
-
// Iterate over the client provider hosts that belong to kOrigin1.
- results.clear();
+ std::set<ServiceWorkerProviderHost*> results;
for (auto it = context()->GetClientProviderHostIterator(kOrigin1);
!it->IsAtEnd(); it->Advance()) {
results.insert(it->GetProviderHost());
diff --git a/chromium/content/browser/service_worker/service_worker_context_watcher.cc b/chromium/content/browser/service_worker/service_worker_context_watcher.cc
index 08006a83a07..983547fe8ed 100644
--- a/chromium/content/browser/service_worker/service_worker_context_watcher.cc
+++ b/chromium/content/browser/service_worker/service_worker_context_watcher.cc
@@ -7,14 +7,13 @@
#include <utility>
#include "base/bind.h"
-#include "base/memory/ptr_util.h"
#include "content/browser/service_worker/embedded_worker_status.h"
#include "content/browser/service_worker/service_worker_context_wrapper.h"
#include "content/browser/service_worker/service_worker_version.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/console_message_level.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
#include "url/gurl.h"
namespace content {
diff --git a/chromium/content/browser/service_worker/service_worker_context_watcher.h b/chromium/content/browser/service_worker/service_worker_context_watcher.h
index 2aede25980b..aa432522b51 100644
--- a/chromium/content/browser/service_worker/service_worker_context_watcher.h
+++ b/chromium/content/browser/service_worker/service_worker_context_watcher.h
@@ -14,7 +14,7 @@
#include "content/browser/service_worker/service_worker_context_core_observer.h"
#include "content/browser/service_worker/service_worker_info.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_provider_type.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_provider_type.mojom.h"
namespace content {
diff --git a/chromium/content/browser/service_worker/service_worker_context_watcher_unittest.cc b/chromium/content/browser/service_worker/service_worker_context_watcher_unittest.cc
index c9bb895faef..3bc8afdbd8a 100644
--- a/chromium/content/browser/service_worker/service_worker_context_watcher_unittest.cc
+++ b/chromium/content/browser/service_worker/service_worker_context_watcher_unittest.cc
@@ -11,7 +11,7 @@
#include "content/browser/service_worker/service_worker_context_wrapper.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
@@ -146,7 +146,7 @@ class ServiceWorkerContextWatcherTest : public testing::Test {
int64_t registration_id = blink::mojom::kInvalidServiceWorkerRegistrationId;
context()->RegisterServiceWorker(
script_url, options,
- base::Bind(&DidRegisterServiceWorker, &registration_id));
+ base::BindOnce(&DidRegisterServiceWorker, &registration_id));
base::RunLoop().RunUntilIdle();
return registration_id;
}
@@ -154,7 +154,7 @@ class ServiceWorkerContextWatcherTest : public testing::Test {
ServiceWorkerStatusCode UnregisterServiceWorker(const GURL& scope) {
ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_FAILED;
context()->UnregisterServiceWorker(
- scope, base::Bind(&DidUnregisterServiceWorker, &status));
+ scope, base::BindOnce(&DidUnregisterServiceWorker, &status));
base::RunLoop().RunUntilIdle();
return status;
}
diff --git a/chromium/content/browser/service_worker/service_worker_context_wrapper.cc b/chromium/content/browser/service_worker/service_worker_context_wrapper.cc
index 3af66c5a20f..241193f74fd 100644
--- a/chromium/content/browser/service_worker/service_worker_context_wrapper.cc
+++ b/chromium/content/browser/service_worker/service_worker_context_wrapper.cc
@@ -32,7 +32,7 @@
#include "net/base/url_util.h"
#include "storage/browser/quota/quota_manager_proxy.h"
#include "storage/browser/quota/special_storage_policy.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
@@ -42,15 +42,15 @@ typedef std::set<std::string> HeaderNameSet;
base::LazyInstance<HeaderNameSet>::DestructorAtExit g_excluded_header_name_set =
LAZY_INSTANCE_INITIALIZER;
-void WorkerStarted(const ServiceWorkerContextWrapper::StatusCallback& callback,
+void WorkerStarted(ServiceWorkerContextWrapper::StatusCallback callback,
ServiceWorkerStatusCode status) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
- base::BindOnce(callback, status));
+ base::BindOnce(std::move(callback), status));
}
void StartActiveWorkerOnIO(
- const ServiceWorkerContextWrapper::StatusCallback& callback,
+ ServiceWorkerContextWrapper::StatusCallback callback,
ServiceWorkerStatusCode status,
scoped_refptr<ServiceWorkerRegistration> registration) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
@@ -60,12 +60,12 @@ void StartActiveWorkerOnIO(
// |registration| is 1, it will be deleted after WorkerStarted is called.
registration->active_version()->StartWorker(
ServiceWorkerMetrics::EventType::UNKNOWN,
- base::BindOnce(WorkerStarted, callback));
+ base::BindOnce(WorkerStarted, std::move(callback)));
return;
}
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
- base::BindOnce(callback, SERVICE_WORKER_ERROR_NOT_FOUND));
+ base::BindOnce(std::move(callback), SERVICE_WORKER_ERROR_NOT_FOUND));
}
void SkipWaitingWorkerOnIO(
@@ -224,8 +224,8 @@ void ServiceWorkerContextWrapper::DeleteAndStartOver() {
// here.
return;
}
- context_core_->DeleteAndStartOver(
- base::Bind(&ServiceWorkerContextWrapper::DidDeleteAndStartOver, this));
+ context_core_->DeleteAndStartOver(base::BindOnce(
+ &ServiceWorkerContextWrapper::DidDeleteAndStartOver, this));
}
StoragePartitionImpl* ServiceWorkerContextWrapper::storage_partition() const {
@@ -281,7 +281,7 @@ void ServiceWorkerContextWrapper::RegisterServiceWorker(
net::SimplifyUrlForRequest(options.scope), options.update_via_cache);
context()->RegisterServiceWorker(
net::SimplifyUrlForRequest(script_url), options_to_pass,
- base::Bind(&FinishRegistrationOnIO, base::Passed(std::move(callback))));
+ base::BindOnce(&FinishRegistrationOnIO, std::move(callback)));
}
void ServiceWorkerContextWrapper::UnregisterServiceWorker(
@@ -302,7 +302,7 @@ void ServiceWorkerContextWrapper::UnregisterServiceWorker(
context()->UnregisterServiceWorker(
net::SimplifyUrlForRequest(pattern),
- base::Bind(&FinishUnregistrationOnIO, base::Passed(std::move(callback))));
+ base::BindOnce(&FinishUnregistrationOnIO, std::move(callback)));
}
bool ServiceWorkerContextWrapper::StartingExternalRequest(
@@ -509,14 +509,14 @@ ServiceWorkerContextWrapper::GetAllLiveVersionInfo() {
void ServiceWorkerContextWrapper::HasMainFrameProviderHost(
const GURL& origin,
- const BoolCallback& callback) const {
+ BoolCallback callback) const {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!context_core_) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
- FROM_HERE, base::BindOnce(callback, false));
+ FROM_HERE, base::BindOnce(std::move(callback), false));
return;
}
- context_core_->HasMainFrameProviderHost(origin, callback);
+ context_core_->HasMainFrameProviderHost(origin, std::move(callback));
}
std::unique_ptr<std::vector<std::pair<int, int>>>
@@ -668,42 +668,46 @@ void ServiceWorkerContextWrapper::StoreRegistrationUserData(
int64_t registration_id,
const GURL& origin,
const std::vector<std::pair<std::string, std::string>>& key_value_pairs,
- const StatusCallback& callback) {
+ StatusCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!context_core_) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
- FROM_HERE, base::BindOnce(callback, SERVICE_WORKER_ERROR_ABORT));
+ FROM_HERE,
+ base::BindOnce(std::move(callback), SERVICE_WORKER_ERROR_ABORT));
return;
}
context_core_->storage()->StoreUserData(registration_id, origin.GetOrigin(),
- key_value_pairs, callback);
+ key_value_pairs, std::move(callback));
}
void ServiceWorkerContextWrapper::ClearRegistrationUserData(
int64_t registration_id,
const std::vector<std::string>& keys,
- const StatusCallback& callback) {
+ StatusCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!context_core_) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
- FROM_HERE, base::BindOnce(callback, SERVICE_WORKER_ERROR_ABORT));
+ FROM_HERE,
+ base::BindOnce(std::move(callback), SERVICE_WORKER_ERROR_ABORT));
return;
}
- context_core_->storage()->ClearUserData(registration_id, keys, callback);
+ context_core_->storage()->ClearUserData(registration_id, keys,
+ std::move(callback));
}
void ServiceWorkerContextWrapper::ClearRegistrationUserDataByKeyPrefixes(
int64_t registration_id,
const std::vector<std::string>& key_prefixes,
- const StatusCallback& callback) {
+ StatusCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!context_core_) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
- FROM_HERE, base::BindOnce(callback, SERVICE_WORKER_ERROR_ABORT));
+ FROM_HERE,
+ base::BindOnce(std::move(callback), SERVICE_WORKER_ERROR_ABORT));
return;
}
- context_core_->storage()->ClearUserDataByKeyPrefixes(registration_id,
- key_prefixes, callback);
+ context_core_->storage()->ClearUserDataByKeyPrefixes(
+ registration_id, key_prefixes, std::move(callback));
}
void ServiceWorkerContextWrapper::GetUserDataForAllRegistrations(
@@ -738,25 +742,24 @@ void ServiceWorkerContextWrapper::GetUserDataForAllRegistrationsByKeyPrefix(
key_prefix, std::move(callback));
}
-void ServiceWorkerContextWrapper::StartServiceWorker(
- const GURL& pattern,
- const StatusCallback& callback) {
+void ServiceWorkerContextWrapper::StartServiceWorker(const GURL& pattern,
+ StatusCallback callback) {
if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&ServiceWorkerContextWrapper::StartServiceWorker, this,
- pattern, callback));
+ pattern, std::move(callback)));
return;
}
if (!context_core_) {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
- base::BindOnce(callback, SERVICE_WORKER_ERROR_ABORT));
+ base::BindOnce(std::move(callback), SERVICE_WORKER_ERROR_ABORT));
return;
}
context_core_->storage()->FindRegistrationForPattern(
net::SimplifyUrlForRequest(pattern),
- base::BindOnce(&StartActiveWorkerOnIO, callback));
+ base::BindOnce(&StartActiveWorkerOnIO, std::move(callback)));
}
void ServiceWorkerContextWrapper::SkipWaitingWorker(const GURL& pattern) {
@@ -814,6 +817,16 @@ void ServiceWorkerContextWrapper::RemoveObserver(
core_observer_list_->RemoveObserver(observer);
}
+base::WeakPtr<ServiceWorkerProviderHost>
+ServiceWorkerContextWrapper::PreCreateHostForSharedWorker(
+ int process_id,
+ mojom::ServiceWorkerProviderInfoForSharedWorkerPtr* out_provider_info) {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+
+ return ServiceWorkerProviderHost::PreCreateForSharedWorker(
+ context()->AsWeakPtr(), process_id, out_provider_info);
+}
+
ServiceWorkerContextWrapper::~ServiceWorkerContextWrapper() {
// Explicitly remove this object as an observer to avoid use-after-frees in
// tests where this object is not guaranteed to outlive the
diff --git a/chromium/content/browser/service_worker/service_worker_context_wrapper.h b/chromium/content/browser/service_worker/service_worker_context_wrapper.h
index 3dedf308040..96ec90d9a1c 100644
--- a/chromium/content/browser/service_worker/service_worker_context_wrapper.h
+++ b/chromium/content/browser/service_worker/service_worker_context_wrapper.h
@@ -48,8 +48,8 @@ class CONTENT_EXPORT ServiceWorkerContextWrapper
public ServiceWorkerContextCoreObserver,
public base::RefCountedThreadSafe<ServiceWorkerContextWrapper> {
public:
- using StatusCallback = base::Callback<void(ServiceWorkerStatusCode)>;
- using BoolCallback = base::Callback<void(bool)>;
+ using StatusCallback = base::OnceCallback<void(ServiceWorkerStatusCode)>;
+ using BoolCallback = base::OnceCallback<void(bool)>;
using FindRegistrationCallback =
ServiceWorkerStorage::FindRegistrationCallback;
using GetRegistrationsInfosCallback =
@@ -140,7 +140,7 @@ class CONTENT_EXPORT ServiceWorkerContextWrapper
// Must be called from the IO thread.
void HasMainFrameProviderHost(const GURL& origin,
- const BoolCallback& callback) const;
+ BoolCallback callback) const;
// Returns all render process ids and frame ids for the given |origin|.
std::unique_ptr<
@@ -224,14 +224,14 @@ class CONTENT_EXPORT ServiceWorkerContextWrapper
int64_t registration_id,
const GURL& origin,
const std::vector<std::pair<std::string, std::string>>& key_value_pairs,
- const StatusCallback& callback);
+ StatusCallback callback);
void ClearRegistrationUserData(int64_t registration_id,
const std::vector<std::string>& keys,
- const StatusCallback& callback);
+ StatusCallback callback);
void ClearRegistrationUserDataByKeyPrefixes(
int64_t registration_id,
const std::vector<std::string>& key_prefixes,
- const StatusCallback& callback);
+ StatusCallback callback);
void GetUserDataForAllRegistrations(
const std::string& key,
GetUserDataForAllRegistrationsCallback callback);
@@ -241,7 +241,7 @@ class CONTENT_EXPORT ServiceWorkerContextWrapper
// This function can be called from any thread, but the callback will always
// be called on the UI thread.
- void StartServiceWorker(const GURL& pattern, const StatusCallback& callback);
+ void StartServiceWorker(const GURL& pattern, StatusCallback callback);
// These methods can be called from any thread.
void SkipWaitingWorker(const GURL& pattern);
@@ -254,6 +254,17 @@ class CONTENT_EXPORT ServiceWorkerContextWrapper
bool is_incognito() const { return is_incognito_; }
+ // S13nServiceWorker:
+ // Used for starting a shared worker. Returns a provider host for the shared
+ // worker and fills |out_provider_info| with info to send to the renderer to
+ // connect to the host. The host stays alive as long as this info stays alive
+ // (namely, as long as |out_provider_info->host_ptr_info| stays alive).
+ //
+ // Must be called on the IO thread.
+ base::WeakPtr<ServiceWorkerProviderHost> PreCreateHostForSharedWorker(
+ int process_id,
+ mojom::ServiceWorkerProviderInfoForSharedWorkerPtr* out_provider_info);
+
private:
friend class BackgroundSyncManagerTest;
friend class base::RefCountedThreadSafe<ServiceWorkerContextWrapper>;
diff --git a/chromium/content/browser/service_worker/service_worker_controllee_request_handler.cc b/chromium/content/browser/service_worker/service_worker_controllee_request_handler.cc
index 2ed0c353cad..ea569859aef 100644
--- a/chromium/content/browser/service_worker/service_worker_controllee_request_handler.cc
+++ b/chromium/content/browser/service_worker/service_worker_controllee_request_handler.cc
@@ -232,7 +232,7 @@ void ServiceWorkerControlleeRequestHandler::MaybeCreateLoader(
resource_request.site_for_cookies);
if (url_job_->ShouldFallbackToNetwork()) {
- // We're falling back to the next URLLoaderRequestHandler, forward
+ // We're falling back to the next NavigationLoaderInterceptor, forward
// the request and clear job now.
url_job_->FallbackToNetwork();
ClearJob();
@@ -271,7 +271,7 @@ ServiceWorkerControlleeRequestHandler::MaybeCreateSubresourceLoaderParams() {
controller_info->object_info = provider_host_->GetOrCreateServiceWorkerHandle(
provider_host_->controller());
params.controller_service_worker_info = std::move(controller_info);
- return params;
+ return base::Optional<SubresourceLoaderParams>(std::move(params));
}
void ServiceWorkerControlleeRequestHandler::PrepareForMainResource(
@@ -288,7 +288,7 @@ void ServiceWorkerControlleeRequestHandler::PrepareForMainResource(
// in redirect case, unassociate it now.
provider_host_->DisassociateRegistration();
- // Also prevent a registrater job for establishing an association to a new
+ // Also prevent a register job from establishing an association to a new
// registration while we're finding an existing registration.
provider_host_->SetAllowAssociation(false);
@@ -350,14 +350,13 @@ void ServiceWorkerControlleeRequestHandler::
context_->UpdateServiceWorker(
registration.get(), true /* force_bypass_cache */,
true /* skip_script_comparison */,
- base::Bind(&self::DidUpdateRegistration, weak_factory_.GetWeakPtr(),
- registration));
+ base::BindOnce(&self::DidUpdateRegistration, weak_factory_.GetWeakPtr(),
+ registration));
return;
}
- // Initiate activation of a waiting version.
- // Usually a register job initiates activation but that
- // doesn't happen if the browser exits prior to activation
+ // Initiate activation of a waiting version. Usually a register job initiates
+ // activation but that doesn't happen if the browser exits prior to activation
// having occurred. This check handles that case.
if (registration->waiting_version())
registration->ActivateWaitingVersionWhenReady();
diff --git a/chromium/content/browser/service_worker/service_worker_controllee_request_handler.h b/chromium/content/browser/service_worker/service_worker_controllee_request_handler.h
index 5b874a5755f..f5b750685e3 100644
--- a/chromium/content/browser/service_worker/service_worker_controllee_request_handler.h
+++ b/chromium/content/browser/service_worker/service_worker_controllee_request_handler.h
@@ -76,7 +76,7 @@ class CONTENT_EXPORT ServiceWorkerControlleeRequestHandler
// This could get called multiple times during the lifetime in redirect
// cases. (In fallback-to-network cases we basically forward the request
// to the request to the next request handler)
- // URLLoaderRequestHandler overrides:
+ // NavigationLoaderInterceptor overrides:
void MaybeCreateLoader(const network::ResourceRequest& request,
ResourceContext* resource_context,
LoaderCallback callback) override;
diff --git a/chromium/content/browser/service_worker/service_worker_controllee_request_handler_unittest.cc b/chromium/content/browser/service_worker/service_worker_controllee_request_handler_unittest.cc
index 177dfa75b78..5974fee450c 100644
--- a/chromium/content/browser/service_worker/service_worker_controllee_request_handler_unittest.cc
+++ b/chromium/content/browser/service_worker/service_worker_controllee_request_handler_unittest.cc
@@ -12,7 +12,6 @@
#include "base/logging.h"
#include "base/run_loop.h"
#include "components/offline_pages/buildflags/buildflags.h"
-#include "content/browser/browser_thread_impl.h"
#include "content/browser/service_worker/embedded_worker_test_helper.h"
#include "content/browser/service_worker/service_worker_context_core.h"
#include "content/browser/service_worker/service_worker_provider_host.h"
@@ -34,7 +33,7 @@
#include "services/network/public/cpp/resource_request_body.h"
#include "services/network/public/mojom/request_context_frame_type.mojom.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
namespace service_worker_controllee_request_handler_unittest {
diff --git a/chromium/content/browser/service_worker/service_worker_data_pipe_reader.cc b/chromium/content/browser/service_worker/service_worker_data_pipe_reader.cc
index ab8c0743deb..0343e2e2822 100644
--- a/chromium/content/browser/service_worker/service_worker_data_pipe_reader.cc
+++ b/chromium/content/browser/service_worker/service_worker_data_pipe_reader.cc
@@ -18,7 +18,9 @@ ServiceWorkerDataPipeReader::ServiceWorkerDataPipeReader(
: owner_(owner),
streaming_version_(streaming_version),
stream_pending_buffer_size_(0),
- handle_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL),
+ handle_watcher_(FROM_HERE,
+ mojo::SimpleWatcher::ArmingPolicy::MANUAL,
+ base::SequencedTaskRunnerHandle::Get()),
stream_(std::move(stream_handle->stream)),
binding_(this, std::move(stream_handle->callback_request)),
producer_state_(State::kStreaming) {
diff --git a/chromium/content/browser/service_worker/service_worker_data_pipe_reader.h b/chromium/content/browser/service_worker/service_worker_data_pipe_reader.h
index 228b49772d8..081d3620111 100644
--- a/chromium/content/browser/service_worker/service_worker_data_pipe_reader.h
+++ b/chromium/content/browser/service_worker/service_worker_data_pipe_reader.h
@@ -10,7 +10,7 @@
#include "mojo/public/cpp/bindings/binding.h"
#include "mojo/public/cpp/system/data_pipe.h"
#include "mojo/public/cpp/system/simple_watcher.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_stream_handle.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_stream_handle.mojom.h"
namespace net {
class IOBuffer;
diff --git a/chromium/content/browser/service_worker/service_worker_data_pipe_reader_unittest.cc b/chromium/content/browser/service_worker/service_worker_data_pipe_reader_unittest.cc
index 75ca86fb120..4b9a1d71457 100644
--- a/chromium/content/browser/service_worker/service_worker_data_pipe_reader_unittest.cc
+++ b/chromium/content/browser/service_worker/service_worker_data_pipe_reader_unittest.cc
@@ -16,7 +16,7 @@
#include "services/network/public/cpp/resource_request_body.h"
#include "services/network/public/mojom/request_context_frame_type.mojom.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
diff --git a/chromium/content/browser/service_worker/service_worker_database.cc b/chromium/content/browser/service_worker/service_worker_database.cc
index 032021571ad..746351acfb8 100644
--- a/chromium/content/browser/service_worker/service_worker_database.cc
+++ b/chromium/content/browser/service_worker/service_worker_database.cc
@@ -19,8 +19,8 @@
#include "content/browser/service_worker/service_worker_metrics.h"
#include "content/common/service_worker/service_worker_utils.h"
#include "content/public/common/content_switches.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
#include "third_party/leveldatabase/env_chromium.h"
#include "third_party/leveldatabase/leveldb_chrome.h"
#include "third_party/leveldatabase/src/include/leveldb/db.h"
diff --git a/chromium/content/browser/service_worker/service_worker_database.h b/chromium/content/browser/service_worker/service_worker_database.h
index a55f7c1c0ed..c320569785c 100644
--- a/chromium/content/browser/service_worker/service_worker_database.h
+++ b/chromium/content/browser/service_worker/service_worker_database.h
@@ -23,7 +23,7 @@
#include "content/common/content_export.h"
#include "content/common/service_worker/service_worker_status_code.h"
#include "content/common/service_worker/service_worker_types.h"
-#include "third_party/WebKit/public/common/origin_trials/trial_token_validator.h"
+#include "third_party/blink/public/common/origin_trials/trial_token_validator.h"
#include "url/gurl.h"
#include "url/origin.h"
diff --git a/chromium/content/browser/service_worker/service_worker_database_unittest.cc b/chromium/content/browser/service_worker/service_worker_database_unittest.cc
index d4f5eb2044a..8b0dca82d17 100644
--- a/chromium/content/browser/service_worker/service_worker_database_unittest.cc
+++ b/chromium/content/browser/service_worker/service_worker_database_unittest.cc
@@ -20,8 +20,8 @@
#include "content/public/common/content_switches.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
#include "third_party/leveldatabase/src/include/leveldb/write_batch.h"
#include "url/origin.h"
diff --git a/chromium/content/browser/service_worker/service_worker_dispatcher_host.cc b/chromium/content/browser/service_worker/service_worker_dispatcher_host.cc
index c1d3345495b..5401fdb46d8 100644
--- a/chromium/content/browser/service_worker/service_worker_dispatcher_host.cc
+++ b/chromium/content/browser/service_worker/service_worker_dispatcher_host.cc
@@ -14,16 +14,15 @@
#include "base/threading/thread_task_runner_handle.h"
#include "base/trace_event/trace_event.h"
#include "content/browser/bad_message.h"
-#include "content/browser/service_worker/embedded_worker_registry.h"
#include "content/browser/service_worker/embedded_worker_status.h"
#include "content/browser/service_worker/service_worker_context_core.h"
#include "content/browser/service_worker/service_worker_context_wrapper.h"
#include "content/browser/service_worker/service_worker_handle.h"
#include "content/browser/service_worker/service_worker_navigation_handle_core.h"
#include "content/browser/service_worker/service_worker_registration.h"
-#include "content/common/service_worker/embedded_worker_messages.h"
#include "content/common/service_worker/service_worker_messages.h"
#include "content/common/service_worker/service_worker_utils.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
@@ -32,11 +31,10 @@
#include "content/public/common/content_client.h"
#include "content/public/common/origin_util.h"
#include "ipc/ipc_message_macros.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_error_type.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_provider_type.mojom.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerError.h"
-#include "third_party/WebKit/public/platform/web_feature.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_error_type.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_provider_type.mojom.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_error.h"
#include "url/gurl.h"
using blink::MessagePortChannel;
@@ -47,7 +45,7 @@ namespace content {
namespace {
const uint32_t kServiceWorkerFilteredMessageClasses[] = {
- ServiceWorkerMsgStart, EmbeddedWorkerMsgStart,
+ ServiceWorkerMsgStart,
};
} // namespace
@@ -65,8 +63,7 @@ ServiceWorkerDispatcherHost::ServiceWorkerDispatcherHost(
weak_ptr_factory_(this) {}
ServiceWorkerDispatcherHost::~ServiceWorkerDispatcherHost() {
- // Temporary CHECK for debugging https://crbug.com/736203.
- CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
+ DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
if (GetContext() && phase_ == Phase::kAddedToContext)
GetContext()->RemoveDispatcherHost(render_process_id_);
}
@@ -96,8 +93,7 @@ void ServiceWorkerDispatcherHost::Init(
void ServiceWorkerDispatcherHost::OnFilterAdded(IPC::Channel* channel) {
TRACE_EVENT0("ServiceWorker",
"ServiceWorkerDispatcherHost::OnFilterAdded");
- // Temporary CHECK for debugging https://crbug.com/736203.
- CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
+ DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
channel_ready_ = true;
std::vector<std::unique_ptr<IPC::Message>> messages;
messages.swap(pending_messages_);
@@ -107,8 +103,7 @@ void ServiceWorkerDispatcherHost::OnFilterAdded(IPC::Channel* channel) {
}
void ServiceWorkerDispatcherHost::OnFilterRemoved() {
- // Temporary CHECK for debugging https://crbug.com/736203.
- CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
+ DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
// Don't wait until the destructor to teardown since a new dispatcher host
// for this process might be created before then.
if (GetContext() && phase_ == Phase::kAddedToContext) {
@@ -128,19 +123,7 @@ void ServiceWorkerDispatcherHost::OnDestruct() const {
bool ServiceWorkerDispatcherHost::OnMessageReceived(
const IPC::Message& message) {
- bool handled = true;
- IPC_BEGIN_MESSAGE_MAP(ServiceWorkerDispatcherHost, message)
- IPC_MESSAGE_HANDLER(EmbeddedWorkerHostMsg_CountFeature, OnCountFeature)
- IPC_MESSAGE_UNHANDLED(handled = false)
- IPC_END_MESSAGE_MAP()
-
- if (!handled && GetContext()) {
- handled = GetContext()->embedded_worker_registry()->OnMessageReceived(
- message, render_process_id_);
- if (!handled)
- bad_message::ReceivedBadMessage(this, bad_message::SWDH_NOT_HANDLED);
- }
- return handled;
+ return false;
}
bool ServiceWorkerDispatcherHost::Send(IPC::Message* message) {
@@ -154,33 +137,6 @@ bool ServiceWorkerDispatcherHost::Send(IPC::Message* message) {
return true;
}
-void ServiceWorkerDispatcherHost::RegisterServiceWorkerHandle(
- std::unique_ptr<ServiceWorkerHandle> handle) {
- int handle_id = handle->handle_id();
- handles_.AddWithID(std::move(handle), handle_id);
-}
-
-ServiceWorkerHandle* ServiceWorkerDispatcherHost::FindServiceWorkerHandle(
- int provider_id,
- int64_t version_id) {
- for (base::IDMap<std::unique_ptr<ServiceWorkerHandle>>::iterator iter(
- &handles_);
- !iter.IsAtEnd(); iter.Advance()) {
- ServiceWorkerHandle* handle = iter.GetCurrentValue();
- DCHECK(handle);
- DCHECK(handle->version());
- if (handle->provider_id() == provider_id &&
- handle->version()->version_id() == version_id) {
- return handle;
- }
- }
- return nullptr;
-}
-
-void ServiceWorkerDispatcherHost::UnregisterServiceWorkerHandle(int handle_id) {
- handles_.Remove(handle_id);
-}
-
base::WeakPtr<ServiceWorkerDispatcherHost>
ServiceWorkerDispatcherHost::AsWeakPtr() {
return weak_ptr_factory_.GetWeakPtr();
@@ -198,74 +154,55 @@ void ServiceWorkerDispatcherHost::OnProviderCreated(
return;
}
- if (IsBrowserSideNavigationEnabled() &&
- ServiceWorkerUtils::IsBrowserAssignedProviderId(info.provider_id)) {
- std::unique_ptr<ServiceWorkerProviderHost> provider_host;
- // PlzNavigate
+ // Provider hosts for navigations are precreated on the browser process with a
+ // browser-assigned id. The renderer process calls OnProviderCreated once it
+ // creates the provider.
+ if (ServiceWorkerUtils::IsBrowserAssignedProviderId(info.provider_id)) {
+ if (info.type != blink::mojom::ServiceWorkerProviderType::kForWindow) {
+ bad_message::ReceivedBadMessage(
+ this, bad_message::SWDH_PROVIDER_CREATED_ILLEGAL_TYPE_NOT_WINDOW);
+ return;
+ }
+
// Retrieve the provider host previously created for navigation requests.
+ std::unique_ptr<ServiceWorkerProviderHost> provider_host;
ServiceWorkerNavigationHandleCore* navigation_handle_core =
GetContext()->GetNavigationHandleCore(info.provider_id);
if (navigation_handle_core != nullptr)
provider_host = navigation_handle_core->RetrievePreCreatedHost();
// If no host is found, create one.
- if (provider_host == nullptr) {
+ // TODO(crbug.com/789111#c14): This is probably not right, see bug.
+ if (!provider_host) {
GetContext()->AddProviderHost(ServiceWorkerProviderHost::Create(
render_process_id_, std::move(info), GetContext()->AsWeakPtr(),
AsWeakPtr()));
return;
}
- // Otherwise, completed the initialization of the pre-created host.
- if (info.type != blink::mojom::ServiceWorkerProviderType::kForWindow) {
- bad_message::ReceivedBadMessage(
- this, bad_message::SWDH_PROVIDER_CREATED_ILLEGAL_TYPE_NOT_WINDOW);
- return;
- }
+ // Otherwise, complete initialization of the pre-created host.
provider_host->CompleteNavigationInitialized(render_process_id_,
std::move(info), AsWeakPtr());
GetContext()->AddProviderHost(std::move(provider_host));
- } else {
- // Provider hosts for service workers should be pre-created in StartWorker
- // in ServiceWorkerVersion.
- if (info.type ==
- blink::mojom::ServiceWorkerProviderType::kForServiceWorker) {
- bad_message::ReceivedBadMessage(
- this, bad_message::SWDH_PROVIDER_CREATED_ILLEGAL_TYPE_CONTROLLER);
- return;
- }
- if (ServiceWorkerUtils::IsBrowserAssignedProviderId(info.provider_id)) {
- bad_message::ReceivedBadMessage(
- this, bad_message::SWDH_PROVIDER_CREATED_BAD_ID);
- return;
- }
- GetContext()->AddProviderHost(ServiceWorkerProviderHost::Create(
- render_process_id_, std::move(info), GetContext()->AsWeakPtr(),
- AsWeakPtr()));
+ return;
}
-}
-void ServiceWorkerDispatcherHost::OnCountFeature(int64_t version_id,
- uint32_t feature) {
- if (!GetContext())
- return;
- ServiceWorkerVersion* version = GetContext()->GetLiveVersion(version_id);
- if (!version)
- return;
- if (feature >=
- static_cast<uint32_t>(blink::mojom::WebFeature::kNumberOfFeatures)) {
- // We don't use BadMessageReceived here since this IPC will be converted to
- // a Mojo method call soon, which will validate inputs for us.
- // TODO(xiaofeng.zhang): Convert the OnCountFeature IPC into a Mojo method
- // call.
+ // Provider hosts for service workers don't call OnProviderCreated. They are
+ // precreated and ServiceWorkerProviderHost::CompleteStartWorkerPreparation is
+ // called during the startup sequence once a process is allocated.
+ if (info.type == blink::mojom::ServiceWorkerProviderType::kForServiceWorker) {
+ bad_message::ReceivedBadMessage(
+ this, bad_message::SWDH_PROVIDER_CREATED_ILLEGAL_TYPE_SERVICE_WORKER);
return;
}
- version->CountFeature(feature);
+
+ GetContext()->AddProviderHost(ServiceWorkerProviderHost::Create(
+ render_process_id_, std::move(info), GetContext()->AsWeakPtr(),
+ AsWeakPtr()));
}
ServiceWorkerContextCore* ServiceWorkerDispatcherHost::GetContext() {
- // Temporary CHECK for debugging https://crbug.com/736203.
- CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
+ DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
if (!context_wrapper_.get())
return nullptr;
return context_wrapper_->context();
diff --git a/chromium/content/browser/service_worker/service_worker_dispatcher_host.h b/chromium/content/browser/service_worker/service_worker_dispatcher_host.h
index 43d549e06a1..89a2aae8739 100644
--- a/chromium/content/browser/service_worker/service_worker_dispatcher_host.h
+++ b/chromium/content/browser/service_worker/service_worker_dispatcher_host.h
@@ -10,7 +10,6 @@
#include <memory>
#include <vector>
-#include "base/containers/id_map.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/optional.h"
@@ -22,14 +21,13 @@
#include "content/public/browser/browser_associated_interface.h"
#include "content/public/browser/browser_message_filter.h"
#include "mojo/public/cpp/bindings/strong_associated_binding_set.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
class ResourceContext;
class ServiceWorkerContextCore;
class ServiceWorkerContextWrapper;
-class ServiceWorkerHandle;
namespace service_worker_dispatcher_host_unittest {
class ServiceWorkerDispatcherHostTest;
@@ -44,20 +42,17 @@ FORWARD_DECLARE_TEST(BackgroundSyncManagerTest,
// ServiceWorkerDispatcherHost is the browser-side endpoint for several IPC
// messages for service workers. There is a 1:1 correspondence between
// renderer processes and ServiceWorkerDispatcherHosts. Currently
-// ServiceWorkerDispatcherHost handles both legacy IPC messages (to and from
-// its corresponding ServiceWorkerDispatcher on the renderer) and Mojo IPC
-// messages (from any ServiceWorkerNetworkProvider on the renderer).
-//
-// Most messages are "from" a "service worker provider" on the renderer (a
-// ServiceWorkerNetworkProvider or a blink::WebServiceWorkerProvider), hence
-// they include a provider_id which must match to a ServiceWorkerProviderHost.
+// ServiceWorkerDispatcherHost sends the legacy IPC message
+// ServiceWorkerMsg_ServiceWorkerStateChanged to its corresponding
+// ServiceWorkerDispatcher on the renderer and receives Mojo IPC messages from
+// any ServiceWorkerNetworkProvider on the renderer.
//
// ServiceWorkerDispatcherHost is created on the UI thread in
-// RenderProcessHostImpl::Init() via CreateMessageFilters(). But initialization
-// and destruction occur on the IO thread, as does most (or all?) message
-// handling. It lives as long as the renderer process lives. Therefore much
-// tracking of renderer processes in browser-side service worker code is built
-// on ServiceWorkerDispatcherHost lifetime.
+// RenderProcessHostImpl::Init() via CreateMessageFilters(), but initialization,
+// destruction, and IPC message handling occur on the IO thread. It lives as
+// long as the renderer process lives. Therefore much tracking of renderer
+// processes in browser-side service worker code is built on
+// ServiceWorkerDispatcherHost lifetime.
//
// This class is bound with mojom::ServiceWorkerDispatcherHost. All
// InterfacePtrs on the same render process are bound to the same
@@ -88,14 +83,6 @@ class CONTENT_EXPORT ServiceWorkerDispatcherHost
// be destroyed.
bool Send(IPC::Message* message) override;
- // These methods are virtual only for testing.
- virtual void RegisterServiceWorkerHandle(
- std::unique_ptr<ServiceWorkerHandle> handle);
- virtual void UnregisterServiceWorkerHandle(int handle_id);
-
- ServiceWorkerHandle* FindServiceWorkerHandle(int provider_id,
- int64_t version_id);
-
ResourceContext* resource_context() { return resource_context_; }
base::WeakPtr<ServiceWorkerDispatcherHost> AsWeakPtr();
@@ -127,9 +114,6 @@ class CONTENT_EXPORT ServiceWorkerDispatcherHost
// mojom::ServiceWorkerDispatcherHost implementation
void OnProviderCreated(ServiceWorkerProviderHostInfo info) override;
- // IPC Message handlers
- void OnCountFeature(int64_t version_id, uint32_t feature);
-
ServiceWorkerContextCore* GetContext();
const int render_process_id_;
@@ -139,8 +123,6 @@ class CONTENT_EXPORT ServiceWorkerDispatcherHost
// Only accessed on the IO thread.
scoped_refptr<ServiceWorkerContextWrapper> context_wrapper_;
- base::IDMap<std::unique_ptr<ServiceWorkerHandle>> handles_;
-
bool channel_ready_; // True after BrowserMessageFilter::sender_ != NULL.
std::vector<std::unique_ptr<IPC::Message>> pending_messages_;
diff --git a/chromium/content/browser/service_worker/service_worker_dispatcher_host_unittest.cc b/chromium/content/browser/service_worker/service_worker_dispatcher_host_unittest.cc
index b47f138c02a..b4394c09853 100644
--- a/chromium/content/browser/service_worker/service_worker_dispatcher_host_unittest.cc
+++ b/chromium/content/browser/service_worker/service_worker_dispatcher_host_unittest.cc
@@ -10,10 +10,8 @@
#include "base/command_line.h"
#include "base/files/file_path.h"
-#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/time/time.h"
-#include "content/browser/browser_thread_impl.h"
#include "content/browser/service_worker/embedded_worker_instance.h"
#include "content/browser/service_worker/embedded_worker_registry.h"
#include "content/browser/service_worker/embedded_worker_status.h"
@@ -23,7 +21,6 @@
#include "content/browser/service_worker/service_worker_handle.h"
#include "content/browser/service_worker/service_worker_navigation_handle_core.h"
#include "content/browser/service_worker/service_worker_test_utils.h"
-#include "content/common/service_worker/embedded_worker_messages.h"
#include "content/common/service_worker/service_worker_messages.h"
#include "content/common/service_worker/service_worker_utils.h"
#include "content/public/common/browser_side_navigation_policy.h"
@@ -31,9 +28,9 @@
#include "content/public/test/mock_resource_context.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_provider_type.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_provider_type.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
namespace service_worker_dispatcher_host_unittest {
diff --git a/chromium/content/browser/service_worker/service_worker_fetch_dispatcher.cc b/chromium/content/browser/service_worker/service_worker_fetch_dispatcher.cc
index 72d2209d8cd..da9ecafedbf 100644
--- a/chromium/content/browser/service_worker/service_worker_fetch_dispatcher.cc
+++ b/chromium/content/browser/service_worker/service_worker_fetch_dispatcher.cc
@@ -11,7 +11,6 @@
#include "base/bind.h"
#include "base/containers/queue.h"
#include "base/feature_list.h"
-#include "base/memory/ptr_util.h"
#include "base/time/time.h"
#include "base/trace_event/trace_event.h"
#include "content/browser/devtools/service_worker_devtools_agent_host.h"
@@ -173,9 +172,8 @@ class DelegatingURLLoaderClient final : public network::mojom::URLLoaderClient {
}
void OnReceiveResponse(
const network::ResourceResponseHead& head,
- const base::Optional<net::SSLInfo>& ssl_info,
network::mojom::DownloadedTempFilePtr downloaded_file) override {
- client_->OnReceiveResponse(head, ssl_info, std::move(downloaded_file));
+ client_->OnReceiveResponse(head, std::move(downloaded_file));
DCHECK(on_response_);
std::move(on_response_).Run();
AddDevToolsCallback(
@@ -225,7 +223,7 @@ class DelegatingURLLoaderClient final : public network::mojom::URLLoaderClient {
}
void AddDevToolsCallback(
base::Callback<void(const WorkerId&, const std::string&)> callback) {
- devtools_callbacks.push(callback);
+ devtools_callbacks.push(std::move(callback));
MaybeRunDevToolsCallbacks();
}
diff --git a/chromium/content/browser/service_worker/service_worker_fetch_dispatcher.h b/chromium/content/browser/service_worker/service_worker_fetch_dispatcher.h
index 873f4d74d7c..f2ac45ac5ca 100644
--- a/chromium/content/browser/service_worker/service_worker_fetch_dispatcher.h
+++ b/chromium/content/browser/service_worker/service_worker_fetch_dispatcher.h
@@ -23,8 +23,8 @@
#include "net/log/net_log_with_source.h"
#include "services/network/public/mojom/url_loader.mojom.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
-#include "third_party/WebKit/public/mojom/blob/blob.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_event_status.mojom.h"
+#include "third_party/blink/public/mojom/blob/blob.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_event_status.mojom.h"
namespace net {
class URLRequest;
diff --git a/chromium/content/browser/service_worker/service_worker_handle.cc b/chromium/content/browser/service_worker/service_worker_handle.cc
index 48a7a52c396..1b87b9edab0 100644
--- a/chromium/content/browser/service_worker/service_worker_handle.cc
+++ b/chromium/content/browser/service_worker/service_worker_handle.cc
@@ -4,10 +4,8 @@
#include "content/browser/service_worker/service_worker_handle.h"
-#include "base/memory/ptr_util.h"
#include "content/browser/service_worker/service_worker_client_utils.h"
#include "content/browser/service_worker/service_worker_context_core.h"
-#include "content/browser/service_worker/service_worker_dispatcher_host.h"
#include "content/browser/service_worker/service_worker_provider_host.h"
#include "content/browser/service_worker/service_worker_registration.h"
#include "content/browser/service_worker/service_worker_type_converters.h"
@@ -153,39 +151,22 @@ void DispatchExtendableMessageEventFromServiceWorker(
} // namespace
-// static
-base::WeakPtr<ServiceWorkerHandle> ServiceWorkerHandle::Create(
- ServiceWorkerDispatcherHost* dispatcher_host,
- base::WeakPtr<ServiceWorkerContextCore> context,
- base::WeakPtr<ServiceWorkerProviderHost> provider_host,
- ServiceWorkerVersion* version,
- blink::mojom::ServiceWorkerObjectInfoPtr* out_info) {
- DCHECK(context && provider_host && version && out_info);
- ServiceWorkerHandle* handle =
- new ServiceWorkerHandle(dispatcher_host, context, provider_host, version);
- *out_info = handle->CreateObjectInfo();
- return handle->AsWeakPtr();
-}
-
ServiceWorkerHandle::ServiceWorkerHandle(
- ServiceWorkerDispatcherHost* dispatcher_host,
base::WeakPtr<ServiceWorkerContextCore> context,
- base::WeakPtr<ServiceWorkerProviderHost> provider_host,
- ServiceWorkerVersion* version)
- : dispatcher_host_(dispatcher_host),
- context_(context),
+ ServiceWorkerProviderHost* provider_host,
+ scoped_refptr<ServiceWorkerVersion> version)
+ : context_(context),
provider_host_(provider_host),
+ provider_origin_(url::Origin::Create(provider_host->document_url())),
provider_id_(provider_host->provider_id()),
handle_id_(context->GetNewServiceWorkerHandleId()),
- version_(version),
+ version_(std::move(version)),
weak_ptr_factory_(this) {
DCHECK(context_ && provider_host_ && version_);
DCHECK(context_->GetLiveRegistration(version_->registration_id()));
version_->AddListener(this);
bindings_.set_connection_error_handler(base::BindRepeating(
&ServiceWorkerHandle::OnConnectionError, base::Unretained(this)));
- if (dispatcher_host_)
- dispatcher_host_->RegisterServiceWorkerHandle(base::WrapUnique(this));
}
ServiceWorkerHandle::~ServiceWorkerHandle() {
@@ -194,8 +175,6 @@ ServiceWorkerHandle::~ServiceWorkerHandle() {
void ServiceWorkerHandle::OnVersionStateChanged(ServiceWorkerVersion* version) {
DCHECK(version);
- if (!provider_host_)
- return;
provider_host_->SendServiceWorkerStateChangedMessage(
handle_id_,
mojo::ConvertTo<blink::mojom::ServiceWorkerState>(version->status()));
@@ -213,26 +192,15 @@ ServiceWorkerHandle::CreateObjectInfo() {
return info;
}
-void ServiceWorkerHandle::RegisterIntoDispatcherHost(
- ServiceWorkerDispatcherHost* dispatcher_host) {
- DCHECK(ServiceWorkerUtils::IsServicificationEnabled() ||
- IsNavigationMojoResponseEnabled());
- DCHECK(!dispatcher_host_);
- dispatcher_host_ = dispatcher_host;
- dispatcher_host_->RegisterServiceWorkerHandle(base::WrapUnique(this));
-}
-
void ServiceWorkerHandle::PostMessageToServiceWorker(
- ::blink::TransferableMessage message,
- const url::Origin& source_origin) {
+ ::blink::TransferableMessage message) {
// When this method is called the encoded_message inside message could just
// point to the IPC message's buffer. But that buffer can become invalid
// before the message is passed on to the service worker, so make sure
// message owns its data.
message.EnsureDataIsOwned();
- DispatchExtendableMessageEvent(std::move(message), source_origin,
- base::DoNothing());
+ DispatchExtendableMessageEvent(std::move(message), base::DoNothing());
}
void ServiceWorkerHandle::TerminateForTesting(
@@ -242,21 +210,19 @@ void ServiceWorkerHandle::TerminateForTesting(
void ServiceWorkerHandle::DispatchExtendableMessageEvent(
::blink::TransferableMessage message,
- const url::Origin& source_origin,
StatusCallback callback) {
- if (!context_ || !provider_host_) {
- std::move(callback).Run(SERVICE_WORKER_ERROR_FAILED);
+ if (!context_) {
+ std::move(callback).Run(SERVICE_WORKER_ERROR_ABORT);
return;
}
+ DCHECK_EQ(provider_origin_,
+ url::Origin::Create(provider_host_->document_url()));
switch (provider_host_->provider_type()) {
case blink::mojom::ServiceWorkerProviderType::kForWindow:
- // TODO(leonhsl): Move kForSharedWorker to the kUnknown block to clarify
- // that currently a shared worker can not postMessage to a service worker.
- case blink::mojom::ServiceWorkerProviderType::kForSharedWorker:
service_worker_client_utils::GetClient(
- provider_host_.get(),
+ provider_host_,
base::BindOnce(&DispatchExtendableMessageEventFromClient, version_,
- std::move(message), source_origin,
+ std::move(message), provider_origin_,
std::move(callback)));
return;
case blink::mojom::ServiceWorkerProviderType::kForServiceWorker: {
@@ -268,11 +234,14 @@ void ServiceWorkerHandle::DispatchExtendableMessageEvent(
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(&DispatchExtendableMessageEventFromServiceWorker,
- version_, std::move(message), source_origin,
+ version_, std::move(message), provider_origin_,
base::make_optional(timeout), std::move(callback),
- provider_host_));
+ provider_host_->AsWeakPtr()));
return;
}
+ case blink::mojom::ServiceWorkerProviderType::kForSharedWorker:
+ // Shared workers don't yet have access to ServiceWorker objects, so they
+ // can't postMessage to one (https://crbug.com/371690).
case blink::mojom::ServiceWorkerProviderType::kUnknown:
break;
}
@@ -287,16 +256,8 @@ void ServiceWorkerHandle::OnConnectionError() {
// If there are still bindings, |this| is still being used.
if (!bindings_.empty())
return;
- // S13nServiceWorker: This handle may have been precreated before registering
- // to a dispatcher host. Just self-destruct since we're no longer needed.
- if (!dispatcher_host_) {
- DCHECK(ServiceWorkerUtils::IsServicificationEnabled() ||
- IsNavigationMojoResponseEnabled());
- delete this;
- return;
- }
// Will destroy |this|.
- dispatcher_host_->UnregisterServiceWorkerHandle(handle_id_);
+ provider_host_->RemoveServiceWorkerHandle(version_->version_id());
}
} // namespace content
diff --git a/chromium/content/browser/service_worker/service_worker_handle.h b/chromium/content/browser/service_worker/service_worker_handle.h
index e9427e07431..b6a2d421279 100644
--- a/chromium/content/browser/service_worker/service_worker_handle.h
+++ b/chromium/content/browser/service_worker/service_worker_handle.h
@@ -14,16 +14,12 @@
#include "content/common/content_export.h"
#include "content/common/service_worker/service_worker_types.h"
#include "mojo/public/cpp/bindings/associated_binding_set.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
-
-namespace url {
-class Origin;
-} // namespace url
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "url/origin.h"
namespace content {
class ServiceWorkerContextCore;
-class ServiceWorkerDispatcherHost;
class ServiceWorkerProviderHost;
namespace service_worker_handle_unittest {
@@ -42,22 +38,9 @@ class CONTENT_EXPORT ServiceWorkerHandle
: public blink::mojom::ServiceWorkerObjectHost,
public ServiceWorkerVersion::Listener {
public:
- // Creates a newly created instance for a live version. |out_info| holds the
- // first ServiceWorkerObjectHost Mojo connection to this instance, which will
- // delete itself once it detects that all the Mojo connections have gone
- // away.
- //
- // This instance registers itself into |dispatcher_host| to be owned by the
- // dispatcher host. S13nServiceWorker: |dispatcher_host| may be null.
- // RegisterIntoDispatcherHost() should be called later to register the handle
- // once the host is known.
- static base::WeakPtr<ServiceWorkerHandle> Create(
- ServiceWorkerDispatcherHost* dispatcher_host,
- base::WeakPtr<ServiceWorkerContextCore> context,
- base::WeakPtr<ServiceWorkerProviderHost> provider_host,
- ServiceWorkerVersion* version,
- blink::mojom::ServiceWorkerObjectInfoPtr* out_info);
-
+ ServiceWorkerHandle(base::WeakPtr<ServiceWorkerContextCore> context,
+ ServiceWorkerProviderHost* provider_host,
+ scoped_refptr<ServiceWorkerVersion> version);
~ServiceWorkerHandle() override;
// ServiceWorkerVersion::Listener overrides.
@@ -66,10 +49,6 @@ class CONTENT_EXPORT ServiceWorkerHandle
// Establishes a new mojo connection into |bindings_|.
blink::mojom::ServiceWorkerObjectInfoPtr CreateObjectInfo();
- // Should only be called on a ServiceWorkerHandle instance constructed with
- // null |dispatcher_host| before.
- void RegisterIntoDispatcherHost(ServiceWorkerDispatcherHost* dispatcher_host);
-
int provider_id() const { return provider_id_; }
int handle_id() const { return handle_id_; }
ServiceWorkerVersion* version() { return version_.get(); }
@@ -77,32 +56,31 @@ class CONTENT_EXPORT ServiceWorkerHandle
private:
friend class service_worker_handle_unittest::ServiceWorkerHandleTest;
- ServiceWorkerHandle(ServiceWorkerDispatcherHost* dispatcher_host,
- base::WeakPtr<ServiceWorkerContextCore> context,
- base::WeakPtr<ServiceWorkerProviderHost> provider_host,
- ServiceWorkerVersion* version);
-
// Implements blink::mojom::ServiceWorkerObjectHost.
- void PostMessageToServiceWorker(::blink::TransferableMessage message,
- const url::Origin& source_origin) override;
+ void PostMessageToServiceWorker(
+ ::blink::TransferableMessage message) override;
void TerminateForTesting(TerminateForTestingCallback callback) override;
+ // TODO(leonhsl): Remove |callback| parameter because it's just for unit tests
+ // and production code does not use it. We need to figure out another way to
+ // observe the dispatch result in unit tests.
void DispatchExtendableMessageEvent(
::blink::TransferableMessage message,
- const url::Origin& source_origin,
base::OnceCallback<void(ServiceWorkerStatusCode)> callback);
base::WeakPtr<ServiceWorkerHandle> AsWeakPtr();
void OnConnectionError();
- // |dispatcher_host_| may get a valid value via ctor or
- // RegisterIntoDispatcherHost() function, after that |dispatcher_host_| starts
- // to own |this|, then, |dispatcher_host_| is valid throughout the lifetime of
- // |this|.
- ServiceWorkerDispatcherHost* dispatcher_host_;
base::WeakPtr<ServiceWorkerContextCore> context_;
- base::WeakPtr<ServiceWorkerProviderHost> provider_host_;
+ // |provider_host_| is valid throughout lifetime of |this| because it owns
+ // |this|.
+ ServiceWorkerProviderHost* provider_host_;
+ // The origin of the |provider_host_|. Note that this is const because once a
+ // JavaScript ServiceWorker object is created for an execution context, we
+ // don't expect that context to change origins and still hold on to the
+ // object.
+ const url::Origin provider_origin_;
const int provider_id_;
const int handle_id_;
scoped_refptr<ServiceWorkerVersion> version_;
diff --git a/chromium/content/browser/service_worker/service_worker_handle_unittest.cc b/chromium/content/browser/service_worker/service_worker_handle_unittest.cc
index 9ece9392e2f..1c31c0c11ff 100644
--- a/chromium/content/browser/service_worker/service_worker_handle_unittest.cc
+++ b/chromium/content/browser/service_worker/service_worker_handle_unittest.cc
@@ -16,7 +16,6 @@
#include "content/browser/service_worker/service_worker_registration.h"
#include "content/browser/service_worker/service_worker_test_utils.h"
#include "content/browser/service_worker/service_worker_version.h"
-#include "content/common/service_worker/embedded_worker_messages.h"
#include "content/common/service_worker/service_worker_messages.h"
#include "content/common/service_worker/service_worker_types.h"
#include "content/public/browser/render_frame_host.h"
@@ -29,8 +28,8 @@
#include "ipc/ipc_message.h"
#include "ipc/ipc_test_sink.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_state.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_state.mojom.h"
namespace content {
namespace service_worker_handle_unittest {
@@ -184,9 +183,8 @@ class ServiceWorkerHandleTest : public testing::Test {
void CallDispatchExtendableMessageEvent(
ServiceWorkerHandle* handle,
::blink::TransferableMessage message,
- const url::Origin& source_origin,
base::OnceCallback<void(ServiceWorkerStatusCode)> callback) {
- handle->DispatchExtendableMessageEvent(std::move(message), source_origin,
+ handle->DispatchExtendableMessageEvent(std::move(message),
std::move(callback));
}
@@ -194,6 +192,15 @@ class ServiceWorkerHandleTest : public testing::Test {
return handle->bindings_.size();
}
+ ServiceWorkerHandle* GetServiceWorkerHandle(
+ ServiceWorkerProviderHost* provider_host,
+ int64_t version_id) {
+ auto iter = provider_host->handles_.find(version_id);
+ if (iter != provider_host->handles_.end())
+ return iter->second.get();
+ return nullptr;
+ }
+
IPC::TestSink* ipc_sink() { return helper_->ipc_sink(); }
TestBrowserThreadBundle browser_thread_bundle_;
@@ -223,12 +230,10 @@ TEST_F(ServiceWorkerHandleTest, OnVersionStateChanged) {
helper_->mock_render_process_id(), kProviderId,
helper_->context()->AsWeakPtr(), kRenderFrameId,
dispatcher_host_.get(), &remote_endpoint);
- blink::mojom::ServiceWorkerObjectInfoPtr info;
- // ServiceWorkerHandle lifetime is controlled by |info| and is also owned by
- // |dispatcher_host_|.
- base::WeakPtr<ServiceWorkerHandle> handle = ServiceWorkerHandle::Create(
- dispatcher_host_.get(), helper_->context()->AsWeakPtr(),
- provider_host->AsWeakPtr(), version_.get(), &info);
+ blink::mojom::ServiceWorkerObjectInfoPtr info =
+ provider_host->GetOrCreateServiceWorkerHandle(version_.get());
+ ServiceWorkerHandle* handle =
+ GetServiceWorkerHandle(provider_host.get(), version_->version_id());
// Start the worker, and then...
ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_FAILED;
@@ -283,16 +288,12 @@ TEST_F(ServiceWorkerHandleTest,
// Prepare a ServiceWorkerHandle corresponding to a JavaScript ServiceWorker
// object in the service worker execution context for |version_|.
- EXPECT_FALSE(dispatcher_host_->FindServiceWorkerHandle(
- version_->provider_host()->provider_id(), version_->version_id()));
- blink::mojom::ServiceWorkerObjectInfoPtr info;
- // ServiceWorkerHandle lifetime is controlled by |info| and is also owned by
- // |dispatcher_host_|.
- base::WeakPtr<ServiceWorkerHandle> sender_worker_handle =
- ServiceWorkerHandle::Create(
- dispatcher_host_.get(), helper_->context()->AsWeakPtr(),
- version_->provider_host()->AsWeakPtr(), version_.get(), &info);
- EXPECT_EQ(1u, GetBindingsCount(sender_worker_handle.get()));
+ ServiceWorkerProviderHost* provider_host = version_->provider_host();
+ blink::mojom::ServiceWorkerObjectInfoPtr info =
+ provider_host->GetOrCreateServiceWorkerHandle(version_.get());
+ ServiceWorkerHandle* sender_worker_handle =
+ GetServiceWorkerHandle(provider_host, version_->version_id());
+ EXPECT_EQ(1u, GetBindingsCount(sender_worker_handle));
// Dispatch an ExtendableMessageEvent simulating calling
// ServiceWorker#postMessage() on the ServiceWorker object corresponding to
@@ -302,8 +303,7 @@ TEST_F(ServiceWorkerHandleTest,
called = false;
status = SERVICE_WORKER_ERROR_MAX_VALUE;
CallDispatchExtendableMessageEvent(
- sender_worker_handle.get(), std::move(message),
- url::Origin::Create(version_->scope().GetOrigin()),
+ sender_worker_handle, std::move(message),
base::BindOnce(&SaveStatusCallback, &called, &status));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(called);
@@ -312,7 +312,7 @@ TEST_F(ServiceWorkerHandleTest,
// ExtendableMessageEventTestHelper, and the source service worker object info
// should correspond to the pair (|version_->provider_host()|, |version_|),
// means it should correspond to |sender_worker_handle|.
- EXPECT_EQ(2u, GetBindingsCount(sender_worker_handle.get()));
+ EXPECT_EQ(2u, GetBindingsCount(sender_worker_handle));
const std::vector<mojom::ExtendableMessageEventPtr>& events =
static_cast<ExtendableMessageEventTestHelper*>(helper_.get())->events();
EXPECT_EQ(1u, events.size());
@@ -350,13 +350,12 @@ TEST_F(ServiceWorkerHandleTest, DispatchExtendableMessageEvent_FromClient) {
ServiceWorkerProviderHost::Create(
frame_host->GetProcess()->GetID(), std::move(provider_host_info),
helper_->context()->AsWeakPtr(), dispatcher_host_->AsWeakPtr());
+ provider_host->SetDocumentUrl(pattern);
// Prepare a ServiceWorkerHandle for the above |provider_host|.
- blink::mojom::ServiceWorkerObjectInfoPtr info;
- // ServiceWorkerHandle lifetime is controlled by |info| and is also owned by
- // |dispatcher_host_|.
- base::WeakPtr<ServiceWorkerHandle> handle = ServiceWorkerHandle::Create(
- dispatcher_host_.get(), helper_->context()->AsWeakPtr(),
- provider_host->AsWeakPtr(), version_.get(), &info);
+ blink::mojom::ServiceWorkerObjectInfoPtr info =
+ provider_host->GetOrCreateServiceWorkerHandle(version_.get());
+ ServiceWorkerHandle* handle =
+ GetServiceWorkerHandle(provider_host.get(), version_->version_id());
// Simulate dispatching an ExtendableMessageEvent.
blink::TransferableMessage message;
@@ -364,8 +363,7 @@ TEST_F(ServiceWorkerHandleTest, DispatchExtendableMessageEvent_FromClient) {
bool called = false;
ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_MAX_VALUE;
CallDispatchExtendableMessageEvent(
- handle.get(), std::move(message),
- url::Origin::Create(version_->scope().GetOrigin()),
+ handle, std::move(message),
base::BindOnce(&SaveStatusCallback, &called, &status));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(called);
@@ -407,13 +405,12 @@ TEST_F(ServiceWorkerHandleTest, DispatchExtendableMessageEvent_Fail) {
ServiceWorkerProviderHost::Create(
frame_host->GetProcess()->GetID(), std::move(provider_host_info),
helper_->context()->AsWeakPtr(), dispatcher_host_->AsWeakPtr());
+ provider_host->SetDocumentUrl(pattern);
// Prepare a ServiceWorkerHandle for the above |provider_host|.
- blink::mojom::ServiceWorkerObjectInfoPtr info;
- // ServiceWorkerHandle lifetime is controlled by |info| and is also owned by
- // |dispatcher_host_|.
- base::WeakPtr<ServiceWorkerHandle> handle = ServiceWorkerHandle::Create(
- dispatcher_host_.get(), helper_->context()->AsWeakPtr(),
- provider_host->AsWeakPtr(), version_.get(), &info);
+ blink::mojom::ServiceWorkerObjectInfoPtr info =
+ provider_host->GetOrCreateServiceWorkerHandle(version_.get());
+ ServiceWorkerHandle* handle =
+ GetServiceWorkerHandle(provider_host.get(), version_->version_id());
// Try to dispatch ExtendableMessageEvent. This should fail to start the
// worker and to dispatch the event.
@@ -422,8 +419,7 @@ TEST_F(ServiceWorkerHandleTest, DispatchExtendableMessageEvent_Fail) {
bool called = false;
ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_MAX_VALUE;
CallDispatchExtendableMessageEvent(
- handle.get(), std::move(message),
- url::Origin::Create(version_->scope().GetOrigin()),
+ handle, std::move(message),
base::BindOnce(&SaveStatusCallback, &called, &status));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(called);
diff --git a/chromium/content/browser/service_worker/service_worker_info.cc b/chromium/content/browser/service_worker/service_worker_info.cc
index 40405d1c770..c6412175033 100644
--- a/chromium/content/browser/service_worker/service_worker_info.cc
+++ b/chromium/content/browser/service_worker/service_worker_info.cc
@@ -9,8 +9,8 @@
#include "content/public/common/browser_side_navigation_policy.h"
#include "content/public/common/child_process_host.h"
#include "ipc/ipc_message.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
diff --git a/chromium/content/browser/service_worker/service_worker_info.h b/chromium/content/browser/service_worker/service_worker_info.h
index 3c5c7fecda7..945008dadcd 100644
--- a/chromium/content/browser/service_worker/service_worker_info.h
+++ b/chromium/content/browser/service_worker/service_worker_info.h
@@ -14,7 +14,7 @@
#include "content/browser/service_worker/service_worker_version.h"
#include "content/common/content_export.h"
#include "content/common/service_worker/service_worker_types.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_provider_type.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_provider_type.mojom.h"
#include "url/gurl.h"
namespace content {
diff --git a/chromium/content/browser/service_worker/service_worker_installed_script_loader.cc b/chromium/content/browser/service_worker/service_worker_installed_script_loader.cc
index 2b5d946b866..8283e936fdc 100644
--- a/chromium/content/browser/service_worker/service_worker_installed_script_loader.cc
+++ b/chromium/content/browser/service_worker/service_worker_installed_script_loader.cc
@@ -16,7 +16,7 @@
#include "content/common/service_worker/service_worker_utils.h"
#include "net/cert/cert_status_flags.h"
#include "services/network/public/cpp/resource_response.h"
-#include "third_party/WebKit/public/common/mime_util/mime_util.h"
+#include "third_party/blink/public/common/mime_util/mime_util.h"
namespace content {
@@ -52,8 +52,8 @@ void ServiceWorkerInstalledScriptLoader::OnStarted(
// Just drain the metadata (V8 code cache): this entire class is just to
// handle a corner case for non-installed service workers and high performance
// is not needed.
- metadata_drainer_ = std::make_unique<mojo::common::DataPipeDrainer>(
- this, std::move(metadata_handle));
+ metadata_drainer_ =
+ std::make_unique<mojo::DataPipeDrainer>(this, std::move(metadata_handle));
// We continue in OnHttpInfoRead().
}
@@ -78,11 +78,10 @@ void ServiceWorkerInstalledScriptLoader::OnHttpInfoRead(
head.socket_address = info->socket_address;
head.cert_status = info->ssl_info.cert_status;
- base::Optional<net::SSLInfo> ssl_info;
if (options_ & network::mojom::kURLLoadOptionSendSSLInfoWithResponse)
- ssl_info = info->ssl_info;
+ head.ssl_info = info->ssl_info;
- client_->OnReceiveResponse(head, ssl_info, nullptr /* downloaded_file */);
+ client_->OnReceiveResponse(head, nullptr /* downloaded_file */);
client_->OnStartLoadingResponseBody(std::move(body_handle_));
// We continue in OnFinished().
}
diff --git a/chromium/content/browser/service_worker/service_worker_installed_script_loader.h b/chromium/content/browser/service_worker/service_worker_installed_script_loader.h
index c02d9317de3..ad4844c1d64 100644
--- a/chromium/content/browser/service_worker/service_worker_installed_script_loader.h
+++ b/chromium/content/browser/service_worker/service_worker_installed_script_loader.h
@@ -8,9 +8,9 @@
#include "content/browser/service_worker/service_worker_disk_cache.h"
#include "content/browser/service_worker/service_worker_installed_script_reader.h"
#include "content/common/content_export.h"
-#include "mojo/common/data_pipe_drainer.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "mojo/public/cpp/system/data_pipe.h"
+#include "mojo/public/cpp/system/data_pipe_drainer.h"
#include "services/network/public/mojom/url_loader.mojom.h"
namespace content {
@@ -27,7 +27,7 @@ namespace content {
class CONTENT_EXPORT ServiceWorkerInstalledScriptLoader
: public network::mojom::URLLoader,
public ServiceWorkerInstalledScriptReader::Client,
- public mojo::common::DataPipeDrainer::Client {
+ public mojo::DataPipeDrainer::Client {
public:
ServiceWorkerInstalledScriptLoader(
uint32_t options,
@@ -56,7 +56,7 @@ class CONTENT_EXPORT ServiceWorkerInstalledScriptLoader
void ResumeReadingBodyFromNet() override;
private:
- // mojo::common::DataPipeDrainer::Client overrides:
+ // mojo::DataPipeDrainer::Client overrides:
// These just do nothing.
void OnDataAvailable(const void* data, size_t num_bytes) override {}
void OnDataComplete() override {}
@@ -69,7 +69,7 @@ class CONTENT_EXPORT ServiceWorkerInstalledScriptLoader
std::string encoding_;
mojo::ScopedDataPipeConsumerHandle body_handle_;
uint64_t body_size_ = 0;
- std::unique_ptr<mojo::common::DataPipeDrainer> metadata_drainer_;
+ std::unique_ptr<mojo::DataPipeDrainer> metadata_drainer_;
DISALLOW_COPY_AND_ASSIGN(ServiceWorkerInstalledScriptLoader);
};
diff --git a/chromium/content/browser/service_worker/service_worker_installed_script_reader.cc b/chromium/content/browser/service_worker/service_worker_installed_script_reader.cc
index 8ee5ba099e5..a70872a74d8 100644
--- a/chromium/content/browser/service_worker/service_worker_installed_script_reader.cc
+++ b/chromium/content/browser/service_worker/service_worker_installed_script_reader.cc
@@ -21,7 +21,9 @@ class ServiceWorkerInstalledScriptReader::MetaDataSender {
: meta_data_(std::move(meta_data)),
bytes_sent_(0),
handle_(std::move(handle)),
- watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::AUTOMATIC),
+ watcher_(FROM_HERE,
+ mojo::SimpleWatcher::ArmingPolicy::AUTOMATIC,
+ base::SequencedTaskRunnerHandle::Get()),
weak_factory_(this) {}
void Start(base::OnceCallback<void(bool /* success */)> callback) {
@@ -82,7 +84,9 @@ ServiceWorkerInstalledScriptReader::ServiceWorkerInstalledScriptReader(
Client* client)
: reader_(std::move(reader)),
client_(client),
- body_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL),
+ body_watcher_(FROM_HERE,
+ mojo::SimpleWatcher::ArmingPolicy::MANUAL,
+ base::SequencedTaskRunnerHandle::Get()),
weak_factory_(this) {}
ServiceWorkerInstalledScriptReader::~ServiceWorkerInstalledScriptReader() {}
@@ -91,8 +95,8 @@ void ServiceWorkerInstalledScriptReader::Start() {
auto info_buf = base::MakeRefCounted<HttpResponseInfoIOBuffer>();
reader_->ReadInfo(
info_buf.get(),
- base::Bind(&ServiceWorkerInstalledScriptReader::OnReadInfoComplete,
- AsWeakPtr(), info_buf));
+ base::BindOnce(&ServiceWorkerInstalledScriptReader::OnReadInfoComplete,
+ AsWeakPtr(), info_buf));
}
void ServiceWorkerInstalledScriptReader::OnReadInfoComplete(
@@ -200,8 +204,8 @@ void ServiceWorkerInstalledScriptReader::OnWritableBody(MojoResult) {
body_pending_write_.get());
reader_->ReadData(
buffer.get(), num_bytes,
- base::Bind(&ServiceWorkerInstalledScriptReader::OnResponseDataRead,
- AsWeakPtr()));
+ base::BindOnce(&ServiceWorkerInstalledScriptReader::OnResponseDataRead,
+ AsWeakPtr()));
}
void ServiceWorkerInstalledScriptReader::OnResponseDataRead(int read_bytes) {
diff --git a/chromium/content/browser/service_worker/service_worker_installed_scripts_sender.h b/chromium/content/browser/service_worker/service_worker_installed_scripts_sender.h
index d97ae2b32b5..81531ca5c3a 100644
--- a/chromium/content/browser/service_worker/service_worker_installed_scripts_sender.h
+++ b/chromium/content/browser/service_worker/service_worker_installed_scripts_sender.h
@@ -10,7 +10,7 @@
#include "content/common/content_export.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "mojo/public/cpp/system/data_pipe.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_installed_scripts_manager.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_installed_scripts_manager.mojom.h"
namespace content {
diff --git a/chromium/content/browser/service_worker/service_worker_installed_scripts_sender_unittest.cc b/chromium/content/browser/service_worker/service_worker_installed_scripts_sender_unittest.cc
index 48a64621739..4a441aaf7e2 100644
--- a/chromium/content/browser/service_worker/service_worker_installed_scripts_sender_unittest.cc
+++ b/chromium/content/browser/service_worker/service_worker_installed_scripts_sender_unittest.cc
@@ -17,7 +17,7 @@
#include "net/base/io_buffer.h"
#include "net/base/test_completion_callback.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
diff --git a/chromium/content/browser/service_worker/service_worker_internals_ui.cc b/chromium/content/browser/service_worker/service_worker_internals_ui.cc
index 22d1e1cf892..6770fe5ac9d 100644
--- a/chromium/content/browser/service_worker/service_worker_internals_ui.cc
+++ b/chromium/content/browser/service_worker/service_worker_internals_ui.cc
@@ -12,7 +12,6 @@
#include <vector>
#include "base/bind.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/values.h"
#include "content/browser/devtools/devtools_agent_host_impl.h"
@@ -33,7 +32,7 @@
#include "content/public/browser/web_ui_data_source.h"
#include "content/public/common/child_process_host.h"
#include "content/public/common/url_constants.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
using base::DictionaryValue;
using base::ListValue;
@@ -343,31 +342,27 @@ ServiceWorkerInternalsUI::ServiceWorkerInternalsUI(WebUI* web_ui)
WebUIDataSource::Add(browser_context, source);
web_ui->RegisterMessageCallback(
- "GetOptions",
- base::Bind(&ServiceWorkerInternalsUI::GetOptions,
- base::Unretained(this)));
+ "GetOptions", base::BindRepeating(&ServiceWorkerInternalsUI::GetOptions,
+ base::Unretained(this)));
web_ui->RegisterMessageCallback(
- "SetOption",
- base::Bind(&ServiceWorkerInternalsUI::SetOption, base::Unretained(this)));
+ "SetOption", base::BindRepeating(&ServiceWorkerInternalsUI::SetOption,
+ base::Unretained(this)));
web_ui->RegisterMessageCallback(
"getAllRegistrations",
- base::Bind(&ServiceWorkerInternalsUI::GetAllRegistrations,
- base::Unretained(this)));
+ base::BindRepeating(&ServiceWorkerInternalsUI::GetAllRegistrations,
+ base::Unretained(this)));
web_ui->RegisterMessageCallback(
- "stop", base::Bind(&ServiceWorkerInternalsUI::StopWorker,
- base::Unretained(this)));
+ "stop", base::BindRepeating(&ServiceWorkerInternalsUI::StopWorker,
+ base::Unretained(this)));
web_ui->RegisterMessageCallback(
- "inspect",
- base::Bind(&ServiceWorkerInternalsUI::InspectWorker,
- base::Unretained(this)));
+ "inspect", base::BindRepeating(&ServiceWorkerInternalsUI::InspectWorker,
+ base::Unretained(this)));
web_ui->RegisterMessageCallback(
- "unregister",
- base::Bind(&ServiceWorkerInternalsUI::Unregister,
- base::Unretained(this)));
+ "unregister", base::BindRepeating(&ServiceWorkerInternalsUI::Unregister,
+ base::Unretained(this)));
web_ui->RegisterMessageCallback(
- "start",
- base::Bind(&ServiceWorkerInternalsUI::StartWorker,
- base::Unretained(this)));
+ "start", base::BindRepeating(&ServiceWorkerInternalsUI::StartWorker,
+ base::Unretained(this)));
}
ServiceWorkerInternalsUI::~ServiceWorkerInternalsUI() {
@@ -378,7 +373,8 @@ ServiceWorkerInternalsUI::~ServiceWorkerInternalsUI() {
BrowserContext::StoragePartitionCallback remove_observer_cb =
base::Bind(&ServiceWorkerInternalsUI::RemoveObserverFromStoragePartition,
base::Unretained(this));
- BrowserContext::ForEachStoragePartition(browser_context, remove_observer_cb);
+ BrowserContext::ForEachStoragePartition(browser_context,
+ std::move(remove_observer_cb));
}
void ServiceWorkerInternalsUI::GetOptions(const ListValue* args) {
@@ -409,7 +405,8 @@ void ServiceWorkerInternalsUI::GetAllRegistrations(const ListValue* args) {
BrowserContext::StoragePartitionCallback add_context_cb =
base::Bind(&ServiceWorkerInternalsUI::AddContextFromStoragePartition,
base::Unretained(this));
- BrowserContext::ForEachStoragePartition(browser_context, add_context_cb);
+ BrowserContext::ForEachStoragePartition(browser_context,
+ std::move(add_context_cb));
}
void ServiceWorkerInternalsUI::AddContextFromStoragePartition(
@@ -473,7 +470,8 @@ bool ServiceWorkerInternalsUI::GetServiceWorkerContext(
base::Unretained(this),
partition_id,
&result_partition);
- BrowserContext::ForEachStoragePartition(browser_context, find_context_cb);
+ BrowserContext::ForEachStoragePartition(browser_context,
+ std::move(find_context_cb));
if (!result_partition)
return false;
*context = static_cast<ServiceWorkerContextWrapper*>(
@@ -523,11 +521,11 @@ void ServiceWorkerInternalsUI::InspectWorker(const ListValue* args) {
->GetDevToolsAgentHostForWorker(process_host_id,
devtools_agent_route_id));
if (!agent_host.get()) {
- callback.Run(SERVICE_WORKER_ERROR_NOT_FOUND);
+ std::move(callback).Run(SERVICE_WORKER_ERROR_NOT_FOUND);
return;
}
agent_host->Inspect();
- callback.Run(SERVICE_WORKER_OK);
+ std::move(callback).Run(SERVICE_WORKER_OK);
}
void ServiceWorkerInternalsUI::Unregister(const ListValue* args) {
@@ -547,7 +545,7 @@ void ServiceWorkerInternalsUI::Unregister(const ListValue* args) {
base::Callback<void(ServiceWorkerStatusCode)> callback =
base::Bind(OperationCompleteCallback, AsWeakPtr(), callback_id);
- UnregisterWithScope(context, GURL(scope_string), callback);
+ UnregisterWithScope(context, GURL(scope_string), std::move(callback));
}
void ServiceWorkerInternalsUI::StartWorker(const ListValue* args) {
@@ -566,7 +564,7 @@ void ServiceWorkerInternalsUI::StartWorker(const ListValue* args) {
}
base::Callback<void(ServiceWorkerStatusCode)> callback =
base::Bind(OperationCompleteCallback, AsWeakPtr(), callback_id);
- context->StartServiceWorker(GURL(scope_string), callback);
+ context->StartServiceWorker(GURL(scope_string), std::move(callback));
}
void ServiceWorkerInternalsUI::StopWorkerWithId(
diff --git a/chromium/content/browser/service_worker/service_worker_job_coordinator.cc b/chromium/content/browser/service_worker/service_worker_job_coordinator.cc
index 3155dac9ba2..c8ea110fd33 100644
--- a/chromium/content/browser/service_worker/service_worker_job_coordinator.cc
+++ b/chromium/content/browser/service_worker/service_worker_job_coordinator.cc
@@ -11,7 +11,7 @@
#include "base/memory/ptr_util.h"
#include "content/browser/service_worker/service_worker_register_job_base.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
@@ -105,23 +105,23 @@ ServiceWorkerJobCoordinator::~ServiceWorkerJobCoordinator() {
void ServiceWorkerJobCoordinator::Register(
const GURL& script_url,
const blink::mojom::ServiceWorkerRegistrationOptions& options,
- const ServiceWorkerRegisterJob::RegistrationCallback& callback) {
+ ServiceWorkerRegisterJob::RegistrationCallback callback) {
std::unique_ptr<ServiceWorkerRegisterJobBase> job(
new ServiceWorkerRegisterJob(context_, script_url, options));
ServiceWorkerRegisterJob* queued_job = static_cast<ServiceWorkerRegisterJob*>(
job_queues_[options.scope].Push(std::move(job)));
- queued_job->AddCallback(callback);
+ queued_job->AddCallback(std::move(callback));
}
void ServiceWorkerJobCoordinator::Unregister(
const GURL& pattern,
- const ServiceWorkerUnregisterJob::UnregistrationCallback& callback) {
+ ServiceWorkerUnregisterJob::UnregistrationCallback callback) {
std::unique_ptr<ServiceWorkerRegisterJobBase> job(
new ServiceWorkerUnregisterJob(context_, pattern));
ServiceWorkerUnregisterJob* queued_job =
static_cast<ServiceWorkerUnregisterJob*>(
job_queues_[pattern].Push(std::move(job)));
- queued_job->AddCallback(callback);
+ queued_job->AddCallback(std::move(callback));
}
void ServiceWorkerJobCoordinator::Update(
@@ -139,7 +139,7 @@ void ServiceWorkerJobCoordinator::Update(
ServiceWorkerRegistration* registration,
bool force_bypass_cache,
bool skip_script_comparison,
- const ServiceWorkerRegisterJob::RegistrationCallback& callback) {
+ ServiceWorkerRegisterJob::RegistrationCallback callback) {
DCHECK(registration);
ServiceWorkerRegisterJob* queued_job = static_cast<ServiceWorkerRegisterJob*>(
job_queues_[registration->pattern()].Push(
@@ -147,7 +147,7 @@ void ServiceWorkerJobCoordinator::Update(
new ServiceWorkerRegisterJob(context_, registration,
force_bypass_cache,
skip_script_comparison))));
- queued_job->AddCallback(callback);
+ queued_job->AddCallback(std::move(callback));
}
void ServiceWorkerJobCoordinator::AbortAll() {
diff --git a/chromium/content/browser/service_worker/service_worker_job_coordinator.h b/chromium/content/browser/service_worker/service_worker_job_coordinator.h
index 6eeef5fb227..cae8d52c46f 100644
--- a/chromium/content/browser/service_worker/service_worker_job_coordinator.h
+++ b/chromium/content/browser/service_worker/service_worker_job_coordinator.h
@@ -13,7 +13,7 @@
#include "content/browser/service_worker/service_worker_register_job.h"
#include "content/browser/service_worker/service_worker_unregister_job.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
#include "url/gurl.h"
namespace content {
@@ -29,18 +29,17 @@ class CONTENT_EXPORT ServiceWorkerJobCoordinator {
void Register(const GURL& script_url,
const blink::mojom::ServiceWorkerRegistrationOptions& options,
- const ServiceWorkerRegisterJob::RegistrationCallback& callback);
+ ServiceWorkerRegisterJob::RegistrationCallback callback);
- void Unregister(
- const GURL& pattern,
- const ServiceWorkerUnregisterJob::UnregistrationCallback& callback);
+ void Unregister(const GURL& pattern,
+ ServiceWorkerUnregisterJob::UnregistrationCallback callback);
void Update(ServiceWorkerRegistration* registration, bool force_bypass_cache);
void Update(ServiceWorkerRegistration* registration,
bool force_bypass_cache,
bool skip_script_comparison,
- const ServiceWorkerRegisterJob::RegistrationCallback& callback);
+ ServiceWorkerRegisterJob::RegistrationCallback callback);
// Calls ServiceWorkerRegisterJobBase::Abort() on all jobs and removes them.
void AbortAll();
diff --git a/chromium/content/browser/service_worker/service_worker_job_unittest.cc b/chromium/content/browser/service_worker/service_worker_job_unittest.cc
index 64ee5077c63..78c577fe053 100644
--- a/chromium/content/browser/service_worker/service_worker_job_unittest.cc
+++ b/chromium/content/browser/service_worker/service_worker_job_unittest.cc
@@ -8,26 +8,22 @@
#include "base/files/scoped_temp_dir.h"
#include "base/logging.h"
#include "base/macros.h"
-#include "base/message_loop/message_loop.h"
#include "base/optional.h"
#include "base/run_loop.h"
#include "base/test/test_simple_task_runner.h"
#include "base/time/time.h"
-#include "content/browser/browser_thread_impl.h"
#include "content/browser/service_worker/embedded_worker_registry.h"
#include "content/browser/service_worker/embedded_worker_status.h"
#include "content/browser/service_worker/embedded_worker_test_helper.h"
#include "content/browser/service_worker/service_worker_context_core.h"
#include "content/browser/service_worker/service_worker_context_wrapper.h"
#include "content/browser/service_worker/service_worker_disk_cache.h"
-#include "content/browser/service_worker/service_worker_dispatcher_host.h"
#include "content/browser/service_worker/service_worker_handle.h"
#include "content/browser/service_worker/service_worker_job_coordinator.h"
#include "content/browser/service_worker/service_worker_registration.h"
#include "content/browser/service_worker/service_worker_registration_object_host.h"
#include "content/browser/service_worker/service_worker_registration_status.h"
#include "content/browser/service_worker/service_worker_test_utils.h"
-#include "content/common/service_worker/embedded_worker_messages.h"
#include "content/common/service_worker/service_worker_messages.h"
#include "content/common/service_worker/service_worker_utils.h"
#include "content/public/test/test_browser_context.h"
@@ -38,10 +34,10 @@
#include "net/base/test_completion_callback.h"
#include "net/http/http_response_headers.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_event_status.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_event_status.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
using net::IOBuffer;
using net::TestCompletionCallback;
@@ -52,42 +48,6 @@ namespace content {
namespace {
-// A dispatcher host that holds on to all registered ServiceWorkerHandles.
-class KeepHandlesDispatcherHost : public ServiceWorkerDispatcherHost {
- public:
- KeepHandlesDispatcherHost(int render_process_id,
- ResourceContext* resource_context)
- : ServiceWorkerDispatcherHost(render_process_id, resource_context) {}
- void RegisterServiceWorkerHandle(
- std::unique_ptr<ServiceWorkerHandle> handle) override {
- handles_.push_back(std::move(handle));
- }
-
- void UnregisterServiceWorkerHandle(int handle_id) override {
- auto iter = handles_.begin();
- for (; iter != handles_.end(); ++iter) {
- if ((*iter)->handle_id() == handle_id)
- break;
- }
- ASSERT_NE(handles_.end(), iter);
- handles_.erase(iter);
- }
-
- void Clear() {
- handles_.clear();
- }
-
- const std::vector<std::unique_ptr<ServiceWorkerHandle>>& handles() {
- return handles_;
- }
-
- private:
- ~KeepHandlesDispatcherHost() override {}
-
- std::vector<std::unique_ptr<ServiceWorkerHandle>> handles_;
- DISALLOW_COPY_AND_ASSIGN(KeepHandlesDispatcherHost);
-};
-
void SaveRegistrationCallback(
ServiceWorkerStatusCode expected_status,
bool* called,
@@ -121,8 +81,8 @@ ServiceWorkerRegisterJob::RegistrationCallback SaveRegistration(
bool* called,
scoped_refptr<ServiceWorkerRegistration>* registration) {
*called = false;
- return base::Bind(
- &SaveRegistrationCallback, expected_status, called, registration);
+ return base::BindOnce(&SaveRegistrationCallback, expected_status, called,
+ registration);
}
ServiceWorkerStorage::FindRegistrationCallback SaveFoundRegistration(
@@ -146,7 +106,7 @@ ServiceWorkerUnregisterJob::UnregistrationCallback SaveUnregistration(
ServiceWorkerStatusCode expected_status,
bool* called) {
*called = false;
- return base::Bind(&SaveUnregistrationCallback, expected_status, called);
+ return base::BindOnce(&SaveUnregistrationCallback, expected_status, called);
}
} // namespace
@@ -340,41 +300,32 @@ TEST_F(ServiceWorkerJobTest, Register) {
// Make sure registrations are cleaned up when they are unregistered.
TEST_F(ServiceWorkerJobTest, Unregister) {
- // During registration, service worker handles will be created to host the
- // {installing,waiting,active} service worker objects for
- // ServiceWorkerGlobalScope#registration. KeepHandlesDispatcherHost will store
- // the handles.
- scoped_refptr<KeepHandlesDispatcherHost> dispatcher_host =
- base::MakeRefCounted<KeepHandlesDispatcherHost>(
- helper_->mock_render_process_id(),
- helper_->browser_context()->GetResourceContext());
- helper_->RegisterDispatcherHost(helper_->mock_render_process_id(),
- dispatcher_host);
- dispatcher_host->Init(helper_->context_wrapper());
-
blink::mojom::ServiceWorkerRegistrationOptions options;
options.scope = GURL("http://www.example.com/");
scoped_refptr<ServiceWorkerRegistration> registration =
RunRegisterJob(GURL("http://www.example.com/service_worker.js"), options);
+ scoped_refptr<ServiceWorkerVersion> version = registration->active_version();
- // During the above registration, a service worker registration object host
- // for ServiceWorkerGlobalScope#registration has been created/added into
- // |provider_host|.
ServiceWorkerProviderHost* provider_host =
registration->active_version()->provider_host();
ASSERT_NE(nullptr, provider_host);
+ // One ServiceWorkerRegistrationObjectHost should have been created for the
+ // new registration.
EXPECT_EQ(1UL, provider_host->registration_object_hosts_.size());
- EXPECT_EQ(3UL, dispatcher_host->handles().size());
+ // One ServiceWorkerHandle should have been created for the new service
+ // worker.
+ EXPECT_EQ(1UL, provider_host->handles_.size());
RunUnregisterJob(options.scope);
- // Clear all service worker handles.
- dispatcher_host->Clear();
- EXPECT_EQ(0UL, dispatcher_host->handles().size());
- // The service worker registration object host has been destroyed together
- // with |provider_host| by the above unregistration. Then the only reference
- // to the registration should be |registration|.
+ // The service worker registration object host and service worker handle have
+ // been destroyed together with |provider_host| by the above unregistration.
+ // Then |registration| and |version| should be the last one reference to the
+ // corresponding instance.
EXPECT_TRUE(registration->HasOneRef());
+ EXPECT_TRUE(version->HasOneRef());
+ EXPECT_EQ(EmbeddedWorkerStatus::STOPPED, version->running_status());
+ EXPECT_EQ(ServiceWorkerVersion::REDUNDANT, version->status());
registration =
FindRegistrationForPattern(options.scope, SERVICE_WORKER_ERROR_NOT_FOUND);
@@ -417,16 +368,6 @@ TEST_F(ServiceWorkerJobTest, RegisterNewScript) {
// Make sure that when registering a duplicate pattern+script_url
// combination, that the same registration is used.
TEST_F(ServiceWorkerJobTest, RegisterDuplicateScript) {
- // During registration, handles will be created for hosting the worker's
- // context. KeepHandlesDispatcherHost will store the handles.
- scoped_refptr<KeepHandlesDispatcherHost> dispatcher_host =
- new KeepHandlesDispatcherHost(
- helper_->mock_render_process_id(),
- helper_->browser_context()->GetResourceContext());
- helper_->RegisterDispatcherHost(helper_->mock_render_process_id(),
- dispatcher_host);
- dispatcher_host->Init(helper_->context_wrapper());
-
GURL script_url("http://www.example.com/service_worker.js");
blink::mojom::ServiceWorkerRegistrationOptions options;
options.scope = GURL("http://www.example.com/");
@@ -442,7 +383,7 @@ TEST_F(ServiceWorkerJobTest, RegisterDuplicateScript) {
ASSERT_NE(nullptr, provider_host);
// Clear all service worker handles.
- dispatcher_host->Clear();
+ provider_host->handles_.clear();
// Ensure that the registration's object host doesn't have the reference.
EXPECT_EQ(1UL, provider_host->registration_object_hosts_.size());
provider_host->registration_object_hosts_.clear();
@@ -471,15 +412,6 @@ TEST_F(ServiceWorkerJobTest, RegisterDuplicateScript) {
// is updated when registering a duplicate pattern+script_url with a different
// update_via_cache value.
TEST_F(ServiceWorkerJobTest, RegisterWithDifferentUpdateViaCache) {
- // During registration, handles will be created for hosting the worker's
- // context. KeepHandlesDispatcherHost will store the handles.
- auto dispatcher_host = base::MakeRefCounted<KeepHandlesDispatcherHost>(
- helper_->mock_render_process_id(),
- helper_->browser_context()->GetResourceContext());
- helper_->RegisterDispatcherHost(helper_->mock_render_process_id(),
- dispatcher_host);
- dispatcher_host->Init(helper_->context_wrapper());
-
GURL script_url("https://www.example.com/service_worker.js");
blink::mojom::ServiceWorkerRegistrationOptions options;
options.scope = GURL("https://www.example.com/");
@@ -498,7 +430,7 @@ TEST_F(ServiceWorkerJobTest, RegisterWithDifferentUpdateViaCache) {
ASSERT_NE(nullptr, provider_host);
// Clear all service worker handles.
- dispatcher_host->Clear();
+ provider_host->handles_.clear();
// Ensure that the registration's object host doesn't have the reference.
EXPECT_EQ(1UL, provider_host->registration_object_hosts_.size());
provider_host->registration_object_hosts_.clear();
@@ -899,9 +831,7 @@ const std::string kScope("scope/");
const std::string kScript("script.js");
void RunNestedUntilIdle() {
- base::MessageLoop::ScopedNestableTaskAllower allow(
- base::MessageLoop::current());
- base::RunLoop().RunUntilIdle();
+ base::RunLoop(base::RunLoop::Type::kNestableTasksAllowed).RunUntilIdle();
}
void OnIOComplete(int* rv_out, int rv) {
diff --git a/chromium/content/browser/service_worker/service_worker_lifetime_tracker.cc b/chromium/content/browser/service_worker/service_worker_lifetime_tracker.cc
index 6a6d28cf062..9cb28153972 100644
--- a/chromium/content/browser/service_worker/service_worker_lifetime_tracker.cc
+++ b/chromium/content/browser/service_worker/service_worker_lifetime_tracker.cc
@@ -15,7 +15,7 @@ ServiceWorkerLifetimeTracker::ServiceWorkerLifetimeTracker()
: ServiceWorkerLifetimeTracker(base::DefaultTickClock::GetInstance()) {}
ServiceWorkerLifetimeTracker::ServiceWorkerLifetimeTracker(
- base::TickClock* tick_clock)
+ const base::TickClock* tick_clock)
: tick_clock_(tick_clock) {}
ServiceWorkerLifetimeTracker::~ServiceWorkerLifetimeTracker() = default;
diff --git a/chromium/content/browser/service_worker/service_worker_lifetime_tracker.h b/chromium/content/browser/service_worker/service_worker_lifetime_tracker.h
index 12b0eb16c23..7fd677dc2d4 100644
--- a/chromium/content/browser/service_worker/service_worker_lifetime_tracker.h
+++ b/chromium/content/browser/service_worker/service_worker_lifetime_tracker.h
@@ -10,7 +10,6 @@
#include "base/gtest_prod_util.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/time/tick_clock.h"
#include "base/timer/timer.h"
#include "content/common/content_export.h"
@@ -22,7 +21,7 @@ namespace content {
class CONTENT_EXPORT ServiceWorkerLifetimeTracker {
public:
ServiceWorkerLifetimeTracker();
- explicit ServiceWorkerLifetimeTracker(base::TickClock* tick_clock);
+ explicit ServiceWorkerLifetimeTracker(const base::TickClock* tick_clock);
virtual ~ServiceWorkerLifetimeTracker();
// Called when the worker started running.
@@ -38,7 +37,7 @@ class CONTENT_EXPORT ServiceWorkerLifetimeTracker {
void RecordHistograms();
- base::TickClock* tick_clock_;
+ const base::TickClock* tick_clock_;
std::map<int64_t /* embedded_worker_id */, base::TimeTicks /* start_time */>
running_workers_;
diff --git a/chromium/content/browser/service_worker/service_worker_metrics.cc b/chromium/content/browser/service_worker/service_worker_metrics.cc
index 03552196265..463d9e7d2dd 100644
--- a/chromium/content/browser/service_worker/service_worker_metrics.cc
+++ b/chromium/content/browser/service_worker/service_worker_metrics.cc
@@ -613,19 +613,6 @@ void ServiceWorkerMetrics::RecordInstallEventStatus(
SERVICE_WORKER_ERROR_MAX_VALUE);
}
-void ServiceWorkerMetrics::RecordForeignFetchRegistrationCount(
- size_t scope_count,
- size_t origin_count) {
- UMA_HISTOGRAM_COUNTS_100("ServiceWorker.ForeignFetch.ScopeCount",
- scope_count);
- if (scope_count > 0) {
- // Only record number of origins if service worker registered for at least
- // one foreign fetch scope.
- UMA_HISTOGRAM_COUNTS_100("ServiceWorker.ForeignFetch.OriginCount",
- origin_count);
- }
-}
-
void ServiceWorkerMetrics::RecordEventDispatchingDelay(EventType event_type,
base::TimeDelta time,
Site site_for_metrics) {
@@ -769,20 +756,17 @@ void ServiceWorkerMetrics::RecordStatusZeroResponseError(
blink::mojom::ServiceWorkerResponseError error) {
if (is_main_resource) {
UMA_HISTOGRAM_ENUMERATION(
- "ServiceWorker.URLRequestJob.MainResource.StatusZeroError", error,
- static_cast<int>(blink::mojom::ServiceWorkerResponseError::kLast) + 1);
+ "ServiceWorker.URLRequestJob.MainResource.StatusZeroError", error);
} else {
UMA_HISTOGRAM_ENUMERATION(
- "ServiceWorker.URLRequestJob.Subresource.StatusZeroError", error,
- static_cast<int>(blink::mojom::ServiceWorkerResponseError::kLast) + 1);
+ "ServiceWorker.URLRequestJob.Subresource.StatusZeroError", error);
}
}
void ServiceWorkerMetrics::RecordFallbackedRequestMode(
network::mojom::FetchRequestMode mode) {
- UMA_HISTOGRAM_ENUMERATION(
- "ServiceWorker.URLRequestJob.FallbackedRequestMode", mode,
- static_cast<int>(network::mojom::FetchRequestMode::kLast) + 1);
+ UMA_HISTOGRAM_ENUMERATION("ServiceWorker.URLRequestJob.FallbackedRequestMode",
+ mode);
}
void ServiceWorkerMetrics::RecordProcessCreated(bool is_new_process) {
diff --git a/chromium/content/browser/service_worker/service_worker_metrics.h b/chromium/content/browser/service_worker/service_worker_metrics.h
index fe9e9e2d0ee..e0a5ce15932 100644
--- a/chromium/content/browser/service_worker/service_worker_metrics.h
+++ b/chromium/content/browser/service_worker/service_worker_metrics.h
@@ -299,9 +299,6 @@ class ServiceWorkerMetrics {
bool is_shutdown);
static void RecordInstallEventStatus(ServiceWorkerStatusCode status);
- static void RecordForeignFetchRegistrationCount(size_t scope_count,
- size_t origin_count);
-
// Records how often a dispatched event times out.
static void RecordEventTimeout(EventType event);
diff --git a/chromium/content/browser/service_worker/service_worker_navigation_handle.h b/chromium/content/browser/service_worker/service_worker_navigation_handle.h
index c5c69388cf7..e1f32a87465 100644
--- a/chromium/content/browser/service_worker/service_worker_navigation_handle.h
+++ b/chromium/content/browser/service_worker/service_worker_navigation_handle.h
@@ -28,12 +28,12 @@ class ServiceWorkerNavigationHandleCore;
// pointer to the ServiceWorkerNavigationHandleCore.
//
// 3) If we pre-create a ServiceWorkerProviderHost for this navigation, its
-// ownershipped is passed to the ServiceWorkerNavigationHandleCore. The
+// ownership is passed to the ServiceWorkerNavigationHandleCore. The
// ServiceWorkerNavigationHandleCore id is updated.
//
// 4) The ServiceWorkerNavigationHandleCore informs the
-// ServiceWorkerNavigationHandle on the UI that the service worker provider
-// id was updated.
+// ServiceWorkerNavigationHandle on the UI thread that the service worker
+// provider id was updated.
//
// 5) When the navigation is ready to commit, the NavigationRequest will
// update the RequestNavigationParams based on the id from the
diff --git a/chromium/content/browser/service_worker/service_worker_navigation_loader.cc b/chromium/content/browser/service_worker/service_worker_navigation_loader.cc
index deaa67086c7..241e860824a 100644
--- a/chromium/content/browser/service_worker/service_worker_navigation_loader.cc
+++ b/chromium/content/browser/service_worker/service_worker_navigation_loader.cc
@@ -71,7 +71,7 @@ class ServiceWorkerNavigationLoader::StreamWaiter
};
ServiceWorkerNavigationLoader::ServiceWorkerNavigationLoader(
- URLLoaderRequestHandler::LoaderCallback callback,
+ NavigationLoaderInterceptor::LoaderCallback callback,
Delegate* delegate,
const network::ResourceRequest& resource_request,
scoped_refptr<URLLoaderFactoryGetter> url_loader_factory_getter)
@@ -83,12 +83,7 @@ ServiceWorkerNavigationLoader::ServiceWorkerNavigationLoader(
weak_factory_(this) {
DCHECK(ServiceWorkerUtils::IsMainResourceType(
static_cast<ResourceType>(resource_request.resource_type)));
- DCHECK_EQ(network::mojom::FetchRequestMode::kNavigate,
- resource_request_.fetch_request_mode);
- DCHECK_EQ(network::mojom::FetchCredentialsMode::kInclude,
- resource_request_.fetch_credentials_mode);
- DCHECK_EQ(network::mojom::FetchRedirectMode::kManual,
- resource_request_.fetch_redirect_mode);
+
response_head_.load_timing.request_start = base::TimeTicks::Now();
response_head_.load_timing.request_start_time = base::Time::Now();
}
@@ -198,7 +193,7 @@ void ServiceWorkerNavigationLoader::CommitResponseHeaders() {
DCHECK_EQ(Status::kStarted, status_);
DCHECK(url_loader_client_.is_bound());
status_ = Status::kSentHeader;
- url_loader_client_->OnReceiveResponse(response_head_, ssl_info_,
+ url_loader_client_->OnReceiveResponse(response_head_,
nullptr /* downloaded_file */);
}
@@ -264,8 +259,8 @@ void ServiceWorkerNavigationLoader::DidDispatchFetchEvent(
return;
}
- // Creates a new HttpResponseInfo using the the ServiceWorker script's
- // HttpResponseInfo to show HTTPS padlock.
+ // Get SSLInfo from the ServiceWorker script's HttpResponseInfo to show HTTPS
+ // padlock.
// TODO(horo): When we support mixed-content (HTTP) no-cors requests from a
// ServiceWorker, we have to check the security level of the responses.
const net::HttpResponseInfo* main_script_http_info =
@@ -301,6 +296,7 @@ void ServiceWorkerNavigationLoader::StartResponse(
response_head_.did_service_worker_navigation_preload =
did_navigation_preload_;
response_head_.load_timing.receive_headers_end = base::TimeTicks::Now();
+ response_head_.ssl_info = ssl_info_;
// Handle a redirect response. ComputeRedirectInfo returns non-null redirect
// info if the given response is a redirect.
@@ -368,9 +364,9 @@ void ServiceWorkerNavigationLoader::FollowRedirect() {
}
void ServiceWorkerNavigationLoader::ProceedWithResponse() {
- // TODO(arthursonzogni): Implement this for navigation requests if the
- // ServiceWorker service is enabled before the Network Service.
- NOTREACHED();
+ // ServiceWorkerNavigationLoader doesn't need to wait for
+ // ProceedWithResponse() since it doesn't use MojoAsyncResourceHandler to load
+ // the resource request.
}
void ServiceWorkerNavigationLoader::SetPriority(net::RequestPriority priority,
diff --git a/chromium/content/browser/service_worker/service_worker_navigation_loader.h b/chromium/content/browser/service_worker/service_worker_navigation_loader.h
index 29293f14c99..4f12d5b6d15 100644
--- a/chromium/content/browser/service_worker/service_worker_navigation_loader.h
+++ b/chromium/content/browser/service_worker/service_worker_navigation_loader.h
@@ -10,7 +10,7 @@
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
-#include "content/browser/loader/url_loader_request_handler.h"
+#include "content/browser/loader/navigation_loader_interceptor.h"
#include "content/browser/service_worker/service_worker_fetch_dispatcher.h"
#include "content/browser/service_worker/service_worker_metrics.h"
#include "content/browser/service_worker/service_worker_response_type.h"
@@ -21,8 +21,8 @@
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "mojo/public/cpp/system/data_pipe.h"
#include "services/network/public/mojom/url_loader.mojom.h"
-#include "third_party/WebKit/public/mojom/blob/blob.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_stream_handle.mojom.h"
+#include "third_party/blink/public/mojom/blob/blob.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_stream_handle.mojom.h"
namespace content {
@@ -30,17 +30,18 @@ struct ServiceWorkerResponse;
class ServiceWorkerVersion;
// S13nServiceWorker:
-// ServiceWorkerNavigationLoader is the URLLoader used for navigation requests
-// that (potentially) go through a service worker. This loader is only used for
-// the main resource request; once the navigation is committed, the page loads
+// ServiceWorkerNavigationLoader is the URLLoader used for main resource
+// requests (i.e., navigation and shared worker requests) that (potentially) go
+// through a service worker. This loader is only used for the main resource
+// request; once the response is delivered, the resulting client loads
// subresources via ServiceWorkerSubresourceLoader.
//
// This class works similarly to ServiceWorkerURLRequestJob but with
// network::mojom::URLLoader instead of URLRequest.
//
// This class is owned by the job wrapper until it is bound to a URLLoader
-// request. After it is bound |this| is kept alive until the Mojo connection
-// to this URLLoader is dropped.
+// request. After it is bound |this| is kept alive until the Mojo connection to
+// this URLLoader is dropped.
class CONTENT_EXPORT ServiceWorkerNavigationLoader
: public network::mojom::URLLoader {
public:
@@ -48,9 +49,9 @@ class CONTENT_EXPORT ServiceWorkerNavigationLoader
using ResponseType = ServiceWorkerResponseType;
// Created by ServiceWorkerControlleeRequestHandler::MaybeCreateLoader
- // when starting to load a page for navigation.
+ // when starting to load a main resource.
//
- // This job typically works in the following order:
+ // For the navigation case, this job typically works in the following order:
// 1. One of the FallbackTo* or ForwardTo* methods are called via
// URLJobWrapper by ServiceWorkerControlleeRequestHandler, which
// determines how the request should be served (e.g. should fallback
@@ -71,8 +72,11 @@ class CONTENT_EXPORT ServiceWorkerNavigationLoader
// NavigationURLLoaderNetworkService (for resource loading for navigation).
// This forwards the blob/stream data pipe to the NavigationURLLoader if
// the response body was sent as a blob/stream.
+ //
+ // Loads for shared workers work similarly, except SharedWorkerScriptLoader
+ // is used instead of NavigationURLLoaderNetworkService.
ServiceWorkerNavigationLoader(
- URLLoaderRequestHandler::LoaderCallback loader_callback,
+ NavigationLoaderInterceptor::LoaderCallback loader_callback,
Delegate* delegate,
const network::ResourceRequest& resource_request,
scoped_refptr<URLLoaderFactoryGetter> url_loader_factory_getter);
@@ -148,7 +152,7 @@ class CONTENT_EXPORT ServiceWorkerNavigationLoader
void DeleteIfNeeded();
ResponseType response_type_ = ResponseType::NOT_DETERMINED;
- URLLoaderRequestHandler::LoaderCallback loader_callback_;
+ NavigationLoaderInterceptor::LoaderCallback loader_callback_;
Delegate* delegate_;
network::ResourceRequest resource_request_;
diff --git a/chromium/content/browser/service_worker/service_worker_navigation_loader_unittest.cc b/chromium/content/browser/service_worker/service_worker_navigation_loader_unittest.cc
index a2b7c725f88..e37883b9028 100644
--- a/chromium/content/browser/service_worker/service_worker_navigation_loader_unittest.cc
+++ b/chromium/content/browser/service_worker/service_worker_navigation_loader_unittest.cc
@@ -6,7 +6,7 @@
#include "base/run_loop.h"
#include "base/test/scoped_feature_list.h"
-#include "content/browser/loader/url_loader_request_handler.h"
+#include "content/browser/loader/navigation_loader_interceptor.h"
#include "content/browser/service_worker/embedded_worker_test_helper.h"
#include "content/browser/service_worker/service_worker_context_core.h"
#include "content/browser/service_worker/service_worker_registration.h"
@@ -16,8 +16,8 @@
#include "content/common/service_worker/service_worker_utils.h"
#include "content/common/single_request_url_loader_factory.h"
#include "content/public/test/test_browser_thread_bundle.h"
-#include "mojo/common/data_pipe_utils.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
+#include "mojo/public/cpp/system/data_pipe_utils.h"
#include "net/http/http_util.h"
#include "net/ssl/ssl_info.h"
#include "net/test/cert_test_util.h"
@@ -31,8 +31,8 @@
#include "storage/browser/blob/blob_impl.h"
#include "storage/browser/blob/blob_storage_context.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_event_status.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_event_status.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
namespace service_worker_navigation_loader_unittest {
@@ -85,7 +85,6 @@ class NavigationPreloadLoaderClient final
// network::mojom::URLLoaderClient implementation
void OnReceiveResponse(
const network::ResourceResponseHead& response_head,
- const base::Optional<net::SSLInfo>& ssl_info,
network::mojom::DownloadedTempFilePtr downloaded_file) override {
response_head_ = response_head;
}
@@ -178,7 +177,7 @@ class MockNetworkURLLoaderFactory final
network::ResourceResponseHead response;
response.headers = info.headers;
response.headers->GetMimeType(&response.mime_type);
- client->OnReceiveResponse(response, base::nullopt, nullptr);
+ client->OnReceiveResponse(response, nullptr);
std::string body = "this body came from the network";
uint32_t bytes_written = body.size();
@@ -690,8 +689,8 @@ TEST_F(ServiceWorkerNavigationLoaderTest, BlobResponse) {
// Test the body.
std::string body;
EXPECT_TRUE(client_.response_body().is_valid());
- EXPECT_TRUE(mojo::common::BlockingCopyToString(
- client_.response_body_release(), &body));
+ EXPECT_TRUE(
+ mojo::BlockingCopyToString(client_.response_body_release(), &body));
EXPECT_EQ(kResponseBody, body);
EXPECT_EQ(net::OK, client_.completion_status().error_code);
}
@@ -759,8 +758,8 @@ TEST_F(ServiceWorkerNavigationLoaderTest, StreamResponse) {
// Test the body.
std::string response;
EXPECT_TRUE(client_.response_body().is_valid());
- EXPECT_TRUE(mojo::common::BlockingCopyToString(
- client_.response_body_release(), &response));
+ EXPECT_TRUE(
+ mojo::BlockingCopyToString(client_.response_body_release(), &response));
EXPECT_EQ(kResponseBody, response);
}
@@ -797,8 +796,8 @@ TEST_F(ServiceWorkerNavigationLoaderTest, StreamResponse_Abort) {
// Test the body.
std::string response;
EXPECT_TRUE(client_.response_body().is_valid());
- EXPECT_TRUE(mojo::common::BlockingCopyToString(
- client_.response_body_release(), &response));
+ EXPECT_TRUE(
+ mojo::BlockingCopyToString(client_.response_body_release(), &response));
EXPECT_EQ(kResponseBody, response);
}
@@ -949,8 +948,8 @@ TEST_F(ServiceWorkerNavigationLoaderTest, NavigationPreload) {
std::string response;
EXPECT_TRUE(client_.response_body().is_valid());
- EXPECT_TRUE(mojo::common::BlockingCopyToString(
- client_.response_body_release(), &response));
+ EXPECT_TRUE(
+ mojo::BlockingCopyToString(client_.response_body_release(), &response));
EXPECT_EQ("this body came from the network", response);
}
diff --git a/chromium/content/browser/service_worker/service_worker_new_script_loader.cc b/chromium/content/browser/service_worker/service_worker_new_script_loader.cc
index a78f3446514..578d4ad6511 100644
--- a/chromium/content/browser/service_worker/service_worker_new_script_loader.cc
+++ b/chromium/content/browser/service_worker/service_worker_new_script_loader.cc
@@ -18,7 +18,7 @@
#include "content/common/service_worker/service_worker_utils.h"
#include "net/cert/cert_status_flags.h"
#include "services/network/public/cpp/resource_response.h"
-#include "third_party/WebKit/public/common/mime_util/mime_util.h"
+#include "third_party/blink/public/common/mime_util/mime_util.h"
namespace content {
@@ -40,7 +40,9 @@ ServiceWorkerNewScriptLoader::ServiceWorkerNewScriptLoader(
resource_type_(static_cast<ResourceType>(resource_request.resource_type)),
version_(version),
network_client_binding_(this),
- network_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL),
+ network_watcher_(FROM_HERE,
+ mojo::SimpleWatcher::ArmingPolicy::MANUAL,
+ base::SequencedTaskRunnerHandle::Get()),
client_(std::move(client)),
weak_factory_(this) {
// ServiceWorkerNewScriptLoader is used for fetching the service worker main
@@ -94,6 +96,10 @@ ServiceWorkerNewScriptLoader::ServiceWorkerNewScriptLoader(
cache_resource_id);
AdvanceState(State::kStarted);
+ // Disable MIME sniffing sniffing. The spec requires the header list to have
+ // a JavaScript MIME type. Therefore, no sniffing is needed.
+ options &= ~network::mojom::kURLLoadOptionSniffMimeType;
+
network::mojom::URLLoaderClientPtr network_client;
network_client_binding_.Bind(mojo::MakeRequest(&network_client));
loader_factory_getter->GetNetworkFactory()->CreateLoaderAndStart(
@@ -130,10 +136,10 @@ void ServiceWorkerNewScriptLoader::ResumeReadingBodyFromNet() {
void ServiceWorkerNewScriptLoader::OnReceiveResponse(
const network::ResourceResponseHead& response_head,
- const base::Optional<net::SSLInfo>& ssl_info,
network::mojom::DownloadedTempFilePtr downloaded_file) {
if (!version_->context() || version_->is_redundant()) {
- CommitCompleted(network::URLLoaderCompletionStatus(net::ERR_FAILED));
+ CommitCompleted(network::URLLoaderCompletionStatus(net::ERR_FAILED),
+ kServiceWorkerFetchScriptError);
return;
}
@@ -141,8 +147,8 @@ void ServiceWorkerNewScriptLoader::OnReceiveResponse(
// At least we need headers and SSL info.
auto response_info = std::make_unique<net::HttpResponseInfo>();
response_info->headers = response_head.headers;
- if (ssl_info.has_value())
- response_info->ssl_info = *ssl_info;
+ if (response_head.ssl_info.has_value())
+ response_info->ssl_info = *response_head.ssl_info;
response_info->was_fetched_via_spdy = response_head.was_fetched_via_spdy;
response_info->was_alpn_negotiated = response_head.was_alpn_negotiated;
response_info->alpn_negotiated_protocol =
@@ -155,10 +161,12 @@ void ServiceWorkerNewScriptLoader::OnReceiveResponse(
if (response_head.headers->response_code() / 100 != 2) {
// Non-2XX HTTP status code is handled as an error.
- // TODO(nhiroki): Show an error message equivalent to kBadHTTPResponseError
- // in service_worker_write_to_cache_job.cc.
+ std::string error_message =
+ base::StringPrintf(kServiceWorkerBadHTTPResponseError,
+ response_head.headers->response_code());
CommitCompleted(
- network::URLLoaderCompletionStatus(net::ERR_INVALID_RESPONSE));
+ network::URLLoaderCompletionStatus(net::ERR_INVALID_RESPONSE),
+ error_message);
return;
}
@@ -166,25 +174,28 @@ void ServiceWorkerNewScriptLoader::OnReceiveResponse(
if (net::IsCertStatusError(response_head.cert_status) &&
!base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kIgnoreCertificateErrors)) {
- // TODO(nhiroki): Show an error message equivalent to kSSLError in
- // service_worker_write_to_cache_job.cc.
- CommitCompleted(network::URLLoaderCompletionStatus(
- net::MapCertStatusToNetError(response_head.cert_status)));
+ CommitCompleted(
+ network::URLLoaderCompletionStatus(
+ net::MapCertStatusToNetError(response_head.cert_status)),
+ kServiceWorkerSSLError);
return;
}
if (resource_type_ == RESOURCE_TYPE_SERVICE_WORKER) {
if (!blink::IsSupportedJavascriptMimeType(response_head.mime_type)) {
- // TODO(nhiroki): Show an error message equivalent to kNoMIMEError or
- // kBadMIMEError in service_worker_write_to_cache_job.cc.
+ std::string error_message =
+ response_head.mime_type.empty()
+ ? kServiceWorkerNoMIMEError
+ : base::StringPrintf(kServiceWorkerBadMIMEError,
+ response_head.mime_type.c_str());
CommitCompleted(
- network::URLLoaderCompletionStatus(net::ERR_INSECURE_RESPONSE));
+ network::URLLoaderCompletionStatus(net::ERR_INSECURE_RESPONSE),
+ error_message);
return;
}
// Check the path restriction defined in the spec:
// https://w3c.github.io/ServiceWorker/#service-worker-script-response
- const char kServiceWorkerAllowed[] = "Service-Worker-Allowed";
std::string service_worker_allowed;
bool has_header = response_head.headers->EnumerateHeader(
nullptr, kServiceWorkerAllowed, &service_worker_allowed);
@@ -192,9 +203,9 @@ void ServiceWorkerNewScriptLoader::OnReceiveResponse(
if (!ServiceWorkerUtils::IsPathRestrictionSatisfied(
version_->scope(), request_url_,
has_header ? &service_worker_allowed : nullptr, &error_message)) {
- // TODO(nhiroki): Report |error_message|.
CommitCompleted(
- network::URLLoaderCompletionStatus(net::ERR_INSECURE_RESPONSE));
+ network::URLLoaderCompletionStatus(net::ERR_INSECURE_RESPONSE),
+ error_message);
return;
}
@@ -204,8 +215,7 @@ void ServiceWorkerNewScriptLoader::OnReceiveResponse(
WriteHeaders(
base::MakeRefCounted<HttpResponseInfoIOBuffer>(response_info.release()));
- client_->OnReceiveResponse(response_head, ssl_info,
- std::move(downloaded_file));
+ client_->OnReceiveResponse(response_head, std::move(downloaded_file));
}
void ServiceWorkerNewScriptLoader::OnReceiveRedirect(
@@ -215,10 +225,8 @@ void ServiceWorkerNewScriptLoader::OnReceiveRedirect(
//
// Step 7.5: "Set request's redirect mode to "error"."
// https://w3c.github.io/ServiceWorker/#update-algorithm
- //
- // TODO(nhiroki): Show an error message equivalent to kRedirectError in
- // service_worker_write_to_cache_job.cc.
- CommitCompleted(network::URLLoaderCompletionStatus(net::ERR_UNSAFE_REDIRECT));
+ CommitCompleted(network::URLLoaderCompletionStatus(net::ERR_UNSAFE_REDIRECT),
+ kServiceWorkerRedirectError);
}
void ServiceWorkerNewScriptLoader::OnDataDownloaded(int64_t data_len,
@@ -250,7 +258,8 @@ void ServiceWorkerNewScriptLoader::OnStartLoadingResponseBody(
mojo::ScopedDataPipeConsumerHandle client_consumer;
if (mojo::CreateDataPipe(nullptr, &client_producer_, &client_consumer) !=
MOJO_RESULT_OK) {
- CommitCompleted(network::URLLoaderCompletionStatus(net::ERR_FAILED));
+ CommitCompleted(network::URLLoaderCompletionStatus(net::ERR_FAILED),
+ kServiceWorkerFetchScriptError);
return;
}
@@ -264,7 +273,7 @@ void ServiceWorkerNewScriptLoader::OnStartLoadingResponseBody(
void ServiceWorkerNewScriptLoader::OnComplete(
const network::URLLoaderCompletionStatus& status) {
if (status.error_code != net::OK) {
- CommitCompleted(status);
+ CommitCompleted(status, kServiceWorkerFetchScriptError);
return;
}
@@ -279,7 +288,8 @@ void ServiceWorkerNewScriptLoader::OnComplete(
// storage.
return;
case State::kWroteData:
- CommitCompleted(network::URLLoaderCompletionStatus(net::OK));
+ CommitCompleted(network::URLLoaderCompletionStatus(net::OK),
+ std::string() /* status_message */);
return;
}
NOTREACHED() << static_cast<int>(state_);
@@ -328,7 +338,8 @@ void ServiceWorkerNewScriptLoader::WriteHeaders(
void ServiceWorkerNewScriptLoader::OnWriteHeadersComplete(net::Error error) {
DCHECK_NE(net::ERR_IO_PENDING, error);
if (error != net::OK) {
- CommitCompleted(network::URLLoaderCompletionStatus(error));
+ CommitCompleted(network::URLLoaderCompletionStatus(error),
+ kServiceWorkerFetchScriptError);
return;
}
AdvanceState(State::kWroteHeaders);
@@ -371,7 +382,8 @@ void ServiceWorkerNewScriptLoader::OnNetworkDataAvailable(MojoResult) {
// notified via OnComplete().
AdvanceState(State::kWroteData);
if (network_load_completed_)
- CommitCompleted(network::URLLoaderCompletionStatus(net::OK));
+ CommitCompleted(network::URLLoaderCompletionStatus(net::OK),
+ std::string() /* status_message */);
return;
case MOJO_RESULT_SHOULD_WAIT:
network_watcher_.ArmOrNotify();
@@ -387,15 +399,16 @@ void ServiceWorkerNewScriptLoader::WriteData(
// next time.
uint32_t bytes_written = std::min<uint32_t>(kReadBufferSize, bytes_available);
- auto buffer = base::MakeRefCounted<network::MojoToNetIOBuffer>(
- pending_buffer.get(), bytes_written);
+ auto buffer =
+ base::MakeRefCounted<net::WrappedIOBuffer>(pending_buffer->buffer());
MojoResult result = client_producer_->WriteData(
buffer->data(), &bytes_written, MOJO_WRITE_DATA_FLAG_NONE);
switch (result) {
case MOJO_RESULT_OK:
break;
case MOJO_RESULT_FAILED_PRECONDITION:
- CommitCompleted(network::URLLoaderCompletionStatus(net::ERR_FAILED));
+ CommitCompleted(network::URLLoaderCompletionStatus(net::ERR_FAILED),
+ kServiceWorkerFetchScriptError);
return;
case MOJO_RESULT_SHOULD_WAIT:
// No data was written to |client_producer_| because the pipe was full.
@@ -432,7 +445,8 @@ void ServiceWorkerNewScriptLoader::OnWriteDataComplete(
net::Error error) {
DCHECK_NE(net::ERR_IO_PENDING, error);
if (error != net::OK) {
- CommitCompleted(network::URLLoaderCompletionStatus(error));
+ CommitCompleted(network::URLLoaderCompletionStatus(error),
+ kServiceWorkerFetchScriptError);
return;
}
DCHECK(pending_buffer);
@@ -443,7 +457,8 @@ void ServiceWorkerNewScriptLoader::OnWriteDataComplete(
}
void ServiceWorkerNewScriptLoader::CommitCompleted(
- const network::URLLoaderCompletionStatus& status) {
+ const network::URLLoaderCompletionStatus& status,
+ const std::string& status_message) {
AdvanceState(State::kCompleted);
net::Error error_code = static_cast<net::Error>(status.error_code);
int bytes_written = -1;
@@ -459,16 +474,13 @@ void ServiceWorkerNewScriptLoader::CommitCompleted(
} else {
// AddMessageConsole must be called before notifying that an error occurred
// because the worker stops soon after receiving the error response.
- // TODO(nhiroki): Provide more accurate error message instead of
- // |kFetchScriptError|.
// TODO(nhiroki): Consider replacing this hacky way with the new error code
// handling mechanism in URLLoader.
version_->embedded_worker()->AddMessageToConsole(
- blink::WebConsoleMessage::kLevelError, kFetchScriptError);
+ blink::WebConsoleMessage::kLevelError, status_message);
}
version_->script_cache_map()->NotifyFinishedCaching(
- request_url_, bytes_written, error_code,
- std::string() /* status_message */);
+ request_url_, bytes_written, error_code, status_message);
// TODO(nhiroki): Record ServiceWorkerMetrics::CountWriteResponseResult().
// (https://crbug.com/762357)
diff --git a/chromium/content/browser/service_worker/service_worker_new_script_loader.h b/chromium/content/browser/service_worker/service_worker_new_script_loader.h
index 994f24701c1..621ce8ef458 100644
--- a/chromium/content/browser/service_worker/service_worker_new_script_loader.h
+++ b/chromium/content/browser/service_worker/service_worker_new_script_loader.h
@@ -70,7 +70,6 @@ class CONTENT_EXPORT ServiceWorkerNewScriptLoader
// network::mojom::URLLoaderClient for the network load:
void OnReceiveResponse(
const network::ResourceResponseHead& response_head,
- const base::Optional<net::SSLInfo>& ssl_info,
network::mojom::DownloadedTempFilePtr downloaded_file) override;
void OnReceiveRedirect(
const net::RedirectInfo& redirect_info,
@@ -120,7 +119,8 @@ class CONTENT_EXPORT ServiceWorkerNewScriptLoader
// This is the last method that is called on this class. Notifies the final
// result to |client_| and clears all mojo connections etc.
- void CommitCompleted(const network::URLLoaderCompletionStatus& status);
+ void CommitCompleted(const network::URLLoaderCompletionStatus& status,
+ const std::string& status_message);
const GURL request_url_;
diff --git a/chromium/content/browser/service_worker/service_worker_new_script_loader_unittest.cc b/chromium/content/browser/service_worker/service_worker_new_script_loader_unittest.cc
index 5664ba199c8..c034c9c80d5 100644
--- a/chromium/content/browser/service_worker/service_worker_new_script_loader_unittest.cc
+++ b/chromium/content/browser/service_worker/service_worker_new_script_loader_unittest.cc
@@ -13,8 +13,8 @@
#include "content/browser/service_worker/service_worker_disk_cache.h"
#include "content/browser/url_loader_factory_getter.h"
#include "content/public/test/test_browser_thread_bundle.h"
-#include "mojo/common/data_pipe_utils.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
+#include "mojo/public/cpp/system/data_pipe_utils.h"
#include "net/base/test_completion_callback.h"
#include "net/http/http_util.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
@@ -23,7 +23,7 @@
#include "services/network/public/cpp/url_loader_completion_status.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
#include "services/network/test/test_url_loader_client.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
@@ -99,8 +99,7 @@ class MockNetworkURLLoaderFactory final
client->OnReceiveRedirect(net::RedirectInfo(), response_head);
return;
}
- client->OnReceiveResponse(response_head, base::nullopt /* ssl_info */,
- nullptr /* downloaded_file */);
+ client->OnReceiveResponse(response_head, nullptr /* downloaded_file */);
// Pass the response body to the client.
uint32_t bytes_written = response.body.size();
@@ -302,8 +301,8 @@ TEST_F(ServiceWorkerNewScriptLoaderTest, Success) {
EXPECT_TRUE(client_->has_received_response());
EXPECT_TRUE(client_->response_body().is_valid());
std::string response;
- EXPECT_TRUE(mojo::common::BlockingCopyToString(
- client_->response_body_release(), &response));
+ EXPECT_TRUE(
+ mojo::BlockingCopyToString(client_->response_body_release(), &response));
EXPECT_EQ(mock_server_->Get(kScriptURL).body, response);
// The response should also be stored in the storage.
@@ -326,8 +325,8 @@ TEST_F(ServiceWorkerNewScriptLoaderTest, Success_EmptyBody) {
EXPECT_TRUE(client_->has_received_response());
EXPECT_TRUE(client_->response_body().is_valid());
std::string response;
- EXPECT_TRUE(mojo::common::BlockingCopyToString(
- client_->response_body_release(), &response));
+ EXPECT_TRUE(
+ mojo::BlockingCopyToString(client_->response_body_release(), &response));
EXPECT_TRUE(response.empty());
// The response should also be stored in the storage.
@@ -356,8 +355,8 @@ TEST_F(ServiceWorkerNewScriptLoaderTest, Success_LargeBody) {
EXPECT_TRUE(client_->has_received_response());
EXPECT_TRUE(client_->response_body().is_valid());
std::string response;
- EXPECT_TRUE(mojo::common::BlockingCopyToString(
- client_->response_body_release(), &response));
+ EXPECT_TRUE(
+ mojo::BlockingCopyToString(client_->response_body_release(), &response));
EXPECT_EQ(mock_server_->Get(kScriptURL).body, response);
// The response should also be stored in the storage.
@@ -478,8 +477,8 @@ TEST_F(ServiceWorkerNewScriptLoaderTest, Success_PathRestriction) {
EXPECT_TRUE(client_->has_received_response());
EXPECT_TRUE(client_->response_body().is_valid());
std::string response;
- EXPECT_TRUE(mojo::common::BlockingCopyToString(
- client_->response_body_release(), &response));
+ EXPECT_TRUE(
+ mojo::BlockingCopyToString(client_->response_body_release(), &response));
EXPECT_EQ(mock_server_->Get(kScriptURL).body, response);
// The response should also be stored in the storage.
diff --git a/chromium/content/browser/service_worker/service_worker_process_manager.cc b/chromium/content/browser/service_worker/service_worker_process_manager.cc
index f47f72cd9d6..79850cf30c1 100644
--- a/chromium/content/browser/service_worker/service_worker_process_manager.cc
+++ b/chromium/content/browser/service_worker/service_worker_process_manager.cc
@@ -66,7 +66,8 @@ void ServiceWorkerProcessManager::Shutdown() {
if (it.second->HasProcess()) {
RenderProcessHost* process = it.second->GetProcess();
if (!process->IsKeepAliveRefCountDisabled())
- process->DecrementKeepAliveRefCount();
+ process->DecrementKeepAliveRefCount(
+ RenderProcessHost::KeepAliveClientType::kServiceWorker);
}
}
}
@@ -156,7 +157,8 @@ ServiceWorkerStatusCode ServiceWorkerProcessManager::AllocateWorkerProcess(
worker_process_map_.emplace(embedded_worker_id, std::move(site_instance));
if (!rph->IsKeepAliveRefCountDisabled())
- rph->IncrementKeepAliveRefCount();
+ rph->IncrementKeepAliveRefCount(
+ RenderProcessHost::KeepAliveClientType::kServiceWorker);
out_info->process_id = rph->GetID();
out_info->start_situation = start_situation;
return SERVICE_WORKER_OK;
@@ -186,7 +188,8 @@ void ServiceWorkerProcessManager::ReleaseWorkerProcess(int embedded_worker_id) {
if (it->second->HasProcess()) {
RenderProcessHost* process = it->second->GetProcess();
if (!process->IsKeepAliveRefCountDisabled())
- process->DecrementKeepAliveRefCount();
+ process->DecrementKeepAliveRefCount(
+ RenderProcessHost::KeepAliveClientType::kServiceWorker);
}
worker_process_map_.erase(it);
}
diff --git a/chromium/content/browser/service_worker/service_worker_process_manager_unittest.cc b/chromium/content/browser/service_worker/service_worker_process_manager_unittest.cc
index 21bba85474e..0139091213d 100644
--- a/chromium/content/browser/service_worker/service_worker_process_manager_unittest.cc
+++ b/chromium/content/browser/service_worker/service_worker_process_manager_unittest.cc
@@ -5,7 +5,6 @@
#include "content/browser/service_worker/service_worker_process_manager.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/test/scoped_feature_list.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/site_instance_impl.h"
@@ -36,7 +35,11 @@ class SiteInstanceRenderProcessHostFactory : public RenderProcessHostFactory {
SiteInstance* site_instance) const override {
processes_.push_back(
std::make_unique<MockRenderProcessHost>(browser_context));
- last_site_instance_used_ = site_instance;
+
+ // A spare RenderProcessHost is created with a null SiteInstance.
+ if (site_instance)
+ last_site_instance_used_ = site_instance;
+
return processes_.back().get();
}
diff --git a/chromium/content/browser/service_worker/service_worker_provider_host.cc b/chromium/content/browser/service_worker/service_worker_provider_host.cc
index 3fd12f21fa4..bdbd4e18287 100644
--- a/chromium/content/browser/service_worker/service_worker_provider_host.cc
+++ b/chromium/content/browser/service_worker/service_worker_provider_host.cc
@@ -30,6 +30,7 @@
#include "content/common/service_worker/service_worker_messages.h"
#include "content/common/service_worker/service_worker_types.h"
#include "content/common/service_worker/service_worker_utils.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
@@ -42,10 +43,10 @@
#include "net/base/url_util.h"
#include "services/network/public/cpp/resource_request_body.h"
#include "storage/browser/blob/blob_storage_context.h"
-#include "third_party/WebKit/public/common/message_port/message_port_channel.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_client.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/common/message_port/message_port_channel.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_client.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
@@ -109,15 +110,14 @@ class ServiceWorkerURLTrackingRequestHandler
void RemoveProviderHost(base::WeakPtr<ServiceWorkerContextCore> context,
int process_id,
int provider_id) {
- // Temporary CHECK for debugging https://crbug.com/750267.
- CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
+ DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
TRACE_EVENT0("ServiceWorker",
"ServiceWorkerProviderHost::RemoveProviderHost");
if (!context || !context->GetProviderHost(process_id, provider_id)) {
- // In some cancellation of navigation cases, it is possible for the
- // pre-created host, whose |provider_id| is assigned by the browser process,
- // to have been destroyed before being claimed by the renderer. The provider
- // is then destroyed in the renderer, and no matching host will be found.
+ // In some cases, it is possible for the Mojo endpoint of a pre-created
+ // host to be destroyed before being claimed by the renderer and
+ // having the host become owned by ServiceWorkerContextCore. The owner of
+ // the host is responsible for deleting the host, so just return here.
return;
}
context->RemoveProviderHost(process_id, provider_id);
@@ -136,6 +136,38 @@ void GetInterfaceImpl(const std::string& interface_name,
origin);
}
+ServiceWorkerMetrics::EventType PurposeToEventType(
+ mojom::ControllerServiceWorkerPurpose purpose) {
+ switch (purpose) {
+ case mojom::ControllerServiceWorkerPurpose::FETCH_SUB_RESOURCE:
+ return ServiceWorkerMetrics::EventType::FETCH_SUB_RESOURCE;
+ }
+ NOTREACHED();
+ return ServiceWorkerMetrics::EventType::UNKNOWN;
+}
+
+// TODO(crbug/831255): Temporary debugging for the linked bug.
+std::string URLStringForBadMessage(const GURL& url) {
+ return url.possibly_invalid_spec().substr(0, 64);
+}
+
+// TODO(crbug/831255): Temporary debugging for the linked bug.
+std::string ProviderTypeStringForBadMessage(
+ blink::mojom::ServiceWorkerProviderType type) {
+ switch (type) {
+ case blink::mojom::ServiceWorkerProviderType::kUnknown:
+ return "unknown";
+ case blink::mojom::ServiceWorkerProviderType::kForSharedWorker:
+ return "shared";
+ case blink::mojom::ServiceWorkerProviderType::kForServiceWorker:
+ return "service";
+ case blink::mojom::ServiceWorkerProviderType::kForWindow:
+ return "window";
+ }
+ NOTREACHED();
+ return std::string();
+}
+
} // anonymous namespace
// static
@@ -170,13 +202,43 @@ ServiceWorkerProviderHost::PreCreateForController(
}
// static
+base::WeakPtr<ServiceWorkerProviderHost>
+ServiceWorkerProviderHost::PreCreateForSharedWorker(
+ base::WeakPtr<ServiceWorkerContextCore> context,
+ int process_id,
+ mojom::ServiceWorkerProviderInfoForSharedWorkerPtr* out_provider_info) {
+ auto host = base::WrapUnique(new ServiceWorkerProviderHost(
+ ChildProcessHost::kInvalidUniqueID,
+ ServiceWorkerProviderHostInfo(
+ NextBrowserProvidedProviderId(), MSG_ROUTING_NONE,
+ blink::mojom::ServiceWorkerProviderType::kForSharedWorker,
+ true /* is_parent_frame_secure */),
+ context, nullptr));
+ host->dispatcher_host_ = context->GetDispatcherHost(process_id)->AsWeakPtr();
+ host->render_process_id_ = process_id;
+
+ (*out_provider_info)->provider_id = host->provider_id();
+ (*out_provider_info)->client_request = mojo::MakeRequest(&host->container_);
+ host->binding_.Bind(
+ mojo::MakeRequest(&((*out_provider_info)->host_ptr_info)));
+ host->binding_.set_connection_error_handler(base::BindOnce(
+ &RemoveProviderHost, context, process_id, host->provider_id()));
+
+ auto weak_ptr = host->AsWeakPtr();
+ context->AddProviderHost(std::move(host));
+ return weak_ptr;
+}
+
+// static
std::unique_ptr<ServiceWorkerProviderHost> ServiceWorkerProviderHost::Create(
int process_id,
ServiceWorkerProviderHostInfo info,
base::WeakPtr<ServiceWorkerContextCore> context,
base::WeakPtr<ServiceWorkerDispatcherHost> dispatcher_host) {
- return base::WrapUnique(new ServiceWorkerProviderHost(
+ auto host = base::WrapUnique(new ServiceWorkerProviderHost(
process_id, std::move(info), context, dispatcher_host));
+ host->is_execution_ready_ = true;
+ return host;
}
ServiceWorkerProviderHost::ServiceWorkerProviderHost(
@@ -220,8 +282,7 @@ ServiceWorkerProviderHost::ServiceWorkerProviderHost(
}
ServiceWorkerProviderHost::~ServiceWorkerProviderHost() {
- // Temporary CHECK for debugging https://crbug.com/750267.
- CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
+ DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
if (context_)
context_->UnregisterProviderHostByClientID(client_uuid_);
@@ -353,6 +414,11 @@ void ServiceWorkerProviderHost::SetControllerVersionAttribute(
SendSetControllerServiceWorker(notify_controllerchange);
}
+bool ServiceWorkerProviderHost::IsProviderForServiceWorker() const {
+ return info_.type ==
+ blink::mojom::ServiceWorkerProviderType::kForServiceWorker;
+}
+
bool ServiceWorkerProviderHost::IsProviderForClient() const {
switch (info_.type) {
case blink::mojom::ServiceWorkerProviderType::kForWindow:
@@ -361,7 +427,7 @@ bool ServiceWorkerProviderHost::IsProviderForClient() const {
case blink::mojom::ServiceWorkerProviderType::kForServiceWorker:
return false;
case blink::mojom::ServiceWorkerProviderType::kUnknown:
- NOTREACHED() << info_.type;
+ break;
}
NOTREACHED() << info_.type;
return false;
@@ -376,7 +442,7 @@ blink::mojom::ServiceWorkerClientType ServiceWorkerProviderHost::client_type()
return blink::mojom::ServiceWorkerClientType::kSharedWorker;
case blink::mojom::ServiceWorkerProviderType::kForServiceWorker:
case blink::mojom::ServiceWorkerProviderType::kUnknown:
- NOTREACHED() << info_.type;
+ break;
}
NOTREACHED() << info_.type;
return blink::mojom::ServiceWorkerClientType::kWindow;
@@ -445,6 +511,11 @@ void ServiceWorkerProviderHost::RemoveServiceWorkerRegistrationObjectHost(
registration_object_hosts_.erase(registration_id);
}
+void ServiceWorkerProviderHost::RemoveServiceWorkerHandle(int64_t version_id) {
+ DCHECK(base::ContainsKey(handles_, version_id));
+ handles_.erase(version_id);
+}
+
bool ServiceWorkerProviderHost::AllowServiceWorker(const GURL& scope) {
return GetContentClient()->browser()->AllowServiceWorker(
scope, IsProviderForClient() ? topmost_frame_url() : document_url(),
@@ -476,10 +547,8 @@ ServiceWorkerProviderHost::CreateRequestHandler(
// scripts.
// TODO(falken): Really it should be treated as an error to set
// |skip_service_worker| for requests to start the service worker, but it's
- // difficult to fix that renderer-side, since we don't know whether a request
- // is for a service worker without access to IsHostToRunningServiceWorker() as
- // that state is stored browser-side.
- if (IsHostToRunningServiceWorker() &&
+ // difficult to fix that renderer-side (maybe try after S13nServiceWorker).
+ if (IsProviderForServiceWorker() &&
(resource_type == RESOURCE_TYPE_SERVICE_WORKER ||
resource_type == RESOURCE_TYPE_SCRIPT)) {
skip_service_worker = false;
@@ -490,7 +559,7 @@ ServiceWorkerProviderHost::CreateRequestHandler(
return std::make_unique<ServiceWorkerURLTrackingRequestHandler>(
context_, AsWeakPtr(), blob_storage_context, resource_type);
}
- if (IsHostToRunningServiceWorker()) {
+ if (IsProviderForServiceWorker()) {
return std::make_unique<ServiceWorkerContextRequestHandler>(
context_, AsWeakPtr(), blob_storage_context, resource_type);
}
@@ -508,29 +577,15 @@ ServiceWorkerProviderHost::GetOrCreateServiceWorkerHandle(
ServiceWorkerVersion* version) {
if (!context_ || !version)
return nullptr;
- if (!dispatcher_host_) {
- DCHECK(ServiceWorkerUtils::IsServicificationEnabled() ||
- IsNavigationMojoResponseEnabled());
- blink::mojom::ServiceWorkerObjectInfoPtr info;
- // This is called before the dispatcher host is created.
- // |precreated_controller_handle_| instance's lifetime is controlled by its
- // own internal Mojo connections via |info|.
- precreated_controller_handle_ = ServiceWorkerHandle::Create(
- nullptr, context_, AsWeakPtr(), version, &info);
- return info;
- }
- ServiceWorkerHandle* handle = dispatcher_host_->FindServiceWorkerHandle(
- provider_id(), version->version_id());
- if (handle) {
- return handle->CreateObjectInfo();
- }
- blink::mojom::ServiceWorkerObjectInfoPtr info;
- // ServiceWorkerHandle lifetime is controlled by |info| and is also owned by
- // |dispatcher_host_|.
- ServiceWorkerHandle::Create(dispatcher_host_.get(), context_, AsWeakPtr(),
- version, &info);
- return info;
+ const int64_t version_id = version->version_id();
+ auto existing_handle = handles_.find(version_id);
+ if (existing_handle != handles_.end())
+ return existing_handle->second->CreateObjectInfo();
+
+ handles_[version_id] =
+ std::make_unique<ServiceWorkerHandle>(context_, this, version);
+ return handles_[version_id]->CreateObjectInfo();
}
bool ServiceWorkerProviderHost::CanAssociateRegistration(
@@ -555,17 +610,12 @@ void ServiceWorkerProviderHost::PostMessageToClient(
std::move(message));
}
-void ServiceWorkerProviderHost::CountFeature(uint32_t feature) {
+void ServiceWorkerProviderHost::CountFeature(blink::mojom::WebFeature feature) {
if (!dispatcher_host_)
return;
// CountFeature message should be sent only for clients.
DCHECK(IsProviderForClient());
- DCHECK_LT(feature,
- static_cast<uint32_t>(blink::mojom::WebFeature::kNumberOfFeatures));
-
- blink::mojom::WebFeature web_feature =
- static_cast<blink::mojom::WebFeature>(feature);
- container_->CountFeature(web_feature);
+ container_->CountFeature(feature);
}
void ServiceWorkerProviderHost::ClaimedByRegistration(
@@ -592,6 +642,8 @@ void ServiceWorkerProviderHost::CompleteNavigationInitialized(
DCHECK_EQ(info_.provider_id, info.provider_id);
DCHECK_NE(MSG_ROUTING_NONE, info.route_id);
+ is_execution_ready_ = true;
+
// Connect with the mojom::ServiceWorkerContainer on the renderer.
DCHECK(!container_.is_bound());
DCHECK(!binding_.is_bound());
@@ -609,18 +661,6 @@ void ServiceWorkerProviderHost::CompleteNavigationInitialized(
if (!controller_)
return;
- if ((ServiceWorkerUtils::IsServicificationEnabled() ||
- IsNavigationMojoResponseEnabled()) &&
- precreated_controller_handle_) {
- // S13nServiceWorker: register the pre-created handle for the controller
- // service worker with the dispatcher host, now that it exists.
- DCHECK_NE(blink::mojom::kInvalidServiceWorkerHandleId,
- precreated_controller_handle_->handle_id());
- precreated_controller_handle_->RegisterIntoDispatcherHost(
- dispatcher_host_.get());
- precreated_controller_handle_ = nullptr;
- }
-
// In S13nServiceWorker/NavigationMojoResponse case the controller is already
// sent in navigation commit, but we still need this for
// S13nServiceWorker/NavigationMojoResponse case for setting the use counter
@@ -650,6 +690,7 @@ ServiceWorkerProviderHost::CompleteStartWorkerPreparation(
DCHECK(dispatcher_host);
render_process_id_ = process_id;
dispatcher_host_ = dispatcher_host->AsWeakPtr();
+ SetDocumentUrl(running_hosted_version()->script_url());
// Retrieve the registration associated with |version|. The registration
// must be alive because the version keeps it during starting worker.
@@ -684,13 +725,15 @@ ServiceWorkerProviderHost::CompleteStartWorkerPreparation(
mojom::kNavigation_ServiceWorkerSpec, process_id,
mojo::MakeRequest(&provider_info->interface_provider)));
- // Set the document URL to the script url in order to allow
- // register/unregister/getRegistration on ServiceWorkerGlobalScope.
- SetDocumentUrl(running_hosted_version()->script_url());
-
return provider_info;
}
+void ServiceWorkerProviderHost::CompleteSharedWorkerPreparation() {
+ DCHECK_EQ(blink::mojom::ServiceWorkerProviderType::kForSharedWorker,
+ provider_type());
+ is_execution_ready_ = true;
+}
+
void ServiceWorkerProviderHost::SendServiceWorkerStateChangedMessage(
int worker_handle_id,
blink::mojom::ServiceWorkerState state) {
@@ -796,11 +839,8 @@ void ServiceWorkerProviderHost::SendSetControllerServiceWorker(
// Populate used features for UseCounter purposes.
std::vector<blink::mojom::WebFeature> used_features;
- for (const uint32_t feature : controller_->used_features()) {
- DCHECK_LT(feature, static_cast<uint32_t>(
- blink::mojom::WebFeature::kNumberOfFeatures));
- used_features.push_back(static_cast<blink::mojom::WebFeature>(feature));
- }
+ for (const blink::mojom::WebFeature feature : controller_->used_features())
+ used_features.push_back(feature);
// S13nServiceWorker: Pass an endpoint for the client to talk to this
// controller.
@@ -1042,16 +1082,26 @@ void ServiceWorkerProviderHost::GetRegistrationForReady(
ReturnRegistrationForReadyIfNeeded();
}
-void ServiceWorkerProviderHost::GetControllerServiceWorker(
- mojom::ControllerServiceWorkerRequest controller_request) {
+void ServiceWorkerProviderHost::StartControllerComplete(
+ mojom::ControllerServiceWorkerRequest controller_request,
+ ServiceWorkerStatusCode status) {
+ DCHECK(ServiceWorkerUtils::IsServicificationEnabled());
+ if (status == SERVICE_WORKER_OK)
+ controller_->controller()->Clone(std::move(controller_request));
+}
+
+void ServiceWorkerProviderHost::EnsureControllerServiceWorker(
+ mojom::ControllerServiceWorkerRequest controller_request,
+ mojom::ControllerServiceWorkerPurpose purpose) {
// TODO(kinuko): Log the reasons we drop the request.
if (!dispatcher_host_ || !IsContextAlive() || !controller_)
return;
- // TODO(kinuko): Call version_->StartWorker() here if the service
- // is not starting or running. https://crbug.com/797222
DCHECK(ServiceWorkerUtils::IsServicificationEnabled());
- controller_->controller()->Clone(std::move(controller_request));
+ controller_->RunAfterStartWorker(
+ PurposeToEventType(purpose),
+ base::BindOnce(&ServiceWorkerProviderHost::StartControllerComplete,
+ AsWeakPtr(), std::move(controller_request)));
}
void ServiceWorkerProviderHost::CloneForWorker(
@@ -1061,6 +1111,10 @@ void ServiceWorkerProviderHost::CloneForWorker(
std::move(container_host_request));
}
+void ServiceWorkerProviderHost::Ping(PingCallback callback) {
+ std::move(callback).Run();
+}
+
bool ServiceWorkerProviderHost::IsValidRegisterMessage(
const GURL& script_url,
const blink::mojom::ServiceWorkerRegistrationOptions& options,
@@ -1069,17 +1123,41 @@ bool ServiceWorkerProviderHost::IsValidRegisterMessage(
*out_error = ServiceWorkerConsts::kBadMessageFromNonWindow;
return false;
}
- if (!options.scope.is_valid() || !script_url.is_valid()) {
- *out_error = ServiceWorkerConsts::kBadMessageInvalidURL;
+ // TODO(crbug/831255): Temporary detailed messages for the linked bug.
+ // These message are compact since there are only 256 characters available.
+ const std::string provider_str =
+ ProviderTypeStringForBadMessage(provider_type());
+ std::stringstream stream;
+ if (!document_url_.is_valid()) {
+ stream << "SWPH_REGISTER_INVALID_DOCUMENT:" << provider_str
+ << "d=" << URLStringForBadMessage(document_url_);
+ *out_error = stream.str();
return false;
}
+ if (!options.scope.is_valid()) {
+ stream << "SWPH_REGISTER_INVALID_SCOPE:" << provider_str
+ << "p=" << URLStringForBadMessage(options.scope);
+ *out_error = stream.str();
+ return false;
+ }
+ if (!script_url.is_valid()) {
+ stream << "SWPH_REGISTER_INVALID_SCRIPT: " << provider_str
+ << "s=" << URLStringForBadMessage(script_url);
+ *out_error = stream.str();
+ return false;
+ }
+
if (ServiceWorkerUtils::ContainsDisallowedCharacter(options.scope, script_url,
out_error)) {
return false;
}
- std::vector<GURL> urls = {document_url(), options.scope, script_url};
+ std::vector<GURL> urls = {document_url_, options.scope, script_url};
if (!ServiceWorkerUtils::AllOriginsMatchAndCanAccessServiceWorkers(urls)) {
- *out_error = ServiceWorkerConsts::kBadMessageImproperOrigins;
+ stream << "SWPH_REGISTER:" << provider_str
+ << ",d=" << URLStringForBadMessage(document_url_)
+ << ",p=" << URLStringForBadMessage(options.scope)
+ << ",s=" << URLStringForBadMessage(script_url);
+ *out_error = stream.str();
return false;
}
@@ -1141,7 +1219,7 @@ void ServiceWorkerProviderHost::GetInterface(
mojo::ScopedMessagePipeHandle interface_pipe) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DCHECK_NE(kDocumentMainThreadId, render_thread_id_);
- DCHECK(IsHostToRunningServiceWorker());
+ DCHECK(IsProviderForServiceWorker());
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::BindOnce(
diff --git a/chromium/content/browser/service_worker/service_worker_provider_host.h b/chromium/content/browser/service_worker/service_worker_provider_host.h
index 4187669e5f9..a82b1ffd2b5 100644
--- a/chromium/content/browser/service_worker/service_worker_provider_host.h
+++ b/chromium/content/browser/service_worker/service_worker_provider_host.h
@@ -32,13 +32,18 @@
#include "mojo/public/cpp/bindings/binding_set.h"
#include "services/network/public/mojom/fetch_api.mojom.h"
#include "services/network/public/mojom/request_context_frame_type.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_provider_type.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_provider_type.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/platform/web_feature.mojom.h"
namespace network {
class ResourceRequestBody;
}
+namespace service_worker_handle_unittest {
+class ServiceWorkerHandleTest;
+}
+
namespace storage {
class BlobStorageContext;
}
@@ -60,38 +65,64 @@ FORWARD_DECLARE_TEST(ServiceWorkerDispatcherHostTest,
DispatchExtendableMessageEvent_Fail);
} // namespace service_worker_dispatcher_host_unittest
-// This class is the browser-process representation of a service worker
-// provider. There are two general types of providers: 1) those for a client
-// (windows or shared workers), and 2) those for hosting a running service
-// worker.
+// ServiceWorkerProviderHost is the browser-process representation of a
+// renderer-process entity that can involve service workers. Currently, these
+// entities are frames or workers. So basically, one ServiceWorkerProviderHost
+// instance is the browser process's source of truth about one frame/worker in a
+// renderer process, which the browser process uses when performing operations
+// involving service workers.
+//
+// ServiceWorkerProviderHost lives on the IO thread, since all nearly all
+// browser process service worker machinery lives on the IO thread.
+//
+// Example:
+// * A new service worker registration is created. The browser process loops
+// over all ServiceWorkerProviderHosts to find clients (frames and shared
+// workers) with a URL inside the registration's scope, and has the provider
+// host watch the registration in order to resolve navigator.serviceWorker.ready
+// once the registration settles, if neeed.
+//
+// "Provider" is a somewhat tricky term. The idea is that a provider is what
+// attaches to a frame/worker and "provides" it with functionality related to
+// service workers. This functionality is mostly granted by creating the
+// ServiceWorkerProviderHost for this frame/worker, which, again, makes the
+// frame/worker alive in the browser's service worker world.
+//
+// The analogue of ServiceWorkerProviderHost ("provider host") on the renderer
+// process is ServiceWorkerProviderContext ("provider"). A provider host has a
+// Mojo connection to the provider in the renderer. Destruction of the host
+// happens upon disconnection of the Mojo pipe.
+//
+// There are two general types of providers:
+// 1) those for service worker clients (windows or shared workers), and
+// 2) those for service workers themselves.
//
-// For client providers, there is a provider per document or a worker and the
-// lifetime of this object is tied to the lifetime of its document or the worker
-// in the renderer process. This class holds service worker state that is scoped
-// to an individual document or a worker.
+// For client providers, there is a provider per frame or shared worker in the
+// renderer process. The lifetime of this host object is tied to the lifetime of
+// the document or the worker.
//
-// For providers hosting a running service worker, this class will observe
-// resource loads made directly by the service worker.
+// For service worker providers, there is a provider per running service worker
+// in the renderer process. The lifetime of this host object is tied to the
+// lifetime of the running service worker.
//
// A ServiceWorkerProviderHost is created in the following situations:
//
// 1) For a client created for a navigation (for both top-level and
// non-top-level frames), the provider host for the resulting document is
-// pre-created by the browser process. Upon navigation commit, the
-// ServiceWorkerNetworkProvider is created on the renderer, at which point the
-// Mojo connection is established.
+// pre-created by the browser process. Upon navigation commit, the provider is
+// created on the renderer, which sends an OnProviderCreated IPC to establish
+// the Mojo connection.
//
-// 2) For clients created by the renderer not due to navigations (SharedWorkers
-// and about:blank iframes), the provider host is created when the
-// ServiceWorkerNetworkProvider is created by the renderer process.
+// 2) For clients created by the renderer not due to navigations (shared workers
+// in the non-S13nServiceWorker case, and about:blank iframes), the provider
+// host is created and the Mojo connection is established when the provider is
+// created by the renderer process and sends an OnProviderCreated IPC.
//
-// 3) For service workers, the provider host is created on the browser process
-// before sending the start worker IPC message. The provider host's Mojo's
-// connection to the renderer is established in the start worker message.
-//
-// Destruction of the ServiceWorkerProviderHost instance happens on
-// disconnection of the Mojo's pipe from the renderer side regardless of what
-// the provider is for.
+// 3) For shared workers in the S13nServiceWorker case and for service workers,
+// the provider host is pre-created by the browser process, and information
+// about the host is sent in the start worker IPC message. The Mojo connection
+// is established when renderer process receives the start message and creates
+// the provider.
class CONTENT_EXPORT ServiceWorkerProviderHost
: public ServiceWorkerRegistration::Listener,
public base::SupportsWeakPtr<ServiceWorkerProviderHost>,
@@ -111,12 +142,22 @@ class CONTENT_EXPORT ServiceWorkerProviderHost
bool are_ancestors_secure,
const WebContentsGetter& web_contents_getter);
- // Creates a ServiceWorkerProviderHost for hosting a running service worker.
+ // Creates a ServiceWorkerProviderHost for a service worker execution context.
// Information about this provider host is passed down to the service worker
// via StartWorker message.
static std::unique_ptr<ServiceWorkerProviderHost> PreCreateForController(
base::WeakPtr<ServiceWorkerContextCore> context);
+ // S13nServiceWorker:
+ // Used for starting a shared worker. Returns a provider host for the shared
+ // worker and fills |out_provider_info| with info to send to the renderer to
+ // connect to the host. The host stays alive as long as this info stays alive
+ // (namely, as long as |out_provider_info->host_ptr_info| stays alive).
+ static base::WeakPtr<ServiceWorkerProviderHost> PreCreateForSharedWorker(
+ base::WeakPtr<ServiceWorkerContextCore> context,
+ int process_id,
+ mojom::ServiceWorkerProviderInfoForSharedWorkerPtr* out_provider_info);
+
// Used to create a ServiceWorkerProviderHost when the renderer-side provider
// is created. This ProviderHost will be created for the process specified by
// |process_id|.
@@ -150,10 +191,6 @@ class CONTENT_EXPORT ServiceWorkerProviderHost
// security, so they must be set properly before calling this function.
bool IsContextSecureForServiceWorker() const;
- bool IsHostToRunningServiceWorker() {
- return running_hosted_version_.get() != nullptr;
- }
-
// Returns this provider's controller. The controller is typically the same as
// active_version() but can differ in the following cases:
// (1) The client was created before the registration existed or had an active
@@ -197,8 +234,9 @@ class CONTENT_EXPORT ServiceWorkerProviderHost
return associated_registration_.get();
}
- // The running version, if any, that this provider is providing resource
- // loads for.
+ // For service worker execution contexts. The version of the service worker.
+ // This is nullptr when the worker is still starting up (until
+ // CompleteStartWorkerPreparation() is called).
ServiceWorkerVersion* running_hosted_version() const {
DCHECK(!running_hosted_version_ ||
info_.type ==
@@ -207,8 +245,8 @@ class CONTENT_EXPORT ServiceWorkerProviderHost
}
// S13nServiceWorker:
- // For service worker clients. Similar to GetControllerServiceWorker, but this
- // returns a bound Mojo ptr which is supposed to be sent to clients. The
+ // For service worker clients. Similar to EnsureControllerServiceWorker, but
+ // this returns a bound Mojo ptr which is supposed to be sent to clients. The
// controller ptr passed to the clients will be used to intercept requests
// from them.
// It is invalid to call this when controller_ is null.
@@ -224,6 +262,21 @@ class CONTENT_EXPORT ServiceWorkerProviderHost
//
// This may return nullptr if the controller service worker does not have a
// fetch handler, i.e. when the renderer does not need the controller ptr.
+ //
+ // WARNING:
+ // Unlike EnsureControllerServiceWorker, this method doesn't guarantee that
+ // the controller worker is running because this method can be called in some
+ // situations where the worker isn't running yet. When the returned ptr is
+ // stored somewhere and intended to use later, clients need to make sure
+ // that the worker is eventually started to use the ptr.
+ // Currently all the callsites do this, i.e. they start the worker before
+ // or after calling this, but there's no mechanism to prevent future breakage.
+ // TODO(crbug.com/827935): Figure out a way to prevent misuse of this method.
+ // TODO(crbug.com/827935): Make sure the connection error handler fires in
+ // ControllerServiceWorkerConnector (so that it can correctly call
+ // EnsureControllerServiceWorker later) if the worker gets killed before
+ // events are dispatched.
+ //
// TODO(kinuko): revisit this if we start to use the ControllerServiceWorker
// for posting messages.
mojom::ControllerServiceWorkerPtr GetControllerServiceWorkerPtr();
@@ -231,19 +284,27 @@ class CONTENT_EXPORT ServiceWorkerProviderHost
// Sets the |document_url_|. When this object is for a client,
// |matching_registrations_| gets also updated to ensure that |document_url_|
// is in scope of all |matching_registrations_|.
+ // |document_url_| is the service worker script URL if this is for a
+ // service worker execution context. It will be used when creating
+ // ServiceWorkerHandle or handling ServiceWorkerRegistration#{*} calls etc.
+ // TODO(leonhsl): We should rename |document_url_| to something more
+ // appropriate and/or split this class into one for clients vs one for service
+ // workers.
void SetDocumentUrl(const GURL& url);
const GURL& document_url() const { return document_url_; }
// For service worker clients. Sets the |topmost_frame_url|.
void SetTopmostFrameUrl(const GURL& url);
// For service worker clients, used for permission checks. Use document_url()
- // instead if |this| is hosting a running service worker.
+ // instead if |this| is for a service worker execution context.
const GURL& topmost_frame_url() const;
blink::mojom::ServiceWorkerProviderType provider_type() const {
return info_.type;
}
+ bool IsProviderForServiceWorker() const;
bool IsProviderForClient() const;
+ // Can only be called when IsProviderForClient() is true.
blink::mojom::ServiceWorkerClientType client_type() const;
// For service worker clients. Associates to |registration| to listen for its
@@ -275,6 +336,8 @@ class CONTENT_EXPORT ServiceWorkerProviderHost
// The object info holds a Mojo connection to the ServiceWorkerHandle for the
// |version| to ensure the handle stays alive while the object info is alive.
// A new handle is created if one does not already exist.
+ // TODO(leonhsl): Make |version| be a scoped_refptr because we'll take its
+ // ownership.
blink::mojom::ServiceWorkerObjectInfoPtr GetOrCreateServiceWorkerHandle(
ServiceWorkerVersion* version);
@@ -296,7 +359,7 @@ class CONTENT_EXPORT ServiceWorkerProviderHost
// Notifies the client that its controller used a feature, for UseCounter
// purposes. This can only be called if IsProviderForClient() is true.
- void CountFeature(uint32_t feature);
+ void CountFeature(blink::mojom::WebFeature feature);
// |registration| claims the document to be controlled.
void ClaimedByRegistration(ServiceWorkerRegistration* registration);
@@ -318,6 +381,10 @@ class CONTENT_EXPORT ServiceWorkerProviderHost
int process_id,
scoped_refptr<ServiceWorkerVersion> hosted_version);
+ // Called when the shared worker main script resource has finished loading.
+ // After this is called, is_execution_ready() returns true.
+ void CompleteSharedWorkerPreparation();
+
// Sends event messages to the renderer. Events for the worker are queued up
// until the worker thread id is known via SetReadyToSendMessagesToWorker().
void SendServiceWorkerStateChangedMessage(
@@ -338,6 +405,9 @@ class CONTENT_EXPORT ServiceWorkerProviderHost
// |registration_id|.
void RemoveServiceWorkerRegistrationObjectHost(int64_t registration_id);
+ // Removes the ServiceWorkerHandle corresponding to |version_id|.
+ void RemoveServiceWorkerHandle(int64_t version_id);
+
// Calls ContentBrowserClient::AllowServiceWorker(). Returns true if content
// settings allows service workers to run at |scope|. If this provider is for
// a window client, the check involves the topmost frame url as well as
@@ -349,11 +419,14 @@ class CONTENT_EXPORT ServiceWorkerProviderHost
// cache.
void NotifyControllerLost();
+ bool is_execution_ready() const { return is_execution_ready_; }
+
private:
friend class LinkHeaderServiceWorkerTest;
friend class ServiceWorkerProviderHostTest;
friend class ServiceWorkerWriteToCacheJobTest;
friend class ServiceWorkerContextRequestHandlerTest;
+ friend class service_worker_handle_unittest::ServiceWorkerHandleTest;
FRIEND_TEST_ALL_PREFIXES(ServiceWorkerWriteToCacheJobTest, Update_SameScript);
FRIEND_TEST_ALL_PREFIXES(ServiceWorkerWriteToCacheJobTest,
Update_SameSizeScript);
@@ -426,10 +499,12 @@ class CONTENT_EXPORT ServiceWorkerProviderHost
void GetRegistrations(GetRegistrationsCallback callback) override;
void GetRegistrationForReady(
GetRegistrationForReadyCallback callback) override;
- void GetControllerServiceWorker(
- mojom::ControllerServiceWorkerRequest controller_request) override;
+ void EnsureControllerServiceWorker(
+ mojom::ControllerServiceWorkerRequest controller_request,
+ mojom::ControllerServiceWorkerPurpose purpose) override;
void CloneForWorker(
mojom::ServiceWorkerContainerHostRequest container_host_request) override;
+ void Ping(PingCallback callback) override;
// Callback for ServiceWorkerContextCore::RegisterServiceWorker().
void RegistrationComplete(RegisterCallback callback,
@@ -451,6 +526,11 @@ class CONTENT_EXPORT ServiceWorkerProviderHost
const std::vector<scoped_refptr<ServiceWorkerRegistration>>&
registrations);
+ // Callback for ServiceWorkerVersion::RunAfterStartWorker()
+ void StartControllerComplete(
+ mojom::ControllerServiceWorkerRequest controller_request,
+ ServiceWorkerStatusCode status);
+
bool IsValidRegisterMessage(
const GURL& script_url,
const blink::mojom::ServiceWorkerRegistrationOptions& options,
@@ -461,7 +541,7 @@ class CONTENT_EXPORT ServiceWorkerProviderHost
bool IsValidGetRegistrationForReadyMessage(std::string* out_error) const;
// service_manager::mojom::InterfaceProvider:
- // For provider hosts that are hosting a running service worker.
+ // For service worker execution contexts.
void GetInterface(const std::string& interface_name,
mojo::ScopedMessagePipeHandle interface_pipe) override;
@@ -490,9 +570,9 @@ class CONTENT_EXPORT ServiceWorkerProviderHost
const base::TimeTicks create_time_;
int render_process_id_;
- // For provider hosts that are hosting a running service worker, the id of the
- // service worker thread or |kInvalidEmbeddedWorkerThreadId| before the
- // service worker starts up. Otherwise, |kDocumentMainThreadId|.
+ // For service worker execution contexts, the id of the service worker thread
+ // or |kInvalidEmbeddedWorkerThreadId| before the service worker starts up.
+ // Otherwise, |kDocumentMainThreadId|.
int render_thread_id_;
ServiceWorkerProviderHostInfo info_;
@@ -522,6 +602,13 @@ class CONTENT_EXPORT ServiceWorkerProviderHost
std::unique_ptr<ServiceWorkerRegistrationObjectHost>>
registration_object_hosts_;
+ // Contains all ServiceWorkerHandle instances corresponding to
+ // the service worker JavaScript objects for the hosted execution
+ // context (service worker global scope or service worker client) in the
+ // renderer process.
+ std::map<int64_t /* version_id */, std::unique_ptr<ServiceWorkerHandle>>
+ handles_;
+
// The ready() promise is only allowed to be created once.
// |get_ready_callback_| has three states:
// 1. |get_ready_callback_| is null when ready() has not yet been called.
@@ -531,8 +618,15 @@ class CONTENT_EXPORT ServiceWorkerProviderHost
// been run.
std::unique_ptr<GetRegistrationForReadyCallback> get_ready_callback_;
+ // For service worker clients. The controller service worker (i.e.,
+ // ServiceWorkerContainer#controller).
scoped_refptr<ServiceWorkerVersion> controller_;
+ // For service worker execution contexts. The ServiceWorkerVersion of the
+ // service worker this is a provider for. This is nullptr if the service
+ // worker is still being started up (until CompleteStartWorkerPreparation() is
+ // called).
scoped_refptr<ServiceWorkerVersion> running_hosted_version_;
+
base::WeakPtr<ServiceWorkerContextCore> context_;
// |dispatcher_host_| is expected to outlive |this| because it destroys
@@ -550,7 +644,7 @@ class CONTENT_EXPORT ServiceWorkerProviderHost
// ServiceWorkerContainer that |this| is a ServiceWorkerContainerHost for.
mojom::ServiceWorkerContainerAssociatedPtr container_;
// |binding_| is the Mojo binding that keeps the connection to the
- // renderer-side counterpart (content::ServiceWorkerNetworkProvider). When the
+ // renderer-side counterpart (content::ServiceWorkerProviderContext). When the
// connection bound on |binding_| gets killed from the renderer side, or the
// bound |ServiceWorkerProviderInfoForStartWorker::host_ptr_info| is otherwise
// destroyed before being passed to the renderer, this
@@ -571,16 +665,15 @@ class CONTENT_EXPORT ServiceWorkerProviderHost
std::vector<base::Closure> queued_events_;
- // S13nServiceWorker/NavigationMojoResponse:
- // A service worker handle for the controller service worker that is
- // pre-created before the renderer process (and therefore the dispatcher host)
- // is created.
- base::WeakPtr<ServiceWorkerHandle> precreated_controller_handle_;
-
- // For provider hosts that are hosting a running service worker.
+ // For service worker execution contexts.
mojo::Binding<service_manager::mojom::InterfaceProvider>
interface_provider_binding_;
+ // For service worker clients. True if the main resource for this host has
+ // finished loading. When false, the document URL may still change due to
+ // redirects.
+ bool is_execution_ready_ = false;
+
DISALLOW_COPY_AND_ASSIGN(ServiceWorkerProviderHost);
};
diff --git a/chromium/content/browser/service_worker/service_worker_provider_host_unittest.cc b/chromium/content/browser/service_worker/service_worker_provider_host_unittest.cc
index 38e10296250..21722145594 100644
--- a/chromium/content/browser/service_worker/service_worker_provider_host_unittest.cc
+++ b/chromium/content/browser/service_worker/service_worker_provider_host_unittest.cc
@@ -8,7 +8,6 @@
#include <utility>
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/weak_ptr.h"
#include "base/run_loop.h"
#include "base/threading/thread_task_runner_handle.h"
@@ -30,8 +29,8 @@
#include "content/test/test_content_client.h"
#include "mojo/edk/embedder/embedder.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
@@ -226,6 +225,17 @@ class ServiceWorkerProviderHostTest : public testing::Test {
void OnMojoError(const std::string& error) { bad_messages_.push_back(error); }
+ bool CanFindClientProviderHost(ServiceWorkerProviderHost* host) {
+ for (std::unique_ptr<ServiceWorkerContextCore::ProviderHostIterator> it =
+ context_->GetClientProviderHostIterator(
+ host->document_url().GetOrigin());
+ !it->IsAtEnd(); it->Advance()) {
+ if (host == it->GetProviderHost())
+ return true;
+ }
+ return false;
+ }
+
std::vector<std::string> bad_messages_;
TestBrowserThreadBundle thread_bundle_;
std::unique_ptr<EmbeddedWorkerTestHelper> helper_;
@@ -799,4 +809,46 @@ TEST_F(ServiceWorkerProviderHostTest,
EXPECT_EQ(1u, bad_messages_.size());
}
+// Test that a "reserved" (i.e., not execution ready) shared worker client is
+// not included when iterating over client provider hosts. If it were, it'd be
+// undesirably exposed via the Clients API.
+TEST_F(ServiceWorkerProviderHostTest,
+ ReservedClientsAreNotExposedToClientsAPI) {
+ {
+ auto provider_info = mojom::ServiceWorkerProviderInfoForSharedWorker::New();
+ base::WeakPtr<ServiceWorkerProviderHost> host =
+ ServiceWorkerProviderHost::PreCreateForSharedWorker(
+ context_->AsWeakPtr(), helper_->mock_render_process_id(),
+ &provider_info);
+ const GURL url("https://www.example.com/shared_worker.js");
+ host->SetTopmostFrameUrl(url);
+ EXPECT_FALSE(CanFindClientProviderHost(host.get()));
+ host->CompleteSharedWorkerPreparation();
+ EXPECT_TRUE(CanFindClientProviderHost(host.get()));
+ }
+
+ {
+ std::unique_ptr<ServiceWorkerProviderHost> host =
+ ServiceWorkerProviderHost::PreCreateNavigationHost(
+ helper_->context()->AsWeakPtr(), true,
+ base::RepeatingCallback<WebContents*(void)>());
+ ServiceWorkerProviderHostInfo info(
+ host->provider_id(), 1 /* route_id */,
+ blink::mojom::ServiceWorkerProviderType::kForWindow,
+ true /* is_parent_frame_secure */);
+ ServiceWorkerRemoteProviderEndpoint remote_endpoint;
+ remote_endpoint.BindWithProviderHostInfo(&info);
+ host->SetDocumentUrl(GURL("https://www.example.com/page"));
+ EXPECT_FALSE(CanFindClientProviderHost(host.get()));
+
+ host->CompleteNavigationInitialized(
+ helper_->mock_render_process_id(), std::move(info),
+ helper_->GetDispatcherHostForProcess(helper_->mock_render_process_id())
+ ->AsWeakPtr());
+ auto* host_rawptr = host.get();
+ context_->AddProviderHost(std::move(host));
+ EXPECT_TRUE(CanFindClientProviderHost(host_rawptr));
+ }
+}
+
} // namespace content
diff --git a/chromium/content/browser/service_worker/service_worker_quota_client.h b/chromium/content/browser/service_worker/service_worker_quota_client.h
index 23a44871928..bd263d5310a 100644
--- a/chromium/content/browser/service_worker/service_worker_quota_client.h
+++ b/chromium/content/browser/service_worker/service_worker_quota_client.h
@@ -9,7 +9,7 @@
#include "base/memory/ref_counted.h"
#include "content/common/content_export.h"
#include "storage/browser/quota/quota_client.h"
-#include "third_party/WebKit/public/mojom/quota/quota_types.mojom.h"
+#include "third_party/blink/public/mojom/quota/quota_types.mojom.h"
#include "url/origin.h"
namespace content {
diff --git a/chromium/content/browser/service_worker/service_worker_read_from_cache_job_unittest.cc b/chromium/content/browser/service_worker/service_worker_read_from_cache_job_unittest.cc
index 493088c3154..85f49357f2e 100644
--- a/chromium/content/browser/service_worker/service_worker_read_from_cache_job_unittest.cc
+++ b/chromium/content/browser/service_worker/service_worker_read_from_cache_job_unittest.cc
@@ -26,7 +26,7 @@
#include "net/url_request/url_request_status.h"
#include "net/url_request/url_request_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
diff --git a/chromium/content/browser/service_worker/service_worker_register_job.cc b/chromium/content/browser/service_worker/service_worker_register_job.cc
index 7ce0873799c..d1d5416741b 100644
--- a/chromium/content/browser/service_worker/service_worker_register_job.cc
+++ b/chromium/content/browser/service_worker/service_worker_register_job.cc
@@ -25,7 +25,7 @@
#include "content/public/browser/browser_thread.h"
#include "mojo/public/cpp/bindings/associated_binding.h"
#include "net/base/net_errors.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
namespace content {
@@ -75,15 +75,14 @@ ServiceWorkerRegisterJob::~ServiceWorkerRegisterJob() {
<< "Jobs should only be interrupted during shutdown.";
}
-void ServiceWorkerRegisterJob::AddCallback(
- const RegistrationCallback& callback) {
+void ServiceWorkerRegisterJob::AddCallback(RegistrationCallback callback) {
if (!is_promise_resolved_) {
- callbacks_.push_back(callback);
+ callbacks_.emplace_back(std::move(callback));
return;
}
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
- base::BindOnce(callback, promise_resolved_status_,
+ base::BindOnce(std::move(callback), promise_resolved_status_,
promise_resolved_status_message_,
base::RetainedRef(promise_resolved_registration_)));
}
@@ -389,7 +388,7 @@ void ServiceWorkerRegisterJob::OnStartWorkerFinished(
if (main_script_status.status() != net::URLRequestStatus::SUCCESS) {
message = new_version()->script_cache_map()->main_script_status_message();
if (message.empty())
- message = kFetchScriptError;
+ message = kServiceWorkerFetchScriptError;
}
Complete(status, message);
}
@@ -579,11 +578,8 @@ void ServiceWorkerRegisterJob::ResolvePromise(
promise_resolved_status_ = status;
promise_resolved_status_message_ = status_message,
promise_resolved_registration_ = registration;
- for (std::vector<RegistrationCallback>::iterator it = callbacks_.begin();
- it != callbacks_.end();
- ++it) {
- it->Run(status, status_message, registration);
- }
+ for (RegistrationCallback& callback : callbacks_)
+ std::move(callback).Run(status, status_message, registration);
callbacks_.clear();
}
@@ -591,14 +587,14 @@ void ServiceWorkerRegisterJob::AddRegistrationToMatchingProviderHosts(
ServiceWorkerRegistration* registration) {
DCHECK(registration);
for (std::unique_ptr<ServiceWorkerContextCore::ProviderHostIterator> it =
- context_->GetProviderHostIterator();
+ context_->GetClientProviderHostIterator(
+ registration->pattern().GetOrigin());
!it->IsAtEnd(); it->Advance()) {
ServiceWorkerProviderHost* host = it->GetProviderHost();
- if (host->IsHostToRunningServiceWorker())
- continue;
if (!ServiceWorkerUtils::ScopeMatches(registration->pattern(),
- host->document_url()))
+ host->document_url())) {
continue;
+ }
host->AddMatchingRegistration(registration);
}
}
diff --git a/chromium/content/browser/service_worker/service_worker_register_job.h b/chromium/content/browser/service_worker/service_worker_register_job.h
index 8e2492975e4..cd726a0661b 100644
--- a/chromium/content/browser/service_worker/service_worker_register_job.h
+++ b/chromium/content/browser/service_worker/service_worker_register_job.h
@@ -15,8 +15,8 @@
#include "content/browser/service_worker/service_worker_register_job_base.h"
#include "content/browser/service_worker/service_worker_registration.h"
#include "content/common/service_worker/service_worker_status_code.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_event_status.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_event_status.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
#include "url/gurl.h"
namespace content {
@@ -38,9 +38,9 @@ namespace content {
class ServiceWorkerRegisterJob : public ServiceWorkerRegisterJobBase,
public EmbeddedWorkerInstance::Listener {
public:
- typedef base::Callback<void(ServiceWorkerStatusCode status,
- const std::string& status_message,
- ServiceWorkerRegistration* registration)>
+ typedef base::OnceCallback<void(ServiceWorkerStatusCode status,
+ const std::string& status_message,
+ ServiceWorkerRegistration* registration)>
RegistrationCallback;
// For registration jobs.
@@ -59,7 +59,7 @@ class ServiceWorkerRegisterJob : public ServiceWorkerRegisterJobBase,
// Registers a callback to be called when the promise would resolve (whether
// successfully or not). Multiple callbacks may be registered.
- void AddCallback(const RegistrationCallback& callback);
+ void AddCallback(RegistrationCallback callback);
// ServiceWorkerRegisterJobBase implementation:
void Start() override;
diff --git a/chromium/content/browser/service_worker/service_worker_registration.cc b/chromium/content/browser/service_worker/service_worker_registration.cc
index 6dedd7bc2a6..3791d4e7af3 100644
--- a/chromium/content/browser/service_worker/service_worker_registration.cc
+++ b/chromium/content/browser/service_worker/service_worker_registration.cc
@@ -16,7 +16,7 @@
#include "content/common/service_worker/service_worker_messages.h"
#include "content/common/service_worker/service_worker_utils.h"
#include "content/public/browser/browser_thread.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
@@ -219,11 +219,9 @@ void ServiceWorkerRegistration::ClaimClients() {
DCHECK(active_version());
for (std::unique_ptr<ServiceWorkerContextCore::ProviderHostIterator> it =
- context_->GetProviderHostIterator();
+ context_->GetClientProviderHostIterator(pattern_.GetOrigin());
!it->IsAtEnd(); it->Advance()) {
ServiceWorkerProviderHost* host = it->GetProviderHost();
- if (host->IsHostToRunningServiceWorker())
- continue;
if (host->controller() == active_version())
continue;
if (!host->IsContextSecureForServiceWorker())
diff --git a/chromium/content/browser/service_worker/service_worker_registration.h b/chromium/content/browser/service_worker/service_worker_registration.h
index 4fb403ba23f..164a9ac1960 100644
--- a/chromium/content/browser/service_worker/service_worker_registration.h
+++ b/chromium/content/browser/service_worker/service_worker_registration.h
@@ -18,7 +18,7 @@
#include "content/browser/service_worker/service_worker_version.h"
#include "content/common/content_export.h"
#include "content/common/service_worker/service_worker_types.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
#include "url/gurl.h"
namespace content {
diff --git a/chromium/content/browser/service_worker/service_worker_registration_object_host.cc b/chromium/content/browser/service_worker/service_worker_registration_object_host.cc
index 8d18858e7b8..11837fba49e 100644
--- a/chromium/content/browser/service_worker/service_worker_registration_object_host.cc
+++ b/chromium/content/browser/service_worker/service_worker_registration_object_host.cc
@@ -4,14 +4,13 @@
#include "content/browser/service_worker/service_worker_registration_object_host.h"
-#include "base/memory/ptr_util.h"
#include "content/browser/service_worker/service_worker_consts.h"
#include "content/browser/service_worker/service_worker_context_core.h"
#include "content/browser/service_worker/service_worker_handle.h"
#include "content/browser/service_worker/service_worker_provider_host.h"
#include "content/common/service_worker/service_worker_utils.h"
#include "net/http/http_util.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
diff --git a/chromium/content/browser/service_worker/service_worker_registration_object_host.h b/chromium/content/browser/service_worker/service_worker_registration_object_host.h
index 13dbd346683..9b978c6761c 100644
--- a/chromium/content/browser/service_worker/service_worker_registration_object_host.h
+++ b/chromium/content/browser/service_worker/service_worker_registration_object_host.h
@@ -14,7 +14,7 @@
#include "content/common/content_export.h"
#include "content/common/service_worker/service_worker_types.h"
#include "mojo/public/cpp/bindings/associated_binding_set.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
diff --git a/chromium/content/browser/service_worker/service_worker_registration_status.cc b/chromium/content/browser/service_worker/service_worker_registration_status.cc
index 21863f4efdb..97954034a48 100644
--- a/chromium/content/browser/service_worker/service_worker_registration_status.cc
+++ b/chromium/content/browser/service_worker/service_worker_registration_status.cc
@@ -8,7 +8,7 @@
#include "base/logging.h"
#include "base/strings/utf_string_conversions.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_error_type.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_error_type.mojom.h"
namespace content {
diff --git a/chromium/content/browser/service_worker/service_worker_registration_status.h b/chromium/content/browser/service_worker/service_worker_registration_status.h
index 37c1815b4d9..b7368901770 100644
--- a/chromium/content/browser/service_worker/service_worker_registration_status.h
+++ b/chromium/content/browser/service_worker/service_worker_registration_status.h
@@ -7,7 +7,7 @@
#include "base/strings/string16.h"
#include "content/common/service_worker/service_worker_status_code.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerError.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_error.h"
namespace content {
diff --git a/chromium/content/browser/service_worker/service_worker_registration_unittest.cc b/chromium/content/browser/service_worker/service_worker_registration_unittest.cc
index 31735f73eb9..c3c86f49727 100644
--- a/chromium/content/browser/service_worker/service_worker_registration_unittest.cc
+++ b/chromium/content/browser/service_worker/service_worker_registration_unittest.cc
@@ -28,8 +28,8 @@
#include "content/test/test_content_browser_client.h"
#include "mojo/edk/embedder/embedder.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
#include "url/gurl.h"
namespace content {
diff --git a/chromium/content/browser/service_worker/service_worker_request_handler.cc b/chromium/content/browser/service_worker/service_worker_request_handler.cc
index a0892b30666..2ca37e938e9 100644
--- a/chromium/content/browser/service_worker/service_worker_request_handler.cc
+++ b/chromium/content/browser/service_worker/service_worker_request_handler.cc
@@ -9,7 +9,7 @@
#include "base/command_line.h"
#include "base/macros.h"
-#include "content/browser/loader/url_loader_request_handler.h"
+#include "content/browser/loader/navigation_loader_interceptor.h"
#include "content/browser/service_worker/service_worker_context_core.h"
#include "content/browser/service_worker/service_worker_context_wrapper.h"
#include "content/browser/service_worker/service_worker_navigation_handle_core.h"
@@ -86,6 +86,15 @@ void ServiceWorkerRequestHandler::InitializeForNavigation(
const base::Callback<WebContents*(void)>& web_contents_getter) {
CHECK(IsBrowserSideNavigationEnabled());
+ // S13nServiceWorker enabled, NetworkService disabled:
+ // To start the navigation, InitializeForNavigationNetworkService() is called
+ // instead of this, but when that request handler falls back to network,
+ // InitializeForNavigation() is called.
+ // Since we already determined to fall back to network, don't create another
+ // handler.
+ if (ServiceWorkerUtils::IsServicificationEnabled())
+ return;
+
// Only create a handler when there is a ServiceWorkerNavigationHandlerCore
// to take ownership of a pre-created SeviceWorkerProviderHost.
if (!navigation_handle_core)
@@ -131,7 +140,7 @@ void ServiceWorkerRequestHandler::InitializeForNavigation(
// S13nServiceWorker:
// static
-std::unique_ptr<URLLoaderRequestHandler>
+std::unique_ptr<NavigationLoaderInterceptor>
ServiceWorkerRequestHandler::InitializeForNavigationNetworkService(
const network::ResourceRequest& resource_request,
ResourceContext* resource_context,
@@ -181,7 +190,35 @@ ServiceWorkerRequestHandler::InitializeForNavigationNetworkService(
// ServiceWorkerNavigationHandleCore.
navigation_handle_core->DidPreCreateProviderHost(std::move(provider_host));
- return base::WrapUnique<URLLoaderRequestHandler>(handler.release());
+ return base::WrapUnique<NavigationLoaderInterceptor>(handler.release());
+}
+
+// static
+std::unique_ptr<NavigationLoaderInterceptor>
+ServiceWorkerRequestHandler::InitializeForSharedWorker(
+ const network::ResourceRequest& resource_request,
+ base::WeakPtr<ServiceWorkerProviderHost> host) {
+ DCHECK(ServiceWorkerUtils::IsServicificationEnabled());
+
+ // Create the handler even for insecure HTTP since it's used in the
+ // case of redirect to HTTPS.
+ if (!resource_request.url.SchemeIsHTTPOrHTTPS() &&
+ !OriginCanAccessServiceWorkers(resource_request.url)) {
+ return nullptr;
+ }
+
+ std::unique_ptr<ServiceWorkerRequestHandler> handler(
+ host->CreateRequestHandler(
+ resource_request.fetch_request_mode,
+ resource_request.fetch_credentials_mode,
+ resource_request.fetch_redirect_mode,
+ resource_request.fetch_integrity, resource_request.keepalive,
+ RESOURCE_TYPE_SHARED_WORKER, REQUEST_CONTEXT_TYPE_SHARED_WORKER,
+ resource_request.fetch_frame_type,
+ nullptr /* blob_storage_context: unused in S13n */,
+ resource_request.request_body, resource_request.skip_service_worker));
+
+ return base::WrapUnique<NavigationLoaderInterceptor>(handler.release());
}
// static
diff --git a/chromium/content/browser/service_worker/service_worker_request_handler.h b/chromium/content/browser/service_worker/service_worker_request_handler.h
index ef6d7d26970..da73b702058 100644
--- a/chromium/content/browser/service_worker/service_worker_request_handler.h
+++ b/chromium/content/browser/service_worker/service_worker_request_handler.h
@@ -12,7 +12,7 @@
#include "base/memory/weak_ptr.h"
#include "base/supports_user_data.h"
#include "base/time/time.h"
-#include "content/browser/loader/url_loader_request_handler.h"
+#include "content/browser/loader/navigation_loader_interceptor.h"
#include "content/common/content_export.h"
#include "content/common/service_worker/service_worker_status_code.h"
#include "content/common/service_worker/service_worker_types.h"
@@ -49,7 +49,7 @@ class WebContents;
// Created one per URLRequest and attached to each request.
class CONTENT_EXPORT ServiceWorkerRequestHandler
: public base::SupportsUserData::Data,
- public URLLoaderRequestHandler {
+ public NavigationLoaderInterceptor {
public:
// PlzNavigate
// Attaches a newly created handler if the given |request| needs to be handled
@@ -68,8 +68,8 @@ class CONTENT_EXPORT ServiceWorkerRequestHandler
// S13nServiceWorker:
// Same as InitializeForNavigation() but instead of attaching to a URLRequest,
- // just creates a URLLoaderRequestHandler and returns it.
- static std::unique_ptr<URLLoaderRequestHandler>
+ // just creates a NavigationLoaderInterceptor and returns it.
+ static std::unique_ptr<NavigationLoaderInterceptor>
InitializeForNavigationNetworkService(
const network::ResourceRequest& resource_request,
ResourceContext* resource_context,
@@ -83,6 +83,10 @@ class CONTENT_EXPORT ServiceWorkerRequestHandler
scoped_refptr<network::ResourceRequestBody> body,
const base::Callback<WebContents*(void)>& web_contents_getter);
+ static std::unique_ptr<NavigationLoaderInterceptor> InitializeForSharedWorker(
+ const network::ResourceRequest& resource_request,
+ base::WeakPtr<ServiceWorkerProviderHost> host);
+
// Attaches a newly created handler if the given |request| needs to
// be handled by ServiceWorker.
// TODO(kinuko): While utilizing UserData to attach data to URLRequest
@@ -134,7 +138,7 @@ class CONTENT_EXPORT ServiceWorkerRequestHandler
net::NetworkDelegate* network_delegate,
ResourceContext* context) = 0;
- // URLLoaderRequestHandler overrides.
+ // NavigationLoaderInterceptor overrides.
void MaybeCreateLoader(const network::ResourceRequest& request,
ResourceContext* resource_context,
LoaderCallback callback) override;
diff --git a/chromium/content/browser/service_worker/service_worker_script_loader_factory.cc b/chromium/content/browser/service_worker/service_worker_script_loader_factory.cc
index 46bcfb42dc4..a61fc1f14fe 100644
--- a/chromium/content/browser/service_worker/service_worker_script_loader_factory.cc
+++ b/chromium/content/browser/service_worker/service_worker_script_loader_factory.cc
@@ -24,7 +24,7 @@ ServiceWorkerScriptLoaderFactory::ServiceWorkerScriptLoaderFactory(
: context_(context),
provider_host_(provider_host),
loader_factory_getter_(loader_factory_getter) {
- DCHECK(provider_host_->IsHostToRunningServiceWorker());
+ DCHECK(provider_host_->IsProviderForServiceWorker());
}
ServiceWorkerScriptLoaderFactory::~ServiceWorkerScriptLoaderFactory() = default;
diff --git a/chromium/content/browser/service_worker/service_worker_storage.cc b/chromium/content/browser/service_worker/service_worker_storage.cc
index 31277926c84..08f439d6e4c 100644
--- a/chromium/content/browser/service_worker/service_worker_storage.cc
+++ b/chromium/content/browser/service_worker/service_worker_storage.cc
@@ -29,10 +29,10 @@
#include "net/base/net_errors.h"
#include "storage/browser/quota/quota_manager_proxy.h"
#include "storage/browser/quota/special_storage_policy.h"
-#include "third_party/WebKit/public/mojom/quota/quota_types.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
-#include "third_party/WebKit/public/platform/web_feature.mojom.h"
+#include "third_party/blink/public/mojom/quota/quota_types.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/platform/web_feature.mojom.h"
using std::swap;
@@ -431,7 +431,8 @@ void ServiceWorkerStorage::StoreRegistration(
if (version->origin_trial_tokens())
data.origin_trial_tokens = *version->origin_trial_tokens();
data.navigation_preload_state = registration->navigation_preload_state();
- data.used_features = version->used_features();
+ for (const blink::mojom::WebFeature feature : version->used_features())
+ data.used_features.insert(static_cast<uint32_t>(feature));
ResourceList resources;
version->script_cache_map()->GetResources(&resources);
@@ -1540,16 +1541,14 @@ ServiceWorkerStorage::GetOrCreateRegistration(
// TODO(falken): Maybe Chrome should have a generic mechanism to detect
// profile downgrade and just abort? Or we could just crash here, but that
// seems extreme and difficult for a user to escape.
- std::set<uint32_t> used_features = data.used_features;
- for (auto it = used_features.begin(); it != used_features.end();) {
- if (*it >=
+ std::set<blink::mojom::WebFeature> used_features;
+ for (const uint32_t feature : data.used_features) {
+ if (feature <
static_cast<uint32_t>(blink::mojom::WebFeature::kNumberOfFeatures)) {
- it = used_features.erase(it);
- } else {
- ++it;
+ used_features.insert(static_cast<blink::mojom::WebFeature>(feature));
}
}
- version->set_used_features(used_features);
+ version->set_used_features(std::move(used_features));
}
if (version->status() == ServiceWorkerVersion::ACTIVATED)
diff --git a/chromium/content/browser/service_worker/service_worker_storage_unittest.cc b/chromium/content/browser/service_worker/service_worker_storage_unittest.cc
index 002ee831382..8ab6e03831c 100644
--- a/chromium/content/browser/service_worker/service_worker_storage_unittest.cc
+++ b/chromium/content/browser/service_worker/service_worker_storage_unittest.cc
@@ -17,7 +17,6 @@
#include "base/test/histogram_tester.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
-#include "content/browser/browser_thread_impl.h"
#include "content/browser/service_worker/embedded_worker_test_helper.h"
#include "content/browser/service_worker/service_worker_context_core.h"
#include "content/browser/service_worker/service_worker_disk_cache.h"
@@ -40,8 +39,8 @@
#include "net/test/cert_test_util.h"
#include "net/test/test_data_directory.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
using net::IOBuffer;
using net::TestCompletionCallback;
@@ -697,7 +696,10 @@ TEST_F(ServiceWorkerStorageTest, StoreFindUpdateDeleteRegistration) {
const int64_t kVersionId = 0;
const base::Time kToday = base::Time::Now();
const base::Time kYesterday = kToday - base::TimeDelta::FromDays(1);
- std::set<uint32_t> used_features = {124, 901, 1019};
+ std::set<blink::mojom::WebFeature> used_features = {
+ blink::mojom::WebFeature::kServiceWorkerControlledPage,
+ blink::mojom::WebFeature::kReferrerPolicyHeader,
+ blink::mojom::WebFeature::kLocationOrigin};
scoped_refptr<ServiceWorkerRegistration> found_registration;
@@ -731,7 +733,8 @@ TEST_F(ServiceWorkerStorageTest, StoreFindUpdateDeleteRegistration) {
ServiceWorkerVersion::FetchHandlerExistence::EXISTS);
live_version->SetStatus(ServiceWorkerVersion::INSTALLED);
live_version->script_cache_map()->SetResources(resources);
- live_version->set_used_features(used_features);
+ live_version->set_used_features(
+ std::set<blink::mojom::WebFeature>(used_features));
live_registration->SetWaitingVersion(live_version);
live_registration->set_last_update_check(kYesterday);
EXPECT_EQ(SERVICE_WORKER_OK,
diff --git a/chromium/content/browser/service_worker/service_worker_test_utils.cc b/chromium/content/browser/service_worker/service_worker_test_utils.cc
index 4d05a4374ad..67e56a81a2b 100644
--- a/chromium/content/browser/service_worker/service_worker_test_utils.cc
+++ b/chromium/content/browser/service_worker/service_worker_test_utils.cc
@@ -225,7 +225,8 @@ WriteToDiskCacheWithCustomResponseInfoAsync(
WriteBodyToDiskCache(std::move(body_writer), std::move(http_info), body,
barrier);
auto metadata_writer = storage->CreateResponseMetadataWriter(resource_id);
- WriteMetaDataToDiskCache(std::move(metadata_writer), meta_data, barrier);
+ WriteMetaDataToDiskCache(std::move(metadata_writer), meta_data,
+ std::move(barrier));
return ServiceWorkerDatabase::ResourceRecord(resource_id, script_url,
body.size());
}
diff --git a/chromium/content/browser/service_worker/service_worker_test_utils.h b/chromium/content/browser/service_worker/service_worker_test_utils.h
index 318e7d24be3..363387afbde 100644
--- a/chromium/content/browser/service_worker/service_worker_test_utils.h
+++ b/chromium/content/browser/service_worker/service_worker_test_utils.h
@@ -16,7 +16,7 @@
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace net {
diff --git a/chromium/content/browser/service_worker/service_worker_type_converters.h b/chromium/content/browser/service_worker/service_worker_type_converters.h
index 322455eaec4..207ef89cc3c 100644
--- a/chromium/content/browser/service_worker/service_worker_type_converters.h
+++ b/chromium/content/browser/service_worker/service_worker_type_converters.h
@@ -7,8 +7,8 @@
#include "content/browser/service_worker/service_worker_version.h"
#include "content/common/service_worker/service_worker_status_code.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_event_status.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_state.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_event_status.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_state.mojom.h"
namespace mojo {
diff --git a/chromium/content/browser/service_worker/service_worker_unregister_job.cc b/chromium/content/browser/service_worker/service_worker_unregister_job.cc
index 76e053bec92..64eb79e375d 100644
--- a/chromium/content/browser/service_worker/service_worker_unregister_job.cc
+++ b/chromium/content/browser/service_worker/service_worker_unregister_job.cc
@@ -11,7 +11,7 @@
#include "content/browser/service_worker/service_worker_storage.h"
#include "content/browser/service_worker/service_worker_version.h"
#include "content/common/service_worker/service_worker_utils.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
@@ -28,9 +28,8 @@ ServiceWorkerUnregisterJob::ServiceWorkerUnregisterJob(
ServiceWorkerUnregisterJob::~ServiceWorkerUnregisterJob() {}
-void ServiceWorkerUnregisterJob::AddCallback(
- const UnregistrationCallback& callback) {
- callbacks_.push_back(callback);
+void ServiceWorkerUnregisterJob::AddCallback(UnregistrationCallback callback) {
+ callbacks_.emplace_back(std::move(callback));
}
void ServiceWorkerUnregisterJob::Start() {
@@ -98,11 +97,8 @@ void ServiceWorkerUnregisterJob::ResolvePromise(
ServiceWorkerStatusCode status) {
DCHECK(!is_promise_resolved_);
is_promise_resolved_ = true;
- for (std::vector<UnregistrationCallback>::iterator it = callbacks_.begin();
- it != callbacks_.end();
- ++it) {
- it->Run(registration_id, status);
- }
+ for (UnregistrationCallback& callback : callbacks_)
+ std::move(callback).Run(registration_id, status);
}
} // namespace content
diff --git a/chromium/content/browser/service_worker/service_worker_unregister_job.h b/chromium/content/browser/service_worker/service_worker_unregister_job.h
index 9e4f2ff348e..0ded1bb3cd1 100644
--- a/chromium/content/browser/service_worker/service_worker_unregister_job.h
+++ b/chromium/content/browser/service_worker/service_worker_unregister_job.h
@@ -28,8 +28,8 @@ class ServiceWorkerRegistration;
// ServiceWorkerRegistration itself.
class ServiceWorkerUnregisterJob : public ServiceWorkerRegisterJobBase {
public:
- typedef base::Callback<void(int64_t registration_id,
- ServiceWorkerStatusCode status)>
+ typedef base::OnceCallback<void(int64_t registration_id,
+ ServiceWorkerStatusCode status)>
UnregistrationCallback;
ServiceWorkerUnregisterJob(base::WeakPtr<ServiceWorkerContextCore> context,
@@ -38,7 +38,7 @@ class ServiceWorkerUnregisterJob : public ServiceWorkerRegisterJobBase {
// Registers a callback to be called when the job completes (whether
// successfully or not). Multiple callbacks may be registered.
- void AddCallback(const UnregistrationCallback& callback);
+ void AddCallback(UnregistrationCallback callback);
// ServiceWorkerRegisterJobBase implementation:
void Start() override;
diff --git a/chromium/content/browser/service_worker/service_worker_url_job_wrapper.h b/chromium/content/browser/service_worker/service_worker_url_job_wrapper.h
index bd12480ec35..acaf609c685 100644
--- a/chromium/content/browser/service_worker/service_worker_url_job_wrapper.h
+++ b/chromium/content/browser/service_worker/service_worker_url_job_wrapper.h
@@ -6,7 +6,7 @@
#define CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_JOB_WRAPPER_H_
#include "base/macros.h"
-#include "content/browser/loader/url_loader_request_handler.h"
+#include "content/browser/loader/navigation_loader_interceptor.h"
#include "content/browser/service_worker/service_worker_metrics.h"
#include "content/common/content_export.h"
diff --git a/chromium/content/browser/service_worker/service_worker_url_request_job_unittest.cc b/chromium/content/browser/service_worker/service_worker_url_request_job_unittest.cc
index c4d65e0b440..20b8ee246d9 100644
--- a/chromium/content/browser/service_worker/service_worker_url_request_job_unittest.cc
+++ b/chromium/content/browser/service_worker/service_worker_url_request_job_unittest.cc
@@ -12,7 +12,6 @@
#include "base/callback.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/test/histogram_tester.h"
@@ -62,10 +61,10 @@
#include "storage/browser/blob/blob_url_request_job_factory.h"
#include "storage/common/blob_storage/blob_handle.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_event_status.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_installed_scripts_manager.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_event_status.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_installed_scripts_manager.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
namespace service_worker_url_request_job_unittest {
diff --git a/chromium/content/browser/service_worker/service_worker_version.cc b/chromium/content/browser/service_worker/service_worker_version.cc
index 2417abcfdae..025c6403566 100644
--- a/chromium/content/browser/service_worker/service_worker_version.cc
+++ b/chromium/content/browser/service_worker/service_worker_version.cc
@@ -26,7 +26,6 @@
#include "content/browser/child_process_security_policy_impl.h"
#include "content/browser/service_worker/embedded_worker_registry.h"
#include "content/browser/service_worker/payment_handler_support.h"
-#include "content/browser/service_worker/service_worker_client_utils.h"
#include "content/browser/service_worker/service_worker_context_core.h"
#include "content/browser/service_worker/service_worker_context_wrapper.h"
#include "content/browser/service_worker/service_worker_installed_scripts_sender.h"
@@ -34,7 +33,6 @@
#include "content/browser/service_worker/service_worker_type_converters.h"
#include "content/common/origin_trials/trial_policy_impl.h"
#include "content/common/service_worker/embedded_worker.mojom.h"
-#include "content/common/service_worker/embedded_worker_messages.h"
#include "content/common/service_worker/service_worker_messages.h"
#include "content/common/service_worker/service_worker_utils.h"
#include "content/public/browser/browser_thread.h"
@@ -46,16 +44,13 @@
#include "content/public/common/result_codes.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_response_info.h"
-#include "third_party/WebKit/public/common/origin_trials/trial_token_validator.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_error_type.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_installed_scripts_manager.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
-#include "third_party/WebKit/public/web/WebConsoleMessage.h"
+#include "third_party/blink/public/common/origin_trials/trial_token_validator.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_error_type.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_installed_scripts_manager.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/web/web_console_message.h"
namespace content {
-
-using StatusCallback = ServiceWorkerVersion::StatusCallback;
-
namespace {
// Timeout for an installed worker to start.
@@ -103,7 +98,7 @@ void RunCallbacks(ServiceWorkerVersion* version,
// An adapter to run a |callback| after StartWorker.
void RunCallbackAfterStartWorker(base::WeakPtr<ServiceWorkerVersion> version,
- StatusCallback callback,
+ ServiceWorkerVersion::StatusCallback callback,
ServiceWorkerStatusCode status) {
if (status == SERVICE_WORKER_OK &&
version->running_status() != EmbeddedWorkerStatus::RUNNING) {
@@ -892,7 +887,8 @@ void ServiceWorkerVersion::SimulatePingTimeoutForTesting() {
ping_controller_->SimulateTimeoutForTesting();
}
-void ServiceWorkerVersion::SetTickClockForTesting(base::TickClock* tick_clock) {
+void ServiceWorkerVersion::SetTickClockForTesting(
+ const base::TickClock* tick_clock) {
tick_clock_ = tick_clock;
}
@@ -1035,16 +1031,6 @@ void ServiceWorkerVersion::OnReportConsoleMessage(int source_identifier,
}
}
-bool ServiceWorkerVersion::OnMessageReceived(const IPC::Message& message) {
- bool handled = true;
- IPC_BEGIN_MESSAGE_MAP(ServiceWorkerVersion, message)
- IPC_MESSAGE_HANDLER(ServiceWorkerHostMsg_PostMessageToClient,
- OnPostMessageToClient)
- IPC_MESSAGE_UNHANDLED(handled = false)
- IPC_END_MESSAGE_MAP()
- return handled;
-}
-
void ServiceWorkerVersion::OnStartSentAndScriptEvaluated(
ServiceWorkerStatusCode status) {
if (status != SERVICE_WORKER_OK) {
@@ -1124,6 +1110,10 @@ void ServiceWorkerVersion::GetClient(const std::string& client_uuid,
if (!provider_host ||
provider_host->document_url().GetOrigin() != script_url_.GetOrigin()) {
// The promise will be resolved to 'undefined'.
+ // Note that we don't BadMessage here since Clients#get() can be passed an
+ // arbitrary UUID. The BadMessages for the origin mismatches below are
+ // appropriate because the UUID is taken directly from a Client object so we
+ // expect it to be valid.
std::move(callback).Run(nullptr);
return;
}
@@ -1132,7 +1122,7 @@ void ServiceWorkerVersion::GetClient(const std::string& client_uuid,
void ServiceWorkerVersion::OpenNewTab(const GURL& url,
OpenNewTabCallback callback) {
- OpenWindow(url, WindowOpenDisposition::NEW_FOREGROUND_TAB,
+ OpenWindow(url, service_worker_client_utils::WindowType::NEW_TAB_WINDOW,
std::move(callback));
}
@@ -1150,12 +1140,32 @@ void ServiceWorkerVersion::OpenPaymentHandlerWindow(
PaymentHandlerSupport::ShowPaymentHandlerWindow(
url, context_.get(),
base::BindOnce(&DidShowPaymentHandlerWindow, url, context_),
- base::BindOnce(&ServiceWorkerVersion::OpenWindow,
- weak_factory_.GetWeakPtr(), url,
- WindowOpenDisposition::NEW_POPUP),
+ base::BindOnce(
+ &ServiceWorkerVersion::OpenWindow, weak_factory_.GetWeakPtr(), url,
+ service_worker_client_utils::WindowType::PAYMENT_HANDLER_WINDOW),
std::move(callback));
}
+void ServiceWorkerVersion::PostMessageToClient(
+ const std::string& client_uuid,
+ blink::TransferableMessage message) {
+ if (!context_)
+ return;
+ ServiceWorkerProviderHost* provider_host =
+ context_->GetProviderHostByClientID(client_uuid);
+ if (!provider_host) {
+ // The client may already have been closed, just ignore.
+ return;
+ }
+ if (provider_host->document_url().GetOrigin() != script_url_.GetOrigin()) {
+ mojo::ReportBadMessage(
+ "Received Client#postMessage() request for a cross-origin client.");
+ binding_.Close();
+ return;
+ }
+ provider_host->PostMessageToClient(this, std::move(message));
+}
+
void ServiceWorkerVersion::FocusClient(const std::string& client_uuid,
FocusClientCallback callback) {
if (!context_) {
@@ -1170,15 +1180,16 @@ void ServiceWorkerVersion::FocusClient(const std::string& client_uuid,
return;
}
if (provider_host->document_url().GetOrigin() != script_url_.GetOrigin()) {
- // The client does not belong to the same origin as this ServiceWorker,
- // possibly due to timing issue or bad message.
- std::move(callback).Run(nullptr /* client */);
+ mojo::ReportBadMessage(
+ "Received WindowClient#focus() request for a cross-origin client.");
+ binding_.Close();
return;
}
if (provider_host->client_type() !=
blink::mojom::ServiceWorkerClientType::kWindow) {
// focus() should be called only for WindowClient.
- mojo::ReportBadMessage("Received focus() request for a non-window client.");
+ mojo::ReportBadMessage(
+ "Received WindowClient#focus() request for a non-window client.");
binding_.Close();
return;
}
@@ -1223,6 +1234,20 @@ void ServiceWorkerVersion::NavigateClient(const std::string& client_uuid,
std::string("The client was not found."));
return;
}
+ if (provider_host->document_url().GetOrigin() != script_url_.GetOrigin()) {
+ mojo::ReportBadMessage(
+ "Received WindowClient#navigate() request for a cross-origin client.");
+ binding_.Close();
+ return;
+ }
+ if (provider_host->client_type() !=
+ blink::mojom::ServiceWorkerClientType::kWindow) {
+ // navigate() should be called only for WindowClient.
+ mojo::ReportBadMessage(
+ "Received WindowClient#navigate() request for a non-window client.");
+ binding_.Close();
+ return;
+ }
if (provider_host->active_version() != this) {
std::move(callback).Run(
false /* success */, nullptr /* client */,
@@ -1291,9 +1316,10 @@ void ServiceWorkerVersion::OnClearCachedMetadataFinished(int64_t callback_id,
listener.OnCachedMetadataUpdated(this, 0);
}
-void ServiceWorkerVersion::OpenWindow(GURL url,
- WindowOpenDisposition disposition,
- OpenNewTabCallback callback) {
+void ServiceWorkerVersion::OpenWindow(
+ GURL url,
+ service_worker_client_utils::WindowType type,
+ OpenNewTabCallback callback) {
// Just respond failure if we are shutting down.
if (!context_) {
std::move(callback).Run(
@@ -1326,7 +1352,7 @@ void ServiceWorkerVersion::OpenWindow(GURL url,
}
service_worker_client_utils::OpenWindow(
- url, script_url_, embedded_worker_->process_id(), context_, disposition,
+ url, script_url_, embedded_worker_->process_id(), context_, type,
base::BindOnce(&OnOpenWindowFinished, std::move(callback)));
}
@@ -1348,7 +1374,7 @@ void ServiceWorkerVersion::OnSimpleEventFinished(
std::move(callback).Run(mojo::ConvertTo<ServiceWorkerStatusCode>(status));
}
-void ServiceWorkerVersion::CountFeature(uint32_t feature) {
+void ServiceWorkerVersion::CountFeature(blink::mojom::WebFeature feature) {
if (!used_features_.insert(feature).second)
return;
for (auto provider_host_by_uuid : controllee_map_)
@@ -1370,29 +1396,6 @@ bool ServiceWorkerVersion::IsInstalled(ServiceWorkerVersion::Status status) {
return false;
}
-void ServiceWorkerVersion::OnPostMessageToClient(
- const std::string& client_uuid,
- const scoped_refptr<base::RefCountedData<blink::TransferableMessage>>&
- message) {
- if (!context_)
- return;
- TRACE_EVENT1("ServiceWorker",
- "ServiceWorkerVersion::OnPostMessageToDocument",
- "Client id", client_uuid);
- ServiceWorkerProviderHost* provider_host =
- context_->GetProviderHostByClientID(client_uuid);
- if (!provider_host) {
- // The client may already have been closed, just ignore.
- return;
- }
- if (provider_host->document_url().GetOrigin() != script_url_.GetOrigin()) {
- // The client does not belong to the same origin as this ServiceWorker,
- // possibly due to timing issue or bad message.
- return;
- }
- provider_host->PostMessageToClient(this, std::move(message->data));
-}
-
void ServiceWorkerVersion::OnPongFromWorker() {
ping_controller_->OnPongReceived();
}
diff --git a/chromium/content/browser/service_worker/service_worker_version.h b/chromium/content/browser/service_worker/service_worker_version.h
index ce0bfe6b8dc..c0aba6af7c5 100644
--- a/chromium/content/browser/service_worker/service_worker_version.h
+++ b/chromium/content/browser/service_worker/service_worker_version.h
@@ -19,7 +19,6 @@
#include "base/containers/id_map.h"
#include "base/gtest_prod_util.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/observer_list.h"
#include "base/optional.h"
@@ -30,6 +29,7 @@
#include "base/timer/timer.h"
#include "content/browser/service_worker/embedded_worker_instance.h"
#include "content/browser/service_worker/embedded_worker_status.h"
+#include "content/browser/service_worker/service_worker_client_utils.h"
#include "content/browser/service_worker/service_worker_context_request_handler.h"
#include "content/browser/service_worker/service_worker_metrics.h"
#include "content/browser/service_worker/service_worker_script_cache_map.h"
@@ -41,11 +41,11 @@
#include "ipc/ipc_message.h"
#include "mojo/public/cpp/bindings/interface_ptr.h"
#include "services/service_manager/public/cpp/interface_provider.h"
-#include "third_party/WebKit/public/common/origin_trials/trial_token_validator.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_client.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_event_status.mojom.h"
-#include "ui/base/mojo/window_open_disposition.mojom.h"
+#include "third_party/blink/public/common/origin_trials/trial_token_validator.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_client.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_event_status.mojom.h"
+#include "third_party/blink/public/platform/web_feature.mojom.h"
#include "url/gurl.h"
#include "url/origin.h"
@@ -323,7 +323,9 @@ class CONTENT_EXPORT ServiceWorkerVersion
// This must be called when the worker is running.
mojom::ServiceWorkerEventDispatcher* event_dispatcher() {
- DCHECK(event_dispatcher_.is_bound());
+ // Temporarily CHECK for debugging https://crbug.com/817981.
+ CHECK(event_dispatcher_.is_bound());
+ CHECK(event_dispatcher_.get());
return event_dispatcher_.get();
}
@@ -435,7 +437,7 @@ class CONTENT_EXPORT ServiceWorkerVersion
void SimulatePingTimeoutForTesting();
// Used to allow tests to change time for testing.
- void SetTickClockForTesting(base::TickClock* tick_clock);
+ void SetTickClockForTesting(const base::TickClock* tick_clock);
// Used to allow tests to change wall clock for testing.
void SetClockForTesting(base::Clock* clock);
@@ -463,11 +465,13 @@ class CONTENT_EXPORT ServiceWorkerVersion
return max_request_expiration_time_ - tick_clock_->NowTicks();
}
- void CountFeature(uint32_t feature);
- void set_used_features(const std::set<uint32_t>& used_features) {
- used_features_ = used_features;
+ void CountFeature(blink::mojom::WebFeature feature);
+ void set_used_features(std::set<blink::mojom::WebFeature> used_features) {
+ used_features_ = std::move(used_features);
+ }
+ const std::set<blink::mojom::WebFeature>& used_features() const {
+ return used_features_;
}
- const std::set<uint32_t>& used_features() const { return used_features_; }
static bool IsInstalled(ServiceWorkerVersion::Status status);
@@ -615,7 +619,6 @@ class CONTENT_EXPORT ServiceWorkerVersion
const base::string16& message,
int line_number,
const GURL& source_url) override;
- bool OnMessageReceived(const IPC::Message& message) override;
void OnStartSentAndScriptEvaluated(ServiceWorkerStatusCode status);
@@ -632,6 +635,8 @@ class CONTENT_EXPORT ServiceWorkerVersion
void OpenPaymentHandlerWindow(
const GURL& url,
OpenPaymentHandlerWindowCallback callback) override;
+ void PostMessageToClient(const std::string& client_uuid,
+ blink::TransferableMessage message) override;
void FocusClient(const std::string& client_uuid,
FocusClientCallback callback) override;
void NavigateClient(const std::string& client_uuid,
@@ -644,16 +649,9 @@ class CONTENT_EXPORT ServiceWorkerVersion
int result);
void OnClearCachedMetadataFinished(int64_t callback_id, int result);
void OpenWindow(GURL url,
- WindowOpenDisposition disposition,
+ service_worker_client_utils::WindowType type,
OpenNewTabCallback callback);
- // Message handlers.
-
- void OnPostMessageToClient(
- const std::string& client_uuid,
- const scoped_refptr<base::RefCountedData<blink::TransferableMessage>>&
- message);
-
void OnPongFromWorker();
void DidEnsureLiveRegistrationForStartWorker(
@@ -836,7 +834,7 @@ class CONTENT_EXPORT ServiceWorkerVersion
ServiceWorkerStatusCode start_worker_status_ = SERVICE_WORKER_OK;
// The clock used to vend tick time.
- base::TickClock* tick_clock_;
+ const base::TickClock* tick_clock_;
// The clock used for actual (wall clock) time
base::Clock* clock_;
@@ -855,9 +853,8 @@ class CONTENT_EXPORT ServiceWorkerVersion
base::Optional<ServiceWorkerMetrics::EventType> start_worker_first_purpose_;
// This is the set of features that were used up until installation of this
- // version completed, or used during the lifetime of |this|. The values must
- // be from blink::UseCounter::Feature enum.
- std::set<uint32_t> used_features_;
+ // version completed, or used during the lifetime of |this|.
+ std::set<blink::mojom::WebFeature> used_features_;
std::unique_ptr<blink::TrialTokenValidator> validator_;
diff --git a/chromium/content/browser/service_worker/service_worker_version_unittest.cc b/chromium/content/browser/service_worker/service_worker_version_unittest.cc
index b27604eb3c0..8023d7da5fa 100644
--- a/chromium/content/browser/service_worker/service_worker_version_unittest.cc
+++ b/chromium/content/browser/service_worker/service_worker_version_unittest.cc
@@ -29,27 +29,10 @@
#include "content/public/test/test_utils.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_event_status.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_installed_scripts_manager.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
-
-// IPC messages for testing ---------------------------------------------------
-
-#undef IPC_IPC_MESSAGE_MACROS_H_
-#undef IPC_MESSAGE_EXTRA
-#define IPC_MESSAGE_IMPL
-#include "ipc/ipc_message_macros.h"
-#include "ipc/ipc_message_templates_impl.h"
-
-#define IPC_MESSAGE_START TestMsgStart
-
-IPC_MESSAGE_CONTROL0(TestMsg_Message)
-IPC_MESSAGE_ROUTED1(TestMsg_MessageFromWorker, int)
-
-IPC_MESSAGE_ROUTED2(TestMsg_TestEventResult, int, std::string)
-
-// ---------------------------------------------------------------------------
+#include "third_party/blink/public/mojom/service_worker/service_worker.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_event_status.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_installed_scripts_manager.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
namespace service_worker_version_unittest {
@@ -59,17 +42,6 @@ class MessageReceiver : public EmbeddedWorkerTestHelper {
MessageReceiver() : EmbeddedWorkerTestHelper(base::FilePath()) {}
~MessageReceiver() override {}
- void SimulateSendValueToBrowser(int embedded_worker_id, int value) {
- SimulateSend(new TestMsg_MessageFromWorker(embedded_worker_id, value));
- }
-
- void SimulateSendEventResult(int embedded_worker_id,
- int request_id,
- const std::string& reply) {
- SimulateSend(
- new TestMsg_TestEventResult(embedded_worker_id, request_id, reply));
- }
-
void SimulateSetCachedMetadata(int embedded_worker_id,
const GURL& url,
const std::vector<uint8_t>& data) {
@@ -107,10 +79,6 @@ class MessageReceiver : public EmbeddedWorkerTestHelper {
}
private:
- void OnMessage() {
- // Do nothing.
- }
-
std::map<
int /* embedded_worker_id */,
blink::mojom::ServiceWorkerHostAssociatedPtr /* service_worker_host */>
@@ -130,35 +98,6 @@ void ObserveStatusChanges(ServiceWorkerVersion* version,
&ObserveStatusChanges, base::Unretained(version), statuses));
}
-// A specialized listener class to receive test messages from a worker.
-class MessageReceiverFromWorker : public EmbeddedWorkerInstance::Listener {
- public:
- explicit MessageReceiverFromWorker(EmbeddedWorkerInstance* instance)
- : instance_(instance) {
- instance_->AddListener(this);
- }
- ~MessageReceiverFromWorker() override { instance_->RemoveListener(this); }
-
- void OnStarted() override { NOTREACHED(); }
- void OnStopped(EmbeddedWorkerStatus old_status) override { NOTREACHED(); }
- bool OnMessageReceived(const IPC::Message& message) override {
- bool handled = true;
- IPC_BEGIN_MESSAGE_MAP(MessageReceiverFromWorker, message)
- IPC_MESSAGE_HANDLER(TestMsg_MessageFromWorker, OnMessageFromWorker)
- IPC_MESSAGE_UNHANDLED(handled = false)
- IPC_END_MESSAGE_MAP()
- return handled;
- }
-
- void OnMessageFromWorker(int value) { received_values_.push_back(value); }
- const std::vector<int>& received_values() const { return received_values_; }
-
- private:
- EmbeddedWorkerInstance* instance_;
- std::vector<int> received_values_;
- DISALLOW_COPY_AND_ASSIGN(MessageReceiverFromWorker);
-};
-
base::Time GetYesterday() {
return base::Time::Now() - base::TimeDelta::FromDays(1) -
base::TimeDelta::FromSeconds(1);
@@ -575,24 +514,6 @@ TEST_F(ServiceWorkerVersionTest, StartUnregisteredButStillLiveWorker) {
EXPECT_EQ(EmbeddedWorkerStatus::RUNNING, version_->running_status());
}
-TEST_F(ServiceWorkerVersionTest, ReceiveMessageFromWorker) {
- // Start worker.
- StartWorker(version_.get(), ServiceWorkerMetrics::EventType::UNKNOWN);
-
- MessageReceiverFromWorker receiver(version_->embedded_worker());
-
- // Simulate sending some dummy values from the worker.
- helper_->SimulateSendValueToBrowser(
- version_->embedded_worker()->embedded_worker_id(), 555);
- helper_->SimulateSendValueToBrowser(
- version_->embedded_worker()->embedded_worker_id(), 777);
-
- // Verify the receiver received the values.
- ASSERT_EQ(2U, receiver.received_values().size());
- EXPECT_EQ(555, receiver.received_values()[0]);
- EXPECT_EQ(777, receiver.received_values()[1]);
-}
-
TEST_F(ServiceWorkerVersionTest, InstallAndWaitCompletion) {
version_->SetStatus(ServiceWorkerVersion::INSTALLING);
diff --git a/chromium/content/browser/service_worker/service_worker_write_to_cache_job.cc b/chromium/content/browser/service_worker/service_worker_write_to_cache_job.cc
index a4805f18a87..7b25cc96dcd 100644
--- a/chromium/content/browser/service_worker/service_worker_write_to_cache_job.cc
+++ b/chromium/content/browser/service_worker/service_worker_write_to_cache_job.cc
@@ -6,7 +6,6 @@
#include "base/bind.h"
#include "base/command_line.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/stringprintf.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/trace_event/trace_event.h"
@@ -27,25 +26,16 @@
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_status.h"
-#include "third_party/WebKit/public/common/mime_util/mime_util.h"
-#include "third_party/WebKit/public/web/WebConsoleMessage.h"
+#include "third_party/blink/public/common/mime_util/mime_util.h"
+#include "third_party/blink/public/web/web_console_message.h"
namespace content {
namespace {
const char kKilledError[] = "The request to fetch the script was interrupted.";
-const char kBadHTTPResponseError[] =
- "A bad HTTP response code (%d) was received when fetching the script.";
-const char kSSLError[] =
- "An SSL certificate error occurred when fetching the script.";
-const char kBadMIMEError[] = "The script has an unsupported MIME type ('%s').";
-const char kNoMIMEError[] = "The script does not have a MIME type.";
const char kClientAuthenticationError[] =
"Client authentication was required to fetch the script.";
-const char kRedirectError[] =
- "The script resource is behind a redirect, which is disallowed.";
-const char kServiceWorkerAllowed[] = "Service-Worker-Allowed";
bool ShouldIgnoreSSLError(net::URLRequest* request) {
const net::HttpNetworkSession::Params* session_params =
@@ -186,7 +176,7 @@ int ServiceWorkerWriteToCacheJob::ReadRawData(net::IOBuffer* buf,
if (rv < 0) {
net::Error error = static_cast<net::Error>(rv);
- error = NotifyFinishedCaching(error, kFetchScriptError);
+ error = NotifyFinishedCaching(error, kServiceWorkerFetchScriptError);
DCHECK_EQ(rv, error);
return error;
}
@@ -272,7 +262,7 @@ void ServiceWorkerWriteToCacheJob::OnReceivedRedirect(
TRACE_EVENT0("ServiceWorker",
"ServiceWorkerWriteToCacheJob::OnReceivedRedirect");
// Script resources can't redirect.
- NotifyStartErrorHelper(net::ERR_UNSAFE_REDIRECT, kRedirectError);
+ NotifyStartErrorHelper(net::ERR_UNSAFE_REDIRECT, kServiceWorkerRedirectError);
}
void ServiceWorkerWriteToCacheJob::OnAuthRequired(
@@ -308,7 +298,7 @@ void ServiceWorkerWriteToCacheJob::OnSSLCertificateError(
} else {
NotifyStartErrorHelper(
net::Error(net::MapCertStatusToNetError(ssl_info.cert_status)),
- kSSLError);
+ kServiceWorkerSSLError);
}
}
@@ -319,12 +309,12 @@ void ServiceWorkerWriteToCacheJob::OnResponseStarted(net::URLRequest* request,
if (net_error != net::OK) {
net::Error error = static_cast<net::Error>(net_error);
- NotifyStartErrorHelper(error, kFetchScriptError);
+ NotifyStartErrorHelper(error, kServiceWorkerFetchScriptError);
return;
}
if (request->GetResponseCode() / 100 != 2) {
- std::string error_message =
- base::StringPrintf(kBadHTTPResponseError, request->GetResponseCode());
+ std::string error_message = base::StringPrintf(
+ kServiceWorkerBadHTTPResponseError, request->GetResponseCode());
NotifyStartErrorHelper(net::ERR_INVALID_RESPONSE, error_message);
// TODO(michaeln): Instead of error'ing immediately, send the net
// response to our consumer, just don't cache it?
@@ -336,7 +326,7 @@ void ServiceWorkerWriteToCacheJob::OnResponseStarted(net::URLRequest* request,
!ShouldIgnoreSSLError(request)) {
NotifyStartErrorHelper(net::Error(net::MapCertStatusToNetError(
request->ssl_info().cert_status)),
- kSSLError);
+ kServiceWorkerSSLError);
return;
}
@@ -345,9 +335,9 @@ void ServiceWorkerWriteToCacheJob::OnResponseStarted(net::URLRequest* request,
request->GetMimeType(&mime_type);
if (!blink::IsSupportedJavascriptMimeType(mime_type)) {
std::string error_message =
- mime_type.empty()
- ? kNoMIMEError
- : base::StringPrintf(kBadMIMEError, mime_type.c_str());
+ mime_type.empty() ? kServiceWorkerNoMIMEError
+ : base::StringPrintf(kServiceWorkerBadMIMEError,
+ mime_type.c_str());
NotifyStartErrorHelper(net::ERR_INSECURE_RESPONSE, error_message);
return;
}
@@ -410,7 +400,7 @@ void ServiceWorkerWriteToCacheJob::OnReadCompleted(net::URLRequest* request,
int result;
if (bytes_read < 0) {
net::Error error = static_cast<net::Error>(bytes_read);
- result = NotifyFinishedCaching(error, kFetchScriptError);
+ result = NotifyFinishedCaching(error, kServiceWorkerFetchScriptError);
} else {
result = HandleNetData(bytes_read);
}
@@ -475,7 +465,8 @@ net::Error ServiceWorkerWriteToCacheJob::NotifyFinishedCaching(
// response.
version_->embedded_worker()->AddMessageToConsole(
blink::WebConsoleMessage::kLevelError,
- status_message.empty() ? kFetchScriptError : status_message);
+ status_message.empty() ? kServiceWorkerFetchScriptError
+ : status_message);
} else {
size = cache_writer_->bytes_written();
}
diff --git a/chromium/content/browser/service_worker/service_worker_write_to_cache_job_unittest.cc b/chromium/content/browser/service_worker/service_worker_write_to_cache_job_unittest.cc
index e99f8b3479f..0b248f1fd2e 100644
--- a/chromium/content/browser/service_worker/service_worker_write_to_cache_job_unittest.cc
+++ b/chromium/content/browser/service_worker/service_worker_write_to_cache_job_unittest.cc
@@ -38,7 +38,7 @@
#include "services/network/public/mojom/request_context_frame_type.mojom.h"
#include "storage/browser/blob/blob_storage_context.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
namespace service_worker_write_to_cache_job_unittest {
diff --git a/chromium/content/browser/shared_worker/DEPS b/chromium/content/browser/shared_worker/DEPS
index 54247a69bd5..749142bbf09 100644
--- a/chromium/content/browser/shared_worker/DEPS
+++ b/chromium/content/browser/shared_worker/DEPS
@@ -1,5 +1,4 @@
include_rules = [
- "+third_party/WebKit/public/platform/web_feature.mojom.h",
- "+third_party/WebKit/public/web/shared_worker_creation_context_type.mojom.h",
- "+third_party/WebKit/public/web/worker_content_settings_proxy.mojom.h",
+ "+third_party/blink/public/platform/web_feature.mojom.h",
+ "+third_party/blink/public/web/worker_content_settings_proxy.mojom.h",
]
diff --git a/chromium/content/browser/shared_worker/shared_worker_connector_impl.cc b/chromium/content/browser/shared_worker/shared_worker_connector_impl.cc
index 11b579bdeca..4b08ffd8b66 100644
--- a/chromium/content/browser/shared_worker/shared_worker_connector_impl.cc
+++ b/chromium/content/browser/shared_worker/shared_worker_connector_impl.cc
@@ -11,7 +11,7 @@
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_process_host.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
-#include "third_party/WebKit/public/common/message_port/message_port_channel.h"
+#include "third_party/blink/public/common/message_port/message_port_channel.h"
namespace content {
diff --git a/chromium/content/browser/shared_worker/shared_worker_content_settings_proxy_impl.h b/chromium/content/browser/shared_worker/shared_worker_content_settings_proxy_impl.h
index 967f28d88f1..03ffc05e0cf 100644
--- a/chromium/content/browser/shared_worker/shared_worker_content_settings_proxy_impl.h
+++ b/chromium/content/browser/shared_worker/shared_worker_content_settings_proxy_impl.h
@@ -10,7 +10,7 @@
#include "content/common/content_export.h"
#include "content/public/browser/resource_context.h"
#include "mojo/public/cpp/bindings/binding.h"
-#include "third_party/WebKit/public/web/worker_content_settings_proxy.mojom.h"
+#include "third_party/blink/public/web/worker_content_settings_proxy.mojom.h"
#include "url/origin.h"
namespace content {
diff --git a/chromium/content/browser/shared_worker/shared_worker_host.cc b/chromium/content/browser/shared_worker/shared_worker_host.cc
index 12d52395812..623c6617174 100644
--- a/chromium/content/browser/shared_worker/shared_worker_host.cc
+++ b/chromium/content/browser/shared_worker/shared_worker_host.cc
@@ -7,6 +7,7 @@
#include <utility>
#include "base/metrics/histogram_macros.h"
+#include "base/unguessable_token.h"
#include "content/browser/devtools/shared_worker_devtools_manager.h"
#include "content/browser/interface_provider_filtering.h"
#include "content/browser/renderer_interface_binders.h"
@@ -18,9 +19,9 @@
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_client.h"
-#include "third_party/WebKit/public/common/message_port/message_port_channel.h"
-#include "third_party/WebKit/public/platform/web_feature.mojom.h"
-#include "third_party/WebKit/public/web/worker_content_settings_proxy.mojom.h"
+#include "third_party/blink/public/common/message_port/message_port_channel.h"
+#include "third_party/blink/public/platform/web_feature.mojom.h"
+#include "third_party/blink/public/web/worker_content_settings_proxy.mojom.h"
namespace content {
namespace {
@@ -77,29 +78,44 @@ SharedWorkerHost::~SharedWorkerHost() {
void SharedWorkerHost::Start(
mojom::SharedWorkerFactoryPtr factory,
- bool pause_on_start,
- const base::UnguessableToken& devtools_worker_token) {
+ mojom::ServiceWorkerProviderInfoForSharedWorkerPtr
+ service_worker_provider_info,
+ network::mojom::URLLoaderFactoryAssociatedPtrInfo script_loader_factory) {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+
+ mojom::SharedWorkerInfoPtr info(mojom::SharedWorkerInfo::New(
+ instance_->url(), instance_->name(), instance_->content_security_policy(),
+ instance_->content_security_policy_type(),
+ instance_->creation_address_space()));
+
+ // Register with DevTools.
+ bool pause_on_start;
+ base::UnguessableToken devtools_worker_token;
+ SharedWorkerDevToolsManager::GetInstance()->WorkerCreated(
+ this, &pause_on_start, &devtools_worker_token);
+
+ // Set up content settings interface.
blink::mojom::WorkerContentSettingsProxyPtr content_settings;
content_settings_ = std::make_unique<SharedWorkerContentSettingsProxyImpl>(
instance_->url(), this, mojo::MakeRequest(&content_settings));
+ // Set up host interface.
mojom::SharedWorkerHostPtr host;
binding_.Bind(mojo::MakeRequest(&host));
+ // Set up interface provider interface.
service_manager::mojom::InterfaceProviderPtr interface_provider;
interface_provider_binding_.Bind(FilterRendererExposedInterfaces(
mojom::kNavigation_SharedWorkerSpec, process_id_,
mojo::MakeRequest(&interface_provider)));
- mojom::SharedWorkerInfoPtr info(mojom::SharedWorkerInfo::New(
- instance_->url(), instance_->name(), instance_->content_security_policy(),
- instance_->content_security_policy_type(),
- instance_->creation_address_space()));
-
- factory->CreateSharedWorker(
+ // Send the CreateSharedWorker message.
+ factory_ = std::move(factory);
+ factory_->CreateSharedWorker(
std::move(info), pause_on_start, devtools_worker_token,
- std::move(content_settings), std::move(host), mojo::MakeRequest(&worker_),
- std::move(interface_provider));
+ std::move(content_settings), std::move(service_worker_provider_info),
+ std::move(script_loader_factory), std::move(host),
+ mojo::MakeRequest(&worker_), std::move(interface_provider));
// Monitor the lifetime of the worker.
worker_.set_connection_error_handler(base::BindOnce(
diff --git a/chromium/content/browser/shared_worker/shared_worker_host.h b/chromium/content/browser/shared_worker/shared_worker_host.h
index 3a85dd31a9c..dd95fc35655 100644
--- a/chromium/content/browser/shared_worker/shared_worker_host.h
+++ b/chromium/content/browser/shared_worker/shared_worker_host.h
@@ -16,13 +16,15 @@
#include "base/strings/string16.h"
#include "base/time/time.h"
#include "base/unguessable_token.h"
+#include "content/common/service_worker/service_worker_provider.mojom.h"
#include "content/common/shared_worker/shared_worker.mojom.h"
#include "content/common/shared_worker/shared_worker_client.mojom.h"
#include "content/common/shared_worker/shared_worker_factory.mojom.h"
#include "content/common/shared_worker/shared_worker_host.mojom.h"
#include "mojo/public/cpp/bindings/binding.h"
+#include "services/network/public/mojom/url_loader_factory.mojom.h"
#include "services/service_manager/public/mojom/interface_provider.mojom.h"
-#include "third_party/WebKit/public/web/devtools_agent.mojom.h"
+#include "third_party/blink/public/web/devtools_agent.mojom.h"
class GURL;
@@ -31,7 +33,6 @@ class MessagePortChannel;
}
namespace content {
-
class SharedWorkerContentSettingsProxyImpl;
class SharedWorkerInstance;
class SharedWorkerServiceImpl;
@@ -49,9 +50,22 @@ class SharedWorkerHost : public mojom::SharedWorkerHost,
~SharedWorkerHost() override;
// Starts the SharedWorker in the renderer process.
- void Start(mojom::SharedWorkerFactoryPtr factory,
- bool pause_on_start,
- const base::UnguessableToken& devtools_worker_token);
+ //
+ // S13nServiceWorker:
+ // |service_worker_provider_info| is sent to the renderer process and contains
+ // information about its ServiceWorkerProviderHost, the browser-side host for
+ // supporting the shared worker as a service worker client.
+ //
+ // S13nServiceWorker:
+ // |script_loader_factory| is sent to the renderer process and is to be used
+ // to request the shared worker's script. Currently it's only non-null when
+ // S13nServiceWorker is enabled, to allow service worker machinery to observe
+ // the request, but other web platform features may also use it someday.
+ void Start(
+ mojom::SharedWorkerFactoryPtr factory,
+ mojom::ServiceWorkerProviderInfoForSharedWorkerPtr
+ service_worker_provider_info,
+ network::mojom::URLLoaderFactoryAssociatedPtrInfo script_loader_factory);
void AllowFileSystem(const GURL& url,
base::OnceCallback<void(bool)> callback);
@@ -109,6 +123,7 @@ class SharedWorkerHost : public mojom::SharedWorkerHost,
mojo::ScopedMessagePipeHandle interface_pipe) override;
mojo::Binding<mojom::SharedWorkerHost> binding_;
+ // |service_| owns |this|.
SharedWorkerServiceImpl* service_;
std::unique_ptr<SharedWorkerInstance> instance_;
ClientList clients_;
@@ -126,6 +141,12 @@ class SharedWorkerHost : public mojom::SharedWorkerHost,
std::unique_ptr<SharedWorkerContentSettingsProxyImpl> content_settings_;
+ // This is kept alive during the lifetime of the shared worker, since it's
+ // associated with Mojo interfaces (ServiceWorkerContainer and
+ // URLLoaderFactory) that are needed to stay alive while the worker is
+ // starting or running.
+ mojom::SharedWorkerFactoryPtr factory_;
+
mojo::Binding<service_manager::mojom::InterfaceProvider>
interface_provider_binding_;
diff --git a/chromium/content/browser/shared_worker/shared_worker_instance.h b/chromium/content/browser/shared_worker/shared_worker_instance.h
index 62de2075a7c..eb909daa38d 100644
--- a/chromium/content/browser/shared_worker/shared_worker_instance.h
+++ b/chromium/content/browser/shared_worker/shared_worker_instance.h
@@ -8,9 +8,9 @@
#include <string>
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/mojom/net/ip_address_space.mojom.h"
-#include "third_party/WebKit/public/platform/WebContentSecurityPolicy.h"
-#include "third_party/WebKit/public/web/shared_worker_creation_context_type.mojom.h"
+#include "third_party/blink/public/mojom/net/ip_address_space.mojom.h"
+#include "third_party/blink/public/mojom/shared_worker/shared_worker_creation_context_type.mojom.h"
+#include "third_party/blink/public/platform/web_content_security_policy.h"
#include "url/gurl.h"
#include "url/origin.h"
diff --git a/chromium/content/browser/shared_worker/shared_worker_script_loader.cc b/chromium/content/browser/shared_worker/shared_worker_script_loader.cc
new file mode 100644
index 00000000000..ff39e068b26
--- /dev/null
+++ b/chromium/content/browser/shared_worker/shared_worker_script_loader.cc
@@ -0,0 +1,203 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/shared_worker/shared_worker_script_loader.h"
+
+#include "content/browser/loader/navigation_loader_interceptor.h"
+#include "content/browser/service_worker/service_worker_provider_host.h"
+#include "content/browser/url_loader_factory_getter.h"
+#include "content/common/service_worker/service_worker_utils.h"
+#include "content/public/browser/resource_context.h"
+#include "net/url_request/redirect_util.h"
+
+namespace content {
+
+SharedWorkerScriptLoader::SharedWorkerScriptLoader(
+ int32_t routing_id,
+ int32_t request_id,
+ uint32_t options,
+ const network::ResourceRequest& resource_request,
+ network::mojom::URLLoaderClientPtr client,
+ base::WeakPtr<ServiceWorkerProviderHost> service_worker_provider_host,
+ ResourceContext* resource_context,
+ scoped_refptr<URLLoaderFactoryGetter> loader_factory_getter,
+ const net::MutableNetworkTrafficAnnotationTag& traffic_annotation)
+ : routing_id_(routing_id),
+ request_id_(request_id),
+ options_(options),
+ resource_request_(resource_request),
+ client_(std::move(client)),
+ service_worker_provider_host_(service_worker_provider_host),
+ resource_context_(resource_context),
+ loader_factory_getter_(std::move(loader_factory_getter)),
+ traffic_annotation_(traffic_annotation),
+ url_loader_client_binding_(this),
+ weak_factory_(this) {
+ DCHECK(ServiceWorkerUtils::IsServicificationEnabled());
+
+ if (service_worker_provider_host_) {
+ service_worker_interceptor_ =
+ ServiceWorkerRequestHandler::InitializeForSharedWorker(
+ resource_request_, service_worker_provider_host_);
+ }
+
+ Start();
+}
+
+SharedWorkerScriptLoader::~SharedWorkerScriptLoader() = default;
+
+void SharedWorkerScriptLoader::Start() {
+ if (service_worker_interceptor_) {
+ service_worker_interceptor_->MaybeCreateLoader(
+ resource_request_, resource_context_,
+ base::BindOnce(&SharedWorkerScriptLoader::MaybeStartLoader,
+ weak_factory_.GetWeakPtr(),
+ service_worker_interceptor_.get()));
+ return;
+ }
+
+ LoadFromNetwork();
+}
+
+void SharedWorkerScriptLoader::MaybeStartLoader(
+ NavigationLoaderInterceptor* interceptor,
+ SingleRequestURLLoaderFactory::RequestHandler single_request_handler) {
+ if (single_request_handler) {
+ // The interceptor elected to handle the request. Use it.
+ network::mojom::URLLoaderClientPtr client;
+ url_loader_client_binding_.Bind(mojo::MakeRequest(&client));
+ url_loader_factory_ = base::MakeRefCounted<SingleRequestURLLoaderFactory>(
+ std::move(single_request_handler));
+ url_loader_factory_->CreateLoaderAndStart(
+ mojo::MakeRequest(&url_loader_), routing_id_, request_id_, options_,
+ resource_request_, std::move(client), traffic_annotation_);
+ // We continue in URLLoaderClient calls.
+ return;
+ }
+
+ // TODO(falken): Support blob urls.
+
+ LoadFromNetwork();
+}
+
+void SharedWorkerScriptLoader::LoadFromNetwork() {
+ network::mojom::URLLoaderClientPtr client;
+ url_loader_client_binding_.Bind(mojo::MakeRequest(&client));
+ url_loader_factory_ = loader_factory_getter_->GetNetworkFactory();
+ url_loader_factory_->CreateLoaderAndStart(
+ mojo::MakeRequest(&url_loader_), routing_id_, request_id_, options_,
+ resource_request_, std::move(client), traffic_annotation_);
+ // We continue in URLLoaderClient calls.
+}
+
+// URLLoader -------------------------------------------------------------------
+// When this class gets a FollowRedirect IPC from the renderer, it restarts with
+// the new URL.
+
+void SharedWorkerScriptLoader::FollowRedirect() {
+ DCHECK(redirect_info_);
+
+ // |should_clear_upload| is unused because there is no body anyway.
+ DCHECK(!resource_request_.request_body);
+ bool should_clear_upload = false;
+ net::RedirectUtil::UpdateHttpRequest(
+ resource_request_.url, resource_request_.method, *redirect_info_,
+ &resource_request_.headers, &should_clear_upload);
+
+ resource_request_.url = redirect_info_->new_url;
+ resource_request_.method = redirect_info_->new_method;
+ resource_request_.site_for_cookies = redirect_info_->new_site_for_cookies;
+ resource_request_.referrer = GURL(redirect_info_->new_referrer);
+ resource_request_.referrer_policy = redirect_info_->new_referrer_policy;
+
+ // Restart the request.
+ url_loader_client_binding_.Unbind();
+ redirect_info_.reset();
+ Start();
+}
+
+void SharedWorkerScriptLoader::ProceedWithResponse() {
+ // Only for navigations.
+ NOTREACHED();
+}
+
+// Below we make a small effort to support the other URLLoader functions by
+// forwarding to the current |url_loader_| if any, but don't bother queuing
+// state or propagating state to a new URLLoader upon redirect.
+void SharedWorkerScriptLoader::SetPriority(net::RequestPriority priority,
+ int32_t intra_priority_value) {
+ if (url_loader_)
+ url_loader_->SetPriority(priority, intra_priority_value);
+}
+
+void SharedWorkerScriptLoader::PauseReadingBodyFromNet() {
+ if (url_loader_)
+ url_loader_->PauseReadingBodyFromNet();
+}
+
+void SharedWorkerScriptLoader::ResumeReadingBodyFromNet() {
+ if (url_loader_)
+ url_loader_->ResumeReadingBodyFromNet();
+}
+
+// URLLoaderClient ----------------------------------------------------------
+// This class forwards any client messages to the outer client in the renderer.
+// Additionally, on redirects it saves the redirect info so if the renderer
+// calls FollowRedirect(), it can do so.
+
+void SharedWorkerScriptLoader::OnReceiveResponse(
+ const network::ResourceResponseHead& response_head,
+ network::mojom::DownloadedTempFilePtr downloaded_file) {
+ client_->OnReceiveResponse(response_head, std::move(downloaded_file));
+}
+
+void SharedWorkerScriptLoader::OnReceiveRedirect(
+ const net::RedirectInfo& redirect_info,
+ const network::ResourceResponseHead& response_head) {
+ if (--redirect_limit_ == 0) {
+ client_->OnComplete(
+ network::URLLoaderCompletionStatus(net::ERR_TOO_MANY_REDIRECTS));
+ return;
+ }
+
+ redirect_info_ = redirect_info;
+ client_->OnReceiveRedirect(redirect_info, response_head);
+}
+
+void SharedWorkerScriptLoader::OnDataDownloaded(int64_t data_len,
+ int64_t encoded_data_len) {
+ client_->OnDataDownloaded(data_len, encoded_data_len);
+}
+
+void SharedWorkerScriptLoader::OnUploadProgress(
+ int64_t current_position,
+ int64_t total_size,
+ OnUploadProgressCallback ack_callback) {
+ client_->OnUploadProgress(current_position, total_size,
+ std::move(ack_callback));
+}
+
+void SharedWorkerScriptLoader::OnReceiveCachedMetadata(
+ const std::vector<uint8_t>& data) {
+ client_->OnReceiveCachedMetadata(data);
+}
+
+void SharedWorkerScriptLoader::OnTransferSizeUpdated(
+ int32_t transfer_size_diff) {
+ client_->OnTransferSizeUpdated(transfer_size_diff);
+}
+
+void SharedWorkerScriptLoader::OnStartLoadingResponseBody(
+ mojo::ScopedDataPipeConsumerHandle consumer) {
+ client_->OnStartLoadingResponseBody(std::move(consumer));
+}
+
+void SharedWorkerScriptLoader::OnComplete(
+ const network::URLLoaderCompletionStatus& status) {
+ if (status.error_code == net::OK)
+ service_worker_provider_host_->CompleteSharedWorkerPreparation();
+ client_->OnComplete(status);
+}
+
+} // namespace content
diff --git a/chromium/content/browser/shared_worker/shared_worker_script_loader.h b/chromium/content/browser/shared_worker/shared_worker_script_loader.h
new file mode 100644
index 00000000000..7e61d8c6c69
--- /dev/null
+++ b/chromium/content/browser/shared_worker/shared_worker_script_loader.h
@@ -0,0 +1,106 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_BROWSER_SHARED_WORKER_SHARED_WORKER_SCRIPT_LOADER_H_
+#define CONTENT_BROWSER_SHARED_WORKER_SHARED_WORKER_SCRIPT_LOADER_H_
+
+#include "base/macros.h"
+#include "content/common/single_request_url_loader_factory.h"
+#include "mojo/public/cpp/bindings/binding.h"
+#include "net/traffic_annotation/network_traffic_annotation.h"
+#include "services/network/public/cpp/resource_request.h"
+#include "services/network/public/mojom/url_loader.mojom.h"
+
+namespace content {
+class NavigationLoaderInterceptor;
+class ResourceContext;
+class ServiceWorkerProviderHost;
+class URLLoaderFactoryGetter;
+
+// The URLLoader for loading a shared worker script. Only used for the main
+// script request.
+//
+// This acts much like NavigationURLLoaderNetworkService. It allows a
+// NavigationLoaderInterceptor to intercept the request with its own loader, and
+// goes to the network loader otherwise. Once a loader is started, this class
+// acts as the URLLoaderClient for it, forwarding messages to the outer client.
+// On redirects, it starts over with the new request URL, possibly starting a
+// new loader and becoming the client of that.
+//
+// Lives on the IO thread.
+class SharedWorkerScriptLoader : public network::mojom::URLLoader,
+ public network::mojom::URLLoaderClient {
+ public:
+ SharedWorkerScriptLoader(
+ int32_t routing_id,
+ int32_t request_id,
+ uint32_t options,
+ const network::ResourceRequest& resource_request,
+ network::mojom::URLLoaderClientPtr client,
+ base::WeakPtr<ServiceWorkerProviderHost> service_worker_provider_host,
+ ResourceContext* resource_context,
+ scoped_refptr<URLLoaderFactoryGetter> loader_factory_getter,
+ const net::MutableNetworkTrafficAnnotationTag& traffic_annotation);
+ ~SharedWorkerScriptLoader() override;
+
+ // network::mojom::URLLoader:
+ void FollowRedirect() override;
+ void ProceedWithResponse() override;
+ void SetPriority(net::RequestPriority priority,
+ int32_t intra_priority_value) override;
+ void PauseReadingBodyFromNet() override;
+ void ResumeReadingBodyFromNet() override;
+
+ // network::mojom::URLLoaderClient:
+ void OnReceiveResponse(
+ const network::ResourceResponseHead& response_head,
+ network::mojom::DownloadedTempFilePtr downloaded_file) override;
+ void OnReceiveRedirect(
+ const net::RedirectInfo& redirect_info,
+ const network::ResourceResponseHead& response_head) override;
+ void OnDataDownloaded(int64_t data_len, int64_t encoded_data_len) override;
+ void OnUploadProgress(int64_t current_position,
+ int64_t total_size,
+ OnUploadProgressCallback ack_callback) override;
+ void OnReceiveCachedMetadata(const std::vector<uint8_t>& data) override;
+ void OnTransferSizeUpdated(int32_t transfer_size_diff) override;
+ void OnStartLoadingResponseBody(
+ mojo::ScopedDataPipeConsumerHandle body) override;
+ void OnComplete(const network::URLLoaderCompletionStatus& status) override;
+
+ private:
+ void Start();
+ void MaybeStartLoader(
+ NavigationLoaderInterceptor* interceptor,
+ SingleRequestURLLoaderFactory::RequestHandler single_request_handler);
+ void LoadFromNetwork();
+
+ // TODO(falken): Add other interceptors like in
+ // NavigationURLLoaderNetworkService.
+ std::unique_ptr<NavigationLoaderInterceptor> service_worker_interceptor_;
+
+ const int32_t routing_id_;
+ const int32_t request_id_;
+ const uint32_t options_;
+ network::ResourceRequest resource_request_;
+ network::mojom::URLLoaderClientPtr client_;
+ base::WeakPtr<ServiceWorkerProviderHost> service_worker_provider_host_;
+ ResourceContext* resource_context_;
+ scoped_refptr<URLLoaderFactoryGetter> loader_factory_getter_;
+ net::MutableNetworkTrafficAnnotationTag traffic_annotation_;
+
+ base::Optional<net::RedirectInfo> redirect_info_;
+ int redirect_limit_ = net::URLRequest::kMaxRedirects;
+
+ network::mojom::URLLoaderPtr url_loader_;
+ mojo::Binding<network::mojom::URLLoaderClient> url_loader_client_binding_;
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
+
+ base::WeakPtrFactory<SharedWorkerScriptLoader> weak_factory_;
+
+ DISALLOW_COPY_AND_ASSIGN(SharedWorkerScriptLoader);
+};
+
+} // namespace content
+#endif // CONTENT_BROWSER_SHARED_WORKER_SHARED_WORKER_SCRIPT_LOADER_H_
diff --git a/chromium/content/browser/shared_worker/shared_worker_script_loader_factory.cc b/chromium/content/browser/shared_worker/shared_worker_script_loader_factory.cc
new file mode 100644
index 00000000000..f819351042c
--- /dev/null
+++ b/chromium/content/browser/shared_worker/shared_worker_script_loader_factory.cc
@@ -0,0 +1,69 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/shared_worker/shared_worker_script_loader_factory.h"
+
+#include <memory>
+#include "content/browser/service_worker/service_worker_context_core.h"
+#include "content/browser/service_worker/service_worker_context_wrapper.h"
+#include "content/browser/service_worker/service_worker_provider_host.h"
+#include "content/browser/service_worker/service_worker_version.h"
+#include "content/browser/shared_worker/shared_worker_script_loader.h"
+#include "content/browser/url_loader_factory_getter.h"
+#include "content/common/service_worker/service_worker_utils.h"
+#include "mojo/public/cpp/bindings/strong_binding.h"
+#include "services/network/public/cpp/resource_response.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_provider_type.mojom.h"
+
+namespace content {
+
+SharedWorkerScriptLoaderFactory::SharedWorkerScriptLoaderFactory(
+ ServiceWorkerContextWrapper* context,
+ base::WeakPtr<ServiceWorkerProviderHost> service_worker_provider_host,
+ ResourceContext* resource_context,
+ scoped_refptr<URLLoaderFactoryGetter> loader_factory_getter)
+ : service_worker_provider_host_(service_worker_provider_host),
+ resource_context_(resource_context),
+ loader_factory_getter_(loader_factory_getter) {
+ DCHECK(ServiceWorkerUtils::IsServicificationEnabled());
+ DCHECK_EQ(service_worker_provider_host_->provider_type(),
+ blink::mojom::ServiceWorkerProviderType::kForSharedWorker);
+}
+
+SharedWorkerScriptLoaderFactory::~SharedWorkerScriptLoaderFactory() {}
+
+void SharedWorkerScriptLoaderFactory::CreateLoaderAndStart(
+ network::mojom::URLLoaderRequest request,
+ int32_t routing_id,
+ int32_t request_id,
+ uint32_t options,
+ const network::ResourceRequest& resource_request,
+ network::mojom::URLLoaderClientPtr client,
+ const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) {
+ // Handle only the main script (RESOURCE_TYPE_SHARED_WORKER). Import scripts
+ // should go to the network loader or controller.
+ if (resource_request.resource_type != RESOURCE_TYPE_SHARED_WORKER) {
+ mojo::ReportBadMessage(
+ "SharedWorkerScriptLoaderFactory should only get requests for shared "
+ "worker scripts");
+ return;
+ }
+
+ // Create a SharedWorkerScriptLoader to load the script.
+ mojo::MakeStrongBinding(
+ std::make_unique<SharedWorkerScriptLoader>(
+ routing_id, request_id, options, resource_request, std::move(client),
+ service_worker_provider_host_, resource_context_,
+ loader_factory_getter_, traffic_annotation),
+ std::move(request));
+}
+
+void SharedWorkerScriptLoaderFactory::Clone(
+ network::mojom::URLLoaderFactoryRequest request) {
+ // This method is required to support synchronous requests, which shared
+ // worker script requests are not.
+ NOTIMPLEMENTED();
+}
+
+} // namespace content
diff --git a/chromium/content/browser/shared_worker/shared_worker_script_loader_factory.h b/chromium/content/browser/shared_worker/shared_worker_script_loader_factory.h
new file mode 100644
index 00000000000..7e0e4c5ceae
--- /dev/null
+++ b/chromium/content/browser/shared_worker/shared_worker_script_loader_factory.h
@@ -0,0 +1,59 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_BROWSER_SHARED_WORKER_SHARED_WORKER_SCRIPT_LOADER_FACTORY_H_
+#define CONTENT_BROWSER_SHARED_WORKER_SHARED_WORKER_SCRIPT_LOADER_FACTORY_H_
+
+#include "base/macros.h"
+#include "services/network/public/mojom/url_loader_factory.mojom.h"
+
+namespace content {
+
+class ServiceWorkerContextWrapper;
+class ServiceWorkerProviderHost;
+class URLLoaderFactoryGetter;
+class ResourceContext;
+
+// S13nServiceWorker:
+// Created per one running shared worker for loading its script.
+//
+// Shared worker script loads require special logic because they are similiar to
+// navigations from the point of view of web platform features like service
+// worker.
+//
+// This creates a SharedWorkerScriptLoader to load the script, which follows
+// redirects and sets the controller service worker on the shared worker if
+// needed.
+class SharedWorkerScriptLoaderFactory
+ : public network::mojom::URLLoaderFactory {
+ public:
+ SharedWorkerScriptLoaderFactory(
+ ServiceWorkerContextWrapper* context,
+ base::WeakPtr<ServiceWorkerProviderHost> provider_host,
+ ResourceContext* resource_context,
+ scoped_refptr<URLLoaderFactoryGetter> loader_factory_getter);
+ ~SharedWorkerScriptLoaderFactory() override;
+
+ // network::mojom::URLLoaderFactory:
+ void CreateLoaderAndStart(network::mojom::URLLoaderRequest request,
+ int32_t routing_id,
+ int32_t request_id,
+ uint32_t options,
+ const network::ResourceRequest& resource_request,
+ network::mojom::URLLoaderClientPtr client,
+ const net::MutableNetworkTrafficAnnotationTag&
+ traffic_annotation) override;
+ void Clone(network::mojom::URLLoaderFactoryRequest request) override;
+
+ private:
+ base::WeakPtr<ServiceWorkerProviderHost> service_worker_provider_host_;
+ ResourceContext* resource_context_ = nullptr;
+ scoped_refptr<URLLoaderFactoryGetter> loader_factory_getter_;
+
+ DISALLOW_COPY_AND_ASSIGN(SharedWorkerScriptLoaderFactory);
+};
+
+} // namespace content
+
+#endif // CONTENT_BROWSER_SHARED_WORKER_SHARED_WORKER_SCRIPT_LOADER_FACTORY_H_
diff --git a/chromium/content/browser/shared_worker/shared_worker_service_impl.cc b/chromium/content/browser/shared_worker/shared_worker_service_impl.cc
index a0a98e30439..5589e34dec3 100644
--- a/chromium/content/browser/shared_worker/shared_worker_service_impl.cc
+++ b/chromium/content/browser/shared_worker/shared_worker_service_impl.cc
@@ -12,11 +12,13 @@
#include "base/callback.h"
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "content/browser/devtools/shared_worker_devtools_manager.h"
#include "content/browser/shared_worker/shared_worker_host.h"
#include "content/browser/shared_worker/shared_worker_instance.h"
+#include "content/browser/shared_worker/shared_worker_script_loader_factory.h"
+#include "content/browser/storage_partition_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
+#include "content/common/service_worker/service_worker_provider.mojom.h"
+#include "content/common/service_worker/service_worker_utils.h"
#include "content/common/shared_worker/shared_worker_client.mojom.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
@@ -24,7 +26,8 @@
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/common/bind_interface_helpers.h"
-#include "third_party/WebKit/public/common/message_port/message_port_channel.h"
+#include "mojo/public/cpp/bindings/strong_associated_binding.h"
+#include "third_party/blink/public/common/message_port/message_port_channel.h"
#include "url/origin.h"
namespace content {
@@ -35,9 +38,38 @@ bool IsShuttingDown(RenderProcessHost* host) {
host->IsKeepAliveRefCountDisabled();
}
+void CreateScriptLoaderOnIO(
+ scoped_refptr<URLLoaderFactoryGetter> loader_factory_getter,
+ scoped_refptr<ServiceWorkerContextWrapper> context,
+ int process_id,
+ base::OnceCallback<void(mojom::ServiceWorkerProviderInfoForSharedWorkerPtr,
+ network::mojom::URLLoaderFactoryAssociatedPtrInfo)>
+ callback) {
+ // Set up for service worker.
+ auto provider_info = mojom::ServiceWorkerProviderInfoForSharedWorker::New();
+ base::WeakPtr<ServiceWorkerProviderHost> host =
+ context->PreCreateHostForSharedWorker(process_id, &provider_info);
+
+ // Create the SharedWorkerScriptLoaderFactory.
+ network::mojom::URLLoaderFactoryAssociatedPtrInfo script_loader_factory;
+ mojo::MakeStrongAssociatedBinding(
+ std::make_unique<SharedWorkerScriptLoaderFactory>(
+ context.get(), host->AsWeakPtr(), context->resource_context(),
+ std::move(loader_factory_getter)),
+ mojo::MakeRequest(&script_loader_factory));
+
+ BrowserThread::PostTask(
+ BrowserThread::UI, FROM_HERE,
+ base::BindOnce(std::move(callback), std::move(provider_info),
+ std::move(script_loader_factory)));
+}
+
} // namespace
-SharedWorkerServiceImpl::SharedWorkerServiceImpl() {}
+SharedWorkerServiceImpl::SharedWorkerServiceImpl(
+ scoped_refptr<ServiceWorkerContextWrapper> service_worker_context)
+ : service_worker_context_(std::move(service_worker_context)),
+ weak_factory_(this) {}
SharedWorkerServiceImpl::~SharedWorkerServiceImpl() {}
@@ -128,8 +160,26 @@ void SharedWorkerServiceImpl::ConnectToWorker(
DestroyHost(host);
}
+ // Bounce to the IO thread to setup service worker support in case the request
+ // for the worker script will need to be intercepted by service workers.
+ // TODO(falken): Move service worker to the UI thread.
+ if (ServiceWorkerUtils::IsServicificationEnabled()) {
+ BrowserThread::PostTask(
+ BrowserThread::IO, FROM_HERE,
+ base::BindOnce(&CreateScriptLoaderOnIO,
+ service_worker_context_->storage_partition()
+ ->url_loader_factory_getter(),
+ service_worker_context_, process_id,
+ base::BindOnce(&SharedWorkerServiceImpl::CreateWorker,
+ weak_factory_.GetWeakPtr(),
+ std::move(instance), std::move(client),
+ process_id, frame_id, message_port)));
+ return;
+ }
+
CreateWorker(std::move(instance), std::move(client), process_id, frame_id,
- message_port);
+ message_port, nullptr /* service_worker_provider_info */,
+ {} /* script_loader_factory */);
}
void SharedWorkerServiceImpl::DestroyHost(SharedWorkerHost* host) {
@@ -142,7 +192,8 @@ void SharedWorkerServiceImpl::DestroyHost(SharedWorkerHost* host) {
std::move(terminate_all_workers_callback_).Run();
if (!IsShuttingDown(process_host))
- process_host->DecrementKeepAliveRefCount();
+ process_host->DecrementKeepAliveRefCount(
+ RenderProcessHost::KeepAliveClientType::kSharedWorker);
}
void SharedWorkerServiceImpl::CreateWorker(
@@ -150,9 +201,12 @@ void SharedWorkerServiceImpl::CreateWorker(
mojom::SharedWorkerClientPtr client,
int process_id,
int frame_id,
- const blink::MessagePortChannel& message_port) {
- // Re-use the process that requested the shared worker.
- int worker_process_id = process_id;
+ const blink::MessagePortChannel& message_port,
+ mojom::ServiceWorkerProviderInfoForSharedWorkerPtr
+ service_worker_provider_info,
+ network::mojom::URLLoaderFactoryAssociatedPtrInfo
+ script_loader_factory_info) {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
RenderProcessHost* process_host = RenderProcessHost::FromID(process_id);
// If the requesting process is shutting down, then just drop this request on
@@ -161,27 +215,20 @@ void SharedWorkerServiceImpl::CreateWorker(
return;
// Keep the renderer process alive that will be hosting the shared worker.
- process_host->IncrementKeepAliveRefCount();
-
- auto host = std::make_unique<SharedWorkerHost>(this, std::move(instance),
- worker_process_id);
-
- bool pause_on_start;
- base::UnguessableToken devtools_worker_token;
- SharedWorkerDevToolsManager::GetInstance()->WorkerCreated(
- host.get(), &pause_on_start, &devtools_worker_token);
+ process_host->IncrementKeepAliveRefCount(
+ RenderProcessHost::KeepAliveClientType::kSharedWorker);
+ auto host =
+ std::make_unique<SharedWorkerHost>(this, std::move(instance), process_id);
// Get the factory used to instantiate the new shared worker instance in
// the target process.
mojom::SharedWorkerFactoryPtr factory;
BindInterface(process_host, &factory);
- host->Start(std::move(factory), pause_on_start, devtools_worker_token);
+ host->Start(std::move(factory), std::move(service_worker_provider_info),
+ std::move(script_loader_factory_info));
host->AddClient(std::move(client), process_id, frame_id, message_port);
- const GURL url = host->instance()->url();
- const std::string name = host->instance()->name();
-
worker_hosts_.insert(std::move(host));
}
diff --git a/chromium/content/browser/shared_worker/shared_worker_service_impl.h b/chromium/content/browser/shared_worker/shared_worker_service_impl.h
index 86cd0e8e163..c4075f85b8b 100644
--- a/chromium/content/browser/shared_worker/shared_worker_service_impl.h
+++ b/chromium/content/browser/shared_worker/shared_worker_service_impl.h
@@ -14,23 +14,26 @@
#include "base/containers/unique_ptr_adapters.h"
#include "base/macros.h"
#include "base/memory/singleton.h"
+#include "content/browser/service_worker/service_worker_context_wrapper.h"
#include "content/browser/shared_worker/shared_worker_host.h"
+#include "content/common/service_worker/service_worker_provider.mojom.h"
#include "content/common/shared_worker/shared_worker_connector.mojom.h"
#include "content/common/shared_worker/shared_worker_factory.mojom.h"
#include "content/public/browser/shared_worker_service.h"
+#include "services/network/public/mojom/url_loader_factory.mojom.h"
namespace blink {
class MessagePortChannel;
}
namespace content {
-
class SharedWorkerInstance;
class SharedWorkerHost;
class CONTENT_EXPORT SharedWorkerServiceImpl : public SharedWorkerService {
public:
- SharedWorkerServiceImpl();
+ explicit SharedWorkerServiceImpl(
+ scoped_refptr<ServiceWorkerContextWrapper> service_worker_context);
~SharedWorkerServiceImpl() override;
// SharedWorkerService implementation.
@@ -58,7 +61,11 @@ class CONTENT_EXPORT SharedWorkerServiceImpl : public SharedWorkerService {
mojom::SharedWorkerClientPtr client,
int process_id,
int frame_id,
- const blink::MessagePortChannel& message_port);
+ const blink::MessagePortChannel& message_port,
+ mojom::ServiceWorkerProviderInfoForSharedWorkerPtr
+ service_worker_provider_info,
+ network::mojom::URLLoaderFactoryAssociatedPtrInfo
+ script_loader_factory_info);
// Returns nullptr if there is no such host.
SharedWorkerHost* FindSharedWorkerHost(int process_id, int route_id);
@@ -69,6 +76,10 @@ class CONTENT_EXPORT SharedWorkerServiceImpl : public SharedWorkerService {
worker_hosts_;
base::OnceClosure terminate_all_workers_callback_;
+ scoped_refptr<ServiceWorkerContextWrapper> service_worker_context_;
+
+ base::WeakPtrFactory<SharedWorkerServiceImpl> weak_factory_;
+
DISALLOW_COPY_AND_ASSIGN(SharedWorkerServiceImpl);
};
diff --git a/chromium/content/browser/shared_worker/shared_worker_service_impl_unittest.cc b/chromium/content/browser/shared_worker/shared_worker_service_impl_unittest.cc
index ff4f922554a..d3ac80d6a79 100644
--- a/chromium/content/browser/shared_worker/shared_worker_service_impl_unittest.cc
+++ b/chromium/content/browser/shared_worker/shared_worker_service_impl_unittest.cc
@@ -14,7 +14,6 @@
#include "base/atomic_sequence_num.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/strings/string16.h"
#include "base/strings/utf_string_conversions.h"
@@ -31,7 +30,7 @@
#include "mojo/public/cpp/bindings/binding.h"
#include "mojo/public/cpp/test_support/test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/common/message_port/message_port_channel.h"
+#include "third_party/blink/public/common/message_port/message_port_channel.h"
using blink::MessagePortChannel;
@@ -193,6 +192,10 @@ class MockSharedWorkerFactory : public mojom::SharedWorkerFactory {
bool pause_on_start,
const base::UnguessableToken& devtools_worker_token,
blink::mojom::WorkerContentSettingsProxyPtr content_settings,
+ mojom::ServiceWorkerProviderInfoForSharedWorkerPtr
+ service_worker_provider_info,
+ network::mojom::URLLoaderFactoryAssociatedPtrInfo
+ script_loader_factory_ptr_info,
mojom::SharedWorkerHostPtr host,
mojom::SharedWorkerRequest request,
service_manager::mojom::InterfaceProviderPtr interface_provider)
diff --git a/chromium/content/browser/shared_worker/worker_browsertest.cc b/chromium/content/browser/shared_worker/worker_browsertest.cc
index 7689f026057..6c9a3d21a54 100644
--- a/chromium/content/browser/shared_worker/worker_browsertest.cc
+++ b/chromium/content/browser/shared_worker/worker_browsertest.cc
@@ -81,7 +81,7 @@ class WorkerTest : public ContentBrowserTest {
void RunTest(const GURL& url) { RunTest(shell(), url); }
static void QuitUIMessageLoop(base::Callback<void()> callback) {
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, callback);
+ BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, std::move(callback));
}
void NavigateAndWaitForAuth(const GURL& url) {
diff --git a/chromium/content/browser/site_instance_impl.cc b/chromium/content/browser/site_instance_impl.cc
index 6dcae695d00..d1ec2e7afab 100644
--- a/chromium/content/browser/site_instance_impl.cc
+++ b/chromium/content/browser/site_instance_impl.cc
@@ -9,16 +9,15 @@
#include "base/command_line.h"
#include "base/debug/crash_logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "content/browser/browsing_instance.h"
#include "content/browser/child_process_security_policy_impl.h"
#include "content/browser/frame_host/debug_urls.h"
#include "content/browser/frame_host/frame_tree_node.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
-#include "content/browser/site_isolation_policy.h"
#include "content/browser/storage_partition_impl.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/render_process_host_factory.h"
+#include "content/public/browser/site_isolation_policy.h"
#include "content/public/browser/web_ui_controller_factory.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/url_constants.h"
@@ -29,6 +28,9 @@ namespace content {
int32_t SiteInstanceImpl::next_site_instance_id_ = 1;
+using CheckOriginLockResult =
+ ChildProcessSecurityPolicyImpl::CheckOriginLockResult;
+
SiteInstanceImpl::SiteInstanceImpl(BrowsingInstance* browsing_instance)
: id_(next_site_instance_id_++),
active_frame_count_(0),
@@ -412,10 +414,8 @@ GURL SiteInstance::GetSiteForURL(BrowserContext* browser_context,
// origin lookup.
auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
url::Origin isolated_origin;
- if (policy->GetMatchingIsolatedOrigin(url::Origin::Create(url),
- &isolated_origin)) {
+ if (policy->GetMatchingIsolatedOrigin(origin, &isolated_origin))
return isolated_origin.GetURL();
- }
// If the url has a host, then determine the site. Skip file URLs to avoid a
// situation where site URL of file://localhost/ would mismatch Blink's origin
@@ -433,11 +433,18 @@ GURL SiteInstance::GetSiteForURL(BrowserContext* browser_context,
// If there is no host but there is a scheme, return the scheme.
// This is useful for cases like file URLs.
- if (url.has_scheme())
+ if (!origin.unique()) {
+ // Prefer to use the scheme of |origin| rather than |url|, to correctly
+ // cover blob: and filesystem: URIs (see also https://crbug.com/697111).
+ DCHECK(!origin.scheme().empty());
+ return GURL(origin.scheme() + ":");
+ } else if (url.has_scheme()) {
+ DCHECK(!url.scheme().empty());
return GURL(url.scheme() + ":");
+ }
// Otherwise the URL should be invalid; return an empty site.
- DCHECK(!url.is_valid());
+ DCHECK(!url.is_valid()) << url;
return GURL();
}
@@ -560,7 +567,7 @@ void SiteInstanceImpl::LockToOriginIfNeeded() {
CHECK(!process_->IsForGuestsOnly());
switch (lock_state) {
- case ChildProcessSecurityPolicyImpl::CheckOriginLockResult::NO_LOCK: {
+ case CheckOriginLockResult::NO_LOCK: {
// TODO(nick): When all sites are isolated, this operation provides
// strong protection. If only some sites are isolated, we need
// additional logic to prevent the non-isolated sites from requesting
@@ -568,8 +575,7 @@ void SiteInstanceImpl::LockToOriginIfNeeded() {
policy->LockToOrigin(process_->GetID(), site_);
break;
}
- case ChildProcessSecurityPolicyImpl::CheckOriginLockResult::
- HAS_WRONG_LOCK:
+ case CheckOriginLockResult::HAS_WRONG_LOCK:
// We should never attempt to reassign a different origin lock to a
// process.
base::debug::SetCrashKeyString(bad_message::GetRequestedSiteURLKey(),
@@ -581,8 +587,7 @@ void SiteInstanceImpl::LockToOriginIfNeeded() {
<< " but the process is already locked to "
<< policy->GetOriginLock(process_->GetID());
break;
- case ChildProcessSecurityPolicyImpl::CheckOriginLockResult::
- HAS_EQUAL_LOCK:
+ case CheckOriginLockResult::HAS_EQUAL_LOCK:
// Process already has the right origin lock assigned. This case will
// happen for commits to |site_| after the first one.
break;
@@ -593,15 +598,16 @@ void SiteInstanceImpl::LockToOriginIfNeeded() {
// If the site that we've just committed doesn't require a dedicated
// process, make sure we aren't putting it in a process for a site that
// does.
- base::debug::SetCrashKeyString(bad_message::GetRequestedSiteURLKey(),
- site_.spec());
- base::debug::SetCrashKeyString(
- bad_message::GetKilledProcessOriginLockKey(),
- policy->GetOriginLock(process_->GetID()).spec());
- CHECK_EQ(lock_state,
- ChildProcessSecurityPolicyImpl::CheckOriginLockResult::NO_LOCK)
- << "Trying to commit non-isolated site " << site_
- << " in process locked to " << policy->GetOriginLock(process_->GetID());
+ if (lock_state != CheckOriginLockResult::NO_LOCK) {
+ base::debug::SetCrashKeyString(bad_message::GetRequestedSiteURLKey(),
+ site_.spec());
+ base::debug::SetCrashKeyString(
+ bad_message::GetKilledProcessOriginLockKey(),
+ policy->GetOriginLock(process_->GetID()).spec());
+ CHECK(false) << "Trying to commit non-isolated site " << site_
+ << " in process locked to "
+ << policy->GetOriginLock(process_->GetID());
+ }
}
}
diff --git a/chromium/content/browser/site_instance_impl_unittest.cc b/chromium/content/browser/site_instance_impl_unittest.cc
index ef953854632..95595ca8c75 100644
--- a/chromium/content/browser/site_instance_impl_unittest.cc
+++ b/chromium/content/browser/site_instance_impl_unittest.cc
@@ -16,7 +16,6 @@
#include "base/run_loop.h"
#include "base/strings/string16.h"
#include "base/test/scoped_feature_list.h"
-#include "content/browser/browser_thread_impl.h"
#include "content/browser/browsing_instance.h"
#include "content/browser/child_process_security_policy_impl.h"
#include "content/browser/frame_host/navigation_entry_impl.h"
@@ -105,8 +104,8 @@ class SiteInstanceTest : public testing::Test {
void SetUp() override {
old_browser_client_ = SetBrowserClientForTesting(&browser_client_);
- url::AddStandardScheme(kPrivilegedScheme, url::SCHEME_WITHOUT_PORT);
- url::AddStandardScheme(kChromeUIScheme, url::SCHEME_WITHOUT_PORT);
+ url::AddStandardScheme(kPrivilegedScheme, url::SCHEME_WITH_HOST);
+ url::AddStandardScheme(kChromeUIScheme, url::SCHEME_WITH_HOST);
RenderProcessHostImpl::set_render_process_host_factory(&rph_factory_);
}
@@ -128,6 +127,8 @@ class SiteInstanceTest : public testing::Test {
// scheduled for deletion. Here, call DrainMessageLoop() again so the
// AppCacheDatabase actually gets deleted.
DrainMessageLoop();
+
+ ResetSchemesAndOriginsWhitelist();
}
void set_privileged_process_id(int process_id) {
@@ -361,6 +362,13 @@ TEST_F(SiteInstanceTest, GetSiteForURL) {
site_url = SiteInstanceImpl::GetSiteForURL(nullptr, test_url);
EXPECT_EQ(GURL("gopher://chromium.org"), site_url);
+ // Blob URLs with file origin also extract the site from the origin.
+ test_url = GURL("blob:file:///1029e5a4-2983-4b90-a585-ed217563acfeb");
+ site_url = SiteInstanceImpl::GetSiteForURL(nullptr, test_url);
+ EXPECT_EQ(GURL("file:"), site_url);
+ EXPECT_EQ("file", site_url.scheme());
+ EXPECT_FALSE(site_url.has_host());
+
// Private domains are preserved, appspot being such a site.
test_url = GURL(
"blob:http://www.example.appspot.com:44/"
@@ -617,20 +625,22 @@ TEST_F(SiteInstanceTest, ProcessSharingByType) {
if (AreAllSitesIsolatedForTesting())
return;
- // On Android by default the number of renderer hosts is unlimited and process
- // sharing doesn't happen. We set the override so that the test can run
- // everywhere.
- RenderProcessHost::SetMaxRendererProcessCount(kMaxRendererProcessCount);
-
ChildProcessSecurityPolicyImpl* policy =
ChildProcessSecurityPolicyImpl::GetInstance();
// Make a bunch of mock renderers so that we hit the limit.
std::unique_ptr<TestBrowserContext> browser_context(new TestBrowserContext());
std::vector<std::unique_ptr<MockRenderProcessHost>> hosts;
- for (size_t i = 0; i < kMaxRendererProcessCount; ++i)
+ for (size_t i = 0; i < kMaxRendererProcessCount; ++i) {
hosts.push_back(
std::make_unique<MockRenderProcessHost>(browser_context.get()));
+ hosts[i]->SetIsUsed();
+ }
+
+ // On Android by default the number of renderer hosts is unlimited and process
+ // sharing doesn't happen. We set the override so that the test can run
+ // everywhere.
+ RenderProcessHost::SetMaxRendererProcessCount(kMaxRendererProcessCount);
// Create some extension instances and make sure they share a process.
scoped_refptr<SiteInstanceImpl> extension1_instance(
diff --git a/chromium/content/browser/site_per_process_browsertest.cc b/chromium/content/browser/site_per_process_browsertest.cc
index 36fab771cf3..9d72cdc7599 100644
--- a/chromium/content/browser/site_per_process_browsertest.cc
+++ b/chromium/content/browser/site_per_process_browsertest.cc
@@ -22,6 +22,7 @@
#include "base/json/json_reader.h"
#include "base/location.h"
#include "base/memory/ptr_util.h"
+#include "base/message_loop/message_loop.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/sequenced_task_runner.h"
@@ -73,6 +74,7 @@
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/url_constants.h"
+#include "content/public/common/use_zoom_for_dsf_policy.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/public/test/navigation_handle_observer.h"
@@ -96,10 +98,10 @@
#include "services/network/public/cpp/features.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/common/feature_policy/feature_policy.h"
-#include "third_party/WebKit/public/common/frame/sandbox_flags.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
-#include "third_party/WebKit/public/platform/WebInsecureRequestPolicy.h"
+#include "third_party/blink/public/common/feature_policy/feature_policy.h"
+#include "third_party/blink/public/common/frame/sandbox_flags.h"
+#include "third_party/blink/public/platform/web_input_event.h"
+#include "third_party/blink/public/platform/web_insecure_request_policy.h"
#include "ui/display/display_switches.h"
#include "ui/display/screen.h"
#include "ui/events/base_event_utils.h"
@@ -233,33 +235,6 @@ double GetPageScaleFactor(Shell* shell) {
.page_scale_factor;
}
-// Helper function to retrieve the bounding client rect of the element
-// identified by |sel| inside |rfh|.
-gfx::Rect GetBoundingClientRect(RenderFrameHostImpl* rfh,
- const std::string& sel) {
- std::string result;
- EXPECT_TRUE(ExecuteScriptAndExtractString(
- rfh,
- base::StringPrintf(
- "{"
- " let rect = document.querySelector('%s').getBoundingClientRect();"
- " let msg = `${rect.x},${rect.y},${rect.width},${rect.height}`;"
- " window.domAutomationController.send(msg);"
- "}",
- sel.c_str()),
- &result));
- std::vector<std::string> tokens = base::SplitString(
- result, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
- EXPECT_EQ(4U, tokens.size());
- double x = 0.0, y = 0.0, width = 0.0, height = 0.0;
- EXPECT_TRUE(base::StringToDouble(tokens[0], &x));
- EXPECT_TRUE(base::StringToDouble(tokens[1], &y));
- EXPECT_TRUE(base::StringToDouble(tokens[2], &width));
- EXPECT_TRUE(base::StringToDouble(tokens[3], &height));
- return {static_cast<int>(x), static_cast<int>(y), static_cast<int>(width),
- static_cast<int>(height)};
-}
-
class RedirectNotificationObserver : public NotificationObserver {
public:
// Register to listen for notifications of the given type from either a
@@ -415,29 +390,6 @@ class UserInteractionObserver : public WebContentsObserver {
DISALLOW_COPY_AND_ASSIGN(UserInteractionObserver);
};
-// This observer is used to wait for its owner FrameTreeNode to become deleted.
-class FrameDeletedObserver : public FrameTreeNode::Observer {
- public:
- explicit FrameDeletedObserver(FrameTreeNode* owner)
- : owner_(owner), message_loop_runner_(new MessageLoopRunner) {
- owner->AddObserver(this);
- }
-
- void Wait() { message_loop_runner_->Run(); }
-
- private:
- // FrameTreeNode::Observer
- void OnFrameTreeNodeDestroyed(FrameTreeNode* node) override {
- if (node == owner_)
- message_loop_runner_->Quit();
- }
-
- FrameTreeNode* owner_;
- scoped_refptr<MessageLoopRunner> message_loop_runner_;
-
- DISALLOW_COPY_AND_ASSIGN(FrameDeletedObserver);
-};
-
// Helper function to focus a frame by sending it a mouse click and then
// waiting for it to become focused.
void FocusFrame(FrameTreeNode* frame) {
@@ -569,6 +521,17 @@ blink::ParsedFeaturePolicy CreateFPHeaderMatchesAll(
return result;
}
+// Check frame depth on node, widget, and process all match expected depth.
+void CheckFrameDepth(unsigned int expected_depth, FrameTreeNode* node) {
+ EXPECT_EQ(expected_depth, node->depth());
+ RenderProcessHost::Priority priority =
+ node->current_frame_host()->GetRenderWidgetHost()->GetPriority();
+ EXPECT_EQ(expected_depth, priority.frame_depth);
+ EXPECT_EQ(
+ expected_depth,
+ node->current_frame_host()->GetProcess()->GetFrameDepthForTesting());
+}
+
} // namespace
//
@@ -709,6 +672,109 @@ class SitePerProcessEmbedderCSPEnforcementBrowserTest
}
};
+// SitePerProcessProgrammaticScrollTest.
+
+class SitePerProcessProgrammaticScrollTest : public SitePerProcessBrowserTest {
+ public:
+ SitePerProcessProgrammaticScrollTest()
+ : kInfinity(1000000U), kPositiveXYPlane(0, 0, kInfinity, kInfinity) {}
+
+ protected:
+ const size_t kInfinity;
+ const std::string kIframeOutOfViewHTML = "/iframe_out_of_view.html";
+ const std::string kIframeClippedHTML = "/iframe_clipped.html";
+ const std::string kInputBoxHTML = "/input_box.html";
+ const std::string kIframeSelector = "iframe";
+ const std::string kInputSelector = "input";
+ const gfx::Rect kPositiveXYPlane;
+
+ // Waits until the |load| handle is called inside the frame.
+ void WaitForOnLoad(FrameTreeNode* node) {
+ RunCommandAndWaitForResponse(node, "notifyWhenLoaded();", "LOADED");
+ }
+
+ void WaitForElementVisible(FrameTreeNode* node, const std::string& sel) {
+ RunCommandAndWaitForResponse(
+ node,
+ base::StringPrintf("notifyWhenVisible(document.querySelector('%s'));",
+ sel.c_str()),
+ "VISIBLE");
+ }
+
+ void WaitForViewportToStabilize(FrameTreeNode* node) {
+ RunCommandAndWaitForResponse(node, "notifyWhenViewportStable(0);",
+ "VIEWPORT_STABLE");
+ }
+
+ void AddFocusedInputField(FrameTreeNode* node) {
+ ASSERT_TRUE(ExecuteScript(node, "addFocusedInputField();"));
+ }
+
+ void SetWindowScroll(FrameTreeNode* node, int x, int y) {
+ ASSERT_TRUE(ExecuteScript(
+ node, base::StringPrintf("window.scrollTo(%d, %d);", x, y)));
+ }
+
+ // Helper function to retrieve the bounding client rect of the element
+ // identified by |sel| inside |rfh|.
+ gfx::Rect GetBoundingClientRect(FrameTreeNode* node, const std::string& sel) {
+ std::string result;
+ EXPECT_TRUE(ExecuteScriptAndExtractString(
+ node,
+ base::StringPrintf(
+ "window.domAutomationController.send(rectAsString("
+ " document.querySelector('%s').getBoundingClientRect()));",
+ sel.c_str()),
+ &result));
+ return GetRectFromString(result);
+ }
+
+ // Returns a rect representing the current |visualViewport| in the main frame
+ // of |contents|.
+ gfx::Rect GetVisualViewport(FrameTreeNode* node) {
+ std::string result;
+ EXPECT_TRUE(ExecuteScriptAndExtractString(
+ node,
+ "window.domAutomationController.send("
+ " rectAsString(visualViewportAsRect()));",
+ &result));
+ return GetRectFromString(result);
+ }
+
+ float GetVisualViewportScale(FrameTreeNode* node) {
+ double scale;
+ EXPECT_TRUE(ExecuteScriptAndExtractDouble(
+ node, "window.domAutomationController.send(visualViewport.scale);",
+ &scale));
+ return static_cast<float>(scale);
+ }
+
+ private:
+ void RunCommandAndWaitForResponse(FrameTreeNode* node,
+ const std::string& command,
+ const std::string& response) {
+ std::string msg_from_renderer;
+ ASSERT_TRUE(
+ ExecuteScriptAndExtractString(node, command, &msg_from_renderer));
+ ASSERT_EQ(response, msg_from_renderer);
+ }
+
+ gfx::Rect GetRectFromString(const std::string& str) {
+ std::vector<std::string> tokens = base::SplitString(
+ str, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
+ EXPECT_EQ(4U, tokens.size());
+ double x = 0.0, y = 0.0, width = 0.0, height = 0.0;
+ EXPECT_TRUE(base::StringToDouble(tokens[0], &x));
+ EXPECT_TRUE(base::StringToDouble(tokens[1], &y));
+ EXPECT_TRUE(base::StringToDouble(tokens[2], &width));
+ EXPECT_TRUE(base::StringToDouble(tokens[3], &height));
+ return {static_cast<int>(x), static_cast<int>(y), static_cast<int>(width),
+ static_cast<int>(height)};
+ }
+
+ DISALLOW_COPY_AND_ASSIGN(SitePerProcessProgrammaticScrollTest);
+};
+
IN_PROC_BROWSER_TEST_F(SitePerProcessHighDPIBrowserTest,
SubframeLoadsWithCorrectDeviceScaleFactor) {
GURL main_url(embedded_test_server()->GetURL(
@@ -1109,8 +1175,8 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
blink::WebGestureEvent gesture_scroll_begin(
blink::WebGestureEvent::kGestureScrollBegin,
blink::WebInputEvent::kNoModifiers,
- blink::WebInputEvent::GetStaticTimeStampForTests());
- gesture_scroll_begin.source_device = blink::kWebGestureDeviceTouchscreen;
+ blink::WebInputEvent::GetStaticTimeStampForTests(),
+ blink::kWebGestureDeviceTouchscreen);
gesture_scroll_begin.data.scroll_begin.delta_hint_units =
blink::WebGestureEvent::ScrollUnits::kPrecisePixels;
gesture_scroll_begin.data.scroll_begin.delta_x_hint = 0.f;
@@ -1121,8 +1187,8 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
blink::WebGestureEvent gesture_scroll_update(
blink::WebGestureEvent::kGestureScrollUpdate,
blink::WebInputEvent::kNoModifiers,
- blink::WebInputEvent::GetStaticTimeStampForTests());
- gesture_scroll_update.source_device = blink::kWebGestureDeviceTouchscreen;
+ blink::WebInputEvent::GetStaticTimeStampForTests(),
+ blink::kWebGestureDeviceTouchscreen);
gesture_scroll_update.data.scroll_update.delta_units =
blink::WebGestureEvent::ScrollUnits::kPrecisePixels;
gesture_scroll_update.data.scroll_update.delta_x = 0.f;
@@ -1134,8 +1200,8 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
blink::WebGestureEvent gesture_fling_start(
blink::WebGestureEvent::kGestureFlingStart,
blink::WebInputEvent::kNoModifiers,
- blink::WebInputEvent::GetStaticTimeStampForTests());
- gesture_fling_start.source_device = blink::kWebGestureDeviceTouchscreen;
+ blink::WebInputEvent::GetStaticTimeStampForTests(),
+ blink::kWebGestureDeviceTouchscreen);
gesture_fling_start.data.fling_start.velocity_x = 0.f;
gesture_fling_start.data.fling_start.velocity_y = 5.f;
@@ -1322,34 +1388,31 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, ScrollBubblingFromOOPIFTest) {
blink::WebGestureEvent gesture_event(
blink::WebGestureEvent::kGestureScrollBegin,
blink::WebInputEvent::kNoModifiers,
- blink::WebInputEvent::GetStaticTimeStampForTests());
- gesture_event.source_device = blink::kWebGestureDeviceTouchpad;
- gesture_event.x = 1;
- gesture_event.y = 1;
+ blink::WebInputEvent::GetStaticTimeStampForTests(),
+ blink::kWebGestureDeviceTouchpad);
+ gesture_event.SetPositionInWidget(gfx::PointF(1, 1));
gesture_event.data.scroll_begin.delta_x_hint = 0.0f;
gesture_event.data.scroll_begin.delta_y_hint = 6.0f;
rwhv_nested->GetRenderWidgetHost()->ForwardGestureEvent(gesture_event);
- gesture_event = blink::WebGestureEvent(
- blink::WebGestureEvent::kGestureScrollUpdate,
- blink::WebInputEvent::kNoModifiers,
- blink::WebInputEvent::GetStaticTimeStampForTests());
- gesture_event.source_device = blink::kWebGestureDeviceTouchpad;
- gesture_event.x = 1;
- gesture_event.y = 1;
+ gesture_event =
+ blink::WebGestureEvent(blink::WebGestureEvent::kGestureScrollUpdate,
+ blink::WebInputEvent::kNoModifiers,
+ blink::WebInputEvent::GetStaticTimeStampForTests(),
+ blink::kWebGestureDeviceTouchpad);
+ gesture_event.SetPositionInWidget(gfx::PointF(1, 1));
gesture_event.data.scroll_update.delta_x = 0.0f;
gesture_event.data.scroll_update.delta_y = 6.0f;
gesture_event.data.scroll_update.velocity_x = 0;
gesture_event.data.scroll_update.velocity_y = 0;
rwhv_nested->GetRenderWidgetHost()->ForwardGestureEvent(gesture_event);
- gesture_event = blink::WebGestureEvent(
- blink::WebGestureEvent::kGestureScrollEnd,
- blink::WebInputEvent::kNoModifiers,
- blink::WebInputEvent::GetStaticTimeStampForTests());
- gesture_event.source_device = blink::kWebGestureDeviceTouchpad;
- gesture_event.x = 1;
- gesture_event.y = 1;
+ gesture_event =
+ blink::WebGestureEvent(blink::WebGestureEvent::kGestureScrollEnd,
+ blink::WebInputEvent::kNoModifiers,
+ blink::WebInputEvent::GetStaticTimeStampForTests(),
+ blink::kWebGestureDeviceTouchpad);
+ gesture_event.SetPositionInWidget(gfx::PointF(1, 1));
rwhv_nested->GetRenderWidgetHost()->ForwardGestureEvent(gesture_event);
filter->WaitForRect();
@@ -1385,6 +1448,52 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, ScrollBubblingFromOOPIFTest) {
DCHECK_EQ(filter->last_rect().y(), 0);
}
+// Test that fling on an out-of-process iframe progresses properly.
+IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, GestureFlingStart) {
+ GURL main_url(embedded_test_server()->GetURL(
+ "a.com", "/cross_site_iframe_factory.html?a(b)"));
+ EXPECT_TRUE(NavigateToURL(shell(), main_url));
+
+ FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
+ ->GetFrameTree()
+ ->root();
+ ASSERT_EQ(1U, root->child_count());
+
+ FrameTreeNode* child_iframe_node = root->child_at(0);
+
+ RenderWidgetHost* child_rwh =
+ child_iframe_node->current_frame_host()->GetRenderWidgetHost();
+
+ WaitForChildFrameSurfaceReady(child_iframe_node->current_frame_host());
+
+ // Send a GSB to start scrolling sequence.
+ blink::WebGestureEvent gesture_scroll_begin(
+ blink::WebGestureEvent::kGestureScrollBegin,
+ blink::WebInputEvent::kNoModifiers,
+ blink::WebInputEvent::GetStaticTimeStampForTests());
+ gesture_scroll_begin.SetSourceDevice(blink::kWebGestureDeviceTouchscreen);
+ gesture_scroll_begin.data.scroll_begin.delta_hint_units =
+ blink::WebGestureEvent::ScrollUnits::kPrecisePixels;
+ gesture_scroll_begin.data.scroll_begin.delta_x_hint = 0.f;
+ gesture_scroll_begin.data.scroll_begin.delta_y_hint = 5.f;
+ child_rwh->ForwardGestureEvent(gesture_scroll_begin);
+
+ // Send a GFS and wait for the ack of the first GSU generated from progressing
+ // the fling on the browser.
+ InputEventAckWaiter gesture_scroll_update_ack_observer(
+ child_rwh, blink::WebInputEvent::kGestureScrollUpdate);
+ gesture_scroll_update_ack_observer.Reset();
+ blink::WebGestureEvent gesture_fling_start(
+ blink::WebGestureEvent::kGestureFlingStart,
+ blink::WebInputEvent::kNoModifiers,
+ blink::WebInputEvent::GetStaticTimeStampForTests());
+ gesture_fling_start.SetSourceDevice(blink::kWebGestureDeviceTouchscreen);
+ gesture_fling_start.data.fling_start.velocity_x = 0.f;
+ gesture_fling_start.data.fling_start.velocity_y = 50.f;
+ child_rwh->ForwardGestureEvent(gesture_fling_start);
+ gesture_scroll_update_ack_observer.Wait();
+}
+
class ScrollObserver : public RenderWidgetHost::InputEventObserver {
public:
ScrollObserver(double delta_x, double delta_y) { Reset(delta_x, delta_y); }
@@ -1577,20 +1686,9 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
scroll_observer.Wait();
}
-class SitePerProcessDisableThreadedScrollingBrowserTest
- : public SitePerProcessBrowserTest {
- protected:
- void SetUpCommandLine(base::CommandLine* command_line) override {
- SitePerProcessBrowserTest::SetUpCommandLine(command_line);
- command_line->AppendSwitch(switches::kDisableThreadedScrolling);
- }
-};
-
// Ensure that the scrollability of a local subframe in an OOPIF is considered
// when acknowledging GestureScrollBegin events sent to OOPIFs.
-// TODO(mcnee): Figure out why DisableThreadedScrolling is necessary here.
-IN_PROC_BROWSER_TEST_F(SitePerProcessDisableThreadedScrollingBrowserTest,
- ScrollLocalSubframeInOOPIF) {
+IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, ScrollLocalSubframeInOOPIF) {
ui::GestureConfiguration::GetInstance()->set_scroll_debounce_interval_in_ms(
0);
@@ -1641,7 +1739,12 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessDisableThreadedScrollingBrowserTest,
state == content::INPUT_EVENT_ACK_STATE_CONSUMED;
}));
- // Now scroll the inner frame downward,
+ // Wait until renderer's compositor thread is synced. Otherwise the non fast
+ // scrollable regions won't be set when the event arrives.
+ MainThreadFrameObserver observer(rwhv_child->GetRenderWidgetHost());
+ observer.Wait();
+
+ // Now scroll the inner frame downward.
blink::WebMouseWheelEvent scroll_event(
blink::WebInputEvent::kMouseWheel, blink::WebInputEvent::kNoModifiers,
blink::WebInputEvent::GetStaticTimeStampForTests());
@@ -1659,50 +1762,44 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessDisableThreadedScrollingBrowserTest,
// nested <iframe>'s after the inner-most frame scrolls into view. The
// measurements are for two identical pages where one page does not have any
// OOPIFs while the other has some nested OOPIFs.
-IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, ScrollElementIntoView) {
+#if defined(OS_LINUX)
+// crbug.com/827431
+#define MAYBE_ScrollElementIntoView DISABLED_ScrollElementIntoView
+#else
+#define MAYBE_ScrollElementIntoView ScrollElementIntoView
+#endif
+
+IN_PROC_BROWSER_TEST_F(SitePerProcessProgrammaticScrollTest,
+ MAYBE_ScrollElementIntoView) {
const GURL url_a(
- embedded_test_server()->GetURL("a.com", "/iframe_out_of_view.html"));
+ embedded_test_server()->GetURL("a.com", kIframeOutOfViewHTML));
const GURL url_b(
- embedded_test_server()->GetURL("b.com", "/iframe_out_of_view.html"));
+ embedded_test_server()->GetURL("b.com", kIframeOutOfViewHTML));
const GURL url_c(
- embedded_test_server()->GetURL("c.com", "/iframe_out_of_view.html"));
+ embedded_test_server()->GetURL("c.com", kIframeOutOfViewHTML));
- // Script which runs and returns with a |kRendererMsgLoaded| when load handler
- // is called. This is a good point to read bounding client rect values as
- // basic layout has already been completed.
- const std::string kWaitForFrameLoadScript = "notifyWhenLoaded();";
- const std::string kRendererMsgLoaded = "LOADED";
// Number of <iframe>'s which will not be empty. The actual frame tree has two
// more nodes one for root and one for the inner-most empty <iframe>.
const size_t kNonEmptyIframesCount = 5;
- // Sent in 'load' handlers.
- const std::string kIframeSelector = "iframe";
- const int kRectDimensionErrorTolerance = 0;
- const int kInfinity = 1000000;
- const gfx::Rect kPositiveXYPlane(0, 0, kInfinity, kInfinity);
const std::string kScrollIntoViewScript =
"document.body.scrollIntoView({'behavior' : 'instant'});";
- std::string msg_from_renderer;
+ const int kRectDimensionErrorTolerance = 0;
// First, recursively set the |scrollTop| and |scrollLeft| of |document.body|
// to its maximum and then navigate the <iframe> to |url_a|. The page will be
// structured as a(a(a(a(a(a(a)))))) where the inner-most <iframe> is empty.
ASSERT_TRUE(NavigateToURL(shell(), url_a));
FrameTreeNode* node = web_contents()->GetFrameTree()->root();
- ASSERT_TRUE(ExecuteScriptAndExtractString(node, kWaitForFrameLoadScript,
- &msg_from_renderer));
- ASSERT_EQ(kRendererMsgLoaded, msg_from_renderer);
+ WaitForOnLoad(node);
std::vector<gfx::Rect> reference_page_bounds_before_scroll = {
- GetBoundingClientRect(node->current_frame_host(), kIframeSelector)};
+ GetBoundingClientRect(node, kIframeSelector)};
node = node->child_at(0);
for (size_t index = 0; index < kNonEmptyIframesCount; ++index) {
NavigateFrameToURL(node, url_a);
- ASSERT_TRUE(ExecuteScriptAndExtractString(node, kWaitForFrameLoadScript,
- &msg_from_renderer));
- ASSERT_EQ(kRendererMsgLoaded, msg_from_renderer);
+ WaitForOnLoad(node);
// Store |document.querySelector('iframe').getBoundingClientRect()|.
reference_page_bounds_before_scroll.push_back(
- GetBoundingClientRect(node->current_frame_host(), kIframeSelector));
+ GetBoundingClientRect(node, kIframeSelector));
node = node->child_at(0);
}
// Sanity-check: If the page is setup properly then all the <iframe>s should
@@ -1716,11 +1813,11 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, ScrollElementIntoView) {
// page which contains OOPIFs.
node = web_contents()->GetFrameTree()->root();
std::vector<gfx::Rect> reference_page_bounds_after_scroll = {
- GetBoundingClientRect(node->current_frame_host(), kIframeSelector)};
+ GetBoundingClientRect(node, kIframeSelector)};
node = node->child_at(0);
for (size_t index = 0; index < kNonEmptyIframesCount; ++index) {
reference_page_bounds_after_scroll.push_back(
- GetBoundingClientRect(node->current_frame_host(), kIframeSelector));
+ GetBoundingClientRect(node, kIframeSelector));
node = node->child_at(0);
}
@@ -1728,20 +1825,16 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, ScrollElementIntoView) {
// structured as b(b(a(c(a(a(a)))))) where the inner-most <iframe> is empty.
ASSERT_TRUE(NavigateToURL(shell(), url_b));
node = web_contents()->GetFrameTree()->root();
- ASSERT_TRUE(ExecuteScriptAndExtractString(node, kWaitForFrameLoadScript,
- &msg_from_renderer));
- ASSERT_EQ(kRendererMsgLoaded, msg_from_renderer);
+ WaitForOnLoad(node);
std::vector<gfx::Rect> test_page_bounds_before_scroll = {
- GetBoundingClientRect(node->current_frame_host(), kIframeSelector)};
+ GetBoundingClientRect(node, kIframeSelector)};
const GURL iframe_urls[] = {url_b, url_a, url_c, url_a, url_a};
node = node->child_at(0);
for (size_t index = 0; index < kNonEmptyIframesCount; ++index) {
NavigateFrameToURL(node, iframe_urls[index]);
- ASSERT_TRUE(ExecuteScriptAndExtractString(node, kWaitForFrameLoadScript,
- &msg_from_renderer));
- ASSERT_EQ(kRendererMsgLoaded, msg_from_renderer);
+ WaitForOnLoad(node);
test_page_bounds_before_scroll.push_back(
- GetBoundingClientRect(node->current_frame_host(), kIframeSelector));
+ GetBoundingClientRect(node, kIframeSelector));
node = node->child_at(0);
}
// Sanity-check: The bounds should match those from non-OOPIF page.
@@ -1758,7 +1851,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, ScrollElementIntoView) {
RenderFrameHostImpl* current_rfh = node->current_frame_host()->GetParent();
while (current_rfh) {
gfx::Rect current_bounds =
- GetBoundingClientRect(current_rfh, kIframeSelector);
+ GetBoundingClientRect(current_rfh->frame_tree_node(), kIframeSelector);
gfx::Rect reference_bounds = reference_page_bounds_after_scroll[index];
if (current_bounds.ApproximatelyEqual(reference_bounds,
kRectDimensionErrorTolerance)) {
@@ -1773,55 +1866,175 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, ScrollElementIntoView) {
}
}
-// This test verifies that Scrolling a focused editable element into view works
-// when the element is inside an OOPIF.
-// Flaky test, see crbug.com/793616
-IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
- DISABLED_ScrollFocusedEditableElementIntoView) {
- GURL main_frame_url(
- embedded_test_server()->GetURL("a.com", "/iframe_out_of_view.html"));
- EXPECT_TRUE(NavigateToURL(shell(), main_frame_url));
- FrameTreeNode* root = web_contents()->GetFrameTree()->root();
+// This test verifies that ScrollFocusedEditableElementIntoView works correctly
+// for OOPIFs. Essentially, the test verifies that in a similar setup, the
+// resultant page scale factor is the same for OOPIF and non-OOPIF cases. This
+// also verifies that in response to the scroll command, the root-layer scrolls
+// correctly and the <input> is visible in visual viewport.
+#if defined(OS_ANDROID)
+// crbug.com/793616
+#define MAYBE_ScrollFocusedEditableElementIntoView \
+ DISABLED_ScrollFocusedEditableElementIntoView
+#else
+#define MAYBE_ScrollFocusedEditableElementIntoView \
+ ScrollFocusedEditableElementIntoView
+#endif
+IN_PROC_BROWSER_TEST_F(SitePerProcessProgrammaticScrollTest,
+ MAYBE_ScrollFocusedEditableElementIntoView) {
+ GURL url_a(embedded_test_server()->GetURL("a.com", kIframeOutOfViewHTML));
+ GURL url_b(embedded_test_server()->GetURL("b.com", kIframeOutOfViewHTML));
- GURL child_frame_url(
- embedded_test_server()->GetURL("b.com", "/page_with_input_field.html"));
- NavigateFrameToURL(root->child_at(0), child_frame_url);
+#if defined(OS_ANDROID)
+ // The reason for Android specific code is that
+ // AutoZoomFocusedNodeToLegibleScale is in blink's WebSettings and difficult
+ // to access from here. It so happens that the setting is on for Android.
+
+ // A lower bound on the ratio of page scale factor after scroll. The actual
+ // value depends on minReadableCaretHeight / caret_bounds.Height(). The page
+ // is setup so caret height is quite small so the expected scale should be
+ // larger than 2.0.
+ float kLowerBoundOnScaleAfterScroll = 2.0;
+ float kEpsilon = 0.1;
+#endif
- RenderFrameHostImpl* main_frame = root->current_frame_host();
- RenderFrameHostImpl* child_frame = root->child_at(0)->current_frame_host();
+ ASSERT_TRUE(NavigateToURL(shell(), url_a));
+ FrameTreeNode* root = web_contents()->GetFrameTree()->root();
+ WaitForOnLoad(root);
+ NavigateFrameToURL(root->child_at(0), url_a);
+ WaitForOnLoad(root->child_at(0));
+#if defined(OS_ANDROID)
+ float scale_before_scroll_nonoopif = GetVisualViewportScale(root);
+#endif
+ AddFocusedInputField(root->child_at(0));
+ // Focusing <input> causes scrollIntoView(). The following line makes sure
+ // that the <iframe> is out of view again.
+ SetWindowScroll(root, 0, 0);
+ ASSERT_FALSE(GetVisualViewport(root).Intersects(
+ GetBoundingClientRect(root, kIframeSelector)));
+ root->child_at(0)
+ ->current_frame_host()
+ ->GetFrameInputHandler()
+ ->ScrollFocusedEditableNodeIntoRect(gfx::Rect());
+ WaitForElementVisible(root, kIframeSelector);
+#if defined(OS_ANDROID)
+ float scale_after_scroll_nonoopif = GetVisualViewportScale(root);
+ // Increased scale means zoom triggered correctly.
+ EXPECT_GT(scale_after_scroll_nonoopif - scale_before_scroll_nonoopif,
+ kEpsilon);
+ EXPECT_GT(scale_after_scroll_nonoopif, kLowerBoundOnScaleAfterScroll);
+#endif
- // Focus the input field.
- std::string result;
+ // Retry the test on an OOPIF page.
+ Shell* new_shell = CreateBrowser();
+ ASSERT_TRUE(NavigateToURL(new_shell, url_b));
+ root = static_cast<WebContentsImpl*>(new_shell->web_contents())
+ ->GetFrameTree()
+ ->root();
+ WaitForOnLoad(root);
+#if defined(OS_ANDROID)
+ float scale_before_scroll_oopif = GetVisualViewportScale(root);
+ // Sanity-check:
+ ASSERT_NEAR(scale_before_scroll_oopif, scale_before_scroll_nonoopif,
+ kEpsilon);
+#endif
+ NavigateFrameToURL(root->child_at(0), url_a);
+ WaitForOnLoad(root->child_at(0));
+ AddFocusedInputField(root->child_at(0));
+ SetWindowScroll(root, 0, 0);
+ ASSERT_FALSE(GetVisualViewport(root).Intersects(
+ GetBoundingClientRect(root, kIframeSelector)));
+ root->child_at(0)
+ ->current_frame_host()
+ ->GetFrameInputHandler()
+ ->ScrollFocusedEditableNodeIntoRect(gfx::Rect());
+ WaitForElementVisible(root, kIframeSelector);
+#if defined(OS_ANDROID)
+ float scale_after_scroll_oopif = GetVisualViewportScale(root);
+ EXPECT_GT(scale_after_scroll_oopif - scale_before_scroll_oopif, kEpsilon);
+ EXPECT_GT(scale_after_scroll_oopif, kLowerBoundOnScaleAfterScroll);
+ // The scale is based on the caret height and it should be the same in both
+ // OOPIF and non-OOPIF pages.
+ EXPECT_NEAR(scale_after_scroll_oopif, scale_after_scroll_nonoopif, kEpsilon);
+#endif
+ // Make sure the <input> is at least partly visible in the |visualViewport|.
+ gfx::Rect final_visual_viewport_oopif = GetVisualViewport(root);
+ gfx::Rect iframe_bounds_after_scroll_oopif =
+ GetBoundingClientRect(root, kIframeSelector);
+ gfx::Rect input_bounds_after_scroll_oopif =
+ GetBoundingClientRect(root->child_at(0), kInputSelector);
+ input_bounds_after_scroll_oopif +=
+ iframe_bounds_after_scroll_oopif.OffsetFromOrigin();
ASSERT_TRUE(
- ExecuteScriptAndExtractString(child_frame, "focusInputField()", &result));
- ASSERT_EQ(result, "input-focus");
-
- // Wait and verify that before scrolling the child <iframe> is not visible.
- while (main_frame->GetView()->GetViewBounds().Intersects(
- child_frame->GetView()->GetViewBounds())) {
- base::RunLoop run_loop;
- base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
- FROM_HERE, run_loop.QuitClosure(), TestTimeouts::tiny_timeout());
- run_loop.Run();
- }
-
- child_frame->GetFrameInputHandler()->ScrollFocusedEditableNodeIntoRect(
- gfx::Rect());
+ final_visual_viewport_oopif.Intersects(input_bounds_after_scroll_oopif));
+}
- // Wait until the child frame is visible.
- while (!root->current_frame_host()->GetView()->GetViewBounds().Intersects(
- child_frame->GetView()->GetViewBounds())) {
- base::RunLoop run_loop;
- base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
- FROM_HERE, run_loop.QuitClosure(), TestTimeouts::tiny_timeout());
- run_loop.Run();
- }
+IN_PROC_BROWSER_TEST_F(SitePerProcessProgrammaticScrollTest,
+ ScrollClippedFocusedEditableElementIntoView) {
+ GURL url_a(embedded_test_server()->GetURL("a.com", kIframeClippedHTML));
+ GURL child_url_b(embedded_test_server()->GetURL("b.com", kInputBoxHTML));
- // Verify that the bounding box of the <input> is visible inside the main
- // frame.
- gfx::Rect test_rect = GetBoundingClientRect(child_frame, "input");
- test_rect += child_frame->GetView()->GetViewBounds().OffsetFromOrigin();
- EXPECT_TRUE(main_frame->GetView()->GetViewBounds().Intersects(test_rect));
+ ASSERT_TRUE(NavigateToURL(shell(), url_a));
+ FrameTreeNode* root = web_contents()->GetFrameTree()->root();
+ WaitForOnLoad(root);
+ NavigateFrameToURL(root->child_at(0), child_url_b);
+ WaitForOnLoad(root->child_at(0));
+
+ SetWindowScroll(root, 0, 0);
+ SetWindowScroll(root->child_at(0), 1000, 2000);
+
+ float scale_before = GetVisualViewportScale(root);
+
+ // The input_box page focuses the input box on load. This call should
+ // simulate the scroll into view we do when an input box is tapped.
+ root->child_at(0)
+ ->current_frame_host()
+ ->GetFrameInputHandler()
+ ->ScrollFocusedEditableNodeIntoRect(gfx::Rect());
+
+ // The scroll into view is animated on the compositor. Make sure we wait
+ // until that's completed before testing the rects.
+ WaitForElementVisible(root, kIframeSelector);
+ WaitForViewportToStabilize(root);
+
+ // These rects are in the coordinate space of the root frame.
+ gfx::Rect visual_viewport_rect = GetVisualViewport(root);
+ gfx::Rect window_rect = GetBoundingClientRect(root, ":root");
+ gfx::Rect iframe_rect = GetBoundingClientRect(root, "iframe");
+ gfx::Rect clip_rect = GetBoundingClientRect(root, "#clip");
+
+ // This is in the coordinate space of the iframe, we'll add the iframe offset
+ // after to put it into the root frame's coordinate space.
+ gfx::Rect input_rect = GetBoundingClientRect(root->child_at(0), "input");
+
+ // Make sure the input rect is visible in the iframe.
+ EXPECT_TRUE(gfx::Rect(iframe_rect.size()).Intersects(input_rect))
+ << "Input box [" << input_rect.ToString() << "] isn't visible in iframe ["
+ << gfx::Rect(iframe_rect.size()).ToString() << "]";
+
+ input_rect += iframe_rect.OffsetFromOrigin();
+
+ // Make sure the input rect is visible through the clipping layer.
+ EXPECT_TRUE(clip_rect.Intersects(input_rect))
+ << "Input box [" << input_rect.ToString() << "] isn't scrolled into view "
+ << "of the clipping layer [" << clip_rect.ToString() << "]";
+
+ // And finally, it should be visible in the layout and visual viewports.
+ EXPECT_TRUE(window_rect.Intersects(input_rect))
+ << "Input box [" << input_rect.ToString() << "] isn't visible in the "
+ << "layout viewport [" << window_rect.ToString() << "]";
+ EXPECT_TRUE(visual_viewport_rect.Intersects(input_rect))
+ << "Input box [" << input_rect.ToString() << "] isn't visible in the "
+ << "visual viewport [" << visual_viewport_rect.ToString() << "]";
+
+ float scale_after = GetVisualViewportScale(root);
+
+// Make sure we still zoom in on the input box on platforms that zoom into the
+// focused editable.
+#if defined(OS_ANDROID)
+ EXPECT_GT(scale_after, scale_before);
+#else
+ EXPECT_FLOAT_EQ(scale_after, scale_before);
+#endif
}
// Tests OOPIF rendering by checking that the RWH of the iframe generates
@@ -2133,7 +2346,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
// parent frame.
RenderFrameDeletedObserver deleted_observer2(
root->child_at(0)->current_frame_host());
- GURL about_blank_url("about:blank");
+ GURL about_blank_url("about:blank#foo");
NavigateIframeToURL(shell()->web_contents(), "child-0", about_blank_url);
EXPECT_TRUE(observer.last_navigation_succeeded());
EXPECT_EQ(about_blank_url, observer.last_navigation_url());
@@ -2168,7 +2381,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
// own context. It should stay in the same SiteInstance as before, not the
// parent one.
TestFrameNavigationObserver frame_observer(child);
- ExecuteScriptAsync(child, "window.location.href = 'about:blank';");
+ ExecuteScriptAsync(child, "window.location.href = 'about:blank#foo';");
frame_observer.Wait();
EXPECT_EQ(about_blank_url, child->current_url());
@@ -2223,7 +2436,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
RenderProcessHost* child_process = node2->current_frame_host()->GetProcess();
RenderProcessHostWatcher crash_observer(
child_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
- child_process->Shutdown(0, false);
+ child_process->Shutdown(0);
crash_observer.Wait();
// Now navigate the second iframe (node3) to the same site as the node2.
@@ -2259,7 +2472,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, RemoveFocusFromKilledFrame) {
RenderProcessHost* child_process = node2->current_frame_host()->GetProcess();
RenderProcessHostWatcher crash_observer(
child_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
- child_process->Shutdown(0, false);
+ child_process->Shutdown(0);
crash_observer.Wait();
// Try to focus the root's owning WebContents.
@@ -2336,7 +2549,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
root->child_at(0)->current_frame_host()->GetProcess();
RenderProcessHostWatcher crash_observer(
child_process_b, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
- child_process_b->Shutdown(0, false);
+ child_process_b->Shutdown(0);
crash_observer.Wait();
// The Site C frame (a child of the crashed Site B frame) should go away,
@@ -2561,7 +2774,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
root->child_at(0)->current_frame_host()->GetProcess();
RenderProcessHostWatcher crash_observer(
child_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
- child_process->Shutdown(0, false);
+ child_process->Shutdown(0);
crash_observer.Wait();
// Navigate the second subframe to b.com to recreate the b.com process.
@@ -2625,7 +2838,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
root->child_at(0)->current_frame_host()->GetProcess();
RenderProcessHostWatcher crash_observer(
child_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
- child_process->Shutdown(0, false);
+ child_process->Shutdown(0);
crash_observer.Wait();
// Add a new child frame to the third subframe.
@@ -2690,7 +2903,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
EXPECT_TRUE(ExecuteScript(root, "popup = window.open('about:blank');"));
Shell* popup = new_shell_observer.GetShell();
GURL popup_url(embedded_test_server()->GetURL("b.com", "/title2.html"));
- EXPECT_TRUE(NavigateToURL(popup, popup_url));
+ EXPECT_TRUE(NavigateToURLFromRenderer(popup, popup_url));
// Verify that each top-level frame has proxies in the other's SiteInstance.
FrameTreeNode* popup_root =
@@ -2712,7 +2925,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
RenderProcessHost* child_process = root->current_frame_host()->GetProcess();
RenderProcessHostWatcher crash_observer(
child_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
- child_process->Shutdown(0, false);
+ child_process->Shutdown(0);
crash_observer.Wait();
EXPECT_FALSE(root->current_frame_host()->IsRenderFrameLive());
@@ -2812,7 +3025,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
root->child_at(0)->current_frame_host()->GetProcess();
RenderProcessHostWatcher crash_observer(
child_process_b, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
- child_process_b->Shutdown(0, false);
+ child_process_b->Shutdown(0);
crash_observer.Wait();
// Make sure proxy C has gone from root.
@@ -2855,7 +3068,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, CrashSubframe) {
{
RenderProcessHostWatcher crash_observer(
child_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
- child_process->Shutdown(0, false);
+ child_process->Shutdown(0);
crash_observer.Wait();
}
@@ -2879,7 +3092,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, CrashSubframe) {
{
RenderProcessHostWatcher crash_observer(
root_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
- root_process->Shutdown(0, false);
+ root_process->Shutdown(0);
crash_observer.Wait();
}
EXPECT_EQ(0U, root->child_count());
@@ -4430,8 +4643,9 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
ShellAddedObserver new_shell_observer;
EXPECT_TRUE(ExecuteScript(web_contents(), "window.open('about:blank');"));
Shell* popup = new_shell_observer.GetShell();
- EXPECT_TRUE(NavigateToURL(popup, embedded_test_server()->GetURL(
- "bar.com", "/navigate_opener.html")));
+ EXPECT_TRUE(NavigateToURLFromRenderer(
+ popup,
+ embedded_test_server()->GetURL("bar.com", "/navigate_opener.html")));
// Show an interstitial in the opener.
TestInterstitialDelegate* delegate = new TestInterstitialDelegate;
@@ -4481,7 +4695,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
Shell* popup = new_shell_observer.GetShell();
GURL popup_url(
embedded_test_server()->GetURL("bar.com", "/post_message.html"));
- EXPECT_TRUE(NavigateToURL(popup, popup_url));
+ EXPECT_TRUE(NavigateToURLFromRenderer(popup, popup_url));
// From the popup, open another popup for baz.com. This will be used to
// check that the whole opener chain is processed when creating proxies and
@@ -4491,7 +4705,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
Shell* popup2 = new_shell_observer2.GetShell();
GURL popup2_url(
embedded_test_server()->GetURL("baz.com", "/post_message.html"));
- EXPECT_TRUE(NavigateToURL(popup2, popup2_url));
+ EXPECT_TRUE(NavigateToURLFromRenderer(popup2, popup2_url));
// Ensure that we've created proxies for SiteInstances of both popups (C, D)
// in the main window's frame tree.
@@ -4789,7 +5003,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, NavigatePopupToIllegalURL) {
popup->web_contents()->GetLastCommittedURL());
// Navigate popup back to a cross-site URL.
- EXPECT_TRUE(NavigateToURL(popup, popup_url));
+ EXPECT_TRUE(NavigateToURLFromRenderer(popup, popup_url));
EXPECT_NE(popup->web_contents()->GetSiteInstance(),
shell()->web_contents()->GetSiteInstance());
@@ -4843,7 +5057,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
// Navigate the popup cross-site and ensure it's still reachable via
// window.open from the main frame.
GURL d_url(embedded_test_server()->GetURL("d.com", "/title3.html"));
- EXPECT_TRUE(NavigateToURL(foo_shell, d_url));
+ EXPECT_TRUE(NavigateToURLFromRenderer(foo_shell, d_url));
EXPECT_EQ(d_url, foo_root->current_url());
NavigateNamedFrame(shell(), named_frame_url, "foo");
EXPECT_TRUE(WaitForLoadStop(foo_shell->web_contents()));
@@ -4928,7 +5142,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, UpdateSubframeOpener) {
EXPECT_TRUE(popup_shell);
GURL popup_url(embedded_test_server()->GetURL(
"bar.com", "/frame_tree/page_with_post_message_frames.html"));
- EXPECT_TRUE(NavigateToURL(popup_shell, popup_url));
+ EXPECT_TRUE(NavigateToURLFromRenderer(popup_shell, popup_url));
FrameTreeNode* popup_root =
static_cast<WebContentsImpl*>(popup_shell->web_contents())
@@ -5197,7 +5411,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
// destroy |rfh| and |rvh| before they are checked in the test.
GURL b_url(embedded_test_server()->GetURL("b.com", "/title2.html"));
TestFrameNavigationObserver commit_observer(root);
- shell()->LoadURL(b_url);
+ EXPECT_TRUE(ExecuteScript(shell(), "location = '" + b_url.spec() + "'"));
commit_observer.WaitForCommit();
EXPECT_FALSE(deleted_observer.deleted());
@@ -5223,10 +5437,11 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
EXPECT_FALSE(root->frame_tree()->GetRenderViewHost(site_instance));
EXPECT_TRUE(deleted_observer.deleted());
- // Start a navigation back to A and check that the RenderViewHost wasn't
- // reused.
+ // Start a navigation back to A, being careful to stay in the same
+ // BrowsingInstance, and check that the RenderViewHost wasn't reused.
TestNavigationObserver navigation_observer(shell()->web_contents());
- shell()->LoadURL(a_url);
+ shell()->LoadURLForFrame(a_url, std::string(),
+ ui::PageTransitionFromInt(ui::PAGE_TRANSITION_LINK));
RenderViewHostImpl* pending_rvh =
root->render_manager()->speculative_frame_host()->render_view_host();
EXPECT_EQ(site_instance, pending_rvh->GetSiteInstance());
@@ -5579,7 +5794,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
// Navigate the first child frame to 'about:blank' (which is a
// remote-to-local transition), and then detach it.
- FrameDeletedObserver observer(root->child_at(0));
+ FrameDeletedObserver observer(root->child_at(0)->current_frame_host());
std::string script =
"var f = document.querySelector('iframe');"
"f.contentWindow.location.href = 'about:blank';"
@@ -5622,7 +5837,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
// Tell parent to remove the first child. This should happen after the
// previous navigation starts but before it commits.
- FrameDeletedObserver observer(child);
+ FrameDeletedObserver observer(child->current_frame_host());
EXPECT_TRUE(ExecuteScript(
root, "document.body.removeChild(document.querySelector('iframe'));"));
observer.Wait();
@@ -5653,7 +5868,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, NavigateAboutBlankAndDetach) {
// Navigate the child frame to "about:blank" from the parent document and
// wait for it to be removed.
- FrameDeletedObserver observer(child);
+ FrameDeletedObserver observer(child->current_frame_host());
EXPECT_TRUE(ExecuteScript(
root, base::StringPrintf("f.src = '%s'", url::kAboutBlankURL)));
observer.Wait();
@@ -5697,7 +5912,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
root->child_at(0)->render_manager()->GetProxyToParent()->GetRoutingID();
// Tell main frame A to delete its subframe B.
- FrameDeletedObserver observer(root->child_at(0));
+ FrameDeletedObserver observer(root->child_at(0)->current_frame_host());
EXPECT_TRUE(ExecuteScript(
root, "document.body.removeChild(document.querySelector('iframe'));"));
@@ -7087,7 +7302,8 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
// termination.
RenderProcessHost* subframe_process =
root->child_at(0)->current_frame_host()->GetProcess();
- subframe_process->IncrementKeepAliveRefCount();
+ subframe_process->IncrementKeepAliveRefCount(
+ RenderProcessHostImpl::KeepAliveClientType::kFetch);
// Navigate the subframe away from b.com. Since this is the last active
// frame in the b.com process, this causes the RenderWidget and RenderView to
@@ -7109,7 +7325,8 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
// process hasn't heard the OnChannelError yet). This race will need to be
// fixed.
- subframe_process->DecrementKeepAliveRefCount();
+ subframe_process->DecrementKeepAliveRefCount(
+ RenderProcessHostImpl::KeepAliveClientType::kFetch);
}
// Tests that an input event targeted to a out-of-process iframe correctly
@@ -7588,7 +7805,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
// Navigate main tab to a b.com URL that will not commit.
GURL stall_url(embedded_test_server()->GetURL("b.com", "/title2.html"));
TestNavigationManager delayer(shell()->web_contents(), stall_url);
- shell()->LoadURL(stall_url);
+ EXPECT_TRUE(ExecuteScript(shell(), "location = '" + stall_url.spec() + "'"));
EXPECT_TRUE(delayer.WaitForRequestStart());
// The pending RFH should be in the same process as the popup.
@@ -7602,7 +7819,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
// and the popup.
RenderProcessHostWatcher crash_observer(
pending_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
- EXPECT_TRUE(pending_process->Shutdown(0, false));
+ EXPECT_TRUE(pending_process->Shutdown(0));
crash_observer.Wait();
// The pending RFH should have been canceled and destroyed, so that it won't
@@ -7615,7 +7832,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
// Navigate main tab to b.com again. This should not crash.
GURL b_url(embedded_test_server()->GetURL("b.com", "/title3.html"));
- EXPECT_TRUE(NavigateToURL(shell(), b_url));
+ EXPECT_TRUE(NavigateToURLFromRenderer(shell(), b_url));
// The b.com RVH in the main tab should become active.
EXPECT_TRUE(rvh->is_active());
@@ -7647,7 +7864,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
GURL stall_url(embedded_test_server()->GetURL("b.com", "/title2.html"));
NavigationHandleObserver handle_observer(shell()->web_contents(), stall_url);
TestNavigationManager delayer(shell()->web_contents(), stall_url);
- shell()->LoadURL(stall_url);
+ EXPECT_TRUE(ExecuteScript(shell(), "location = '" + stall_url.spec() + "'"));
EXPECT_TRUE(delayer.WaitForRequestStart());
// Kill the b.com process, currently in use by the pending RenderFrameHost
@@ -7656,7 +7873,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
popup_shell->web_contents()->GetMainFrame()->GetProcess();
RenderProcessHostWatcher crash_observer(
pending_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
- EXPECT_TRUE(pending_process->Shutdown(0, false));
+ EXPECT_TRUE(pending_process->Shutdown(0));
crash_observer.Wait();
// Since the navigation above didn't commit, the b.com RenderViewHost in the
@@ -7671,7 +7888,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
// RenderViewHost was brought into an active state by the navigation to
// |stall_url| above, even though it never committed.
GURL b_url(embedded_test_server()->GetURL("b.com", "/title3.html"));
- EXPECT_TRUE(NavigateToURL(popup_shell, b_url));
+ EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(popup_shell, b_url));
EXPECT_FALSE(rvh->is_active());
}
@@ -7695,7 +7912,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
RenderProcessHost* child_process = child->current_frame_host()->GetProcess();
RenderProcessHostWatcher crash_observer(
child_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
- child_process->Shutdown(0, false);
+ child_process->Shutdown(0);
crash_observer.Wait();
EXPECT_FALSE(child->current_frame_host()->IsRenderFrameLive());
@@ -8024,18 +8241,18 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
// Open a popup and navigate it to b.com.
Shell* popup = OpenPopup(shell(), a_url, "popup");
- EXPECT_TRUE(NavigateToURL(popup, b_url));
+ EXPECT_TRUE(NavigateToURLFromRenderer(popup, b_url));
// Open a second popup and navigate it to b.com, which redirects to c.com.
// The navigation to b.com will create a pending RenderFrameHost, which will
- // be canceled during the redirect to c.com. Note that NavigateToURL will
- // return false because the committed URL won't match the requested URL due
- // to the redirect.
+ // be canceled during the redirect to c.com. Note that
+ // NavigateToURLFromRenderer will return false because the committed URL
+ // won't match the requested URL due to the redirect.
Shell* popup2 = OpenPopup(shell(), a_url, "popup2");
TestNavigationObserver observer(popup2->web_contents());
GURL redirect_url(embedded_test_server()->GetURL(
"b.com", "/server-redirect?" + c_url.spec()));
- EXPECT_FALSE(NavigateToURL(popup2, redirect_url));
+ EXPECT_FALSE(NavigateToURLFromRenderer(popup2, redirect_url));
EXPECT_EQ(c_url, observer.last_navigation_url());
EXPECT_TRUE(observer.last_navigation_succeeded());
@@ -8046,14 +8263,14 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
popup->web_contents()->GetMainFrame()->GetProcess();
RenderProcessHostWatcher crash_observer(
b_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
- b_process->Shutdown(0, false);
+ b_process->Shutdown(0);
crash_observer.Wait();
// Navigate the second popup to b.com. This used to crash when creating the
// RenderView, because it reused the RenderViewHost created by the canceled
// navigation to b.com, and that RenderViewHost had a stale main frame
// routing ID and active state.
- EXPECT_TRUE(NavigateToURL(popup2, b_url));
+ EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(popup2, b_url));
}
// Check that after a pending RFH is canceled and replaced with a proxy (which
@@ -8071,7 +8288,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
// Open a popup and navigate it to b.com.
Shell* popup = OpenPopup(shell(), a_url, "popup");
- EXPECT_TRUE(NavigateToURL(popup, b_url));
+ EXPECT_TRUE(NavigateToURLFromRenderer(popup, b_url));
// Open a second popup and navigate it to b.com, which redirects to c.com.
// The navigation to b.com will create a pending RenderFrameHost, which will
@@ -8082,14 +8299,14 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
TestNavigationObserver observer(popup2->web_contents());
GURL redirect_url(embedded_test_server()->GetURL(
"b.com", "/server-redirect?" + c_url.spec()));
- EXPECT_FALSE(NavigateToURL(popup2, redirect_url));
+ EXPECT_FALSE(NavigateToURLFromRenderer(popup2, redirect_url));
EXPECT_EQ(c_url, observer.last_navigation_url());
EXPECT_TRUE(observer.last_navigation_succeeded());
// Navigate the second popup to b.com. This used to crash the b.com renderer
// because it failed to delete the canceled RFH's RenderFrame, so this caused
// it to try to create a frame widget which already existed.
- EXPECT_TRUE(NavigateToURL(popup2, b_url));
+ EXPECT_TRUE(NavigateToURLFromRenderer(popup2, b_url));
}
// Check that when a pending RFH is canceled and a proxy needs to be created in
@@ -8105,7 +8322,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
// Open a popup and navigate it to b.com.
Shell* popup = OpenPopup(shell(), a_url, "popup");
- EXPECT_TRUE(NavigateToURL(popup, b_url));
+ EXPECT_TRUE(NavigateToURLFromRenderer(popup, b_url));
// Open a second popup and navigate it to b.com, which redirects to c.com.
// The navigation to b.com will create a pending RenderFrameHost, which will
@@ -8116,7 +8333,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
TestNavigationObserver observer(popup2->web_contents());
GURL redirect_url(embedded_test_server()->GetURL(
"b.com", "/server-redirect?" + c_url.spec()));
- EXPECT_FALSE(NavigateToURL(popup2, redirect_url));
+ EXPECT_FALSE(NavigateToURLFromRenderer(popup2, redirect_url));
EXPECT_EQ(c_url, observer.last_navigation_url());
EXPECT_TRUE(observer.last_navigation_succeeded());
@@ -8145,7 +8362,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
// reach the window reference for |popup2| due to a security restriction in
// Blink. So, navigate the main tab to b.com and then send a postMessage to
// |popup2|. This is allowed since the main tab is |popup2|'s opener.
- EXPECT_TRUE(NavigateToURL(shell(), b_url));
+ EXPECT_TRUE(NavigateToURLFromRenderer(shell(), b_url));
base::string16 expected_title(base::UTF8ToUTF16("foo"));
TitleWatcher title_watcher(popup2->web_contents(), expected_title);
@@ -8316,6 +8533,126 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessFeaturePolicyJavaScriptBrowserTest,
EXPECT_FALSE(success);
}
+// Test that the constructed feature policy is correct in sandboxed
+// frames. Sandboxed frames have an opaque origin, and if the frame policy,
+// which is constructed in the parent frame, cannot send that origin through
+// the browser process to the sandboxed frame, then the sandboxed frame's
+// policy will be incorrect.
+//
+// This is a regression test for https://crbug.com/690520
+IN_PROC_BROWSER_TEST_F(SitePerProcessFeaturePolicyJavaScriptBrowserTest,
+ TestAllowAttributeInSandboxedFrame) {
+ GURL main_url(embedded_test_server()->GetURL(
+ "a.com",
+ "/cross_site_iframe_factory.html?"
+ "a(b{allow-geolocation,sandbox-allow-scripts})"));
+ GURL nav_url(embedded_test_server()->GetURL("c.com", "/title1.html"));
+
+ EXPECT_TRUE(NavigateToURL(shell(), main_url));
+
+ FrameTreeNode* root = web_contents()->GetFrameTree()->root();
+ EXPECT_TRUE(root->current_replication_state().feature_policy_header.empty());
+ EXPECT_EQ(1UL, root->child_count());
+ // Verify that the child frame is sandboxed with an opaque origin.
+ EXPECT_TRUE(root->child_at(0)
+ ->current_frame_host()
+ ->GetLastCommittedOrigin()
+ .unique());
+ // And verify that the origin in the replication state is also opaque.
+ EXPECT_TRUE(root->child_at(0)->current_origin().unique());
+
+ // Ask the sandboxed iframe to report the enabled state of the geolocation
+ // feature. If the declared policy was correctly flagged as referring to the
+ // opaque origin, then the policy in the sandboxed renderer will be
+ // constructed correctly, and geolocation will be enabled in the sandbox.
+ // Otherwise, it will be disabled, as geolocation is disabled by default in
+ // cross-origin frames.
+ bool success = false;
+ EXPECT_TRUE(ExecuteScriptAndExtractBool(
+ root->child_at(0),
+ "window.domAutomationController.send("
+ "document.policy.allowsFeature('geolocation'));",
+ &success));
+ EXPECT_TRUE(success);
+
+ TestNavigationObserver load_observer(shell()->web_contents());
+ EXPECT_TRUE(ExecuteScript(
+ root->child_at(0), "document.location.href=\"" + nav_url.spec() + "\""));
+ load_observer.Wait();
+
+ // Verify that the child frame is sandboxed with an opaque origin.
+ EXPECT_TRUE(root->child_at(0)
+ ->current_frame_host()
+ ->GetLastCommittedOrigin()
+ .unique());
+ // And verify that the origin in the replication state is also opaque.
+ EXPECT_TRUE(root->child_at(0)->current_origin().unique());
+
+ EXPECT_TRUE(ExecuteScriptAndExtractBool(
+ root->child_at(0),
+ "window.domAutomationController.send("
+ "document.policy.allowsFeature('geolocation'));",
+ &success));
+ EXPECT_TRUE(success);
+}
+
+// Test that the constructed feature policy is correct in sandboxed
+// frames. Sandboxed frames have an opaque origin, and if the frame policy,
+// which is constructed in the parent frame, cannot send that origin through
+// the browser process to the sandboxed frame, then the sandboxed frame's
+// policy will be incorrect.
+//
+// This is a regression test for https://crbug.com/690520
+IN_PROC_BROWSER_TEST_F(SitePerProcessFeaturePolicyJavaScriptBrowserTest,
+ TestAllowAttributeInOpaqueOriginAfterNavigation) {
+ GURL main_url(embedded_test_server()->GetURL(
+ "a.com", "/page_with_data_iframe_and_allow.html"));
+ GURL nav_url(embedded_test_server()->GetURL("c.com", "/title1.html"));
+
+ EXPECT_TRUE(NavigateToURL(shell(), main_url));
+
+ FrameTreeNode* root = web_contents()->GetFrameTree()->root();
+ EXPECT_TRUE(root->current_replication_state().feature_policy_header.empty());
+ EXPECT_EQ(1UL, root->child_count());
+ // Verify that the child frame has an opaque origin.
+ EXPECT_TRUE(root->child_at(0)
+ ->current_frame_host()
+ ->GetLastCommittedOrigin()
+ .unique());
+ // And verify that the origin in the replication state is also opaque.
+ EXPECT_TRUE(root->child_at(0)->current_origin().unique());
+
+ // Verify that geolocation is enabled in the document.
+ bool success = false;
+ EXPECT_TRUE(ExecuteScriptAndExtractBool(
+ root->child_at(0),
+ "window.domAutomationController.send("
+ "document.policy.allowsFeature('geolocation'));",
+ &success));
+ EXPECT_TRUE(success);
+
+ TestNavigationObserver load_observer(shell()->web_contents());
+ EXPECT_TRUE(ExecuteScript(
+ root->child_at(0), "document.location.href=\"" + nav_url.spec() + "\""));
+ load_observer.Wait();
+
+ // Verify that the child frame no longer has an opaque origin.
+ EXPECT_FALSE(root->child_at(0)
+ ->current_frame_host()
+ ->GetLastCommittedOrigin()
+ .unique());
+ // Verify that the origin in the replication state is also no longer opaque.
+ EXPECT_FALSE(root->child_at(0)->current_origin().unique());
+
+ // Verify that the new document does not have geolocation enabled.
+ EXPECT_TRUE(ExecuteScriptAndExtractBool(
+ root->child_at(0),
+ "window.domAutomationController.send("
+ "document.policy.allowsFeature('geolocation'));",
+ &success));
+ EXPECT_FALSE(success);
+}
+
// Ensure that an iframe that navigates cross-site doesn't use the same process
// as its parent. Then when its parent navigates it via the "srcdoc" attribute,
// it must reuse its parent's process.
@@ -8371,7 +8708,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
{
RenderProcessHostWatcher crash_observer(
child_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
- child_process->Shutdown(0, false);
+ child_process->Shutdown(0);
crash_observer.Wait();
}
EXPECT_FALSE(child->current_frame_host()->IsRenderFrameLive());
@@ -8546,7 +8883,9 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
EXPECT_FALSE(initial_effective_policy[0].origins[0].unique());
// Set the "sandbox" attribute; pending policy should update, and should now
- // contain a unique origin, but effective policy should remain unchanged.
+ // be flagged as matching the opaque origin of the frame (without containing
+ // an actual opaque origin, since the parent frame doesn't actually have that
+ // origin yet) but the effective policy should remain unchanged.
EXPECT_TRUE(ExecuteScript(
root, "document.getElementById('child-2').setAttribute('sandbox','')"));
const blink::ParsedFeaturePolicy updated_effective_policy =
@@ -8555,15 +8894,15 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
root->child_at(2)->pending_frame_policy().container_policy;
EXPECT_EQ(1UL, updated_effective_policy[0].origins.size());
EXPECT_FALSE(updated_effective_policy[0].origins[0].unique());
- EXPECT_EQ(1UL, updated_pending_policy[0].origins.size());
- EXPECT_TRUE(updated_pending_policy[0].origins[0].unique());
+ EXPECT_TRUE(updated_pending_policy[0].matches_opaque_src);
+ EXPECT_EQ(0UL, updated_pending_policy[0].origins.size());
// Navigate the frame; pending policy should now be committed.
NavigateFrameToURL(root->child_at(2), nav_url);
const blink::ParsedFeaturePolicy final_effective_policy =
root->child_at(2)->effective_frame_policy().container_policy;
- EXPECT_EQ(1UL, final_effective_policy[0].origins.size());
- EXPECT_TRUE(final_effective_policy[0].origins[0].unique());
+ EXPECT_TRUE(final_effective_policy[0].matches_opaque_src);
+ EXPECT_EQ(0UL, final_effective_policy[0].origins.size());
}
// Test harness that allows for "barrier" style delaying of requests matching
@@ -9058,8 +9397,8 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
OpenPopup(shell(), GURL(url::kAboutBlankURL), "foo");
// Navigate foo -> bar -> foo.
- EXPECT_TRUE(NavigateToURL(shell(), bar_url));
- EXPECT_TRUE(NavigateToURL(shell(), foo_url));
+ EXPECT_TRUE(NavigateToURLFromRenderer(shell(), bar_url));
+ EXPECT_TRUE(NavigateToURLFromRenderer(shell(), foo_url));
// There should be three history entries.
EXPECT_EQ(3, web_contents()->GetController().GetEntryCount());
@@ -9540,7 +9879,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
// Before it commits, start and commit a navigation to b.com in the second
// tab.
GURL new_url_2(embedded_test_server()->GetURL("b.com", "/title2.html"));
- EXPECT_TRUE(NavigateToURL(popup_shell, new_url_2));
+ EXPECT_TRUE(NavigateToURLFromRenderer(popup_shell, new_url_2));
// Check that the opener still has a speculative RenderFrameHost and a
// corresponding proxy for b.com.
@@ -9593,28 +9932,25 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, TestChildProcessImportance) {
FrameTreeNode* child = root->child_at(0);
// Importance should survive initial navigation.
+ EXPECT_EQ(ChildProcessImportance::MODERATE,
+ root->current_frame_host()->GetProcess()->GetEffectiveImportance());
EXPECT_EQ(
ChildProcessImportance::MODERATE,
- root->current_frame_host()->GetProcess()->ComputeEffectiveImportance());
- EXPECT_EQ(
- ChildProcessImportance::MODERATE,
- child->current_frame_host()->GetProcess()->ComputeEffectiveImportance());
+ child->current_frame_host()->GetProcess()->GetEffectiveImportance());
// Check setting importance.
web_contents()->SetImportance(ChildProcessImportance::NORMAL);
+ EXPECT_EQ(ChildProcessImportance::NORMAL,
+ root->current_frame_host()->GetProcess()->GetEffectiveImportance());
EXPECT_EQ(
ChildProcessImportance::NORMAL,
- root->current_frame_host()->GetProcess()->ComputeEffectiveImportance());
- EXPECT_EQ(
- ChildProcessImportance::NORMAL,
- child->current_frame_host()->GetProcess()->ComputeEffectiveImportance());
+ child->current_frame_host()->GetProcess()->GetEffectiveImportance());
web_contents()->SetImportance(ChildProcessImportance::IMPORTANT);
+ EXPECT_EQ(ChildProcessImportance::IMPORTANT,
+ root->current_frame_host()->GetProcess()->GetEffectiveImportance());
EXPECT_EQ(
ChildProcessImportance::IMPORTANT,
- root->current_frame_host()->GetProcess()->ComputeEffectiveImportance());
- EXPECT_EQ(
- ChildProcessImportance::IMPORTANT,
- child->current_frame_host()->GetProcess()->ComputeEffectiveImportance());
+ child->current_frame_host()->GetProcess()->GetEffectiveImportance());
// Check importance is maintained if child navigates to new domain.
int old_child_process_id = child->current_frame_host()->GetProcess()->GetID();
@@ -9628,7 +9964,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, TestChildProcessImportance) {
EXPECT_NE(old_child_process_id, new_child_process_id);
EXPECT_EQ(
ChildProcessImportance::IMPORTANT,
- child->current_frame_host()->GetProcess()->ComputeEffectiveImportance());
+ child->current_frame_host()->GetProcess()->GetEffectiveImportance());
// Check importance is maintained if root navigates to new domain.
int old_root_process_id = root->current_frame_host()->GetProcess()->GetID();
@@ -9641,9 +9977,8 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, TestChildProcessImportance) {
EXPECT_EQ(0u, root->child_count());
int new_root_process_id = root->current_frame_host()->GetProcess()->GetID();
EXPECT_NE(old_root_process_id, new_root_process_id);
- EXPECT_EQ(
- ChildProcessImportance::IMPORTANT,
- root->current_frame_host()->GetProcess()->ComputeEffectiveImportance());
+ EXPECT_EQ(ChildProcessImportance::IMPORTANT,
+ root->current_frame_host()->GetProcess()->GetEffectiveImportance());
// Check interstitial maintains importance.
TestInterstitialDelegate* delegate = new TestInterstitialDelegate;
@@ -9657,11 +9992,11 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, TestChildProcessImportance) {
RenderProcessHost* interstitial_process =
interstitial->GetMainFrame()->GetProcess();
EXPECT_EQ(ChildProcessImportance::IMPORTANT,
- interstitial_process->ComputeEffectiveImportance());
+ interstitial_process->GetEffectiveImportance());
web_contents()->SetImportance(ChildProcessImportance::MODERATE);
EXPECT_EQ(ChildProcessImportance::MODERATE,
- interstitial_process->ComputeEffectiveImportance());
+ interstitial_process->GetEffectiveImportance());
}
// Tests for Android TouchSelectionEditing.
@@ -10438,6 +10773,60 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
EXPECT_NE(third_shell_instance->GetProcess(), bar_process);
}
+// Check that when a subframe reuses an existing process for the same site
+// across BrowsingInstances, a browser-initiated navigation in that subframe's
+// tab doesn't unnecessarily share the reused process. See
+// https://crbug.com/803367.
+IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
+ NoProcessSharingAfterSubframeReusesExistingProcess) {
+ GURL foo_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
+ EXPECT_TRUE(NavigateToURL(shell(), foo_url));
+ FrameTreeNode* root = web_contents()->GetFrameTree()->root();
+ SiteInstanceImpl* foo_instance =
+ root->current_frame_host()->GetSiteInstance();
+
+ // Open an unrelated tab in a separate BrowsingInstance, and navigate it to
+ // to bar.com.
+ GURL bar_url(
+ embedded_test_server()->GetURL("bar.com", "/page_with_iframe.html"));
+ Shell* second_shell = CreateBrowser();
+ EXPECT_TRUE(NavigateToURL(second_shell, bar_url));
+ FrameTreeNode* second_root =
+ static_cast<WebContentsImpl*>(second_shell->web_contents())
+ ->GetFrameTree()
+ ->root();
+ FrameTreeNode* second_child = second_root->child_at(0);
+ scoped_refptr<SiteInstanceImpl> bar_instance =
+ second_root->current_frame_host()->GetSiteInstance();
+ EXPECT_FALSE(bar_instance->IsRelatedSiteInstance(foo_instance));
+
+ // Navigate the second tab's subframe to foo.com. Confirm that it reuses
+ // first tab's process.
+ NavigateIframeToURL(second_shell->web_contents(), "test_iframe", foo_url);
+ EXPECT_EQ(foo_url, second_child->current_url());
+ scoped_refptr<SiteInstanceImpl> second_child_foo_instance =
+ second_child->current_frame_host()->GetSiteInstance();
+ EXPECT_EQ(
+ SiteInstanceImpl::ProcessReusePolicy::REUSE_PENDING_OR_COMMITTED_SITE,
+ second_child_foo_instance->process_reuse_policy());
+ EXPECT_NE(foo_instance, second_child_foo_instance);
+ EXPECT_EQ(foo_instance->GetProcess(),
+ second_child_foo_instance->GetProcess());
+
+ // Perform a browser-initiated address bar navigation in the second tab to
+ // foo.com. This should swap BrowsingInstances and end up in a separate
+ // process from the first tab.
+ EXPECT_TRUE(NavigateToURL(second_shell, foo_url));
+ SiteInstanceImpl* new_instance =
+ second_root->current_frame_host()->GetSiteInstance();
+ EXPECT_NE(second_child_foo_instance, new_instance);
+ EXPECT_FALSE(second_child_foo_instance->IsRelatedSiteInstance(new_instance));
+ EXPECT_FALSE(bar_instance->IsRelatedSiteInstance(new_instance));
+ EXPECT_FALSE(foo_instance->IsRelatedSiteInstance(new_instance));
+ EXPECT_NE(new_instance->GetProcess(), foo_instance->GetProcess());
+ EXPECT_NE(new_instance->GetProcess(), bar_instance->GetProcess());
+}
+
namespace {
// Intercepts the next DidCommitProvisionalLoad message for |deferred_url| in
@@ -10576,7 +10965,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
CommitMessageOrderReverser commit_order_reverser(
shell()->web_contents(), kSubframeSameSiteUrl /* deferred_url */,
- did_start_deferring_commit_callback);
+ std::move(did_start_deferring_commit_callback));
ASSERT_TRUE(ExecuteScript(shell(), kAddSameSiteDynamicSubframe));
commit_order_reverser.WaitForBothCommits();
@@ -10766,6 +11155,63 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, SizeAvailableAfterCommit) {
EXPECT_GT(height, 0);
}
+// Test that a late swapout ACK won't incorrectly mark RenderViewHost as
+// inactive if it's already been reused and switched to active by another
+// navigation. See https://crbug.com/823567.
+IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
+ RenderViewHostStaysActiveWithLateSwapoutACK) {
+ EXPECT_TRUE(NavigateToURL(
+ shell(), embedded_test_server()->GetURL("a.com", "/title1.html")));
+
+ // Open a popup and navigate it to a.com.
+ Shell* popup = OpenPopup(
+ shell(), embedded_test_server()->GetURL("a.com", "/title2.html"), "foo");
+ WebContentsImpl* popup_contents =
+ static_cast<WebContentsImpl*>(popup->web_contents());
+ RenderFrameHostImpl* rfh = popup_contents->GetMainFrame();
+ RenderViewHostImpl* rvh = rfh->render_view_host();
+
+ // Disable the swapout ACK and the swapout timer.
+ scoped_refptr<SwapoutACKMessageFilter> filter = new SwapoutACKMessageFilter();
+ rfh->GetProcess()->AddFilter(filter.get());
+ rfh->DisableSwapOutTimerForTesting();
+
+ // Navigate popup to b.com. Because there's an opener, the RVH for a.com
+ // stays around in swapped-out state.
+ EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(
+ popup, embedded_test_server()->GetURL("b.com", "/title3.html")));
+ EXPECT_FALSE(rvh->is_active());
+
+ // The old RenderFrameHost is now pending deletion.
+ ASSERT_TRUE(rfh->IsRenderFrameLive());
+ ASSERT_FALSE(rfh->is_active());
+
+ // Kill the b.com process.
+ RenderProcessHost* b_process = popup_contents->GetMainFrame()->GetProcess();
+ RenderProcessHostWatcher crash_observer(
+ b_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
+ b_process->Shutdown(0);
+ crash_observer.Wait();
+
+ // Go back in the popup from b.com to a.com/title2.html. Because the current
+ // b.com RFH is dead, the new RFH is committed right away (without waiting
+ // for renderer to commit), so that users don't need to look at the sad tab.
+ TestNavigationObserver back_observer(popup_contents);
+ popup_contents->GetController().GoBack();
+
+ // Pretend that the original RFH in a.com now finishes running its unload
+ // handler and sends the swapout ACK.
+ rfh->OnSwappedOut();
+
+ // Wait for the new a.com navigation to finish.
+ back_observer.Wait();
+
+ // The RVH for a.com should've been reused, and it should be active. Its
+ // main frame should've been updated to the RFH from the back navigation.
+ EXPECT_EQ(popup_contents->GetMainFrame()->render_view_host(), rvh);
+ EXPECT_TRUE(rvh->is_active());
+ EXPECT_EQ(rvh->GetMainFrame(), popup_contents->GetMainFrame());
+}
// Check that when A opens a new window with B which embeds an A subframe, the
// subframe is visible and generates paint events. See
@@ -10778,14 +11224,6 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
GURL popup_url(embedded_test_server()->GetURL(
"b.com", "/cross_site_iframe_factory.html?b(b)"));
Shell* popup_shell = OpenPopup(shell()->web_contents(), popup_url, "popup");
-
-#if defined(OS_ANDROID)
- // Workaround for https://crbug.com/823493 on Android content shell, where
- // window.open() won't initially show the contents of the new window, and
- // resizing it will force the contents to be shown.
- popup_shell->SizeTo(gfx::Size(500, 500));
-#endif
-
FrameTreeNode* popup_child =
static_cast<WebContentsImpl*>(popup_shell->web_contents())
->GetFrameTree()
@@ -10806,4 +11244,559 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
counter.WaitForNewFrames(10u);
}
+IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, FrameDepthSimple) {
+ // Five nodes, from depth 0 to 4.
+ GURL main_url(embedded_test_server()->GetURL(
+ "a.com", "/cross_site_iframe_factory.html?a(b(c(d(e))))"));
+ const size_t number_of_nodes = 5;
+ EXPECT_TRUE(NavigateToURL(shell(), main_url));
+
+ FrameTreeNode* node = web_contents()->GetFrameTree()->root();
+ for (unsigned int expected_depth = 0; expected_depth < number_of_nodes;
+ ++expected_depth) {
+ CheckFrameDepth(expected_depth, node);
+
+ if (expected_depth + 1 < number_of_nodes)
+ node = node->child_at(0);
+ }
+}
+
+IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, FrameDepthTest) {
+ GURL main_url(embedded_test_server()->GetURL(
+ "a.com", "/cross_site_iframe_factory.html?a(a,b(a))"));
+ EXPECT_TRUE(NavigateToURL(shell(), main_url));
+
+ FrameTreeNode* root = web_contents()->GetFrameTree()->root();
+ CheckFrameDepth(0u, root);
+
+ FrameTreeNode* child0 = root->child_at(0);
+ {
+ EXPECT_EQ(1u, child0->depth());
+ RenderProcessHost::Priority priority =
+ child0->current_frame_host()->GetRenderWidgetHost()->GetPriority();
+ // Same site instance as root.
+ EXPECT_EQ(0u, priority.frame_depth);
+ EXPECT_EQ(
+ 0u,
+ child0->current_frame_host()->GetProcess()->GetFrameDepthForTesting());
+ }
+
+ FrameTreeNode* child1 = root->child_at(1);
+ CheckFrameDepth(1u, child1);
+ // In addition, site b's inactive Widget should not contribute priority.
+ RenderViewHostImpl* child1_rvh =
+ child1->current_frame_host()->render_view_host();
+ EXPECT_FALSE(child1_rvh->is_active());
+ EXPECT_EQ(RenderProcessHostImpl::kMaxFrameDepthForPriority,
+ child1_rvh->GetWidget()->GetPriority().frame_depth);
+ EXPECT_FALSE(static_cast<RenderWidgetHostOwnerDelegate*>(child1_rvh)
+ ->ShouldContributePriorityToProcess());
+
+ FrameTreeNode* grand_child = root->child_at(1)->child_at(0);
+ {
+ EXPECT_EQ(2u, grand_child->depth());
+ RenderProcessHost::Priority priority =
+ grand_child->current_frame_host()->GetRenderWidgetHost()->GetPriority();
+ EXPECT_EQ(2u, priority.frame_depth);
+ // Same process as root
+ EXPECT_EQ(0u, grand_child->current_frame_host()
+ ->GetProcess()
+ ->GetFrameDepthForTesting());
+ }
+}
+
+IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, VisibilityFrameDepthTest) {
+ GURL main_url(embedded_test_server()->GetURL(
+ "a.com", "/cross_site_iframe_factory.html?a(b)"));
+ GURL popup_url(embedded_test_server()->GetURL("b.com", "/title1.html"));
+ EXPECT_TRUE(NavigateToURL(shell(), main_url));
+ FrameTreeNode* root = web_contents()->GetFrameTree()->root();
+ Shell* new_shell = OpenPopup(root->child_at(0), popup_url, "");
+ FrameTreeNode* popup_root =
+ static_cast<WebContentsImpl*>(new_shell->web_contents())
+ ->GetFrameTree()
+ ->root();
+
+ // Subframe and popup share the same process. Both are visible, so depth
+ // should be 0.
+ RenderProcessHost* subframe_process =
+ root->child_at(0)->current_frame_host()->GetProcess();
+ RenderProcessHost* popup_process =
+ popup_root->current_frame_host()->GetProcess();
+ EXPECT_EQ(subframe_process, popup_process);
+ EXPECT_EQ(2, popup_process->VisibleClientCount());
+ EXPECT_EQ(0u, popup_process->GetFrameDepthForTesting());
+
+ // Hide popup. Process should have one visible client and depth should be 1,
+ // since depth 0 popup is hidden.
+ new_shell->web_contents()->WasHidden();
+ EXPECT_EQ(1, popup_process->VisibleClientCount());
+ EXPECT_EQ(1u, popup_process->GetFrameDepthForTesting());
+
+ // Navigate main page to same origin as popup in same BrowsingInstance,
+ // s main page should run in the same process as the popup. The depth on the
+ // process should be 0, from the main frame of main page.
+ EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(shell(), popup_url));
+ // Performing a Load causes aura window to be focused (see
+ // Shell::LoadURLForFrame) which recomputes window occlusion for all windows
+ // (on chromeos) which unhides the popup. Hide popup again.
+ new_shell->web_contents()->WasHidden();
+ RenderProcessHost* new_root_process =
+ root->current_frame_host()->GetProcess();
+ EXPECT_EQ(new_root_process, popup_process);
+ EXPECT_EQ(1, popup_process->VisibleClientCount());
+ EXPECT_EQ(0u, popup_process->GetFrameDepthForTesting());
+
+ // Go back on main page. Should go back to same state as before navigation.
+ TestNavigationObserver back_load_observer(shell()->web_contents());
+ shell()->web_contents()->GetController().GoBack();
+ back_load_observer.Wait();
+ EXPECT_EQ(1, popup_process->VisibleClientCount());
+ EXPECT_EQ(1u, popup_process->GetFrameDepthForTesting());
+
+ // Unhide popup. Should go back to same state as before hide.
+ new_shell->web_contents()->WasShown();
+ EXPECT_EQ(2, popup_process->VisibleClientCount());
+ EXPECT_EQ(0u, popup_process->GetFrameDepthForTesting());
+}
+
+// Ensure that after a main frame with an OOPIF is navigated cross-site, the
+// unload handler in the OOPIF sees correct main frame origin, namely the old
+// and not the new origin. See https://crbug.com/825283.
+IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
+ ParentOriginDoesNotChangeInUnloadHandler) {
+ GURL main_url(embedded_test_server()->GetURL(
+ "a.com", "/cross_site_iframe_factory.html?a(b)"));
+ EXPECT_TRUE(NavigateToURL(shell(), main_url));
+ FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
+ ->GetFrameTree()
+ ->root();
+
+ // Open a popup on b.com. The b.com subframe on the main frame will use this
+ // in its unload handler.
+ GURL b_url(embedded_test_server()->GetURL("b.com", "/title1.html"));
+ EXPECT_TRUE(OpenPopup(shell()->web_contents(), b_url, "popup"));
+
+ // Add an unload handler to b.com subframe, which will look up the top
+ // frame's origin and send it via domAutomationController. Unfortunately,
+ // the subframe's browser-side state will have been torn down when it runs
+ // the unload handler, so to ensure that the message can be received, send it
+ // through the popup.
+ EXPECT_TRUE(
+ ExecuteScript(root->child_at(0),
+ "window.onunload = function(e) {"
+ " window.open('','popup').domAutomationController.send("
+ " 'top-origin ' + location.ancestorOrigins[0]);"
+ "};"));
+
+ // Navigate the main frame to c.com and wait for the message from the
+ // subframe's unload handler.
+ GURL c_url(embedded_test_server()->GetURL("c.com", "/title1.html"));
+ DOMMessageQueue msg_queue;
+ EXPECT_TRUE(NavigateToURL(shell(), c_url));
+ std::string message, top_origin;
+ while (msg_queue.WaitForMessage(&message)) {
+ base::TrimString(message, "\"", &message);
+ auto message_parts = base::SplitString(message, " ", base::TRIM_WHITESPACE,
+ base::SPLIT_WANT_NONEMPTY);
+ if (message_parts[0] == "top-origin") {
+ top_origin = message_parts[1];
+ break;
+ }
+ }
+
+ // The top frame's origin should be a.com, not c.com.
+ EXPECT_EQ(top_origin + "/", main_url.GetOrigin().spec());
+}
+
+// Check that when a postMessage is called on a remote frame, it waits for the
+// current script block to finish executing before forwarding the postMessage,
+// so that if the script causes any other IPCs to be sent in the same event
+// loop iteration, those IPCs are processed, and their side effects are
+// observed by the target frame before it receives the forwarded postMessage.
+// See https://crbug.com/828529.
+IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
+ CrossProcessPostMessageWaitsForCurrentScriptToFinish) {
+ GURL main_url(embedded_test_server()->GetURL(
+ "a.com", "/cross_site_iframe_factory.html?a(b)"));
+ EXPECT_TRUE(NavigateToURL(shell(), main_url));
+ FrameTreeNode* root = web_contents()->GetFrameTree()->root();
+ EXPECT_EQ(root, root->frame_tree()->GetFocusedFrame());
+
+ // Add an onmessage handler to the subframe to send back a bool of whether
+ // the subframe has focus.
+ EXPECT_TRUE(
+ ExecuteScript(root->child_at(0),
+ "window.addEventListener('message', function(event) {\n"
+ " domAutomationController.send(document.hasFocus());\n"
+ "});"));
+
+ // Now, send a postMessage from main frame to subframe, and then focus the
+ // subframe in the same script. postMessage should be scheduled after the
+ // focus() call, so the IPC to focus the subframe should arrive before the
+ // postMessage IPC, and the subframe should already know that it's focused in
+ // the onmessage handler.
+ bool child_has_focus = false;
+ EXPECT_TRUE(ExecuteScriptAndExtractBool(root,
+ "frames[0].postMessage('','*');\n"
+ "frames[0].focus();\n",
+ &child_has_focus));
+ EXPECT_TRUE(child_has_focus);
+}
+
+// Ensure that if a cross-process postMessage is scheduled, and then the target
+// frame is detached before the postMessage is forwarded, the source frame's
+// renderer does not crash.
+IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
+ CrossProcessPostMessageAndDetachTarget) {
+ GURL main_url(embedded_test_server()->GetURL(
+ "a.com", "/cross_site_iframe_factory.html?a(b)"));
+ EXPECT_TRUE(NavigateToURL(shell(), main_url));
+ FrameTreeNode* root = web_contents()->GetFrameTree()->root();
+
+ // Send a postMessage to the subframe and then immediately detach the
+ // subframe.
+ EXPECT_TRUE(ExecuteScript(root,
+ "frames[0].postMessage('','*');\n"
+ "document.body.removeChild(\n"
+ " document.querySelector('iframe'));\n"));
+
+ // Test passes if the main renderer doesn't crash. Use setTimeout to ensure
+ // this ping is evaluated after the (scheduled) postMessage is processed.
+ bool success;
+ EXPECT_TRUE(ExecuteScriptAndExtractBool(
+ root,
+ "setTimeout(() => { window.domAutomationController.send(true); }, 0)",
+ &success));
+ EXPECT_TRUE(success);
+}
+
+// Class to monitor incoming FrameHostMsg_UpdateViewportIntersection messages.
+class UpdateViewportIntersectionMessageFilter
+ : public content::BrowserMessageFilter {
+ public:
+ UpdateViewportIntersectionMessageFilter()
+ : content::BrowserMessageFilter(FrameMsgStart), msg_received_(false) {}
+
+ bool OnMessageReceived(const IPC::Message& message) override {
+ IPC_BEGIN_MESSAGE_MAP(UpdateViewportIntersectionMessageFilter, message)
+ IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateViewportIntersection,
+ OnUpdateViewportIntersection)
+ IPC_END_MESSAGE_MAP()
+ return false;
+ }
+
+ gfx::Rect GetCompositingRect() const { return compositing_rect_; }
+
+ void Wait() {
+ DCHECK(!run_loop_);
+ if (msg_received_) {
+ msg_received_ = false;
+ return;
+ }
+ run_loop_.reset(new base::RunLoop());
+ run_loop_->Run();
+ run_loop_.reset();
+ msg_received_ = false;
+ }
+
+ private:
+ ~UpdateViewportIntersectionMessageFilter() override {}
+
+ void OnUpdateViewportIntersection(const gfx::Rect& viewport_intersection,
+ const gfx::Rect& compositing_rect) {
+ content::BrowserThread::PostTask(
+ content::BrowserThread::UI, FROM_HERE,
+ base::BindOnce(&UpdateViewportIntersectionMessageFilter::
+ OnUpdateViewportIntersectionOnUI,
+ this, compositing_rect));
+ }
+ void OnUpdateViewportIntersectionOnUI(const gfx::Rect& compositing_rect) {
+ compositing_rect_ = compositing_rect;
+ msg_received_ = true;
+ if (run_loop_)
+ run_loop_->Quit();
+ }
+ std::unique_ptr<base::RunLoop> run_loop_;
+ bool msg_received_;
+ gfx::Rect compositing_rect_;
+ DISALLOW_COPY_AND_ASSIGN(UpdateViewportIntersectionMessageFilter);
+};
+
+// Tests that when a large OOPIF has been scaled, the compositor raster area
+// sent from the embedder is correct.
+#if defined(OS_ANDROID)
+// Temporarily disabled on Android because this doesn't account for browser
+// control height or page scale factor.
+#define MAYBE_ScaledIframeRasterSize DISABLED_ScaledframeRasterSize
+#else
+#define MAYBE_ScaledIframeRasterSize ScaledIframeRasterSize
+#endif
+IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
+ MAYBE_ScaledIframeRasterSize) {
+ GURL http_url(embedded_test_server()->GetURL(
+ "a.com", "/frame_tree/page_with_scaled_large_frame.html"));
+ EXPECT_TRUE(NavigateToURL(shell(), http_url));
+
+ FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
+ ->GetFrameTree()
+ ->root();
+
+ scoped_refptr<UpdateViewportIntersectionMessageFilter> filter =
+ new UpdateViewportIntersectionMessageFilter();
+ root->current_frame_host()->GetProcess()->AddFilter(filter.get());
+
+ EXPECT_TRUE(ExecuteScript(
+ root, "document.getElementsByTagName('div')[0].scrollTo(0, 5000);"));
+
+ gfx::Rect compositing_rect;
+ while (compositing_rect.y() == 0) {
+ // Ignore any messages that arrive before the compositing_rect scrolls
+ // away from the origin.
+ filter->Wait();
+ compositing_rect = filter->GetCompositingRect();
+ }
+
+ float scale_factor = 1.0f;
+ if (IsUseZoomForDSFEnabled())
+ scale_factor = GetFrameDeviceScaleFactor(shell()->web_contents());
+
+ // The math below replicates the calculations in
+ // RemoteFrameView::GetCompositingRect(). That could be subject to tweaking,
+ // which would have to be reflected in these test expectations. Also, any
+ // changes to Blink that would affect the size of the frame rect or the
+ // visibile viewport would need to be accounted for.
+ // The multiplication by 5 accounts for the 0.2 scale factor in the test,
+ // which increases the area that has to be drawn in the OOPIF.
+ int view_height = root->current_frame_host()
+ ->GetRenderWidgetHost()
+ ->GetView()
+ ->GetViewBounds()
+ .height() *
+ 5 * scale_factor;
+ int expected_height = view_height * 13 / 10;
+
+ // 185 is the height of the div in the main page after subtracting scroll
+ // bar height.
+ int expected_offset =
+ (5000 * scale_factor) - (expected_height - 185 * scale_factor) / 2;
+
+ // Allow a small amount for rounding differences from applying page and
+ // device scale factors at different times.
+ EXPECT_GE(compositing_rect.height(), expected_height - 2);
+ EXPECT_LE(compositing_rect.height(), expected_height + 2);
+ EXPECT_GE(compositing_rect.y(), expected_offset - 2);
+ EXPECT_LE(compositing_rect.y(), expected_offset + 2);
+}
+
+// Similar to ScaledIFrameRasterSize but with nested OOPIFs to ensure
+// propagation works correctly.
+#if defined(OS_ANDROID)
+// Temporarily disabled on Android because this doesn't account for browser
+// control height or page scale factor.
+#define MAYBE_ScaledNestedIframeRasterSize DISABLED_ScaledNestedIframeRasterSize
+#else
+#define MAYBE_ScaledNestedIframeRasterSize ScaledNestedIframeRasterSize
+#endif
+IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
+ MAYBE_ScaledNestedIframeRasterSize) {
+ GURL http_url(embedded_test_server()->GetURL(
+ "a.com", "/frame_tree/page_with_scaled_large_frames_nested.html"));
+ EXPECT_TRUE(NavigateToURL(shell(), http_url));
+
+ FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
+ ->GetFrameTree()
+ ->root();
+ FrameTreeNode* child = root->child_at(0);
+
+ NavigateFrameToURL(
+ child,
+ embedded_test_server()->GetURL(
+ "bar.com", "/frame_tree/page_with_large_scrollable_frame.html"));
+
+ EXPECT_EQ(
+ " Site A ------------ proxies for B C\n"
+ " +--Site B ------- proxies for A C\n"
+ " +--Site C -- proxies for A B\n"
+ "Where A = http://a.com/\n"
+ " B = http://bar.com/\n"
+ " C = http://baz.com/",
+ DepictFrameTree(root));
+
+ // This adds the filter to the immediate child iframe. It verifies that the
+ // child sets the nested iframe's compositing rect correctly.
+ scoped_refptr<UpdateViewportIntersectionMessageFilter> filter =
+ new UpdateViewportIntersectionMessageFilter();
+ child->current_frame_host()->GetProcess()->AddFilter(filter.get());
+
+ // This scrolls the div containing in the 'Site B' iframe that contains the
+ // 'Site C' iframe, and then we verify that the 'Site C' frame receives the
+ // correct compositor frame.
+ EXPECT_TRUE(ExecuteScript(
+ child, "document.getElementsByTagName('div')[0].scrollTo(0, 5000);"));
+
+ gfx::Rect compositing_rect;
+ while (compositing_rect.y() == 0) {
+ // Ignore any messages that arrive before the compositing_rect scrolls
+ // away from the origin.
+ filter->Wait();
+ compositing_rect = filter->GetCompositingRect();
+ }
+
+ float scale_factor = 1.0f;
+ if (IsUseZoomForDSFEnabled())
+ scale_factor = GetFrameDeviceScaleFactor(shell()->web_contents());
+
+ // See comment in ScaledIframeRasterSize for explanation of this. In this
+ // case, the raster area of the large iframe should be restricted to
+ // approximately the area of the smaller iframe in which it is embedded.
+ int view_height = child->current_frame_host()
+ ->GetRenderWidgetHost()
+ ->GetView()
+ ->GetViewBounds()
+ .height() *
+ scale_factor +
+ 5;
+ int expected_height = view_height * 13 / 10;
+ int expected_offset =
+ (5000 * scale_factor) - (expected_height - 185 * scale_factor) / 2;
+
+ // Allow a small amount for rounding differences from applying page and
+ // device scale factors at different times.
+ EXPECT_GE(compositing_rect.height(), expected_height - 2);
+ EXPECT_LE(compositing_rect.height(), expected_height + 2);
+ EXPECT_GE(compositing_rect.y(), expected_offset - 2);
+ EXPECT_LE(compositing_rect.y(), expected_offset + 2);
+}
+
+// Verify that OOPIF select element popup menu coordinates account for scroll
+// offset in containers embedding frame.
+IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, PopupMenuInTallIframeTest) {
+ GURL main_url(embedded_test_server()->GetURL(
+ "/frame_tree/page_with_tall_positioned_frame.html"));
+ EXPECT_TRUE(NavigateToURL(shell(), main_url));
+
+ FrameTreeNode* root = web_contents()->GetFrameTree()->root();
+ FrameTreeNode* child_node = root->child_at(0);
+ GURL site_url(embedded_test_server()->GetURL(
+ "baz.com", "/site_isolation/page-with-select.html"));
+ NavigateFrameToURL(child_node, site_url);
+
+ scoped_refptr<UpdateViewportIntersectionMessageFilter> filter =
+ new UpdateViewportIntersectionMessageFilter();
+ root->current_frame_host()->GetProcess()->AddFilter(filter.get());
+
+ // Position the select element so that it is out of the viewport, then scroll
+ // it into view.
+ EXPECT_TRUE(ExecuteScript(
+ child_node, "document.querySelector('select').style.top='2000px';"));
+ EXPECT_TRUE(ExecuteScript(root, "window.scrollTo(0, 1900);"));
+
+ // Wait for a viewport intersection update to be dispatched to the child, and
+ // ensure it is processed by the browser before continuing.
+ filter->Wait();
+ {
+ // This yields the UI thread in order to ensure that the new viewport
+ // intersection is sent to the to child renderer before the mouse click
+ // below.
+ base::RunLoop loop;
+ base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
+ loop.QuitClosure());
+ loop.Run();
+ }
+
+ scoped_refptr<ShowWidgetMessageFilter> show_widget_filter =
+ new ShowWidgetMessageFilter();
+ child_node->current_frame_host()->GetProcess()->AddFilter(
+ show_widget_filter.get());
+
+ SimulateMouseClick(child_node->current_frame_host()->GetRenderWidgetHost(),
+ 55, 2005);
+
+ // Dismiss the popup.
+ SimulateMouseClick(child_node->current_frame_host()->GetRenderWidgetHost(), 1,
+ 1);
+
+ // The test passes if this wait returns, indicating that the popup was
+ // scrolled into view and the OOPIF renderer displayed it. Other tests verify
+ // the correctness of popup menu coordinates.
+ show_widget_filter->Wait();
+}
+
+namespace {
+
+// Helper class to intercept DidCommitProvisionalLoad messages and inject a
+// call to close the current tab right before them.
+class ClosePageBeforeCommitHelper : public DidCommitProvisionalLoadInterceptor {
+ public:
+ explicit ClosePageBeforeCommitHelper(WebContents* web_contents)
+ : DidCommitProvisionalLoadInterceptor(web_contents) {}
+
+ void Wait() {
+ run_loop_.reset(new base::RunLoop());
+ run_loop_->Run();
+ run_loop_.reset();
+ }
+
+ private:
+ // DidCommitProvisionalLoadInterceptor:
+ void WillDispatchDidCommitProvisionalLoad(
+ RenderFrameHost* render_frame_host,
+ ::FrameHostMsg_DidCommitProvisionalLoad_Params* params,
+ service_manager::mojom::InterfaceProviderRequest*
+ interface_provider_request) override {
+ RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>(
+ render_frame_host->GetRenderViewHost());
+ EXPECT_TRUE(rvh->is_active());
+ rvh->ClosePage();
+ if (run_loop_)
+ run_loop_->Quit();
+ }
+
+ std::unique_ptr<base::RunLoop> run_loop_;
+
+ DISALLOW_COPY_AND_ASSIGN(ClosePageBeforeCommitHelper);
+};
+
+} // namespace
+
+// Verify that when a tab is closed just before a commit IPC arrives for a
+// subframe in the tab, a subsequent resource timing IPC from the subframe RFH
+// won't generate a renderer kill. See https://crbug.com/805705.
+IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
+ CloseTabBeforeSubframeCommits) {
+ GURL main_url(embedded_test_server()->GetURL(
+ "a.com", "/cross_site_iframe_factory.html?a(b)"));
+ EXPECT_TRUE(NavigateToURL(shell(), main_url));
+ FrameTreeNode* root = web_contents()->GetFrameTree()->root();
+
+ // Open a popup in a.com to keep that process alive.
+ GURL same_site_url(embedded_test_server()->GetURL("a.com", "/title1.html"));
+ Shell* new_shell = OpenPopup(root, same_site_url, "");
+
+ // Add a blank grandchild frame.
+ RenderFrameHostCreatedObserver frame_observer(shell()->web_contents(), 1);
+ EXPECT_TRUE(ExecuteScript(
+ root->child_at(0),
+ "document.body.appendChild(document.createElement('iframe'));"));
+ frame_observer.Wait();
+ FrameTreeNode* grandchild = root->child_at(0)->child_at(0);
+
+ // Navigate grandchild to an a.com URL. Note that only a frame's initial
+ // navigation forwards resource timing info to parent, so it's important that
+ // this iframe was initially blank.
+ //
+ // Just before this URL commits, close the page.
+ ClosePageBeforeCommitHelper close_page_helper(web_contents());
+ EXPECT_TRUE(
+ ExecuteScript(grandchild, "location = '" + same_site_url.spec() + "';"));
+ close_page_helper.Wait();
+
+ // Test passes if the a.com renderer doesn't crash. Ping to verify.
+ bool success;
+ EXPECT_TRUE(ExecuteScriptAndExtractBool(
+ new_shell, "window.domAutomationController.send(true);", &success));
+ EXPECT_TRUE(success);
+}
+
} // namespace content
diff --git a/chromium/content/browser/site_per_process_hit_test_browsertest.cc b/chromium/content/browser/site_per_process_hit_test_browsertest.cc
index 70bcad9c09c..f758815ac57 100644
--- a/chromium/content/browser/site_per_process_hit_test_browsertest.cc
+++ b/chromium/content/browser/site_per_process_hit_test_browsertest.cc
@@ -20,10 +20,12 @@
#include "content/browser/renderer_host/render_widget_host_view_child_frame.h"
#include "content/common/frame_messages.h"
#include "content/common/view_messages.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/screen_info.h"
#include "content/public/common/use_zoom_for_dsf_policy.h"
+#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_utils.h"
@@ -107,38 +109,71 @@ class TestInputEventObserver : public RenderWidgetHost::InputEventObserver {
event_ = ui::WebInputEventTraits::Clone(event);
};
+ const std::vector<InputEventAckSource>& events_acked() {
+ return events_acked_;
+ }
+
+ void OnInputEventAck(InputEventAckSource source,
+ InputEventAckState state,
+ const blink::WebInputEvent&) override {
+ events_acked_.push_back(source);
+ }
+
private:
RenderWidgetHost* host_;
std::vector<blink::WebInputEvent::Type> events_received_;
+ std::vector<InputEventAckSource> events_acked_;
ui::WebScopedInputEvent event_;
DISALLOW_COPY_AND_ASSIGN(TestInputEventObserver);
};
// |position_in_widget| is in the coord space of |rwhv|.
+template <typename PointType>
void SetWebEventPositions(blink::WebPointerProperties* event,
- const gfx::PointF& position_in_widget,
- RenderWidgetHostViewBase* rwhv) {
- event->SetPositionInWidget(position_in_widget.x(), position_in_widget.y());
+ const PointType& position_in_widget,
+ RenderWidgetHostViewBase* rwhv,
+ RenderWidgetHostViewBase* rwhv_root) {
+ event->SetPositionInWidget(gfx::PointF(position_in_widget));
+ const gfx::PointF position_in_root =
+ rwhv->TransformPointToRootCoordSpaceF(event->PositionInWidget());
const gfx::PointF point_in_screen =
- event->PositionInWidget() + rwhv->GetViewBounds().OffsetFromOrigin();
+ position_in_root + rwhv_root->GetViewBounds().OffsetFromOrigin();
event->SetPositionInScreen(point_in_screen.x(), point_in_screen.y());
}
+// For convenience when setting the position in the space of the root RWHV.
+template <typename PointType>
void SetWebEventPositions(blink::WebPointerProperties* event,
- const gfx::Point& position_in_widget,
- RenderWidgetHostViewBase* rwhv) {
- SetWebEventPositions(event, gfx::PointF(position_in_widget), rwhv);
+ const PointType& position_in_widget,
+ RenderWidgetHostViewBase* rwhv_root) {
+ DCHECK(!rwhv_root->IsRenderWidgetHostViewChildFrame());
+ SetWebEventPositions(event, position_in_widget, rwhv_root, rwhv_root);
}
-#if !defined(OS_MACOSX) && !defined(OS_ANDROID)
+#if defined(USE_AURA)
// |event->location()| is in the coord space of |rwhv|.
void UpdateEventRootLocation(ui::LocatedEvent* event,
- RenderWidgetHostViewBase* rwhv) {
- event->set_root_location(event->location() +
- rwhv->GetViewBounds().OffsetFromOrigin());
+ RenderWidgetHostViewBase* rwhv,
+ RenderWidgetHostViewBase* rwhv_root) {
+ const gfx::Point position_in_root =
+ rwhv->TransformPointToRootCoordSpace(event->location());
+
+ gfx::Point root_location = position_in_root;
+ aura::Window::ConvertPointToTarget(
+ rwhv_root->GetNativeView(), rwhv_root->GetNativeView()->GetRootWindow(),
+ &root_location);
+
+ event->set_root_location(root_location);
}
-#endif
+
+// For convenience when setting the position in the space of the root RWHV.
+void UpdateEventRootLocation(ui::LocatedEvent* event,
+ RenderWidgetHostViewBase* rwhv_root) {
+ DCHECK(!rwhv_root->IsRenderWidgetHostViewChildFrame());
+ UpdateEventRootLocation(event, rwhv_root, rwhv_root);
+}
+#endif // defined(USE_AURA)
void RouteMouseEventAndWaitUntilDispatch(
RenderWidgetHostInputEventRouter* router,
@@ -437,7 +472,7 @@ bool ConvertJSONToRect(const std::string& str, gfx::Rect* rect) {
} // namespace
class SitePerProcessHitTestBrowserTest
- : public testing::WithParamInterface<std::tuple<bool, float>>,
+ : public testing::WithParamInterface<std::tuple<int, float>>,
public SitePerProcessBrowserTest {
public:
SitePerProcessHitTestBrowserTest() {}
@@ -445,8 +480,11 @@ class SitePerProcessHitTestBrowserTest
protected:
void SetUpCommandLine(base::CommandLine* command_line) override {
SitePerProcessBrowserTest::SetUpCommandLine(command_line);
- if (std::get<0>(GetParam())) {
+ if (std::get<0>(GetParam()) == 1) {
feature_list_.InitAndEnableFeature(features::kEnableVizHitTestDrawQuad);
+ } else if (std::get<0>(GetParam()) == 2) {
+ feature_list_.InitAndEnableFeature(
+ features::kEnableVizHitTestSurfaceLayer);
}
}
@@ -601,20 +639,10 @@ IN_PROC_BROWSER_TEST_P(SitePerProcessInternalsHitTestBrowserTest,
&div_scroll_top_start));
EXPECT_EQ(0.0, div_scroll_top_start);
- // Wait until renderer's compositor thread is synced. Otherwise the event
- // handler won't be installed when the event arrives.
- MainThreadFrameObserver observer(rwhv_root->GetRenderWidgetHost());
+ // Wait until renderer's compositor thread is synced. Otherwise the non fast
+ // scrollable regions won't be set when the event arrives.
+ MainThreadFrameObserver observer(rwhv_nested->GetRenderWidgetHost());
observer.Wait();
- {
- base::RunLoop run_loop;
- base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
- FROM_HERE, run_loop.QuitClosure(),
- // tiny_timeout() is too small to run without flakes, but
- // action_timeout() is 100 times bigger, which is overkill. We use a
- // custom delay here to achieve a balance.
- base::TimeDelta::FromMilliseconds(1000));
- run_loop.Run();
- }
// Send a wheel to scroll the div.
gfx::Point location(point_f.x(), point_f.y());
@@ -624,11 +652,11 @@ IN_PROC_BROWSER_TEST_P(SitePerProcessInternalsHitTestBrowserTest,
2); // This must be '2' or it gets silently
// dropped.
UpdateEventRootLocation(&scroll_event, rwhv_root);
- rwhv_root->OnScrollEvent(&scroll_event);
InputEventAckWaiter ack_observer(
parent_iframe_node->current_frame_host()->GetRenderWidgetHost(),
blink::WebInputEvent::kGestureScrollUpdate);
+ rwhv_root->OnScrollEvent(&scroll_event);
ack_observer.Wait();
// Check compositor layers.
@@ -759,21 +787,6 @@ IN_PROC_BROWSER_TEST_P(SitePerProcessInternalsHitTestBrowserTest,
&div_scroll_top_start));
EXPECT_EQ(0.0, div_scroll_top_start);
- // Wait until renderer's compositor thread is synced. Otherwise the event
- // handler won't be installed when the event arrives.
- MainThreadFrameObserver observer(rwhv_root->GetRenderWidgetHost());
- observer.Wait();
- {
- base::RunLoop run_loop;
- base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
- FROM_HERE, run_loop.QuitClosure(),
- // tiny_timeout() is too small to run without flakes, but
- // action_timeout() is 100 times bigger, which is overkill. We use a
- // custom delay here to achieve a balance.
- base::TimeDelta::FromMilliseconds(1000));
- run_loop.Run();
- }
-
// Send a wheel to scroll the parent containing the div.
gfx::Point location(point_f.x(), point_f.y());
ui::ScrollEvent scroll_event(ui::ET_SCROLL, location, ui::EventTimeForNow(),
@@ -782,13 +795,16 @@ IN_PROC_BROWSER_TEST_P(SitePerProcessInternalsHitTestBrowserTest,
2); // This must be '2' or it gets silently
// dropped.
UpdateEventRootLocation(&scroll_event, rwhv_root);
- rwhv_root->OnScrollEvent(&scroll_event);
InputEventAckWaiter ack_observer(
parent_iframe_node->current_frame_host()->GetRenderWidgetHost(),
blink::WebInputEvent::kGestureScrollUpdate);
+ rwhv_root->OnScrollEvent(&scroll_event);
ack_observer.Wait();
+ MainThreadFrameObserver thread_observer(rwhv_parent->GetRenderWidgetHost());
+ thread_observer.Wait();
+
// Check compositor layers.
EXPECT_TRUE(ExecuteScriptAndExtractString(
nested_iframe_node->current_frame_host(),
@@ -897,7 +913,7 @@ IN_PROC_BROWSER_TEST_P(SitePerProcessHitTestBrowserTest,
iframe_node->current_frame_host()->GetSiteInstance()->GetProcess();
RenderProcessHostWatcher crash_observer(
rph, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
- EXPECT_TRUE(rph->Shutdown(0, false));
+ EXPECT_TRUE(rph->Shutdown(0));
crash_observer.Wait();
scroll_event.delta_y = 0.0f;
scroll_event.phase = blink::WebMouseWheelEvent::kPhaseEnded;
@@ -951,8 +967,10 @@ IN_PROC_BROWSER_TEST_P(SitePerProcessHitTestBrowserTest,
const blink::WebGestureEvent& gesture_event =
static_cast<const blink::WebGestureEvent&>(event);
- EXPECT_NEAR(expected_position.x(), gesture_event.x, 1);
- EXPECT_NEAR(expected_position.y(), gesture_event.y, 1);
+ EXPECT_NEAR(expected_position.x(), gesture_event.PositionInWidget().x,
+ 1);
+ EXPECT_NEAR(expected_position.y(), gesture_event.PositionInWidget().y,
+ 1);
return true;
});
@@ -1018,8 +1036,8 @@ IN_PROC_BROWSER_TEST_P(SitePerProcessHitTestBrowserTest,
WaitForChildFrameSurfaceReady(child_node->current_frame_host());
- ASSERT_EQ(gfx::Vector2dF(), rwhv_root->GetLastScrollOffset());
- ASSERT_EQ(gfx::Vector2dF(), rwhv_child->GetLastScrollOffset());
+ ASSERT_TRUE(rwhv_root->IsScrollOffsetAtTop());
+ ASSERT_TRUE(rwhv_child->IsScrollOffsetAtTop());
RenderWidgetHostInputEventRouter* router =
static_cast<WebContentsImpl*>(shell()->web_contents())
@@ -1057,8 +1075,8 @@ IN_PROC_BROWSER_TEST_P(SitePerProcessHitTestBrowserTest,
blink::WebGestureEvent gesture_event(
blink::WebInputEvent::kGestureTapDown,
blink::WebInputEvent::kNoModifiers,
- blink::WebInputEvent::GetStaticTimeStampForTests());
- gesture_event.source_device = blink::kWebGestureDeviceTouchscreen;
+ blink::WebInputEvent::GetStaticTimeStampForTests(),
+ blink::kWebGestureDeviceTouchscreen);
gesture_event.unique_touch_event_id = touch_event.unique_touch_event_id;
router->RouteGestureEvent(rwhv_root, &gesture_event,
ui::LatencyInfo(ui::SourceEventType::TOUCH));
@@ -1103,8 +1121,8 @@ IN_PROC_BROWSER_TEST_P(SitePerProcessHitTestBrowserTest,
blink::WebGestureEvent gesture_scroll_begin(
blink::WebGestureEvent::kGestureScrollBegin,
blink::WebInputEvent::kNoModifiers,
- blink::WebInputEvent::GetStaticTimeStampForTests());
- gesture_scroll_begin.source_device = blink::kWebGestureDeviceTouchscreen;
+ blink::WebInputEvent::GetStaticTimeStampForTests(),
+ blink::kWebGestureDeviceTouchscreen);
gesture_scroll_begin.unique_touch_event_id = 1;
gesture_scroll_begin.data.scroll_begin.delta_hint_units =
blink::WebGestureEvent::ScrollUnits::kPrecisePixels;
@@ -1128,8 +1146,8 @@ IN_PROC_BROWSER_TEST_P(SitePerProcessHitTestBrowserTest,
blink::WebGestureEvent gesture_scroll_update(
blink::WebGestureEvent::kGestureScrollUpdate,
blink::WebInputEvent::kNoModifiers,
- blink::WebInputEvent::GetStaticTimeStampForTests());
- gesture_scroll_update.source_device = blink::kWebGestureDeviceTouchscreen;
+ blink::WebInputEvent::GetStaticTimeStampForTests(),
+ blink::kWebGestureDeviceTouchscreen);
gesture_scroll_update.unique_touch_event_id = 1;
gesture_scroll_update.data.scroll_update.delta_units =
blink::WebGestureEvent::ScrollUnits::kPrecisePixels;
@@ -1169,8 +1187,8 @@ IN_PROC_BROWSER_TEST_P(SitePerProcessHitTestBrowserTest,
blink::WebGestureEvent gesture_scroll_end(
blink::WebGestureEvent::kGestureScrollEnd,
blink::WebInputEvent::kNoModifiers,
- blink::WebInputEvent::GetStaticTimeStampForTests());
- gesture_scroll_end.source_device = blink::kWebGestureDeviceTouchscreen;
+ blink::WebInputEvent::GetStaticTimeStampForTests(),
+ blink::kWebGestureDeviceTouchscreen);
gesture_scroll_end.unique_touch_event_id = 1;
gesture_scroll_end.data.scroll_end.delta_units =
blink::WebGestureEvent::ScrollUnits::kPrecisePixels;
@@ -1387,6 +1405,79 @@ IN_PROC_BROWSER_TEST_P(SitePerProcessHighDPIHitTestBrowserTest,
HitTestWatermark(shell(), embedded_test_server());
}
+IN_PROC_BROWSER_TEST_P(SitePerProcessHitTestBrowserTest,
+ HitTestStaleDataDeletedView) {
+ // Have two iframes to avoid going to short circuit path during the second
+ // targeting.
+ GURL main_url(
+ embedded_test_server()->GetURL("/frame_tree/page_with_two_iframes.html"));
+ EXPECT_TRUE(NavigateToURL(shell(), main_url));
+
+ // It is safe to obtain the root frame tree node here, as it doesn't change.
+ auto* web_contents = static_cast<WebContentsImpl*>(shell()->web_contents());
+ FrameTreeNode* root = web_contents->GetFrameTree()->root();
+ ASSERT_EQ(2U, root->child_count());
+
+ FrameTreeNode* child_node1 = root->child_at(0);
+ GURL site_url1(embedded_test_server()->GetURL("bar.com", "/title1.html"));
+ EXPECT_EQ(site_url1, child_node1->current_url());
+ EXPECT_NE(shell()->web_contents()->GetSiteInstance(),
+ child_node1->current_frame_host()->GetSiteInstance());
+
+ FrameTreeNode* child_node2 = root->child_at(1);
+ GURL site_url2(embedded_test_server()->GetURL("baz.com", "/title1.html"));
+ EXPECT_EQ(site_url2, child_node2->current_url());
+ EXPECT_NE(shell()->web_contents()->GetSiteInstance(),
+ child_node2->current_frame_host()->GetSiteInstance());
+
+ RenderWidgetHostImpl* root_rwh = static_cast<RenderWidgetHostImpl*>(
+ root->current_frame_host()->GetRenderWidgetHost());
+ RenderWidgetHostViewBase* rwhv_parent =
+ static_cast<RenderWidgetHostViewBase*>(root_rwh->GetView());
+ RenderWidgetHostViewBase* rwhv_child2 =
+ static_cast<RenderWidgetHostViewBase*>(
+ child_node2->current_frame_host()->GetRenderWidgetHost()->GetView());
+
+ WaitForChildFrameSurfaceReady(child_node1->current_frame_host());
+ WaitForChildFrameSurfaceReady(child_node2->current_frame_host());
+
+ const gfx::PointF child_location(50, 50);
+ gfx::PointF parent_location =
+ rwhv_child2->TransformPointToRootCoordSpaceF(child_location);
+ // Send a mouse-down at the center of the child2. This should go to the
+ // child2.
+ DispatchMouseEventAndWaitUntilDispatch(
+ web_contents, rwhv_parent, parent_location, rwhv_child2, child_location);
+
+ // Remove the iframe from the page. Add an infinite loop at the end so that
+ // renderer wouldn't submit updated hit-test data.
+ FrameDeletedObserver delete_observer(child_node2->current_frame_host());
+ ExecuteScriptAsync(
+ root,
+ "document.body.removeChild(document.getElementsByName('frame2')[0]);"
+ "while(true) {}");
+ delete_observer.Wait();
+ EXPECT_EQ(1U, root->child_count());
+
+ // The synchronous targeting for the same location should now find the
+ // root-view as the target (and require async-targeting), since child2 has
+ // been removed. We cannot actually attempt to dispatch the event though,
+ // since it would try to do asynchronous targeting by asking the root-view,
+ // whose main-thread is blocked because of the infinite-loop in the injected
+ // javascript above.
+ blink::WebMouseEvent down_event(
+ blink::WebInputEvent::kMouseDown, blink::WebInputEvent::kNoModifiers,
+ blink::WebInputEvent::GetStaticTimeStampForTests());
+ down_event.button = blink::WebPointerProperties::Button::kLeft;
+ down_event.click_count = 1;
+ SetWebEventPositions(&down_event, parent_location, rwhv_parent);
+ auto result = web_contents->GetInputEventRouter()->FindTargetSynchronously(
+ rwhv_parent, down_event);
+ EXPECT_EQ(result.view, rwhv_parent);
+ EXPECT_TRUE(result.should_query_view);
+ EXPECT_EQ(result.target_location.value(), parent_location);
+}
+
// This test tests that browser process hittesting ignores frames with
// pointer-events: none.
IN_PROC_BROWSER_TEST_P(SitePerProcessHitTestBrowserTest,
@@ -1491,6 +1582,142 @@ IN_PROC_BROWSER_TEST_P(SitePerProcessHitTestBrowserTest,
EXPECT_FALSE(child_frame_monitor.EventWasReceived());
}
+// Tooltips aren't used on Android, so no need to compile/run this test in that
+// case.
+#if !defined(OS_ANDROID)
+class TooltipMonitor : public CursorManager::TooltipObserver {
+ public:
+ TooltipMonitor(CursorManager* cursor_manager) : run_loop_(new base::RunLoop) {
+ DCHECK(cursor_manager);
+ cursor_manager->SetTooltipObserverForTesting(this);
+ }
+ ~TooltipMonitor() override {}
+
+ void Reset() {
+ run_loop_.reset(new base::RunLoop);
+ tooltips_received_.clear();
+ }
+
+ void OnSetTooltipTextForView(const RenderWidgetHostViewBase* view,
+ const base::string16& tooltip_text) override {
+ tooltips_received_.push_back(tooltip_text);
+ if (tooltip_text == tooltip_text_wanted_ && run_loop_->running())
+ run_loop_->Quit();
+ }
+
+ void WaitUntil(const base::string16& tooltip_text) {
+ tooltip_text_wanted_ = tooltip_text;
+ auto it = std::find(tooltips_received_.begin(), tooltips_received_.end(),
+ tooltip_text);
+ if (it != tooltips_received_.end())
+ return;
+ run_loop_->Run();
+ }
+
+ private:
+ std::unique_ptr<base::RunLoop> run_loop_;
+ base::string16 tooltip_text_wanted_;
+ std::vector<base::string16> tooltips_received_;
+
+ DISALLOW_COPY_AND_ASSIGN(TooltipMonitor);
+}; // class TooltipMonitor
+
+IN_PROC_BROWSER_TEST_P(SitePerProcessHitTestBrowserTest,
+ CrossProcessTooltipTest) {
+ GURL main_url(embedded_test_server()->GetURL(
+ "a.com", "/cross_site_iframe_factory.html?a(b)"));
+ EXPECT_TRUE(NavigateToURL(shell(), main_url));
+
+ FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
+ ->GetFrameTree()
+ ->root();
+
+ EXPECT_EQ(
+ " Site A ------------ proxies for B\n"
+ " +--Site B ------- proxies for A\n"
+ "Where A = http://a.com/\n"
+ " B = http://b.com/",
+ DepictFrameTree(root));
+
+ FrameTreeNode* b_node = root->child_at(0);
+
+ RenderWidgetHostViewBase* rwhv_a = static_cast<RenderWidgetHostViewBase*>(
+ root->current_frame_host()->GetRenderWidgetHost()->GetView());
+ RenderWidgetHostViewBase* rwhv_b = static_cast<RenderWidgetHostViewBase*>(
+ b_node->current_frame_host()->GetRenderWidgetHost()->GetView());
+
+ DCHECK(rwhv_a->GetCursorManager());
+
+ TooltipMonitor tooltip_monitor(rwhv_a->GetCursorManager());
+
+ WaitForChildFrameSurfaceReady(b_node->current_frame_host());
+
+ // Make sure the point_in_a_frame value is outside the default 8px margin
+ // for the body element.
+ gfx::Point point_in_a_frame(10, 10);
+ gfx::Point point_in_b_frame =
+ rwhv_b->TransformPointToRootCoordSpace(gfx::Point(25, 25));
+
+ // Create listeners for mouse events. These are used to verify that the
+ // RenderWidgetHostInputEventRouter is generating MouseLeave, etc for
+ // the right renderers.
+ RenderWidgetHostMouseEventMonitor a_frame_monitor(
+ root->current_frame_host()->GetRenderWidgetHost());
+ RenderWidgetHostMouseEventMonitor b_frame_monitor(
+ b_node->current_frame_host()->GetRenderWidgetHost());
+
+ // Add tooltip text to both the body and the iframe in A.
+ std::string script =
+ "body = document.body.setAttribute('title', 'body_tooltip');\n"
+ "iframe = document.getElementsByTagName('iframe')[0];\n"
+ "iframe.setAttribute('title','iframe_for_b');";
+ EXPECT_TRUE(ExecuteScript(root->current_frame_host(), script));
+
+ // Send mouse events to both A and B.
+ blink::WebMouseEvent mouse_event(
+ blink::WebInputEvent::kMouseMove, blink::WebInputEvent::kNoModifiers,
+ blink::WebInputEvent::GetStaticTimeStampForTests());
+ auto* router = web_contents()->GetInputEventRouter();
+
+ // Alternate mouse moves between main frame and the cross-process iframe to
+ // test that the tool tip in the iframe can override the one set by the main
+ // frame renderer, even on a second entry into the iframe.
+ gfx::Point current_point;
+ for (int iteration = 0; iteration < 2; ++iteration) {
+ // The following is a bit of a hack to prevent hitting the same
+ // position/node check in ChromeClient::SetToolTip().
+ current_point = point_in_a_frame;
+ current_point.Offset(iteration, iteration);
+ SetWebEventPositions(&mouse_event, current_point, rwhv_a);
+ RouteMouseEventAndWaitUntilDispatch(router, rwhv_a, rwhv_a, &mouse_event);
+ EXPECT_TRUE(a_frame_monitor.EventWasReceived());
+ a_frame_monitor.ResetEventReceived();
+ // B will receive a mouseLeave on all but the first iteration.
+ EXPECT_EQ(iteration != 0, b_frame_monitor.EventWasReceived());
+ b_frame_monitor.ResetEventReceived();
+
+ tooltip_monitor.WaitUntil(base::UTF8ToUTF16("body_tooltip"));
+ tooltip_monitor.Reset();
+
+ // Next send a MouseMove to B frame, and A should receive a MouseMove event.
+ current_point = point_in_b_frame;
+ current_point.Offset(iteration, iteration);
+ SetWebEventPositions(&mouse_event, current_point, rwhv_a);
+ RouteMouseEventAndWaitUntilDispatch(router, rwhv_a, rwhv_b, &mouse_event);
+ EXPECT_TRUE(a_frame_monitor.EventWasReceived());
+ EXPECT_EQ(a_frame_monitor.event().GetType(),
+ blink::WebInputEvent::kMouseMove);
+ a_frame_monitor.ResetEventReceived();
+ EXPECT_TRUE(b_frame_monitor.EventWasReceived());
+ b_frame_monitor.ResetEventReceived();
+ tooltip_monitor.WaitUntil(base::string16());
+ tooltip_monitor.Reset();
+ }
+
+ rwhv_a->GetCursorManager()->SetTooltipObserverForTesting(nullptr);
+}
+#endif // !defined(OS_ANDROID)
+
// This test verifies that MouseEnter and MouseLeave events fire correctly
// when the mouse cursor moves between processes.
IN_PROC_BROWSER_TEST_P(SitePerProcessHitTestBrowserTest,
@@ -1987,6 +2214,7 @@ class SitePerProcessMouseWheelHitTestBrowserTest
if (base::FeatureList::IsEnabled(features::kAsyncWheelEvents) &&
base::FeatureList::IsEnabled(
features::kTouchpadAndWheelScrollLatching)) {
+ DCHECK(rwhv_root->wheel_scroll_latching_enabled());
EXPECT_TRUE(msg_queue.WaitForMessage(&reply));
EXPECT_EQ("\"scroll: 2\"", reply);
}
@@ -2001,17 +2229,30 @@ class SitePerProcessMouseWheelHitTestBrowserTest
EXPECT_EQ("\"scroll: 3\"", reply);
}
- protected:
- base::test::ScopedFeatureList feature_list_;
-
private:
RenderWidgetHostViewAura* rwhv_root_;
};
-IN_PROC_BROWSER_TEST_P(SitePerProcessMouseWheelHitTestBrowserTest,
- MultipleSubframeWheelEventsOnMainThread) {
- feature_list_.InitWithFeatures({}, {features::kTouchpadAndWheelScrollLatching,
- features::kAsyncWheelEvents});
+// Subclass to disable wheel scroll latching in failing tests.
+// https://crbug.com/800822
+class SitePerProcessMouseWheelHitTestBrowserTestWheelScrollLatchingDisabled
+ : public SitePerProcessMouseWheelHitTestBrowserTest {
+ public:
+ SitePerProcessMouseWheelHitTestBrowserTestWheelScrollLatchingDisabled() {}
+ void SetUp() override {
+ feature_list_.InitWithFeatures({},
+ {features::kTouchpadAndWheelScrollLatching,
+ features::kAsyncWheelEvents});
+ SitePerProcessMouseWheelHitTestBrowserTest::SetUp();
+ }
+
+ private:
+ base::test::ScopedFeatureList feature_list_;
+};
+
+IN_PROC_BROWSER_TEST_P(
+ SitePerProcessMouseWheelHitTestBrowserTestWheelScrollLatchingDisabled,
+ MultipleSubframeWheelEventsOnMainThread) {
GURL main_url(embedded_test_server()->GetURL(
"/frame_tree/page_with_two_positioned_frames.html"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
@@ -2051,10 +2292,9 @@ IN_PROC_BROWSER_TEST_P(SitePerProcessMouseWheelHitTestBrowserTest,
// Verifies that test in SubframeWheelEventsOnMainThread also makes sense for
// the same page loaded in the mainframe.
-IN_PROC_BROWSER_TEST_P(SitePerProcessMouseWheelHitTestBrowserTest,
- MainframeWheelEventsOnMainThread) {
- feature_list_.InitWithFeatures({}, {features::kTouchpadAndWheelScrollLatching,
- features::kAsyncWheelEvents});
+IN_PROC_BROWSER_TEST_P(
+ SitePerProcessMouseWheelHitTestBrowserTestWheelScrollLatchingDisabled,
+ MainframeWheelEventsOnMainThread) {
GURL main_url(
embedded_test_server()->GetURL("/page_with_scrollable_div.html"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
@@ -2128,7 +2368,7 @@ IN_PROC_BROWSER_TEST_P(SitePerProcessMouseWheelHitTestBrowserTest,
root->child_at(0)->current_frame_host()->GetProcess();
RenderProcessHostWatcher crash_observer(
child_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
- child_process->Shutdown(0, false);
+ child_process->Shutdown(0);
crash_observer.Wait();
EXPECT_EQ(nullptr, router->wheel_target_.target);
}
@@ -2532,10 +2772,9 @@ void SendTouchpadFlingSequenceWithExpectedTarget(
blink::WebGestureEvent gesture_event(
blink::WebGestureEvent::kGestureScrollBegin,
blink::WebInputEvent::kNoModifiers,
- blink::WebInputEvent::GetStaticTimeStampForTests());
- gesture_event.source_device = blink::kWebGestureDeviceTouchpad;
- gesture_event.x = gesture_point.x();
- gesture_event.y = gesture_point.y();
+ blink::WebInputEvent::GetStaticTimeStampForTests(),
+ blink::kWebGestureDeviceTouchpad);
+ gesture_event.SetPositionInWidget(gfx::PointF(gesture_point));
gesture_event.data.scroll_begin.delta_x_hint = 0.0f;
gesture_event.data.scroll_begin.delta_y_hint = 1.0f;
expected_target->GetRenderWidgetHost()->ForwardGestureEvent(gesture_event);
@@ -2572,10 +2811,9 @@ void SendTouchpadFlingSequenceWithExpectedTarget(
blink::WebGestureEvent gesture_event(
blink::WebGestureEvent::kGestureScrollEnd,
blink::WebInputEvent::kNoModifiers,
- blink::WebInputEvent::GetStaticTimeStampForTests());
- gesture_event.source_device = blink::kWebGestureDeviceTouchpad;
- gesture_event.x = gesture_point.x();
- gesture_event.y = gesture_point.y();
+ blink::WebInputEvent::GetStaticTimeStampForTests(),
+ blink::kWebGestureDeviceTouchpad);
+ gesture_event.SetPositionInWidget(gfx::PointF(gesture_point));
expected_target->GetRenderWidgetHost()->ForwardGestureEvent(gesture_event);
}
}
@@ -2583,8 +2821,9 @@ void SendTouchpadFlingSequenceWithExpectedTarget(
} // anonymous namespace
+// Flaky, see https://crbug.com/823578
IN_PROC_BROWSER_TEST_P(SitePerProcessHitTestBrowserTest,
- InputEventRouterGestureTargetMapTest) {
+ DISABLED_InputEventRouterGestureTargetMapTest) {
GURL main_url(embedded_test_server()->GetURL(
"/frame_tree/page_with_positioned_nested_frames.html"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
@@ -2949,76 +3188,6 @@ IN_PROC_BROWSER_TEST_P(SitePerProcessHighDPIHitTestBrowserTest,
CreateContextMenuTestHelper(shell(), embedded_test_server());
}
-class ShowWidgetMessageFilter : public content::BrowserMessageFilter {
- public:
- ShowWidgetMessageFilter()
-#if defined(OS_MACOSX) || defined(OS_ANDROID)
- : content::BrowserMessageFilter(FrameMsgStart),
-#else
- : content::BrowserMessageFilter(ViewMsgStart),
-#endif
- message_loop_runner_(new content::MessageLoopRunner) {
- }
-
- bool OnMessageReceived(const IPC::Message& message) override {
- IPC_BEGIN_MESSAGE_MAP(ShowWidgetMessageFilter, message)
-#if defined(OS_MACOSX) || defined(OS_ANDROID)
- IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup)
-#else
- IPC_MESSAGE_HANDLER(ViewHostMsg_ShowWidget, OnShowWidget)
-#endif
- IPC_END_MESSAGE_MAP()
- return false;
- }
-
- gfx::Rect last_initial_rect() const { return initial_rect_; }
-
- int last_routing_id() const { return routing_id_; }
-
- void Wait() {
- initial_rect_ = gfx::Rect();
- routing_id_ = MSG_ROUTING_NONE;
- message_loop_runner_->Run();
- }
-
- void Reset() {
- initial_rect_ = gfx::Rect();
- routing_id_ = MSG_ROUTING_NONE;
- message_loop_runner_ = new content::MessageLoopRunner;
- }
-
- private:
- ~ShowWidgetMessageFilter() override {}
-
- void OnShowWidget(int route_id, const gfx::Rect& initial_rect) {
- content::BrowserThread::PostTask(
- content::BrowserThread::UI, FROM_HERE,
- base::BindOnce(&ShowWidgetMessageFilter::OnShowWidgetOnUI, this,
- route_id, initial_rect));
- }
-
-#if defined(OS_MACOSX) || defined(OS_ANDROID)
- void OnShowPopup(const FrameHostMsg_ShowPopup_Params& params) {
- content::BrowserThread::PostTask(
- content::BrowserThread::UI, FROM_HERE,
- base::Bind(&ShowWidgetMessageFilter::OnShowWidgetOnUI, this,
- MSG_ROUTING_NONE, params.bounds));
- }
-#endif
-
- void OnShowWidgetOnUI(int route_id, const gfx::Rect& initial_rect) {
- initial_rect_ = initial_rect;
- routing_id_ = route_id;
- message_loop_runner_->Quit();
- }
-
- scoped_refptr<content::MessageLoopRunner> message_loop_runner_;
- gfx::Rect initial_rect_;
- int routing_id_;
-
- DISALLOW_COPY_AND_ASSIGN(ShowWidgetMessageFilter);
-};
-
// Test that clicking a select element in an out-of-process iframe creates
// a popup menu in the correct position.
IN_PROC_BROWSER_TEST_P(SitePerProcessHitTestBrowserTest, PopupMenuTest) {
@@ -3286,14 +3455,6 @@ class SitePerProcessGestureHitTestBrowserTest
blink::WebInputEvent::kTouchStart);
rwhva->OnTouchEvent(&touch_pressed);
waiter.Wait();
- ui::TouchEvent touch_released(
- ui::ET_TOUCH_RELEASED, position, ui::EventTimeForNow(),
- ui::PointerDetails(ui::EventPointerType::POINTER_TYPE_TOUCH,
- /* pointer_id*/ 0,
- /* radius_x */ 1.0f,
- /* radius_y */ 1.0f,
- /* force */ 1.0f));
- rwhva->OnTouchEvent(&touch_released);
ui::GestureEventDetails gesture_tap_down_details(ui::ET_GESTURE_TAP_DOWN);
gesture_tap_down_details.set_device_type(
@@ -3342,6 +3503,21 @@ class SitePerProcessGestureHitTestBrowserTest
gesture_scroll_end_details, touch_pressed.unique_event_id());
UpdateEventRootLocation(&gesture_scroll_end, rwhva);
rwhva->OnGestureEvent(&gesture_scroll_end);
+
+ // TouchActionFilter is reset when a touch event sequence ends, so in order
+ // to preserve the touch action set by TouchStart, we end release touch
+ // after pinch gestures.
+ ui::TouchEvent touch_released(
+ ui::ET_TOUCH_RELEASED, position, ui::EventTimeForNow(),
+ ui::PointerDetails(ui::EventPointerType::POINTER_TYPE_TOUCH,
+ /* pointer_id*/ 0,
+ /* radius_x */ 1.0f,
+ /* radius_y */ 1.0f,
+ /* force */ 1.0f));
+ InputEventAckWaiter touch_released_waiter(expected_target_rwh,
+ blink::WebInputEvent::kTouchEnd);
+ rwhva->OnTouchEvent(&touch_released);
+ touch_released_waiter.Wait();
}
void SetupRootAndChild() {
@@ -3404,13 +3580,13 @@ IN_PROC_BROWSER_TEST_P(SitePerProcessGestureHitTestBrowserTest,
EXPECT_TRUE(child_frame_monitor.EventWasReceived());
EXPECT_EQ(blink::WebInputEvent::kTouchStart,
child_frame_monitor.events_received()[0]);
- EXPECT_EQ(blink::WebInputEvent::kTouchEnd,
- child_frame_monitor.events_received()[1]);
EXPECT_EQ(blink::WebInputEvent::kGestureTapDown,
- child_frame_monitor.events_received()[2]);
+ child_frame_monitor.events_received()[1]);
EXPECT_EQ(blink::WebInputEvent::kGestureScrollBegin,
- child_frame_monitor.events_received()[3]);
+ child_frame_monitor.events_received()[2]);
EXPECT_EQ(blink::WebInputEvent::kGestureScrollEnd,
+ child_frame_monitor.events_received()[3]);
+ EXPECT_EQ(blink::WebInputEvent::kTouchEnd,
child_frame_monitor.events_received()[4]);
}
@@ -3433,22 +3609,95 @@ IN_PROC_BROWSER_TEST_P(SitePerProcessGestureHitTestBrowserTest,
EXPECT_TRUE(root_frame_monitor.EventWasReceived());
EXPECT_EQ(blink::WebInputEvent::kTouchStart,
root_frame_monitor.events_received()[0]);
- EXPECT_EQ(blink::WebInputEvent::kTouchEnd,
- root_frame_monitor.events_received()[1]);
EXPECT_EQ(blink::WebInputEvent::kGestureTapDown,
- root_frame_monitor.events_received()[2]);
+ root_frame_monitor.events_received()[1]);
EXPECT_EQ(blink::WebInputEvent::kGestureScrollBegin,
- root_frame_monitor.events_received()[3]);
+ root_frame_monitor.events_received()[2]);
EXPECT_EQ(blink::WebInputEvent::kGesturePinchBegin,
- root_frame_monitor.events_received()[4]);
+ root_frame_monitor.events_received()[3]);
EXPECT_EQ(blink::WebInputEvent::kGesturePinchEnd,
- root_frame_monitor.events_received()[5]);
+ root_frame_monitor.events_received()[4]);
EXPECT_EQ(blink::WebInputEvent::kGestureScrollEnd,
+ root_frame_monitor.events_received()[5]);
+ EXPECT_EQ(blink::WebInputEvent::kTouchEnd,
root_frame_monitor.events_received()[6]);
// Verify child-RWHI gets no events.
EXPECT_FALSE(child_frame_monitor.EventWasReceived());
}
+
+IN_PROC_BROWSER_TEST_P(SitePerProcessGestureHitTestBrowserTest,
+ SubframeGesturePinchDeniedBySubframeTouchAction) {
+ GURL main_url(embedded_test_server()->GetURL(
+ "a.com", "/cross_site_iframe_factory.html?a(b)"));
+
+ EXPECT_TRUE(NavigateToURL(shell(), main_url));
+
+ // It is safe to obtain the root frame tree node here, as it doesn't change.
+ FrameTreeNode* root_node =
+ static_cast<WebContentsImpl*>(shell()->web_contents())
+ ->GetFrameTree()
+ ->root();
+ ASSERT_EQ(1U, root_node->child_count());
+
+ FrameTreeNode* child_node = root_node->child_at(0);
+ GURL b_url(embedded_test_server()->GetURL(
+ "b.com", "/div_with_touch_action_none.html"));
+ NavigateFrameToURL(child_node, b_url);
+
+ ASSERT_EQ(
+ " Site A ------------ proxies for B\n"
+ " +--Site B ------- proxies for A\n"
+ "Where A = http://a.com/\n"
+ " B = http://b.com/",
+ DepictFrameTree(root_node));
+
+ rwhv_child_ = static_cast<RenderWidgetHostViewBase*>(
+ child_node->current_frame_host()->GetRenderWidgetHost()->GetView());
+
+ rwhva_root_ = static_cast<RenderWidgetHostViewAura*>(
+ shell()->web_contents()->GetRenderWidgetHostView());
+
+ WaitForChildFrameSurfaceReady(child_node->current_frame_host());
+
+ MainThreadFrameObserver observer(rwhv_child_->GetRenderWidgetHost());
+ observer.Wait();
+
+ rwhi_child_ = child_node->current_frame_host()->GetRenderWidgetHost();
+ rwhi_root_ = root_node->current_frame_host()->GetRenderWidgetHost();
+
+ TestInputEventObserver root_frame_monitor(rwhi_root_);
+ TestInputEventObserver child_frame_monitor(rwhi_child_);
+
+ gfx::Rect bounds = rwhv_child_->GetViewBounds();
+ bounds.Offset(gfx::Point() - rwhva_root_->GetViewBounds().origin());
+
+ SendPinchBeginEndSequence(rwhva_root_, bounds.CenterPoint(), rwhi_child_);
+
+ // Verify that root-RWHI gets nothing.
+ EXPECT_FALSE(root_frame_monitor.EventWasReceived());
+ // Verify that child-RWHI gets TS/GTD/GSB/GPB/GPE/GSE/TE.
+ EXPECT_EQ(blink::WebInputEvent::kTouchStart,
+ child_frame_monitor.events_received()[0]);
+ EXPECT_EQ(blink::WebInputEvent::kGestureTapDown,
+ child_frame_monitor.events_received()[1]);
+ EXPECT_EQ(blink::WebInputEvent::kGestureScrollBegin,
+ child_frame_monitor.events_received()[2]);
+ EXPECT_EQ(blink::WebInputEvent::kGesturePinchBegin,
+ child_frame_monitor.events_received()[3]);
+ EXPECT_EQ(blink::WebInputEvent::kGesturePinchEnd,
+ child_frame_monitor.events_received()[4]);
+ EXPECT_EQ(blink::WebInputEvent::kGestureScrollEnd,
+ child_frame_monitor.events_received()[5]);
+ EXPECT_EQ(blink::WebInputEvent::kTouchEnd,
+ child_frame_monitor.events_received()[6]);
+
+ // Verify that the pinch gestures are consumed by browser.
+ EXPECT_EQ(InputEventAckSource::BROWSER,
+ child_frame_monitor.events_acked()[3]);
+ EXPECT_EQ(InputEventAckSource::BROWSER,
+ child_frame_monitor.events_acked()[4]);
+}
#endif // defined(USE_AURA)
// Test that MouseDown and MouseUp to the same coordinates do not result in
@@ -3591,11 +3840,12 @@ IN_PROC_BROWSER_TEST_P(SitePerProcessHitTestBrowserTest, HitTestNestedFrames) {
}
}
+static const int kHitTestOption[] = {0, 1, 2};
static const float kOneScale[] = {1.f};
INSTANTIATE_TEST_CASE_P(/* no prefix */,
SitePerProcessHitTestBrowserTest,
- testing::Combine(testing::Bool(),
+ testing::Combine(testing::ValuesIn(kHitTestOption),
testing::ValuesIn(kOneScale)));
// TODO(wjmaclean): Since the next two test fixtures only differ in DSF
// values, should we combine them into one using kMultiScale? This
@@ -3603,26 +3853,31 @@ INSTANTIATE_TEST_CASE_P(/* no prefix */,
// particular platforms.
INSTANTIATE_TEST_CASE_P(/* no prefix */,
SitePerProcessHighDPIHitTestBrowserTest,
- testing::Combine(testing::Bool(),
+ testing::Combine(testing::ValuesIn(kHitTestOption),
testing::ValuesIn(kOneScale)));
INSTANTIATE_TEST_CASE_P(/* no prefix */,
SitePerProcessNonIntegerScaleFactorHitTestBrowserTest,
- testing::Combine(testing::Bool(),
+ testing::Combine(testing::ValuesIn(kHitTestOption),
testing::ValuesIn(kOneScale)));
#if defined(USE_AURA)
static const float kMultiScale[] = {1.f, 1.5f, 2.f};
INSTANTIATE_TEST_CASE_P(/* no prefix */,
SitePerProcessInternalsHitTestBrowserTest,
- testing::Combine(testing::Bool(),
+ testing::Combine(testing::ValuesIn(kHitTestOption),
testing::ValuesIn(kMultiScale)));
INSTANTIATE_TEST_CASE_P(/* no prefix */,
SitePerProcessMouseWheelHitTestBrowserTest,
- testing::Combine(testing::Bool(),
+ testing::Combine(testing::ValuesIn(kHitTestOption),
testing::ValuesIn(kOneScale)));
+INSTANTIATE_TEST_CASE_P(
+ /* no prefix */,
+ SitePerProcessMouseWheelHitTestBrowserTestWheelScrollLatchingDisabled,
+ testing::Combine(testing::ValuesIn(kHitTestOption),
+ testing::ValuesIn(kOneScale)));
INSTANTIATE_TEST_CASE_P(/* no prefix */,
SitePerProcessGestureHitTestBrowserTest,
- testing::Combine(testing::Bool(),
+ testing::Combine(testing::ValuesIn(kHitTestOption),
testing::ValuesIn(kOneScale)));
#endif
diff --git a/chromium/content/browser/site_per_process_mac_browsertest.mm b/chromium/content/browser/site_per_process_mac_browsertest.mm
index 4f068ba30c9..dc16103b3aa 100644
--- a/chromium/content/browser/site_per_process_mac_browsertest.mm
+++ b/chromium/content/browser/site_per_process_mac_browsertest.mm
@@ -9,6 +9,7 @@
#include "base/mac/mac_util.h"
#include "content/browser/renderer_host/render_widget_host_input_event_router.h"
#include "content/browser/renderer_host/render_widget_host_view_mac.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/public/test/test_utils.h"
diff --git a/chromium/content/browser/speech/speech_recognition_browsertest.cc b/chromium/content/browser/speech/speech_recognition_browsertest.cc
index fad9fdc2d6b..fc367e3d119 100644
--- a/chromium/content/browser/speech/speech_recognition_browsertest.cc
+++ b/chromium/content/browser/speech/speech_recognition_browsertest.cc
@@ -11,11 +11,15 @@
#include "base/bind.h"
#include "base/location.h"
+#include "base/numerics/safe_conversions.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
+#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
+#include "base/sys_byteorder.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
+#include "content/browser/speech/proto/google_streaming_api.pb.h"
#include "content/browser/speech/speech_recognition_engine.h"
#include "content/browser/speech/speech_recognition_manager_impl.h"
#include "content/browser/speech/speech_recognizer_impl.h"
@@ -25,58 +29,66 @@
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
+#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_utils.h"
#include "content/shell/browser/shell.h"
-#include "content/test/mock_google_streaming_server.h"
#include "media/audio/audio_system_impl.h"
#include "media/audio/audio_thread_impl.h"
#include "media/audio/mock_audio_manager.h"
#include "media/audio/test_audio_input_controller_factory.h"
+#include "net/test/embedded_test_server/controllable_http_response.h"
+#include "net/test/embedded_test_server/embedded_test_server.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::RunLoop;
namespace content {
-class SpeechRecognitionBrowserTest :
- public ContentBrowserTest,
- public MockGoogleStreamingServer::Delegate,
- public media::TestAudioInputControllerDelegate {
+namespace {
+
+std::string MakeGoodResponse() {
+ proto::SpeechRecognitionEvent proto_event;
+ proto_event.set_status(proto::SpeechRecognitionEvent::STATUS_SUCCESS);
+ proto::SpeechRecognitionResult* proto_result = proto_event.add_result();
+ SpeechRecognitionResult result;
+ result.hypotheses.push_back(SpeechRecognitionHypothesis(
+ base::UTF8ToUTF16("Pictures of the moon"), 1.0F));
+ proto_result->set_final(!result.is_provisional);
+ for (size_t i = 0; i < result.hypotheses.size(); ++i) {
+ proto::SpeechRecognitionAlternative* proto_alternative =
+ proto_result->add_alternative();
+ const SpeechRecognitionHypothesis& hypothesis = result.hypotheses[i];
+ proto_alternative->set_confidence(hypothesis.confidence);
+ proto_alternative->set_transcript(base::UTF16ToUTF8(hypothesis.utterance));
+ }
+
+ std::string msg_string;
+ proto_event.SerializeToString(&msg_string);
+
+ // Prepend 4 byte prefix length indication to the protobuf message as
+ // envisaged by the google streaming recognition webservice protocol.
+ uint32_t prefix =
+ base::HostToNet32(base::checked_cast<uint32_t>(msg_string.size()));
+ msg_string.insert(0, reinterpret_cast<char*>(&prefix), sizeof(prefix));
+ return msg_string;
+}
+
+} // namespace
+
+class SpeechRecognitionBrowserTest
+ : public ContentBrowserTest,
+ public media::TestAudioInputControllerDelegate {
public:
enum StreamingServerState {
kIdle,
kTestAudioControllerOpened,
- kClientConnected,
- kClientAudioUpload,
- kClientAudioUploadComplete,
kTestAudioControllerClosed,
- kClientDisconnected
};
- // MockGoogleStreamingServerDelegate methods.
- void OnClientConnected() override {
- ASSERT_EQ(kTestAudioControllerOpened, streaming_server_state_);
- streaming_server_state_ = kClientConnected;
- }
-
- void OnClientAudioUpload() override {
- if (streaming_server_state_ == kClientConnected)
- streaming_server_state_ = kClientAudioUpload;
- }
-
- void OnClientAudioUploadComplete() override {
- ASSERT_EQ(kTestAudioControllerClosed, streaming_server_state_);
- streaming_server_state_ = kClientAudioUploadComplete;
- }
-
- void OnClientDisconnected() override {
- ASSERT_EQ(kClientAudioUploadComplete, streaming_server_state_);
- streaming_server_state_ = kClientDisconnected;
- }
-
// media::TestAudioInputControllerDelegate methods.
void TestAudioControllerOpened(
media::TestAudioInputController* controller) override {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
ASSERT_EQ(kIdle, streaming_server_state_);
streaming_server_state_ = kTestAudioControllerOpened;
const int capture_packet_interval_ms =
@@ -91,12 +103,18 @@ class SpeechRecognitionBrowserTest :
void TestAudioControllerClosed(
media::TestAudioInputController* controller) override {
- ASSERT_EQ(kClientAudioUpload, streaming_server_state_);
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+ ASSERT_EQ(kTestAudioControllerOpened, streaming_server_state_);
streaming_server_state_ = kTestAudioControllerClosed;
- mock_streaming_server_->MockGoogleStreamingServer::SimulateResult(
- GetGoodSpeechResult());
+
+ content::BrowserThread::PostTask(
+ content::BrowserThread::UI, FROM_HERE,
+ base::BindOnce(&SpeechRecognitionBrowserTest::SendResponse,
+ base::Unretained(this)));
}
+ void SendResponse() {}
+
// Helper methods used by test fixtures.
GURL GetTestUrlFromFragment(const std::string& fragment) {
return GURL(GetTestUrl("speech", "web_speech_recognition.html").spec() +
@@ -117,7 +135,6 @@ class SpeechRecognitionBrowserTest :
test_audio_input_controller_factory_.set_delegate(this);
media::AudioInputController::set_factory_for_testing(
&test_audio_input_controller_factory_);
- mock_streaming_server_.reset(new MockGoogleStreamingServer(this));
streaming_server_state_ = kIdle;
ASSERT_TRUE(SpeechRecognitionManagerImpl::GetInstance());
@@ -139,7 +156,6 @@ class SpeechRecognitionBrowserTest :
audio_manager_->Shutdown();
test_audio_input_controller_factory_.set_delegate(nullptr);
- mock_streaming_server_.reset();
}
private:
@@ -191,17 +207,10 @@ class SpeechRecognitionBrowserTest :
}
}
- SpeechRecognitionResult GetGoodSpeechResult() {
- SpeechRecognitionResult result;
- result.hypotheses.push_back(SpeechRecognitionHypothesis(
- base::UTF8ToUTF16("Pictures of the moon"), 1.0F));
- return result;
- }
-
std::unique_ptr<media::MockAudioManager> audio_manager_;
std::unique_ptr<media::AudioSystem> audio_system_;
StreamingServerState streaming_server_state_;
- std::unique_ptr<MockGoogleStreamingServer> mock_streaming_server_;
+
media::TestAudioInputControllerFactory test_audio_input_controller_factory_;
};
@@ -223,11 +232,53 @@ IN_PROC_BROWSER_TEST_F(SpeechRecognitionBrowserTest, DISABLED_Precheck) {
#define MAYBE_OneShotRecognition OneShotRecognition
#endif
IN_PROC_BROWSER_TEST_F(SpeechRecognitionBrowserTest, MAYBE_OneShotRecognition) {
- NavigateToURLBlockUntilNavigationsComplete(
- shell(), GetTestUrlFromFragment("oneshot"), 2);
+ // Set up a test server, with two response handlers.
+ net::test_server::ControllableHttpResponse upstream_response(
+ embedded_test_server(), "/foo/up?", true /* relative_url_is_prefix */);
+ net::test_server::ControllableHttpResponse downstream_response(
+ embedded_test_server(), "/foo/down?", true /* relative_url_is_prefix */);
+ ASSERT_TRUE(embedded_test_server()->Start());
+ // Use a base path that doesn't end in a slash to mimic the default URL.
+ std::string web_service_base_url =
+ embedded_test_server()->base_url().spec() + "foo";
+ SpeechRecognitionEngine::set_web_service_base_url_for_tests(
+ web_service_base_url.c_str());
+
+ // Need to watch for two navigations. Can't use
+ // NavigateToURLBlockUntilNavigationsComplete so that the
+ // ControllableHttpResponses can be used to wait for the test server to see
+ // the network requests, and response to them.
+ TestNavigationObserver navigation_observer(shell()->web_contents(), 2);
+ shell()->LoadURL(GetTestUrlFromFragment("oneshot"));
+
+ // Wait for the upstream HTTP request to be completely received, and return an
+ // empty response.
+ upstream_response.WaitForRequest();
+ EXPECT_FALSE(upstream_response.http_request()->content.empty());
+ EXPECT_EQ(net::test_server::METHOD_POST,
+ upstream_response.http_request()->method);
+ EXPECT_EQ("chunked",
+ upstream_response.http_request()->headers.at("Transfer-Encoding"));
+ EXPECT_EQ("audio/x-flac; rate=16000",
+ upstream_response.http_request()->headers.at("Content-Type"));
+ upstream_response.Send("HTTP/1.1 200 OK\r\n\r\n");
+ upstream_response.Done();
- EXPECT_EQ(kClientDisconnected, streaming_server_state());
+ // Wait for the downstream HTTP request to be received, and response with a
+ // valid response.
+ downstream_response.WaitForRequest();
+ EXPECT_EQ(net::test_server::METHOD_GET,
+ downstream_response.http_request()->method);
+ downstream_response.Send("HTTP/1.1 200 OK\r\n\r\n" + MakeGoodResponse());
+ downstream_response.Done();
+
+ navigation_observer.Wait();
+
+ EXPECT_EQ(kTestAudioControllerClosed, streaming_server_state());
EXPECT_EQ("goodresult1", GetPageFragment());
+
+ // Remove reference to URL string that's on the stack.
+ SpeechRecognitionEngine::set_web_service_base_url_for_tests(nullptr);
}
} // namespace content
diff --git a/chromium/content/browser/speech/speech_recognition_dispatcher_host.cc b/chromium/content/browser/speech/speech_recognition_dispatcher_host.cc
index 24f487018ab..1e34625f16b 100644
--- a/chromium/content/browser/speech/speech_recognition_dispatcher_host.cc
+++ b/chromium/content/browser/speech/speech_recognition_dispatcher_host.cc
@@ -4,15 +4,19 @@
#include "content/browser/speech/speech_recognition_dispatcher_host.h"
+#include <memory>
+
#include "base/bind.h"
#include "base/command_line.h"
#include "base/lazy_instance.h"
#include "content/browser/browser_plugin/browser_plugin_guest.h"
#include "content/browser/child_process_security_policy_impl.h"
-#include "content/browser/renderer_host/render_view_host_impl.h"
+#include "content/browser/frame_host/frame_tree_node.h"
+#include "content/browser/frame_host/render_frame_host_manager.h"
#include "content/browser/speech/speech_recognition_manager_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/common/speech_recognition_messages.h"
+#include "content/public/browser/browser_context.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/speech_recognition_manager_delegate.h"
#include "content/public/browser/speech_recognition_session_config.h"
@@ -34,8 +38,6 @@ SpeechRecognitionDispatcherHost::SpeechRecognitionDispatcherHost(
}
SpeechRecognitionDispatcherHost::~SpeechRecognitionDispatcherHost() {
- SpeechRecognitionManager::GetInstance()->AbortAllSessionsForRenderProcess(
- render_process_id_);
}
base::WeakPtr<SpeechRecognitionDispatcherHost>
@@ -77,7 +79,7 @@ void SpeechRecognitionDispatcherHost::OnChannelClosing() {
void SpeechRecognitionDispatcherHost::OnStartRequest(
const SpeechRecognitionHostMsg_StartRequest_Params& params) {
- SpeechRecognitionHostMsg_StartRequest_Params input_params(params);
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
// Check that the origin specified by the renderer process is one
// that it is allowed to access.
@@ -90,68 +92,69 @@ void SpeechRecognitionDispatcherHost::OnStartRequest(
}
int embedder_render_process_id = 0;
- int embedder_render_view_id = MSG_ROUTING_NONE;
- RenderViewHostImpl* render_view_host =
- RenderViewHostImpl::FromID(render_process_id_, params.render_view_id);
- if (!render_view_host) {
- // RVH can be null if the tab was closed while continuous mode speech
- // recognition was running. This seems to happen on mac.
- LOG(WARNING) << "SRDH::OnStartRequest, RenderViewHost does not exist";
+ int embedder_render_frame_id = MSG_ROUTING_NONE;
+
+ WebContentsImpl* web_contents =
+ static_cast<WebContentsImpl*>(WebContentsImpl::FromRenderFrameHostID(
+ render_process_id_, params.render_frame_id));
+ if (!web_contents) {
+ // The render frame id is renderer-provided. If it's invalid, don't crash.
+ DLOG(ERROR) << "SRDH::OnStartRequest, invalid frame";
return;
}
- WebContentsImpl* web_contents = static_cast<WebContentsImpl*>(
- WebContents::FromRenderViewHost(render_view_host));
- WebContentsImpl* outer_web_contents = web_contents->GetOuterWebContents();
+ // If the speech API request was from an inner WebContents or a guest, save
+ // the context of the outer WebContents or the embedder since we will use it
+ // to decide permission.
+ WebContents* outer_web_contents = web_contents->GetOuterWebContents();
if (outer_web_contents) {
- // If the speech API request was from an inner WebContents or a guest, save
- // the context of the outer WebContents or the embedder since we will use it
- // to decide permission.
- embedder_render_process_id =
- outer_web_contents->GetRenderViewHost()->GetProcess()->GetID();
+ RenderFrameHost* embedder_frame = nullptr;
+
+ FrameTreeNode* embedder_frame_node = web_contents->GetMainFrame()
+ ->frame_tree_node()
+ ->render_manager()
+ ->GetOuterDelegateNode();
+ if (embedder_frame_node) {
+ embedder_frame = embedder_frame_node->current_frame_host();
+ } else {
+ // The outer web contents is embedded using the browser plugin. Fall back
+ // to a simple lookup of the main frame. TODO(avi): When the browser
+ // plugin is retired, remove this code.
+ embedder_frame = outer_web_contents->GetMainFrame();
+ }
+
+ embedder_render_process_id = embedder_frame->GetProcess()->GetID();
DCHECK_NE(embedder_render_process_id, 0);
- embedder_render_view_id =
- outer_web_contents->GetRenderViewHost()->GetRoutingID();
- DCHECK_NE(embedder_render_view_id, MSG_ROUTING_NONE);
+ embedder_render_frame_id = embedder_frame->GetRoutingID();
+ DCHECK_NE(embedder_render_frame_id, MSG_ROUTING_NONE);
}
- // TODO(lazyboy): Check if filter_profanities should use |render_process_id|
- // instead of |render_process_id_|.
bool filter_profanities =
SpeechRecognitionManagerImpl::GetInstance() &&
SpeechRecognitionManagerImpl::GetInstance()->delegate() &&
SpeechRecognitionManagerImpl::GetInstance()->delegate()->
FilterProfanities(render_process_id_);
- // TODO(miu): This is a hack to allow SpeechRecognition to operate with the
- // MediaStreamManager, which partitions requests per RenderFrame, not per
- // RenderView. http://crbug.com/390749
- const int params_render_frame_id = render_view_host ?
- render_view_host->GetMainFrame()->GetRoutingID() : MSG_ROUTING_NONE;
+ SpeechRecognitionSessionContext context;
+ context.context_name = params.origin_url;
+ context.render_process_id = render_process_id_;
+ context.render_frame_id = params.render_frame_id;
+ context.embedder_render_process_id = embedder_render_process_id;
+ context.embedder_render_frame_id = embedder_render_frame_id;
+ context.request_id = params.request_id;
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
- base::BindOnce(&SpeechRecognitionDispatcherHost::OnStartRequestOnIO, this,
- embedder_render_process_id, embedder_render_view_id,
- input_params, params_render_frame_id, filter_profanities));
+ base::BindOnce(&SpeechRecognitionDispatcherHost::StartSession,
+ base::Unretained(this), params, context,
+ filter_profanities));
}
-void SpeechRecognitionDispatcherHost::OnStartRequestOnIO(
- int embedder_render_process_id,
- int embedder_render_view_id,
+void SpeechRecognitionDispatcherHost::StartSession(
const SpeechRecognitionHostMsg_StartRequest_Params& params,
- int params_render_frame_id,
+ const SpeechRecognitionSessionContext& context,
bool filter_profanities) {
- SpeechRecognitionSessionContext context;
- context.context_name = params.origin_url;
- context.render_process_id = render_process_id_;
- context.render_view_id = params.render_view_id;
- context.render_frame_id = params_render_frame_id;
- context.embedder_render_process_id = embedder_render_process_id;
- context.embedder_render_view_id = embedder_render_view_id;
- if (embedder_render_process_id)
- context.guest_render_view_id = params.render_view_id;
- context.request_id = params.request_id;
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
SpeechRecognitionSessionConfig config;
config.language = params.language;
@@ -171,10 +174,12 @@ void SpeechRecognitionDispatcherHost::OnStartRequestOnIO(
SpeechRecognitionManager::GetInstance()->StartSession(session_id);
}
-void SpeechRecognitionDispatcherHost::OnAbortRequest(int render_view_id,
+void SpeechRecognitionDispatcherHost::OnAbortRequest(int render_frame_id,
int request_id) {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+
int session_id = SpeechRecognitionManager::GetInstance()->GetSession(
- render_process_id_, render_view_id, request_id);
+ render_process_id_, render_frame_id, request_id);
// The renderer might provide an invalid |request_id| if the session was not
// started as expected, e.g., due to unsatisfied security requirements.
@@ -182,15 +187,19 @@ void SpeechRecognitionDispatcherHost::OnAbortRequest(int render_view_id,
SpeechRecognitionManager::GetInstance()->AbortSession(session_id);
}
-void SpeechRecognitionDispatcherHost::OnAbortAllRequests(int render_view_id) {
- SpeechRecognitionManager::GetInstance()->AbortAllSessionsForRenderView(
- render_process_id_, render_view_id);
+void SpeechRecognitionDispatcherHost::OnAbortAllRequests(int render_frame_id) {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+
+ SpeechRecognitionManager::GetInstance()->AbortAllSessionsForRenderFrame(
+ render_process_id_, render_frame_id);
}
-void SpeechRecognitionDispatcherHost::OnStopCaptureRequest(
- int render_view_id, int request_id) {
+void SpeechRecognitionDispatcherHost::OnStopCaptureRequest(int render_frame_id,
+ int request_id) {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+
int session_id = SpeechRecognitionManager::GetInstance()->GetSession(
- render_process_id_, render_view_id, request_id);
+ render_process_id_, render_frame_id, request_id);
// The renderer might provide an invalid |request_id| if the session was not
// started as expected, e.g., due to unsatisfied security requirements.
@@ -205,42 +214,42 @@ void SpeechRecognitionDispatcherHost::OnStopCaptureRequest(
void SpeechRecognitionDispatcherHost::OnRecognitionStart(int session_id) {
const SpeechRecognitionSessionContext& context =
SpeechRecognitionManager::GetInstance()->GetSessionContext(session_id);
- Send(new SpeechRecognitionMsg_Started(context.render_view_id,
+ Send(new SpeechRecognitionMsg_Started(context.render_frame_id,
context.request_id));
}
void SpeechRecognitionDispatcherHost::OnAudioStart(int session_id) {
const SpeechRecognitionSessionContext& context =
SpeechRecognitionManager::GetInstance()->GetSessionContext(session_id);
- Send(new SpeechRecognitionMsg_AudioStarted(context.render_view_id,
+ Send(new SpeechRecognitionMsg_AudioStarted(context.render_frame_id,
context.request_id));
}
void SpeechRecognitionDispatcherHost::OnSoundStart(int session_id) {
const SpeechRecognitionSessionContext& context =
SpeechRecognitionManager::GetInstance()->GetSessionContext(session_id);
- Send(new SpeechRecognitionMsg_SoundStarted(context.render_view_id,
+ Send(new SpeechRecognitionMsg_SoundStarted(context.render_frame_id,
context.request_id));
}
void SpeechRecognitionDispatcherHost::OnSoundEnd(int session_id) {
const SpeechRecognitionSessionContext& context =
SpeechRecognitionManager::GetInstance()->GetSessionContext(session_id);
- Send(new SpeechRecognitionMsg_SoundEnded(context.render_view_id,
+ Send(new SpeechRecognitionMsg_SoundEnded(context.render_frame_id,
context.request_id));
}
void SpeechRecognitionDispatcherHost::OnAudioEnd(int session_id) {
const SpeechRecognitionSessionContext& context =
SpeechRecognitionManager::GetInstance()->GetSessionContext(session_id);
- Send(new SpeechRecognitionMsg_AudioEnded(context.render_view_id,
+ Send(new SpeechRecognitionMsg_AudioEnded(context.render_frame_id,
context.request_id));
}
void SpeechRecognitionDispatcherHost::OnRecognitionEnd(int session_id) {
const SpeechRecognitionSessionContext& context =
SpeechRecognitionManager::GetInstance()->GetSessionContext(session_id);
- Send(new SpeechRecognitionMsg_Ended(context.render_view_id,
+ Send(new SpeechRecognitionMsg_Ended(context.render_frame_id,
context.request_id));
}
@@ -249,9 +258,8 @@ void SpeechRecognitionDispatcherHost::OnRecognitionResults(
const SpeechRecognitionResults& results) {
const SpeechRecognitionSessionContext& context =
SpeechRecognitionManager::GetInstance()->GetSessionContext(session_id);
- Send(new SpeechRecognitionMsg_ResultRetrieved(context.render_view_id,
- context.request_id,
- results));
+ Send(new SpeechRecognitionMsg_ResultRetrieved(context.render_frame_id,
+ context.request_id, results));
}
void SpeechRecognitionDispatcherHost::OnRecognitionError(
@@ -259,9 +267,8 @@ void SpeechRecognitionDispatcherHost::OnRecognitionError(
const SpeechRecognitionError& error) {
const SpeechRecognitionSessionContext& context =
SpeechRecognitionManager::GetInstance()->GetSessionContext(session_id);
- Send(new SpeechRecognitionMsg_ErrorOccurred(context.render_view_id,
- context.request_id,
- error));
+ Send(new SpeechRecognitionMsg_ErrorOccurred(context.render_frame_id,
+ context.request_id, error));
}
// The events below are currently not used by speech JS APIs implementation.
diff --git a/chromium/content/browser/speech/speech_recognition_dispatcher_host.h b/chromium/content/browser/speech/speech_recognition_dispatcher_host.h
index 08d09d0eb43..babf35dc9b4 100644
--- a/chromium/content/browser/speech/speech_recognition_dispatcher_host.h
+++ b/chromium/content/browser/speech/speech_recognition_dispatcher_host.h
@@ -11,6 +11,7 @@
#include "base/memory/weak_ptr.h"
#include "content/common/content_export.h"
#include "content/public/browser/browser_message_filter.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/speech_recognition_event_listener.h"
#include "net/url_request/url_request_context_getter.h"
@@ -19,11 +20,12 @@ struct SpeechRecognitionHostMsg_StartRequest_Params;
namespace content {
class SpeechRecognitionManager;
+struct SpeechRecognitionSessionContext;
// SpeechRecognitionDispatcherHost is a delegate for Speech API messages used by
// RenderMessageFilter. Basically it acts as a proxy, relaying the events coming
// from the SpeechRecognitionManager to IPC messages (and vice versa).
-// It's the complement of SpeechRecognitionDispatcher (owned by RenderView).
+// It's the complement of SpeechRecognitionDispatcher (owned by RenderFrame).
class CONTENT_EXPORT SpeechRecognitionDispatcherHost
: public BrowserMessageFilter,
public SpeechRecognitionEventListener {
@@ -66,15 +68,12 @@ class CONTENT_EXPORT SpeechRecognitionDispatcherHost
void OnStartRequest(
const SpeechRecognitionHostMsg_StartRequest_Params& params);
- void OnStartRequestOnIO(
- int embedder_render_process_id,
- int embedder_render_view_id,
- const SpeechRecognitionHostMsg_StartRequest_Params& params,
- int params_render_frame_id,
- bool filter_profanities);
- void OnAbortRequest(int render_view_id, int request_id);
- void OnStopCaptureRequest(int render_view_id, int request_id);
- void OnAbortAllRequests(int render_view_id);
+ void StartSession(const SpeechRecognitionHostMsg_StartRequest_Params& params,
+ const SpeechRecognitionSessionContext& context,
+ bool filter_profanities);
+ void OnAbortRequest(int render_frame_id, int request_id);
+ void OnStopCaptureRequest(int render_frame_id, int request_id);
+ void OnAbortAllRequests(int render_frame_id);
int render_process_id_;
scoped_refptr<net::URLRequestContextGetter> context_getter_;
diff --git a/chromium/content/browser/speech/speech_recognition_engine.cc b/chromium/content/browser/speech/speech_recognition_engine.cc
index e273b90874e..856f9a1df55 100644
--- a/chromium/content/browser/speech/speech_recognition_engine.cc
+++ b/chromium/content/browser/speech/speech_recognition_engine.cc
@@ -38,6 +38,9 @@ const char kWebServiceBaseUrl[] =
const char kDownstreamUrl[] = "/down?";
const char kUpstreamUrl[] = "/up?";
+// Used to override |kWebServiceBaseUrl| when non-null, only set in tests.
+const char* web_service_base_url_for_tests = nullptr;
+
// This matches the maximum maxAlternatives value supported by the server.
const uint32_t kMaxMaxAlternatives = 30;
@@ -106,6 +109,11 @@ SpeechRecognitionEngine::~SpeechRecognitionEngine() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
}
+void SpeechRecognitionEngine::set_web_service_base_url_for_tests(
+ const char* base_url_for_tests) {
+ web_service_base_url_for_tests = base_url_for_tests;
+}
+
void SpeechRecognitionEngine::SetConfig(const Config& config) {
config_ = config;
}
@@ -330,13 +338,17 @@ SpeechRecognitionEngine::ConnectBothStreams(const FSMEventArgs&) {
config_.preamble->sample_depth * 8));
}
+ const char* web_service_base_url = !web_service_base_url_for_tests
+ ? kWebServiceBaseUrl
+ : web_service_base_url_for_tests;
+
// Setup downstream fetcher.
std::vector<std::string> downstream_args;
downstream_args.push_back(
"key=" + net::EscapeQueryParamValue(google_apis::GetAPIKey(), true));
downstream_args.push_back("pair=" + request_key);
downstream_args.push_back("output=pb");
- GURL downstream_url(std::string(kWebServiceBaseUrl) +
+ GURL downstream_url(std::string(web_service_base_url) +
std::string(kDownstreamUrl) +
base::JoinString(downstream_args, "&"));
@@ -432,7 +444,8 @@ SpeechRecognitionEngine::ConnectBothStreams(const FSMEventArgs&) {
upstream_args.push_back(
"audioFormat=" + net::EscapeQueryParamValue(audio_format, true));
}
- GURL upstream_url(std::string(kWebServiceBaseUrl) +
+
+ GURL upstream_url(std::string(web_service_base_url) +
std::string(kUpstreamUrl) +
base::JoinString(upstream_args, "&"));
diff --git a/chromium/content/browser/speech/speech_recognition_engine.h b/chromium/content/browser/speech/speech_recognition_engine.h
index 9792d3aaa6b..6ac7f2528b4 100644
--- a/chromium/content/browser/speech/speech_recognition_engine.h
+++ b/chromium/content/browser/speech/speech_recognition_engine.h
@@ -104,6 +104,10 @@ class CONTENT_EXPORT SpeechRecognitionEngine : public net::URLFetcherDelegate {
explicit SpeechRecognitionEngine(net::URLRequestContextGetter* context);
~SpeechRecognitionEngine() override;
+ // Sets the URL requests are sent to for tests.
+ static void set_web_service_base_url_for_tests(
+ const char* base_url_for_tests);
+
void SetConfig(const Config& config);
void StartRecognition();
void EndRecognition();
diff --git a/chromium/content/browser/speech/speech_recognition_manager_impl.cc b/chromium/content/browser/speech/speech_recognition_manager_impl.cc
index 46b84d72f3c..b197c9c5535 100644
--- a/chromium/content/browser/speech/speech_recognition_manager_impl.cc
+++ b/chromium/content/browser/speech/speech_recognition_manager_impl.cc
@@ -4,10 +4,15 @@
#include "content/browser/speech/speech_recognition_manager_impl.h"
+#include <algorithm>
+#include <map>
#include <utility>
#include "base/bind.h"
+#include "base/callback.h"
#include "base/location.h"
+#include "base/memory/ref_counted_delete_on_sequence.h"
+#include "base/sequenced_task_runner.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
@@ -16,13 +21,15 @@
#include "content/browser/renderer_host/media/media_stream_ui_proxy.h"
#include "content/browser/speech/speech_recognition_engine.h"
#include "content/browser/speech/speech_recognizer_impl.h"
-#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
+#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/resource_context.h"
#include "content/public/browser/speech_recognition_event_listener.h"
#include "content/public/browser/speech_recognition_manager_delegate.h"
#include "content/public/browser/speech_recognition_session_config.h"
#include "content/public/browser/speech_recognition_session_context.h"
+#include "content/public/browser/web_contents.h"
+#include "content/public/browser/web_contents_observer.h"
#include "content/public/common/speech_recognition_error.h"
#include "content/public/common/speech_recognition_result.h"
#include "media/audio/audio_device_description.h"
@@ -45,6 +52,155 @@ SpeechRecognitionManagerImpl* g_speech_recognition_manager_impl;
} // namespace
+class SpeechRecognitionManagerImpl::FrameDeletionObserver {
+ public:
+ using FrameDeletedCallback =
+ base::RepeatingCallback<void(int /* session_id */)>;
+ explicit FrameDeletionObserver(FrameDeletedCallback frame_deleted_callback);
+
+ void CreateObserverForSession(int render_process_id,
+ int render_frame_id,
+ int session_id);
+
+ void RemoveObserverForSession(int render_process_id,
+ int render_frame_id,
+ int session_id);
+
+ private:
+ class ContentsObserver;
+ friend class ContentsObserver;
+
+ friend struct BrowserThread::DeleteOnThread<BrowserThread::UI>;
+ friend class base::DeleteHelper<FrameDeletionObserver>;
+
+ ~FrameDeletionObserver();
+
+ FrameDeletedCallback frame_deleted_callback_;
+ std::map<WebContents*, std::unique_ptr<ContentsObserver>> contents_observers_;
+};
+
+class SpeechRecognitionManagerImpl::FrameDeletionObserver::ContentsObserver
+ : public WebContentsObserver {
+ public:
+ ContentsObserver(WebContents* web_contents,
+ FrameDeletionObserver* parent_observer)
+ : WebContentsObserver(web_contents), parent_observer_(parent_observer) {}
+
+ void AddObservedFrame(RenderFrameHost* render_frame_host, int session_id);
+ void RemoveObservedFrame(RenderFrameHost* render_frame_host, int session_id);
+
+ void RenderFrameDeleted(RenderFrameHost* render_frame_host) override;
+
+ private:
+ FrameDeletionObserver* parent_observer_;
+
+ // A multimap from the frame to the session_ids started by that frame.
+ // Although a rare case, theoretically a frame can start multiple sessions.
+ std::multimap<RenderFrameHost*, int> observed_frames_;
+};
+
+SpeechRecognitionManagerImpl::FrameDeletionObserver::FrameDeletionObserver(
+ FrameDeletedCallback frame_deleted_callback)
+ : frame_deleted_callback_(std::move(frame_deleted_callback)) {}
+
+void SpeechRecognitionManagerImpl::FrameDeletionObserver::
+ CreateObserverForSession(int render_process_id,
+ int render_frame_id,
+ int session_id) {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+
+ RenderFrameHost* render_frame_host =
+ RenderFrameHost::FromID(render_process_id, render_frame_id);
+ if (!render_frame_host)
+ return;
+
+ WebContents* web_contents =
+ WebContents::FromRenderFrameHost(render_frame_host);
+ if (!web_contents)
+ return;
+
+ auto& observer = contents_observers_[web_contents];
+ if (!observer)
+ observer = std::make_unique<ContentsObserver>(web_contents, this);
+
+ observer->AddObservedFrame(render_frame_host, session_id);
+}
+
+void SpeechRecognitionManagerImpl::FrameDeletionObserver::
+ RemoveObserverForSession(int render_process_id,
+ int render_frame_id,
+ int session_id) {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+
+ RenderFrameHost* render_frame_host =
+ RenderFrameHost::FromID(render_process_id, render_frame_id);
+ if (!render_frame_host)
+ return;
+
+ WebContents* web_contents =
+ WebContents::FromRenderFrameHost(render_frame_host);
+ if (!web_contents)
+ return;
+
+ auto it = contents_observers_.find(web_contents);
+ if (it == contents_observers_.end())
+ return;
+
+ it->second->RemoveObservedFrame(render_frame_host, session_id);
+}
+
+SpeechRecognitionManagerImpl::FrameDeletionObserver::~FrameDeletionObserver() {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+
+ DCHECK_EQ(0u, contents_observers_.size());
+}
+
+void SpeechRecognitionManagerImpl::FrameDeletionObserver::ContentsObserver::
+ AddObservedFrame(RenderFrameHost* render_frame_host, int session_id) {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+
+ observed_frames_.emplace(render_frame_host, session_id);
+}
+
+void SpeechRecognitionManagerImpl::FrameDeletionObserver::ContentsObserver::
+ RemoveObservedFrame(RenderFrameHost* render_frame_host, int session_id) {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+
+ auto iters = observed_frames_.equal_range(render_frame_host);
+ auto it = std::find_if(iters.first, iters.second,
+ [render_frame_host, session_id](
+ std::pair<RenderFrameHost* const, int>& map_pair) {
+ return map_pair.first == render_frame_host &&
+ map_pair.second == session_id;
+ });
+
+ if (it == iters.second)
+ return;
+
+ observed_frames_.erase(it);
+ if (!observed_frames_.size())
+ parent_observer_->contents_observers_.erase(web_contents());
+
+ // |this| may be deleted.
+}
+
+void SpeechRecognitionManagerImpl::FrameDeletionObserver::ContentsObserver::
+ RenderFrameDeleted(RenderFrameHost* render_frame_host) {
+ auto iters = observed_frames_.equal_range(render_frame_host);
+ for (auto it = iters.first; it != iters.second; ++it) {
+ BrowserThread::GetTaskRunnerForThread(BrowserThread::IO)
+ ->PostTask(FROM_HERE,
+ base::BindOnce(parent_observer_->frame_deleted_callback_,
+ it->second));
+ }
+
+ observed_frames_.erase(iters.first, iters.second);
+ if (!observed_frames_.size())
+ parent_observer_->contents_observers_.erase(web_contents());
+
+ // |this| is likely deleted.
+}
+
SpeechRecognitionManager* SpeechRecognitionManager::GetInstance() {
if (manager_for_tests_)
return manager_for_tests_;
@@ -76,6 +232,10 @@ SpeechRecognitionManagerImpl::SpeechRecognitionManagerImpl(
weak_factory_(this) {
DCHECK(!g_speech_recognition_manager_impl);
g_speech_recognition_manager_impl = this;
+
+ frame_deletion_observer_.reset(new FrameDeletionObserver(
+ base::BindRepeating(&SpeechRecognitionManagerImpl::AbortSessionImpl,
+ weak_factory_.GetWeakPtr())));
}
SpeechRecognitionManagerImpl::~SpeechRecognitionManagerImpl() {
@@ -135,6 +295,17 @@ int SpeechRecognitionManagerImpl::CreateSession(
sessions_[session_id] = std::move(session);
+ // The deletion observer is owned by this class, so it's safe to use
+ // Unretained.
+ BrowserThread::GetTaskRunnerForThread(BrowserThread::UI)
+ ->PostTask(
+ FROM_HERE,
+ base::BindOnce(&SpeechRecognitionManagerImpl::FrameDeletionObserver::
+ CreateObserverForSession,
+ base::Unretained(frame_deletion_observer_.get()),
+ config.initial_context.render_process_id,
+ config.initial_context.render_frame_id, session_id));
+
return session_id;
}
@@ -164,11 +335,11 @@ void SpeechRecognitionManagerImpl::RecognitionAllowedCallback(int session_id,
bool ask_user,
bool is_allowed) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
- if (!SessionExists(session_id))
- return;
auto iter = sessions_.find(session_id);
- DCHECK(iter != sessions_.end());
+ if (iter == sessions_.end())
+ return;
+
Session* session = iter->second.get();
if (session->abort_requested)
@@ -229,10 +400,32 @@ void SpeechRecognitionManagerImpl::MediaRequestPermissionCallback(
void SpeechRecognitionManagerImpl::AbortSession(int session_id) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
- if (!SessionExists(session_id))
+ auto iter = sessions_.find(session_id);
+ if (iter == sessions_.end())
return;
+ // The deletion observer is owned by this class, so it's safe to use
+ // Unretained.
+ BrowserThread::GetTaskRunnerForThread(BrowserThread::UI)
+ ->PostTask(
+ FROM_HERE,
+ base::BindOnce(&SpeechRecognitionManagerImpl::FrameDeletionObserver::
+ RemoveObserverForSession,
+ base::Unretained(frame_deletion_observer_.get()),
+ iter->second->config.initial_context.render_process_id,
+ iter->second->config.initial_context.render_frame_id,
+ session_id));
+
+ AbortSessionImpl(session_id);
+}
+
+void SpeechRecognitionManagerImpl::AbortSessionImpl(int session_id) {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+
auto iter = sessions_.find(session_id);
+ if (iter == sessions_.end())
+ return;
+
iter->second->ui.reset();
if (iter->second->abort_requested)
@@ -248,10 +441,11 @@ void SpeechRecognitionManagerImpl::AbortSession(int session_id) {
void SpeechRecognitionManagerImpl::StopAudioCaptureForSession(int session_id) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
- if (!SessionExists(session_id))
- return;
auto iter = sessions_.find(session_id);
+ if (iter == sessions_.end())
+ return;
+
iter->second->ui.reset();
base::ThreadTaskRunnerHandle::Get()->PostTask(
@@ -398,17 +592,18 @@ void SpeechRecognitionManagerImpl::OnRecognitionEnd(int session_id) {
EVENT_RECOGNITION_ENDED));
}
-int SpeechRecognitionManagerImpl::GetSession(
- int render_process_id, int render_view_id, int request_id) const {
+int SpeechRecognitionManagerImpl::GetSession(int render_process_id,
+ int render_frame_id,
+ int request_id) const {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
auto iter = std::find_if(
sessions_.begin(), sessions_.end(),
- [render_process_id, render_view_id, request_id](
+ [render_process_id, render_frame_id, request_id](
const std::pair<int, std::unique_ptr<Session>>& session_pair) {
const SpeechRecognitionSessionContext& context =
session_pair.second->context;
return context.render_process_id == render_process_id &&
- context.render_view_id == render_view_id &&
+ context.render_frame_id == render_frame_id &&
context.request_id == request_id;
});
if (iter == sessions_.end())
@@ -422,29 +617,15 @@ SpeechRecognitionManagerImpl::GetSessionContext(int session_id) const {
return GetSession(session_id)->context;
}
-void SpeechRecognitionManagerImpl::AbortAllSessionsForRenderProcess(
- int render_process_id) {
- // This method gracefully destroys sessions for the listener. However, since
- // the listener itself is likely to be destroyed after this call, we avoid
- // dispatching further events to it, marking the |listener_is_active| flag.
- DCHECK_CURRENTLY_ON(BrowserThread::IO);
- for (const auto& session_pair : sessions_) {
- Session* session = session_pair.second.get();
- if (session->context.render_process_id == render_process_id) {
- AbortSession(session->id);
- session->listener_is_active = false;
- }
- }
-}
-
-void SpeechRecognitionManagerImpl::AbortAllSessionsForRenderView(
+void SpeechRecognitionManagerImpl::AbortAllSessionsForRenderFrame(
int render_process_id,
- int render_view_id) {
+ int render_frame_id) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
+
for (const auto& session_pair : sessions_) {
Session* session = session_pair.second.get();
if (session->context.render_process_id == render_process_id &&
- session->context.render_view_id == render_view_id) {
+ session->context.render_frame_id == render_frame_id) {
AbortSession(session->id);
}
}
@@ -475,7 +656,7 @@ void SpeechRecognitionManagerImpl::DispatchEvent(int session_id,
// This FSM handles the evolution of each session, from the viewpoint of the
// interaction with the user (that may be either the browser end-user which
-// interacts with UI bubbles, or JS developer intracting with JS methods).
+// interacts with UI bubbles, or JS developer interacting with JS methods).
// All the events received by the SpeechRecognizer instances (one for each
// session) are always routed to the SpeechRecognitionEventListener(s)
// regardless the choices taken in this FSM.
@@ -626,7 +807,7 @@ SpeechRecognitionManagerImpl::GetSession(int session_id) const {
SpeechRecognitionEventListener* SpeechRecognitionManagerImpl::GetListener(
int session_id) const {
Session* session = GetSession(session_id);
- if (session->listener_is_active && session->config.event_listener)
+ if (session->config.event_listener)
return session->config.event_listener.get();
return nullptr;
}
@@ -642,10 +823,7 @@ SpeechRecognitionManagerImpl::GetSessionConfig(int session_id) const {
}
SpeechRecognitionManagerImpl::Session::Session()
- : id(kSessionIDInvalid),
- abort_requested(false),
- listener_is_active(true) {
-}
+ : id(kSessionIDInvalid), abort_requested(false) {}
SpeechRecognitionManagerImpl::Session::~Session() {
}
diff --git a/chromium/content/browser/speech/speech_recognition_manager_impl.h b/chromium/content/browser/speech/speech_recognition_manager_impl.h
index 167714a2b48..89a8f048a54 100644
--- a/chromium/content/browser/speech/speech_recognition_manager_impl.h
+++ b/chromium/content/browser/speech/speech_recognition_manager_impl.h
@@ -8,10 +8,10 @@
#include <memory>
#include <string>
-#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/containers/flat_map.h"
#include "base/memory/weak_ptr.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/speech_recognition_event_listener.h"
#include "content/public/browser/speech_recognition_manager.h"
#include "content/public/browser/speech_recognition_session_config.h"
@@ -41,7 +41,7 @@ class SpeechRecognizer;
// are waiting for results but not recording audio.
//
// The SpeechRecognitionManager has the following responsibilities:
-// - Handles requests received from various render views and makes sure only
+// - Handles requests received from various render frames and makes sure only
// one of them accesses the audio device at any given time.
// - Handles the instantiation of SpeechRecognitionEngine objects when
// requested by SpeechRecognitionSessions.
@@ -61,16 +61,15 @@ class CONTENT_EXPORT SpeechRecognitionManagerImpl
int CreateSession(const SpeechRecognitionSessionConfig& config) override;
void StartSession(int session_id) override;
void AbortSession(int session_id) override;
- void AbortAllSessionsForRenderProcess(int render_process_id) override;
- void AbortAllSessionsForRenderView(int render_process_id,
- int render_view_id) override;
+ void AbortAllSessionsForRenderFrame(int render_process_id,
+ int render_frame_id) override;
void StopAudioCaptureForSession(int session_id) override;
const SpeechRecognitionSessionConfig& GetSessionConfig(
int session_id) const override;
SpeechRecognitionSessionContext GetSessionContext(
int session_id) const override;
int GetSession(int render_process_id,
- int render_view_id,
+ int render_frame_id,
int request_id) const override;
// SpeechRecognitionEventListener methods.
@@ -105,6 +104,8 @@ class CONTENT_EXPORT SpeechRecognitionManagerImpl
~SpeechRecognitionManagerImpl() override;
private:
+ class FrameDeletionObserver;
+
// Data types for the internal Finite State Machine (FSM).
enum FSMState {
SESSION_STATE_IDLE = 0,
@@ -128,13 +129,14 @@ class CONTENT_EXPORT SpeechRecognitionManagerImpl
int id;
bool abort_requested;
- bool listener_is_active;
SpeechRecognitionSessionConfig config;
SpeechRecognitionSessionContext context;
scoped_refptr<SpeechRecognizer> recognizer;
std::unique_ptr<MediaStreamUIProxy> ui;
};
+ void AbortSessionImpl(int session_id);
+
// Callback issued by the SpeechRecognitionManagerDelegate for reporting
// asynchronously the result of the CheckRecognitionIsAllowed call.
void RecognitionAllowedCallback(int session_id,
@@ -175,6 +177,11 @@ class CONTENT_EXPORT SpeechRecognitionManagerImpl
SpeechRecognitionEventListener* GetDelegateListener() const;
int GetNextSessionID();
+ // This class lives on the UI thread; all access to it must be done on that
+ // thread.
+ std::unique_ptr<FrameDeletionObserver, BrowserThread::DeleteOnUIThread>
+ frame_deletion_observer_;
+
media::AudioSystem* audio_system_;
media::AudioManager* audio_manager_;
MediaStreamManager* media_stream_manager_;
diff --git a/chromium/content/browser/speech/speech_recognizer_impl.cc b/chromium/content/browser/speech/speech_recognizer_impl.cc
index b89e70c7ed4..7cb388ad30a 100644
--- a/chromium/content/browser/speech/speech_recognizer_impl.cc
+++ b/chromium/content/browser/speech/speech_recognizer_impl.cc
@@ -15,6 +15,7 @@
#include "content/browser/browser_main_loop.h"
#include "content/browser/media/media_internals.h"
#include "content/browser/speech/audio_buffer.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/speech_recognition_event_listener.h"
#include "media/audio/audio_manager.h"
#include "media/audio/audio_system.h"
diff --git a/chromium/content/browser/ssl/ssl_manager.cc b/chromium/content/browser/ssl/ssl_manager.cc
index f3e19156ea2..235a0c00803 100644
--- a/chromium/content/browser/ssl/ssl_manager.cc
+++ b/chromium/content/browser/ssl/ssl_manager.cc
@@ -9,7 +9,6 @@
#include "base/bind.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/utf_string_conversions.h"
#include "base/supports_user_data.h"
@@ -345,7 +344,8 @@ void SSLManager::OnCertErrorInternal(std::unique_ptr<SSLErrorHandler> handler,
GetContentClient()->browser()->AllowCertificateError(
web_contents, cert_error, ssl_info, request_url, resource_type, fatal,
expired_previous_decision,
- base::Bind(&OnAllowCertificateWithRecordDecision, true, callback));
+ base::Bind(&OnAllowCertificateWithRecordDecision, true,
+ std::move(callback)));
}
bool SSLManager::UpdateEntry(NavigationEntryImpl* entry,
diff --git a/chromium/content/browser/startup_task_runner.cc b/chromium/content/browser/startup_task_runner.cc
index 8e680bd6d08..5adeb6ae6e1 100644
--- a/chromium/content/browser/startup_task_runner.cc
+++ b/chromium/content/browser/startup_task_runner.cc
@@ -17,7 +17,7 @@ StartupTaskRunner::StartupTaskRunner(
StartupTaskRunner::~StartupTaskRunner() {}
-void StartupTaskRunner::AddTask(StartupTask& callback) {
+void StartupTaskRunner::AddTask(StartupTask callback) {
task_list_.push_back(callback);
}
diff --git a/chromium/content/browser/startup_task_runner.h b/chromium/content/browser/startup_task_runner.h
index 8f70ed2114f..c5f09f66e45 100644
--- a/chromium/content/browser/startup_task_runner.h
+++ b/chromium/content/browser/startup_task_runner.h
@@ -43,7 +43,7 @@ class CONTENT_EXPORT StartupTaskRunner {
~StartupTaskRunner();
// Add a task to the queue of startup tasks to be run.
- void AddTask(StartupTask& callback);
+ void AddTask(StartupTask callback);
// Start running the tasks asynchronously.
void StartRunningTasksAsync();
diff --git a/chromium/content/browser/startup_task_runner_unittest.cc b/chromium/content/browser/startup_task_runner_unittest.cc
index 29fa995c0e0..738940a0a07 100644
--- a/chromium/content/browser/startup_task_runner_unittest.cc
+++ b/chromium/content/browser/startup_task_runner_unittest.cc
@@ -120,11 +120,11 @@ TEST_F(StartupTaskRunnerTest, SynchronousExecution) {
StartupTask task1 =
base::Bind(&StartupTaskRunnerTest::Task1, base::Unretained(this));
- runner.AddTask(task1);
+ runner.AddTask(std::move(task1));
EXPECT_EQ(GetLastTask(), 0);
StartupTask task2 =
base::Bind(&StartupTaskRunnerTest::Task2, base::Unretained(this));
- runner.AddTask(task2);
+ runner.AddTask(std::move(task2));
// Nothing should run until we tell them to.
EXPECT_EQ(GetLastTask(), 0);
@@ -158,11 +158,11 @@ TEST_F(StartupTaskRunnerTest, NullObserver) {
StartupTask task1 =
base::Bind(&StartupTaskRunnerTest::Task1, base::Unretained(this));
- runner.AddTask(task1);
+ runner.AddTask(std::move(task1));
EXPECT_EQ(GetLastTask(), 0);
StartupTask task2 =
base::Bind(&StartupTaskRunnerTest::Task2, base::Unretained(this));
- runner.AddTask(task2);
+ runner.AddTask(std::move(task2));
// Nothing should run until we tell them to.
EXPECT_EQ(GetLastTask(), 0);
@@ -193,11 +193,11 @@ TEST_F(StartupTaskRunnerTest, SynchronousExecutionFailedTask) {
StartupTask task3 =
base::Bind(&StartupTaskRunnerTest::FailingTask, base::Unretained(this));
- runner.AddTask(task3);
+ runner.AddTask(std::move(task3));
EXPECT_EQ(GetLastTask(), 0);
StartupTask task2 =
base::Bind(&StartupTaskRunnerTest::Task2, base::Unretained(this));
- runner.AddTask(task2);
+ runner.AddTask(std::move(task2));
// Nothing should run until we tell them to.
EXPECT_EQ(GetLastTask(), 0);
@@ -234,10 +234,10 @@ TEST_F(StartupTaskRunnerTest, AsynchronousExecution) {
StartupTask task1 =
base::Bind(&StartupTaskRunnerTest::Task1, base::Unretained(this));
- runner.AddTask(task1);
+ runner.AddTask(std::move(task1));
StartupTask task2 =
base::Bind(&StartupTaskRunnerTest::Task2, base::Unretained(this));
- runner.AddTask(task2);
+ runner.AddTask(std::move(task2));
// Nothing should run until we tell them to.
EXPECT_EQ(GetLastTask(), 0);
@@ -280,10 +280,10 @@ TEST_F(StartupTaskRunnerTest, AsynchronousExecutionFailedTask) {
StartupTask task3 =
base::Bind(&StartupTaskRunnerTest::FailingTask, base::Unretained(this));
- runner.AddTask(task3);
+ runner.AddTask(std::move(task3));
StartupTask task2 =
base::Bind(&StartupTaskRunnerTest::Task2, base::Unretained(this));
- runner.AddTask(task2);
+ runner.AddTask(std::move(task2));
// Nothing should run until we tell them to.
EXPECT_EQ(GetLastTask(), 0);
diff --git a/chromium/content/browser/storage_partition_impl.cc b/chromium/content/browser/storage_partition_impl.cc
index 4a651d96253..9f0423752c5 100644
--- a/chromium/content/browser/storage_partition_impl.cc
+++ b/chromium/content/browser/storage_partition_impl.cc
@@ -27,7 +27,9 @@
#include "content/browser/gpu/shader_cache_factory.h"
#include "content/browser/loader/prefetch_url_loader_service.h"
#include "content/browser/notifications/platform_notification_context_impl.h"
+#include "content/browser/web_package/web_package_context_impl.h"
#include "content/common/dom_storage/dom_storage_types.h"
+#include "content/common/service_worker/service_worker_utils.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
@@ -45,7 +47,7 @@
#include "net/cookies/cookie_monster.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#include "services/network/network_context.h"
#include "services/network/network_service.h"
#include "services/network/public/cpp/features.h"
@@ -54,7 +56,7 @@
#include "storage/browser/blob/blob_storage_context.h"
#include "storage/browser/database/database_tracker.h"
#include "storage/browser/quota/quota_manager.h"
-#include "third_party/WebKit/public/mojom/quota/quota_types.mojom.h"
+#include "third_party/blink/public/mojom/quota/quota_types.mojom.h"
#if !defined(OS_ANDROID)
#include "content/browser/host_zoom_map_impl.h"
@@ -291,7 +293,7 @@ class StoragePartitionImpl::NetworkContextOwner {
};
class StoragePartitionImpl::URLLoaderFactoryForBrowserProcess
- : public SharedURLLoaderFactory {
+ : public network::SharedURLLoaderFactory {
public:
explicit URLLoaderFactoryForBrowserProcess(
StoragePartitionImpl* storage_partition)
@@ -316,7 +318,7 @@ class StoragePartitionImpl::URLLoaderFactoryForBrowserProcess
}
// SharedURLLoaderFactory implementation:
- std::unique_ptr<SharedURLLoaderFactoryInfo> Clone() override {
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo> Clone() override {
NOTREACHED() << "This isn't supported. If you need a SharedURLLoaderFactory"
" on the IO thread, get it from URLLoaderFactoryGetter.";
return nullptr;
@@ -581,7 +583,7 @@ std::unique_ptr<StoragePartitionImpl> StoragePartitionImpl::Create(
// Ensure that these methods are called on the UI thread, except for
// unittests where a UI thread might not have been created.
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI) ||
- !BrowserThread::IsMessageLoopValid(BrowserThread::UI));
+ !BrowserThread::IsThreadInitialized(BrowserThread::UI));
base::FilePath partition_path =
context->GetPath().Append(relative_partition_path);
@@ -632,8 +634,8 @@ std::unique_ptr<StoragePartitionImpl> StoragePartitionImpl::Create(
partition->service_worker_context_ = new ServiceWorkerContextWrapper(context);
partition->service_worker_context_->set_storage_partition(partition.get());
- partition->shared_worker_service_ =
- std::make_unique<SharedWorkerServiceImpl>();
+ partition->shared_worker_service_ = std::make_unique<SharedWorkerServiceImpl>(
+ partition->service_worker_context_);
partition->appcache_service_ =
new ChromeAppCacheService(quota_manager_proxy.get());
@@ -651,6 +653,8 @@ std::unique_ptr<StoragePartitionImpl> StoragePartitionImpl::Create(
partition->service_worker_context_);
partition->platform_notification_context_->Initialize();
+ partition->web_package_context_ = std::make_unique<WebPackageContextImpl>();
+
partition->background_fetch_context_ =
new BackgroundFetchContext(context, partition->service_worker_context_);
@@ -667,7 +671,8 @@ std::unique_ptr<StoragePartitionImpl> StoragePartitionImpl::Create(
scoped_refptr<ChromeBlobStorageContext> blob_context =
ChromeBlobStorageContext::GetFor(context);
- if (base::FeatureList::IsEnabled(network::features::kNetworkService)) {
+ if (base::FeatureList::IsEnabled(network::features::kNetworkService) ||
+ ServiceWorkerUtils::IsServicificationEnabled()) {
BlobURLLoaderFactory::BlobContextGetter blob_getter =
base::BindOnce(&BlobStorageContextGetterForStorage, blob_context);
partition->blob_url_loader_factory_ =
@@ -708,28 +713,27 @@ StoragePartitionImpl::GetMediaURLRequestContext() {
}
network::mojom::NetworkContext* StoragePartitionImpl::GetNetworkContext() {
- // Create the NetworkContext as needed, when the network service is disabled.
- if (!base::FeatureList::IsEnabled(network::features::kNetworkService)) {
- if (network_context_)
- return network_context_.get();
- DCHECK(!network_context_owner_);
- network_context_owner_ = std::make_unique<NetworkContextOwner>();
- BrowserThread::PostTask(
- BrowserThread::IO, FROM_HERE,
- base::BindOnce(&NetworkContextOwner::Initialize,
- base::Unretained(network_context_owner_.get()),
- MakeRequest(&network_context_), url_request_context_));
- return network_context_.get();
- }
-
if (!network_context_.is_bound() || network_context_.encountered_error()) {
network_context_ = GetContentClient()->browser()->CreateNetworkContext(
browser_context_, is_in_memory_, relative_partition_path_);
+ if (!network_context_) {
+ // TODO(mmenke): Remove once https://crbug.com/827928 is fixed.
+ CHECK(url_request_context_);
+
+ DCHECK(!base::FeatureList::IsEnabled(network::features::kNetworkService));
+ DCHECK(!network_context_owner_);
+ network_context_owner_ = std::make_unique<NetworkContextOwner>();
+ BrowserThread::PostTask(
+ BrowserThread::IO, FROM_HERE,
+ base::BindOnce(&NetworkContextOwner::Initialize,
+ base::Unretained(network_context_owner_.get()),
+ MakeRequest(&network_context_), url_request_context_));
+ }
}
return network_context_.get();
}
-scoped_refptr<SharedURLLoaderFactory>
+scoped_refptr<network::SharedURLLoaderFactory>
StoragePartitionImpl::GetURLLoaderFactoryForBrowserProcess() {
if (!shared_url_loader_factory_for_browser_process_) {
shared_url_loader_factory_for_browser_process_ =
@@ -738,6 +742,11 @@ StoragePartitionImpl::GetURLLoaderFactoryForBrowserProcess() {
return shared_url_loader_factory_for_browser_process_;
}
+std::unique_ptr<network::SharedURLLoaderFactoryInfo>
+StoragePartitionImpl::GetURLLoaderFactoryForBrowserProcessIOThread() {
+ return url_loader_factory_getter_->GetNetworkFactoryInfo();
+}
+
network::mojom::CookieManager*
StoragePartitionImpl::GetCookieManagerForBrowserProcess() {
// Create the CookieManager as needed.
@@ -810,6 +819,10 @@ StoragePartitionImpl::GetPlatformNotificationContext() {
return platform_notification_context_.get();
}
+WebPackageContext* StoragePartitionImpl::GetWebPackageContext() {
+ return web_package_context_.get();
+}
+
BackgroundFetchContext* StoragePartitionImpl::GetBackgroundFetchContext() {
return background_fetch_context_.get();
}
@@ -930,9 +943,10 @@ void StoragePartitionImpl::QuotaManagedDataDeletionHelper::ClearDataOnIOThread(
// ClearQuotaManagedOriginsOnIOThread().
quota_manager->GetOriginsModifiedSince(
blink::mojom::StorageType::kPersistent, begin,
- base::Bind(&QuotaManagedDataDeletionHelper::ClearOriginsOnIOThread,
- base::Unretained(this), base::RetainedRef(quota_manager),
- special_storage_policy, origin_matcher, decrement_callback));
+ base::BindOnce(&QuotaManagedDataDeletionHelper::ClearOriginsOnIOThread,
+ base::Unretained(this), base::RetainedRef(quota_manager),
+ special_storage_policy, origin_matcher,
+ decrement_callback));
}
// Do the same for temporary quota.
@@ -940,9 +954,10 @@ void StoragePartitionImpl::QuotaManagedDataDeletionHelper::ClearDataOnIOThread(
IncrementTaskCountOnIO();
quota_manager->GetOriginsModifiedSince(
blink::mojom::StorageType::kTemporary, begin,
- base::Bind(&QuotaManagedDataDeletionHelper::ClearOriginsOnIOThread,
- base::Unretained(this), base::RetainedRef(quota_manager),
- special_storage_policy, origin_matcher, decrement_callback));
+ base::BindOnce(&QuotaManagedDataDeletionHelper::ClearOriginsOnIOThread,
+ base::Unretained(this), base::RetainedRef(quota_manager),
+ special_storage_policy, origin_matcher,
+ decrement_callback));
}
// Do the same for syncable quota.
@@ -950,9 +965,10 @@ void StoragePartitionImpl::QuotaManagedDataDeletionHelper::ClearDataOnIOThread(
IncrementTaskCountOnIO();
quota_manager->GetOriginsModifiedSince(
blink::mojom::StorageType::kSyncable, begin,
- base::Bind(&QuotaManagedDataDeletionHelper::ClearOriginsOnIOThread,
- base::Unretained(this), base::RetainedRef(quota_manager),
- special_storage_policy, origin_matcher, decrement_callback));
+ base::BindOnce(&QuotaManagedDataDeletionHelper::ClearOriginsOnIOThread,
+ base::Unretained(this), base::RetainedRef(quota_manager),
+ special_storage_policy, origin_matcher,
+ std::move(decrement_callback)));
}
DecrementTaskCountOnIO();
@@ -993,8 +1009,8 @@ void StoragePartitionImpl::QuotaManagedDataDeletionHelper::
quota_manager->DeleteOriginData(
*origin, quota_storage_type,
StoragePartitionImpl::GenerateQuotaClientMask(remove_mask_),
- base::Bind(&OnQuotaManagedOriginDeleted, origin->GetOrigin(),
- quota_storage_type, deletion_task_count, callback));
+ base::BindOnce(&OnQuotaManagedOriginDeleted, origin->GetOrigin(),
+ quota_storage_type, deletion_task_count, callback));
}
(*deletion_task_count)--;
@@ -1104,7 +1120,7 @@ void StoragePartitionImpl::DataDeletionHelper::ClearDataOnUIThread(
FROM_HERE,
base::BindOnce(&ClearPluginPrivateDataOnFileTaskRunner,
base::WrapRefCounted(filesystem_context), storage_origin,
- begin, end, decrement_callback));
+ begin, end, std::move(decrement_callback)));
}
#endif // BUILDFLAG(ENABLE_PLUGINS)
diff --git a/chromium/content/browser/storage_partition_impl.h b/chromium/content/browser/storage_partition_impl.h
index 580d2e0d78d..38d0aadaad6 100644
--- a/chromium/content/browser/storage_partition_impl.h
+++ b/chromium/content/browser/storage_partition_impl.h
@@ -50,6 +50,7 @@ class BackgroundFetchContext;
class BlobRegistryWrapper;
class BlobURLLoaderFactory;
class PrefetchURLLoaderService;
+class WebPackageContextImpl;
class CONTENT_EXPORT StoragePartitionImpl
: public StoragePartition,
@@ -91,8 +92,10 @@ class CONTENT_EXPORT StoragePartitionImpl
net::URLRequestContextGetter* GetURLRequestContext() override;
net::URLRequestContextGetter* GetMediaURLRequestContext() override;
network::mojom::NetworkContext* GetNetworkContext() override;
- scoped_refptr<SharedURLLoaderFactory> GetURLLoaderFactoryForBrowserProcess()
- override;
+ scoped_refptr<network::SharedURLLoaderFactory>
+ GetURLLoaderFactoryForBrowserProcess() override;
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo>
+ GetURLLoaderFactoryForBrowserProcessIOThread() override;
network::mojom::CookieManager* GetCookieManagerForBrowserProcess() override;
storage::QuotaManager* GetQuotaManager() override;
ChromeAppCacheService* GetAppCacheService() override;
@@ -110,6 +113,7 @@ class CONTENT_EXPORT StoragePartitionImpl
ZoomLevelDelegate* GetZoomLevelDelegate() override;
#endif // !defined(OS_ANDROID)
PlatformNotificationContextImpl* GetPlatformNotificationContext() override;
+ WebPackageContext* GetWebPackageContext() override;
void ClearDataForOrigin(uint32_t remove_mask,
uint32_t quota_storage_remove_mask,
const GURL& storage_origin) override;
@@ -301,6 +305,7 @@ class CONTENT_EXPORT StoragePartitionImpl
scoped_refptr<HostZoomLevelContext> host_zoom_level_context_;
#endif // !defined(OS_ANDROID)
scoped_refptr<PlatformNotificationContextImpl> platform_notification_context_;
+ std::unique_ptr<WebPackageContextImpl> web_package_context_;
scoped_refptr<BackgroundFetchContext> background_fetch_context_;
scoped_refptr<BackgroundSyncContext> background_sync_context_;
scoped_refptr<PaymentAppContextImpl> payment_app_context_;
diff --git a/chromium/content/browser/storage_partition_impl_map.cc b/chromium/content/browser/storage_partition_impl_map.cc
index 09937db9157..7225a2a55d2 100644
--- a/chromium/content/browser/storage_partition_impl_map.cc
+++ b/chromium/content/browser/storage_partition_impl_map.cc
@@ -14,7 +14,6 @@
#include "base/files/file_util.h"
#include "base/location.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
@@ -403,19 +402,13 @@ StoragePartitionImpl* StoragePartitionImplMap::Get(
ChromeBlobStorageContext::GetFor(browser_context_);
StreamContext* stream_context = StreamContext::GetFor(browser_context_);
ProtocolHandlerMap protocol_handlers;
- protocol_handlers[url::kBlobScheme] =
- linked_ptr<net::URLRequestJobFactory::ProtocolHandler>(
- new BlobProtocolHandler(blob_storage_context, stream_context));
- protocol_handlers[url::kFileSystemScheme] =
- linked_ptr<net::URLRequestJobFactory::ProtocolHandler>(
- CreateFileSystemProtocolHandler(partition_domain,
- partition->GetFileSystemContext()));
+ protocol_handlers[url::kBlobScheme] = std::make_unique<BlobProtocolHandler>(
+ blob_storage_context, stream_context);
+ protocol_handlers[url::kFileSystemScheme] = CreateFileSystemProtocolHandler(
+ partition_domain, partition->GetFileSystemContext());
for (const auto& scheme : URLDataManagerBackend::GetWebUISchemes()) {
- protocol_handlers[scheme] =
- linked_ptr<net::URLRequestJobFactory::ProtocolHandler>(
- URLDataManagerBackend::CreateProtocolHandler(
- browser_context_->GetResourceContext(), blob_storage_context)
- .release());
+ protocol_handlers[scheme] = URLDataManagerBackend::CreateProtocolHandler(
+ browser_context_->GetResourceContext(), blob_storage_context);
}
URLRequestInterceptorScopedVector request_interceptors;
@@ -546,7 +539,7 @@ void StoragePartitionImplMap::PostCreateInitialization(
}
// Check first to avoid memory leak in unittests.
- if (BrowserThread::IsMessageLoopValid(BrowserThread::IO)) {
+ if (BrowserThread::IsThreadInitialized(BrowserThread::IO)) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(
diff --git a/chromium/content/browser/storage_partition_impl_map_unittest.cc b/chromium/content/browser/storage_partition_impl_map_unittest.cc
index 06dff808934..89fc1685515 100644
--- a/chromium/content/browser/storage_partition_impl_map_unittest.cc
+++ b/chromium/content/browser/storage_partition_impl_map_unittest.cc
@@ -8,8 +8,10 @@
#include "base/files/file_util.h"
#include "base/run_loop.h"
-#include "base/test/scoped_task_environment.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/test/test_browser_context.h"
+#include "content/public/test/test_browser_thread_bundle.h"
+#include "content/public/test/test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace content {
@@ -65,8 +67,8 @@ TEST(StoragePartitionConfigTest, OperatorLess) {
}
TEST(StoragePartitionImplMapTest, GarbageCollect) {
+ TestBrowserThreadBundle thread_bundle;
TestBrowserContext browser_context;
- base::test::ScopedTaskEnvironment scoped_task_environment;
StoragePartitionImplMap storage_partition_impl_map(&browser_context);
std::unique_ptr<base::hash_set<base::FilePath>> active_paths(
@@ -87,7 +89,7 @@ TEST(StoragePartitionImplMapTest, GarbageCollect) {
storage_partition_impl_map.GarbageCollect(std::move(active_paths),
run_loop.QuitClosure());
run_loop.Run();
- scoped_task_environment.RunUntilIdle();
+ content::RunAllPendingInMessageLoop(content::BrowserThread::IO);
EXPECT_TRUE(base::PathExists(active_path));
EXPECT_FALSE(base::PathExists(inactive_path));
diff --git a/chromium/content/browser/storage_partition_impl_unittest.cc b/chromium/content/browser/storage_partition_impl_unittest.cc
index cfb2f80782e..b51d8011af8 100644
--- a/chromium/content/browser/storage_partition_impl_unittest.cc
+++ b/chromium/content/browser/storage_partition_impl_unittest.cc
@@ -13,8 +13,7 @@
#include "base/single_thread_task_runner.h"
#include "base/threading/thread.h"
#include "base/threading/thread_task_runner_handle.h"
-#include "components/leveldb/public/cpp/util.h"
-#include "content/browser/browser_thread_impl.h"
+#include "components/services/leveldb/public/cpp/util.h"
#include "content/browser/dom_storage/local_storage_database.pb.h"
#include "content/browser/gpu/shader_cache_factory.h"
#include "content/browser/storage_partition_impl.h"
@@ -29,14 +28,13 @@
#include "net/cookies/cookie_store.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#include "storage/browser/quota/quota_manager.h"
#include "storage/browser/test/mock_quota_manager.h"
#include "storage/browser/test/mock_special_storage_policy.h"
#include "testing/gtest/include/gtest/gtest.h"
#if BUILDFLAG(ENABLE_PLUGINS)
-#include "base/memory/ptr_util.h"
#include "ppapi/shared_impl/ppapi_constants.h" // nogncheck
#include "storage/browser/fileapi/async_file_util.h"
#include "storage/browser/fileapi/file_system_context.h"
@@ -344,8 +342,8 @@ class RemovePluginPrivateDataTester {
async_file_util->CreateOrOpen(
std::move(operation_context), clearkey_file_,
base::File::FLAG_OPEN | base::File::FLAG_WRITE,
- base::Bind(&RemovePluginPrivateDataTester::OnFileOpened,
- base::Unretained(this), &file, &await_completion));
+ base::BindOnce(&RemovePluginPrivateDataTester::OnFileOpened,
+ base::Unretained(this), &file, &await_completion));
await_completion.BlockUntilNotified();
return file;
}
@@ -391,8 +389,8 @@ class RemovePluginPrivateDataTester {
storage::QuotaManager::kNoLimit);
file_util->EnsureFileExists(
std::move(operation_context), file_url,
- base::Bind(&RemovePluginPrivateDataTester::OnFileCreated,
- base::Unretained(this), &await_completion));
+ base::BindOnce(&RemovePluginPrivateDataTester::OnFileCreated,
+ base::Unretained(this), &await_completion));
await_completion.BlockUntilNotified();
return file_url;
}
@@ -406,8 +404,8 @@ class RemovePluginPrivateDataTester {
filesystem_context_);
file_util->DeleteFile(
std::move(operation_context), file_url,
- base::Bind(&RemovePluginPrivateDataTester::OnFileDeleted,
- base::Unretained(this), &await_completion));
+ base::BindOnce(&RemovePluginPrivateDataTester::OnFileDeleted,
+ base::Unretained(this), &await_completion));
await_completion.BlockUntilNotified();
}
@@ -421,10 +419,10 @@ class RemovePluginPrivateDataTester {
std::unique_ptr<storage::FileSystemOperationContext> operation_context =
std::make_unique<storage::FileSystemOperationContext>(
filesystem_context_);
- file_util->Touch(std::move(operation_context), file_url, time_stamp,
- time_stamp,
- base::Bind(&RemovePluginPrivateDataTester::OnFileTouched,
- base::Unretained(this), &await_completion));
+ file_util->Touch(
+ std::move(operation_context), file_url, time_stamp, time_stamp,
+ base::BindOnce(&RemovePluginPrivateDataTester::OnFileTouched,
+ base::Unretained(this), &await_completion));
await_completion.BlockUntilNotified();
}
@@ -1152,7 +1150,7 @@ TEST_F(StoragePartitionImplTest, RemoveCookieWithMatcher) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(&ClearCookiesWithMatcher, partition, base::Time(),
- base::Time::Max(), false_predicate, &run_loop));
+ base::Time::Max(), std::move(false_predicate), &run_loop));
run_loop.RunUntilIdle();
EXPECT_TRUE(tester.ContainsCookie());
@@ -1161,7 +1159,7 @@ TEST_F(StoragePartitionImplTest, RemoveCookieWithMatcher) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(&ClearCookiesWithMatcher, partition, base::Time(),
- base::Time::Max(), true_predicate, &run_loop2));
+ base::Time::Max(), std::move(true_predicate), &run_loop2));
run_loop2.RunUntilIdle();
EXPECT_FALSE(tester.ContainsCookie());
}
diff --git a/chromium/content/browser/streams/OWNERS b/chromium/content/browser/streams/OWNERS
index fe068abcea7..a11430957ec 100644
--- a/chromium/content/browser/streams/OWNERS
+++ b/chromium/content/browser/streams/OWNERS
@@ -1,4 +1,5 @@
-tyoshino@chromium.org
+ricea@chromium.org
+yhirano@chromium.org
# TEAM: blink-network-dev@chromium.org
# COMPONENT: Blink>Network>StreamsAPI
diff --git a/chromium/content/browser/streams/stream.cc b/chromium/content/browser/streams/stream.cc
index 5cb066a5ac3..8a018a7895f 100644
--- a/chromium/content/browser/streams/stream.cc
+++ b/chromium/content/browser/streams/stream.cc
@@ -87,15 +87,7 @@ void Stream::Abort() {
void Stream::OnResponseStarted(const net::HttpResponseInfo& response_info) {
DCHECK(!metadata_);
- if (response_info.headers) {
- metadata_.reset(new StreamMetadata(response_info));
- return;
- }
- // Assume request wasn't backed by HTTP and produce fake "200 OK" response,
- // as some consumers expect it for, say, data urls.
- net::HttpResponseInfo fake_response_info = response_info;
- fake_response_info.headers = new net::HttpResponseHeaders("HTTP/1.1 200 OK");
- metadata_ = std::make_unique<StreamMetadata>(fake_response_info);
+ metadata_ = std::make_unique<StreamMetadata>(response_info);
}
void Stream::UpdateNetworkStats(int64_t raw_body_bytes, int64_t total_bytes) {
diff --git a/chromium/content/browser/streams/stream_context.cc b/chromium/content/browser/streams/stream_context.cc
index 7aafca3aafc..0ab6a2d6f96 100644
--- a/chromium/content/browser/streams/stream_context.cc
+++ b/chromium/content/browser/streams/stream_context.cc
@@ -5,7 +5,6 @@
#include "content/browser/streams/stream_context.h"
#include "base/bind.h"
-#include "base/memory/ptr_util.h"
#include "content/browser/streams/stream_registry.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
@@ -29,7 +28,7 @@ StreamContext* StreamContext::GetFor(BrowserContext* context) {
kStreamContextKeyName,
std::make_unique<UserDataAdapter<StreamContext>>(stream.get()));
// Check first to avoid memory leak in unittests.
- if (BrowserThread::IsMessageLoopValid(BrowserThread::IO)) {
+ if (BrowserThread::IsThreadInitialized(BrowserThread::IO)) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&StreamContext::InitializeOnIOThread, stream));
@@ -51,7 +50,7 @@ void StreamContext::DeleteOnCorrectThread() const {
// the current thread.
// TODO(zork): Remove this custom deleter, and fix the leaks in all the
// tests.
- if (BrowserThread::IsMessageLoopValid(BrowserThread::IO) &&
+ if (BrowserThread::IsThreadInitialized(BrowserThread::IO) &&
!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, this);
return;
diff --git a/chromium/content/browser/streams/stream_url_request_job_unittest.cc b/chromium/content/browser/streams/stream_url_request_job_unittest.cc
index c4f9e232136..82fc52257da 100644
--- a/chromium/content/browser/streams/stream_url_request_job_unittest.cc
+++ b/chromium/content/browser/streams/stream_url_request_job_unittest.cc
@@ -4,7 +4,6 @@
#include "content/browser/streams/stream_url_request_job.h"
-#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/test/test_simple_task_runner.h"
diff --git a/chromium/content/browser/theme_helper_mac.h b/chromium/content/browser/theme_helper_mac.h
index 52da98f1b9c..644b37b5b2d 100644
--- a/chromium/content/browser/theme_helper_mac.h
+++ b/chromium/content/browser/theme_helper_mac.h
@@ -9,7 +9,7 @@
#include "base/memory/singleton.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
-#include "third_party/WebKit/public/platform/mac/WebScrollbarTheme.h"
+#include "third_party/blink/public/platform/mac/web_scrollbar_theme.h"
namespace content {
diff --git a/chromium/content/browser/top_document_isolation_browsertest.cc b/chromium/content/browser/top_document_isolation_browsertest.cc
index de9288e443b..6f6e7bef494 100644
--- a/chromium/content/browser/top_document_isolation_browsertest.cc
+++ b/chromium/content/browser/top_document_isolation_browsertest.cc
@@ -233,7 +233,7 @@ IN_PROC_BROWSER_TEST_F(TopDocumentIsolationTest,
GURL ba_url(embedded_test_server()->GetURL(
"b.com", "/cross_site_iframe_factory.html?b(a, c)"));
- NavigateToURL(shell(), ba_url);
+ EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(shell(), ba_url));
// This navigation destroys the popup's opener, so we allow the main frame to
// commit in a top level process for b.com, in spite of the b.com popup in the
@@ -254,7 +254,7 @@ IN_PROC_BROWSER_TEST_F(TopDocumentIsolationTest,
// Navigate the popup to a new site.
GURL c_url(embedded_test_server()->GetURL(
"c.com", "/cross_site_iframe_factory.html?c(c, c, c, c)"));
- NavigateToURL(popup, c_url);
+ EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(popup, c_url));
EXPECT_EQ(
" Site D ------------ proxies for B\n"
" |--Site D ------- proxies for B\n"
@@ -264,7 +264,7 @@ IN_PROC_BROWSER_TEST_F(TopDocumentIsolationTest,
"Where B = default subframe process\n"
" D = http://c.com/",
DepictFrameTree(popup_root));
- NavigateToURL(shell(), c_url);
+ EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(shell(), c_url));
EXPECT_EQ(
" Site D\n"
" |--Site D\n"
@@ -348,7 +348,7 @@ IN_PROC_BROWSER_TEST_F(TopDocumentIsolationTest,
"c.com", "/cross_site_iframe_factory.html?c(a, b)"));
{
RenderFrameDeletedObserver deleted_observer(root()->current_frame_host());
- NavigateToURL(shell(), cab_url);
+ EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(shell(), cab_url));
deleted_observer.WaitUntilDeleted();
}
@@ -376,7 +376,7 @@ IN_PROC_BROWSER_TEST_F(TopDocumentIsolationTest,
{
RenderFrameDeletedObserver deleted_observer(
popup_root->current_frame_host());
- NavigateToURL(popup, d_url);
+ EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(popup, d_url));
deleted_observer.WaitUntilDeleted();
}
EXPECT_EQ(
@@ -386,7 +386,7 @@ IN_PROC_BROWSER_TEST_F(TopDocumentIsolationTest,
DepictFrameTree(popup_root));
{
RenderFrameDeletedObserver deleted_observer(root()->current_frame_host());
- NavigateToURL(shell(), d_url);
+ EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(shell(), d_url));
deleted_observer.WaitUntilDeleted();
}
EXPECT_EQ(
diff --git a/chromium/content/browser/tracing/background_tracing_manager_browsertest.cc b/chromium/content/browser/tracing/background_tracing_manager_browsertest.cc
index 96add2be93a..ead569f8522 100644
--- a/chromium/content/browser/tracing/background_tracing_manager_browsertest.cc
+++ b/chromium/content/browser/tracing/background_tracing_manager_browsertest.cc
@@ -18,6 +18,7 @@
#include "base/trace_event/trace_event.h"
#include "content/browser/tracing/background_tracing_manager_impl.h"
#include "content/browser/tracing/background_tracing_rule.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
@@ -140,7 +141,8 @@ class BackgroundTracingManagerUploadConfigWrapper {
EXPECT_EQ(Z_STREAM_END, result);
last_file_contents_.assign(output_str.data(), bytes_written);
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, done_callback);
+ BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
+ std::move(done_callback));
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, callback_);
}
@@ -167,7 +169,7 @@ void StartedFinalizingCallback(base::Closure callback,
bool value) {
EXPECT_EQ(expected, value);
if (!callback.is_null())
- callback.Run();
+ std::move(callback).Run();
}
std::unique_ptr<BackgroundTracingConfig> CreatePreemptiveConfig() {
diff --git a/chromium/content/browser/tracing/background_tracing_manager_impl.cc b/chromium/content/browser/tracing/background_tracing_manager_impl.cc
index 1450f0b48de..6fd8e9c19e2 100644
--- a/chromium/content/browser/tracing/background_tracing_manager_impl.cc
+++ b/chromium/content/browser/tracing/background_tracing_manager_impl.cc
@@ -113,7 +113,7 @@ void BackgroundTracingManagerImpl::AddMetadataGeneratorFunction() {
void BackgroundTracingManagerImpl::WhenIdle(
base::Callback<void()> idle_callback) {
CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
- idle_callback_ = idle_callback;
+ idle_callback_ = std::move(idle_callback);
}
bool BackgroundTracingManagerImpl::SetActiveScenario(
@@ -339,7 +339,7 @@ void BackgroundTracingManagerImpl::TriggerNamedEvent(
content::BrowserThread::PostTask(
content::BrowserThread::UI, FROM_HERE,
base::BindOnce(&BackgroundTracingManagerImpl::TriggerNamedEvent,
- base::Unretained(this), handle, callback));
+ base::Unretained(this), handle, std::move(callback)));
return;
}
@@ -359,12 +359,12 @@ void BackgroundTracingManagerImpl::TriggerNamedEvent(
if (!is_valid_trigger) {
if (!callback.is_null())
- callback.Run(false);
+ std::move(callback).Run(false);
return;
}
triggered_named_event_handle_ = handle;
- OnRuleTriggered(triggered_rule, callback);
+ OnRuleTriggered(triggered_rule, std::move(callback));
}
void BackgroundTracingManagerImpl::OnRuleTriggered(
@@ -375,7 +375,7 @@ void BackgroundTracingManagerImpl::OnRuleTriggered(
double trigger_chance = triggered_rule->trigger_chance();
if (trigger_chance < 1.0 && base::RandDouble() > trigger_chance) {
if (!callback.is_null())
- callback.Run(false);
+ std::move(callback).Run(false);
return;
}
@@ -400,7 +400,7 @@ void BackgroundTracingManagerImpl::OnRuleTriggered(
trace_delay = -1;
} else {
if (!callback.is_null())
- callback.Run(false);
+ std::move(callback).Run(false);
return;
}
}
@@ -410,7 +410,7 @@ void BackgroundTracingManagerImpl::OnRuleTriggered(
// otherwise we do nothing.
if (!is_tracing_ || is_gathering_ || tracing_timer_) {
if (!callback.is_null())
- callback.Run(false);
+ std::move(callback).Run(false);
return;
}
@@ -418,9 +418,9 @@ void BackgroundTracingManagerImpl::OnRuleTriggered(
}
if (trace_delay < 0) {
- BeginFinalizing(callback);
+ BeginFinalizing(std::move(callback));
} else {
- tracing_timer_.reset(new TracingTimer(callback));
+ tracing_timer_.reset(new TracingTimer(std::move(callback)));
tracing_timer_->StartTimer(trace_delay);
}
@@ -509,7 +509,7 @@ void BackgroundTracingManagerImpl::OnFinalizeStarted(
base::Unretained(this)));
}
if (!started_finalizing_closure.is_null())
- started_finalizing_closure.Run();
+ std::move(started_finalizing_closure).Run();
}
void BackgroundTracingManagerImpl::OnFinalizeComplete() {
@@ -582,19 +582,21 @@ void BackgroundTracingManagerImpl::BeginFinalizing(
}
if (is_allowed_finalization) {
trace_data_endpoint = TracingControllerImpl::CreateCompressedStringEndpoint(
- TracingControllerImpl::CreateCallbackEndpoint(
- base::Bind(&BackgroundTracingManagerImpl::OnFinalizeStarted,
- base::Unretained(this), started_finalizing_closure)),
+ TracingControllerImpl::CreateCallbackEndpoint(base::Bind(
+ &BackgroundTracingManagerImpl::OnFinalizeStarted,
+ base::Unretained(this), std::move(started_finalizing_closure))),
true /* compress_with_background_priority */);
RecordBackgroundTracingMetric(FINALIZATION_ALLOWED);
} else {
- if (!callback.is_null()) {
+ if (!std::move(callback).is_null()) {
trace_data_endpoint =
TracingControllerImpl::CreateCallbackEndpoint(base::BindRepeating(
[](base::Closure closure,
std::unique_ptr<const base::DictionaryValue> metadata,
- base::RefCountedString* file_contents) { closure.Run(); },
- started_finalizing_closure));
+ base::RefCountedString* file_contents) {
+ std::move(closure).Run();
+ },
+ std::move(started_finalizing_closure)));
}
RecordBackgroundTracingMetric(FINALIZATION_DISALLOWED);
}
diff --git a/chromium/content/browser/tracing/background_tracing_rule.h b/chromium/content/browser/tracing/background_tracing_rule.h
index 9d0a91eb01f..63f102393a6 100644
--- a/chromium/content/browser/tracing/background_tracing_rule.h
+++ b/chromium/content/browser/tracing/background_tracing_rule.h
@@ -8,7 +8,6 @@
#include <memory>
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/values.h"
#include "content/browser/tracing/background_tracing_config_impl.h"
#include "content/common/content_export.h"
diff --git a/chromium/content/browser/tracing/etw_tracing_agent_win.cc b/chromium/content/browser/tracing/etw_tracing_agent_win.cc
index 7b9a956649c..adc428b6a9c 100644
--- a/chromium/content/browser/tracing/etw_tracing_agent_win.cc
+++ b/chromium/content/browser/tracing/etw_tracing_agent_win.cc
@@ -166,8 +166,8 @@ void EtwTracingAgent::ProcessEvent(EVENT_TRACE* event) {
void EtwTracingAgent::AddSyncEventToBuffer() {
// Sync the clocks.
- base::Time walltime = base::Time::NowFromSystemTime();
- base::TimeTicks now = base::TimeTicks::Now();
+ base::Time walltime = base::subtle::TimeNowFromSystemTimeIgnoringOverride();
+ base::TimeTicks now = TRACE_TIME_TICKS_NOW();
LARGE_INTEGER walltime_in_us;
walltime_in_us.QuadPart = walltime.ToInternalValue();
diff --git a/chromium/content/browser/tracing/memory_instrumentation_browsertest.cc b/chromium/content/browser/tracing/memory_instrumentation_browsertest.cc
index ceef3b2f6b5..5ebe6aa5eb3 100644
--- a/chromium/content/browser/tracing/memory_instrumentation_browsertest.cc
+++ b/chromium/content/browser/tracing/memory_instrumentation_browsertest.cc
@@ -6,6 +6,9 @@
#include "base/bind.h"
#include "base/run_loop.h"
+#include "content/public/browser/render_frame_host.h"
+#include "content/public/browser/render_process_host.h"
+#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
@@ -29,13 +32,18 @@ class MemoryInstrumentationTest : public ContentBrowserTest {
};
uint64_t GetPrivateFootprintKb(ProcessType type,
- const GlobalMemoryDump& global_dump) {
+ const GlobalMemoryDump& global_dump,
+ base::ProcessId pid = base::kNullProcessId) {
const GlobalMemoryDump::ProcessDump* target_dump = nullptr;
for (const auto& dump : global_dump.process_dumps()) {
- if (dump.process_type() == type) {
- EXPECT_FALSE(target_dump);
- target_dump = &dump;
- }
+ if (dump.process_type() != type)
+ continue;
+
+ if (pid != base::kNullProcessId && pid != dump.pid())
+ continue;
+
+ EXPECT_FALSE(target_dump);
+ target_dump = &dump;
}
EXPECT_TRUE(target_dump);
return target_dump->os_dump().private_footprint_kb;
@@ -51,7 +59,7 @@ std::unique_ptr<GlobalMemoryDump> DoGlobalDump() {
std::unique_ptr<GlobalMemoryDump> result) {
EXPECT_TRUE(success);
*out_result = std::move(result);
- quit_closure.Run();
+ std::move(quit_closure).Run();
},
run_loop.QuitClosure(), &result));
run_loop.Run();
@@ -87,6 +95,9 @@ IN_PROC_BROWSER_TEST_F(MemoryInstrumentationTest,
EXPECT_EQ(x[0] + x[kAllocSize - 1], 2);
content::WebContents* web_contents = shell()->web_contents();
+ base::ProcessId renderer_pid =
+ base::GetProcId(web_contents->GetMainFrame()->GetProcess()->GetHandle());
+
// Should allocate at least 4*10^6 / 1024 = 4000kb.
EXPECT_TRUE(content::ExecuteScript(web_contents,
"var a = Array(1000000).fill(1234);\n"));
@@ -109,9 +120,9 @@ IN_PROC_BROWSER_TEST_F(MemoryInstrumentationTest,
AllOf(Ge(kAllocSizeKb - 3000), Le(kAllocSizeKb + 3000)));
int64_t before_renderer_kb =
- GetPrivateFootprintKb(ProcessType::RENDERER, *before_ptr);
+ GetPrivateFootprintKb(ProcessType::RENDERER, *before_ptr, renderer_pid);
int64_t during_renderer_kb =
- GetPrivateFootprintKb(ProcessType::RENDERER, *during_ptr);
+ GetPrivateFootprintKb(ProcessType::RENDERER, *during_ptr, renderer_pid);
EXPECT_GE(during_renderer_kb - before_renderer_kb, 3000);
}
diff --git a/chromium/content/browser/tracing/memory_tracing_browsertest.cc b/chromium/content/browser/tracing/memory_tracing_browsertest.cc
index 1ac32852508..0b38bbb9686 100644
--- a/chromium/content/browser/tracing/memory_tracing_browsertest.cc
+++ b/chromium/content/browser/tracing/memory_tracing_browsertest.cc
@@ -57,17 +57,17 @@ class MemoryTracingTest : public ContentBrowserTest {
// the run loop (which is the IN_PROC_BROWSER_TEST_F main thread).
if (!task_runner->RunsTasksInCurrentSequence()) {
task_runner->PostTask(
- FROM_HERE,
- base::BindOnce(&MemoryTracingTest::OnGlobalMemoryDumpDone,
- base::Unretained(this), task_runner, closure,
- request_index, success, dump_guid));
+ FROM_HERE, base::BindOnce(&MemoryTracingTest::OnGlobalMemoryDumpDone,
+ base::Unretained(this), task_runner,
+ std::move(closure), request_index, success,
+ dump_guid));
return;
}
if (success)
EXPECT_NE(0u, dump_guid);
OnMemoryDumpDone(request_index, success);
if (!closure.is_null())
- closure.Run();
+ std::move(closure).Run();
}
void RequestGlobalDumpWithClosure(
@@ -85,11 +85,11 @@ class MemoryTracingTest : public ContentBrowserTest {
RequestGlobalDumpAndAppendToTrace,
base::Unretained(
memory_instrumentation::MemoryInstrumentation::GetInstance()),
- dump_type, level_of_detail, callback));
+ dump_type, level_of_detail, std::move(callback)));
} else {
memory_instrumentation::MemoryInstrumentation::GetInstance()
->RequestGlobalDumpAndAppendToTrace(dump_type, level_of_detail,
- callback);
+ std::move(callback));
}
}
@@ -137,7 +137,9 @@ class MemoryTracingTest : public ContentBrowserTest {
TracingControllerImpl::CreateCallbackEndpoint(base::BindRepeating(
[](base::Closure quit_closure,
std::unique_ptr<const base::DictionaryValue> metadata,
- base::RefCountedString* trace_str) { quit_closure.Run(); },
+ base::RefCountedString* trace_str) {
+ std::move(quit_closure).Run();
+ },
run_loop.QuitClosure())));
EXPECT_TRUE(success);
run_loop.Run();
diff --git a/chromium/content/browser/tracing/power_tracing_agent.cc b/chromium/content/browser/tracing/power_tracing_agent.cc
index 515144b6247..af496fb0d81 100644
--- a/chromium/content/browser/tracing/power_tracing_agent.cc
+++ b/chromium/content/browser/tracing/power_tracing_agent.cc
@@ -158,7 +158,7 @@ void PowerTracingAgent::RequestClockSyncMarkerOnIOThread(
}
request_clock_sync_marker_callback_ = callback;
- request_clock_sync_marker_start_time_ = base::TimeTicks::Now();
+ request_clock_sync_marker_start_time_ = TRACE_TIME_TICKS_NOW();
battor_agent_->RecordClockSyncMarker(sync_id);
}
@@ -167,7 +167,7 @@ void PowerTracingAgent::OnRecordClockSyncMarkerComplete(
DCHECK_CURRENTLY_ON(BrowserThread::IO);
base::TimeTicks issue_start_ts = request_clock_sync_marker_start_time_;
- base::TimeTicks issue_end_ts = base::TimeTicks::Now();
+ base::TimeTicks issue_end_ts = TRACE_TIME_TICKS_NOW();
if (error != battor::BATTOR_ERROR_NONE)
issue_start_ts = issue_end_ts = base::TimeTicks();
diff --git a/chromium/content/browser/tracing/tracing_controller_browsertest.cc b/chromium/content/browser/tracing/tracing_controller_browsertest.cc
index e00c023335d..ba83d7cfed8 100644
--- a/chromium/content/browser/tracing/tracing_controller_browsertest.cc
+++ b/chromium/content/browser/tracing/tracing_controller_browsertest.cc
@@ -138,12 +138,12 @@ class TracingControllerTest : public ContentBrowserTest {
const std::set<std::string>& categories) {
get_categories_done_callback_count_++;
EXPECT_TRUE(categories.size() > 0);
- quit_callback.Run();
+ std::move(quit_callback).Run();
}
void StartTracingDoneCallbackTest(base::Closure quit_callback) {
enable_recording_done_callback_count_++;
- quit_callback.Run();
+ std::move(quit_callback).Run();
}
void StopTracingStringDoneCallbackTest(
@@ -154,7 +154,7 @@ class TracingControllerTest : public ContentBrowserTest {
last_metadata_ = std::move(metadata);
last_data_ = data->data();
EXPECT_TRUE(data->size() > 0);
- quit_callback.Run();
+ std::move(quit_callback).Run();
}
void StopTracingFileDoneCallbackTest(base::Closure quit_callback,
@@ -167,7 +167,7 @@ class TracingControllerTest : public ContentBrowserTest {
base::GetFileSize(file_path, &file_size);
EXPECT_GT(file_size, 0);
}
- quit_callback.Run();
+ std::move(quit_callback).Run();
last_actual_recording_file_path_ = file_path;
}
@@ -206,8 +206,8 @@ class TracingControllerTest : public ContentBrowserTest {
base::Bind(&TracingControllerTest::StartTracingDoneCallbackTest,
base::Unretained(this),
run_loop.QuitClosure());
- bool result = controller->StartTracing(
- TraceConfig(), callback);
+ bool result =
+ controller->StartTracing(TraceConfig(), std::move(callback));
ASSERT_TRUE(result);
run_loop.Run();
EXPECT_EQ(enable_recording_done_callback_count(), 1);
@@ -221,7 +221,7 @@ class TracingControllerTest : public ContentBrowserTest {
&TracingControllerTest::StopTracingStringDoneCallbackTest,
base::Unretained(this), run_loop.QuitClosure());
bool result = controller->StopTracing(
- TracingController::CreateStringEndpoint(callback));
+ TracingController::CreateStringEndpoint(std::move(callback)));
ASSERT_TRUE(result);
run_loop.Run();
EXPECT_EQ(disable_recording_done_callback_count(), 1);
@@ -251,7 +251,7 @@ class TracingControllerTest : public ContentBrowserTest {
TraceConfig config = TraceConfig();
config.EnableArgumentFilter();
- bool result = controller->StartTracing(config, callback);
+ bool result = controller->StartTracing(config, std::move(callback));
ASSERT_TRUE(result);
run_loop.Run();
EXPECT_EQ(enable_recording_done_callback_count(), 1);
@@ -266,7 +266,7 @@ class TracingControllerTest : public ContentBrowserTest {
base::Unretained(this), run_loop.QuitClosure());
scoped_refptr<TracingController::TraceDataEndpoint> trace_data_endpoint =
- TracingController::CreateStringEndpoint(callback);
+ TracingController::CreateStringEndpoint(std::move(callback));
metadata_ = std::make_unique<base::DictionaryValue>();
metadata_->SetString("not-whitelisted", "this_not_found");
@@ -289,7 +289,8 @@ class TracingControllerTest : public ContentBrowserTest {
TracingController::StartTracingDoneCallback callback =
base::Bind(&TracingControllerTest::StartTracingDoneCallbackTest,
base::Unretained(this), run_loop.QuitClosure());
- bool result = controller->StartTracing(TraceConfig(), callback);
+ bool result =
+ controller->StartTracing(TraceConfig(), std::move(callback));
ASSERT_TRUE(result);
run_loop.Run();
EXPECT_EQ(enable_recording_done_callback_count(), 1);
@@ -304,7 +305,7 @@ class TracingControllerTest : public ContentBrowserTest {
base::Unretained(this), run_loop.QuitClosure());
bool result = controller->StopTracing(
TracingControllerImpl::CreateCompressedStringEndpoint(
- new TracingControllerTestEndpoint(callback),
+ new TracingControllerTestEndpoint(std::move(callback)),
true /* compress_with_background_priority */));
ASSERT_TRUE(result);
run_loop.Run();
@@ -324,7 +325,8 @@ class TracingControllerTest : public ContentBrowserTest {
base::Bind(&TracingControllerTest::StartTracingDoneCallbackTest,
base::Unretained(this),
run_loop.QuitClosure());
- bool result = controller->StartTracing(TraceConfig(), callback);
+ bool result =
+ controller->StartTracing(TraceConfig(), std::move(callback));
ASSERT_TRUE(result);
run_loop.Run();
EXPECT_EQ(enable_recording_done_callback_count(), 1);
@@ -337,8 +339,9 @@ class TracingControllerTest : public ContentBrowserTest {
base::Unretained(this),
run_loop.QuitClosure(),
result_file_path);
- bool result = controller->StopTracing(
- TracingController::CreateFileEndpoint(result_file_path, callback));
+ bool result =
+ controller->StopTracing(TracingController::CreateFileEndpoint(
+ result_file_path, std::move(callback)));
ASSERT_TRUE(result);
run_loop.Run();
EXPECT_EQ(disable_recording_done_callback_count(), 1);
@@ -365,7 +368,7 @@ IN_PROC_BROWSER_TEST_F(TracingControllerTest, GetCategories) {
base::Bind(&TracingControllerTest::GetCategoriesDoneCallbackTest,
base::Unretained(this),
run_loop.QuitClosure());
- ASSERT_TRUE(controller->GetCategories(callback));
+ ASSERT_TRUE(controller->GetCategories(std::move(callback)));
run_loop.Run();
EXPECT_EQ(get_categories_done_callback_count(), 1);
}
@@ -468,7 +471,9 @@ IN_PROC_BROWSER_TEST_F(TracingControllerTest,
TracingControllerImpl::CreateCallbackEndpoint(base::BindRepeating(
[](base::Closure quit_closure,
std::unique_ptr<const base::DictionaryValue> metadata,
- base::RefCountedString* trace_str) { quit_closure.Run(); },
+ base::RefCountedString* trace_str) {
+ std::move(quit_closure).Run();
+ },
run_loop.QuitClosure()))));
run_loop.Run();
}
@@ -484,7 +489,9 @@ IN_PROC_BROWSER_TEST_F(TracingControllerTest, DoubleStopTracing) {
TracingControllerImpl::CreateCallbackEndpoint(base::BindRepeating(
[](base::Closure quit_closure,
std::unique_ptr<const base::DictionaryValue> metadata,
- base::RefCountedString* trace_str) { quit_closure.Run(); },
+ base::RefCountedString* trace_str) {
+ std::move(quit_closure).Run();
+ },
run_loop.QuitClosure()))));
EXPECT_FALSE(controller->StopTracing(nullptr));
run_loop.Run();
diff --git a/chromium/content/browser/tracing/tracing_controller_impl.cc b/chromium/content/browser/tracing/tracing_controller_impl.cc
index 568e01150c7..14eff00db8c 100644
--- a/chromium/content/browser/tracing/tracing_controller_impl.cc
+++ b/chromium/content/browser/tracing/tracing_controller_impl.cc
@@ -13,7 +13,6 @@
#include "base/cpu.h"
#include "base/files/file_tracing.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/string_split.h"
#include "base/strings/stringprintf.h"
#include "base/sys_info.h"
@@ -21,6 +20,7 @@
#include "base/trace_event/trace_config.h"
#include "base/values.h"
#include "build/build_config.h"
+#include "components/tracing/common/trace_config_file.h"
#include "content/browser/tracing/file_tracing_provider_impl.h"
#include "content/browser/tracing/tracing_ui.h"
#include "content/public/browser/browser_thread.h"
@@ -146,8 +146,8 @@ void TracingControllerImpl::AddAgents() {
agents_.push_back(std::make_unique<EtwTracingAgent>(connector));
#endif
- auto chrome_agent =
- std::make_unique<tracing::ChromeTraceEventAgent>(connector);
+ auto chrome_agent = std::make_unique<tracing::ChromeTraceEventAgent>(
+ connector, true /* request_clock_sync_marker_on_android */);
// For adding general CPU, network, OS, and other system information to the
// metadata.
chrome_agent->AddMetadataGeneratorFunction(base::BindRepeating(
@@ -239,7 +239,7 @@ TracingControllerImpl::GenerateMetadataDict() const {
base::CommandLine::ForCurrentProcess()->GetCommandLineString());
base::Time::Exploded ctime;
- base::Time::Now().UTCExplode(&ctime);
+ TRACE_TIME_NOW().UTCExplode(&ctime);
std::string time_string = base::StringPrintf(
"%u-%u-%u %d:%d:%d", ctime.year, ctime.month, ctime.day_of_month,
ctime.hour, ctime.minute, ctime.second);
@@ -326,12 +326,13 @@ bool TracingControllerImpl::StopTracing(
return false;
DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ tracing::TraceConfigFile::GetInstance()->SetDisabled();
trace_data_endpoint_ = std::move(trace_data_endpoint);
is_data_complete_ = false;
is_metadata_available_ = false;
mojo::DataPipe data_pipe;
- drainer_.reset(new mojo::common::DataPipeDrainer(
- this, std::move(data_pipe.consumer_handle)));
+ drainer_.reset(
+ new mojo::DataPipeDrainer(this, std::move(data_pipe.consumer_handle)));
if (agent_label.empty()) {
// Stop and flush all agents.
coordinator_->StopAndFlush(
diff --git a/chromium/content/browser/tracing/tracing_controller_impl.h b/chromium/content/browser/tracing/tracing_controller_impl.h
index 6a3d8c9601a..ea35ddd324c 100644
--- a/chromium/content/browser/tracing/tracing_controller_impl.h
+++ b/chromium/content/browser/tracing/tracing_controller_impl.h
@@ -13,7 +13,7 @@
#include "base/memory/ref_counted.h"
#include "content/common/content_export.h"
#include "content/public/browser/tracing_controller.h"
-#include "mojo/common/data_pipe_drainer.h"
+#include "mojo/public/cpp/system/data_pipe_drainer.h"
#include "services/tracing/public/mojom/tracing.mojom.h"
namespace base {
@@ -32,7 +32,7 @@ class TracingDelegate;
class TracingUI;
class TracingControllerImpl : public TracingController,
- public mojo::common::DataPipeDrainer::Client {
+ public mojo::DataPipeDrainer::Client {
public:
// Create an endpoint for dumping the trace data to a callback.
CONTENT_EXPORT static scoped_refptr<TraceDataEndpoint> CreateCallbackEndpoint(
@@ -69,7 +69,7 @@ class TracingControllerImpl : public TracingController,
void AddAgents();
std::unique_ptr<base::DictionaryValue> GenerateMetadataDict() const;
- // mojo::Common::DataPipeDrainer::Client
+ // mojo::DataPipeDrainer::Client
void OnDataAvailable(const void* data, size_t num_bytes) override;
void OnDataComplete() override;
@@ -82,7 +82,7 @@ class TracingControllerImpl : public TracingController,
std::vector<std::unique_ptr<tracing::mojom::Agent>> agents_;
std::unique_ptr<TracingDelegate> delegate_;
std::unique_ptr<base::trace_event::TraceConfig> trace_config_;
- std::unique_ptr<mojo::common::DataPipeDrainer> drainer_;
+ std::unique_ptr<mojo::DataPipeDrainer> drainer_;
scoped_refptr<TraceDataEndpoint> trace_data_endpoint_;
std::unique_ptr<base::DictionaryValue> filtered_metadata_;
std::set<TracingUI*> tracing_uis_;
diff --git a/chromium/content/browser/tracing/tracing_controller_impl_data_endpoint.cc b/chromium/content/browser/tracing/tracing_controller_impl_data_endpoint.cc
index 5ce323dd793..4fcd026465f 100644
--- a/chromium/content/browser/tracing/tracing_controller_impl_data_endpoint.cc
+++ b/chromium/content/browser/tracing/tracing_controller_impl_data_endpoint.cc
@@ -7,7 +7,6 @@
#include "base/files/file_util.h"
#include "base/json/json_writer.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted_memory.h"
#include "base/sequenced_task_runner.h"
#include "base/strings/pattern.h"
@@ -70,7 +69,7 @@ class FileTraceDataEndpoint : public TracingController::TraceDataEndpoint {
FROM_HERE,
base::BindOnce(
&FileTraceDataEndpoint::ReceiveTraceChunkOnBlockingThread, this,
- base::Passed(std::move(chunk))));
+ std::move(chunk)));
}
void ReceiveTraceFinalContents(
diff --git a/chromium/content/browser/tracing/tracing_ui.cc b/chromium/content/browser/tracing/tracing_ui.cc
index c30a376b71c..fd922b3e90f 100644
--- a/chromium/content/browser/tracing/tracing_ui.cc
+++ b/chromium/content/browser/tracing/tracing_ui.cc
@@ -168,10 +168,10 @@ TracingUI::TracingUI(WebUI* web_ui)
weak_factory_(this) {
web_ui->RegisterMessageCallback(
"doUpload",
- base::Bind(&TracingUI::DoUpload, base::Unretained(this)));
+ base::BindRepeating(&TracingUI::DoUpload, base::Unretained(this)));
web_ui->RegisterMessageCallback(
- "doUploadBase64",
- base::Bind(&TracingUI::DoUploadBase64Encoded, base::Unretained(this)));
+ "doUploadBase64", base::BindRepeating(&TracingUI::DoUploadBase64Encoded,
+ base::Unretained(this)));
// Set up the chrome://tracing/ source.
BrowserContext* browser_context =
@@ -247,7 +247,8 @@ void TracingUI::DoUploadInternal(const std::string& file_contents,
GetURLRequestContext());
DCHECK(trace_uploader_);
trace_uploader_->DoUpload(file_contents, upload_mode, nullptr,
- progress_callback, done_callback);
+ std::move(progress_callback),
+ std::move(done_callback));
// TODO(mmandlis): Add support for stopping the upload in progress.
}
diff --git a/chromium/content/browser/url_loader_factory_getter.cc b/chromium/content/browser/url_loader_factory_getter.cc
index 4ec3a205161..2a6b4f38ccb 100644
--- a/chromium/content/browser/url_loader_factory_getter.cc
+++ b/chromium/content/browser/url_loader_factory_getter.cc
@@ -7,6 +7,7 @@
#include "base/bind.h"
#include "base/lazy_instance.h"
#include "content/browser/storage_partition_impl.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/mojom/network_service.mojom.h"
namespace content {
@@ -16,6 +17,86 @@ base::LazyInstance<URLLoaderFactoryGetter::GetNetworkFactoryCallback>::Leaky
g_get_network_factory_callback = LAZY_INSTANCE_INITIALIZER;
}
+class URLLoaderFactoryGetter::URLLoaderFactoryForIOThreadInfo
+ : public network::SharedURLLoaderFactoryInfo {
+ public:
+ URLLoaderFactoryForIOThreadInfo() = default;
+ explicit URLLoaderFactoryForIOThreadInfo(
+ scoped_refptr<URLLoaderFactoryGetter> factory_getter)
+ : factory_getter_(std::move(factory_getter)) {}
+ ~URLLoaderFactoryForIOThreadInfo() override = default;
+
+ scoped_refptr<URLLoaderFactoryGetter>& url_loader_factory_getter() {
+ return factory_getter_;
+ }
+
+ protected:
+ // SharedURLLoaderFactoryInfo implementation.
+ scoped_refptr<network::SharedURLLoaderFactory> CreateFactory() override;
+
+ scoped_refptr<URLLoaderFactoryGetter> factory_getter_;
+
+ DISALLOW_COPY_AND_ASSIGN(URLLoaderFactoryForIOThreadInfo);
+};
+
+class URLLoaderFactoryGetter::URLLoaderFactoryForIOThread
+ : public network::SharedURLLoaderFactory {
+ public:
+ explicit URLLoaderFactoryForIOThread(
+ scoped_refptr<URLLoaderFactoryGetter> factory_getter)
+ : factory_getter_(std::move(factory_getter)) {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+ }
+
+ explicit URLLoaderFactoryForIOThread(
+ std::unique_ptr<URLLoaderFactoryForIOThreadInfo> info)
+ : factory_getter_(std::move(info->url_loader_factory_getter())) {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+ }
+
+ // mojom::URLLoaderFactory implementation:
+ void CreateLoaderAndStart(network::mojom::URLLoaderRequest request,
+ int32_t routing_id,
+ int32_t request_id,
+ uint32_t options,
+ const network::ResourceRequest& url_request,
+ network::mojom::URLLoaderClientPtr client,
+ const net::MutableNetworkTrafficAnnotationTag&
+ traffic_annotation) override {
+ DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
+ if (!factory_getter_)
+ return;
+ factory_getter_->GetURLLoaderFactory()->CreateLoaderAndStart(
+ std::move(request), routing_id, request_id, options, url_request,
+ std::move(client), traffic_annotation);
+ }
+
+ // SharedURLLoaderFactory implementation:
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo> Clone() override {
+ NOTREACHED() << "This isn't supported. If you need a SharedURLLoaderFactory"
+ " on the UI thread, get it from StoragePartition.";
+ return nullptr;
+ }
+
+ private:
+ friend class base::RefCounted<URLLoaderFactoryForIOThread>;
+ ~URLLoaderFactoryForIOThread() override = default;
+
+ scoped_refptr<URLLoaderFactoryGetter> factory_getter_;
+
+ DISALLOW_COPY_AND_ASSIGN(URLLoaderFactoryForIOThread);
+};
+
+scoped_refptr<network::SharedURLLoaderFactory>
+URLLoaderFactoryGetter::URLLoaderFactoryForIOThreadInfo::CreateFactory() {
+ auto other = std::make_unique<URLLoaderFactoryForIOThreadInfo>();
+ other->factory_getter_ = std::move(factory_getter_);
+
+ return base::MakeRefCounted<URLLoaderFactoryForIOThread>(std::move(other));
+}
+
+// -----------------------------------------------------------------------------
+
URLLoaderFactoryGetter::URLLoaderFactoryGetter() {}
void URLLoaderFactoryGetter::Initialize(StoragePartitionImpl* partition) {
@@ -41,7 +122,21 @@ void URLLoaderFactoryGetter::OnStoragePartitionDestroyed() {
partition_ = nullptr;
}
-network::mojom::URLLoaderFactory* URLLoaderFactoryGetter::GetNetworkFactory() {
+scoped_refptr<network::SharedURLLoaderFactory>
+URLLoaderFactoryGetter::GetNetworkFactory() {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+ return base::MakeRefCounted<URLLoaderFactoryForIOThread>(
+ base::WrapRefCounted(this));
+}
+
+std::unique_ptr<network::SharedURLLoaderFactoryInfo>
+URLLoaderFactoryGetter::GetNetworkFactoryInfo() {
+ return std::make_unique<URLLoaderFactoryForIOThreadInfo>(
+ base::WrapRefCounted(this));
+}
+
+network::mojom::URLLoaderFactory*
+URLLoaderFactoryGetter::GetURLLoaderFactory() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (g_get_network_factory_callback.Get() && !test_factory_)
g_get_network_factory_callback.Get().Run(this);
@@ -59,6 +154,12 @@ network::mojom::URLLoaderFactory* URLLoaderFactoryGetter::GetNetworkFactory() {
return network_factory_.get();
}
+void URLLoaderFactoryGetter::CloneNetworkFactory(
+ network::mojom::URLLoaderFactoryRequest network_factory_request) {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+ GetURLLoaderFactory()->Clone(std::move(network_factory_request));
+}
+
network::mojom::URLLoaderFactory* URLLoaderFactoryGetter::GetBlobFactory() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
return blob_factory_.get();
diff --git a/chromium/content/browser/url_loader_factory_getter.h b/chromium/content/browser/url_loader_factory_getter.h
index 47c73da086d..2386c82bd4c 100644
--- a/chromium/content/browser/url_loader_factory_getter.h
+++ b/chromium/content/browser/url_loader_factory_getter.h
@@ -12,6 +12,11 @@
#include "content/public/browser/browser_thread.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
+namespace network {
+class SharedURLLoaderFactoryInfo;
+class SharedURLLoaderFactory;
+} // namespace network
+
namespace content {
class StoragePartitionImpl;
@@ -34,9 +39,23 @@ class URLLoaderFactoryGetter
// be called when the partition is going away.
void OnStoragePartitionDestroyed();
- // Called on the IO thread to get the URLLoaderFactory to the network service.
- // The pointer shouldn't be cached.
- CONTENT_EXPORT network::mojom::URLLoaderFactory* GetNetworkFactory();
+ // Called on the IO thread to get a shared wrapper to this
+ // URLLoaderFactoryGetter, which can be used to access the URLLoaderFactory
+ // to the network service and supports auto-reconnect after crash.
+ CONTENT_EXPORT scoped_refptr<network::SharedURLLoaderFactory>
+ GetNetworkFactory();
+
+ // Called on the UI thread to get an info that holds a reference to this
+ // URLLoaderFactoryGetter, which can be used to construct a similar
+ // SharedURLLoaderFactory as returned from |GetNetworkFactory()| on IO thread.
+ CONTENT_EXPORT std::unique_ptr<network::SharedURLLoaderFactoryInfo>
+ GetNetworkFactoryInfo();
+
+ // Called on the IO thread. Will clone the internal factory to the network
+ // service which doesn't support auto-reconnect after crash. Useful for
+ // one-off requests (e.g. A single navigation) to avoid additional mojo hop.
+ CONTENT_EXPORT void CloneNetworkFactory(
+ network::mojom::URLLoaderFactoryRequest network_factory_request);
// Called on the IO thread to get the URLLoaderFactory to the blob service.
// The pointer shouldn't be cached.
@@ -52,10 +71,10 @@ class URLLoaderFactoryGetter
return &network_factory_;
}
- // When this global function is set, if GetNetworkFactory is called and
- // |test_factory_| is null, then the callback will be run.
- // This method must be called either on the IO thread or before threads start.
- // This callback is run on the IO thread.
+ // When this global function is set, if GetURLLoaderFactory is called and
+ // |test_factory_| is null, then the callback will be run. This method must be
+ // called either on the IO thread or before threads start. This callback is
+ // run on the IO thread.
using GetNetworkFactoryCallback = base::RepeatingCallback<void(
URLLoaderFactoryGetter* url_loader_factory_getter)>;
CONTENT_EXPORT static void SetGetNetworkFactoryCallbackForTesting(
@@ -65,6 +84,9 @@ class URLLoaderFactoryGetter
CONTENT_EXPORT void FlushNetworkInterfaceOnIOThreadForTesting();
private:
+ class URLLoaderFactoryForIOThreadInfo;
+ class URLLoaderFactoryForIOThread;
+
friend class base::DeleteHelper<URLLoaderFactoryGetter>;
friend struct BrowserThread::DeleteOnThread<BrowserThread::IO>;
@@ -77,6 +99,10 @@ class URLLoaderFactoryGetter
void HandleNetworkFactoryRequestOnUIThread(
network::mojom::URLLoaderFactoryRequest network_factory_request);
+ // Called on the IO thread to get the URLLoaderFactory to the network service.
+ // The pointer shouldn't be cached.
+ network::mojom::URLLoaderFactory* GetURLLoaderFactory();
+
// Call |network_factory_.FlushForTesting()|. For test use only.
void FlushNetworkInterfaceForTesting();
diff --git a/chromium/content/browser/utility_process_host_impl.cc b/chromium/content/browser/utility_process_host.cc
index 51f997c262b..39b89cd36c3 100644
--- a/chromium/content/browser/utility_process_host_impl.cc
+++ b/chromium/content/browser/utility_process_host.cc
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "content/browser/utility_process_host_impl.h"
+#include "content/browser/utility_process_host.h"
#include <utility>
@@ -11,26 +11,24 @@
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
-#include "base/memory/ptr_util.h"
#include "base/sequenced_task_runner.h"
#include "base/strings/utf_string_conversions.h"
#include "components/network_session_configurator/common/network_switches.h"
#include "content/browser/browser_child_process_host_impl.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/service_manager/service_manager_context.h"
+#include "content/browser/utility_process_host_client.h"
#include "content/common/child_process_host_impl.h"
#include "content/common/in_process_child_thread_params.h"
#include "content/common/service_manager/child_connection.h"
-#include "content/public/browser/browser_message_filter.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
-#include "content/public/browser/utility_process_host_client.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/process_type.h"
#include "content/public/common/sandboxed_process_launcher_delegate.h"
#include "content/public/common/service_manager_connection.h"
#include "content/public/common/service_names.mojom.h"
-#include "content/public/common/zygote_features.h"
+#include "content/public/common/zygote_buildflags.h"
#include "media/base/media_switches.h"
#include "services/network/public/cpp/network_switches.h"
#include "services/service_manager/public/cpp/interface_provider.h"
@@ -54,10 +52,9 @@ class UtilitySandboxedProcessLauncherDelegate
: public SandboxedProcessLauncherDelegate {
public:
UtilitySandboxedProcessLauncherDelegate(
- const base::FilePath& exposed_dir,
service_manager::SandboxType sandbox_type,
const base::EnvironmentMap& env)
- : exposed_dir_(exposed_dir),
+ :
#if defined(OS_POSIX)
env_(env),
#endif
@@ -87,30 +84,13 @@ class UtilitySandboxedProcessLauncherDelegate
service_manager::SANDBOX_TYPE_NO_SANDBOX_AND_ELEVATED_PRIVILEGES;
}
- bool PreSpawnTarget(sandbox::TargetPolicy* policy) override {
- if (exposed_dir_.empty())
- return true;
-
- sandbox::ResultCode result;
- result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
- sandbox::TargetPolicy::FILES_ALLOW_ANY,
- exposed_dir_.value().c_str());
- if (result != sandbox::SBOX_ALL_OK)
- return false;
-
- base::FilePath exposed_files = exposed_dir_.AppendASCII("*");
- result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
- sandbox::TargetPolicy::FILES_ALLOW_ANY,
- exposed_files.value().c_str());
- return result == sandbox::SBOX_ALL_OK;
- }
+ bool PreSpawnTarget(sandbox::TargetPolicy* policy) override { return true; }
#endif // OS_WIN
#if BUILDFLAG(USE_ZYGOTE_HANDLE)
ZygoteHandle GetZygote() override {
if (service_manager::IsUnsandboxedSandboxType(sandbox_type_) ||
- sandbox_type_ == service_manager::SANDBOX_TYPE_NETWORK ||
- !exposed_dir_.empty()) {
+ sandbox_type_ == service_manager::SANDBOX_TYPE_NETWORK) {
return nullptr;
}
return GetGenericZygote();
@@ -126,8 +106,6 @@ class UtilitySandboxedProcessLauncherDelegate
}
private:
- base::FilePath exposed_dir_;
-
#if defined(OS_POSIX)
base::EnvironmentMap env_;
#endif // OS_WIN
@@ -136,18 +114,12 @@ class UtilitySandboxedProcessLauncherDelegate
UtilityMainThreadFactoryFunction g_utility_main_thread_factory = nullptr;
-UtilityProcessHost* UtilityProcessHost::Create(
- const scoped_refptr<UtilityProcessHostClient>& client,
- const scoped_refptr<base::SequencedTaskRunner>& client_task_runner) {
- return new UtilityProcessHostImpl(client, client_task_runner);
-}
-
-void UtilityProcessHostImpl::RegisterUtilityMainThreadFactory(
+void UtilityProcessHost::RegisterUtilityMainThreadFactory(
UtilityMainThreadFactoryFunction create) {
g_utility_main_thread_factory = create;
}
-UtilityProcessHostImpl::UtilityProcessHostImpl(
+UtilityProcessHost::UtilityProcessHost(
const scoped_refptr<UtilityProcessHostClient>& client,
const scoped_refptr<base::SequencedTaskRunner>& client_task_runner)
: client_(client),
@@ -161,76 +133,68 @@ UtilityProcessHostImpl::UtilityProcessHostImpl(
started_(false),
name_(base::ASCIIToUTF16("utility process")),
weak_ptr_factory_(this) {
- process_.reset(new BrowserChildProcessHostImpl(
- PROCESS_TYPE_UTILITY, this, mojom::kUtilityServiceName));
+ process_.reset(new BrowserChildProcessHostImpl(PROCESS_TYPE_UTILITY, this,
+ mojom::kUtilityServiceName));
}
-UtilityProcessHostImpl::~UtilityProcessHostImpl() {
+UtilityProcessHost::~UtilityProcessHost() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
}
-base::WeakPtr<UtilityProcessHost> UtilityProcessHostImpl::AsWeakPtr() {
+base::WeakPtr<UtilityProcessHost> UtilityProcessHost::AsWeakPtr() {
return weak_ptr_factory_.GetWeakPtr();
}
-bool UtilityProcessHostImpl::Send(IPC::Message* message) {
+bool UtilityProcessHost::Send(IPC::Message* message) {
if (!StartProcess())
return false;
return process_->Send(message);
}
-void UtilityProcessHostImpl::SetExposedDir(const base::FilePath& dir) {
- exposed_dir_ = dir;
-}
-
-void UtilityProcessHostImpl::SetSandboxType(
+void UtilityProcessHost::SetSandboxType(
service_manager::SandboxType sandbox_type) {
DCHECK(sandbox_type != service_manager::SANDBOX_TYPE_INVALID);
sandbox_type_ = sandbox_type;
}
-const ChildProcessData& UtilityProcessHostImpl::GetData() {
+const ChildProcessData& UtilityProcessHost::GetData() {
return process_->GetData();
}
#if defined(OS_POSIX)
-void UtilityProcessHostImpl::SetEnv(const base::EnvironmentMap& env) {
+void UtilityProcessHost::SetEnv(const base::EnvironmentMap& env) {
env_ = env;
}
#endif
-bool UtilityProcessHostImpl::Start() {
+bool UtilityProcessHost::Start() {
return StartProcess();
}
-void UtilityProcessHostImpl::BindInterface(
+void UtilityProcessHost::BindInterface(
const std::string& interface_name,
mojo::ScopedMessagePipeHandle interface_pipe) {
process_->child_connection()->BindInterface(interface_name,
std::move(interface_pipe));
}
-void UtilityProcessHostImpl::SetName(const base::string16& name) {
+void UtilityProcessHost::SetName(const base::string16& name) {
name_ = name;
}
-void UtilityProcessHostImpl::SetServiceIdentity(
+void UtilityProcessHost::SetServiceIdentity(
const service_manager::Identity& identity) {
service_identity_ = identity;
}
-void UtilityProcessHostImpl::AddFilter(BrowserMessageFilter* filter) {
- process_->AddFilter(filter);
-}
-
-void UtilityProcessHostImpl::SetLaunchCallback(
+void UtilityProcessHost::SetLaunchCallback(
base::OnceCallback<void(base::ProcessId)> callback) {
DCHECK(!launched_);
launch_callback_ = std::move(callback);
}
-bool UtilityProcessHostImpl::StartProcess() {
+bool UtilityProcessHost::StartProcess() {
if (started_)
return true;
@@ -252,39 +216,40 @@ bool UtilityProcessHostImpl::StartProcess() {
const base::CommandLine& browser_command_line =
*base::CommandLine::ForCurrentProcess();
- bool has_cmd_prefix = browser_command_line.HasSwitch(
- switches::kUtilityCmdPrefix);
+ bool has_cmd_prefix =
+ browser_command_line.HasSwitch(switches::kUtilityCmdPrefix);
- #if defined(OS_ANDROID)
- // readlink("/prof/self/exe") sometimes fails on Android at startup.
- // As a workaround skip calling it here, since the executable name is
- // not needed on Android anyway. See crbug.com/500854.
+#if defined(OS_ANDROID)
+ // readlink("/prof/self/exe") sometimes fails on Android at startup.
+ // As a workaround skip calling it here, since the executable name is
+ // not needed on Android anyway. See crbug.com/500854.
std::unique_ptr<base::CommandLine> cmd_line =
std::make_unique<base::CommandLine>(base::CommandLine::NO_PROGRAM);
- #else
- int child_flags = child_flags_;
-
- // When running under gdb, forking /proc/self/exe ends up forking the gdb
- // executable instead of Chromium. It is almost safe to assume that no
- // updates will happen while a developer is running with
- // |switches::kUtilityCmdPrefix|. See ChildProcessHost::GetChildPath() for
- // a similar case with Valgrind.
- if (has_cmd_prefix)
- child_flags = ChildProcessHost::CHILD_NORMAL;
-
- base::FilePath exe_path = ChildProcessHost::GetChildPath(child_flags);
- if (exe_path.empty()) {
- NOTREACHED() << "Unable to get utility process binary name.";
- return false;
- }
-
- std::unique_ptr<base::CommandLine> cmd_line =
- std::make_unique<base::CommandLine>(exe_path);
- #endif
+#else
+ int child_flags = child_flags_;
+
+ // When running under gdb, forking /proc/self/exe ends up forking the gdb
+ // executable instead of Chromium. It is almost safe to assume that no
+ // updates will happen while a developer is running with
+ // |switches::kUtilityCmdPrefix|. See ChildProcessHost::GetChildPath() for
+ // a similar case with Valgrind.
+ if (has_cmd_prefix)
+ child_flags = ChildProcessHost::CHILD_NORMAL;
+
+ base::FilePath exe_path = ChildProcessHost::GetChildPath(child_flags);
+ if (exe_path.empty()) {
+ NOTREACHED() << "Unable to get utility process binary name.";
+ return false;
+ }
+
+ std::unique_ptr<base::CommandLine> cmd_line =
+ std::make_unique<base::CommandLine>(exe_path);
+#endif
cmd_line->AppendSwitchASCII(switches::kProcessType,
switches::kUtilityProcess);
BrowserChildProcessHostImpl::CopyFeatureAndFieldTrialFlags(cmd_line.get());
+ BrowserChildProcessHostImpl::CopyTraceStartupFlags(cmd_line.get());
std::string locale = GetContentClient()->browser()->GetApplicationLocale();
cmd_line->AppendSwitchASCII(switches::kLang, locale);
@@ -297,6 +262,7 @@ bool UtilityProcessHostImpl::StartProcess() {
// Browser command-line switches to propagate to the utility process.
static const char* const kSwitchNames[] = {
+ network::switches::kForceEffectiveConnectionType,
network::switches::kHostResolverRules,
network::switches::kIgnoreCertificateErrorsSPKIList,
network::switches::kLogNetLog,
@@ -330,11 +296,6 @@ bool UtilityProcessHostImpl::StartProcess() {
switches::kUtilityCmdPrefix));
}
- if (!exposed_dir_.empty()) {
- cmd_line->AppendSwitchPath(switches::kUtilityProcessAllowedDir,
- exposed_dir_);
- }
-
const bool is_service = service_identity_.has_value();
if (is_service) {
GetContentClient()->browser()->AdjustUtilityServiceProcessCommandLine(
@@ -342,14 +303,14 @@ bool UtilityProcessHostImpl::StartProcess() {
}
process_->Launch(std::make_unique<UtilitySandboxedProcessLauncherDelegate>(
- exposed_dir_, sandbox_type_, env_),
+ sandbox_type_, env_),
std::move(cmd_line), true);
}
return true;
}
-bool UtilityProcessHostImpl::OnMessageReceived(const IPC::Message& message) {
+bool UtilityProcessHost::OnMessageReceived(const IPC::Message& message) {
if (!client_.get())
return true;
@@ -362,13 +323,13 @@ bool UtilityProcessHostImpl::OnMessageReceived(const IPC::Message& message) {
return true;
}
-void UtilityProcessHostImpl::OnProcessLaunched() {
+void UtilityProcessHost::OnProcessLaunched() {
launched_ = true;
if (launch_callback_)
std::move(launch_callback_).Run(process_->GetProcess().Pid());
}
-void UtilityProcessHostImpl::OnProcessLaunchFailed(int error_code) {
+void UtilityProcessHost::OnProcessLaunchFailed(int error_code) {
if (!client_.get())
return;
@@ -378,7 +339,7 @@ void UtilityProcessHostImpl::OnProcessLaunchFailed(int error_code) {
error_code));
}
-void UtilityProcessHostImpl::OnProcessCrashed(int exit_code) {
+void UtilityProcessHost::OnProcessCrashed(int exit_code) {
if (!client_.get())
return;
@@ -387,16 +348,16 @@ void UtilityProcessHostImpl::OnProcessCrashed(int exit_code) {
client_, exit_code));
}
-void UtilityProcessHostImpl::NotifyAndDelete(int error_code) {
+void UtilityProcessHost::NotifyAndDelete(int error_code) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
- base::BindOnce(&UtilityProcessHostImpl::NotifyLaunchFailedAndDelete,
+ base::BindOnce(&UtilityProcessHost::NotifyLaunchFailedAndDelete,
weak_ptr_factory_.GetWeakPtr(), error_code));
}
// static
-void UtilityProcessHostImpl::NotifyLaunchFailedAndDelete(
- base::WeakPtr<UtilityProcessHostImpl> host,
+void UtilityProcessHost::NotifyLaunchFailedAndDelete(
+ base::WeakPtr<UtilityProcessHost> host,
int error_code) {
if (!host)
return;
diff --git a/chromium/content/browser/utility_process_host_impl.h b/chromium/content/browser/utility_process_host.h
index a02ba191dac..2ef900333a2 100644
--- a/chromium/content/browser/utility_process_host_impl.h
+++ b/chromium/content/browser/utility_process_host.h
@@ -2,61 +2,90 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef CONTENT_BROWSER_UTILITY_PROCESS_HOST_IMPL_H_
-#define CONTENT_BROWSER_UTILITY_PROCESS_HOST_IMPL_H_
+#ifndef CONTENT_BROWSER_UTILITY_PROCESS_HOST_H_
+#define CONTENT_BROWSER_UTILITY_PROCESS_HOST_H_
#include <memory>
#include <string>
+#include "base/environment.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/optional.h"
+#include "base/process/launch.h"
#include "build/build_config.h"
+#include "content/common/content_export.h"
#include "content/public/browser/browser_child_process_host_delegate.h"
-#include "content/public/browser/utility_process_host.h"
+#include "ipc/ipc_sender.h"
+#include "mojo/public/cpp/system/message_pipe.h"
#include "services/service_manager/public/cpp/identity.h"
+#include "services/service_manager/sandbox/sandbox_type.h"
namespace base {
-class FilePath;
class SequencedTaskRunner;
class Thread;
-}
+} // namespace base
namespace content {
-class BrowserMessageFilter;
class BrowserChildProcessHostImpl;
class InProcessChildThreadParams;
+class UtilityProcessHostClient;
+struct ChildProcessData;
typedef base::Thread* (*UtilityMainThreadFactoryFunction)(
const InProcessChildThreadParams&);
-class CONTENT_EXPORT UtilityProcessHostImpl
- : public UtilityProcessHost,
+// This class acts as the browser-side host to a utility child process. A
+// utility process is a short-lived process that is created to run a specific
+// task. This class lives solely on the IO thread.
+// If you need a single method call in the process, use StartFooBar(p).
+// If you need multiple batches of work to be done in the process, use
+// StartBatchMode(), then multiple calls to StartFooBar(p), then finish with
+// EndBatchMode().
+// If you need to bind Mojo interfaces, use Start() to start the child
+// process and then call BindInterface().
+//
+// Note: If your class keeps a ptr to an object of this type, grab a weak ptr to
+// avoid a use after free since this object is deleted synchronously but the
+// client notification is asynchronous. See http://crbug.com/108871.
+class CONTENT_EXPORT UtilityProcessHost
+ : public IPC::Sender,
public BrowserChildProcessHostDelegate {
public:
static void RegisterUtilityMainThreadFactory(
UtilityMainThreadFactoryFunction create);
- UtilityProcessHostImpl(
+ // |client| is optional. If supplied it will be notified of incoming messages
+ // from the utility process.
+ // |client_task_runner| is required if |client| is supplied and is the task
+ // runner upon which |client| will be invoked.
+ UtilityProcessHost(
const scoped_refptr<UtilityProcessHostClient>& client,
const scoped_refptr<base::SequencedTaskRunner>& client_task_runner);
- ~UtilityProcessHostImpl() override;
+ ~UtilityProcessHost() override;
- // UtilityProcessHost:
- base::WeakPtr<UtilityProcessHost> AsWeakPtr() override;
- bool Send(IPC::Message* message) override;
- void SetExposedDir(const base::FilePath& dir) override;
- void SetSandboxType(service_manager::SandboxType sandbox_type) override;
- const ChildProcessData& GetData() override;
+ base::WeakPtr<UtilityProcessHost> AsWeakPtr();
+
+ // Makes the process run with a specific sandbox type, or unsandboxed if
+ // SANDBOX_TYPE_NO_SANDBOX is specified.
+ void SetSandboxType(service_manager::SandboxType sandbox_type);
+
+ // Returns information about the utility child process.
+ const ChildProcessData& GetData();
#if defined(OS_POSIX)
- void SetEnv(const base::EnvironmentMap& env) override;
+ void SetEnv(const base::EnvironmentMap& env);
#endif
- bool Start() override;
+
+ // Starts the utility process.
+ bool Start();
+
+ // Binds an interface exposed by the utility process.
void BindInterface(const std::string& interface_name,
- mojo::ScopedMessagePipeHandle interface_pipe) override;
- void SetName(const base::string16& name) override;
- void AddFilter(BrowserMessageFilter* filter) override;
+ mojo::ScopedMessagePipeHandle interface_pipe);
+
+ // Sets the name of the process to appear in the task manager.
+ void SetName(const base::string16& name);
void set_child_flags(int flags) { child_flags_ = flags; }
@@ -73,6 +102,9 @@ class CONTENT_EXPORT UtilityProcessHostImpl
// Starts the child process if needed, returns true on success.
bool StartProcess();
+ // IPCSender:
+ bool Send(IPC::Message* message) override;
+
// BrowserChildProcessHostDelegate:
bool OnMessageReceived(const IPC::Message& message) override;
void OnProcessLaunched() override;
@@ -84,7 +116,7 @@ class CONTENT_EXPORT UtilityProcessHostImpl
// Notifies the client that the launch failed and deletes |host|.
static void NotifyLaunchFailedAndDelete(
- base::WeakPtr<UtilityProcessHostImpl> host,
+ base::WeakPtr<UtilityProcessHost> host,
int error_code);
// Pointer to our client interface used for progress notifications.
@@ -93,9 +125,6 @@ class CONTENT_EXPORT UtilityProcessHostImpl
// Task runner used for posting progess notifications to |client_|.
scoped_refptr<base::SequencedTaskRunner> client_task_runner_;
- // Directory opened through the child process sandbox if needed.
- base::FilePath exposed_dir_;
-
// Launch the child process with switches that will setup this sandbox type.
service_manager::SandboxType sandbox_type_;
@@ -128,11 +157,11 @@ class CONTENT_EXPORT UtilityProcessHostImpl
base::OnceCallback<void(base::ProcessId)> launch_callback_;
// Used to vend weak pointers, and should always be declared last.
- base::WeakPtrFactory<UtilityProcessHostImpl> weak_ptr_factory_;
+ base::WeakPtrFactory<UtilityProcessHost> weak_ptr_factory_;
- DISALLOW_COPY_AND_ASSIGN(UtilityProcessHostImpl);
+ DISALLOW_COPY_AND_ASSIGN(UtilityProcessHost);
};
} // namespace content
-#endif // CONTENT_BROWSER_UTILITY_PROCESS_HOST_IMPL_H_
+#endif // CONTENT_BROWSER_UTILITY_PROCESS_HOST_H_
diff --git a/chromium/content/browser/utility_process_host_impl_browsertest.cc b/chromium/content/browser/utility_process_host_browsertest.cc
index 280a37d80f0..44ed195c008 100644
--- a/chromium/content/browser/utility_process_host_impl_browsertest.cc
+++ b/chromium/content/browser/utility_process_host_browsertest.cc
@@ -5,16 +5,18 @@
#include "base/bind.h"
#include "base/run_loop.h"
#include "base/strings/utf_string_conversions.h"
+#include "build/build_config.h"
+#include "content/browser/utility_process_host.h"
+#include "content/browser/utility_process_host_client.h"
#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/utility_process_host.h"
-#include "content/public/browser/utility_process_host_client.h"
+#include "content/public/common/bind_interface_helpers.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/public/test/test_service.mojom.h"
namespace content {
-class UtilityProcessHostImplBrowserTest : public ContentBrowserTest {
+class UtilityProcessHostBrowserTest : public ContentBrowserTest {
public:
void RunUtilityProcess(bool elevated) {
base::RunLoop run_loop;
@@ -22,14 +24,16 @@ class UtilityProcessHostImplBrowserTest : public ContentBrowserTest {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(
- &UtilityProcessHostImplBrowserTest::RunUtilityProcessOnIOThread,
+ &UtilityProcessHostBrowserTest::RunUtilityProcessOnIOThread,
base::Unretained(this), elevated));
run_loop.Run();
}
protected:
void RunUtilityProcessOnIOThread(bool elevated) {
- UtilityProcessHost* host = UtilityProcessHost::Create(nullptr, nullptr);
+ UtilityProcessHost* host =
+ new UtilityProcessHost(/*client=*/nullptr,
+ /*client_task_runner=*/nullptr);
host->SetName(base::ASCIIToUTF16("TestProcess"));
#if defined(OS_WIN)
if (elevated)
@@ -39,9 +43,8 @@ class UtilityProcessHostImplBrowserTest : public ContentBrowserTest {
EXPECT_TRUE(host->Start());
BindInterface(host, &service_);
- service_->DoSomething(
- base::BindOnce(&UtilityProcessHostImplBrowserTest::OnSomething,
- base::Unretained(this)));
+ service_->DoSomething(base::BindOnce(
+ &UtilityProcessHostBrowserTest::OnSomething, base::Unretained(this)));
}
void OnSomething() {
@@ -53,13 +56,12 @@ class UtilityProcessHostImplBrowserTest : public ContentBrowserTest {
base::Closure done_closure_;
};
-IN_PROC_BROWSER_TEST_F(UtilityProcessHostImplBrowserTest, LaunchProcess) {
+IN_PROC_BROWSER_TEST_F(UtilityProcessHostBrowserTest, LaunchProcess) {
RunUtilityProcess(false);
}
#if defined(OS_WIN)
-IN_PROC_BROWSER_TEST_F(UtilityProcessHostImplBrowserTest,
- LaunchElevatedProcess) {
+IN_PROC_BROWSER_TEST_F(UtilityProcessHostBrowserTest, LaunchElevatedProcess) {
RunUtilityProcess(true);
}
#endif
diff --git a/chromium/content/public/browser/utility_process_host_client.h b/chromium/content/browser/utility_process_host_client.h
index cf546476ac0..7972fa8ec55 100644
--- a/chromium/content/public/browser/utility_process_host_client.h
+++ b/chromium/content/browser/utility_process_host_client.h
@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef CONTENT_PUBLIC_BROWSER_UTILITY_PROCESS_HOST_CLIENT_H_
-#define CONTENT_PUBLIC_BROWSER_UTILITY_PROCESS_HOST_CLIENT_H_
+#ifndef CONTENT_BROWSER_UTILITY_PROCESS_HOST_CLIENT_H_
+#define CONTENT_BROWSER_UTILITY_PROCESS_HOST_CLIENT_H_
#include "base/memory/ref_counted.h"
#include "content/common/content_export.h"
@@ -38,4 +38,4 @@ class UtilityProcessHostClient
}; // namespace content
-#endif // CONTENT_PUBLIC_BROWSER_UTILITY_PROCESS_HOST_CLIENT_H_
+#endif // CONTENT_BROWSER_UTILITY_PROCESS_HOST_CLIENT_H_
diff --git a/chromium/content/browser/utility_process_mojo_client_browsertest.cc b/chromium/content/browser/utility_process_mojo_client_browsertest.cc
deleted file mode 100644
index 11d005512ed..00000000000
--- a/chromium/content/browser/utility_process_mojo_client_browsertest.cc
+++ /dev/null
@@ -1,172 +0,0 @@
-// Copyright 2016 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/public/browser/utility_process_mojo_client.h"
-
-#include <memory>
-
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/command_line.h"
-#include "base/run_loop.h"
-#include "base/strings/utf_string_conversions.h"
-#include "content/public/common/content_switches.h"
-#include "content/public/test/content_browser_test.h"
-#include "content/public/test/test_service.mojom.h"
-
-namespace content {
-
-// Test fixture used to make different Mojo calls to the utility process.
-class UtilityProcessMojoClientBrowserTest : public ContentBrowserTest {
- public:
- enum RunOption {
- SANDBOXED, UNSANDBOXED, ELEVATED
- };
-
- void StartMojoService(RunOption option = SANDBOXED) {
- mojo_client_.reset(new UtilityProcessMojoClient<mojom::TestService>(
- base::ASCIIToUTF16("TestUtilityProcessMojoClient")));
-
- mojo_client_->set_error_callback(
- base::Bind(&UtilityProcessMojoClientBrowserTest::OnConnectionError,
- base::Unretained(this)));
-
- // This test case needs to have the sandbox disabled.
- if (option == UNSANDBOXED)
- mojo_client_->set_disable_sandbox();
-#if defined(OS_WIN)
- // This test case needs utility process UAC privilege elevation.
- if (option == ELEVATED)
- mojo_client_->set_run_elevated();
-#endif // defined(OS_WIN)
-
- mojo_client_->Start();
- }
-
- // Called when a response is received from a call to DoSomething() or
- // DoTerminateProcess().
- void OnResponseReceived() {
- response_received_ = true;
- done_closure_.Run();
- }
-
- // Called when a connection error happen between the test and the utility
- // process.
- void OnConnectionError() {
- error_happened_ = true;
- done_closure_.Run();
- }
-
- // Called when a responsed is received from a call to CreateFolder().
- void OnCreateFolderFinished(bool succeeded) {
- response_received_ = true;
- sandbox_succeeded_ = succeeded;
- done_closure_.Run();
- }
-
- protected:
- std::unique_ptr<UtilityProcessMojoClient<mojom::TestService>>
- mojo_client_;
- base::Closure done_closure_;
-
- // The test result that is compared to the current test case.
- bool response_received_ = false;
- bool error_happened_ = false;
- bool sandbox_succeeded_ = false;
-};
-
-// Successful call through the Mojo service with response back.
-IN_PROC_BROWSER_TEST_F(UtilityProcessMojoClientBrowserTest, CallService) {
- base::RunLoop run_loop;
- done_closure_ = run_loop.QuitClosure();
-
- StartMojoService();
-
- mojo_client_->service()->DoSomething(
- base::BindOnce(&UtilityProcessMojoClientBrowserTest::OnResponseReceived,
- base::Unretained(this)));
-
- run_loop.Run();
- EXPECT_TRUE(response_received_);
- EXPECT_FALSE(error_happened_);
-}
-
-// Call the Mojo service but the utility process terminates before getting
-// the result back.
-IN_PROC_BROWSER_TEST_F(UtilityProcessMojoClientBrowserTest, ConnectionError) {
- base::RunLoop run_loop;
- done_closure_ = run_loop.QuitClosure();
-
- StartMojoService();
-
- mojo_client_->service()->DoTerminateProcess(
- base::BindOnce(&UtilityProcessMojoClientBrowserTest::OnResponseReceived,
- base::Unretained(this)));
-
- run_loop.Run();
- EXPECT_FALSE(response_received_);
- EXPECT_TRUE(error_happened_);
-}
-
-// Android doesn't support non-sandboxed utility processes.
-#if !defined(OS_ANDROID)
-// Call a function that fails because the sandbox is still enabled.
-IN_PROC_BROWSER_TEST_F(UtilityProcessMojoClientBrowserTest, SandboxFailure) {
- base::RunLoop run_loop;
- done_closure_ = run_loop.QuitClosure();
-
- StartMojoService();
-
- mojo_client_->service()->CreateFolder(base::BindOnce(
- &UtilityProcessMojoClientBrowserTest::OnCreateFolderFinished,
- base::Unretained(this)));
-
- run_loop.Run();
- EXPECT_TRUE(response_received_);
- // If the sandbox is disabled by the command line, this will succeed.
- if (!base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kNoSandbox))
- EXPECT_FALSE(sandbox_succeeded_);
- EXPECT_FALSE(error_happened_);
-}
-
-// Call a function that succeeds only when the sandbox is disabled.
-IN_PROC_BROWSER_TEST_F(UtilityProcessMojoClientBrowserTest, SandboxSuccess) {
- base::RunLoop run_loop;
- done_closure_ = run_loop.QuitClosure();
-
- StartMojoService(UNSANDBOXED);
-
- mojo_client_->service()->CreateFolder(base::BindOnce(
- &UtilityProcessMojoClientBrowserTest::OnCreateFolderFinished,
- base::Unretained(this)));
-
- run_loop.Run();
- EXPECT_TRUE(response_received_);
- EXPECT_TRUE(sandbox_succeeded_);
- EXPECT_FALSE(error_happened_);
-}
-#endif // !defined(OS_ANDROID)
-
-#if defined(OS_WIN)
-// Call a function that succeeds with process elevation. Elevation is only
-// available on WIN, and is used to permit UAC prompts for operations that
-// need user approval before proceeding.
-IN_PROC_BROWSER_TEST_F(UtilityProcessMojoClientBrowserTest, ElevatedSuccess) {
- base::RunLoop run_loop;
- done_closure_ = run_loop.QuitClosure();
-
- StartMojoService(ELEVATED);
-
- mojo_client_->service()->CreateFolder(
- base::Bind(&UtilityProcessMojoClientBrowserTest::OnCreateFolderFinished,
- base::Unretained(this)));
-
- run_loop.Run();
- EXPECT_TRUE(response_received_);
- EXPECT_TRUE(sandbox_succeeded_);
- EXPECT_FALSE(error_happened_);
-}
-#endif // defined(OS_WIN)
-
-} // namespace content
diff --git a/chromium/content/browser/vibration_browsertest.cc b/chromium/content/browser/vibration_browsertest.cc
index 663ef62ab93..ec6b12a21c7 100644
--- a/chromium/content/browser/vibration_browsertest.cc
+++ b/chromium/content/browser/vibration_browsertest.cc
@@ -47,7 +47,7 @@ class VibrationTest : public ContentBrowserTest,
protected:
bool TriggerVibrate(int duration, base::Closure vibrate_done) {
- vibrate_done_ = vibrate_done;
+ vibrate_done_ = std::move(vibrate_done);
bool result;
RenderFrameHost* frame = shell()->web_contents()->GetMainFrame();
diff --git a/chromium/content/browser/wake_lock/wake_lock_browsertest.cc b/chromium/content/browser/wake_lock/wake_lock_browsertest.cc
index 013fdfd46b4..0b87944e8da 100644
--- a/chromium/content/browser/wake_lock/wake_lock_browsertest.cc
+++ b/chromium/content/browser/wake_lock/wake_lock_browsertest.cc
@@ -378,7 +378,7 @@ IN_PROC_BROWSER_TEST_F(WakeLockTest, UnlockAfterCrashOutOfProcessFrame) {
RenderProcessHostWatcher watcher(
GetNestedFrame()->GetProcess(),
RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
- GetNestedFrame()->GetProcess()->Shutdown(0, false);
+ GetNestedFrame()->GetProcess()->Shutdown(0);
watcher.Wait();
// Screen wake lock should be released.
diff --git a/chromium/content/browser/web_contents/aura/gesture_nav_simple.cc b/chromium/content/browser/web_contents/aura/gesture_nav_simple.cc
index 2bf8f708c5d..1462b5578cb 100644
--- a/chromium/content/browser/web_contents/aura/gesture_nav_simple.cc
+++ b/chromium/content/browser/web_contents/aura/gesture_nav_simple.cc
@@ -7,7 +7,6 @@
#include <utility>
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/metrics/user_metrics.h"
#include "cc/paint/paint_flags.h"
@@ -555,6 +554,12 @@ bool GestureNavSimple::OnOverscrollUpdate(float delta_x, float delta_y) {
}
void GestureNavSimple::OnOverscrollComplete(OverscrollMode overscroll_mode) {
+ if (mode_ == OverscrollMode::OVERSCROLL_NONE) {
+ // Previous mode change has been ignored because of overscroll-behavior
+ // value; so, ignore this, too.
+ return;
+ }
+
DCHECK_EQ(mode_, overscroll_mode);
mode_ = OVERSCROLL_NONE;
@@ -597,7 +602,31 @@ void GestureNavSimple::OnOverscrollComplete(OverscrollMode overscroll_mode) {
void GestureNavSimple::OnOverscrollModeChange(OverscrollMode old_mode,
OverscrollMode new_mode,
- OverscrollSource source) {
+ OverscrollSource source,
+ cc::OverscrollBehavior behavior) {
+ DCHECK(old_mode == OverscrollMode::OVERSCROLL_NONE ||
+ new_mode == OverscrollMode::OVERSCROLL_NONE);
+
+ // Do not start a new gesture-nav if overscroll-behavior-x is not auto.
+ if ((new_mode == OverscrollMode::OVERSCROLL_EAST ||
+ new_mode == OverscrollMode::OVERSCROLL_WEST) &&
+ behavior.x != cc::OverscrollBehavior::kOverscrollBehaviorTypeAuto) {
+ return;
+ }
+
+ // Do not start a new pull-to-refresh if overscroll-behavior-y is not auto.
+ if (new_mode == OverscrollMode::OVERSCROLL_SOUTH &&
+ behavior.y != cc::OverscrollBehavior::kOverscrollBehaviorTypeAuto) {
+ return;
+ }
+
+ if (old_mode != OverscrollMode::OVERSCROLL_NONE &&
+ mode_ == OverscrollMode::OVERSCROLL_NONE) {
+ // Previous mode change has been ignored because of overscroll-behavior
+ // value; so, ignore this one, too.
+ return;
+ }
+
DCHECK_EQ(mode_, old_mode);
if (mode_ == new_mode)
return;
diff --git a/chromium/content/browser/web_contents/aura/gesture_nav_simple.h b/chromium/content/browser/web_contents/aura/gesture_nav_simple.h
index 040da490c2a..0ede7b99213 100644
--- a/chromium/content/browser/web_contents/aura/gesture_nav_simple.h
+++ b/chromium/content/browser/web_contents/aura/gesture_nav_simple.h
@@ -9,6 +9,7 @@
#include "base/macros.h"
#include "content/browser/renderer_host/overscroll_controller_delegate.h"
+#include "content/common/content_export.h"
namespace content {
@@ -17,7 +18,7 @@ class WebContentsImpl;
// A simple delegate for the overscroll controller that paints an arrow on top
// of the web-contents as a hint for pending navigations from overscroll.
-class GestureNavSimple : public OverscrollControllerDelegate {
+class CONTENT_EXPORT GestureNavSimple : public OverscrollControllerDelegate {
public:
explicit GestureNavSimple(WebContentsImpl* web_contents);
~GestureNavSimple() override;
@@ -27,15 +28,16 @@ class GestureNavSimple : public OverscrollControllerDelegate {
void OnAffordanceAnimationEnded();
private:
+ friend class GestureNavSimpleTest;
+
// OverscrollControllerDelegate:
gfx::Size GetDisplaySize() const override;
- void OnOverscrollBehaviorUpdate(
- cc::OverscrollBehavior overscroll_behavior) override {}
bool OnOverscrollUpdate(float delta_x, float delta_y) override;
void OnOverscrollComplete(OverscrollMode overscroll_mode) override;
void OnOverscrollModeChange(OverscrollMode old_mode,
OverscrollMode new_mode,
- OverscrollSource source) override;
+ OverscrollSource source,
+ cc::OverscrollBehavior behavior) override;
base::Optional<float> GetMaxOverscrollDelta() const override;
WebContentsImpl* web_contents_ = nullptr;
diff --git a/chromium/content/browser/web_contents/aura/gesture_nav_simple_unittest.cc b/chromium/content/browser/web_contents/aura/gesture_nav_simple_unittest.cc
new file mode 100644
index 00000000000..9864bef84fc
--- /dev/null
+++ b/chromium/content/browser/web_contents/aura/gesture_nav_simple_unittest.cc
@@ -0,0 +1,360 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/web_contents/aura/gesture_nav_simple.h"
+
+#include "content/public/browser/browser_context.h"
+#include "content/public/browser/site_instance.h"
+#include "content/test/test_render_view_host.h"
+#include "content/test/test_web_contents.h"
+#include "ui/aura/window.h"
+
+#include <memory>
+
+namespace content {
+
+namespace {
+
+// A subclass of TestWebContents that offers a fake content window.
+class GestureNavTestWebContents : public TestWebContents {
+ public:
+ ~GestureNavTestWebContents() override {}
+
+ static GestureNavTestWebContents* Create(
+ BrowserContext* browser_context,
+ scoped_refptr<SiteInstance> instance,
+ std::unique_ptr<aura::Window> fake_native_view,
+ std::unique_ptr<aura::Window> fake_contents_window) {
+ auto* web_contents = new GestureNavTestWebContents(
+ browser_context, std::move(fake_native_view),
+ std::move(fake_contents_window));
+ web_contents->Init(
+ WebContents::CreateParams(browser_context, std::move(instance)));
+ return web_contents;
+ }
+
+ // Overriden from TestWebContents:
+ gfx::NativeView GetNativeView() override { return fake_native_view_.get(); }
+
+ gfx::NativeView GetContentNativeView() override {
+ return fake_contents_window_.get();
+ }
+
+ protected:
+ explicit GestureNavTestWebContents(
+ BrowserContext* browser_context,
+ std::unique_ptr<aura::Window> fake_native_view,
+ std::unique_ptr<aura::Window> fake_contents_window)
+ : TestWebContents(browser_context),
+ fake_native_view_(std::move(fake_native_view)),
+ fake_contents_window_(std::move(fake_contents_window)) {}
+
+ private:
+ std::unique_ptr<aura::Window> fake_native_view_;
+ std::unique_ptr<aura::Window> fake_contents_window_;
+};
+
+} // namespace
+
+class GestureNavSimpleTest : public RenderViewHostImplTestHarness {
+ public:
+ GestureNavSimpleTest()
+ : first_("https://www.google.com"), second_("http://www.chromium.org") {}
+
+ ~GestureNavSimpleTest() override {}
+
+ protected:
+ // RenderViewHostImplTestHarness:
+ void SetUp() override {
+ RenderViewHostImplTestHarness::SetUp();
+
+ // Set up the fake web contents native view.
+ auto fake_native_view = std::make_unique<aura::Window>(nullptr);
+ fake_native_view->Init(ui::LAYER_SOLID_COLOR);
+ root_window()->AddChild(fake_native_view.get());
+ fake_native_view->SetBounds(gfx::Rect(root_window()->bounds().size()));
+
+ // Set up the fake contents window.
+ auto fake_contents_window = std::make_unique<aura::Window>(nullptr);
+ fake_contents_window->Init(ui::LAYER_SOLID_COLOR);
+ root_window()->AddChild(fake_contents_window.get());
+ fake_contents_window->SetBounds(gfx::Rect(root_window()->bounds().size()));
+
+ // Replace the default test web contents with our custom class.
+ SetContents(GestureNavTestWebContents::Create(
+ browser_context(), SiteInstance::Create(browser_context()),
+ std::move(fake_native_view), std::move(fake_contents_window)));
+
+ // Add two pages to navigation history.
+ contents()->NavigateAndCommit(first_);
+ EXPECT_TRUE(controller().GetVisibleEntry());
+ EXPECT_FALSE(controller().CanGoBack());
+
+ contents()->NavigateAndCommit(second_);
+ EXPECT_TRUE(controller().CanGoBack());
+ EXPECT_FALSE(controller().CanGoForward());
+
+ gesture_nav_simple_ = std::make_unique<GestureNavSimple>(contents());
+ }
+
+ void TearDown() override {
+ gesture_nav_simple_ = nullptr;
+ RenderViewHostImplTestHarness::TearDown();
+ }
+
+ const GURL first() const { return first_; }
+ const GURL second() const { return second_; }
+
+ void OnOverscrollModeChange(OverscrollMode old_mode,
+ OverscrollMode new_mode,
+ OverscrollSource source,
+ cc::OverscrollBehavior behavior) {
+ gesture_nav_simple_->OnOverscrollModeChange(old_mode, new_mode, source,
+ behavior);
+ }
+
+ void OnOverscrollComplete(OverscrollMode overscroll_mode) {
+ gesture_nav_simple_->OnOverscrollComplete(overscroll_mode);
+ }
+
+ OverscrollMode mode() const { return gesture_nav_simple_->mode_; }
+ OverscrollSource source() const { return gesture_nav_simple_->source_; }
+
+ private:
+ // Test URLs.
+ const GURL first_;
+ const GURL second_;
+
+ std::unique_ptr<GestureNavSimple> gesture_nav_simple_;
+
+ DISALLOW_COPY_AND_ASSIGN(GestureNavSimpleTest);
+};
+
+// Tests that setting 'overscroll-behavior-x' to 'auto' allows gesture-nav.
+TEST_F(GestureNavSimpleTest, OverscrollBehaviorXAutoAllowsGestureNav) {
+ EXPECT_EQ(second(), contents()->GetURL());
+
+ cc::OverscrollBehavior behavior_x_auto;
+ behavior_x_auto.x = cc::OverscrollBehavior::kOverscrollBehaviorTypeAuto;
+
+ OnOverscrollModeChange(OverscrollMode::OVERSCROLL_NONE,
+ OverscrollMode::OVERSCROLL_EAST,
+ OverscrollSource::TOUCHSCREEN, behavior_x_auto);
+
+ EXPECT_EQ(OverscrollMode::OVERSCROLL_EAST, mode());
+ EXPECT_EQ(OverscrollSource::TOUCHSCREEN, source());
+}
+
+// Tests that setting 'overscroll-behavior-x' to 'contain' prevents gesture-nav.
+TEST_F(GestureNavSimpleTest, OverscrollBehaviorXContainPreventsGestureNav) {
+ EXPECT_EQ(second(), contents()->GetURL());
+
+ cc::OverscrollBehavior behavior_x_contain;
+ behavior_x_contain.x = cc::OverscrollBehavior::kOverscrollBehaviorTypeContain;
+
+ OnOverscrollModeChange(OverscrollMode::OVERSCROLL_NONE,
+ OverscrollMode::OVERSCROLL_EAST,
+ OverscrollSource::TOUCHSCREEN, behavior_x_contain);
+
+ EXPECT_EQ(OverscrollMode::OVERSCROLL_NONE, mode());
+ EXPECT_EQ(OverscrollSource::NONE, source());
+}
+
+// Tests that setting 'overscroll-behavior-x' to 'none' prevents gesture-nav.
+TEST_F(GestureNavSimpleTest, OverscrollBehaviorXNonePreventsGestureNav) {
+ EXPECT_EQ(second(), contents()->GetURL());
+
+ cc::OverscrollBehavior behavior_x_none;
+ behavior_x_none.x = cc::OverscrollBehavior::kOverscrollBehaviorTypeNone;
+
+ OnOverscrollModeChange(OverscrollMode::OVERSCROLL_NONE,
+ OverscrollMode::OVERSCROLL_EAST,
+ OverscrollSource::TOUCHSCREEN, behavior_x_none);
+
+ EXPECT_EQ(OverscrollMode::OVERSCROLL_NONE, mode());
+ EXPECT_EQ(OverscrollSource::NONE, source());
+}
+
+// Tests that setting 'overscroll-behavior-y' to 'auto' allows pull-to-refresh.
+TEST_F(GestureNavSimpleTest, OverscrollBehaviorYAutoAllowsPullToRefresh) {
+ cc::OverscrollBehavior behavior_y_auto;
+ behavior_y_auto.y = cc::OverscrollBehavior::kOverscrollBehaviorTypeAuto;
+
+ OnOverscrollModeChange(OverscrollMode::OVERSCROLL_NONE,
+ OverscrollMode::OVERSCROLL_SOUTH,
+ OverscrollSource::TOUCHSCREEN, behavior_y_auto);
+
+ EXPECT_EQ(OverscrollMode::OVERSCROLL_SOUTH, mode());
+ EXPECT_EQ(OverscrollSource::TOUCHSCREEN, source());
+}
+
+// Tests that setting 'overscroll-behavior-y' to 'contain' prevents
+// pull-to-refresh.
+TEST_F(GestureNavSimpleTest, OverscrollBehaviorYContainPreventsPullToRefresh) {
+ cc::OverscrollBehavior behavior_y_contain;
+ behavior_y_contain.y = cc::OverscrollBehavior::kOverscrollBehaviorTypeContain;
+
+ OnOverscrollModeChange(OverscrollMode::OVERSCROLL_NONE,
+ OverscrollMode::OVERSCROLL_SOUTH,
+ OverscrollSource::TOUCHSCREEN, behavior_y_contain);
+
+ EXPECT_EQ(OverscrollMode::OVERSCROLL_NONE, mode());
+ EXPECT_EQ(OverscrollSource::NONE, source());
+}
+
+// Tests that setting 'overscroll-behavior-y' to 'none' prevents
+// pull-to-refresh.
+TEST_F(GestureNavSimpleTest, OverscrollBehaviorYNonePreventsPullToRefresh) {
+ cc::OverscrollBehavior behavior_y_none;
+ behavior_y_none.y = cc::OverscrollBehavior::kOverscrollBehaviorTypeNone;
+
+ OnOverscrollModeChange(OverscrollMode::OVERSCROLL_NONE,
+ OverscrollMode::OVERSCROLL_SOUTH,
+ OverscrollSource::TOUCHSCREEN, behavior_y_none);
+
+ EXPECT_EQ(OverscrollMode::OVERSCROLL_NONE, mode());
+ EXPECT_EQ(OverscrollSource::NONE, source());
+}
+
+// Tests that setting 'overscroll-behavior-x' to a value that prevents
+// gesture-nav after it has started does not affect aborting it.
+TEST_F(GestureNavSimpleTest, PreventGestureNavBeforeAbort) {
+ EXPECT_EQ(second(), contents()->GetURL());
+
+ cc::OverscrollBehavior behavior_x_auto;
+ behavior_x_auto.x = cc::OverscrollBehavior::kOverscrollBehaviorTypeAuto;
+ cc::OverscrollBehavior behavior_x_contain;
+ behavior_x_contain.x = cc::OverscrollBehavior::kOverscrollBehaviorTypeContain;
+
+ OnOverscrollModeChange(OverscrollMode::OVERSCROLL_NONE,
+ OverscrollMode::OVERSCROLL_EAST,
+ OverscrollSource::TOUCHSCREEN, behavior_x_auto);
+
+ EXPECT_EQ(OverscrollMode::OVERSCROLL_EAST, mode());
+ EXPECT_EQ(OverscrollSource::TOUCHSCREEN, source());
+
+ OnOverscrollModeChange(OverscrollMode::OVERSCROLL_EAST,
+ OverscrollMode::OVERSCROLL_NONE,
+ OverscrollSource::TOUCHSCREEN, behavior_x_contain);
+
+ EXPECT_EQ(OverscrollMode::OVERSCROLL_NONE, mode());
+ EXPECT_EQ(OverscrollSource::NONE, source());
+ EXPECT_EQ(second(), contents()->GetURL());
+}
+
+// Tests that after gesture-nav was prevented due to 'overscroll-behavior-x',
+// setting it to 'auto' does not affect aborting overscroll.
+TEST_F(GestureNavSimpleTest, AllowGestureNavBeforeAbort) {
+ EXPECT_EQ(second(), contents()->GetURL());
+
+ cc::OverscrollBehavior behavior_x_contain;
+ behavior_x_contain.x = cc::OverscrollBehavior::kOverscrollBehaviorTypeContain;
+ cc::OverscrollBehavior behavior_x_auto;
+ behavior_x_auto.x = cc::OverscrollBehavior::kOverscrollBehaviorTypeAuto;
+
+ OnOverscrollModeChange(OverscrollMode::OVERSCROLL_NONE,
+ OverscrollMode::OVERSCROLL_EAST,
+ OverscrollSource::TOUCHSCREEN, behavior_x_contain);
+
+ EXPECT_EQ(OverscrollMode::OVERSCROLL_NONE, mode());
+ EXPECT_EQ(OverscrollSource::NONE, source());
+
+ OnOverscrollModeChange(OverscrollMode::OVERSCROLL_EAST,
+ OverscrollMode::OVERSCROLL_NONE,
+ OverscrollSource::TOUCHSCREEN, behavior_x_auto);
+
+ EXPECT_EQ(OverscrollMode::OVERSCROLL_NONE, mode());
+ EXPECT_EQ(OverscrollSource::NONE, source());
+ EXPECT_EQ(second(), contents()->GetURL());
+}
+
+// Tests that preventing gesture-nav using 'overscroll-behavior-x' does not
+// affect completing overscroll.
+TEST_F(GestureNavSimpleTest, CompletePreventedGestureNav) {
+ EXPECT_EQ(second(), contents()->GetURL());
+
+ cc::OverscrollBehavior behavior_x_contain;
+ behavior_x_contain.x = cc::OverscrollBehavior::kOverscrollBehaviorTypeContain;
+
+ OnOverscrollModeChange(OverscrollMode::OVERSCROLL_NONE,
+ OverscrollMode::OVERSCROLL_EAST,
+ OverscrollSource::TOUCHSCREEN, behavior_x_contain);
+
+ EXPECT_EQ(OverscrollMode::OVERSCROLL_NONE, mode());
+ EXPECT_EQ(OverscrollSource::NONE, source());
+
+ OnOverscrollComplete(OverscrollMode::OVERSCROLL_EAST);
+
+ EXPECT_EQ(OverscrollMode::OVERSCROLL_NONE, mode());
+ EXPECT_EQ(OverscrollSource::NONE, source());
+ EXPECT_EQ(second(), contents()->GetURL());
+}
+
+// Tests that setting 'overscroll-behavior-y' to a value that prevents
+// pull-to-refresh after it has started does not affect aborting it.
+TEST_F(GestureNavSimpleTest, PreventPullToRefreshBeforeAbort) {
+ cc::OverscrollBehavior behavior_y_auto;
+ behavior_y_auto.y = cc::OverscrollBehavior::kOverscrollBehaviorTypeAuto;
+ cc::OverscrollBehavior behavior_y_contain;
+ behavior_y_contain.y = cc::OverscrollBehavior::kOverscrollBehaviorTypeContain;
+
+ OnOverscrollModeChange(OverscrollMode::OVERSCROLL_NONE,
+ OverscrollMode::OVERSCROLL_SOUTH,
+ OverscrollSource::TOUCHSCREEN, behavior_y_auto);
+
+ EXPECT_EQ(OverscrollMode::OVERSCROLL_SOUTH, mode());
+ EXPECT_EQ(OverscrollSource::TOUCHSCREEN, source());
+
+ OnOverscrollModeChange(OverscrollMode::OVERSCROLL_SOUTH,
+ OverscrollMode::OVERSCROLL_NONE,
+ OverscrollSource::TOUCHSCREEN, behavior_y_contain);
+
+ EXPECT_EQ(OverscrollMode::OVERSCROLL_NONE, mode());
+ EXPECT_EQ(OverscrollSource::NONE, source());
+}
+
+// Tests that after pull-to-refresh was prevented due to
+// 'overscroll-behavior-y', setting it to 'auto' does not affect aborting
+// overscroll.
+TEST_F(GestureNavSimpleTest, AllowPullToRefreshBeforeAbort) {
+ cc::OverscrollBehavior behavior_y_contain;
+ behavior_y_contain.y = cc::OverscrollBehavior::kOverscrollBehaviorTypeContain;
+ cc::OverscrollBehavior behavior_y_auto;
+ behavior_y_auto.y = cc::OverscrollBehavior::kOverscrollBehaviorTypeAuto;
+
+ OnOverscrollModeChange(OverscrollMode::OVERSCROLL_NONE,
+ OverscrollMode::OVERSCROLL_SOUTH,
+ OverscrollSource::TOUCHSCREEN, behavior_y_contain);
+
+ EXPECT_EQ(OverscrollMode::OVERSCROLL_NONE, mode());
+ EXPECT_EQ(OverscrollSource::NONE, source());
+
+ OnOverscrollModeChange(OverscrollMode::OVERSCROLL_SOUTH,
+ OverscrollMode::OVERSCROLL_NONE,
+ OverscrollSource::TOUCHSCREEN, behavior_y_auto);
+
+ EXPECT_EQ(OverscrollMode::OVERSCROLL_NONE, mode());
+ EXPECT_EQ(OverscrollSource::NONE, source());
+}
+
+// Tests that preventing pull-to-refresh using 'overscroll-behavior-y' does not
+// affect completing overscroll.
+TEST_F(GestureNavSimpleTest, CompletePreventedPullToRefresh) {
+ cc::OverscrollBehavior behavior_y_contain;
+ behavior_y_contain.y = cc::OverscrollBehavior::kOverscrollBehaviorTypeContain;
+
+ OnOverscrollModeChange(OverscrollMode::OVERSCROLL_NONE,
+ OverscrollMode::OVERSCROLL_SOUTH,
+ OverscrollSource::TOUCHSCREEN, behavior_y_contain);
+
+ EXPECT_EQ(OverscrollMode::OVERSCROLL_NONE, mode());
+ EXPECT_EQ(OverscrollSource::NONE, source());
+
+ OnOverscrollComplete(OverscrollMode::OVERSCROLL_SOUTH);
+
+ EXPECT_EQ(OverscrollMode::OVERSCROLL_NONE, mode());
+ EXPECT_EQ(OverscrollSource::NONE, source());
+}
+
+} // namespace content
diff --git a/chromium/content/browser/web_contents/aura/overscroll_navigation_overlay_unittest.cc b/chromium/content/browser/web_contents/aura/overscroll_navigation_overlay_unittest.cc
index c3d13d852c4..110658ebc58 100644
--- a/chromium/content/browser/web_contents/aura/overscroll_navigation_overlay_unittest.cc
+++ b/chromium/content/browser/web_contents/aura/overscroll_navigation_overlay_unittest.cc
@@ -444,7 +444,8 @@ TEST_F(OverscrollNavigationOverlayTest, CloseDuringAnimation) {
ui::ScopedAnimationDurationScaleMode normal_duration_(
ui::ScopedAnimationDurationScaleMode::NORMAL_DURATION);
GetOverlay()->owa_->OnOverscrollModeChange(OVERSCROLL_NONE, OVERSCROLL_EAST,
- OverscrollSource::TOUCHSCREEN);
+ OverscrollSource::TOUCHSCREEN,
+ cc::OverscrollBehavior());
GetOverlay()->owa_->OnOverscrollComplete(OVERSCROLL_EAST);
EXPECT_EQ(GetOverlay()->direction_, NavigationDirection::BACK);
OverscrollTestWebContents* test_web_contents =
@@ -463,7 +464,8 @@ TEST_F(OverscrollNavigationOverlayTest, ImmediateLoadOnNavigate) {
// navigation starts.
ImmediateLoadObserver immediate_nav(contents());
GetOverlay()->owa_->OnOverscrollModeChange(OVERSCROLL_NONE, OVERSCROLL_EAST,
- OverscrollSource::TOUCHPAD);
+ OverscrollSource::TOUCHPAD,
+ cc::OverscrollBehavior());
// This will start and immediately complete the navigation.
GetOverlay()->owa_->OnOverscrollComplete(OVERSCROLL_EAST);
EXPECT_FALSE(GetOverlay()->window_.get());
diff --git a/chromium/content/browser/web_contents/aura/overscroll_window_animation.cc b/chromium/content/browser/web_contents/aura/overscroll_window_animation.cc
index cd36565d0c7..c7cf437d837 100644
--- a/chromium/content/browser/web_contents/aura/overscroll_window_animation.cc
+++ b/chromium/content/browser/web_contents/aura/overscroll_window_animation.cc
@@ -62,11 +62,6 @@ gfx::Size OverscrollWindowAnimation::GetDisplaySize() const {
.size();
}
-void OverscrollWindowAnimation::OnOverscrollBehaviorUpdate(
- cc::OverscrollBehavior overscroll_behavior) {
- overscroll_behavior_ = overscroll_behavior;
-}
-
bool OverscrollWindowAnimation::OnOverscrollUpdate(float delta_x,
float delta_y) {
if (direction_ == SLIDE_NONE)
@@ -96,12 +91,13 @@ void OverscrollWindowAnimation::OnImplicitAnimationsCompleted() {
void OverscrollWindowAnimation::OnOverscrollModeChange(
OverscrollMode old_mode,
OverscrollMode new_mode,
- OverscrollSource source) {
+ OverscrollSource source,
+ cc::OverscrollBehavior behavior) {
DCHECK_NE(old_mode, new_mode);
Direction new_direction = GetDirectionForMode(new_mode);
if (new_direction == SLIDE_NONE ||
- overscroll_behavior_.x != cc::OverscrollBehavior::OverscrollBehaviorType::
- kOverscrollBehaviorTypeAuto) {
+ behavior.x != cc::OverscrollBehavior::OverscrollBehaviorType::
+ kOverscrollBehaviorTypeAuto) {
// The user cancelled the in progress animation.
if (is_active())
CancelSlide();
diff --git a/chromium/content/browser/web_contents/aura/overscroll_window_animation.h b/chromium/content/browser/web_contents/aura/overscroll_window_animation.h
index 26e1f571bf3..a29cc6b7355 100644
--- a/chromium/content/browser/web_contents/aura/overscroll_window_animation.h
+++ b/chromium/content/browser/web_contents/aura/overscroll_window_animation.h
@@ -85,13 +85,12 @@ class CONTENT_EXPORT OverscrollWindowAnimation
// OverscrollControllerDelegate:
gfx::Size GetDisplaySize() const override;
- void OnOverscrollBehaviorUpdate(
- cc::OverscrollBehavior overscroll_behavior) override;
bool OnOverscrollUpdate(float delta_x, float delta_y) override;
void OnOverscrollComplete(OverscrollMode overscroll_mode) override;
void OnOverscrollModeChange(OverscrollMode old_mode,
OverscrollMode new_mode,
- OverscrollSource source) override;
+ OverscrollSource source,
+ cc::OverscrollBehavior behavior) override;
base::Optional<float> GetMaxOverscrollDelta() const override;
private:
@@ -137,12 +136,6 @@ class CONTENT_EXPORT OverscrollWindowAnimation
// on the delegate.
OverscrollSource overscroll_source_ = OverscrollSource::NONE;
- // OverscrollBehavior of the current overscroll gesture. Updated by
- // OnOverscrollBehaviorUpdate(). This happens before before
- // OnOverscrollModeChange and OnOverscrollUpdate. It prevents overscroll
- // navigation if its x value is not auto.
- cc::OverscrollBehavior overscroll_behavior_;
-
// Indicates if the current slide has been cancelled. True while the cancel
// animation is in progress.
bool overscroll_cancelled_;
diff --git a/chromium/content/browser/web_contents/aura/overscroll_window_animation_unittest.cc b/chromium/content/browser/web_contents/aura/overscroll_window_animation_unittest.cc
index 66c1599f2cf..9fc3c913e58 100644
--- a/chromium/content/browser/web_contents/aura/overscroll_window_animation_unittest.cc
+++ b/chromium/content/browser/web_contents/aura/overscroll_window_animation_unittest.cc
@@ -128,7 +128,8 @@ TEST_F(OverscrollWindowAnimationTest, BasicOverscroll) {
// Start an OVERSCROLL_EAST gesture.
owa()->OnOverscrollModeChange(OVERSCROLL_NONE, OVERSCROLL_EAST,
- OverscrollSource::TOUCHPAD);
+ OverscrollSource::TOUCHPAD,
+ cc::OverscrollBehavior());
EXPECT_TRUE(owa()->is_active());
EXPECT_EQ(OverscrollSource::TOUCHPAD, owa()->overscroll_source());
EXPECT_TRUE(overscroll_started());
@@ -149,11 +150,13 @@ TEST_F(OverscrollWindowAnimationTest, BasicOverscroll) {
TEST_F(OverscrollWindowAnimationTest, BasicAbort) {
// Start an OVERSCROLL_EAST gesture.
owa()->OnOverscrollModeChange(OVERSCROLL_NONE, OVERSCROLL_EAST,
- OverscrollSource::TOUCHSCREEN);
+ OverscrollSource::TOUCHSCREEN,
+ cc::OverscrollBehavior());
EXPECT_EQ(OverscrollSource::TOUCHSCREEN, owa()->overscroll_source());
// Abort the overscroll.
owa()->OnOverscrollModeChange(OVERSCROLL_EAST, OVERSCROLL_NONE,
- OverscrollSource::TOUCHSCREEN);
+ OverscrollSource::TOUCHSCREEN,
+ cc::OverscrollBehavior());
EXPECT_EQ(OverscrollSource::NONE, owa()->overscroll_source());
EXPECT_FALSE(owa()->is_active());
EXPECT_TRUE(overscroll_started());
@@ -167,7 +170,8 @@ TEST_F(OverscrollWindowAnimationTest, BasicCannotNavigate) {
set_create_window(false);
// Start an OVERSCROLL_EAST gesture.
owa()->OnOverscrollModeChange(OVERSCROLL_NONE, OVERSCROLL_EAST,
- OverscrollSource::TOUCHPAD);
+ OverscrollSource::TOUCHPAD,
+ cc::OverscrollBehavior());
EXPECT_FALSE(owa()->is_active());
EXPECT_EQ(OverscrollSource::NONE, owa()->overscroll_source());
EXPECT_TRUE(overscroll_started());
@@ -190,7 +194,8 @@ TEST_F(OverscrollWindowAnimationTest, NewOverscrollCompletesPreviousGesture) {
ui::LayerAnimatorTestController test_controller(animator);
// Start an OVERSCROLL_EAST gesture.
owa()->OnOverscrollModeChange(OVERSCROLL_NONE, OVERSCROLL_EAST,
- OverscrollSource::TOUCHPAD);
+ OverscrollSource::TOUCHPAD,
+ cc::OverscrollBehavior());
// Finishes the OVERSCROLL_EAST gesture. At this point the window should be
// being animated to its final position.
@@ -204,7 +209,8 @@ TEST_F(OverscrollWindowAnimationTest, NewOverscrollCompletesPreviousGesture) {
// Start another OVERSCROLL_EAST gesture.
owa()->OnOverscrollModeChange(OVERSCROLL_NONE, OVERSCROLL_EAST,
- OverscrollSource::TOUCHSCREEN);
+ OverscrollSource::TOUCHSCREEN,
+ cc::OverscrollBehavior());
EXPECT_TRUE(owa()->is_active());
EXPECT_EQ(OverscrollSource::TOUCHSCREEN, owa()->overscroll_source());
EXPECT_TRUE(overscroll_started());
@@ -249,9 +255,9 @@ TEST_F(OverscrollWindowAnimationTest, OverscrollBehaviorAutoAllowsOverscroll) {
cc::OverscrollBehavior overscroll_behavior;
overscroll_behavior.x = cc::OverscrollBehavior::OverscrollBehaviorType::
kOverscrollBehaviorTypeAuto;
- owa()->OnOverscrollBehaviorUpdate(overscroll_behavior);
owa()->OnOverscrollModeChange(OVERSCROLL_NONE, OVERSCROLL_EAST,
- OverscrollSource::TOUCHPAD);
+ OverscrollSource::TOUCHPAD,
+ overscroll_behavior);
EXPECT_TRUE(owa()->is_active());
EXPECT_EQ(OverscrollSource::TOUCHPAD, owa()->overscroll_source());
EXPECT_TRUE(overscroll_started());
@@ -271,9 +277,9 @@ TEST_F(OverscrollWindowAnimationTest,
cc::OverscrollBehavior overscroll_behavior;
overscroll_behavior.x = cc::OverscrollBehavior::OverscrollBehaviorType::
kOverscrollBehaviorTypeContain;
- owa()->OnOverscrollBehaviorUpdate(overscroll_behavior);
owa()->OnOverscrollModeChange(OVERSCROLL_NONE, OVERSCROLL_EAST,
- OverscrollSource::TOUCHPAD);
+ OverscrollSource::TOUCHPAD,
+ overscroll_behavior);
EXPECT_FALSE(owa()->is_active());
EXPECT_FALSE(overscroll_started());
EXPECT_FALSE(overscroll_completing());
@@ -292,9 +298,9 @@ TEST_F(OverscrollWindowAnimationTest,
cc::OverscrollBehavior overscroll_behavior;
overscroll_behavior.x = cc::OverscrollBehavior::OverscrollBehaviorType::
kOverscrollBehaviorTypeNone;
- owa()->OnOverscrollBehaviorUpdate(overscroll_behavior);
owa()->OnOverscrollModeChange(OVERSCROLL_NONE, OVERSCROLL_EAST,
- OverscrollSource::TOUCHPAD);
+ OverscrollSource::TOUCHPAD,
+ overscroll_behavior);
EXPECT_FALSE(owa()->is_active());
EXPECT_FALSE(overscroll_started());
EXPECT_FALSE(overscroll_completing());
@@ -315,9 +321,9 @@ TEST_F(OverscrollWindowAnimationTest,
kOverscrollBehaviorTypeAuto;
overscroll_behavior.y = cc::OverscrollBehavior::OverscrollBehaviorType::
kOverscrollBehaviorTypeNone;
- owa()->OnOverscrollBehaviorUpdate(overscroll_behavior);
owa()->OnOverscrollModeChange(OVERSCROLL_NONE, OVERSCROLL_EAST,
- OverscrollSource::TOUCHPAD);
+ OverscrollSource::TOUCHPAD,
+ overscroll_behavior);
EXPECT_TRUE(owa()->is_active());
EXPECT_EQ(OverscrollSource::TOUCHPAD, owa()->overscroll_source());
EXPECT_TRUE(overscroll_started());
diff --git a/chromium/content/browser/web_contents/aura/overscroll_window_delegate.cc b/chromium/content/browser/web_contents/aura/overscroll_window_delegate.cc
index 23aadf26406..3e4851888ed 100644
--- a/chromium/content/browser/web_contents/aura/overscroll_window_delegate.cc
+++ b/chromium/content/browser/web_contents/aura/overscroll_window_delegate.cc
@@ -43,14 +43,16 @@ void OverscrollWindowDelegate::StartOverscroll(OverscrollSource source) {
overscroll_mode_ = OVERSCROLL_EAST;
else
overscroll_mode_ = OVERSCROLL_WEST;
- delegate_->OnOverscrollModeChange(old_mode, overscroll_mode_, source);
+ delegate_->OnOverscrollModeChange(old_mode, overscroll_mode_, source,
+ cc::OverscrollBehavior());
}
void OverscrollWindowDelegate::ResetOverscroll() {
if (overscroll_mode_ == OVERSCROLL_NONE)
return;
delegate_->OnOverscrollModeChange(overscroll_mode_, OVERSCROLL_NONE,
- OverscrollSource::NONE);
+ OverscrollSource::NONE,
+ cc::OverscrollBehavior());
overscroll_mode_ = OVERSCROLL_NONE;
delta_x_ = 0;
}
diff --git a/chromium/content/browser/web_contents/aura/overscroll_window_delegate_unittest.cc b/chromium/content/browser/web_contents/aura/overscroll_window_delegate_unittest.cc
index f8f4828b380..bddc9a007cd 100644
--- a/chromium/content/browser/web_contents/aura/overscroll_window_delegate_unittest.cc
+++ b/chromium/content/browser/web_contents/aura/overscroll_window_delegate_unittest.cc
@@ -81,9 +81,6 @@ class OverscrollWindowDelegateTest : public aura::test::AuraTestBase,
return gfx::Size(kTestDisplayWidth, kTestDisplayWidth);
}
- void OnOverscrollBehaviorUpdate(
- cc::OverscrollBehavior overscroll_behavior) override {}
-
bool OnOverscrollUpdate(float delta_x, float delta_y) override {
return true;
}
@@ -94,7 +91,8 @@ class OverscrollWindowDelegateTest : public aura::test::AuraTestBase,
void OnOverscrollModeChange(OverscrollMode old_mode,
OverscrollMode new_mode,
- OverscrollSource source) override {
+ OverscrollSource source,
+ cc::OverscrollBehavior behavior) override {
mode_changed_ = true;
current_mode_ = new_mode;
if (current_mode_ != OVERSCROLL_NONE)
diff --git a/chromium/content/browser/web_contents/web_contents_android.cc b/chromium/content/browser/web_contents/web_contents_android.cc
index f51fe3061b4..775b21206ed 100644
--- a/chromium/content/browser/web_contents/web_contents_android.cc
+++ b/chromium/content/browser/web_contents/web_contents_android.cc
@@ -8,6 +8,7 @@
#include <string>
#include <vector>
+#include "base/android/callback_android.h"
#include "base/android/jni_android.h"
#include "base/android/jni_array.h"
#include "base/android/jni_string.h"
@@ -16,7 +17,7 @@
#include "base/json/json_writer.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
+#include "base/task_scheduler/post_task.h"
#include "content/browser/accessibility/browser_accessibility_android.h"
#include "content/browser/accessibility/browser_accessibility_manager_android.h"
#include "content/browser/android/content_view_core.h"
@@ -45,6 +46,7 @@
#include "ui/android/overscroll_refresh_handler.h"
#include "ui/android/window_android.h"
#include "ui/gfx/android/java_bitmap.h"
+#include "ui/gfx/codec/jpeg_codec.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
@@ -132,6 +134,34 @@ void AXTreeSnapshotCallback(const ScopedJavaGlobalRef<jobject>& callback,
Java_WebContentsImpl_onAccessibilitySnapshot(env, j_root, callback);
}
+std::string CompressAndSaveBitmap(const std::string& dir,
+ const SkBitmap& bitmap) {
+ base::AssertBlockingAllowed();
+
+ std::vector<unsigned char> data;
+ if (!gfx::JPEGCodec::Encode(bitmap, 85, &data))
+ return std::string();
+
+ base::FilePath screenshot_dir(dir);
+ if (!base::DirectoryExists(screenshot_dir)) {
+ base::CreateDirectory(screenshot_dir);
+ }
+
+ base::FilePath screenshot_path;
+ base::ScopedFILE out_file(
+ base::CreateAndOpenTemporaryFileInDir(screenshot_dir, &screenshot_path));
+ unsigned int bytes_written =
+ fwrite(reinterpret_cast<const char*>(data.data()), 1, data.size(),
+ out_file.get());
+
+ // If there were errors, don't leave a partial file around.
+ if (bytes_written != data.size()) {
+ base::DeleteFile(screenshot_path, false);
+ return std::string();
+ }
+ return screenshot_path.value();
+}
+
} // namespace
// static
@@ -561,10 +591,10 @@ void WebContentsAndroid::RequestAccessibilitySnapshot(
ScopedJavaGlobalRef<jobject> j_callback;
j_callback.Reset(env, callback);
- WebContentsImpl::AXTreeSnapshotCallback snapshot_callback =
- base::Bind(&AXTreeSnapshotCallback, j_callback);
- static_cast<WebContentsImpl*>(web_contents_)->RequestAXTreeSnapshot(
- snapshot_callback);
+ static_cast<WebContentsImpl*>(web_contents_)
+ ->RequestAXTreeSnapshot(
+ base::BindOnce(&AXTreeSnapshotCallback, j_callback),
+ ui::kAXModeComplete);
}
ScopedJavaLocalRef<jstring> WebContentsAndroid::GetEncoding(
@@ -590,12 +620,14 @@ void WebContentsAndroid::GetContentBitmap(
const JavaParamRef<jobject>& obj,
jint width,
jint height,
+ const JavaParamRef<jstring>& jpath,
const JavaParamRef<jobject>& jcallback) {
- RenderWidgetHostViewAndroid* view = GetRenderWidgetHostViewAndroid();
base::OnceCallback<void(const SkBitmap&)> result_callback = base::BindOnce(
&WebContentsAndroid::OnFinishGetContentBitmap, weak_factory_.GetWeakPtr(),
ScopedJavaGlobalRef<jobject>(env, obj),
- ScopedJavaGlobalRef<jobject>(env, jcallback));
+ ScopedJavaGlobalRef<jobject>(env, jcallback),
+ ConvertJavaStringToUTF8(env, jpath));
+ RenderWidgetHostViewAndroid* view = GetRenderWidgetHostViewAndroid();
if (!view) {
std::move(result_callback).Run(SkBitmap());
return;
@@ -705,13 +737,22 @@ ScopedJavaLocalRef<jobject> WebContentsAndroid::GetOrCreateEventForwarder(
void WebContentsAndroid::OnFinishGetContentBitmap(
const JavaRef<jobject>& obj,
const JavaRef<jobject>& callback,
+ const std::string& path,
const SkBitmap& bitmap) {
JNIEnv* env = base::android::AttachCurrentThread();
ScopedJavaLocalRef<jobject> java_bitmap;
- if (!bitmap.drawsNothing())
- java_bitmap = gfx::ConvertToJavaBitmap(&bitmap);
- Java_WebContentsImpl_onGetContentBitmapFinished(env, obj, callback,
- java_bitmap);
+ if (!bitmap.drawsNothing()) {
+ auto task_runner = base::CreateSequencedTaskRunnerWithTraits(
+ {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN});
+ base::PostTaskAndReplyWithResult(
+ task_runner.get(), FROM_HERE,
+ base::BindOnce(&CompressAndSaveBitmap, path, bitmap),
+ base::BindOnce(&base::android::RunStringCallbackAndroid,
+ ScopedJavaGlobalRef<jobject>(env, callback.obj())));
+ return;
+ }
+ // If readback failed, call empty callback
+ base::android::RunStringCallbackAndroid(callback, std::string());
}
void WebContentsAndroid::OnFinishDownloadImage(
diff --git a/chromium/content/browser/web_contents/web_contents_android.h b/chromium/content/browser/web_contents/web_contents_android.h
index 47e379e5516..2896fa2a5ec 100644
--- a/chromium/content/browser/web_contents/web_contents_android.h
+++ b/chromium/content/browser/web_contents/web_contents_android.h
@@ -178,6 +178,7 @@ class CONTENT_EXPORT WebContentsAndroid
const base::android::JavaParamRef<jobject>& obj,
jint width,
jint height,
+ const base::android::JavaParamRef<jstring>& jpath,
const base::android::JavaParamRef<jobject>& jcallback);
void ReloadLoFiImages(JNIEnv* env,
@@ -206,6 +207,7 @@ class CONTENT_EXPORT WebContentsAndroid
bool IsPictureInPictureAllowedForFullscreenVideo(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj);
+
base::android::ScopedJavaLocalRef<jobject> GetFullscreenVideoSize(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj);
@@ -228,6 +230,7 @@ class CONTENT_EXPORT WebContentsAndroid
void OnFinishGetContentBitmap(const base::android::JavaRef<jobject>& obj,
const base::android::JavaRef<jobject>& callback,
+ const std::string& path,
const SkBitmap& bitmap);
void OnFinishDownloadImage(const base::android::JavaRef<jobject>& obj,
diff --git a/chromium/content/browser/web_contents/web_contents_impl.cc b/chromium/content/browser/web_contents/web_contents_impl.cc
index c5f0ba58549..942a35d355a 100644
--- a/chromium/content/browser/web_contents/web_contents_impl.cc
+++ b/chromium/content/browser/web_contents/web_contents_impl.cc
@@ -56,6 +56,7 @@
#include "content/browser/frame_host/navigator_impl.h"
#include "content/browser/frame_host/render_frame_host_impl.h"
#include "content/browser/frame_host/render_frame_proxy_host.h"
+#include "content/browser/gpu/gpu_data_manager_impl.h"
#include "content/browser/loader/loader_io_thread_notifier.h"
#include "content/browser/loader/resource_dispatcher_host_impl.h"
#include "content/browser/manifest/manifest_manager_host.h"
@@ -91,6 +92,7 @@
#include "content/public/browser/ax_event_notification_details.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_plugin_guest_manager.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/focused_node_details.h"
@@ -114,6 +116,7 @@
#include "content/public/common/browser_side_navigation_policy.h"
#include "content/public/common/child_process_host.h"
#include "content/public/common/content_constants.h"
+#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/page_state.h"
#include "content/public/common/page_zoom.h"
@@ -127,17 +130,18 @@
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#include "services/device/public/mojom/constants.mojom.h"
#include "services/metrics/public/cpp/ukm_recorder.h"
#include "services/service_manager/public/cpp/connector.h"
#include "services/service_manager/public/cpp/interface_provider.h"
-#include "third_party/WebKit/public/common/frame/sandbox_flags.h"
-#include "third_party/WebKit/public/common/mime_util/mime_util.h"
-#include "third_party/WebKit/public/platform/WebSecurityStyle.h"
+#include "third_party/blink/public/common/frame/sandbox_flags.h"
+#include "third_party/blink/public/common/mime_util/mime_util.h"
+#include "third_party/blink/public/platform/web_security_style.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/accessibility/ax_tree_combiner.h"
#include "ui/base/layout.h"
+#include "ui/events/base_event_utils.h"
#include "ui/events/blink/web_input_event_traits.h"
#include "ui/gl/gl_switches.h"
@@ -158,10 +162,6 @@
#include "content/browser/host_zoom_map_observer.h"
#endif // OS_ANDROID
-#if defined(OS_MACOSX)
-#include "base/mac/foundation_util.h"
-#endif
-
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/browser/media/session/pepper_playback_observer.h"
#endif
@@ -176,8 +176,9 @@ const char kDotGoogleDotCom[] = ".google.com";
const void* const kWebContentsAndroidKey = &kWebContentsAndroidKey;
#endif
-base::LazyInstance<std::vector<WebContentsImpl::CreatedCallback>>::
- DestructorAtExit g_created_callbacks = LAZY_INSTANCE_INITIALIZER;
+base::LazyInstance<std::vector<
+ WebContentsImpl::FriendWrapper::CreatedCallback>>::DestructorAtExit
+ g_created_callbacks = LAZY_INSTANCE_INITIALIZER;
void NotifyCacheOnIO(
scoped_refptr<net::URLRequestContextGetter> request_context,
@@ -219,44 +220,6 @@ void ResetAccessibility(RenderFrameHost* rfh) {
static_cast<RenderFrameHostImpl*>(rfh)->AccessibilityReset();
}
-using AXTreeSnapshotCallback =
- base::Callback<void(const ui::AXTreeUpdate&)>;
-
-// Helper class used by WebContentsImpl::RequestAXTreeSnapshot.
-// Handles the callbacks from parallel snapshot requests to each frame,
-// and feeds the results to an AXTreeCombiner, which converts them into a
-// single combined accessibility tree.
-class AXTreeSnapshotCombiner : public base::RefCounted<AXTreeSnapshotCombiner> {
- public:
- explicit AXTreeSnapshotCombiner(AXTreeSnapshotCallback callback)
- : callback_(callback) {
- }
-
- AXTreeSnapshotCallback AddFrame(bool is_root) {
- // Adds a reference to |this|.
- return base::Bind(&AXTreeSnapshotCombiner::ReceiveSnapshot,
- this,
- is_root);
- }
-
- void ReceiveSnapshot(bool is_root, const ui::AXTreeUpdate& snapshot) {
- combiner_.AddTree(snapshot, is_root);
- }
-
- private:
- friend class base::RefCounted<AXTreeSnapshotCombiner>;
-
- // This is called automatically after the last call to ReceiveSnapshot
- // when there are no more references to this object.
- ~AXTreeSnapshotCombiner() {
- combiner_.Combine();
- callback_.Run(combiner_.combined());
- }
-
- ui::AXTreeCombiner combiner_;
- AXTreeSnapshotCallback callback_;
-};
-
// Helper for GetInnerWebContents().
bool GetInnerWebContentsHelper(
std::vector<WebContentsImpl*>* all_guest_contents,
@@ -531,9 +494,6 @@ WebContentsImpl::WebContentsImpl(BrowserContext* browser_context)
last_sent_theme_color_(SK_ColorTRANSPARENT),
did_first_visually_non_empty_paint_(false),
capturer_count_(0),
- should_normally_be_visible_(true),
- should_normally_be_occluded_(false),
- did_first_set_visible_(false),
is_being_destroyed_(false),
is_notifying_observers_(false),
notify_disconnection_(false),
@@ -557,7 +517,6 @@ WebContentsImpl::WebContentsImpl(BrowserContext* browser_context)
#if !defined(OS_ANDROID)
page_scale_factor_is_one_(true),
#endif // !defined(OS_ANDROID)
- mouse_lock_widget_(nullptr),
is_overlay_content_(false),
showing_context_menu_(false),
loading_weak_factory_(this),
@@ -1075,17 +1034,68 @@ void WebContentsImpl::AddAccessibilityMode(ui::AXMode mode) {
SetAccessibilityMode(new_mode);
}
-void WebContentsImpl::RequestAXTreeSnapshot(
- const AXTreeSnapshotCallback& callback) {
+// Helper class used by WebContentsImpl::RequestAXTreeSnapshot.
+// Handles the callbacks from parallel snapshot requests to each frame,
+// and feeds the results to an AXTreeCombiner, which converts them into a
+// single combined accessibility tree.
+class WebContentsImpl::AXTreeSnapshotCombiner
+ : public base::RefCounted<AXTreeSnapshotCombiner> {
+ public:
+ explicit AXTreeSnapshotCombiner(AXTreeSnapshotCallback callback)
+ : callback_(std::move(callback)) {}
+
+ AXTreeSnapshotCallback AddFrame(bool is_root) {
+ // Adds a reference to |this|.
+ return base::BindOnce(&AXTreeSnapshotCombiner::ReceiveSnapshot, this,
+ is_root);
+ }
+
+ void ReceiveSnapshot(bool is_root, const ui::AXTreeUpdate& snapshot) {
+ combiner_.AddTree(snapshot, is_root);
+ }
+
+ private:
+ friend class base::RefCounted<AXTreeSnapshotCombiner>;
+
+ // This is called automatically after the last call to ReceiveSnapshot
+ // when there are no more references to this object.
+ ~AXTreeSnapshotCombiner() {
+ combiner_.Combine();
+ std::move(callback_).Run(combiner_.combined());
+ }
+
+ ui::AXTreeCombiner combiner_;
+ AXTreeSnapshotCallback callback_;
+};
+
+void WebContentsImpl::RequestAXTreeSnapshot(AXTreeSnapshotCallback callback,
+ ui::AXMode ax_mode) {
// Send a request to each of the frames in parallel. Each one will return
// an accessibility tree snapshot, and AXTreeSnapshotCombiner will combine
// them into a single tree and call |callback| with that result, then
// delete |combiner|.
- AXTreeSnapshotCombiner* combiner = new AXTreeSnapshotCombiner(callback);
+ FrameTreeNode* root_node = frame_tree_.root();
+ AXTreeSnapshotCombiner* combiner =
+ new AXTreeSnapshotCombiner(std::move(callback));
+
+ RecursiveRequestAXTreeSnapshotOnFrame(root_node, combiner, ax_mode);
+}
+
+void WebContentsImpl::RecursiveRequestAXTreeSnapshotOnFrame(
+ FrameTreeNode* root_node,
+ AXTreeSnapshotCombiner* combiner,
+ ui::AXMode ax_mode) {
for (FrameTreeNode* frame_tree_node : frame_tree_.Nodes()) {
- bool is_root = frame_tree_node->parent() == nullptr;
- frame_tree_node->current_frame_host()->RequestAXTreeSnapshot(
- combiner->AddFrame(is_root));
+ WebContentsImpl* inner_contents =
+ node_.GetInnerWebContentsInFrame(frame_tree_node);
+ if (inner_contents) {
+ inner_contents->RecursiveRequestAXTreeSnapshotOnFrame(root_node, combiner,
+ ax_mode);
+ } else {
+ bool is_root = frame_tree_node == root_node;
+ frame_tree_node->current_frame_host()->RequestAXTreeSnapshot(
+ combiner->AddFrame(is_root), ax_mode);
+ }
}
}
@@ -1146,7 +1156,7 @@ std::vector<WebContentsImpl*> WebContentsImpl::GetInnerWebContents() {
if (browser_plugin_embedder_) {
std::vector<WebContentsImpl*> inner_contents;
GetBrowserContext()->GetGuestManager()->ForEachGuest(
- this, base::Bind(&GetInnerWebContentsHelper, &inner_contents));
+ this, base::BindRepeating(&GetInnerWebContentsHelper, &inner_contents));
return inner_contents;
}
@@ -1181,10 +1191,13 @@ WebUI* WebContentsImpl::GetCommittedWebUI() const {
return frame_tree_.root()->current_frame_host()->web_ui();
}
-void WebContentsImpl::SetUserAgentOverride(const std::string& override) {
+void WebContentsImpl::SetUserAgentOverride(const std::string& override,
+ bool override_in_new_tabs) {
if (GetUserAgentOverride() == override)
return;
+ should_override_user_agent_in_new_tabs_ = override_in_new_tabs;
+
renderer_preferences_.user_agent_override = override;
// Send the new override string to the renderer.
@@ -1206,6 +1219,10 @@ const std::string& WebContentsImpl::GetUserAgentOverride() const {
return renderer_preferences_.user_agent_override;
}
+bool WebContentsImpl::ShouldOverrideUserAgentInNewTabs() {
+ return should_override_user_agent_in_new_tabs_;
+}
+
void WebContentsImpl::EnableWebContentsOnlyAccessibilityMode() {
if (!GetAccessibilityMode().is_mode_off()) {
for (RenderFrameHost* rfh : GetAllFrames())
@@ -1318,8 +1335,13 @@ const std::string& WebContentsImpl::GetEncoding() const {
return canonical_encoding_;
}
+void WebContentsImpl::SetWasDiscarded(bool was_discarded) {
+ GetFrameTree()->root()->set_was_discarded();
+}
+
void WebContentsImpl::IncrementCapturerCount(const gfx::Size& capture_size) {
DCHECK(!is_being_destroyed_);
+ const bool was_captured = IsBeingCaptured();
++capturer_count_;
DVLOG(1) << "There are now " << capturer_count_
<< " capturing(s) of WebContentsImpl@" << this;
@@ -1331,8 +1353,14 @@ void WebContentsImpl::IncrementCapturerCount(const gfx::Size& capture_size) {
OnPreferredSizeChanged(preferred_size_);
}
- // Ensure that all views are un-occluded before capture begins.
- DoWasUnOccluded();
+ if (GetVisibility() != Visibility::VISIBLE && !was_captured) {
+ // Ensure that all views act as if they were visible before capture begins.
+ // TODO(fdoray): Replace RenderWidgetHostView::WasUnOccluded() with a method
+ // to explicitly notify the RenderWidgetHostView that capture began.
+ // https://crbug.com/668690
+ for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree())
+ view->WasUnOccluded();
+ }
}
void WebContentsImpl::DecrementCapturerCount() {
@@ -1349,13 +1377,12 @@ void WebContentsImpl::DecrementCapturerCount() {
preferred_size_for_capture_ = gfx::Size();
OnPreferredSizeChanged(old_size);
- if (IsHidden()) {
+ if (visibility_ == Visibility::HIDDEN) {
DVLOG(1) << "Executing delayed WasHidden().";
WasHidden();
- }
-
- if (should_normally_be_occluded_)
+ } else if (visibility_ == Visibility::OCCLUDED) {
WasOccluded();
+ }
}
}
@@ -1466,8 +1493,6 @@ void WebContentsImpl::SetLastActiveTime(base::TimeTicks last_active_time) {
}
void WebContentsImpl::WasShown() {
- const Visibility previous_visibility = GetVisibility();
-
controller_.SetActive(true);
if (auto* view = GetRenderWidgetHostView()) {
@@ -1483,13 +1508,10 @@ void WebContentsImpl::WasShown() {
SendPageMessage(new PageMsg_WasShown(MSG_ROUTING_NONE));
last_active_time_ = base::TimeTicks::Now();
- should_normally_be_visible_ = true;
- NotifyVisibilityChanged(previous_visibility);
+ SetVisibility(Visibility::VISIBLE);
}
void WebContentsImpl::WasHidden() {
- const Visibility previous_visibility = GetVisibility();
-
// If there are entities capturing screenshots or video (e.g., mirroring),
// don't activate the "disable rendering" optimization.
if (!IsBeingCaptured()) {
@@ -1508,8 +1530,21 @@ void WebContentsImpl::WasHidden() {
SendPageMessage(new PageMsg_WasHidden(MSG_ROUTING_NONE));
}
- should_normally_be_visible_ = false;
- NotifyVisibilityChanged(previous_visibility);
+ SetVisibility(Visibility::HIDDEN);
+}
+
+bool WebContentsImpl::HasRecentInteractiveInputEvent() const {
+ static constexpr base::TimeDelta kMaxInterval =
+ base::TimeDelta::FromSeconds(5);
+ base::TimeDelta delta =
+ ui::EventTimeForNow() - last_interactive_input_event_time_;
+ // Note: the expectation is that the caller is typically expecting an input
+ // event, e.g. validating that a WebUI message that requires a gesture is
+ // actually attached to a gesture. Logging to UMA here should hopefully give
+ // sufficient data if 5 seconds is actually sufficient (or even too high a
+ // threshhold).
+ UMA_HISTOGRAM_TIMES("Tabs.TimeSinceLastInteraction", delta);
+ return delta <= kMaxInterval;
}
#if defined(OS_ANDROID)
@@ -1542,39 +1577,15 @@ void WebContentsImpl::SetImportance(ChildProcessImportance importance) {
#endif
void WebContentsImpl::WasOccluded() {
- const Visibility previous_visibility = GetVisibility();
-
if (!IsBeingCaptured()) {
for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree())
view->WasOccluded();
}
-
- should_normally_be_occluded_ = true;
- NotifyVisibilityChanged(previous_visibility);
-}
-
-void WebContentsImpl::WasUnOccluded() {
- const Visibility previous_visibility = GetVisibility();
-
- if (!IsBeingCaptured())
- DoWasUnOccluded();
-
- should_normally_be_occluded_ = false;
- NotifyVisibilityChanged(previous_visibility);
-}
-
-void WebContentsImpl::DoWasUnOccluded() {
- // TODO(fdoray): Only call WasUnOccluded on frames in the active viewport.
- for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree())
- view->WasUnOccluded();
+ SetVisibility(Visibility::OCCLUDED);
}
Visibility WebContentsImpl::GetVisibility() const {
- if (!should_normally_be_visible_)
- return Visibility::HIDDEN;
- if (should_normally_be_occluded_)
- return Visibility::OCCLUDED;
- return Visibility::VISIBLE;
+ return visibility_;
}
bool WebContentsImpl::NeedToFireBeforeUnload() {
@@ -1665,6 +1676,22 @@ void WebContentsImpl::DidChangeVisibleSecurityState() {
}
}
+void WebContentsImpl::NotifyPreferencesChanged() {
+ std::set<RenderViewHost*> render_view_host_set;
+ for (FrameTreeNode* node : frame_tree_.Nodes()) {
+ RenderWidgetHost* render_widget_host =
+ node->current_frame_host()->GetRenderWidgetHost();
+ if (!render_widget_host)
+ continue;
+ RenderViewHost* render_view_host = RenderViewHost::From(render_widget_host);
+ if (!render_view_host)
+ continue;
+ render_view_host_set.insert(render_view_host);
+ }
+ for (RenderViewHost* render_view_host : render_view_host_set)
+ render_view_host->OnWebkitPreferencesChanged();
+}
+
void WebContentsImpl::Stop() {
for (FrameTreeNode* node : frame_tree_.Nodes())
node->StopLoading();
@@ -1672,6 +1699,10 @@ void WebContentsImpl::Stop() {
observer.NavigationStopped();
}
+void WebContentsImpl::FreezePage() {
+ SendPageMessage(new PageMsg_FreezePage(MSG_ROUTING_NONE));
+}
+
WebContents* WebContentsImpl::Clone() {
// We use our current SiteInstance since the cloned entry will use it anyway.
// We pass our own opener so that the cloned page can access it if it was set
@@ -1727,7 +1758,8 @@ void WebContentsImpl::Init(const WebContents::CreateParams& params) {
// This is set before initializing the render manager since
// RenderFrameHostManager::Init calls back into us via its delegate to ask if
// it should be hidden.
- should_normally_be_visible_ = !params.initially_hidden;
+ visibility_ =
+ params.initially_hidden ? Visibility::HIDDEN : Visibility::VISIBLE;
// The routing ids must either all be set or all be unset.
DCHECK((params.routing_id == MSG_ROUTING_NONE &&
@@ -1928,6 +1960,8 @@ void WebContentsImpl::RenderWidgetDeleted(
if (render_widget_host == mouse_lock_widget_)
LostMouseLock(mouse_lock_widget_);
+
+ CancelKeyboardLock(keyboard_lock_widget_);
}
void WebContentsImpl::RenderWidgetGotFocus(
@@ -2095,9 +2129,13 @@ void WebContentsImpl::EnterFullscreenMode(const GURL& origin) {
->ShutdownAndDestroyWidget(true);
}
- if (delegate_)
+ if (delegate_) {
delegate_->EnterFullscreenModeForTab(this, origin);
+ if (keyboard_lock_widget_)
+ delegate_->RequestKeyboardLock(this, esc_key_locked_);
+ }
+
for (auto& observer : observers_)
observer.DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab(), false);
}
@@ -2117,9 +2155,13 @@ void WebContentsImpl::ExitFullscreenMode(bool will_cause_resize) {
video_view->ExitFullscreen();
#endif
- if (delegate_)
+ if (delegate_) {
delegate_->ExitFullscreenModeForTab(this);
+ if (keyboard_lock_widget_)
+ delegate_->CancelKeyboardLockRequest(this);
+ }
+
// The fullscreen state is communicated to the renderer through a resize
// message. If the change in fullscreen state doesn't cause a view resize
// then we must ensure web contents exit the fullscreen state by explicitly
@@ -2232,6 +2274,46 @@ RenderWidgetHostImpl* WebContentsImpl::GetMouseLockWidget() {
return nullptr;
}
+bool WebContentsImpl::RequestKeyboardLock(
+ RenderWidgetHostImpl* render_widget_host,
+ bool esc_key_locked) {
+ DCHECK(render_widget_host);
+ if (render_widget_host->delegate()->GetAsWebContents() != this) {
+ NOTREACHED();
+ return false;
+ }
+
+ // KeyboardLock is only supported when called by the top-level browsing
+ // context and is not supported in embedded content scenarios.
+ if (GetOuterWebContents())
+ return false;
+
+ esc_key_locked_ = esc_key_locked;
+ keyboard_lock_widget_ = render_widget_host;
+
+ if (delegate_)
+ delegate_->RequestKeyboardLock(this, esc_key_locked_);
+ return true;
+}
+
+void WebContentsImpl::CancelKeyboardLock(
+ RenderWidgetHostImpl* render_widget_host) {
+ if (!keyboard_lock_widget_ || render_widget_host != keyboard_lock_widget_)
+ return;
+
+ RenderWidgetHostImpl* old_keyboard_lock_widget = keyboard_lock_widget_;
+ keyboard_lock_widget_ = nullptr;
+
+ if (delegate_)
+ delegate_->CancelKeyboardLockRequest(this);
+
+ old_keyboard_lock_widget->CancelKeyboardLock();
+}
+
+RenderWidgetHostImpl* WebContentsImpl::GetKeyboardLockWidget() {
+ return keyboard_lock_widget_;
+}
+
void WebContentsImpl::OnRenderFrameProxyVisibilityChanged(bool visible) {
if (visible && !GetOuterWebContents()->IsHidden())
WasShown();
@@ -2466,12 +2548,6 @@ void WebContentsImpl::CreateNewWidget(int32_t render_process_id,
// Save the created widget associated with the route so we can show it later.
pending_widget_views_[std::make_pair(render_process_id, route_id)] =
widget_view;
-
-#if defined(OS_MACOSX)
- // A RenderWidgetHostViewMac has lifetime scoped to the view. We'll retain it
- // to allow it to survive the trip without being hosted.
- base::mac::NSObjectRetain(widget_view->GetNativeView());
-#endif
}
void WebContentsImpl::ShowCreatedWindow(int process_id,
@@ -2550,19 +2626,11 @@ void WebContentsImpl::ShowCreatedWidget(int process_id,
widget_host_view->InitAsPopup(view, initial_rect);
}
- RenderWidgetHostImpl* render_widget_host_impl =
- widget_host_view->GetRenderWidgetHostImpl();
+ RenderWidgetHostImpl* render_widget_host_impl = widget_host_view->host();
render_widget_host_impl->Init();
// Only allow privileged mouse lock for fullscreen render widget, which is
// used to implement Pepper Flash fullscreen.
render_widget_host_impl->set_allow_privileged_mouse_lock(is_fullscreen);
-
-#if defined(OS_MACOSX)
- // A RenderWidgetHostViewMac has lifetime scoped to the view. Now that it's
- // properly embedded (or purposefully ignored) we can release the retain we
- // took in CreateNewWidget().
- base::mac::NSObjectRelease(widget_host_view->GetNativeView());
-#endif
}
WebContentsImpl* WebContentsImpl::GetCreatedWindow(
@@ -2625,12 +2693,13 @@ void WebContentsImpl::RequestMediaAccessPermission(
}
bool WebContentsImpl::CheckMediaAccessPermission(
+ RenderFrameHost* render_frame_host,
const url::Origin& security_origin,
MediaStreamType type) {
DCHECK(type == MEDIA_DEVICE_AUDIO_CAPTURE ||
type == MEDIA_DEVICE_VIDEO_CAPTURE);
return delegate_ && delegate_->CheckMediaAccessPermission(
- this, security_origin.GetURL(), type);
+ render_frame_host, security_origin.GetURL(), type);
}
std::string WebContentsImpl::GetDefaultMediaDeviceID(MediaStreamType type) {
@@ -2891,11 +2960,6 @@ void WebContentsImpl::ResizeDueToAutoResize(
if (delegate_)
delegate_->ResizeDueToAutoResize(this, new_size);
-
- RenderWidgetHostViewBase* view =
- static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
- if (view)
- view->ResizeDueToAutoResize(new_size, sequence_number);
}
gfx::Size WebContentsImpl::GetAutoResizeSize() {
@@ -3259,13 +3323,18 @@ bool WebContentsImpl::ShowingInterstitialPage() const {
void WebContentsImpl::AdjustPreviewsStateForNavigation(
PreviewsState* previews_state) {
if (delegate_)
- delegate_->AdjustPreviewsStateForNavigation(previews_state);
+ delegate_->AdjustPreviewsStateForNavigation(this, previews_state);
}
InterstitialPageImpl* WebContentsImpl::GetInterstitialPage() const {
return interstitial_page_;
}
+void WebContentsImpl::PausePageScheduledTasks(bool paused) {
+ SendPageMessage(
+ new PageMsg_PausePageScheduledTasks(MSG_ROUTING_NONE, paused));
+}
+
bool WebContentsImpl::IsSavable() {
// WebKit creates Document object when MIME type is application/xhtml+xml,
// so we also support this MIME type.
@@ -3310,12 +3379,14 @@ bool WebContentsImpl::SavePage(const base::FilePath& main_file,
void WebContentsImpl::SaveFrame(const GURL& url,
const Referrer& referrer) {
- SaveFrameWithHeaders(url, referrer, std::string());
+ SaveFrameWithHeaders(url, referrer, std::string(), base::string16());
}
-void WebContentsImpl::SaveFrameWithHeaders(const GURL& url,
- const Referrer& referrer,
- const std::string& headers) {
+void WebContentsImpl::SaveFrameWithHeaders(
+ const GURL& url,
+ const Referrer& referrer,
+ const std::string& headers,
+ const base::string16& suggested_filename) {
if (!GetLastCommittedURL().is_valid())
return;
if (delegate_ && delegate_->SaveFrame(url, referrer))
@@ -3377,6 +3448,7 @@ void WebContentsImpl::SaveFrameWithHeaders(const GURL& url,
params->add_request_header(key_value.first, key_value.second);
}
}
+ params->set_suggested_name(suggested_filename);
params->set_download_source(download::DownloadSource::WEB_CONTENTS_API);
BrowserContext::GetDownloadManager(GetBrowserContext())
->DownloadUrl(std::move(params));
@@ -3384,8 +3456,9 @@ void WebContentsImpl::SaveFrameWithHeaders(const GURL& url,
void WebContentsImpl::GenerateMHTML(
const MHTMLGenerationParams& params,
- const base::Callback<void(int64_t)>& callback) {
- MHTMLGenerationManager::GetInstance()->SaveMHTML(this, params, callback);
+ base::OnceCallback<void(int64_t)> callback) {
+ MHTMLGenerationManager::GetInstance()->SaveMHTML(this, params,
+ std::move(callback));
}
const std::string& WebContentsImpl::GetContentsMimeType() const {
@@ -3420,22 +3493,22 @@ void WebContentsImpl::DragSourceEndedAt(float client_x,
}
void WebContentsImpl::LoadStateChanged(
- const GURL& url,
+ const std::string& host,
const net::LoadStateWithParam& load_state,
uint64_t upload_position,
uint64_t upload_size) {
- base::string16 host = url_formatter::IDNToUnicode(url.host());
+ base::string16 host16 = url_formatter::IDNToUnicode(host);
// Drop no-op updates.
if (load_state_.state == load_state.state &&
load_state_.param == load_state.param &&
upload_position_ == upload_position && upload_size_ == upload_size &&
- load_state_host_ == host) {
+ load_state_host_ == host16) {
return;
}
load_state_ = load_state;
upload_position_ = upload_position;
upload_size_ = upload_size;
- load_state_host_ = host;
+ load_state_host_ = host16;
if (load_state_.state == net::LOAD_STATE_READING_RESPONSE)
SetNotWaitingForResponse();
if (IsLoading()) {
@@ -3444,10 +3517,12 @@ void WebContentsImpl::LoadStateChanged(
}
}
-void WebContentsImpl::NotifyVisibilityChanged(Visibility previous_visibility) {
+void WebContentsImpl::SetVisibility(Visibility visibility) {
+ const Visibility previous_visibility = visibility_;
+ visibility_ = visibility;
+
// Notify observers if the visibility changed or if WasShown() is being called
// for the first time.
- const Visibility visibility = GetVisibility();
if (visibility != previous_visibility ||
(visibility == Visibility::VISIBLE && !did_first_set_visible_)) {
for (auto& observer : observers_)
@@ -3474,9 +3549,8 @@ void WebContentsImpl::SystemDragEnded(RenderWidgetHost* source_rwh) {
browser_plugin_embedder_->SystemDragEnded();
}
-void WebContentsImpl::UserGestureDone() {
- OnUserInteraction(GetRenderViewHost()->GetWidget(),
- blink::WebInputEvent::kUndefined);
+void WebContentsImpl::NavigatedByUser() {
+ OnUserInteraction(blink::WebInputEvent::kUndefined);
}
void WebContentsImpl::SetClosedByUserGesture(bool value) {
@@ -3528,6 +3602,24 @@ bool WebContentsImpl::GotResponseToLockMouseRequest(bool allowed) {
return false;
}
+bool WebContentsImpl::GotResponseToKeyboardLockRequest(bool allowed) {
+ if (!keyboard_lock_widget_)
+ return false;
+
+ if (keyboard_lock_widget_->delegate()->GetAsWebContents() != this) {
+ NOTREACHED();
+ return false;
+ }
+
+ // KeyboardLock is only supported when called by the top-level browsing
+ // context and is not supported in embedded content scenarios.
+ if (GetOuterWebContents())
+ return false;
+
+ keyboard_lock_widget_->GotResponseToKeyboardLockRequest(allowed);
+ return true;
+}
+
bool WebContentsImpl::HasOpener() const {
return GetOpener() != nullptr;
}
@@ -3559,7 +3651,7 @@ int WebContentsImpl::DownloadImage(
bool is_favicon,
uint32_t max_bitmap_size,
bool bypass_cache,
- const WebContents::ImageDownloadCallback& callback) {
+ WebContents::ImageDownloadCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
static int next_image_download_id = 0;
const content::mojom::ImageDownloaderPtr& mojo_image_downloader =
@@ -3568,20 +3660,22 @@ int WebContentsImpl::DownloadImage(
if (!mojo_image_downloader) {
// If the renderer process is dead (i.e. crash, or memory pressure on
// Android), the downloader service will be invalid. Pre-Mojo, this would
- // hang the callback indefinetly since the IPC would be dropped. Now,
+ // hang the callback indefinitely since the IPC would be dropped. Now,
// respond with a 400 HTTP error code to indicate that something went wrong.
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::BindOnce(&WebContentsImpl::OnDidDownloadImage,
- weak_factory_.GetWeakPtr(), callback, download_id, url,
- 400, std::vector<SkBitmap>(), std::vector<gfx::Size>()));
+ weak_factory_.GetWeakPtr(), std::move(callback),
+ download_id, url, 400, std::vector<SkBitmap>(),
+ std::vector<gfx::Size>()));
return download_id;
}
mojo_image_downloader->DownloadImage(
url, is_favicon, max_bitmap_size, bypass_cache,
base::BindOnce(&WebContentsImpl::OnDidDownloadImage,
- weak_factory_.GetWeakPtr(), callback, download_id, url));
+ weak_factory_.GetWeakPtr(), std::move(callback),
+ download_id, url));
return download_id;
}
@@ -3616,8 +3710,8 @@ bool WebContentsImpl::WasEverAudible() {
return was_ever_audible_;
}
-void WebContentsImpl::GetManifest(const GetManifestCallback& callback) {
- manifest_manager_host_->GetManifest(callback);
+void WebContentsImpl::GetManifest(GetManifestCallback callback) {
+ manifest_manager_host_->GetManifest(std::move(callback));
}
void WebContentsImpl::ExitFullscreen(bool will_cause_resize) {
@@ -3708,6 +3802,26 @@ void WebContentsImpl::ReadyToCommitNavigation(
for (auto& observer : observers_)
observer.ReadyToCommitNavigation(navigation_handle);
+ // If any domains are blocked from accessing 3D APIs because they may
+ // have caused the GPU to reset recently, unblock them here if the user
+ // initiated this navigation. This implies that the user was involved in
+ // the decision to navigate, so there's no concern about
+ // denial-of-service issues. Want to do this as early as
+ // possible to avoid race conditions with pages attempting to access
+ // WebGL early on.
+ //
+ // TODO(crbug.com/617904): currently navigations initiated by the browser
+ // (reload button, reload menu option, pressing return in the Omnibox)
+ // return false from HasUserGesture(). If or when that is addressed,
+ // remove the check for IsRendererInitiated() below.
+ //
+ // TODO(crbug.com/832180): HasUserGesture comes from the renderer
+ // process and isn't validated. Until it is, don't trust it.
+ if (!navigation_handle->IsRendererInitiated()) {
+ GpuDataManagerImpl::GetInstance()->UnblockDomainFrom3DAPIs(
+ navigation_handle->GetURL());
+ }
+
if (navigation_handle->IsSameDocument())
return;
@@ -4027,20 +4141,18 @@ void WebContentsImpl::ViewSource(RenderFrameHostImpl* frame) {
}
void WebContentsImpl::SubresourceResponseStarted(const GURL& url,
- const GURL& referrer,
- const std::string& method,
- ResourceType resource_type,
- const std::string& ip,
net::CertStatus cert_status) {
- for (auto& observer : observers_) {
- observer.SubresourceResponseStarted(url, referrer, method, resource_type,
- ip);
- }
-
controller_.ssl_manager()->DidStartResourceResponse(url, cert_status);
SetNotWaitingForResponse();
}
+void WebContentsImpl::ResourceLoadComplete(
+ mojom::ResourceLoadInfoPtr resource_load_info) {
+ for (auto& observer : observers_) {
+ observer.ResourceLoadComplete(*resource_load_info);
+ }
+}
+
void WebContentsImpl::PrintCrossProcessSubframe(
const gfx::Rect& rect,
int document_cookie,
@@ -4064,9 +4176,15 @@ void WebContentsImpl::PrintCrossProcessSubframe(
}
void WebContentsImpl::UpdatePictureInPictureSurfaceId(
- viz::SurfaceId surface_id) {
+ const viz::SurfaceId& surface_id,
+ const gfx::Size& natural_size) {
+ if (delegate_)
+ delegate_->UpdatePictureInPictureSurfaceId(surface_id, natural_size);
+}
+
+void WebContentsImpl::ExitPictureInPicture() {
if (delegate_)
- delegate_->UpdatePictureInPictureSurfaceId(surface_id);
+ delegate_->ExitPictureInPicture();
}
#if defined(OS_ANDROID)
@@ -4340,14 +4458,14 @@ void WebContentsImpl::OnRequestPpapiBrokerPermission(
&WebContentsImpl::SendPpapiBrokerPermissionResult, base::Unretained(this),
source->GetProcess()->GetID(), ppb_broker_route_id);
if (!delegate_) {
- permission_result_callback.Run(false);
+ std::move(permission_result_callback).Run(false);
return;
}
if (!delegate_->RequestPpapiBrokerPermission(this, url, plugin_path,
permission_result_callback)) {
NOTIMPLEMENTED();
- permission_result_callback.Run(false);
+ std::move(permission_result_callback).Run(false);
}
}
@@ -4674,6 +4792,16 @@ void WebContentsImpl::RunJavaScriptDialog(RenderFrameHost* render_frame_host,
const base::string16& default_prompt,
JavaScriptDialogType dialog_type,
IPC::Message* reply_msg) {
+ // Ensure that if showing a dialog is the first thing that a page does, that
+ // the contents of the previous page aren't shown behind it. This is required
+ // because showing a dialog freezes the renderer, so no frames will be coming
+ // from it. https://crbug.com/823353
+ auto* render_widget_host_impl =
+ static_cast<RenderFrameHostImpl*>(render_frame_host)
+ ->GetRenderWidgetHost();
+ if (render_widget_host_impl)
+ render_widget_host_impl->ForceFirstFrameAfterNavigationTimeout();
+
// Running a dialog causes an exit to webpage-initiated fullscreen.
// http://crbug.com/728276
if (IsFullscreenForCurrentTab())
@@ -4695,7 +4823,8 @@ void WebContentsImpl::RunJavaScriptDialog(RenderFrameHost* render_frame_host,
// want the hidden page's dialogs to interfere with the interstitial.
bool should_suppress = ShowingInterstitialPage() ||
(delegate_ && delegate_->ShouldSuppressDialogs(this));
- bool has_handlers = page_handlers.size() || (delegate_ && dialog_manager_);
+ bool has_non_devtools_handlers = delegate_ && dialog_manager_;
+ bool has_handlers = page_handlers.size() || has_non_devtools_handlers;
bool suppress_this_message = should_suppress || !has_handlers;
if (suppress_this_message) {
@@ -4711,7 +4840,7 @@ void WebContentsImpl::RunJavaScriptDialog(RenderFrameHost* render_frame_host,
for (auto* handler : page_handlers) {
handler->DidRunJavaScriptDialog(
render_frame_host->GetLastCommittedURL(), message, default_prompt,
- dialog_type,
+ dialog_type, has_non_devtools_handlers,
base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false));
}
@@ -4733,6 +4862,16 @@ void WebContentsImpl::RunBeforeUnloadConfirm(
RenderFrameHost* render_frame_host,
bool is_reload,
IPC::Message* reply_msg) {
+ // Ensure that if showing a dialog is the first thing that a page does, that
+ // the contents of the previous page aren't shown behind it. This is required
+ // because showing a dialog freezes the renderer, so no frames will be coming
+ // from it. https://crbug.com/823353
+ auto* render_widget_host_impl =
+ static_cast<RenderFrameHostImpl*>(render_frame_host)
+ ->GetRenderWidgetHost();
+ if (render_widget_host_impl)
+ render_widget_host_impl->ForceFirstFrameAfterNavigationTimeout();
+
// Running a dialog causes an exit to webpage-initiated fullscreen.
// http://crbug.com/728276
if (IsFullscreenForCurrentTab())
@@ -4756,7 +4895,8 @@ void WebContentsImpl::RunBeforeUnloadConfirm(
bool should_suppress = ShowingInterstitialPage() || !rfhi->is_active() ||
(delegate_ && delegate_->ShouldSuppressDialogs(this));
- bool has_handlers = page_handlers.size() || (delegate_ && dialog_manager_);
+ bool has_non_devtools_handlers = delegate_ && dialog_manager_;
+ bool has_handlers = page_handlers.size() || has_non_devtools_handlers;
if (should_suppress || !has_handlers) {
std::move(callback).Run(false, true, base::string16());
return;
@@ -4770,7 +4910,7 @@ void WebContentsImpl::RunBeforeUnloadConfirm(
GURL frame_url = rfhi->GetLastCommittedURL();
for (auto* handler : page_handlers) {
handler->DidRunBeforeUnloadConfirm(
- frame_url,
+ frame_url, has_non_devtools_handlers,
base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false));
}
@@ -4951,11 +5091,6 @@ void WebContentsImpl::RenderViewReady(RenderViewHost* rvh) {
rwhv->SetMainFrameAXTreeID(GetMainFrame()->GetAXTreeID());
notify_disconnection_ = true;
- // TODO(avi): Remove. http://crbug.com/170921
- NotificationService::current()->Notify(
- NOTIFICATION_WEB_CONTENTS_CONNECTED,
- Source<WebContents>(this),
- NotificationService::NoDetails());
bool was_crashed = IsCrashed();
SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING, 0);
@@ -5459,21 +5594,25 @@ bool WebContentsImpl::DidAddMessageToConsole(int32_t level,
source_id);
}
-void WebContentsImpl::OnUserInteraction(
+void WebContentsImpl::DidReceiveInputEvent(
RenderWidgetHostImpl* render_widget_host,
const blink::WebInputEvent::Type type) {
+ // Ideally, this list would be based more off of
+ // https://whatwg.org/C/interaction.html#triggered-by-user-activation.
+ if (type != blink::WebInputEvent::kMouseDown &&
+ type != blink::WebInputEvent::kGestureScrollBegin &&
+ type != blink::WebInputEvent::kTouchStart &&
+ type != blink::WebInputEvent::kRawKeyDown)
+ return;
+
// Ignore unless the widget is currently in the frame tree.
if (!HasMatchingWidgetHost(&frame_tree_, render_widget_host))
return;
- for (auto& observer : observers_)
- observer.DidGetUserInteraction(type);
+ if (type != blink::WebInputEvent::kGestureScrollBegin)
+ last_interactive_input_event_time_ = ui::EventTimeForNow();
- ResourceDispatcherHostImpl* rdh = ResourceDispatcherHostImpl::Get();
- // Exclude scroll events as user gestures for resource load dispatches.
- // rdh is NULL in unittests.
- if (rdh && type != blink::WebInputEvent::kMouseWheel)
- rdh->OnUserGesture();
+ OnUserInteraction(type);
}
void WebContentsImpl::FocusOwningWebContents(
@@ -5739,13 +5878,14 @@ bool WebContentsImpl::CompletedFirstVisuallyNonEmptyPaint() const {
#endif
void WebContentsImpl::OnDidDownloadImage(
- const ImageDownloadCallback& callback,
+ ImageDownloadCallback callback,
int id,
const GURL& image_url,
int32_t http_status_code,
const std::vector<SkBitmap>& images,
const std::vector<gfx::Size>& original_image_sizes) {
- callback.Run(id, http_status_code, image_url, images, original_image_sizes);
+ std::move(callback).Run(id, http_status_code, image_url, images,
+ original_image_sizes);
}
void WebContentsImpl::OnDialogClosed(int render_process_id,
@@ -5799,7 +5939,7 @@ void WebContentsImpl::SetEncoding(const std::string& encoding) {
}
bool WebContentsImpl::IsHidden() {
- return !IsBeingCaptured() && !should_normally_be_visible_;
+ return !IsBeingCaptured() && visibility_ != Visibility::VISIBLE;
}
int WebContentsImpl::GetOuterDelegateFrameTreeNodeId() {
@@ -5859,6 +5999,20 @@ void WebContentsImpl::OnPreferredSizeChanged(const gfx::Size& old_size) {
delegate_->UpdatePreferredSize(this, new_size);
}
+void WebContentsImpl::OnUserInteraction(const blink::WebInputEvent::Type type) {
+ for (auto& observer : observers_)
+ observer.DidGetUserInteraction(type);
+
+ // TODO(https://crbug.com/827659): This used to check if type != kMouseWheel.
+ // However, due to the caller already filtering event types, this would never
+ // be called with type == kMouseWheel so checking for that here is pointless.
+ // However, mouse wheel events *also* generate a kGestureScrollBegin event...
+ // which is *not* filtered out. Maybe they should be?
+ ResourceDispatcherHostImpl* rdh = ResourceDispatcherHostImpl::Get();
+ if (rdh) // null in unittests. =(
+ rdh->OnUserGesture();
+}
+
std::unique_ptr<WebUIImpl> WebContentsImpl::CreateWebUI(const GURL& url) {
std::unique_ptr<WebUIImpl> web_ui = std::make_unique<WebUIImpl>(this);
WebUIController* controller =
@@ -5996,9 +6150,10 @@ void WebContentsImpl::ClearDeviceEmulationSize() {
// emulation.
// TODO(jzfeng): Prohibit resizing RWHV through any other means (at least when
// WebContentsView size changes).
- if (!view_size_before_emulation_.IsEmpty() &&
- rwhv->GetViewBounds().size() == device_emulation_size_)
+ if (!view_size_before_emulation_.IsEmpty() && rwhv &&
+ rwhv->GetViewBounds().size() == device_emulation_size_) {
rwhv->SetSize(view_size_before_emulation_);
+ }
device_emulation_size_ = gfx::Size();
view_size_before_emulation_ = gfx::Size();
}
@@ -6050,25 +6205,44 @@ int WebContentsImpl::GetCurrentlyPlayingVideoCount() {
return currently_playing_video_count_;
}
-void WebContentsImpl::UpdateWebContentsVisibility(bool visible) {
+void WebContentsImpl::UpdateWebContentsVisibility(Visibility visibility) {
+ // Occlusion is disabled when |features::kWebContentsOcclusion| is disabled
+ // (for power and speed impact assessment) or when
+ // |switches::kDisableBackgroundingOccludedWindowsForTesting| is specified on
+ // the command line (to avoid flakiness in browser tests).
+ const bool occlusion_is_disabled =
+ !base::FeatureList::IsEnabled(features::kWebContentsOcclusion) ||
+ base::CommandLine::ForCurrentProcess()->HasSwitch(
+ switches::kDisableBackgroundingOccludedWindowsForTesting);
+ if (occlusion_is_disabled && visibility == Visibility::OCCLUDED)
+ visibility = Visibility::VISIBLE;
+
if (!did_first_set_visible_) {
- // If this WebContents has not yet been set to be visible for the first
- // time, ignore any requests to make it hidden, since resources would
- // immediately be destroyed and only re-created after content loaded. In
- // this state the window content is undefined and can show garbage.
- // However, the page load mechanism requires an activation call through a
- // visibility call to (re)load.
- if (visible) {
+ if (visibility == Visibility::VISIBLE) {
+ // A WebContents created with CreateParams::initially_hidden = false
+ // starts with GetVisibility() == Visibility::VISIBLE even though it is
+ // not really visible. Call WasShown() when it becomes visible for real as
+ // the page load mechanism and some WebContentsObserver rely on that.
WasShown();
did_first_set_visible_ = true;
}
+
+ // Trust the initial visibility of the WebContents and do not switch it to
+ // HIDDEN or OCCLUDED before it becomes VISIBLE for real. Doing so would
+ // result in destroying resources that would immediately be recreated (e.g.
+ // UpdateWebContents(HIDDEN) can be called when a WebContents is added to a
+ // hidden window that is about to be shown).
+
return;
}
- if (visible == should_normally_be_visible_)
+
+ if (visibility == visibility_)
return;
- if (visible)
+ if (visibility == Visibility::VISIBLE)
WasShown();
+ else if (visibility == Visibility::OCCLUDED)
+ WasOccluded();
else
WasHidden();
}
@@ -6105,16 +6279,10 @@ void WebContentsImpl::UpdateUrlForUkmSource(ukm::UkmRecorder* service,
void WebContentsImpl::FocusedNodeTouched(bool editable) {
#if defined(OS_WIN)
- // We use the cursor position to determine where the touch occurred.
RenderWidgetHostView* view = GetRenderWidgetHostView();
if (!view)
return;
- POINT cursor_pos = {};
- ::GetCursorPos(&cursor_pos);
- float scale = GetScaleFactorForView(view);
- gfx::Point location_dips_screen =
- gfx::ConvertPointToDIP(scale, gfx::Point(cursor_pos));
- view->FocusedNodeTouched(location_dips_screen, editable);
+ view->FocusedNodeTouched(editable);
#endif
}
@@ -6152,22 +6320,6 @@ bool WebContentsImpl::IsShowingContextMenuOnPage() const {
return showing_context_menu_;
}
-void WebContentsImpl::NotifyPreferencesChanged() {
- std::set<RenderViewHost*> render_view_host_set;
- for (FrameTreeNode* node : frame_tree_.Nodes()) {
- RenderWidgetHost* render_widget_host =
- node->current_frame_host()->GetRenderWidgetHost();
- if (!render_widget_host)
- continue;
- RenderViewHost* render_view_host = RenderViewHost::From(render_widget_host);
- if (!render_view_host)
- continue;
- render_view_host_set.insert(render_view_host);
- }
- for (RenderViewHost* render_view_host : render_view_host_set)
- render_view_host->OnWebkitPreferencesChanged();
-}
-
download::DownloadUrlParameters::RequestHeadersType
WebContentsImpl::ParseDownloadHeaders(const std::string& headers) {
download::DownloadUrlParameters::RequestHeadersType request_headers;
diff --git a/chromium/content/browser/web_contents/web_contents_impl.h b/chromium/content/browser/web_contents/web_contents_impl.h
index 5ec427cda0e..aeda7bbac34 100644
--- a/chromium/content/browser/web_contents/web_contents_impl.h
+++ b/chromium/content/browser/web_contents/web_contents_impl.h
@@ -20,6 +20,7 @@
#include "base/macros.h"
#include "base/observer_list.h"
#include "base/process/process.h"
+#include "base/time/time.h"
#include "base/values.h"
#include "build/build_config.h"
#include "components/download/public/common/download_url_parameters.h"
@@ -49,12 +50,12 @@
#include "content/public/common/three_d_api_types.h"
#include "net/base/load_states.h"
#include "net/http/http_response_headers.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#include "services/device/public/mojom/geolocation_context.mojom.h"
#include "services/device/public/mojom/wake_lock.mojom.h"
#include "services/metrics/public/cpp/ukm_recorder.h"
-#include "third_party/WebKit/public/mojom/color_chooser/color_chooser.mojom.h"
-#include "third_party/WebKit/public/platform/WebDragOperation.h"
+#include "third_party/blink/public/mojom/color_chooser/color_chooser.mojom.h"
+#include "third_party/blink/public/platform/web_drag_operation.h"
#include "ui/accessibility/ax_modes.h"
#include "ui/base/page_transition_types.h"
#include "ui/gfx/geometry/rect_f.h"
@@ -201,13 +202,13 @@ class CONTENT_EXPORT WebContentsImpl : public WebContents,
RenderWidgetHost* source_rwh);
// Notification that the RenderViewHost's load state changed.
- void LoadStateChanged(const GURL& url,
+ void LoadStateChanged(const std::string& host,
const net::LoadStateWithParam& load_state,
uint64_t upload_position,
uint64_t upload_size);
- // Notify observers that the visibility changed.
- void NotifyVisibilityChanged(Visibility previous_visibility);
+ // Set the visibility to |visibility| and notifies observers.
+ void SetVisibility(Visibility visibility);
// Notify observers that the web contents has been focused.
void NotifyWebContentsFocused(RenderWidgetHost* render_widget_host);
@@ -223,8 +224,6 @@ class CONTENT_EXPORT WebContentsImpl : public WebContents,
return screen_orientation_provider_.get();
}
- bool should_normally_be_visible() { return should_normally_be_visible_; }
-
// Broadcasts the mode change to all frames.
void SetAccessibilityMode(ui::AXMode mode);
@@ -287,6 +286,13 @@ class CONTENT_EXPORT WebContentsImpl : public WebContents,
return manifest_manager_host_.get();
}
+ // TODO(https://crbug.com/826293): This is a simple mitigation to validate
+ // that an action that requires a user gesture actually has one in the
+ // trustworthy browser process, rather than relying on the untrustworthy
+ // renderer. This should be eventually merged into and accounted for in the
+ // user activation work.
+ bool HasRecentInteractiveInputEvent() const;
+
#if defined(OS_ANDROID)
std::set<RenderWidgetHostImpl*> GetAllRenderWidgetHosts();
void SetImportance(ChildProcessImportance importance);
@@ -319,8 +325,10 @@ class CONTENT_EXPORT WebContentsImpl : public WebContents,
SkColor GetThemeColor() const override;
WebUI* GetWebUI() const override;
WebUI* GetCommittedWebUI() const override;
- void SetUserAgentOverride(const std::string& override) override;
+ void SetUserAgentOverride(const std::string& override,
+ bool override_in_new_tabs) override;
const std::string& GetUserAgentOverride() const override;
+ bool ShouldOverrideUserAgentInNewTabs() override;
void EnableWebContentsOnlyAccessibilityMode() override;
bool IsWebContentsOnlyAccessibilityModeForTesting() const override;
bool IsFullAccessibilityModeForTesting() const override;
@@ -334,10 +342,12 @@ class CONTENT_EXPORT WebContentsImpl : public WebContents,
bool IsWaitingForResponse() const override;
const net::LoadStateWithParam& GetLoadState() const override;
const base::string16& GetLoadStateHost() const override;
- void RequestAXTreeSnapshot(const AXTreeSnapshotCallback& callback) override;
+ void RequestAXTreeSnapshot(AXTreeSnapshotCallback callback,
+ ui::AXMode ax_mode) override;
uint64_t GetUploadSize() const override;
uint64_t GetUploadPosition() const override;
const std::string& GetEncoding() const override;
+ void SetWasDiscarded(bool was_discarded) override;
void IncrementCapturerCount(const gfx::Size& capture_size) override;
void DecrementCapturerCount() override;
bool IsBeingCaptured() const override;
@@ -357,7 +367,6 @@ class CONTENT_EXPORT WebContentsImpl : public WebContents,
void WasShown() override;
void WasHidden() override;
void WasOccluded() override;
- void WasUnOccluded() override;
Visibility GetVisibility() const override;
bool NeedToFireBeforeUnload() override;
void DispatchBeforeUnload() override;
@@ -366,8 +375,10 @@ class CONTENT_EXPORT WebContentsImpl : public WebContents,
RenderFrameHost* outer_contents_frame) override;
WebContentsImpl* GetOuterWebContents() override;
void DidChangeVisibleSecurityState() override;
+ void NotifyPreferencesChanged() override;
void Stop() override;
+ void FreezePage() override;
WebContents* Clone() override;
void ReloadFocusedFrame(bool bypass_cache) override;
void Undo() override;
@@ -410,15 +421,16 @@ class CONTENT_EXPORT WebContentsImpl : public WebContents,
void SaveFrame(const GURL& url, const Referrer& referrer) override;
void SaveFrameWithHeaders(const GURL& url,
const Referrer& referrer,
- const std::string& headers) override;
+ const std::string& headers,
+ const base::string16& suggested_filename) override;
void GenerateMHTML(const MHTMLGenerationParams& params,
- const base::Callback<void(int64_t)>& callback) override;
+ base::OnceCallback<void(int64_t)> callback) override;
const std::string& GetContentsMimeType() const override;
bool WillNotifyDisconnection() const override;
RendererPreferences* GetMutableRendererPrefs() override;
void Close() override;
void SystemDragEnded(RenderWidgetHost* source_rwh) override;
- void UserGestureDone() override;
+ void NavigatedByUser() override;
void SetClosedByUserGesture(bool value) override;
bool GetClosedByUserGesture() const override;
int GetMinimumZoomPercent() const override;
@@ -426,6 +438,7 @@ class CONTENT_EXPORT WebContentsImpl : public WebContents,
void SetPageScale(float page_scale_factor) override;
gfx::Size GetPreferredSize() const override;
bool GotResponseToLockMouseRequest(bool allowed) override;
+ bool GotResponseToKeyboardLockRequest(bool allowed) override;
bool HasOpener() const override;
RenderFrameHostImpl* GetOpener() const override;
bool HasOriginalOpener() const override;
@@ -436,7 +449,7 @@ class CONTENT_EXPORT WebContentsImpl : public WebContents,
bool is_favicon,
uint32_t max_bitmap_size,
bool bypass_cache,
- const ImageDownloadCallback& callback) override;
+ ImageDownloadCallback callback) override;
bool IsSubframe() const override;
void Find(int request_id,
const base::string16& search_text,
@@ -444,7 +457,7 @@ class CONTENT_EXPORT WebContentsImpl : public WebContents,
void StopFinding(StopFindAction action) override;
bool WasRecentlyAudible() override;
bool WasEverAudible() override;
- void GetManifest(const GetManifestCallback& callback) override;
+ void GetManifest(GetManifestCallback callback) override;
bool IsFullscreenForCurrentTab() const override;
void ExitFullscreen(bool will_cause_resize) override;
void ResumeLoadingCreatedWebContents() override;
@@ -453,6 +466,7 @@ class CONTENT_EXPORT WebContentsImpl : public WebContents,
void ClearFocusedElement() override;
bool IsShowingContextMenu() const override;
void SetShowingContextMenu(bool showing) override;
+ void PausePageScheduledTasks(bool paused) override;
#if defined(OS_ANDROID)
base::android::ScopedJavaLocalRef<jobject> GetJavaWebContents() override;
@@ -568,12 +582,12 @@ class CONTENT_EXPORT WebContentsImpl : public WebContents,
override;
#endif
void SubresourceResponseStarted(const GURL& url,
- const GURL& referrer,
- const std::string& method,
- ResourceType resource_type,
- const std::string& ip,
net::CertStatus cert_status) override;
- void UpdatePictureInPictureSurfaceId(viz::SurfaceId surface_id) override;
+ void ResourceLoadComplete(
+ mojom::ResourceLoadInfoPtr resource_load_information) override;
+ void UpdatePictureInPictureSurfaceId(const viz::SurfaceId& surface_id,
+ const gfx::Size& natural_size) override;
+ void ExitPictureInPicture() override;
// RenderViewHostDelegate ----------------------------------------------------
RenderViewHostDelegateView* GetDelegateView() override;
@@ -600,8 +614,8 @@ class CONTENT_EXPORT WebContentsImpl : public WebContents,
const base::string16& source_id) override;
RendererPreferences GetRendererPrefs(
BrowserContext* browser_context) const override;
- void OnUserInteraction(RenderWidgetHostImpl* render_widget_host,
- const blink::WebInputEvent::Type type) override;
+ void DidReceiveInputEvent(RenderWidgetHostImpl* render_widget_host,
+ const blink::WebInputEvent::Type type) override;
void OnIgnoredUIEvent() override;
void Activate() override;
void UpdatePreferredSize(const gfx::Size& pref_size) override;
@@ -619,7 +633,8 @@ class CONTENT_EXPORT WebContentsImpl : public WebContents,
void RequestMediaAccessPermission(
const MediaStreamRequest& request,
const MediaResponseCallback& callback) override;
- bool CheckMediaAccessPermission(const url::Origin& security_origin,
+ bool CheckMediaAccessPermission(RenderFrameHost* render_frame_host,
+ const url::Origin& security_origin,
MediaStreamType type) override;
std::string GetDefaultMediaDeviceID(MediaStreamType type) override;
SessionStorageNamespace* GetSessionStorageNamespace(
@@ -719,6 +734,10 @@ class CONTENT_EXPORT WebContentsImpl : public WebContents,
bool user_gesture,
bool last_unlocked_by_target,
bool privileged) override;
+ bool RequestKeyboardLock(RenderWidgetHostImpl* render_widget_host,
+ bool esc_key_locked) override;
+ void CancelKeyboardLock(RenderWidgetHostImpl* render_widget_host) override;
+ RenderWidgetHostImpl* GetKeyboardLockWidget() override;
// The following function is already listed under WebContents overrides:
// bool IsFullscreenForCurrentTab() const override;
blink::WebDisplayMode GetDisplayMode(
@@ -840,8 +859,6 @@ class CONTENT_EXPORT WebContentsImpl : public WebContents,
// Unpause the throbber if it was paused.
void DidProceedOnInterstitial() override;
- typedef base::Callback<void(WebContents*)> CreatedCallback;
-
// Forces overscroll to be disabled (used by touch emulation).
void SetForceDisableOverscrollContent(bool force_disable);
@@ -878,7 +895,7 @@ class CONTENT_EXPORT WebContentsImpl : public WebContents,
}
// Update the web contents visibility.
- void UpdateWebContentsVisibility(bool visible);
+ void UpdateWebContentsVisibility(Visibility visibility);
// Called by FindRequestManager when find replies come in from a renderer
// process.
@@ -1070,11 +1087,8 @@ class CONTENT_EXPORT WebContentsImpl : public WebContents,
// all the unique RenderWidgetHostViews.
std::set<RenderWidgetHostView*> GetRenderWidgetHostViewsInTree();
- // Calls WasUnOccluded() on all RenderWidgetHostViews in the frame tree.
- void DoWasUnOccluded();
-
// Called with the result of a DownloadImage() request.
- void OnDidDownloadImage(const ImageDownloadCallback& callback,
+ void OnDidDownloadImage(ImageDownloadCallback callback,
int id,
const GURL& image_url,
int32_t http_status_code,
@@ -1303,6 +1317,8 @@ class CONTENT_EXPORT WebContentsImpl : public WebContents,
// |delegate_|.
void OnPreferredSizeChanged(const gfx::Size& old_size);
+ void OnUserInteraction(const blink::WebInputEvent::Type type);
+
// Internal helper to create WebUI objects associated with |this|. |url| is
// used to determine which WebUI should be created (if any).
std::unique_ptr<WebUIImpl> CreateWebUI(const GURL& url);
@@ -1324,10 +1340,6 @@ class CONTENT_EXPORT WebContentsImpl : public WebContents,
// certificate via --allow-insecure-localhost.
void ShowInsecureLocalhostWarningIfNeeded();
- // Notify this WebContents that the preferences have changed. This will send
- // an IPC to all the renderer process associated with this WebContents.
- void NotifyPreferencesChanged();
-
// Format of |headers| is a new line separated list of key value pairs:
// "<key1>: <value1>\r\n<key2>: <value2>".
static download::DownloadUrlParameters::RequestHeadersType
@@ -1344,6 +1356,11 @@ class CONTENT_EXPORT WebContentsImpl : public WebContents,
// See also UpdateTargetURL.
void ClearTargetURL();
+ class AXTreeSnapshotCombiner;
+ void RecursiveRequestAXTreeSnapshotOnFrame(FrameTreeNode* root_node,
+ AXTreeSnapshotCombiner* combiner,
+ ui::AXMode ax_mode);
+
// Data for core operation ---------------------------------------------------
// Delegate for notifying our owner about stuff. Not owned by us.
@@ -1472,17 +1489,13 @@ class CONTENT_EXPORT WebContentsImpl : public WebContents,
// be told it is hidden.
int capturer_count_;
- // Tracks whether RWHV should be visible once capturer_count_ becomes zero.
- bool should_normally_be_visible_;
+ // The visibility of the WebContents. Initialized from
+ // |CreateParams::initially_hidden|. Updated from
+ // UpdateWebContentsVisibility(), WasShown(), WasHidden(), WasOccluded().
+ Visibility visibility_ = Visibility::VISIBLE;
- // Tracks whether RWHV should be occluded once |capturer_count_| becomes zero.
- bool should_normally_be_occluded_;
-
- // Tracks whether this WebContents was ever set to be visible. Used to
- // facilitate WebContents being loaded in the background by setting
- // |should_normally_be_visible_|. Ensures WasShown() will trigger when first
- // becoming visible to the user, and prevents premature unloading.
- bool did_first_set_visible_;
+ // Whether there has been a call to UpdateWebContentsVisibility(VISIBLE).
+ bool did_first_set_visible_ = false;
// See getter above.
bool is_being_destroyed_;
@@ -1516,6 +1529,11 @@ class CONTENT_EXPORT WebContentsImpl : public WebContents,
// the WebContents creation time.
base::TimeTicks last_active_time_;
+ // The time that this WebContents last received an 'interactive' input event
+ // from the user. Interactive input events are things like mouse clicks and
+ // keyboard input, but not mouse wheel scrolling or mouse moves.
+ base::TimeTicks last_interactive_input_event_time_;
+
// See description above setter.
bool closed_by_user_gesture_;
@@ -1664,7 +1682,16 @@ class CONTENT_EXPORT WebContentsImpl : public WebContents,
// Stores the RenderWidgetHost that currently holds a mouse lock or nullptr if
// there's no RenderWidgetHost holding a lock.
- RenderWidgetHostImpl* mouse_lock_widget_;
+ RenderWidgetHostImpl* mouse_lock_widget_ = nullptr;
+
+ // Stores the RenderWidgetHost that currently holds a keyboard lock or nullptr
+ // if no RenderWidgetHost has the keyboard locked.
+ RenderWidgetHostImpl* keyboard_lock_widget_ = nullptr;
+
+ // Indicates whether the escape key is one of the requested keys to be locked.
+ // This information is used to drive the browser UI so the correct exit
+ // instructions are displayed to the user in fullscreen mode.
+ bool esc_key_locked_ = false;
#if defined(OS_ANDROID)
std::unique_ptr<service_manager::InterfaceProvider> java_interfaces_;
@@ -1685,6 +1712,9 @@ class CONTENT_EXPORT WebContentsImpl : public WebContents,
// Helper variable for resolving races in UpdateTargetURL / ClearTargetURL.
RenderViewHost* view_that_set_last_target_url_ = nullptr;
+ // Whether we should override user agent in new tabs.
+ bool should_override_user_agent_in_new_tabs_ = false;
+
base::WeakPtrFactory<WebContentsImpl> loading_weak_factory_;
base::WeakPtrFactory<WebContentsImpl> weak_factory_;
@@ -1694,6 +1724,9 @@ class CONTENT_EXPORT WebContentsImpl : public WebContents,
// Dangerous methods which should never be made part of the public API, so we
// grant their use only to an explicit friend list (c++ attorney/client idiom).
class CONTENT_EXPORT WebContentsImpl::FriendWrapper {
+ public:
+ using CreatedCallback = base::RepeatingCallback<void(WebContents*)>;
+
private:
friend class TestNavigationObserver;
friend class WebContentsAddedObserver;
diff --git a/chromium/content/browser/web_contents/web_contents_impl_browsertest.cc b/chromium/content/browser/web_contents/web_contents_impl_browsertest.cc
index f4b95cc3b77..5a902419130 100644
--- a/chromium/content/browser/web_contents/web_contents_impl_browsertest.cc
+++ b/chromium/content/browser/web_contents/web_contents_impl_browsertest.cc
@@ -3,6 +3,7 @@
// found in the LICENSE file.
#include <utility>
+#include <vector>
#include "base/macros.h"
#include "base/memory/ref_counted.h"
@@ -10,8 +11,10 @@
#include "base/run_loop.h"
#include "base/strings/pattern.h"
#include "base/strings/utf_string_conversions.h"
+#include "base/time/time.h"
#include "base/values.h"
#include "build/build_config.h"
+#include "components/url_formatter/url_formatter.h"
#include "content/browser/frame_host/frame_tree.h"
#include "content/browser/frame_host/navigation_entry_impl.h"
#include "content/browser/loader/resource_dispatcher_host_impl.h"
@@ -19,6 +22,7 @@
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/browser/web_contents/web_contents_view.h"
#include "content/common/frame_messages.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/javascript_dialog_manager.h"
#include "content/public/browser/load_notification_details.h"
#include "content/public/browser/navigation_controller.h"
@@ -38,15 +42,23 @@
#include "content/public/test/content_browser_test_utils.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_utils.h"
+#include "content/public/test/url_loader_interceptor.h"
#include "content/shell/browser/shell.h"
#include "content/test/content_browser_test_utils_internal.h"
#include "net/dns/mock_host_resolver.h"
+#include "net/test/embedded_test_server/controllable_http_response.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "url/gurl.h"
namespace content {
+#define SCOPE_TRACED(statement) \
+ { \
+ SCOPED_TRACE(#statement); \
+ statement; \
+ }
+
void ResizeWebContentsView(Shell* shell, const gfx::Size& size,
bool set_start_page) {
// Shell::SizeTo is not implemented on Aura; WebContentsView::SizeContents
@@ -75,6 +87,8 @@ class WebContentsImplBrowserTest : public ContentBrowserTest {
}
void SetUpOnMainThread() override {
+ host_resolver()->AddRuleWithLatency("slow.com", "127.0.0.1",
+ 1000 * 60 * 60 /* ms */);
// Setup the server to allow serving separate sites, so we can perform
// cross-process navigation.
host_resolver()->AddRule("*", "127.0.0.1");
@@ -605,6 +619,253 @@ IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
EXPECT_TRUE(new_web_contents_observer.RenderViewCreatedCalled());
}
+// Observer class to track resource loads.
+class ResourceLoadObserver : public WebContentsObserver {
+ public:
+ explicit ResourceLoadObserver(Shell* shell)
+ : WebContentsObserver(shell->web_contents()) {}
+
+ const std::vector<mojom::ResourceLoadInfoPtr>& resource_load_infos() const {
+ return resource_load_infos_;
+ }
+
+ const std::vector<GURL>& memory_cached_loaded_urls() const {
+ return memory_cached_loaded_urls_;
+ }
+
+ // Use this method with the SCOPED_TRACE macro, so it shows the caller context
+ // if it fails.
+ void CheckResourceLoaded(const GURL& url,
+ const GURL& referrer,
+ const std::string& load_method,
+ content::ResourceType resource_type,
+ const std::string& mime_type,
+ const std::string& ip_address,
+ bool was_cached,
+ bool first_network_request,
+ const base::TimeTicks& before_request,
+ const base::TimeTicks& after_request) {
+ bool resource_load_info_found = false;
+ for (const auto& resource_load_info : resource_load_infos_) {
+ if (resource_load_info->url == url) {
+ resource_load_info_found = true;
+ EXPECT_EQ(referrer, resource_load_info->referrer);
+ EXPECT_EQ(load_method, resource_load_info->method);
+ EXPECT_EQ(resource_type, resource_load_info->resource_type);
+ if (!first_network_request)
+ EXPECT_GT(resource_load_info->request_id, 0);
+ EXPECT_EQ(mime_type, resource_load_info->mime_type);
+ if (!ip_address.empty()) {
+ ASSERT_TRUE(resource_load_info->ip);
+ EXPECT_EQ(ip_address, resource_load_info->ip->ToString());
+ }
+ EXPECT_EQ(was_cached, resource_load_info->was_cached);
+ // Simple sanity check of the request start time.
+ EXPECT_GT(resource_load_info->request_start, before_request);
+ EXPECT_GT(after_request, resource_load_info->request_start);
+ }
+ }
+ EXPECT_TRUE(resource_load_info_found);
+ }
+
+ void Reset() {
+ resource_load_infos_.clear();
+ memory_cached_loaded_urls_.clear();
+ }
+
+ private:
+ // WebContentsObserver implementation:
+ void ResourceLoadComplete(
+ const mojom::ResourceLoadInfo& resource_load_info) override {
+ resource_load_infos_.push_back(resource_load_info.Clone());
+ }
+
+ void DidLoadResourceFromMemoryCache(const GURL& url,
+ const std::string& mime_type,
+ ResourceType resource_type) override {
+ memory_cached_loaded_urls_.push_back(url);
+ }
+
+ std::vector<GURL> memory_cached_loaded_urls_;
+ std::vector<mojom::ResourceLoadInfoPtr> resource_load_infos_;
+
+ DISALLOW_COPY_AND_ASSIGN(ResourceLoadObserver);
+};
+
+IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, ResourceLoadComplete) {
+ ResourceLoadObserver observer(shell());
+ ASSERT_TRUE(embedded_test_server()->Start());
+ // Load a page with an image and an image.
+ GURL page_url(embedded_test_server()->GetURL("/page_with_iframe.html"));
+ base::TimeTicks before = base::TimeTicks::Now();
+ NavigateToURL(shell(), page_url);
+ base::TimeTicks after = base::TimeTicks::Now();
+ ASSERT_EQ(3U, observer.resource_load_infos().size());
+ // TODO(crbug.com/826082): we should test the IP address/MIME type parameters
+ // for frames once they are reported correctly.
+ SCOPE_TRACED(observer.CheckResourceLoaded(
+ page_url, /*referrer=*/GURL(), "GET", content::RESOURCE_TYPE_MAIN_FRAME,
+ /*mime-type*/ "",
+ /*ip_address=*/"",
+ /*was_cached=*/false, /*first_network_request=*/true, before, after));
+ SCOPE_TRACED(observer.CheckResourceLoaded(
+ embedded_test_server()->GetURL("/image.jpg"),
+ /*referrer=*/page_url, "GET", content::RESOURCE_TYPE_IMAGE, "image/jpeg",
+ "127.0.0.1",
+ /*was_cached=*/false, /*first_network_request=*/false, before, after));
+ SCOPE_TRACED(observer.CheckResourceLoaded(
+ embedded_test_server()->GetURL("/title1.html"),
+ /*referrer=*/page_url, "GET", content::RESOURCE_TYPE_SUB_FRAME,
+ /*mime_type=*/"",
+ /*ip_address=*/"",
+ /*was_cached=*/false, /*first_network_request=*/false, before, after));
+}
+
+// Same as WebContentsImplBrowserTest.ResourceLoadComplete but with resources
+// retrieved from the network cache.
+IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
+ ResourceLoadCompleteFromNetworkCache) {
+ ResourceLoadObserver observer(shell());
+ ASSERT_TRUE(embedded_test_server()->Start());
+ GURL page_url(
+ embedded_test_server()->GetURL("/page_with_cached_subresource.html"));
+ base::TimeTicks before = base::TimeTicks::Now();
+ NavigateToURL(shell(), page_url);
+ base::TimeTicks after = base::TimeTicks::Now();
+
+ // TODO(crbug.com/826082): we should test the IP address/MIME type parameters
+ // for frames once they are reported correctly.
+ GURL resource_url = embedded_test_server()->GetURL("/cachetime");
+ ASSERT_EQ(2U, observer.resource_load_infos().size());
+ SCOPE_TRACED(observer.CheckResourceLoaded(
+ page_url, /*referrer=*/GURL(), "GET", content::RESOURCE_TYPE_MAIN_FRAME,
+ /*mime-type*/ "",
+ /*ip_address=*/"", /*was_cached=*/false, /*first_network_request=*/true,
+ before, after));
+ SCOPE_TRACED(observer.CheckResourceLoaded(
+ resource_url, /*referrer=*/page_url, "GET", content::RESOURCE_TYPE_SCRIPT,
+ "text/html", "127.0.0.1",
+ /*was_cached=*/false, /*first_network_request=*/false, before, after));
+ EXPECT_TRUE(observer.resource_load_infos()[1]->network_accessed);
+ EXPECT_TRUE(observer.memory_cached_loaded_urls().empty());
+ observer.Reset();
+
+ // Loading again should serve the request out of the in-memory cache.
+ before = base::TimeTicks::Now();
+ NavigateToURL(shell(), page_url);
+ after = base::TimeTicks::Now();
+ ASSERT_EQ(1U, observer.resource_load_infos().size());
+ SCOPE_TRACED(observer.CheckResourceLoaded(
+ page_url, /*referrer=*/GURL(), "GET", content::RESOURCE_TYPE_MAIN_FRAME,
+ /*mime-type*/ "", /*ip_address=*/"",
+ /*was_cached=*/false, /*first_network_request=*/false, before, after));
+ ASSERT_EQ(1U, observer.memory_cached_loaded_urls().size());
+ EXPECT_EQ(resource_url, observer.memory_cached_loaded_urls()[0]);
+ observer.Reset();
+
+ // Kill the renderer process so when the navigate again, it will be a fresh
+ // renderer with an empty in-memory cache.
+ NavigateToURL(shell(), GURL("chrome:crash"));
+
+ // Reload that URL, the subresource should be served from the network cache.
+ before = base::TimeTicks::Now();
+ NavigateToURL(shell(), page_url);
+ after = base::TimeTicks::Now();
+ ASSERT_EQ(2U, observer.resource_load_infos().size());
+ SCOPE_TRACED(observer.CheckResourceLoaded(
+ page_url, /*referrer=*/GURL(), "GET", content::RESOURCE_TYPE_MAIN_FRAME,
+ /*mime-type*/ "", /*ip_address=*/"",
+ /*was_cached=*/false, /*first_network_request=*/true, before, after));
+ SCOPE_TRACED(observer.CheckResourceLoaded(
+ resource_url, /*referrer=*/page_url, "GET", content::RESOURCE_TYPE_SCRIPT,
+ "text/html", "127.0.0.1",
+ /*was_cached=*/true, /*first_network_request=*/false, before, after));
+ EXPECT_TRUE(observer.memory_cached_loaded_urls().empty());
+ EXPECT_FALSE(observer.resource_load_infos()[1]->network_accessed);
+}
+
+IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
+ ResourceLoadCompleteFromLocalResource) {
+ ResourceLoadObserver observer(shell());
+ ASSERT_TRUE(embedded_test_server()->Start());
+ NavigateToURL(shell(),
+ GURL(embedded_test_server()->GetURL("/page_with_image.html")));
+ ASSERT_EQ(2U, observer.resource_load_infos().size());
+ // TODO(crbug.com/826082): network_accessed should be true on the frame.
+ EXPECT_FALSE(observer.resource_load_infos()[0]->network_accessed);
+ EXPECT_TRUE(observer.resource_load_infos()[1]->network_accessed);
+ observer.Reset();
+
+ NavigateToURL(shell(), GURL("chrome://gpu"));
+ ASSERT_LE(1U, observer.resource_load_infos().size());
+ for (const mojom::ResourceLoadInfoPtr& resource_load_info :
+ observer.resource_load_infos()) {
+ EXPECT_FALSE(resource_load_info->network_accessed);
+ }
+}
+
+IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
+ ResourceLoadCompleteWithRedirect) {
+ ResourceLoadObserver observer(shell());
+ ASSERT_TRUE(embedded_test_server()->Start());
+
+ GURL page_destination_url(
+ embedded_test_server()->GetURL("/page_with_image_redirect.html"));
+ GURL page_original_url(embedded_test_server()->GetURL(
+ "/server-redirect?" + page_destination_url.spec()));
+ NavigateToURL(shell(), page_original_url);
+
+ ASSERT_EQ(2U, observer.resource_load_infos().size());
+ const mojom::ResourceLoadInfoPtr& page_load_info =
+ observer.resource_load_infos()[0];
+ // TODO(crbug.com/826082): turn this back on when the ResourceDispatcher
+ // receives redirects for the main frame.
+ // EXPECT_EQ(page_destination_url, page_load_info->url);
+ EXPECT_EQ(page_original_url, page_load_info->original_url);
+
+ GURL image_destination_url(embedded_test_server()->GetURL("/blank.jpg"));
+ GURL image_original_url(
+ embedded_test_server()->GetURL("/server-redirect?blank.jpg"));
+ const mojom::ResourceLoadInfoPtr& image_load_info =
+ observer.resource_load_infos()[1];
+ EXPECT_EQ(image_destination_url, image_load_info->url);
+ EXPECT_EQ(image_original_url, image_load_info->original_url);
+}
+
+IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
+ ResourceLoadCompleteNetError) {
+ ResourceLoadObserver observer(shell());
+ ASSERT_TRUE(embedded_test_server()->Start());
+
+ GURL page_url(embedded_test_server()->GetURL("/page_with_image.html"));
+ GURL image_url(embedded_test_server()->GetURL("/blank.jpg"));
+
+ // Load the page without errors.
+ NavigateToURL(shell(), page_url);
+ ASSERT_EQ(2U, observer.resource_load_infos().size());
+ EXPECT_EQ(net::OK, observer.resource_load_infos()[0]->net_error);
+ EXPECT_EQ(net::OK, observer.resource_load_infos()[1]->net_error);
+ observer.Reset();
+
+ // Load the page and simulate a network error.
+ content::URLLoaderInterceptor url_interceptor(base::BindRepeating(
+ [](const GURL& url,
+ content::URLLoaderInterceptor::RequestParams* params) {
+ if (params->url_request.url != url)
+ return false;
+ network::URLLoaderCompletionStatus status;
+ status.error_code = net::ERR_ADDRESS_UNREACHABLE;
+ params->client->OnComplete(status);
+ return true;
+ },
+ image_url));
+ NavigateToURL(shell(), page_url);
+ ASSERT_EQ(2U, observer.resource_load_infos().size());
+ EXPECT_EQ(net::OK, observer.resource_load_infos()[0]->net_error);
+ EXPECT_EQ(net::ERR_ADDRESS_UNREACHABLE,
+ observer.resource_load_infos()[1]->net_error);
+}
+
struct LoadProgressDelegateAndObserver : public WebContentsDelegate,
public WebContentsObserver {
explicit LoadProgressDelegateAndObserver(Shell* shell)
@@ -1419,8 +1680,8 @@ void DownloadImageTestInternal(Shell* shell,
shell->LoadURL(GURL("about:blank"));
shell->web_contents()->DownloadImage(
image_url, false, 1024, false,
- base::Bind(&DownloadImageObserver::OnFinishDownloadImage,
- base::Unretained(&download_image_observer)));
+ base::BindOnce(&DownloadImageObserver::OnFinishDownloadImage,
+ base::Unretained(&download_image_observer)));
// Wait for response.
loop_runner->Run();
@@ -1472,7 +1733,7 @@ IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, DownloadImage_NoValidImage) {
base::RunLoop run_loop;
shell()->web_contents()->DownloadImage(
kImageUrl, false, 2, false,
- base::Bind(&ExpectNoValidImageCallback, run_loop.QuitClosure()));
+ base::BindOnce(&ExpectNoValidImageCallback, run_loop.QuitClosure()));
run_loop.Run();
}
@@ -1565,7 +1826,7 @@ IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, UserAgentOverride) {
&header_value));
EXPECT_NE(kUserAgentOverride, header_value);
- shell()->web_contents()->SetUserAgentOverride("foo");
+ shell()->web_contents()->SetUserAgentOverride("foo", false);
NavigateToURL(shell(), kUrl);
EXPECT_TRUE(ExecuteScriptAndExtractString(
shell()->web_contents(),
@@ -1773,4 +2034,177 @@ IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, UpdateTargetURL) {
target_url_waiter.WaitForUpdatedTargetURL());
}
+// TODO(mmenke): Beef up testing of LoadState a little. In particular, check
+// LoadState itself, not just the host name, check upload progress, check the
+// param, and make sure RDH pushes the data to the browser process.
+IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, UpdateLoadState) {
+ // Controlled responses for image requests made in the test. They will
+ // alternate being the "most interesting" for the purposes of notifying the
+ // WebContents.
+ auto a_response =
+ std::make_unique<net::test_server::ControllableHttpResponse>(
+ embedded_test_server(), "/a_img");
+ auto slow_response =
+ std::make_unique<net::test_server::ControllableHttpResponse>(
+ embedded_test_server(), "/slow_img");
+ auto c_response =
+ std::make_unique<net::test_server::ControllableHttpResponse>(
+ embedded_test_server(), "/c_img");
+ ASSERT_TRUE(embedded_test_server()->Start());
+
+ // This is a hack to ensure that the resource scheduler has at least one
+ // loading client for the duration of the test. Could alternatively delay some
+ // subresources on the main target page, but it would require care to ensure
+ // *all* other resources are completed before the test properly gets started.
+ Shell* popup = CreateBrowser();
+ const GURL kPopupUrl(embedded_test_server()->GetURL("/title1.html"));
+ TestNavigationManager popup_delayer(popup->web_contents(), kPopupUrl);
+ popup->LoadURL(kPopupUrl);
+ EXPECT_TRUE(popup_delayer.WaitForResponse());
+
+ EXPECT_TRUE(NavigateToURL(
+ shell(), embedded_test_server()->GetURL(
+ "a.com", "/cross_site_iframe_factory.html?a(b(c))")));
+ WebContentsImpl* web_contents =
+ static_cast<WebContentsImpl*>(shell()->web_contents());
+ FrameTreeNode* a_frame = web_contents->GetFrameTree()->root();
+ FrameTreeNode* slow_frame = a_frame->child_at(0);
+ FrameTreeNode* c_frame = slow_frame->child_at(0);
+
+ // Start loading the respective resources in each frame.
+ auto load_resource = [](FrameTreeNode* frame, const std::string url) {
+ std::string partial_script = R"(
+ var img = new Image();
+ img.src = '%s';
+ document.body.appendChild(img);
+ )";
+ std::string script =
+ base::StringPrintf(partial_script.c_str(), url.c_str());
+ EXPECT_TRUE(ExecuteScript(frame, script));
+ };
+
+ // Blocks until the img element in |frame| finishes.
+ auto wait_for_img_finished = [](FrameTreeNode* frame) {
+ bool finished = false;
+ std::string script = R"(
+ var img = document.getElementsByTagName('img')[0];
+ if (img.complete)
+ window.domAutomationController.send(true);
+ else
+ img.onload = img.onerror = window.domAutomationController.send(true);
+ )";
+ EXPECT_TRUE(ExecuteScriptAndExtractBool(frame, script.c_str(), &finished));
+ };
+
+ // Requests a load state notification from the RDHI and waits until the update
+ // is posted back on the UI thread. Due to PostTaskAndReply, relies on
+ // UpdateLoadInfo synchronously posting a task to the WebContents.
+ auto update_load_state_and_wait = []() {
+ base::RunLoop run_loop;
+ BrowserThread::PostTaskAndReply(
+ BrowserThread::IO, FROM_HERE,
+ base::BindOnce(&ResourceDispatcherHostImpl::UpdateLoadInfo,
+ base::Unretained(ResourceDispatcherHostImpl::Get())),
+ run_loop.QuitClosure());
+ run_loop.Run();
+ };
+
+ // There should be no outgoing requests, so the load state should be empty.
+ update_load_state_and_wait();
+ EXPECT_TRUE(web_contents->GetLoadStateHost().empty());
+ EXPECT_EQ(url_formatter::IDNToUnicode(kPopupUrl.host()),
+ popup->web_contents()->GetLoadStateHost());
+
+ load_resource(a_frame, "/a_img");
+ a_response->WaitForRequest();
+ update_load_state_and_wait();
+ EXPECT_EQ(url_formatter::IDNToUnicode("a.com"),
+ web_contents->GetLoadStateHost());
+
+ // slow_img should never get past DNS resolution for the remainder of the
+ // test. Ensure that a_img is further along (and therefore more interesting).
+ load_resource(slow_frame, "http://slow.com/slow_img");
+ update_load_state_and_wait();
+ EXPECT_EQ(url_formatter::IDNToUnicode("a.com"),
+ web_contents->GetLoadStateHost());
+
+ // Finish a_img and start c_img, ensure it passes slow_img.
+ a_response->Done();
+ load_resource(c_frame, "/c_img");
+ wait_for_img_finished(a_frame);
+ c_response->WaitForRequest();
+ update_load_state_and_wait();
+ EXPECT_EQ(url_formatter::IDNToUnicode("c.com"),
+ web_contents->GetLoadStateHost());
+
+ // Finish c_img and ensure slow_img (the last outgoing request) is the most
+ // interesting.
+ c_response->Done();
+ wait_for_img_finished(c_frame);
+ update_load_state_and_wait();
+ EXPECT_EQ(url_formatter::IDNToUnicode("slow.com"),
+ web_contents->GetLoadStateHost());
+}
+
+// Disabled due to flakes on Linux. https://crbug.com/832191
+#if defined(OS_LINUX)
+#define MAYBE_PausePageScheduledTasks DISABLED_PausePageScheduledTasks
+#else
+#define MAYBE_PausePageScheduledTasks PausePageScheduledTasks
+#endif
+IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
+ MAYBE_PausePageScheduledTasks) {
+ EXPECT_TRUE(embedded_test_server()->Start());
+
+ GURL test_url = embedded_test_server()->GetURL("/pause_schedule_task.html");
+ NavigateToURL(shell(), test_url);
+ EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
+
+ int text_length;
+ EXPECT_TRUE(content::ExecuteScriptAndExtractInt(
+ shell(),
+ "domAutomationController.send(document.getElementById('textfield')."
+ "value.length)",
+ &text_length));
+ EXPECT_GT(text_length, 0);
+
+ // Suspend blink schedule tasks.
+ shell()->web_contents()->PausePageScheduledTasks(true);
+
+ EXPECT_TRUE(content::ExecuteScriptAndExtractInt(
+ shell(),
+ "domAutomationController.send(document.getElementById('textfield')."
+ "value.length)",
+ &text_length));
+ EXPECT_GT(text_length, 0);
+
+ int next_text_length;
+ EXPECT_TRUE(content::ExecuteScriptAndExtractInt(
+ shell(),
+ "domAutomationController.send(document.getElementById('textfield')."
+ "value.length)",
+ &next_text_length));
+ EXPECT_EQ(text_length, next_text_length);
+
+ // Resume the paused blink schedule tasks.
+ shell()->web_contents()->PausePageScheduledTasks(false);
+
+ // We call a document.getElementById five times in order to give the
+ // javascript time to run with DOM again.
+ for (int i = 0; i < 5; i++) {
+ EXPECT_TRUE(content::ExecuteScriptAndExtractInt(
+ shell(),
+ "domAutomationController.send(document.getElementById('textfield')."
+ "value.length)",
+ &next_text_length));
+ }
+
+ EXPECT_TRUE(content::ExecuteScriptAndExtractInt(
+ shell(),
+ "domAutomationController.send(document.getElementById('textfield')."
+ "value.length)",
+ &next_text_length));
+ EXPECT_GT(next_text_length, text_length);
+}
+
} // namespace content
diff --git a/chromium/content/browser/web_contents/web_contents_impl_unittest.cc b/chromium/content/browser/web_contents/web_contents_impl_unittest.cc
index 955e6331269..b88f6ee6a1c 100644
--- a/chromium/content/browser/web_contents/web_contents_impl_unittest.cc
+++ b/chromium/content/browser/web_contents/web_contents_impl_unittest.cc
@@ -9,6 +9,7 @@
#include "base/logging.h"
#include "base/macros.h"
#include "base/strings/utf_string_conversions.h"
+#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "components/download/public/common/download_url_parameters.h"
#include "content/browser/frame_host/interstitial_page_impl.h"
@@ -42,6 +43,7 @@
#include "content/public/common/bindings_policy.h"
#include "content/public/common/browser_side_navigation_policy.h"
#include "content/public/common/content_constants.h"
+#include "content/public/common/content_features.h"
#include "content/public/common/url_constants.h"
#include "content/public/test/mock_render_process_host.h"
#include "content/public/test/navigation_simulator.h"
@@ -55,7 +57,7 @@
#include "net/test/cert_test_util.h"
#include "net/test/test_data_directory.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/common/frame/sandbox_flags.h"
+#include "third_party/blink/public/common/frame/sandbox_flags.h"
#include "third_party/skia/include/core/SkColor.h"
#include "url/url_constants.h"
@@ -691,33 +693,35 @@ TEST_F(WebContentsImplTest, NavigateTwoTabsCrossSite) {
// Navigate first contents to a new site.
const GURL url2a("http://www.yahoo.com");
- controller().LoadURL(
- url2a, Referrer(), ui::PAGE_TRANSITION_TYPED, std::string());
+ controller().LoadURL(url2a, Referrer(), ui::PAGE_TRANSITION_LINK,
+ std::string());
entry_id = controller().GetPendingEntry()->GetUniqueID();
orig_rfh->PrepareForCommit();
TestRenderFrameHost* pending_rfh_a = contents()->GetPendingMainFrame();
+ if (AreAllSitesIsolatedForTesting())
+ EXPECT_TRUE(contents()->CrossProcessNavigationPending());
contents()->TestDidNavigate(pending_rfh_a, entry_id, true, url2a,
- ui::PAGE_TRANSITION_TYPED);
+ ui::PAGE_TRANSITION_LINK);
SiteInstance* instance2a = contents()->GetSiteInstance();
EXPECT_NE(instance1, instance2a);
// Navigate second contents to the same site as the first tab.
const GURL url2b("http://mail.yahoo.com");
contents2->GetController().LoadURL(url2b, Referrer(),
- ui::PAGE_TRANSITION_TYPED,
- std::string());
+ ui::PAGE_TRANSITION_LINK, std::string());
entry_id = contents2->GetController().GetPendingEntry()->GetUniqueID();
TestRenderFrameHost* rfh2 = contents2->GetMainFrame();
rfh2->PrepareForCommit();
TestRenderFrameHost* pending_rfh_b = contents2->GetPendingMainFrame();
EXPECT_NE(nullptr, pending_rfh_b);
- EXPECT_TRUE(contents2->CrossProcessNavigationPending());
+ if (AreAllSitesIsolatedForTesting())
+ EXPECT_TRUE(contents2->CrossProcessNavigationPending());
// NOTE(creis): We used to be in danger of showing a crash page here if the
// second contents hadn't navigated somewhere first (bug 1145430). That case
// is now covered by the CrossSiteBoundariesAfterCrash test.
contents2->TestDidNavigate(pending_rfh_b, entry_id, true, url2b,
- ui::PAGE_TRANSITION_TYPED);
+ ui::PAGE_TRANSITION_LINK);
SiteInstance* instance2b = contents2->GetSiteInstance();
EXPECT_NE(instance1, instance2b);
@@ -2733,78 +2737,119 @@ TEST_F(WebContentsImplTest, CapturerOverridesPreferredSize) {
EXPECT_EQ(original_preferred_size, contents()->GetPreferredSize());
}
-TEST_F(WebContentsImplTest, CapturerPreventsHiding) {
- const gfx::Size original_preferred_size(1024, 768);
- contents()->UpdatePreferredSize(original_preferred_size);
+TEST_F(WebContentsImplTest, UpdateWebContentsVisibility) {
+ base::test::ScopedFeatureList scoped_feature_list;
+ scoped_feature_list.InitAndEnableFeature(features::kWebContentsOcclusion);
TestRenderWidgetHostView* view = static_cast<TestRenderWidgetHostView*>(
main_test_rfh()->GetRenderViewHost()->GetWidget()->GetView());
+ TestWebContentsObserver observer(contents());
- // With no capturers, setting and un-setting occlusion should change the
- // view's occlusion state.
EXPECT_FALSE(view->is_showing());
- contents()->WasShown();
+ EXPECT_FALSE(view->is_occluded());
+
+ // WebContents must be made visible once before it can be hidden.
+ contents()->UpdateWebContentsVisibility(Visibility::HIDDEN);
+ EXPECT_FALSE(view->is_showing());
+ EXPECT_FALSE(view->is_occluded());
+ EXPECT_EQ(Visibility::VISIBLE, contents()->GetVisibility());
+
+ contents()->UpdateWebContentsVisibility(Visibility::VISIBLE);
EXPECT_TRUE(view->is_showing());
- contents()->WasHidden();
+ EXPECT_FALSE(view->is_occluded());
+ EXPECT_EQ(Visibility::VISIBLE, contents()->GetVisibility());
+
+ // Hiding/occluding/showing the WebContents should hide and show |view|.
+ contents()->UpdateWebContentsVisibility(Visibility::HIDDEN);
EXPECT_FALSE(view->is_showing());
- contents()->WasShown();
+ EXPECT_FALSE(view->is_occluded());
+ EXPECT_EQ(Visibility::HIDDEN, contents()->GetVisibility());
+
+ contents()->UpdateWebContentsVisibility(Visibility::VISIBLE);
EXPECT_TRUE(view->is_showing());
+ EXPECT_FALSE(view->is_occluded());
+ EXPECT_EQ(Visibility::VISIBLE, contents()->GetVisibility());
- // Add a capturer and try to hide the contents. The view will remain visible.
- contents()->IncrementCapturerCount(gfx::Size());
- contents()->WasHidden();
+ contents()->UpdateWebContentsVisibility(Visibility::OCCLUDED);
EXPECT_TRUE(view->is_showing());
+ EXPECT_TRUE(view->is_occluded());
+ EXPECT_EQ(Visibility::OCCLUDED, contents()->GetVisibility());
- // Remove the capturer, and the WasHidden should take effect.
- contents()->DecrementCapturerCount();
+ contents()->UpdateWebContentsVisibility(Visibility::VISIBLE);
+ EXPECT_TRUE(view->is_showing());
+ EXPECT_FALSE(view->is_occluded());
+ EXPECT_EQ(Visibility::VISIBLE, contents()->GetVisibility());
+
+ contents()->UpdateWebContentsVisibility(Visibility::OCCLUDED);
+ EXPECT_TRUE(view->is_showing());
+ EXPECT_TRUE(view->is_occluded());
+ EXPECT_EQ(Visibility::OCCLUDED, contents()->GetVisibility());
+
+ contents()->UpdateWebContentsVisibility(Visibility::HIDDEN);
EXPECT_FALSE(view->is_showing());
+ EXPECT_EQ(Visibility::HIDDEN, contents()->GetVisibility());
}
-TEST_F(WebContentsImplTest, CapturerPreventsOcclusion) {
- const gfx::Size original_preferred_size(1024, 768);
- contents()->UpdatePreferredSize(original_preferred_size);
+namespace {
+void HideOrOccludeWithCapturerTest(WebContentsImpl* contents,
+ Visibility hidden_or_occluded) {
TestRenderWidgetHostView* view = static_cast<TestRenderWidgetHostView*>(
- main_test_rfh()->GetRenderViewHost()->GetWidget()->GetView());
+ contents->GetRenderWidgetHostView());
- // With no capturers, setting and un-setting occlusion should change the
- // view's occlusion state.
- EXPECT_FALSE(view->is_occluded());
- contents()->WasOccluded();
- EXPECT_TRUE(view->is_occluded());
- contents()->WasUnOccluded();
- EXPECT_FALSE(view->is_occluded());
- contents()->WasOccluded();
- EXPECT_TRUE(view->is_occluded());
+ EXPECT_FALSE(view->is_showing());
- // Adding a capturer on an occluded WebContents should cause the view to be
- // unoccluded. Removing the capturer should cause the view to be occluded
- // again.
- contents()->IncrementCapturerCount(gfx::Size());
+ // WebContents must be made visible once before it can be hidden.
+ contents->UpdateWebContentsVisibility(Visibility::VISIBLE);
+ EXPECT_TRUE(view->is_showing());
EXPECT_FALSE(view->is_occluded());
+ EXPECT_EQ(Visibility::VISIBLE, contents->GetVisibility());
- contents()->DecrementCapturerCount();
- EXPECT_TRUE(view->is_occluded());
+ // Add a capturer when the contents is visible and then hide the contents.
+ // |view| should remain visible.
+ contents->IncrementCapturerCount(gfx::Size());
+ contents->UpdateWebContentsVisibility(hidden_or_occluded);
+ EXPECT_TRUE(view->is_showing());
+ EXPECT_FALSE(view->is_occluded());
+ EXPECT_EQ(hidden_or_occluded, contents->GetVisibility());
+
+ // Remove the capturer when the contents is hidden/occluded. |view| should be
+ // hidden/occluded.
+ contents->DecrementCapturerCount();
+ if (hidden_or_occluded == Visibility::HIDDEN) {
+ EXPECT_FALSE(view->is_showing());
+ } else {
+ EXPECT_TRUE(view->is_showing());
+ EXPECT_TRUE(view->is_occluded());
+ }
- // Adding a capturer on an unoccluded WebContents should not change the
- // occlusion state of the view. Calling WasOccluded() on an unoccluded
- // WebContents() that has a capturer should not change the occlusion state of
- // the view. Removing the capturer should cause the view to become occluded.
- contents()->WasUnOccluded();
+ // Add a capturer when the contents is hidden. |view| should be unoccluded.
+ contents->IncrementCapturerCount(gfx::Size());
EXPECT_FALSE(view->is_occluded());
- contents()->IncrementCapturerCount(gfx::Size());
+
+ // Show the contents. The view should be visible.
+ contents->UpdateWebContentsVisibility(Visibility::VISIBLE);
+ EXPECT_TRUE(view->is_showing());
EXPECT_FALSE(view->is_occluded());
+ EXPECT_EQ(Visibility::VISIBLE, contents->GetVisibility());
- contents()->WasOccluded();
+ // Remove the capturer when the contents is visible. The view should remain
+ // visible.
+ contents->DecrementCapturerCount();
+ EXPECT_TRUE(view->is_showing());
EXPECT_FALSE(view->is_occluded());
+}
- contents()->DecrementCapturerCount();
- EXPECT_TRUE(view->is_occluded());
+} // namespace
- // Calling WasUnoccluded() on a WebContents with no capturers should cause the
- // view to become unoccluded.
- contents()->WasUnOccluded();
- EXPECT_FALSE(view->is_occluded());
+TEST_F(WebContentsImplTest, HideWithCapturer) {
+ HideOrOccludeWithCapturerTest(contents(), Visibility::HIDDEN);
+}
+
+TEST_F(WebContentsImplTest, OccludeWithCapturer) {
+ base::test::ScopedFeatureList scoped_feature_list;
+ scoped_feature_list.InitAndEnableFeature(features::kWebContentsOcclusion);
+ HideOrOccludeWithCapturerTest(contents(), Visibility::OCCLUDED);
}
// Tests that GetLastActiveTime starts with a real, non-zero time and updates
@@ -2976,21 +3021,36 @@ TEST_F(WebContentsImplTest, ActiveContentsCountNavigate) {
contents->CommitPendingNavigation();
EXPECT_EQ(1u, instance->GetRelatedActiveContentsCount());
- // Navigate to a URL in a different site.
- const GURL kUrl = GURL("http://b.com");
- contents->GetController().LoadURL(kUrl,
- Referrer(),
- ui::PAGE_TRANSITION_TYPED,
+ // Navigate to a URL in a different site in the same BrowsingInstance.
+ const GURL kUrl2("http://b.com");
+ contents->GetController().LoadURL(kUrl2, Referrer(), ui::PAGE_TRANSITION_LINK,
std::string());
int entry_id = contents->GetController().GetPendingEntry()->GetUniqueID();
contents->GetMainFrame()->PrepareForCommit();
- EXPECT_TRUE(contents->CrossProcessNavigationPending());
+ if (AreAllSitesIsolatedForTesting())
+ EXPECT_TRUE(contents->CrossProcessNavigationPending());
EXPECT_EQ(1u, instance->GetRelatedActiveContentsCount());
- contents->GetPendingMainFrame()->SendNavigate(entry_id, true, kUrl);
+ contents->GetPendingMainFrame()->SendNavigate(entry_id, true, kUrl2);
EXPECT_EQ(1u, instance->GetRelatedActiveContentsCount());
- contents.reset();
+ // Navigate to a URL in a different site and different BrowsingInstance, by
+ // using a TYPED page transition instead of LINK.
+ const GURL kUrl3("http://c.com");
+ contents->GetController().LoadURL(kUrl3, Referrer(),
+ ui::PAGE_TRANSITION_TYPED, std::string());
+ entry_id = contents->GetController().GetPendingEntry()->GetUniqueID();
+ contents->GetMainFrame()->PrepareForCommit();
+ EXPECT_TRUE(contents->CrossProcessNavigationPending());
+ EXPECT_EQ(1u, instance->GetRelatedActiveContentsCount());
+ scoped_refptr<SiteInstance> new_instance =
+ contents->GetPendingMainFrame()->GetSiteInstance();
+ contents->GetPendingMainFrame()->SendNavigate(entry_id, true, kUrl3);
EXPECT_EQ(0u, instance->GetRelatedActiveContentsCount());
+ EXPECT_EQ(1u, new_instance->GetRelatedActiveContentsCount());
+ EXPECT_FALSE(new_instance->IsRelatedSiteInstance(instance.get()));
+
+ contents.reset();
+ EXPECT_EQ(0u, new_instance->GetRelatedActiveContentsCount());
}
// Tests that GetRelatedActiveContentsCount tracks BrowsingInstance changes
@@ -3446,6 +3506,32 @@ TEST_F(WebContentsImplTest, ThemeColorChangeDependingOnFirstVisiblePaint) {
EXPECT_EQ(SK_ColorGREEN, observer.last_theme_color());
}
+TEST_F(WebContentsImplTest, PictureInPictureMediaPlayerIdWasChanged) {
+ const int kPlayerVideoOnlyId = 30; /* arbitrary and used for tests */
+
+ MediaWebContentsObserver* observer =
+ contents()->media_web_contents_observer();
+ TestRenderFrameHost* rfh = main_test_rfh();
+ rfh->InitializeRenderFrameIfNeeded();
+
+ // If Picture-in-Picture was never triggered, the media player id would not be
+ // set.
+ EXPECT_FALSE(observer->GetPictureInPictureVideoMediaPlayerId().has_value());
+
+ rfh->OnMessageReceived(
+ MediaPlayerDelegateHostMsg_OnPictureInPictureSourceChanged(
+ rfh->GetRoutingID(), kPlayerVideoOnlyId));
+ EXPECT_TRUE(observer->GetPictureInPictureVideoMediaPlayerId().has_value());
+ EXPECT_EQ(kPlayerVideoOnlyId,
+ observer->GetPictureInPictureVideoMediaPlayerId()->second);
+
+ // Picture-in-Picture media player id should be reset when the media is
+ // destroyed.
+ rfh->OnMessageReceived(MediaPlayerDelegateHostMsg_OnMediaDestroyed(
+ rfh->GetRoutingID(), kPlayerVideoOnlyId));
+ EXPECT_FALSE(observer->GetPictureInPictureVideoMediaPlayerId().has_value());
+}
+
TEST_F(WebContentsImplTest, ParseDownloadHeaders) {
download::DownloadUrlParameters::RequestHeadersType request_headers =
WebContentsImpl::ParseDownloadHeaders("A: 1\r\nB: 2\r\nC: 3\r\n\r\n");
@@ -3549,8 +3635,8 @@ TEST_F(WebContentsImplTest, StartingSandboxFlags) {
blink::WebSandboxFlags::kPopups | blink::WebSandboxFlags::kModals |
blink::WebSandboxFlags::kTopNavigation;
params.starting_sandbox_flags = expected_flags;
- WebContentsImpl* new_contents =
- WebContentsImpl::CreateWithOpener(params, nullptr);
+ std::unique_ptr<WebContentsImpl> new_contents(
+ WebContentsImpl::CreateWithOpener(params, nullptr));
FrameTreeNode* root = new_contents->GetFrameTree()->root();
blink::WebSandboxFlags pending_flags =
root->pending_frame_policy().sandbox_flags;
diff --git a/chromium/content/browser/web_contents/web_contents_view_android.cc b/chromium/content/browser/web_contents/web_contents_view_android.cc
index fe3709bd8b3..4f8a55220b8 100644
--- a/chromium/content/browser/web_contents/web_contents_view_android.cc
+++ b/chromium/content/browser/web_contents/web_contents_view_android.cc
@@ -4,13 +4,16 @@
#include "content/browser/web_contents/web_contents_view_android.h"
+#include "base/android/build_info.h"
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/logging.h"
#include "cc/layers/layer.h"
#include "content/browser/accessibility/browser_accessibility_manager_android.h"
-#include "content/browser/android/content_view_core.h"
+#include "content/browser/android/content_feature_list.h"
#include "content/browser/android/gesture_listener_manager.h"
+#include "content/browser/android/select_popup.h"
+#include "content/browser/android/selection/selection_popup_controller.h"
#include "content/browser/frame_host/interstitial_page_impl.h"
#include "content/browser/renderer_host/display_util.h"
#include "content/browser/renderer_host/render_view_host_factory.h"
@@ -40,6 +43,18 @@ namespace content {
namespace {
+// True if we want to disable Android native event batching and use
+// compositor event queue.
+bool ShouldRequestUnbufferedDispatch() {
+ static bool should_request_unbuffered_dispatch =
+ base::FeatureList::IsEnabled(
+ content::android::kRequestUnbufferedDispatch) &&
+ base::android::BuildInfo::GetInstance()->sdk_int() >=
+ base::android::SDK_VERSION_LOLLIPOP &&
+ !content::GetContentClient()->UsingSynchronousCompositing();
+ return should_request_unbuffered_dispatch;
+}
+
RenderWidgetHostViewAndroid* GetRenderWidgetHostViewAndroid(
WebContents* web_contents) {
RenderWidgetHostView* rwhv = NULL;
@@ -87,33 +102,20 @@ WebContentsViewAndroid::WebContentsViewAndroid(
WebContentsImpl* web_contents,
WebContentsViewDelegate* delegate)
: web_contents_(web_contents),
- content_view_core_(NULL),
delegate_(delegate),
view_(this, ui::ViewAndroid::LayoutType::NORMAL),
- synchronous_compositor_client_(nullptr) {}
+ synchronous_compositor_client_(nullptr) {
+ view_.SetLayer(cc::Layer::Create());
+}
WebContentsViewAndroid::~WebContentsViewAndroid() {
if (view_.GetLayer())
view_.GetLayer()->RemoveFromParent();
}
-void WebContentsViewAndroid::SetContentViewCore(
- ContentViewCore* content_view_core) {
- content_view_core_ = content_view_core;
- RenderWidgetHostViewAndroid* rwhv = GetRenderWidgetHostViewAndroid();
- if (rwhv)
- rwhv->SetContentViewCore(content_view_core_);
-
- if (web_contents_->ShowingInterstitialPage()) {
- rwhv = static_cast<RenderWidgetHostViewAndroid*>(
- web_contents_->GetInterstitialPage()
- ->GetMainFrame()
- ->GetRenderViewHost()
- ->GetWidget()
- ->GetView());
- if (rwhv)
- rwhv->SetContentViewCore(content_view_core_);
- }
+void WebContentsViewAndroid::SetSelectPopup(
+ std::unique_ptr<SelectPopup> select_popup) {
+ select_popup_ = std::move(select_popup);
}
void WebContentsViewAndroid::SetOverscrollRefreshHandler(
@@ -160,7 +162,7 @@ WebContentsViewAndroid::GetRenderWidgetHostViewAndroid() {
}
gfx::NativeWindow WebContentsViewAndroid::GetTopLevelNativeWindow() const {
- return content_view_core_ ? content_view_core_->GetWindowAndroid() : nullptr;
+ return view_.GetWindowAndroid();
}
void WebContentsViewAndroid::GetContainerBounds(gfx::Rect* out) const {
@@ -247,8 +249,7 @@ RenderWidgetHostViewBase* WebContentsViewAndroid::CreateViewForWidget(
// order to paint it. See ContentView::GetRenderWidgetHostViewAndroid for an
// example of how this is achieved for InterstitialPages.
RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(render_widget_host);
- RenderWidgetHostViewAndroid* rwhv =
- new RenderWidgetHostViewAndroid(rwhi, content_view_core_);
+ auto* rwhv = new RenderWidgetHostViewAndroid(rwhi, &view_);
rwhv->SetSynchronousCompositorClient(synchronous_compositor_client_);
return rwhv;
}
@@ -256,7 +257,7 @@ RenderWidgetHostViewBase* WebContentsViewAndroid::CreateViewForWidget(
RenderWidgetHostViewBase* WebContentsViewAndroid::CreateViewForPopupWidget(
RenderWidgetHost* render_widget_host) {
RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(render_widget_host);
- return new RenderWidgetHostViewAndroid(rwhi, NULL);
+ return new RenderWidgetHostViewAndroid(rwhi, nullptr);
}
void WebContentsViewAndroid::RenderViewCreated(RenderViewHost* host) {
@@ -289,16 +290,15 @@ void WebContentsViewAndroid::ShowPopupMenu(
const std::vector<MenuItem>& items,
bool right_aligned,
bool allow_multiple_selection) {
- if (content_view_core_) {
- content_view_core_->ShowSelectPopupMenu(
- render_frame_host, bounds, items, selected_item,
- allow_multiple_selection, right_aligned);
+ if (select_popup_) {
+ select_popup_->ShowMenu(render_frame_host, bounds, items, selected_item,
+ allow_multiple_selection, right_aligned);
}
}
void WebContentsViewAndroid::HidePopupMenu() {
- if (content_view_core_)
- content_view_core_->HideSelectPopupMenu();
+ if (select_popup_)
+ select_popup_->HideMenu();
}
void WebContentsViewAndroid::StartDragging(
@@ -344,8 +344,8 @@ void WebContentsViewAndroid::StartDragging(
return;
}
- if (content_view_core_)
- content_view_core_->HidePopupsAndPreserveSelection();
+ if (selection_popup_controller_)
+ selection_popup_controller_->HidePopupsAndPreserveSelection();
}
void WebContentsViewAndroid::UpdateDragCursor(blink::WebDragOperation op) {
@@ -487,8 +487,10 @@ bool WebContentsViewAndroid::DoBrowserControlsShrinkBlinkSize() const {
}
bool WebContentsViewAndroid::OnTouchEvent(const ui::MotionEventAndroid& event) {
- if (event.GetAction() == ui::MotionEventAndroid::Action::DOWN)
- content_view_core_->OnTouchDown(event.GetJavaObject());
+ if (event.GetAction() == ui::MotionEventAndroid::Action::DOWN &&
+ ShouldRequestUnbufferedDispatch()) {
+ view_.RequestUnbufferedDispatch(event);
+ }
return false; // let the children handle the actual event.
}
diff --git a/chromium/content/browser/web_contents/web_contents_view_android.h b/chromium/content/browser/web_contents/web_contents_view_android.h
index 830ffe5e7a8..9c21662393b 100644
--- a/chromium/content/browser/web_contents/web_contents_view_android.h
+++ b/chromium/content/browser/web_contents/web_contents_view_android.h
@@ -19,8 +19,9 @@
#include "ui/gfx/geometry/rect_f.h"
namespace content {
-class ContentViewCore;
class RenderWidgetHostViewAndroid;
+class SelectPopup;
+class SelectionPopupController;
class SynchronousCompositorClient;
class WebContentsImpl;
@@ -33,15 +34,17 @@ class WebContentsViewAndroid : public WebContentsView,
WebContentsViewDelegate* delegate);
~WebContentsViewAndroid() override;
- // Sets the interface to the view system. ContentViewCore is owned
- // by its Java ContentViewCore counterpart, whose lifetime is managed
- // by the UI frontend.
- void SetContentViewCore(ContentViewCore* content_view_core);
+ // Sets the object that show/hide popup view for <select> tag.
+ void SetSelectPopup(std::unique_ptr<SelectPopup> select_popup);
void set_synchronous_compositor_client(SynchronousCompositorClient* client) {
synchronous_compositor_client_ = client;
}
+ void set_selection_popup_controller(SelectionPopupController* controller) {
+ selection_popup_controller_ = controller;
+ }
+
SynchronousCompositorClient* synchronous_compositor_client() const {
return synchronous_compositor_client_;
}
@@ -126,9 +129,6 @@ class WebContentsViewAndroid : public WebContentsView,
// The WebContents whose contents we display.
WebContentsImpl* web_contents_;
- // ContentViewCore is our interface to the view system.
- ContentViewCore* content_view_core_;
-
// Handles "overscroll to refresh" events
std::unique_ptr<ui::OverscrollRefreshHandler> overscroll_refresh_handler_;
@@ -141,6 +141,11 @@ class WebContentsViewAndroid : public WebContentsView,
// Interface used to get notified of events from the synchronous compositor.
SynchronousCompositorClient* synchronous_compositor_client_;
+ SelectionPopupController* selection_popup_controller_ = nullptr;
+
+ // Show/hide popup UI for <select> tag.
+ std::unique_ptr<SelectPopup> select_popup_;
+
gfx::PointF drag_location_;
gfx::PointF drag_screen_location_;
diff --git a/chromium/content/browser/web_contents/web_contents_view_aura.cc b/chromium/content/browser/web_contents/web_contents_view_aura.cc
index 5d28247a316..3aea2d29dc4 100644
--- a/chromium/content/browser/web_contents/web_contents_view_aura.cc
+++ b/chromium/content/browser/web_contents/web_contents_view_aura.cc
@@ -11,7 +11,6 @@
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
@@ -51,7 +50,7 @@
#include "content/public/common/content_switches.h"
#include "content/public/common/drop_data.h"
#include "net/base/filename_util.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/client/drag_drop_client.h"
#include "ui/aura/client/drag_drop_delegate.h"
@@ -60,6 +59,7 @@
#include "ui/aura/env.h"
#include "ui/aura/window.h"
#include "ui/aura/window_observer.h"
+#include "ui/aura/window_occlusion_tracker.h"
#include "ui/aura/window_tree_host.h"
#include "ui/aura/window_tree_host_observer.h"
#include "ui/base/clipboard/clipboard.h"
@@ -424,13 +424,10 @@ class WebContentsViewAura::WindowObserver
intptr_t old) override {
if (key != aura::client::kMirroringEnabledKey)
return;
- if (window->GetProperty(aura::client::kMirroringEnabledKey)) {
+ if (window->GetProperty(aura::client::kMirroringEnabledKey))
view_->web_contents_->IncrementCapturerCount(gfx::Size());
- view_->web_contents_->UpdateWebContentsVisibility(true);
- } else {
+ else
view_->web_contents_->DecrementCapturerCount();
- view_->web_contents_->UpdateWebContentsVisibility(window->IsVisible());
- }
}
// Overridden WindowTreeHostObserver:
@@ -497,7 +494,6 @@ WebContentsViewAura::~WebContentsViewAura() {
return;
window_observer_.reset();
- window_->RemoveObserver(this);
// Window needs a valid delegate during its destructor, so we explicitly
// delete it here.
@@ -560,19 +556,20 @@ void WebContentsViewAura::EndDrag(RenderWidgetHost* source_rwh,
void WebContentsViewAura::InstallOverscrollControllerDelegate(
RenderWidgetHostViewAura* view) {
- const OverscrollConfig::Mode mode = OverscrollConfig::GetMode();
+ const OverscrollConfig::HistoryNavigationMode mode =
+ OverscrollConfig::GetHistoryNavigationMode();
switch (mode) {
- case OverscrollConfig::Mode::kDisabled:
+ case OverscrollConfig::HistoryNavigationMode::kDisabled:
navigation_overlay_.reset();
break;
- case OverscrollConfig::Mode::kParallaxUi:
+ case OverscrollConfig::HistoryNavigationMode::kParallaxUi:
view->overscroll_controller()->set_delegate(this);
if (!navigation_overlay_ && !is_mus_browser_plugin_guest_) {
navigation_overlay_.reset(
new OverscrollNavigationOverlay(web_contents_, window_.get()));
}
break;
- case OverscrollConfig::Mode::kSimpleUi:
+ case OverscrollConfig::HistoryNavigationMode::kSimpleUi:
navigation_overlay_.reset();
if (!gesture_nav_simple_)
gesture_nav_simple_.reset(new GestureNavSimple(web_contents_));
@@ -739,7 +736,6 @@ void WebContentsViewAura::CreateAuraWindow(aura::Window* context) {
window_->SetType(aura::client::WINDOW_TYPE_CONTROL);
window_->SetName("WebContentsViewAura");
window_->Init(ui::LAYER_NOT_DRAWN);
- window_->AddObserver(this);
aura::Window* root_window = context ? context->GetRootWindow() : nullptr;
if (root_window) {
// There are places where there is no context currently because object
@@ -754,6 +750,7 @@ void WebContentsViewAura::CreateAuraWindow(aura::Window* context) {
root_window->GetBoundsInScreen());
}
window_->layer()->SetMasksToBounds(true);
+ aura::WindowOcclusionTracker::Track(window_.get());
// WindowObserver is not interesting and is problematic for Browser Plugin
// guests.
@@ -835,8 +832,12 @@ RenderWidgetHostViewBase* WebContentsViewAura::CreateViewForPopupWidget(
}
void WebContentsViewAura::SetPageTitle(const base::string16& title) {
- if (!is_mus_browser_plugin_guest_)
+ if (!is_mus_browser_plugin_guest_) {
window_->SetTitle(title);
+ aura::Window* child_window = GetContentNativeView();
+ if (child_window)
+ child_window->SetTitle(title);
+ }
}
void WebContentsViewAura::RenderViewCreated(RenderViewHost* host) {
@@ -881,11 +882,6 @@ void WebContentsViewAura::ShowContextMenu(RenderFrameHost* render_frame_host,
}
if (delegate_) {
- RenderWidgetHostViewAura* view = ToRenderWidgetHostViewAura(
- web_contents_->GetRenderWidgetHostView());
- if (view && !view->OnShowContextMenu(params))
- return;
-
delegate_->ShowContextMenu(render_frame_host, params);
// WARNING: we may have been deleted during the call to ShowContextMenu().
}
@@ -993,12 +989,6 @@ gfx::Size WebContentsViewAura::GetDisplaySize() const {
.size();
}
-void WebContentsViewAura::OnOverscrollBehaviorUpdate(
- cc::OverscrollBehavior overscroll_behavior) {
- navigation_overlay_->relay_delegate()->OnOverscrollBehaviorUpdate(
- overscroll_behavior);
-}
-
bool WebContentsViewAura::OnOverscrollUpdate(float delta_x, float delta_y) {
if (current_overscroll_gesture_ != OVERSCROLL_EAST &&
current_overscroll_gesture_ != OVERSCROLL_WEST) {
@@ -1013,12 +1003,14 @@ void WebContentsViewAura::OnOverscrollComplete(OverscrollMode mode) {
CompleteOverscrollNavigation(mode);
}
-void WebContentsViewAura::OnOverscrollModeChange(OverscrollMode old_mode,
- OverscrollMode new_mode,
- OverscrollSource source) {
+void WebContentsViewAura::OnOverscrollModeChange(
+ OverscrollMode old_mode,
+ OverscrollMode new_mode,
+ OverscrollSource source,
+ cc::OverscrollBehavior behavior) {
current_overscroll_gesture_ = new_mode;
navigation_overlay_->relay_delegate()->OnOverscrollModeChange(
- old_mode, new_mode, source);
+ old_mode, new_mode, source, behavior);
completed_overscroll_gesture_ = OVERSCROLL_NONE;
}
@@ -1105,6 +1097,16 @@ void WebContentsViewAura::OnWindowDestroyed(aura::Window* window) {
void WebContentsViewAura::OnWindowTargetVisibilityChanged(bool visible) {
}
+void WebContentsViewAura::OnWindowOcclusionChanged(
+ aura::Window::OcclusionState occlusion_state) {
+ web_contents_->UpdateWebContentsVisibility(
+ occlusion_state == aura::Window::OcclusionState::VISIBLE
+ ? content::Visibility::VISIBLE
+ : (occlusion_state == aura::Window::OcclusionState::OCCLUDED
+ ? content::Visibility::OCCLUDED
+ : content::Visibility::HIDDEN));
+}
+
bool WebContentsViewAura::HasHitTestMask() const {
return false;
}
@@ -1276,19 +1278,6 @@ int WebContentsViewAura::OnPerformDrop(const ui::DropTargetEvent& event) {
return ConvertFromWeb(current_drag_op_);
}
-void WebContentsViewAura::OnWindowVisibilityChanged(aura::Window* window,
- bool visible) {
- // Ignore any visibility changes in the hierarchy below.
- if (window != window_.get() && window_->Contains(window))
- return;
-
- // |visible| indicates whether |window| (which points to |window_| or one of
- // its ancestors) is visible within its parent. What we really need is
- // |window_->IsVisible()|, which indicates whether |window_| and all its
- // ancestors are visible.
- web_contents_->UpdateWebContentsVisibility(window_->IsVisible());
-}
-
#if BUILDFLAG(USE_EXTERNAL_POPUP_MENU)
void WebContentsViewAura::ShowPopupMenu(RenderFrameHost* render_frame_host,
const gfx::Rect& bounds,
diff --git a/chromium/content/browser/web_contents/web_contents_view_aura.h b/chromium/content/browser/web_contents/web_contents_view_aura.h
index 50c22b1dfb5..82807c7f77f 100644
--- a/chromium/content/browser/web_contents/web_contents_view_aura.h
+++ b/chromium/content/browser/web_contents/web_contents_view_aura.h
@@ -16,15 +16,11 @@
#include "content/browser/renderer_host/overscroll_controller_delegate.h"
#include "content/browser/renderer_host/render_view_host_delegate_view.h"
#include "content/browser/web_contents/web_contents_view.h"
+#include "content/common/buildflags.h"
#include "content/common/content_export.h"
-#include "content/common/features.h"
#include "ui/aura/client/drag_drop_delegate.h"
+#include "ui/aura/window.h"
#include "ui/aura/window_delegate.h"
-#include "ui/aura/window_observer.h"
-
-namespace aura {
-class Window;
-}
namespace ui {
class DropTargetEvent;
@@ -46,8 +42,7 @@ class CONTENT_EXPORT WebContentsViewAura
public RenderViewHostDelegateView,
public OverscrollControllerDelegate,
public aura::WindowDelegate,
- public aura::client::DragDropDelegate,
- public aura::WindowObserver {
+ public aura::client::DragDropDelegate {
public:
WebContentsViewAura(WebContentsImpl* web_contents,
WebContentsViewDelegate* delegate);
@@ -155,12 +150,12 @@ class CONTENT_EXPORT WebContentsViewAura
// Overridden from OverscrollControllerDelegate:
gfx::Size GetDisplaySize() const override;
- void OnOverscrollBehaviorUpdate(cc::OverscrollBehavior) override;
bool OnOverscrollUpdate(float delta_x, float delta_y) override;
void OnOverscrollComplete(OverscrollMode overscroll_mode) override;
void OnOverscrollModeChange(OverscrollMode old_mode,
OverscrollMode new_mode,
- OverscrollSource source) override;
+ OverscrollSource source,
+ cc::OverscrollBehavior behavior) override;
base::Optional<float> GetMaxOverscrollDelta() const override;
// Overridden from aura::WindowDelegate:
@@ -181,6 +176,8 @@ class CONTENT_EXPORT WebContentsViewAura
void OnWindowDestroying(aura::Window* window) override;
void OnWindowDestroyed(aura::Window* window) override;
void OnWindowTargetVisibilityChanged(bool visible) override;
+ void OnWindowOcclusionChanged(
+ aura::Window::OcclusionState occlusion_state) override;
bool HasHitTestMask() const override;
void GetHitTestMask(gfx::Path* mask) const override;
@@ -194,9 +191,6 @@ class CONTENT_EXPORT WebContentsViewAura
void OnDragExited() override;
int OnPerformDrop(const ui::DropTargetEvent& event) override;
- // Overridden from aura::WindowObserver:
- void OnWindowVisibilityChanged(aura::Window* window, bool visible) override;
-
FRIEND_TEST_ALL_PREFIXES(WebContentsViewAuraTest, EnableDisableOverscroll);
const bool is_mus_browser_plugin_guest_;
diff --git a/chromium/content/browser/web_contents/web_contents_view_aura_browsertest.cc b/chromium/content/browser/web_contents/web_contents_view_aura_browsertest.cc
index 251e0450330..35a9c560d09 100644
--- a/chromium/content/browser/web_contents/web_contents_view_aura_browsertest.cc
+++ b/chromium/content/browser/web_contents/web_contents_view_aura_browsertest.cc
@@ -28,6 +28,7 @@
#include "content/common/input_messages.h"
#include "content/common/view_messages.h"
#include "content/public/browser/browser_message_filter.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/overscroll_configuration.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_widget_host.h"
@@ -36,7 +37,7 @@
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
-#include "content/public/test/scoped_overscroll_mode.h"
+#include "content/public/test/scoped_overscroll_modes.h"
#include "content/public/test/test_renderer_host.h"
#include "content/public/test/test_utils.h"
#include "content/shell/browser/shell.h"
@@ -466,8 +467,8 @@ IN_PROC_BROWSER_TEST_F(WebContentsViewAuraTest,
blink::WebGestureEvent gesture_scroll_begin(
blink::WebGestureEvent::kGestureScrollBegin,
blink::WebInputEvent::kNoModifiers,
- blink::WebInputEvent::GetStaticTimeStampForTests());
- gesture_scroll_begin.source_device = blink::kWebGestureDeviceTouchscreen;
+ blink::WebInputEvent::GetStaticTimeStampForTests(),
+ blink::kWebGestureDeviceTouchscreen);
gesture_scroll_begin.data.scroll_begin.delta_hint_units =
blink::WebGestureEvent::ScrollUnits::kPrecisePixels;
gesture_scroll_begin.data.scroll_begin.delta_x_hint = 0.f;
@@ -477,8 +478,8 @@ IN_PROC_BROWSER_TEST_F(WebContentsViewAuraTest,
blink::WebGestureEvent gesture_scroll_update(
blink::WebGestureEvent::kGestureScrollUpdate,
blink::WebInputEvent::kNoModifiers,
- blink::WebInputEvent::GetStaticTimeStampForTests());
- gesture_scroll_update.source_device = blink::kWebGestureDeviceTouchscreen;
+ blink::WebInputEvent::GetStaticTimeStampForTests(),
+ blink::kWebGestureDeviceTouchscreen);
gesture_scroll_update.data.scroll_update.delta_units =
blink::WebGestureEvent::ScrollUnits::kPrecisePixels;
gesture_scroll_update.data.scroll_update.delta_y = 0.f;
@@ -612,7 +613,8 @@ IN_PROC_BROWSER_TEST_F(WebContentsViewAuraTest,
#define MAYBE_OverscrollScreenshot OverscrollScreenshot
#endif
IN_PROC_BROWSER_TEST_F(WebContentsViewAuraTest, MAYBE_OverscrollScreenshot) {
- ScopedOverscrollMode scoped_mode(OverscrollConfig::Mode::kParallaxUi);
+ ScopedHistoryNavigationMode scoped_mode(
+ OverscrollConfig::HistoryNavigationMode::kParallaxUi);
ASSERT_NO_FATAL_FAILURE(StartTestWithPage("/overscroll_navigation.html"));
WebContentsImpl* web_contents =
@@ -703,7 +705,8 @@ IN_PROC_BROWSER_TEST_F(WebContentsViewAuraTest, MAYBE_OverscrollScreenshot) {
// RenderViewHost to be swapped out.
IN_PROC_BROWSER_TEST_F(WebContentsViewAuraTest,
MAYBE_ScreenshotForSwappedOutRenderViews) {
- ScopedOverscrollMode scoped_mode(OverscrollConfig::Mode::kParallaxUi);
+ ScopedHistoryNavigationMode scoped_mode(
+ OverscrollConfig::HistoryNavigationMode::kParallaxUi);
ASSERT_NO_FATAL_FAILURE(StartTestWithPage("/overscroll_navigation.html"));
// Create a new server with a different site.
@@ -775,7 +778,8 @@ IN_PROC_BROWSER_TEST_F(WebContentsViewAuraTest,
// Tests that navigations resulting from reloads, history.replaceState,
// and history.pushState do not capture screenshots.
IN_PROC_BROWSER_TEST_F(WebContentsViewAuraTest, ReplaceStateReloadPushState) {
- ScopedOverscrollMode scoped_mode(OverscrollConfig::Mode::kParallaxUi);
+ ScopedHistoryNavigationMode scoped_mode(
+ OverscrollConfig::HistoryNavigationMode::kParallaxUi);
ASSERT_NO_FATAL_FAILURE(StartTestWithPage("/overscroll_navigation.html"));
WebContentsImpl* web_contents =
@@ -924,19 +928,6 @@ IN_PROC_BROWSER_TEST_F(WebContentsViewAuraTest,
EXPECT_FALSE(controller.CanGoForward());
}
-// Verify that hiding a parent of the renderer will hide the content too.
-IN_PROC_BROWSER_TEST_F(WebContentsViewAuraTest, HideContentOnParenHide) {
- ASSERT_NO_FATAL_FAILURE(StartTestWithPage("/title1.html"));
- WebContentsImpl* web_contents =
- static_cast<WebContentsImpl*>(shell()->web_contents());
- aura::Window* content = web_contents->GetNativeView()->parent();
- EXPECT_TRUE(web_contents->should_normally_be_visible());
- content->Hide();
- EXPECT_FALSE(web_contents->should_normally_be_visible());
- content->Show();
- EXPECT_TRUE(web_contents->should_normally_be_visible());
-}
-
// Ensure that SnapToPhysicalPixelBoundary() is called on WebContentsView parent
// change. This is a regression test for http://crbug.com/388908.
// Disabled due to flakiness: https://crbug.com/807107.
diff --git a/chromium/content/browser/web_contents/web_contents_view_aura_unittest.cc b/chromium/content/browser/web_contents/web_contents_view_aura_unittest.cc
index fb4d3da9c7e..03d3de9320f 100644
--- a/chromium/content/browser/web_contents/web_contents_view_aura_unittest.cc
+++ b/chromium/content/browser/web_contents/web_contents_view_aura_unittest.cc
@@ -4,16 +4,26 @@
#include "content/browser/web_contents/web_contents_view_aura.h"
+#include <memory>
+
#include "base/command_line.h"
#include "base/test/scoped_command_line.h"
+#include "base/test/scoped_feature_list.h"
#include "content/browser/web_contents/web_contents_impl.h"
+#include "content/public/common/content_features.h"
#include "content/public/test/test_renderer_host.h"
#include "testing/gtest/include/gtest/gtest.h"
+#include "ui/aura/test/test_windows.h"
#include "ui/aura/window.h"
#include "ui/display/display_switches.h"
+#include "ui/gfx/geometry/rect.h"
namespace content {
+namespace {
+constexpr gfx::Rect kBounds = gfx::Rect(0, 0, 20, 20);
+} // namespace
+
class WebContentsViewAuraTest : public RenderViewHostTestHarness {
public:
WebContentsViewAuraTest() = default;
@@ -21,6 +31,8 @@ class WebContentsViewAuraTest : public RenderViewHostTestHarness {
void SetUp() override {
RenderViewHostTestHarness::SetUp();
+ root_window()->SetBounds(kBounds);
+ web_contents()->GetNativeView()->SetBounds(kBounds);
web_contents()->GetNativeView()->Show();
root_window()->AddChild(web_contents()->GetNativeView());
}
@@ -47,4 +59,21 @@ TEST_F(WebContentsViewAuraTest, ShowHideParent) {
EXPECT_EQ(web_contents()->GetVisibility(), content::Visibility::VISIBLE);
}
+TEST_F(WebContentsViewAuraTest, OccludeView) {
+ base::test::ScopedFeatureList scoped_feature_list;
+ scoped_feature_list.InitAndEnableFeature(features::kWebContentsOcclusion);
+
+ // |other_window| occludes |web_contents()| when it's shown.
+ std::unique_ptr<aura::Window> other_window(
+ aura::test::CreateTestWindowWithDelegateAndType(
+ nullptr, aura::client::WINDOW_TYPE_NORMAL, 0, kBounds, root_window(),
+ false));
+
+ EXPECT_EQ(web_contents()->GetVisibility(), Visibility::VISIBLE);
+ other_window->Show();
+ EXPECT_EQ(web_contents()->GetVisibility(), Visibility::OCCLUDED);
+ other_window->Hide();
+ EXPECT_EQ(web_contents()->GetVisibility(), Visibility::VISIBLE);
+}
+
} // namespace content
diff --git a/chromium/content/browser/web_contents/web_contents_view_mac.mm b/chromium/content/browser/web_contents/web_contents_view_mac.mm
index d3533591027..6a9ee15776b 100644
--- a/chromium/content/browser/web_contents/web_contents_view_mac.mm
+++ b/chromium/content/browser/web_contents/web_contents_view_mac.mm
@@ -8,7 +8,6 @@
#include <string>
-#include "base/command_line.h"
#import "base/mac/mac_util.h"
#import "base/mac/scoped_sending_event.h"
#include "base/mac/sdk_forward_declarations.h"
@@ -26,7 +25,6 @@
#include "content/public/browser/interstitial_page.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/browser/web_contents_view_delegate.h"
-#include "content/public/common/content_switches.h"
#include "skia/ext/skia_utils_mac.h"
#import "third_party/mozilla/NSPasteboard+Utils.h"
#include "ui/base/clipboard/custom_data_helper.h"
@@ -665,8 +663,12 @@ void WebContentsViewMac::CloseTab() {
if (!webContents || webContents->IsBeingDestroyed())
return;
- const bool viewVisible = [self window] && ![self isHiddenOrHasHiddenAncestor];
- webContents->UpdateWebContentsVisibility(viewVisible);
+ if ([self isHiddenOrHasHiddenAncestor] || ![self window])
+ webContents->UpdateWebContentsVisibility(content::Visibility::HIDDEN);
+ else if ([[self window] occlusionState] & NSWindowOcclusionStateVisible)
+ webContents->UpdateWebContentsVisibility(content::Visibility::VISIBLE);
+ else
+ webContents->UpdateWebContentsVisibility(content::Visibility::OCCLUDED);
}
- (void)resizeSubviewsWithOldSize:(NSSize)oldBoundsSize {
@@ -687,42 +689,25 @@ void WebContentsViewMac::CloseTab() {
- (void)viewWillMoveToWindow:(NSWindow*)newWindow {
NSWindow* oldWindow = [self window];
-
NSNotificationCenter* notificationCenter =
[NSNotificationCenter defaultCenter];
- // Occlusion is highly undesirable for browser tests, since it will
- // flakily change test behavior.
- static bool isDisabled = base::CommandLine::ForCurrentProcess()->HasSwitch(
- switches::kDisableBackgroundingOccludedWindowsForTesting);
-
- if (!isDisabled) {
- if (oldWindow) {
- [notificationCenter
- removeObserver:self
- name:NSWindowDidChangeOcclusionStateNotification
- object:oldWindow];
- }
- if (newWindow) {
- [notificationCenter
- addObserver:self
- selector:@selector(windowChangedOcclusionState:)
- name:NSWindowDidChangeOcclusionStateNotification
- object:newWindow];
- }
+ if (oldWindow) {
+ [notificationCenter
+ removeObserver:self
+ name:NSWindowDidChangeOcclusionStateNotification
+ object:oldWindow];
+ }
+ if (newWindow) {
+ [notificationCenter addObserver:self
+ selector:@selector(windowChangedOcclusionState:)
+ name:NSWindowDidChangeOcclusionStateNotification
+ object:newWindow];
}
}
- (void)windowChangedOcclusionState:(NSNotification*)notification {
- NSWindow* window = [notification object];
- WebContentsImpl* webContents = [self webContents];
- if (window && webContents && !webContents->IsBeingDestroyed()) {
- if ([window occlusionState] & NSWindowOcclusionStateVisible) {
- webContents->WasUnOccluded();
- } else {
- webContents->WasOccluded();
- }
- }
+ [self updateWebContentsVisibility];
}
- (void)viewDidMoveToWindow {
diff --git a/chromium/content/browser/web_contents/web_contents_view_mac_unittest.mm b/chromium/content/browser/web_contents/web_contents_view_mac_unittest.mm
index 0b1dd34b42b..d18ac92c06e 100644
--- a/chromium/content/browser/web_contents/web_contents_view_mac_unittest.mm
+++ b/chromium/content/browser/web_contents/web_contents_view_mac_unittest.mm
@@ -5,15 +5,23 @@
#import "content/browser/web_contents/web_contents_view_mac.h"
#include "base/mac/scoped_nsobject.h"
+#include "base/macros.h"
+#include "content/public/browser/web_contents.h"
+#include "content/public/test/test_renderer_host.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"
+#include "ui/base/test/cocoa_helper.h"
#import "ui/base/test/cocoa_helper.h"
+namespace content {
+
namespace {
class WebContentsViewCocoaTest : public ui::CocoaTest {
};
+} // namespace
+
TEST_F(WebContentsViewCocoaTest, NonWebDragSourceTest) {
base::scoped_nsobject<WebContentsViewCocoa> view(
[[WebContentsViewCocoa alloc] init]);
@@ -28,4 +36,40 @@ TEST_F(WebContentsViewCocoaTest, NonWebDragSourceTest) {
[view draggingSourceOperationMaskForLocal:NO]);
}
+namespace {
+
+class WebContentsViewMacTest : public RenderViewHostTestHarness {
+ protected:
+ WebContentsViewMacTest() = default;
+
+ void SetUp() override {
+ RenderViewHostTestHarness::SetUp();
+ window_.reset([[CocoaTestHelperWindow alloc] init]);
+ [[window_ contentView] addSubview:web_contents()->GetNativeView()];
+ }
+
+ base::scoped_nsobject<CocoaTestHelperWindow> window_;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(WebContentsViewMacTest);
+};
+
} // namespace
+
+TEST_F(WebContentsViewMacTest, ShowHideParent) {
+ EXPECT_EQ(Visibility::VISIBLE, web_contents()->GetVisibility());
+ [[window_ contentView] setHidden:YES];
+ EXPECT_EQ(Visibility::HIDDEN, web_contents()->GetVisibility());
+ [[window_ contentView] setHidden:NO];
+ EXPECT_EQ(Visibility::VISIBLE, web_contents()->GetVisibility());
+}
+
+TEST_F(WebContentsViewMacTest, OccludeView) {
+ EXPECT_EQ(Visibility::VISIBLE, web_contents()->GetVisibility());
+ [window_ setPretendIsOccluded:YES];
+ EXPECT_EQ(Visibility::OCCLUDED, web_contents()->GetVisibility());
+ [window_ setPretendIsOccluded:NO];
+ EXPECT_EQ(Visibility::VISIBLE, web_contents()->GetVisibility());
+}
+
+} // namespace content
diff --git a/chromium/content/browser/web_contents/web_drag_dest_mac.mm b/chromium/content/browser/web_contents/web_drag_dest_mac.mm
index 35c4ee35242..cec3bd8a97b 100644
--- a/chromium/content/browser/web_contents/web_drag_dest_mac.mm
+++ b/chromium/content/browser/web_contents/web_drag_dest_mac.mm
@@ -16,7 +16,7 @@
#include "content/public/browser/web_drag_dest_delegate.h"
#include "content/public/common/child_process_host.h"
#include "content/public/common/drop_data.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#import "third_party/mozilla/NSPasteboard+Utils.h"
#include "ui/base/clipboard/custom_data_helper.h"
#include "ui/base/cocoa/cocoa_base_utils.h"
diff --git a/chromium/content/browser/web_contents/web_drag_utils_win.h b/chromium/content/browser/web_contents/web_drag_utils_win.h
index 3fd6d099851..d1330205140 100644
--- a/chromium/content/browser/web_contents/web_drag_utils_win.h
+++ b/chromium/content/browser/web_contents/web_drag_utils_win.h
@@ -5,7 +5,7 @@
#ifndef CONTENT_BROWSER_WEB_CONTENTS_WEB_DRAG_UTILS_WIN_H_
#define CONTENT_BROWSER_WEB_CONTENTS_WEB_DRAG_UTILS_WIN_H_
-#include "third_party/WebKit/public/platform/WebDragOperation.h"
+#include "third_party/blink/public/platform/web_drag_operation.h"
#include <windows.h>
diff --git a/chromium/content/browser/web_contents_binding_set_browsertest.cc b/chromium/content/browser/web_contents_binding_set_browsertest.cc
index 3d9ba3d2250..25fb7151b61 100644
--- a/chromium/content/browser/web_contents_binding_set_browsertest.cc
+++ b/chromium/content/browser/web_contents_binding_set_browsertest.cc
@@ -3,7 +3,6 @@
// found in the LICENSE file.
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/browser/web_contents_binding_set.h"
diff --git a/chromium/content/browser/web_package/mock_signed_exchange_handler.cc b/chromium/content/browser/web_package/mock_signed_exchange_handler.cc
index 44f0899e842..2381c3b9e62 100644
--- a/chromium/content/browser/web_package/mock_signed_exchange_handler.cc
+++ b/chromium/content/browser/web_package/mock_signed_exchange_handler.cc
@@ -6,6 +6,7 @@
#include "base/callback.h"
#include "base/strings/stringprintf.h"
+#include "content/browser/web_package/signed_exchange_cert_fetcher_factory.h"
#include "net/filter/source_stream.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_util.h"
@@ -31,7 +32,7 @@ MockSignedExchangeHandler::MockSignedExchangeHandler(
}
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(std::move(headers_callback), error, request_url,
- "GET", head, std::move(body), base::nullopt));
+ "GET", head, std::move(body)));
}
MockSignedExchangeHandler::~MockSignedExchangeHandler() {}
@@ -51,9 +52,7 @@ MockSignedExchangeHandlerFactory::~MockSignedExchangeHandlerFactory() = default;
std::unique_ptr<SignedExchangeHandler> MockSignedExchangeHandlerFactory::Create(
std::unique_ptr<net::SourceStream> body,
ExchangeHeadersCallback headers_callback,
- url::Origin request_initiator,
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory,
- URLLoaderThrottlesGetter url_loader_throttles_getter) {
+ std::unique_ptr<SignedExchangeCertFetcherFactory> cert_fetcher_factory) {
return std::make_unique<MockSignedExchangeHandler>(
error_, request_url_, mime_type_, response_headers_, std::move(body),
std::move(headers_callback));
diff --git a/chromium/content/browser/web_package/mock_signed_exchange_handler.h b/chromium/content/browser/web_package/mock_signed_exchange_handler.h
index cc20f64e3d6..6c7bf97cd14 100644
--- a/chromium/content/browser/web_package/mock_signed_exchange_handler.h
+++ b/chromium/content/browser/web_package/mock_signed_exchange_handler.h
@@ -13,6 +13,8 @@
namespace content {
+class SignedExchangeCertFetcherFactory;
+
class MockSignedExchangeHandler final : public SignedExchangeHandler {
public:
MockSignedExchangeHandler(net::Error error,
@@ -32,8 +34,6 @@ class MockSignedExchangeHandlerFactory final
public:
using ExchangeHeadersCallback =
SignedExchangeHandler::ExchangeHeadersCallback;
- using URLLoaderThrottlesGetter =
- SignedExchangeHandler::URLLoaderThrottlesGetter;
// Creates a factory that creates SignedExchangeHandler which always fires
// a headers callback with the given |error|, |request_url|, |mime_type|
@@ -49,9 +49,8 @@ class MockSignedExchangeHandlerFactory final
std::unique_ptr<SignedExchangeHandler> Create(
std::unique_ptr<net::SourceStream> body,
ExchangeHeadersCallback headers_callback,
- url::Origin request_initiator,
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory,
- URLLoaderThrottlesGetter url_loader_throttles_getter) override;
+ std::unique_ptr<SignedExchangeCertFetcherFactory> cert_fetcher_factory)
+ override;
private:
const net::Error error_;
diff --git a/chromium/content/browser/web_package/signed_exchange_cert_fetcher.cc b/chromium/content/browser/web_package/signed_exchange_cert_fetcher.cc
index d8d7427ce12..30b0a30eb6b 100644
--- a/chromium/content/browser/web_package/signed_exchange_cert_fetcher.cc
+++ b/chromium/content/browser/web_package/signed_exchange_cert_fetcher.cc
@@ -4,16 +4,22 @@
#include "content/browser/web_package/signed_exchange_cert_fetcher.h"
+#include "base/format_macros.h"
#include "base/numerics/safe_conversions.h"
#include "base/strings/string_piece.h"
+#include "base/strings/stringprintf.h"
+#include "base/trace_event/trace_event.h"
+#include "content/browser/loader/resource_dispatcher_host_impl.h"
+#include "content/browser/web_package/signed_exchange_consts.h"
+#include "content/browser/web_package/signed_exchange_utils.h"
#include "content/common/throttling_url_loader.h"
#include "content/public/common/resource_type.h"
-#include "content/public/common/shared_url_loader_factory.h"
#include "content/public/common/url_loader_throttle.h"
#include "ipc/ipc_message.h"
#include "mojo/public/cpp/system/simple_watcher.h"
#include "net/base/load_flags.h"
#include "net/http/http_status_code.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
namespace content {
@@ -53,118 +59,42 @@ const net::NetworkTrafficAnnotationTag kCertFetcherTrafficAnnotation =
"type of request."
)");
-bool ConsumeByte(base::StringPiece* data, uint8_t* out) {
- if (data->empty())
- return false;
- *out = (*data)[0];
- data->remove_prefix(1);
- return true;
-}
-
-bool Consume2Bytes(base::StringPiece* data, uint16_t* out) {
- if (data->size() < 2)
- return false;
- *out = (static_cast<uint8_t>((*data)[0]) << 8) |
- static_cast<uint8_t>((*data)[1]);
- data->remove_prefix(2);
- return true;
-}
-
-bool Consume3Bytes(base::StringPiece* data, uint32_t* out) {
- if (data->size() < 3)
- return false;
- *out = (static_cast<uint8_t>((*data)[0]) << 16) |
- (static_cast<uint8_t>((*data)[1]) << 8) |
- static_cast<uint8_t>((*data)[2]);
- data->remove_prefix(3);
- return true;
-}
-
} // namespace
// static
std::unique_ptr<SignedExchangeCertFetcher>
SignedExchangeCertFetcher::CreateAndStart(
- scoped_refptr<SharedURLLoaderFactory> shared_url_loader_factory,
+ scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory,
std::vector<std::unique_ptr<URLLoaderThrottle>> throttles,
const GURL& cert_url,
url::Origin request_initiator,
bool force_fetch,
- CertificateCallback callback) {
+ CertificateCallback callback,
+ const signed_exchange_utils::LogCallback& error_message_callback) {
+ TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeCertFetcher::CreateAndStart");
std::unique_ptr<SignedExchangeCertFetcher> cert_fetcher(
new SignedExchangeCertFetcher(
std::move(shared_url_loader_factory), std::move(throttles), cert_url,
- std::move(request_initiator), force_fetch, std::move(callback)));
+ std::move(request_initiator), force_fetch, std::move(callback),
+ std::move(error_message_callback)));
cert_fetcher->Start();
return cert_fetcher;
}
-// static
-base::Optional<std::vector<base::StringPiece>>
-SignedExchangeCertFetcher::GetCertChainFromMessage(base::StringPiece message) {
- uint8_t cert_request_context_size = 0;
- if (!ConsumeByte(&message, &cert_request_context_size)) {
- DVLOG(1) << "Can't read certificate request request context size.";
- return base::nullopt;
- }
- if (cert_request_context_size != 0) {
- DVLOG(1) << "Invalid certificate request context size: "
- << static_cast<int>(cert_request_context_size);
- return base::nullopt;
- }
- uint32_t cert_list_size = 0;
- if (!Consume3Bytes(&message, &cert_list_size)) {
- DVLOG(1) << "Can't read certificate list size.";
- return base::nullopt;
- }
-
- if (cert_list_size != message.length()) {
- DVLOG(1) << "Certificate list size error: cert_list_size=" << cert_list_size
- << " remaining=" << message.length();
- return base::nullopt;
- }
-
- std::vector<base::StringPiece> certs;
- while (!message.empty()) {
- uint32_t cert_data_size = 0;
- if (!Consume3Bytes(&message, &cert_data_size)) {
- DVLOG(1) << "Can't read certificate data size.";
- return base::nullopt;
- }
- if (message.length() < cert_data_size) {
- DVLOG(1) << "Certificate data size error: cert_data_size="
- << cert_data_size << " remaining=" << message.length();
- return base::nullopt;
- }
- certs.emplace_back(message.substr(0, cert_data_size));
- message.remove_prefix(cert_data_size);
-
- uint16_t extensions_size = 0;
- if (!Consume2Bytes(&message, &extensions_size)) {
- DVLOG(1) << "Can't read extensions size.";
- return base::nullopt;
- }
- if (message.length() < extensions_size) {
- DVLOG(1) << "Extensions size error: extensions_size=" << extensions_size
- << " remaining=" << message.length();
- return base::nullopt;
- }
- message.remove_prefix(extensions_size);
- }
- return certs;
-}
-
SignedExchangeCertFetcher::SignedExchangeCertFetcher(
- scoped_refptr<SharedURLLoaderFactory> shared_url_loader_factory,
+ scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory,
std::vector<std::unique_ptr<URLLoaderThrottle>> throttles,
const GURL& cert_url,
url::Origin request_initiator,
bool force_fetch,
- CertificateCallback callback)
+ CertificateCallback callback,
+ const signed_exchange_utils::LogCallback& error_message_callback)
: shared_url_loader_factory_(std::move(shared_url_loader_factory)),
throttles_(std::move(throttles)),
resource_request_(std::make_unique<network::ResourceRequest>()),
- callback_(std::move(callback)) {
+ callback_(std::move(callback)),
+ error_message_callback_(std::move(error_message_callback)) {
// TODO(https://crbug.com/803774): Revisit more ResourceRequest flags.
resource_request_->url = cert_url;
resource_request_->request_initiator = std::move(request_initiator);
@@ -186,21 +116,26 @@ SignedExchangeCertFetcher::~SignedExchangeCertFetcher() = default;
void SignedExchangeCertFetcher::Start() {
url_loader_ = ThrottlingURLLoader::CreateLoaderAndStart(
std::move(shared_url_loader_factory_), std::move(throttles_),
- 0 /* routing_id */, 0 /* request_id */,
+ 0 /* routing_id */,
+ ResourceDispatcherHostImpl::Get()->MakeRequestID() /* request_id */,
network::mojom::kURLLoadOptionNone, resource_request_.get(), this,
kCertFetcherTrafficAnnotation, base::ThreadTaskRunnerHandle::Get());
}
void SignedExchangeCertFetcher::Abort() {
+ TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeCertFetcher::Abort");
DCHECK(callback_);
url_loader_ = nullptr;
body_.reset();
handle_watcher_ = nullptr;
body_string_.clear();
- std::move(callback_).Run(scoped_refptr<net::X509Certificate>());
+ std::move(callback_).Run(nullptr);
}
void SignedExchangeCertFetcher::OnHandleReady(MojoResult result) {
+ TRACE_EVENT_BEGIN0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeCertFetcher::OnHandleReady");
const void* buffer = nullptr;
uint32_t num_bytes = 0;
MojoResult rv =
@@ -209,6 +144,9 @@ void SignedExchangeCertFetcher::OnHandleReady(MojoResult result) {
if (body_string_.size() + num_bytes > g_max_cert_size_for_signed_exchange) {
body_->EndReadData(num_bytes);
Abort();
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeCertFetcher::OnHandleReady", error_message_callback_,
+ "The response body size of certificate message exceeds the limit.");
return;
}
body_string_.append(static_cast<const char*>(buffer), num_bytes);
@@ -218,48 +156,70 @@ void SignedExchangeCertFetcher::OnHandleReady(MojoResult result) {
} else {
DCHECK_EQ(MOJO_RESULT_SHOULD_WAIT, rv);
}
+ TRACE_EVENT_END0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeCertFetcher::OnHandleReady");
}
void SignedExchangeCertFetcher::OnDataComplete() {
+ TRACE_EVENT_BEGIN0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeCertFetcher::OnDataComplete");
DCHECK(callback_);
url_loader_ = nullptr;
body_.reset();
handle_watcher_ = nullptr;
- base::Optional<std::vector<base::StringPiece>> der_certs =
- GetCertChainFromMessage(body_string_);
- if (!der_certs) {
- body_string_.clear();
- std::move(callback_).Run(scoped_refptr<net::X509Certificate>());
+
+ std::unique_ptr<SignedExchangeCertificateChain> cert_chain =
+ SignedExchangeCertificateChain::Parse(body_string_);
+ body_string_.clear();
+ if (!cert_chain) {
+ std::move(callback_).Run(nullptr);
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeCertFetcher::OnDataComplete", error_message_callback_,
+ "Failed to get certificate chain from message.");
return;
}
- scoped_refptr<net::X509Certificate> cert =
- net::X509Certificate::CreateFromDERCertChain(*der_certs);
- body_string_.clear();
- std::move(callback_).Run(std::move(cert));
+ std::move(callback_).Run(std::move(cert_chain));
+ TRACE_EVENT_END0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeCertFetcher::OnDataComplete");
}
// network::mojom::URLLoaderClient
void SignedExchangeCertFetcher::OnReceiveResponse(
const network::ResourceResponseHead& head,
- const base::Optional<net::SSLInfo>& ssl_info,
network::mojom::DownloadedTempFilePtr downloaded_file) {
+ TRACE_EVENT_BEGIN0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeCertFetcher::OnReceiveResponse");
if (head.headers->response_code() != net::HTTP_OK) {
Abort();
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeCertFetcher::OnReceiveResponse", error_message_callback_,
+ base::StringPrintf("Invalid reponse code: %d",
+ head.headers->response_code()));
return;
}
if (head.content_length > 0) {
if (base::checked_cast<size_t>(head.content_length) >
g_max_cert_size_for_signed_exchange) {
Abort();
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeCertFetcher::OnReceiveResponse",
+ error_message_callback_,
+ base::StringPrintf("Invalid content length: %" PRIu64,
+ head.content_length));
+
return;
}
body_string_.reserve(head.content_length);
}
+ TRACE_EVENT_END0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeCertFetcher::OnReceiveResponse");
}
void SignedExchangeCertFetcher::OnReceiveRedirect(
const net::RedirectInfo& redirect_info,
const network::ResourceResponseHead& head) {
+ TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeCertFetcher::OnReceiveRedirect");
// Currently the cert fetcher doesn't allow any redirects.
Abort();
}
@@ -291,9 +251,12 @@ void SignedExchangeCertFetcher::OnTransferSizeUpdated(
void SignedExchangeCertFetcher::OnStartLoadingResponseBody(
mojo::ScopedDataPipeConsumerHandle body) {
+ TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeCertFetcher::OnStartLoadingResponseBody");
body_ = std::move(body);
handle_watcher_ = std::make_unique<mojo::SimpleWatcher>(
- FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::AUTOMATIC);
+ FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::AUTOMATIC,
+ base::SequencedTaskRunnerHandle::Get());
handle_watcher_->Watch(
body_.get(), MOJO_HANDLE_SIGNAL_READABLE,
base::BindRepeating(&SignedExchangeCertFetcher::OnHandleReady,
@@ -302,6 +265,8 @@ void SignedExchangeCertFetcher::OnStartLoadingResponseBody(
void SignedExchangeCertFetcher::OnComplete(
const network::URLLoaderCompletionStatus& status) {
+ TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeCertFetcher::OnComplete");
if (!handle_watcher_)
Abort();
}
diff --git a/chromium/content/browser/web_package/signed_exchange_cert_fetcher.h b/chromium/content/browser/web_package/signed_exchange_cert_fetcher.h
index 7925995f74f..55f77debb9d 100644
--- a/chromium/content/browser/web_package/signed_exchange_cert_fetcher.h
+++ b/chromium/content/browser/web_package/signed_exchange_cert_fetcher.h
@@ -8,18 +8,19 @@
#include <string>
#include <vector>
-#include "base/callback_forward.h"
+#include "base/callback.h"
#include "base/callback_helpers.h"
#include "base/memory/weak_ptr.h"
#include "base/optional.h"
-#include "base/strings/string_piece_forward.h"
+#include "content/browser/web_package/signed_exchange_certificate_chain.h"
+#include "content/browser/web_package/signed_exchange_utils.h"
#include "content/common/content_export.h"
#include "services/network/public/mojom/url_loader.mojom.h"
#include "url/origin.h"
-namespace net {
-class X509Certificate;
-} // namespace net
+namespace network {
+class SharedURLLoaderFactory;
+} // namespace network
namespace mojo {
class SimpleWatcher;
@@ -27,7 +28,6 @@ class SimpleWatcher;
namespace content {
-class SharedURLLoaderFactory;
class ThrottlingURLLoader;
class URLLoaderThrottle;
@@ -35,25 +35,24 @@ class CONTENT_EXPORT SignedExchangeCertFetcher
: public network::mojom::URLLoaderClient {
public:
using CertificateCallback =
- base::OnceCallback<void(scoped_refptr<net::X509Certificate>)>;
+ base::OnceCallback<void(std::unique_ptr<SignedExchangeCertificateChain>)>;
// Starts fetching the certificate using a ThrottlingURLLoader created with
// the |shared_url_loader_factory| and the |throttles|. The |callback| will
// be called with the certificate if succeeded. Otherwise it will be called
// with null. If the returned fetcher is destructed before the |callback| is
// called, the request will be canceled and the |callback| will no be called.
+ //
+ // Using SignedExchangeCertFetcherFactory is preferred rather than directly
+ // calling this.
static std::unique_ptr<SignedExchangeCertFetcher> CreateAndStart(
- scoped_refptr<SharedURLLoaderFactory> shared_url_loader_factory,
+ scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory,
std::vector<std::unique_ptr<URLLoaderThrottle>> throttles,
const GURL& cert_url,
url::Origin request_initiator,
bool force_fetch,
- CertificateCallback callback);
-
- // Parses a TLS 1.3 Certificate message containing X.509v3 certificates and
- // returns a vector of cert_data. Returns nullopt when failed to parse.
- static base::Optional<std::vector<base::StringPiece>> GetCertChainFromMessage(
- base::StringPiece message);
+ CertificateCallback callback,
+ const signed_exchange_utils::LogCallback& error_message_callback);
~SignedExchangeCertFetcher() override;
@@ -68,12 +67,13 @@ class CONTENT_EXPORT SignedExchangeCertFetcher
static base::ScopedClosureRunner SetMaxCertSizeForTest(size_t max_cert_size);
SignedExchangeCertFetcher(
- scoped_refptr<SharedURLLoaderFactory> shared_url_loader_factory,
+ scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory,
std::vector<std::unique_ptr<URLLoaderThrottle>> throttles,
const GURL& cert_url,
url::Origin request_initiator,
bool force_fetch,
- CertificateCallback callback);
+ CertificateCallback callback,
+ const signed_exchange_utils::LogCallback& error_message_callback);
void Start();
void Abort();
void OnHandleReady(MojoResult result);
@@ -82,7 +82,6 @@ class CONTENT_EXPORT SignedExchangeCertFetcher
// network::mojom::URLLoaderClient
void OnReceiveResponse(
const network::ResourceResponseHead& head,
- const base::Optional<net::SSLInfo>& ssl_info,
network::mojom::DownloadedTempFilePtr downloaded_file) override;
void OnReceiveRedirect(const net::RedirectInfo& redirect_info,
const network::ResourceResponseHead& head) override;
@@ -96,10 +95,11 @@ class CONTENT_EXPORT SignedExchangeCertFetcher
mojo::ScopedDataPipeConsumerHandle body) override;
void OnComplete(const network::URLLoaderCompletionStatus& status) override;
- scoped_refptr<SharedURLLoaderFactory> shared_url_loader_factory_;
+ scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory_;
std::vector<std::unique_ptr<URLLoaderThrottle>> throttles_;
std::unique_ptr<network::ResourceRequest> resource_request_;
CertificateCallback callback_;
+ signed_exchange_utils::LogCallback error_message_callback_;
std::unique_ptr<ThrottlingURLLoader> url_loader_;
mojo::ScopedDataPipeConsumerHandle body_;
diff --git a/chromium/content/browser/web_package/signed_exchange_cert_fetcher_factory.cc b/chromium/content/browser/web_package/signed_exchange_cert_fetcher_factory.cc
new file mode 100644
index 00000000000..40d63e33e51
--- /dev/null
+++ b/chromium/content/browser/web_package/signed_exchange_cert_fetcher_factory.cc
@@ -0,0 +1,65 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/web_package/signed_exchange_cert_fetcher_factory.h"
+
+#include "content/public/common/url_loader_throttle.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
+
+namespace content {
+
+SignedExchangeCertFetcherFactory::~SignedExchangeCertFetcherFactory() = default;
+
+class SignedExchangeCertFetcherFactoryImpl
+ : public SignedExchangeCertFetcherFactory {
+ public:
+ SignedExchangeCertFetcherFactoryImpl(
+ url::Origin request_initiator,
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
+ URLLoaderThrottlesGetter url_loader_throttles_getter)
+ : request_initiator_(std::move(request_initiator)),
+ url_loader_factory_(std::move(url_loader_factory)),
+ url_loader_throttles_getter_(std::move(url_loader_throttles_getter)) {}
+
+ std::unique_ptr<SignedExchangeCertFetcher> CreateFetcherAndStart(
+ const GURL& cert_url,
+ bool force_fetch,
+ SignedExchangeCertFetcher::CertificateCallback callback,
+ const signed_exchange_utils::LogCallback& error_message_callback)
+ override;
+
+ private:
+ url::Origin request_initiator_;
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
+ URLLoaderThrottlesGetter url_loader_throttles_getter_;
+};
+
+std::unique_ptr<SignedExchangeCertFetcher>
+SignedExchangeCertFetcherFactoryImpl::CreateFetcherAndStart(
+ const GURL& cert_url,
+ bool force_fetch,
+ SignedExchangeCertFetcher::CertificateCallback callback,
+ const signed_exchange_utils::LogCallback& error_message_callback) {
+ DCHECK(url_loader_factory_);
+ DCHECK(url_loader_throttles_getter_);
+ std::vector<std::unique_ptr<URLLoaderThrottle>> throttles =
+ std::move(url_loader_throttles_getter_).Run();
+ return SignedExchangeCertFetcher::CreateAndStart(
+ std::move(url_loader_factory_), std::move(throttles), cert_url,
+ std::move(request_initiator_), force_fetch, std::move(callback),
+ std::move(error_message_callback));
+}
+
+// static
+std::unique_ptr<SignedExchangeCertFetcherFactory>
+SignedExchangeCertFetcherFactory::Create(
+ url::Origin request_initiator,
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
+ URLLoaderThrottlesGetter url_loader_throttles_getter) {
+ return std::make_unique<SignedExchangeCertFetcherFactoryImpl>(
+ std::move(request_initiator), std::move(url_loader_factory),
+ std::move(url_loader_throttles_getter));
+}
+
+} // namespace content
diff --git a/chromium/content/browser/web_package/signed_exchange_cert_fetcher_factory.h b/chromium/content/browser/web_package/signed_exchange_cert_fetcher_factory.h
new file mode 100644
index 00000000000..4567bf09a74
--- /dev/null
+++ b/chromium/content/browser/web_package/signed_exchange_cert_fetcher_factory.h
@@ -0,0 +1,48 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_BROWSER_WEB_PACKAGE_SIGNED_EXCHANGE_CERT_FETCHER_FACTORY_H_
+#define CONTENT_BROWSER_WEB_PACKAGE_SIGNED_EXCHANGE_CERT_FETCHER_FACTORY_H_
+
+#include <memory>
+#include <vector>
+
+#include "base/callback_forward.h"
+#include "content/browser/web_package/signed_exchange_cert_fetcher.h"
+#include "content/browser/web_package/signed_exchange_utils.h"
+#include "content/common/content_export.h"
+#include "url/origin.h"
+
+namespace network {
+class SharedURLLoaderFactory;
+} // namespace network
+
+namespace content {
+
+class SignedExchangeCertFetcher;
+class URLLoaderThrottle;
+
+// An interface for creating SignedExchangeCertFetcher object.
+class CONTENT_EXPORT SignedExchangeCertFetcherFactory {
+ public:
+ virtual ~SignedExchangeCertFetcherFactory();
+ // Creates a SignedExchangeCertFetcher and starts fetching the certificate.
+ // Can be called at most once.
+ virtual std::unique_ptr<SignedExchangeCertFetcher> CreateFetcherAndStart(
+ const GURL& cert_url,
+ bool force_fetch,
+ SignedExchangeCertFetcher::CertificateCallback callback,
+ const signed_exchange_utils::LogCallback& error_message_callback) = 0;
+
+ using URLLoaderThrottlesGetter = base::RepeatingCallback<
+ std::vector<std::unique_ptr<content::URLLoaderThrottle>>()>;
+ static std::unique_ptr<SignedExchangeCertFetcherFactory> Create(
+ url::Origin request_initiator,
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
+ URLLoaderThrottlesGetter url_loader_throttles_getter);
+};
+
+} // namespace content
+
+#endif // CONTENT_BROWSER_WEB_PACKAGE_SIGNED_EXCHANGE_CERT_FETCHER_FACTORY_H_
diff --git a/chromium/content/browser/web_package/signed_exchange_cert_fetcher_unittest.cc b/chromium/content/browser/web_package/signed_exchange_cert_fetcher_unittest.cc
index 00efc6b60c8..ea7c1eba82e 100644
--- a/chromium/content/browser/web_package/signed_exchange_cert_fetcher_unittest.cc
+++ b/chromium/content/browser/web_package/signed_exchange_cert_fetcher_unittest.cc
@@ -4,14 +4,17 @@
#include "content/browser/web_package/signed_exchange_cert_fetcher.h"
+#include "base/callback.h"
#include "base/optional.h"
#include "base/strings/string_piece.h"
#include "base/test/scoped_task_environment.h"
-#include "content/common/weak_wrapper_shared_url_loader_factory.h"
+#include "content/browser/loader/resource_dispatcher_host_impl.h"
+#include "content/browser/web_package/signed_exchange_utils.h"
#include "content/public/common/resource_type.h"
#include "content/public/common/url_loader_throttle.h"
-#include "mojo/common/data_pipe_utils.h"
+#include "content/public/common/weak_wrapper_shared_url_loader_factory.h"
#include "mojo/public/cpp/bindings/binding.h"
+#include "mojo/public/cpp/system/data_pipe_utils.h"
#include "net/base/load_flags.h"
#include "net/cert/x509_util.h"
#include "net/test/cert_test_util.h"
@@ -24,13 +27,6 @@ namespace content {
namespace {
-base::Optional<std::vector<base::StringPiece>> GetCertChain(
- const uint8_t* input,
- size_t input_size) {
- return SignedExchangeCertFetcher::GetCertChainFromMessage(
- base::StringPiece(reinterpret_cast<const char*>(input), input_size));
-}
-
class DeferringURLLoaderThrottle final : public URLLoaderThrottle {
public:
DeferringURLLoaderThrottle() = default;
@@ -133,11 +129,12 @@ class URLLoaderFactoryForMockLoader final
DISALLOW_COPY_AND_ASSIGN(URLLoaderFactoryForMockLoader);
};
-void ForwardCertificateCallback(bool* called,
- scoped_refptr<net::X509Certificate>* out_cert,
- scoped_refptr<net::X509Certificate> cert) {
+void ForwardCertificateCallback(
+ bool* called,
+ std::unique_ptr<SignedExchangeCertificateChain>* out_cert,
+ std::unique_ptr<SignedExchangeCertificateChain> cert_chain) {
*called = true;
- *out_cert = std::move(cert);
+ *out_cert = std::move(cert_chain);
}
class SignedExchangeCertFetcherTest : public testing::Test {
@@ -145,7 +142,10 @@ class SignedExchangeCertFetcherTest : public testing::Test {
SignedExchangeCertFetcherTest()
: url_(GURL("https://www.example.com/cert")),
request_initiator_(
- url::Origin::Create(GURL("https://htxg.example.com/test.htxg"))) {}
+ url::Origin::Create(GURL("https://htxg.example.com/test.htxg"))),
+ resource_dispatcher_host_(CreateDownloadHandlerIntercept(),
+ base::ThreadTaskRunnerHandle::Get(),
+ true /* enable_resource_scheduler */) {}
~SignedExchangeCertFetcherTest() override {}
protected:
@@ -191,8 +191,7 @@ class SignedExchangeCertFetcherTest : public testing::Test {
CreateCertMessage(CreateCertMessageFromCert(*certificate));
mojo::DataPipe data_pipe(message.size());
- CHECK(mojo::common::BlockingCopyFromString(message,
- data_pipe.producer_handle));
+ CHECK(mojo::BlockingCopyFromString(message, data_pipe.producer_handle));
return std::move(data_pipe.consumer_handle);
}
@@ -212,7 +211,7 @@ class SignedExchangeCertFetcherTest : public testing::Test {
base::MakeRefCounted<WeakWrapperSharedURLLoaderFactory>(
&mock_loader_factory_),
std::move(throttles_), url_, request_initiator_, force_fetch,
- std::move(callback));
+ std::move(callback), signed_exchange_utils::LogCallback());
}
void CallOnReceiveResponse() {
@@ -221,8 +220,7 @@ class SignedExchangeCertFetcherTest : public testing::Test {
base::MakeRefCounted<net::HttpResponseHeaders>("HTTP/1.1 200 OK");
mock_loader_factory_.client_ptr()->OnReceiveResponse(
- resource_response, base::Optional<net::SSLInfo>(),
- nullptr /* downloaded_file */);
+ resource_response, nullptr /* downloaded_file */);
}
DeferringURLLoaderThrottle* InitializeDeferringURLLoaderThrottle() {
@@ -238,11 +236,12 @@ class SignedExchangeCertFetcherTest : public testing::Test {
const GURL url_;
const url::Origin request_initiator_;
bool callback_called_ = false;
- scoped_refptr<net::X509Certificate> cert_result_;
+ std::unique_ptr<SignedExchangeCertificateChain> cert_result_;
URLLoaderFactoryForMockLoader mock_loader_factory_;
std::vector<std::unique_ptr<URLLoaderThrottle>> throttles_;
base::test::ScopedTaskEnvironment scoped_task_environment_;
+ ResourceDispatcherHostImpl resource_dispatcher_host_;
private:
DISALLOW_COPY_AND_ASSIGN(SignedExchangeCertFetcherTest);
@@ -250,248 +249,6 @@ class SignedExchangeCertFetcherTest : public testing::Test {
} // namespace
-TEST(SignedExchangeCertFetcherParseTest, OneCert) {
- const uint8_t input[] = {
- // clang-format off
- 0x00, // request context size
- 0x00, 0x00, 0x07, // certificate list size
-
- 0x00, 0x00, 0x02, // cert data size
- 0x11, 0x22, // cert data
- 0x00, 0x00, // extensions size
- // clang-format on
- };
- base::Optional<std::vector<base::StringPiece>> certs =
- GetCertChain(input, arraysize(input));
- ASSERT_TRUE(certs);
- ASSERT_EQ(1u, certs->size());
- const uint8_t kExpected[] = {
- // clang-format off
- 0x11, 0x22, // cert data
- // clang-format on
- };
- EXPECT_THAT((*certs)[0],
- testing::ElementsAreArray(kExpected, arraysize(kExpected)));
-}
-
-TEST(SignedExchangeCertFetcherParseTest, OneCertWithExtension) {
- const uint8_t input[] = {
- // clang-format off
- 0x00, // request context size
- 0x00, 0x00, 0x0A, // certificate list size
-
- 0x00, 0x00, 0x02, // cert data size
- 0x11, 0x22, // cert data
- 0x00, 0x03, // extensions size
- 0xE1, 0xE2, 0xE3, // extensions data
- // clang-format on
- };
- base::Optional<std::vector<base::StringPiece>> certs =
- GetCertChain(input, arraysize(input));
- ASSERT_TRUE(certs);
- ASSERT_EQ(1u, certs->size());
- const uint8_t kExpected[] = {
- // clang-format off
- 0x11, 0x22, // cert data
- // clang-format on
- };
- EXPECT_THAT((*certs)[0],
- testing::ElementsAreArray(kExpected, arraysize(kExpected)));
-}
-
-TEST(SignedExchangeCertFetcherParseTest, TwoCerts) {
- const uint8_t input[] = {
- // clang-format off
- 0x00, // request context size
- 0x00, 0x01, 0x13, // certificate list size
-
- 0x00, 0x01, 0x04, // cert data size
-
- // cert data
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
-
- 0x00, 0x00, // extensions size
-
- 0x00, 0x00, 0x05, // cert data size
- 0x33, 0x44, 0x55, 0x66, 0x77, // cert data
- 0x00, 0x00, // extensions size
-
- // clang-format on
- };
-
- const uint8_t kExpected1[] = {
- // clang-format off
- // cert data
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
- // clang-format on
- };
- const uint8_t kExpected2[] = {
- // clang-format off
- 0x33, 0x44, 0x55, 0x66, 0x77, // cert data
- // clang-format on
- };
-
- base::Optional<std::vector<base::StringPiece>> certs =
- GetCertChain(input, sizeof(input));
- ASSERT_TRUE(certs);
- ASSERT_EQ(2u, certs->size());
- EXPECT_THAT((*certs)[0],
- testing::ElementsAreArray(kExpected1, arraysize(kExpected1)));
- EXPECT_THAT((*certs)[1],
- testing::ElementsAreArray(kExpected2, arraysize(kExpected2)));
-}
-
-TEST(SignedExchangeCertFetcherParseTest, Empty) {
- EXPECT_FALSE(GetCertChain(nullptr, 0));
-}
-
-TEST(SignedExchangeCertFetcherParseTest, InvalidRequestContextSize) {
- const uint8_t input[] = {
- // clang-format off
- 0x01, // request context size: must be zero
- 0x20, // request context
- // clang-format on
- };
- EXPECT_FALSE(GetCertChain(input, arraysize(input)));
-}
-
-TEST(SignedExchangeCertFetcherParseTest, CanNotReadCertListSize1) {
- const uint8_t input[] = {
- // clang-format off
- 0x00, // request context size
- 0x01, // certificate list size: must be 3 bytes
- // clang-format on
- };
- EXPECT_FALSE(GetCertChain(input, arraysize(input)));
-}
-
-TEST(SignedExchangeCertFetcherParseTest, CanNotReadCertListSize2) {
- const uint8_t input[] = {
- // clang-format off
- 0x00, // request context size
- 0x00, 0x01, // certificate list size: must be 3 bytes
- // clang-format on
- };
- EXPECT_FALSE(GetCertChain(input, arraysize(input)));
-}
-
-TEST(SignedExchangeCertFetcherParseTest, CertListSizeError) {
- const uint8_t input[] = {
- // clang-format off
- 0x00, // request context size
- 0x00, 0x01, 0x01, // certificate list size: 257 (This must be 7)
-
- 0x00, 0x00, 0x02, // cert data size
- 0x11, 0x22, // cert data
- 0x00, 0x00, // extensions size
- // clang-format on
- };
- EXPECT_FALSE(GetCertChain(input, arraysize(input)));
-}
-
-TEST(SignedExchangeCertFetcherParseTest, CanNotReadCertDataSize) {
- const uint8_t input[] = {
- // clang-format off
- 0x00, // request context size
- 0x00, 0x00, 0x02, // certificate list size
-
- 0x00, 0x01, // cert data size: must be 3 bytes
- // clang-format on
- };
- EXPECT_FALSE(GetCertChain(input, arraysize(input)));
-}
-
-TEST(SignedExchangeCertFetcherParseTest, CertDataSizeError) {
- const uint8_t input[] = {
- // clang-format off
- 0x00, // request context size
- 0x00, 0x00, 0x04, // certificate list size
-
- 0x00, 0x00, 0x02, // cert data size
- 0x11, // cert data: Need 2 bytes
- // clang-format on
- };
- EXPECT_FALSE(GetCertChain(input, arraysize(input)));
-}
-
-TEST(SignedExchangeCertFetcherParseTest, CanNotReadExtensionsSize) {
- const uint8_t input[] = {
- // clang-format off
- 0x00, // request context size
- 0x00, 0x00, 0x06, // certificate list size
-
- 0x00, 0x00, 0x02, // cert data size
- 0x11, 0x22, // cert data
- 0x00, // extensions size : must be 2 bytes
- // clang-format on
- };
- EXPECT_FALSE(GetCertChain(input, arraysize(input)));
-}
-
-TEST(SignedExchangeCertFetcherParseTest, ExtensionsSizeError) {
- const uint8_t input[] = {
- // clang-format off
- 0x00, // request context size
- 0x00, 0x00, 0x07, // certificate list size
-
- 0x00, 0x00, 0x02, // cert data size
- 0x11, 0x22, // cert data
- 0x00, 0x01, // extensions size
- // clang-format on
- };
- EXPECT_FALSE(GetCertChain(input, arraysize(input)));
-}
-
TEST_F(SignedExchangeCertFetcherTest, Simple) {
std::unique_ptr<SignedExchangeCertFetcher> fetcher =
CreateFetcherAndStart(false /* force_fetch */);
@@ -516,7 +273,7 @@ TEST_F(SignedExchangeCertFetcherTest, Simple) {
EXPECT_TRUE(callback_called_);
ASSERT_TRUE(cert_result_);
EXPECT_EQ(GetTestDataCertFingerprint256(),
- cert_result_->CalculateChainFingerprint256());
+ cert_result_->cert()->CalculateChainFingerprint256());
}
TEST_F(SignedExchangeCertFetcherTest, MultipleChunked) {
@@ -527,13 +284,13 @@ TEST_F(SignedExchangeCertFetcherTest, MultipleChunked) {
const std::string message =
CreateCertMessage(CreateCertMessageFromCert(*certificate));
mojo::DataPipe data_pipe(message.size() / 2 + 1);
- ASSERT_TRUE(mojo::common::BlockingCopyFromString(
+ ASSERT_TRUE(mojo::BlockingCopyFromString(
message.substr(0, message.size() / 2), data_pipe.producer_handle));
mock_loader_factory_.client_ptr()->OnStartLoadingResponseBody(
std::move(data_pipe.consumer_handle));
RunUntilIdle();
- ASSERT_TRUE(mojo::common::BlockingCopyFromString(
- message.substr(message.size() / 2), data_pipe.producer_handle));
+ ASSERT_TRUE(mojo::BlockingCopyFromString(message.substr(message.size() / 2),
+ data_pipe.producer_handle));
data_pipe.producer_handle.reset();
mock_loader_factory_.client_ptr()->OnComplete(
network::URLLoaderCompletionStatus(net::OK));
@@ -542,7 +299,7 @@ TEST_F(SignedExchangeCertFetcherTest, MultipleChunked) {
EXPECT_TRUE(callback_called_);
ASSERT_TRUE(cert_result_);
EXPECT_EQ(certificate->CalculateChainFingerprint256(),
- cert_result_->CalculateChainFingerprint256());
+ cert_result_->cert()->CalculateChainFingerprint256());
}
TEST_F(SignedExchangeCertFetcherTest, ForceFetchAndFail) {
@@ -578,8 +335,7 @@ TEST_F(SignedExchangeCertFetcherTest, MaxCertSize_Exceeds) {
CreateFetcherAndStart(false /* force_fetch */);
CallOnReceiveResponse();
mojo::DataPipe data_pipe(message.size());
- CHECK(
- mojo::common::BlockingCopyFromString(message, data_pipe.producer_handle));
+ CHECK(mojo::BlockingCopyFromString(message, data_pipe.producer_handle));
data_pipe.producer_handle.reset();
mock_loader_factory_.client_ptr()->OnStartLoadingResponseBody(
std::move(data_pipe.consumer_handle));
@@ -602,8 +358,7 @@ TEST_F(SignedExchangeCertFetcherTest, MaxCertSize_SameSize) {
CreateFetcherAndStart(false /* force_fetch */);
CallOnReceiveResponse();
mojo::DataPipe data_pipe(message.size());
- CHECK(
- mojo::common::BlockingCopyFromString(message, data_pipe.producer_handle));
+ CHECK(mojo::BlockingCopyFromString(message, data_pipe.producer_handle));
data_pipe.producer_handle.reset();
mock_loader_factory_.client_ptr()->OnStartLoadingResponseBody(
std::move(data_pipe.consumer_handle));
@@ -626,13 +381,13 @@ TEST_F(SignedExchangeCertFetcherTest, MaxCertSize_MultipleChunked) {
CreateFetcherAndStart(false /* force_fetch */);
CallOnReceiveResponse();
mojo::DataPipe data_pipe(message.size() / 2 + 1);
- ASSERT_TRUE(mojo::common::BlockingCopyFromString(
+ ASSERT_TRUE(mojo::BlockingCopyFromString(
message.substr(0, message.size() / 2), data_pipe.producer_handle));
mock_loader_factory_.client_ptr()->OnStartLoadingResponseBody(
std::move(data_pipe.consumer_handle));
RunUntilIdle();
- ASSERT_TRUE(mojo::common::BlockingCopyFromString(
- message.substr(message.size() / 2), data_pipe.producer_handle));
+ ASSERT_TRUE(mojo::BlockingCopyFromString(message.substr(message.size() / 2),
+ data_pipe.producer_handle));
data_pipe.producer_handle.reset();
mock_loader_factory_.client_ptr()->OnComplete(
network::URLLoaderCompletionStatus(net::OK));
@@ -656,11 +411,9 @@ TEST_F(SignedExchangeCertFetcherTest, MaxCertSize_ContentLengthCheck) {
base::MakeRefCounted<net::HttpResponseHeaders>("HTTP/1.1 200 OK");
resource_response.content_length = message.size();
mock_loader_factory_.client_ptr()->OnReceiveResponse(
- resource_response, base::Optional<net::SSLInfo>(),
- nullptr /* downloaded_file */);
+ resource_response, nullptr /* downloaded_file */);
mojo::DataPipe data_pipe(message.size());
- CHECK(
- mojo::common::BlockingCopyFromString(message, data_pipe.producer_handle));
+ CHECK(mojo::BlockingCopyFromString(message, data_pipe.producer_handle));
data_pipe.producer_handle.reset();
mock_loader_factory_.client_ptr()->OnStartLoadingResponseBody(
std::move(data_pipe.consumer_handle));
@@ -692,8 +445,7 @@ TEST_F(SignedExchangeCertFetcherTest, Abort_404) {
resource_response.headers =
base::MakeRefCounted<net::HttpResponseHeaders>("HTTP/1.1 404 Not Found");
mock_loader_factory_.client_ptr()->OnReceiveResponse(
- resource_response, base::Optional<net::SSLInfo>(),
- nullptr /* downloaded_file */);
+ resource_response, nullptr /* downloaded_file */);
RunUntilIdle();
EXPECT_TRUE(callback_called_);
@@ -706,8 +458,7 @@ TEST_F(SignedExchangeCertFetcherTest, Invalid_CertData) {
CallOnReceiveResponse();
const std::string message = CreateCertMessage("Invalid Cert Data");
mojo::DataPipe data_pipe(message.size());
- CHECK(
- mojo::common::BlockingCopyFromString(message, data_pipe.producer_handle));
+ CHECK(mojo::BlockingCopyFromString(message, data_pipe.producer_handle));
data_pipe.producer_handle.reset();
mock_loader_factory_.client_ptr()->OnStartLoadingResponseBody(
std::move(data_pipe.consumer_handle));
@@ -727,8 +478,7 @@ TEST_F(SignedExchangeCertFetcherTest, Invalid_CertMessage) {
const std::string message = "Invalid cert message";
mojo::DataPipe data_pipe(message.size());
- CHECK(
- mojo::common::BlockingCopyFromString(message, data_pipe.producer_handle));
+ CHECK(mojo::BlockingCopyFromString(message, data_pipe.producer_handle));
data_pipe.producer_handle.reset();
mock_loader_factory_.client_ptr()->OnStartLoadingResponseBody(
std::move(data_pipe.consumer_handle));
@@ -775,7 +525,7 @@ TEST_F(SignedExchangeCertFetcherTest, Throttle_Simple) {
EXPECT_TRUE(callback_called_);
ASSERT_TRUE(cert_result_);
EXPECT_EQ(GetTestDataCertFingerprint256(),
- cert_result_->CalculateChainFingerprint256());
+ cert_result_->cert()->CalculateChainFingerprint256());
}
TEST_F(SignedExchangeCertFetcherTest, Throttle_AbortsOnRequest) {
@@ -881,15 +631,15 @@ TEST_F(SignedExchangeCertFetcherTest, DeleteFetcher_WhileReceivingBody) {
const std::string message =
CreateCertMessage(CreateCertMessageFromCert(*certificate));
mojo::DataPipe data_pipe(message.size() / 2 + 1);
- ASSERT_TRUE(mojo::common::BlockingCopyFromString(
+ ASSERT_TRUE(mojo::BlockingCopyFromString(
message.substr(0, message.size() / 2), data_pipe.producer_handle));
mock_loader_factory_.client_ptr()->OnStartLoadingResponseBody(
std::move(data_pipe.consumer_handle));
RunUntilIdle();
fetcher.reset();
RunUntilIdle();
- ASSERT_TRUE(mojo::common::BlockingCopyFromString(
- message.substr(message.size() / 2), data_pipe.producer_handle));
+ ASSERT_TRUE(mojo::BlockingCopyFromString(message.substr(message.size() / 2),
+ data_pipe.producer_handle));
RunUntilIdle();
EXPECT_FALSE(callback_called_);
@@ -904,8 +654,7 @@ TEST_F(SignedExchangeCertFetcherTest, DeleteFetcher_AfterReceivingBody) {
const std::string message =
CreateCertMessage(CreateCertMessageFromCert(*certificate));
mojo::DataPipe data_pipe(message.size());
- CHECK(
- mojo::common::BlockingCopyFromString(message, data_pipe.producer_handle));
+ CHECK(mojo::BlockingCopyFromString(message, data_pipe.producer_handle));
mock_loader_factory_.client_ptr()->OnStartLoadingResponseBody(
std::move(data_pipe.consumer_handle));
RunUntilIdle();
@@ -950,7 +699,7 @@ TEST_F(SignedExchangeCertFetcherTest, CloseClientPipe_WhileReceivingBody) {
const std::string message =
CreateCertMessage(CreateCertMessageFromCert(*certificate));
mojo::DataPipe data_pipe(message.size() / 2 + 1);
- ASSERT_TRUE(mojo::common::BlockingCopyFromString(
+ ASSERT_TRUE(mojo::BlockingCopyFromString(
message.substr(0, message.size() / 2), data_pipe.producer_handle));
mock_loader_factory_.client_ptr()->OnStartLoadingResponseBody(
std::move(data_pipe.consumer_handle));
@@ -971,8 +720,7 @@ TEST_F(SignedExchangeCertFetcherTest, CloseClientPipe_AfterReceivingBody) {
const std::string message =
CreateCertMessage(CreateCertMessageFromCert(*certificate));
mojo::DataPipe data_pipe(message.size());
- CHECK(
- mojo::common::BlockingCopyFromString(message, data_pipe.producer_handle));
+ CHECK(mojo::BlockingCopyFromString(message, data_pipe.producer_handle));
mock_loader_factory_.client_ptr()->OnStartLoadingResponseBody(
std::move(data_pipe.consumer_handle));
RunUntilIdle();
@@ -984,7 +732,7 @@ TEST_F(SignedExchangeCertFetcherTest, CloseClientPipe_AfterReceivingBody) {
EXPECT_TRUE(callback_called_);
ASSERT_TRUE(cert_result_);
EXPECT_EQ(certificate->CalculateChainFingerprint256(),
- cert_result_->CalculateChainFingerprint256());
+ cert_result_->cert()->CalculateChainFingerprint256());
}
} // namespace content
diff --git a/chromium/content/browser/web_package/signed_exchange_certificate_chain.cc b/chromium/content/browser/web_package/signed_exchange_certificate_chain.cc
new file mode 100644
index 00000000000..ea587d6979d
--- /dev/null
+++ b/chromium/content/browser/web_package/signed_exchange_certificate_chain.cc
@@ -0,0 +1,126 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/web_package/signed_exchange_certificate_chain.h"
+
+#include "base/command_line.h"
+#include "base/memory/ptr_util.h"
+#include "base/trace_event/trace_event.h"
+#include "content/browser/web_package/signed_exchange_consts.h"
+#include "content/public/common/content_switches.h"
+#include "net/cert/x509_certificate.h"
+
+namespace content {
+
+namespace {
+
+bool ConsumeByte(base::StringPiece* data, uint8_t* out) {
+ if (data->empty())
+ return false;
+ *out = (*data)[0];
+ data->remove_prefix(1);
+ return true;
+}
+
+bool Consume2Bytes(base::StringPiece* data, uint16_t* out) {
+ if (data->size() < 2)
+ return false;
+ *out = (static_cast<uint8_t>((*data)[0]) << 8) |
+ static_cast<uint8_t>((*data)[1]);
+ data->remove_prefix(2);
+ return true;
+}
+
+bool Consume3Bytes(base::StringPiece* data, uint32_t* out) {
+ if (data->size() < 3)
+ return false;
+ *out = (static_cast<uint8_t>((*data)[0]) << 16) |
+ (static_cast<uint8_t>((*data)[1]) << 8) |
+ static_cast<uint8_t>((*data)[2]);
+ data->remove_prefix(3);
+ return true;
+}
+
+} // namespace
+
+// static
+std::unique_ptr<SignedExchangeCertificateChain>
+SignedExchangeCertificateChain::Parse(base::StringPiece cert_response_body) {
+ base::Optional<std::vector<base::StringPiece>> der_certs =
+ GetCertChainFromMessage(cert_response_body);
+ if (!der_certs)
+ return nullptr;
+
+ scoped_refptr<net::X509Certificate> cert =
+ net::X509Certificate::CreateFromDERCertChain(*der_certs);
+ if (!cert)
+ return nullptr;
+ return base::WrapUnique(new SignedExchangeCertificateChain(cert));
+}
+
+// static
+base::Optional<std::vector<base::StringPiece>>
+SignedExchangeCertificateChain::GetCertChainFromMessage(
+ base::StringPiece message) {
+ uint8_t cert_request_context_size = 0;
+ if (!ConsumeByte(&message, &cert_request_context_size)) {
+ DVLOG(1) << "Can't read certificate request request context size.";
+ return base::nullopt;
+ }
+ if (cert_request_context_size != 0) {
+ DVLOG(1) << "Invalid certificate request context size: "
+ << static_cast<int>(cert_request_context_size);
+ return base::nullopt;
+ }
+ uint32_t cert_list_size = 0;
+ if (!Consume3Bytes(&message, &cert_list_size)) {
+ DVLOG(1) << "Can't read certificate list size.";
+ return base::nullopt;
+ }
+
+ if (cert_list_size != message.length()) {
+ DVLOG(1) << "Certificate list size error: cert_list_size=" << cert_list_size
+ << " remaining=" << message.length();
+ return base::nullopt;
+ }
+
+ std::vector<base::StringPiece> certs;
+ while (!message.empty()) {
+ uint32_t cert_data_size = 0;
+ if (!Consume3Bytes(&message, &cert_data_size)) {
+ DVLOG(1) << "Can't read certificate data size.";
+ return base::nullopt;
+ }
+ if (message.length() < cert_data_size) {
+ DVLOG(1) << "Certificate data size error: cert_data_size="
+ << cert_data_size << " remaining=" << message.length();
+ return base::nullopt;
+ }
+ certs.emplace_back(message.substr(0, cert_data_size));
+ message.remove_prefix(cert_data_size);
+
+ uint16_t extensions_size = 0;
+ if (!Consume2Bytes(&message, &extensions_size)) {
+ DVLOG(1) << "Can't read extensions size.";
+ return base::nullopt;
+ }
+ if (message.length() < extensions_size) {
+ DVLOG(1) << "Extensions size error: extensions_size=" << extensions_size
+ << " remaining=" << message.length();
+ return base::nullopt;
+ }
+ message.remove_prefix(extensions_size);
+ }
+ return certs;
+}
+
+SignedExchangeCertificateChain::SignedExchangeCertificateChain(
+ scoped_refptr<net::X509Certificate> cert)
+ : cert_(cert) {
+ DCHECK(cert);
+}
+
+SignedExchangeCertificateChain::~SignedExchangeCertificateChain() = default;
+
+} // namespace content
diff --git a/chromium/content/browser/web_package/signed_exchange_certificate_chain.h b/chromium/content/browser/web_package/signed_exchange_certificate_chain.h
new file mode 100644
index 00000000000..d98d57e5e73
--- /dev/null
+++ b/chromium/content/browser/web_package/signed_exchange_certificate_chain.h
@@ -0,0 +1,48 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_BROWSER_WEB_PACKAGE_SIGNED_EXCHANGE_CERTIFICATE_CHAIN_H_
+#define CONTENT_BROWSER_WEB_PACKAGE_SIGNED_EXCHANGE_CERTIFICATE_CHAIN_H_
+
+#include <memory>
+
+#include "base/containers/span.h"
+#include "base/memory/scoped_refptr.h"
+#include "base/optional.h"
+#include "base/strings/string_piece_forward.h"
+#include "content/common/content_export.h"
+
+namespace net {
+class X509Certificate;
+} // namespace net
+
+namespace content {
+
+// SignedExchangeCertificateChain contains all information in signed exchange
+// certificate chain.
+// https://wicg.github.io/webpackage/draft-yasskin-http-origin-signed-responses.html#cert-chain-format
+class CONTENT_EXPORT SignedExchangeCertificateChain {
+ public:
+ static std::unique_ptr<SignedExchangeCertificateChain> Parse(
+ base::StringPiece cert_response_body);
+
+ // Parses a TLS 1.3 Certificate message containing X.509v3 certificates and
+ // returns a vector of cert_data. Returns nullopt when failed to parse.
+ static base::Optional<std::vector<base::StringPiece>> GetCertChainFromMessage(
+ base::StringPiece message);
+
+ ~SignedExchangeCertificateChain();
+
+ const scoped_refptr<net::X509Certificate>& cert() const { return cert_; }
+
+ private:
+ explicit SignedExchangeCertificateChain(
+ scoped_refptr<net::X509Certificate> cert);
+
+ scoped_refptr<net::X509Certificate> cert_;
+};
+
+} // namespace content
+
+#endif // CONTENT_BROWSER_WEB_PACKAGE_SIGNED_EXCHANGE_CERTIFICATE_CHAIN_H_
diff --git a/chromium/content/browser/web_package/signed_exchange_certificate_chain_fuzzer.cc b/chromium/content/browser/web_package/signed_exchange_certificate_chain_fuzzer.cc
new file mode 100644
index 00000000000..e2ccc4ba21e
--- /dev/null
+++ b/chromium/content/browser/web_package/signed_exchange_certificate_chain_fuzzer.cc
@@ -0,0 +1,17 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/web_package/signed_exchange_certificate_chain.h" // nogncheck
+
+#include "base/strings/string_piece.h"
+
+namespace content {
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+ base::StringPiece input(reinterpret_cast<const char*>(data), size);
+ SignedExchangeCertificateChain::GetCertChainFromMessage(input);
+ return 0;
+}
+
+} // namespace content
diff --git a/chromium/content/browser/web_package/signed_exchange_certificate_chain_unittest.cc b/chromium/content/browser/web_package/signed_exchange_certificate_chain_unittest.cc
new file mode 100644
index 00000000000..1dd2681422e
--- /dev/null
+++ b/chromium/content/browser/web_package/signed_exchange_certificate_chain_unittest.cc
@@ -0,0 +1,267 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/web_package/signed_exchange_certificate_chain.h"
+
+#include "base/optional.h"
+#include "base/strings/string_piece.h"
+#include "testing/gmock/include/gmock/gmock.h"
+#include "testing/gtest/include/gtest/gtest.h"
+
+namespace content {
+
+namespace {
+
+base::Optional<std::vector<base::StringPiece>> GetCertChain(
+ const uint8_t* input,
+ size_t input_size) {
+ return SignedExchangeCertificateChain::GetCertChainFromMessage(
+ base::StringPiece(reinterpret_cast<const char*>(input), input_size));
+}
+
+} // namespace
+
+TEST(SignedExchangeCertificateParseTest, OneCert) {
+ const uint8_t input[] = {
+ // clang-format off
+ 0x00, // request context size
+ 0x00, 0x00, 0x07, // certificate list size
+
+ 0x00, 0x00, 0x02, // cert data size
+ 0x11, 0x22, // cert data
+ 0x00, 0x00, // extensions size
+ // clang-format on
+ };
+ base::Optional<std::vector<base::StringPiece>> certs =
+ GetCertChain(input, arraysize(input));
+ ASSERT_TRUE(certs);
+ ASSERT_EQ(1u, certs->size());
+ const uint8_t kExpected[] = {
+ // clang-format off
+ 0x11, 0x22, // cert data
+ // clang-format on
+ };
+ EXPECT_THAT((*certs)[0],
+ testing::ElementsAreArray(kExpected, arraysize(kExpected)));
+}
+
+TEST(SignedExchangeCertificateParseTest, OneCertWithExtension) {
+ const uint8_t input[] = {
+ // clang-format off
+ 0x00, // request context size
+ 0x00, 0x00, 0x0A, // certificate list size
+
+ 0x00, 0x00, 0x02, // cert data size
+ 0x11, 0x22, // cert data
+ 0x00, 0x03, // extensions size
+ 0xE1, 0xE2, 0xE3, // extensions data
+ // clang-format on
+ };
+ base::Optional<std::vector<base::StringPiece>> certs =
+ GetCertChain(input, arraysize(input));
+ ASSERT_TRUE(certs);
+ ASSERT_EQ(1u, certs->size());
+ const uint8_t kExpected[] = {
+ // clang-format off
+ 0x11, 0x22, // cert data
+ // clang-format on
+ };
+ EXPECT_THAT((*certs)[0],
+ testing::ElementsAreArray(kExpected, arraysize(kExpected)));
+}
+
+TEST(SignedExchangeCertificateParseTest, TwoCerts) {
+ const uint8_t input[] = {
+ // clang-format off
+ 0x00, // request context size
+ 0x00, 0x01, 0x13, // certificate list size
+
+ 0x00, 0x01, 0x04, // cert data size
+
+ // cert data
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+
+ 0x00, 0x00, // extensions size
+
+ 0x00, 0x00, 0x05, // cert data size
+ 0x33, 0x44, 0x55, 0x66, 0x77, // cert data
+ 0x00, 0x00, // extensions size
+
+ // clang-format on
+ };
+
+ const uint8_t kExpected1[] = {
+ // clang-format off
+ // cert data
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
+ // clang-format on
+ };
+ const uint8_t kExpected2[] = {
+ // clang-format off
+ 0x33, 0x44, 0x55, 0x66, 0x77, // cert data
+ // clang-format on
+ };
+
+ base::Optional<std::vector<base::StringPiece>> certs =
+ GetCertChain(input, sizeof(input));
+ ASSERT_TRUE(certs);
+ ASSERT_EQ(2u, certs->size());
+ EXPECT_THAT((*certs)[0],
+ testing::ElementsAreArray(kExpected1, arraysize(kExpected1)));
+ EXPECT_THAT((*certs)[1],
+ testing::ElementsAreArray(kExpected2, arraysize(kExpected2)));
+}
+
+TEST(SignedExchangeCertificateParseTest, Empty) {
+ EXPECT_FALSE(GetCertChain(nullptr, 0));
+}
+
+TEST(SignedExchangeCertificateParseTest, InvalidRequestContextSize) {
+ const uint8_t input[] = {
+ // clang-format off
+ 0x01, // request context size: must be zero
+ 0x20, // request context
+ // clang-format on
+ };
+ EXPECT_FALSE(GetCertChain(input, arraysize(input)));
+}
+
+TEST(SignedExchangeCertificateParseTest, CanNotReadCertListSize1) {
+ const uint8_t input[] = {
+ // clang-format off
+ 0x00, // request context size
+ 0x01, // certificate list size: must be 3 bytes
+ // clang-format on
+ };
+ EXPECT_FALSE(GetCertChain(input, arraysize(input)));
+}
+
+TEST(SignedExchangeCertificateParseTest, CanNotReadCertListSize2) {
+ const uint8_t input[] = {
+ // clang-format off
+ 0x00, // request context size
+ 0x00, 0x01, // certificate list size: must be 3 bytes
+ // clang-format on
+ };
+ EXPECT_FALSE(GetCertChain(input, arraysize(input)));
+}
+
+TEST(SignedExchangeCertificateParseTest, CertListSizeError) {
+ const uint8_t input[] = {
+ // clang-format off
+ 0x00, // request context size
+ 0x00, 0x01, 0x01, // certificate list size: 257 (This must be 7)
+
+ 0x00, 0x00, 0x02, // cert data size
+ 0x11, 0x22, // cert data
+ 0x00, 0x00, // extensions size
+ // clang-format on
+ };
+ EXPECT_FALSE(GetCertChain(input, arraysize(input)));
+}
+
+TEST(SignedExchangeCertificateParseTest, CanNotReadCertDataSize) {
+ const uint8_t input[] = {
+ // clang-format off
+ 0x00, // request context size
+ 0x00, 0x00, 0x02, // certificate list size
+
+ 0x00, 0x01, // cert data size: must be 3 bytes
+ // clang-format on
+ };
+ EXPECT_FALSE(GetCertChain(input, arraysize(input)));
+}
+
+TEST(SignedExchangeCertificateParseTest, CertDataSizeError) {
+ const uint8_t input[] = {
+ // clang-format off
+ 0x00, // request context size
+ 0x00, 0x00, 0x04, // certificate list size
+
+ 0x00, 0x00, 0x02, // cert data size
+ 0x11, // cert data: Need 2 bytes
+ // clang-format on
+ };
+ EXPECT_FALSE(GetCertChain(input, arraysize(input)));
+}
+
+TEST(SignedExchangeCertificateParseTest, CanNotReadExtensionsSize) {
+ const uint8_t input[] = {
+ // clang-format off
+ 0x00, // request context size
+ 0x00, 0x00, 0x06, // certificate list size
+
+ 0x00, 0x00, 0x02, // cert data size
+ 0x11, 0x22, // cert data
+ 0x00, // extensions size : must be 2 bytes
+ // clang-format on
+ };
+ EXPECT_FALSE(GetCertChain(input, arraysize(input)));
+}
+
+TEST(SignedExchangeCertificateParseTest, ExtensionsSizeError) {
+ const uint8_t input[] = {
+ // clang-format off
+ 0x00, // request context size
+ 0x00, 0x00, 0x07, // certificate list size
+
+ 0x00, 0x00, 0x02, // cert data size
+ 0x11, 0x22, // cert data
+ 0x00, 0x01, // extensions size
+ // clang-format on
+ };
+ EXPECT_FALSE(GetCertChain(input, arraysize(input)));
+}
+
+} // namespace content
diff --git a/chromium/content/browser/web_package/signed_exchange_consts.h b/chromium/content/browser/web_package/signed_exchange_consts.h
index ad8dcd8afe0..a289b8d015d 100644
--- a/chromium/content/browser/web_package/signed_exchange_consts.h
+++ b/chromium/content/browser/web_package/signed_exchange_consts.h
@@ -7,18 +7,18 @@
namespace content {
-// Field names defined in the application/http-exchange+cbor content type:
-// https://wicg.github.io/webpackage/draft-yasskin-http-origin-signed-responses.html#rfc.section.5
+constexpr char kAcceptHeaderSignedExchangeSuffix[] =
+ ",application/signed-exchange;v=b0";
+
+// Field names defined in the application/signed-exchange content type:
+// https://wicg.github.io/webpackage/draft-yasskin-httpbis-origin-signed-exchanges-impl.html#application-signed-exchange
+
constexpr char kCertSha256Key[] = "certSha256";
constexpr char kDateKey[] = "date";
constexpr char kExpiresKey[] = "expires";
constexpr char kHeadersKey[] = "headers";
-constexpr char kHtxg[] = "htxg";
constexpr char kMethodKey[] = ":method";
-constexpr char kPayload[] = "payload";
-constexpr char kRequest[] = "request";
-constexpr char kResponse[] = "response";
-constexpr char kSignedHeadersName[] = "signed-headers";
+constexpr char kSignature[] = "signature";
constexpr char kStatusKey[] = ":status";
constexpr char kUrlKey[] = ":url";
constexpr char kValidityUrlKey[] = "validityUrl";
diff --git a/chromium/content/browser/web_package/signed_exchange_handler.cc b/chromium/content/browser/web_package/signed_exchange_handler.cc
index da36b355476..d4e878f17b2 100644
--- a/chromium/content/browser/web_package/signed_exchange_handler.cc
+++ b/chromium/content/browser/web_package/signed_exchange_handler.cc
@@ -5,288 +5,404 @@
#include "content/browser/web_package/signed_exchange_handler.h"
#include "base/feature_list.h"
-#include "components/cbor/cbor_reader.h"
+#include "base/strings/stringprintf.h"
+#include "base/time/time.h"
+#include "base/trace_event/trace_event.h"
#include "content/browser/loader/merkle_integrity_source_stream.h"
-#include "content/browser/web_package/signed_exchange_cert_fetcher.h"
+#include "content/browser/web_package/signed_exchange_cert_fetcher_factory.h"
+#include "content/browser/web_package/signed_exchange_certificate_chain.h"
#include "content/browser/web_package/signed_exchange_consts.h"
-#include "content/browser/web_package/signed_exchange_header_parser.h"
+#include "content/browser/web_package/signed_exchange_header.h"
+#include "content/browser/web_package/signed_exchange_signature_verifier.h"
+#include "content/browser/web_package/signed_exchange_utils.h"
+#include "content/public/browser/browser_thread.h"
+#include "content/public/browser/render_frame_host.h"
+#include "content/public/browser/web_contents.h"
#include "content/public/common/content_features.h"
-#include "content/public/common/shared_url_loader_factory.h"
#include "content/public/common/url_loader_throttle.h"
#include "mojo/public/cpp/system/string_data_pipe_producer.h"
#include "net/base/io_buffer.h"
+#include "net/cert/cert_status_flags.h"
+#include "net/cert/cert_verifier.h"
#include "net/cert/x509_certificate.h"
#include "net/filter/source_stream.h"
-#include "net/http/http_response_headers.h"
-#include "net/http/http_util.h"
+#include "net/ssl/ssl_config.h"
+#include "net/ssl/ssl_config_service.h"
+#include "net/ssl/ssl_info.h"
+#include "net/url_request/url_request_context.h"
+#include "net/url_request/url_request_context_getter.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/cpp/resource_response.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/cpp/url_loader_completion_status.h"
namespace content {
namespace {
-constexpr size_t kBufferSizeForRead = 65536;
+// 256KB (Maximum header size) * 2, since signed exchange header contains
+// request and response headers.
+constexpr size_t kMaxHeadersCBORLength = 512 * 1024;
constexpr char kMiHeader[] = "MI";
-cbor::CBORValue BytestringFromString(base::StringPiece in_string) {
- return cbor::CBORValue(
- std::vector<uint8_t>(in_string.begin(), in_string.end()));
-}
+net::CertVerifier* g_cert_verifier_for_testing = nullptr;
+
+base::Optional<base::Time> g_verification_time_for_testing;
-bool IsStringEqualTo(const cbor::CBORValue& value, const char* str) {
- return value.is_string() && value.GetString() == str;
+base::Time GetVerificationTime() {
+ if (g_verification_time_for_testing)
+ return *g_verification_time_for_testing;
+ return base::Time::Now();
}
-// TODO(https://crbug.com/803774): Just for now, remove once we have streaming
-// CBOR parser.
-class BufferSourceStream : public net::SourceStream {
- public:
- BufferSourceStream(const std::vector<uint8_t>& bytes)
- : net::SourceStream(SourceStream::TYPE_NONE), buf_(bytes), ptr_(0u) {}
- int Read(net::IOBuffer* dest_buffer,
- int buffer_size,
- const net::CompletionCallback& callback) override {
- int bytes = std::min(static_cast<int>(buf_.size() - ptr_), buffer_size);
- if (bytes > 0) {
- memcpy(dest_buffer->data(), &buf_[ptr_], bytes);
- ptr_ += bytes;
- }
- return bytes;
+void AddErrorMessageToConsole(int frame_tree_node_id,
+ const std::string& message) {
+ // |frame_tree_node_id| is -1 for unittests.
+ if (frame_tree_node_id == -1)
+ return;
+ if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
+ BrowserThread::PostTask(
+ BrowserThread::UI, FROM_HERE,
+ base::BindOnce(&AddErrorMessageToConsole, frame_tree_node_id, message));
+ return;
}
- std::string Description() const override { return "buffer"; }
-
- private:
- std::vector<uint8_t> buf_;
- size_t ptr_;
-};
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ WebContents* web_contents =
+ WebContents::FromFrameTreeNodeId(frame_tree_node_id);
+ if (!web_contents)
+ return;
+ web_contents->GetMainFrame()->AddMessageToConsole(
+ content::CONSOLE_MESSAGE_LEVEL_ERROR, message);
+}
} // namespace
+// static
+void SignedExchangeHandler::SetCertVerifierForTesting(
+ net::CertVerifier* cert_verifier) {
+ g_cert_verifier_for_testing = cert_verifier;
+}
+
+// static
+void SignedExchangeHandler::SetVerificationTimeForTesting(
+ base::Optional<base::Time> verification_time_for_testing) {
+ g_verification_time_for_testing = verification_time_for_testing;
+}
+
SignedExchangeHandler::SignedExchangeHandler(
+ std::string content_type,
std::unique_ptr<net::SourceStream> body,
ExchangeHeadersCallback headers_callback,
- url::Origin request_initiator,
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory,
- URLLoaderThrottlesGetter url_loader_throttles_getter)
+ std::unique_ptr<SignedExchangeCertFetcherFactory> cert_fetcher_factory,
+ scoped_refptr<net::URLRequestContextGetter> request_context_getter,
+ int frame_tree_node_id)
: headers_callback_(std::move(headers_callback)),
source_(std::move(body)),
- request_initiator_(std::move(request_initiator)),
- url_loader_factory_(std::move(url_loader_factory)),
- url_loader_throttles_getter_(std::move(url_loader_throttles_getter)),
+ cert_fetcher_factory_(std::move(cert_fetcher_factory)),
+ request_context_getter_(std::move(request_context_getter)),
+ net_log_(net::NetLogWithSource::Make(
+ request_context_getter_->GetURLRequestContext()->net_log(),
+ net::NetLogSourceType::CERT_VERIFIER_JOB)),
+ error_message_callback_(
+ base::BindRepeating(&AddErrorMessageToConsole, frame_tree_node_id)),
weak_factory_(this) {
DCHECK(base::FeatureList::IsEnabled(features::kSignedHTTPExchange));
+ TRACE_EVENT_BEGIN0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeHandler::SignedExchangeHandler");
- // Triggering the first read (asynchronously) for CBOR parsing.
- read_buf_ = base::MakeRefCounted<net::IOBufferWithSize>(kBufferSizeForRead);
+ base::Optional<std::string> content_type_version_param;
+ if (!SignedExchangeHeaderParser::GetVersionParamFromContentType(
+ content_type, &content_type_version_param) ||
+ !content_type_version_param || *content_type_version_param != "b0") {
+ base::SequencedTaskRunnerHandle::Get()->PostTask(
+ FROM_HERE, base::BindOnce(&SignedExchangeHandler::RunErrorCallback,
+ weak_factory_.GetWeakPtr(), net::ERR_FAILED));
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeHandler::SignedExchangeHandler", error_message_callback_,
+ base::StringPrintf("Unsupported version of the content type. Currentry "
+ "content type must be "
+ "\"application/signed-exchange;v=b0\". But the "
+ "response content type was \"%s\"",
+ content_type.c_str()));
+ return;
+ }
+
+ // Triggering the read (asynchronously) for the encoded header length.
+ SetupBuffers(SignedExchangeHeader::kEncodedHeaderLengthInBytes);
base::SequencedTaskRunnerHandle::Get()->PostTask(
- FROM_HERE, base::BindOnce(&SignedExchangeHandler::ReadLoop,
+ FROM_HERE, base::BindOnce(&SignedExchangeHandler::DoHeaderLoop,
weak_factory_.GetWeakPtr()));
+ TRACE_EVENT_END0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeCertFetcher::SignedExchangeHandler");
}
SignedExchangeHandler::~SignedExchangeHandler() = default;
-SignedExchangeHandler::SignedExchangeHandler() : weak_factory_(this) {}
+SignedExchangeHandler::SignedExchangeHandler()
+ : error_message_callback_(base::BindRepeating(&AddErrorMessageToConsole,
+ -1 /* frame_tree_node_id */)),
+ weak_factory_(this) {}
+
+void SignedExchangeHandler::SetupBuffers(size_t size) {
+ header_buf_ = base::MakeRefCounted<net::IOBuffer>(size);
+ header_read_buf_ =
+ base::MakeRefCounted<net::DrainableIOBuffer>(header_buf_.get(), size);
+}
-void SignedExchangeHandler::ReadLoop() {
- DCHECK(headers_callback_);
- DCHECK(read_buf_);
+void SignedExchangeHandler::DoHeaderLoop() {
+ DCHECK(state_ == State::kReadingHeadersLength ||
+ state_ == State::kReadingHeaders);
int rv = source_->Read(
- read_buf_.get(), read_buf_->size(),
- base::BindRepeating(&SignedExchangeHandler::DidRead,
+ header_read_buf_.get(), header_read_buf_->BytesRemaining(),
+ base::BindRepeating(&SignedExchangeHandler::DidReadHeader,
base::Unretained(this), false /* sync */));
if (rv != net::ERR_IO_PENDING)
- DidRead(true /* sync */, rv);
+ DidReadHeader(true /* sync */, rv);
}
-void SignedExchangeHandler::DidRead(bool completed_syncly, int result) {
+void SignedExchangeHandler::DidReadHeader(bool completed_syncly, int result) {
+ TRACE_EVENT_BEGIN0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeHandler::DidReadHeader");
if (result < 0) {
- DVLOG(1) << "Error reading body stream: " << result;
RunErrorCallback(static_cast<net::Error>(result));
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeHandler::DidReadHeader", error_message_callback_,
+ base::StringPrintf("Error reading body stream. result: %d", result));
return;
}
if (result == 0) {
- if (!RunHeadersCallback())
- RunErrorCallback(net::ERR_FAILED);
+ RunErrorCallback(net::ERR_FAILED);
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeHandler::DidReadHeader", error_message_callback_,
+ "Stream ended while reading signed exchange header.");
return;
}
- original_body_string_.append(read_buf_->data(), result);
+ header_read_buf_->DidConsume(result);
+ if (header_read_buf_->BytesRemaining() == 0) {
+ switch (state_) {
+ case State::kReadingHeadersLength:
+ if (!ParseHeadersLength())
+ RunErrorCallback(net::ERR_FAILED);
+ break;
+ case State::kReadingHeaders:
+ if (!ParseHeadersAndFetchCertificate())
+ RunErrorCallback(net::ERR_FAILED);
+ break;
+ default:
+ NOTREACHED();
+ }
+ }
+
+ if (state_ != State::kReadingHeadersLength &&
+ state_ != State::kReadingHeaders) {
+ TRACE_EVENT_END1(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeHandler::DidReadHeader", "state",
+ static_cast<int>(state_));
+ return;
+ }
+ // Trigger the next read.
if (completed_syncly) {
base::SequencedTaskRunnerHandle::Get()->PostTask(
- FROM_HERE, base::BindOnce(&SignedExchangeHandler::ReadLoop,
+ FROM_HERE, base::BindOnce(&SignedExchangeHandler::DoHeaderLoop,
weak_factory_.GetWeakPtr()));
} else {
- ReadLoop();
+ DoHeaderLoop();
}
+ TRACE_EVENT_END0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeCertFetcher::DidReadHeader");
}
-bool SignedExchangeHandler::RunHeadersCallback() {
- DCHECK(headers_callback_);
-
- cbor::CBORReader::DecoderError error;
- base::Optional<cbor::CBORValue> root = cbor::CBORReader::Read(
- base::span<const uint8_t>(
- reinterpret_cast<const uint8_t*>(original_body_string_.data()),
- original_body_string_.size()),
- &error);
- if (!root) {
- DVLOG(1) << "CBOR parsing failed: "
- << cbor::CBORReader::ErrorCodeToString(error);
- return false;
- }
- original_body_string_.clear();
-
- if (!root->is_array()) {
- DVLOG(1) << "CBOR root is not an array";
- return false;
- }
- const auto& root_array = root->GetArray();
- if (!IsStringEqualTo(root_array[0], kHtxg)) {
- DVLOG(1) << "CBOR has no htxg signature";
+bool SignedExchangeHandler::ParseHeadersLength() {
+ TRACE_EVENT_BEGIN0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeHandler::ParseHeadersLength");
+ DCHECK_EQ(state_, State::kReadingHeadersLength);
+
+ headers_length_ = SignedExchangeHeader::ParseHeadersLength(
+ base::make_span(reinterpret_cast<uint8_t*>(header_buf_->data()),
+ SignedExchangeHeader::kEncodedHeaderLengthInBytes));
+ if (headers_length_ == 0 || headers_length_ > kMaxHeadersCBORLength) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeHandler::ParseHeadersLength", error_message_callback_,
+ base::StringPrintf("Invalid CBOR header length: %zu", headers_length_));
return false;
}
- if (!IsStringEqualTo(root_array[1], kRequest)) {
- DVLOG(1) << "request field not found";
- return false;
- }
+ // Set up a new buffer for CBOR-encoded buffer reading.
+ SetupBuffers(headers_length_);
+ state_ = State::kReadingHeaders;
+ TRACE_EVENT_END0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeCertFetcher::ParseHeadersLength");
+ return true;
+}
- if (!root_array[2].is_map()) {
- DVLOG(1) << "request field is not a map";
+bool SignedExchangeHandler::ParseHeadersAndFetchCertificate() {
+ TRACE_EVENT_BEGIN0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeHandler::ParseHeadersAndFetchCertificate");
+ DCHECK_EQ(state_, State::kReadingHeaders);
+
+ header_ = SignedExchangeHeader::Parse(
+ base::make_span(reinterpret_cast<uint8_t*>(header_buf_->data()),
+ headers_length_),
+ error_message_callback_);
+ header_read_buf_ = nullptr;
+ header_buf_ = nullptr;
+ if (!header_) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeHandler::ParseHeadersAndFetchCertificate",
+ error_message_callback_, "Failed to parse SignedExchange header.");
return false;
}
- const auto& request_map = root_array[2].GetMap();
- // TODO(https://crbug.com/803774): request payload may come here.
+ const GURL cert_url = header_->signature().cert_url;
+ // TODO(https://crbug.com/819467): When we will support ed25519Key, |cert_url|
+ // may be empty.
+ DCHECK(cert_url.is_valid());
+
+ DCHECK(cert_fetcher_factory_);
+ cert_fetcher_ = std::move(cert_fetcher_factory_)
+ ->CreateFetcherAndStart(
+ cert_url, false,
+ base::BindOnce(&SignedExchangeHandler::OnCertReceived,
+ base::Unretained(this)),
+ error_message_callback_);
+
+ state_ = State::kFetchingCertificate;
+ TRACE_EVENT_END0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeHandler::ParseHeadersAndFetchCertificate");
+ return true;
+}
- if (!IsStringEqualTo(root_array[3], kResponse)) {
- DVLOG(1) << "response field not found";
- return false;
- }
+void SignedExchangeHandler::RunErrorCallback(net::Error error) {
+ DCHECK_NE(state_, State::kHeadersCallbackCalled);
+ std::move(headers_callback_)
+ .Run(error, GURL(), std::string(), network::ResourceResponseHead(),
+ nullptr);
+ state_ = State::kHeadersCallbackCalled;
+}
- if (!root_array[4].is_map()) {
- DVLOG(1) << "response field is not a map";
- return false;
+void SignedExchangeHandler::OnCertReceived(
+ std::unique_ptr<SignedExchangeCertificateChain> cert_chain) {
+ TRACE_EVENT_BEGIN0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeHandler::OnCertReceived");
+ DCHECK_EQ(state_, State::kFetchingCertificate);
+ if (!cert_chain) {
+ RunErrorCallback(net::ERR_FAILED);
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeHandler::OnCertReceived", error_message_callback_,
+ "Failed to fetch the certificate.");
+ return;
}
- const auto& response_map = root_array[4].GetMap();
- if (!IsStringEqualTo(root_array[5], kPayload)) {
- DVLOG(1) << "payload field not found";
- return false;
+ if (SignedExchangeSignatureVerifier::Verify(*header_, cert_chain->cert(),
+ GetVerificationTime(),
+ error_message_callback_) !=
+ SignedExchangeSignatureVerifier::Result::kSuccess) {
+ RunErrorCallback(net::ERR_FAILED);
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeHandler::OnCertReceived", error_message_callback_,
+ "Failed to verify the signed exchange header.");
+ return;
}
-
- if (!root_array[6].is_bytestring()) {
- DVLOG(1) << "payload field is not a bytestring";
- return false;
+ net::URLRequestContext* request_context =
+ request_context_getter_->GetURLRequestContext();
+ if (!request_context) {
+ RunErrorCallback(net::ERR_CONTEXT_SHUT_DOWN);
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeHandler::OnCertReceived", error_message_callback_,
+ "No request context available.");
+ return;
}
- const auto& payload_bytes = root_array[6].GetBytestring();
- auto url_iter = request_map.find(BytestringFromString(kUrlKey));
- if (url_iter == request_map.end() || !url_iter->second.is_bytestring()) {
- DVLOG(1) << ":url is not found or not a bytestring";
- return false;
- }
- request_url_ = GURL(url_iter->second.GetBytestringAsString());
+ unverified_cert_chain_ = std::move(cert_chain);
+
+ net::SSLConfig config;
+ request_context->ssl_config_service()->GetSSLConfig(&config);
+
+ net::CertVerifier* cert_verifier = g_cert_verifier_for_testing
+ ? g_cert_verifier_for_testing
+ : request_context->cert_verifier();
+ // TODO(https://crbug.com/815024): Get the OCSP response from the
+ // “status_request” extension of the main-certificate, and check the lifetime
+ // (nextUpdate - thisUpdate) is less than 7 days.
+ int result = cert_verifier->Verify(
+ net::CertVerifier::RequestParams(
+ unverified_cert_chain_->cert(), header_->request_url().host(),
+ config.GetCertVerifyFlags(), std::string() /* ocsp_response */,
+ net::CertificateList()),
+ net::SSLConfigService::GetCRLSet().get(), &cert_verify_result_,
+ base::BindRepeating(&SignedExchangeHandler::OnCertVerifyComplete,
+ base::Unretained(this)),
+ &cert_verifier_request_, net_log_);
+ // TODO(https://crbug.com/803774): Avoid these recursive patterns by using
+ // explicit state machines (eg: DoLoop() in //net).
+ if (result != net::ERR_IO_PENDING)
+ OnCertVerifyComplete(result);
+
+ TRACE_EVENT_END0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeHandler::OnCertReceived");
+}
- auto method_iter = request_map.find(BytestringFromString(kMethodKey));
- if (method_iter == request_map.end() ||
- !method_iter->second.is_bytestring()) {
- DVLOG(1) << ":method is not found or not a bytestring";
- return false;
- }
- request_method_ = std::string(method_iter->second.GetBytestringAsString());
+void SignedExchangeHandler::OnCertVerifyComplete(int result) {
+ TRACE_EVENT_BEGIN0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeHandler::OnCertVerifyComplete");
- auto status_iter = response_map.find(BytestringFromString(kStatusKey));
- if (status_iter == response_map.end() ||
- !status_iter->second.is_bytestring()) {
- DVLOG(1) << ":status is not found or not a bytestring";
- return false;
- }
- base::StringPiece status_code_str =
- status_iter->second.GetBytestringAsString();
-
- base::Optional<std::vector<SignedExchangeHeaderParser::Signature>> signatures;
-
- std::string fake_header_str("HTTP/1.1 ");
- status_code_str.AppendToString(&fake_header_str);
- fake_header_str.append(" OK\r\n");
- for (const auto& it : response_map) {
- if (!it.first.is_bytestring() || !it.second.is_bytestring()) {
- DVLOG(1) << "Non-bytestring value in the response map";
- return false;
- }
- base::StringPiece name = it.first.GetBytestringAsString();
- base::StringPiece value = it.second.GetBytestringAsString();
- if (name == kMethodKey)
- continue;
-
- name.AppendToString(&fake_header_str);
- fake_header_str.append(": ");
- value.AppendToString(&fake_header_str);
- fake_header_str.append("\r\n");
- if (std::string(name) == "signature") {
- signatures = SignedExchangeHeaderParser::ParseSignature(value);
- }
- }
- fake_header_str.append("\r\n");
- response_head_.headers = base::MakeRefCounted<net::HttpResponseHeaders>(
- net::HttpUtil::AssembleRawHeaders(fake_header_str.c_str(),
- fake_header_str.size()));
- // TODO(https://crbug.com/803774): |mime_type| should be derived from
- // "Content-Type" header.
- response_head_.mime_type = "text/html";
-
- // TODO(https://crbug.com/803774): Check that the Signature header entry has
- // integrity="mi".
- std::string mi_header_value;
- if (!response_head_.headers->EnumerateHeader(nullptr, kMiHeader,
- &mi_header_value)) {
- DVLOG(1) << "Signed exchange has no MI: header";
- return false;
+ if (result != net::OK) {
+ RunErrorCallback(static_cast<net::Error>(result));
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeHandler::OnCertVerifyComplete", error_message_callback_,
+ base::StringPrintf("Certificate verification error: %d", result));
+ return;
}
- auto payload_stream = std::make_unique<BufferSourceStream>(payload_bytes);
- mi_stream_ = std::make_unique<MerkleIntegritySourceStream>(
- mi_header_value, std::move(payload_stream));
-
- if (!signatures || signatures->empty())
- return false;
- DCHECK(url_loader_factory_);
- DCHECK(url_loader_throttles_getter_);
- std::vector<std::unique_ptr<URLLoaderThrottle>> throttles =
- std::move(url_loader_throttles_getter_).Run();
- cert_fetcher_ = SignedExchangeCertFetcher::CreateAndStart(
- std::move(url_loader_factory_), std::move(throttles),
- GURL((*signatures)[0].cert_url), std::move(request_initiator_), false,
- base::BindOnce(&SignedExchangeHandler::OnCertReceived,
- base::Unretained(this)));
- return true;
-}
+ network::ResourceResponseHead response_head;
+ response_head.headers = header_->BuildHttpResponseHeaders();
+ response_head.headers->GetMimeTypeAndCharset(&response_head.mime_type,
+ &response_head.charset);
-void SignedExchangeHandler::RunErrorCallback(net::Error error) {
- DCHECK(headers_callback_);
- std::move(headers_callback_)
- .Run(error, GURL(), std::string(), network::ResourceResponseHead(),
- nullptr, base::nullopt);
-}
+ // TODO(https://crbug.com/803774): Resource timing for signed exchange
+ // loading is not speced yet. https://github.com/WICG/webpackage/issues/156
+ response_head.load_timing.request_start_time = base::Time::Now();
+ base::TimeTicks now(base::TimeTicks::Now());
+ response_head.load_timing.request_start = now;
+ response_head.load_timing.send_start = now;
+ response_head.load_timing.send_end = now;
+ response_head.load_timing.receive_headers_end = now;
-void SignedExchangeHandler::OnCertReceived(
- scoped_refptr<net::X509Certificate> cert) {
- if (!cert) {
- DVLOG(1) << "Fetching certificate error";
+ std::string mi_header_value;
+ if (!response_head.headers->EnumerateHeader(nullptr, kMiHeader,
+ &mi_header_value)) {
RunErrorCallback(net::ERR_FAILED);
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeHandler::OnCertVerifyComplete", error_message_callback_,
+ "Signed exchange has no MI: header");
return;
}
- // TODO(https://crbug.com/803774): Verify the certificate and generate a
- // SSLInfo.
+ auto mi_stream = std::make_unique<MerkleIntegritySourceStream>(
+ mi_header_value, std::move(source_));
+
+ net::SSLInfo ssl_info;
+ ssl_info.cert = cert_verify_result_.verified_cert;
+ ssl_info.unverified_cert = unverified_cert_chain_->cert();
+ ssl_info.cert_status = cert_verify_result_.cert_status;
+ ssl_info.is_issued_by_known_root =
+ cert_verify_result_.is_issued_by_known_root;
+ ssl_info.public_key_hashes = cert_verify_result_.public_key_hashes;
+ ssl_info.ocsp_result = cert_verify_result_.ocsp_result;
+ ssl_info.is_fatal_cert_error =
+ net::IsCertStatusError(ssl_info.cert_status) &&
+ !net::IsCertStatusMinorError(ssl_info.cert_status);
+ response_head.ssl_info = std::move(ssl_info);
+ // TODO(https://crbug.com/815025): Verify the Certificate Transparency status.
std::move(headers_callback_)
- .Run(net::OK, request_url_, request_method_, response_head_,
- std::move(mi_stream_), base::Optional<net::SSLInfo>());
+ .Run(net::OK, header_->request_url(), header_->request_method(),
+ response_head, std::move(mi_stream));
+ state_ = State::kHeadersCallbackCalled;
+ TRACE_EVENT_END0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeHandler::OnCertVerifyComplete");
}
} // namespace content
diff --git a/chromium/content/browser/web_package/signed_exchange_handler.h b/chromium/content/browser/web_package/signed_exchange_handler.h
index 648fb01f08c..84f9fe4bd6f 100644
--- a/chromium/content/browser/web_package/signed_exchange_handler.h
+++ b/chromium/content/browser/web_package/signed_exchange_handler.h
@@ -9,91 +9,122 @@
#include "base/callback.h"
#include "base/optional.h"
+#include "base/time/time.h"
+#include "content/browser/web_package/signed_exchange_header.h"
+#include "content/browser/web_package/signed_exchange_utils.h"
#include "content/common/content_export.h"
-#include "content/public/common/shared_url_loader_factory.h"
#include "mojo/public/cpp/system/data_pipe.h"
#include "net/base/completion_callback.h"
-#include "net/ssl/ssl_info.h"
-#include "services/network/public/cpp/resource_response.h"
+#include "net/cert/cert_verifier.h"
+#include "net/cert/cert_verify_result.h"
+#include "net/log/net_log_with_source.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "url/gurl.h"
#include "url/origin.h"
namespace net {
+class CertVerifier;
+class CertVerifyResult;
+class DrainableIOBuffer;
class SourceStream;
-}
+class URLRequestContextGetter;
+} // namespace net
+
+namespace network {
+struct ResourceResponseHead;
+} // namespace network
namespace content {
-class SharedURLLoaderFactory;
class SignedExchangeCertFetcher;
-class URLLoaderThrottle;
-class MerkleIntegritySourceStream;
+class SignedExchangeCertFetcherFactory;
+class SignedExchangeCertificateChain;
-// IMPORTANT: Currenly SignedExchangeHandler doesn't implement any verifying
+// IMPORTANT: Currenly SignedExchangeHandler partially implements the verifying
// logic.
// TODO(https://crbug.com/803774): Implement verifying logic.
class CONTENT_EXPORT SignedExchangeHandler {
public:
// TODO(https://crbug.com/803774): Add verification status here.
- using ExchangeHeadersCallback =
- base::OnceCallback<void(net::Error error,
- const GURL& request_url,
- const std::string& request_method,
- const network::ResourceResponseHead&,
- std::unique_ptr<net::SourceStream> payload_stream,
- base::Optional<net::SSLInfo>)>;
+ using ExchangeHeadersCallback = base::OnceCallback<void(
+ net::Error error,
+ const GURL& request_url,
+ const std::string& request_method,
+ const network::ResourceResponseHead&,
+ std::unique_ptr<net::SourceStream> payload_stream)>;
+
+ // TODO(https://crbug.com/817187): Find a more sophisticated way to use a
+ // MockCertVerifier in browser tests instead of using the static method.
+ static void SetCertVerifierForTesting(net::CertVerifier* cert_verifier);
- using URLLoaderThrottlesGetter = base::RepeatingCallback<
- std::vector<std::unique_ptr<content::URLLoaderThrottle>>()>;
+ static void SetVerificationTimeForTesting(
+ base::Optional<base::Time> verification_time_for_testing);
// Once constructed |this| starts reading the |body| and parses the response
// as a signed HTTP exchange. The response body of the exchange can be read
- // from |payload_stream| passed to |headers_callback|. |url_loader_factory|
- // and |url_loader_throttles_getter| are used to set up a network URLLoader to
- // actually fetch the certificate.
+ // from |payload_stream| passed to |headers_callback|. |cert_fetcher_factory|
+ // is used to create a SignedExchangeCertFetcher that fetches the certificate.
SignedExchangeHandler(
+ std::string content_type,
std::unique_ptr<net::SourceStream> body,
ExchangeHeadersCallback headers_callback,
- url::Origin request_initiator,
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory,
- URLLoaderThrottlesGetter url_loader_throttles_getter);
+ std::unique_ptr<SignedExchangeCertFetcherFactory> cert_fetcher_factory,
+ scoped_refptr<net::URLRequestContextGetter> request_context_getter,
+ int frame_tree_node_id);
~SignedExchangeHandler();
protected:
SignedExchangeHandler();
private:
- void ReadLoop();
- void DidRead(bool completed_syncly, int result);
- bool RunHeadersCallback();
+ enum class State {
+ kReadingHeadersLength,
+ kReadingHeaders,
+ kFetchingCertificate,
+ kHeadersCallbackCalled,
+ };
+
+ void SetupBuffers(size_t size);
+ void DoHeaderLoop();
+ void DidReadHeader(bool completed_syncly, int result);
+ bool ParseHeadersLength();
+ bool ParseHeadersAndFetchCertificate();
void RunErrorCallback(net::Error);
- void OnCertReceived(scoped_refptr<net::X509Certificate> cert);
-
- // Signed exchange contents.
- GURL request_url_;
- std::string request_method_;
- network::ResourceResponseHead response_head_;
+ void OnCertReceived(
+ std::unique_ptr<SignedExchangeCertificateChain> cert_chain);
+ void OnCertVerifyComplete(int result);
ExchangeHeadersCallback headers_callback_;
std::unique_ptr<net::SourceStream> source_;
- // TODO(https://crbug.cxom/803774): Just for now. Implement the streaming
- // parser.
- scoped_refptr<net::IOBufferWithSize> read_buf_;
- std::string original_body_string_;
+ State state_ = State::kReadingHeadersLength;
+ // Buffer used for header reading.
+ scoped_refptr<net::IOBuffer> header_buf_;
+ // Wrapper around |header_buf_| to progressively read fixed-size data.
+ scoped_refptr<net::DrainableIOBuffer> header_read_buf_;
+ size_t headers_length_ = 0;
- std::unique_ptr<MerkleIntegritySourceStream> mi_stream_;
-
- // Used to create |cert_fetcher_|.
- url::Origin request_initiator_;
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory_;
- // This getter is guaranteed to be valid at least until the headers callback
- // is run.
- URLLoaderThrottlesGetter url_loader_throttles_getter_;
+ base::Optional<SignedExchangeHeader> header_;
+ std::unique_ptr<SignedExchangeCertFetcherFactory> cert_fetcher_factory_;
std::unique_ptr<SignedExchangeCertFetcher> cert_fetcher_;
+ scoped_refptr<net::URLRequestContextGetter> request_context_getter_;
+
+ std::unique_ptr<SignedExchangeCertificateChain> unverified_cert_chain_;
+
+ // CertVerifyResult must be freed after the Request has been destructed.
+ // So |cert_verify_result_| must be written before |cert_verifier_request_|.
+ net::CertVerifyResult cert_verify_result_;
+ std::unique_ptr<net::CertVerifier::Request> cert_verifier_request_;
+
+ // TODO(https://crbug.com/767450): figure out what we should do for NetLog
+ // with Network Service.
+ net::NetLogWithSource net_log_;
+
+ signed_exchange_utils::LogCallback error_message_callback_;
+
base::WeakPtrFactory<SignedExchangeHandler> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(SignedExchangeHandler);
@@ -107,10 +138,8 @@ class SignedExchangeHandlerFactory {
virtual std::unique_ptr<SignedExchangeHandler> Create(
std::unique_ptr<net::SourceStream> body,
SignedExchangeHandler::ExchangeHeadersCallback headers_callback,
- url::Origin request_initiator,
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory,
- SignedExchangeHandler::URLLoaderThrottlesGetter
- url_loader_throttles_getter) = 0;
+ std::unique_ptr<SignedExchangeCertFetcherFactory>
+ cert_fetcher_factory) = 0;
};
} // namespace content
diff --git a/chromium/content/browser/web_package/signed_exchange_handler_unittest.cc b/chromium/content/browser/web_package/signed_exchange_handler_unittest.cc
new file mode 100644
index 00000000000..fbcb5b29a0b
--- /dev/null
+++ b/chromium/content/browser/web_package/signed_exchange_handler_unittest.cc
@@ -0,0 +1,355 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/web_package/signed_exchange_handler.h"
+
+#include "base/bind.h"
+#include "base/callback.h"
+#include "base/files/file_path.h"
+#include "base/files/file_util.h"
+#include "base/path_service.h"
+#include "base/test/scoped_feature_list.h"
+#include "base/test/scoped_task_environment.h"
+#include "content/browser/web_package/signed_exchange_cert_fetcher_factory.h"
+#include "content/browser/web_package/signed_exchange_utils.h"
+#include "content/public/common/content_features.h"
+#include "content/public/common/content_paths.h"
+#include "net/base/io_buffer.h"
+#include "net/base/test_completion_callback.h"
+#include "net/cert/mock_cert_verifier.h"
+#include "net/filter/mock_source_stream.h"
+#include "net/test/cert_test_util.h"
+#include "net/test/test_data_directory.h"
+#include "net/url_request/url_request_test_util.h"
+#include "testing/gtest/include/gtest/gtest.h"
+
+namespace content {
+
+namespace {
+
+const uint64_t kSignatureHeaderDate = 1520834000;
+const int kOutputBufferSize = 4096;
+
+std::string GetTestFileContents(base::StringPiece name) {
+ base::FilePath path;
+ PathService::Get(content::DIR_TEST_DATA, &path);
+ path = path.AppendASCII("htxg").AppendASCII(name);
+
+ std::string contents;
+ CHECK(base::ReadFileToString(path, &contents));
+ return contents;
+}
+
+scoped_refptr<net::X509Certificate> LoadCertificate(
+ const std::string& cert_file) {
+ base::ScopedAllowBlockingForTesting allow_io;
+ return net::CreateCertificateChainFromFile(
+ net::GetTestCertsDirectory(), cert_file,
+ net::X509Certificate::FORMAT_PEM_CERT_SEQUENCE);
+}
+
+class MockSignedExchangeCertFetcherFactory
+ : public SignedExchangeCertFetcherFactory {
+ public:
+ void ExpectFetch(const GURL& cert_url, const std::string& cert_str) {
+ expected_cert_url_ = cert_url;
+ cert_str_ = cert_str;
+ }
+
+ std::unique_ptr<SignedExchangeCertFetcher> CreateFetcherAndStart(
+ const GURL& cert_url,
+ bool force_fetch,
+ SignedExchangeCertFetcher::CertificateCallback callback,
+ const signed_exchange_utils::LogCallback& error_message_callback)
+ override {
+ EXPECT_EQ(cert_url, expected_cert_url_);
+
+ auto cert_chain = SignedExchangeCertificateChain::Parse(cert_str_);
+ EXPECT_TRUE(cert_chain);
+
+ base::SequencedTaskRunnerHandle::Get()->PostTask(
+ FROM_HERE, base::BindOnce(std::move(callback), std::move(cert_chain)));
+ return nullptr;
+ }
+
+ private:
+ GURL expected_cert_url_;
+ std::string cert_str_;
+};
+
+} // namespace
+
+class SignedExchangeHandlerTest
+ : public ::testing::TestWithParam<net::MockSourceStream::Mode> {
+ public:
+ SignedExchangeHandlerTest()
+ : mock_cert_verifier_(std::make_unique<net::MockCertVerifier>()),
+ request_initiator_(
+ url::Origin::Create(GURL("https://htxg.example.com/test.htxg"))) {}
+
+ void SetUp() override {
+ SignedExchangeHandler::SetCertVerifierForTesting(mock_cert_verifier_.get());
+ SignedExchangeHandler::SetVerificationTimeForTesting(
+ base::Time::UnixEpoch() +
+ base::TimeDelta::FromSeconds(kSignatureHeaderDate));
+ feature_list_.InitAndEnableFeature(features::kSignedHTTPExchange);
+
+ std::unique_ptr<net::MockSourceStream> source(new net::MockSourceStream());
+ source->set_read_one_byte_at_a_time(true);
+ source_ = source.get();
+ auto cert_fetcher_factory =
+ std::make_unique<MockSignedExchangeCertFetcherFactory>();
+ mock_cert_fetcher_factory_ = cert_fetcher_factory.get();
+ request_context_getter_ = new net::TestURLRequestContextGetter(
+ scoped_task_environment_.GetMainThreadTaskRunner());
+ handler_ = std::make_unique<SignedExchangeHandler>(
+ "application/signed-exchange;v=b0", std::move(source),
+ base::BindOnce(&SignedExchangeHandlerTest::OnHeaderFound,
+ base::Unretained(this)),
+ std::move(cert_fetcher_factory), request_context_getter_,
+ -1 /* frame_tree_node_id */);
+ }
+
+ void TearDown() override {
+ SignedExchangeHandler::SetCertVerifierForTesting(nullptr);
+ SignedExchangeHandler::SetVerificationTimeForTesting(
+ base::Optional<base::Time>());
+ }
+
+ // Reads from |stream| until an error occurs or the EOF is reached.
+ // When an error occurs, returns the net error code. When an EOF is reached,
+ // returns the number of bytes read. If |output| is non-null, appends data
+ // read to it.
+ int ReadStream(net::SourceStream* stream, std::string* output) {
+ scoped_refptr<net::IOBuffer> output_buffer =
+ new net::IOBuffer(kOutputBufferSize);
+ int bytes_read = 0;
+ while (true) {
+ net::TestCompletionCallback callback;
+ int rv = stream->Read(output_buffer.get(), kOutputBufferSize,
+ callback.callback());
+ if (rv == net::ERR_IO_PENDING) {
+ while (source_->awaiting_completion())
+ source_->CompleteNextRead();
+ rv = callback.WaitForResult();
+ }
+ if (rv == net::OK)
+ break;
+ if (rv < net::OK)
+ return rv;
+ EXPECT_GT(rv, net::OK);
+ bytes_read += rv;
+ if (output)
+ output->append(output_buffer->data(), rv);
+ }
+ return bytes_read;
+ }
+
+ int ReadPayloadStream(std::string* output) {
+ return ReadStream(payload_stream_.get(), output);
+ }
+
+ bool read_header() const { return read_header_; }
+ net::Error error() const { return error_; }
+ const network::ResourceResponseHead& resource_response() const {
+ return resource_response_;
+ }
+
+ void WaitForHeader() {
+ while (!read_header()) {
+ while (source_->awaiting_completion())
+ source_->CompleteNextRead();
+ scoped_task_environment_.RunUntilIdle();
+ }
+ }
+
+ protected:
+ MockSignedExchangeCertFetcherFactory* mock_cert_fetcher_factory_;
+ std::unique_ptr<net::MockCertVerifier> mock_cert_verifier_;
+ net::MockSourceStream* source_;
+ std::unique_ptr<SignedExchangeHandler> handler_;
+
+ private:
+ void OnHeaderFound(net::Error error,
+ const GURL&,
+ const std::string&,
+ const network::ResourceResponseHead& resource_response,
+ std::unique_ptr<net::SourceStream> payload_stream) {
+ read_header_ = true;
+ error_ = error;
+ resource_response_ = resource_response;
+ payload_stream_ = std::move(payload_stream);
+ }
+
+ base::test::ScopedFeatureList feature_list_;
+ base::test::ScopedTaskEnvironment scoped_task_environment_;
+ scoped_refptr<net::TestURLRequestContextGetter> request_context_getter_;
+ const url::Origin request_initiator_;
+
+ bool read_header_ = false;
+ net::Error error_;
+ network::ResourceResponseHead resource_response_;
+ std::unique_ptr<net::SourceStream> payload_stream_;
+};
+
+TEST_P(SignedExchangeHandlerTest, Empty) {
+ source_->AddReadResult(nullptr, 0, net::OK, GetParam());
+
+ WaitForHeader();
+
+ ASSERT_TRUE(read_header());
+ EXPECT_EQ(net::ERR_FAILED, error());
+}
+
+TEST_P(SignedExchangeHandlerTest, Simple) {
+ mock_cert_fetcher_factory_->ExpectFetch(
+ GURL("https://cert.example.org/cert.msg"),
+ GetTestFileContents("wildcard_example.org.public.pem.msg"));
+
+ // Make the MockCertVerifier treat the certificate "wildcard.pem" as valid for
+ // "*.example.org".
+ scoped_refptr<net::X509Certificate> original_cert =
+ LoadCertificate("wildcard.pem");
+ net::CertVerifyResult dummy_result;
+ dummy_result.verified_cert = original_cert;
+ dummy_result.cert_status = net::OK;
+ mock_cert_verifier_->AddResultForCertAndHost(original_cert, "*.example.org",
+ dummy_result, net::OK);
+
+ std::string contents = GetTestFileContents("test.example.org_test.htxg");
+ source_->AddReadResult(contents.data(), contents.size(), net::OK, GetParam());
+ source_->AddReadResult(nullptr, 0, net::OK, GetParam());
+
+ WaitForHeader();
+
+ ASSERT_TRUE(read_header());
+ EXPECT_EQ(net::OK, error());
+ EXPECT_EQ(200, resource_response().headers->response_code());
+ EXPECT_EQ("text/html", resource_response().mime_type);
+ EXPECT_EQ("utf-8", resource_response().charset);
+ EXPECT_FALSE(resource_response().load_timing.request_start_time.is_null());
+ EXPECT_FALSE(resource_response().load_timing.request_start.is_null());
+ EXPECT_FALSE(resource_response().load_timing.send_start.is_null());
+ EXPECT_FALSE(resource_response().load_timing.send_end.is_null());
+ EXPECT_FALSE(resource_response().load_timing.receive_headers_end.is_null());
+
+ std::string payload;
+ int rv = ReadPayloadStream(&payload);
+
+ std::string expected_payload = GetTestFileContents("test.html");
+
+ EXPECT_EQ(payload, expected_payload);
+ EXPECT_EQ(rv, static_cast<int>(expected_payload.size()));
+}
+
+TEST_P(SignedExchangeHandlerTest, MimeType) {
+ mock_cert_fetcher_factory_->ExpectFetch(
+ GURL("https://cert.example.org/cert.msg"),
+ GetTestFileContents("wildcard_example.org.public.pem.msg"));
+
+ mock_cert_verifier_->set_default_result(net::OK);
+ std::string contents = GetTestFileContents("test.example.org_hello.txt.htxg");
+ source_->AddReadResult(contents.data(), contents.size(), net::OK, GetParam());
+ source_->AddReadResult(nullptr, 0, net::OK, GetParam());
+
+ WaitForHeader();
+
+ ASSERT_TRUE(read_header());
+ EXPECT_EQ(net::OK, error());
+ EXPECT_EQ(200, resource_response().headers->response_code());
+ EXPECT_EQ("text/plain", resource_response().mime_type);
+ EXPECT_EQ("iso-8859-1", resource_response().charset);
+
+ std::string payload;
+ int rv = ReadPayloadStream(&payload);
+
+ std::string expected_payload = GetTestFileContents("hello.txt");
+
+ EXPECT_EQ(payload, expected_payload);
+ EXPECT_EQ(rv, static_cast<int>(expected_payload.size()));
+}
+
+TEST_P(SignedExchangeHandlerTest, ParseError) {
+ const uint8_t data[] = {0x00, 0x00, 0x01, 0x00};
+ source_->AddReadResult(reinterpret_cast<const char*>(data), sizeof(data),
+ net::OK, GetParam());
+ WaitForHeader();
+
+ ASSERT_TRUE(read_header());
+ EXPECT_EQ(net::ERR_FAILED, error());
+}
+
+TEST_P(SignedExchangeHandlerTest, TruncatedInHeader) {
+ std::string contents = GetTestFileContents("test.example.org_test.htxg");
+ contents.resize(30);
+ source_->AddReadResult(contents.data(), contents.size(), net::OK, GetParam());
+ source_->AddReadResult(nullptr, 0, net::OK, GetParam());
+
+ WaitForHeader();
+
+ ASSERT_TRUE(read_header());
+ EXPECT_EQ(net::ERR_FAILED, error());
+}
+
+TEST_P(SignedExchangeHandlerTest, CertSha256Mismatch) {
+ // The certificate is for "127.0.0.1". And the SHA 256 hash of the certificate
+ // is different from the certSha256 of the signature in the htxg file. So the
+ // certification verification must fail.
+ mock_cert_fetcher_factory_->ExpectFetch(
+ GURL("https://cert.example.org/cert.msg"),
+ GetTestFileContents("127.0.0.1.public.pem.msg"));
+
+ // Set the default result of MockCertVerifier to OK, to check that the
+ // verification of SignedExchange must fail even if the certificate is valid.
+ mock_cert_verifier_->set_default_result(net::OK);
+
+ std::string contents = GetTestFileContents("test.example.org_test.htxg");
+ source_->AddReadResult(contents.data(), contents.size(), net::OK, GetParam());
+ source_->AddReadResult(nullptr, 0, net::OK, GetParam());
+
+ WaitForHeader();
+
+ ASSERT_TRUE(read_header());
+ EXPECT_EQ(net::ERR_FAILED, error());
+ // Drain the MockSourceStream, otherwise its destructer causes DCHECK failure.
+ ReadStream(source_, nullptr);
+}
+
+TEST_P(SignedExchangeHandlerTest, VerifyCertFailure) {
+ mock_cert_fetcher_factory_->ExpectFetch(
+ GURL("https://cert.example.org/cert.msg"),
+ GetTestFileContents("wildcard_example.org.public.pem.msg"));
+
+ // Make the MockCertVerifier treat the certificate "wildcard.pem" as valid for
+ // "*.example.org".
+ scoped_refptr<net::X509Certificate> original_cert =
+ LoadCertificate("wildcard.pem");
+ net::CertVerifyResult dummy_result;
+ dummy_result.verified_cert = original_cert;
+ dummy_result.cert_status = net::OK;
+ mock_cert_verifier_->AddResultForCertAndHost(original_cert, "*.example.org",
+ dummy_result, net::OK);
+
+ // The certificate is for "*.example.com". But the request URL of the htxg
+ // file is "https://test.example.com/test/". So the certification verification
+ // must fail.
+ std::string contents =
+ GetTestFileContents("test.example.com_invalid_test.htxg");
+ source_->AddReadResult(contents.data(), contents.size(), net::OK, GetParam());
+ source_->AddReadResult(nullptr, 0, net::OK, GetParam());
+
+ WaitForHeader();
+
+ ASSERT_TRUE(read_header());
+ EXPECT_EQ(net::ERR_CERT_INVALID, error());
+ // Drain the MockSourceStream, otherwise its destructer causes DCHECK failure.
+ ReadStream(source_, nullptr);
+}
+
+INSTANTIATE_TEST_CASE_P(SignedExchangeHandlerTests,
+ SignedExchangeHandlerTest,
+ ::testing::Values(net::MockSourceStream::SYNC,
+ net::MockSourceStream::ASYNC));
+
+} // namespace content
diff --git a/chromium/content/browser/web_package/signed_exchange_header.cc b/chromium/content/browser/web_package/signed_exchange_header.cc
index 1d885dce07c..a97e746c4eb 100644
--- a/chromium/content/browser/web_package/signed_exchange_header.cc
+++ b/chromium/content/browser/web_package/signed_exchange_header.cc
@@ -6,20 +6,383 @@
#include <utility>
+#include "base/callback.h"
+#include "base/format_macros.h"
+#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
+#include "base/strings/stringprintf.h"
+#include "base/trace_event/trace_event.h"
+#include "components/cbor/cbor_reader.h"
+#include "content/browser/web_package/signed_exchange_consts.h"
+#include "content/browser/web_package/signed_exchange_utils.h"
+#include "net/http/http_util.h"
namespace content {
+namespace {
+
+// IsStateful{Request,Response}Header return true if |name| is a stateful
+// header field. Stateful header fields will cause validation failure of
+// signed exchanges.
+// Note that |name| must be lower-cased.
+// https://wicg.github.io/webpackage/draft-yasskin-httpbis-origin-signed-exchanges-impl.html#stateful-headers
+bool IsStatefulRequestHeader(base::StringPiece name) {
+ DCHECK_EQ(name, base::ToLowerASCII(name));
+
+ const char* const kStatefulRequestHeaders[] = {
+ "authorization", "cookie", "cookie2", "proxy-authorization",
+ "sec-webSocket-key"};
+
+ for (const char* field : kStatefulRequestHeaders) {
+ if (name == field)
+ return true;
+ }
+ return false;
+}
+
+bool IsStatefulResponseHeader(base::StringPiece name) {
+ DCHECK_EQ(name, base::ToLowerASCII(name));
+
+ const char* const kStatefulResponseHeaders[] = {
+ "authentication-control",
+ "authentication-info",
+ "optional-www-authenticate",
+ "proxy-authenticate",
+ "proxy-authentication-info",
+ "sec-websocket-accept",
+ "set-cookie",
+ "set-cookie2",
+ "setprofile",
+ "www-authenticate",
+ };
+
+ for (const char* field : kStatefulResponseHeaders) {
+ if (name == field)
+ return true;
+ }
+ return false;
+}
+
+bool IsMethodCacheable(base::StringPiece method) {
+ return method == "GET" || method == "HEAD" || method == "POST";
+}
+
+bool ParseRequestMap(
+ const cbor::CBORValue& value,
+ SignedExchangeHeader* out,
+ const signed_exchange_utils::LogCallback& error_message_callback) {
+ TRACE_EVENT_BEGIN0(TRACE_DISABLED_BY_DEFAULT("loading"), "ParseRequestMap");
+ if (!value.is_map()) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "ParseRequestMap", error_message_callback,
+ base::StringPrintf(
+ "Expected request map, got non-map type. Actual type: %d",
+ static_cast<int>(value.type())));
+ return false;
+ }
+
+ const cbor::CBORValue::MapValue& request_map = value.GetMap();
+
+ auto url_iter = request_map.find(
+ cbor::CBORValue(kUrlKey, cbor::CBORValue::Type::BYTE_STRING));
+ if (url_iter == request_map.end() || !url_iter->second.is_bytestring()) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "ParseRequestMap", error_message_callback,
+ ":url is not found or not a bytestring.");
+ return false;
+ }
+ out->set_request_url(GURL(url_iter->second.GetBytestringAsString()));
+ if (!out->request_url().is_valid()) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "ParseRequestMap", error_message_callback, ":url is not a valid URL.");
+ return false;
+ }
+ if (out->request_url().has_ref()) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "ParseRequestMap", error_message_callback,
+ ":url can't have a fragment.");
+ return false;
+ }
+
+ auto method_iter = request_map.find(
+ cbor::CBORValue(kMethodKey, cbor::CBORValue::Type::BYTE_STRING));
+ if (method_iter == request_map.end() ||
+ !method_iter->second.is_bytestring()) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "ParseRequestMap", error_message_callback,
+ ":method is not found or not a bytestring.");
+ return false;
+ }
+ base::StringPiece method_str = method_iter->second.GetBytestringAsString();
+ // 3. If exchange’s request method is not safe (Section 4.2.1 of [RFC7231])
+ // or not cacheable (Section 4.2.3 of [RFC7231]), return “invalid”.
+ // [spec text]
+ if (!net::HttpUtil::IsMethodSafe(method_str.as_string()) ||
+ !IsMethodCacheable(method_str)) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "ParseRequestMap", error_message_callback,
+ base::StringPrintf(
+ "Request method is not safe or not cacheable. method: %s",
+ method_str.as_string().c_str()));
+ return false;
+ }
+ out->set_request_method(method_str);
+
+ for (const auto& it : request_map) {
+ if (!it.first.is_bytestring() || !it.second.is_bytestring()) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "ParseRequestMap", error_message_callback,
+ "Non-bytestring value in the request map.");
+ return false;
+ }
+ base::StringPiece name_str = it.first.GetBytestringAsString();
+ if (name_str == kUrlKey || name_str == kMethodKey)
+ continue;
+
+ // TODO(kouhei): Add spec ref here once
+ // https://github.com/WICG/webpackage/issues/161 is resolved.
+ if (name_str != base::ToLowerASCII(name_str)) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "ParseRequestMap", error_message_callback,
+ base::StringPrintf(
+ "Request header name should be lower-cased. header name: %s",
+ name_str.as_string().c_str()));
+ return false;
+ }
+
+ // 4. If exchange’s headers contain a stateful header field, as defined in
+ // Section 4.1, return “invalid”. [spec text]
+ if (IsStatefulRequestHeader(name_str)) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "ParseRequestMap", error_message_callback,
+ base::StringPrintf(
+ "Exchange contains stateful request header. header name: %s",
+ name_str.as_string().c_str()));
+ return false;
+ }
+ }
+
+ TRACE_EVENT_END0(TRACE_DISABLED_BY_DEFAULT("loading"), "ParseRequestMap");
+ return true;
+}
+
+bool ParseResponseMap(
+ const cbor::CBORValue& value,
+ SignedExchangeHeader* out,
+ const signed_exchange_utils::LogCallback& error_message_callback) {
+ TRACE_EVENT_BEGIN0(TRACE_DISABLED_BY_DEFAULT("loading"), "ParseResponseMap");
+ if (!value.is_map()) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "ParseResponseMap", error_message_callback,
+ base::StringPrintf(
+ "Expected request map, got non-map type. Actual type: %d",
+ static_cast<int>(value.type())));
+ return false;
+ }
+
+ const cbor::CBORValue::MapValue& response_map = value.GetMap();
+ auto status_iter = response_map.find(
+ cbor::CBORValue(kStatusKey, cbor::CBORValue::Type::BYTE_STRING));
+ if (status_iter == response_map.end() ||
+ !status_iter->second.is_bytestring()) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "ParseRequestMap", error_message_callback,
+ ":status is not found or not a bytestring.");
+ return false;
+ }
+ base::StringPiece response_code_str =
+ status_iter->second.GetBytestringAsString();
+ int response_code;
+ if (!base::StringToInt(response_code_str, &response_code)) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "ParseRequestMap", error_message_callback,
+ "Failed to parse status code to integer.");
+ return false;
+ }
+ out->set_response_code(static_cast<net::HttpStatusCode>(response_code));
+
+ for (const auto& it : response_map) {
+ if (!it.first.is_bytestring() || !it.second.is_bytestring()) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "ParseRequestMap", error_message_callback,
+ "Non-bytestring value in the response map.");
+ return false;
+ }
+ base::StringPiece name_str = it.first.GetBytestringAsString();
+ if (name_str == kStatusKey)
+ continue;
+ if (!net::HttpUtil::IsValidHeaderName(name_str)) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "ParseResponseMap", error_message_callback,
+ base::StringPrintf("Invalid header name. header_name: %s",
+ name_str.as_string().c_str()));
+ return false;
+ }
+
+ // TODO(kouhei): Add spec ref here once
+ // https://github.com/WICG/webpackage/issues/161 is resolved.
+ if (name_str != base::ToLowerASCII(name_str)) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "ParseResponseMap", error_message_callback,
+ base::StringPrintf(
+ "Response header name should be lower-cased. header_name: %s",
+ name_str.as_string().c_str()));
+ return false;
+ }
+
+ // 4. If exchange’s headers contain a stateful header field, as defined in
+ // Section 4.1, return “invalid”. [spec text]
+ if (IsStatefulResponseHeader(name_str)) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "ParseResponseMap", error_message_callback,
+ base::StringPrintf(
+ "Exchange contains stateful response header. header_name: %s",
+ name_str.as_string().c_str()));
+ return false;
+ }
+
+ base::StringPiece value_str = it.second.GetBytestringAsString();
+ if (!net::HttpUtil::IsValidHeaderValue(value_str)) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "ParseRequestMap", error_message_callback, "Invalid header value.");
+ return false;
+ }
+ if (!out->AddResponseHeader(name_str, value_str)) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "ParseResponseMap", error_message_callback,
+ base::StringPrintf("Duplicate header value. header_name: %s",
+ name_str.as_string().c_str()));
+ return false;
+ }
+ }
+
+ TRACE_EVENT_END0(TRACE_DISABLED_BY_DEFAULT("loading"), "ParseResponseMap");
+ return true;
+}
+
+} // namespace
+
+constexpr size_t SignedExchangeHeader::kEncodedHeaderLengthInBytes;
+
+// static
+size_t SignedExchangeHeader::ParseHeadersLength(
+ base::span<const uint8_t> input) {
+ DCHECK_EQ(input.size(), SignedExchangeHeader::kEncodedHeaderLengthInBytes);
+ return static_cast<size_t>(input[0]) << 16 |
+ static_cast<size_t>(input[1]) << 8 | static_cast<size_t>(input[2]);
+}
+
+// static
+base::Optional<SignedExchangeHeader> SignedExchangeHeader::Parse(
+ base::span<const uint8_t> input,
+ const signed_exchange_utils::LogCallback& error_message_callback) {
+ TRACE_EVENT_BEGIN0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeHeader::Parse");
+ cbor::CBORReader::DecoderError error;
+ base::Optional<cbor::CBORValue> value = cbor::CBORReader::Read(input, &error);
+ if (!value.has_value()) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeHeader::Parse", error_message_callback,
+ base::StringPrintf("Failed to decode CBORValue. CBOR error: %s",
+ cbor::CBORReader::ErrorCodeToString(error)));
+ return base::nullopt;
+ }
+ if (!value->is_array()) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeHeader::Parse", error_message_callback,
+ base::StringPrintf(
+ "Expected top-level CBORValue to be an array. Actual type : %d",
+ static_cast<int>(value->type())));
+ return base::nullopt;
+ }
+
+ const cbor::CBORValue::ArrayValue& top_level_array = value->GetArray();
+ constexpr size_t kTopLevelArraySize = 2;
+ if (top_level_array.size() != kTopLevelArraySize) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeHeader::Parse", error_message_callback,
+ base::StringPrintf("Expected top-level array to have 2 elements. "
+ "Actual element count: %" PRIuS,
+ top_level_array.size()));
+ return base::nullopt;
+ }
+
+ SignedExchangeHeader ret;
+
+ if (!ParseRequestMap(top_level_array[0], &ret, error_message_callback)) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeHeader::Parse", error_message_callback,
+ "Failed to parse request map.");
+ return base::nullopt;
+ }
+ if (!ParseResponseMap(top_level_array[1], &ret, error_message_callback)) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeHeader::Parse", error_message_callback,
+ "Failed to parse response map.");
+ return base::nullopt;
+ }
+
+ auto signature_iter = ret.response_headers_.find(kSignature);
+ if (signature_iter == ret.response_headers_.end()) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeHeader::Parse", error_message_callback,
+ "No signature header found.");
+ return base::nullopt;
+ }
+
+ base::Optional<std::vector<SignedExchangeHeaderParser::Signature>>
+ signatures = SignedExchangeHeaderParser::ParseSignature(
+ signature_iter->second, error_message_callback);
+ if (!signatures || signatures->empty()) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeHeader::Parse", error_message_callback,
+ "Failed to parse signature.");
+ return base::nullopt;
+ }
+
+ ret.signature_ = (*signatures)[0];
+
+ TRACE_EVENT_END0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeHeader::Parse");
+ return std::move(ret);
+}
+
SignedExchangeHeader::SignedExchangeHeader() = default;
+SignedExchangeHeader::SignedExchangeHeader(const SignedExchangeHeader&) =
+ default;
+SignedExchangeHeader::SignedExchangeHeader(SignedExchangeHeader&&) = default;
SignedExchangeHeader::~SignedExchangeHeader() = default;
+SignedExchangeHeader& SignedExchangeHeader::operator=(SignedExchangeHeader&&) =
+ default;
-void SignedExchangeHeader::AddResponseHeader(base::StringPiece name,
+bool SignedExchangeHeader::AddResponseHeader(base::StringPiece name,
base::StringPiece value) {
- std::string name_string;
- std::string value_string;
- name.CopyToString(&name_string);
- value.CopyToString(&value_string);
- response_headers_[name_string] = value_string;
+ std::string name_str = name.as_string();
+ DCHECK_EQ(name_str, base::ToLowerASCII(name))
+ << "Response header names should be always lower-cased.";
+ if (response_headers_.find(name_str) != response_headers_.end())
+ return false;
+
+ response_headers_.emplace(std::move(name_str), value.as_string());
+ return true;
+}
+
+scoped_refptr<net::HttpResponseHeaders>
+SignedExchangeHeader::BuildHttpResponseHeaders() const {
+ std::string header_str("HTTP/1.1 ");
+ header_str.append(base::NumberToString(response_code()));
+ header_str.append(" ");
+ header_str.append(net::GetHttpReasonPhrase(response_code()));
+ header_str.append(" \r\n");
+ for (const auto& it : response_headers()) {
+ header_str.append(it.first);
+ header_str.append(": ");
+ header_str.append(it.second);
+ header_str.append("\r\n");
+ }
+ header_str.append("\r\n");
+ return base::MakeRefCounted<net::HttpResponseHeaders>(
+ net::HttpUtil::AssembleRawHeaders(header_str.c_str(), header_str.size()));
}
} // namespace content
diff --git a/chromium/content/browser/web_package/signed_exchange_header.h b/chromium/content/browser/web_package/signed_exchange_header.h
index c83df578810..7c31a43806f 100644
--- a/chromium/content/browser/web_package/signed_exchange_header.h
+++ b/chromium/content/browser/web_package/signed_exchange_header.h
@@ -8,8 +8,15 @@
#include <map>
#include <string>
+#include "base/callback_forward.h"
+#include "base/containers/span.h"
+#include "base/optional.h"
#include "base/strings/string_piece.h"
+#include "base/strings/string_util.h"
+#include "content/browser/web_package/signed_exchange_header_parser.h"
+#include "content/browser/web_package/signed_exchange_utils.h"
#include "content/common/content_export.h"
+#include "net/http/http_response_headers.h"
#include "net/http/http_status_code.h"
#include "url/gurl.h"
@@ -17,13 +24,36 @@ namespace content {
// SignedExchangeHeader contains all information captured in signed exchange
// envelope but the payload.
-// https://wicg.github.io/webpackage/draft-yasskin-http-origin-signed-responses.html
+// https://wicg.github.io/webpackage/draft-yasskin-httpbis-origin-signed-exchanges-impl.html
class CONTENT_EXPORT SignedExchangeHeader {
public:
+ static constexpr size_t kEncodedHeaderLengthInBytes = 3;
+ // Parse big-endian encoded length of the following CBOR-encoded
+ // signed exchange header.
+ // Note: |input| must be pointing to a valid memory address that has at least
+ // |kEncodedHeaderLengthInBytes|.
+ static size_t ParseHeadersLength(base::span<const uint8_t> input);
+
+ using HeaderMap = std::map<std::string, std::string>;
+
+ // Parse headers from the application/signed-exchange;v=b0 format.
+ // https://wicg.github.io/webpackage/draft-yasskin-httpbis-origin-signed-exchanges-impl.html#application-signed-exchange
+ //
+ // This also performs the step 3 and 4 of "Cross-origin trust" validation.
+ // https://wicg.github.io/webpackage/draft-yasskin-httpbis-origin-signed-exchanges-impl.html#cross-origin-trust
+ static base::Optional<SignedExchangeHeader> Parse(
+ base::span<const uint8_t> input,
+ const signed_exchange_utils::LogCallback& error_message_callback);
SignedExchangeHeader();
+ SignedExchangeHeader(const SignedExchangeHeader&);
+ SignedExchangeHeader(SignedExchangeHeader&&);
+ SignedExchangeHeader& operator=(SignedExchangeHeader&&);
~SignedExchangeHeader();
- void AddResponseHeader(base::StringPiece name, base::StringPiece value);
+ // AddResponseHeader returns false on duplicated keys. |name| must be
+ // lower-cased.
+ bool AddResponseHeader(base::StringPiece name, base::StringPiece value);
+ scoped_refptr<net::HttpResponseHeaders> BuildHttpResponseHeaders() const;
const GURL& request_url() const { return request_url_; };
void set_request_url(GURL url) { request_url_ = std::move(url); }
@@ -36,8 +66,14 @@ class CONTENT_EXPORT SignedExchangeHeader {
net::HttpStatusCode response_code() const { return response_code_; }
void set_response_code(net::HttpStatusCode c) { response_code_ = c; }
- const std::map<std::string, std::string>& response_headers() const {
- return response_headers_;
+ const HeaderMap& response_headers() const { return response_headers_; }
+
+ const SignedExchangeHeaderParser::Signature& signature() const {
+ return signature_;
+ }
+ void SetSignatureForTesting(
+ const SignedExchangeHeaderParser::Signature& sig) {
+ signature_ = sig;
}
private:
@@ -45,7 +81,8 @@ class CONTENT_EXPORT SignedExchangeHeader {
std::string request_method_;
net::HttpStatusCode response_code_;
- std::map<std::string, std::string> response_headers_;
+ HeaderMap response_headers_;
+ SignedExchangeHeaderParser::Signature signature_;
};
} // namespace content
diff --git a/chromium/content/browser/web_package/signed_exchange_header_parser.cc b/chromium/content/browser/web_package/signed_exchange_header_parser.cc
index c1e7f87f335..310d29f4450 100644
--- a/chromium/content/browser/web_package/signed_exchange_header_parser.cc
+++ b/chromium/content/browser/web_package/signed_exchange_header_parser.cc
@@ -9,6 +9,11 @@
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
+#include "base/strings/stringprintf.h"
+#include "base/trace_event/trace_event.h"
+#include "content/browser/web_package/signed_exchange_consts.h"
+#include "content/browser/web_package/signed_exchange_utils.h"
+#include "crypto/sha2.h"
namespace content {
@@ -123,7 +128,7 @@ class StructuredHeaderParser {
failed_ = true;
return s;
}
- while (input_.front() != '"') {
+ while (!ConsumeChar('"')) {
size_t len = input_.find_first_of("\"\\");
if (len == base::StringPiece::npos) {
DVLOG(1) << "ReadString: missing closing '\"'";
@@ -142,7 +147,6 @@ class StructuredHeaderParser {
input_.remove_prefix(1);
}
}
- input_.remove_prefix(1); // Consume '"'
return s;
}
@@ -187,24 +191,23 @@ class StructuredHeaderParser {
} // namespace
-base::Optional<std::vector<std::string>>
-SignedExchangeHeaderParser::ParseSignedHeaders(
- const std::string& signed_headers_str) {
- std::vector<std::string> headers;
- StructuredHeaderParser parser(signed_headers_str);
- parser.ParseStringList(&headers);
- if (!parser.ParsedSuccessfully())
- return base::nullopt;
- return headers;
-}
-
+// static
base::Optional<std::vector<SignedExchangeHeaderParser::Signature>>
-SignedExchangeHeaderParser::ParseSignature(base::StringPiece signature_str) {
+SignedExchangeHeaderParser::ParseSignature(
+ base::StringPiece signature_str,
+ const signed_exchange_utils::LogCallback& error_message_callback) {
+ TRACE_EVENT_BEGIN0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeHeaderParser::ParseSignature");
+
StructuredHeaderParser parser(signature_str);
std::vector<ParameterisedLabel> values;
parser.ParseParameterisedLabelList(&values);
- if (!parser.ParsedSuccessfully())
+ if (!parser.ParsedSuccessfully()) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeHeaderParser::ParseSignature", error_message_callback,
+ "Failed to parse signature header.");
return base::nullopt;
+ }
std::vector<Signature> signatures;
signatures.reserve(values.size());
@@ -213,38 +216,92 @@ SignedExchangeHeaderParser::ParseSignature(base::StringPiece signature_str) {
Signature& sig = signatures.back();
sig.label = value.label;
sig.sig = value.params["sig"];
+ if (sig.sig.empty()) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeHeaderParser::ParseSignature", error_message_callback,
+ "'sig' parameter is not set,");
+ return base::nullopt;
+ }
sig.integrity = value.params["integrity"];
- sig.cert_url = value.params["certUrl"];
- sig.cert_sha256 = value.params["certSha256"];
- sig.ed25519_key = value.params["ed25519Key"];
- sig.validity_url = value.params["validityUrl"];
-
- if (!base::StringToUint64(value.params["date"], &sig.date)) {
- DVLOG(1) << "ParseSignature: 'date' parameter is not a number: "
- << sig.date;
+ if (sig.integrity.empty()) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeHeaderParser::ParseSignature", error_message_callback,
+ "'integrity' parameter is not set.");
return base::nullopt;
}
- if (!base::StringToUint64(value.params["expires"], &sig.expires)) {
- DVLOG(1) << "ParseSignature: 'expires' parameter is not a number:"
- << sig.expires;
+ sig.cert_url = GURL(value.params["certUrl"]);
+ if (!sig.cert_url.is_valid() || sig.cert_url.has_ref()) {
+ // TODO(https://crbug.com/819467) : When we will support "ed25519Key", the
+ // params may not have "certUrl".
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeHeaderParser::ParseSignature", error_message_callback,
+ "'certUrl' parameter is not a valid URL.");
return base::nullopt;
}
-
- bool has_cert = !sig.cert_url.empty() && !sig.cert_sha256.empty();
- bool has_ed25519_key = !sig.ed25519_key.empty();
- if (sig.sig.empty() || sig.integrity.empty() || sig.validity_url.empty() ||
- (!has_cert && !has_ed25519_key)) {
- DVLOG(1) << "ParseSignature: incomplete signature";
+ const std::string cert_sha256_string = value.params["certSha256"];
+ if (cert_sha256_string.size() != crypto::kSHA256Length) {
+ // TODO(https://crbug.com/819467) : When we will support "ed25519Key", the
+ // params may not have "certSha256".
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeHeaderParser::ParseSignature", error_message_callback,
+ "'certSha256' parameter is not a SHA-256 digest.");
return base::nullopt;
}
- if (has_cert && has_ed25519_key) {
- DVLOG(1) << "ParseSignature: signature has both certUrl and ed25519Key";
+ net::SHA256HashValue cert_sha256;
+ memcpy(&cert_sha256.data, cert_sha256_string.data(), crypto::kSHA256Length);
+ sig.cert_sha256 = std::move(cert_sha256);
+ // TODO(https://crbug.com/819467): Support ed25519key.
+ // sig.ed25519_key = value.params["ed25519Key"];
+ sig.validity_url = GURL(value.params["validityUrl"]);
+ if (!sig.validity_url.is_valid()) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeHeaderParser::ParseSignature", error_message_callback,
+ "'validityUrl' parameter is not a valid URL.");
+ return base::nullopt;
+ }
+ if (sig.validity_url.has_ref()) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeHeaderParser::ParseSignature", error_message_callback,
+ "'validityUrl' parameter can't have a fragment.");
+ return base::nullopt;
+ }
+ if (!base::StringToUint64(value.params["date"], &sig.date)) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeHeaderParser::ParseSignature", error_message_callback,
+ "'date' parameter is not a number.");
+ return base::nullopt;
+ }
+ if (!base::StringToUint64(value.params["expires"], &sig.expires)) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeHeaderParser::ParseSignature", error_message_callback,
+ "'expires' parameter is not a number.");
return base::nullopt;
}
}
+ TRACE_EVENT_END0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeHeaderParser::ParseSignature");
return signatures;
}
+// static
+bool SignedExchangeHeaderParser::GetVersionParamFromContentType(
+ base::StringPiece content_type,
+ base::Optional<std::string>* version_param) {
+ DCHECK(version_param);
+ StructuredHeaderParser parser(content_type);
+ ParameterisedLabel parameterised_label;
+ parser.ParseParameterisedLabel(&parameterised_label);
+ if (!parser.ParsedSuccessfully())
+ return false;
+ const auto it = parameterised_label.params.find("v");
+ if (it == parameterised_label.params.end()) {
+ *version_param = base::nullopt;
+ } else {
+ *version_param = it->second;
+ }
+ return true;
+}
+
SignedExchangeHeaderParser::Signature::Signature() = default;
SignedExchangeHeaderParser::Signature::Signature(const Signature& other) =
default;
diff --git a/chromium/content/browser/web_package/signed_exchange_header_parser.h b/chromium/content/browser/web_package/signed_exchange_header_parser.h
index e2a884cebb8..68b23813eb1 100644
--- a/chromium/content/browser/web_package/signed_exchange_header_parser.h
+++ b/chromium/content/browser/web_package/signed_exchange_header_parser.h
@@ -8,15 +8,20 @@
#include <stdint.h>
#include <string>
#include <vector>
+
+#include "base/callback_forward.h"
#include "base/macros.h"
#include "base/optional.h"
#include "base/strings/string_piece.h"
+#include "content/browser/web_package/signed_exchange_utils.h"
#include "content/common/content_export.h"
+#include "net/base/hash_value.h"
+#include "url/gurl.h"
namespace content {
// Provide parsers for signed-exchange headers.
-// https://wicg.github.io/webpackage/draft-yasskin-http-origin-signed-responses.html
+// https://wicg.github.io/webpackage/draft-yasskin-httpbis-origin-signed-exchanges-impl.html
class CONTENT_EXPORT SignedExchangeHeaderParser {
public:
struct CONTENT_EXPORT Signature {
@@ -27,23 +32,27 @@ class CONTENT_EXPORT SignedExchangeHeaderParser {
std::string label;
std::string sig;
std::string integrity;
- std::string cert_url;
- std::string cert_sha256;
- std::string ed25519_key;
- std::string validity_url;
+ GURL cert_url;
+ base::Optional<net::SHA256HashValue> cert_sha256;
+ // TODO(https://crbug.com/819467): Support ed25519key.
+ // std::string ed25519_key;
+ GURL validity_url;
uint64_t date;
uint64_t expires;
};
- // Parses a value of the Signed-Headers header.
- // https://wicg.github.io/webpackage/draft-yasskin-http-origin-signed-responses.html#rfc.section.3.1
- static base::Optional<std::vector<std::string>> ParseSignedHeaders(
- const std::string& signed_headers_str);
-
// Parses a value of the Signature header.
- // https://wicg.github.io/webpackage/draft-yasskin-http-origin-signed-responses.html#rfc.section.3.2
+ // https://wicg.github.io/webpackage/draft-yasskin-httpbis-origin-signed-exchanges-impl.html#signature-header
static base::Optional<std::vector<Signature>> ParseSignature(
- base::StringPiece signature_str);
+ base::StringPiece signature_str,
+ const signed_exchange_utils::LogCallback& error_message_callback);
+
+ // Parses |content_type| to get the value of "v=" parameter of the signed
+ // exchange. Example: "b0" for "application/signed-exchange;v=b0". Returns
+ // false if failed to parse.
+ static bool GetVersionParamFromContentType(
+ base::StringPiece content_type,
+ base::Optional<std::string>* version_param);
};
} // namespace content
diff --git a/chromium/content/browser/web_package/signed_exchange_header_parser_unittest.cc b/chromium/content/browser/web_package/signed_exchange_header_parser_unittest.cc
index eb6e18c8e46..a433f84d124 100644
--- a/chromium/content/browser/web_package/signed_exchange_header_parser_unittest.cc
+++ b/chromium/content/browser/web_package/signed_exchange_header_parser_unittest.cc
@@ -3,6 +3,9 @@
// found in the LICENSE file.
#include "content/browser/web_package/signed_exchange_header_parser.h"
+
+#include "base/callback.h"
+#include "content/browser/web_package/signed_exchange_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace content {
@@ -12,39 +15,6 @@ class SignedExchangeHeaderParserTest : public ::testing::Test {
SignedExchangeHeaderParserTest() {}
};
-TEST_F(SignedExchangeHeaderParserTest, ParseSignedHeaders) {
- const char hdr_string[] = "\"content-type\", \"digest\"";
- base::Optional<std::vector<std::string>> headers =
- SignedExchangeHeaderParser::ParseSignedHeaders(hdr_string);
- EXPECT_TRUE(headers.has_value());
- ASSERT_EQ(headers->size(), 2u);
- EXPECT_EQ(headers->at(0), "content-type");
- EXPECT_EQ(headers->at(1), "digest");
-}
-
-TEST_F(SignedExchangeHeaderParserTest, SignedHeadersNoQuotes) {
- const char hdr_string[] = "content-type, digest";
- base::Optional<std::vector<std::string>> headers =
- SignedExchangeHeaderParser::ParseSignedHeaders(hdr_string);
- EXPECT_FALSE(headers.has_value());
-}
-
-TEST_F(SignedExchangeHeaderParserTest, SignedHeadersParseError) {
- const char hdr_string[] = "\"content-type\", \"digest";
- base::Optional<std::vector<std::string>> headers =
- SignedExchangeHeaderParser::ParseSignedHeaders(hdr_string);
- EXPECT_FALSE(headers.has_value());
-}
-
-TEST_F(SignedExchangeHeaderParserTest, QuotedChar) {
- const char hdr_string[] = R"("\\o/")";
- base::Optional<std::vector<std::string>> headers =
- SignedExchangeHeaderParser::ParseSignedHeaders(hdr_string);
- EXPECT_TRUE(headers.has_value());
- ASSERT_EQ(headers->size(), 1u);
- EXPECT_EQ(headers->at(0), "\\o/");
-}
-
TEST_F(SignedExchangeHeaderParserTest, ParseSignature) {
const char hdr_string[] =
"sig1;"
@@ -55,13 +25,15 @@ TEST_F(SignedExchangeHeaderParserTest, ParseSignature) {
" certUrl=\"https://example.com/oldcerts\";"
" certSha256=*W7uB969dFW3Mb5ZefPS9Tq5ZbH5iSmOILpjv2qEArmI;"
" date=1511128380; expires=1511733180,"
- "srisig;"
- " sig=*lGZVaJJM5f2oGczFlLmBdKTDL+QADza4BgeO494ggACYJOvrof6uh5OJCcwKrk7DK+"
- "LBch0jssDYPp5CLc1SDA;"
+ "sig2;"
+ " sig=*MEQCIGjZRqTRf9iKNkGFyzRMTFgwf/BrY2ZNIP/dykhUV0aYAiBTXg+8wujoT4n/W+"
+ "cNgb7pGqQvIUGYZ8u8HZJ5YH26Qg;"
" integrity=\"mi\";"
" validityUrl=\"https://example.com/resource.validity.1511128380\";"
- " ed25519Key=*zsSevyFsxyZHiUluVBDd4eypdRLTqyWRVOJuuKUz+A8;"
+ " certUrl=\"https://example.com/newcerts\";"
+ " certSha256=*J/lEm9kNRODdCmINbvitpvdYKNQ+YgBj99DlYp4fEXw;"
" date=1511128380; expires=1511733180";
+
const uint8_t decoded_sig1[] = {
0x30, 0x45, 0x02, 0x21, 0x00, 0xd7, 0x94, 0x8d, 0xa0, 0x37, 0x74, 0x4d,
0x06, 0x58, 0x05, 0x8a, 0xe4, 0x4d, 0x16, 0x96, 0x57, 0x70, 0x32, 0x1a,
@@ -69,24 +41,25 @@ TEST_F(SignedExchangeHeaderParserTest, ParseSignature) {
0x2c, 0x02, 0x20, 0x6b, 0xd0, 0xec, 0x54, 0xe3, 0x0c, 0xfa, 0x0e, 0x58,
0xa7, 0x01, 0x01, 0x74, 0x65, 0xb7, 0xb1, 0x2f, 0x9b, 0xbe, 0x79, 0x80,
0x24, 0x98, 0x92, 0x33, 0x08, 0x6e, 0x05, 0xda, 0xa9, 0xe5, 0x46};
- const uint8_t decoded_cert_sha256[] = {
- 0x5b, 0xbb, 0x81, 0xf7, 0xaf, 0x5d, 0x15, 0x6d, 0xcc, 0x6f, 0x96,
- 0x5e, 0x7c, 0xf4, 0xbd, 0x4e, 0xae, 0x59, 0x6c, 0x7e, 0x62, 0x4a,
- 0x63, 0x88, 0x2e, 0x98, 0xef, 0xda, 0xa1, 0x00, 0xae, 0x62};
+ const net::SHA256HashValue decoded_cert_sha256_1 = {
+ {0x5b, 0xbb, 0x81, 0xf7, 0xaf, 0x5d, 0x15, 0x6d, 0xcc, 0x6f, 0x96,
+ 0x5e, 0x7c, 0xf4, 0xbd, 0x4e, 0xae, 0x59, 0x6c, 0x7e, 0x62, 0x4a,
+ 0x63, 0x88, 0x2e, 0x98, 0xef, 0xda, 0xa1, 0x00, 0xae, 0x62}};
const uint8_t decoded_sig2[] = {
- 0x94, 0x66, 0x55, 0x68, 0x92, 0x4c, 0xe5, 0xfd, 0xa8, 0x19, 0xcc,
- 0xc5, 0x94, 0xb9, 0x81, 0x74, 0xa4, 0xc3, 0x2f, 0xe4, 0x00, 0x0f,
- 0x36, 0xb8, 0x06, 0x07, 0x8e, 0xe3, 0xde, 0x20, 0x80, 0x00, 0x98,
- 0x24, 0xeb, 0xeb, 0xa1, 0xfe, 0xae, 0x87, 0x93, 0x89, 0x09, 0xcc,
- 0x0a, 0xae, 0x4e, 0xc3, 0x2b, 0xe2, 0xc1, 0x72, 0x1d, 0x23, 0xb2,
- 0xc0, 0xd8, 0x3e, 0x9e, 0x42, 0x2d, 0xcd, 0x52, 0x0c};
- const uint8_t decoded_ed25519_key[] = {
- 0xce, 0xc4, 0x9e, 0xbf, 0x21, 0x6c, 0xc7, 0x26, 0x47, 0x89, 0x49,
- 0x6e, 0x54, 0x10, 0xdd, 0xe1, 0xec, 0xa9, 0x75, 0x12, 0xd3, 0xab,
- 0x25, 0x91, 0x54, 0xe2, 0x6e, 0xb8, 0xa5, 0x33, 0xf8, 0x0f};
-
- auto signatures = SignedExchangeHeaderParser::ParseSignature(hdr_string);
- EXPECT_TRUE(signatures.has_value());
+ 0x30, 0x44, 0x02, 0x20, 0x68, 0xd9, 0x46, 0xa4, 0xd1, 0x7f, 0xd8, 0x8a,
+ 0x36, 0x41, 0x85, 0xcb, 0x34, 0x4c, 0x4c, 0x58, 0x30, 0x7f, 0xf0, 0x6b,
+ 0x63, 0x66, 0x4d, 0x20, 0xff, 0xdd, 0xca, 0x48, 0x54, 0x57, 0x46, 0x98,
+ 0x02, 0x20, 0x53, 0x5e, 0x0f, 0xbc, 0xc2, 0xe8, 0xe8, 0x4f, 0x89, 0xff,
+ 0x5b, 0xe7, 0x0d, 0x81, 0xbe, 0xe9, 0x1a, 0xa4, 0x2f, 0x21, 0x41, 0x98,
+ 0x67, 0xcb, 0xbc, 0x1d, 0x92, 0x79, 0x60, 0x7d, 0xba, 0x42};
+ const net::SHA256HashValue decoded_cert_sha256_2 = {
+ {0x27, 0xf9, 0x44, 0x9b, 0xd9, 0x0d, 0x44, 0xe0, 0xdd, 0x0a, 0x62,
+ 0x0d, 0x6e, 0xf8, 0xad, 0xa6, 0xf7, 0x58, 0x28, 0xd4, 0x3e, 0x62,
+ 0x00, 0x63, 0xf7, 0xd0, 0xe5, 0x62, 0x9e, 0x1f, 0x11, 0x7c}};
+
+ auto signatures = SignedExchangeHeaderParser::ParseSignature(
+ hdr_string, signed_exchange_utils::LogCallback());
+ ASSERT_TRUE(signatures.has_value());
ASSERT_EQ(signatures->size(), 2u);
EXPECT_EQ(signatures->at(0).label, "sig1");
@@ -97,22 +70,19 @@ TEST_F(SignedExchangeHeaderParserTest, ParseSignature) {
EXPECT_EQ(signatures->at(0).validity_url,
"https://example.com/resource.validity.1511128380");
EXPECT_EQ(signatures->at(0).cert_url, "https://example.com/oldcerts");
- EXPECT_EQ(signatures->at(0).cert_sha256,
- std::string(reinterpret_cast<const char*>(decoded_cert_sha256),
- sizeof(decoded_cert_sha256)));
+ EXPECT_EQ(signatures->at(0).cert_sha256, decoded_cert_sha256_1);
EXPECT_EQ(signatures->at(0).date, 1511128380ul);
EXPECT_EQ(signatures->at(0).expires, 1511733180ul);
- EXPECT_EQ(signatures->at(1).label, "srisig");
+ EXPECT_EQ(signatures->at(1).label, "sig2");
EXPECT_EQ(signatures->at(1).sig,
std::string(reinterpret_cast<const char*>(decoded_sig2),
sizeof(decoded_sig2)));
EXPECT_EQ(signatures->at(1).integrity, "mi");
EXPECT_EQ(signatures->at(1).validity_url,
"https://example.com/resource.validity.1511128380");
- EXPECT_EQ(signatures->at(1).ed25519_key,
- std::string(reinterpret_cast<const char*>(decoded_ed25519_key),
- sizeof(decoded_ed25519_key)));
+ EXPECT_EQ(signatures->at(1).cert_url, "https://example.com/newcerts");
+ EXPECT_EQ(signatures->at(1).cert_sha256, decoded_cert_sha256_2);
EXPECT_EQ(signatures->at(1).date, 1511128380ul);
EXPECT_EQ(signatures->at(1).expires, 1511733180ul);
}
@@ -127,11 +97,12 @@ TEST_F(SignedExchangeHeaderParserTest, IncompleteSignature) {
" certUrl=\"https://example.com/oldcerts\";"
" certSha256=*W7uB969dFW3Mb5ZefPS9Tq5ZbH5iSmOILpjv2qEArmI;"
" date=1511128380; expires=1511733180";
- auto signatures = SignedExchangeHeaderParser::ParseSignature(hdr_string);
+ auto signatures = SignedExchangeHeaderParser::ParseSignature(
+ hdr_string, signed_exchange_utils::LogCallback());
EXPECT_FALSE(signatures.has_value());
}
-TEST_F(SignedExchangeHeaderParserTest, HasBothCertAndEd25519Key) {
+TEST_F(SignedExchangeHeaderParserTest, DuplicatedParam) {
const char hdr_string[] =
"sig1;"
" sig=*MEUCIQDXlI2gN3RNBlgFiuRNFpZXcDIaUpX6HIEwcZEc0cZYLAIga9DsVOMM+"
@@ -139,26 +110,173 @@ TEST_F(SignedExchangeHeaderParserTest, HasBothCertAndEd25519Key) {
" integrity=\"mi\";"
" validityUrl=\"https://example.com/resource.validity.1511128380\";"
" certUrl=\"https://example.com/oldcerts\";"
+ " certUrl=\"https://example.com/oldcerts\";"
" certSha256=*W7uB969dFW3Mb5ZefPS9Tq5ZbH5iSmOILpjv2qEArmI;"
- " ed25519Key=*zsSevyFsxyZHiUluVBDd4eypdRLTqyWRVOJuuKUz+A8;"
" date=1511128380; expires=1511733180";
- auto signatures = SignedExchangeHeaderParser::ParseSignature(hdr_string);
+ auto signatures = SignedExchangeHeaderParser::ParseSignature(
+ hdr_string, signed_exchange_utils::LogCallback());
EXPECT_FALSE(signatures.has_value());
}
-TEST_F(SignedExchangeHeaderParserTest, DuplicatedParam) {
+TEST_F(SignedExchangeHeaderParserTest, InvalidCertURL) {
const char hdr_string[] =
"sig1;"
" sig=*MEUCIQDXlI2gN3RNBlgFiuRNFpZXcDIaUpX6HIEwcZEc0cZYLAIga9DsVOMM+"
"g5YpwEBdGW3sS+bvnmAJJiSMwhuBdqp5UY;"
" integrity=\"mi\";"
" validityUrl=\"https://example.com/resource.validity.1511128380\";"
+ " certUrl=\"https:://example.com/oldcerts\";"
+ " certSha256=*W7uB969dFW3Mb5ZefPS9Tq5ZbH5iSmOILpjv2qEArmI;"
+ " date=1511128380; expires=1511733180";
+ auto signatures = SignedExchangeHeaderParser::ParseSignature(
+ hdr_string, signed_exchange_utils::LogCallback());
+ EXPECT_FALSE(signatures.has_value());
+}
+
+TEST_F(SignedExchangeHeaderParserTest, CertURLWithFragment) {
+ const char hdr_string[] =
+ "sig1;"
+ " sig=*MEUCIQDXlI2gN3RNBlgFiuRNFpZXcDIaUpX6HIEwcZEc0cZYLAIga9DsVOMM+"
+ "g5YpwEBdGW3sS+bvnmAJJiSMwhuBdqp5UY;"
+ " integrity=\"mi\";"
+ " validityUrl=\"https://example.com/resource.validity.1511128380\";"
+ " certUrl=\"https://example.com/oldcerts#test\";"
+ " certSha256=*W7uB969dFW3Mb5ZefPS9Tq5ZbH5iSmOILpjv2qEArmI;"
+ " date=1511128380; expires=1511733180";
+ auto signatures = SignedExchangeHeaderParser::ParseSignature(
+ hdr_string, signed_exchange_utils::LogCallback());
+ EXPECT_FALSE(signatures.has_value());
+}
+
+TEST_F(SignedExchangeHeaderParserTest, RelativeCertURL) {
+ const char hdr_string[] =
+ "sig1;"
+ " sig=*MEUCIQDXlI2gN3RNBlgFiuRNFpZXcDIaUpX6HIEwcZEc0cZYLAIga9DsVOMM+"
+ "g5YpwEBdGW3sS+bvnmAJJiSMwhuBdqp5UY;"
+ " integrity=\"mi\";"
+ " validityUrl=\"https://example.com/resource.validity.1511128380\";"
+ " certUrl=\"oldcerts\";"
+ " certSha256=*W7uB969dFW3Mb5ZefPS9Tq5ZbH5iSmOILpjv2qEArmI;"
+ " date=1511128380; expires=1511733180";
+ auto signatures = SignedExchangeHeaderParser::ParseSignature(
+ hdr_string, signed_exchange_utils::LogCallback());
+ EXPECT_FALSE(signatures.has_value());
+}
+
+TEST_F(SignedExchangeHeaderParserTest, InvalidValidityUrl) {
+ const char hdr_string[] =
+ "sig1;"
+ " sig=*MEUCIQDXlI2gN3RNBlgFiuRNFpZXcDIaUpX6HIEwcZEc0cZYLAIga9DsVOMM+"
+ "g5YpwEBdGW3sS+bvnmAJJiSMwhuBdqp5UY;"
+ " integrity=\"mi\";"
+ " validityUrl=\"https:://example.com/resource.validity.1511128380\";"
" certUrl=\"https://example.com/oldcerts\";"
+ " certSha256=*W7uB969dFW3Mb5ZefPS9Tq5ZbH5iSmOILpjv2qEArmI;"
+ " date=1511128380; expires=1511733180";
+ auto signatures = SignedExchangeHeaderParser::ParseSignature(
+ hdr_string, signed_exchange_utils::LogCallback());
+ EXPECT_FALSE(signatures.has_value());
+}
+
+TEST_F(SignedExchangeHeaderParserTest, ValidityUrlWithFragment) {
+ const char hdr_string[] =
+ "sig1;"
+ " sig=*MEUCIQDXlI2gN3RNBlgFiuRNFpZXcDIaUpX6HIEwcZEc0cZYLAIga9DsVOMM+"
+ "g5YpwEBdGW3sS+bvnmAJJiSMwhuBdqp5UY;"
+ " integrity=\"mi\";"
+ " validityUrl=\"https://example.com/resource.validity.1511128380#test\";"
" certUrl=\"https://example.com/oldcerts\";"
" certSha256=*W7uB969dFW3Mb5ZefPS9Tq5ZbH5iSmOILpjv2qEArmI;"
" date=1511128380; expires=1511733180";
- auto signatures = SignedExchangeHeaderParser::ParseSignature(hdr_string);
+ auto signatures = SignedExchangeHeaderParser::ParseSignature(
+ hdr_string, signed_exchange_utils::LogCallback());
+ EXPECT_FALSE(signatures.has_value());
+}
+
+TEST_F(SignedExchangeHeaderParserTest, RelativeValidityUrl) {
+ const char hdr_string[] =
+ "sig1;"
+ " sig=*MEUCIQDXlI2gN3RNBlgFiuRNFpZXcDIaUpX6HIEwcZEc0cZYLAIga9DsVOMM+"
+ "g5YpwEBdGW3sS+bvnmAJJiSMwhuBdqp5UY;"
+ " integrity=\"mi\";"
+ " validityUrl=\"resource.validity.1511128380\";"
+ " certUrl=\"https://example.com/oldcerts\";"
+ " certSha256=*W7uB969dFW3Mb5ZefPS9Tq5ZbH5iSmOILpjv2qEArmI;"
+ " date=1511128380; expires=1511733180";
+ auto signatures = SignedExchangeHeaderParser::ParseSignature(
+ hdr_string, signed_exchange_utils::LogCallback());
+ EXPECT_FALSE(signatures.has_value());
+}
+
+TEST_F(SignedExchangeHeaderParserTest, InvalidCertSHA256) {
+ const char hdr_string[] =
+ "sig1;"
+ " sig=*MEUCIQDXlI2gN3RNBlgFiuRNFpZXcDIaUpX6HIEwcZEc0cZYLAIga9DsVOMM+"
+ "g5YpwEBdGW3sS+bvnmAJJiSMwhuBdqp5UY;"
+ " integrity=\"mi\";"
+ " validityUrl=\"https://example.com/resource.validity.1511128380\";"
+ " certUrl=\"https://example.com/oldcerts\";"
+ " certSha256=*W7uB969dFW3Mb5ZefPS9;"
+ " date=1511128380; expires=1511733180";
+ auto signatures = SignedExchangeHeaderParser::ParseSignature(
+ hdr_string, signed_exchange_utils::LogCallback());
+ EXPECT_FALSE(signatures.has_value());
+}
+
+TEST_F(SignedExchangeHeaderParserTest, OpenQuoteAtEnd) {
+ const char hdr_string[] = "sig1; sig=\"";
+ auto signatures = SignedExchangeHeaderParser::ParseSignature(
+ hdr_string, signed_exchange_utils::LogCallback());
EXPECT_FALSE(signatures.has_value());
}
+TEST_F(SignedExchangeHeaderParserTest, VersionParam_None) {
+ const char content_type[] = "application/signed-exchange";
+ base::Optional<std::string> version;
+ EXPECT_TRUE(SignedExchangeHeaderParser::GetVersionParamFromContentType(
+ content_type, &version));
+ EXPECT_FALSE(version);
+}
+
+TEST_F(SignedExchangeHeaderParserTest, VersionParam_NoneWithSemicolon) {
+ const char content_type[] = "application/signed-exchange;";
+ base::Optional<std::string> version;
+ EXPECT_FALSE(SignedExchangeHeaderParser::GetVersionParamFromContentType(
+ content_type, &version));
+}
+
+TEST_F(SignedExchangeHeaderParserTest, VersionParam_EmptyString) {
+ const char content_type[] = "application/signed-exchange;v=";
+ base::Optional<std::string> version;
+ EXPECT_FALSE(SignedExchangeHeaderParser::GetVersionParamFromContentType(
+ content_type, &version));
+}
+
+TEST_F(SignedExchangeHeaderParserTest, VersionParam_Simple) {
+ const char content_type[] = "application/signed-exchange;v=b0";
+ base::Optional<std::string> version;
+ EXPECT_TRUE(SignedExchangeHeaderParser::GetVersionParamFromContentType(
+ content_type, &version));
+ ASSERT_TRUE(version);
+ EXPECT_EQ(*version, "b0");
+}
+
+TEST_F(SignedExchangeHeaderParserTest, VersionParam_SimpleWithSpace) {
+ const char content_type[] = "application/signed-exchange; v=b0";
+ base::Optional<std::string> version;
+ EXPECT_TRUE(SignedExchangeHeaderParser::GetVersionParamFromContentType(
+ content_type, &version));
+ ASSERT_TRUE(version);
+ EXPECT_EQ(*version, "b0");
+}
+
+TEST_F(SignedExchangeHeaderParserTest, VersionParam_SimpleWithDoublequotes) {
+ const char content_type[] = "application/signed-exchange;v=\"b0\"";
+ base::Optional<std::string> version;
+ EXPECT_TRUE(SignedExchangeHeaderParser::GetVersionParamFromContentType(
+ content_type, &version));
+ ASSERT_TRUE(version);
+ EXPECT_EQ(*version, "b0");
+}
+
} // namespace content
diff --git a/chromium/content/browser/web_package/signed_exchange_header_unittest.cc b/chromium/content/browser/web_package/signed_exchange_header_unittest.cc
new file mode 100644
index 00000000000..a12c0c7f2a4
--- /dev/null
+++ b/chromium/content/browser/web_package/signed_exchange_header_unittest.cc
@@ -0,0 +1,212 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/web_package/signed_exchange_header.h"
+
+#include "base/callback.h"
+#include "base/files/file_path.h"
+#include "base/files/file_util.h"
+#include "base/path_service.h"
+#include "components/cbor/cbor_values.h"
+#include "components/cbor/cbor_writer.h"
+#include "content/browser/web_package/signed_exchange_consts.h"
+#include "content/browser/web_package/signed_exchange_utils.h"
+#include "content/public/common/content_paths.h"
+#include "testing/gtest/include/gtest/gtest.h"
+
+namespace content {
+
+namespace {
+
+const char kSignatureString[] =
+ "sig1;"
+ " sig=*MEUCIQDXlI2gN3RNBlgFiuRNFpZXcDIaUpX6HIEwcZEc0cZYLAIga9DsVOMM+"
+ "g5YpwEBdGW3sS+bvnmAJJiSMwhuBdqp5UY;"
+ " integrity=\"mi\";"
+ " validityUrl=\"https://example.com/resource.validity.1511128380\";"
+ " certUrl=\"https://example.com/oldcerts\";"
+ " certSha256=*W7uB969dFW3Mb5ZefPS9Tq5ZbH5iSmOILpjv2qEArmI;"
+ " date=1511128380; expires=1511733180";
+
+cbor::CBORValue CBORByteString(const char* str) {
+ return cbor::CBORValue(str, cbor::CBORValue::Type::BYTE_STRING);
+}
+
+base::Optional<SignedExchangeHeader> GenerateHeaderAndParse(
+ const std::map<const char*, const char*>& request_map,
+ const std::map<const char*, const char*>& response_map) {
+ cbor::CBORValue::MapValue request_cbor_map;
+ cbor::CBORValue::MapValue response_cbor_map;
+ for (auto& pair : request_map)
+ request_cbor_map[CBORByteString(pair.first)] = CBORByteString(pair.second);
+ for (auto& pair : response_map)
+ response_cbor_map[CBORByteString(pair.first)] = CBORByteString(pair.second);
+
+ cbor::CBORValue::ArrayValue array;
+ array.push_back(cbor::CBORValue(std::move(request_cbor_map)));
+ array.push_back(cbor::CBORValue(std::move(response_cbor_map)));
+
+ auto serialized = cbor::CBORWriter::Write(cbor::CBORValue(std::move(array)));
+ return SignedExchangeHeader::Parse(
+ base::make_span(serialized->data(), serialized->size()),
+ signed_exchange_utils::LogCallback());
+}
+
+} // namespace
+
+TEST(SignedExchangeHeaderTest, ParseHeaderLength) {
+ constexpr struct {
+ uint8_t bytes[SignedExchangeHeader::kEncodedHeaderLengthInBytes];
+ size_t expected;
+ } kTestCases[] = {
+ {{0x00, 0x00, 0x01}, 1u}, {{0x01, 0xe2, 0x40}, 123456u},
+ };
+
+ int test_element_index = 0;
+ for (const auto& test_case : kTestCases) {
+ SCOPED_TRACE(testing::Message() << "testing case " << test_element_index++);
+ EXPECT_EQ(SignedExchangeHeader::ParseHeadersLength(test_case.bytes),
+ test_case.expected);
+ }
+}
+
+TEST(SignedExchangeHeaderTest, ParseGoldenFile) {
+ base::FilePath test_htxg_path;
+ PathService::Get(content::DIR_TEST_DATA, &test_htxg_path);
+ test_htxg_path = test_htxg_path.AppendASCII("htxg").AppendASCII(
+ "test.example.org_test.htxg");
+
+ std::string contents;
+ ASSERT_TRUE(base::ReadFileToString(test_htxg_path, &contents));
+ auto* contents_bytes = reinterpret_cast<const uint8_t*>(contents.data());
+
+ ASSERT_GT(contents.size(), SignedExchangeHeader::kEncodedHeaderLengthInBytes);
+ size_t header_size = SignedExchangeHeader::ParseHeadersLength(base::make_span(
+ contents_bytes, SignedExchangeHeader::kEncodedHeaderLengthInBytes));
+ ASSERT_GT(contents.size(),
+ SignedExchangeHeader::kEncodedHeaderLengthInBytes + header_size);
+
+ const auto cbor_bytes = base::make_span<const uint8_t>(
+ contents_bytes + SignedExchangeHeader::kEncodedHeaderLengthInBytes,
+ header_size);
+ const base::Optional<SignedExchangeHeader> header =
+ SignedExchangeHeader::Parse(cbor_bytes,
+ signed_exchange_utils::LogCallback());
+ ASSERT_TRUE(header.has_value());
+ EXPECT_EQ(header->request_url(), GURL("https://test.example.org/test/"));
+ EXPECT_EQ(header->request_method(), "GET");
+ EXPECT_EQ(header->response_code(), static_cast<net::HttpStatusCode>(200u));
+ EXPECT_EQ(header->response_headers().size(), 4u);
+ EXPECT_EQ(header->response_headers().find("content-encoding")->second,
+ "mi-sha256");
+}
+
+TEST(SignedExchangeHeaderTest, ValidHeader) {
+ auto header = GenerateHeaderAndParse(
+ {
+ {kUrlKey, "https://test.example.org/test/"}, {kMethodKey, "GET"},
+ },
+ {
+ {kStatusKey, "200"}, {kSignature, kSignatureString},
+ });
+ ASSERT_TRUE(header.has_value());
+ EXPECT_EQ(header->request_url(), GURL("https://test.example.org/test/"));
+ EXPECT_EQ(header->request_method(), "GET");
+ EXPECT_EQ(header->response_code(), static_cast<net::HttpStatusCode>(200u));
+ EXPECT_EQ(header->response_headers().size(), 1u);
+}
+
+TEST(SignedExchangeHeaderTest, UnsafeMethod) {
+ auto header = GenerateHeaderAndParse(
+ {
+ {kUrlKey, "https://test.example.org/test/"}, {kMethodKey, "POST"},
+ },
+ {
+ {kStatusKey, "200"}, {kSignature, kSignatureString},
+ });
+ ASSERT_FALSE(header.has_value());
+}
+
+TEST(SignedExchangeHeaderTest, InvalidURL) {
+ auto header = GenerateHeaderAndParse(
+ {
+ {kUrlKey, "https:://test.example.org/test/"}, {kMethodKey, "GET"},
+ },
+ {
+ {kStatusKey, "200"}, {kSignature, kSignatureString},
+ });
+ ASSERT_FALSE(header.has_value());
+}
+
+TEST(SignedExchangeHeaderTest, URLWithFragment) {
+ auto header = GenerateHeaderAndParse(
+ {
+ {kUrlKey, "https://test.example.org/test/#foo"}, {kMethodKey, "GET"},
+ },
+ {
+ {kStatusKey, "200"}, {kSignature, kSignatureString},
+ });
+ ASSERT_FALSE(header.has_value());
+}
+
+TEST(SignedExchangeHeaderTest, RelativeURL) {
+ auto header = GenerateHeaderAndParse(
+ {
+ {kUrlKey, "test/"}, {kMethodKey, "GET"},
+ },
+ {
+ {kStatusKey, "200"}, {kSignature, kSignatureString},
+ });
+ ASSERT_FALSE(header.has_value());
+}
+
+TEST(SignedExchangeHeaderTest, StatefulRequestHeader) {
+ auto header = GenerateHeaderAndParse(
+ {
+ {kUrlKey, "https://test.example.org/test/"},
+ {kMethodKey, "GET"},
+ {"authorization", "Basic Zm9vOmJhcg=="},
+ },
+ {
+ {kStatusKey, "200"}, {kSignature, kSignatureString},
+ });
+ ASSERT_FALSE(header.has_value());
+}
+
+TEST(SignedExchangeHeaderTest, StatefulResponseHeader) {
+ auto header = GenerateHeaderAndParse(
+ {
+ {kUrlKey, "https://test.example.org/test/"}, {kMethodKey, "GET"},
+ },
+ {
+ {kStatusKey, "200"},
+ {kSignature, kSignatureString},
+ {"set-cookie", "foo=bar"},
+ });
+ ASSERT_FALSE(header.has_value());
+}
+
+TEST(SignedExchangeHeaderTest, UppercaseRequestMap) {
+ auto header = GenerateHeaderAndParse(
+ {{kUrlKey, "https://test.example.org/test/"},
+ {kMethodKey, "GET"},
+ {"Accept-Language", "en-us"}},
+ {
+ {kStatusKey, "200"}, {kSignature, kSignatureString},
+ });
+ ASSERT_FALSE(header.has_value());
+}
+
+TEST(SignedExchangeHeaderTest, UppercaseResponseMap) {
+ auto header = GenerateHeaderAndParse(
+ {
+ {kUrlKey, "https://test.example.org/test/"}, {kMethodKey, "GET"},
+ },
+ {{kStatusKey, "200"},
+ {kSignature, kSignatureString},
+ {"Content-Length", "123"}});
+ ASSERT_FALSE(header.has_value());
+}
+
+} // namespace content
diff --git a/chromium/content/browser/web_package/signed_exchange_parser.cc b/chromium/content/browser/web_package/signed_exchange_parser.cc
deleted file mode 100644
index a87f00187a6..00000000000
--- a/chromium/content/browser/web_package/signed_exchange_parser.cc
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/web_package/signed_exchange_parser.h"
-
-namespace content {
-
-SignedExchangeParser::SignedExchangeParser(HeaderCallback header_callback)
- : header_callback_(std::move(header_callback)) {}
-
-SignedExchangeParser::~SignedExchangeParser() = default;
-
-SignedExchangeParser::ConsumeResult SignedExchangeParser::TryConsume(
- base::span<const uint8_t> input,
- size_t* consumed_bytes,
- base::span<uint8_t> output,
- size_t* written) {
- NOTIMPLEMENTED();
- return ConsumeResult::SUCCESS;
-}
-
-} // namespace content
diff --git a/chromium/content/browser/web_package/signed_exchange_parser.h b/chromium/content/browser/web_package/signed_exchange_parser.h
deleted file mode 100644
index 40d149c4ab6..00000000000
--- a/chromium/content/browser/web_package/signed_exchange_parser.h
+++ /dev/null
@@ -1,122 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_WEB_PACKAGE_SIGNED_EXCHANGE_PARSER_H_
-#define CONTENT_BROWSER_WEB_PACKAGE_SIGNED_EXCHANGE_PARSER_H_
-
-#include <stdint.h>
-
-#include "base/callback.h"
-#include "base/containers/span.h"
-#include "base/macros.h"
-#include "content/browser/web_package/signed_exchange_header.h"
-#include "content/common/content_export.h"
-
-namespace content {
-
-// SignedExchangeParser is a streaming parser for signed-exchange envelope
-// format.
-// https://wicg.github.io/webpackage/draft-yasskin-http-origin-signed-responses.html#rfc.section.5
-class CONTENT_EXPORT SignedExchangeParser {
- public:
- using HeaderCallback = base::OnceCallback<void(const SignedExchangeHeader&)>;
-
- explicit SignedExchangeParser(HeaderCallback header_callback);
- ~SignedExchangeParser();
-
- // ConsumeResult is used to communicate the parser state based on what action
- // the callee should take. See also the "Usage example" code in TryConsume()
- // on how to interpret the values.
- enum class ConsumeResult {
- // The parser successfully finished parsing the entire item/HTXG, and
- // ensured that there are no extraneous data.
- SUCCESS,
- // The parser aborted processing input due to invalid data.
- PARSE_ERROR,
- // The parser can yield more output, but needs more data in order to make
- // progress. The caller needs to call again with new |input| containing
- // unconsumed bytes from the previous call and some new data.
- // Note that |output| buffer can also be populated with new data
- // in this case, so caller needs to check |written| and drain it.
- MORE_INPUT_NEEDED,
- // The parser sees more payload in the byte stream, but the |output| buffer
- // was too short to write entire payload. The caller is expected to drain
- // |output| buffer and call again, along with the consumed bytes |input|
- // buffer shift just like done for MORE_INPUT_NEEDED.
- MORE_OUTPUT_AVAILABLE,
- };
-
- // Try to consume an encoded signed-exchange byte stream and make progress.
- //
- // SignedExchangeParser is a streaming parser.
- // e.g. It doesn't require the entire signed-exchange at once, and you are
- // allowed to pass in encoded signed-exchange byte stream in chunks.
- //
- // A signed-exchange byte stream is provided via |input|, and number of
- // |input| bytes consumed in the call is written to |consumed_bytes|.
- // The parser may not consume all the bytes in |input|, and expects that
- // more bytes are appended to the unconsumed bytes when called next time.
- //
- // TryConsume() will synchronously call the HeaderCallback once it is done
- // processing the header part.
- // Once the parser reaches payload part, the payload is extracted to
- // |output|. Number of payload bytes written to |output| buffer is provided
- // to |written|.
- //
- // To complete the parse of a signed-exchange, multiple calls to TryConsume
- // is expected. Please refer to example code below and ConsumeResult enum
- // comments for details.
- //
- // Usage example:
- //
- // std::vector<uint8_t> input;
- // size_t input_valid = read(fd, input.data(), input.size();
- // std::vector<uint8_t> output;
- //
- // for (;;) {
- // size_t consumed_bytes, written;
- // auto cr = parser.TryConsume(input.first(input_valid), &consumed_bytes,
- // output, &written);
- // write(outfd, output.data(), output.data() + written);
- //
- // switch (cr) {
- // case ConsumeResult::SUCCESS:
- // return true;
- // case ConsumeResult::PARSE_ERROR:
- // return false;
- // default:
- // }
- //
- // // Prepare input that didn't get consumed in the previous TryConsume()
- // // call for next TryConsume() call.
- // size_t unconsumed_input = input.size() - consumed_bytes;
- // if (unconsumed_input)
- // memmove(input.data(), input.data() + consumed_bytes, unconsumed_input);
- //
- // switch (cr) {
- // case ConsumeResult::MORE_INPUT_NEEDED:
- // input_valid = read(infd, input.data() + unconsumed_input,
- // consumed_bytes);
- // // read error handling omitted for brevity.
- // break;
- // case ConsumeResult::MORE_OUTPUT_AVAILABLE:
- // break;
- // default:
- // NOTREACHED();
- // }
- // }
- ConsumeResult TryConsume(base::span<const uint8_t> input,
- size_t* consumed_bytes,
- base::span<uint8_t> output,
- size_t* written);
-
- private:
- HeaderCallback header_callback_;
-
- DISALLOW_COPY_AND_ASSIGN(SignedExchangeParser);
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_WEB_PACKAGE_SIGNED_EXCHANGE_PARSER_H_
diff --git a/chromium/content/browser/web_package/signed_exchange_signature_verifier.cc b/chromium/content/browser/web_package/signed_exchange_signature_verifier.cc
index 64254bc5448..bbc94fbeaf9 100644
--- a/chromium/content/browser/web_package/signed_exchange_signature_verifier.cc
+++ b/chromium/content/browser/web_package/signed_exchange_signature_verifier.cc
@@ -5,13 +5,18 @@
#include "content/browser/web_package/signed_exchange_signature_verifier.h"
#include "base/containers/span.h"
+#include "base/format_macros.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
-#include "components/cbor/cbor_values.h"
+#include "base/strings/stringprintf.h"
+#include "base/time/time.h"
+#include "base/trace_event/trace_event.h"
#include "components/cbor/cbor_writer.h"
#include "content/browser/web_package/signed_exchange_consts.h"
+#include "content/browser/web_package/signed_exchange_header.h"
#include "content/browser/web_package/signed_exchange_header_parser.h"
+#include "content/browser/web_package/signed_exchange_utils.h"
#include "crypto/signature_verifier.h"
#include "net/cert/asn1_util.h"
#include "net/cert/x509_util.h"
@@ -20,79 +25,61 @@ namespace content {
namespace {
-// https://wicg.github.io/webpackage/draft-yasskin-http-origin-signed-responses.html#rfc.section.3.6
-// Step 11. "Let message be the concatenation of the following byte strings."
+// https://wicg.github.io/webpackage/draft-yasskin-httpbis-origin-signed-exchanges-impl.html#signature-validity
+// Step 7. "Let message be the concatenation of the following byte strings."
constexpr uint8_t kMessageHeader[] =
- // 11.1. "A string that consists of octet 32 (0x20) repeated 64 times."
+ // 7.1. "A string that consists of octet 32 (0x20) repeated 64 times."
// [spec text]
"\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20"
"\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20"
"\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20"
"\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20"
- // 11.2. "A context string: the ASCII encoding of "HTTP Exchange"."
+ // 7.2. "A context string: the ASCII encoding of "HTTP Exchange"."
// [spec text]
- // 11.3. "A single 0 byte which serves as a separator." [spec text]
+ // 7.3. "A single 0 byte which serves as a separator." [spec text]
"HTTP Exchange";
base::Optional<cbor::CBORValue> GenerateCanonicalRequestCBOR(
- const SignedExchangeSignatureVerifier::Input& input) {
+ const SignedExchangeHeader& header) {
cbor::CBORValue::MapValue map;
map.insert_or_assign(
cbor::CBORValue(kMethodKey, cbor::CBORValue::Type::BYTE_STRING),
- cbor::CBORValue(input.method, cbor::CBORValue::Type::BYTE_STRING));
+ cbor::CBORValue(header.request_method(),
+ cbor::CBORValue::Type::BYTE_STRING));
map.insert_or_assign(
cbor::CBORValue(kUrlKey, cbor::CBORValue::Type::BYTE_STRING),
- cbor::CBORValue(input.url, cbor::CBORValue::Type::BYTE_STRING));
+ cbor::CBORValue(header.request_url().spec(),
+ cbor::CBORValue::Type::BYTE_STRING));
return cbor::CBORValue(map);
}
base::Optional<cbor::CBORValue> GenerateCanonicalResponseCBOR(
- const SignedExchangeSignatureVerifier::Input& input) {
- const auto& headers = input.response_headers;
-
- auto it = headers.find(kSignedHeadersName);
- if (it == headers.end()) {
- DVLOG(1) << "The Signed-Headers http header not found";
- return base::nullopt;
- }
- const std::string& signed_header_value = it->second;
-
- base::Optional<std::vector<std::string>> signed_headers =
- SignedExchangeHeaderParser::ParseSignedHeaders(signed_header_value);
- if (!signed_headers)
- return base::nullopt;
-
+ const SignedExchangeHeader& header) {
+ const auto& headers = header.response_headers();
cbor::CBORValue::MapValue map;
- std::string response_code_str = base::NumberToString(input.response_code);
+ std::string response_code_str = base::NumberToString(header.response_code());
map.insert_or_assign(
cbor::CBORValue(kStatusKey, cbor::CBORValue::Type::BYTE_STRING),
cbor::CBORValue(response_code_str, cbor::CBORValue::Type::BYTE_STRING));
-
- for (const std::string& name : *signed_headers) {
- auto headers_it = headers.find(name);
- if (headers_it == headers.end()) {
- DVLOG(1) << "Signed header \"" << name
- << "\" expected, but not found in response_headers.";
- return base::nullopt;
- }
- const std::string& value = headers_it->second;
+ for (const auto& pair : headers) {
+ if (pair.first == kSignature)
+ continue;
map.insert_or_assign(
- cbor::CBORValue(name, cbor::CBORValue::Type::BYTE_STRING),
- cbor::CBORValue(value, cbor::CBORValue::Type::BYTE_STRING));
+ cbor::CBORValue(pair.first, cbor::CBORValue::Type::BYTE_STRING),
+ cbor::CBORValue(pair.second, cbor::CBORValue::Type::BYTE_STRING));
}
-
return cbor::CBORValue(map);
}
-// Generate CBORValue from |input| as specified in:
-// https://wicg.github.io/webpackage/draft-yasskin-http-origin-signed-responses.html#rfc.section.3.4
+// Generate CBORValue from |header| as specified in:
+// https://wicg.github.io/webpackage/draft-yasskin-httpbis-origin-signed-exchanges-impl.html#cbor-representation
base::Optional<cbor::CBORValue> GenerateCanonicalExchangeHeadersCBOR(
- const SignedExchangeSignatureVerifier::Input& input) {
- auto req_val = GenerateCanonicalRequestCBOR(input);
+ const SignedExchangeHeader& header) {
+ auto req_val = GenerateCanonicalRequestCBOR(header);
if (!req_val)
return base::nullopt;
- auto res_val = GenerateCanonicalResponseCBOR(input);
+ auto res_val = GenerateCanonicalResponseCBOR(header);
if (!res_val)
return base::nullopt;
@@ -103,58 +90,66 @@ base::Optional<cbor::CBORValue> GenerateCanonicalExchangeHeadersCBOR(
}
// Generate a CBOR map value as specified in
-// https://wicg.github.io/webpackage/draft-yasskin-http-origin-signed-responses.html#rfc.section.3.6
-// Step 11.4.
+// https://wicg.github.io/webpackage/draft-yasskin-httpbis-origin-signed-exchanges-impl.html#signature-validity
+// Step 7.4.
base::Optional<cbor::CBORValue> GenerateSignedMessageCBOR(
- const SignedExchangeSignatureVerifier::Input& input) {
- auto headers_val = GenerateCanonicalExchangeHeadersCBOR(input);
+ const SignedExchangeHeader& header) {
+ auto headers_val = GenerateCanonicalExchangeHeadersCBOR(header);
if (!headers_val)
return base::nullopt;
- // 11.4. "The bytes of the canonical CBOR serialization (Section 3.5) of
+ // 7.4. "The bytes of the canonical CBOR serialization (Section 3.4) of
// a CBOR map mapping:" [spec text]
cbor::CBORValue::MapValue map;
- // 11.4.1. "If certSha256 is set: The text string "certSha256" to the byte
+ // 7.4.1. "If certSha256 is set: The text string "certSha256" to the byte
// string value of certSha256." [spec text]
- if (!input.signature.cert_sha256.empty()) {
- map.insert_or_assign(cbor::CBORValue(kCertSha256Key),
- cbor::CBORValue(input.signature.cert_sha256,
- cbor::CBORValue::Type::BYTE_STRING));
+ if (header.signature().cert_sha256.has_value()) {
+ map.insert_or_assign(
+ cbor::CBORValue(kCertSha256Key),
+ cbor::CBORValue(
+ base::StringPiece(reinterpret_cast<const char*>(
+ header.signature().cert_sha256->data),
+ sizeof(header.signature().cert_sha256->data)),
+ cbor::CBORValue::Type::BYTE_STRING));
}
- // 11.4.2. "The text string "validityUrl" to the byte string value of
+ // 7.4.2. "The text string "validityUrl" to the byte string value of
// validityUrl." [spec text]
map.insert_or_assign(cbor::CBORValue(kValidityUrlKey),
- cbor::CBORValue(input.signature.validity_url,
+ cbor::CBORValue(header.signature().validity_url.spec(),
cbor::CBORValue::Type::BYTE_STRING));
- // 11.4.3. "The text string "date" to the integer value of date." [spec text]
- if (!base::IsValueInRangeForNumericType<int64_t>(input.signature.date))
+ // 7.4.3. "The text string "date" to the integer value of date." [spec text]
+ if (!base::IsValueInRangeForNumericType<int64_t>(header.signature().date))
return base::nullopt;
map.insert_or_assign(
cbor::CBORValue(kDateKey),
- cbor::CBORValue(base::checked_cast<int64_t>(input.signature.date)));
- // 11.4.4. "The text string "expires" to the integer value of expires."
+ cbor::CBORValue(base::checked_cast<int64_t>(header.signature().date)));
+ // 7.4.4. "The text string "expires" to the integer value of expires."
// [spec text]
- if (!base::IsValueInRangeForNumericType<int64_t>(input.signature.expires))
+ if (!base::IsValueInRangeForNumericType<int64_t>(header.signature().expires))
return base::nullopt;
map.insert_or_assign(
cbor::CBORValue(kExpiresKey),
- cbor::CBORValue(base::checked_cast<int64_t>(input.signature.expires)));
- // 11.4.5. "The text string "headers" to the CBOR representation
- // (Section 3.4) of exchange's headers." [spec text]
+ cbor::CBORValue(base::checked_cast<int64_t>(header.signature().expires)));
+ // 7.4.5. "The text string "headers" to the CBOR representation
+ // (Section 3.2) of exchange's headers." [spec text]
map.insert_or_assign(cbor::CBORValue(kHeadersKey), std::move(*headers_val));
return cbor::CBORValue(map);
}
-bool VerifySignature(base::span<const uint8_t> sig,
- base::span<const uint8_t> msg,
- scoped_refptr<net::X509Certificate> cert) {
+bool VerifySignature(
+ base::span<const uint8_t> sig,
+ base::span<const uint8_t> msg,
+ scoped_refptr<net::X509Certificate> cert,
+ const signed_exchange_utils::LogCallback& error_message_callback) {
+ TRACE_EVENT_BEGIN0(TRACE_DISABLED_BY_DEFAULT("loading"), "VerifySignature");
base::StringPiece spki;
if (!net::asn1::ExtractSPKIFromDERCert(
net::x509_util::CryptoBufferAsStringPiece(cert->cert_buffer()),
&spki)) {
- DVLOG(1) << "Failed to extract SPKI.";
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "VerifySignature", error_message_callback, "Failed to extract SPKI.");
return false;
}
@@ -165,7 +160,9 @@ bool VerifySignature(base::span<const uint8_t> sig,
if (type != net::X509Certificate::kPublicKeyTypeRSA) {
// TODO(crbug.com/803774): Add support for ecdsa_secp256r1_sha256 and
// ecdsa_secp384r1_sha384.
- DVLOG(1) << "Unsupported public key type: " << type;
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "VerifySignature", error_message_callback,
+ base::StringPrintf("Unsupported public key type: %d", type));
return false;
}
@@ -175,80 +172,173 @@ bool VerifySignature(base::span<const uint8_t> sig,
if (!verifier.VerifyInit(
crypto::SignatureVerifier::RSA_PSS_SHA256, sig.data(), sig.size(),
reinterpret_cast<const uint8_t*>(spki.data()), spki.size())) {
- DVLOG(1) << "VerifyInit failed.";
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "VerifySignature", error_message_callback, "VerifyInit failed.");
return false;
}
verifier.VerifyUpdate(msg.data(), msg.size());
- return verifier.VerifyFinal();
+ if (!verifier.VerifyFinal()) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "VerifySignature", error_message_callback, "VerifyFinal failed.");
+ return false;
+ }
+ TRACE_EVENT_END0(TRACE_DISABLED_BY_DEFAULT("loading"), "VerifySignature");
+ return true;
+}
+
+std::string HexDump(const std::vector<uint8_t>& msg) {
+ std::string output;
+ for (const auto& byte : msg) {
+ base::StringAppendF(&output, "%02x", byte);
+ }
+ return output;
}
base::Optional<std::vector<uint8_t>> GenerateSignedMessage(
- const SignedExchangeSignatureVerifier::Input& input) {
- // GenerateSignedMessageCBOR corresponds to Step 11.4.
- base::Optional<cbor::CBORValue> cbor_val = GenerateSignedMessageCBOR(input);
- if (!cbor_val)
+ const SignedExchangeHeader& header) {
+ TRACE_EVENT_BEGIN0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "GenerateSignedMessage");
+
+ // GenerateSignedMessageCBOR corresponds to Step 7.4.
+ base::Optional<cbor::CBORValue> cbor_val = GenerateSignedMessageCBOR(header);
+ if (!cbor_val) {
+ TRACE_EVENT_END1(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "GenerateSignedMessage", "error",
+ "GenerateSignedMessageCBOR failed.");
return base::nullopt;
+ }
+
base::Optional<std::vector<uint8_t>> cbor_message =
cbor::CBORWriter::Write(*cbor_val);
- if (!cbor_message)
+ if (!cbor_message) {
+ TRACE_EVENT_END1(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "GenerateSignedMessage", "error",
+ "CBORWriter::Write failed.");
return base::nullopt;
+ }
- // https://wicg.github.io/webpackage/draft-yasskin-http-origin-signed-responses.html#rfc.section.3.6
- // Step 11. "Let message be the concatenation of the following byte strings."
+ // https://wicg.github.io/webpackage/draft-yasskin-httpbis-origin-signed-exchanges-impl.html#signature-validity
+ // Step 7. "Let message be the concatenation of the following byte strings."
std::vector<uint8_t> message;
- // see kMessageHeader for Steps 11.1 to 11.3.
+ // see kMessageHeader for Steps 7.1 to 7.3.
message.reserve(arraysize(kMessageHeader) + cbor_message->size());
message.insert(message.end(), std::begin(kMessageHeader),
std::end(kMessageHeader));
- // 11.4. "The text string “headers” to the CBOR representation (Section 3.4)
- // of exchange’s headers." [spec text]
+ // 7.4. "The bytes of the canonical CBOR serialization (Section 3.4) of
+ // a CBOR map mapping:" [spec text]
message.insert(message.end(), cbor_message->begin(), cbor_message->end());
+ TRACE_EVENT_END1(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "GenerateSignedMessage", "dump", HexDump(message));
return message;
}
+base::Time TimeFromSignedExchangeUnixTime(uint64_t t) {
+ return base::Time::UnixEpoch() + base::TimeDelta::FromSeconds(t);
+}
+
+// Implements steps 5-6 of
+// https://wicg.github.io/webpackage/draft-yasskin-httpbis-origin-signed-exchanges-impl.html#signature-validity
+bool VerifyTimestamps(const SignedExchangeHeader& header,
+ const base::Time& verification_time) {
+ base::Time expires_time =
+ TimeFromSignedExchangeUnixTime(header.signature().expires);
+ base::Time creation_time =
+ TimeFromSignedExchangeUnixTime(header.signature().date);
+
+ // 5. "If expires is more than 7 days (604800 seconds) after date, return
+ // "invalid"." [spec text]
+ if ((expires_time - creation_time).InSeconds() > 604800)
+ return false;
+
+ // 6. "If the current time is before date or after expires, return
+ // "invalid"."
+ if (verification_time < creation_time || expires_time < verification_time)
+ return false;
+
+ return true;
+}
+
} // namespace
-SignedExchangeSignatureVerifier::Input::Input() = default;
+SignedExchangeSignatureVerifier::Result SignedExchangeSignatureVerifier::Verify(
+ const SignedExchangeHeader& header,
+ scoped_refptr<net::X509Certificate> certificate,
+ const base::Time& verification_time,
+ const signed_exchange_utils::LogCallback& error_message_callback) {
+ TRACE_EVENT_BEGIN0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeSignatureVerifier::Verify");
+
+ if (!VerifyTimestamps(header, verification_time)) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeSignatureVerifier::Verify", error_message_callback,
+ base::StringPrintf(
+ "Invalid timestamp. creation_time: %" PRIu64
+ ", expires_time: %" PRIu64 ", verification_time: %" PRIu64,
+ header.signature().date, header.signature().expires,
+ (verification_time - base::Time::UnixEpoch()).InSeconds()));
+ return Result::kErrInvalidTimestamp;
+ }
-SignedExchangeSignatureVerifier::Input::Input(const Input&) = default;
+ if (!certificate) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeSignatureVerifier::Verify", error_message_callback,
+ "No certificate set.");
+ return Result::kErrNoCertificate;
+ }
-SignedExchangeSignatureVerifier::Input::~Input() = default;
+ if (!header.signature().cert_sha256.has_value()) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeSignatureVerifier::Verify", error_message_callback,
+ "No certSha256 set.");
+ return Result::kErrNoCertificateSHA256;
+ }
-bool SignedExchangeSignatureVerifier::Verify(const Input& input) {
- // TODO(crbug.com/803774): Verify input.signature.certSha256 against
- // input.certificate.
+ // The main-certificate is the first certificate in certificate-chain.
+ if (*header.signature().cert_sha256 !=
+ net::X509Certificate::CalculateFingerprint256(
+ certificate->cert_buffer())) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeSignatureVerifier::Verify", error_message_callback,
+ "certSha256 mismatch.");
+ return Result::kErrCertificateSHA256Mismatch;
+ }
- auto message = GenerateSignedMessage(input);
+ auto message = GenerateSignedMessage(header);
if (!message) {
- DVLOG(1) << "Failed to reconstruct signed message.";
- return false;
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeSignatureVerifier::Verify", error_message_callback,
+ "Failed to reconstruct signed message.");
+ return Result::kErrInvalidSignatureFormat;
}
- const std::string& sig = input.signature.sig;
+ const std::string& sig = header.signature().sig;
if (!VerifySignature(
base::make_span(reinterpret_cast<const uint8_t*>(sig.data()),
sig.size()),
- *message, input.certificate)) {
- DVLOG(1) << "Failed to verify signature \"sig\".";
- return false;
+ *message, certificate, error_message_callback)) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeSignatureVerifier::Verify", error_message_callback,
+ "Failed to verify signature \"sig\".");
+ return Result::kErrSignatureVerificationFailed;
}
- if (!base::EqualsCaseInsensitiveASCII(input.signature.integrity, "mi")) {
- DVLOG(1)
- << "The current implemention only supports \"mi\" integrity scheme.";
- return false;
+ if (!base::EqualsCaseInsensitiveASCII(header.signature().integrity, "mi")) {
+ signed_exchange_utils::RunErrorMessageCallbackAndEndTraceEvent(
+ "SignedExchangeSignatureVerifier::Verify", error_message_callback,
+ "The current implemention only supports \"mi\" integrity scheme.");
+ return Result::kErrInvalidSignatureIntegrity;
}
- // TODO(crbug.com/803774): Verify input.signature.{date,expires}.
-
- return true;
+ TRACE_EVENT_END0(TRACE_DISABLED_BY_DEFAULT("loading"),
+ "SignedExchangeSignatureVerifier::Verify");
+ return Result::kSuccess;
}
base::Optional<std::vector<uint8_t>>
SignedExchangeSignatureVerifier::EncodeCanonicalExchangeHeaders(
- const SignedExchangeSignatureVerifier::Input& input) {
+ const SignedExchangeHeader& header) {
base::Optional<cbor::CBORValue> cbor_val =
- GenerateCanonicalExchangeHeadersCBOR(input);
+ GenerateCanonicalExchangeHeadersCBOR(header);
if (!cbor_val)
return base::nullopt;
diff --git a/chromium/content/browser/web_package/signed_exchange_signature_verifier.h b/chromium/content/browser/web_package/signed_exchange_signature_verifier.h
index d30dde05311..42260d2d767 100644
--- a/chromium/content/browser/web_package/signed_exchange_signature_verifier.h
+++ b/chromium/content/browser/web_package/signed_exchange_signature_verifier.h
@@ -9,14 +9,21 @@
#include <string>
#include <vector>
+#include "base/callback.h"
#include "base/memory/ref_counted.h"
#include "base/optional.h"
-#include "content/browser/web_package/signed_exchange_header_parser.h"
+#include "content/browser/web_package/signed_exchange_utils.h"
#include "content/common/content_export.h"
#include "net/cert/x509_certificate.h"
+namespace base {
+class Time;
+} // namespace base
+
namespace content {
+class SignedExchangeHeader;
+
// SignedExchangeSignatureVerifier verifies the signature of the given
// signed exchange. This is done by reconstructing the signed message
// and verifying the cryptographic signature enclosed in "Signature" response
@@ -26,28 +33,28 @@ namespace content {
// of the certificate used to generate the signature, which can't be done
// synchronously. (See SignedExchangeCertFetcher for this logic.)
//
-// https://wicg.github.io/webpackage/draft-yasskin-http-origin-signed-responses.html#rfc.section.3.6
+// https://wicg.github.io/webpackage/draft-yasskin-httpbis-origin-signed-exchanges-impl.html#signature-validity
class CONTENT_EXPORT SignedExchangeSignatureVerifier final {
public:
- struct CONTENT_EXPORT Input {
- public:
- Input();
- Input(const Input&);
- ~Input();
-
- std::string method;
- std::string url;
- int response_code;
- std::map<std::string, std::string> response_headers;
-
- SignedExchangeHeaderParser::Signature signature;
- scoped_refptr<net::X509Certificate> certificate;
+ enum class Result {
+ kSuccess,
+ kErrNoCertificate,
+ kErrNoCertificateSHA256,
+ kErrCertificateSHA256Mismatch,
+ kErrInvalidSignatureFormat,
+ kErrSignatureVerificationFailed,
+ kErrInvalidSignatureIntegrity,
+ kErrInvalidTimestamp
};
- static bool Verify(const Input& input);
+ static Result Verify(
+ const SignedExchangeHeader& header,
+ scoped_refptr<net::X509Certificate> certificate,
+ const base::Time& verification_time,
+ const signed_exchange_utils::LogCallback& error_message_callback);
static base::Optional<std::vector<uint8_t>> EncodeCanonicalExchangeHeaders(
- const Input& input);
+ const SignedExchangeHeader& header);
};
} // namespace content
diff --git a/chromium/content/browser/web_package/signed_exchange_signature_verifier_unittest.cc b/chromium/content/browser/web_package/signed_exchange_signature_verifier_unittest.cc
index 17ade678a8d..a2d952aba1a 100644
--- a/chromium/content/browser/web_package/signed_exchange_signature_verifier_unittest.cc
+++ b/chromium/content/browser/web_package/signed_exchange_signature_verifier_unittest.cc
@@ -4,7 +4,10 @@
#include "content/browser/web_package/signed_exchange_signature_verifier.h"
+#include "base/callback.h"
+#include "content/browser/web_package/signed_exchange_header.h"
#include "content/browser/web_package/signed_exchange_header_parser.h"
+#include "content/browser/web_package/signed_exchange_utils.h"
#include "net/cert/x509_certificate.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -13,20 +16,15 @@ namespace content {
namespace {
TEST(SignedExchangeSignatureVerifier, EncodeCanonicalExchangeHeaders) {
- SignedExchangeSignatureVerifier::Input input;
- input.method = "GET";
- input.url = "https://example.com/index.html";
- input.response_code = 200;
- input.response_headers.insert(
- std::make_pair("content-type", "text/html; charset=utf-8"));
- input.response_headers.insert(
- std::make_pair("content-encoding", "mi-sha256"));
- input.response_headers.insert(std::make_pair("unsigned-header", "foobar"));
- input.response_headers.insert(std::make_pair(
- "signed-headers", "\"content-type\", \"content-encoding\""));
+ SignedExchangeHeader header;
+ header.set_request_method("GET");
+ header.set_request_url(GURL("https://example.com/index.html"));
+ header.set_response_code(net::HTTP_OK);
+ header.AddResponseHeader("content-type", "text/html; charset=utf-8");
+ header.AddResponseHeader("content-encoding", "mi-sha256");
base::Optional<std::vector<uint8_t>> encoded =
- SignedExchangeSignatureVerifier::EncodeCanonicalExchangeHeaders(input);
+ SignedExchangeSignatureVerifier::EncodeCanonicalExchangeHeaders(header);
ASSERT_TRUE(encoded.has_value());
static const uint8_t kExpected[] = {
@@ -62,6 +60,9 @@ TEST(SignedExchangeSignatureVerifier, EncodeCanonicalExchangeHeaders) {
testing::ElementsAreArray(kExpected, arraysize(kExpected)));
}
+const uint64_t kSignatureHeaderDate = 1517892341;
+const uint64_t kSignatureHeaderExpires = 1517895941;
+
// clang-format off
constexpr char kSignatureHeader[] =
"sig; "
@@ -77,6 +78,23 @@ constexpr char kSignatureHeader[] =
"date=1517892341; expires=1517895941";
// clang-format on
+// |expires| (1518497142) is more than 7 days (604800 seconds) after |date|
+// (1517892341).
+// clang-format off
+constexpr char kSignatureHeaderInvalidExpires[] =
+ "sig; "
+ "sig=*RhjjWuXi87riQUu90taBHFJgTo8XBhiCe9qTJMP7/XVPu2diRGipo06HoGsyXkidHiiW"
+ "743JgoNmO7CjfeVXLXQgKDxtGidATtPsVadAT4JpBDZJWSUg5qAbWcASXjyO38Uhq9gJkeu4w"
+ "1MRMGkvpgVXNjYhi5/9NUer1xEUuJh5UbIDhGrfMihwj+c30nW+qz0n5lCrYonk+Sc0jGcLgc"
+ "aDLptqRhOG5S+avwKmbQoqtD0JSc/53L5xXjppyvSA2fRmoDlqVQpX4uzRKq9cny7fZ3qgpZ/"
+ "YOCuT7wMj7oVEur175QLe2F8ktKH9arSEiquhFJxBIIIXza8PJnmL5w;"
+ "validityUrl=\"https://example.com/resource.validity.msg\"; "
+ "integrity=\"mi\"; "
+ "certUrl=\"https://example.com/cert.msg\"; "
+ "certSha256=*3wfzkF4oKGUwoQ0rE7U11FIdcA/8biGzlaACeRQQH6k; "
+ "date=1517892341; expires=1518497142";
+// clang-format on
+
constexpr char kCertPEM[] = R"(
-----BEGIN CERTIFICATE-----
MIID9zCCAt+gAwIBAgIUde2ndSB4271TAGDk0Ft+WuCCGnMwDQYJKoZIhvcNAQEL
@@ -104,7 +122,11 @@ wYxI2+BLS6X5NpI=
-----END CERTIFICATE-----)";
TEST(SignedExchangeSignatureVerifier, Verify) {
- auto signature = SignedExchangeHeaderParser::ParseSignature(kSignatureHeader);
+ base::Time verification_time =
+ base::Time::UnixEpoch() +
+ base::TimeDelta::FromSeconds(kSignatureHeaderDate);
+ auto signature = SignedExchangeHeaderParser::ParseSignature(
+ kSignatureHeader, signed_exchange_utils::LogCallback());
ASSERT_TRUE(signature.has_value());
ASSERT_EQ(1u, signature->size());
@@ -113,30 +135,83 @@ TEST(SignedExchangeSignatureVerifier, Verify) {
kCertPEM, arraysize(kCertPEM), net::X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1u, certlist.size());
- SignedExchangeSignatureVerifier::Input input;
- input.method = "GET";
- input.url = "https://example.com/index.html";
- input.response_code = 200;
- input.response_headers.insert(
- std::make_pair("content-type", "text/html; charset=utf-8"));
- input.response_headers.insert(
- std::make_pair("content-encoding", "mi-sha256"));
- input.response_headers.insert(std::make_pair(
- "mi", "mi-sha256=4ld4G-h-sQSoLBD39ndIO15O_82NXSzq9UMFEYI02JQ"));
- input.response_headers.insert(std::make_pair(
- "signed-headers", "\"content-type\", \"content-encoding\", \"mi\""));
- input.signature = (*signature)[0];
- input.certificate = certlist[0];
-
- EXPECT_TRUE(SignedExchangeSignatureVerifier::Verify(input));
-
- SignedExchangeSignatureVerifier::Input corrupted_input(input);
- corrupted_input.url = "https://example.com/bad.html";
- EXPECT_FALSE(SignedExchangeSignatureVerifier::Verify(corrupted_input));
-
- SignedExchangeSignatureVerifier::Input badsig_input(input);
- badsig_input.signature.sig[0]++;
- EXPECT_FALSE(SignedExchangeSignatureVerifier::Verify(badsig_input));
+ SignedExchangeHeader header;
+ header.set_request_method("GET");
+ header.set_request_url(GURL("https://example.com/index.html"));
+ header.set_response_code(net::HTTP_OK);
+ header.AddResponseHeader("content-type", "text/html; charset=utf-8");
+ header.AddResponseHeader("content-encoding", "mi-sha256");
+ header.AddResponseHeader(
+ "mi", "mi-sha256=4ld4G-h-sQSoLBD39ndIO15O_82NXSzq9UMFEYI02JQ");
+ header.SetSignatureForTesting((*signature)[0]);
+
+ auto certificate = certlist[0];
+
+ EXPECT_EQ(SignedExchangeSignatureVerifier::Result::kSuccess,
+ SignedExchangeSignatureVerifier::Verify(
+ header, certificate, verification_time,
+ signed_exchange_utils::LogCallback()));
+
+ EXPECT_EQ(SignedExchangeSignatureVerifier::Result::kErrInvalidTimestamp,
+ SignedExchangeSignatureVerifier::Verify(
+ header, certificate,
+ base::Time::UnixEpoch() +
+ base::TimeDelta::FromSeconds(kSignatureHeaderDate - 1),
+ signed_exchange_utils::LogCallback()));
+
+ EXPECT_EQ(SignedExchangeSignatureVerifier::Result::kSuccess,
+ SignedExchangeSignatureVerifier::Verify(
+ header, certificate,
+ base::Time::UnixEpoch() +
+ base::TimeDelta::FromSeconds(kSignatureHeaderExpires),
+ signed_exchange_utils::LogCallback()));
+
+ EXPECT_EQ(SignedExchangeSignatureVerifier::Result::kErrInvalidTimestamp,
+ SignedExchangeSignatureVerifier::Verify(
+ header, certificate,
+ base::Time::UnixEpoch() +
+ base::TimeDelta::FromSeconds(kSignatureHeaderExpires + 1),
+ signed_exchange_utils::LogCallback()));
+
+ SignedExchangeHeader invalid_expires_header(header);
+ auto invalid_expires_signature = SignedExchangeHeaderParser::ParseSignature(
+ kSignatureHeaderInvalidExpires, signed_exchange_utils::LogCallback());
+ ASSERT_TRUE(invalid_expires_signature.has_value());
+ ASSERT_EQ(1u, invalid_expires_signature->size());
+ invalid_expires_header.SetSignatureForTesting(
+ (*invalid_expires_signature)[0]);
+ EXPECT_EQ(SignedExchangeSignatureVerifier::Result::kErrInvalidTimestamp,
+ SignedExchangeSignatureVerifier::Verify(
+ invalid_expires_header, certificate, verification_time,
+ signed_exchange_utils::LogCallback()));
+
+ SignedExchangeHeader corrupted_header(header);
+ corrupted_header.set_request_url(GURL("https://example.com/bad.html"));
+ EXPECT_EQ(
+ SignedExchangeSignatureVerifier::Result::kErrSignatureVerificationFailed,
+ SignedExchangeSignatureVerifier::Verify(
+ corrupted_header, certificate, verification_time,
+ signed_exchange_utils::LogCallback()));
+
+ SignedExchangeHeader badsig_header(header);
+ SignedExchangeHeaderParser::Signature badsig = header.signature();
+ badsig.sig[0]++;
+ badsig_header.SetSignatureForTesting(badsig);
+ EXPECT_EQ(
+ SignedExchangeSignatureVerifier::Result::kErrSignatureVerificationFailed,
+ SignedExchangeSignatureVerifier::Verify(
+ badsig_header, certificate, verification_time,
+ signed_exchange_utils::LogCallback()));
+
+ SignedExchangeHeader badsigsha256_header(header);
+ SignedExchangeHeaderParser::Signature badsigsha256 = header.signature();
+ badsigsha256.cert_sha256->data[0]++;
+ badsigsha256_header.SetSignatureForTesting(badsigsha256);
+ EXPECT_EQ(
+ SignedExchangeSignatureVerifier::Result::kErrCertificateSHA256Mismatch,
+ SignedExchangeSignatureVerifier::Verify(
+ badsigsha256_header, certificate, verification_time,
+ signed_exchange_utils::LogCallback()));
}
} // namespace
diff --git a/chromium/content/browser/web_package/signed_exchange_url_loader_factory_for_non_network_service.cc b/chromium/content/browser/web_package/signed_exchange_url_loader_factory_for_non_network_service.cc
index ce522a3ab72..ce2bce7b937 100644
--- a/chromium/content/browser/web_package/signed_exchange_url_loader_factory_for_non_network_service.cc
+++ b/chromium/content/browser/web_package/signed_exchange_url_loader_factory_for_non_network_service.cc
@@ -50,7 +50,7 @@ void SignedExchangeURLLoaderFactoryForNonNetworkService::CreateLoaderAndStart(
std::move(client), traffic_annotation);
}
-std::unique_ptr<SharedURLLoaderFactoryInfo>
+std::unique_ptr<network::SharedURLLoaderFactoryInfo>
SignedExchangeURLLoaderFactoryForNonNetworkService::Clone() {
NOTREACHED();
return nullptr;
diff --git a/chromium/content/browser/web_package/signed_exchange_url_loader_factory_for_non_network_service.h b/chromium/content/browser/web_package/signed_exchange_url_loader_factory_for_non_network_service.h
index 8ae02c93b7d..e101f3d060e 100644
--- a/chromium/content/browser/web_package/signed_exchange_url_loader_factory_for_non_network_service.h
+++ b/chromium/content/browser/web_package/signed_exchange_url_loader_factory_for_non_network_service.h
@@ -6,7 +6,7 @@
#define CONTENT_BROWSER_WEB_PACKAGE_SIGNED_EXCHANGE_URL_LOADER_FACTORY_FOR_NON_NETWORK_SERVICE_H_
#include "content/public/common/resource_type.h"
-#include "content/public/common/shared_url_loader_factory.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
namespace net {
class URLRequestContextGetter;
@@ -14,13 +14,12 @@ class URLRequestContextGetter;
namespace content {
-class URLRequestContextGetter;
class ResourceContext;
// A URLLoaderFactory used for fetching certificate of signed HTTP exchange
// when NetworkService is not enabled.
class SignedExchangeURLLoaderFactoryForNonNetworkService
- : public SharedURLLoaderFactory {
+ : public network::SharedURLLoaderFactory {
public:
SignedExchangeURLLoaderFactoryForNonNetworkService(
ResourceContext* resource_context,
@@ -35,7 +34,7 @@ class SignedExchangeURLLoaderFactoryForNonNetworkService
network::mojom::URLLoaderClientPtr client,
const net::MutableNetworkTrafficAnnotationTag&
traffic_annotation) override;
- std::unique_ptr<SharedURLLoaderFactoryInfo> Clone() override;
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo> Clone() override;
private:
~SignedExchangeURLLoaderFactoryForNonNetworkService() override;
diff --git a/chromium/content/browser/web_package/signed_exchange_utils.cc b/chromium/content/browser/web_package/signed_exchange_utils.cc
new file mode 100644
index 00000000000..5fa03263441
--- /dev/null
+++ b/chromium/content/browser/web_package/signed_exchange_utils.cc
@@ -0,0 +1,24 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/web_package/signed_exchange_utils.h"
+
+#include "base/callback.h"
+#include "base/trace_event/trace_event.h"
+
+namespace content {
+namespace signed_exchange_utils {
+
+void RunErrorMessageCallbackAndEndTraceEvent(const char* name,
+ const LogCallback& callback,
+ const std::string& error_message) {
+ if (callback)
+ callback.Run(error_message);
+
+ TRACE_EVENT_END1(TRACE_DISABLED_BY_DEFAULT("loading"), name, "error",
+ error_message);
+}
+
+} // namespace signed_exchange_utils
+} // namespace content
diff --git a/chromium/content/browser/web_package/signed_exchange_utils.h b/chromium/content/browser/web_package/signed_exchange_utils.h
new file mode 100644
index 00000000000..d48d8347ad1
--- /dev/null
+++ b/chromium/content/browser/web_package/signed_exchange_utils.h
@@ -0,0 +1,27 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_BROWSER_WEB_PACKAGE_SIGNED_EXCHANGE_UTILS_H_
+#define CONTENT_BROWSER_WEB_PACKAGE_SIGNED_EXCHANGE_UTILS_H_
+
+#include <string>
+
+#include "base/callback_forward.h"
+
+namespace content {
+namespace signed_exchange_utils {
+
+using LogCallback = base::RepeatingCallback<void(const std::string&)>;
+
+// Runs |callback| with |error_message| if |callback| is not null. And calls
+// TRACE_EVENT_END() with "disabled-by-default-loading" category, |name| and
+// |error_meassage|.
+void RunErrorMessageCallbackAndEndTraceEvent(const char* name,
+ const LogCallback& callback,
+ const std::string& error_message);
+
+} // namespace signed_exchange_utils
+} // namespace content
+
+#endif // CONTENT_BROWSER_WEB_PACKAGE_SIGNED_EXCHANGE_UTILS_H_
diff --git a/chromium/content/browser/web_package/web_package_context_impl.cc b/chromium/content/browser/web_package/web_package_context_impl.cc
new file mode 100644
index 00000000000..86367c49ad5
--- /dev/null
+++ b/chromium/content/browser/web_package/web_package_context_impl.cc
@@ -0,0 +1,22 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/web_package/web_package_context_impl.h"
+
+#include "content/browser/web_package/signed_exchange_handler.h"
+#include "content/public/browser/browser_thread.h"
+
+namespace content {
+
+WebPackageContextImpl::WebPackageContextImpl() = default;
+
+WebPackageContextImpl::~WebPackageContextImpl() = default;
+
+void WebPackageContextImpl::SetSignedExchangeVerificationTimeForTesting(
+ base::Optional<base::Time> time) {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+ SignedExchangeHandler::SetVerificationTimeForTesting(time);
+}
+
+} // namespace content
diff --git a/chromium/content/browser/web_package/web_package_context_impl.h b/chromium/content/browser/web_package/web_package_context_impl.h
new file mode 100644
index 00000000000..b0c198d5fd2
--- /dev/null
+++ b/chromium/content/browser/web_package/web_package_context_impl.h
@@ -0,0 +1,24 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_BROWSER_WEB_PACKAGE_WEB_PACKAGE_CONTEXT_IMPL_H_
+#define CONTENT_BROWSER_WEB_PACKAGE_WEB_PACKAGE_CONTEXT_IMPL_H_
+
+#include "content/public/browser/web_package_context.h"
+
+#include "content/common/content_export.h"
+
+namespace content {
+
+class WebPackageContextImpl : public WebPackageContext {
+ public:
+ WebPackageContextImpl();
+ ~WebPackageContextImpl() override;
+ void SetSignedExchangeVerificationTimeForTesting(
+ base::Optional<base::Time> time) override;
+};
+
+} // namespace content
+
+#endif // CONTENT_BROWSER_WEB_PACKAGE_WEB_PACKAGE_CONTEXT_IMPL_H_
diff --git a/chromium/content/browser/web_package/web_package_loader.cc b/chromium/content/browser/web_package/web_package_loader.cc
index d055039da2f..6e563d35a87 100644
--- a/chromium/content/browser/web_package/web_package_loader.cc
+++ b/chromium/content/browser/web_package/web_package_loader.cc
@@ -10,12 +10,14 @@
#include "base/strings/stringprintf.h"
#include "content/browser/loader/data_pipe_to_source_stream.h"
#include "content/browser/loader/source_stream_to_data_pipe.h"
+#include "content/browser/web_package/signed_exchange_cert_fetcher_factory.h"
#include "content/browser/web_package/signed_exchange_handler.h"
#include "content/public/common/content_features.h"
-#include "content/public/common/shared_url_loader_factory.h"
#include "net/cert/cert_status_flags.h"
#include "net/http/http_util.h"
+#include "net/url_request/url_request_context_getter.h"
#include "services/network/public/cpp/features.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/cpp/url_loader_completion_status.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
@@ -78,18 +80,28 @@ WebPackageLoader::WebPackageLoader(
network::mojom::URLLoaderClientEndpointsPtr endpoints,
url::Origin request_initiator,
uint32_t url_loader_options,
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory,
- URLLoaderThrottlesGetter url_loader_throttles_getter)
+ int frame_tree_node_id,
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
+ URLLoaderThrottlesGetter url_loader_throttles_getter,
+ scoped_refptr<net::URLRequestContextGetter> request_context_getter)
: original_response_timing_info_(
std::make_unique<ResponseTimingInfo>(original_response)),
forwarding_client_(std::move(forwarding_client)),
url_loader_client_binding_(this),
request_initiator_(request_initiator),
url_loader_options_(url_loader_options),
+ frame_tree_node_id_(frame_tree_node_id),
url_loader_factory_(std::move(url_loader_factory)),
url_loader_throttles_getter_(std::move(url_loader_throttles_getter)),
+ request_context_getter_(std::move(request_context_getter)),
weak_factory_(this) {
DCHECK(base::FeatureList::IsEnabled(features::kSignedHTTPExchange));
+
+ // Can't use HttpResponseHeaders::GetMimeType() because SignedExchangeHandler
+ // checks "v=" parameter.
+ original_response.headers->EnumerateHeader(nullptr, "content-type",
+ &content_type_);
+
url_loader_.Bind(std::move(endpoints->url_loader));
if (url_loader_options_ &
@@ -113,7 +125,6 @@ WebPackageLoader::~WebPackageLoader() = default;
void WebPackageLoader::OnReceiveResponse(
const network::ResourceResponseHead& response_head,
- const base::Optional<net::SSLInfo>& ssl_info,
network::mojom::DownloadedTempFilePtr downloaded_file) {
// Must not be called because this WebPackageLoader and the client endpoints
// were bound after OnReceiveResponse() is called.
@@ -156,22 +167,25 @@ void WebPackageLoader::OnTransferSizeUpdated(int32_t transfer_size_diff) {
void WebPackageLoader::OnStartLoadingResponseBody(
mojo::ScopedDataPipeConsumerHandle body) {
+ auto cert_fetcher_factory = SignedExchangeCertFetcherFactory::Create(
+ std::move(request_initiator_), std::move(url_loader_factory_),
+ std::move(url_loader_throttles_getter_));
+
if (g_signed_exchange_factory_for_testing_) {
signed_exchange_handler_ = g_signed_exchange_factory_for_testing_->Create(
std::make_unique<DataPipeToSourceStream>(std::move(body)),
base::BindOnce(&WebPackageLoader::OnHTTPExchangeFound,
weak_factory_.GetWeakPtr()),
- std::move(request_initiator_), std::move(url_loader_factory_),
- std::move(url_loader_throttles_getter_));
+ std::move(cert_fetcher_factory));
return;
}
signed_exchange_handler_ = std::make_unique<SignedExchangeHandler>(
- std::make_unique<DataPipeToSourceStream>(std::move(body)),
+ content_type_, std::make_unique<DataPipeToSourceStream>(std::move(body)),
base::BindOnce(&WebPackageLoader::OnHTTPExchangeFound,
weak_factory_.GetWeakPtr()),
- std::move(request_initiator_), std::move(url_loader_factory_),
- std::move(url_loader_throttles_getter_));
+ std::move(cert_fetcher_factory), std::move(request_context_getter_),
+ frame_tree_node_id_);
}
void WebPackageLoader::OnComplete(
@@ -217,8 +231,7 @@ void WebPackageLoader::OnHTTPExchangeFound(
const GURL& request_url,
const std::string& request_method,
const network::ResourceResponseHead& resource_response,
- std::unique_ptr<net::SourceStream> payload_stream,
- base::Optional<net::SSLInfo> ssl_info) {
+ std::unique_ptr<net::SourceStream> payload_stream) {
if (error) {
// This will eventually delete |this|.
forwarding_client_->OnComplete(network::URLLoaderCompletionStatus(error));
@@ -232,19 +245,24 @@ void WebPackageLoader::OnHTTPExchangeFound(
std::move(original_response_timing_info_)->CreateRedirectResponseHead());
forwarding_client_.reset();
- if (ssl_info &&
+ const base::Optional<net::SSLInfo>& ssl_info = resource_response.ssl_info;
+ if (ssl_info.has_value() &&
(url_loader_options_ &
network::mojom::kURLLoadOptionSendSSLInfoForCertificateError) &&
net::IsCertStatusError(ssl_info->cert_status) &&
!net::IsCertStatusMinorError(ssl_info->cert_status)) {
ssl_info_ = ssl_info;
}
- if (!(url_loader_options_ &
+ if (ssl_info.has_value() &&
+ !(url_loader_options_ &
network::mojom::kURLLoadOptionSendSSLInfoWithResponse)) {
- ssl_info = base::nullopt;
+ network::ResourceResponseHead response_info = resource_response;
+ response_info.ssl_info = base::nullopt;
+ client_->OnReceiveResponse(response_info, nullptr /* downloaded_file */);
+ } else {
+ client_->OnReceiveResponse(resource_response,
+ nullptr /* downloaded_file */);
}
- client_->OnReceiveResponse(resource_response, std::move(ssl_info),
- nullptr /* downloaded_file */);
// Currently we always assume that we have body.
// TODO(https://crbug.com/80374): Add error handling and bail out
diff --git a/chromium/content/browser/web_package/web_package_loader.h b/chromium/content/browser/web_package/web_package_loader.h
index 80fbddf969a..115bc2b8513 100644
--- a/chromium/content/browser/web_package/web_package_loader.h
+++ b/chromium/content/browser/web_package/web_package_loader.h
@@ -17,11 +17,15 @@
namespace net {
class SourceStream;
+class URLRequestContextGetter;
} // namespace net
+namespace network {
+class SharedURLLoaderFactory;
+} // namespace network
+
namespace content {
-class SharedURLLoaderFactory;
class SignedExchangeHandler;
class SignedExchangeHandlerFactory;
class URLLoaderThrottle;
@@ -38,20 +42,22 @@ class WebPackageLoader final : public network::mojom::URLLoaderClient,
using URLLoaderThrottlesGetter = base::RepeatingCallback<
std::vector<std::unique_ptr<content::URLLoaderThrottle>>()>;
- WebPackageLoader(const network::ResourceResponseHead& original_response,
- network::mojom::URLLoaderClientPtr forwarding_client,
- network::mojom::URLLoaderClientEndpointsPtr endpoints,
- url::Origin request_initiator,
- uint32_t url_loader_options,
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory,
- URLLoaderThrottlesGetter url_loader_throttles_getter);
+ WebPackageLoader(
+ const network::ResourceResponseHead& original_response,
+ network::mojom::URLLoaderClientPtr forwarding_client,
+ network::mojom::URLLoaderClientEndpointsPtr endpoints,
+ url::Origin request_initiator,
+ uint32_t url_loader_options,
+ int frame_tree_node_id,
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
+ URLLoaderThrottlesGetter url_loader_throttles_getter,
+ scoped_refptr<net::URLRequestContextGetter> request_context_getter);
~WebPackageLoader() override;
// network::mojom::URLLoaderClient implementation
// Only OnStartLoadingResponseBody() and OnComplete() are called.
void OnReceiveResponse(
const network::ResourceResponseHead& response_head,
- const base::Optional<net::SSLInfo>& ssl_info,
network::mojom::DownloadedTempFilePtr downloaded_file) override;
void OnReceiveRedirect(
const net::RedirectInfo& redirect_info,
@@ -90,8 +96,7 @@ class WebPackageLoader final : public network::mojom::URLLoaderClient,
const GURL& request_url,
const std::string& request_method,
const network::ResourceResponseHead& resource_response,
- std::unique_ptr<net::SourceStream> payload_stream,
- base::Optional<net::SSLInfo> ssl_info);
+ std::unique_ptr<net::SourceStream> payload_stream);
void FinishReadingBody(int result);
@@ -121,11 +126,15 @@ class WebPackageLoader final : public network::mojom::URLLoaderClient,
url::Origin request_initiator_;
const uint32_t url_loader_options_;
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory_;
+ const int frame_tree_node_id_;
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
URLLoaderThrottlesGetter url_loader_throttles_getter_;
+ scoped_refptr<net::URLRequestContextGetter> request_context_getter_;
base::Optional<net::SSLInfo> ssl_info_;
+ std::string content_type_;
+
base::WeakPtrFactory<WebPackageLoader> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(WebPackageLoader);
diff --git a/chromium/content/browser/web_package/web_package_prefetch_handler.cc b/chromium/content/browser/web_package/web_package_prefetch_handler.cc
index 0827f954c23..40f151b71f0 100644
--- a/chromium/content/browser/web_package/web_package_prefetch_handler.cc
+++ b/chromium/content/browser/web_package/web_package_prefetch_handler.cc
@@ -7,8 +7,8 @@
#include "content/browser/web_package/signed_exchange_url_loader_factory_for_non_network_service.h"
#include "content/browser/web_package/web_package_loader.h"
#include "content/browser/web_package/web_package_request_handler.h"
-#include "content/common/weak_wrapper_shared_url_loader_factory.h"
#include "content/public/common/content_features.h"
+#include "content/public/common/weak_wrapper_shared_url_loader_factory.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "net/url_request/url_request_context_getter.h"
#include "services/network/public/cpp/features.h"
@@ -29,10 +29,11 @@ bool WebPackagePrefetchHandler::IsResponseForWebPackage(
}
WebPackagePrefetchHandler::WebPackagePrefetchHandler(
+ int frame_tree_node_id,
const network::ResourceResponseHead& response,
network::mojom::URLLoaderPtr network_loader,
network::mojom::URLLoaderClientRequest network_client_request,
- scoped_refptr<SharedURLLoaderFactory> network_loader_factory,
+ scoped_refptr<network::SharedURLLoaderFactory> network_loader_factory,
url::Origin request_initiator,
URLLoaderThrottlesGetter loader_throttles_getter,
ResourceContext* resource_context,
@@ -45,7 +46,7 @@ WebPackagePrefetchHandler::WebPackagePrefetchHandler(
std::move(network_client_request));
network::mojom::URLLoaderClientPtr client;
loader_client_binding_.Bind(mojo::MakeRequest(&client));
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory;
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory;
if (!base::FeatureList::IsEnabled(network::features::kNetworkService)) {
url_loader_factory = base::MakeRefCounted<
SignedExchangeURLLoaderFactoryForNonNetworkService>(
@@ -56,7 +57,8 @@ WebPackagePrefetchHandler::WebPackagePrefetchHandler(
web_package_loader_ = std::make_unique<WebPackageLoader>(
response, std::move(client), std::move(endpoints),
std::move(request_initiator), network::mojom::kURLLoadOptionNone,
- std::move(url_loader_factory), loader_throttles_getter);
+ frame_tree_node_id, std::move(url_loader_factory),
+ loader_throttles_getter, request_context_getter);
}
WebPackagePrefetchHandler::~WebPackagePrefetchHandler() = default;
@@ -75,7 +77,6 @@ WebPackagePrefetchHandler::FollowRedirect(
void WebPackagePrefetchHandler::OnReceiveResponse(
const network::ResourceResponseHead& head,
- const base::Optional<net::SSLInfo>& ssl_info,
network::mojom::DownloadedTempFilePtr downloaded_file) {
NOTREACHED();
}
diff --git a/chromium/content/browser/web_package/web_package_prefetch_handler.h b/chromium/content/browser/web_package/web_package_prefetch_handler.h
index 97158c2a45e..cd69ad6c9b8 100644
--- a/chromium/content/browser/web_package/web_package_prefetch_handler.h
+++ b/chromium/content/browser/web_package/web_package_prefetch_handler.h
@@ -13,11 +13,14 @@ namespace net {
class URLRequestContextGetter;
}
+namespace network {
+class SharedURLLoaderFactory;
+}
+
namespace content {
class ResourceContext;
class URLLoaderThrottle;
-class SharedURLLoaderFactory;
class WebPackageLoader;
// Attached to each PrefetchURLLoader if the prefetch is for a signed exchange.
@@ -34,10 +37,11 @@ class WebPackagePrefetchHandler final : public network::mojom::URLLoaderClient {
// |forwarding_client| is a pointer to the downstream client (typically who
// creates this handler).
WebPackagePrefetchHandler(
+ int frame_tree_node_id,
const network::ResourceResponseHead& response,
network::mojom::URLLoaderPtr network_loader,
network::mojom::URLLoaderClientRequest network_client_request,
- scoped_refptr<SharedURLLoaderFactory> network_loader_factory,
+ scoped_refptr<network::SharedURLLoaderFactory> network_loader_factory,
url::Origin request_initiator,
URLLoaderThrottlesGetter loader_throttles_getter,
ResourceContext* resource_context,
@@ -58,7 +62,6 @@ class WebPackagePrefetchHandler final : public network::mojom::URLLoaderClient {
// network::mojom::URLLoaderClient overrides:
void OnReceiveResponse(
const network::ResourceResponseHead& head,
- const base::Optional<net::SSLInfo>& ssl_info,
network::mojom::DownloadedTempFilePtr downloaded_file) override;
void OnReceiveRedirect(const net::RedirectInfo& redirect_info,
const network::ResourceResponseHead& head) override;
diff --git a/chromium/content/browser/web_package/web_package_request_handler.cc b/chromium/content/browser/web_package/web_package_request_handler.cc
index 91a58605787..8eadeabc9f2 100644
--- a/chromium/content/browser/web_package/web_package_request_handler.cc
+++ b/chromium/content/browser/web_package/web_package_request_handler.cc
@@ -11,10 +11,11 @@
#include "content/browser/web_package/web_package_loader.h"
#include "content/common/throttling_url_loader.h"
#include "content/public/common/content_features.h"
-#include "content/public/common/shared_url_loader_factory.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "net/http/http_response_headers.h"
+#include "net/url_request/url_request_context_getter.h"
#include "services/network/public/cpp/resource_response.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/mojom/url_loader.mojom.h"
namespace content {
@@ -23,18 +24,22 @@ namespace content {
bool WebPackageRequestHandler::IsSupportedMimeType(
const std::string& mime_type) {
DCHECK(base::FeatureList::IsEnabled(features::kSignedHTTPExchange));
- return mime_type == "application/http-exchange+cbor";
+ return mime_type == "application/signed-exchange";
}
WebPackageRequestHandler::WebPackageRequestHandler(
url::Origin request_initiator,
uint32_t url_loader_options,
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory,
- URLLoaderThrottlesGetter url_loader_throttles_getter)
+ int frame_tree_node_id,
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
+ URLLoaderThrottlesGetter url_loader_throttles_getter,
+ scoped_refptr<net::URLRequestContextGetter> request_context_getter)
: request_initiator_(std::move(request_initiator)),
url_loader_options_(url_loader_options),
+ frame_tree_node_id_(frame_tree_node_id),
url_loader_factory_(url_loader_factory),
url_loader_throttles_getter_(std::move(url_loader_throttles_getter)),
+ request_context_getter_(std::move(request_context_getter)),
weak_factory_(this) {
DCHECK(base::FeatureList::IsEnabled(features::kSignedHTTPExchange));
}
@@ -78,8 +83,9 @@ bool WebPackageRequestHandler::MaybeCreateLoaderForResponse(
// to support SafeBrowsing checking of the content of the WebPackage.
web_package_loader_ = std::make_unique<WebPackageLoader>(
response, std::move(client), url_loader->Unbind(),
- std::move(request_initiator_), url_loader_options_,
- std::move(url_loader_factory_), std::move(url_loader_throttles_getter_));
+ std::move(request_initiator_), url_loader_options_, frame_tree_node_id_,
+ std::move(url_loader_factory_), std::move(url_loader_throttles_getter_),
+ std::move(request_context_getter_));
return true;
}
diff --git a/chromium/content/browser/web_package/web_package_request_handler.h b/chromium/content/browser/web_package/web_package_request_handler.h
index dda5c7ef286..d988475af35 100644
--- a/chromium/content/browser/web_package/web_package_request_handler.h
+++ b/chromium/content/browser/web_package/web_package_request_handler.h
@@ -6,17 +6,24 @@
#define CONTENT_BROWSER_WEB_PACKAGE_WEB_PACKAGE_REQUEST_HANDLER_H_
#include "base/memory/weak_ptr.h"
-#include "content/browser/loader/url_loader_request_handler.h"
+#include "content/browser/loader/navigation_loader_interceptor.h"
#include "content/public/common/resource_type.h"
#include "url/origin.h"
-namespace content {
+namespace net {
+class URLRequestContextGetter;
+} // namespace net
+namespace network {
class SharedURLLoaderFactory;
+} // namespace network
+
+namespace content {
+
class URLLoaderThrottle;
class WebPackageLoader;
-class WebPackageRequestHandler final : public URLLoaderRequestHandler {
+class WebPackageRequestHandler final : public NavigationLoaderInterceptor {
public:
using URLLoaderThrottlesGetter = base::RepeatingCallback<
std::vector<std::unique_ptr<content::URLLoaderThrottle>>()>;
@@ -26,11 +33,13 @@ class WebPackageRequestHandler final : public URLLoaderRequestHandler {
WebPackageRequestHandler(
url::Origin request_initiator,
uint32_t url_loader_options,
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory,
- URLLoaderThrottlesGetter url_loader_throttles_getter);
+ int frame_tree_node_id,
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
+ URLLoaderThrottlesGetter url_loader_throttles_getter,
+ scoped_refptr<net::URLRequestContextGetter> request_context_getter);
~WebPackageRequestHandler() override;
- // URLLoaderRequestHandler implementation
+ // NavigationLoaderInterceptor implementation
void MaybeCreateLoader(const network::ResourceRequest& resource_request,
ResourceContext* resource_context,
LoaderCallback callback) override;
@@ -51,8 +60,10 @@ class WebPackageRequestHandler final : public URLLoaderRequestHandler {
url::Origin request_initiator_;
const uint32_t url_loader_options_;
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory_;
+ const int frame_tree_node_id_;
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
URLLoaderThrottlesGetter url_loader_throttles_getter_;
+ scoped_refptr<net::URLRequestContextGetter> request_context_getter_;
base::WeakPtrFactory<WebPackageRequestHandler> weak_factory_;
diff --git a/chromium/content/browser/web_package/web_package_request_handler_browsertest.cc b/chromium/content/browser/web_package/web_package_request_handler_browsertest.cc
index ff5805c0581..038e49d457f 100644
--- a/chromium/content/browser/web_package/web_package_request_handler_browsertest.cc
+++ b/chromium/content/browser/web_package/web_package_request_handler_browsertest.cc
@@ -7,9 +7,13 @@
#include "base/strings/utf_string_conversions.h"
#include "base/test/scoped_feature_list.h"
#include "base/threading/thread_restrictions.h"
+#include "base/time/time.h"
+#include "content/browser/web_package/signed_exchange_handler.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_handle.h"
+#include "content/public/browser/ssl_status.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/common/content_features.h"
@@ -20,16 +24,23 @@
#include "content/public/test/test_navigation_throttle.h"
#include "content/public/test/url_loader_interceptor.h"
#include "content/shell/browser/shell.h"
+#include "net/cert/cert_verify_result.h"
+#include "net/cert/mock_cert_verifier.h"
+#include "net/test/cert_test_util.h"
+#include "net/test/embedded_test_server/http_request.h"
#include "net/test/test_data_directory.h"
#include "net/test/url_request/url_request_mock_http_job.h"
#include "net/url_request/url_request_filter.h"
#include "net/url_request/url_request_interceptor.h"
#include "services/network/public/cpp/features.h"
+#include "testing/gmock/include/gmock/gmock-matchers.h"
namespace content {
namespace {
+const uint64_t kSignatureHeaderDate = 1520834000; // 2018-03-12T05:53:20Z
+
const char* kMockHeaderFileSuffix = ".mock-http-headers";
class NavigationFailureObserver : public WebContentsObserver {
@@ -64,10 +75,16 @@ class WebPackageRequestHandlerBrowserTest
: public ContentBrowserTest,
public testing::WithParamInterface<bool> {
public:
- WebPackageRequestHandlerBrowserTest() = default;
+ WebPackageRequestHandlerBrowserTest()
+ : mock_cert_verifier_(std::make_unique<net::MockCertVerifier>()){};
~WebPackageRequestHandlerBrowserTest() = default;
void SetUp() override {
+ SignedExchangeHandler::SetCertVerifierForTesting(mock_cert_verifier_.get());
+ SignedExchangeHandler::SetVerificationTimeForTesting(
+ base::Time::UnixEpoch() +
+ base::TimeDelta::FromSeconds(kSignatureHeaderDate));
+
if (is_network_service_enabled()) {
feature_list_.InitWithFeatures(
{features::kSignedHTTPExchange, network::features::kNetworkService},
@@ -78,9 +95,22 @@ class WebPackageRequestHandlerBrowserTest
ContentBrowserTest::SetUp();
}
- void TearDownOnMainThread() override { interceptor_.reset(); }
+ void TearDownOnMainThread() override {
+ interceptor_.reset();
+ SignedExchangeHandler::SetCertVerifierForTesting(nullptr);
+ SignedExchangeHandler::SetVerificationTimeForTesting(
+ base::Optional<base::Time>());
+ }
protected:
+ static scoped_refptr<net::X509Certificate> LoadCertificate(
+ const std::string& cert_file) {
+ base::ScopedAllowBlockingForTesting allow_io;
+ return net::CreateCertificateChainFromFile(
+ net::GetTestCertsDirectory(), cert_file,
+ net::X509Certificate::FORMAT_PEM_CERT_SEQUENCE);
+ }
+
void InstallUrlInterceptor(const GURL& url, const std::string& data_path) {
if (base::FeatureList::IsEnabled(network::features::kNetworkService)) {
if (!interceptor_) {
@@ -97,6 +127,8 @@ class WebPackageRequestHandlerBrowserTest
}
}
+ std::unique_ptr<net::MockCertVerifier> mock_cert_verifier_;
+
private:
static std::string ReadFile(const std::string& data_path) {
base::ScopedAllowBlockingForTesting allow_io;
@@ -153,6 +185,24 @@ IN_PROC_BROWSER_TEST_P(WebPackageRequestHandlerBrowserTest, Simple) {
GURL("https://cert.example.org/cert.msg"),
"content/test/data/htxg/wildcard_example.org.public.pem.msg");
+ // Make the MockCertVerifier treat the certificate "wildcard.pem" as valid for
+ // "*.example.org".
+ scoped_refptr<net::X509Certificate> original_cert =
+ LoadCertificate("wildcard.pem");
+ net::CertVerifyResult dummy_result;
+ dummy_result.verified_cert = original_cert;
+ dummy_result.cert_status = net::OK;
+ mock_cert_verifier_->AddResultForCertAndHost(original_cert, "*.example.org",
+ dummy_result, net::OK);
+
+ embedded_test_server()->RegisterRequestMonitor(
+ base::BindRepeating([](const net::test_server::HttpRequest& request) {
+ if (request.relative_url == "/htxg/test.example.org_test.htxg") {
+ const auto& accept_value = request.headers.find("accept")->second;
+ EXPECT_THAT(accept_value,
+ ::testing::HasSubstr("application/signed-exchange;v=b0"));
+ }
+ }));
embedded_test_server()->ServeFilesFromSourceDirectory("content/test/data");
ASSERT_TRUE(embedded_test_server()->Start());
GURL url = embedded_test_server()->GetURL("/htxg/test.example.org_test.htxg");
@@ -160,6 +210,52 @@ IN_PROC_BROWSER_TEST_P(WebPackageRequestHandlerBrowserTest, Simple) {
TitleWatcher title_watcher(shell()->web_contents(), title);
NavigateToURL(shell(), url);
EXPECT_EQ(title, title_watcher.WaitAndGetTitle());
+
+ NavigationEntry* entry =
+ shell()->web_contents()->GetController().GetVisibleEntry();
+ EXPECT_TRUE(entry->GetSSL().initialized);
+ EXPECT_FALSE(!!(entry->GetSSL().content_status &
+ SSLStatus::DISPLAYED_INSECURE_CONTENT));
+ ASSERT_TRUE(entry->GetSSL().certificate);
+
+ // "wildcard_example.org.public.pem.msg" is generated from "wildcard.pem". So
+ // the SHA256 of the certificates must match.
+ const net::SHA256HashValue fingerprint =
+ net::X509Certificate::CalculateFingerprint256(
+ entry->GetSSL().certificate->cert_buffer());
+ const net::SHA256HashValue original_fingerprint =
+ net::X509Certificate::CalculateFingerprint256(
+ original_cert->cert_buffer());
+ EXPECT_EQ(original_fingerprint, fingerprint);
+}
+
+IN_PROC_BROWSER_TEST_P(WebPackageRequestHandlerBrowserTest,
+ InvalidContentType) {
+ InstallUrlInterceptor(
+ GURL("https://cert.example.org/cert.msg"),
+ "content/test/data/htxg/wildcard_example.org.public.pem.msg");
+
+ // Make the MockCertVerifier treat the certificate "wildcard.pem" as valid for
+ // "*.example.org".
+ scoped_refptr<net::X509Certificate> original_cert =
+ LoadCertificate("wildcard.pem");
+ net::CertVerifyResult dummy_result;
+ dummy_result.verified_cert = original_cert;
+ dummy_result.cert_status = net::OK;
+ mock_cert_verifier_->AddResultForCertAndHost(original_cert, "*.example.org",
+ dummy_result, net::OK);
+
+ embedded_test_server()->ServeFilesFromSourceDirectory("content/test/data");
+ ASSERT_TRUE(embedded_test_server()->Start());
+ GURL url = embedded_test_server()->GetURL(
+ "/htxg/test.example.org_test_invalid_content_type.htxg");
+
+ NavigationFailureObserver failure_observer(shell()->web_contents());
+ NavigateToURL(shell(), url);
+ EXPECT_TRUE(failure_observer.did_fail());
+ NavigationEntry* entry =
+ shell()->web_contents()->GetController().GetVisibleEntry();
+ EXPECT_EQ(content::PAGE_TYPE_ERROR, entry->GetPageType());
}
IN_PROC_BROWSER_TEST_P(WebPackageRequestHandlerBrowserTest, CertNotFound) {
diff --git a/chromium/content/browser/webauth/OWNERS b/chromium/content/browser/webauth/OWNERS
index e2c72da9630..f1f0a3ef8d6 100644
--- a/chromium/content/browser/webauth/OWNERS
+++ b/chromium/content/browser/webauth/OWNERS
@@ -2,4 +2,8 @@ engedy@chromium.org
mkwst@chromium.org
vasilii@chromium.org
-# Component: Blink>WebAuth \ No newline at end of file
+per-file *_type_converter*.*=set noparent
+per-file *_type_converter*.*=file://ipc/SECURITY_OWNERS
+
+# Component: Blink>WebAuthentication
+# TEAM: identity-dev@chromium.org
diff --git a/chromium/content/browser/webauth/authenticator_impl.cc b/chromium/content/browser/webauth/authenticator_impl.cc
index 3c53a60cd04..08a8a7be414 100644
--- a/chromium/content/browser/webauth/authenticator_impl.cc
+++ b/chromium/content/browser/webauth/authenticator_impl.cc
@@ -14,22 +14,34 @@
#include "base/rand_util.h"
#include "base/timer/timer.h"
#include "content/browser/bad_message.h"
+#include "content/browser/webauth/authenticator_type_converters.h"
#include "content/public/browser/content_browser_client.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_widget_host_view.h"
+#include "content/public/browser/web_contents.h"
#include "content/public/common/content_client.h"
+#include "content/public/common/content_features.h"
#include "content/public/common/origin_util.h"
#include "content/public/common/service_manager_connection.h"
#include "crypto/sha2.h"
+#include "device/fido/authenticator_selection_criteria.h"
+#include "device/fido/ctap_get_assertion_request.h"
+#include "device/fido/ctap_make_credential_request.h"
+#include "device/fido/fido_transport_protocol.h"
+#include "device/fido/get_assertion_request_handler.h"
+#include "device/fido/make_credential_request_handler.h"
+#include "device/fido/public_key_credential_descriptor.h"
+#include "device/fido/public_key_credential_params.h"
#include "device/fido/u2f_register.h"
#include "device/fido/u2f_request.h"
-#include "device/fido/u2f_return_code.h"
#include "device/fido/u2f_sign.h"
-#include "device/fido/u2f_transport_protocol.h"
#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "services/service_manager/public/cpp/connector.h"
+#include "url/url_constants.h"
#include "url/url_util.h"
namespace content {
@@ -49,7 +61,15 @@ constexpr int32_t kCoseEs256 = -7;
bool HasValidEffectiveDomain(url::Origin caller_origin) {
return !caller_origin.unique() &&
!url::HostIsIPAddress(caller_origin.host()) &&
- content::IsOriginSecure(caller_origin.GetURL());
+ content::IsOriginSecure(caller_origin.GetURL()) &&
+ // Additionally, the scheme is required to be HTTP(S). Other schemes
+ // may be supported in the future but the webauthn relying party is
+ // just the domain of the origin so we would have to define how the
+ // authority part of other schemes maps to a "domain" without
+ // collisions. Given the |IsOriginSecure| check, just above, HTTP is
+ // effectively restricted to just "localhost".
+ (caller_origin.scheme() == url::kHttpScheme ||
+ caller_origin.scheme() == url::kHttpsScheme);
}
// Ensure the relying party ID is a registrable domain suffix of or equal
@@ -132,7 +152,7 @@ bool IsAppIdAllowedForOrigin(const GURL& appid, const url::Origin& origin) {
const GURL kGstatic1 =
GURL("https://www.gstatic.com/securitykey/origins.json");
const GURL kGstatic2 =
- GURL("https://www.gstatic.com/a/google.com/securitykey/origins.json");
+ GURL("https://www.gstatic.com/securitykey/a/google.com/origins.json");
DCHECK(kGstatic1.is_valid() && kGstatic2.is_valid());
if (origin.DomainIs("google.com") && !appid.has_ref() &&
@@ -144,7 +164,9 @@ bool IsAppIdAllowedForOrigin(const GURL& appid, const url::Origin& origin) {
return false;
}
-bool HasValidAlgorithm(
+// Check that at least one of the cryptographic parameters is supported.
+// Only ES256 is currently supported by U2F_V2 (CTAP 1.0).
+bool IsAlgorithmSupportedByU2fAuthenticators(
const std::vector<webauth::mojom::PublicKeyCredentialParametersPtr>&
parameters) {
for (const auto& params : parameters) {
@@ -154,6 +176,21 @@ bool HasValidAlgorithm(
return false;
}
+// Verify that the request doesn't contain parameters that U2F authenticators
+// cannot fulfill.
+bool AreOptionsSupportedByU2fAuthenticators(
+ const webauth::mojom::PublicKeyCredentialCreationOptionsPtr& options) {
+ if (options->authenticator_selection) {
+ if (options->authenticator_selection->user_verification ==
+ webauth::mojom::UserVerificationRequirement::REQUIRED ||
+ options->authenticator_selection->require_resident_key ||
+ options->authenticator_selection->authenticator_attachment ==
+ webauth::mojom::AuthenticatorAttachment::PLATFORM)
+ return false;
+ }
+ return true;
+}
+
std::vector<std::vector<uint8_t>> FilterCredentialList(
const std::vector<webauth::mojom::PublicKeyCredentialDescriptorPtr>&
descriptors) {
@@ -167,6 +204,45 @@ std::vector<std::vector<uint8_t>> FilterCredentialList(
return handles;
}
+device::CtapMakeCredentialRequest CreateCtapMakeCredentialRequest(
+ std::vector<uint8_t> client_data_hash,
+ const webauth::mojom::PublicKeyCredentialCreationOptionsPtr& options) {
+ auto credential_params = mojo::ConvertTo<
+ std::vector<device::PublicKeyCredentialParams::CredentialInfo>>(
+ options->public_key_parameters);
+
+ device::CtapMakeCredentialRequest make_credential_param(
+ std::move(client_data_hash),
+ mojo::ConvertTo<device::PublicKeyCredentialRpEntity>(
+ options->relying_party),
+ mojo::ConvertTo<device::PublicKeyCredentialUserEntity>(options->user),
+ device::PublicKeyCredentialParams(std::move(credential_params)));
+
+ auto exclude_list =
+ mojo::ConvertTo<std::vector<device::PublicKeyCredentialDescriptor>>(
+ options->exclude_credentials);
+
+ make_credential_param.SetExcludeList(std::move(exclude_list));
+ return make_credential_param;
+}
+
+device::CtapGetAssertionRequest CreateCtapGetAssertionRequest(
+ std::vector<uint8_t> client_data_hash,
+ const webauth::mojom::PublicKeyCredentialRequestOptionsPtr& options) {
+ device::CtapGetAssertionRequest request_parameter(
+ options->relying_party_id, std::move(client_data_hash));
+
+ auto allowed_list =
+ mojo::ConvertTo<std::vector<device::PublicKeyCredentialDescriptor>>(
+ options->allow_credentials);
+
+ request_parameter.SetAllowList(std::move(allowed_list));
+ request_parameter.SetUserVerification(
+ mojo::ConvertTo<device::UserVerificationRequirement>(
+ options->user_verification));
+ return request_parameter;
+}
+
std::vector<uint8_t> ConstructClientDataHash(const std::string& client_data) {
// SHA-256 hash of the JSON data structure.
std::vector<uint8_t> client_data_hash(crypto::kSHA256Length);
@@ -204,13 +280,14 @@ base::Optional<std::vector<uint8_t>> ProcessAppIdExtension(
}
webauth::mojom::MakeCredentialAuthenticatorResponsePtr
-CreateMakeCredentialResponse(const std::string& client_data_json,
- device::RegisterResponseData response_data) {
+CreateMakeCredentialResponse(
+ const std::string& client_data_json,
+ device::AuthenticatorMakeCredentialResponse response_data) {
auto response = webauth::mojom::MakeCredentialAuthenticatorResponse::New();
auto common_info = webauth::mojom::CommonCredentialInfo::New();
common_info->client_data_json.assign(client_data_json.begin(),
client_data_json.end());
- common_info->raw_id = response_data.raw_id();
+ common_info->raw_id = response_data.raw_credential_id();
common_info->id = response_data.GetId();
response->info = std::move(common_info);
response->attestation_object =
@@ -220,17 +297,22 @@ CreateMakeCredentialResponse(const std::string& client_data_json,
webauth::mojom::GetAssertionAuthenticatorResponsePtr CreateGetAssertionResponse(
const std::string& client_data_json,
- device::SignResponseData response_data) {
+ device::AuthenticatorGetAssertionResponse response_data,
+ bool echo_appid_extension) {
auto response = webauth::mojom::GetAssertionAuthenticatorResponse::New();
auto common_info = webauth::mojom::CommonCredentialInfo::New();
common_info->client_data_json.assign(client_data_json.begin(),
client_data_json.end());
- common_info->raw_id = response_data.raw_id();
+ common_info->raw_id = response_data.raw_credential_id();
common_info->id = response_data.GetId();
response->info = std::move(common_info);
- response->authenticator_data = response_data.GetAuthenticatorDataBytes();
+ response->authenticator_data =
+ response_data.auth_data().SerializeToByteArray();
response->signature = response_data.signature();
- response->user_handle.emplace();
+ response->echo_appid_extension = echo_appid_extension;
+ response_data.user_entity()
+ ? response->user_handle.emplace(response_data.user_entity()->user_id())
+ : response->user_handle.emplace();
return response;
}
@@ -246,31 +328,38 @@ std::string Base64UrlEncode(const base::span<const uint8_t> input) {
} // namespace
AuthenticatorImpl::AuthenticatorImpl(RenderFrameHost* render_frame_host)
- : timer_(std::make_unique<base::OneShotTimer>()),
+ : WebContentsObserver(WebContents::FromRenderFrameHost(render_frame_host)),
render_frame_host_(render_frame_host),
+ timer_(std::make_unique<base::OneShotTimer>()),
+ binding_(this),
weak_factory_(this) {
DCHECK(render_frame_host_);
DCHECK(timer_);
+
+ protocols_.insert(device::FidoTransportProtocol::kUsbHumanInterfaceDevice);
+ if (base::FeatureList::IsEnabled(features::kWebAuthBle)) {
+ protocols_.insert(device::FidoTransportProtocol::kBluetoothLowEnergy);
+ }
}
AuthenticatorImpl::AuthenticatorImpl(RenderFrameHost* render_frame_host,
service_manager::Connector* connector,
std::unique_ptr<base::OneShotTimer> timer)
- : protocols_({/* no protocols in tests */}),
- timer_(std::move(timer)),
+ : WebContentsObserver(WebContents::FromRenderFrameHost(render_frame_host)),
render_frame_host_(render_frame_host),
connector_(connector),
+ timer_(std::move(timer)),
+ binding_(this),
weak_factory_(this) {
DCHECK(render_frame_host_);
DCHECK(timer_);
}
-AuthenticatorImpl::~AuthenticatorImpl() {
- bindings_.CloseAllBindings();
-}
+AuthenticatorImpl::~AuthenticatorImpl() {}
void AuthenticatorImpl::Bind(webauth::mojom::AuthenticatorRequest request) {
- bindings_.AddBinding(this, std::move(request));
+ DCHECK(!binding_.is_bound());
+ binding_.Bind(std::move(request));
}
// static
@@ -332,13 +421,19 @@ std::string AuthenticatorImpl::SerializeCollectedClientDataToJson(
void AuthenticatorImpl::MakeCredential(
webauth::mojom::PublicKeyCredentialCreationOptionsPtr options,
MakeCredentialCallback callback) {
- if (u2f_request_) {
- InvokeCallbackAndCleanup(
- std::move(callback),
+ if (u2f_request_ || ctap_request_) {
+ std::move(callback).Run(
webauth::mojom::AuthenticatorStatus::PENDING_REQUEST, nullptr);
return;
}
+ if (!GetContentClient()->browser()->IsFocused(
+ WebContents::FromRenderFrameHost(render_frame_host_))) {
+ std::move(callback).Run(webauth::mojom::AuthenticatorStatus::NOT_FOCUSED,
+ nullptr);
+ return;
+ }
+
url::Origin caller_origin = render_frame_host_->GetLastCommittedOrigin();
relying_party_id_ = options->relying_party->id;
@@ -347,7 +442,8 @@ void AuthenticatorImpl::MakeCredential(
bad_message::AUTH_INVALID_EFFECTIVE_DOMAIN);
InvokeCallbackAndCleanup(
std::move(callback),
- webauth::mojom::AuthenticatorStatus::INVALID_DOMAIN, nullptr);
+ webauth::mojom::AuthenticatorStatus::INVALID_DOMAIN, nullptr,
+ Focus::kDontCheck);
return;
}
@@ -356,16 +452,30 @@ void AuthenticatorImpl::MakeCredential(
bad_message::AUTH_INVALID_RELYING_PARTY);
InvokeCallbackAndCleanup(
std::move(callback),
- webauth::mojom::AuthenticatorStatus::INVALID_DOMAIN, nullptr);
+ webauth::mojom::AuthenticatorStatus::INVALID_DOMAIN, nullptr,
+ Focus::kDontCheck);
+ return;
+ }
+
+ // Verify that the request doesn't contain parameters that U2F authenticators
+ // cannot fulfill.
+ // TODO(crbug.com/819256): Improve messages for "Not Allowed" errors.
+ if (!base::FeatureList::IsEnabled(features::kWebAuthCtap2) &&
+ !AreOptionsSupportedByU2fAuthenticators(options)) {
+ InvokeCallbackAndCleanup(
+ std::move(callback),
+ webauth::mojom::AuthenticatorStatus::AUTHENTICATOR_CRITERIA_UNSUPPORTED,
+ nullptr, Focus::kDontCheck);
return;
}
- // Check that at least one of the cryptographic parameters is supported.
- // Only ES256 is currently supported by U2F_V2.
- if (!HasValidAlgorithm(options->public_key_parameters)) {
+ if (!base::FeatureList::IsEnabled(features::kWebAuthCtap2) &&
+ !IsAlgorithmSupportedByU2fAuthenticators(
+ options->public_key_parameters)) {
InvokeCallbackAndCleanup(
std::move(callback),
- webauth::mojom::AuthenticatorStatus::NOT_SUPPORTED_ERROR, nullptr);
+ webauth::mojom::AuthenticatorStatus::ALGORITHM_UNSUPPORTED, nullptr,
+ Focus::kDontCheck);
return;
}
@@ -400,27 +510,42 @@ void AuthenticatorImpl::MakeCredential(
attestation_preference_ = options->attestation;
- // TODO(kpaulhamus): Mock U2fRegister for unit tests.
- // http://crbug.com/785955.
- // Per fido-u2f-raw-message-formats:
- // The challenge parameter is the SHA-256 hash of the Client Data,
- // Among other things, the Client Data contains the challenge from the
- // relying party (hence the name of the parameter).
- u2f_request_ = device::U2fRegister::TryRegistration(
- connector_, protocols_, registered_keys,
- ConstructClientDataHash(client_data_json_),
- CreateApplicationParameter(relying_party_id_), individual_attestation,
- base::BindOnce(&AuthenticatorImpl::OnRegisterResponse,
- weak_factory_.GetWeakPtr()));
+ if (base::FeatureList::IsEnabled(features::kWebAuthCtap2)) {
+ auto authenticator_selection_criteria =
+ options->authenticator_selection
+ ? mojo::ConvertTo<device::AuthenticatorSelectionCriteria>(
+ options->authenticator_selection)
+ : device::AuthenticatorSelectionCriteria();
+
+ ctap_request_ = std::make_unique<device::MakeCredentialRequestHandler>(
+ connector_, protocols_,
+ CreateCtapMakeCredentialRequest(
+ ConstructClientDataHash(client_data_json_), options),
+ std::move(authenticator_selection_criteria),
+ base::BindOnce(&AuthenticatorImpl::OnRegisterResponse,
+ weak_factory_.GetWeakPtr()));
+ } else {
+ // TODO(kpaulhamus): Mock U2fRegister for unit tests.
+ // http://crbug.com/785955.
+ // Per fido-u2f-raw-message-formats:
+ // The challenge parameter is the SHA-256 hash of the Client Data,
+ // Among other things, the Client Data contains the challenge from the
+ // relying party (hence the name of the parameter).
+ u2f_request_ = device::U2fRegister::TryRegistration(
+ connector_, protocols_, registered_keys,
+ ConstructClientDataHash(client_data_json_),
+ CreateApplicationParameter(relying_party_id_), individual_attestation,
+ base::BindOnce(&AuthenticatorImpl::OnRegisterResponse,
+ weak_factory_.GetWeakPtr()));
+ }
}
// mojom:Authenticator
void AuthenticatorImpl::GetAssertion(
webauth::mojom::PublicKeyCredentialRequestOptionsPtr options,
GetAssertionCallback callback) {
- if (u2f_request_) {
- InvokeCallbackAndCleanup(
- std::move(callback),
+ if (u2f_request_ || ctap_request_) {
+ std::move(callback).Run(
webauth::mojom::AuthenticatorStatus::PENDING_REQUEST, nullptr);
return;
}
@@ -445,6 +570,17 @@ void AuthenticatorImpl::GetAssertion(
return;
}
+ // To use U2F, the relying party must not require user verification.
+ if (!base::FeatureList::IsEnabled(features::kWebAuthCtap2) &&
+ options->user_verification ==
+ webauth::mojom::UserVerificationRequirement::REQUIRED) {
+ InvokeCallbackAndCleanup(
+ std::move(callback),
+ webauth::mojom::AuthenticatorStatus::USER_VERIFICATION_UNSUPPORTED,
+ nullptr);
+ return;
+ }
+
std::vector<uint8_t> application_parameter =
CreateApplicationParameter(options->relying_party_id);
@@ -458,15 +594,36 @@ void AuthenticatorImpl::GetAssertion(
}
alternative_application_parameter = std::move(appid_hash);
+ // TODO(agl): needs a test once a suitable, mock U2F device exists.
+ echo_appid_extension_ = true;
}
- DCHECK(get_assertion_response_callback_.is_null());
- get_assertion_response_callback_ = std::move(callback);
-
- // Pass along valid keys from allow_list, if any.
+ // Pass along valid keys from allow_list.
std::vector<std::vector<uint8_t>> handles =
FilterCredentialList(std::move(options->allow_credentials));
+ // There are two different descriptions of what should happen when
+ // "allowCredentials" is empty.
+ // a) WebAuthN 6.2.3 step 6[1] implies "NotAllowedError".
+ // b) CTAP step 7.2 step 2[2] says the device should error out with
+ // "CTAP2_ERR_OPTION_NOT_SUPPORTED". This also resolves to "NotAllowedError".
+ // The behavior in both cases is consistent with the current implementation.
+ // TODO(crbug.com/831712): When CTAP2 authenticators are supported, this check
+ // should be enforced by handlers in fido/device on a per-device basis.
+
+ // [1] https://w3c.github.io/webauthn/#authenticatorgetassertion
+ // [2]
+ // https://fidoalliance.org/specs/fido-v2.0-ps-20170927/fido-client-to-authenticator-protocol-v2.0-ps-20170927.html
+ if (handles.empty()) {
+ InvokeCallbackAndCleanup(
+ std::move(callback),
+ webauth::mojom::AuthenticatorStatus::EMPTY_ALLOW_CREDENTIALS, nullptr);
+ return;
+ }
+
+ DCHECK(get_assertion_response_callback_.is_null());
+ get_assertion_response_callback_ = std::move(callback);
+
timer_->Start(
FROM_HERE, options->adjusted_timeout,
base::Bind(&AuthenticatorImpl::OnTimeout, base::Unretained(this)));
@@ -481,43 +638,95 @@ void AuthenticatorImpl::GetAssertion(
client_data::kGetType, caller_origin, std::move(options->challenge),
base::nullopt);
- u2f_request_ = device::U2fSign::TrySign(
- connector_, protocols_, handles,
- ConstructClientDataHash(client_data_json_), application_parameter,
- alternative_application_parameter,
- base::BindOnce(&AuthenticatorImpl::OnSignResponse,
- weak_factory_.GetWeakPtr()));
+ if (base::FeatureList::IsEnabled(features::kWebAuthCtap2)) {
+ ctap_request_ = std::make_unique<device::GetAssertionRequestHandler>(
+ connector_, protocols_,
+ CreateCtapGetAssertionRequest(
+ ConstructClientDataHash(client_data_json_), options),
+ base::BindOnce(&AuthenticatorImpl::OnSignResponse,
+ weak_factory_.GetWeakPtr()));
+ } else {
+ u2f_request_ = device::U2fSign::TrySign(
+ connector_, protocols_, handles,
+ ConstructClientDataHash(client_data_json_), application_parameter,
+ alternative_application_parameter,
+ base::BindOnce(&AuthenticatorImpl::OnSignResponse,
+ weak_factory_.GetWeakPtr()));
+ }
+}
+
+void AuthenticatorImpl::DidFinishNavigation(
+ NavigationHandle* navigation_handle) {
+ if (!navigation_handle->HasCommitted() ||
+ navigation_handle->IsSameDocument() ||
+ navigation_handle->GetRenderFrameHost() != render_frame_host_) {
+ return;
+ }
+
+ binding_.Close();
+ Cleanup();
+}
+
+void AuthenticatorImpl::RenderFrameDeleted(RenderFrameHost* render_frame_host) {
+ // In tests, the AuthenticatorImpl may outlive the RenderFrameHost, although
+ // this cannot happen in a non-test context because, normally,
+ // AuthenticatorImpl is owned by RenderFrameHost.
+ if (render_frame_host != render_frame_host_) {
+ return;
+ }
+
+ binding_.Close();
+ Cleanup();
}
// Callback to handle the async registration response from a U2fDevice.
void AuthenticatorImpl::OnRegisterResponse(
- device::U2fReturnCode status_code,
- base::Optional<device::RegisterResponseData> response_data) {
+ device::FidoReturnCode status_code,
+ base::Optional<device::AuthenticatorMakeCredentialResponse> response_data) {
+ if (!u2f_request_ && !ctap_request_) {
+ // Either the callback has been called immediately (in which case
+ // |u2f_request_| / |ctap_request_| won't have been set yet), or
+ // |RenderFrameDeleted| / |DidFinishNavigation| noticed that this object has
+ // been orphaned.
+ return;
+ }
+
switch (status_code) {
- case device::U2fReturnCode::CONDITIONS_NOT_SATISFIED:
+ case device::FidoReturnCode::kUserConsentButCredentialExcluded:
// Duplicate registration: the new credential would be created on an
// authenticator that already contains one of the credentials in
// |exclude_credentials|.
InvokeCallbackAndCleanup(
std::move(make_credential_response_callback_),
- webauth::mojom::AuthenticatorStatus::NOT_ALLOWED_ERROR, nullptr);
+ webauth::mojom::AuthenticatorStatus::CREDENTIAL_EXCLUDED, nullptr,
+ Focus::kDoCheck);
return;
- case device::U2fReturnCode::FAILURE:
+ case device::FidoReturnCode::kAuthenticatorResponseInvalid:
// The response from the authenticator was corrupted.
InvokeCallbackAndCleanup(
std::move(make_credential_response_callback_),
- webauth::mojom::AuthenticatorStatus::NOT_ALLOWED_ERROR, nullptr);
+ webauth::mojom::AuthenticatorStatus::NOT_ALLOWED_ERROR, nullptr,
+ Focus::kDoCheck);
return;
- case device::U2fReturnCode::INVALID_PARAMS:
+ case device::FidoReturnCode::kUserConsentButCredentialNotRecognized:
NOTREACHED();
return;
- case device::U2fReturnCode::SUCCESS:
+ case device::FidoReturnCode::kSuccess:
DCHECK(response_data.has_value());
if (attestation_preference_ !=
webauth::mojom::AttestationConveyancePreference::NONE) {
- // Potentially show a permission prompt before returning the
- // attestation data.
+ // Check for focus before (potentially) showing a permissions bubble
+ // that might take focus.
+ if (!GetContentClient()->browser()->IsFocused(
+ WebContents::FromRenderFrameHost(render_frame_host_))) {
+ InvokeCallbackAndCleanup(
+ std::move(make_credential_response_callback_),
+ webauth::mojom::AuthenticatorStatus::NOT_FOCUSED, nullptr,
+ Focus::kDontCheck);
+ return;
+ }
+
GetContentClient()->browser()->ShouldReturnAttestationForWebauthnRPID(
render_frame_host_, relying_party_id_,
render_frame_host_->GetLastCommittedOrigin(),
@@ -532,58 +741,104 @@ void AuthenticatorImpl::OnRegisterResponse(
std::move(make_credential_response_callback_),
webauth::mojom::AuthenticatorStatus::SUCCESS,
CreateMakeCredentialResponse(std::move(client_data_json_),
- std::move(*response_data)));
+ std::move(*response_data)),
+ Focus::kDoCheck);
return;
}
NOTREACHED();
}
void AuthenticatorImpl::OnRegisterResponseAttestationDecided(
- device::RegisterResponseData response_data,
+ device::AuthenticatorMakeCredentialResponse response_data,
bool attestation_permitted) {
DCHECK(attestation_preference_ !=
webauth::mojom::AttestationConveyancePreference::NONE);
- if (!attestation_permitted) {
- // To protect users from being identified without consent, we let the
- // timeout run out.
- // See https://w3c.github.io/webauthn/#sec-assertion-privacy.
+ if (!u2f_request_ && !ctap_request_) {
+ // |DidFinishNavigation| / |RenderFrameDeleted| noticed that this object has
+ // been orphaned.
return;
- } else {
+ }
+
+ // At this point, the final focus check has already been done because it's
+ // possible that a permissions bubble might have focus and thus, if we did a
+ // focus check, it would (incorrectly) fail.
+
+ if (!attestation_permitted) {
InvokeCallbackAndCleanup(
std::move(make_credential_response_callback_),
- webauth::mojom::AuthenticatorStatus::SUCCESS,
- CreateMakeCredentialResponse(std::move(client_data_json_),
- std::move(response_data)));
+ webauth::mojom::AuthenticatorStatus::NOT_ALLOWED_ERROR, nullptr,
+ Focus::kDontCheck);
+ return;
+ }
+
+ // The check for IsAttestationCertificateInappropriatelyIdentifying is
+ // performed after the permissions prompt, even though we know the answer
+ // before, because this still effectively discloses the make & model of the
+ // authenticator: If an RP sees a "none" attestation from Chrome after
+ // requesting direct attestation then it knows that it was one of the tokens
+ // with inappropriate certs.
+ if (response_data.IsAttestationCertificateInappropriatelyIdentifying() &&
+ !GetContentClient()
+ ->browser()
+ ->ShouldPermitIndividualAttestationForWebauthnRPID(
+ render_frame_host_->GetProcess()->GetBrowserContext(),
+ relying_party_id_)) {
+ // The attestation response is incorrectly individually identifiable, but
+ // the consent is for make & model information about a token, not for
+ // individually-identifiable information. Erase the attestation to stop it
+ // begin a tracking signal.
+
+ // The only way to get the underlying attestation will be to list the RP ID
+ // in the enterprise policy, because that enables the individual attestation
+ // bit in the register request and permits individual attestation generally.
+ response_data.EraseAttestationStatement();
}
+
+ InvokeCallbackAndCleanup(
+ std::move(make_credential_response_callback_),
+ webauth::mojom::AuthenticatorStatus::SUCCESS,
+ CreateMakeCredentialResponse(std::move(client_data_json_),
+ std::move(response_data)),
+ Focus::kDontCheck);
}
void AuthenticatorImpl::OnSignResponse(
- device::U2fReturnCode status_code,
- base::Optional<device::SignResponseData> response_data) {
+ device::FidoReturnCode status_code,
+ base::Optional<device::AuthenticatorGetAssertionResponse> response_data) {
+ if (!u2f_request_ && !ctap_request_) {
+ // Either the callback has been called immediately (in which case
+ // |u2f_request_| / |ctap_request_| won't have been set yet), or
+ // |DidFinishNavigation| / |RenderFrameDeleted| noticed that this object has
+ // been orphaned.
+ return;
+ }
+
switch (status_code) {
- case device::U2fReturnCode::CONDITIONS_NOT_SATISFIED:
+ case device::FidoReturnCode::kUserConsentButCredentialNotRecognized:
// No authenticators contained the credential.
InvokeCallbackAndCleanup(
std::move(get_assertion_response_callback_),
- webauth::mojom::AuthenticatorStatus::NOT_ALLOWED_ERROR, nullptr);
+ webauth::mojom::AuthenticatorStatus::CREDENTIAL_NOT_RECOGNIZED,
+ nullptr);
return;
- case device::U2fReturnCode::FAILURE:
+ case device::FidoReturnCode::kAuthenticatorResponseInvalid:
// The response from the authenticator was corrupted.
InvokeCallbackAndCleanup(
- std::move(make_credential_response_callback_),
+ std::move(get_assertion_response_callback_),
webauth::mojom::AuthenticatorStatus::NOT_ALLOWED_ERROR, nullptr);
return;
- case device::U2fReturnCode::INVALID_PARAMS:
+ case device::FidoReturnCode::kUserConsentButCredentialExcluded:
NOTREACHED();
return;
- case device::U2fReturnCode::SUCCESS:
+ case device::FidoReturnCode::kSuccess:
DCHECK(response_data.has_value());
InvokeCallbackAndCleanup(
std::move(get_assertion_response_callback_),
webauth::mojom::AuthenticatorStatus::SUCCESS,
CreateGetAssertionResponse(std::move(client_data_json_),
- std::move(*response_data)));
+ std::move(*response_data),
+ echo_appid_extension_));
return;
}
NOTREACHED();
@@ -597,7 +852,8 @@ void AuthenticatorImpl::OnTimeout() {
if (make_credential_response_callback_) {
InvokeCallbackAndCleanup(
std::move(make_credential_response_callback_),
- webauth::mojom::AuthenticatorStatus::NOT_ALLOWED_ERROR, nullptr);
+ webauth::mojom::AuthenticatorStatus::NOT_ALLOWED_ERROR, nullptr,
+ Focus::kDontCheck);
} else if (get_assertion_response_callback_) {
InvokeCallbackAndCleanup(
std::move(get_assertion_response_callback_),
@@ -608,8 +864,17 @@ void AuthenticatorImpl::OnTimeout() {
void AuthenticatorImpl::InvokeCallbackAndCleanup(
MakeCredentialCallback callback,
webauth::mojom::AuthenticatorStatus status,
- webauth::mojom::MakeCredentialAuthenticatorResponsePtr response) {
- std::move(callback).Run(status, std::move(response));
+ webauth::mojom::MakeCredentialAuthenticatorResponsePtr response,
+ Focus check_focus) {
+ if (check_focus != Focus::kDontCheck &&
+ !GetContentClient()->browser()->IsFocused(
+ WebContents::FromRenderFrameHost(render_frame_host_))) {
+ std::move(callback).Run(webauth::mojom::AuthenticatorStatus::NOT_FOCUSED,
+ nullptr);
+ } else {
+ std::move(callback).Run(status, std::move(response));
+ }
+
Cleanup();
}
@@ -624,9 +889,11 @@ void AuthenticatorImpl::InvokeCallbackAndCleanup(
void AuthenticatorImpl::Cleanup() {
timer_->Stop();
u2f_request_.reset();
+ ctap_request_.reset();
make_credential_response_callback_.Reset();
get_assertion_response_callback_.Reset();
client_data_json_.clear();
+ echo_appid_extension_ = false;
}
} // namespace content
diff --git a/chromium/content/browser/webauth/authenticator_impl.h b/chromium/content/browser/webauth/authenticator_impl.h
index edadc614bc3..5fe89035a1a 100644
--- a/chromium/content/browser/webauth/authenticator_impl.h
+++ b/chromium/content/browser/webauth/authenticator_impl.h
@@ -15,11 +15,13 @@
#include "base/macros.h"
#include "base/optional.h"
#include "content/common/content_export.h"
-#include "device/fido/register_response_data.h"
-#include "device/fido/sign_response_data.h"
-#include "device/fido/u2f_transport_protocol.h"
-#include "mojo/public/cpp/bindings/binding_set.h"
-#include "third_party/WebKit/public/platform/modules/webauth/authenticator.mojom.h"
+#include "content/public/browser/web_contents_observer.h"
+#include "device/fido/authenticator_get_assertion_response.h"
+#include "device/fido/authenticator_make_credential_response.h"
+#include "device/fido/fido_constants.h"
+#include "device/fido/fido_transport_protocol.h"
+#include "mojo/public/cpp/bindings/binding.h"
+#include "third_party/blink/public/platform/modules/webauth/authenticator.mojom.h"
#include "url/origin.h"
namespace base {
@@ -27,8 +29,12 @@ class OneShotTimer;
}
namespace device {
+
class U2fRequest;
-enum class U2fReturnCode : uint8_t;
+class FidoRequestHandlerBase;
+
+enum class FidoReturnCode : uint8_t;
+
} // namespace device
namespace service_manager {
@@ -52,7 +58,8 @@ CONTENT_EXPORT extern const char kGetType[];
} // namespace client_data
// Implementation of the public Authenticator interface.
-class CONTENT_EXPORT AuthenticatorImpl : public webauth::mojom::Authenticator {
+class CONTENT_EXPORT AuthenticatorImpl : public webauth::mojom::Authenticator,
+ public WebContentsObserver {
public:
explicit AuthenticatorImpl(RenderFrameHost* render_frame_host);
@@ -64,14 +71,22 @@ class CONTENT_EXPORT AuthenticatorImpl : public webauth::mojom::Authenticator {
std::unique_ptr<base::OneShotTimer>);
~AuthenticatorImpl() override;
- // Creates a binding between this object and |request|. Note that a
- // AuthenticatorImpl instance can be bound to multiple requests (as happens in
- // the case of simultaneous starting and finishing operations).
+ // Creates a binding between this implementation and |request|.
+ //
+ // Note that one AuthenticatorImpl instance can be bound to exactly one
+ // interface connection at a time, and disconnected when the frame navigates
+ // to a new active document.
void Bind(webauth::mojom::AuthenticatorRequest request);
private:
friend class AuthenticatorImplTest;
+ // Enumerates whether or not to check that the WebContents has focus.
+ enum class Focus {
+ kDoCheck,
+ kDontCheck,
+ };
+
// Builds the CollectedClientData[1] dictionary with the given values,
// serializes it to JSON, and returns the resulting string.
// [1] https://w3c.github.io/webauthn/#dictdef-collectedclientdata
@@ -85,25 +100,30 @@ class CONTENT_EXPORT AuthenticatorImpl : public webauth::mojom::Authenticator {
void MakeCredential(
webauth::mojom::PublicKeyCredentialCreationOptionsPtr options,
MakeCredentialCallback callback) override;
-
void GetAssertion(
webauth::mojom::PublicKeyCredentialRequestOptionsPtr options,
GetAssertionCallback callback) override;
+ // WebContentsObserver:
+ void DidFinishNavigation(NavigationHandle* navigation_handle) override;
+ void RenderFrameDeleted(RenderFrameHost* render_frame_host) override;
+
// Callback to handle the async response from a U2fDevice.
void OnRegisterResponse(
- device::U2fReturnCode status_code,
- base::Optional<device::RegisterResponseData> response_data);
+ device::FidoReturnCode status_code,
+ base::Optional<device::AuthenticatorMakeCredentialResponse>
+ response_data);
// Callback to complete the registration process once a decision about
// whether or not to return attestation data has been made.
void OnRegisterResponseAttestationDecided(
- device::RegisterResponseData response_data,
+ device::AuthenticatorMakeCredentialResponse response_data,
bool attestation_permitted);
// Callback to handle the async response from a U2fDevice.
- void OnSignResponse(device::U2fReturnCode status_code,
- base::Optional<device::SignResponseData> response_data);
+ void OnSignResponse(
+ device::FidoReturnCode status_code,
+ base::Optional<device::AuthenticatorGetAssertionResponse> response_data);
// Runs when timer expires and cancels all issued requests to a U2fDevice.
void OnTimeout();
@@ -111,32 +131,36 @@ class CONTENT_EXPORT AuthenticatorImpl : public webauth::mojom::Authenticator {
void InvokeCallbackAndCleanup(
MakeCredentialCallback callback,
webauth::mojom::AuthenticatorStatus status,
- webauth::mojom::MakeCredentialAuthenticatorResponsePtr response);
+ webauth::mojom::MakeCredentialAuthenticatorResponsePtr response,
+ Focus focus_check);
void InvokeCallbackAndCleanup(
GetAssertionCallback callback,
webauth::mojom::AuthenticatorStatus status,
webauth::mojom::GetAssertionAuthenticatorResponsePtr response);
void Cleanup();
- // Owns pipes to this Authenticator from |render_frame_host_|.
- mojo::BindingSet<webauth::mojom::Authenticator> bindings_;
- std::unique_ptr<device::U2fRequest> u2f_request_;
-
- // Support both HID and BLE.
- base::flat_set<device::U2fTransportProtocol> protocols_ = {
- device::U2fTransportProtocol::kUsbHumanInterfaceDevice,
- device::U2fTransportProtocol::kBluetoothLowEnergy};
+ RenderFrameHost* render_frame_host_;
+ service_manager::Connector* connector_ = nullptr;
+ base::flat_set<device::FidoTransportProtocol> protocols_;
+ std::unique_ptr<device::U2fRequest> u2f_request_;
+ std::unique_ptr<device::FidoRequestHandlerBase> ctap_request_;
MakeCredentialCallback make_credential_response_callback_;
GetAssertionCallback get_assertion_response_callback_;
-
- // Holds the client data to be returned to the caller in JSON format.
std::string client_data_json_;
webauth::mojom::AttestationConveyancePreference attestation_preference_;
std::string relying_party_id_;
std::unique_ptr<base::OneShotTimer> timer_;
- RenderFrameHost* render_frame_host_;
- service_manager::Connector* connector_ = nullptr;
+
+ // Whether or not a GetAssertion call should return a PublicKeyCredential
+ // instance whose getClientExtensionResults() method yields a
+ // AuthenticationExtensions dictionary that contains the `appid: true`
+ // extension output.
+ bool echo_appid_extension_ = false;
+
+ // Owns pipes to this Authenticator from |render_frame_host_|.
+ mojo::Binding<webauth::mojom::Authenticator> binding_;
+
base::WeakPtrFactory<AuthenticatorImpl> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(AuthenticatorImpl);
diff --git a/chromium/content/browser/webauth/authenticator_impl_unittest.cc b/chromium/content/browser/webauth/authenticator_impl_unittest.cc
index 4b7248df527..f309233ee08 100644
--- a/chromium/content/browser/webauth/authenticator_impl_unittest.cc
+++ b/chromium/content/browser/webauth/authenticator_impl_unittest.cc
@@ -13,12 +13,19 @@
#include "base/json/json_writer.h"
#include "base/run_loop.h"
#include "base/test/gtest_util.h"
+#include "base/test/scoped_feature_list.h"
#include "base/test/test_mock_time_task_runner.h"
#include "base/time/tick_clock.h"
#include "base/time/time.h"
+#include "components/cbor/cbor_reader.h"
+#include "components/cbor/cbor_values.h"
#include "content/public/browser/render_frame_host.h"
+#include "content/public/common/content_features.h"
+#include "content/public/test/test_service_manager_context.h"
#include "content/test/test_render_frame_host.h"
#include "device/fido/fake_hid_impl_for_testing.h"
+#include "device/fido/scoped_virtual_fido_device.h"
+#include "device/fido/test_callback_receiver.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "services/device/public/mojom/constants.mojom.h"
#include "testing/gmock/include/gmock/gmock.h"
@@ -28,18 +35,26 @@ namespace content {
using ::testing::_;
+using cbor::CBORValue;
+using cbor::CBORReader;
+using webauth::mojom::AttestationConveyancePreference;
using webauth::mojom::AuthenticatorPtr;
+using webauth::mojom::AuthenticatorSelectionCriteria;
+using webauth::mojom::AuthenticatorSelectionCriteriaPtr;
using webauth::mojom::AuthenticatorStatus;
using webauth::mojom::GetAssertionAuthenticatorResponsePtr;
using webauth::mojom::MakeCredentialAuthenticatorResponsePtr;
using webauth::mojom::PublicKeyCredentialCreationOptions;
using webauth::mojom::PublicKeyCredentialCreationOptionsPtr;
+using webauth::mojom::PublicKeyCredentialDescriptor;
+using webauth::mojom::PublicKeyCredentialDescriptorPtr;
using webauth::mojom::PublicKeyCredentialParameters;
using webauth::mojom::PublicKeyCredentialParametersPtr;
using webauth::mojom::PublicKeyCredentialRequestOptions;
using webauth::mojom::PublicKeyCredentialRequestOptionsPtr;
using webauth::mojom::PublicKeyCredentialRpEntity;
using webauth::mojom::PublicKeyCredentialRpEntityPtr;
+using webauth::mojom::PublicKeyCredentialType;
using webauth::mojom::PublicKeyCredentialUserEntity;
using webauth::mojom::PublicKeyCredentialUserEntityPtr;
@@ -47,8 +62,9 @@ namespace {
typedef struct {
const char* origin;
- const char* relying_party_id;
-} OriginRelyingPartyIdPair;
+ // Either a relying party ID or a U2F AppID.
+ const char* claimed_authority;
+} OriginClaimedAuthorityPair;
constexpr char kTestOrigin1[] = "https://a.google.com";
constexpr char kTestRelyingPartyId[] = "google.com";
@@ -72,7 +88,7 @@ constexpr char kTestSignClientDataJsonString[] =
R"("https://a.google.com","tokenBinding":{"status":"not-supported"},)"
R"("type":"webauthn.get"})";
-constexpr OriginRelyingPartyIdPair kValidRelyingPartyTestCases[] = {
+constexpr OriginClaimedAuthorityPair kValidRelyingPartyTestCases[] = {
{"http://localhost", "localhost"},
{"https://myawesomedomain", "myawesomedomain"},
{"https://foo.bar.google.com", "foo.bar.google.com"},
@@ -94,13 +110,9 @@ constexpr OriginRelyingPartyIdPair kValidRelyingPartyTestCases[] = {
{"https://.google.com", ".google.com"},
{"https://..google.com", ".google.com"},
{"https://accounts.google.com", ".google.com"},
-
- // The spec notes that RPs should not use non-https schemes, but this is
- // technically still valid according to the authoritative parts.
- {"wss:///google.com", "google.com"},
};
-constexpr OriginRelyingPartyIdPair kInvalidRelyingPartyTestCases[] = {
+constexpr OriginClaimedAuthorityPair kInvalidRelyingPartyTestCases[] = {
{"https://google.com", "com"},
{"http://google.com", "google.com"},
{"http://myawesomedomain", "myawesomedomain"},
@@ -145,6 +157,9 @@ constexpr OriginRelyingPartyIdPair kInvalidRelyingPartyTestCases[] = {
{"gopher://google.com", "google.com"},
{"ftp://google.com", "google.com"},
{"file:///google.com", "google.com"},
+ // Use of webauthn from a WSS origin may be technically valid, but we
+ // prohibit use on non-HTTPS origins. (At least for now.)
+ {"wss://google.com", "google.com"},
{"data:,", ""},
{"https://google.com", ""},
@@ -157,8 +172,33 @@ constexpr OriginRelyingPartyIdPair kInvalidRelyingPartyTestCases[] = {
// This case is acceptable according to spec, but both renderer
// and browser handling currently do not permit it.
{"https://login.awesomecompany", "awesomecompany"},
+
+ // These are AppID test cases, but should also be invalid relying party
+ // examples too.
+ {"https://example.com", "https://com/"},
+ {"https://example.com", "https://com/foo"},
+ {"https://example.com", "https://foo.com/"},
+ {"https://example.com", "http://example.com"},
+ {"http://example.com", "https://example.com"},
+ {"https://127.0.0.1", "https://127.0.0.1"},
+ {"https://www.notgoogle.com",
+ "https://www.gstatic.com/securitykey/origins.json"},
+ {"https://www.google.com",
+ "https://www.gstatic.com/securitykey/origins.json#x"},
+ {"https://www.google.com",
+ "https://www.gstatic.com/securitykey/origins.json2"},
+ {"https://www.google.com", "https://gstatic.com/securitykey/origins.json"},
+ {"https://ggoogle.com", "https://www.gstatic.com/securitykey/origi"},
+ {"https://com", "https://www.gstatic.com/securitykey/origins.json"},
};
+using TestMakeCredentialCallback = device::test::StatusAndValueCallbackReceiver<
+ AuthenticatorStatus,
+ MakeCredentialAuthenticatorResponsePtr>;
+using TestGetAssertionCallback = device::test::StatusAndValueCallbackReceiver<
+ AuthenticatorStatus,
+ GetAssertionAuthenticatorResponsePtr>;
+
std::vector<uint8_t> GetTestChallengeBytes() {
return std::vector<uint8_t>(std::begin(kTestChallengeBytes),
std::end(kTestChallengeBytes));
@@ -191,6 +231,26 @@ GetTestPublicKeyCredentialParameters(int32_t algorithm_identifier) {
return parameters;
}
+AuthenticatorSelectionCriteriaPtr GetTestAuthenticatorSelectionCriteria() {
+ auto criteria = AuthenticatorSelectionCriteria::New();
+ criteria->authenticator_attachment =
+ webauth::mojom::AuthenticatorAttachment::NO_PREFERENCE;
+ criteria->require_resident_key = false;
+ criteria->user_verification =
+ webauth::mojom::UserVerificationRequirement::PREFERRED;
+ return criteria;
+}
+
+std::vector<PublicKeyCredentialDescriptorPtr> GetTestAllowCredentials() {
+ std::vector<PublicKeyCredentialDescriptorPtr> descriptors;
+ auto credential = PublicKeyCredentialDescriptor::New();
+ credential->type = PublicKeyCredentialType::PUBLIC_KEY;
+ std::vector<uint8_t> id(32, 0x0A);
+ credential->id = id;
+ descriptors.push_back(std::move(credential));
+ return descriptors;
+}
+
PublicKeyCredentialCreationOptionsPtr
GetTestPublicKeyCredentialCreationOptions() {
auto options = PublicKeyCredentialCreationOptions::New();
@@ -200,6 +260,7 @@ GetTestPublicKeyCredentialCreationOptions() {
GetTestPublicKeyCredentialParameters(kCoseEs256);
options->challenge.assign(32, 0x0A);
options->adjusted_timeout = base::TimeDelta::FromMinutes(1);
+ options->authenticator_selection = GetTestAuthenticatorSelectionCriteria();
return options;
}
@@ -209,75 +270,12 @@ GetTestPublicKeyCredentialRequestOptions() {
options->relying_party_id = std::string(kTestRelyingPartyId);
options->challenge.assign(32, 0x0A);
options->adjusted_timeout = base::TimeDelta::FromMinutes(1);
+ options->user_verification =
+ webauth::mojom::UserVerificationRequirement::PREFERRED;
+ options->allow_credentials = GetTestAllowCredentials();
return options;
}
-class TestMakeCredentialCallback {
- public:
- TestMakeCredentialCallback()
- : callback_(base::BindOnce(&TestMakeCredentialCallback::ReceivedCallback,
- base::Unretained(this))) {}
- ~TestMakeCredentialCallback() {}
-
- void ReceivedCallback(AuthenticatorStatus status,
- MakeCredentialAuthenticatorResponsePtr credential) {
- response_ = std::make_pair(status, std::move(credential));
- std::move(closure_).Run();
- }
-
- // TODO(crbug.com/799044) - simplify the runloop usage.
- void WaitForCallback() {
- closure_ = run_loop_.QuitClosure();
- run_loop_.Run();
- }
-
- AuthenticatorImpl::MakeCredentialCallback callback() {
- return std::move(callback_);
- }
-
- AuthenticatorStatus GetResponseStatus() { return response_.first; }
-
- private:
- std::pair<AuthenticatorStatus, MakeCredentialAuthenticatorResponsePtr>
- response_;
- base::Closure closure_;
- AuthenticatorImpl::MakeCredentialCallback callback_;
- base::RunLoop run_loop_;
-};
-
-class TestGetAssertionCallback {
- public:
- TestGetAssertionCallback()
- : callback_(base::BindOnce(&TestGetAssertionCallback::ReceivedCallback,
- base::Unretained(this))) {}
- ~TestGetAssertionCallback() {}
-
- void ReceivedCallback(AuthenticatorStatus status,
- GetAssertionAuthenticatorResponsePtr credential) {
- response_ = std::make_pair(status, std::move(credential));
- std::move(closure_).Run();
- }
-
- // TODO(crbug.com/799044) - simplify the runloop usage.
- void WaitForCallback() {
- closure_ = run_loop_.QuitClosure();
- run_loop_.Run();
- }
-
- AuthenticatorStatus GetResponseStatus() { return response_.first; }
-
- AuthenticatorImpl::GetAssertionCallback callback() {
- return std::move(callback_);
- }
-
- private:
- std::pair<AuthenticatorStatus, GetAssertionAuthenticatorResponsePtr>
- response_;
- base::OnceClosure closure_;
- AuthenticatorImpl::GetAssertionCallback callback_;
- base::RunLoop run_loop_;
-};
-
} // namespace
class AuthenticatorImplTest : public content::RenderViewHostTestHarness {
@@ -329,6 +327,23 @@ class AuthenticatorImplTest : public content::RenderViewHostTestHarness {
token_binding);
}
+ AuthenticatorStatus TryAuthenticationWithAppId(const std::string& origin,
+ const std::string& appid) {
+ const GURL origin_url(origin);
+ NavigateAndCommit(origin_url);
+ AuthenticatorPtr authenticator = ConnectToAuthenticator();
+ PublicKeyCredentialRequestOptionsPtr options =
+ GetTestPublicKeyCredentialRequestOptions();
+ options->relying_party_id = origin_url.host();
+ options->appid = appid;
+
+ TestGetAssertionCallback cb;
+ authenticator->GetAssertion(std::move(options), cb.callback());
+ cb.WaitForCallback();
+
+ return cb.status();
+ }
+
private:
std::unique_ptr<AuthenticatorImpl> authenticator_impl_;
};
@@ -338,43 +353,41 @@ TEST_F(AuthenticatorImplTest, MakeCredentialOriginAndRpIds) {
// These instances should return security errors (for circumstances
// that would normally crash the renderer).
for (auto test_case : kInvalidRelyingPartyTestCases) {
- SCOPED_TRACE(std::string(test_case.relying_party_id) + " " +
+ SCOPED_TRACE(std::string(test_case.claimed_authority) + " " +
std::string(test_case.origin));
NavigateAndCommit(GURL(test_case.origin));
AuthenticatorPtr authenticator = ConnectToAuthenticator();
PublicKeyCredentialCreationOptionsPtr options =
GetTestPublicKeyCredentialCreationOptions();
- options->relying_party->id = test_case.relying_party_id;
+ options->relying_party->id = test_case.claimed_authority;
TestMakeCredentialCallback cb;
authenticator->MakeCredential(std::move(options), cb.callback());
cb.WaitForCallback();
- EXPECT_EQ(webauth::mojom::AuthenticatorStatus::INVALID_DOMAIN,
- cb.GetResponseStatus());
+ EXPECT_EQ(AuthenticatorStatus::INVALID_DOMAIN, cb.status());
}
// These instances pass the origin and relying party checks and return at
// the algorithm check.
for (auto test_case : kValidRelyingPartyTestCases) {
- SCOPED_TRACE(std::string(test_case.relying_party_id) + " " +
+ SCOPED_TRACE(std::string(test_case.claimed_authority) + " " +
std::string(test_case.origin));
NavigateAndCommit(GURL(test_case.origin));
AuthenticatorPtr authenticator = ConnectToAuthenticator();
PublicKeyCredentialCreationOptionsPtr options =
GetTestPublicKeyCredentialCreationOptions();
- options->relying_party->id = test_case.relying_party_id;
+ options->relying_party->id = test_case.claimed_authority;
options->public_key_parameters = GetTestPublicKeyCredentialParameters(123);
TestMakeCredentialCallback cb;
authenticator->MakeCredential(std::move(options), cb.callback());
cb.WaitForCallback();
- EXPECT_EQ(webauth::mojom::AuthenticatorStatus::NOT_SUPPORTED_ERROR,
- cb.GetResponseStatus());
+ EXPECT_EQ(AuthenticatorStatus::ALGORITHM_UNSUPPORTED, cb.status());
}
}
-// Test that service returns NOT_IMPLEMENTED_ERROR if no parameters contain
+// Test that service returns ALGORITHM_UNSUPPORTED if no parameters contain
// a supported algorithm.
TEST_F(AuthenticatorImplTest, MakeCredentialNoSupportedAlgorithm) {
SimulateNavigation(GURL(kTestOrigin1));
@@ -387,8 +400,76 @@ TEST_F(AuthenticatorImplTest, MakeCredentialNoSupportedAlgorithm) {
TestMakeCredentialCallback cb;
authenticator->MakeCredential(std::move(options), cb.callback());
cb.WaitForCallback();
- EXPECT_EQ(webauth::mojom::AuthenticatorStatus::NOT_SUPPORTED_ERROR,
- cb.GetResponseStatus());
+ EXPECT_EQ(AuthenticatorStatus::ALGORITHM_UNSUPPORTED, cb.status());
+}
+
+// Test that service returns USER_VERIFICATION_UNSUPPORTED if user verification
+// is REQUIRED for get().
+TEST_F(AuthenticatorImplTest, GetAssertionUserVerification) {
+ SimulateNavigation(GURL(kTestOrigin1));
+ AuthenticatorPtr authenticator = ConnectToAuthenticator();
+
+ PublicKeyCredentialRequestOptionsPtr options =
+ GetTestPublicKeyCredentialRequestOptions();
+ options->user_verification =
+ webauth::mojom::UserVerificationRequirement::REQUIRED;
+ TestGetAssertionCallback cb;
+ authenticator->GetAssertion(std::move(options), cb.callback());
+ cb.WaitForCallback();
+ EXPECT_EQ(AuthenticatorStatus::USER_VERIFICATION_UNSUPPORTED, cb.status());
+}
+
+// Test that service returns AUTHENTICATOR_CRITERIA_UNSUPPORTED if user
+// verification is REQUIRED for create().
+TEST_F(AuthenticatorImplTest, MakeCredentialUserVerification) {
+ SimulateNavigation(GURL(kTestOrigin1));
+ AuthenticatorPtr authenticator = ConnectToAuthenticator();
+
+ PublicKeyCredentialCreationOptionsPtr options =
+ GetTestPublicKeyCredentialCreationOptions();
+ options->authenticator_selection->user_verification =
+ webauth::mojom::UserVerificationRequirement::REQUIRED;
+
+ TestMakeCredentialCallback cb;
+ authenticator->MakeCredential(std::move(options), cb.callback());
+ cb.WaitForCallback();
+ EXPECT_EQ(AuthenticatorStatus::AUTHENTICATOR_CRITERIA_UNSUPPORTED,
+ cb.status());
+}
+
+// Test that service returns AUTHENTICATOR_CRITERIA_UNSUPPORTED if resident key
+// is requested for create().
+TEST_F(AuthenticatorImplTest, MakeCredentialResidentKey) {
+ SimulateNavigation(GURL(kTestOrigin1));
+ AuthenticatorPtr authenticator = ConnectToAuthenticator();
+
+ PublicKeyCredentialCreationOptionsPtr options =
+ GetTestPublicKeyCredentialCreationOptions();
+ options->authenticator_selection->require_resident_key = true;
+
+ TestMakeCredentialCallback cb;
+ authenticator->MakeCredential(std::move(options), cb.callback());
+ cb.WaitForCallback();
+ EXPECT_EQ(AuthenticatorStatus::AUTHENTICATOR_CRITERIA_UNSUPPORTED,
+ cb.status());
+}
+
+// Test that service returns AUTHENTICATOR_CRITERIA_UNSUPPORTED if a platform
+// authenticator is requested for U2F.
+TEST_F(AuthenticatorImplTest, MakeCredentialPlatformAuthenticator) {
+ SimulateNavigation(GURL(kTestOrigin1));
+ AuthenticatorPtr authenticator = ConnectToAuthenticator();
+
+ PublicKeyCredentialCreationOptionsPtr options =
+ GetTestPublicKeyCredentialCreationOptions();
+ options->authenticator_selection->authenticator_attachment =
+ webauth::mojom::AuthenticatorAttachment::PLATFORM;
+
+ TestMakeCredentialCallback cb;
+ authenticator->MakeCredential(std::move(options), cb.callback());
+ cb.WaitForCallback();
+ EXPECT_EQ(AuthenticatorStatus::AUTHENTICATOR_CRITERIA_UNSUPPORTED,
+ cb.status());
}
// Parses its arguments as JSON and expects that all the keys in the first are
@@ -473,8 +554,8 @@ TEST_F(AuthenticatorImplTest, TestMakeCredentialTimeout) {
// Set up a timer for testing.
auto task_runner = base::MakeRefCounted<base::TestMockTimeTaskRunner>(
base::Time::Now(), base::TimeTicks::Now());
- auto tick_clock = task_runner->GetMockTickClock();
- auto timer = std::make_unique<base::OneShotTimer>(tick_clock.get());
+ auto timer =
+ std::make_unique<base::OneShotTimer>(task_runner->GetMockTickClock());
timer->SetTaskRunner(task_runner);
AuthenticatorPtr authenticator =
ConnectToAuthenticator(connector.get(), std::move(timer));
@@ -485,85 +566,74 @@ TEST_F(AuthenticatorImplTest, TestMakeCredentialTimeout) {
base::RunLoop().RunUntilIdle();
task_runner->FastForwardBy(base::TimeDelta::FromMinutes(1));
cb.WaitForCallback();
- EXPECT_EQ(webauth::mojom::AuthenticatorStatus::NOT_ALLOWED_ERROR,
- cb.GetResponseStatus());
+ EXPECT_EQ(AuthenticatorStatus::NOT_ALLOWED_ERROR, cb.status());
}
// Verify behavior for various combinations of origins and RP IDs.
TEST_F(AuthenticatorImplTest, GetAssertionOriginAndRpIds) {
// These instances should return security errors (for circumstances
// that would normally crash the renderer).
- for (const OriginRelyingPartyIdPair& test_case :
+ for (const OriginClaimedAuthorityPair& test_case :
kInvalidRelyingPartyTestCases) {
- SCOPED_TRACE(std::string(test_case.relying_party_id) + " " +
+ SCOPED_TRACE(std::string(test_case.claimed_authority) + " " +
std::string(test_case.origin));
NavigateAndCommit(GURL(test_case.origin));
AuthenticatorPtr authenticator = ConnectToAuthenticator();
PublicKeyCredentialRequestOptionsPtr options =
GetTestPublicKeyCredentialRequestOptions();
- options->relying_party_id = test_case.relying_party_id;
+ options->relying_party_id = test_case.claimed_authority;
TestGetAssertionCallback cb;
authenticator->GetAssertion(std::move(options), cb.callback());
cb.WaitForCallback();
- EXPECT_EQ(webauth::mojom::AuthenticatorStatus::INVALID_DOMAIN,
- cb.GetResponseStatus());
+ EXPECT_EQ(AuthenticatorStatus::INVALID_DOMAIN, cb.status());
}
}
-typedef struct {
- const char* origin;
- const char* appid;
- bool should_succeed;
-} OriginAppIdPair;
-
-constexpr OriginAppIdPair kInvalidAppIdCases[] = {
- {"https://example.com", "https://com/foo", false},
- {"https://example.com", "https://foo.com/", false},
- {"https://example.com", "http://example.com", false},
- {"http://example.com", "https://example.com", false},
- {"https://127.0.0.1", "https://127.0.0.1", false},
- {"https://www.notgoogle.com",
- "https://www.gstatic.com/securitykey/origins.json", false},
-
- /* Cannot be tested yet:
- {"https://example.com", "https://example.com", true},
- {"https://www.example.com", "https://example.com", true},
- {"https://example.com", "https://www.example.com", true},
- {"https://example.com", "https://foo.bar.example.com", true},
- {"https://example.com", "https://foo.bar.example.com/foo/bar", true},
+constexpr OriginClaimedAuthorityPair kValidAppIdCases[] = {
+ {"https://example.com", "https://example.com"},
+ {"https://www.example.com", "https://example.com"},
+ {"https://example.com", "https://www.example.com"},
+ {"https://example.com", "https://foo.bar.example.com"},
+ {"https://example.com", "https://foo.bar.example.com/foo/bar"},
+ {"https://google.com", "https://www.gstatic.com/securitykey/origins.json"},
{"https://www.google.com",
- "https://www.gstatic.com/securitykey/origins.json", true},
+ "https://www.gstatic.com/securitykey/origins.json"},
{"https://www.google.com",
- "https://www.gstatic.com/securitykey/a/google.com/origins.json", true},
- */
+ "https://www.gstatic.com/securitykey/a/google.com/origins.json"},
+ {"https://accounts.google.com",
+ "https://www.gstatic.com/securitykey/origins.json"},
};
// Verify behavior for various combinations of origins and RP IDs.
TEST_F(AuthenticatorImplTest, AppIdExtension) {
- for (const auto& test_case : kInvalidAppIdCases) {
+ TestServiceManagerContext smc;
+ device::test::ScopedVirtualFidoDevice virtual_device;
+
+ for (const auto& test_case : kValidAppIdCases) {
SCOPED_TRACE(std::string(test_case.origin) + " " +
- std::string(test_case.appid));
+ std::string(test_case.claimed_authority));
- CHECK(!test_case.should_succeed) << "can't test this yet";
+ EXPECT_EQ(AuthenticatorStatus::CREDENTIAL_NOT_RECOGNIZED,
+ TryAuthenticationWithAppId(test_case.origin,
+ test_case.claimed_authority));
+ }
- const GURL origin_url(test_case.origin);
- NavigateAndCommit(origin_url);
- AuthenticatorPtr authenticator = ConnectToAuthenticator();
- PublicKeyCredentialRequestOptionsPtr options =
- GetTestPublicKeyCredentialRequestOptions();
- options->relying_party_id = origin_url.host();
- options->appid = std::string(test_case.appid);
+ // All the invalid relying party test cases should also be invalid as AppIDs.
+ for (const auto& test_case : kInvalidRelyingPartyTestCases) {
+ SCOPED_TRACE(std::string(test_case.origin) + " " +
+ std::string(test_case.claimed_authority));
- TestGetAssertionCallback cb;
- authenticator->GetAssertion(std::move(options), cb.callback());
- cb.WaitForCallback();
- EXPECT_EQ(webauth::mojom::AuthenticatorStatus::INVALID_DOMAIN,
- cb.GetResponseStatus());
- }
+ if (strlen(test_case.claimed_authority) == 0) {
+ // In this case, no AppID is actually being tested.
+ continue;
+ }
- // TODO(agl): test positive cases once a mock U2F device exists.
+ EXPECT_EQ(AuthenticatorStatus::INVALID_DOMAIN,
+ TryAuthenticationWithAppId(test_case.origin,
+ test_case.claimed_authority));
+ }
}
TEST_F(AuthenticatorImplTest, TestGetAssertionTimeout) {
@@ -586,19 +656,471 @@ TEST_F(AuthenticatorImplTest, TestGetAssertionTimeout) {
// Set up a timer for testing.
auto task_runner = base::MakeRefCounted<base::TestMockTimeTaskRunner>(
base::Time::Now(), base::TimeTicks::Now());
- auto tick_clock = task_runner->GetMockTickClock();
- auto timer = std::make_unique<base::OneShotTimer>(tick_clock.get());
+ auto timer =
+ std::make_unique<base::OneShotTimer>(task_runner->GetMockTickClock());
+ timer->SetTaskRunner(task_runner);
+ AuthenticatorPtr authenticator =
+ ConnectToAuthenticator(connector.get(), std::move(timer));
+
+ authenticator->GetAssertion(std::move(options), cb.callback());
+
+ // Trigger timer.
+ base::RunLoop().RunUntilIdle();
+ task_runner->FastForwardBy(base::TimeDelta::FromMinutes(1));
+ cb.WaitForCallback();
+ EXPECT_EQ(AuthenticatorStatus::NOT_ALLOWED_ERROR, cb.status());
+}
+
+TEST_F(AuthenticatorImplTest, OversizedCredentialId) {
+ device::test::ScopedVirtualFidoDevice scoped_virtual_device;
+ TestServiceManagerContext service_manager_context;
+
+ // 255 is the maximum size of a U2F credential ID. We also test one greater
+ // (256) to ensure that nothing untoward happens.
+ const std::vector<size_t> kSizes = {255, 256};
+
+ for (const size_t size : kSizes) {
+ SCOPED_TRACE(size);
+
+ SimulateNavigation(GURL(kTestOrigin1));
+ AuthenticatorPtr authenticator = ConnectToAuthenticator();
+ PublicKeyCredentialRequestOptionsPtr options =
+ GetTestPublicKeyCredentialRequestOptions();
+ auto credential = PublicKeyCredentialDescriptor::New();
+ credential->type = PublicKeyCredentialType::PUBLIC_KEY;
+ credential->id.resize(size);
+
+ const bool should_be_valid = size < 256;
+ if (should_be_valid) {
+ ASSERT_TRUE(scoped_virtual_device.mutable_state()->InjectRegistration(
+ credential->id, kTestRelyingPartyId));
+ }
+
+ options->allow_credentials.emplace_back(std::move(credential));
+
+ TestGetAssertionCallback cb;
+ authenticator->GetAssertion(std::move(options), cb.callback());
+ cb.WaitForCallback();
+
+ if (should_be_valid) {
+ EXPECT_EQ(AuthenticatorStatus::SUCCESS, cb.status());
+ } else {
+ EXPECT_EQ(AuthenticatorStatus::CREDENTIAL_NOT_RECOGNIZED, cb.status());
+ }
+ }
+}
+
+TEST_F(AuthenticatorImplTest, TestU2fDeviceDoesNotSupportMakeCredential) {
+ base::test::ScopedFeatureList scoped_feature_list;
+ scoped_feature_list.InitAndEnableFeature(features::kWebAuthCtap2);
+
+ SimulateNavigation(GURL(kTestOrigin1));
+ PublicKeyCredentialCreationOptionsPtr options =
+ GetTestPublicKeyCredentialCreationOptions();
+ TestMakeCredentialCallback cb;
+
+ // Set up service_manager::Connector for tests.
+ auto fake_hid_manager = std::make_unique<device::FakeHidManager>();
+ service_manager::mojom::ConnectorRequest request;
+ auto connector = service_manager::Connector::Create(&request);
+
+ // Set up a timer for testing.
+ auto task_runner = base::MakeRefCounted<base::TestMockTimeTaskRunner>(
+ base::Time::Now(), base::TimeTicks::Now());
+ auto timer =
+ std::make_unique<base::OneShotTimer>(task_runner->GetMockTickClock());
timer->SetTaskRunner(task_runner);
AuthenticatorPtr authenticator =
ConnectToAuthenticator(connector.get(), std::move(timer));
+ device::test::ScopedVirtualFidoDevice virtual_device;
+ authenticator->MakeCredential(std::move(options), cb.callback());
+
+ // Trigger timer.
+ base::RunLoop().RunUntilIdle();
+ task_runner->FastForwardBy(base::TimeDelta::FromMinutes(1));
+ cb.WaitForCallback();
+ EXPECT_EQ(AuthenticatorStatus::NOT_ALLOWED_ERROR, cb.status());
+}
+
+TEST_F(AuthenticatorImplTest, TestU2fDeviceDoesNotSupportGetAssertion) {
+ base::test::ScopedFeatureList scoped_feature_list;
+ scoped_feature_list.InitAndEnableFeature(features::kWebAuthCtap2);
+
+ SimulateNavigation(GURL(kTestOrigin1));
+ PublicKeyCredentialRequestOptionsPtr options =
+ GetTestPublicKeyCredentialRequestOptions();
+ TestGetAssertionCallback cb;
+
+ // Set up service_manager::Connector for tests.
+ auto fake_hid_manager = std::make_unique<device::FakeHidManager>();
+ service_manager::mojom::ConnectorRequest request;
+ auto connector = service_manager::Connector::Create(&request);
+
+ // Set up a timer for testing.
+ auto task_runner = base::MakeRefCounted<base::TestMockTimeTaskRunner>(
+ base::Time::Now(), base::TimeTicks::Now());
+ auto timer =
+ std::make_unique<base::OneShotTimer>(task_runner->GetMockTickClock());
+ timer->SetTaskRunner(task_runner);
+ AuthenticatorPtr authenticator =
+ ConnectToAuthenticator(connector.get(), std::move(timer));
+
+ device::test::ScopedVirtualFidoDevice virtual_device;
authenticator->GetAssertion(std::move(options), cb.callback());
// Trigger timer.
base::RunLoop().RunUntilIdle();
task_runner->FastForwardBy(base::TimeDelta::FromMinutes(1));
cb.WaitForCallback();
- EXPECT_EQ(webauth::mojom::AuthenticatorStatus::NOT_ALLOWED_ERROR,
- cb.GetResponseStatus());
+ EXPECT_EQ(AuthenticatorStatus::NOT_ALLOWED_ERROR, cb.status());
+}
+
+TEST_F(AuthenticatorImplTest, GetAssertionWithEmptyAllowCredentials) {
+ device::test::ScopedVirtualFidoDevice scoped_virtual_device;
+ TestServiceManagerContext service_manager_context;
+
+ SimulateNavigation(GURL(kTestOrigin1));
+ AuthenticatorPtr authenticator = ConnectToAuthenticator();
+ PublicKeyCredentialRequestOptionsPtr options =
+ GetTestPublicKeyCredentialRequestOptions();
+ options->allow_credentials.clear();
+
+ TestGetAssertionCallback cb;
+ authenticator->GetAssertion(std::move(options), cb.callback());
+ cb.WaitForCallback();
+
+ EXPECT_EQ(AuthenticatorStatus::EMPTY_ALLOW_CREDENTIALS, cb.status());
}
+
+enum class IndividualAttestation {
+ REQUESTED,
+ NOT_REQUESTED,
+};
+
+enum class AttestationConsent {
+ GRANTED,
+ DENIED,
+};
+
+// Implements ContentBrowserClient and allows webauthn-related calls to be
+// mocked.
+class AuthenticatorTestContentBrowserClient : public ContentBrowserClient {
+ public:
+ bool ShouldPermitIndividualAttestationForWebauthnRPID(
+ content::BrowserContext* browser_context,
+ const std::string& rp_id) override {
+ return individual_attestation_ == IndividualAttestation::REQUESTED;
+ }
+
+ void ShouldReturnAttestationForWebauthnRPID(
+ content::RenderFrameHost* rfh,
+ const std::string& rp_id,
+ const url::Origin& origin,
+ base::OnceCallback<void(bool)> callback) override {
+ std::move(callback).Run(attestation_consent_ ==
+ AttestationConsent::GRANTED);
+ }
+
+ bool IsFocused(content::WebContents* web_contents) override {
+ return focused_;
+ }
+
+ void set_individual_attestation(IndividualAttestation value) {
+ individual_attestation_ = value;
+ }
+
+ void set_attestation_consent(AttestationConsent value) {
+ attestation_consent_ = value;
+ }
+
+ void set_focused(bool is_focused) { focused_ = is_focused; }
+
+ private:
+ IndividualAttestation individual_attestation_ =
+ IndividualAttestation::NOT_REQUESTED;
+ AttestationConsent attestation_consent_ = AttestationConsent::DENIED;
+ bool focused_ = true;
+};
+
+// A test class that installs and removes an
+// |AuthenticatorTestContentBrowserClient| automatically and can run tests
+// against simulated attestation results.
+class AuthenticatorContentBrowserClientTest : public AuthenticatorImplTest {
+ public:
+ AuthenticatorContentBrowserClientTest() = default;
+
+ struct TestCase {
+ AttestationConveyancePreference attestation_requested;
+ IndividualAttestation individual_attestation;
+ AttestationConsent attestation_consent;
+ AuthenticatorStatus expected_status;
+ const char* expected_attestation_format;
+ const char* expected_certificate_substring;
+ };
+
+ void SetUp() override {
+ AuthenticatorImplTest::SetUp();
+ old_client_ = SetBrowserClientForTesting(&test_client_);
+ }
+
+ void TearDown() override {
+ SetBrowserClientForTesting(old_client_);
+ AuthenticatorImplTest::TearDown();
+ }
+
+ void RunTestCases(const std::vector<TestCase>& tests) {
+ TestServiceManagerContext smc_;
+ AuthenticatorPtr authenticator = ConnectToAuthenticator();
+
+ for (size_t i = 0; i < tests.size(); i++) {
+ const auto& test = tests[i];
+ SCOPED_TRACE(test.attestation_consent == AttestationConsent::GRANTED
+ ? "consent granted"
+ : "consent denied");
+ SCOPED_TRACE(test.individual_attestation ==
+ IndividualAttestation::REQUESTED
+ ? "individual attestation"
+ : "no individual attestation");
+ SCOPED_TRACE(
+ AttestationConveyancePreferenceToString(test.attestation_requested));
+ SCOPED_TRACE(i);
+
+ test_client_.set_individual_attestation(test.individual_attestation);
+ test_client_.set_attestation_consent(test.attestation_consent);
+
+ PublicKeyCredentialCreationOptionsPtr options =
+ GetTestPublicKeyCredentialCreationOptions();
+ options->relying_party->id = "example.com";
+ options->adjusted_timeout = base::TimeDelta::FromSeconds(1);
+ options->attestation = test.attestation_requested;
+ TestMakeCredentialCallback cb;
+ authenticator->MakeCredential(std::move(options), cb.callback());
+ cb.WaitForCallback();
+ ASSERT_EQ(test.expected_status, cb.status());
+
+ if (test.expected_status != AuthenticatorStatus::SUCCESS) {
+ ASSERT_STREQ("", test.expected_attestation_format);
+ continue;
+ }
+
+ base::Optional<CBORValue> attestation_value =
+ CBORReader::Read(cb.value()->attestation_object);
+ ASSERT_TRUE(attestation_value);
+ ASSERT_TRUE(attestation_value->is_map());
+ const auto& attestation = attestation_value->GetMap();
+ ExpectMapHasKeyWithStringValue(attestation, "fmt",
+ test.expected_attestation_format);
+ if (strlen(test.expected_certificate_substring) > 0) {
+ ExpectCertificateContainingSubstring(
+ attestation, test.expected_certificate_substring);
+ }
+ }
+ }
+
+ protected:
+ AuthenticatorTestContentBrowserClient test_client_;
+ device::test::ScopedVirtualFidoDevice virtual_device_;
+
+ private:
+ static const char* AttestationConveyancePreferenceToString(
+ AttestationConveyancePreference v) {
+ switch (v) {
+ case AttestationConveyancePreference::NONE:
+ return "none";
+ case AttestationConveyancePreference::INDIRECT:
+ return "indirect";
+ case AttestationConveyancePreference::DIRECT:
+ return "direct";
+ default:
+ NOTREACHED();
+ return "";
+ }
+ }
+
+ // Expects that |map| contains the given key with a string-value equal to
+ // |expected|.
+ static void ExpectMapHasKeyWithStringValue(const CBORValue::MapValue& map,
+ const char* key,
+ const char* expected) {
+ const auto it = map.find(CBORValue(key));
+ ASSERT_TRUE(it != map.end()) << "No such key '" << key << "'";
+ const auto& value = it->second;
+ EXPECT_TRUE(value.is_string())
+ << "Value of '" << key << "' has type "
+ << static_cast<int>(value.type()) << ", but expected to find a string";
+ EXPECT_EQ(std::string(expected), value.GetString())
+ << "Value of '" << key << "' is '" << value.GetString()
+ << "', but expected to find '" << expected << "'";
+ }
+
+ // Asserts that the webauthn attestation CBOR map in |attestation| contains
+ // a single X.509 certificate containing |substring|.
+ static void ExpectCertificateContainingSubstring(
+ const CBORValue::MapValue& attestation,
+ const std::string& substring) {
+ const auto& attestation_statement_it =
+ attestation.find(CBORValue("attStmt"));
+ ASSERT_TRUE(attestation_statement_it != attestation.end());
+ ASSERT_TRUE(attestation_statement_it->second.is_map());
+ const auto& attestation_statement =
+ attestation_statement_it->second.GetMap();
+ const auto& x5c_it = attestation_statement.find(CBORValue("x5c"));
+ ASSERT_TRUE(x5c_it != attestation_statement.end());
+ ASSERT_TRUE(x5c_it->second.is_array());
+ const auto& x5c = x5c_it->second.GetArray();
+ ASSERT_EQ(1u, x5c.size());
+ ASSERT_TRUE(x5c[0].is_bytestring());
+ base::StringPiece cert = x5c[0].GetBytestringAsString();
+ EXPECT_TRUE(cert.find(substring) != cert.npos);
+ }
+
+ ContentBrowserClient* old_client_ = nullptr;
+
+ DISALLOW_COPY_AND_ASSIGN(AuthenticatorContentBrowserClientTest);
+};
+
+TEST_F(AuthenticatorContentBrowserClientTest, AttestationBehaviour) {
+ const char kStandardCommonName[] = "U2F Attestation";
+ const char kIndividualCommonName[] = "Individual Cert";
+
+ const std::vector<TestCase> kTests = {
+ {
+ AttestationConveyancePreference::NONE,
+ IndividualAttestation::NOT_REQUESTED, AttestationConsent::DENIED,
+ AuthenticatorStatus::SUCCESS, "none", "",
+ },
+ {
+ AttestationConveyancePreference::NONE,
+ IndividualAttestation::REQUESTED, AttestationConsent::DENIED,
+ AuthenticatorStatus::SUCCESS, "none", "",
+ },
+ {
+ AttestationConveyancePreference::INDIRECT,
+ IndividualAttestation::NOT_REQUESTED, AttestationConsent::DENIED,
+ AuthenticatorStatus::NOT_ALLOWED_ERROR, "", "",
+ },
+ {
+ AttestationConveyancePreference::INDIRECT,
+ IndividualAttestation::REQUESTED, AttestationConsent::DENIED,
+ AuthenticatorStatus::NOT_ALLOWED_ERROR, "", "",
+ },
+ {
+ AttestationConveyancePreference::INDIRECT,
+ IndividualAttestation::NOT_REQUESTED, AttestationConsent::GRANTED,
+ AuthenticatorStatus::SUCCESS, "fido-u2f", kStandardCommonName,
+ },
+ {
+ AttestationConveyancePreference::INDIRECT,
+ IndividualAttestation::REQUESTED, AttestationConsent::GRANTED,
+ AuthenticatorStatus::SUCCESS, "fido-u2f", kIndividualCommonName,
+ },
+ {
+ AttestationConveyancePreference::DIRECT,
+ IndividualAttestation::NOT_REQUESTED, AttestationConsent::DENIED,
+ AuthenticatorStatus::NOT_ALLOWED_ERROR, "", "",
+ },
+ {
+ AttestationConveyancePreference::DIRECT,
+ IndividualAttestation::REQUESTED, AttestationConsent::DENIED,
+ AuthenticatorStatus::NOT_ALLOWED_ERROR, "", "",
+ },
+ {
+ AttestationConveyancePreference::DIRECT,
+ IndividualAttestation::NOT_REQUESTED, AttestationConsent::GRANTED,
+ AuthenticatorStatus::SUCCESS, "fido-u2f", kStandardCommonName,
+ },
+ {
+ AttestationConveyancePreference::DIRECT,
+ IndividualAttestation::REQUESTED, AttestationConsent::GRANTED,
+ AuthenticatorStatus::SUCCESS, "fido-u2f", kIndividualCommonName,
+ },
+ };
+
+ virtual_device_.mutable_state()->attestation_cert_common_name =
+ kStandardCommonName;
+ virtual_device_.mutable_state()->individual_attestation_cert_common_name =
+ kIndividualCommonName;
+ NavigateAndCommit(GURL("https://example.com"));
+
+ RunTestCases(kTests);
+}
+
+TEST_F(AuthenticatorContentBrowserClientTest,
+ InappropriatelyIdentifyingAttestation) {
+ // This common name is used by several devices that have inappropriately
+ // identifying attestation certificates.
+ const char kCommonName[] = "FT FIDO 0100";
+
+ const std::vector<TestCase> kTests = {
+ {
+ AttestationConveyancePreference::DIRECT,
+ IndividualAttestation::NOT_REQUESTED, AttestationConsent::DENIED,
+ AuthenticatorStatus::NOT_ALLOWED_ERROR, "", "",
+ },
+ {
+ AttestationConveyancePreference::DIRECT,
+ IndividualAttestation::NOT_REQUESTED, AttestationConsent::GRANTED,
+ AuthenticatorStatus::SUCCESS,
+ // If individual attestation was not requested then the attestation
+ // certificate will be removed, even if consent is given, because
+ // the consent isn't to be tracked.
+ "none", "",
+ },
+ {
+ AttestationConveyancePreference::DIRECT,
+ IndividualAttestation::REQUESTED, AttestationConsent::GRANTED,
+ AuthenticatorStatus::SUCCESS, "fido-u2f", kCommonName,
+ },
+ };
+
+ virtual_device_.mutable_state()->attestation_cert_common_name = kCommonName;
+ virtual_device_.mutable_state()->individual_attestation_cert_common_name =
+ kCommonName;
+ NavigateAndCommit(GURL("https://example.com"));
+
+ RunTestCases(kTests);
+}
+
+TEST_F(AuthenticatorContentBrowserClientTest, Unfocused) {
+ // When the |ContentBrowserClient| considers the tab to be unfocused,
+ // registration requests should fail with a |NOT_FOCUSED| error, but getting
+ // assertions should still work.
+ test_client_.set_focused(false);
+
+ NavigateAndCommit(GURL(kTestOrigin1));
+ AuthenticatorPtr authenticator = ConnectToAuthenticator();
+
+ {
+ PublicKeyCredentialCreationOptionsPtr options =
+ GetTestPublicKeyCredentialCreationOptions();
+ options->public_key_parameters = GetTestPublicKeyCredentialParameters(123);
+
+ TestMakeCredentialCallback cb;
+ authenticator->MakeCredential(std::move(options), cb.callback());
+ cb.WaitForCallback();
+ EXPECT_EQ(AuthenticatorStatus::NOT_FOCUSED, cb.status());
+ }
+
+ {
+ TestServiceManagerContext service_manager_context;
+
+ PublicKeyCredentialRequestOptionsPtr options =
+ GetTestPublicKeyCredentialRequestOptions();
+
+ auto credential = PublicKeyCredentialDescriptor::New();
+ credential->type = PublicKeyCredentialType::PUBLIC_KEY;
+ credential->id.resize(16);
+ ASSERT_TRUE(virtual_device_.mutable_state()->InjectRegistration(
+ credential->id, kTestRelyingPartyId));
+ options->allow_credentials.emplace_back(std::move(credential));
+
+ TestGetAssertionCallback cb;
+ authenticator->GetAssertion(std::move(options), cb.callback());
+ cb.WaitForCallback();
+
+ EXPECT_EQ(AuthenticatorStatus::SUCCESS, cb.status());
+ }
+}
+
} // namespace content
diff --git a/chromium/content/browser/webauth/authenticator_type_converters.cc b/chromium/content/browser/webauth/authenticator_type_converters.cc
new file mode 100644
index 00000000000..c8d238b97ad
--- /dev/null
+++ b/chromium/content/browser/webauth/authenticator_type_converters.cc
@@ -0,0 +1,164 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/webauth/authenticator_type_converters.h"
+
+#include <algorithm>
+
+#include "device/fido/fido_constants.h"
+
+namespace mojo {
+
+using ::webauth::mojom::PublicKeyCredentialUserEntityPtr;
+using ::webauth::mojom::PublicKeyCredentialRpEntityPtr;
+using ::webauth::mojom::AuthenticatorTransport;
+using ::webauth::mojom::PublicKeyCredentialType;
+using ::webauth::mojom::PublicKeyCredentialParametersPtr;
+using ::webauth::mojom::PublicKeyCredentialDescriptorPtr;
+using ::webauth::mojom::AuthenticatorSelectionCriteriaPtr;
+using ::webauth::mojom::AuthenticatorAttachment;
+using ::webauth::mojom::UserVerificationRequirement;
+
+// static
+::device::FidoTransportProtocol
+TypeConverter<::device::FidoTransportProtocol, AuthenticatorTransport>::Convert(
+ const AuthenticatorTransport& input) {
+ switch (input) {
+ case AuthenticatorTransport::USB:
+ return ::device::FidoTransportProtocol::kUsbHumanInterfaceDevice;
+ case AuthenticatorTransport::NFC:
+ return ::device::FidoTransportProtocol::kNearFieldCommunication;
+ case AuthenticatorTransport::BLE:
+ return ::device::FidoTransportProtocol::kBluetoothLowEnergy;
+ }
+ NOTREACHED();
+ return ::device::FidoTransportProtocol::kUsbHumanInterfaceDevice;
+}
+
+// static
+::device::CredentialType
+TypeConverter<::device::CredentialType, PublicKeyCredentialType>::Convert(
+ const PublicKeyCredentialType& input) {
+ switch (input) {
+ case PublicKeyCredentialType::PUBLIC_KEY:
+ return ::device::CredentialType::kPublicKey;
+ }
+ NOTREACHED();
+ return ::device::CredentialType::kPublicKey;
+}
+
+// static
+std::vector<::device::PublicKeyCredentialParams::CredentialInfo>
+TypeConverter<std::vector<::device::PublicKeyCredentialParams::CredentialInfo>,
+ std::vector<PublicKeyCredentialParametersPtr>>::
+ Convert(const std::vector<PublicKeyCredentialParametersPtr>& input) {
+ std::vector<::device::PublicKeyCredentialParams::CredentialInfo>
+ credential_params;
+ credential_params.reserve(input.size());
+
+ for (const auto& credential : input) {
+ credential_params.emplace_back(
+ ::device::PublicKeyCredentialParams::CredentialInfo{
+ ConvertTo<::device::CredentialType>(credential->type),
+ credential->algorithm_identifier});
+ }
+
+ return credential_params;
+}
+
+// static
+std::vector<::device::PublicKeyCredentialDescriptor>
+TypeConverter<std::vector<::device::PublicKeyCredentialDescriptor>,
+ std::vector<PublicKeyCredentialDescriptorPtr>>::
+ Convert(const std::vector<PublicKeyCredentialDescriptorPtr>& input) {
+ std::vector<::device::PublicKeyCredentialDescriptor> credential_descriptors;
+ credential_descriptors.reserve(input.size());
+
+ for (const auto& credential : input) {
+ credential_descriptors.emplace_back(::device::PublicKeyCredentialDescriptor(
+ device::to_string(
+ ConvertTo<::device::CredentialType>(credential->type)),
+ credential->id));
+ }
+ return credential_descriptors;
+}
+
+// static
+::device::UserVerificationRequirement
+TypeConverter<::device::UserVerificationRequirement,
+ UserVerificationRequirement>::
+ Convert(const ::webauth::mojom::UserVerificationRequirement& input) {
+ switch (input) {
+ case UserVerificationRequirement::PREFERRED:
+ return ::device::UserVerificationRequirement::kPreferred;
+ case UserVerificationRequirement::REQUIRED:
+ return ::device::UserVerificationRequirement::kRequired;
+ case UserVerificationRequirement::DISCOURAGED:
+ return ::device::UserVerificationRequirement::kDiscouraged;
+ }
+ NOTREACHED();
+ return ::device::UserVerificationRequirement::kPreferred;
+}
+
+// static
+::device::AuthenticatorSelectionCriteria::AuthenticatorAttachment TypeConverter<
+ ::device::AuthenticatorSelectionCriteria::AuthenticatorAttachment,
+ AuthenticatorAttachment>::Convert(const AuthenticatorAttachment& input) {
+ switch (input) {
+ case AuthenticatorAttachment::NO_PREFERENCE:
+ return ::device::AuthenticatorSelectionCriteria::AuthenticatorAttachment::
+ kAny;
+ case AuthenticatorAttachment::PLATFORM:
+ return ::device::AuthenticatorSelectionCriteria::AuthenticatorAttachment::
+ kPlatform;
+ case AuthenticatorAttachment::CROSS_PLATFORM:
+ return ::device::AuthenticatorSelectionCriteria::AuthenticatorAttachment::
+ kCrossPlatform;
+ }
+ NOTREACHED();
+ return ::device::AuthenticatorSelectionCriteria::AuthenticatorAttachment::
+ kAny;
+}
+
+// static
+::device::AuthenticatorSelectionCriteria
+TypeConverter<::device::AuthenticatorSelectionCriteria,
+ AuthenticatorSelectionCriteriaPtr>::
+ Convert(const AuthenticatorSelectionCriteriaPtr& input) {
+ return device::AuthenticatorSelectionCriteria(
+ ConvertTo<
+ ::device::AuthenticatorSelectionCriteria::AuthenticatorAttachment>(
+ input->authenticator_attachment),
+ input->require_resident_key,
+ ConvertTo<::device::UserVerificationRequirement>(
+ input->user_verification));
+}
+
+// static
+::device::PublicKeyCredentialRpEntity
+TypeConverter<::device::PublicKeyCredentialRpEntity,
+ PublicKeyCredentialRpEntityPtr>::
+ Convert(const PublicKeyCredentialRpEntityPtr& input) {
+ device::PublicKeyCredentialRpEntity rp_entity(input->id);
+ rp_entity.SetRpName(input->name);
+ if (input->icon)
+ rp_entity.SetRpIconUrl(*input->icon);
+
+ return rp_entity;
+}
+
+// static
+::device::PublicKeyCredentialUserEntity
+TypeConverter<::device::PublicKeyCredentialUserEntity,
+ PublicKeyCredentialUserEntityPtr>::
+ Convert(const PublicKeyCredentialUserEntityPtr& input) {
+ device::PublicKeyCredentialUserEntity user_entity(input->id);
+ user_entity.SetUserName(input->name).SetDisplayName(input->display_name);
+ if (input->icon)
+ user_entity.SetIconUrl(*input->icon);
+
+ return user_entity;
+}
+
+} // namespace mojo
diff --git a/chromium/content/browser/webauth/authenticator_type_converters.h b/chromium/content/browser/webauth/authenticator_type_converters.h
new file mode 100644
index 00000000000..0f5c2a1a13c
--- /dev/null
+++ b/chromium/content/browser/webauth/authenticator_type_converters.h
@@ -0,0 +1,94 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_BROWSER_WEBAUTH_AUTHENTICATOR_TYPE_CONVERTERS_H_
+#define CONTENT_BROWSER_WEBAUTH_AUTHENTICATOR_TYPE_CONVERTERS_H_
+
+#include <vector>
+
+#include "device/fido/authenticator_selection_criteria.h"
+#include "device/fido/fido_transport_protocol.h"
+#include "device/fido/public_key_credential_descriptor.h"
+#include "device/fido/public_key_credential_params.h"
+#include "device/fido/public_key_credential_rp_entity.h"
+#include "device/fido/public_key_credential_user_entity.h"
+#include "mojo/public/cpp/bindings/type_converter.h"
+#include "third_party/blink/public/platform/modules/webauth/authenticator.mojom.h"
+
+// TODO(hongjunchoi): Remove type converters and instead expose mojo interface
+// directly from device/fido service.
+// See: https://crbug.com/831209
+namespace mojo {
+
+template <>
+struct TypeConverter<::device::FidoTransportProtocol,
+ ::webauth::mojom::AuthenticatorTransport> {
+ static ::device::FidoTransportProtocol Convert(
+ const ::webauth::mojom::AuthenticatorTransport& input);
+};
+
+template <>
+struct TypeConverter<::device::CredentialType,
+ ::webauth::mojom::PublicKeyCredentialType> {
+ static ::device::CredentialType Convert(
+ const ::webauth::mojom::PublicKeyCredentialType& input);
+};
+
+template <>
+struct TypeConverter<
+ std::vector<::device::PublicKeyCredentialParams::CredentialInfo>,
+ std::vector<::webauth::mojom::PublicKeyCredentialParametersPtr>> {
+ static std::vector<::device::PublicKeyCredentialParams::CredentialInfo>
+ Convert(const std::vector<::webauth::mojom::PublicKeyCredentialParametersPtr>&
+ input);
+};
+
+template <>
+struct TypeConverter<
+ std::vector<::device::PublicKeyCredentialDescriptor>,
+ std::vector<::webauth::mojom::PublicKeyCredentialDescriptorPtr>> {
+ static std::vector<::device::PublicKeyCredentialDescriptor> Convert(
+ const std::vector<::webauth::mojom::PublicKeyCredentialDescriptorPtr>&
+ input);
+};
+
+template <>
+struct TypeConverter<
+ ::device::AuthenticatorSelectionCriteria::AuthenticatorAttachment,
+ ::webauth::mojom::AuthenticatorAttachment> {
+ static ::device::AuthenticatorSelectionCriteria::AuthenticatorAttachment
+ Convert(const ::webauth::mojom::AuthenticatorAttachment& input);
+};
+
+template <>
+struct TypeConverter<::device::UserVerificationRequirement,
+ ::webauth::mojom::UserVerificationRequirement> {
+ static ::device::UserVerificationRequirement Convert(
+ const ::webauth::mojom::UserVerificationRequirement& input);
+};
+
+template <>
+struct TypeConverter<::device::AuthenticatorSelectionCriteria,
+ ::webauth::mojom::AuthenticatorSelectionCriteriaPtr> {
+ static ::device::AuthenticatorSelectionCriteria Convert(
+ const ::webauth::mojom::AuthenticatorSelectionCriteriaPtr& input);
+};
+
+template <>
+struct TypeConverter<::device::PublicKeyCredentialRpEntity,
+ ::webauth::mojom::PublicKeyCredentialRpEntityPtr> {
+ static ::device::PublicKeyCredentialRpEntity Convert(
+ const ::webauth::mojom::PublicKeyCredentialRpEntityPtr& input);
+};
+
+template <>
+struct TypeConverter<::device::PublicKeyCredentialUserEntity,
+ ::webauth::mojom::PublicKeyCredentialUserEntityPtr> {
+ static ::device::PublicKeyCredentialUserEntity Convert(
+ const ::webauth::mojom::PublicKeyCredentialUserEntityPtr& input);
+};
+
+} // namespace mojo
+
+#endif // CONTENT_BROWSER_WEBAUTH_AUTHENTICATOR_TYPE_CONVERTERS_H_
diff --git a/chromium/content/browser/webauth/scoped_virtual_authenticator_environment.cc b/chromium/content/browser/webauth/scoped_virtual_authenticator_environment.cc
new file mode 100644
index 00000000000..630260d0cf8
--- /dev/null
+++ b/chromium/content/browser/webauth/scoped_virtual_authenticator_environment.cc
@@ -0,0 +1,119 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/webauth/scoped_virtual_authenticator_environment.h"
+
+#include <utility>
+
+#include "base/stl_util.h"
+#include "content/browser/webauth/authenticator_type_converters.h"
+#include "content/browser/webauth/virtual_authenticator.h"
+#include "content/browser/webauth/virtual_discovery.h"
+
+namespace content {
+
+namespace {
+
+webauth::test::mojom::VirtualAuthenticatorPtr GetMojoPtrToVirtualAuthenticator(
+ VirtualAuthenticator* authenticator) {
+ webauth::test::mojom::VirtualAuthenticatorPtr mojo_authenticator_ptr;
+ authenticator->AddBinding(mojo::MakeRequest(&mojo_authenticator_ptr));
+ return mojo_authenticator_ptr;
+}
+
+} // namespace
+
+// static
+ScopedVirtualAuthenticatorEnvironment*
+ScopedVirtualAuthenticatorEnvironment::GetInstance() {
+ static base::NoDestructor<ScopedVirtualAuthenticatorEnvironment> environment;
+ return environment.get();
+}
+
+ScopedVirtualAuthenticatorEnvironment::ScopedVirtualAuthenticatorEnvironment() =
+ default;
+ScopedVirtualAuthenticatorEnvironment::
+ ~ScopedVirtualAuthenticatorEnvironment() = default;
+
+void ScopedVirtualAuthenticatorEnvironment::AddBinding(
+ webauth::test::mojom::VirtualAuthenticatorManagerRequest request) {
+ bindings_.AddBinding(this, std::move(request));
+}
+
+void ScopedVirtualAuthenticatorEnvironment::CreateAuthenticator(
+ webauth::test::mojom::VirtualAuthenticatorOptionsPtr options,
+ CreateAuthenticatorCallback callback) {
+ auto authenticator = std::make_unique<VirtualAuthenticator>(
+ mojo::ConvertTo<::device::FidoTransportProtocol>(options->transport));
+ auto* authenticator_ptr = authenticator.get();
+ authenticators_.emplace(authenticator_ptr->unique_id(),
+ std::move(authenticator));
+
+ for (auto* discovery : discoveries_) {
+ if (discovery->transport() != authenticator_ptr->transport())
+ continue;
+ discovery->AddVirtualDevice(authenticator_ptr->ConstructDevice());
+ }
+
+ std::move(callback).Run(GetMojoPtrToVirtualAuthenticator(authenticator_ptr));
+}
+
+void ScopedVirtualAuthenticatorEnvironment::GetAuthenticators(
+ GetAuthenticatorsCallback callback) {
+ std::vector<webauth::test::mojom::VirtualAuthenticatorPtrInfo>
+ mojo_authenticators;
+ for (auto& authenticator : authenticators_) {
+ mojo_authenticators.push_back(
+ GetMojoPtrToVirtualAuthenticator(authenticator.second.get())
+ .PassInterface());
+ }
+
+ std::move(callback).Run(std::move(mojo_authenticators));
+}
+
+void ScopedVirtualAuthenticatorEnvironment::RemoveAuthenticator(
+ const std::string& id,
+ RemoveAuthenticatorCallback callback) {
+ const bool removed = authenticators_.erase(id);
+ if (removed) {
+ for (auto* discovery : discoveries_)
+ discovery->RemoveVirtualDevice(id);
+ }
+
+ std::move(callback).Run(removed);
+}
+
+void ScopedVirtualAuthenticatorEnvironment::ClearAuthenticators(
+ ClearAuthenticatorsCallback callback) {
+ for (auto& authenticator : authenticators_) {
+ for (auto* discovery : discoveries_) {
+ discovery->RemoveVirtualDevice(authenticator.second->unique_id());
+ }
+ }
+ authenticators_.clear();
+
+ std::move(callback).Run();
+}
+
+std::unique_ptr<::device::FidoDiscovery>
+ScopedVirtualAuthenticatorEnvironment::CreateFidoDiscovery(
+ device::FidoTransportProtocol transport,
+ ::service_manager::Connector* connector) {
+ auto discovery = std::make_unique<VirtualFidoDiscovery>(this, transport);
+ for (auto& authenticator : authenticators_) {
+ if (discovery->transport() != authenticator.second->transport())
+ continue;
+ discovery->AddVirtualDevice(authenticator.second->ConstructDevice());
+ }
+ discoveries_.insert(discovery.get());
+ return discovery;
+}
+
+void ScopedVirtualAuthenticatorEnvironment::OnDiscoveryDestroyed(
+ VirtualFidoDiscovery* discovery) {
+ DCHECK(base::ContainsKey(discoveries_, discovery));
+ discoveries_.erase(discovery);
+}
+
+} // namespace content
diff --git a/chromium/content/browser/webauth/scoped_virtual_authenticator_environment.h b/chromium/content/browser/webauth/scoped_virtual_authenticator_environment.h
new file mode 100644
index 00000000000..142f6f2af32
--- /dev/null
+++ b/chromium/content/browser/webauth/scoped_virtual_authenticator_environment.h
@@ -0,0 +1,81 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_BROWSER_WEBAUTH_SCOPED_VIRTUAL_AUTHENTICATOR_ENVIRONMENT_H_
+#define CONTENT_BROWSER_WEBAUTH_SCOPED_VIRTUAL_AUTHENTICATOR_ENVIRONMENT_H_
+
+#include <map>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "base/macros.h"
+#include "base/no_destructor.h"
+#include "content/common/content_export.h"
+#include "device/fido/fido_discovery.h"
+#include "mojo/public/cpp/bindings/binding_set.h"
+#include "third_party/blink/public/platform/modules/webauth/virtual_authenticator.mojom.h"
+
+namespace content {
+
+class VirtualAuthenticator;
+class VirtualFidoDiscovery;
+
+// Implements the Mojo interface representing a scoped virtual environment for
+// the Web Authentication API. While in scope, the API is disconnected from the
+// real world and allows setting up and configuration of virtual authenticator
+// devices for testing.
+//
+// This class is a singleton. The virtual state is persisted for the entire
+// lifetime of the browser process and shared by all frames in all WebContents
+// and across all BrowserContexts.
+class CONTENT_EXPORT ScopedVirtualAuthenticatorEnvironment
+ : public webauth::test::mojom::VirtualAuthenticatorManager,
+ protected device::internal::ScopedFidoDiscoveryFactory {
+ public:
+ static ScopedVirtualAuthenticatorEnvironment* GetInstance();
+
+ void AddBinding(
+ webauth::test::mojom::VirtualAuthenticatorManagerRequest request);
+
+ protected:
+ ScopedVirtualAuthenticatorEnvironment();
+ ~ScopedVirtualAuthenticatorEnvironment() override;
+
+ // webauth::test::mojom::VirtualAuthenticatorManager:
+ void CreateAuthenticator(
+ webauth::test::mojom::VirtualAuthenticatorOptionsPtr options,
+ CreateAuthenticatorCallback callback) override;
+ void GetAuthenticators(GetAuthenticatorsCallback callback) override;
+ void RemoveAuthenticator(const std::string& id,
+ RemoveAuthenticatorCallback callback) override;
+ void ClearAuthenticators(ClearAuthenticatorsCallback callback) override;
+
+ // ScopedFidoDiscoveryFactory:
+ std::unique_ptr<::device::FidoDiscovery> CreateFidoDiscovery(
+ device::FidoTransportProtocol transport,
+ ::service_manager::Connector* connector) override;
+
+ private:
+ friend class base::NoDestructor<ScopedVirtualAuthenticatorEnvironment>;
+ friend class VirtualFidoDiscovery;
+
+ // Called by VirtualFidoDiscoveries when they are destructed.
+ void OnDiscoveryDestroyed(VirtualFidoDiscovery* discovery);
+
+ mojo::BindingSet<webauth::test::mojom::VirtualAuthenticatorManager> bindings_;
+
+ // The key is the unique_id of the corresponding value (the authenticator).
+ std::map<std::string, std::unique_ptr<VirtualAuthenticator>> authenticators_;
+
+ // Discoveries are owned by U2fRequest and FidoRequestHandler, and
+ // automatically unregister themselves upon their destruction.
+ std::set<VirtualFidoDiscovery*> discoveries_;
+
+ DISALLOW_COPY_AND_ASSIGN(ScopedVirtualAuthenticatorEnvironment);
+};
+
+} // namespace content
+
+#endif // CONTENT_BROWSER_WEBAUTH_SCOPED_VIRTUAL_AUTHENTICATOR_ENVIRONMENT_H_
diff --git a/chromium/content/browser/webauth/virtual_authenticator.cc b/chromium/content/browser/webauth/virtual_authenticator.cc
new file mode 100644
index 00000000000..f830a24927a
--- /dev/null
+++ b/chromium/content/browser/webauth/virtual_authenticator.cc
@@ -0,0 +1,82 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/webauth/virtual_authenticator.h"
+
+#include <utility>
+#include <vector>
+
+#include "base/guid.h"
+#include "crypto/ec_private_key.h"
+
+namespace content {
+
+VirtualAuthenticator::VirtualAuthenticator(
+ ::device::FidoTransportProtocol transport)
+ : transport_(transport),
+ unique_id_(base::GenerateGUID()),
+ state_(base::MakeRefCounted<::device::VirtualFidoDevice::State>()) {}
+
+VirtualAuthenticator::~VirtualAuthenticator() = default;
+
+void VirtualAuthenticator::AddBinding(
+ webauth::test::mojom::VirtualAuthenticatorRequest request) {
+ binding_set_.AddBinding(this, std::move(request));
+}
+
+std::unique_ptr<::device::FidoDevice> VirtualAuthenticator::ConstructDevice() {
+ return std::make_unique<::device::VirtualFidoDevice>(state_);
+}
+
+void VirtualAuthenticator::GetUniqueId(GetUniqueIdCallback callback) {
+ std::move(callback).Run(unique_id_);
+}
+
+void VirtualAuthenticator::GetRegistrations(GetRegistrationsCallback callback) {
+ std::vector<webauth::test::mojom::RegisteredKeyPtr> mojo_registered_keys;
+ for (const auto& registration : state_->registrations) {
+ auto mojo_registered_key = webauth::test::mojom::RegisteredKey::New();
+ mojo_registered_key->key_handle = registration.first;
+ mojo_registered_key->counter = registration.second.counter;
+ mojo_registered_key->application_parameter =
+ registration.second.application_parameter;
+ registration.second.private_key->ExportPrivateKey(
+ &mojo_registered_key->private_key);
+ mojo_registered_keys.push_back(std::move(mojo_registered_key));
+ }
+ std::move(callback).Run(std::move(mojo_registered_keys));
+}
+
+void VirtualAuthenticator::AddRegistration(
+ webauth::test::mojom::RegisteredKeyPtr registration,
+ AddRegistrationCallback callback) {
+ bool success = false;
+ std::tie(std::ignore, success) = state_->registrations.emplace(
+ std::move(registration->key_handle),
+ ::device::VirtualFidoDevice::RegistrationData(
+ crypto::ECPrivateKey::CreateFromPrivateKeyInfo(
+ registration->private_key),
+ std::move(registration->application_parameter),
+ registration->counter));
+ std::move(callback).Run(success);
+}
+
+void VirtualAuthenticator::ClearRegistrations(
+ ClearRegistrationsCallback callback) {
+ state_->registrations.clear();
+ std::move(callback).Run();
+}
+
+void VirtualAuthenticator::SetUserPresence(bool present,
+ SetUserPresenceCallback callback) {
+ // TODO(https://crbug.com/785955): Implement once VirtualFidoDevice supports
+ // this.
+ std::move(callback).Run();
+}
+
+void VirtualAuthenticator::GetUserPresence(GetUserPresenceCallback callback) {
+ std::move(callback).Run(false);
+}
+
+} // namespace content
diff --git a/chromium/content/browser/webauth/virtual_authenticator.h b/chromium/content/browser/webauth/virtual_authenticator.h
new file mode 100644
index 00000000000..c0ee5797447
--- /dev/null
+++ b/chromium/content/browser/webauth/virtual_authenticator.h
@@ -0,0 +1,68 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_BROWSER_WEBAUTH_VIRTUAL_AUTHENTICATOR_H_
+#define CONTENT_BROWSER_WEBAUTH_VIRTUAL_AUTHENTICATOR_H_
+
+#include <memory>
+#include <string>
+
+#include "base/macros.h"
+#include "base/memory/ref_counted.h"
+#include "content/common/content_export.h"
+#include "device/fido/fido_transport_protocol.h"
+#include "device/fido/virtual_fido_device.h"
+#include "mojo/public/cpp/bindings/binding_set.h"
+#include "third_party/blink/public/platform/modules/webauth/virtual_authenticator.mojom.h"
+
+namespace content {
+
+// Implements the Mojo interface representing a stateful virtual authenticator.
+//
+// This class has very little logic itself, it merely stores a unique ID and the
+// state of the authenticator, whereas performing all cryptographic operations
+// is delegated to the VirtualFidoDevice class.
+class CONTENT_EXPORT VirtualAuthenticator
+ : public webauth::test::mojom::VirtualAuthenticator {
+ public:
+ explicit VirtualAuthenticator(::device::FidoTransportProtocol transport);
+ ~VirtualAuthenticator() override;
+
+ void AddBinding(webauth::test::mojom::VirtualAuthenticatorRequest request);
+
+ ::device::FidoTransportProtocol transport() const { return transport_; }
+ const std::string& unique_id() const { return unique_id_; }
+
+ // Constructs a VirtualFidoDevice instance that will perform cryptographic
+ // operations on behalf of, and using the state stored in this virtual
+ // authenticator.
+ //
+ // There is an N:1 relationship between VirtualFidoDevices and this class, so
+ // this method can be called any number of times.
+ std::unique_ptr<::device::FidoDevice> ConstructDevice();
+
+ protected:
+ // webauth::test::mojom::VirtualAuthenticator:
+ void GetUniqueId(GetUniqueIdCallback callback) override;
+
+ void GetRegistrations(GetRegistrationsCallback callback) override;
+ void AddRegistration(webauth::test::mojom::RegisteredKeyPtr registration,
+ AddRegistrationCallback callback) override;
+ void ClearRegistrations(ClearRegistrationsCallback callback) override;
+
+ void SetUserPresence(bool present, SetUserPresenceCallback callback) override;
+ void GetUserPresence(GetUserPresenceCallback callback) override;
+
+ private:
+ const ::device::FidoTransportProtocol transport_;
+ const std::string unique_id_;
+ scoped_refptr<::device::VirtualFidoDevice::State> state_;
+ mojo::BindingSet<webauth::test::mojom::VirtualAuthenticator> binding_set_;
+
+ DISALLOW_COPY_AND_ASSIGN(VirtualAuthenticator);
+};
+
+} // namespace content
+
+#endif // CONTENT_BROWSER_WEBAUTH_VIRTUAL_AUTHENTICATOR_H_
diff --git a/chromium/content/browser/webauth/virtual_discovery.cc b/chromium/content/browser/webauth/virtual_discovery.cc
new file mode 100644
index 00000000000..1f37ee855ba
--- /dev/null
+++ b/chromium/content/browser/webauth/virtual_discovery.cc
@@ -0,0 +1,52 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/browser/webauth/virtual_discovery.h"
+
+#include "base/bind.h"
+#include "base/bind_helpers.h"
+#include "base/location.h"
+#include "base/logging.h"
+#include "base/threading/thread_task_runner_handle.h"
+#include "content/browser/webauth/scoped_virtual_authenticator_environment.h"
+#include "device/fido/fido_device.h"
+
+namespace content {
+
+VirtualFidoDiscovery::VirtualFidoDiscovery(
+ ScopedVirtualAuthenticatorEnvironment* environment,
+ ::device::FidoTransportProtocol transport)
+ : FidoDiscovery(transport), environment_(environment) {}
+
+VirtualFidoDiscovery::~VirtualFidoDiscovery() {
+ environment_->OnDiscoveryDestroyed(this);
+}
+
+void VirtualFidoDiscovery::AddVirtualDevice(
+ std::unique_ptr<::device::FidoDevice> device) {
+ // The real implementation would never notify the client's observer about
+ // devices before the client calls Start(), mimic the same behavior.
+ if (is_start_requested()) {
+ FidoDiscovery::AddDevice(std::move(device));
+ } else {
+ devices_pending_discovery_start_.push_back(std::move(device));
+ }
+}
+
+bool VirtualFidoDiscovery::RemoveVirtualDevice(base::StringPiece device_id) {
+ DCHECK(is_start_requested());
+ return ::device::FidoDiscovery::RemoveDevice(device_id);
+}
+
+void VirtualFidoDiscovery::StartInternal() {
+ for (auto& device : devices_pending_discovery_start_)
+ FidoDiscovery::AddDevice(std::move(device));
+ devices_pending_discovery_start_.clear();
+
+ base::ThreadTaskRunnerHandle::Get()->PostTask(
+ FROM_HERE, base::BindOnce(&VirtualFidoDiscovery::NotifyDiscoveryStarted,
+ base::Unretained(this), true /* success */));
+}
+
+} // namespace content
diff --git a/chromium/content/browser/webauth/virtual_discovery.h b/chromium/content/browser/webauth/virtual_discovery.h
new file mode 100644
index 00000000000..7c57b042ff9
--- /dev/null
+++ b/chromium/content/browser/webauth/virtual_discovery.h
@@ -0,0 +1,53 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_BROWSER_WEBAUTH_VIRTUAL_DISCOVERY_H_
+#define CONTENT_BROWSER_WEBAUTH_VIRTUAL_DISCOVERY_H_
+
+#include <memory>
+#include <vector>
+
+#include "base/macros.h"
+#include "base/strings/string_piece.h"
+#include "content/common/content_export.h"
+#include "device/fido/fido_discovery.h"
+
+namespace device {
+class FidoDevice;
+}
+
+namespace content {
+
+class ScopedVirtualAuthenticatorEnvironment;
+
+// A fully automated FidoDiscovery implementation, which is disconnected from
+// the real world, and discovers VirtualFidoDevice instances.
+class CONTENT_EXPORT VirtualFidoDiscovery : public ::device::FidoDiscovery {
+ public:
+ // The |environment| must outlive this instance.
+ VirtualFidoDiscovery(ScopedVirtualAuthenticatorEnvironment* environment,
+ ::device::FidoTransportProtocol transport);
+
+ // Notifies the |environment| of this instance being destroyed.
+ ~VirtualFidoDiscovery() override;
+
+ void AddVirtualDevice(std::unique_ptr<::device::FidoDevice> device);
+ bool RemoveVirtualDevice(base::StringPiece device_id);
+
+ protected:
+ // FidoDiscovery:
+ void StartInternal() override;
+
+ private:
+ ScopedVirtualAuthenticatorEnvironment* environment_ = nullptr;
+
+ std::vector<std::unique_ptr<::device::FidoDevice>>
+ devices_pending_discovery_start_;
+
+ DISALLOW_COPY_AND_ASSIGN(VirtualFidoDiscovery);
+};
+
+} // namespace content
+
+#endif // CONTENT_BROWSER_WEBAUTH_VIRTUAL_DISCOVERY_H_
diff --git a/chromium/content/browser/webauth/webauth_browsertest.cc b/chromium/content/browser/webauth/webauth_browsertest.cc
index e02f2e96246..b86f292e90d 100644
--- a/chromium/content/browser/webauth/webauth_browsertest.cc
+++ b/chromium/content/browser/webauth/webauth_browsertest.cc
@@ -8,66 +8,298 @@
#include "base/command_line.h"
#include "base/macros.h"
+#include "base/run_loop.h"
+#include "base/test/bind_test_util.h"
#include "base/test/scoped_feature_list.h"
-#include "base/test/test_mock_time_task_runner.h"
-#include "base/time/tick_clock.h"
-#include "base/time/time.h"
#include "components/network_session_configurator/common/network_switches.h"
+#include "content/browser/frame_host/render_frame_host_impl.h"
#include "content/browser/webauth/authenticator_impl.h"
+#include "content/public/browser/navigation_handle.h"
+#include "content/public/browser/navigation_throttle.h"
#include "content/public/browser/web_contents.h"
+#include "content/public/browser/web_contents_observer.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/service_manager_connection.h"
-#include "content/public/test/browser_test.h"
+#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/shell/browser/shell.h"
+#include "content/test/did_commit_provisional_load_interceptor.h"
+#include "device/fido/fake_fido_discovery.h"
#include "device/fido/fake_hid_impl_for_testing.h"
+#include "device/fido/fido_test_data.h"
+#include "device/fido/mock_fido_device.h"
+#include "device/fido/test_callback_receiver.h"
#include "net/dns/mock_host_resolver.h"
#include "services/device/public/mojom/constants.mojom.h"
#include "services/service_manager/public/cpp/connector.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/modules/webauth/authenticator.mojom.h"
+#include "third_party/blink/public/platform/modules/webauth/authenticator.mojom.h"
namespace content {
+namespace {
+
+using webauth::mojom::Authenticator;
using webauth::mojom::AuthenticatorPtr;
using webauth::mojom::AuthenticatorStatus;
using webauth::mojom::GetAssertionAuthenticatorResponsePtr;
using webauth::mojom::MakeCredentialAuthenticatorResponsePtr;
-class WebAuthBrowserTest : public content::ContentBrowserTest {
+using TestCreateCallbackReceiver =
+ ::device::test::StatusAndValueCallbackReceiver<
+ AuthenticatorStatus,
+ MakeCredentialAuthenticatorResponsePtr>;
+
+using TestGetCallbackReceiver = ::device::test::StatusAndValueCallbackReceiver<
+ AuthenticatorStatus,
+ GetAssertionAuthenticatorResponsePtr>;
+
+constexpr char kRelyingPartySecurityErrorMessage[] =
+ "SecurityError: The relying party ID 'localhost' is not a registrable "
+ "domain suffix of, nor equal to 'https://www.acme.com";
+
+constexpr char kAlgorithmUnsupportedErrorMessage[] =
+ "NotSupportedError: None of the algorithms specified in "
+ "`pubKeyCredParams` are compatible with "
+ "CTAP1/U2F authenticators, and CTAP2 "
+ "authenticators are not yet supported.";
+
+constexpr char kAuthenticatorCriteriaErrorMessage[] =
+ "NotSupportedError: The specified `authenticatorSelection` "
+ "criteria cannot be fulfilled by CTAP1/U2F "
+ "authenticators, and CTAP2 authenticators "
+ "are not yet supported.";
+
+constexpr char kUserVerificationErrorMessage[] =
+ "NotSupportedError: The specified `userVerification` "
+ "requirement cannot be fulfilled by "
+ "CTAP1/U2F authenticators, and CTAP2 "
+ "authenticators are not yet supported.";
+
+constexpr char kEmptyAllowCredentialsErrorMessage[] =
+ "NotSupportedError: The `allowCredentials` list cannot be left "
+ "empty for CTAP1/U2F authenticators, and "
+ "support for CTAP2 authenticators is not yet "
+ "implemented.";
+
+// Templates to be used with base::ReplaceStringPlaceholders. Can be
+// modified to include up to 9 replacements. The default values for
+// any additional replacements added should also be added to the
+// CreateParameters struct.
+constexpr char kCreatePublicKeyTemplate[] =
+ "navigator.credentials.create({ publicKey: {"
+ " challenge: new TextEncoder().encode('climb a mountain'),"
+ " rp: { id: '$3', name: 'Acme' },"
+ " user: { "
+ " id: new TextEncoder().encode('1098237235409872'),"
+ " name: 'avery.a.jones@example.com',"
+ " displayName: 'Avery A. Jones', "
+ " icon: 'https://pics.acme.com/00/p/aBjjjpqPb.png'},"
+ " pubKeyCredParams: [{ type: 'public-key', alg: '$4'}],"
+ " timeout: 60000,"
+ " excludeCredentials: [],"
+ " authenticatorSelection : {"
+ " requireResidentKey: $1,"
+ " userVerification: '$2',"
+ " authenticatorAttachment: '$5' }}"
+ "}).catch(c => window.domAutomationController.send(c.toString()));";
+
+constexpr char kPlatform[] = "platform";
+constexpr char kCrossPlatform[] = "cross-platform";
+constexpr char kPreferredVerification[] = "preferred";
+constexpr char kRequiredVerification[] = "required";
+
+// Default values for kCreatePublicKeyTemplate.
+struct CreateParameters {
+ const char* rp_id = "acme.com";
+ bool require_resident_key = false;
+ const char* user_verification = kPreferredVerification;
+ const char* authenticator_attachment = kCrossPlatform;
+ const char* algorithm_identifier = "-7";
+};
+
+std::string BuildCreateCallWithParameters(const CreateParameters& parameters) {
+ std::vector<std::string> substititions;
+ substititions.push_back(parameters.require_resident_key ? "true" : "false");
+ substititions.push_back(parameters.user_verification);
+ substititions.push_back(parameters.rp_id);
+ substititions.push_back(parameters.algorithm_identifier);
+ substititions.push_back(parameters.authenticator_attachment);
+ return base::ReplaceStringPlaceholders(kCreatePublicKeyTemplate,
+ substititions, nullptr);
+}
+
+constexpr char kGetPublicKeyTemplate[] =
+ "navigator.credentials.get({ publicKey: {"
+ " challenge: new TextEncoder().encode('climb a mountain'),"
+ " rp: 'acme.com',"
+ " timeout: 60000,"
+ " userVerification: '$1',"
+ " $2}"
+ "}).catch(c => window.domAutomationController.send(c.toString()));";
+
+// Default values for kGetPublicKeyTemplate.
+struct GetParameters {
+ const char* user_verification = kPreferredVerification;
+ const char* allow_credentials =
+ "allowCredentials: [{ type: 'public-key',"
+ " id: new TextEncoder().encode('allowedCredential'),"
+ " transports: ['usb', 'nfc', 'ble']}]";
+};
+
+std::string BuildGetCallWithParameters(const GetParameters& parameters) {
+ std::vector<std::string> substititions;
+ substititions.push_back(parameters.user_verification);
+ substititions.push_back(parameters.allow_credentials);
+ return base::ReplaceStringPlaceholders(kGetPublicKeyTemplate, substititions,
+ nullptr);
+}
+
+// Helper class that executes the given |closure| the very last moment before
+// the next navigation commits in a given WebContents.
+class ClosureExecutorBeforeNavigationCommit
+ : public DidCommitProvisionalLoadInterceptor {
public:
- WebAuthBrowserTest() : https_server_(net::EmbeddedTestServer::TYPE_HTTPS) {
- scoped_feature_list_.InitAndEnableFeature(features::kWebAuth);
+ ClosureExecutorBeforeNavigationCommit(WebContents* web_contents,
+ base::OnceClosure closure)
+ : DidCommitProvisionalLoadInterceptor(web_contents),
+ closure_(std::move(closure)) {}
+ ~ClosureExecutorBeforeNavigationCommit() override = default;
+
+ protected:
+ void WillDispatchDidCommitProvisionalLoad(
+ RenderFrameHost* render_frame_host,
+ ::FrameHostMsg_DidCommitProvisionalLoad_Params* params,
+ service_manager::mojom::InterfaceProviderRequest*
+ interface_provider_request) override {
+ if (closure_)
+ std::move(closure_).Run();
}
- void SetUp() override { content::ContentBrowserTest::SetUp(); }
+ private:
+ base::OnceClosure closure_;
+ DISALLOW_COPY_AND_ASSIGN(ClosureExecutorBeforeNavigationCommit);
+};
+
+// Cancels all navigations in a WebContents while in scope.
+class ScopedNavigationCancellingThrottleInstaller : public WebContentsObserver {
+ public:
+ ScopedNavigationCancellingThrottleInstaller(WebContents* web_contents)
+ : WebContentsObserver(web_contents) {}
+ ~ScopedNavigationCancellingThrottleInstaller() override = default;
+
+ protected:
+ class CancellingThrottle : public NavigationThrottle {
+ public:
+ CancellingThrottle(NavigationHandle* handle) : NavigationThrottle(handle) {}
+ ~CancellingThrottle() override = default;
+
+ protected:
+ const char* GetNameForLogging() override {
+ return "ScopedNavigationCancellingThrottleInstaller::CancellingThrottle";
+ }
+
+ ThrottleCheckResult WillStartRequest() override {
+ return ThrottleCheckResult(CANCEL);
+ }
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(CancellingThrottle);
+ };
+
+ void DidStartNavigation(NavigationHandle* navigation_handle) override {
+ navigation_handle->RegisterThrottleForTesting(
+ std::make_unique<CancellingThrottle>(navigation_handle));
+ }
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(ScopedNavigationCancellingThrottleInstaller);
+};
+
+// Test fixture base class for common tasks.
+class WebAuthBrowserTestBase : public content::ContentBrowserTest {
+ protected:
+ WebAuthBrowserTestBase()
+ : https_server_(net::EmbeddedTestServer::TYPE_HTTPS) {}
+
+ virtual std::vector<base::Feature> GetFeaturesToEnable() {
+ return {features::kWebAuth, features::kWebAuthBle};
+ }
void SetUpOnMainThread() override {
host_resolver()->AddRule("*", "127.0.0.1");
- https_server_.ServeFilesFromSourceDirectory("content/test/data");
- ASSERT_TRUE(https_server_.Start());
+ https_server().ServeFilesFromSourceDirectory("content/test/data");
+ ASSERT_TRUE(https_server().Start());
+
+ NavigateToURL(shell(), GetHttpsURL("www.acme.com", "/title1.html"));
}
+ GURL GetHttpsURL(const std::string& hostname,
+ const std::string& relative_url) {
+ return https_server_.GetURL(hostname, relative_url);
+ }
+
+ net::EmbeddedTestServer& https_server() { return https_server_; }
+ device::test::ScopedFakeFidoDiscoveryFactory* discovery_factory() {
+ return &factory_;
+ }
+
+ private:
void SetUpCommandLine(base::CommandLine* command_line) override {
+ scoped_feature_list_.InitWithFeatures(GetFeaturesToEnable(), {});
command_line->AppendSwitch(
switches::kEnableExperimentalWebPlatformFeatures);
command_line->AppendSwitch(switches::kIgnoreCertificateErrors);
}
- static constexpr int32_t kCOSEAlgorithmIdentifierES256 = -7;
+ base::test::ScopedFeatureList scoped_feature_list_;
+ net::EmbeddedTestServer https_server_;
+ device::test::ScopedFakeFidoDiscoveryFactory factory_;
+
+ DISALLOW_COPY_AND_ASSIGN(WebAuthBrowserTestBase);
+};
+
+} // namespace
+
+// WebAuthLocalClientBrowserTest ----------------------------------------------
+
+// Browser test fixture where the webauth::mojom::Authenticator interface is
+// accessed from a testing client in the browser process.
+class WebAuthLocalClientBrowserTest : public WebAuthBrowserTestBase {
+ public:
+ WebAuthLocalClientBrowserTest() = default;
+ ~WebAuthLocalClientBrowserTest() override = default;
+
+ protected:
+ void SetUpOnMainThread() override {
+ WebAuthBrowserTestBase::SetUpOnMainThread();
+ ConnectToAuthenticator();
+ }
+
+ void ConnectToAuthenticator() {
+ auto* interface_provider =
+ static_cast<service_manager::mojom::InterfaceProvider*>(
+ static_cast<RenderFrameHostImpl*>(
+ shell()->web_contents()->GetMainFrame()));
+
+ interface_provider->GetInterface(
+ Authenticator::Name_,
+ mojo::MakeRequest(&authenticator_ptr_).PassMessagePipe());
+ }
webauth::mojom::PublicKeyCredentialCreationOptionsPtr
BuildBasicCreateOptions() {
auto rp = webauth::mojom::PublicKeyCredentialRpEntity::New(
- "example.com", "example.com", base::nullopt);
+ "acme.com", "acme.com", base::nullopt);
std::vector<uint8_t> kTestUserId{0, 0, 0};
auto user = webauth::mojom::PublicKeyCredentialUserEntity::New(
kTestUserId, "name", base::nullopt, "displayName");
+ static constexpr int32_t kCOSEAlgorithmIdentifierES256 = -7;
auto param = webauth::mojom::PublicKeyCredentialParameters::New();
param->type = webauth::mojom::PublicKeyCredentialType::PUBLIC_KEY;
param->algorithm_identifier = kCOSEAlgorithmIdentifierES256;
@@ -79,7 +311,7 @@ class WebAuthBrowserTest : public content::ContentBrowserTest {
std::move(rp), std::move(user), kTestChallenge, std::move(parameters),
base::TimeDelta::FromSeconds(30),
std::vector<webauth::mojom::PublicKeyCredentialDescriptorPtr>(),
- webauth::mojom::AttestationConveyancePreference::NONE);
+ nullptr, webauth::mojom::AttestationConveyancePreference::NONE);
return mojo_options;
}
@@ -89,134 +321,410 @@ class WebAuthBrowserTest : public content::ContentBrowserTest {
std::vector<webauth::mojom::AuthenticatorTransport> transports;
transports.push_back(webauth::mojom::AuthenticatorTransport::USB);
- std::vector<uint8_t> kCredentialId{0, 0, 0};
auto descriptor = webauth::mojom::PublicKeyCredentialDescriptor::New(
- webauth::mojom::PublicKeyCredentialType::PUBLIC_KEY, kCredentialId,
+ webauth::mojom::PublicKeyCredentialType::PUBLIC_KEY,
+ std::vector<uint8_t>(
+ std::begin(device::test_data::kTestGetAssertionCredentialId),
+ std::end(device::test_data::kTestGetAssertionCredentialId)),
transports);
credentials.push_back(std::move(descriptor));
std::vector<uint8_t> kTestChallenge{0, 0, 0};
auto mojo_options = webauth::mojom::PublicKeyCredentialRequestOptions::New(
- kTestChallenge, base::TimeDelta::FromSeconds(30), "example.com",
- std::move(credentials), base::nullopt);
+ kTestChallenge, base::TimeDelta::FromSeconds(30), "acme.com",
+ std::move(credentials),
+ webauth::mojom::UserVerificationRequirement::PREFERRED, base::nullopt);
return mojo_options;
}
- GURL GetHttpsURL(const std::string& hostname,
- const std::string& relative_url) {
- return https_server_.GetURL(hostname, relative_url);
- }
+ void WaitForConnectionError() {
+ ASSERT_TRUE(authenticator_ptr_);
+ ASSERT_TRUE(authenticator_ptr_.is_bound());
+ if (authenticator_ptr_.encountered_error())
+ return;
- AuthenticatorPtr ConnectToAuthenticatorWithTestConnector() {
- // Set up service_manager::Connector for tests.
- auto fake_hid_manager = std::make_unique<device::FakeHidManager>();
- service_manager::mojom::ConnectorRequest request;
- auto connector = service_manager::Connector::Create(&request);
- service_manager::Connector::TestApi test_api(connector.get());
- test_api.OverrideBinderForTesting(
- service_manager::Identity(device::mojom::kServiceName),
- device::mojom::HidManager::Name_,
- base::BindRepeating(&device::FakeHidManager::AddBinding,
- base::Unretained(fake_hid_manager.get())));
-
- authenticator_impl_.reset(new content::AuthenticatorImpl(
- shell()->web_contents()->GetMainFrame(), connector.get(),
- std::make_unique<base::OneShotTimer>()));
- AuthenticatorPtr authenticator;
- authenticator_impl_->Bind(mojo::MakeRequest(&authenticator));
- return authenticator;
+ base::RunLoop run_loop;
+ authenticator_ptr_.set_connection_error_handler(run_loop.QuitClosure());
+ run_loop.Run();
}
+ AuthenticatorPtr& authenticator() { return authenticator_ptr_; }
+
private:
- base::test::ScopedFeatureList scoped_feature_list_;
- net::EmbeddedTestServer https_server_;
- std::unique_ptr<content::AuthenticatorImpl> authenticator_impl_;
+ AuthenticatorPtr authenticator_ptr_;
- DISALLOW_COPY_AND_ASSIGN(WebAuthBrowserTest);
+ DISALLOW_COPY_AND_ASSIGN(WebAuthLocalClientBrowserTest);
};
-class MockCreateCallback {
- public:
- MockCreateCallback() = default;
- MOCK_METHOD0_T(Run, void());
+// Tests that no crash occurs when the implementation is destroyed with a
+// pending navigator.credentials.create({publicKey: ...}) call.
+IN_PROC_BROWSER_TEST_F(WebAuthLocalClientBrowserTest,
+ CreatePublicKeyCredentialThenNavigateAway) {
+ auto* fake_hid_discovery = discovery_factory()->ForgeNextHidDiscovery();
+ TestCreateCallbackReceiver create_callback_receiver;
+ authenticator()->MakeCredential(BuildBasicCreateOptions(),
+ create_callback_receiver.callback());
+
+ fake_hid_discovery->WaitForCallToStartAndSimulateSuccess();
+ NavigateToURL(shell(), GetHttpsURL("www.acme.com", "/title2.html"));
+ WaitForConnectionError();
+
+ // The next active document should be able to successfully call
+ // navigator.credentials.create({publicKey: ...}) again.
+ ConnectToAuthenticator();
+ fake_hid_discovery = discovery_factory()->ForgeNextHidDiscovery();
+ authenticator()->MakeCredential(BuildBasicCreateOptions(),
+ create_callback_receiver.callback());
+ fake_hid_discovery->WaitForCallToStartAndSimulateSuccess();
+}
- using MakeCredentialCallback =
- base::OnceCallback<void(AuthenticatorStatus,
- MakeCredentialAuthenticatorResponsePtr)>;
+// Tests that no crash occurs when the implementation is destroyed with a
+// pending navigator.credentials.get({publicKey: ...}) call.
+IN_PROC_BROWSER_TEST_F(WebAuthLocalClientBrowserTest,
+ GetPublicKeyCredentialThenNavigateAway) {
+ auto* fake_hid_discovery = discovery_factory()->ForgeNextHidDiscovery();
+ TestGetCallbackReceiver get_callback_receiver;
+ authenticator()->GetAssertion(BuildBasicGetOptions(),
+ get_callback_receiver.callback());
+
+ fake_hid_discovery->WaitForCallToStartAndSimulateSuccess();
+ NavigateToURL(shell(), GetHttpsURL("www.acme.com", "/title2.html"));
+ WaitForConnectionError();
+
+ // The next active document should be able to successfully call
+ // navigator.credentials.get({publicKey: ...}) again.
+ ConnectToAuthenticator();
+ fake_hid_discovery = discovery_factory()->ForgeNextHidDiscovery();
+ authenticator()->GetAssertion(BuildBasicGetOptions(),
+ get_callback_receiver.callback());
+ fake_hid_discovery->WaitForCallToStartAndSimulateSuccess();
+}
- void RunWrapper(AuthenticatorStatus unused,
- MakeCredentialAuthenticatorResponsePtr unused2) {
- Run();
- }
+// Tests that the webauth::mojom::Authenticator connection is not closed on a
+// cancelled navigation.
+IN_PROC_BROWSER_TEST_F(WebAuthLocalClientBrowserTest,
+ CreatePublicKeyCredentialAfterCancelledNavigation) {
+ ScopedNavigationCancellingThrottleInstaller navigation_canceller(
+ shell()->web_contents());
- MakeCredentialCallback Get() {
- return base::BindOnce(&MockCreateCallback::RunWrapper,
- base::Unretained(this));
- }
+ NavigateToURL(shell(), GetHttpsURL("www.acme.com", "/title2.html"));
+
+ auto* fake_hid_discovery = discovery_factory()->ForgeNextHidDiscovery();
+ TestCreateCallbackReceiver create_callback_receiver;
+ authenticator()->MakeCredential(BuildBasicCreateOptions(),
+ create_callback_receiver.callback());
+
+ fake_hid_discovery->WaitForCallToStartAndSimulateSuccess();
+}
+
+// Tests that a navigator.credentials.create({publicKey: ...}) issued at the
+// moment just before a navigation commits is not serviced.
+IN_PROC_BROWSER_TEST_F(WebAuthLocalClientBrowserTest,
+ CreatePublicKeyCredentialRacingWithNavigation) {
+ TestCreateCallbackReceiver create_callback_receiver;
+ auto request_options = BuildBasicCreateOptions();
+
+ ClosureExecutorBeforeNavigationCommit executor(
+ shell()->web_contents(), base::BindLambdaForTesting([&]() {
+ authenticator()->MakeCredential(std::move(request_options),
+ create_callback_receiver.callback());
+ }));
+
+ auto* fake_hid_discovery = discovery_factory()->ForgeNextHidDiscovery();
+ NavigateToURL(shell(), GetHttpsURL("www.acme.com", "/title2.html"));
+ WaitForConnectionError();
+
+ // Normally, when the request is serviced, the implementation retrieves the
+ // factory as one of the first steps. Here, the request should not have been
+ // serviced at all, so the fake request should still be pending on the fake
+ // factory.
+ auto hid_discovery = ::device::FidoDiscovery::Create(
+ ::device::FidoTransportProtocol::kUsbHumanInterfaceDevice, nullptr);
+ ASSERT_TRUE(!!hid_discovery);
+
+ // The next active document should be able to successfully call
+ // navigator.credentials.create({publicKey: ...}) again.
+ ConnectToAuthenticator();
+ fake_hid_discovery = discovery_factory()->ForgeNextHidDiscovery();
+ authenticator()->MakeCredential(BuildBasicCreateOptions(),
+ create_callback_receiver.callback());
+ fake_hid_discovery->WaitForCallToStartAndSimulateSuccess();
+}
+
+// Regression test for https://crbug.com/818219.
+IN_PROC_BROWSER_TEST_F(WebAuthLocalClientBrowserTest,
+ CreatePublicKeyCredentialTwiceInARow) {
+ TestCreateCallbackReceiver callback_receiver_1;
+ TestCreateCallbackReceiver callback_receiver_2;
+ authenticator()->MakeCredential(BuildBasicCreateOptions(),
+ callback_receiver_1.callback());
+ authenticator()->MakeCredential(BuildBasicCreateOptions(),
+ callback_receiver_2.callback());
+ callback_receiver_2.WaitForCallback();
+
+ EXPECT_EQ(AuthenticatorStatus::PENDING_REQUEST, callback_receiver_2.status());
+ EXPECT_FALSE(callback_receiver_1.was_called());
+}
+
+// Regression test for https://crbug.com/818219.
+IN_PROC_BROWSER_TEST_F(WebAuthLocalClientBrowserTest,
+ GetPublicKeyCredentialTwiceInARow) {
+ TestGetCallbackReceiver callback_receiver_1;
+ TestGetCallbackReceiver callback_receiver_2;
+ authenticator()->GetAssertion(BuildBasicGetOptions(),
+ callback_receiver_1.callback());
+ authenticator()->GetAssertion(BuildBasicGetOptions(),
+ callback_receiver_2.callback());
+ callback_receiver_2.WaitForCallback();
+
+ EXPECT_EQ(AuthenticatorStatus::PENDING_REQUEST, callback_receiver_2.status());
+ EXPECT_FALSE(callback_receiver_1.was_called());
+}
+
+IN_PROC_BROWSER_TEST_F(WebAuthLocalClientBrowserTest,
+ CreatePublicKeyCredentialWhileRequestIsPending) {
+ auto* fake_hid_discovery = discovery_factory()->ForgeNextHidDiscovery();
+ TestCreateCallbackReceiver callback_receiver_1;
+ TestCreateCallbackReceiver callback_receiver_2;
+ authenticator()->MakeCredential(BuildBasicCreateOptions(),
+ callback_receiver_1.callback());
+ fake_hid_discovery->WaitForCallToStartAndSimulateSuccess();
+
+ authenticator()->MakeCredential(BuildBasicCreateOptions(),
+ callback_receiver_2.callback());
+ callback_receiver_2.WaitForCallback();
+
+ EXPECT_EQ(AuthenticatorStatus::PENDING_REQUEST, callback_receiver_2.status());
+ EXPECT_FALSE(callback_receiver_1.was_called());
+}
+
+IN_PROC_BROWSER_TEST_F(WebAuthLocalClientBrowserTest,
+ GetPublicKeyCredentialWhileRequestIsPending) {
+ auto* fake_hid_discovery = discovery_factory()->ForgeNextHidDiscovery();
+ TestGetCallbackReceiver callback_receiver_1;
+ TestGetCallbackReceiver callback_receiver_2;
+ authenticator()->GetAssertion(BuildBasicGetOptions(),
+ callback_receiver_1.callback());
+ fake_hid_discovery->WaitForCallToStartAndSimulateSuccess();
+
+ authenticator()->GetAssertion(BuildBasicGetOptions(),
+ callback_receiver_2.callback());
+ callback_receiver_2.WaitForCallback();
+
+ EXPECT_EQ(AuthenticatorStatus::PENDING_REQUEST, callback_receiver_2.status());
+ EXPECT_FALSE(callback_receiver_1.was_called());
+}
+
+// WebAuthJavascriptClientBrowserTest -----------------------------------------
+
+// Browser test fixture where the webauth::mojom::Authenticator interface is
+// normally accessed from Javascript in the renderer process.
+class WebAuthJavascriptClientBrowserTest : public WebAuthBrowserTestBase {
+ public:
+ WebAuthJavascriptClientBrowserTest() = default;
+ ~WebAuthJavascriptClientBrowserTest() override = default;
private:
- DISALLOW_COPY_AND_ASSIGN(MockCreateCallback);
+ base::test::ScopedFeatureList scoped_feature_list_;
+
+ DISALLOW_COPY_AND_ASSIGN(WebAuthJavascriptClientBrowserTest);
};
-class MockGetCallback {
- public:
- MockGetCallback() = default;
- MOCK_METHOD0_T(Run, void());
+// Tests that when navigator.credentials.create() is called with user
+// verification required we get a NotSupportedError.
+IN_PROC_BROWSER_TEST_F(WebAuthJavascriptClientBrowserTest,
+ CreatePublicKeyCredentialWithUserVerification) {
+ CreateParameters parameters;
+ parameters.user_verification = kRequiredVerification;
+ std::string result;
+ ASSERT_TRUE(content::ExecuteScriptAndExtractString(
+ shell()->web_contents()->GetMainFrame(),
+ BuildCreateCallWithParameters(parameters), &result));
+ ASSERT_EQ(kAuthenticatorCriteriaErrorMessage, result);
+}
- using GetAssertionCallback =
- base::OnceCallback<void(AuthenticatorStatus,
- GetAssertionAuthenticatorResponsePtr)>;
+// Tests that when navigator.credentials.create() is called with resident key
+// required, we get a NotSupportedError.
+IN_PROC_BROWSER_TEST_F(WebAuthJavascriptClientBrowserTest,
+ CreatePublicKeyCredentialWithResidentKeyRequired) {
+ CreateParameters parameters;
+ parameters.require_resident_key = true;
+ std::string result;
+ ASSERT_TRUE(content::ExecuteScriptAndExtractString(
+ shell()->web_contents()->GetMainFrame(),
+ BuildCreateCallWithParameters(parameters), &result));
+
+ ASSERT_EQ(kAuthenticatorCriteriaErrorMessage, result);
+}
- void RunWrapper(AuthenticatorStatus unused,
- GetAssertionAuthenticatorResponsePtr unused2) {
- Run();
- }
+// Tests that when navigator.credentials.create() is called with an invalid
+// relying party id, we get a SecurityError.
+IN_PROC_BROWSER_TEST_F(WebAuthJavascriptClientBrowserTest,
+ CreatePublicKeyCredentialInvalidRp) {
+ CreateParameters parameters;
+ parameters.rp_id = "localhost";
+ std::string result;
+ ASSERT_TRUE(content::ExecuteScriptAndExtractString(
+ shell()->web_contents()->GetMainFrame(),
+ BuildCreateCallWithParameters(parameters), &result));
+
+ ASSERT_EQ(kRelyingPartySecurityErrorMessage,
+ result.substr(0, strlen(kRelyingPartySecurityErrorMessage)));
+}
+
+// Tests that when navigator.credentials.create() is called with an
+// unsupported algorithm, we get a NotSupportedError.
+IN_PROC_BROWSER_TEST_F(WebAuthJavascriptClientBrowserTest,
+ CreatePublicKeyCredentialAlgorithmNotSupported) {
+ CreateParameters parameters;
+ parameters.algorithm_identifier = "123";
+ std::string result;
+ ASSERT_TRUE(content::ExecuteScriptAndExtractString(
+ shell()->web_contents()->GetMainFrame(),
+ BuildCreateCallWithParameters(parameters), &result));
+
+ ASSERT_EQ(kAlgorithmUnsupportedErrorMessage, result);
+}
+
+// Tests that when navigator.credentials.create() is called with a
+// platform authenticator requested, we get a NotSupportedError.
+IN_PROC_BROWSER_TEST_F(WebAuthJavascriptClientBrowserTest,
+ CreatePublicKeyCredentialPlatformAuthenticator) {
+ CreateParameters parameters;
+ parameters.authenticator_attachment = kPlatform;
+ std::string result;
+ ASSERT_TRUE(content::ExecuteScriptAndExtractString(
+ shell()->web_contents()->GetMainFrame(),
+ BuildCreateCallWithParameters(parameters), &result));
+
+ ASSERT_EQ(kAuthenticatorCriteriaErrorMessage, result);
+}
+
+// Tests that when navigator.credentials.get() is called with user verification
+// required, we get a NotSupportedError.
+IN_PROC_BROWSER_TEST_F(WebAuthJavascriptClientBrowserTest,
+ GetPublicKeyCredentialUserVerification) {
+ GetParameters parameters;
+ parameters.user_verification = "required";
+ std::string result;
+ ASSERT_TRUE(content::ExecuteScriptAndExtractString(
+ shell()->web_contents()->GetMainFrame(),
+ BuildGetCallWithParameters(parameters), &result));
+ ASSERT_EQ(kUserVerificationErrorMessage, result);
+}
+
+// Tests that when navigator.credentials.get() is called with an empty
+// allowCredentials list, we get a NotSupportedError.
+IN_PROC_BROWSER_TEST_F(WebAuthJavascriptClientBrowserTest,
+ GetPublicKeyCredentialEmptyAllowCredentialsList) {
+ GetParameters parameters;
+ parameters.allow_credentials = "";
+ std::string result;
+ ASSERT_TRUE(content::ExecuteScriptAndExtractString(
+ shell()->web_contents()->GetMainFrame(),
+ BuildGetCallWithParameters(parameters), &result));
+ ASSERT_EQ(kEmptyAllowCredentialsErrorMessage, result);
+}
- GetAssertionCallback Get() {
- return base::BindOnce(&MockGetCallback::RunWrapper, base::Unretained(this));
+// WebAuthBrowserBleDisabledTest
+// ----------------------------------------------
+
+// A test fixture that does not enable BLE discovery.
+class WebAuthBrowserBleDisabledTest : public WebAuthLocalClientBrowserTest {
+ public:
+ WebAuthBrowserBleDisabledTest() = default;
+
+ protected:
+ std::vector<base::Feature> GetFeaturesToEnable() override {
+ return {features::kWebAuth};
}
private:
- DISALLOW_COPY_AND_ASSIGN(MockGetCallback);
+ base::test::ScopedFeatureList scoped_feature_list_;
+ DISALLOW_COPY_AND_ASSIGN(WebAuthBrowserBleDisabledTest);
};
-// Tests.
+// Tests that the BLE discovery does not start when the WebAuthnBle feature
+// flag is disabled.
+IN_PROC_BROWSER_TEST_F(WebAuthBrowserBleDisabledTest, CheckBleDisabled) {
+ auto* fake_hid_discovery = discovery_factory()->ForgeNextHidDiscovery();
+ auto* fake_ble_discovery = discovery_factory()->ForgeNextBleDiscovery();
+
+ // Do something that will start discoveries.
+ TestCreateCallbackReceiver create_callback_receiver;
+ authenticator()->MakeCredential(BuildBasicCreateOptions(),
+ create_callback_receiver.callback());
+
+ fake_hid_discovery->WaitForCallToStart();
+ EXPECT_TRUE(fake_hid_discovery->is_start_requested());
+ EXPECT_FALSE(fake_ble_discovery->is_start_requested());
+}
-// Tests that no crash occurs when navigating away during a pending
-// create(publicKey) request.
-IN_PROC_BROWSER_TEST_F(WebAuthBrowserTest,
- CreatePublicKeyCredentialNavigateAway) {
- const GURL a_url1 = GetHttpsURL("www.example.com", "/title1.html");
- const GURL b_url1 = GetHttpsURL("www.test.com", "/title1.html");
+// WebAuthBrowserCtapTest ----------------------------------------------
- NavigateToURL(shell(), a_url1);
+// A test fixture that enables CTAP only flag.
+class WebAuthBrowserCtapTest : public WebAuthLocalClientBrowserTest {
+ public:
+ WebAuthBrowserCtapTest() = default;
- AuthenticatorPtr authenticator = ConnectToAuthenticatorWithTestConnector();
+ protected:
+ std::vector<base::Feature> GetFeaturesToEnable() override {
+ return {features::kWebAuth, features::kWebAuthCtap2};
+ }
- MockCreateCallback create_callback;
- EXPECT_CALL(create_callback, Run()).Times(0);
- authenticator->MakeCredential(BuildBasicCreateOptions(),
- create_callback.Get());
+ private:
+ base::test::ScopedFeatureList scoped_feature_list_;
+ DISALLOW_COPY_AND_ASSIGN(WebAuthBrowserCtapTest);
+};
- ASSERT_NO_FATAL_FAILURE(NavigateToURL(shell(), b_url1));
+// TODO(hongjunchoi): Implement VirtualCtap2Device to replace mocking.
+// See: https://crbugs.com/829413
+IN_PROC_BROWSER_TEST_F(WebAuthBrowserCtapTest, TestCtapMakeCredential) {
+ auto* fake_hid_discovery = discovery_factory()->ForgeNextHidDiscovery();
+
+ TestCreateCallbackReceiver create_callback_receiver;
+ authenticator()->MakeCredential(BuildBasicCreateOptions(),
+ create_callback_receiver.callback());
+
+ fake_hid_discovery->WaitForCallToStartAndSimulateSuccess();
+ auto device = std::make_unique<device::MockFidoDevice>();
+ EXPECT_CALL(*device, GetId()).WillRepeatedly(testing::Return("device0"));
+ device->ExpectCtap2CommandAndRespondWith(
+ device::CtapRequestCommand::kAuthenticatorGetInfo,
+ device::test_data::kTestAuthenticatorGetInfoResponse);
+ device->ExpectCtap2CommandAndRespondWith(
+ device::CtapRequestCommand::kAuthenticatorMakeCredential,
+ device::test_data::kTestMakeCredentialResponse);
+
+ fake_hid_discovery->AddDevice(std::move(device));
+
+ create_callback_receiver.WaitForCallback();
+ EXPECT_EQ(AuthenticatorStatus::SUCCESS, create_callback_receiver.status());
}
-// Tests that no crash occurs when navigating away during a pending
-// get(publicKey) request.
-IN_PROC_BROWSER_TEST_F(WebAuthBrowserTest, GetPublicKeyCredentialNavigateAway) {
- const GURL a_url1 = GetHttpsURL("www.example.com", "/title1.html");
- const GURL b_url1 = GetHttpsURL("www.test.com", "/title1.html");
+IN_PROC_BROWSER_TEST_F(WebAuthBrowserCtapTest, TestCtapGetAssertion) {
+ auto* fake_hid_discovery = discovery_factory()->ForgeNextHidDiscovery();
- NavigateToURL(shell(), a_url1);
+ TestGetCallbackReceiver get_callback_receiver;
+ auto get_assertion_request_params = BuildBasicGetOptions();
+ authenticator()->GetAssertion(std::move(get_assertion_request_params),
+ get_callback_receiver.callback());
- AuthenticatorPtr authenticator = ConnectToAuthenticatorWithTestConnector();
+ fake_hid_discovery->WaitForCallToStartAndSimulateSuccess();
+ auto device = std::make_unique<device::MockFidoDevice>();
+ EXPECT_CALL(*device, GetId()).WillRepeatedly(testing::Return("device0"));
+ device->ExpectCtap2CommandAndRespondWith(
+ device::CtapRequestCommand::kAuthenticatorGetInfo,
+ device::test_data::kTestAuthenticatorGetInfoResponse);
+ device->ExpectCtap2CommandAndRespondWith(
+ device::CtapRequestCommand::kAuthenticatorGetAssertion,
+ device::test_data::kTestGetAssertionResponse);
- MockGetCallback get_callback;
- EXPECT_CALL(get_callback, Run()).Times(0);
- authenticator->GetAssertion(BuildBasicGetOptions(), get_callback.Get());
+ fake_hid_discovery->AddDevice(std::move(device));
- ASSERT_NO_FATAL_FAILURE(NavigateToURL(shell(), b_url1));
+ get_callback_receiver.WaitForCallback();
+ EXPECT_EQ(AuthenticatorStatus::SUCCESS, get_callback_receiver.status());
}
} // namespace content
diff --git a/chromium/content/browser/webrtc/webrtc_audio_debug_recordings_browsertest.cc b/chromium/content/browser/webrtc/webrtc_audio_debug_recordings_browsertest.cc
index b519009c895..09e55b0a0f0 100644
--- a/chromium/content/browser/webrtc/webrtc_audio_debug_recordings_browsertest.cc
+++ b/chromium/content/browser/webrtc/webrtc_audio_debug_recordings_browsertest.cc
@@ -104,11 +104,10 @@ class WebRtcAudioDebugRecordingsBrowserTest
~WebRtcAudioDebugRecordingsBrowserTest() override {}
};
-#if defined(OS_ANDROID) && defined(ADDRESS_SANITIZER)
+#if defined(OS_ANDROID)
// Renderer crashes under Android ASAN: https://crbug.com/408496.
-#define MAYBE_CallWithAudioDebugRecordings DISABLED_CallWithAudioDebugRecordings
-#elif defined(OS_ANDROID)
-// Renderer crashes on Android M. https://crbug.com/535728.
+// Renderer crashes under Android: https://crbug.com/820934.
+// Failures on Android M. https://crbug.com/535728.
#define MAYBE_CallWithAudioDebugRecordings DISABLED_CallWithAudioDebugRecordings
#else
#define MAYBE_CallWithAudioDebugRecordings CallWithAudioDebugRecordings
@@ -203,8 +202,9 @@ IN_PROC_BROWSER_TEST_F(WebRtcAudioDebugRecordingsBrowserTest,
// TODO(grunell): Add test for multiple dumps when re-use of
// MediaStreamAudioProcessor in AudioCapturer has been removed.
-#if defined(OS_ANDROID) && defined(ADDRESS_SANITIZER)
+#if defined(OS_ANDROID)
// Renderer crashes under Android ASAN: https://crbug.com/408496.
+// Renderer crashes under Android: https://crbug.com/820934.
#define MAYBE_CallWithAudioDebugRecordingsEnabledThenDisabled \
DISABLED_CallWithAudioDebugRecordingsEnabledThenDisabled
#else
@@ -252,12 +252,10 @@ IN_PROC_BROWSER_TEST_F(WebRtcAudioDebugRecordingsBrowserTest,
base::ThreadRestrictions::SetIOAllowed(prev_io_allowed);
}
-#if defined(OS_ANDROID) && defined(ADDRESS_SANITIZER)
+#if defined(OS_ANDROID)
// Renderer crashes under Android ASAN: https://crbug.com/408496.
-#define MAYBE_TwoCallsWithAudioDebugRecordings \
- DISABLED_TwoCallsWithAudioDebugRecordings
-#elif defined(OS_ANDROID)
-// Renderer crashes on Android M. https://crbug.com/535728.
+// Renderer crashes under Android: https://crbug.com/820934.
+// Failures on Android M. https://crbug.com/535728.
#define MAYBE_TwoCallsWithAudioDebugRecordings \
DISABLED_TwoCallsWithAudioDebugRecordings
#else
diff --git a/chromium/content/browser/webrtc/webrtc_browsertest.cc b/chromium/content/browser/webrtc/webrtc_browsertest.cc
index 7514b39c878..820322191dc 100644
--- a/chromium/content/browser/webrtc/webrtc_browsertest.cc
+++ b/chromium/content/browser/webrtc/webrtc_browsertest.cc
@@ -177,13 +177,7 @@ IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest,
// This test will modify the SDP offer to use no encryption, which should
// cause SetLocalDescription to fail.
-// Flaky on MAC: http://crbug/810321.
-#if defined(OS_MACOSX)
-#define MAYBE_NegotiateNonCryptoCall DISABLED_NegotiateNonCryptoCall
-#else
-#define MAYBE_NegotiateNonCryptoCall NegotiateNonCryptoCall
-#endif
-IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, MAYBE_NegotiateNonCryptoCall) {
+IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, NegotiateNonCryptoCall) {
MakeTypicalPeerConnectionCall("negotiateNonCryptoCall();");
}
diff --git a/chromium/content/browser/webrtc/webrtc_capture_from_element_browsertest.cc b/chromium/content/browser/webrtc/webrtc_capture_from_element_browsertest.cc
index f12dfb7d34c..d4d59b8c93a 100644
--- a/chromium/content/browser/webrtc/webrtc_capture_from_element_browsertest.cc
+++ b/chromium/content/browser/webrtc/webrtc_capture_from_element_browsertest.cc
@@ -10,7 +10,7 @@
#include "content/shell/common/shell_switches.h"
#include "media/base/media_switches.h"
#include "media/base/test_data_util.h"
-#include "media/mojo/features.h"
+#include "media/mojo/buildflags.h"
#if defined(OS_ANDROID)
#include "base/android/build_info.h"
diff --git a/chromium/content/browser/webrtc/webrtc_content_browsertest_base.cc b/chromium/content/browser/webrtc/webrtc_content_browsertest_base.cc
index afa6c43b58b..6c1cd8c7d72 100644
--- a/chromium/content/browser/webrtc/webrtc_content_browsertest_base.cc
+++ b/chromium/content/browser/webrtc/webrtc_content_browsertest_base.cc
@@ -123,7 +123,7 @@ bool WebRtcContentBrowserTestBase::HasAudioOutputDevices() {
audio_system->HasOutputDevices(base::BindOnce(
[](base::Closure finished_callback, bool* result, bool received) {
*result = received;
- finished_callback.Run();
+ std::move(finished_callback).Run();
},
run_loop.QuitClosure(), &has_devices));
run_loop.Run();
diff --git a/chromium/content/browser/webrtc/webrtc_event_log_manager.cc b/chromium/content/browser/webrtc/webrtc_event_log_manager.cc
deleted file mode 100644
index 0b0c81f703a..00000000000
--- a/chromium/content/browser/webrtc/webrtc_event_log_manager.cc
+++ /dev/null
@@ -1,669 +0,0 @@
-// Copyright (c) 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/webrtc/webrtc_event_log_manager.h"
-
-#include "base/task_scheduler/post_task.h"
-#include "content/common/media/peer_connection_tracker_messages.h"
-#include "content/public/browser/browser_context.h"
-#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/render_process_host.h"
-
-namespace content {
-
-namespace {
-
-using BrowserContextId = WebRtcEventLogManager::BrowserContextId;
-
-const BrowserContextId kNullBrowserContextId =
- reinterpret_cast<BrowserContextId>(nullptr);
-
-class PeerConnectionTrackerProxyImpl
- : public WebRtcEventLogManager::PeerConnectionTrackerProxy {
- public:
- ~PeerConnectionTrackerProxyImpl() override = default;
-
- void SetWebRtcEventLoggingState(const WebRtcEventLogPeerConnectionKey& key,
- bool event_logging_enabled) override {
- BrowserThread::PostTask(
- BrowserThread::UI, FROM_HERE,
- base::BindOnce(
- &PeerConnectionTrackerProxyImpl::SetWebRtcEventLoggingStateInternal,
- key, event_logging_enabled));
- }
-
- private:
- static void SetWebRtcEventLoggingStateInternal(
- WebRtcEventLogPeerConnectionKey key,
- bool event_logging_enabled) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- RenderProcessHost* host = RenderProcessHost::FromID(key.render_process_id);
- if (!host) {
- return; // The host has been asynchronously removed; not a problem.
- }
- if (event_logging_enabled) {
- host->Send(new PeerConnectionTracker_StartEventLogOutput(key.lid));
- } else {
- host->Send(new PeerConnectionTracker_StopEventLog(key.lid));
- }
- }
-};
-
-const BrowserContext* GetBrowserContext(int render_process_id) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- RenderProcessHost* const host = RenderProcessHost::FromID(render_process_id);
- return host ? host->GetBrowserContext() : nullptr;
-}
-
-} // namespace
-
-const size_t kWebRtcEventLogManagerUnlimitedFileSize = 0;
-
-WebRtcEventLogManager* WebRtcEventLogManager::g_webrtc_event_log_manager =
- nullptr;
-
-BrowserContextId WebRtcEventLogManager::GetBrowserContextId(
- const BrowserContext* browser_context) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- return reinterpret_cast<BrowserContextId>(browser_context);
-}
-
-BrowserContextId WebRtcEventLogManager::GetBrowserContextId(
- int render_process_id) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- const BrowserContext* browser_context = GetBrowserContext(render_process_id);
- return GetBrowserContextId(browser_context);
-}
-
-WebRtcEventLogManager* WebRtcEventLogManager::CreateSingletonInstance() {
- DCHECK(!g_webrtc_event_log_manager);
- g_webrtc_event_log_manager = new WebRtcEventLogManager;
- return g_webrtc_event_log_manager;
-}
-
-WebRtcEventLogManager* WebRtcEventLogManager::GetInstance() {
- return g_webrtc_event_log_manager;
-}
-
-WebRtcEventLogManager::WebRtcEventLogManager()
- : WebRtcEventLogManager(base::CreateSequencedTaskRunnerWithTraits(
- {base::MayBlock(), base::TaskPriority::BACKGROUND,
- base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})) {}
-
-WebRtcEventLogManager::WebRtcEventLogManager(
- const scoped_refptr<base::SequencedTaskRunner>& task_runner)
- : local_logs_observer_(nullptr),
- remote_logs_observer_(nullptr),
- local_logs_manager_(this),
- remote_logs_manager_(this),
- pc_tracker_proxy_(new PeerConnectionTrackerProxyImpl),
- task_runner_(task_runner) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DCHECK(!g_webrtc_event_log_manager);
- g_webrtc_event_log_manager = this;
-}
-
-WebRtcEventLogManager::~WebRtcEventLogManager() {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- for (RenderProcessHost* host : observed_render_process_hosts_) {
- host->RemoveObserver(this);
- }
-
- DCHECK(g_webrtc_event_log_manager);
- g_webrtc_event_log_manager = nullptr;
-}
-
-void WebRtcEventLogManager::EnableForBrowserContext(
- const BrowserContext* browser_context,
- base::OnceClosure reply) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DCHECK(browser_context);
- CHECK(!browser_context->IsOffTheRecord());
-
- // The object outlives the task queue - base::Unretained(this) is safe.
- task_runner_->PostTask(
- FROM_HERE,
- base::BindOnce(&WebRtcEventLogManager::EnableForBrowserContextInternal,
- base::Unretained(this),
- GetBrowserContextId(browser_context),
- browser_context->GetPath(), std::move(reply)));
-}
-
-void WebRtcEventLogManager::DisableForBrowserContext(
- BrowserContextId browser_context_id,
- base::OnceClosure reply) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DCHECK_NE(browser_context_id, kNullBrowserContextId);
-
- // The object outlives the task queue - base::Unretained(this) is safe.
- task_runner_->PostTask(
- FROM_HERE,
- base::BindOnce(&WebRtcEventLogManager::DisableForBrowserContextInternal,
- base::Unretained(this), browser_context_id,
- std::move(reply)));
-}
-
-void WebRtcEventLogManager::PeerConnectionAdded(
- int render_process_id,
- int lid,
- base::OnceCallback<void(bool)> reply) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- RenderProcessHost* rph = RenderProcessHost::FromID(render_process_id);
- if (!rph) {
- // RPH died before processing of this notification.
- MaybeReply(std::move(reply), false);
- return;
- }
-
- auto it = observed_render_process_hosts_.find(rph);
- if (it == observed_render_process_hosts_.end()) {
- // This is the first PeerConnection which we see that's associated
- // with this RPH.
- rph->AddObserver(this);
- observed_render_process_hosts_.insert(rph);
- }
-
- const auto browser_context_id = GetBrowserContextId(rph->GetBrowserContext());
- DCHECK_NE(browser_context_id, kNullBrowserContextId);
-
- // The object outlives the task queue - base::Unretained(this) is safe.
- task_runner_->PostTask(
- FROM_HERE,
- base::BindOnce(
- &WebRtcEventLogManager::PeerConnectionAddedInternal,
- base::Unretained(this),
- PeerConnectionKey(render_process_id, lid, browser_context_id),
- std::move(reply)));
-}
-
-void WebRtcEventLogManager::PeerConnectionRemoved(
- int render_process_id,
- int lid,
- base::OnceCallback<void(bool)> reply) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- const auto browser_context_id = GetBrowserContextId(render_process_id);
- if (browser_context_id == kNullBrowserContextId) {
- // RPH died before processing of this notification. This is handled by
- // RenderProcessExited() / RenderProcessHostDestroyed.
- MaybeReply(std::move(reply), false);
- return;
- }
-
- // The object outlives the task queue - base::Unretained(this) is safe.
- task_runner_->PostTask(
- FROM_HERE,
- base::BindOnce(
- &WebRtcEventLogManager::PeerConnectionRemovedInternal,
- base::Unretained(this),
- PeerConnectionKey(render_process_id, lid, browser_context_id),
- std::move(reply)));
-}
-
-void WebRtcEventLogManager::PeerConnectionStopped(
- int render_process_id,
- int lid,
- base::OnceCallback<void(bool)> reply) {
- return PeerConnectionRemoved(render_process_id, lid, std::move(reply));
-}
-
-void WebRtcEventLogManager::EnableLocalLogging(
- const base::FilePath& base_path,
- size_t max_file_size_bytes,
- base::OnceCallback<void(bool)> reply) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DCHECK(!base_path.empty());
- // The object outlives the task queue - base::Unretained(this) is safe.
- task_runner_->PostTask(
- FROM_HERE,
- base::BindOnce(&WebRtcEventLogManager::EnableLocalLoggingInternal,
- base::Unretained(this), base_path, max_file_size_bytes,
- std::move(reply)));
-}
-
-void WebRtcEventLogManager::DisableLocalLogging(
- base::OnceCallback<void(bool)> reply) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- // The object outlives the task queue - base::Unretained(this) is safe.
- task_runner_->PostTask(
- FROM_HERE,
- base::BindOnce(&WebRtcEventLogManager::DisableLocalLoggingInternal,
- base::Unretained(this), std::move(reply)));
-}
-
-void WebRtcEventLogManager::StartRemoteLogging(
- int render_process_id,
- int lid,
- size_t max_file_size_bytes,
- const std::string& metadata,
- base::OnceCallback<void(bool)> reply) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- const BrowserContext* browser_context = GetBrowserContext(render_process_id);
- if (!browser_context || browser_context->IsOffTheRecord()) {
- // RPH died before processing of this notification, or is incognito.
- MaybeReply(std::move(reply), false);
- return;
- }
-
- const auto browser_context_id = GetBrowserContextId(browser_context);
- DCHECK_NE(browser_context_id, kNullBrowserContextId);
-
- // The object outlives the task queue - base::Unretained(this) is safe.
- task_runner_->PostTask(
- FROM_HERE,
- base::BindOnce(
- &WebRtcEventLogManager::StartRemoteLoggingInternal,
- base::Unretained(this),
- PeerConnectionKey(render_process_id, lid, browser_context_id),
- browser_context->GetPath(), max_file_size_bytes, metadata,
- std::move(reply)));
-}
-
-void WebRtcEventLogManager::OnWebRtcEventLogWrite(
- int render_process_id,
- int lid,
- const std::string& message,
- base::OnceCallback<void(std::pair<bool, bool>)> reply) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- const BrowserContext* browser_context = GetBrowserContext(render_process_id);
- if (!browser_context) {
- // RPH died before processing of this notification.
- MaybeReply(std::move(reply), false, false);
- return;
- }
-
- const auto browser_context_id = GetBrowserContextId(browser_context);
- DCHECK_NE(browser_context_id, kNullBrowserContextId);
-
- const bool remote_logging_allowed = !browser_context->IsOffTheRecord();
-
- // The object outlives the task queue - base::Unretained(this) is safe.
- task_runner_->PostTask(
- FROM_HERE,
- base::BindOnce(
- &WebRtcEventLogManager::OnWebRtcEventLogWriteInternal,
- base::Unretained(this),
- PeerConnectionKey(render_process_id, lid, browser_context_id),
- remote_logging_allowed, message, std::move(reply)));
-}
-
-void WebRtcEventLogManager::SetLocalLogsObserver(
- WebRtcLocalEventLogsObserver* observer,
- base::OnceClosure reply) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- // The object outlives the task queue - base::Unretained(this) is safe.
- task_runner_->PostTask(
- FROM_HERE,
- base::BindOnce(&WebRtcEventLogManager::SetLocalLogsObserverInternal,
- base::Unretained(this), observer, std::move(reply)));
-}
-
-void WebRtcEventLogManager::SetRemoteLogsObserver(
- WebRtcRemoteEventLogsObserver* observer,
- base::OnceClosure reply) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- // The object outlives the task queue - base::Unretained(this) is safe.
- task_runner_->PostTask(
- FROM_HERE,
- base::BindOnce(&WebRtcEventLogManager::SetRemoteLogsObserverInternal,
- base::Unretained(this), observer, std::move(reply)));
-}
-
-scoped_refptr<base::SequencedTaskRunner>&
-WebRtcEventLogManager::GetTaskRunnerForTesting() {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- return task_runner_;
-}
-
-void WebRtcEventLogManager::RenderProcessExited(RenderProcessHost* host,
- base::TerminationStatus status,
- int exit_code) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- RenderProcessHostExitedDestroyed(host);
-}
-
-void WebRtcEventLogManager::RenderProcessHostDestroyed(
- RenderProcessHost* host) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- RenderProcessHostExitedDestroyed(host);
-}
-
-void WebRtcEventLogManager::RenderProcessHostExitedDestroyed(
- RenderProcessHost* host) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DCHECK(host);
-
- auto it = observed_render_process_hosts_.find(host);
- if (it == observed_render_process_hosts_.end()) {
- return; // We've never seen PeerConnections associated with this RPH.
- }
- host->RemoveObserver(this);
- observed_render_process_hosts_.erase(host);
-
- // The object outlives the task queue - base::Unretained(this) is safe.
- task_runner_->PostTask(
- FROM_HERE,
- base::BindOnce(&WebRtcEventLogManager::RenderProcessExitedInternal,
- base::Unretained(this), host->GetID()));
-}
-
-void WebRtcEventLogManager::OnLocalLogStarted(PeerConnectionKey peer_connection,
- const base::FilePath& file_path) {
- DCHECK(task_runner_->RunsTasksInCurrentSequence());
-
- OnLoggingTargetStarted(LoggingTarget::kLocalLogging, peer_connection);
-
- if (local_logs_observer_) {
- local_logs_observer_->OnLocalLogStarted(peer_connection, file_path);
- }
-}
-
-void WebRtcEventLogManager::OnLocalLogStopped(
- PeerConnectionKey peer_connection) {
- DCHECK(task_runner_->RunsTasksInCurrentSequence());
-
- OnLoggingTargetStopped(LoggingTarget::kLocalLogging, peer_connection);
-
- if (local_logs_observer_) {
- local_logs_observer_->OnLocalLogStopped(peer_connection);
- }
-}
-
-void WebRtcEventLogManager::OnRemoteLogStarted(
- PeerConnectionKey key,
- const base::FilePath& file_path) {
- DCHECK(task_runner_->RunsTasksInCurrentSequence());
- OnLoggingTargetStarted(LoggingTarget::kRemoteLogging, key);
- if (remote_logs_observer_) {
- remote_logs_observer_->OnRemoteLogStarted(key, file_path);
- }
-}
-
-void WebRtcEventLogManager::OnRemoteLogStopped(
- WebRtcEventLogPeerConnectionKey key) {
- DCHECK(task_runner_->RunsTasksInCurrentSequence());
- OnLoggingTargetStopped(LoggingTarget::kRemoteLogging, key);
- if (remote_logs_observer_) {
- remote_logs_observer_->OnRemoteLogStopped(key);
- }
-}
-
-void WebRtcEventLogManager::OnLoggingTargetStarted(LoggingTarget target,
- PeerConnectionKey key) {
- DCHECK(task_runner_->RunsTasksInCurrentSequence());
- auto it = peer_connections_with_event_logging_enabled_.find(key);
- if (it != peer_connections_with_event_logging_enabled_.end()) {
- DCHECK_EQ((it->second & target), 0u);
- it->second |= target;
- } else {
- // This is the first client for WebRTC event logging - let WebRTC know
- // that it should start informing us of events.
- peer_connections_with_event_logging_enabled_.emplace(key, target);
- pc_tracker_proxy_->SetWebRtcEventLoggingState(key, true);
- }
-}
-
-void WebRtcEventLogManager::OnLoggingTargetStopped(LoggingTarget target,
- PeerConnectionKey key) {
- DCHECK(task_runner_->RunsTasksInCurrentSequence());
-
- // Record that we're no longer performing this type of logging for this PC.
- auto it = peer_connections_with_event_logging_enabled_.find(key);
- CHECK(it != peer_connections_with_event_logging_enabled_.end());
- DCHECK_NE(it->second, 0u);
- it->second &= ~target;
-
- // If we're not doing any other type of logging for this peer connection,
- // it's time to stop receiving notifications for it from WebRTC.
- if (it->second == 0u) {
- peer_connections_with_event_logging_enabled_.erase(it);
- pc_tracker_proxy_->SetWebRtcEventLoggingState(key, false);
- }
-}
-
-void WebRtcEventLogManager::EnableForBrowserContextInternal(
- BrowserContextId browser_context_id,
- const base::FilePath& browser_context_dir,
- base::OnceClosure reply) {
- DCHECK(task_runner_->RunsTasksInCurrentSequence());
- DCHECK_NE(browser_context_id, kNullBrowserContextId);
-
- remote_logs_manager_.EnableForBrowserContext(browser_context_id,
- browser_context_dir);
-
- if (reply) {
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, std::move(reply));
- }
-}
-
-void WebRtcEventLogManager::DisableForBrowserContextInternal(
- BrowserContextId browser_context_id,
- base::OnceClosure reply) {
- DCHECK(task_runner_->RunsTasksInCurrentSequence());
-
- remote_logs_manager_.DisableForBrowserContext(browser_context_id);
-
- if (reply) {
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, std::move(reply));
- }
-}
-
-void WebRtcEventLogManager::PeerConnectionAddedInternal(
- PeerConnectionKey key,
- base::OnceCallback<void(bool)> reply) {
- DCHECK(task_runner_->RunsTasksInCurrentSequence());
-
- const bool local_result = local_logs_manager_.PeerConnectionAdded(key);
- const bool remote_result = remote_logs_manager_.PeerConnectionAdded(key);
- DCHECK_EQ(local_result, remote_result);
-
- if (reply) {
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
- base::BindOnce(std::move(reply), local_result));
- }
-}
-
-void WebRtcEventLogManager::PeerConnectionRemovedInternal(
- PeerConnectionKey key,
- base::OnceCallback<void(bool)> reply) {
- DCHECK(task_runner_->RunsTasksInCurrentSequence());
-
- const bool local_result = local_logs_manager_.PeerConnectionRemoved(key);
- const bool remote_result = remote_logs_manager_.PeerConnectionRemoved(key);
- DCHECK_EQ(local_result, remote_result);
-
- if (reply) {
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
- base::BindOnce(std::move(reply), local_result));
- }
-}
-
-void WebRtcEventLogManager::EnableLocalLoggingInternal(
- const base::FilePath& base_path,
- size_t max_file_size_bytes,
- base::OnceCallback<void(bool)> reply) {
- DCHECK(task_runner_->RunsTasksInCurrentSequence());
-
- const bool result =
- local_logs_manager_.EnableLogging(base_path, max_file_size_bytes);
-
- if (reply) {
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
- base::BindOnce(std::move(reply), result));
- }
-}
-
-void WebRtcEventLogManager::DisableLocalLoggingInternal(
- base::OnceCallback<void(bool)> reply) {
- DCHECK(task_runner_->RunsTasksInCurrentSequence());
-
- const bool result = local_logs_manager_.DisableLogging();
-
- if (reply) {
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
- base::BindOnce(std::move(reply), result));
- }
-}
-
-void WebRtcEventLogManager::StartRemoteLoggingInternal(
- PeerConnectionKey key,
- const base::FilePath& browser_context_dir,
- size_t max_file_size_bytes,
- const std::string& metadata,
- base::OnceCallback<void(bool)> reply) {
- DCHECK(task_runner_->RunsTasksInCurrentSequence());
-
- const bool result = remote_logs_manager_.StartRemoteLogging(
- key, browser_context_dir, max_file_size_bytes, metadata);
-
- if (reply) {
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
- base::BindOnce(std::move(reply), result));
- }
-}
-
-void WebRtcEventLogManager::OnWebRtcEventLogWriteInternal(
- PeerConnectionKey key,
- bool remote_logging_allowed,
- const std::string& message,
- base::OnceCallback<void(std::pair<bool, bool>)> reply) {
- DCHECK(task_runner_->RunsTasksInCurrentSequence());
-
- const bool local_result = local_logs_manager_.EventLogWrite(key, message);
- const bool remote_result =
- remote_logging_allowed ? remote_logs_manager_.EventLogWrite(key, message)
- : false;
-
- if (reply) {
- BrowserThread::PostTask(
- BrowserThread::UI, FROM_HERE,
- base::BindOnce(std::move(reply),
- std::make_pair(local_result, remote_result)));
- }
-}
-
-void WebRtcEventLogManager::RenderProcessExitedInternal(int render_process_id) {
- DCHECK(task_runner_->RunsTasksInCurrentSequence());
- local_logs_manager_.RenderProcessHostExitedDestroyed(render_process_id);
- remote_logs_manager_.RenderProcessHostExitedDestroyed(render_process_id);
-}
-
-void WebRtcEventLogManager::SetLocalLogsObserverInternal(
- WebRtcLocalEventLogsObserver* observer,
- base::OnceClosure reply) {
- DCHECK(task_runner_->RunsTasksInCurrentSequence());
-
- local_logs_observer_ = observer;
-
- if (reply) {
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, std::move(reply));
- }
-}
-
-void WebRtcEventLogManager::SetRemoteLogsObserverInternal(
- WebRtcRemoteEventLogsObserver* observer,
- base::OnceClosure reply) {
- DCHECK(task_runner_->RunsTasksInCurrentSequence());
-
- remote_logs_observer_ = observer;
-
- if (reply) {
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, std::move(reply));
- }
-}
-
-void WebRtcEventLogManager::MaybeReply(base::OnceClosure reply) {
- if (!reply) {
- return;
- }
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, std::move(reply));
-}
-
-void WebRtcEventLogManager::MaybeReply(base::OnceCallback<void(bool)> reply,
- bool value) {
- if (!reply) {
- return;
- }
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
- base::BindOnce(std::move(reply), value));
-}
-
-void WebRtcEventLogManager::MaybeReply(
- base::OnceCallback<void(std::pair<bool, bool>)> reply,
- bool first,
- bool second) {
- if (!reply) {
- return;
- }
- BrowserThread::PostTask(
- BrowserThread::UI, FROM_HERE,
- base::BindOnce(std::move(reply), std::make_pair(first, second)));
-}
-
-void WebRtcEventLogManager::SetClockForTesting(base::Clock* clock,
- base::OnceClosure reply) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- auto task = [](WebRtcEventLogManager* manager, base::Clock* clock,
- base::OnceClosure reply) {
- manager->local_logs_manager_.SetClockForTesting(clock);
- if (reply) {
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, std::move(reply));
- }
- };
-
- // The object outlives the task queue - base::Unretained(this) is safe.
- task_runner_->PostTask(FROM_HERE, base::BindOnce(task, base::Unretained(this),
- clock, std::move(reply)));
-}
-
-void WebRtcEventLogManager::SetPeerConnectionTrackerProxyForTesting(
- std::unique_ptr<PeerConnectionTrackerProxy> pc_tracker_proxy,
- base::OnceClosure reply) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- auto task = [](WebRtcEventLogManager* manager,
- std::unique_ptr<PeerConnectionTrackerProxy> pc_tracker_proxy,
- base::OnceClosure reply) {
- manager->pc_tracker_proxy_ = std::move(pc_tracker_proxy);
- if (reply) {
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, std::move(reply));
- }
- };
-
- // The object outlives the task queue - base::Unretained(this) is safe.
- task_runner_->PostTask(
- FROM_HERE, base::BindOnce(task, base::Unretained(this),
- std::move(pc_tracker_proxy), std::move(reply)));
-}
-
-void WebRtcEventLogManager::SetWebRtcEventLogUploaderFactoryForTesting(
- std::unique_ptr<WebRtcEventLogUploader::Factory> uploader_factory,
- base::OnceClosure reply) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- auto task =
- [](WebRtcEventLogManager* manager,
- std::unique_ptr<WebRtcEventLogUploader::Factory> uploader_factory,
- base::OnceClosure reply) {
- auto& remote_logs_manager = manager->remote_logs_manager_;
- remote_logs_manager.SetWebRtcEventLogUploaderFactoryForTesting(
- std::move(uploader_factory));
- if (reply) {
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
- std::move(reply));
- }
- };
-
- // The object outlives the task queue - base::Unretained(this) is safe.
- task_runner_->PostTask(
- FROM_HERE, base::BindOnce(task, base::Unretained(this),
- std::move(uploader_factory), std::move(reply)));
-}
-
-} // namespace content
diff --git a/chromium/content/browser/webrtc/webrtc_event_log_manager.h b/chromium/content/browser/webrtc/webrtc_event_log_manager.h
deleted file mode 100644
index 97318d8d237..00000000000
--- a/chromium/content/browser/webrtc/webrtc_event_log_manager.h
+++ /dev/null
@@ -1,366 +0,0 @@
-// Copyright (c) 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_WEBRTC_WEBRTC_EVENT_LOG_MANAGER_H_
-#define CONTENT_BROWSER_WEBRTC_WEBRTC_EVENT_LOG_MANAGER_H_
-
-#include <map>
-#include <memory>
-#include <type_traits>
-#include <utility>
-
-#include "base/callback.h"
-#include "base/containers/flat_set.h"
-#include "base/files/file_path.h"
-#include "base/memory/scoped_refptr.h"
-#include "base/sequenced_task_runner.h"
-#include "base/time/clock.h"
-#include "content/browser/webrtc/webrtc_event_log_manager_common.h"
-#include "content/browser/webrtc/webrtc_local_event_log_manager.h"
-#include "content/browser/webrtc/webrtc_remote_event_log_manager.h"
-#include "content/common/content_export.h"
-#include "content/public/browser/render_process_host_observer.h"
-
-namespace content {
-
-class BrowserContext;
-
-// This is a singleton class running in the browser UI thread (ownership of
-// the only instance lies in BrowserContext). It is in charge of writing WebRTC
-// event logs to temporary files, then uploading those files to remote servers,
-// as well as of writing the logs to files which were manually indicated by the
-// user from the WebRTCIntenals. (A log may simulatenously be written to both,
-// either, or none.)
-// This needs to be final, so that posting |base::Unretained(this)| to the
-// internal task runner would not be a problem during destruction.
-class CONTENT_EXPORT WebRtcEventLogManager final
- : public RenderProcessHostObserver,
- public WebRtcLocalEventLogsObserver,
- public WebRtcRemoteEventLogsObserver {
- public:
- using BrowserContextId = WebRtcEventLogPeerConnectionKey::BrowserContextId;
-
- // To turn WebRTC on and off, we go through PeerConnectionTrackerProxy. In
- // order to make this toggling easily testable, PeerConnectionTrackerProxyImpl
- // will send real messages to PeerConnectionTracker, whereas
- // PeerConnectionTrackerProxyForTesting will be a mock that just makes sure
- // the correct messages were attempted to be sent.
- class PeerConnectionTrackerProxy {
- public:
- virtual ~PeerConnectionTrackerProxy() = default;
- virtual void SetWebRtcEventLoggingState(
- const WebRtcEventLogPeerConnectionKey& key,
- bool event_logging_enabled) = 0;
- };
-
- // Translate a BrowserContext into an ID, allowing associating PeerConnections
- // with it while making sure that its methods would never be called outside
- // of the UI thread.
- static BrowserContextId GetBrowserContextId(
- const BrowserContext* browser_context);
-
- // Fetches the BrowserContext associated with the render process ID, then
- // returns its BrowserContextId. (If the render process has already died,
- // it would have no BrowserContext associated, so kNullBrowserContextId will
- // be returned.)
- static BrowserContextId GetBrowserContextId(int render_process_id);
-
- // Ensures that no previous instantiation of the class was performed, then
- // instantiates the class and returns the object. Subsequent calls to
- // GetInstance() will return this object.
- static WebRtcEventLogManager* CreateSingletonInstance();
-
- // Returns the object previously constructed using CreateSingletonInstance().
- // Can be null in tests.
- static WebRtcEventLogManager* GetInstance();
-
- ~WebRtcEventLogManager() override;
-
- // Enables WebRTC event logging for a given BrowserContext:
- // * Pending logs from previous sessions become eligible to be uploaded.
- // * New logs for active peer connections *may* be recorded. (This does *not*
- // start logging; it just makes it possible.)
- // This function would typically be called during a BrowserContext's
- // initialization.
- // This function must not be called for an off-the-records BrowserContext.
- // Local-logging is not associated with BrowserContexts, and is allowed even
- // if EnableForBrowserContext is not called. That is, even for incognito mode.
- void EnableForBrowserContext(const BrowserContext* browser_context,
- base::OnceClosure reply = base::OnceClosure());
-
- // Disables WebRTC event logging for a given BrowserContext. New remote-bound
- // WebRTC event logs will no longer be created for this BrowserContext.
- // This would typically be called when a BrowserContext is destroyed, so it
- // receives the ID instead of a pointer to the BrowserContext itself, to
- // ensure that it would not call any virtual functions during destruction.
- void DisableForBrowserContext(BrowserContextId browser_context_id,
- base::OnceClosure reply = base::OnceClosure());
-
- // Call this to let the manager know when a PeerConnection was created.
- // If a reply callback is given, it will be posted back to BrowserThread::UI,
- // with true if and only if the operation was successful (failure is only
- // possible if a peer connection with this exact key was previously added,
- // but not removed).
- void PeerConnectionAdded(
- int render_process_id,
- int lid, // Renderer-local PeerConnection ID.
- base::OnceCallback<void(bool)> reply = base::OnceCallback<void(bool)>());
-
- // Call this to let the manager know when a PeerConnection was closed.
- // If a reply callback is given, it will be posted back to BrowserThread::UI,
- // with true if and only if the operation was successful (failure is only
- // possible if a peer connection with this key was not previously added,
- // or if it has since already been removed).
- void PeerConnectionRemoved(
- int render_process_id,
- int lid, // Renderer-local PeerConnection ID.
- base::OnceCallback<void(bool)> reply = base::OnceCallback<void(bool)>());
-
- // Call this to let the manager know when a PeerConnection was stopped.
- // Closing of a peer connection is an irreversible action. Its distinction
- // from the removal event is that it may happen before the peer connection has
- // be garbage collected. From WebRtcEventLogManager's perspective, we treat
- // stopping a peer connection the same as we do its removal. Should a stopped
- // peer connection be later removed, the removal callback will assume the
- // value |false|.
- void PeerConnectionStopped(
- int render_process_id,
- int lid, // Renderer-local PeerConnection ID.
- base::OnceCallback<void(bool)> reply = base::OnceCallback<void(bool)>());
-
- // Enable local logging of RTC events.
- // Local logging is distinguished from remote logging, in that local logs are
- // kept in response to explicit user input, are saved to a specific location,
- // and are never removed by Chrome.
- // The file's actual path is derived from |base_path| by adding a timestamp,
- // the render process ID and the PeerConnection's local ID.
- // If a reply callback is given, it will be posted back to BrowserThread::UI,
- // with true if and only if local logging was *not* already on.
- // Note #1: An illegal file path, or one where we don't have the necessary
- // permissions, does not cause a |false| reply, since even when we have the
- // permissions, we're not guaranteed to keep them, and some files might be
- // legal while others aren't due to additional restrictions (number of files,
- // length of filename, etc.).
- // Note #2: If the number of currently active peer connections exceeds the
- // maximum number of local log files, there is no guarantee about which PCs
- // will get a local log file associated (specifically, we do *not* guarantee
- // it would be either the oldest or the newest).
- void EnableLocalLogging(
- const base::FilePath& base_path,
- size_t max_file_size_bytes = kDefaultMaxLocalLogFileSizeBytes,
- base::OnceCallback<void(bool)> reply = base::OnceCallback<void(bool)>());
-
- // Disable local logging of RTC events.
- // Any active local logs are stopped. Peer connections added after this call
- // will not get a local log associated with them.
- void DisableLocalLogging(
- base::OnceCallback<void(bool)> reply = base::OnceCallback<void(bool)>());
-
- // Start logging the peer connection's WebRTC events to a file, which will
- // later be uploaded to a remote server. If a reply is provided, it will be
- // posted back to BrowserThread::UI with the return value provided by
- // WebRtcRemoteEventLogManager::StartRemoteLogging - see the comment there
- // for more details.
- // One may attach an arbitrary binary string |metadata|, which would be
- // prepended to the WebRTC event log. Its length is counted towards the
- // max file size. (I.e., if the metadata is of length 4 and the max size
- // is 10, only 6 bytes are left available for the actual WebRTC event log.)
- void StartRemoteLogging(
- int render_process_id,
- int lid, // Renderer-local PeerConnection ID.
- size_t max_file_size_bytes,
- const std::string& metadata = "",
- base::OnceCallback<void(bool)> reply = base::OnceCallback<void(bool)>());
-
- // Called when a new log fragment is sent from the renderer. This will
- // potentially be written to a local WebRTC event log, a log destined for
- // upload, or both.
- // If a reply callback is given, it will be posted back to BrowserThread::UI
- // with a pair of bools, the first bool associated with local logging and the
- // second bool associated with remote-bound logging. Each bool assumes the
- // value true if and only if the message was written in its entirety into
- // a local/remote-bound log file.
- void OnWebRtcEventLogWrite(
- int render_process_id,
- int lid, // Renderer-local PeerConnection ID.
- const std::string& message,
- base::OnceCallback<void(std::pair<bool, bool>)> reply =
- base::OnceCallback<void(std::pair<bool, bool>)>());
-
- // Set (or unset) an observer that will be informed whenever a local log file
- // is started/stopped. The observer needs to be able to either run from
- // anywhere. If you need the code to run on specific runners or queues, have
- // the observer post them there.
- // If a reply callback is given, it will be posted back to BrowserThread::UI
- // after the observer has been set.
- void SetLocalLogsObserver(WebRtcLocalEventLogsObserver* observer,
- base::OnceClosure reply = base::OnceClosure());
-
- // Set (or unset) an observer that will be informed whenever a remote log file
- // is started/stopped. Note that this refers to writing these files to disk,
- // not for uploading them to the server.
- // The observer needs to be able to either run from anywhere. If you need the
- // code to run on specific runners or queues, have the observer post
- // them there.
- // If a reply callback is given, it will be posted back to BrowserThread::UI
- // after the observer has been set.
- void SetRemoteLogsObserver(WebRtcRemoteEventLogsObserver* observer,
- base::OnceClosure reply = base::OnceClosure());
-
- protected:
- friend class WebRtcEventLogManagerTest; // Unit tests inject a frozen clock.
- friend class WebRtcInternalsTest; // Unit tests inject a task runner.
-
- WebRtcEventLogManager();
- // This can be used by unit tests to ensure that they would run synchronously.
- explicit WebRtcEventLogManager(
- const scoped_refptr<base::SequencedTaskRunner>& task_runner);
-
- // This allows unit tests that do not wish to change the task runner to still
- // check when certain operations are finished.
- scoped_refptr<base::SequencedTaskRunner>& GetTaskRunnerForTesting();
-
- private:
- using PeerConnectionKey = WebRtcEventLogPeerConnectionKey;
-
- // This bitmap allows us to track for which clients (local/remote logging)
- // we have turned WebRTC event logging on for a given peer connection, so that
- // we may turn it off only when the last client no longer needs it.
- enum LoggingTarget : unsigned int {
- kLocalLogging = 1 << 0,
- kRemoteLogging = 1 << 1
- };
- using LoggingTargetBitmap = std::underlying_type<LoggingTarget>::type;
-
- static WebRtcEventLogManager* g_webrtc_event_log_manager;
-
- // RenderProcessHostObserver implementation.
- void RenderProcessExited(RenderProcessHost* host,
- base::TerminationStatus status,
- int exit_code) override;
- void RenderProcessHostDestroyed(RenderProcessHost* host) override;
-
- // RenderProcessExited() and RenderProcessHostDestroyed() treated similarly
- // by this function.
- void RenderProcessHostExitedDestroyed(RenderProcessHost* host);
-
- // WebRtcLocalEventLogsObserver implementation:
- void OnLocalLogStarted(PeerConnectionKey peer_connection,
- const base::FilePath& file_path) override;
- void OnLocalLogStopped(PeerConnectionKey peer_connection) override;
-
- // WebRtcRemoteEventLogsObserver implementation:
- void OnRemoteLogStarted(PeerConnectionKey key,
- const base::FilePath& file_path) override;
- void OnRemoteLogStopped(PeerConnectionKey key) override;
-
- void OnLoggingTargetStarted(LoggingTarget target, PeerConnectionKey key);
- void OnLoggingTargetStopped(LoggingTarget target, PeerConnectionKey key);
-
- void EnableForBrowserContextInternal(
- BrowserContextId browser_context_id,
- const base::FilePath& browser_context_dir,
- base::OnceClosure reply);
- void DisableForBrowserContextInternal(BrowserContextId browser_context_id,
- base::OnceClosure reply);
-
- void PeerConnectionAddedInternal(PeerConnectionKey key,
- base::OnceCallback<void(bool)> reply);
- void PeerConnectionRemovedInternal(PeerConnectionKey key,
- base::OnceCallback<void(bool)> reply);
-
- void EnableLocalLoggingInternal(const base::FilePath& base_path,
- size_t max_file_size_bytes,
- base::OnceCallback<void(bool)> reply);
- void DisableLocalLoggingInternal(base::OnceCallback<void(bool)> reply);
-
- void StartRemoteLoggingInternal(PeerConnectionKey key,
- const base::FilePath& browser_context_dir,
- size_t max_file_size_bytes,
- const std::string& metadata,
- base::OnceCallback<void(bool)> reply);
-
- void OnWebRtcEventLogWriteInternal(
- PeerConnectionKey key,
- bool remote_logging_allowed,
- const std::string& message,
- base::OnceCallback<void(std::pair<bool, bool>)> reply);
-
- void RenderProcessExitedInternal(int render_process_id);
-
- void SetLocalLogsObserverInternal(WebRtcLocalEventLogsObserver* observer,
- base::OnceClosure reply);
-
- void SetRemoteLogsObserverInternal(WebRtcRemoteEventLogsObserver* observer,
- base::OnceClosure reply);
-
- // Non-empty replies get posted to BrowserThread::UI.
- void MaybeReply(base::OnceClosure reply);
- void MaybeReply(base::OnceCallback<void(bool)> reply, bool value);
- void MaybeReply(base::OnceCallback<void(std::pair<bool, bool>)> reply,
- bool first,
- bool second);
-
- // Injects a fake clock, to be used by tests. For example, this could be
- // used to inject a frozen clock, thereby allowing unit tests to know what a
- // local log's filename would end up being.
- void SetClockForTesting(base::Clock* clock,
- base::OnceClosure reply = base::OnceClosure());
-
- // Injects a PeerConnectionTrackerProxy for testing. The normal tracker proxy
- // is used to communicate back to WebRTC whether event logging is desired for
- // a given peer connection. Using this function, those indications can be
- // intercepted by a unit test.
- void SetPeerConnectionTrackerProxyForTesting(
- std::unique_ptr<PeerConnectionTrackerProxy> pc_tracker_proxy,
- base::OnceClosure reply = base::OnceClosure());
-
- // Injects a fake uploader, to be used by unit tests.
- void SetWebRtcEventLogUploaderFactoryForTesting(
- std::unique_ptr<WebRtcEventLogUploader::Factory> uploader_factory,
- base::OnceClosure reply = base::OnceClosure());
-
- // Observer which will be informed whenever a local log file is started or
- // stopped. Its callbacks are called synchronously from |task_runner_|,
- // so the observer needs to be able to either run from any (sequenced) runner.
- WebRtcLocalEventLogsObserver* local_logs_observer_;
-
- // Observer which will be informed whenever a remote log file is started or
- // stopped. Its callbacks are called synchronously from |task_runner_|,
- // so the observer needs to be able to either run from any (sequenced) runner.
- WebRtcRemoteEventLogsObserver* remote_logs_observer_;
-
- // Manages local-bound logs - logs stored on the local filesystem when
- // logging has been explicitly enabled by the user.
- WebRtcLocalEventLogManager local_logs_manager_;
-
- // Manages remote-bound logs - logs which will be sent to a remote server.
- WebRtcRemoteEventLogManager remote_logs_manager_;
-
- // This keeps track of which peer connections have event logging turned on
- // in WebRTC, and for which client(s).
- std::map<PeerConnectionKey, LoggingTargetBitmap>
- peer_connections_with_event_logging_enabled_;
-
- // The set of RenderProcessHosts with which the manager is registered for
- // observation. Allows us to register for each RPH only once, and get notified
- // when it exits (cleanly or due to a crash).
- // This object is only to be accessed on the UI thread.
- base::flat_set<RenderProcessHost*> observed_render_process_hosts_;
-
- // In production, this holds a small object that just tells WebRTC (via
- // PeerConnectionTracker) to start/stop producing event logs for a specific
- // peer connection. In (relevant) unit tests, a mock will be injected.
- std::unique_ptr<PeerConnectionTrackerProxy> pc_tracker_proxy_;
-
- // The main logic will run sequentially on this runner, on which blocking
- // tasks are allowed.
- scoped_refptr<base::SequencedTaskRunner> task_runner_;
-
- DISALLOW_COPY_AND_ASSIGN(WebRtcEventLogManager);
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_WEBRTC_WEBRTC_EVENT_LOG_MANAGER_H_
diff --git a/chromium/content/browser/webrtc/webrtc_event_log_manager_common.cc b/chromium/content/browser/webrtc/webrtc_event_log_manager_common.cc
deleted file mode 100644
index 85d13f7307b..00000000000
--- a/chromium/content/browser/webrtc/webrtc_event_log_manager_common.cc
+++ /dev/null
@@ -1,52 +0,0 @@
-// Copyright (c) 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/webrtc/webrtc_event_log_manager_common.h"
-
-#include <limits>
-
-namespace content {
-
-bool LogFileWriter::WriteToLogFile(LogFilesMap::iterator it,
- const std::string& message) {
- DCHECK_LE(message.length(),
- static_cast<size_t>(std::numeric_limits<int>::max()));
-
- // Observe the file size limit, if any. Note that base::File's interface does
- // not allow writing more than numeric_limits<int>::max() bytes at a time.
- int message_len = static_cast<int>(message.length()); // DCHECKed above.
- LogFile& log_file = it->second;
- if (log_file.max_file_size_bytes != kWebRtcEventLogManagerUnlimitedFileSize) {
- DCHECK_LT(log_file.file_size_bytes, log_file.max_file_size_bytes);
- const bool size_will_wrap_around =
- log_file.file_size_bytes + message.length() < log_file.file_size_bytes;
- const bool size_limit_will_be_exceeded =
- log_file.file_size_bytes + message.length() >
- log_file.max_file_size_bytes;
- if (size_will_wrap_around || size_limit_will_be_exceeded) {
- CloseLogFile(it);
- return false;
- }
- }
-
- int written = log_file.file.WriteAtCurrentPos(message.c_str(), message_len);
- if (written != message_len) {
- LOG(WARNING) << "WebRTC event log message couldn't be written to the "
- "locally stored file in its entirety.";
- CloseLogFile(it);
- return false;
- }
-
- log_file.file_size_bytes += static_cast<size_t>(written);
- if (log_file.max_file_size_bytes != kWebRtcEventLogManagerUnlimitedFileSize) {
- DCHECK_LE(log_file.file_size_bytes, log_file.max_file_size_bytes);
- if (log_file.file_size_bytes >= log_file.max_file_size_bytes) {
- CloseLogFile(it);
- }
- }
-
- return (static_cast<size_t>(written) == message.length());
-}
-
-} // namespace content
diff --git a/chromium/content/browser/webrtc/webrtc_event_log_manager_common.h b/chromium/content/browser/webrtc/webrtc_event_log_manager_common.h
deleted file mode 100644
index 21e5ea84581..00000000000
--- a/chromium/content/browser/webrtc/webrtc_event_log_manager_common.h
+++ /dev/null
@@ -1,182 +0,0 @@
-// Copyright (c) 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_WEBRTC_WEBRTC_RTC_EVENT_LOG_MANAGER_COMMON_H_
-#define CONTENT_BROWSER_WEBRTC_WEBRTC_RTC_EVENT_LOG_MANAGER_COMMON_H_
-
-#include <map>
-#include <string>
-#include <tuple>
-
-#include "base/files/file.h"
-#include "base/files/file_path.h"
-#include "base/time/time.h"
-#include "build/build_config.h"
-#include "content/common/content_export.h"
-
-// This file is intended for:
-// 1. Code shared between WebRtcEventLogManager, WebRtcLocalEventLogManager
-// and WebRtcRemoteEventLogManager.
-// 2. Code specific to either of the above classes, but which also needs
-// to be seen by unit tests (such as constants).
-
-namespace content {
-
-CONTENT_EXPORT extern const size_t kWebRtcEventLogManagerUnlimitedFileSize;
-
-CONTENT_EXPORT extern const size_t kDefaultMaxLocalLogFileSizeBytes;
-CONTENT_EXPORT extern const size_t kMaxNumberLocalWebRtcEventLogFiles;
-
-// Limit over the number of concurrently active (currently being written to
-// disk) remote-bound log files. This limits IO operations, and so it is
-// applied globally (all browser contexts are limited together).
-CONTENT_EXPORT extern const size_t kMaxActiveRemoteBoundWebRtcEventLogs;
-
-// Limit over the number of pending logs (logs stored on disk and awaiting to
-// be uploaded to a remote server). This limit avoids excessive storage. If a
-// user chooses to have multiple profiles (and hence browser contexts) on a
-// system, it is assumed that the user has enough storage to accommodate
-// the increased storage consumption that comes with it. Therefore, this
-// limit is applied per browser context.
-CONTENT_EXPORT extern const size_t kMaxPendingRemoteBoundWebRtcEventLogs;
-
-// The file extension to be associated with remote-bound logs while they are
-// kept on local disk.
-CONTENT_EXPORT extern const base::FilePath::CharType kRemoteBoundLogExtension[];
-
-// Version of the remote-bound log. Refers to the version of the event logs'
-// encoding, method for separation of metadata from the WebRTC event log, etc.
-CONTENT_EXPORT extern const uint8_t kRemoteBoundWebRtcEventLogFileVersion;
-
-// Remote-bound log headers are composed of:
-// * One byte for the version (for the encoding, metadata format, etc.)
-// * Three bytes encoding the length of the metadata, in bytes.
-// The metadata, which immediately follows the header, is not counted as part
-// of the header size.
-CONTENT_EXPORT extern const size_t kRemoteBoundLogFileHeaderSizeBytes;
-
-// Remote-bound event logs will not be uploaded if the time since their last
-// modification (meaning the time when they were completed) exceeds this value.
-// Such expired files will be purged from disk when examined.
-CONTENT_EXPORT extern const base::TimeDelta
- kRemoteBoundWebRtcEventLogsMaxRetention;
-
-// For a given Chrome session, this is a unique key for PeerConnections.
-// It's not, however, unique between sessions (after Chrome is restarted).
-struct WebRtcEventLogPeerConnectionKey {
- using BrowserContextId = uintptr_t;
-
- constexpr WebRtcEventLogPeerConnectionKey(int render_process_id,
- int lid,
- BrowserContextId browser_context_id)
- : render_process_id(render_process_id),
- lid(lid),
- browser_context_id(browser_context_id) {}
-
- bool operator==(const WebRtcEventLogPeerConnectionKey& other) const {
- // Each RPH is associated with exactly one BrowserContext.
- DCHECK(render_process_id != other.render_process_id ||
- browser_context_id == other.browser_context_id);
-
- const bool equal = std::tie(render_process_id, lid) ==
- std::tie(other.render_process_id, other.lid);
- return equal;
- }
-
- bool operator<(const WebRtcEventLogPeerConnectionKey& other) const {
- // Each RPH is associated with exactly one BrowserContext.
- DCHECK(render_process_id != other.render_process_id ||
- browser_context_id == other.browser_context_id);
-
- return std::tie(render_process_id, lid) <
- std::tie(other.render_process_id, other.lid);
- }
-
- // These two fields are the actual key; any peer connection is uniquely
- // identifiable by the renderer process in which it lives, and its ID within
- // that process.
- int render_process_id;
- int lid; // Renderer-local PeerConnection ID.
-
- // The BrowserContext is not actually part of the key, but each PeerConnection
- // is associated with a BrowserContext, and that BrowserContext is almost
- // always necessary, so it makes sense to remember it along with the key.
- BrowserContextId browser_context_id;
-};
-
-// An observer for notifications of local log files being started/stopped, and
-// the paths which will be used for these logs.
-class WebRtcLocalEventLogsObserver {
- public:
- virtual void OnLocalLogStarted(WebRtcEventLogPeerConnectionKey key,
- const base::FilePath& file_path) = 0;
- virtual void OnLocalLogStopped(WebRtcEventLogPeerConnectionKey key) = 0;
-
- protected:
- virtual ~WebRtcLocalEventLogsObserver() = default;
-};
-
-// An observer for notifications of remote-bound log files being
-// started/stopped. The start event would likely only interest unit tests
-// (because it exposes the randomized filename to them). The stop event is of
-// general interest, because it would often mean that WebRTC can stop sending
-// us event logs for this peer connection.
-// Some cases where OnRemoteLogStopped would be called include:
-// 1. The PeerConnection has become inactive.
-// 2. The file's maximum size has been reached.
-// 3. Any type of error while writing to the file.
-class WebRtcRemoteEventLogsObserver {
- public:
- virtual void OnRemoteLogStarted(WebRtcEventLogPeerConnectionKey key,
- const base::FilePath& file_path) = 0;
- virtual void OnRemoteLogStopped(WebRtcEventLogPeerConnectionKey key) = 0;
-
- protected:
- virtual ~WebRtcRemoteEventLogsObserver() = default;
-};
-
-struct LogFile {
- LogFile(const base::FilePath& path,
- base::File file,
- size_t max_file_size_bytes,
- size_t file_size_bytes = 0)
- : path(path),
- file(std::move(file)),
- max_file_size_bytes(max_file_size_bytes),
- file_size_bytes(file_size_bytes) {}
- const base::FilePath path;
- base::File file;
- const size_t max_file_size_bytes;
- size_t file_size_bytes;
-};
-
-// WebRtcLocalEventLogManager and WebRtcRemoteEventLogManager share some logic
-// when it comes to handling of files on disk.
-class LogFileWriter {
- protected:
- using PeerConnectionKey = WebRtcEventLogPeerConnectionKey;
- using BrowserContextId = PeerConnectionKey::BrowserContextId;
- using LogFilesMap = std::map<PeerConnectionKey, LogFile>;
-
- virtual ~LogFileWriter() = default;
-
- // Given a peer connection and its associated log file, and given a log
- // fragment that should be written to the log file, attempt to write to
- // the log file (return value indicates success/failure).
- // If an error occurs, or if the file reaches its capacity, CloseLogFile()
- // will be called, closing the file.
- bool WriteToLogFile(LogFilesMap::iterator it, const std::string& message);
-
- // Called when WriteToLogFile() either encounters an error, or if the file's
- // intended capacity is reached. It indicates to the inheriting class that
- // the file should also be purged from its set of active log files.
- // The function should return an iterator to the next element in the set
- // of active logs. This makes the function more useful, allowing it to be
- // used when iterating and closing several log files.
- virtual LogFilesMap::iterator CloseLogFile(LogFilesMap::iterator it) = 0;
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_WEBRTC_WEBRTC_RTC_EVENT_LOG_MANAGER_COMMON_H_
diff --git a/chromium/content/browser/webrtc/webrtc_event_log_manager_unittest.cc b/chromium/content/browser/webrtc/webrtc_event_log_manager_unittest.cc
deleted file mode 100644
index 4a6b0699286..00000000000
--- a/chromium/content/browser/webrtc/webrtc_event_log_manager_unittest.cc
+++ /dev/null
@@ -1,2454 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/webrtc/webrtc_event_log_manager.h"
-
-#include <algorithm>
-#include <list>
-#include <memory>
-#include <numeric>
-#include <queue>
-#include <string>
-#include <utility>
-#include <vector>
-
-#include "base/big_endian.h"
-#include "base/bind.h"
-#include "base/files/file.h"
-#include "base/files/file_path.h"
-#include "base/files/file_util.h"
-#include "base/files/scoped_temp_dir.h"
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/optional.h"
-#include "base/run_loop.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/string_util.h"
-#include "base/synchronization/waitable_event.h"
-#include "base/test/gtest_util.h"
-#include "base/test/simple_test_clock.h"
-#include "base/time/time.h"
-#include "build/build_config.h"
-#include "content/browser/webrtc/webrtc_remote_event_log_manager.h"
-#include "content/public/test/mock_render_process_host.h"
-#include "content/public/test/test_browser_context.h"
-#include "content/public/test/test_browser_thread_bundle.h"
-#include "testing/gmock/include/gmock/gmock.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-// TODO(eladalon): Add unit tests for incognito mode. https://crbug.com/775415
-
-#if defined(OS_WIN)
-#define IntToStringType base::IntToString16
-#else
-#define IntToStringType base::IntToString
-#endif
-
-namespace content {
-
-using ::testing::_;
-using ::testing::Invoke;
-using ::testing::NiceMock;
-
-using PeerConnectionKey = WebRtcEventLogPeerConnectionKey;
-
-namespace {
-
-const int kMaxActiveRemoteLogFiles =
- static_cast<int>(kMaxActiveRemoteBoundWebRtcEventLogs);
-const int kMaxPendingRemoteLogFiles =
- static_cast<int>(kMaxPendingRemoteBoundWebRtcEventLogs);
-
-// This implementation does not upload files, nor prtends to have finished an
-// upload. Most importantly, it does not get rid of the locally-stored log file
-// after finishing a simulated upload; this is useful because it keeps the file
-// on disk, where unit tests may inspect it.
-class NullWebRtcEventLogUploader : public WebRtcEventLogUploader {
- public:
- ~NullWebRtcEventLogUploader() override = default;
-
- class Factory : public WebRtcEventLogUploader::Factory {
- public:
- ~Factory() override = default;
-
- std::unique_ptr<WebRtcEventLogUploader> Create(
- const base::FilePath& log_file,
- WebRtcEventLogUploaderObserver* observer) override {
- return std::make_unique<NullWebRtcEventLogUploader>();
- }
- };
-};
-
-class MockWebRtcLocalEventLogsObserver : public WebRtcLocalEventLogsObserver {
- public:
- ~MockWebRtcLocalEventLogsObserver() override = default;
- MOCK_METHOD2(OnLocalLogStarted,
- void(PeerConnectionKey, const base::FilePath&));
- MOCK_METHOD1(OnLocalLogStopped, void(PeerConnectionKey));
-};
-
-class MockWebRtcRemoteEventLogsObserver : public WebRtcRemoteEventLogsObserver {
- public:
- ~MockWebRtcRemoteEventLogsObserver() override = default;
- MOCK_METHOD2(OnRemoteLogStarted,
- void(PeerConnectionKey, const base::FilePath&));
- MOCK_METHOD1(OnRemoteLogStopped, void(PeerConnectionKey));
-};
-
-} // namespace
-
-class WebRtcEventLogManagerTest : public ::testing::TestWithParam<bool> {
- public:
- WebRtcEventLogManagerTest()
- : run_loop_(std::make_unique<base::RunLoop>()),
- uploader_run_loop_(std::make_unique<base::RunLoop>()),
- manager_(WebRtcEventLogManager::CreateSingletonInstance()) {
- EXPECT_TRUE(base::CreateNewTempDirectory(FILE_PATH_LITERAL(""),
- &local_logs_base_dir_));
- if (local_logs_base_dir_.empty()) {
- EXPECT_TRUE(false);
- return;
- }
-
- local_logs_base_path_ =
- local_logs_base_dir_.Append(FILE_PATH_LITERAL("local_event_logs"));
- }
-
- void SetUp() override {
- SetWebRtcEventLogUploaderFactoryForTesting(
- std::make_unique<NullWebRtcEventLogUploader::Factory>());
- browser_context_ = CreateBrowserContext();
- rph_ = std::make_unique<MockRenderProcessHost>(browser_context_.get());
-
- SetLocalLogsObserver(&local_observer_);
- SetRemoteLogsObserver(&remote_observer_);
- }
-
- ~WebRtcEventLogManagerTest() override {
- if (manager_) {
- WaitForPendingTasks();
- DestroyUnitUnderTest();
- }
-
- if (!local_logs_base_dir_.empty()) {
- EXPECT_TRUE(base::DeleteFile(local_logs_base_dir_, true));
- }
-
- // Guard against unexpected state changes.
- EXPECT_TRUE(webrtc_state_change_instructions_.empty());
- }
-
- void DestroyUnitUnderTest() {
- manager_.reset();
- }
-
- void WaitForReply() {
- run_loop_->Run();
- run_loop_.reset(new base::RunLoop); // Allow re-blocking.
- }
-
- void VoidReply() { run_loop_->QuitWhenIdle(); }
-
- base::OnceClosure VoidReplyClosure() {
- return base::BindOnce(&WebRtcEventLogManagerTest::VoidReply,
- base::Unretained(this));
- }
-
- void BoolReply(bool* output, bool value) {
- *output = value;
- run_loop_->QuitWhenIdle();
- }
-
- base::OnceCallback<void(bool)> BoolReplyClosure(bool* output) {
- return base::BindOnce(&WebRtcEventLogManagerTest::BoolReply,
- base::Unretained(this), output);
- }
-
- void BoolPairReply(std::pair<bool, bool>* output,
- std::pair<bool, bool> value) {
- *output = value;
- run_loop_->QuitWhenIdle();
- }
-
- base::OnceCallback<void(std::pair<bool, bool>)> BoolPairReplyClosure(
- std::pair<bool, bool>* output) {
- return base::BindOnce(&WebRtcEventLogManagerTest::BoolPairReply,
- base::Unretained(this), output);
- }
-
- bool PeerConnectionAdded(int render_process_id, int lid) {
- bool result;
- manager_->PeerConnectionAdded(render_process_id, lid,
- BoolReplyClosure(&result));
- WaitForReply();
- return result;
- }
-
- bool PeerConnectionRemoved(int render_process_id, int lid) {
- bool result;
- manager_->PeerConnectionRemoved(render_process_id, lid,
- BoolReplyClosure(&result));
- WaitForReply();
- return result;
- }
-
- bool PeerConnectionStopped(int render_process_id, int lid) {
- bool result;
- manager_->PeerConnectionStopped(render_process_id, lid,
- BoolReplyClosure(&result));
- WaitForReply();
- return result;
- }
-
- bool EnableLocalLogging(
- size_t max_size_bytes = kWebRtcEventLogManagerUnlimitedFileSize) {
- return EnableLocalLogging(local_logs_base_path_, max_size_bytes);
- }
-
- bool EnableLocalLogging(
- base::FilePath local_logs_base_path,
- size_t max_size_bytes = kWebRtcEventLogManagerUnlimitedFileSize) {
- bool result;
- manager_->EnableLocalLogging(local_logs_base_path, max_size_bytes,
- BoolReplyClosure(&result));
- WaitForReply();
- return result;
- }
-
- bool DisableLocalLogging() {
- bool result;
- manager_->DisableLocalLogging(BoolReplyClosure(&result));
- WaitForReply();
- return result;
- }
-
- bool StartRemoteLogging(int render_process_id,
- int lid,
- size_t max_size_bytes = kArbitraryVeryLargeFileSize,
- const std::string& metadata = "") {
- bool result;
- manager_->StartRemoteLogging(render_process_id, lid, max_size_bytes,
- metadata, BoolReplyClosure(&result));
- WaitForReply();
- return result;
- }
-
- bool StartRemoteLogging(int render_process_id,
- int lid,
- const std::string& metadata) {
- return StartRemoteLogging(render_process_id, lid,
- kArbitraryVeryLargeFileSize, metadata);
- }
-
- void SetLocalLogsObserver(WebRtcLocalEventLogsObserver* observer) {
- manager_->SetLocalLogsObserver(observer, VoidReplyClosure());
- WaitForReply();
- }
-
- void SetRemoteLogsObserver(WebRtcRemoteEventLogsObserver* observer) {
- manager_->SetRemoteLogsObserver(observer, VoidReplyClosure());
- WaitForReply();
- }
-
- void SetWebRtcEventLogUploaderFactoryForTesting(
- std::unique_ptr<WebRtcEventLogUploader::Factory> factory) {
- manager_->SetWebRtcEventLogUploaderFactoryForTesting(std::move(factory),
- VoidReplyClosure());
- WaitForReply();
- }
-
- std::pair<bool, bool> OnWebRtcEventLogWrite(int render_process_id,
- int lid,
- const std::string& message) {
- std::pair<bool, bool> result;
- manager_->OnWebRtcEventLogWrite(render_process_id, lid, message,
- BoolPairReplyClosure(&result));
- WaitForReply();
- return result;
- }
-
- void FreezeClockAt(const base::Time::Exploded& frozen_time_exploded) {
- base::Time frozen_time;
- ASSERT_TRUE(
- base::Time::FromLocalExploded(frozen_time_exploded, &frozen_time));
- frozen_clock_.SetNow(frozen_time);
- manager_->SetClockForTesting(&frozen_clock_, VoidReplyClosure());
- WaitForReply();
- }
-
- void SetWebRtcEventLoggingState(PeerConnectionKey key,
- bool event_logging_enabled) {
- webrtc_state_change_instructions_.emplace(key, event_logging_enabled);
- }
-
- void ExpectWebRtcStateChangeInstruction(int render_process_id,
- int lid,
- bool enabled) {
- ASSERT_FALSE(webrtc_state_change_instructions_.empty());
- auto& instruction = webrtc_state_change_instructions_.front();
- EXPECT_EQ(instruction.key.render_process_id, render_process_id);
- EXPECT_EQ(instruction.key.lid, lid);
- EXPECT_EQ(instruction.enabled, enabled);
- webrtc_state_change_instructions_.pop();
- }
-
- void SetPeerConnectionTrackerProxyForTesting(
- std::unique_ptr<WebRtcEventLogManager::PeerConnectionTrackerProxy>
- pc_tracker_proxy) {
- manager_->SetPeerConnectionTrackerProxyForTesting(
- std::move(pc_tracker_proxy), VoidReplyClosure());
- WaitForReply();
- }
-
- std::unique_ptr<TestBrowserContext> CreateBrowserContext(
- base::FilePath local_logs_base_path = base::FilePath()) {
- auto browser_context =
- std::make_unique<TestBrowserContext>(local_logs_base_path);
-
- // Blocks on the unit under test's task runner, so that we won't proceed
- // with the test (e.g. check that files were created) before finished
- // processing this even (which is signaled to it from
- // BrowserContext::EnableForBrowserContext).
- WaitForPendingTasks();
-
- return browser_context;
- }
-
- base::FilePath GetLogsDirectoryPath(
- const base::FilePath& browser_context_dir) {
- return WebRtcRemoteEventLogManager::GetLogsDirectoryPath(
- browser_context_dir);
- }
-
- // Initiate an arbitrary synchronous operation, allowing any tasks pending
- // on the manager's internal task queue to be completed.
- // If given a RunLoop, we first block on it. The reason to do both is that
- // with the RunLoop we wait on some tasks which we know also post additional
- // tasks, then, after that chain is completed, we also wait for any potential
- // leftovers. For example, the run loop could wait for n-1 files to be
- // uploaded, then it is released when the last one's upload is initiated,
- // then we wait for the last file's upload to be completed.
- void WaitForPendingTasks(base::RunLoop* run_loop = nullptr) {
- if (run_loop) {
- run_loop->Run();
- }
-
- base::WaitableEvent event(base::WaitableEvent::ResetPolicy::MANUAL,
- base::WaitableEvent::InitialState::NOT_SIGNALED);
- manager_->GetTaskRunnerForTesting()->PostTask(
- FROM_HERE,
- base::BindOnce([](base::WaitableEvent* event) { event->Signal(); },
- &event));
- event.Wait();
- }
-
- void SuppressUploading() {
- if (!upload_suppressing_browser_context_) { // First suppression.
- upload_suppressing_browser_context_ = CreateBrowserContext();
- }
- DCHECK(!upload_suppressing_rph_) << "Uploading already suppressed.";
- upload_suppressing_rph_ = std::make_unique<MockRenderProcessHost>(
- upload_suppressing_browser_context_.get());
- ASSERT_TRUE(PeerConnectionAdded(upload_suppressing_rph_->GetID(), 0));
- }
-
- void UnsuppressUploading() {
- DCHECK(upload_suppressing_rph_) << "Uploading not suppressed.";
- ASSERT_TRUE(PeerConnectionRemoved(upload_suppressing_rph_->GetID(), 0));
- upload_suppressing_rph_.reset();
- }
-
- void ExpectLocalFileContents(const base::FilePath& file_path,
- const std::string& expected_contents) {
- std::string file_contents;
- ASSERT_TRUE(base::ReadFileToString(file_path, &file_contents));
- EXPECT_EQ(file_contents, expected_contents);
- }
-
- void ExpectRemoteFileContents(const base::FilePath& file_path,
- const std::string& expected_event_log,
- const std::string& expected_metadata = "") {
- std::string file_contents;
- ASSERT_TRUE(base::ReadFileToString(file_path, &file_contents));
-
- // Even an empty file must contain the header.
- ASSERT_GE(file_contents.length(), kRemoteBoundLogFileHeaderSizeBytes);
-
- uint32_t header;
- base::ReadBigEndian<uint32_t>(file_contents.c_str(), &header);
-
- // Make sure it's a supported version.
- const uint8_t version = static_cast<uint8_t>(header >> 24);
- EXPECT_EQ(version, kRemoteBoundWebRtcEventLogFileVersion);
-
- // Verify the metadata is as expected.
- const uint32_t metadata_length = (header & 0xFFFFFFu);
- ASSERT_LE(kRemoteBoundLogFileHeaderSizeBytes + metadata_length,
- file_contents.size());
- const std::string metadata = file_contents.substr(
- kRemoteBoundLogFileHeaderSizeBytes, metadata_length);
- EXPECT_EQ(metadata, expected_metadata);
-
- // Verify the WebRTC event log itself.
- const std::string event_log = file_contents.substr(
- kRemoteBoundLogFileHeaderSizeBytes + metadata_length);
- EXPECT_EQ(event_log, expected_event_log);
- }
-
- static const size_t kArbitraryVeryLargeFileSize = 1000 * 1000 * 1000;
-
- // Testing utilities.
- content::TestBrowserThreadBundle test_browser_thread_bundle_;
- base::SimpleTestClock frozen_clock_;
-
- // The main loop, which allows waiting for the operations invoked on the
- // unit-under-test to be completed. Do not use this object directly from the
- // tests, since that would be error-prone. (Specifically, one must not produce
- // two events that could produce replies, without waiting on the first reply
- // in between.)
- std::unique_ptr<base::RunLoop> run_loop_;
-
- // Allows waiting for upload operations.
- std::unique_ptr<base::RunLoop> uploader_run_loop_;
-
- // Unit under test.
- std::unique_ptr<WebRtcEventLogManager> manager_;
-
- // Default BrowserContext and RenderProcessHost, to be used by tests which
- // do not require anything fancy (such as seeding the BrowserContext with
- // pre-existing logs files from a previous session, or working with multiple
- // BrowserContext objects).
- std::unique_ptr<TestBrowserContext> browser_context_;
- std::unique_ptr<MockRenderProcessHost> rph_;
-
- // Used for suppressing the upload of finished files, by creating an active
- // remote-bound log associated with an independent BrowserContext which
- // does not otherwise interfere with the test.
- std::unique_ptr<TestBrowserContext> upload_suppressing_browser_context_;
- std::unique_ptr<MockRenderProcessHost> upload_suppressing_rph_;
-
- // The directory where we'll save local log files.
- base::FilePath local_logs_base_dir_;
- // local_logs_base_dir_ + log files' name prefix.
- base::FilePath local_logs_base_path_;
-
- // WebRtcEventLogManager instructs WebRTC, via PeerConnectionTracker, to
- // only send WebRTC messages for certain peer connections. Some tests make
- // sure that this is done correctly, by waiting for these notifications, then
- // testing them.
- // Because a single action - disabling of local logging - could crease a
- // series of such instructions, we keep a queue of them. However, were one
- // to actually test that scenario, one would have to account for the lack
- // of a guarantee over the order in which these instructions are produced.
- struct WebRtcStateChangeInstruction {
- WebRtcStateChangeInstruction(PeerConnectionKey key, bool enabled)
- : key(key), enabled(enabled) {}
- PeerConnectionKey key;
- bool enabled;
- };
- std::queue<WebRtcStateChangeInstruction> webrtc_state_change_instructions_;
-
- // Observers for local/remote logging being started/stopped. By having them
- // here, we achieve two goals:
- // 1. Reduce boilerplate in the tests themselves.
- // 2. Avoid lifetime issues, where the observer might be deallocated before
- // a RenderProcessHost is deallocated (which can potentially trigger a
- // callback on the observer).
- NiceMock<MockWebRtcLocalEventLogsObserver> local_observer_;
- NiceMock<MockWebRtcRemoteEventLogsObserver> remote_observer_;
-};
-
-namespace {
-
-// Common default/arbitrary values.
-static constexpr int kPeerConnectionId = 478;
-
-PeerConnectionKey GetPeerConnectionKey(const RenderProcessHost* rph, int lid) {
- const BrowserContext* browser_context = rph->GetBrowserContext();
- const auto browser_context_id =
- WebRtcEventLogManager::GetBrowserContextId(browser_context);
- return PeerConnectionKey(rph->GetID(), lid, browser_context_id);
-}
-
-auto SaveFilePathTo(base::Optional<base::FilePath>* output) {
- return [output](PeerConnectionKey ignored_key, base::FilePath file_path) {
- *output = file_path;
- };
-}
-
-auto SaveKeyAndFilePathTo(base::Optional<PeerConnectionKey>* key_output,
- base::Optional<base::FilePath>* file_path_output) {
- return [key_output, file_path_output](PeerConnectionKey key,
- base::FilePath file_path) {
- *key_output = key;
- *file_path_output = file_path;
- };
-}
-
-class PeerConnectionTrackerProxyForTesting
- : public WebRtcEventLogManager::PeerConnectionTrackerProxy {
- public:
- explicit PeerConnectionTrackerProxyForTesting(WebRtcEventLogManagerTest* test)
- : test_(test) {}
-
- ~PeerConnectionTrackerProxyForTesting() override = default;
-
- void SetWebRtcEventLoggingState(const PeerConnectionKey& key,
- bool event_logging_enabled) override {
- test_->SetWebRtcEventLoggingState(key, event_logging_enabled);
- }
-
- private:
- WebRtcEventLogManagerTest* const test_;
-};
-
-#if defined(OS_POSIX) && !defined(OS_FUCHSIA)
-void RemoveWritePermissionsFromDirectory(const base::FilePath& path) {
- int permissions;
- ASSERT_TRUE(base::GetPosixFilePermissions(path, &permissions));
- constexpr int write_permissions = base::FILE_PERMISSION_WRITE_BY_USER |
- base::FILE_PERMISSION_WRITE_BY_GROUP |
- base::FILE_PERMISSION_WRITE_BY_OTHERS;
- permissions &= ~write_permissions;
- ASSERT_TRUE(base::SetPosixFilePermissions(path, permissions));
-}
-#endif // defined(OS_POSIX) && !defined(OS_FUCHSIA)
-
-// Production code uses the WebRtcEventLogUploaderObserver interface to
-// pass notifications of an upload's completion from the concrete uploader
-// to the remote-logs-manager. In unit tests, these notifications are
-// intercepted, inspected and then passed onwards to the remote-logs-manager.
-// This class simplifies this by getting a hold of the message, sending it
-// to the unit test's observer, then allowing it to proceed to its normal
-// destination.
-class InterceptingWebRtcEventLogUploaderObserver
- : public WebRtcEventLogUploaderObserver {
- public:
- InterceptingWebRtcEventLogUploaderObserver(
- WebRtcEventLogUploaderObserver* intercpeting_observer,
- WebRtcEventLogUploaderObserver* normal_observer)
- : intercpeting_observer_(intercpeting_observer),
- normal_observer_(normal_observer) {}
-
- ~InterceptingWebRtcEventLogUploaderObserver() override = default;
-
- void OnWebRtcEventLogUploadComplete(const base::FilePath& file_path,
- bool upload_successful) override {
- intercpeting_observer_->OnWebRtcEventLogUploadComplete(file_path,
- upload_successful);
- normal_observer_->OnWebRtcEventLogUploadComplete(file_path,
- upload_successful);
- }
-
- private:
- WebRtcEventLogUploaderObserver* const intercpeting_observer_;
- WebRtcEventLogUploaderObserver* const normal_observer_;
-};
-
-// The factory for the following fake uploader produces a sequence of uploaders
-// which fail the test if given a file other than that which they expect. The
-// factory itself likewise fails the test if destroyed before producing all
-// expected uploaders, or if it's asked for more uploaders than it expects to
-// create. This allows us to test for sequences of uploads.
-class FileListExpectingWebRtcEventLogUploader : public WebRtcEventLogUploader {
- public:
- // The logic is in the factory; the uploader just reports success so that the
- // next file may become eligible for uploading.
- explicit FileListExpectingWebRtcEventLogUploader(
- const base::FilePath& log_file,
- bool result,
- WebRtcEventLogUploaderObserver* observer) {
- observer->OnWebRtcEventLogUploadComplete(log_file, result);
- }
-
- ~FileListExpectingWebRtcEventLogUploader() override = default;
-
- class Factory : public WebRtcEventLogUploader::Factory {
- public:
- Factory(std::list<base::FilePath>* expected_files,
- bool result,
- base::RunLoop* run_loop)
- : result_(result), run_loop_(run_loop) {
- expected_files_.swap(*expected_files);
- }
-
- ~Factory() override { EXPECT_TRUE(expected_files_.empty()); }
-
- std::unique_ptr<WebRtcEventLogUploader> Create(
- const base::FilePath& log_file,
- WebRtcEventLogUploaderObserver* observer) override {
- if (expected_files_.empty()) {
- EXPECT_FALSE(true); // More files uploaded than expected.
- } else {
- EXPECT_EQ(log_file, expected_files_.front());
- base::DeleteFile(log_file, false);
- expected_files_.pop_front();
- }
-
- if (expected_files_.empty()) {
- run_loop_->QuitWhenIdle();
- }
-
- return std::make_unique<FileListExpectingWebRtcEventLogUploader>(
- log_file, result_, observer);
- }
-
- private:
- std::list<base::FilePath> expected_files_;
- const bool result_;
- base::RunLoop* const run_loop_;
- };
-};
-
-} // namespace
-
-TEST_F(WebRtcEventLogManagerTest, LocalLogPeerConnectionAddedReturnsTrue) {
- EXPECT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- LocalLogPeerConnectionAddedReturnsFalseIfAlreadyAdded) {
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
- EXPECT_FALSE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
-}
-
-TEST_F(WebRtcEventLogManagerTest, LocalLogPeerConnectionRemovedReturnsTrue) {
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
- EXPECT_TRUE(PeerConnectionRemoved(rph_->GetID(), kPeerConnectionId));
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- LocalLogPeerConnectionRemovedReturnsFalseIfNeverAdded) {
- EXPECT_FALSE(PeerConnectionRemoved(rph_->GetID(), kPeerConnectionId));
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- LocalLogPeerConnectionRemovedReturnsFalseIfAlreadyRemoved) {
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
- ASSERT_TRUE(PeerConnectionRemoved(rph_->GetID(), kPeerConnectionId));
- EXPECT_FALSE(PeerConnectionRemoved(rph_->GetID(), kPeerConnectionId));
-}
-
-TEST_F(WebRtcEventLogManagerTest, LocalLogEnableLocalLoggingReturnsTrue) {
- EXPECT_TRUE(EnableLocalLogging());
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- LocalLogEnableLocalLoggingReturnsFalseIfCalledWhenAlreadyEnabled) {
- ASSERT_TRUE(EnableLocalLogging());
- EXPECT_FALSE(EnableLocalLogging());
-}
-
-TEST_F(WebRtcEventLogManagerTest, LocalLogDisableLocalLoggingReturnsTrue) {
- ASSERT_TRUE(EnableLocalLogging());
- EXPECT_TRUE(DisableLocalLogging());
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- LocalLogDisableLocalLoggingReturnsIfNeverEnabled) {
- EXPECT_FALSE(DisableLocalLogging());
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- LocalLogDisableLocalLoggingReturnsIfAlreadyDisabled) {
- ASSERT_TRUE(EnableLocalLogging());
- ASSERT_TRUE(DisableLocalLogging());
- EXPECT_FALSE(DisableLocalLogging());
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- OnWebRtcEventLogWriteReturnsFalseAndFalseWhenAllLoggingDisabled) {
- // Note that EnableLocalLogging() and StartRemoteLogging() weren't called.
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
- EXPECT_EQ(OnWebRtcEventLogWrite(rph_->GetID(), kPeerConnectionId, "log"),
- std::make_pair(false, false));
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- OnWebRtcEventLogWriteReturnsFalseAndFalseForUnknownPeerConnection) {
- ASSERT_TRUE(EnableLocalLogging());
- // Note that PeerConnectionAdded() wasn't called.
- EXPECT_EQ(OnWebRtcEventLogWrite(rph_->GetID(), kPeerConnectionId, "log"),
- std::make_pair(false, false));
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- OnWebRtcEventLogWriteReturnsLocalTrueWhenPcKnownAndLocalLoggingOn) {
- ASSERT_TRUE(EnableLocalLogging());
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
- EXPECT_EQ(OnWebRtcEventLogWrite(rph_->GetID(), kPeerConnectionId, "log"),
- std::make_pair(true, false));
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- OnWebRtcEventLogWriteReturnsRemoteTrueWhenPcKnownAndRemoteLogging) {
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
- ASSERT_TRUE(StartRemoteLogging(rph_->GetID(), kPeerConnectionId));
- EXPECT_EQ(OnWebRtcEventLogWrite(rph_->GetID(), kPeerConnectionId, "log"),
- std::make_pair(false, true));
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- OnWebRtcEventLogWriteReturnsTrueAndTrueeWhenAllLoggingEnabled) {
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
- ASSERT_TRUE(EnableLocalLogging());
- ASSERT_TRUE(StartRemoteLogging(rph_->GetID(), kPeerConnectionId));
- EXPECT_EQ(OnWebRtcEventLogWrite(rph_->GetID(), kPeerConnectionId, "log"),
- std::make_pair(true, true));
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- OnLocalLogStartedNotCalledIfLocalLoggingEnabledWithoutPeerConnections) {
- EXPECT_CALL(local_observer_, OnLocalLogStarted(_, _)).Times(0);
- ASSERT_TRUE(EnableLocalLogging());
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- OnLocalLogStoppedNotCalledIfLocalLoggingDisabledWithoutPeerConnections) {
- EXPECT_CALL(local_observer_, OnLocalLogStopped(_)).Times(0);
- ASSERT_TRUE(EnableLocalLogging());
- ASSERT_TRUE(DisableLocalLogging());
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- OnLocalLogStartedCalledForPeerConnectionAddedAndLocalLoggingEnabled) {
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
- EXPECT_CALL(local_observer_, OnLocalLogStarted(key, _)).Times(1);
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- ASSERT_TRUE(EnableLocalLogging());
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- OnLocalLogStartedCalledForLocalLoggingEnabledAndPeerConnectionAdded) {
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
- EXPECT_CALL(local_observer_, OnLocalLogStarted(key, _)).Times(1);
- ASSERT_TRUE(EnableLocalLogging());
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- OnLocalLogStoppedCalledAfterLocalLoggingDisabled) {
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
- EXPECT_CALL(local_observer_, OnLocalLogStopped(key)).Times(1);
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- ASSERT_TRUE(EnableLocalLogging());
- ASSERT_TRUE(DisableLocalLogging());
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- OnLocalLogStoppedCalledAfterPeerConnectionRemoved) {
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
- EXPECT_CALL(local_observer_, OnLocalLogStopped(key)).Times(1);
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- ASSERT_TRUE(EnableLocalLogging());
- ASSERT_TRUE(PeerConnectionRemoved(key.render_process_id, key.lid));
-}
-
-TEST_F(WebRtcEventLogManagerTest, LocalLogCreatesEmptyFileWhenStarted) {
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
- base::Optional<base::FilePath> file_path;
- ON_CALL(local_observer_, OnLocalLogStarted(key, _))
- .WillByDefault(Invoke(SaveFilePathTo(&file_path)));
-
- ASSERT_TRUE(EnableLocalLogging());
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- ASSERT_TRUE(file_path);
- ASSERT_FALSE(file_path->empty());
-
- // Make sure the file would be closed, so that we could safely read it.
- ASSERT_TRUE(PeerConnectionRemoved(key.render_process_id, key.lid));
-
- ExpectLocalFileContents(*file_path, "");
-}
-
-TEST_F(WebRtcEventLogManagerTest, LocalLogCreateAndWriteToFile) {
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
-
- base::Optional<base::FilePath> file_path;
- ON_CALL(local_observer_, OnLocalLogStarted(key, _))
- .WillByDefault(Invoke(SaveFilePathTo(&file_path)));
-
- ASSERT_TRUE(EnableLocalLogging());
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- ASSERT_TRUE(file_path);
- ASSERT_FALSE(file_path->empty());
-
- const std::string log = "To strive, to seek, to find, and not to yield.";
- ASSERT_EQ(OnWebRtcEventLogWrite(rph_->GetID(), kPeerConnectionId, log),
- std::make_pair(true, false));
-
- // Make sure the file would be closed, so that we could safely read it.
- ASSERT_TRUE(PeerConnectionRemoved(key.render_process_id, key.lid));
-
- ExpectLocalFileContents(*file_path, log);
-}
-
-TEST_F(WebRtcEventLogManagerTest, LocalLogMultipleWritesToSameFile) {
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
-
- base::Optional<base::FilePath> file_path;
- ON_CALL(local_observer_, OnLocalLogStarted(key, _))
- .WillByDefault(Invoke(SaveFilePathTo(&file_path)));
-
- ASSERT_TRUE(EnableLocalLogging());
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- ASSERT_TRUE(file_path);
- ASSERT_FALSE(file_path->empty());
-
- const std::string logs[] = {"Old age hath yet his honour and his toil;",
- "Death closes all: but something ere the end,",
- "Some work of noble note, may yet be done,",
- "Not unbecoming men that strove with Gods."};
- for (const std::string& log : logs) {
- ASSERT_EQ(OnWebRtcEventLogWrite(key.render_process_id, key.lid, log),
- std::make_pair(true, false));
- }
-
- // Make sure the file would be closed, so that we could safely read it.
- ASSERT_TRUE(PeerConnectionRemoved(key.render_process_id, key.lid));
-
- ExpectLocalFileContents(
- *file_path,
- std::accumulate(std::begin(logs), std::end(logs), std::string()));
-}
-
-TEST_F(WebRtcEventLogManagerTest, LocalLogFileSizeLimitNotExceeded) {
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
-
- base::Optional<base::FilePath> file_path;
- ON_CALL(local_observer_, OnLocalLogStarted(key, _))
- .WillByDefault(Invoke(SaveFilePathTo(&file_path)));
-
- const std::string log = "There lies the port; the vessel puffs her sail:";
- const size_t file_size_limit_bytes = log.length() / 2;
-
- ASSERT_TRUE(EnableLocalLogging(file_size_limit_bytes));
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- ASSERT_TRUE(file_path);
- ASSERT_FALSE(file_path->empty());
-
- // Failure is reported, because not everything could be written. The file
- // will also be closed.
- EXPECT_CALL(local_observer_, OnLocalLogStopped(key)).Times(1);
- ASSERT_EQ(OnWebRtcEventLogWrite(key.render_process_id, key.lid, log),
- std::make_pair(false, false));
-
- // Additional calls to Write() have no effect.
- ASSERT_EQ(OnWebRtcEventLogWrite(key.render_process_id, key.lid, "ignored"),
- std::make_pair(false, false));
-
- ExpectLocalFileContents(*file_path, "");
-}
-
-TEST_F(WebRtcEventLogManagerTest, LocalLogSanityOverUnlimitedFileSizes) {
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
-
- base::Optional<base::FilePath> file_path;
- ON_CALL(local_observer_, OnLocalLogStarted(key, _))
- .WillByDefault(Invoke(SaveFilePathTo(&file_path)));
-
- ASSERT_TRUE(EnableLocalLogging(kWebRtcEventLogManagerUnlimitedFileSize));
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- ASSERT_TRUE(file_path);
- ASSERT_FALSE(file_path->empty());
-
- const std::string log1 = "Who let the dogs out?";
- const std::string log2 = "Woof, woof, woof, woof, woof!";
- ASSERT_EQ(OnWebRtcEventLogWrite(key.render_process_id, key.lid, log1),
- std::make_pair(true, false));
- ASSERT_EQ(OnWebRtcEventLogWrite(key.render_process_id, key.lid, log2),
- std::make_pair(true, false));
-
- // Make sure the file would be closed, so that we could safely read it.
- ASSERT_TRUE(PeerConnectionRemoved(key.render_process_id, key.lid));
-
- ExpectLocalFileContents(*file_path, log1 + log2);
-}
-
-TEST_F(WebRtcEventLogManagerTest, LocalLogNoWriteAfterLogStopped) {
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
-
- base::Optional<base::FilePath> file_path;
- ON_CALL(local_observer_, OnLocalLogStarted(key, _))
- .WillByDefault(Invoke(SaveFilePathTo(&file_path)));
-
- ASSERT_TRUE(EnableLocalLogging());
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- ASSERT_TRUE(file_path);
- ASSERT_FALSE(file_path->empty());
-
- const std::string log_before = "log_before_stop";
- ASSERT_EQ(OnWebRtcEventLogWrite(key.render_process_id, key.lid, log_before),
- std::make_pair(true, false));
- EXPECT_CALL(local_observer_, OnLocalLogStopped(key)).Times(1);
- ASSERT_TRUE(PeerConnectionRemoved(key.render_process_id, key.lid));
-
- const std::string log_after = "log_after_stop";
- ASSERT_EQ(OnWebRtcEventLogWrite(key.render_process_id, key.lid, log_after),
- std::make_pair(false, false));
-
- ExpectLocalFileContents(*file_path, log_before);
-}
-
-TEST_F(WebRtcEventLogManagerTest, LocalLogOnlyWritesTheLogsAfterStarted) {
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
-
- // Calls to Write() before the log was started are ignored.
- EXPECT_CALL(local_observer_, OnLocalLogStarted(_, _)).Times(0);
- const std::string log1 = "The lights begin to twinkle from the rocks:";
- ASSERT_EQ(OnWebRtcEventLogWrite(key.render_process_id, key.lid, log1),
- std::make_pair(false, false));
- ASSERT_TRUE(base::IsDirectoryEmpty(local_logs_base_dir_));
-
- base::Optional<base::FilePath> file_path;
- EXPECT_CALL(local_observer_, OnLocalLogStarted(key, _))
- .Times(1)
- .WillOnce(Invoke(SaveFilePathTo(&file_path)));
-
- ASSERT_TRUE(EnableLocalLogging());
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- ASSERT_TRUE(file_path);
- ASSERT_FALSE(file_path->empty());
-
- // Calls after the log started have an effect. The calls to Write() from
- // before the log started are not remembered.
- const std::string log2 = "The long day wanes: the slow moon climbs: the deep";
- ASSERT_EQ(OnWebRtcEventLogWrite(key.render_process_id, key.lid, log2),
- std::make_pair(true, false));
-
- // Make sure the file would be closed, so that we could safely read it.
- ASSERT_TRUE(PeerConnectionRemoved(rph_->GetID(), kPeerConnectionId));
-
- ExpectLocalFileContents(*file_path, log2);
-}
-
-// Note: This test also covers the scenario LocalLogExistingFilesNotOverwritten,
-// which is therefore not explicitly tested.
-TEST_F(WebRtcEventLogManagerTest, LocalLoggingRestartCreatesNewFile) {
- const std::vector<std::string> logs = {"<setup>", "<punchline>", "<encore>"};
- std::vector<base::Optional<PeerConnectionKey>> keys(logs.size());
- std::vector<base::Optional<base::FilePath>> file_paths(logs.size());
-
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
-
- for (size_t i = 0; i < logs.size(); i++) {
- ON_CALL(local_observer_, OnLocalLogStarted(_, _))
- .WillByDefault(Invoke(SaveKeyAndFilePathTo(&keys[i], &file_paths[i])));
- ASSERT_TRUE(EnableLocalLogging());
- ASSERT_TRUE(keys[i]);
- ASSERT_EQ(*keys[i], GetPeerConnectionKey(rph_.get(), kPeerConnectionId));
- ASSERT_TRUE(file_paths[i]);
- ASSERT_FALSE(file_paths[i]->empty());
- ASSERT_EQ(OnWebRtcEventLogWrite(rph_->GetID(), kPeerConnectionId, logs[i]),
- std::make_pair(true, false));
- ASSERT_TRUE(DisableLocalLogging());
- }
-
- for (size_t i = 0; i < logs.size(); i++) {
- ExpectLocalFileContents(*file_paths[i], logs[i]);
- }
-}
-
-TEST_F(WebRtcEventLogManagerTest, LocalLogMultipleActiveFiles) {
- ASSERT_TRUE(EnableLocalLogging());
-
- std::list<MockRenderProcessHost> rphs;
- for (size_t i = 0; i < 3; i++) {
- rphs.emplace_back(browser_context_.get());
- };
-
- std::vector<PeerConnectionKey> keys;
- for (auto& rph : rphs) {
- keys.push_back(GetPeerConnectionKey(&rph, kPeerConnectionId));
- }
-
- std::vector<base::Optional<base::FilePath>> file_paths(keys.size());
- for (size_t i = 0; i < keys.size(); i++) {
- ON_CALL(local_observer_, OnLocalLogStarted(keys[i], _))
- .WillByDefault(Invoke(SaveFilePathTo(&file_paths[i])));
- ASSERT_TRUE(PeerConnectionAdded(keys[i].render_process_id, keys[i].lid));
- ASSERT_TRUE(file_paths[i]);
- ASSERT_FALSE(file_paths[i]->empty());
- }
-
- std::vector<std::string> logs;
- for (size_t i = 0; i < keys.size(); i++) {
- logs.emplace_back(std::to_string(rph_->GetID()) +
- std::to_string(kPeerConnectionId));
- ASSERT_EQ(
- OnWebRtcEventLogWrite(keys[i].render_process_id, keys[i].lid, logs[i]),
- std::make_pair(true, false));
- }
-
- // Make sure the file woulds be closed, so that we could safely read them.
- ASSERT_TRUE(DisableLocalLogging());
-
- for (size_t i = 0; i < keys.size(); i++) {
- ExpectLocalFileContents(*file_paths[i], logs[i]);
- }
-}
-
-TEST_F(WebRtcEventLogManagerTest, LocalLogLimitActiveLocalLogFiles) {
- ASSERT_TRUE(EnableLocalLogging());
-
- const int kMaxLocalLogFiles =
- static_cast<int>(kMaxNumberLocalWebRtcEventLogFiles);
- for (int i = 0; i < kMaxLocalLogFiles; i++) {
- const auto key = GetPeerConnectionKey(rph_.get(), i);
- EXPECT_CALL(local_observer_, OnLocalLogStarted(key, _)).Times(1);
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), i));
- }
-
- EXPECT_CALL(local_observer_, OnLocalLogStarted(_, _)).Times(0);
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kMaxLocalLogFiles));
-}
-
-// When a log reaches its maximum size limit, it is closed, and no longer
-// counted towards the limit.
-TEST_F(WebRtcEventLogManagerTest, LocalLogFilledLogNotCountedTowardsLogsLimit) {
- const std::string log = "very_short_log";
- ASSERT_TRUE(EnableLocalLogging(log.size()));
-
- const int kMaxLocalLogFiles =
- static_cast<int>(kMaxNumberLocalWebRtcEventLogFiles);
- for (int i = 0; i < kMaxLocalLogFiles; i++) {
- const auto key = GetPeerConnectionKey(rph_.get(), i);
- EXPECT_CALL(local_observer_, OnLocalLogStarted(key, _)).Times(1);
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- }
-
- // By writing to one of the logs, we fill it and end up closing it, allowing
- // an additional log to be written.
- EXPECT_EQ(OnWebRtcEventLogWrite(rph_->GetID(), 0, log),
- std::make_pair(true, false));
-
- // We now have room for one additional log.
- const auto last_key = GetPeerConnectionKey(rph_.get(), kMaxLocalLogFiles);
- EXPECT_CALL(local_observer_, OnLocalLogStarted(last_key, _)).Times(1);
- ASSERT_TRUE(PeerConnectionAdded(last_key.render_process_id, last_key.lid));
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- LocalLogForRemovedPeerConnectionNotCountedTowardsLogsLimit) {
- ASSERT_TRUE(EnableLocalLogging());
-
- const int kMaxLocalLogFiles =
- static_cast<int>(kMaxNumberLocalWebRtcEventLogFiles);
- for (int i = 0; i < kMaxLocalLogFiles; i++) {
- const auto key = GetPeerConnectionKey(rph_.get(), i);
- EXPECT_CALL(local_observer_, OnLocalLogStarted(key, _)).Times(1);
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- }
-
- // When one peer connection is removed, one log is stopped, thereby allowing
- // an additional log to be opened.
- EXPECT_CALL(local_observer_,
- OnLocalLogStopped(GetPeerConnectionKey(rph_.get(), 0)))
- .Times(1);
- ASSERT_TRUE(PeerConnectionRemoved(rph_->GetID(), 0));
-
- // We now have room for one additional log.
- const auto last_key = GetPeerConnectionKey(rph_.get(), kMaxLocalLogFiles);
- EXPECT_CALL(local_observer_, OnLocalLogStarted(last_key, _)).Times(1);
- ASSERT_TRUE(PeerConnectionAdded(last_key.render_process_id, last_key.lid));
-}
-
-TEST_F(WebRtcEventLogManagerTest, LocalLogSanityDestructorWithActiveFile) {
- // We don't actually test that the file was closed, because this behavior
- // is not supported - WebRtcEventLogManager's destructor may never be called,
- // except for in unit tests.
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
- ASSERT_TRUE(EnableLocalLogging());
- DestroyUnitUnderTest(); // Explicitly show destruction does not crash.
-}
-
-TEST_F(WebRtcEventLogManagerTest, LocalLogIllegalPath) {
- // Since the log file won't be properly opened, these will not be called.
- EXPECT_CALL(local_observer_, OnLocalLogStarted(_, _)).Times(0);
- EXPECT_CALL(local_observer_, OnLocalLogStopped(_)).Times(0);
-
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
-
- // See the documentation of the function for why |true| is expected despite
- // the path being illegal.
- const base::FilePath illegal_path(FILE_PATH_LITERAL(":!@#$%|`^&*\\/"));
- EXPECT_TRUE(EnableLocalLogging(illegal_path));
-
- EXPECT_TRUE(base::IsDirectoryEmpty(local_logs_base_dir_));
-}
-
-#if defined(OS_POSIX) && !defined(OS_FUCHSIA)
-TEST_F(WebRtcEventLogManagerTest, LocalLogLegalPathWithoutPermissionsSanity) {
- RemoveWritePermissionsFromDirectory(local_logs_base_dir_);
-
- // Since the log file won't be properly opened, these will not be called.
- EXPECT_CALL(local_observer_, OnLocalLogStarted(_, _)).Times(0);
- EXPECT_CALL(local_observer_, OnLocalLogStopped(_)).Times(0);
-
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
-
- // See the documentation of the function for why |true| is expected despite
- // the path being illegal.
- EXPECT_TRUE(EnableLocalLogging(local_logs_base_path_));
-
- EXPECT_TRUE(base::IsDirectoryEmpty(local_logs_base_dir_));
-
- // Write() has no effect (but is handled gracefully).
- EXPECT_EQ(OnWebRtcEventLogWrite(rph_->GetID(), kPeerConnectionId,
- "Why did the chicken cross the road?"),
- std::make_pair(false, false));
- EXPECT_TRUE(base::IsDirectoryEmpty(local_logs_base_dir_));
-
- // Logging was enabled, even if it had no effect because of the lacking
- // permissions; therefore, the operation of disabling it makes sense.
- EXPECT_TRUE(DisableLocalLogging());
- EXPECT_TRUE(base::IsDirectoryEmpty(local_logs_base_dir_));
-}
-#endif // defined(OS_POSIX) && !defined(OS_FUCHSIA)
-
-TEST_F(WebRtcEventLogManagerTest, LocalLogEmptyStringHandledGracefully) {
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
-
- // By writing a log after the empty string, we show that no odd behavior is
- // encountered, such as closing the file (an actual bug from WebRTC).
- const std::vector<std::string> logs = {"<setup>", "", "<encore>"};
-
- base::Optional<base::FilePath> file_path;
-
- ON_CALL(local_observer_, OnLocalLogStarted(key, _))
- .WillByDefault(Invoke(SaveFilePathTo(&file_path)));
- ASSERT_TRUE(EnableLocalLogging());
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- ASSERT_TRUE(file_path);
- ASSERT_FALSE(file_path->empty());
-
- for (size_t i = 0; i < logs.size(); i++) {
- ASSERT_EQ(OnWebRtcEventLogWrite(key.render_process_id, key.lid, logs[i]),
- std::make_pair(true, false));
- }
- ASSERT_TRUE(DisableLocalLogging());
-
- ExpectLocalFileContents(
- *file_path,
- std::accumulate(std::begin(logs), std::end(logs), std::string()));
-}
-
-TEST_F(WebRtcEventLogManagerTest, LocalLogFilenameMatchesExpectedFormat) {
- using StringType = base::FilePath::StringType;
-
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
-
- base::Optional<base::FilePath> file_path;
- ON_CALL(local_observer_, OnLocalLogStarted(key, _))
- .WillByDefault(Invoke(SaveFilePathTo(&file_path)));
-
- const base::Time::Exploded frozen_time_exploded{
- 2017, // Four digit year "2007"
- 9, // 1-based month (values 1 = January, etc.)
- 3, // 0-based day of week (0 = Sunday, etc.)
- 6, // 1-based day of month (1-31)
- 10, // Hour within the current day (0-23)
- 43, // Minute within the current hour (0-59)
- 29, // Second within the current minute.
- 0 // Milliseconds within the current second (0-999)
- };
- ASSERT_TRUE(frozen_time_exploded.HasValidValues());
- FreezeClockAt(frozen_time_exploded);
-
- const StringType user_defined = FILE_PATH_LITERAL("user_defined");
- const base::FilePath local_logs_base_path =
- local_logs_base_dir_.Append(user_defined);
-
- ASSERT_TRUE(EnableLocalLogging(local_logs_base_path));
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- ASSERT_TRUE(file_path);
- ASSERT_FALSE(file_path->empty());
-
- // [user_defined]_[date]_[time]_[render_process_id]_[lid].log
- const StringType date = FILE_PATH_LITERAL("20170906");
- const StringType time = FILE_PATH_LITERAL("1043");
- base::FilePath expected_path = local_logs_base_path;
- expected_path = local_logs_base_path.InsertBeforeExtension(
- FILE_PATH_LITERAL("_") + date + FILE_PATH_LITERAL("_") + time +
- FILE_PATH_LITERAL("_") + IntToStringType(rph_->GetID()) +
- FILE_PATH_LITERAL("_") + IntToStringType(kPeerConnectionId));
- expected_path = expected_path.AddExtension(FILE_PATH_LITERAL("log"));
-
- EXPECT_EQ(file_path, expected_path);
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- LocalLogFilenameMatchesExpectedFormatRepeatedFilename) {
- using StringType = base::FilePath::StringType;
-
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
-
- base::Optional<base::FilePath> file_path_1;
- base::Optional<base::FilePath> file_path_2;
- EXPECT_CALL(local_observer_, OnLocalLogStarted(key, _))
- .WillOnce(Invoke(SaveFilePathTo(&file_path_1)))
- .WillOnce(Invoke(SaveFilePathTo(&file_path_2)));
-
- const base::Time::Exploded frozen_time_exploded{
- 2017, // Four digit year "2007"
- 9, // 1-based month (values 1 = January, etc.)
- 3, // 0-based day of week (0 = Sunday, etc.)
- 6, // 1-based day of month (1-31)
- 10, // Hour within the current day (0-23)
- 43, // Minute within the current hour (0-59)
- 29, // Second within the current minute.
- 0 // Milliseconds within the current second (0-999)
- };
- ASSERT_TRUE(frozen_time_exploded.HasValidValues());
- FreezeClockAt(frozen_time_exploded);
-
- const StringType user_defined_portion = FILE_PATH_LITERAL("user_defined");
- const base::FilePath local_logs_base_path =
- local_logs_base_dir_.Append(user_defined_portion);
-
- ASSERT_TRUE(EnableLocalLogging(local_logs_base_path));
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- ASSERT_TRUE(file_path_1);
- ASSERT_FALSE(file_path_1->empty());
-
- // [user_defined]_[date]_[time]_[render_process_id]_[lid].log
- const StringType date = FILE_PATH_LITERAL("20170906");
- const StringType time = FILE_PATH_LITERAL("1043");
- base::FilePath expected_path_1 = local_logs_base_path;
- expected_path_1 = local_logs_base_path.InsertBeforeExtension(
- FILE_PATH_LITERAL("_") + date + FILE_PATH_LITERAL("_") + time +
- FILE_PATH_LITERAL("_") + IntToStringType(rph_->GetID()) +
- FILE_PATH_LITERAL("_") + IntToStringType(kPeerConnectionId));
- expected_path_1 = expected_path_1.AddExtension(FILE_PATH_LITERAL("log"));
-
- ASSERT_EQ(file_path_1, expected_path_1);
-
- ASSERT_TRUE(DisableLocalLogging());
- ASSERT_TRUE(EnableLocalLogging(local_logs_base_path));
- ASSERT_TRUE(file_path_2);
- ASSERT_FALSE(file_path_2->empty());
-
- const base::FilePath expected_path_2 =
- expected_path_1.InsertBeforeExtension(FILE_PATH_LITERAL(" (1)"));
-
- // Focus of the test - starting the same log again produces a new file,
- // with an expected new filename.
- ASSERT_EQ(file_path_2, expected_path_2);
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- OnRemoteLogStartedNotCalledIfRemoteLoggingNotEnabled) {
- EXPECT_CALL(remote_observer_, OnRemoteLogStarted(_, _)).Times(0);
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- OnRemoteLogStoppedNotCalledIfRemoteLoggingNotEnabled) {
- EXPECT_CALL(remote_observer_, OnRemoteLogStopped(_)).Times(0);
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- ASSERT_TRUE(PeerConnectionRemoved(key.render_process_id, key.lid));
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- OnRemoteLogStartedCalledIfRemoteLoggingEnabled) {
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
- EXPECT_CALL(remote_observer_, OnRemoteLogStarted(key, _)).Times(1);
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- ASSERT_TRUE(StartRemoteLogging(key.render_process_id, key.lid));
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- OnRemoteLogStoppedCalledIfRemoteLoggingEnabledThenPcRemoved) {
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
- EXPECT_CALL(remote_observer_, OnRemoteLogStopped(key)).Times(1);
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- ASSERT_TRUE(StartRemoteLogging(key.render_process_id, key.lid));
- ASSERT_TRUE(PeerConnectionRemoved(key.render_process_id, key.lid));
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- BrowserContextInitializationCreatesDirectoryForRemoteLogs) {
- auto browser_context = CreateBrowserContext();
- const base::FilePath remote_logs_path =
- GetLogsDirectoryPath(browser_context->GetPath());
- EXPECT_TRUE(base::DirectoryExists(remote_logs_path));
- EXPECT_TRUE(base::IsDirectoryEmpty(remote_logs_path));
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- StartRemoteLoggingReturnsFalseIfUnknownPeerConnection) {
- EXPECT_FALSE(StartRemoteLogging(rph_->GetID(), kPeerConnectionId));
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- StartRemoteLoggingReturnsTrueIfKnownPeerConnection) {
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
- EXPECT_TRUE(StartRemoteLogging(rph_->GetID(), kPeerConnectionId));
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- StartRemoteLoggingReturnsFalseIfRestartAttempt) {
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
- ASSERT_TRUE(StartRemoteLogging(rph_->GetID(), kPeerConnectionId));
- EXPECT_FALSE(StartRemoteLogging(rph_->GetID(), kPeerConnectionId));
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- StartRemoteLoggingReturnsFalseIfUnlimitedFileSize) {
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
- EXPECT_FALSE(StartRemoteLogging(rph_->GetID(), kPeerConnectionId,
- kWebRtcEventLogManagerUnlimitedFileSize));
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- StartRemoteLoggingReturnsFalseIfPeerConnectionAlreadyClosed) {
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
- ASSERT_TRUE(PeerConnectionRemoved(rph_->GetID(), kPeerConnectionId));
- EXPECT_FALSE(StartRemoteLogging(rph_->GetID(), kPeerConnectionId));
-}
-
-TEST_F(WebRtcEventLogManagerTest, StartRemoteLoggingCreatesEmptyFile) {
- base::Optional<base::FilePath> file_path;
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
- EXPECT_CALL(remote_observer_, OnRemoteLogStarted(key, _))
- .Times(1)
- .WillOnce(Invoke(SaveFilePathTo(&file_path)));
-
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
- ASSERT_TRUE(StartRemoteLogging(rph_->GetID(), kPeerConnectionId));
-
- ExpectRemoteFileContents(*file_path, "");
-}
-
-TEST_F(WebRtcEventLogManagerTest, RemoteLogFileCreatedInCorrectDirectory) {
- // Set up separate browser contexts; each one will get one log.
- constexpr size_t kLogsNum = 3;
- std::unique_ptr<TestBrowserContext> browser_contexts[kLogsNum] = {
- CreateBrowserContext(), CreateBrowserContext(), CreateBrowserContext()};
- std::vector<std::unique_ptr<MockRenderProcessHost>> rphs;
- for (auto& browser_context : browser_contexts) {
- rphs.emplace_back(
- std::make_unique<MockRenderProcessHost>(browser_context.get()));
- }
-
- // Prepare to store the logs' paths in distinct memory locations.
- base::Optional<base::FilePath> file_paths[kLogsNum];
- for (size_t i = 0; i < kLogsNum; i++) {
- const auto key = GetPeerConnectionKey(rphs[i].get(), kPeerConnectionId);
- EXPECT_CALL(remote_observer_, OnRemoteLogStarted(key, _))
- .Times(1)
- .WillOnce(Invoke(SaveFilePathTo(&file_paths[i])));
- }
-
- // Start one log for each browser context.
- for (const auto& rph : rphs) {
- ASSERT_TRUE(PeerConnectionAdded(rph->GetID(), kPeerConnectionId));
- ASSERT_TRUE(StartRemoteLogging(rph->GetID(), kPeerConnectionId));
- }
-
- // All log files must be created in their own context's directory.
- for (size_t i = 0; i < arraysize(browser_contexts); i++) {
- ASSERT_TRUE(file_paths[i]);
- EXPECT_TRUE(browser_contexts[i]->GetPath().IsParent(*file_paths[i]));
- }
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- OnWebRtcEventLogWriteWritesToTheRemoteBoundFile) {
- base::Optional<base::FilePath> file_path;
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
- EXPECT_CALL(remote_observer_, OnRemoteLogStarted(key, _))
- .Times(1)
- .WillOnce(Invoke(SaveFilePathTo(&file_path)));
-
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
- ASSERT_TRUE(StartRemoteLogging(rph_->GetID(), kPeerConnectionId));
-
- const char* const log = "1 + 1 = 3";
- EXPECT_EQ(OnWebRtcEventLogWrite(rph_->GetID(), kPeerConnectionId, log),
- std::make_pair(false, true));
-
- ExpectRemoteFileContents(*file_path, log);
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- RemoteBoundLogWithZeroLengthMetadataWrittenCorrectly) {
- base::Optional<base::FilePath> file_path;
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
- EXPECT_CALL(remote_observer_, OnRemoteLogStarted(key, _))
- .Times(1)
- .WillOnce(Invoke(SaveFilePathTo(&file_path)));
-
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
-
- const std::string metadata = "";
- ASSERT_TRUE(StartRemoteLogging(key.render_process_id, key.lid, metadata));
-
- const char* const output = "WebRTC event log";
- EXPECT_EQ(OnWebRtcEventLogWrite(key.render_process_id, key.lid, output),
- std::make_pair(false, true));
-
- ExpectRemoteFileContents(*file_path, output, metadata);
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- RemoteBoundLogWithNonZeroLengthMetadataWrittenCorrectly) {
- base::Optional<base::FilePath> file_path;
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
- EXPECT_CALL(remote_observer_, OnRemoteLogStarted(key, _))
- .Times(1)
- .WillOnce(Invoke(SaveFilePathTo(&file_path)));
-
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
-
- const std::string metadata = "metadata";
- ASSERT_TRUE(StartRemoteLogging(key.render_process_id, key.lid, metadata));
-
- const char* const output = "WebRTC event log";
- EXPECT_EQ(OnWebRtcEventLogWrite(key.render_process_id, key.lid, output),
- std::make_pair(false, true));
-
- ExpectRemoteFileContents(*file_path, output, metadata);
-}
-
-// The scenario RemoteBoundLogWithMaximumSizeLessThanMetadataDisallowed is
-// subcase of this one, and therefore not explicitly tested.
-TEST_F(WebRtcEventLogManagerTest,
- RemoteBoundLogMetadataMustLeaveSomeRoomForWebRtcEventLog) {
- EXPECT_CALL(remote_observer_, OnRemoteLogStarted(_, _)).Times(0);
- EXPECT_CALL(remote_observer_, OnRemoteLogStopped(_)).Times(0);
-
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
-
- const std::string metadata = "metadata";
- const size_t max_log_size =
- kRemoteBoundLogFileHeaderSizeBytes + metadata.length();
- ASSERT_FALSE(StartRemoteLogging(key.render_process_id, key.lid, max_log_size,
- metadata));
-}
-
-TEST_F(WebRtcEventLogManagerTest, WriteToBothLocalAndRemoteFiles) {
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
-
- base::Optional<base::FilePath> local_path;
- EXPECT_CALL(local_observer_, OnLocalLogStarted(key, _))
- .Times(1)
- .WillOnce(Invoke(SaveFilePathTo(&local_path)));
-
- base::Optional<base::FilePath> remote_path;
- EXPECT_CALL(remote_observer_, OnRemoteLogStarted(key, _))
- .Times(1)
- .WillOnce(Invoke(SaveFilePathTo(&remote_path)));
-
- ASSERT_TRUE(EnableLocalLogging());
- ASSERT_TRUE(StartRemoteLogging(key.render_process_id, key.lid));
-
- ASSERT_TRUE(local_path);
- ASSERT_FALSE(local_path->empty());
- ASSERT_TRUE(remote_path);
- ASSERT_FALSE(remote_path->empty());
-
- const char* const log = "logloglog";
- ASSERT_EQ(OnWebRtcEventLogWrite(key.render_process_id, key.lid, log),
- std::make_pair(true, true));
-
- // Ensure the flushing of the file to disk before attempting to read them.
- ASSERT_TRUE(PeerConnectionRemoved(key.render_process_id, key.lid));
-
- ExpectLocalFileContents(*local_path, log);
- ExpectRemoteFileContents(*remote_path, log);
-}
-
-TEST_F(WebRtcEventLogManagerTest, MultipleWritesToSameRemoteBoundLogfile) {
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
-
- base::Optional<base::FilePath> file_path;
- ON_CALL(remote_observer_, OnRemoteLogStarted(key, _))
- .WillByDefault(Invoke(SaveFilePathTo(&file_path)));
-
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- ASSERT_TRUE(StartRemoteLogging(key.render_process_id, key.lid));
- ASSERT_TRUE(file_path);
- ASSERT_FALSE(file_path->empty());
-
- const std::string logs[] = {"ABC", "DEF", "XYZ"};
- for (const std::string& log : logs) {
- ASSERT_EQ(OnWebRtcEventLogWrite(key.render_process_id, key.lid, log),
- std::make_pair(false, true));
- }
-
- // Make sure the file would be closed, so that we could safely read it.
- ASSERT_TRUE(PeerConnectionRemoved(key.render_process_id, key.lid));
-
- ExpectRemoteFileContents(
- *file_path,
- std::accumulate(std::begin(logs), std::end(logs), std::string()));
-}
-
-TEST_F(WebRtcEventLogManagerTest, RemoteLogFileSizeLimitNotExceeded) {
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
- base::Optional<base::FilePath> file_path;
- ON_CALL(remote_observer_, OnRemoteLogStarted(key, _))
- .WillByDefault(Invoke(SaveFilePathTo(&file_path)));
-
- const std::string log = "tpyo";
- const size_t file_size_limit_bytes =
- kRemoteBoundLogFileHeaderSizeBytes + (log.length() / 2);
-
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- ASSERT_TRUE(StartRemoteLogging(key.render_process_id, key.lid,
- file_size_limit_bytes));
-
- // Failure is reported, because not everything could be written. The file
- // will also be closed.
- EXPECT_CALL(remote_observer_, OnRemoteLogStopped(key)).Times(1);
- ASSERT_EQ(OnWebRtcEventLogWrite(key.render_process_id, key.lid, log),
- std::make_pair(false, false));
-
- // Additional calls to Write() have no effect.
- ASSERT_EQ(OnWebRtcEventLogWrite(key.render_process_id, key.lid, "ignored"),
- std::make_pair(false, false));
-
- ExpectRemoteFileContents(*file_path, "");
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- LogMultipleActiveRemoteLogsSameBrowserContext) {
- const std::vector<PeerConnectionKey> keys = {
- GetPeerConnectionKey(rph_.get(), 0), GetPeerConnectionKey(rph_.get(), 1),
- GetPeerConnectionKey(rph_.get(), 2)};
-
- std::vector<base::Optional<base::FilePath>> file_paths(keys.size());
- for (size_t i = 0; i < keys.size(); i++) {
- ON_CALL(remote_observer_, OnRemoteLogStarted(keys[i], _))
- .WillByDefault(Invoke(SaveFilePathTo(&file_paths[i])));
- ASSERT_TRUE(PeerConnectionAdded(keys[i].render_process_id, keys[i].lid));
- ASSERT_TRUE(StartRemoteLogging(keys[i].render_process_id, keys[i].lid));
- ASSERT_TRUE(file_paths[i]);
- ASSERT_FALSE(file_paths[i]->empty());
- }
-
- std::vector<std::string> logs;
- for (size_t i = 0; i < keys.size(); i++) {
- logs.emplace_back(std::to_string(rph_->GetID()) + std::to_string(i));
- ASSERT_EQ(
- OnWebRtcEventLogWrite(keys[i].render_process_id, keys[i].lid, logs[i]),
- std::make_pair(false, true));
- }
-
- // Make sure the file woulds be closed, so that we could safely read them.
- for (auto& key : keys) {
- ASSERT_TRUE(PeerConnectionRemoved(key.render_process_id, key.lid));
- }
-
- for (size_t i = 0; i < keys.size(); i++) {
- ExpectRemoteFileContents(*file_paths[i], logs[i]);
- }
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- LogMultipleActiveRemoteLogsDifferentBrowserContexts) {
- constexpr size_t kLogsNum = 3;
- std::unique_ptr<TestBrowserContext> browser_contexts[kLogsNum] = {
- CreateBrowserContext(), CreateBrowserContext(), CreateBrowserContext()};
- std::vector<std::unique_ptr<MockRenderProcessHost>> rphs;
- for (auto& browser_context : browser_contexts) {
- rphs.emplace_back(
- std::make_unique<MockRenderProcessHost>(browser_context.get()));
- }
-
- std::vector<PeerConnectionKey> keys;
- for (auto& rph : rphs) {
- keys.push_back(GetPeerConnectionKey(rph.get(), kPeerConnectionId));
- }
-
- std::vector<base::Optional<base::FilePath>> file_paths(keys.size());
- for (size_t i = 0; i < keys.size(); i++) {
- ON_CALL(remote_observer_, OnRemoteLogStarted(keys[i], _))
- .WillByDefault(Invoke(SaveFilePathTo(&file_paths[i])));
- ASSERT_TRUE(PeerConnectionAdded(keys[i].render_process_id, keys[i].lid));
- ASSERT_TRUE(StartRemoteLogging(keys[i].render_process_id, keys[i].lid));
- ASSERT_TRUE(file_paths[i]);
- ASSERT_FALSE(file_paths[i]->empty());
- }
-
- std::vector<std::string> logs;
- for (size_t i = 0; i < keys.size(); i++) {
- logs.emplace_back(std::to_string(rph_->GetID()) + std::to_string(i));
- ASSERT_EQ(
- OnWebRtcEventLogWrite(keys[i].render_process_id, keys[i].lid, logs[i]),
- std::make_pair(false, true));
- }
-
- // Make sure the file woulds be closed, so that we could safely read them.
- for (auto& key : keys) {
- ASSERT_TRUE(PeerConnectionRemoved(key.render_process_id, key.lid));
- }
-
- for (size_t i = 0; i < keys.size(); i++) {
- ExpectRemoteFileContents(*file_paths[i], logs[i]);
- }
-}
-
-TEST_F(WebRtcEventLogManagerTest, DifferentRemoteLogsMayHaveDifferentMaximums) {
- const std::string logs[2] = {"abra", "cadabra"};
- std::vector<base::Optional<base::FilePath>> file_paths(arraysize(logs));
- std::vector<PeerConnectionKey> keys;
- for (size_t i = 0; i < arraysize(logs); i++) {
- keys.push_back(GetPeerConnectionKey(rph_.get(), i));
- ON_CALL(remote_observer_, OnRemoteLogStarted(keys[i], _))
- .WillByDefault(Invoke(SaveFilePathTo(&file_paths[i])));
- }
-
- for (size_t i = 0; i < keys.size(); i++) {
- ASSERT_TRUE(PeerConnectionAdded(keys[i].render_process_id, keys[i].lid));
- ASSERT_TRUE(StartRemoteLogging(
- keys[i].render_process_id, keys[i].lid,
- kRemoteBoundLogFileHeaderSizeBytes + logs[i].length()));
- }
-
- for (size_t i = 0; i < keys.size(); i++) {
- // The write is successful, but the file closed, indicating that the maximum
- // file size has been reached.
- EXPECT_CALL(remote_observer_, OnRemoteLogStopped(keys[i])).Times(1);
- ASSERT_EQ(
- OnWebRtcEventLogWrite(keys[i].render_process_id, keys[i].lid, logs[i]),
- std::make_pair(false, true));
- ASSERT_TRUE(file_paths[i]);
- ExpectRemoteFileContents(*file_paths[i], logs[i]);
- }
-}
-
-TEST_F(WebRtcEventLogManagerTest, RemoteLogFileClosedWhenCapacityReached) {
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
- base::Optional<base::FilePath> file_path;
- ON_CALL(remote_observer_, OnRemoteLogStarted(key, _))
- .WillByDefault(Invoke(SaveFilePathTo(&file_path)));
-
- const std::string log = "Let X equal X.";
-
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- ASSERT_TRUE(
- StartRemoteLogging(key.render_process_id, key.lid,
- kRemoteBoundLogFileHeaderSizeBytes + log.length()));
- ASSERT_TRUE(file_path);
-
- EXPECT_CALL(remote_observer_, OnRemoteLogStopped(key)).Times(1);
- EXPECT_EQ(OnWebRtcEventLogWrite(key.render_process_id, key.lid, log),
- std::make_pair(false, true));
-}
-
-#if defined(OS_POSIX) && !defined(OS_FUCHSIA)
-// TODO(eladalon): Add unit tests for lacking read permissions when looking
-// to upload the file. https://crbug.com/775415
-TEST_F(WebRtcEventLogManagerTest,
- FailureToCreateRemoteLogsDirHandledGracefully) {
- base::ScopedTempDir browser_context_dir;
- ASSERT_TRUE(browser_context_dir.CreateUniqueTempDir());
- RemoveWritePermissionsFromDirectory(browser_context_dir.GetPath());
-
- // Graceful handling by BrowserContext::EnableForBrowserContext.
- auto browser_context = CreateBrowserContext(browser_context_dir.Take());
- const base::FilePath remote_logs_path =
- GetLogsDirectoryPath(browser_context->GetPath());
- EXPECT_FALSE(base::DirectoryExists(remote_logs_path));
-
- auto rph = std::make_unique<MockRenderProcessHost>(browser_context.get());
-
- // Graceful handling of PeerConnectionAdded: True returned because the
- // remote-logs' manager can still safely reason about the state of peer
- // connections even if one of its browser contexts is defective.)
- EXPECT_TRUE(PeerConnectionAdded(rph->GetID(), kPeerConnectionId));
-
- // Graceful handling of StartRemoteLogging: False returned because it's
- // impossible to write the log to a file.
- EXPECT_FALSE(StartRemoteLogging(rph->GetID(), kPeerConnectionId));
-
- // Graceful handling of OnWebRtcEventLogWrite: False returned because the log
- // could not be written at all, let alone in its entirety.
- const char* const log = "This is not a log.";
- EXPECT_EQ(OnWebRtcEventLogWrite(rph->GetID(), kPeerConnectionId, log),
- std::make_pair(false, false));
-
- // Graceful handling of PeerConnectionRemoved: True returned because the
- // remote-logs' manager can still safely reason about the state of peer
- // connections even if one of its browser contexts is defective.
- EXPECT_TRUE(PeerConnectionRemoved(rph->GetID(), kPeerConnectionId));
-}
-
-TEST_F(WebRtcEventLogManagerTest, GracefullyHandleFailureToStartRemoteLogFile) {
- // WebRTC logging will not be turned on.
- EXPECT_CALL(remote_observer_, OnRemoteLogStarted(_, _)).Times(0);
- EXPECT_CALL(remote_observer_, OnRemoteLogStopped(_)).Times(0);
-
- // Set up a BrowserContext whose directory we know, so that we would be
- // able to manipulate it.
- base::ScopedTempDir browser_context_dir;
- ASSERT_TRUE(browser_context_dir.CreateUniqueTempDir());
- auto browser_context = CreateBrowserContext(browser_context_dir.Take());
- auto rph = std::make_unique<MockRenderProcessHost>(browser_context.get());
-
- // Remove write permissions from the directory.
- const base::FilePath remote_logs_path =
- GetLogsDirectoryPath(browser_context->GetPath());
- ASSERT_TRUE(base::DirectoryExists(remote_logs_path));
- RemoveWritePermissionsFromDirectory(remote_logs_path);
-
- // StartRemoteLogging() will now fail.
- const auto key = GetPeerConnectionKey(rph.get(), kPeerConnectionId);
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- EXPECT_FALSE(StartRemoteLogging(key.render_process_id, key.lid));
- EXPECT_EQ(OnWebRtcEventLogWrite(key.render_process_id, key.lid, "abc"),
- std::make_pair(false, false));
- EXPECT_TRUE(base::IsDirectoryEmpty(remote_logs_path));
-}
-#endif // defined(OS_POSIX) && !defined(OS_FUCHSIA)
-
-TEST_F(WebRtcEventLogManagerTest, RemoteLogLimitActiveLogFiles) {
- for (int i = 0; i < kMaxActiveRemoteLogFiles + 1; i++) {
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), i));
- }
-
- int i;
- for (i = 0; i < kMaxActiveRemoteLogFiles; i++) {
- EXPECT_CALL(remote_observer_,
- OnRemoteLogStarted(GetPeerConnectionKey(rph_.get(), i), _))
- .Times(1);
- ASSERT_TRUE(StartRemoteLogging(rph_->GetID(), i));
- }
-
- EXPECT_CALL(remote_observer_, OnRemoteLogStarted(_, _)).Times(0);
- EXPECT_FALSE(StartRemoteLogging(rph_->GetID(), i));
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- RemoteLogFilledLogNotCountedTowardsLogsLimit) {
- const std::string log = "very_short_log";
-
- int i;
- for (i = 0; i < kMaxActiveRemoteLogFiles; i++) {
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), i));
- EXPECT_CALL(remote_observer_,
- OnRemoteLogStarted(GetPeerConnectionKey(rph_.get(), i), _))
- .Times(1);
- ASSERT_TRUE(StartRemoteLogging(
- rph_->GetID(), i, kRemoteBoundLogFileHeaderSizeBytes + log.length()));
- }
-
- // By writing to one of the logs until it reaches capacity, we fill it,
- // causing it to close, therefore allowing an additional log.
- EXPECT_EQ(OnWebRtcEventLogWrite(rph_->GetID(), 0, log),
- std::make_pair(false, true));
-
- // We now have room for one additional log.
- ++i;
- EXPECT_CALL(remote_observer_,
- OnRemoteLogStarted(GetPeerConnectionKey(rph_.get(), i), _))
- .Times(1);
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), i));
- ASSERT_TRUE(StartRemoteLogging(rph_->GetID(), i));
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- RemoteLogForRemovedPeerConnectionNotCountedTowardsLogsLimit) {
- for (int i = 0; i < kMaxActiveRemoteLogFiles; i++) {
- const auto key = GetPeerConnectionKey(rph_.get(), i);
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- EXPECT_CALL(remote_observer_, OnRemoteLogStarted(key, _)).Times(1);
- ASSERT_TRUE(StartRemoteLogging(key.render_process_id, key.lid));
- }
-
- // By removing a peer connection associated with one of the logs, we allow
- // an additional log.
- ASSERT_TRUE(PeerConnectionRemoved(rph_->GetID(), 0));
-
- // We now have room for one additional log.
- const auto last_key =
- GetPeerConnectionKey(rph_.get(), kMaxActiveRemoteLogFiles);
- EXPECT_CALL(remote_observer_, OnRemoteLogStarted(last_key, _)).Times(1);
- ASSERT_TRUE(PeerConnectionAdded(last_key.render_process_id, last_key.lid));
- ASSERT_TRUE(StartRemoteLogging(last_key.render_process_id, last_key.lid));
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- ActiveLogsForBrowserContextCountedTowardsItsPendingsLogsLimit) {
- SuppressUploading();
-
- // Produce kMaxPendingRemoteLogFiles pending logs.
- for (int i = 0; i < kMaxPendingRemoteLogFiles; i++) {
- const auto key = GetPeerConnectionKey(rph_.get(), i);
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- ASSERT_TRUE(StartRemoteLogging(key.render_process_id, key.lid));
- ASSERT_TRUE(PeerConnectionRemoved(key.render_process_id, key.lid));
- }
-
- // It is now impossible to start another *active* log for that BrowserContext,
- // because we have too many pending logs (and active logs become pending
- // once completed).
- const auto forbidden =
- GetPeerConnectionKey(rph_.get(), kMaxPendingRemoteLogFiles);
- ASSERT_TRUE(PeerConnectionAdded(forbidden.render_process_id, forbidden.lid));
- EXPECT_FALSE(StartRemoteLogging(forbidden.render_process_id, forbidden.lid));
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- ObserveLimitOnMaximumPendingLogsPerBrowserContext) {
- // Keep one active peer connection on an independent BrowserContext in order
- // to suppress uploading of pending files during this test.
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), 1));
-
- // Create additional BrowserContexts for the test.
- std::unique_ptr<TestBrowserContext> browser_contexts[2] = {
- std::make_unique<TestBrowserContext>(),
- std::make_unique<TestBrowserContext>()};
- std::unique_ptr<MockRenderProcessHost> rphs[2] = {
- std::make_unique<MockRenderProcessHost>(browser_contexts[0].get()),
- std::make_unique<MockRenderProcessHost>(browser_contexts[1].get())};
-
- // Allowed to start kMaxPendingRemoteLogFiles for each BrowserContext.
- for (int i = 0; i < kMaxPendingRemoteLogFiles; i++) {
- const auto key = GetPeerConnectionKey(rphs[0].get(), i);
- // The log could be opened:
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- ASSERT_TRUE(StartRemoteLogging(key.render_process_id, key.lid));
- // The log changes state from ACTIVE to PENDING:
- EXPECT_TRUE(PeerConnectionRemoved(key.render_process_id, key.lid));
- }
-
- // Not allowed to start any more remote-bound logs for that BrowserContext.
- ASSERT_TRUE(PeerConnectionAdded(rphs[0]->GetID(), kMaxPendingRemoteLogFiles));
- EXPECT_FALSE(StartRemoteLogging(rphs[0]->GetID(), kMaxPendingRemoteLogFiles));
-
- // Other BrowserContexts aren't limit by the previous one's limit.
- ASSERT_TRUE(PeerConnectionAdded(rphs[1]->GetID(), 0));
- EXPECT_TRUE(StartRemoteLogging(rphs[1]->GetID(), 0));
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- LogsFromPreviousSessionBecomePendingLogsWhenBrowserContextInitialized) {
- // Create a directory and seed it with log files, simulating the creation
- // of logs in a previous session.
- std::list<base::FilePath> expected_files;
- base::ScopedTempDir browser_context_dir;
- ASSERT_TRUE(browser_context_dir.CreateUniqueTempDir());
-
- const base::FilePath remote_logs_dir =
- GetLogsDirectoryPath(browser_context_dir.GetPath());
- ASSERT_TRUE(CreateDirectory(remote_logs_dir));
-
- for (size_t i = 0; i < kMaxPendingRemoteBoundWebRtcEventLogs; i++) {
- const base::FilePath file_path =
- remote_logs_dir.Append(IntToStringType(i))
- .AddExtension(kRemoteBoundLogExtension);
- constexpr int file_flags = base::File::FLAG_CREATE |
- base::File::FLAG_WRITE |
- base::File::FLAG_EXCLUSIVE_WRITE;
- base::File file(file_path, file_flags);
- ASSERT_TRUE(file.IsValid() && file.created());
- expected_files.push_back(file_path);
- }
-
- // This factory enforces the expectation that the files will be uploaded,
- // all of them, only them, and in the order expected.
- base::RunLoop run_loop;
- SetWebRtcEventLogUploaderFactoryForTesting(
- std::make_unique<FileListExpectingWebRtcEventLogUploader::Factory>(
- &expected_files, true, &run_loop));
-
- auto browser_context = CreateBrowserContext(browser_context_dir.Take());
- auto rph = std::make_unique<MockRenderProcessHost>(browser_context.get());
-
- WaitForPendingTasks(&run_loop);
-}
-
-TEST_P(WebRtcEventLogManagerTest, FinishedRemoteLogsUploadedAndFileDeleted) {
- // |upload_result| show that the files are deleted independent of the
- // upload's success / failure.
- const bool upload_result = GetParam();
-
- const auto key = GetPeerConnectionKey(rph_.get(), 1);
- base::Optional<base::FilePath> log_file;
- ON_CALL(remote_observer_, OnRemoteLogStarted(key, _))
- .WillByDefault(Invoke(SaveFilePathTo(&log_file)));
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- ASSERT_TRUE(StartRemoteLogging(key.render_process_id, key.lid));
- ASSERT_TRUE(log_file);
-
- base::RunLoop run_loop;
- std::list<base::FilePath> expected_files = {*log_file};
- SetWebRtcEventLogUploaderFactoryForTesting(
- std::make_unique<FileListExpectingWebRtcEventLogUploader::Factory>(
- &expected_files, upload_result, &run_loop));
-
- ASSERT_TRUE(PeerConnectionRemoved(key.render_process_id, key.lid));
-
- const base::FilePath remote_logs_path =
- GetLogsDirectoryPath(browser_context_->GetPath());
- EXPECT_TRUE(base::IsDirectoryEmpty(remote_logs_path));
-}
-
-// Note that SuppressUploading() and UnSuppressUploading() use the behavior
-// guaranteed by this test.
-TEST_F(WebRtcEventLogManagerTest, UploadOnlyWhenNoActivePeerConnections) {
- const auto untracked = GetPeerConnectionKey(rph_.get(), 0);
- const auto tracked = GetPeerConnectionKey(rph_.get(), 1);
-
- // Suppresses the uploading of the "tracked" peer connection's log.
- ASSERT_TRUE(PeerConnectionAdded(untracked.render_process_id, untracked.lid));
-
- // The tracked peer connection's log is not uploaded when finished, because
- // another peer connection is still active.
- base::Optional<base::FilePath> log_file;
- ON_CALL(remote_observer_, OnRemoteLogStarted(tracked, _))
- .WillByDefault(Invoke(SaveFilePathTo(&log_file)));
- ASSERT_TRUE(PeerConnectionAdded(tracked.render_process_id, tracked.lid));
- ASSERT_TRUE(StartRemoteLogging(tracked.render_process_id, tracked.lid));
- ASSERT_TRUE(log_file);
- ASSERT_TRUE(PeerConnectionRemoved(tracked.render_process_id, tracked.lid));
-
- // Perform another action synchronously, so that we may be assured that the
- // observer's lack of callbacks was not a timing fluke.
- OnWebRtcEventLogWrite(untracked.render_process_id, untracked.lid, "Ook!");
-
- // Having been convinced that |tracked|'s log was not uploded while
- // |untracked| was active, close |untracked| and see that |tracked|'s log
- // is now uploaded.
- base::RunLoop run_loop;
- std::list<base::FilePath> expected_uploads = {*log_file};
- SetWebRtcEventLogUploaderFactoryForTesting(
- std::make_unique<FileListExpectingWebRtcEventLogUploader::Factory>(
- &expected_uploads, true, &run_loop));
- ASSERT_TRUE(
- PeerConnectionRemoved(untracked.render_process_id, untracked.lid));
-
- WaitForPendingTasks(&run_loop);
-}
-
-TEST_F(WebRtcEventLogManagerTest, UploadOrderDependsOnLastModificationTime) {
- SuppressUploading();
-
- // Create three directories and seed them with log files.
- base::FilePath browser_context_paths[3];
- base::FilePath file_paths[3];
- for (size_t i = 0; i < 3; i++) {
- base::ScopedTempDir browser_context_dir;
- ASSERT_TRUE(browser_context_dir.CreateUniqueTempDir());
- browser_context_paths[i] = browser_context_dir.Take();
-
- const base::FilePath remote_logs_dir =
- GetLogsDirectoryPath(browser_context_paths[i]);
- ASSERT_TRUE(CreateDirectory(remote_logs_dir));
-
- file_paths[i] = remote_logs_dir.AppendASCII("file").AddExtension(
- kRemoteBoundLogExtension);
- constexpr int file_flags = base::File::FLAG_CREATE |
- base::File::FLAG_WRITE |
- base::File::FLAG_EXCLUSIVE_WRITE;
- base::File file(file_paths[i], file_flags);
- ASSERT_TRUE(file.IsValid() && file.created());
- }
-
- // Touch() requires setting the last access time as well. Keep it the same
- // for all files, showing that the difference between them lies elsewhere.
- base::File::Info file_info;
- ASSERT_TRUE(base::GetFileInfo(file_paths[0], &file_info));
- const base::Time shared_last_accessed = file_info.last_accessed;
-
- // Set the files' last modification time according to a non-trivial
- // permutation (not the order of creation or its reverse).
- const size_t permutation[3] = {2, 0, 1};
- std::list<base::FilePath> expected_files;
- base::Time mod_time = base::Time::Now() - base::TimeDelta::FromSeconds(3);
- for (size_t i = 0; i < 3; i++) {
- mod_time += base::TimeDelta::FromSeconds(1); // Back to the future.
- const base::FilePath& path = file_paths[permutation[i]];
- ASSERT_TRUE(base::TouchFile(path, shared_last_accessed, mod_time));
- expected_files.emplace_back(path);
- }
-
- // Recognize the files as pending files by initializing their BrowserContexts.
- std::unique_ptr<TestBrowserContext> browser_contexts[3];
- std::unique_ptr<MockRenderProcessHost> rphs[3];
- for (size_t i = 0; i < 3; i++) {
- browser_contexts[i] = CreateBrowserContext(browser_context_paths[i]);
- rphs[i] =
- std::make_unique<MockRenderProcessHost>(browser_contexts[i].get());
- }
-
- // Show that the files are uploaded by order of modification.
- base::RunLoop run_loop;
- SetWebRtcEventLogUploaderFactoryForTesting(
- std::make_unique<FileListExpectingWebRtcEventLogUploader::Factory>(
- &expected_files, true, &run_loop));
-
- UnsuppressUploading();
-
- WaitForPendingTasks(&run_loop);
-}
-
-TEST_F(WebRtcEventLogManagerTest, ExpiredFilesArePrunedRatherThanUploaded) {
- SuppressUploading();
-
- constexpr size_t kExpired = 0;
- constexpr size_t kFresh = 1;
- DCHECK_GE(kMaxPendingRemoteBoundWebRtcEventLogs, 2u)
- << "Please restructure the test to use separate browser contexts.";
-
- base::FilePath browser_context_path;
- base::FilePath file_paths[2];
- base::ScopedTempDir browser_context_dir;
- ASSERT_TRUE(browser_context_dir.CreateUniqueTempDir());
- browser_context_path = browser_context_dir.Take();
-
- const base::FilePath remote_logs_dir =
- GetLogsDirectoryPath(browser_context_path);
- ASSERT_TRUE(CreateDirectory(remote_logs_dir));
-
- for (size_t i = 0; i < 2; i++) {
- file_paths[i] = remote_logs_dir.Append(IntToStringType(i))
- .AddExtension(kRemoteBoundLogExtension);
- constexpr int file_flags = base::File::FLAG_CREATE |
- base::File::FLAG_WRITE |
- base::File::FLAG_EXCLUSIVE_WRITE;
- base::File file(file_paths[i], file_flags);
- ASSERT_TRUE(file.IsValid() && file.created());
- }
-
- // Touch() requires setting the last access time as well. Keep it current,
- // showing that only the last modification time matters.
- base::File::Info file_info;
- ASSERT_TRUE(base::GetFileInfo(file_paths[0], &file_info));
-
- // Set the expired file's last modification time to past max retention.
- const base::Time expired_mod_time = base::Time::Now() -
- kRemoteBoundWebRtcEventLogsMaxRetention -
- base::TimeDelta::FromSeconds(1);
- ASSERT_TRUE(base::TouchFile(file_paths[kExpired], file_info.last_accessed,
- expired_mod_time));
-
- // Recognize the file as pending by initializing its BrowserContext.
- std::unique_ptr<TestBrowserContext> browser_context;
- browser_context = CreateBrowserContext(browser_context_path);
-
- // Show that the expired file is not uploaded.
- base::RunLoop run_loop;
- std::list<base::FilePath> expected_files = {file_paths[kFresh]};
- SetWebRtcEventLogUploaderFactoryForTesting(
- std::make_unique<FileListExpectingWebRtcEventLogUploader::Factory>(
- &expected_files, true, &run_loop));
-
- UnsuppressUploading();
-
- WaitForPendingTasks(&run_loop);
-
- // Both the uploaded file as well as the expired file have no been removed
- // from local disk.
- EXPECT_TRUE(
- base::IsDirectoryEmpty(GetLogsDirectoryPath(browser_context->GetPath())));
-}
-
-// TODO(eladalon): Add a test showing that a file expiring while another
-// is being uploaded, is not uploaded after the current upload is completed.
-// This is significant because Chrome might stay up for a long time.
-// https://crbug.com/775415
-
-TEST_F(WebRtcEventLogManagerTest, RemoteLogSanityDestructorWithActiveFile) {
- // We don't actually test that the file was closed, because this behavior
- // is not supported - WebRtcEventLogManager's destructor may never be called,
- // except for in unit tests.
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
- ASSERT_TRUE(PeerConnectionRemoved(rph_->GetID(), kPeerConnectionId));
- DestroyUnitUnderTest(); // Explicitly show destruction does not crash.
-}
-
-TEST_F(WebRtcEventLogManagerTest, RemoteLogEmptyStringHandledGracefully) {
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
-
- // By writing a log after the empty string, we show that no odd behavior is
- // encountered, such as closing the file (an actual bug from WebRTC).
- const std::vector<std::string> logs = {"<setup>", "", "<encore>"};
-
- base::Optional<base::FilePath> file_path;
-
- ON_CALL(remote_observer_, OnRemoteLogStarted(key, _))
- .WillByDefault(Invoke(SaveFilePathTo(&file_path)));
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- ASSERT_TRUE(StartRemoteLogging(key.render_process_id, key.lid));
- ASSERT_TRUE(file_path);
- ASSERT_FALSE(file_path->empty());
-
- for (size_t i = 0; i < logs.size(); i++) {
- ASSERT_EQ(OnWebRtcEventLogWrite(key.render_process_id, key.lid, logs[i]),
- std::make_pair(false, true));
- }
- ASSERT_TRUE(PeerConnectionRemoved(key.render_process_id, key.lid));
-
- ExpectRemoteFileContents(
- *file_path,
- std::accumulate(std::begin(logs), std::end(logs), std::string()));
-}
-
-#if defined(OS_POSIX) && !defined(OS_FUCHSIA)
-TEST_F(WebRtcEventLogManagerTest,
- UnopenedRemoteLogFilesNotCountedTowardsActiveLogsLimit) {
- // Set up BrowserContexts whose directories we know, so that we would be
- // able to manipulate them.
- std::unique_ptr<TestBrowserContext> browser_contexts[2];
- std::unique_ptr<MockRenderProcessHost> rphs[2];
- for (size_t i = 0; i < 2; i++) {
- base::ScopedTempDir browser_context_dir;
- ASSERT_TRUE(browser_context_dir.CreateUniqueTempDir());
- browser_contexts[i] = CreateBrowserContext(browser_context_dir.Take());
- rphs[i] =
- std::make_unique<MockRenderProcessHost>(browser_contexts[i].get());
- }
-
- constexpr size_t without_permissions = 0;
- constexpr size_t with_permissions = 1;
-
- // Remove write permissions from one directory.
- const base::FilePath permissions_lacking_remote_logs_path =
- GetLogsDirectoryPath(browser_contexts[without_permissions]->GetPath());
- ASSERT_TRUE(base::DirectoryExists(permissions_lacking_remote_logs_path));
- RemoveWritePermissionsFromDirectory(permissions_lacking_remote_logs_path);
-
- // Fail to start a log associated with the permission-lacking directory.
- ASSERT_TRUE(PeerConnectionAdded(rphs[without_permissions]->GetID(), 0));
- ASSERT_FALSE(StartRemoteLogging(rphs[without_permissions]->GetID(), 0));
-
- // Show that this was not counted towards the limit of active files.
- for (int i = 0; i < kMaxActiveRemoteLogFiles; i++) {
- ASSERT_TRUE(PeerConnectionAdded(rphs[with_permissions]->GetID(), i));
- EXPECT_TRUE(StartRemoteLogging(rphs[with_permissions]->GetID(), i));
- }
-}
-#endif // defined(OS_POSIX) && !defined(OS_FUCHSIA)
-
-TEST_F(WebRtcEventLogManagerTest,
- NoStartWebRtcSendingEventLogsWhenLocalEnabledWithoutPeerConnection) {
- SetPeerConnectionTrackerProxyForTesting(
- std::make_unique<PeerConnectionTrackerProxyForTesting>(this));
- ASSERT_TRUE(EnableLocalLogging());
- EXPECT_TRUE(webrtc_state_change_instructions_.empty());
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- NoStartWebRtcSendingEventLogsWhenPeerConnectionButNoLoggingEnabled) {
- SetPeerConnectionTrackerProxyForTesting(
- std::make_unique<PeerConnectionTrackerProxyForTesting>(this));
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
- EXPECT_TRUE(webrtc_state_change_instructions_.empty());
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- StartWebRtcSendingEventLogsWhenLocalEnabledThenPeerConnectionAdded) {
- SetPeerConnectionTrackerProxyForTesting(
- std::make_unique<PeerConnectionTrackerProxyForTesting>(this));
- ASSERT_TRUE(EnableLocalLogging());
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
- ExpectWebRtcStateChangeInstruction(rph_->GetID(), kPeerConnectionId, true);
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- StartWebRtcSendingEventLogsWhenPeerConnectionAddedThenLocalEnabled) {
- SetPeerConnectionTrackerProxyForTesting(
- std::make_unique<PeerConnectionTrackerProxyForTesting>(this));
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
- ASSERT_TRUE(EnableLocalLogging());
- ExpectWebRtcStateChangeInstruction(rph_->GetID(), kPeerConnectionId, true);
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- StartWebRtcSendingEventLogsWhenRemoteLoggingEnabled) {
- SetPeerConnectionTrackerProxyForTesting(
- std::make_unique<PeerConnectionTrackerProxyForTesting>(this));
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
- ASSERT_TRUE(StartRemoteLogging(rph_->GetID(), kPeerConnectionId));
- ExpectWebRtcStateChangeInstruction(rph_->GetID(), kPeerConnectionId, true);
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- InstructWebRtcToStopSendingEventLogsWhenLocalLoggingStopped) {
- // Setup
- SetPeerConnectionTrackerProxyForTesting(
- std::make_unique<PeerConnectionTrackerProxyForTesting>(this));
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
- ASSERT_TRUE(EnableLocalLogging());
- ExpectWebRtcStateChangeInstruction(rph_->GetID(), kPeerConnectionId, true);
-
- // Test
- ASSERT_TRUE(DisableLocalLogging());
- ExpectWebRtcStateChangeInstruction(rph_->GetID(), kPeerConnectionId, false);
-}
-
-// #1 - Local logging was the cause of the logs.
-TEST_F(WebRtcEventLogManagerTest,
- InstructWebRtcToStopSendingEventLogsWhenPeerConnectionRemoved1) {
- // Setup
- SetPeerConnectionTrackerProxyForTesting(
- std::make_unique<PeerConnectionTrackerProxyForTesting>(this));
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
- ASSERT_TRUE(EnableLocalLogging());
- ExpectWebRtcStateChangeInstruction(rph_->GetID(), kPeerConnectionId, true);
-
- // Test
- ASSERT_TRUE(PeerConnectionRemoved(rph_->GetID(), kPeerConnectionId));
- ExpectWebRtcStateChangeInstruction(rph_->GetID(), kPeerConnectionId, false);
-}
-
-// #2 - Remote logging was the cause of the logs.
-TEST_F(WebRtcEventLogManagerTest,
- InstructWebRtcToStopSendingEventLogsWhenPeerConnectionRemoved2) {
- // Setup
- SetPeerConnectionTrackerProxyForTesting(
- std::make_unique<PeerConnectionTrackerProxyForTesting>(this));
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
- ASSERT_TRUE(StartRemoteLogging(rph_->GetID(), kPeerConnectionId));
- ExpectWebRtcStateChangeInstruction(rph_->GetID(), kPeerConnectionId, true);
-
- // Test
- ASSERT_TRUE(PeerConnectionRemoved(rph_->GetID(), kPeerConnectionId));
- ExpectWebRtcStateChangeInstruction(rph_->GetID(), kPeerConnectionId, false);
-}
-
-// #1 - Local logging added first.
-TEST_F(WebRtcEventLogManagerTest,
- SecondLoggingTargetDoesNotInitiateWebRtcLogging1) {
- // Setup
- SetPeerConnectionTrackerProxyForTesting(
- std::make_unique<PeerConnectionTrackerProxyForTesting>(this));
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
- ASSERT_TRUE(EnableLocalLogging());
- ExpectWebRtcStateChangeInstruction(rph_->GetID(), kPeerConnectionId, true);
-
- // Test
- ASSERT_TRUE(StartRemoteLogging(rph_->GetID(), kPeerConnectionId));
- EXPECT_TRUE(webrtc_state_change_instructions_.empty());
-}
-
-// #2 - Remote logging added first.
-TEST_F(WebRtcEventLogManagerTest,
- SecondLoggingTargetDoesNotInitiateWebRtcLogging2) {
- // Setup
- SetPeerConnectionTrackerProxyForTesting(
- std::make_unique<PeerConnectionTrackerProxyForTesting>(this));
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
- ASSERT_TRUE(StartRemoteLogging(rph_->GetID(), kPeerConnectionId));
- ExpectWebRtcStateChangeInstruction(rph_->GetID(), kPeerConnectionId, true);
-
- // Test
- ASSERT_TRUE(EnableLocalLogging());
- EXPECT_TRUE(webrtc_state_change_instructions_.empty());
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- DisablingLocalLoggingWhenRemoteLoggingEnabledDoesNotStopWebRtcLogging) {
- // Setup
- SetPeerConnectionTrackerProxyForTesting(
- std::make_unique<PeerConnectionTrackerProxyForTesting>(this));
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
- ASSERT_TRUE(EnableLocalLogging());
- ASSERT_TRUE(StartRemoteLogging(rph_->GetID(), kPeerConnectionId));
- ExpectWebRtcStateChangeInstruction(rph_->GetID(), kPeerConnectionId, true);
-
- // Test
- ASSERT_TRUE(DisableLocalLogging());
- EXPECT_TRUE(webrtc_state_change_instructions_.empty());
-
- // Cleanup
- ASSERT_TRUE(PeerConnectionRemoved(rph_->GetID(), kPeerConnectionId));
- ExpectWebRtcStateChangeInstruction(rph_->GetID(), kPeerConnectionId, false);
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- DisablingLocalLoggingAfterPcRemovalHasNoEffectOnWebRtcLogging) {
- // Setup
- SetPeerConnectionTrackerProxyForTesting(
- std::make_unique<PeerConnectionTrackerProxyForTesting>(this));
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
- ASSERT_TRUE(EnableLocalLogging());
- ASSERT_TRUE(StartRemoteLogging(rph_->GetID(), kPeerConnectionId));
- ExpectWebRtcStateChangeInstruction(rph_->GetID(), kPeerConnectionId, true);
-
- // Test
- ASSERT_TRUE(PeerConnectionRemoved(rph_->GetID(), kPeerConnectionId));
- ExpectWebRtcStateChangeInstruction(rph_->GetID(), kPeerConnectionId, false);
- ASSERT_TRUE(DisableLocalLogging());
- EXPECT_TRUE(webrtc_state_change_instructions_.empty());
-}
-
-// Once a peer connection with a given key was removed, it may not again be
-// added. But, if this impossible case occurs, WebRtcEventLogManager will
-// not crash.
-TEST_F(WebRtcEventLogManagerTest, SanityOverRecreatingTheSamePeerConnection) {
- ASSERT_TRUE(EnableLocalLogging());
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
- ASSERT_TRUE(StartRemoteLogging(rph_->GetID(), kPeerConnectionId));
- OnWebRtcEventLogWrite(rph_->GetID(), kPeerConnectionId, "log1");
- ASSERT_TRUE(PeerConnectionRemoved(rph_->GetID(), kPeerConnectionId));
- ASSERT_TRUE(PeerConnectionAdded(rph_->GetID(), kPeerConnectionId));
- OnWebRtcEventLogWrite(rph_->GetID(), kPeerConnectionId, "log2");
-}
-
-// The logs would typically be binary. However, the other tests only cover ASCII
-// characters, for readability. This test shows that this is not a problem.
-TEST_F(WebRtcEventLogManagerTest, LogAllPossibleCharacters) {
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
-
- base::Optional<base::FilePath> local_log_file_path;
- ON_CALL(local_observer_, OnLocalLogStarted(key, _))
- .WillByDefault(Invoke(SaveFilePathTo(&local_log_file_path)));
-
- base::Optional<base::FilePath> remote_log_file_path;
- ON_CALL(remote_observer_, OnRemoteLogStarted(key, _))
- .WillByDefault(Invoke(SaveFilePathTo(&remote_log_file_path)));
-
- ASSERT_TRUE(EnableLocalLogging());
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- ASSERT_TRUE(StartRemoteLogging(key.render_process_id, key.lid));
- ASSERT_TRUE(local_log_file_path);
- ASSERT_FALSE(local_log_file_path->empty());
- ASSERT_TRUE(remote_log_file_path);
- ASSERT_FALSE(remote_log_file_path->empty());
-
- std::string all_chars;
- for (size_t i = 0; i < 256; i++) {
- all_chars += static_cast<uint8_t>(i);
- }
- ASSERT_EQ(OnWebRtcEventLogWrite(key.render_process_id, key.lid, all_chars),
- std::make_pair(true, true));
-
- // Make sure the file would be closed, so that we could safely read it.
- ASSERT_TRUE(PeerConnectionRemoved(key.render_process_id, key.lid));
-
- ExpectLocalFileContents(*local_log_file_path, all_chars);
- ExpectRemoteFileContents(*remote_log_file_path, all_chars);
-}
-
-TEST_F(WebRtcEventLogManagerTest, LocalLogsClosedWhenRenderProcessHostExits) {
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- ASSERT_TRUE(EnableLocalLogging());
-
- // The expectation for OnLocalLogStopped() will be saturated by this
- // destruction of the RenderProcessHost, which triggers an implicit
- // removal of all PeerConnections associated with it.
- EXPECT_CALL(local_observer_, OnLocalLogStopped(key)).Times(1);
- rph_.reset();
-}
-
-TEST_F(WebRtcEventLogManagerTest, RemoteLogsClosedWhenRenderProcessHostExits) {
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- ASSERT_TRUE(StartRemoteLogging(key.render_process_id, key.lid));
-
- // The expectation for OnRemoteLogStopped() will be saturated by this
- // destruction of the RenderProcessHost, which triggers an implicit
- // removal of all PeerConnections associated with it.
- EXPECT_CALL(remote_observer_, OnRemoteLogStopped(key)).Times(1);
- rph_.reset();
-}
-
-// Once a RenderProcessHost exits/crashes, its PeerConnections are removed,
-// which means that they can no longer suppress an upload.
-TEST_F(WebRtcEventLogManagerTest,
- RenderProcessHostExitCanRemoveUploadSuppression) {
- SuppressUploading();
-
- const auto key = GetPeerConnectionKey(rph_.get(), kPeerConnectionId);
- base::Optional<base::FilePath> file_path;
- ON_CALL(remote_observer_, OnRemoteLogStarted(key, _))
- .WillByDefault(Invoke(SaveFilePathTo(&file_path)));
-
- ASSERT_TRUE(PeerConnectionAdded(key.render_process_id, key.lid));
- ASSERT_TRUE(StartRemoteLogging(key.render_process_id, key.lid));
- ASSERT_TRUE(PeerConnectionRemoved(key.render_process_id, key.lid));
- ASSERT_TRUE(file_path);
- ASSERT_FALSE(file_path->empty());
-
- // The above removal is not sufficient to trigger an upload (so the test will
- // not be flaky). It's only once we destroy the RPH with which the suppressing
- // PeerConnection is associated, that upload will take place.
- base::RunLoop run_loop;
- std::list<base::FilePath> expected_files = {*file_path};
- SetWebRtcEventLogUploaderFactoryForTesting(
- std::make_unique<FileListExpectingWebRtcEventLogUploader::Factory>(
- &expected_files, true, &run_loop));
-
- // We destroy the RPH without explicitly removing its PeerConnection (unlike
- // a call to UnsuppressUploading()).
- upload_suppressing_rph_.reset();
-
- WaitForPendingTasks(&run_loop);
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- PeerConnectionAddedOverDestroyedRphReturnsFalse) {
- const int render_process_id = rph_->GetID();
- rph_.reset();
- EXPECT_FALSE(PeerConnectionAdded(render_process_id, kPeerConnectionId));
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- PeerConnectionRemovedOverDestroyedRphReturnsFalse) {
- const int render_process_id = rph_->GetID();
-
- // Setup - make sure the |false| returned by the function being tested is
- // related to the RPH being dead, and not due other restrictions.
- ASSERT_TRUE(PeerConnectionAdded(render_process_id, kPeerConnectionId));
-
- // Test
- rph_.reset();
- EXPECT_FALSE(PeerConnectionRemoved(render_process_id, kPeerConnectionId));
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- PeerConnectionStoppedOverDestroyedRphReturnsFalse) {
- const int render_process_id = rph_->GetID();
-
- // Setup - make sure the |false| returned by the function being tested is
- // related to the RPH being dead, and not due other restrictions.
- ASSERT_TRUE(PeerConnectionAdded(render_process_id, kPeerConnectionId));
-
- // Test
- rph_.reset();
- EXPECT_FALSE(PeerConnectionStopped(render_process_id, kPeerConnectionId));
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- StartRemoteLoggingOverDestroyedRphReturnsFalse) {
- const int render_process_id = rph_->GetID();
-
- // Setup - make sure the |false| returned by the function being tested is
- // related to the RPH being dead, and not due other restrictions.
- ASSERT_TRUE(PeerConnectionAdded(render_process_id, kPeerConnectionId));
-
- // Test
- rph_.reset();
- EXPECT_FALSE(StartRemoteLogging(render_process_id, kPeerConnectionId));
-}
-
-TEST_F(WebRtcEventLogManagerTest,
- OnWebRtcEventLogWriteOverDestroyedRphReturnsFalseAndFalse) {
- const int render_process_id = rph_->GetID();
-
- // Setup - make sure the |false| returned by the function being tested is
- // related to the RPH being dead, and not due other restrictions.
- ASSERT_TRUE(PeerConnectionAdded(render_process_id, kPeerConnectionId));
- ASSERT_TRUE(EnableLocalLogging());
-
- // Test
- rph_.reset();
- EXPECT_EQ(OnWebRtcEventLogWrite(render_process_id, kPeerConnectionId, "log"),
- std::make_pair(false, false));
-}
-
-INSTANTIATE_TEST_CASE_P(UploadCompleteResult,
- WebRtcEventLogManagerTest,
- ::testing::Values(false, true));
-
-} // namespace content
diff --git a/chromium/content/browser/webrtc/webrtc_event_log_uploader.cc b/chromium/content/browser/webrtc/webrtc_event_log_uploader.cc
deleted file mode 100644
index 634dc442980..00000000000
--- a/chromium/content/browser/webrtc/webrtc_event_log_uploader.cc
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright (c) 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/webrtc/webrtc_event_log_uploader.h"
-
-#include "base/files/file_util.h"
-#include "base/logging.h"
-
-namespace content {
-
-WebRtcEventLogUploaderImpl::WebRtcEventLogUploaderImpl(
- const base::FilePath& path,
- WebRtcEventLogUploaderObserver* observer) {
- DCHECK(observer);
-
- // TODO(eladalon): Provide an actual implementation; really upload the file.
- // https://crbug.com/775415
-
- // If the upload was successful, the file is no longer needed.
- // If the upload failed, we don't want to retry, because we run the risk of
- // uploading significant amounts of data once again, only for the upload to
- // fail again after (as an example) wasting 50MBs of upload bandwidth.
- const bool deletion_successful = base::DeleteFile(path, /*recursive=*/false);
- if (!deletion_successful) {
- // This is a somewhat serious (though unlikely) error, because now we'll try
- // to upload this file again next time Chrome launches.
- LOG(ERROR) << "Could not delete pending log file.";
- }
-
- // TODO(eladalon): Provide actual success/failure of upload.
- // https://crbug.com/775415
- observer->OnWebRtcEventLogUploadComplete(path, true);
-}
-
-std::unique_ptr<WebRtcEventLogUploader>
-WebRtcEventLogUploaderImpl::Factory::Create(
- const base::FilePath& log_file,
- WebRtcEventLogUploaderObserver* observer) {
- return std::make_unique<WebRtcEventLogUploaderImpl>(log_file, observer);
-}
-
-} // namespace content
diff --git a/chromium/content/browser/webrtc/webrtc_event_log_uploader.h b/chromium/content/browser/webrtc/webrtc_event_log_uploader.h
deleted file mode 100644
index 03b4d13fa64..00000000000
--- a/chromium/content/browser/webrtc/webrtc_event_log_uploader.h
+++ /dev/null
@@ -1,68 +0,0 @@
-// Copyright (c) 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_WEBRTC_WEBRTC_EVENT_LOG_UPLOADER_H_
-#define CONTENT_BROWSER_WEBRTC_WEBRTC_EVENT_LOG_UPLOADER_H_
-
-#include <memory>
-
-#include "base/files/file_path.h"
-
-namespace content {
-
-// A class implementing this interace can register for notification of an
-// upload's eventual result (success/failure).
-class WebRtcEventLogUploaderObserver {
- public:
- virtual void OnWebRtcEventLogUploadComplete(const base::FilePath& file_path,
- bool upload_successful) = 0;
-
- protected:
- virtual ~WebRtcEventLogUploaderObserver() = default;
-};
-
-// A sublcass of this interface would take ownership of a file, and either
-// upload it to a remote server (actual implementation), or pretend to do
-// so (in unit tests). It will typically take on an observer of type
-// WebRtcEventLogUploaderObserver, and inform it of the success or failure
-// of the upload.
-class WebRtcEventLogUploader {
- public:
- virtual ~WebRtcEventLogUploader() = default;
-
- // Since we'll need more than one instance of the abstract
- // WebRtcEventLogUploader, we'll need an abstract factory for it.
- class Factory {
- public:
- virtual ~Factory() = default;
-
- // Creates uploaders. The observer is passed to each call of Create,
- // rather than be memorized by the factory's constructor, because factories
- // created by unit tests have no visibility into the real implementation's
- // observer (WebRtcRemoteEventLogManager).
- virtual std::unique_ptr<WebRtcEventLogUploader> Create(
- const base::FilePath& log_file,
- WebRtcEventLogUploaderObserver* observer) = 0;
- };
-};
-
-class WebRtcEventLogUploaderImpl : public WebRtcEventLogUploader {
- public:
- WebRtcEventLogUploaderImpl(const base::FilePath& path,
- WebRtcEventLogUploaderObserver* observer);
- ~WebRtcEventLogUploaderImpl() override = default;
-
- class Factory : public WebRtcEventLogUploader::Factory {
- public:
- ~Factory() override = default;
-
- std::unique_ptr<WebRtcEventLogUploader> Create(
- const base::FilePath& log_file,
- WebRtcEventLogUploaderObserver* observer) override;
- };
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_WEBRTC_WEBRTC_EVENT_LOG_UPLOADER_H_
diff --git a/chromium/content/browser/webrtc/webrtc_getusermedia_browsertest.cc b/chromium/content/browser/webrtc/webrtc_getusermedia_browsertest.cc
index 3f07d2a398f..254ff38788f 100644
--- a/chromium/content/browser/webrtc/webrtc_getusermedia_browsertest.cc
+++ b/chromium/content/browser/webrtc/webrtc_getusermedia_browsertest.cc
@@ -259,16 +259,9 @@ IN_PROC_BROWSER_TEST_F(WebRtcGetUserMediaBrowserTest,
ExecuteJavascriptAndWaitForOk("getUserMediaAndClone();");
}
-// http://crbug.com/803516 : Flaky on Linux debug
-#if defined(OS_LINUX) && !defined(NDEBUG)
-#define MAYBE_RenderVideoTrackInMultipleTagsAndPause \
- DISABLED_RenderVideoTrackInMultipleTagsAndPause
-#else
-#define MAYBE_RenderVideoTrackInMultipleTagsAndPause \
- RenderVideoTrackInMultipleTagsAndPause
-#endif
+// TODO(crbug.com/803516) : Flaky on all platforms.
IN_PROC_BROWSER_TEST_F(WebRtcGetUserMediaBrowserTest,
- MAYBE_RenderVideoTrackInMultipleTagsAndPause) {
+ DISABLED_RenderVideoTrackInMultipleTagsAndPause) {
ASSERT_TRUE(embedded_test_server()->Start());
GURL url(embedded_test_server()->GetURL("/media/getusermedia.html"));
diff --git a/chromium/content/browser/webrtc/webrtc_internals.cc b/chromium/content/browser/webrtc/webrtc_internals.cc
index 857f83af3ce..eb7e04af19b 100644
--- a/chromium/content/browser/webrtc/webrtc_internals.cc
+++ b/chromium/content/browser/webrtc/webrtc_internals.cc
@@ -10,7 +10,6 @@
#include <utility>
#include "base/command_line.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/string_number_conversions.h"
#include "build/build_config.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
@@ -19,12 +18,13 @@
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/web_contents.h"
+#include "content/public/browser/webrtc_event_logger.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/service_manager_connection.h"
#include "ipc/ipc_platform_file.h"
#include "media/audio/audio_debug_recording_session.h"
#include "media/audio/audio_manager.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "services/audio/public/cpp/debug_recording_session_factory.h"
#include "services/device/public/mojom/constants.mojom.h"
#include "services/device/public/mojom/wake_lock_provider.mojom.h"
@@ -135,7 +135,10 @@ WebRTCInternals::WebRTCInternals(int aggregate_updates_ms,
if (!command_line_derived_logging_path_.empty()) {
const base::FilePath local_logs_path =
command_line_derived_logging_path_.Append(kEventLogFilename);
- WebRtcEventLogManager::GetInstance()->EnableLocalLogging(local_logs_path);
+ WebRtcEventLogger* const logger = WebRtcEventLogger::Get();
+ if (logger) {
+ logger->EnableLocalLogging(local_logs_path);
+ }
// For clarity's sake, though these aren't supposed to be regarded now:
event_log_recordings_ = true;
event_log_recordings_file_path_.clear();
@@ -381,8 +384,10 @@ void WebRTCInternals::EnableLocalEventLogRecordings(
DCHECK(CanToggleEventLogRecordings());
#if BUILDFLAG(ENABLE_WEBRTC)
#if defined(OS_ANDROID)
- WebRtcEventLogManager::GetInstance()->EnableLocalLogging(
- event_log_recordings_file_path_);
+ WebRtcEventLogger* const logger = WebRtcEventLogger::Get();
+ if (logger) {
+ logger->EnableLocalLogging(event_log_recordings_file_path_);
+ }
#else
DCHECK(web_contents);
DCHECK(!select_file_dialog_);
@@ -402,7 +407,10 @@ void WebRTCInternals::DisableLocalEventLogRecordings() {
// Tear down the dialog since the user has unchecked the event log checkbox.
select_file_dialog_ = nullptr;
DCHECK(CanToggleEventLogRecordings());
- WebRtcEventLogManager::GetInstance()->DisableLocalLogging();
+ WebRtcEventLogger* const logger = WebRtcEventLogger::Get();
+ if (logger) {
+ logger->DisableLocalLogging();
+ }
#endif
}
@@ -450,7 +458,10 @@ void WebRTCInternals::FileSelected(const base::FilePath& path,
case SelectionType::kRtcEventLogs: {
event_log_recordings_file_path_ = path;
event_log_recordings_ = true;
- WebRtcEventLogManager::GetInstance()->EnableLocalLogging(path);
+ WebRtcEventLogger* const logger = WebRtcEventLogger::Get();
+ if (logger) {
+ logger->EnableLocalLogging(path);
+ }
break;
}
case SelectionType::kAudioDebugRecordings: {
diff --git a/chromium/content/browser/webrtc/webrtc_internals.h b/chromium/content/browser/webrtc/webrtc_internals.h
index 6c00d69d0f7..04c8e2a2342 100644
--- a/chromium/content/browser/webrtc/webrtc_internals.h
+++ b/chromium/content/browser/webrtc/webrtc_internals.h
@@ -16,10 +16,9 @@
#include "base/process/process.h"
#include "base/threading/thread_checker.h"
#include "base/values.h"
-#include "content/browser/webrtc/webrtc_event_log_manager.h"
#include "content/common/content_export.h"
#include "content/public/browser/render_process_host_observer.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "services/device/public/mojom/wake_lock.mojom.h"
#include "ui/shell_dialogs/select_file_dialog.h"
@@ -39,13 +38,16 @@ class WebRTCInternalsUIObserver;
class CONTENT_EXPORT WebRTCInternals : public RenderProcessHostObserver,
public ui::SelectFileDialog::Listener {
public:
- // Ensures that no previous instantiation of the class was performed, then
- // instantiates the class and returns the object. Subsequent calls to
- // GetInstance() will return this object.
+ // * CreateSingletonInstance() ensures that no previous instantiation of the
+ // class was performed, then instantiates the class and returns the object.
+ // * GetInstance() returns the object previously constructed using
+ // CreateSingletonInstance(). It may return null in tests.
+ // * Creation is separated from access because WebRTCInternals may only be
+ // created from a context that allows blocking. If GetInstance were allowed
+ // to instantiate, as with a lazily constructed singleton, it would be
+ // difficult to guarantee that its construction is always first attempted
+ // from a context that allows it.
static WebRTCInternals* CreateSingletonInstance();
-
- // Returns the object previously constructed using CreateSingletonInstance().
- // Can be null in tests.
static WebRTCInternals* GetInstance();
~WebRTCInternals() override;
diff --git a/chromium/content/browser/webrtc/webrtc_internals_message_handler.cc b/chromium/content/browser/webrtc/webrtc_internals_message_handler.cc
index 82c50d4c1da..9f6d4fde2f7 100644
--- a/chromium/content/browser/webrtc/webrtc_internals_message_handler.cc
+++ b/chromium/content/browser/webrtc/webrtc_internals_message_handler.cc
@@ -30,35 +30,39 @@ WebRTCInternalsMessageHandler::~WebRTCInternalsMessageHandler() {
}
void WebRTCInternalsMessageHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback("getAllStats",
- base::Bind(&WebRTCInternalsMessageHandler::OnGetAllStats,
- base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "getAllStats",
+ base::BindRepeating(&WebRTCInternalsMessageHandler::OnGetAllStats,
+ base::Unretained(this)));
- web_ui()->RegisterMessageCallback("enableAudioDebugRecordings",
- base::Bind(
+ web_ui()->RegisterMessageCallback(
+ "enableAudioDebugRecordings",
+ base::BindRepeating(
&WebRTCInternalsMessageHandler::OnSetAudioDebugRecordingsEnabled,
- base::Unretained(this),
- true));
+ base::Unretained(this), true));
- web_ui()->RegisterMessageCallback("disableAudioDebugRecordings",
- base::Bind(
+ web_ui()->RegisterMessageCallback(
+ "disableAudioDebugRecordings",
+ base::BindRepeating(
&WebRTCInternalsMessageHandler::OnSetAudioDebugRecordingsEnabled,
- base::Unretained(this),
- false));
+ base::Unretained(this), false));
web_ui()->RegisterMessageCallback(
"enableEventLogRecordings",
- base::Bind(&WebRTCInternalsMessageHandler::OnSetEventLogRecordingsEnabled,
- base::Unretained(this), true));
+ base::BindRepeating(
+ &WebRTCInternalsMessageHandler::OnSetEventLogRecordingsEnabled,
+ base::Unretained(this), true));
web_ui()->RegisterMessageCallback(
"disableEventLogRecordings",
- base::Bind(&WebRTCInternalsMessageHandler::OnSetEventLogRecordingsEnabled,
- base::Unretained(this), false));
+ base::BindRepeating(
+ &WebRTCInternalsMessageHandler::OnSetEventLogRecordingsEnabled,
+ base::Unretained(this), false));
- web_ui()->RegisterMessageCallback("finishedDOMLoad",
- base::Bind(&WebRTCInternalsMessageHandler::OnDOMLoadDone,
- base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "finishedDOMLoad",
+ base::BindRepeating(&WebRTCInternalsMessageHandler::OnDOMLoadDone,
+ base::Unretained(this)));
}
RenderFrameHost* WebRTCInternalsMessageHandler::GetWebRTCInternalsHost() const {
diff --git a/chromium/content/browser/webrtc/webrtc_internals_message_handler_unittest.cc b/chromium/content/browser/webrtc/webrtc_internals_message_handler_unittest.cc
index f830440ba53..a4a4213fec1 100644
--- a/chromium/content/browser/webrtc/webrtc_internals_message_handler_unittest.cc
+++ b/chromium/content/browser/webrtc/webrtc_internals_message_handler_unittest.cc
@@ -12,6 +12,7 @@
#include "content/browser/webrtc/webrtc_internals.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/url_constants.h"
+#include "content/public/test/navigation_simulator.h"
#include "content/public/test/test_web_ui.h"
#include "content/test/test_web_contents.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -77,7 +78,9 @@ TEST_F(WebRtcInternalsMessageHandlerTest, DontRunJSBeforeNavigationCommitted) {
kConstraints);
base::RunLoop().RunUntilIdle();
- static_cast<TestWebContents*>(web_contents())->StartNavigation(webrtc_url);
+ auto navigation = content::NavigationSimulator::CreateBrowserInitiated(
+ webrtc_url, web_contents());
+ navigation->Start();
// We still shouldn't run JS, since navigation to webrtc-internals isn't
// finished.
webrtc_internals.OnRemovePeerConnection(1, 2);
diff --git a/chromium/content/browser/webrtc/webrtc_internals_ui.cc b/chromium/content/browser/webrtc/webrtc_internals_ui.cc
index 6e26375c8ab..ea7d20f6d43 100644
--- a/chromium/content/browser/webrtc/webrtc_internals_ui.cc
+++ b/chromium/content/browser/webrtc/webrtc_internals_ui.cc
@@ -4,7 +4,6 @@
#include "content/browser/webrtc/webrtc_internals_ui.h"
-#include "base/memory/ptr_util.h"
#include "content/browser/webrtc/webrtc_internals_message_handler.h"
#include "content/grit/content_resources.h"
#include "content/public/browser/web_contents.h"
diff --git a/chromium/content/browser/webrtc/webrtc_internals_unittest.cc b/chromium/content/browser/webrtc/webrtc_internals_unittest.cc
index a3d37d37a23..fc9d9402e38 100644
--- a/chromium/content/browser/webrtc/webrtc_internals_unittest.cc
+++ b/chromium/content/browser/webrtc/webrtc_internals_unittest.cc
@@ -9,7 +9,6 @@
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
-#include "base/threading/thread_task_runner_handle.h"
#include "base/values.h"
#include "content/browser/webrtc/webrtc_internals_ui_observer.h"
#include "content/public/test/test_browser_thread.h"
@@ -91,11 +90,6 @@ class WebRTCInternalsForTest : public WebRTCInternals {
};
class WebRtcInternalsTest : public testing::Test {
- public:
- WebRtcInternalsTest()
- : synchronous_webrtc_event_log_manager_(
- base::ThreadTaskRunnerHandle::Get()) {}
-
protected:
void VerifyString(const base::DictionaryValue* dict,
const std::string& key,
@@ -138,9 +132,6 @@ class WebRtcInternalsTest : public testing::Test {
}
TestBrowserThreadBundle test_browser_thread_bundle_;
-
- // Must be constructed before the unit under test.
- WebRtcEventLogManager synchronous_webrtc_event_log_manager_;
};
TEST_F(WebRtcInternalsTest, AddRemoveObserver) {
@@ -507,4 +498,7 @@ TEST_F(WebRtcInternalsTest, WakeLock) {
base::RunLoop().RunUntilIdle();
}
+// TODO(eladalon): Add tests that WebRtcEventLogger::Enable/Disable is
+// correctly called. https://crbug.com/775415
+
} // namespace content
diff --git a/chromium/content/browser/webrtc/webrtc_local_event_log_manager.cc b/chromium/content/browser/webrtc/webrtc_local_event_log_manager.cc
deleted file mode 100644
index b2484fd9c4f..00000000000
--- a/chromium/content/browser/webrtc/webrtc_local_event_log_manager.cc
+++ /dev/null
@@ -1,249 +0,0 @@
-// Copyright (c) 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/webrtc/webrtc_local_event_log_manager.h"
-
-#include "base/files/file_util.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/string_util.h"
-#include "build/build_config.h"
-#include "content/public/browser/browser_thread.h"
-
-#if defined(OS_WIN)
-#define IntToStringType base::IntToString16
-#else
-#define IntToStringType base::IntToString
-#endif
-
-namespace content {
-
-#if defined(OS_ANDROID)
-const size_t kDefaultMaxLocalLogFileSizeBytes = 10000000;
-const size_t kMaxNumberLocalWebRtcEventLogFiles = 3;
-#else
-const size_t kDefaultMaxLocalLogFileSizeBytes = 60000000;
-const size_t kMaxNumberLocalWebRtcEventLogFiles = 5;
-#endif
-
-WebRtcLocalEventLogManager::WebRtcLocalEventLogManager(
- WebRtcLocalEventLogsObserver* observer)
- : observer_(observer),
- clock_for_testing_(nullptr),
- max_log_file_size_bytes_(kDefaultMaxLocalLogFileSizeBytes) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DETACH_FROM_SEQUENCE(io_task_sequence_checker_);
-}
-
-WebRtcLocalEventLogManager::~WebRtcLocalEventLogManager() {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-}
-
-bool WebRtcLocalEventLogManager::PeerConnectionAdded(
- const PeerConnectionKey& key) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
-
- const auto insertion_result = active_peer_connections_.insert(key);
- if (!insertion_result.second) {
- return false; // Attempt to re-add the PeerConnection.
- }
-
- if (!base_path_.empty() &&
- log_files_.size() < kMaxNumberLocalWebRtcEventLogFiles) {
- // Note that success/failure of starting the local log file is unrelated
- // to the success/failure of PeerConnectionAdded().
- StartLogFile(key);
- }
-
- return true;
-}
-
-bool WebRtcLocalEventLogManager::PeerConnectionRemoved(
- const PeerConnectionKey& key) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
-
- auto peer_connection = active_peer_connections_.find(key);
-
- if (peer_connection == active_peer_connections_.end()) {
- DCHECK(log_files_.find(key) == log_files_.end());
- return false;
- }
-
- auto local_log = log_files_.find(key);
- if (local_log != log_files_.end()) {
- // Note that success/failure of stopping the local log file is unrelated
- // to the success/failure of PeerConnectionRemoved().
- CloseLogFile(local_log);
- }
-
- active_peer_connections_.erase(peer_connection);
-
- return true;
-}
-
-bool WebRtcLocalEventLogManager::EnableLogging(const base::FilePath& base_path,
- size_t max_file_size_bytes) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
-
- if (!base_path_.empty()) {
- return false;
- }
-
- DCHECK_EQ(log_files_.size(), 0u);
-
- base_path_ = base_path;
- max_log_file_size_bytes_ = max_file_size_bytes;
-
- for (const PeerConnectionKey& peer_connection : active_peer_connections_) {
- if (log_files_.size() >= kMaxNumberLocalWebRtcEventLogFiles) {
- break;
- }
- StartLogFile(peer_connection);
- }
-
- return true;
-}
-
-bool WebRtcLocalEventLogManager::DisableLogging() {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
-
- if (base_path_.empty()) {
- return false;
- }
-
- for (auto local_log = log_files_.begin(); local_log != log_files_.end();) {
- local_log = CloseLogFile(local_log);
- }
-
- base_path_.clear(); // Marks local-logging as disabled.
- max_log_file_size_bytes_ = kDefaultMaxLocalLogFileSizeBytes;
-
- return true;
-}
-
-bool WebRtcLocalEventLogManager::EventLogWrite(const PeerConnectionKey& key,
- const std::string& message) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
- auto it = log_files_.find(key);
- if (it == log_files_.end()) {
- return false;
- }
- return WriteToLogFile(it, message);
-}
-
-void WebRtcLocalEventLogManager::RenderProcessHostExitedDestroyed(
- int render_process_id) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
-
- // Remove all of the peer connections associated with this render process.
- auto pc_it = active_peer_connections_.begin();
- while (pc_it != active_peer_connections_.end()) {
- if (pc_it->render_process_id == render_process_id) {
- pc_it = active_peer_connections_.erase(pc_it);
- } else {
- ++pc_it;
- }
- }
-
- // Close all of the files that were associated with peer connections which
- // belonged to this render process.
- auto log_it = log_files_.begin();
- while (log_it != log_files_.end()) {
- if (log_it->first.render_process_id == render_process_id) {
- log_it = CloseLogFile(log_it);
- } else {
- ++log_it;
- }
- }
-}
-
-void WebRtcLocalEventLogManager::SetClockForTesting(base::Clock* clock) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
- clock_for_testing_ = clock;
-}
-
-void WebRtcLocalEventLogManager::StartLogFile(const PeerConnectionKey& key) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
-
- // Add some information to the name given by the caller.
- base::FilePath file_path = GetFilePath(base_path_, key);
- CHECK(!file_path.empty()) << "Couldn't set path for local WebRTC log file.";
-
- // In the unlikely case that this filename is already taken, find a unique
- // number to append to the filename, if possible.
- int unique_number =
- base::GetUniquePathNumber(file_path, base::FilePath::StringType());
- if (unique_number < 0) {
- return; // No available file path was found.
- } else if (unique_number != 0) {
- // The filename is taken, but a unique number was found.
- // TODO(eladalon): Fix the way the unique number is used.
- // https://crbug.com/785333
- file_path = file_path.InsertBeforeExtension(FILE_PATH_LITERAL(" (") +
- IntToStringType(unique_number) +
- FILE_PATH_LITERAL(")"));
- }
-
- // Attempt to create the file.
- constexpr int file_flags = base::File::FLAG_CREATE | base::File::FLAG_WRITE |
- base::File::FLAG_EXCLUSIVE_WRITE;
- base::File file(file_path, file_flags);
- if (!file.IsValid() || !file.created()) {
- LOG(WARNING) << "Couldn't create and/or open local WebRTC event log file.";
- return;
- }
-
- // If the file was successfully created, it's now ready to be written to.
- DCHECK(log_files_.find(key) == log_files_.end());
- log_files_.emplace(
- key, LogFile(file_path, std::move(file), max_log_file_size_bytes_));
-
- // The observer needs to be able to run on any TaskQueue.
- if (observer_) {
- observer_->OnLocalLogStarted(key, file_path);
- }
-}
-
-WebRtcLocalEventLogManager::LogFilesMap::iterator
-WebRtcLocalEventLogManager::CloseLogFile(LogFilesMap::iterator it) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
-
- const PeerConnectionKey peer_connection = it->first;
-
- it->second.file.Flush();
- it = log_files_.erase(it); // file.Close() called by destructor.
-
- if (observer_) {
- observer_->OnLocalLogStopped(peer_connection);
- }
-
- return it;
-}
-
-base::FilePath WebRtcLocalEventLogManager::GetFilePath(
- const base::FilePath& base_path,
- const PeerConnectionKey& key) const {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
-
- base::Time::Exploded now;
- if (clock_for_testing_) {
- clock_for_testing_->Now().LocalExplode(&now);
- } else {
- base::Time::Now().LocalExplode(&now);
- }
-
- // [user_defined]_[date]_[time]_[render_process_id]_[lid].log
- char stamp[100];
- int written =
- base::snprintf(stamp, arraysize(stamp), "%04d%02d%02d_%02d%02d_%d_%d",
- now.year, now.month, now.day_of_month, now.hour,
- now.minute, key.render_process_id, key.lid);
- CHECK_GT(written, 0);
- CHECK_LT(static_cast<size_t>(written), arraysize(stamp));
-
- return base_path.InsertBeforeExtension(FILE_PATH_LITERAL("_"))
- .InsertBeforeExtensionASCII(base::StringPiece(stamp))
- .AddExtension(FILE_PATH_LITERAL("log"));
-}
-
-} // namespace content
diff --git a/chromium/content/browser/webrtc/webrtc_local_event_log_manager.h b/chromium/content/browser/webrtc/webrtc_local_event_log_manager.h
deleted file mode 100644
index 1d4aeffe37e..00000000000
--- a/chromium/content/browser/webrtc/webrtc_local_event_log_manager.h
+++ /dev/null
@@ -1,92 +0,0 @@
-// Copyright (c) 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_WEBRTC_WEBRTC_LOCAL_EVENT_LOG_MANAGER_H_
-#define CONTENT_BROWSER_WEBRTC_WEBRTC_LOCAL_EVENT_LOG_MANAGER_H_
-
-#include <map>
-#include <set>
-#include <string>
-
-#include "base/files/file.h"
-#include "base/files/file_path.h"
-#include "base/sequence_checker.h"
-#include "base/time/clock.h"
-#include "content/browser/webrtc/webrtc_event_log_manager_common.h"
-
-namespace content {
-
-class WebRtcLocalEventLogManager final : public LogFileWriter {
- public:
- explicit WebRtcLocalEventLogManager(WebRtcLocalEventLogsObserver* observer);
- ~WebRtcLocalEventLogManager() override;
-
- bool PeerConnectionAdded(const PeerConnectionKey& key);
- bool PeerConnectionRemoved(const PeerConnectionKey& key);
-
- bool EnableLogging(const base::FilePath& base_path,
- size_t max_file_size_bytes);
- bool DisableLogging();
-
- bool EventLogWrite(const PeerConnectionKey& key, const std::string& message);
-
- void RenderProcessHostExitedDestroyed(int render_process_id);
-
- // This function is public, but this entire class is a protected
- // implementation detail of WebRtcEventLogManager, which hides this
- // function from everybody except its own unit tests.
- void SetClockForTesting(base::Clock* clock);
-
- private:
- // Create a local log file.
- void StartLogFile(const PeerConnectionKey& key);
-
- // LogFileWriter implementation. Closes a log file, flushing it to disk
- // and relinquishing its handle.
- LogFilesMap::iterator CloseLogFile(LogFilesMap::iterator it) override;
-
- // Derives the name of a local log file. The format is:
- // [user_defined]_[date]_[time]_[render_process_id]_[lid].log
- base::FilePath GetFilePath(const base::FilePath& base_path,
- const PeerConnectionKey& key) const;
-
- // This object is expected to be created and destroyed on the UI thread,
- // but live on its owner's internal, IO-capable task queue.
- SEQUENCE_CHECKER(io_task_sequence_checker_);
-
- // Observer which will be informed whenever a local log file is started or
- // stopped. Through this, the owning WebRtcEventLogManager can be informed,
- // and decide whether it wants to turn notifications from WebRTC on/off.
- WebRtcLocalEventLogsObserver* const observer_;
-
- // For unit tests only, and specifically for unit tests that verify the
- // filename format (derived from the current time as well as the renderer PID
- // and PeerConnection local ID), we want to make sure that the time and date
- // cannot change between the time the clock is read by the unit under test
- // (namely WebRtcEventLogManager) and the time it's read by the test.
- base::Clock* clock_for_testing_;
-
- // Currently active peer connections. PeerConnections which have been closed
- // are not considered active, regardless of whether they have been torn down.
- std::set<PeerConnectionKey> active_peer_connections_;
-
- // Local log files, stored at the behest of the user (via WebRTCInternals).
- LogFilesMap log_files_;
-
- // If |base_path_| is empty, local logging is disabled.
- // If nonempty, local logging is enabled, and all local logs will be saved
- // to this directory.
- base::FilePath base_path_;
-
- // The maximum size for local logs, in bytes. Note that
- // kWebRtcEventLogManagerUnlimitedFileSize is a sentinel value (with a
- // self-explanatory name).
- size_t max_log_file_size_bytes_;
-
- DISALLOW_COPY_AND_ASSIGN(WebRtcLocalEventLogManager);
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_WEBRTC_WEBRTC_LOCAL_EVENT_LOG_MANAGER_H_
diff --git a/chromium/content/browser/webrtc/webrtc_media_recorder_browsertest.cc b/chromium/content/browser/webrtc/webrtc_media_recorder_browsertest.cc
index a92e78aec1f..8c3c2c12162 100644
--- a/chromium/content/browser/webrtc/webrtc_media_recorder_browsertest.cc
+++ b/chromium/content/browser/webrtc/webrtc_media_recorder_browsertest.cc
@@ -33,13 +33,21 @@ static struct EncodingParameters {
namespace content {
+// All tests in this fixture experience flaky DCHECK failures on macOS; see
+// https://crbug.com/810321.
+#if defined(OS_MACOSX) && DCHECK_IS_ON()
+#define MAYBE_WebRtcMediaRecorderTest DISABLED_WebRtcMediaRecorderTest
+#else
+#define MAYBE_WebRtcMediaRecorderTest WebRtcMediaRecorderTest
+#endif
+
// This class tests the recording of a media stream.
-class WebRtcMediaRecorderTest
+class MAYBE_WebRtcMediaRecorderTest
: public WebRtcContentBrowserTestBase,
public testing::WithParamInterface<struct EncodingParameters> {
public:
- WebRtcMediaRecorderTest() {}
- ~WebRtcMediaRecorderTest() override {}
+ MAYBE_WebRtcMediaRecorderTest() {}
+ ~MAYBE_WebRtcMediaRecorderTest() override {}
void SetUpCommandLine(base::CommandLine* command_line) override {
WebRtcContentBrowserTestBase::SetUpCommandLine(command_line);
@@ -62,18 +70,18 @@ class WebRtcMediaRecorderTest
}
private:
- DISALLOW_COPY_AND_ASSIGN(WebRtcMediaRecorderTest);
+ DISALLOW_COPY_AND_ASSIGN(MAYBE_WebRtcMediaRecorderTest);
};
-IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest, Start) {
+IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcMediaRecorderTest, Start) {
MakeTypicalCall("testStartAndRecorderState();", kMediaRecorderHtmlFile);
}
-IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest, StartAndStop) {
+IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcMediaRecorderTest, StartAndStop) {
MakeTypicalCall("testStartStopAndRecorderState();", kMediaRecorderHtmlFile);
}
-IN_PROC_BROWSER_TEST_P(WebRtcMediaRecorderTest, StartAndDataAvailable) {
+IN_PROC_BROWSER_TEST_P(MAYBE_WebRtcMediaRecorderTest, StartAndDataAvailable) {
MaybeForceDisableEncodeAccelerator(GetParam().disable_accelerator);
MakeTypicalCall(base::StringPrintf("testStartAndDataAvailable(\"%s\");",
GetParam().mime_type.c_str()),
@@ -87,29 +95,31 @@ IN_PROC_BROWSER_TEST_P(WebRtcMediaRecorderTest, StartAndDataAvailable) {
#else
#define MAYBE_StartWithTimeSlice StartWithTimeSlice
#endif
-IN_PROC_BROWSER_TEST_P(WebRtcMediaRecorderTest, MAYBE_StartWithTimeSlice) {
+IN_PROC_BROWSER_TEST_P(MAYBE_WebRtcMediaRecorderTest,
+ MAYBE_StartWithTimeSlice) {
MaybeForceDisableEncodeAccelerator(GetParam().disable_accelerator);
MakeTypicalCall(base::StringPrintf("testStartWithTimeSlice(\"%s\");",
GetParam().mime_type.c_str()),
kMediaRecorderHtmlFile);
}
-IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest, Resume) {
+IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcMediaRecorderTest, Resume) {
MakeTypicalCall("testResumeAndRecorderState();", kMediaRecorderHtmlFile);
}
-IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest, NoResumeWhenRecorderInactive) {
+IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcMediaRecorderTest,
+ NoResumeWhenRecorderInactive) {
MakeTypicalCall("testIllegalResumeThrowsDOMError();", kMediaRecorderHtmlFile);
}
-IN_PROC_BROWSER_TEST_P(WebRtcMediaRecorderTest, ResumeAndDataAvailable) {
+IN_PROC_BROWSER_TEST_P(MAYBE_WebRtcMediaRecorderTest, ResumeAndDataAvailable) {
MaybeForceDisableEncodeAccelerator(GetParam().disable_accelerator);
MakeTypicalCall(base::StringPrintf("testResumeAndDataAvailable(\"%s\");",
GetParam().mime_type.c_str()),
kMediaRecorderHtmlFile);
}
-IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest, Pause) {
+IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcMediaRecorderTest, Pause) {
MakeTypicalCall("testPauseAndRecorderState();", kMediaRecorderHtmlFile);
}
@@ -119,11 +129,11 @@ IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest, Pause) {
#else
#define MAYBE_PauseStop PauseStop
#endif
-IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest, MAYBE_PauseStop) {
+IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcMediaRecorderTest, MAYBE_PauseStop) {
MakeTypicalCall("testPauseStopAndRecorderState();", kMediaRecorderHtmlFile);
}
-IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest,
+IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcMediaRecorderTest,
PausePreventsDataavailableFromBeingFired) {
MakeTypicalCall("testPausePreventsDataavailableFromBeingFired();",
kMediaRecorderHtmlFile);
@@ -135,33 +145,35 @@ IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest,
#else
#define MAYBE_IllegalPauseThrowsDOMError IllegalPauseThrowsDOMError
#endif
-IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest,
+IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcMediaRecorderTest,
MAYBE_IllegalPauseThrowsDOMError) {
MakeTypicalCall("testIllegalPauseThrowsDOMError();", kMediaRecorderHtmlFile);
}
-IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest, TwoChannelAudioRecording) {
+IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcMediaRecorderTest,
+ TwoChannelAudioRecording) {
MakeTypicalCall("testTwoChannelAudio();", kMediaRecorderHtmlFile);
}
-IN_PROC_BROWSER_TEST_P(WebRtcMediaRecorderTest, RecordWithTransparency) {
+IN_PROC_BROWSER_TEST_P(MAYBE_WebRtcMediaRecorderTest, RecordWithTransparency) {
MaybeForceDisableEncodeAccelerator(GetParam().disable_accelerator);
MakeTypicalCall(base::StringPrintf("testRecordWithTransparency(\"%s\");",
GetParam().mime_type.c_str()),
kMediaRecorderHtmlFile);
}
-IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest, IllegalStopThrowsDOMError) {
+IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcMediaRecorderTest,
+ IllegalStopThrowsDOMError) {
MakeTypicalCall("testIllegalStopThrowsDOMError();", kMediaRecorderHtmlFile);
}
-IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest,
+IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcMediaRecorderTest,
IllegalStartWhileRecordingThrowsDOMError) {
MakeTypicalCall("testIllegalStartInRecordingStateThrowsDOMError();",
kMediaRecorderHtmlFile);
}
-IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest,
+IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcMediaRecorderTest,
IllegalStartWhilePausedThrowsDOMError) {
MakeTypicalCall("testIllegalStartInPausedStateThrowsDOMError();",
kMediaRecorderHtmlFile);
@@ -174,7 +186,7 @@ IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest,
#else
#define MAYBE_IllegalRequestDataThrowsDOMError IllegalRequestDataThrowsDOMError
#endif
-IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest,
+IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcMediaRecorderTest,
MAYBE_IllegalRequestDataThrowsDOMError) {
MakeTypicalCall("testIllegalRequestDataThrowsDOMError();",
kMediaRecorderHtmlFile);
@@ -194,7 +206,7 @@ IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest,
#define MAYBE_PeerConnection PeerConnection
#endif
-IN_PROC_BROWSER_TEST_P(WebRtcMediaRecorderTest, MAYBE_PeerConnection) {
+IN_PROC_BROWSER_TEST_P(MAYBE_WebRtcMediaRecorderTest, MAYBE_PeerConnection) {
MaybeForceDisableEncodeAccelerator(GetParam().disable_accelerator);
MakeTypicalCall(base::StringPrintf("testRecordRemotePeerConnection(\"%s\");",
GetParam().mime_type.c_str()),
@@ -209,20 +221,20 @@ IN_PROC_BROWSER_TEST_P(WebRtcMediaRecorderTest, MAYBE_PeerConnection) {
#define MAYBE_AddingTrackToMediaStreamFiresErrorEvent \
AddingTrackToMediaStreamFiresErrorEvent
#endif
-IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest,
+IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcMediaRecorderTest,
MAYBE_AddingTrackToMediaStreamFiresErrorEvent) {
MakeTypicalCall("testAddingTrackToMediaStreamFiresErrorEvent();",
kMediaRecorderHtmlFile);
}
-IN_PROC_BROWSER_TEST_F(WebRtcMediaRecorderTest,
+IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcMediaRecorderTest,
RemovingTrackFromMediaStreamFiresErrorEvent) {
MakeTypicalCall("testRemovingTrackFromMediaStreamFiresErrorEvent();",
kMediaRecorderHtmlFile);
}
INSTANTIATE_TEST_CASE_P(,
- WebRtcMediaRecorderTest,
+ MAYBE_WebRtcMediaRecorderTest,
testing::ValuesIn(kEncodingParameters));
} // namespace content
diff --git a/chromium/content/browser/webrtc/webrtc_remote_event_log_manager.cc b/chromium/content/browser/webrtc/webrtc_remote_event_log_manager.cc
deleted file mode 100644
index c650d5abc27..00000000000
--- a/chromium/content/browser/webrtc/webrtc_remote_event_log_manager.cc
+++ /dev/null
@@ -1,537 +0,0 @@
-// Copyright (c) 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/webrtc/webrtc_remote_event_log_manager.h"
-
-#include <algorithm>
-#include <limits>
-
-#include "base/big_endian.h"
-#include "base/bind.h"
-#include "base/files/file.h"
-#include "base/files/file_enumerator.h"
-#include "base/files/file_path.h"
-#include "base/files/file_util.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/rand_util.h"
-#include "base/threading/sequenced_task_runner_handle.h"
-#include "content/public/browser/browser_thread.h"
-
-namespace content {
-
-// TODO(eladalon): Block remote-bound logging on mobile devices.
-// https://crbug.com/775415
-
-namespace {
-const base::FilePath::CharType kRemoteBoundLogSubDirectory[] =
- FILE_PATH_LITERAL("webrtc_event_logs");
-
-// Purge from local disk a log file which could not be properly started
-// (e.g. error encountered when attempting to write the log header).
-void DiscardLogFile(base::File* file, const base::FilePath& file_path) {
- file->Close();
- if (!base::DeleteFile(file_path, /*recursive=*/false)) {
- LOG(ERROR) << "Failed to delete " << file_path << ".";
- }
-}
-
-bool ValidLogParameters(size_t max_file_size_bytes,
- const std::string& metadata) {
- // TODO(eladalon): Set a tighter limit (following discussion with rschriebman
- // and manj). https://crbug.com/775415
- if (max_file_size_bytes == kWebRtcEventLogManagerUnlimitedFileSize) {
- return false;
- }
-
- if (metadata.length() > 0xFFFFFFu) {
- // We use three bytes to encode the length of the metadata.
- LOG(ERROR) << "Metadata must be less than 2^24 bytes.";
- return false;
- }
-
- if (metadata.size() + kRemoteBoundLogFileHeaderSizeBytes >=
- max_file_size_bytes) {
- LOG(ERROR) << "Max file size and metadata must leave room for event log.";
- return false;
- }
-
- return true;
-}
-} // namespace
-
-const size_t kMaxActiveRemoteBoundWebRtcEventLogs = 3;
-const size_t kMaxPendingRemoteBoundWebRtcEventLogs = 5;
-static_assert(kMaxActiveRemoteBoundWebRtcEventLogs <=
- kMaxPendingRemoteBoundWebRtcEventLogs,
- "This assumption affects unit test coverage.");
-
-const base::TimeDelta kRemoteBoundWebRtcEventLogsMaxRetention =
- base::TimeDelta::FromDays(3);
-
-const base::FilePath::CharType kRemoteBoundLogExtension[] =
- FILE_PATH_LITERAL("log");
-
-const uint8_t kRemoteBoundWebRtcEventLogFileVersion = 0;
-
-const size_t kRemoteBoundLogFileHeaderSizeBytes = sizeof(uint32_t);
-
-WebRtcRemoteEventLogManager::WebRtcRemoteEventLogManager(
- WebRtcRemoteEventLogsObserver* observer)
- : observer_(observer),
- uploader_factory_(new WebRtcEventLogUploaderImpl::Factory) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DETACH_FROM_SEQUENCE(io_task_sequence_checker_);
-}
-
-WebRtcRemoteEventLogManager::~WebRtcRemoteEventLogManager() {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- // TODO(eladalon): Purge from disk files which were being uploaded while
- // destruction took place, thereby avoiding endless attempts to upload
- // the same file. https://crbug.com/775415
-}
-
-void WebRtcRemoteEventLogManager::EnableForBrowserContext(
- BrowserContextId browser_context_id,
- const base::FilePath& browser_context_dir) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
- DCHECK(!BrowserContextEnabled(browser_context_id)) << "Already enabled.";
-
- const base::FilePath remote_bound_logs_dir =
- GetLogsDirectoryPath(browser_context_dir);
- if (!MaybeCreateLogsDirectory(remote_bound_logs_dir)) {
- LOG(WARNING)
- << "WebRtcRemoteEventLogManager couldn't create logs directory.";
- return;
- }
-
- AddPendingLogs(browser_context_id, remote_bound_logs_dir);
-
- enabled_browser_contexts_.insert(browser_context_id);
-}
-
-// TODO(eladalon): Add unit tests. https://crbug.com/775415
-void WebRtcRemoteEventLogManager::DisableForBrowserContext(
- BrowserContextId browser_context_id) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
-
- if (!BrowserContextEnabled(browser_context_id)) {
- return; // Enabling may have failed due to lacking permissions.
- }
-
- enabled_browser_contexts_.erase(browser_context_id);
-
-#if DCHECK_IS_ON()
- // All of the RPHs associated with this BrowserContext must already have
- // exited, which should have implicitly stopped all active logs.
- auto pred = [browser_context_id](decltype(active_logs_)::value_type& log) {
- return log.first.browser_context_id == browser_context_id;
- };
- DCHECK(std::count_if(active_logs_.begin(), active_logs_.end(), pred) == 0u);
-#endif
-
- // Pending logs for this BrowserContext are no longer eligible for upload.
- // (Active uploads, if any, are not affected.)
- for (auto it = pending_logs_.begin(); it != pending_logs_.end();) {
- if (it->browser_context_id == browser_context_id) {
- it = pending_logs_.erase(it);
- } else {
- ++it;
- }
- }
-}
-
-bool WebRtcRemoteEventLogManager::PeerConnectionAdded(
- const PeerConnectionKey& key) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
- PrunePendingLogs(); // Infrequent event - good opportunity to prune.
- const auto result = active_peer_connections_.insert(key);
- return result.second;
-}
-
-bool WebRtcRemoteEventLogManager::PeerConnectionRemoved(
- const PeerConnectionKey& key) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
-
- PrunePendingLogs(); // Infrequent event - good opportunity to prune.
-
- const auto peer_connection = active_peer_connections_.find(key);
- if (peer_connection == active_peer_connections_.end()) {
- return false;
- }
-
- MaybeStopRemoteLogging(key);
-
- active_peer_connections_.erase(peer_connection);
-
- MaybeStartUploading();
-
- return true;
-}
-
-bool WebRtcRemoteEventLogManager::StartRemoteLogging(
- const PeerConnectionKey& key,
- const base::FilePath& browser_context_dir,
- size_t max_file_size_bytes,
- const std::string& metadata) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
-
- if (!ValidLogParameters(max_file_size_bytes, metadata)) {
- return false;
- }
-
- if (!BrowserContextEnabled(key.browser_context_id)) {
- return false;
- }
-
- // May not start logging inactive peer connections.
- if (active_peer_connections_.find(key) == active_peer_connections_.end()) {
- return false;
- }
-
- // May not restart active remote logs.
- auto it = active_logs_.find(key);
- if (it != active_logs_.end()) {
- LOG(ERROR) << "Remote logging already underway for ("
- << key.render_process_id << ", " << key.lid << ").";
- return false;
- }
-
- // This is a good opportunity to prune the list of pending logs, potentially
- // making room for this file.
- PrunePendingLogs();
-
- if (!AdditionalActiveLogAllowed(key.browser_context_id)) {
- return false;
- }
-
- return StartWritingLog(key, browser_context_dir, max_file_size_bytes,
- metadata);
-}
-
-bool WebRtcRemoteEventLogManager::EventLogWrite(const PeerConnectionKey& key,
- const std::string& message) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
-
- auto it = active_logs_.find(key);
- if (it == active_logs_.end()) {
- return false;
- }
- return WriteToLogFile(it, message);
-}
-
-void WebRtcRemoteEventLogManager::RenderProcessHostExitedDestroyed(
- int render_process_id) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
-
- // Closing files will call MaybeStartUploading(). Avoid letting that upload
- // any recently expired files.
- PrunePendingLogs();
-
- // Remove all of the peer connections associated with this render process.
- // It's important to do this before closing the actual files, because closing
- // files can trigger a new upload if no active peer connections are present.
- auto pc_it = active_peer_connections_.begin();
- while (pc_it != active_peer_connections_.end()) {
- if (pc_it->render_process_id == render_process_id) {
- pc_it = active_peer_connections_.erase(pc_it);
- } else {
- ++pc_it;
- }
- }
-
- // Close all of the files that were associated with peer connections which
- // belonged to this render process.
- auto log_it = active_logs_.begin();
- while (log_it != active_logs_.end()) {
- if (log_it->first.render_process_id == render_process_id) {
- log_it = CloseLogFile(log_it);
- } else {
- ++log_it;
- }
- }
-
- // Though CloseLogFile() calls this, it's important to also do this
- // explicitly, since it could be that no files were closed, but some
- // active PeerConnections that were suppressing uploading are now gone.
- MaybeStartUploading();
-}
-
-void WebRtcRemoteEventLogManager::OnWebRtcEventLogUploadComplete(
- const base::FilePath& file_path,
- bool upload_successful) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
-
- // Post a task to deallocate the uploader (can't do this directly,
- // because this function is a callback from the uploader), potentially
- // starting a new upload for the next file.
- base::SequencedTaskRunnerHandle::Get()->PostTask(
- FROM_HERE,
- base::BindOnce(
- &WebRtcRemoteEventLogManager::OnWebRtcEventLogUploadCompleteInternal,
- base::Unretained(this)));
-
- // TODO(eladalon): Send indication of success/failure back to JS.
- // https://crbug.com/775415
-}
-
-void WebRtcRemoteEventLogManager::SetWebRtcEventLogUploaderFactoryForTesting(
- std::unique_ptr<WebRtcEventLogUploader::Factory> uploader_factory) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
-
- uploader_factory_ = std::move(uploader_factory);
-
- // Unit tests would initially set a null uploader factory, so that files would
- // be kept around. Some tests would later change to a different factory
- // (e.g. one that always simulates upload failure); in that case, we should
- // get rid of the null uploader, since it never terminates.
- uploader_.reset();
- MaybeStartUploading();
-}
-
-base::FilePath WebRtcRemoteEventLogManager::GetLogsDirectoryPath(
- const base::FilePath& browser_context_dir) {
- return browser_context_dir.Append(kRemoteBoundLogSubDirectory);
-}
-
-bool WebRtcRemoteEventLogManager::BrowserContextEnabled(
- BrowserContextId browser_context_id) const {
- const auto it = enabled_browser_contexts_.find(browser_context_id);
- return it != enabled_browser_contexts_.cend();
-}
-
-WebRtcRemoteEventLogManager::LogFilesMap::iterator
-WebRtcRemoteEventLogManager::CloseLogFile(LogFilesMap::iterator it) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
-
- const PeerConnectionKey peer_connection = it->first;
-
- it->second.file.Flush();
- it = active_logs_.erase(it); // file.Close() called by destructor.
-
- if (observer_) {
- observer_->OnRemoteLogStopped(peer_connection);
- }
-
- MaybeStartUploading();
-
- return it;
-}
-
-bool WebRtcRemoteEventLogManager::MaybeCreateLogsDirectory(
- const base::FilePath& remote_bound_logs_dir) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
-
- if (base::PathExists(remote_bound_logs_dir)) {
- if (!base::DirectoryExists(remote_bound_logs_dir)) {
- LOG(ERROR) << "Path for remote-bound logs is taken by a non-directory.";
- return false;
- }
- } else if (!base::CreateDirectory(remote_bound_logs_dir)) {
- LOG(ERROR) << "Failed to create the local directory for remote-bound logs.";
- return false;
- }
-
- // TODO(eladalon): Test for appropriate permissions. https://crbug.com/775415
-
- return true;
-}
-
-void WebRtcRemoteEventLogManager::AddPendingLogs(
- BrowserContextId browser_context_id,
- const base::FilePath& remote_bound_logs_dir) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
-
- base::FilePath::StringType pattern =
- base::FilePath::StringType(FILE_PATH_LITERAL("*")) +
- kRemoteBoundLogExtension;
- base::FileEnumerator enumerator(remote_bound_logs_dir,
- /*recursive=*/false,
- base::FileEnumerator::FILES, pattern);
-
- for (auto path = enumerator.Next(); !path.empty(); path = enumerator.Next()) {
- const auto last_modified = enumerator.GetInfo().GetLastModifiedTime();
- auto it = pending_logs_.emplace(browser_context_id, path, last_modified);
- DCHECK(it.second); // No pre-existing entry.
- }
-
- MaybeStartUploading();
-}
-
-bool WebRtcRemoteEventLogManager::StartWritingLog(
- const PeerConnectionKey& key,
- const base::FilePath& browser_context_dir,
- size_t max_file_size_bytes,
- const std::string& metadata) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
-
- // WriteAtCurrentPos() only allows writing up to max-int at a time. We could
- // iterate to do more, but we don't expect to ever need to, so it's easier
- // to disallow it.
- if (metadata.length() >
- static_cast<size_t>(std::numeric_limits<int>::max())) {
- LOG(WARNING) << "Metadata too long to be written in one go.";
- return false;
- }
-
- // Randomize a new filename. In the highly unlikely event that this filename
- // is already taken, it will be treated the same way as any other failure
- // to start the log file.
- // TODO(eladalon): Add a unit test for above comment. https://crbug.com/775415
- const std::string unique_filename =
- "event_log_" + std::to_string(base::RandUint64());
- const base::FilePath base_path = GetLogsDirectoryPath(browser_context_dir);
- const base::FilePath file_path = base_path.AppendASCII(unique_filename)
- .AddExtension(kRemoteBoundLogExtension);
-
- // Attempt to create the file.
- constexpr int file_flags = base::File::FLAG_CREATE | base::File::FLAG_WRITE |
- base::File::FLAG_EXCLUSIVE_WRITE;
- base::File file(file_path, file_flags);
- if (!file.IsValid() || !file.created()) {
- LOG(WARNING) << "Couldn't create and/or open remote WebRTC event log file.";
- return false;
- }
-
- const uint32_t header_host_order =
- static_cast<uint32_t>(metadata.length()) |
- (kRemoteBoundWebRtcEventLogFileVersion << 24);
- static_assert(kRemoteBoundLogFileHeaderSizeBytes == sizeof(uint32_t),
- "Restructure this otherwise.");
- char header[sizeof(uint32_t)];
- base::WriteBigEndian<uint32_t>(header, header_host_order);
- int written = file.WriteAtCurrentPos(header, arraysize(header));
- if (written != arraysize(header)) {
- LOG(WARNING) << "Failed to write header to log file.";
- DiscardLogFile(&file, file_path);
- return false;
- }
-
- const int metadata_length = static_cast<int>(metadata.length());
- written = file.WriteAtCurrentPos(metadata.c_str(), metadata_length);
- if (written != metadata_length) {
- LOG(WARNING) << "Failed to write metadata to log file.";
- DiscardLogFile(&file, file_path);
- return false;
- }
-
- // Record that we're now writing this remote-bound log to this file.
- const size_t header_and_metadata_size_bytes =
- kRemoteBoundLogFileHeaderSizeBytes + metadata_length;
- const auto it = active_logs_.emplace(
- key, LogFile(file_path, std::move(file), max_file_size_bytes,
- header_and_metadata_size_bytes));
- DCHECK(it.second);
-
- observer_->OnRemoteLogStarted(key, file_path);
-
- return true;
-}
-
-void WebRtcRemoteEventLogManager::MaybeStopRemoteLogging(
- const PeerConnectionKey& key) {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
-
- const auto it = active_logs_.find(key);
- if (it == active_logs_.end()) {
- return;
- }
-
- it->second.file.Flush();
- it->second.file.Close();
-
- // The current time is a good enough approximation of the file's last
- // modification time.
- const base::Time last_modified = base::Time::Now();
-
- // The stopped log becomes a pending log. It is no longer an active log.
- const auto emplace_result = pending_logs_.emplace(
- key.browser_context_id, it->second.path, last_modified);
- DCHECK(emplace_result.second); // No pre-existing entry.
- active_logs_.erase(it);
-
- observer_->OnRemoteLogStopped(key);
-
- MaybeStartUploading();
-}
-
-void WebRtcRemoteEventLogManager::PrunePendingLogs() {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
- const base::Time oldest_non_expired_timestamp =
- base::Time::Now() - kRemoteBoundWebRtcEventLogsMaxRetention;
- for (auto it = pending_logs_.begin(); it != pending_logs_.end();) {
- if (it->last_modified < oldest_non_expired_timestamp) {
- if (!base::DeleteFile(it->path, /*recursive=*/false)) {
- LOG(ERROR) << "Failed to delete " << it->path << ".";
- }
- it = pending_logs_.erase(it);
- } else {
- ++it;
- }
- }
-}
-
-bool WebRtcRemoteEventLogManager::AdditionalActiveLogAllowed(
- BrowserContextId browser_context_id) const {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
-
- // Limit over concurrently active logs (across BrowserContext-s).
- if (active_logs_.size() >= kMaxActiveRemoteBoundWebRtcEventLogs) {
- return false;
- }
-
- // Limit over the number of pending logs (per BrowserContext). We count active
- // logs too, since they become pending logs once completed.
- const size_t active_count = std::count_if(
- active_logs_.begin(), active_logs_.end(),
- [browser_context_id](const decltype(active_logs_)::value_type& log) {
- return log.first.browser_context_id == browser_context_id;
- });
- const size_t pending_count = std::count_if(
- pending_logs_.begin(), pending_logs_.end(),
- [browser_context_id](const decltype(pending_logs_)::value_type& log) {
- return log.browser_context_id == browser_context_id;
- });
- return active_count + pending_count < kMaxPendingRemoteBoundWebRtcEventLogs;
-}
-
-bool WebRtcRemoteEventLogManager::UploadingAllowed() const {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
- return active_peer_connections_.empty();
-}
-
-void WebRtcRemoteEventLogManager::MaybeStartUploading() {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
-
- PrunePendingLogs(); // Avoid uploading freshly expired files.
-
- if (uploader_) {
- return; // Upload already underway.
- }
-
- if (pending_logs_.empty()) {
- return; // Nothing to upload.
- }
-
- if (!UploadingAllowed()) {
- return;
- }
-
- // The uploader takes ownership of the file; it's no longer considered to be
- // pending. (If the upload fails, the log will be deleted.)
- // TODO(eladalon): Add more refined retry behavior, so that we would not
- // delete the log permanently if the network is just down, on the one hand,
- // but also would not be uploading unlimited data on endless retries on the
- // other hand. https://crbug.com/775415
- uploader_ = uploader_factory_->Create(pending_logs_.begin()->path, this);
- pending_logs_.erase(pending_logs_.begin());
-}
-
-void WebRtcRemoteEventLogManager::OnWebRtcEventLogUploadCompleteInternal() {
- DCHECK_CALLED_ON_VALID_SEQUENCE(io_task_sequence_checker_);
- uploader_.reset();
- MaybeStartUploading();
-}
-
-} // namespace content
diff --git a/chromium/content/browser/webrtc/webrtc_remote_event_log_manager.h b/chromium/content/browser/webrtc/webrtc_remote_event_log_manager.h
deleted file mode 100644
index 96b557732bc..00000000000
--- a/chromium/content/browser/webrtc/webrtc_remote_event_log_manager.h
+++ /dev/null
@@ -1,238 +0,0 @@
-// Copyright (c) 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_WEBRTC_WEBRTC_REMOTE_EVENT_LOG_MANAGER_H_
-#define CONTENT_BROWSER_WEBRTC_WEBRTC_REMOTE_EVENT_LOG_MANAGER_H_
-
-#include <map>
-#include <set>
-#include <vector>
-
-#include "base/sequence_checker.h"
-#include "base/time/time.h"
-#include "content/browser/webrtc/webrtc_event_log_manager_common.h"
-#include "content/browser/webrtc/webrtc_event_log_uploader.h"
-#include "content/common/content_export.h"
-
-namespace content {
-
-// TODO(eladalon): Prevent uploading of logs when Chrome shutdown imminent.
-// https://crbug.com/775415
-
-class CONTENT_EXPORT WebRtcRemoteEventLogManager final
- : public LogFileWriter,
- public WebRtcEventLogUploaderObserver {
- public:
- explicit WebRtcRemoteEventLogManager(WebRtcRemoteEventLogsObserver* observer);
- ~WebRtcRemoteEventLogManager() override;
-
- // Enables remote-bound logging for a given BrowserContext. Logs stored during
- // previous sessions become eligible for upload, and recording of new logs for
- // peer connections associated with this BrowserContext, in the
- // BrowserContext's user-data directory, becomes possible.
- // This method would typically be called when a BrowserContext is initialized.
- void EnableForBrowserContext(BrowserContextId browser_context_id,
- const base::FilePath& browser_context_dir);
-
- // Enables remote-bound logging for a given BrowserContext. Pending logs from
- // earlier (while it was enabled) may still be uploaded, but no additional
- // logs will be created.
- void DisableForBrowserContext(BrowserContextId browser_context_id);
-
- // Called to inform |this| of peer connections being added/removed.
- // This information is used to:
- // 1. Make decisions about when to upload previously finished logs.
- // 2. When a peer connection is removed, if it was being logged, its log
- // changes from ACTIVE to PENDING.
- // The return value of both methods indicates only the consistency of the
- // information with previously received information (e.g. can't remove a
- // peer connection that was never added, etc.).
- bool PeerConnectionAdded(const PeerConnectionKey& key);
- bool PeerConnectionRemoved(const PeerConnectionKey& key);
-
- // Attempt to start logging the WebRTC events of an active peer connection.
- // Logging is subject to several restrictions:
- // 1. May not log more than kMaxNumberActiveRemoteWebRtcEventLogFiles logs
- // at the same time.
- // 2. Each browser context may have only kMaxPendingLogFilesPerBrowserContext
- // pending logs. Since active logs later become pending logs, it is also
- // forbidden to start a remote-bound log that would, once completed, become
- // a pending log that would exceed that limit.
- // 3. The maximum file size must be sensible.
- // The return value is true if all of the restrictions were observed, and if
- // a file was successfully created for this log.
- bool StartRemoteLogging(const PeerConnectionKey& key,
- const base::FilePath& browser_context_dir,
- size_t max_file_size_bytes,
- const std::string& metadata);
-
- // If an active remote-bound log exists for the given peer connection, this
- // will append |message| to that log.
- // If writing |message| to the log would exceed the log's maximum allowed
- // size, the write is disallowed and the file is closed instead (and changes
- // from ACTIVE to PENDING).
- // If the log file's capacity is exhausted as a result of this function call,
- // or if a write error occurs, the file is closed, and the remote-bound log
- // changes from ACTIVE to PENDING.
- // True is returned if and only if |message| was written in its entirety to
- // an active log.
- bool EventLogWrite(const PeerConnectionKey& key, const std::string& message);
-
- // An implicit PeerConnectionRemoved() on all of the peer connections that
- // were associated with the renderer process.
- void RenderProcessHostExitedDestroyed(int render_process_id);
-
- // WebRtcEventLogUploaderObserver implementation.
- void OnWebRtcEventLogUploadComplete(const base::FilePath& file_path,
- bool upload_successful) override;
-
- // Unit tests may use this to inject null uploaders, or ones which are
- // directly controlled by the unit test (succeed or fail according to the
- // test's needs).
- // Note that for simplicity's sake, this may be called from outside the
- // task queue on which this object lives (WebRtcEventLogManager::task_queue_).
- // Therefore, if a test calls this, it should call it before it initializes
- // any BrowserContext with pending log files in its directory.
- void SetWebRtcEventLogUploaderFactoryForTesting(
- std::unique_ptr<WebRtcEventLogUploader::Factory> uploader_factory);
-
- protected:
- friend class WebRtcEventLogManagerTest;
-
- // Given a BrowserContext's directory, return the path to the directory where
- // we store the pending remote-bound logs associated with this BrowserContext.
- static base::FilePath GetLogsDirectoryPath(
- const base::FilePath& browser_context_dir);
-
- private:
- using PeerConnectionKey = WebRtcEventLogPeerConnectionKey;
-
- struct PendingLog {
- PendingLog(BrowserContextId browser_context_id,
- const base::FilePath& path,
- base::Time last_modified)
- : browser_context_id(browser_context_id),
- path(path),
- last_modified(last_modified) {}
-
- bool operator<(const PendingLog& other) const {
- if (last_modified != other.last_modified) {
- return last_modified < other.last_modified;
- }
- return path < other.path; // Break ties arbitrarily, but consistently.
- }
-
- const BrowserContextId browser_context_id; // This file's owner.
- const base::FilePath path;
- // |last_modified| recorded at BrowserContext initialization. Chrome will
- // not modify it afterwards, and neither should the user.
- const base::Time last_modified;
- };
-
- // Checks whether a browser context has already been enabled via a call to
- // EnableForBrowserContext(), and not yet disabled using a call to
- // DisableForBrowserContext().
- bool BrowserContextEnabled(BrowserContextId browser_context_id) const;
-
- // LogFileWriter implementation. Closes an active log file, changing its
- // state from ACTIVE to PENDING.
- LogFilesMap::iterator CloseLogFile(LogFilesMap::iterator it) override;
-
- // Attempts to create the directory where we'll write the logs, if it does
- // not already exist. Returns true if the directory exists (either it already
- // existed, or it was successfully created).
- bool MaybeCreateLogsDirectory(const base::FilePath& remote_bound_logs_dir);
-
- // Scans the user data directory associated with this BrowserContext for
- // remote-bound logs that were created during previous Chrome sessions.
- // This function does *not* protect against manipulation by the user,
- // who might seed the directory with more files than were permissible.
- void AddPendingLogs(BrowserContextId browser_context_id,
- const base::FilePath& remote_bound_logs_dir);
-
- // Attempts the creation of a locally stored file into which a remote-bound
- // log may be written. True is returned if and only if such a file was
- // successfully created.
- bool StartWritingLog(const PeerConnectionKey& key,
- const base::FilePath& browser_context_dir,
- size_t max_file_size_bytes,
- const std::string& metadata);
-
- // Checks if the referenced peer connection has an associated active
- // remote-bound log. If it does, the log is changed from ACTIVE to PENDING.
- void MaybeStopRemoteLogging(const PeerConnectionKey& key);
-
- // Get rid of pending logs whose age exceeds our retention policy.
- // On the one hand, we want to remove expired files as soon as possible, but
- // on the other hand, we don't want to waste CPU by checking this too often.
- // Therefore, we prune pending files:
- // 1. When a new BrowserContext is initalized, thereby also pruning the
- // pending logs contributed by that BrowserContext.
- // 2. Before initiating a new upload, thereby avoiding uploading a file that
- // has just now expired.
- // 3. On infrequent events - peer connection addition/removal, but NOT
- // on something that could potentially be frequent, such as EventLogWrite.
- // Note that the last modification date of a file, which is the value measured
- // against for retention, is only read from disk once per file, meaning
- // this check is not too expensive.
- void PrunePendingLogs();
-
- // Return |true| if and only if we can start another active log (with respect
- // to limitations on the numbers active and pending logs).
- bool AdditionalActiveLogAllowed(BrowserContextId browser_context_id) const;
-
- // Initiating a new upload is only allowed when there are no active peer
- // connection which might be adversely affected by the bandwidth consumption
- // of the upload.
- // TODO(eladalon): Add support for pausing/resuming an upload when peer
- // connections are added/removed after an upload was already initiated.
- // https://crbug.com/775415
- bool UploadingAllowed() const;
-
- // If no upload is in progress, and if uploading is currently permissible,
- // start a new upload.
- void MaybeStartUploading();
-
- // When an upload is complete, it might be time to upload the next file.
- void OnWebRtcEventLogUploadCompleteInternal();
-
- // This object is expected to be created and destroyed on the UI thread,
- // but live on its owner's internal, IO-capable task queue.
- SEQUENCE_CHECKER(io_task_sequence_checker_);
-
- // This is used to inform WebRtcEventLogManager when remote-bound logging
- // of a peer connection starts/stops, which allows WebRtcEventLogManager to
- // decide when to ask WebRTC to start/stop sending event logs.
- WebRtcRemoteEventLogsObserver* const observer_;
-
- // The IDs of the BrowserContexts for which logging is enabled.
- std::set<BrowserContextId> enabled_browser_contexts_;
-
- // Currently active peer connections. PeerConnections which have been closed
- // are not considered active, regardless of whether they have been torn down.
- std::set<PeerConnectionKey> active_peer_connections_;
-
- // Remote-bound logs which we're currently in the process of writing to disk.
- std::map<PeerConnectionKey, LogFile> active_logs_;
-
- // Remote-bound logs which have been written to disk before (either during
- // this Chrome session or during an earlier one), and which are no waiting to
- // be uploaded.
- std::set<PendingLog> pending_logs_;
-
- // Null if no ongoing upload, or an uploader which owns a file, and is
- // currently busy uploading it to a remote server.
- std::unique_ptr<WebRtcEventLogUploader> uploader_;
-
- // Producer of uploader objects. (In unit tests, this would create
- // null-implementation uploaders, or uploaders whose behavior is controlled
- // by the unit test.)
- std::unique_ptr<WebRtcEventLogUploader::Factory> uploader_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(WebRtcRemoteEventLogManager);
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_WEBRTC_WEBRTC_REMOTE_EVENT_LOG_MANAGER_H_
diff --git a/chromium/content/browser/webrtc/webrtc_stress_pause_browsertest.cc b/chromium/content/browser/webrtc/webrtc_stress_pause_browsertest.cc
index e95a00a2fc9..c7248a879cb 100644
--- a/chromium/content/browser/webrtc/webrtc_stress_pause_browsertest.cc
+++ b/chromium/content/browser/webrtc/webrtc_stress_pause_browsertest.cc
@@ -17,7 +17,7 @@ namespace content {
namespace {
#if defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER) || \
- defined(SYZYASAN) || defined(MEMORY_SANITIZER)
+ defined(MEMORY_SANITIZER)
static const int kTestDurationSecs = 2;
static const int kNumPeerConnections = 3;
#else
diff --git a/chromium/content/browser/webrtc/webrtc_stress_resolution_switch_browsertest.cc b/chromium/content/browser/webrtc/webrtc_stress_resolution_switch_browsertest.cc
index 1494d11b692..2af0209bf70 100644
--- a/chromium/content/browser/webrtc/webrtc_stress_resolution_switch_browsertest.cc
+++ b/chromium/content/browser/webrtc/webrtc_stress_resolution_switch_browsertest.cc
@@ -17,7 +17,7 @@ namespace content {
namespace {
#if defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER) || \
- defined(SYZYASAN) || defined(MEMORY_SANITIZER)
+ defined(MEMORY_SANITIZER)
static const int kTestDurationSecs = 2;
static const int kNumPeerConnections = 3;
#else
diff --git a/chromium/content/browser/webrtc/webrtc_stress_source_switch_browsertest.cc b/chromium/content/browser/webrtc/webrtc_stress_source_switch_browsertest.cc
index 0924d9ec30e..86f3aa1e3b5 100644
--- a/chromium/content/browser/webrtc/webrtc_stress_source_switch_browsertest.cc
+++ b/chromium/content/browser/webrtc/webrtc_stress_source_switch_browsertest.cc
@@ -17,7 +17,7 @@ namespace content {
namespace {
#if defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER) || \
- defined(SYZYASAN) || defined(MEMORY_SANITIZER)
+ defined(MEMORY_SANITIZER)
static const int kTestDurationSecs = 2;
static const int kNumPeerConnections = 3;
#else
diff --git a/chromium/content/browser/websockets/OWNERS b/chromium/content/browser/websockets/OWNERS
index 4546121a80f..d5f50691953 100644
--- a/chromium/content/browser/websockets/OWNERS
+++ b/chromium/content/browser/websockets/OWNERS
@@ -1,5 +1,4 @@
ricea@chromium.org
-tyoshino@chromium.org
yhirano@chromium.org
# TEAM: blink-network-dev@chromium.org
diff --git a/chromium/content/browser/websockets/README.md b/chromium/content/browser/websockets/README.md
index 6f779410d02..80f5e442af1 100644
--- a/chromium/content/browser/websockets/README.md
+++ b/chromium/content/browser/websockets/README.md
@@ -1,5 +1,5 @@
# WebSocket service
-This directory contains the blink::mojom::WebSocket implementation. It hosts
+This directory contains the network::mojom::WebSocket implementation. It hosts
the WebSocket API implementations in Blink over Mojo, and exports the WebSocket
protocol implementation in net/websockets/ as a service.
diff --git a/chromium/content/browser/websockets/websocket_impl.cc b/chromium/content/browser/websockets/websocket_impl.cc
deleted file mode 100644
index 7fe30887b24..00000000000
--- a/chromium/content/browser/websockets/websocket_impl.cc
+++ /dev/null
@@ -1,533 +0,0 @@
-// Copyright 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/browser/websockets/websocket_impl.h"
-
-#include <inttypes.h>
-
-#include <utility>
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#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_util.h"
-#include "base/strings/stringprintf.h"
-#include "base/threading/thread_task_runner_handle.h"
-#include "content/browser/bad_message.h"
-#include "content/browser/child_process_security_policy_impl.h"
-#include "content/browser/ssl/ssl_error_handler.h"
-#include "content/browser/ssl/ssl_manager.h"
-#include "content/browser/websockets/websocket_handshake_request_info_impl.h"
-#include "content/public/browser/storage_partition.h"
-#include "ipc/ipc_message.h"
-#include "net/base/io_buffer.h"
-#include "net/base/net_errors.h"
-#include "net/http/http_request_headers.h"
-#include "net/http/http_response_headers.h"
-#include "net/http/http_util.h"
-#include "net/ssl/ssl_info.h"
-#include "net/url_request/url_request_context_getter.h"
-#include "net/websockets/websocket_channel.h"
-#include "net/websockets/websocket_errors.h"
-#include "net/websockets/websocket_event_interface.h"
-#include "net/websockets/websocket_frame.h" // for WebSocketFrameHeader::OpCode
-#include "net/websockets/websocket_handshake_request_info.h"
-#include "net/websockets/websocket_handshake_response_info.h"
-
-namespace content {
-namespace {
-
-typedef net::WebSocketEventInterface::ChannelState ChannelState;
-
-// Convert a blink::mojom::WebSocketMessageType to a
-// net::WebSocketFrameHeader::OpCode
-net::WebSocketFrameHeader::OpCode MessageTypeToOpCode(
- blink::mojom::WebSocketMessageType type) {
- DCHECK(type == blink::mojom::WebSocketMessageType::CONTINUATION ||
- type == blink::mojom::WebSocketMessageType::TEXT ||
- type == blink::mojom::WebSocketMessageType::BINARY);
- typedef net::WebSocketFrameHeader::OpCode OpCode;
- // These compile asserts verify that the same underlying values are used for
- // both types, so we can simply cast between them.
- static_assert(
- static_cast<OpCode>(blink::mojom::WebSocketMessageType::CONTINUATION) ==
- net::WebSocketFrameHeader::kOpCodeContinuation,
- "enum values must match for opcode continuation");
- static_assert(
- static_cast<OpCode>(blink::mojom::WebSocketMessageType::TEXT) ==
- net::WebSocketFrameHeader::kOpCodeText,
- "enum values must match for opcode text");
- static_assert(
- static_cast<OpCode>(blink::mojom::WebSocketMessageType::BINARY) ==
- net::WebSocketFrameHeader::kOpCodeBinary,
- "enum values must match for opcode binary");
- return static_cast<OpCode>(type);
-}
-
-blink::mojom::WebSocketMessageType OpCodeToMessageType(
- net::WebSocketFrameHeader::OpCode opCode) {
- DCHECK(opCode == net::WebSocketFrameHeader::kOpCodeContinuation ||
- opCode == net::WebSocketFrameHeader::kOpCodeText ||
- opCode == net::WebSocketFrameHeader::kOpCodeBinary);
- // This cast is guaranteed valid by the static_assert() statements above.
- return static_cast<blink::mojom::WebSocketMessageType>(opCode);
-}
-
-} // namespace
-
-// Implementation of net::WebSocketEventInterface. Receives events from our
-// WebSocketChannel object.
-class WebSocketImpl::WebSocketEventHandler final
- : public net::WebSocketEventInterface {
- public:
- explicit WebSocketEventHandler(WebSocketImpl* impl);
- ~WebSocketEventHandler() override;
-
- // net::WebSocketEventInterface implementation
-
- void OnCreateURLRequest(net::URLRequest* url_request) override;
- ChannelState OnAddChannelResponse(const std::string& selected_subprotocol,
- const std::string& extensions) override;
- ChannelState OnDataFrame(bool fin,
- WebSocketMessageType type,
- scoped_refptr<net::IOBuffer> buffer,
- size_t buffer_size) override;
- ChannelState OnClosingHandshake() override;
- ChannelState OnFlowControl(int64_t quota) override;
- ChannelState OnDropChannel(bool was_clean,
- uint16_t code,
- const std::string& reason) override;
- ChannelState OnFailChannel(const std::string& message) override;
- ChannelState OnStartOpeningHandshake(
- std::unique_ptr<net::WebSocketHandshakeRequestInfo> request) override;
- ChannelState OnFinishOpeningHandshake(
- std::unique_ptr<net::WebSocketHandshakeResponseInfo> response) override;
- ChannelState OnSSLCertificateError(
- std::unique_ptr<net::WebSocketEventInterface::SSLErrorCallbacks>
- callbacks,
- const GURL& url,
- const net::SSLInfo& ssl_info,
- bool fatal) override;
-
- private:
- class SSLErrorHandlerDelegate final : public SSLErrorHandler::Delegate {
- public:
- SSLErrorHandlerDelegate(
- std::unique_ptr<net::WebSocketEventInterface::SSLErrorCallbacks>
- callbacks);
- ~SSLErrorHandlerDelegate() override;
-
- base::WeakPtr<SSLErrorHandler::Delegate> GetWeakPtr();
-
- // SSLErrorHandler::Delegate methods
- void CancelSSLRequest(int error, const net::SSLInfo* ssl_info) override;
- void ContinueSSLRequest() override;
-
- private:
- std::unique_ptr<net::WebSocketEventInterface::SSLErrorCallbacks> callbacks_;
- base::WeakPtrFactory<SSLErrorHandlerDelegate> weak_ptr_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(SSLErrorHandlerDelegate);
- };
-
- WebSocketImpl* const impl_;
- std::unique_ptr<SSLErrorHandlerDelegate> ssl_error_handler_delegate_;
-
- DISALLOW_COPY_AND_ASSIGN(WebSocketEventHandler);
-};
-
-WebSocketImpl::WebSocketEventHandler::WebSocketEventHandler(WebSocketImpl* impl)
- : impl_(impl) {
- DVLOG(1) << "WebSocketEventHandler created @"
- << reinterpret_cast<void*>(this);
-}
-
-WebSocketImpl::WebSocketEventHandler::~WebSocketEventHandler() {
- DVLOG(1) << "WebSocketEventHandler destroyed @"
- << reinterpret_cast<void*>(this);
-}
-
-void WebSocketImpl::WebSocketEventHandler::OnCreateURLRequest(
- net::URLRequest* url_request) {
- WebSocketHandshakeRequestInfoImpl::CreateInfoAndAssociateWithRequest(
- impl_->child_id_, impl_->frame_id_, url_request);
-}
-
-ChannelState WebSocketImpl::WebSocketEventHandler::OnAddChannelResponse(
- const std::string& selected_protocol,
- const std::string& extensions) {
- DVLOG(3) << "WebSocketEventHandler::OnAddChannelResponse @"
- << reinterpret_cast<void*>(this)
- << " selected_protocol=\"" << selected_protocol << "\""
- << " extensions=\"" << extensions << "\"";
-
- impl_->delegate_->OnReceivedResponseFromServer(impl_);
-
- impl_->client_->OnAddChannelResponse(selected_protocol, extensions);
-
- return net::WebSocketEventInterface::CHANNEL_ALIVE;
-}
-
-ChannelState WebSocketImpl::WebSocketEventHandler::OnDataFrame(
- bool fin,
- net::WebSocketFrameHeader::OpCode type,
- scoped_refptr<net::IOBuffer> buffer,
- size_t buffer_size) {
- DVLOG(3) << "WebSocketEventHandler::OnDataFrame @"
- << reinterpret_cast<void*>(this)
- << " fin=" << fin
- << " type=" << type << " data is " << buffer_size << " bytes";
-
- // TODO(darin): Avoid this copy.
- std::vector<uint8_t> data_to_pass(buffer_size);
- if (buffer_size > 0) {
- std::copy(buffer->data(), buffer->data() + buffer_size,
- data_to_pass.begin());
- }
-
- impl_->client_->OnDataFrame(fin, OpCodeToMessageType(type), data_to_pass);
-
- return net::WebSocketEventInterface::CHANNEL_ALIVE;
-}
-
-ChannelState WebSocketImpl::WebSocketEventHandler::OnClosingHandshake() {
- DVLOG(3) << "WebSocketEventHandler::OnClosingHandshake @"
- << reinterpret_cast<void*>(this);
-
- impl_->client_->OnClosingHandshake();
-
- return net::WebSocketEventInterface::CHANNEL_ALIVE;
-}
-
-ChannelState WebSocketImpl::WebSocketEventHandler::OnFlowControl(
- int64_t quota) {
- DVLOG(3) << "WebSocketEventHandler::OnFlowControl @"
- << reinterpret_cast<void*>(this)
- << " quota=" << quota;
-
- impl_->client_->OnFlowControl(quota);
-
- return net::WebSocketEventInterface::CHANNEL_ALIVE;
-}
-
-ChannelState WebSocketImpl::WebSocketEventHandler::OnDropChannel(
- bool was_clean,
- uint16_t code,
- const std::string& reason) {
- DVLOG(3) << "WebSocketEventHandler::OnDropChannel @"
- << reinterpret_cast<void*>(this)
- << " was_clean=" << was_clean << " code=" << code
- << " reason=\"" << reason << "\"";
-
- impl_->client_->OnDropChannel(was_clean, code, reason);
-
- // net::WebSocketChannel requires that we delete it at this point.
- impl_->channel_.reset();
-
- return net::WebSocketEventInterface::CHANNEL_DELETED;
-}
-
-ChannelState WebSocketImpl::WebSocketEventHandler::OnFailChannel(
- const std::string& message) {
- DVLOG(3) << "WebSocketEventHandler::OnFailChannel @"
- << reinterpret_cast<void*>(this) << " message=\"" << message << "\"";
-
- impl_->client_->OnFailChannel(message);
-
- // net::WebSocketChannel requires that we delete it at this point.
- impl_->channel_.reset();
-
- return net::WebSocketEventInterface::CHANNEL_DELETED;
-}
-
-ChannelState WebSocketImpl::WebSocketEventHandler::OnStartOpeningHandshake(
- std::unique_ptr<net::WebSocketHandshakeRequestInfo> request) {
- bool should_send =
- ChildProcessSecurityPolicyImpl::GetInstance()->CanReadRawCookies(
- impl_->delegate_->GetClientProcessId());
-
- DVLOG(3) << "WebSocketEventHandler::OnStartOpeningHandshake @"
- << reinterpret_cast<void*>(this) << " should_send=" << should_send;
-
- if (!should_send)
- return WebSocketEventInterface::CHANNEL_ALIVE;
-
- blink::mojom::WebSocketHandshakeRequestPtr request_to_pass(
- blink::mojom::WebSocketHandshakeRequest::New());
- request_to_pass->url.Swap(&request->url);
- net::HttpRequestHeaders::Iterator it(request->headers);
- while (it.GetNext()) {
- blink::mojom::HttpHeaderPtr header(blink::mojom::HttpHeader::New());
- header->name = it.name();
- header->value = it.value();
- request_to_pass->headers.push_back(std::move(header));
- }
- request_to_pass->headers_text =
- base::StringPrintf("GET %s HTTP/1.1\r\n",
- request_to_pass->url.spec().c_str()) +
- request->headers.ToString();
-
- impl_->client_->OnStartOpeningHandshake(std::move(request_to_pass));
-
- return WebSocketEventInterface::CHANNEL_ALIVE;
-}
-
-ChannelState WebSocketImpl::WebSocketEventHandler::OnFinishOpeningHandshake(
- std::unique_ptr<net::WebSocketHandshakeResponseInfo> response) {
- bool should_send =
- ChildProcessSecurityPolicyImpl::GetInstance()->CanReadRawCookies(
- impl_->delegate_->GetClientProcessId());
-
- DVLOG(3) << "WebSocketEventHandler::OnFinishOpeningHandshake "
- << reinterpret_cast<void*>(this) << " should_send=" << should_send;
-
- if (!should_send)
- return WebSocketEventInterface::CHANNEL_ALIVE;
-
- blink::mojom::WebSocketHandshakeResponsePtr response_to_pass(
- blink::mojom::WebSocketHandshakeResponse::New());
- response_to_pass->url.Swap(&response->url);
- response_to_pass->status_code = response->status_code;
- response_to_pass->status_text = response->status_text;
- size_t iter = 0;
- std::string name, value;
- while (response->headers->EnumerateHeaderLines(&iter, &name, &value)) {
- blink::mojom::HttpHeaderPtr header(blink::mojom::HttpHeader::New());
- header->name = name;
- header->value = value;
- response_to_pass->headers.push_back(std::move(header));
- }
- response_to_pass->headers_text =
- net::HttpUtil::ConvertHeadersBackToHTTPResponse(
- response->headers->raw_headers());
-
- impl_->client_->OnFinishOpeningHandshake(std::move(response_to_pass));
-
- return WebSocketEventInterface::CHANNEL_ALIVE;
-}
-
-ChannelState WebSocketImpl::WebSocketEventHandler::OnSSLCertificateError(
- std::unique_ptr<net::WebSocketEventInterface::SSLErrorCallbacks> callbacks,
- const GURL& url,
- const net::SSLInfo& ssl_info,
- bool fatal) {
- DVLOG(3) << "WebSocketEventHandler::OnSSLCertificateError"
- << reinterpret_cast<void*>(this) << " url=" << url.spec()
- << " cert_status=" << ssl_info.cert_status << " fatal=" << fatal;
- ssl_error_handler_delegate_.reset(
- new SSLErrorHandlerDelegate(std::move(callbacks)));
- SSLManager::OnSSLCertificateSubresourceError(
- ssl_error_handler_delegate_->GetWeakPtr(),
- url,
- impl_->delegate_->GetClientProcessId(),
- impl_->frame_id_,
- ssl_info,
- fatal);
- // The above method is always asynchronous.
- return WebSocketEventInterface::CHANNEL_ALIVE;
-}
-
-WebSocketImpl::WebSocketEventHandler::SSLErrorHandlerDelegate::
- SSLErrorHandlerDelegate(
- std::unique_ptr<net::WebSocketEventInterface::SSLErrorCallbacks>
- callbacks)
- : callbacks_(std::move(callbacks)), weak_ptr_factory_(this) {}
-
-WebSocketImpl::WebSocketEventHandler::SSLErrorHandlerDelegate::
- ~SSLErrorHandlerDelegate() {}
-
-base::WeakPtr<SSLErrorHandler::Delegate>
-WebSocketImpl::WebSocketEventHandler::SSLErrorHandlerDelegate::GetWeakPtr() {
- return weak_ptr_factory_.GetWeakPtr();
-}
-
-void WebSocketImpl::WebSocketEventHandler::SSLErrorHandlerDelegate::
- CancelSSLRequest(int error, const net::SSLInfo* ssl_info) {
- DVLOG(3) << "SSLErrorHandlerDelegate::CancelSSLRequest"
- << " error=" << error
- << " cert_status=" << (ssl_info ? ssl_info->cert_status
- : static_cast<net::CertStatus>(-1));
- callbacks_->CancelSSLRequest(error, ssl_info);
-}
-
-void WebSocketImpl::WebSocketEventHandler::SSLErrorHandlerDelegate::
- ContinueSSLRequest() {
- DVLOG(3) << "SSLErrorHandlerDelegate::ContinueSSLRequest";
- callbacks_->ContinueSSLRequest();
-}
-
-WebSocketImpl::WebSocketImpl(Delegate* delegate,
- blink::mojom::WebSocketRequest request,
- int child_id,
- int frame_id,
- url::Origin origin,
- base::TimeDelta delay)
- : delegate_(delegate),
- binding_(this, std::move(request)),
- delay_(delay),
- pending_flow_control_quota_(0),
- child_id_(child_id),
- frame_id_(frame_id),
- origin_(std::move(origin)),
- handshake_succeeded_(false),
- weak_ptr_factory_(this) {
- binding_.set_connection_error_handler(base::BindOnce(
- &WebSocketImpl::OnConnectionError, base::Unretained(this)));
-}
-
-WebSocketImpl::~WebSocketImpl() {}
-
-void WebSocketImpl::GoAway() {
- StartClosingHandshake(static_cast<uint16_t>(net::kWebSocketErrorGoingAway),
- "");
-}
-
-void WebSocketImpl::AddChannelRequest(
- const GURL& socket_url,
- const std::vector<std::string>& requested_protocols,
- const GURL& site_for_cookies,
- const std::string& user_agent_override,
- blink::mojom::WebSocketClientPtr client) {
- DVLOG(3) << "WebSocketImpl::AddChannelRequest @"
- << reinterpret_cast<void*>(this) << " socket_url=\"" << socket_url
- << "\" requested_protocols=\""
- << base::JoinString(requested_protocols, ", ") << "\" origin=\""
- << origin_ << "\" site_for_cookies=\"" << site_for_cookies
- << "\" user_agent_override=\"" << user_agent_override << "\"";
-
- if (client_ || !client) {
- bad_message::ReceivedBadMessage(
- delegate_->GetClientProcessId(),
- bad_message::WSI_UNEXPECTED_ADD_CHANNEL_REQUEST);
- return;
- }
-
- client_ = std::move(client);
-
- DCHECK(!channel_);
- if (delay_ > base::TimeDelta()) {
- base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
- FROM_HERE,
- base::BindOnce(&WebSocketImpl::AddChannel,
- weak_ptr_factory_.GetWeakPtr(), socket_url,
- requested_protocols, site_for_cookies,
- user_agent_override),
- delay_);
- } else {
- AddChannel(socket_url, requested_protocols, site_for_cookies,
- user_agent_override);
- }
-}
-
-void WebSocketImpl::SendFrame(bool fin,
- blink::mojom::WebSocketMessageType type,
- const std::vector<uint8_t>& data) {
- DVLOG(3) << "WebSocketImpl::SendFrame @"
- << reinterpret_cast<void*>(this) << " fin=" << fin
- << " type=" << type << " data is " << data.size() << " bytes";
-
- if (!channel_) {
- // The client should not be sending us frames until after we've informed
- // it that the channel has been opened (OnAddChannelResponse).
- if (handshake_succeeded_) {
- DVLOG(1) << "Dropping frame sent to closed websocket";
- } else {
- bad_message::ReceivedBadMessage(
- delegate_->GetClientProcessId(),
- bad_message::WSI_UNEXPECTED_SEND_FRAME);
- }
- return;
- }
-
- // TODO(darin): Avoid this copy.
- scoped_refptr<net::IOBuffer> data_to_pass(new net::IOBuffer(data.size()));
- std::copy(data.begin(), data.end(), data_to_pass->data());
-
- channel_->SendFrame(fin, MessageTypeToOpCode(type), std::move(data_to_pass),
- data.size());
-}
-
-void WebSocketImpl::SendFlowControl(int64_t quota) {
- DVLOG(3) << "WebSocketImpl::OnFlowControl @"
- << reinterpret_cast<void*>(this) << " quota=" << quota;
-
- if (!channel_) {
- // WebSocketChannel is not yet created due to the delay introduced by
- // per-renderer WebSocket throttling.
- // SendFlowControl() is called after WebSocketChannel is created.
- pending_flow_control_quota_ += quota;
- return;
- }
-
- ignore_result(channel_->SendFlowControl(quota));
-}
-
-void WebSocketImpl::StartClosingHandshake(uint16_t code,
- const std::string& reason) {
- DVLOG(3) << "WebSocketImpl::StartClosingHandshake @"
- << reinterpret_cast<void*>(this)
- << " code=" << code << " reason=\"" << reason << "\"";
-
- if (!channel_) {
- // WebSocketChannel is not yet created due to the delay introduced by
- // per-renderer WebSocket throttling.
- if (client_)
- client_->OnDropChannel(false, net::kWebSocketErrorAbnormalClosure, "");
- return;
- }
-
- ignore_result(channel_->StartClosingHandshake(code, reason));
-}
-
-void WebSocketImpl::OnConnectionError() {
- DVLOG(3) << "WebSocketImpl::OnConnectionError @"
- << reinterpret_cast<void*>(this);
-
- delegate_->OnLostConnectionToClient(this);
-}
-
-void WebSocketImpl::AddChannel(
- const GURL& socket_url,
- const std::vector<std::string>& requested_protocols,
- const GURL& site_for_cookies,
- const std::string& user_agent_override) {
- DVLOG(3) << "WebSocketImpl::AddChannel @" << reinterpret_cast<void*>(this)
- << " socket_url=\"" << socket_url << "\" requested_protocols=\""
- << base::JoinString(requested_protocols, ", ") << "\" origin=\""
- << origin_ << "\" site_for_cookies=\"" << site_for_cookies
- << "\" user_agent_override=\"" << user_agent_override << "\"";
-
- DCHECK(!channel_);
-
- std::unique_ptr<net::WebSocketEventInterface> event_interface(
- new WebSocketEventHandler(this));
- channel_.reset(new net::WebSocketChannel(std::move(event_interface),
- delegate_->GetURLRequestContext()));
-
- int64_t quota = pending_flow_control_quota_;
- pending_flow_control_quota_ = 0;
-
- std::string additional_headers;
- if (!user_agent_override.empty()) {
- if (!net::HttpUtil::IsValidHeaderValue(user_agent_override)) {
- bad_message::ReceivedBadMessage(
- delegate_->GetClientProcessId(),
- bad_message::WSI_INVALID_HEADER_VALUE);
- return;
- }
- additional_headers = base::StringPrintf("%s:%s",
- net::HttpRequestHeaders::kUserAgent,
- user_agent_override.c_str());
- }
- channel_->SendAddChannelRequest(socket_url, requested_protocols, origin_,
- site_for_cookies, additional_headers);
- if (quota > 0)
- SendFlowControl(quota);
-}
-
-} // namespace content
diff --git a/chromium/content/browser/websockets/websocket_impl.h b/chromium/content/browser/websockets/websocket_impl.h
deleted file mode 100644
index 996a443c4e8..00000000000
--- a/chromium/content/browser/websockets/websocket_impl.h
+++ /dev/null
@@ -1,112 +0,0 @@
-// Copyright 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_BROWSER_WEBSOCKETS_WEBSOCKET_IMPL_H_
-#define CONTENT_BROWSER_WEBSOCKETS_WEBSOCKET_IMPL_H_
-
-#include <stdint.h>
-
-#include <memory>
-#include <string>
-#include <vector>
-
-#include "base/macros.h"
-#include "base/memory/weak_ptr.h"
-#include "base/time/time.h"
-#include "content/common/content_export.h"
-#include "mojo/public/cpp/bindings/binding.h"
-#include "third_party/WebKit/public/platform/modules/websockets/websocket.mojom.h"
-#include "url/origin.h"
-
-class GURL;
-
-namespace net {
-class URLRequestContext;
-class WebSocketChannel;
-} // namespace net
-
-namespace content {
-
-// Host of net::WebSocketChannel.
-class CONTENT_EXPORT WebSocketImpl : public blink::mojom::WebSocket {
- public:
- class Delegate {
- public:
- virtual ~Delegate() {}
- virtual int GetClientProcessId() = 0;
- virtual net::URLRequestContext* GetURLRequestContext() = 0;
- virtual void OnReceivedResponseFromServer(WebSocketImpl* impl) = 0;
- virtual void OnLostConnectionToClient(WebSocketImpl* impl) = 0;
- };
-
- WebSocketImpl(Delegate* delegate,
- blink::mojom::WebSocketRequest request,
- int child_id,
- int frame_id,
- url::Origin origin,
- base::TimeDelta delay);
- ~WebSocketImpl() override;
-
- // The renderer process is going away.
- // This function is virtual for testing.
- virtual void GoAway();
-
- // blink::mojom::WebSocket methods:
- void AddChannelRequest(const GURL& url,
- const std::vector<std::string>& requested_protocols,
- const GURL& site_for_cookies,
- const std::string& user_agent_override,
- blink::mojom::WebSocketClientPtr client) override;
- void SendFrame(bool fin,
- blink::mojom::WebSocketMessageType type,
- const std::vector<uint8_t>& data) override;
- void SendFlowControl(int64_t quota) override;
- void StartClosingHandshake(uint16_t code, const std::string& reason) override;
-
- bool handshake_succeeded() const { return handshake_succeeded_; }
- void OnHandshakeSucceeded() { handshake_succeeded_ = true; }
-
- protected:
- class WebSocketEventHandler;
-
- void OnConnectionError();
- void AddChannel(const GURL& socket_url,
- const std::vector<std::string>& requested_protocols,
- const GURL& site_for_cookies,
- const std::string& user_agent_override);
-
- Delegate* delegate_;
- mojo::Binding<blink::mojom::WebSocket> binding_;
-
- blink::mojom::WebSocketClientPtr client_;
-
- // The channel we use to send events to the network.
- std::unique_ptr<net::WebSocketChannel> channel_;
-
- // Delay used for per-renderer WebSocket throttling.
- base::TimeDelta delay_;
-
- // SendFlowControl() is delayed when OnFlowControl() is called before
- // AddChannel() is called.
- // Zero indicates there is no pending SendFlowControl().
- int64_t pending_flow_control_quota_;
-
- int child_id_;
- int frame_id_;
-
- // The web origin to use for the WebSocket.
- const url::Origin origin_;
-
- // handshake_succeeded_ is set and used by WebSocketManager to manage
- // counters for per-renderer WebSocket throttling.
- bool handshake_succeeded_;
-
- base::WeakPtrFactory<WebSocketImpl> weak_ptr_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(WebSocketImpl);
-};
-
-} // namespace content
-
-#endif // CONTENT_BROWSER_WEBSOCKETS_WEBSOCKET_IMPL_H_
diff --git a/chromium/content/browser/websockets/websocket_manager.cc b/chromium/content/browser/websockets/websocket_manager.cc
index ce41b4a534f..fad1a1d3cb4 100644
--- a/chromium/content/browser/websockets/websocket_manager.cc
+++ b/chromium/content/browser/websockets/websocket_manager.cc
@@ -11,8 +11,13 @@
#include "base/callback.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
+#include "base/memory/weak_ptr.h"
#include "base/numerics/safe_conversions.h"
-#include "base/rand_util.h"
+#include "content/browser/bad_message.h"
+#include "content/browser/child_process_security_policy_impl.h"
+#include "content/browser/ssl/ssl_error_handler.h"
+#include "content/browser/ssl/ssl_manager.h"
+#include "content/browser/websockets/websocket_handshake_request_info_impl.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
@@ -25,12 +30,109 @@ namespace {
const char kWebSocketManagerKeyName[] = "web_socket_manager";
-// Max number of pending connections per WebSocketManager used for per-renderer
-// WebSocket throttling.
-const int kMaxPendingWebSocketConnections = 255;
-
} // namespace
+class WebSocketManager::Delegate final : public network::WebSocket::Delegate {
+ public:
+ explicit Delegate(WebSocketManager* manager) : manager_(manager) {}
+ ~Delegate() override {}
+
+ net::URLRequestContext* GetURLRequestContext() override {
+ return manager_->GetURLRequestContext();
+ }
+
+ void OnLostConnectionToClient(network::WebSocket* impl) override {
+ manager_->OnLostConnectionToClient(impl);
+ }
+
+ void OnSSLCertificateError(
+ std::unique_ptr<net::WebSocketEventInterface::SSLErrorCallbacks>
+ callbacks,
+ const GURL& url,
+ int child_id,
+ int frame_id,
+ const net::SSLInfo& ssl_info,
+ bool fatal) override {
+ ssl_error_handler_delegate_ =
+ std::make_unique<SSLErrorHandlerDelegate>(std::move(callbacks));
+ SSLManager::OnSSLCertificateSubresourceError(
+ ssl_error_handler_delegate_->GetWeakPtr(), url, child_id, frame_id,
+ ssl_info, fatal);
+ }
+
+ void ReportBadMessage(BadMessageReason reason,
+ network::WebSocket* impl) override {
+ bad_message::BadMessageReason reason_to_pass =
+ bad_message::WSI_INVALID_HEADER_VALUE;
+ switch (reason) {
+ case BadMessageReason::kInvalidHeaderValue:
+ reason_to_pass = bad_message::WSI_INVALID_HEADER_VALUE;
+ break;
+ case BadMessageReason::kUnexpectedAddChannelRequest:
+ reason_to_pass = bad_message::WSI_UNEXPECTED_ADD_CHANNEL_REQUEST;
+ break;
+ case BadMessageReason::kUnexpectedSendFrame:
+ reason_to_pass = bad_message::WSI_UNEXPECTED_SEND_FRAME;
+ break;
+ }
+ bad_message::ReceivedBadMessage(manager_->process_id_, reason_to_pass);
+ OnLostConnectionToClient(impl);
+ }
+
+ bool CanReadRawCookies() override {
+ return ChildProcessSecurityPolicyImpl::GetInstance()->CanReadRawCookies(
+ manager_->process_id_);
+ }
+
+ void OnCreateURLRequest(int child_id,
+ int frame_id,
+ net::URLRequest* url_request) override {
+ WebSocketHandshakeRequestInfoImpl::CreateInfoAndAssociateWithRequest(
+ child_id, frame_id, url_request);
+ }
+
+ private:
+ class SSLErrorHandlerDelegate final : public SSLErrorHandler::Delegate {
+ public:
+ explicit SSLErrorHandlerDelegate(
+ std::unique_ptr<net::WebSocketEventInterface::SSLErrorCallbacks>
+ callbacks)
+ : callbacks_(std::move(callbacks)), weak_ptr_factory_(this) {}
+ ~SSLErrorHandlerDelegate() override {}
+
+ base::WeakPtr<SSLErrorHandler::Delegate> GetWeakPtr() {
+ return weak_ptr_factory_.GetWeakPtr();
+ }
+
+ // SSLErrorHandler::Delegate methods
+ void CancelSSLRequest(int error, const net::SSLInfo* ssl_info) override {
+ DVLOG(3) << "SSLErrorHandlerDelegate::CancelSSLRequest"
+ << " error=" << error << " cert_status="
+ << (ssl_info ? ssl_info->cert_status
+ : static_cast<net::CertStatus>(-1));
+ callbacks_->CancelSSLRequest(error, ssl_info);
+ }
+
+ void ContinueSSLRequest() override {
+ DVLOG(3) << "SSLErrorHandlerDelegate::ContinueSSLRequest";
+ callbacks_->ContinueSSLRequest();
+ }
+
+ private:
+ std::unique_ptr<net::WebSocketEventInterface::SSLErrorCallbacks> callbacks_;
+
+ base::WeakPtrFactory<SSLErrorHandlerDelegate> weak_ptr_factory_;
+
+ DISALLOW_COPY_AND_ASSIGN(SSLErrorHandlerDelegate);
+ };
+
+ std::unique_ptr<SSLErrorHandlerDelegate> ssl_error_handler_delegate_;
+ // |manager_| outlives this object.
+ WebSocketManager* const manager_;
+
+ DISALLOW_COPY_AND_ASSIGN(Delegate);
+};
+
class WebSocketManager::Handle : public base::SupportsUserData::Data,
public RenderProcessHostObserver {
public:
@@ -58,7 +160,7 @@ class WebSocketManager::Handle : public base::SupportsUserData::Data,
void WebSocketManager::CreateWebSocketForFrame(
int process_id,
int frame_id,
- blink::mojom::WebSocketRequest request) {
+ network::mojom::WebSocketRequest request) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// ForFrame() implies a frame: DCHECK this pre-condition.
@@ -73,7 +175,7 @@ void WebSocketManager::CreateWebSocketForFrame(
void WebSocketManager::CreateWebSocketWithOrigin(
int process_id,
url::Origin origin,
- blink::mojom::WebSocketRequest request,
+ network::mojom::WebSocketRequest request,
int frame_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
@@ -105,11 +207,6 @@ void WebSocketManager::CreateWebSocketWithOrigin(
WebSocketManager::WebSocketManager(int process_id,
StoragePartition* storage_partition)
: process_id_(process_id),
- num_pending_connections_(0),
- num_current_succeeded_connections_(0),
- num_previous_succeeded_connections_(0),
- num_current_failed_connections_(0),
- num_previous_failed_connections_(0),
context_destroyed_(false) {
if (storage_partition) {
url_request_context_getter_ = storage_partition->GetURLRequestContext();
@@ -129,40 +226,39 @@ WebSocketManager::~WebSocketManager() {
if (!context_destroyed_ && url_request_context_getter_)
url_request_context_getter_->RemoveObserver(this);
- for (auto* impl : impls_) {
+ for (const auto& impl : impls_) {
impl->GoAway();
- delete impl;
}
}
void WebSocketManager::DoCreateWebSocket(
int frame_id,
url::Origin origin,
- blink::mojom::WebSocketRequest request) {
+ network::mojom::WebSocketRequest request) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
- if (num_pending_connections_ >= kMaxPendingWebSocketConnections) {
+ if (throttler_.HasTooManyPendingConnections()) {
// Too many websockets!
request.ResetWithReason(
- blink::mojom::WebSocket::kInsufficientResources,
+ network::mojom::WebSocket::kInsufficientResources,
"Error in connection establishment: net::ERR_INSUFFICIENT_RESOURCES");
return;
}
if (context_destroyed_) {
request.ResetWithReason(
- blink::mojom::WebSocket::kInsufficientResources,
+ network::mojom::WebSocket::kInsufficientResources,
"Error in connection establishment: net::ERR_UNEXPECTED");
return;
}
- // Keep all WebSocketImpls alive until either the client drops its
+ // Keep all network::WebSockets alive until either the client drops its
// connection (see OnLostConnectionToClient) or we need to shutdown.
- impls_.insert(CreateWebSocketImpl(this, std::move(request), process_id_,
- frame_id, std::move(origin),
- CalculateDelay()));
- ++num_pending_connections_;
+ impls_.insert(CreateWebSocket(
+ std::make_unique<Delegate>(this), std::move(request),
+ throttler_.IssuePendingConnectionTracker(), process_id_, frame_id,
+ std::move(origin), throttler_.CalculateDelay()));
if (!throttling_period_timer_.IsRunning()) {
throttling_period_timer_.Start(
@@ -173,79 +269,43 @@ void WebSocketManager::DoCreateWebSocket(
}
}
-// Calculate delay as described in the per-renderer WebSocket throttling
-// design doc: https://goo.gl/tldFNn
-base::TimeDelta WebSocketManager::CalculateDelay() const {
- int64_t f = num_previous_failed_connections_ +
- num_current_failed_connections_;
- int64_t s = num_previous_succeeded_connections_ +
- num_current_succeeded_connections_;
- int p = num_pending_connections_;
- return base::TimeDelta::FromMilliseconds(
- base::RandInt(1000, 5000) *
- (1 << std::min(p + f / (s + 1), INT64_C(16))) / 65536);
-}
-
void WebSocketManager::ThrottlingPeriodTimerCallback() {
- num_previous_failed_connections_ = num_current_failed_connections_;
- num_current_failed_connections_ = 0;
-
- num_previous_succeeded_connections_ = num_current_succeeded_connections_;
- num_current_succeeded_connections_ = 0;
-
- if (num_pending_connections_ == 0 &&
- num_previous_failed_connections_ == 0 &&
- num_previous_succeeded_connections_ == 0) {
+ throttler_.Roll();
+ if (throttler_.IsClean())
throttling_period_timer_.Stop();
- }
}
-WebSocketImpl* WebSocketManager::CreateWebSocketImpl(
- WebSocketImpl::Delegate* delegate,
- blink::mojom::WebSocketRequest request,
+std::unique_ptr<network::WebSocket> WebSocketManager::CreateWebSocket(
+ std::unique_ptr<network::WebSocket::Delegate> delegate,
+ network::mojom::WebSocketRequest request,
+ network::WebSocketThrottler::PendingConnection pending_connection_tracker,
int child_id,
int frame_id,
url::Origin origin,
base::TimeDelta delay) {
- return new WebSocketImpl(delegate, std::move(request), child_id, frame_id,
- std::move(origin), delay);
-}
-
-int WebSocketManager::GetClientProcessId() {
- return process_id_;
+ return std::make_unique<network::WebSocket>(
+ std::move(delegate), std::move(request),
+ std::move(pending_connection_tracker), child_id, frame_id,
+ std::move(origin), delay);
}
net::URLRequestContext* WebSocketManager::GetURLRequestContext() {
return url_request_context_getter_->GetURLRequestContext();
}
-void WebSocketManager::OnReceivedResponseFromServer(WebSocketImpl* impl) {
- // The server accepted this WebSocket connection.
- impl->OnHandshakeSucceeded();
- --num_pending_connections_;
- DCHECK_GE(num_pending_connections_, 0);
- ++num_current_succeeded_connections_;
-}
-
-void WebSocketManager::OnLostConnectionToClient(WebSocketImpl* impl) {
+void WebSocketManager::OnLostConnectionToClient(network::WebSocket* impl) {
// The client is no longer interested in this WebSocket.
- if (!impl->handshake_succeeded()) {
- // Update throttling counters (failure).
- --num_pending_connections_;
- DCHECK_GE(num_pending_connections_, 0);
- ++num_current_failed_connections_;
- }
impl->GoAway();
- impls_.erase(impl);
- delete impl;
+ const auto it = impls_.find(impl);
+ DCHECK(it != impls_.end());
+ impls_.erase(it);
}
void WebSocketManager::OnContextShuttingDown() {
context_destroyed_ = true;
url_request_context_getter_ = nullptr;
- for (auto* impl : impls_) {
+ for (const auto& impl : impls_) {
impl->GoAway();
- delete impl;
}
impls_.clear();
}
diff --git a/chromium/content/browser/websockets/websocket_manager.h b/chromium/content/browser/websockets/websocket_manager.h
index db02e6cfcb3..089368539cd 100644
--- a/chromium/content/browser/websockets/websocket_manager.h
+++ b/chromium/content/browser/websockets/websocket_manager.h
@@ -5,44 +5,48 @@
#ifndef CONTENT_BROWSER_WEBSOCKETS_WEBSOCKET_MANAGER_H_
#define CONTENT_BROWSER_WEBSOCKETS_WEBSOCKET_MANAGER_H_
+#include <memory>
#include <set>
#include "base/compiler_specific.h"
+#include "base/containers/unique_ptr_adapters.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/timer/timer.h"
-#include "content/browser/websockets/websocket_impl.h"
#include "content/common/content_export.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_request_context_getter_observer.h"
+#include "services/network/websocket.h"
+#include "services/network/websocket_throttler.h"
namespace content {
class StoragePartition;
// The WebSocketManager is a per child process instance that manages the
-// lifecycle of WebSocketImpl objects. It is responsible for creating
-// WebSocketImpl objects for each WebSocketRequest and throttling the number of
-// WebSocketImpl objects in use.
+// lifecycle of network::WebSocket objects. It is responsible for creating
+// network::WebSocket objects for each WebSocketRequest and throttling the
+// number of network::WebSocket objects in use.
class CONTENT_EXPORT WebSocketManager
- : public WebSocketImpl::Delegate,
- public net::URLRequestContextGetterObserver {
+ : public net::URLRequestContextGetterObserver {
public:
// Called on the UI thread: create a websocket for a frame.
static void CreateWebSocketForFrame(int process_id,
int frame_id,
- blink::mojom::WebSocketRequest request);
+ network::mojom::WebSocketRequest request);
// Called on the UI thread: create a websocket for a worker. Web workers of
// any type (dedicated, shared, service worker) do not have a frame.
- static void CreateWebSocketWithOrigin(int process_id,
- url::Origin origin,
- blink::mojom::WebSocketRequest request,
- int frame_id = MSG_ROUTING_NONE);
+ static void CreateWebSocketWithOrigin(
+ int process_id,
+ url::Origin origin,
+ network::mojom::WebSocketRequest request,
+ int frame_id = MSG_ROUTING_NONE);
// net::URLRequestContextGetterObserver implementation.
void OnContextShuttingDown() override;
protected:
+ class Delegate;
class Handle;
friend class base::DeleteHelper<WebSocketManager>;
@@ -54,47 +58,34 @@ class CONTENT_EXPORT WebSocketManager
~WebSocketManager() override;
void DoCreateWebSocket(int frame_id,
url::Origin origin,
- blink::mojom::WebSocketRequest request);
- base::TimeDelta CalculateDelay() const;
+ network::mojom::WebSocketRequest request);
void ThrottlingPeriodTimerCallback();
// This is virtual to support testing.
- virtual WebSocketImpl* CreateWebSocketImpl(
- WebSocketImpl::Delegate* delegate,
- blink::mojom::WebSocketRequest request,
+ virtual std::unique_ptr<network::WebSocket> CreateWebSocket(
+ std::unique_ptr<network::WebSocket::Delegate> delegate,
+ network::mojom::WebSocketRequest request,
+ network::WebSocketThrottler::PendingConnection pending_connection_tracker,
int child_id,
int frame_id,
url::Origin origin,
base::TimeDelta delay);
- // WebSocketImpl::Delegate methods:
- int GetClientProcessId() override;
- net::URLRequestContext* GetURLRequestContext() override;
- void OnReceivedResponseFromServer(WebSocketImpl* impl) override;
- void OnLostConnectionToClient(WebSocketImpl* impl) override;
+ net::URLRequestContext* GetURLRequestContext();
+ virtual void OnLostConnectionToClient(network::WebSocket* impl);
void ObserveURLRequestContextGetter();
int process_id_;
scoped_refptr<net::URLRequestContextGetter> url_request_context_getter_;
- std::set<WebSocketImpl*> impls_;
+ std::set<std::unique_ptr<network::WebSocket>, base::UniquePtrComparator>
+ impls_;
// Timer and counters for per-renderer WebSocket throttling.
base::RepeatingTimer throttling_period_timer_;
- // The current number of pending connections.
- int num_pending_connections_;
-
- // The number of handshakes that failed in the current and previous time
- // period.
- int64_t num_current_succeeded_connections_;
- int64_t num_previous_succeeded_connections_;
-
- // The number of handshakes that succeeded in the current and previous time
- // period.
- int64_t num_current_failed_connections_;
- int64_t num_previous_failed_connections_;
+ network::WebSocketPerProcessThrottler throttler_;
bool context_destroyed_;
diff --git a/chromium/content/browser/websockets/websocket_manager_unittest.cc b/chromium/content/browser/websockets/websocket_manager_unittest.cc
index d4614960bb4..75c97090474 100644
--- a/chromium/content/browser/websockets/websocket_manager_unittest.cc
+++ b/chromium/content/browser/websockets/websocket_manager_unittest.cc
@@ -19,20 +19,24 @@ namespace {
// This number is unlikely to occur by chance.
static const int kMagicRenderProcessId = 506116062;
-class TestWebSocketImpl : public WebSocketImpl {
+class TestWebSocketImpl : public network::WebSocket {
public:
- TestWebSocketImpl(Delegate* delegate,
- blink::mojom::WebSocketRequest request,
- int process_id,
- int frame_id,
- url::Origin origin,
- base::TimeDelta delay)
- : WebSocketImpl(delegate,
- std::move(request),
- process_id,
- frame_id,
- std::move(origin),
- delay) {}
+ TestWebSocketImpl(
+ std::unique_ptr<Delegate> delegate,
+ network::mojom::WebSocketRequest request,
+ network::WebSocketThrottler::PendingConnection pending_connection_tracker,
+
+ int process_id,
+ int frame_id,
+ url::Origin origin,
+ base::TimeDelta delay)
+ : network::WebSocket(std::move(delegate),
+ std::move(request),
+ std::move(pending_connection_tracker),
+ process_id,
+ frame_id,
+ std::move(origin),
+ delay) {}
base::TimeDelta delay() const { return delay_; }
@@ -50,38 +54,46 @@ class TestWebSocketManager : public WebSocketManager {
return sockets_;
}
- int num_pending_connections() const {
- return num_pending_connections_;
+ int64_t num_pending_connections() const {
+ return throttler_.num_pending_connections();
}
- int64_t num_failed_connections() const {
- return num_current_failed_connections_ + num_previous_failed_connections_;
+ int64_t num_current_succeeded_connections() const {
+ return throttler_.num_current_succeeded_connections();
}
- int64_t num_succeeded_connections() const {
- return num_current_succeeded_connections_ +
- num_previous_succeeded_connections_;
+ int64_t num_previous_succeeded_connections() const {
+ return throttler_.num_previous_succeeded_connections();
+ }
+ int64_t num_current_failed_connections() const {
+ return throttler_.num_current_failed_connections();
+ }
+ int64_t num_previous_failed_connections() const {
+ return throttler_.num_previous_failed_connections();
}
- void DoCreateWebSocket(blink::mojom::WebSocketRequest request) {
+ void DoCreateWebSocket(network::mojom::WebSocketRequest request) {
WebSocketManager::DoCreateWebSocket(MSG_ROUTING_NONE, url::Origin(),
std::move(request));
}
private:
- WebSocketImpl* CreateWebSocketImpl(WebSocketImpl::Delegate* delegate,
- blink::mojom::WebSocketRequest request,
- int process_id,
- int frame_id,
- url::Origin origin,
- base::TimeDelta delay) override {
- TestWebSocketImpl* impl =
- new TestWebSocketImpl(delegate, std::move(request), process_id,
- frame_id, std::move(origin), delay);
+ std::unique_ptr<network::WebSocket> CreateWebSocket(
+ std::unique_ptr<network::WebSocket::Delegate> delegate,
+ network::mojom::WebSocketRequest request,
+ network::WebSocketThrottler::PendingConnection pending_connection_tracker,
+ int process_id,
+ int frame_id,
+ url::Origin origin,
+ base::TimeDelta delay) override {
+ auto impl = std::make_unique<TestWebSocketImpl>(
+ std::move(delegate), std::move(request),
+ std::move(pending_connection_tracker), process_id, frame_id,
+ std::move(origin), delay);
// We keep a vector of sockets here to track their creation order.
- sockets_.push_back(impl);
+ sockets_.push_back(impl.get());
return impl;
}
- void OnLostConnectionToClient(WebSocketImpl* impl) override {
+ void OnLostConnectionToClient(network::WebSocket* impl) override {
auto it = std::find(sockets_.begin(), sockets_.end(),
static_cast<TestWebSocketImpl*>(impl));
ASSERT_TRUE(it != sockets_.end());
@@ -102,14 +114,14 @@ class WebSocketManagerTest : public ::testing::Test {
void AddMultipleChannels(int number_of_channels) {
for (int i = 0; i < number_of_channels; ++i) {
- blink::mojom::WebSocketPtr websocket;
+ network::mojom::WebSocketPtr websocket;
websocket_manager_->DoCreateWebSocket(mojo::MakeRequest(&websocket));
}
}
void AddAndCancelMultipleChannels(int number_of_channels) {
for (int i = 0; i < number_of_channels; ++i) {
- blink::mojom::WebSocketPtr websocket;
+ network::mojom::WebSocketPtr websocket;
websocket_manager_->DoCreateWebSocket(mojo::MakeRequest(&websocket));
websocket_manager_->sockets().back()->SimulateConnectionError();
}
@@ -127,7 +139,7 @@ TEST_F(WebSocketManagerTest, Construct) {
}
TEST_F(WebSocketManagerTest, CreateWebSocket) {
- blink::mojom::WebSocketPtr websocket;
+ network::mojom::WebSocketPtr websocket;
websocket_manager()->DoCreateWebSocket(mojo::MakeRequest(&websocket));
@@ -135,49 +147,13 @@ TEST_F(WebSocketManagerTest, CreateWebSocket) {
}
TEST_F(WebSocketManagerTest, SendFrameButNotConnectedYet) {
- blink::mojom::WebSocketPtr websocket;
+ network::mojom::WebSocketPtr websocket;
websocket_manager()->DoCreateWebSocket(mojo::MakeRequest(&websocket));
// This should not crash.
std::vector<uint8_t> data;
- websocket->SendFrame(true, blink::mojom::WebSocketMessageType::TEXT, data);
-}
-
-TEST_F(WebSocketManagerTest, DelayFor4thPendingConnectionIsZero) {
- AddMultipleChannels(4);
-
- EXPECT_EQ(4, websocket_manager()->num_pending_connections());
- EXPECT_EQ(0, websocket_manager()->num_failed_connections());
- EXPECT_EQ(0, websocket_manager()->num_succeeded_connections());
-
- ASSERT_EQ(4U, websocket_manager()->sockets().size());
- EXPECT_EQ(base::TimeDelta(), websocket_manager()->sockets()[3]->delay());
-}
-
-TEST_F(WebSocketManagerTest, DelayFor8thPendingConnectionIsNonZero) {
- AddMultipleChannels(8);
-
- EXPECT_EQ(8, websocket_manager()->num_pending_connections());
- EXPECT_EQ(0, websocket_manager()->num_failed_connections());
- EXPECT_EQ(0, websocket_manager()->num_succeeded_connections());
-
- ASSERT_EQ(8U, websocket_manager()->sockets().size());
- EXPECT_LT(base::TimeDelta(), websocket_manager()->sockets()[7]->delay());
-}
-
-TEST_F(WebSocketManagerTest, DelayFor17thPendingConnection) {
- AddMultipleChannels(17);
-
- EXPECT_EQ(17, websocket_manager()->num_pending_connections());
- EXPECT_EQ(0, websocket_manager()->num_failed_connections());
- EXPECT_EQ(0, websocket_manager()->num_succeeded_connections());
-
- ASSERT_EQ(17U, websocket_manager()->sockets().size());
- EXPECT_LE(base::TimeDelta::FromMilliseconds(1000),
- websocket_manager()->sockets()[16]->delay());
- EXPECT_GE(base::TimeDelta::FromMilliseconds(5000),
- websocket_manager()->sockets()[16]->delay());
+ websocket->SendFrame(true, network::mojom::WebSocketMessageType::TEXT, data);
}
// The 256th connection is rejected by per-renderer WebSocket throttling.
@@ -186,67 +162,13 @@ TEST_F(WebSocketManagerTest, Rejects256thPendingConnection) {
AddMultipleChannels(256);
EXPECT_EQ(255, websocket_manager()->num_pending_connections());
- EXPECT_EQ(0, websocket_manager()->num_failed_connections());
- EXPECT_EQ(0, websocket_manager()->num_succeeded_connections());
+ EXPECT_EQ(0, websocket_manager()->num_current_succeeded_connections());
+ EXPECT_EQ(0, websocket_manager()->num_previous_succeeded_connections());
+ EXPECT_EQ(0, websocket_manager()->num_current_failed_connections());
+ EXPECT_EQ(0, websocket_manager()->num_previous_failed_connections());
ASSERT_EQ(255U, websocket_manager()->sockets().size());
}
-TEST_F(WebSocketManagerTest, DelayIsZeroAfter3FailedConnections) {
- AddAndCancelMultipleChannels(3);
-
- EXPECT_EQ(0, websocket_manager()->num_pending_connections());
- EXPECT_EQ(3, websocket_manager()->num_failed_connections());
- EXPECT_EQ(0, websocket_manager()->num_succeeded_connections());
-
- AddMultipleChannels(1);
-
- ASSERT_EQ(1U, websocket_manager()->sockets().size());
- EXPECT_EQ(base::TimeDelta(), websocket_manager()->sockets()[0]->delay());
-}
-
-TEST_F(WebSocketManagerTest, DelayIsNonZeroAfter7FailedConnections) {
- AddAndCancelMultipleChannels(7);
-
- EXPECT_EQ(0, websocket_manager()->num_pending_connections());
- EXPECT_EQ(7, websocket_manager()->num_failed_connections());
- EXPECT_EQ(0, websocket_manager()->num_succeeded_connections());
-
- AddMultipleChannels(1);
-
- ASSERT_EQ(1U, websocket_manager()->sockets().size());
- EXPECT_LT(base::TimeDelta(), websocket_manager()->sockets()[0]->delay());
-}
-
-TEST_F(WebSocketManagerTest, DelayAfter16FailedConnections) {
- AddAndCancelMultipleChannels(16);
-
- EXPECT_EQ(0, websocket_manager()->num_pending_connections());
- EXPECT_EQ(16, websocket_manager()->num_failed_connections());
- EXPECT_EQ(0, websocket_manager()->num_succeeded_connections());
-
- AddMultipleChannels(1);
-
- ASSERT_EQ(1U, websocket_manager()->sockets().size());
- EXPECT_LE(base::TimeDelta::FromMilliseconds(1000),
- websocket_manager()->sockets()[0]->delay());
- EXPECT_GE(base::TimeDelta::FromMilliseconds(5000),
- websocket_manager()->sockets()[0]->delay());
-}
-
-TEST_F(WebSocketManagerTest, NotRejectedAfter255FailedConnections) {
- AddAndCancelMultipleChannels(255);
-
- EXPECT_EQ(0, websocket_manager()->num_pending_connections());
- EXPECT_EQ(255, websocket_manager()->num_failed_connections());
- EXPECT_EQ(0, websocket_manager()->num_succeeded_connections());
-
- AddMultipleChannels(1);
-
- EXPECT_EQ(1, websocket_manager()->num_pending_connections());
- EXPECT_EQ(255, websocket_manager()->num_failed_connections());
- EXPECT_EQ(0, websocket_manager()->num_succeeded_connections());
-}
-
} // namespace
} // namespace content
diff --git a/chromium/content/browser/webui/content_web_ui_controller_factory.cc b/chromium/content/browser/webui/content_web_ui_controller_factory.cc
index 0ca8a83848b..0f8982a83ef 100644
--- a/chromium/content/browser/webui/content_web_ui_controller_factory.cc
+++ b/chromium/content/browser/webui/content_web_ui_controller_factory.cc
@@ -17,7 +17,7 @@
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/common/url_constants.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#if BUILDFLAG(ENABLE_WEBRTC)
#include "content/browser/webrtc/webrtc_internals_ui.h"
diff --git a/chromium/content/browser/webui/generic_handler.cc b/chromium/content/browser/webui/generic_handler.cc
index 71259a8066a..9b778bc63ff 100644
--- a/chromium/content/browser/webui/generic_handler.cc
+++ b/chromium/content/browser/webui/generic_handler.cc
@@ -21,8 +21,9 @@ GenericHandler::~GenericHandler() {
}
void GenericHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback("navigateToUrl",
- base::Bind(&GenericHandler::HandleNavigateToUrl, base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "navigateToUrl", base::BindRepeating(&GenericHandler::HandleNavigateToUrl,
+ base::Unretained(this)));
}
void GenericHandler::HandleNavigateToUrl(const base::ListValue* args) {
diff --git a/chromium/content/browser/webui/url_data_manager.cc b/chromium/content/browser/webui/url_data_manager.cc
index bdfc5d93765..a2d542f817e 100644
--- a/chromium/content/browser/webui/url_data_manager.cc
+++ b/chromium/content/browser/webui/url_data_manager.cc
@@ -11,7 +11,6 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/lazy_instance.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted_memory.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/string_util.h"
diff --git a/chromium/content/browser/webui/url_data_manager_backend.cc b/chromium/content/browser/webui/url_data_manager_backend.cc
index daa9763a7dc..8ecdc60b491 100644
--- a/chromium/content/browser/webui/url_data_manager_backend.cc
+++ b/chromium/content/browser/webui/url_data_manager_backend.cc
@@ -14,7 +14,6 @@
#include "base/lazy_instance.h"
#include "base/location.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/memory/ref_counted_memory.h"
#include "base/memory/weak_ptr.h"
@@ -519,15 +518,15 @@ bool URLDataManagerBackend::StartRequest(const net::URLRequest* request,
// on for this path. Call directly into it from this thread, the IO
// thread.
source->source()->StartDataRequest(
- path, wc_getter,
+ path, std::move(wc_getter),
base::Bind(&URLDataSourceImpl::SendResponse, source, request_id));
} else {
// The DataSource wants StartDataRequest to be called on a specific thread,
// usually the UI thread, for this path.
target_runner->PostTask(
- FROM_HERE,
- base::BindOnce(&URLDataManagerBackend::CallStartRequest,
- base::RetainedRef(source), path, wc_getter, request_id));
+ FROM_HERE, base::BindOnce(&URLDataManagerBackend::CallStartRequest,
+ base::RetainedRef(source), path,
+ std::move(wc_getter), request_id));
}
return true;
}
diff --git a/chromium/content/browser/webui/web_ui_data_source_impl.cc b/chromium/content/browser/webui/web_ui_data_source_impl.cc
index 33b118e0c10..ab6ccbba485 100644
--- a/chromium/content/browser/webui/web_ui_data_source_impl.cc
+++ b/chromium/content/browser/webui/web_ui_data_source_impl.cc
@@ -112,24 +112,24 @@ WebUIDataSourceImpl::WebUIDataSourceImpl(const std::string& source_name)
WebUIDataSourceImpl::~WebUIDataSourceImpl() {
}
-void WebUIDataSourceImpl::AddString(const std::string& name,
+void WebUIDataSourceImpl::AddString(base::StringPiece name,
const base::string16& value) {
// TODO(dschuyler): Share only one copy of these strings.
localized_strings_.SetKey(name, base::Value(value));
- replacements_[name] = base::UTF16ToUTF8(value);
+ replacements_[name.as_string()] = base::UTF16ToUTF8(value);
}
-void WebUIDataSourceImpl::AddString(const std::string& name,
+void WebUIDataSourceImpl::AddString(base::StringPiece name,
const std::string& value) {
localized_strings_.SetKey(name, base::Value(value));
- replacements_[name] = value;
+ replacements_[name.as_string()] = value;
}
-void WebUIDataSourceImpl::AddLocalizedString(const std::string& name, int ids) {
+void WebUIDataSourceImpl::AddLocalizedString(base::StringPiece name, int ids) {
std::string utf8_str =
base::UTF16ToUTF8(GetContentClient()->GetLocalizedString(ids));
localized_strings_.SetKey(name, base::Value(utf8_str));
- replacements_[name] = utf8_str;
+ replacements_[name.as_string()] = utf8_str;
}
void WebUIDataSourceImpl::AddLocalizedStrings(
@@ -139,7 +139,7 @@ void WebUIDataSourceImpl::AddLocalizedStrings(
&replacements_);
}
-void WebUIDataSourceImpl::AddBoolean(const std::string& name, bool value) {
+void WebUIDataSourceImpl::AddBoolean(base::StringPiece name, bool value) {
localized_strings_.SetBoolean(name, value);
// TODO(dschuyler): Change name of |localized_strings_| to |load_time_data_|
// or similar. These values haven't been found as strings for
@@ -148,21 +148,21 @@ void WebUIDataSourceImpl::AddBoolean(const std::string& name, bool value) {
// replacements.
}
-void WebUIDataSourceImpl::AddInteger(const std::string& name, int32_t value) {
+void WebUIDataSourceImpl::AddInteger(base::StringPiece name, int32_t value) {
localized_strings_.SetInteger(name, value);
}
-void WebUIDataSourceImpl::SetJsonPath(const std::string& path) {
+void WebUIDataSourceImpl::SetJsonPath(base::StringPiece path) {
DCHECK(json_path_.empty());
DCHECK(!path.empty());
- json_path_ = path;
+ json_path_ = path.as_string();
excluded_paths_.insert(json_path_);
}
-void WebUIDataSourceImpl::AddResourcePath(const std::string &path,
+void WebUIDataSourceImpl::AddResourcePath(base::StringPiece path,
int resource_id) {
- path_to_idr_map_[path] = resource_id;
+ path_to_idr_map_[path.as_string()] = resource_id;
}
void WebUIDataSourceImpl::SetDefaultResource(int resource_id) {
diff --git a/chromium/content/browser/webui/web_ui_data_source_impl.h b/chromium/content/browser/webui/web_ui_data_source_impl.h
index a230f31769a..18c48754437 100644
--- a/chromium/content/browser/webui/web_ui_data_source_impl.h
+++ b/chromium/content/browser/webui/web_ui_data_source_impl.h
@@ -30,15 +30,15 @@ class CONTENT_EXPORT WebUIDataSourceImpl : public URLDataSourceImpl,
public WebUIDataSource {
public:
// WebUIDataSource implementation:
- void AddString(const std::string& name, const base::string16& value) override;
- void AddString(const std::string& name, const std::string& value) override;
- void AddLocalizedString(const std::string& name, int ids) override;
+ void AddString(base::StringPiece name, const base::string16& value) override;
+ void AddString(base::StringPiece name, const std::string& value) override;
+ void AddLocalizedString(base::StringPiece name, int ids) override;
void AddLocalizedStrings(
const base::DictionaryValue& localized_strings) override;
- void AddBoolean(const std::string& name, bool value) override;
- void AddInteger(const std::string& name, int32_t value) override;
- void SetJsonPath(const std::string& path) override;
- void AddResourcePath(const std::string& path, int resource_id) override;
+ void AddBoolean(base::StringPiece name, bool value) override;
+ void AddInteger(base::StringPiece name, int32_t value) override;
+ void SetJsonPath(base::StringPiece path) override;
+ void AddResourcePath(base::StringPiece path, int resource_id) override;
void SetDefaultResource(int resource_id) override;
void SetRequestFilter(
const WebUIDataSource::HandleRequestCallback& callback) override;
diff --git a/chromium/content/browser/webui/web_ui_impl.cc b/chromium/content/browser/webui/web_ui_impl.cc
index eabd4a4a8e6..d759aba3325 100644
--- a/chromium/content/browser/webui/web_ui_impl.cc
+++ b/chromium/content/browser/webui/web_ui_impl.cc
@@ -11,6 +11,7 @@
#include "base/debug/dump_without_crashing.h"
#include "base/json/json_writer.h"
+#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "content/browser/child_process_security_policy_impl.h"
@@ -79,7 +80,7 @@ base::string16 WebUI::GetJavascriptCall(
return result;
}
-WebUIImpl::WebUIImpl(WebContents* contents)
+WebUIImpl::WebUIImpl(WebContentsImpl* contents)
: bindings_(BINDINGS_POLICY_WEB_UI),
web_contents_(contents),
web_contents_observer_(new MainFrameNavigationObserver(this, contents)) {
@@ -122,6 +123,13 @@ void WebUIImpl::OnWebUISend(RenderFrameHost* sender,
if (!sender->IsCurrent())
return;
+ if (base::EndsWith(message, "RequiringGesture",
+ base::CompareCase::SENSITIVE) &&
+ !web_contents_->HasRecentInteractiveInputEvent()) {
+ LOG(ERROR) << message << " received without recent user interaction";
+ return;
+ }
+
ProcessWebUIMessage(source_url, message, args);
}
@@ -239,9 +247,9 @@ void WebUIImpl::CallJavascriptFunctionUnsafe(
ExecuteJavascript(GetJavascriptCall(function_name, args));
}
-void WebUIImpl::RegisterMessageCallback(const std::string &message,
+void WebUIImpl::RegisterMessageCallback(base::StringPiece message,
const MessageCallback& callback) {
- message_callbacks_.insert(std::make_pair(message, callback));
+ message_callbacks_.emplace(message, callback);
}
void WebUIImpl::ProcessWebUIMessage(const GURL& source_url,
@@ -251,11 +259,10 @@ void WebUIImpl::ProcessWebUIMessage(const GURL& source_url,
return;
// Look up the callback for this message.
- MessageCallbackMap::const_iterator callback =
- message_callbacks_.find(message);
- if (callback != message_callbacks_.end()) {
+ auto callback_pair = message_callbacks_.find(message);
+ if (callback_pair != message_callbacks_.end()) {
// Forward this message and content on.
- callback->second.Run(&args);
+ callback_pair->second.Run(&args);
} else {
NOTREACHED() << "Unhandled chrome.send(\"" << message << "\");";
}
diff --git a/chromium/content/browser/webui/web_ui_impl.h b/chromium/content/browser/webui/web_ui_impl.h
index b13969e4080..556102626b3 100644
--- a/chromium/content/browser/webui/web_ui_impl.h
+++ b/chromium/content/browser/webui/web_ui_impl.h
@@ -22,11 +22,12 @@ class Message;
namespace content {
class RenderFrameHost;
+class WebContentsImpl;
class CONTENT_EXPORT WebUIImpl : public WebUI,
public base::SupportsWeakPtr<WebUIImpl> {
public:
- WebUIImpl(WebContents* contents);
+ explicit WebUIImpl(WebContentsImpl* contents);
~WebUIImpl() override;
// Called when a RenderFrame is created for a WebUI (reload after a renderer
@@ -51,8 +52,7 @@ class CONTENT_EXPORT WebUIImpl : public WebUI,
int GetBindings() const override;
void SetBindings(int bindings) override;
void AddMessageHandler(std::unique_ptr<WebUIMessageHandler> handler) override;
- typedef base::Callback<void(const base::ListValue*)> MessageCallback;
- void RegisterMessageCallback(const std::string& message,
+ void RegisterMessageCallback(base::StringPiece message,
const MessageCallback& callback) override;
void ProcessWebUIMessage(const GURL& source_url,
const std::string& message,
@@ -97,8 +97,7 @@ class CONTENT_EXPORT WebUIImpl : public WebUI,
void DisallowJavascriptOnAllHandlers();
// A map of message name -> message handling callback.
- typedef std::map<std::string, MessageCallback> MessageCallbackMap;
- MessageCallbackMap message_callbacks_;
+ std::map<std::string, MessageCallback> message_callbacks_;
// Options that may be overridden by individual Web UI implementations. The
// bool options default to false. See the public getters for more information.
@@ -109,8 +108,8 @@ class CONTENT_EXPORT WebUIImpl : public WebUI,
// The WebUIMessageHandlers we own.
std::vector<std::unique_ptr<WebUIMessageHandler>> handlers_;
- // Non-owning pointer to the WebContents this WebUI is associated with.
- WebContents* web_contents_;
+ // Non-owning pointer to the WebContentsImpl this WebUI is associated with.
+ WebContentsImpl* web_contents_;
// Notifies this WebUI about notifications in the main frame.
std::unique_ptr<MainFrameNavigationObserver> web_contents_observer_;
diff --git a/chromium/content/browser/webui/web_ui_mojo_browsertest.cc b/chromium/content/browser/webui/web_ui_mojo_browsertest.cc
index 5c8b8ce1aef..12e4cdf43fc 100644
--- a/chromium/content/browser/webui/web_ui_mojo_browsertest.cc
+++ b/chromium/content/browser/webui/web_ui_mojo_browsertest.cc
@@ -8,7 +8,6 @@
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted_memory.h"
#include "base/path_service.h"
#include "base/run_loop.h"
diff --git a/chromium/content/browser/webui/web_ui_url_loader_factory.cc b/chromium/content/browser/webui/web_ui_url_loader_factory.cc
index 32457c8510f..fb7a2fe41f9 100644
--- a/chromium/content/browser/webui/web_ui_url_loader_factory.cc
+++ b/chromium/content/browser/webui/web_ui_url_loader_factory.cc
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "content/browser/webui/web_ui_url_loader_factory.h"
+#include "content/public/browser/web_ui_url_loader_factory.h"
#include <map>
@@ -18,7 +18,6 @@
#include "content/browser/blob_storage/chrome_blob_storage_context.h"
#include "content/browser/frame_host/render_frame_host_impl.h"
#include "content/browser/histogram_internals_url_loader.h"
-#include "content/browser/loader/global_routing_id.h"
#include "content/browser/resource_context_impl.h"
#include "content/browser/storage_partition_impl.h"
#include "content/browser/webui/network_error_url_loader.h"
@@ -67,7 +66,7 @@ void ReadData(scoped_refptr<network::ResourceResponse> headers,
network::mojom::URLLoaderClientPtr client;
client.Bind(std::move(client_info));
- client->OnReceiveResponse(headers->head, base::nullopt, nullptr);
+ client->OnReceiveResponse(headers->head, nullptr);
base::StringPiece input(reinterpret_cast<const char*>(bytes->front()),
bytes->size());
@@ -200,26 +199,32 @@ void StartURLLoader(const network::ResourceRequest& request,
scoped_refptr<base::SingleThreadTaskRunner> target_runner =
source->source()->TaskRunnerForRequestPath(path);
if (!target_runner) {
- source->source()->StartDataRequest(path, wc_getter,
- data_available_callback);
+ source->source()->StartDataRequest(path, std::move(wc_getter),
+ std::move(data_available_callback));
return;
}
// The DataSource wants StartDataRequest to be called on a specific
// thread, usually the UI thread, for this path.
target_runner->PostTask(
- FROM_HERE, base::BindOnce(&URLDataSource::StartDataRequest,
- base::Unretained(source->source()), path,
- wc_getter, data_available_callback));
+ FROM_HERE,
+ base::BindOnce(&URLDataSource::StartDataRequest,
+ base::Unretained(source->source()), path,
+ std::move(wc_getter), std::move(data_available_callback)));
}
class WebUIURLLoaderFactory : public network::mojom::URLLoaderFactory,
public WebContentsObserver {
public:
- WebUIURLLoaderFactory(RenderFrameHost* rfh, const std::string& scheme)
+ // |allowed_hosts| is an optional set of allowed host names. If empty then
+ // all hosts are allowed.
+ WebUIURLLoaderFactory(RenderFrameHost* rfh,
+ const std::string& scheme,
+ base::flat_set<std::string> allowed_hosts)
: WebContentsObserver(WebContents::FromRenderFrameHost(rfh)),
render_frame_host_(rfh),
- scheme_(scheme) {}
+ scheme_(scheme),
+ allowed_hosts_(std::move(allowed_hosts)) {}
~WebUIURLLoaderFactory() override {}
@@ -239,14 +244,26 @@ class WebUIURLLoaderFactory : public network::mojom::URLLoaderFactory,
const net::MutableNetworkTrafficAnnotationTag&
traffic_annotation) override {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ DCHECK(!request.download_to_file);
if (request.url.scheme() != scheme_) {
+ DVLOG(1) << "Bad scheme: " << request.url.scheme();
ReceivedBadMessage(render_frame_host_->GetProcess(),
bad_message::WEBUI_BAD_SCHEME_ACCESS);
client->OnComplete(network::URLLoaderCompletionStatus(net::ERR_FAILED));
return;
}
+ if (!allowed_hosts_.empty() &&
+ (!request.url.has_host() ||
+ allowed_hosts_.find(request.url.host()) == allowed_hosts_.end())) {
+ DVLOG(1) << "Bad host: \"" << request.url.host() << '"';
+ ReceivedBadMessage(render_frame_host_->GetProcess(),
+ bad_message::WEBUI_BAD_HOST_ACCESS);
+ client->OnComplete(network::URLLoaderCompletionStatus(net::ERR_FAILED));
+ return;
+ }
+
if (request.url.host_piece() == kChromeUIBlobInternalsHost) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
@@ -303,6 +320,7 @@ class WebUIURLLoaderFactory : public network::mojom::URLLoaderFactory,
RenderFrameHost* render_frame_host_;
std::string scheme_;
+ const base::flat_set<std::string> allowed_hosts_; // if empty all allowed.
mojo::BindingSet<network::mojom::URLLoaderFactory> loader_factory_bindings_;
DISALLOW_COPY_AND_ASSIGN(WebUIURLLoaderFactory);
@@ -310,7 +328,15 @@ class WebUIURLLoaderFactory : public network::mojom::URLLoaderFactory,
} // namespace
-network::mojom::URLLoaderFactoryPtr CreateWebUIURLLoader(
+std::unique_ptr<network::mojom::URLLoaderFactory> CreateWebUIURLLoader(
+ RenderFrameHost* render_frame_host,
+ const std::string& scheme,
+ base::flat_set<std::string> allowed_hosts) {
+ return std::make_unique<WebUIURLLoaderFactory>(render_frame_host, scheme,
+ std::move(allowed_hosts));
+}
+
+network::mojom::URLLoaderFactoryPtr CreateWebUIURLLoaderBinding(
RenderFrameHost* render_frame_host,
const std::string& scheme) {
GlobalFrameRoutingId routing_id(render_frame_host->GetRoutingID(),
@@ -319,7 +345,8 @@ network::mojom::URLLoaderFactoryPtr CreateWebUIURLLoader(
g_web_ui_url_loader_factories.Get().end() ||
g_web_ui_url_loader_factories.Get()[routing_id]->scheme() != scheme) {
g_web_ui_url_loader_factories.Get()[routing_id] =
- std::make_unique<WebUIURLLoaderFactory>(render_frame_host, scheme);
+ std::make_unique<WebUIURLLoaderFactory>(render_frame_host, scheme,
+ base::flat_set<std::string>());
}
return g_web_ui_url_loader_factories.Get()[routing_id]->CreateBinding();
}
diff --git a/chromium/content/browser/webui/web_ui_url_loader_factory.h b/chromium/content/browser/webui/web_ui_url_loader_factory_internal.h
index 834bd7f1ad0..be4749ddb97 100644
--- a/chromium/content/browser/webui/web_ui_url_loader_factory.h
+++ b/chromium/content/browser/webui/web_ui_url_loader_factory_internal.h
@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef CONTENT_BROWSER_WEBUI_WEB_UI_URL_LOADER_FACTORY_H_
-#define CONTENT_BROWSER_WEBUI_WEB_UI_URL_LOADER_FACTORY_H_
+#ifndef CONTENT_BROWSER_WEBUI_WEB_UI_URL_LOADER_FACTORY_INTERNAL_H_
+#define CONTENT_BROWSER_WEBUI_WEB_UI_URL_LOADER_FACTORY_INTERNAL_H_
#include "services/network/public/mojom/url_loader_factory.mojom.h"
@@ -14,10 +14,10 @@ class RenderFrameHost;
// the given |render_frame_host|. The factory will only create loaders for
// requests with the same scheme as |scheme|. This is needed because there is
// more than one scheme used for WebUI, and not all have WebUI bindings.
-network::mojom::URLLoaderFactoryPtr CreateWebUIURLLoader(
+network::mojom::URLLoaderFactoryPtr CreateWebUIURLLoaderBinding(
RenderFrameHost* render_frame_host,
const std::string& scheme);
} // namespace content
-#endif // CONTENT_BROWSER_WEBUI_WEB_UI_URL_LOADER_FACTORY_H_
+#endif // CONTENT_BROWSER_WEBUI_WEB_UI_URL_LOADER_FACTORY_INTERNAL_H_
diff --git a/chromium/content/browser/zygote_host/zygote_host_impl_linux.cc b/chromium/content/browser/zygote_host/zygote_host_impl_linux.cc
index 900ef81f59c..0b764578eca 100644
--- a/chromium/content/browser/zygote_host/zygote_host_impl_linux.cc
+++ b/chromium/content/browser/zygote_host/zygote_host_impl_linux.cc
@@ -211,7 +211,7 @@ pid_t ZygoteHostImpl::LaunchZygote(
if (real_pid != pid) {
// Reap the sandbox.
- base::EnsureProcessGetsReaped(pid);
+ base::EnsureProcessGetsReaped(std::move(process));
}
pid = real_pid;
}
@@ -290,7 +290,7 @@ void ZygoteHostImpl::AdjustRendererOOMScore(base::ProcessHandle pid,
base::Process sandbox_helper_process =
base::LaunchProcess(adj_oom_score_cmdline, options);
if (sandbox_helper_process.IsValid())
- base::EnsureProcessGetsReaped(sandbox_helper_process.Pid());
+ base::EnsureProcessGetsReaped(std::move(sandbox_helper_process));
}
#endif
diff --git a/chromium/content/child/BUILD.gn b/chromium/content/child/BUILD.gn
index 37cdca73cef..fbb110d2d40 100644
--- a/chromium/content/child/BUILD.gn
+++ b/chromium/content/child/BUILD.gn
@@ -4,8 +4,8 @@
import("//build/config/features.gni")
import("//build/config/ui.gni")
-import("//ppapi/features/features.gni")
-import("//third_party/WebKit/public/public_features.gni")
+import("//ppapi/buildflags/buildflags.gni")
+import("//third_party/blink/public/public_features.gni")
if (is_component_build) {
link_target_type = "source_set"
@@ -43,10 +43,10 @@ target(link_target_type, "child") {
"child_process.h",
"child_process_sandbox_support_impl_linux.cc",
"child_process_sandbox_support_impl_linux.h",
+ "child_process_sandbox_support_impl_mac.cc",
+ "child_process_sandbox_support_impl_mac.h",
"child_thread_impl.cc",
"child_thread_impl.h",
- "content_child_helpers.cc",
- "content_child_helpers.h",
"dwrite_font_proxy/dwrite_font_proxy_init_impl_win.cc",
"dwrite_font_proxy/dwrite_font_proxy_init_impl_win.h",
"dwrite_font_proxy/dwrite_font_proxy_win.cc",
@@ -107,7 +107,7 @@ target(link_target_type, "child") {
"//media",
"//media/blink",
"//mojo/common",
- "//mojo/edk/system",
+ "//mojo/edk",
"//net",
"//services/device/public/cpp:device_features",
"//services/device/public/cpp/power_monitor",
@@ -119,12 +119,12 @@ target(link_target_type, "child") {
"//services/tracing/public/cpp",
"//skia",
"//storage/common",
- "//third_party/WebKit/public:blink_headers",
- "//third_party/WebKit/public:features",
- "//third_party/WebKit/public:mojo_bindings",
- "//third_party/WebKit/public:resources",
- "//third_party/WebKit/public:scaled_resources",
- "//third_party/WebKit/public/common",
+ "//third_party/blink/public:blink_headers",
+ "//third_party/blink/public:buildflags",
+ "//third_party/blink/public:mojo_bindings",
+ "//third_party/blink/public:resources",
+ "//third_party/blink/public:scaled_resources",
+ "//third_party/blink/public/common",
"//third_party/ced",
"//third_party/zlib/google:compression_utils",
"//ui/base",
diff --git a/chromium/content/child/assert_matching_enums.cc b/chromium/content/child/assert_matching_enums.cc
index 75b0cc828dc..b2b3db58b71 100644
--- a/chromium/content/child/assert_matching_enums.cc
+++ b/chromium/content/child/assert_matching_enums.cc
@@ -8,11 +8,11 @@
#include "base/macros.h"
#include "content/public/common/screen_orientation_values.h"
#include "media/base/mime_util.h"
-#include "third_party/WebKit/public/platform/WebMenuSourceType.h"
-#include "third_party/WebKit/public/platform/WebTextInputMode.h"
-#include "third_party/WebKit/public/platform/WebTextInputType.h"
-#include "third_party/WebKit/public/platform/modules/screen_orientation/WebScreenOrientationLockType.h"
-#include "third_party/WebKit/public/web/WebFrameSerializerCacheControlPolicy.h"
+#include "third_party/blink/public/platform/modules/screen_orientation/web_screen_orientation_lock_type.h"
+#include "third_party/blink/public/platform/web_menu_source_type.h"
+#include "third_party/blink/public/platform/web_text_input_mode.h"
+#include "third_party/blink/public/platform/web_text_input_type.h"
+#include "third_party/blink/public/web/web_frame_serializer_cache_control_policy.h"
#include "ui/base/ime/text_input_mode.h"
#include "ui/base/ime/text_input_type.h"
#include "ui/base/ui_base_types.h"
diff --git a/chromium/content/child/blink_platform_impl.cc b/chromium/content/child/blink_platform_impl.cc
index d96f505fb11..aa67eb82782 100644
--- a/chromium/content/child/blink_platform_impl.cc
+++ b/chromium/content/child/blink_platform_impl.cc
@@ -13,7 +13,6 @@
#include "base/files/file_path.h"
#include "base/location.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/singleton.h"
#include "base/metrics/user_metrics_action.h"
#include "base/rand_util.h"
@@ -33,27 +32,27 @@
#include "base/trace_event/memory_allocator_dump_guid.h"
#include "base/trace_event/memory_dump_manager.h"
#include "base/trace_event/trace_event.h"
-#include "blink/public/resources/grit/blink_image_resources.h"
-#include "blink/public/resources/grit/blink_resources.h"
-#include "blink/public/resources/grit/media_controls_resources.h"
#include "build/build_config.h"
#include "content/app/resources/grit/content_resources.h"
#include "content/app/strings/grit/content_strings.h"
#include "content/child/child_thread_impl.h"
-#include "content/child/content_child_helpers.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_features.h"
+#include "content/public/common/content_switches.h"
#include "content/public/common/service_manager_connection.h"
#include "content/public/common/service_names.mojom.h"
#include "net/base/net_errors.h"
#include "services/network/public/cpp/features.h"
-#include "third_party/WebKit/public/platform/WebData.h"
-#include "third_party/WebKit/public/platform/WebFloatPoint.h"
-#include "third_party/WebKit/public/platform/WebGestureCurve.h"
-#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
-#include "third_party/WebKit/public/platform/scheduler/child/webthread_base.h"
+#include "third_party/blink/public/platform/scheduler/child/webthread_base.h"
+#include "third_party/blink/public/platform/web_data.h"
+#include "third_party/blink/public/platform/web_float_point.h"
+#include "third_party/blink/public/platform/web_gesture_curve.h"
+#include "third_party/blink/public/platform/web_security_origin.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_url.h"
+#include "third_party/blink/public/resources/grit/blink_image_resources.h"
+#include "third_party/blink/public/resources/grit/blink_resources.h"
+#include "third_party/blink/public/resources/grit/media_controls_resources.h"
#include "third_party/zlib/google/compression_utils.h"
#include "ui/base/layout.h"
#include "ui/events/gestures/blink/web_gesture_curve_impl.h"
@@ -374,24 +373,21 @@ WebString BlinkPlatformImpl::UserAgent() {
std::unique_ptr<blink::WebThread> BlinkPlatformImpl::CreateThread(
const blink::WebThreadCreationParams& params) {
std::unique_ptr<blink::scheduler::WebThreadBase> thread =
- blink::scheduler::WebThreadBase::CreateWorkerThread(
- params.name, base::Thread::Options());
+ blink::scheduler::WebThreadBase::CreateWorkerThread(params);
thread->Init();
WaitUntilWebThreadTLSUpdate(thread.get());
return std::move(thread);
}
std::unique_ptr<blink::WebThread> BlinkPlatformImpl::CreateWebAudioThread() {
- base::Thread::Options thread_options;
-
+ blink::WebThreadCreationParams params(blink::WebThreadType::kWebAudioThread);
// WebAudio uses a thread with |DISPLAY| priority to avoid glitch when the
// system is under the high pressure. Note that the main browser thread also
// runs with same priority. (see: crbug.com/734539)
- thread_options.priority = base::ThreadPriority::DISPLAY;
+ params.thread_options.priority = base::ThreadPriority::DISPLAY;
std::unique_ptr<blink::scheduler::WebThreadBase> thread =
- blink::scheduler::WebThreadBase::CreateWorkerThread(
- "WebAudio Rendering Thread", thread_options);
+ blink::scheduler::WebThreadBase::CreateWorkerThread(params);
thread->Init();
WaitUntilWebThreadTLSUpdate(thread.get());
return std::move(thread);
@@ -542,6 +538,8 @@ const DataResource kDataResources[] = {
{"validation_bubble.css", IDR_VALIDATION_BUBBLE_CSS, ui::SCALE_FACTOR_NONE,
true},
{"placeholderIcon", IDR_PLACEHOLDER_ICON, ui::SCALE_FACTOR_100P, false},
+ {"brokenCanvas", IDR_BROKENCANVAS, ui::SCALE_FACTOR_100P, false},
+ {"brokenCanvas@2x", IDR_BROKENCANVAS, ui::SCALE_FACTOR_200P, false},
};
class NestedMessageLoopRunnerImpl
@@ -744,20 +742,18 @@ bool BlinkPlatformImpl::DatabaseSetFileSize(
return false;
}
-size_t BlinkPlatformImpl::ActualMemoryUsageMB() {
- return GetMemoryUsageKB() >> 10;
-}
-
size_t BlinkPlatformImpl::NumberOfProcessors() {
return static_cast<size_t>(base::SysInfo::NumberOfProcessors());
}
size_t BlinkPlatformImpl::MaxDecodedImageBytes() {
+ const int kMB = 1024 * 1024;
+ const int kMaxNumberOfBytesPerPixel = 4;
#if defined(OS_ANDROID)
if (base::SysInfo::IsLowEndDevice()) {
// Limit image decoded size to 3M pixels on low end devices.
// 4 is maximum number of bytes per pixel.
- return 3 * 1024 * 1024 * 4;
+ return 3 * kMB * kMaxNumberOfBytesPerPixel;
}
// For other devices, limit decoded image size based on the amount of physical
// memory.
@@ -768,7 +764,16 @@ size_t BlinkPlatformImpl::MaxDecodedImageBytes() {
// common texture size.
return base::SysInfo::AmountOfPhysicalMemory() / 25;
#else
- return kNoDecodedImageByteLimit;
+ size_t max_decoded_image_byte_limit = kNoDecodedImageByteLimit;
+ base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess();
+ if (command_line.HasSwitch(switches::kMaxDecodedImageSizeMb)) {
+ if (base::StringToSizeT(
+ command_line.GetSwitchValueASCII(switches::kMaxDecodedImageSizeMb),
+ &max_decoded_image_byte_limit)) {
+ max_decoded_image_byte_limit *= kMB * kMaxNumberOfBytesPerPixel;
+ }
+ }
+ return max_decoded_image_byte_limit;
#endif
}
diff --git a/chromium/content/child/blink_platform_impl.h b/chromium/content/child/blink_platform_impl.h
index 24be82401ec..f9d13cf958a 100644
--- a/chromium/content/child/blink_platform_impl.h
+++ b/chromium/content/child/blink_platform_impl.h
@@ -18,10 +18,10 @@
#include "content/child/webfallbackthemeengine_impl.h"
#include "content/common/content_export.h"
#include "media/blink/webmediacapabilitiesclient_impl.h"
-#include "third_party/WebKit/public/platform/Platform.h"
-#include "third_party/WebKit/public/platform/WebGestureDevice.h"
-#include "third_party/WebKit/public/platform/WebURLError.h"
-#include "third_party/WebKit/public/public_features.h"
+#include "third_party/blink/public/platform/platform.h"
+#include "third_party/blink/public/platform/web_gesture_device.h"
+#include "third_party/blink/public/platform/web_url_error.h"
+#include "third_party/blink/public/public_buildflags.h"
#include "ui/base/layout.h"
#if BUILDFLAG(USE_DEFAULT_RENDER_THEME)
@@ -71,7 +71,6 @@ class CONTENT_EXPORT BlinkPlatformImpl : public blink::Platform {
const blink::WebSecurityOrigin& origin) override;
bool DatabaseSetFileSize(const blink::WebString& vfs_file_name,
long long size) override;
- size_t ActualMemoryUsageMB() override;
size_t NumberOfProcessors() override;
size_t MaxDecodedImageBytes() override;
diff --git a/chromium/content/child/blink_platform_impl_unittest.cc b/chromium/content/child/blink_platform_impl_unittest.cc
index 872734d1ee3..6cb1152a775 100644
--- a/chromium/content/child/blink_platform_impl_unittest.cc
+++ b/chromium/content/child/blink_platform_impl_unittest.cc
@@ -9,8 +9,8 @@
#include "base/run_loop.h"
#include "base/time/time.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
-#include "third_party/WebKit/public/platform/WebString.h"
+#include "third_party/blink/public/platform/web_security_origin.h"
+#include "third_party/blink/public/platform/web_string.h"
#include "url/origin.h"
namespace content {
diff --git a/chromium/content/child/browser_font_resource_trusted.cc b/chromium/content/child/browser_font_resource_trusted.cc
index 64f59f578cb..fb4a65c7f5e 100644
--- a/chromium/content/child/browser_font_resource_trusted.cc
+++ b/chromium/content/child/browser_font_resource_trusted.cc
@@ -18,13 +18,13 @@
#include "ppapi/thunk/ppb_image_data_api.h"
#include "ppapi/thunk/thunk.h"
#include "skia/ext/platform_canvas.h"
-#include "third_party/WebKit/public/platform/WebCanvas.h"
-#include "third_party/WebKit/public/platform/WebFloatPoint.h"
-#include "third_party/WebKit/public/platform/WebFloatRect.h"
-#include "third_party/WebKit/public/platform/WebFont.h"
-#include "third_party/WebKit/public/platform/WebFontDescription.h"
-#include "third_party/WebKit/public/platform/WebRect.h"
-#include "third_party/WebKit/public/platform/WebTextRun.h"
+#include "third_party/blink/public/platform/web_canvas.h"
+#include "third_party/blink/public/platform/web_float_point.h"
+#include "third_party/blink/public/platform/web_float_rect.h"
+#include "third_party/blink/public/platform/web_font.h"
+#include "third_party/blink/public/platform/web_font_description.h"
+#include "third_party/blink/public/platform/web_rect.h"
+#include "third_party/blink/public/platform/web_text_run.h"
#include "third_party/icu/source/common/unicode/ubidi.h"
#include "third_party/skia/include/core/SkRect.h"
diff --git a/chromium/content/child/child_process_sandbox_support_impl_linux.cc b/chromium/content/child/child_process_sandbox_support_impl_linux.cc
index 308d214f099..587ddeab58e 100644
--- a/chromium/content/child/child_process_sandbox_support_impl_linux.cc
+++ b/chromium/content/child/child_process_sandbox_support_impl_linux.cc
@@ -17,10 +17,10 @@
#include "base/trace_event/trace_event.h"
#include "content/public/common/common_sandbox_support_linux.h"
#include "services/service_manager/sandbox/linux/sandbox_linux.h"
-#include "third_party/WebKit/public/platform/WebFontRenderStyle.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebVector.h"
-#include "third_party/WebKit/public/platform/linux/WebFallbackFont.h"
+#include "third_party/blink/public/platform/linux/web_fallback_font.h"
+#include "third_party/blink/public/platform/web_font_render_style.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_vector.h"
namespace content {
diff --git a/chromium/content/child/child_process_sandbox_support_impl_mac.cc b/chromium/content/child/child_process_sandbox_support_impl_mac.cc
new file mode 100644
index 00000000000..0cd80ca28be
--- /dev/null
+++ b/chromium/content/child/child_process_sandbox_support_impl_mac.cc
@@ -0,0 +1,45 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/child/child_process_sandbox_support_impl_mac.h"
+
+#include <utility>
+
+#include "base/mac/scoped_cftyperef.h"
+#include "base/numerics/safe_conversions.h"
+#include "base/strings/string16.h"
+#include "base/strings/sys_string_conversions.h"
+#include "content/common/mac/font_loader.h"
+#include "content/public/child/child_thread.h"
+#include "mojo/public/cpp/system/buffer.h"
+
+namespace content {
+
+bool LoadFont(CTFontRef font, CGFontRef* out, uint32_t* font_id) {
+ base::ScopedCFTypeRef<CFStringRef> name_ref(CTFontCopyPostScriptName(font));
+ base::string16 font_name = SysCFStringRefToUTF16(name_ref);
+ float font_point_size = CTFontGetSize(font);
+ mojo::ScopedSharedBufferHandle font_data;
+ bool success = content::ChildThread::Get()->LoadFont(
+ font_name, font_point_size, &font_data, font_id) &&
+ *font_id > 0 && font_data.is_valid();
+ if (!success) {
+ DLOG(ERROR) << "Bad response from LoadFont() for " << font_name;
+ *out = nullptr;
+ *font_id = 0;
+ return false;
+ }
+
+ uint64_t font_data_size = font_data->GetSize();
+ DCHECK_GT(font_data_size, 0U);
+ DCHECK(base::IsValueInRangeForNumericType<uint32_t>(font_data_size));
+
+ // TODO(jeremy): Need to call back into the requesting process to make sure
+ // that the font isn't already activated, based on the font id. If it's
+ // already activated, don't reactivate it here - https://crbug.com/72727 .
+ return FontLoader::CGFontRefFromBuffer(
+ std::move(font_data), static_cast<uint32_t>(font_data_size), out);
+}
+
+} // namespace content
diff --git a/chromium/content/child/child_process_sandbox_support_impl_mac.h b/chromium/content/child/child_process_sandbox_support_impl_mac.h
new file mode 100644
index 00000000000..53cdad1d52b
--- /dev/null
+++ b/chromium/content/child/child_process_sandbox_support_impl_mac.h
@@ -0,0 +1,18 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_CHILD_CHILD_PROCESS_SANDBOX_SUPPORT_IMPL_MAC_H_
+#define CONTENT_CHILD_CHILD_PROCESS_SANDBOX_SUPPORT_IMPL_MAC_H_
+
+#include <CoreText/CoreText.h>
+
+namespace content {
+
+// Load a font specified by |font| into |out| through communicating
+// with browser.
+bool LoadFont(CTFontRef font, CGFontRef* out, uint32_t* font_id);
+
+}; // namespace content
+
+#endif // CONTENT_CHILD_CHILD_PROCESS_SANDBOX_SUPPORT_IMPL_MAC_H_
diff --git a/chromium/content/child/child_thread_impl.cc b/chromium/content/child/child_thread_impl.cc
index ecf9f7caf08..2663268bce3 100644
--- a/chromium/content/child/child_thread_impl.cc
+++ b/chromium/content/child/child_thread_impl.cc
@@ -17,7 +17,6 @@
#include "base/location.h"
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/message_loop/timer_slack.h"
#include "base/metrics/field_trial.h"
@@ -521,9 +520,15 @@ void ChildThreadImpl::Init(const Options& options) {
if (!base::PowerMonitor::Get() && service_manager_connection_) {
auto power_monitor_source =
std::make_unique<device::PowerMonitorBroadcastSource>(
- GetConnector(), GetIOTaskRunner());
+ GetIOTaskRunner());
+ auto* source_ptr = power_monitor_source.get();
power_monitor_.reset(
new base::PowerMonitor(std::move(power_monitor_source)));
+ // The two-phase init is necessary to ensure that the process-wide
+ // PowerMonitor is set before the power monitor source receives incoming
+ // communication from the browser process (see https://crbug.com/821790 for
+ // details)
+ source_ptr->Init(GetConnector());
}
#if defined(OS_POSIX)
@@ -603,8 +608,8 @@ void ChildThreadImpl::InitTracing() {
channel_->AddFilter(new tracing::ChildTraceMessageFilter(
ChildProcess::current()->io_task_runner()));
- chrome_trace_event_agent_ =
- std::make_unique<tracing::ChromeTraceEventAgent>(GetConnector());
+ chrome_trace_event_agent_ = std::make_unique<tracing::ChromeTraceEventAgent>(
+ GetConnector(), false /* request_clock_sync_marker_on_android */);
}
ChildThreadImpl::~ChildThreadImpl() {
@@ -673,6 +678,22 @@ mojom::FontCacheWin* ChildThreadImpl::GetFontCacheWin() {
}
return font_cache_win_ptr_.get();
}
+#elif defined(OS_MACOSX)
+bool ChildThreadImpl::LoadFont(const base::string16& font_name,
+ float font_point_size,
+ mojo::ScopedSharedBufferHandle* out_font_data,
+ uint32_t* out_font_id) {
+ return GetFontLoaderMac()->LoadFont(font_name, font_point_size, out_font_data,
+ out_font_id);
+}
+
+mojom::FontLoaderMac* ChildThreadImpl::GetFontLoaderMac() {
+ if (!font_loader_mac_ptr_) {
+ GetConnector()->BindInterface(mojom::kBrowserServiceName,
+ &font_loader_mac_ptr_);
+ }
+ return font_loader_mac_ptr_.get();
+}
#endif
void ChildThreadImpl::RecordAction(const base::UserMetricsAction& action) {
@@ -737,7 +758,9 @@ void ChildThreadImpl::OnAssociatedInterfaceRequest(
if (interface_name == mojom::RouteProvider::Name_) {
DCHECK(!route_provider_binding_.is_bound());
route_provider_binding_.Bind(
- mojom::RouteProviderAssociatedRequest(std::move(handle)));
+ mojom::RouteProviderAssociatedRequest(std::move(handle)),
+ ipc_task_runner_ ? ipc_task_runner_
+ : base::ThreadTaskRunnerHandle::Get());
} else {
LOG(ERROR) << "Request for unknown Channel-associated interface: "
<< interface_name;
@@ -759,14 +782,14 @@ void ChildThreadImpl::ProcessShutdown() {
base::RunLoop::QuitCurrentWhenIdleDeprecated();
}
-void ChildThreadImpl::SetIPCLoggingEnabled(bool enable) {
#if BUILDFLAG(IPC_MESSAGE_LOG_ENABLED)
+void ChildThreadImpl::SetIPCLoggingEnabled(bool enable) {
if (enable)
IPC::Logging::GetInstance()->Enable();
else
IPC::Logging::GetInstance()->Disable();
-#endif // IPC_MESSAGE_LOG_ENABLED
}
+#endif // IPC_MESSAGE_LOG_ENABLED
void ChildThreadImpl::OnChildControlRequest(
mojom::ChildControlRequest request) {
diff --git a/chromium/content/child/child_thread_impl.h b/chromium/content/child/child_thread_impl.h
index 0d6aa96f348..523af416a39 100644
--- a/chromium/content/child/child_thread_impl.h
+++ b/chromium/content/child/child_thread_impl.h
@@ -24,7 +24,7 @@
#include "content/common/content_export.h"
#include "content/public/child/child_thread.h"
#include "ipc/ipc.mojom.h"
-#include "ipc/ipc_features.h" // For BUILDFLAG(IPC_MESSAGE_LOG_ENABLED).
+#include "ipc/ipc_buildflags.h" // For BUILDFLAG(IPC_MESSAGE_LOG_ENABLED).
#include "ipc/ipc_platform_file.h"
#include "ipc/message_router.h"
#include "mojo/public/cpp/bindings/associated_binding.h"
@@ -33,6 +33,8 @@
#if defined(OS_WIN)
#include "content/public/common/font_cache_win.mojom.h"
+#elif defined(OS_MACOSX)
+#include "content/common/font_loader_mac.mojom.h"
#endif
namespace base {
@@ -90,6 +92,11 @@ class CONTENT_EXPORT ChildThreadImpl
#if defined(OS_WIN)
void PreCacheFont(const LOGFONT& log_font) override;
void ReleaseCachedFonts() override;
+#elif defined(OS_MACOSX)
+ bool LoadFont(const base::string16& font_name,
+ float font_point_size,
+ mojo::ScopedSharedBufferHandle* out_font_data,
+ uint32_t* out_font_id) override;
#endif
void RecordAction(const base::UserMetricsAction& action) override;
void RecordComputedAction(const std::string& action) override;
@@ -150,7 +157,9 @@ class CONTENT_EXPORT ChildThreadImpl
// mojom::ChildControl
void ProcessShutdown() override;
+#if BUILDFLAG(IPC_MESSAGE_LOG_ENABLED)
void SetIPCLoggingEnabled(bool enable) override;
+#endif
void OnChildControlRequest(mojom::ChildControlRequest);
virtual bool OnControlMessageReceived(const IPC::Message& msg);
@@ -165,6 +174,10 @@ class CONTENT_EXPORT ChildThreadImpl
bool IsInBrowserProcess() const;
+#if defined(OS_MACOSX)
+ virtual mojom::FontLoaderMac* GetFontLoaderMac();
+#endif
+
private:
class ChildThreadMessageRouter : public IPC::MessageRouter {
public:
@@ -216,6 +229,8 @@ class CONTENT_EXPORT ChildThreadImpl
mojom::RouteProviderAssociatedPtr remote_route_provider_;
#if defined(OS_WIN)
mojom::FontCacheWinPtr font_cache_win_ptr_;
+#elif defined(OS_MACOSX)
+ mojom::FontLoaderMacPtr font_loader_mac_ptr_;
#endif
std::unique_ptr<IPC::SyncChannel> channel_;
diff --git a/chromium/content/child/content_child_helpers.cc b/chromium/content/child/content_child_helpers.cc
deleted file mode 100644
index 7ddeb4d16a9..00000000000
--- a/chromium/content/child/content_child_helpers.cc
+++ /dev/null
@@ -1,65 +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 "content/child/content_child_helpers.h"
-
-#include <stdint.h>
-
-#include <memory>
-
-#include "base/logging.h"
-#include "base/process/process_metrics.h"
-#include "build/build_config.h"
-#include "v8/include/v8.h"
-
-#if defined(OS_LINUX)
-#include <malloc.h>
-#endif
-
-namespace content {
-
-// TODO(primiano): get rid of this file together with --memory-metrics.
-// This function is both misplaced and misnamed. If useful, this should
-// be moved to base/process/process_metrics.h. Regardless the name,
-// though, this provides only a partial and misleading value.
-// Unfortunately some telemetry benchmark rely on it and these need to
-// be refactored before getting rid of this. See crbug.com/581365 .
-#if defined(OS_LINUX) || defined(OS_ANDROID)
-size_t GetMemoryUsageKB() {
- struct mallinfo minfo = mallinfo();
- uint64_t mem_usage =
-#if defined(USE_TCMALLOC)
- minfo.uordblks
-#else
- (minfo.hblkhd + minfo.arena)
-#endif
- >> 10;
-
- v8::HeapStatistics stat;
- // TODO(svenpanne) The call below doesn't take web workers into account, this
- // has to be done manually by iterating over all Isolates involved.
- v8::Isolate* isolate = v8::Isolate::GetCurrent();
- if (isolate)
- isolate->GetHeapStatistics(&stat);
- return mem_usage + (static_cast<uint64_t>(stat.total_heap_size()) >> 10);
-}
-#elif defined(OS_MACOSX)
-size_t GetMemoryUsageKB() {
- std::unique_ptr<base::ProcessMetrics> process_metrics(
- // The default port provider is sufficient to get data for the current
- // process.
- base::ProcessMetrics::CreateProcessMetrics(
- base::GetCurrentProcessHandle(), NULL));
- return process_metrics->GetWorkingSetSize() >> 10;
-}
-#else
-size_t GetMemoryUsageKB() {
- std::unique_ptr<base::ProcessMetrics> process_metrics(
- base::ProcessMetrics::CreateProcessMetrics(
- base::GetCurrentProcessHandle()));
- return process_metrics->GetPagefileUsage() >> 10;
-}
-#endif
-
-} // namespace content
diff --git a/chromium/content/child/content_child_helpers.h b/chromium/content/child/content_child_helpers.h
deleted file mode 100644
index 33dc4ab9bf4..00000000000
--- a/chromium/content/child/content_child_helpers.h
+++ /dev/null
@@ -1,20 +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 CONTENT_CHILD_CONTENT_CHILD_HELPERS_H_
-#define CONTENT_CHILD_CONTENT_CHILD_HELPERS_H_
-
-#include <stddef.h>
-
-namespace content {
-
-// Returns an estimate of the memory usage of the renderer process. Different
-// platforms implement this function differently, and count in different
-// allocations. Results are not comparable across platforms. The estimate is
-// computed inside the sandbox and thus its not always accurate.
-size_t GetMemoryUsageKB();
-
-} // content
-
-#endif // CONTENT_CHILD_CONTENT_CHILD_HELPERS_H_
diff --git a/chromium/content/child/dwrite_font_proxy/dwrite_font_proxy_init_impl_win.cc b/chromium/content/child/dwrite_font_proxy/dwrite_font_proxy_init_impl_win.cc
index 7ea43bb9f56..6f8be2d2672 100644
--- a/chromium/content/child/dwrite_font_proxy/dwrite_font_proxy_init_impl_win.cc
+++ b/chromium/content/child/dwrite_font_proxy/dwrite_font_proxy_init_impl_win.cc
@@ -16,7 +16,7 @@
#include "content/child/font_warmup_win.h"
#include "content/public/common/service_names.mojom.h"
#include "skia/ext/fontmgr_default_win.h"
-#include "third_party/WebKit/public/web/win/WebFontRendering.h"
+#include "third_party/blink/public/web/win/web_font_rendering.h"
#include "third_party/skia/include/ports/SkFontMgr.h"
#include "third_party/skia/include/ports/SkTypeface_win.h"
diff --git a/chromium/content/child/font_warmup_win.cc b/chromium/content/child/font_warmup_win.cc
index 19350e968e1..d9e98c1f790 100644
--- a/chromium/content/child/font_warmup_win.cc
+++ b/chromium/content/child/font_warmup_win.cc
@@ -23,7 +23,7 @@
#include "base/win/iat_patch_function.h"
#include "base/win/windows_version.h"
#include "build/build_config.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#include "skia/ext/fontmgr_default_win.h"
#include "third_party/skia/include/core/SkRefCnt.h"
#include "third_party/skia/include/ports/SkFontMgr.h"
@@ -355,18 +355,20 @@ class GdiFontPatchDataImpl : public content::GdiFontPatchData {
GdiFontPatchDataImpl::GdiFontPatchDataImpl(const base::FilePath& path) {
DoSingleGdiPatch(create_compatible_dc_patch_, path, "CreateCompatibleDC",
- CreateCompatibleDCPatch);
+ reinterpret_cast<void*>(CreateCompatibleDCPatch));
DoSingleGdiPatch(create_font_indirect_patch_, path, "CreateFontIndirectW",
- CreateFontIndirectWPatch);
- DoSingleGdiPatch(create_delete_dc_patch_, path, "DeleteDC", DeleteDCPatch);
+ reinterpret_cast<void*>(CreateFontIndirectWPatch));
+ DoSingleGdiPatch(create_delete_dc_patch_, path, "DeleteDC",
+ reinterpret_cast<void*>(DeleteDCPatch));
DoSingleGdiPatch(create_delete_object_patch_, path, "DeleteObject",
- DeleteObjectPatch);
+ reinterpret_cast<void*>(DeleteObjectPatch));
DoSingleGdiPatch(create_enum_font_families_patch_, path,
- "EnumFontFamiliesExW", EnumFontFamiliesExWPatch);
+ "EnumFontFamiliesExW",
+ reinterpret_cast<void*>(EnumFontFamiliesExWPatch));
DoSingleGdiPatch(create_get_font_data_patch_, path, "GetFontData",
- GetFontDataPatch);
+ reinterpret_cast<void*>(GetFontDataPatch));
DoSingleGdiPatch(create_select_object_patch_, path, "SelectObject",
- SelectObjectPatch);
+ reinterpret_cast<void*>(SelectObjectPatch));
}
} // namespace
@@ -398,26 +400,29 @@ void PatchServiceManagerCalls() {
is_patched = true;
- DWORD patched =
- g_iat_patch_open_sc_manager.Patch(L"dwrite.dll", service_provider_dll,
- "OpenSCManagerW", OpenSCManagerWPatch);
+ DWORD patched = g_iat_patch_open_sc_manager.Patch(
+ L"dwrite.dll", service_provider_dll, "OpenSCManagerW",
+ reinterpret_cast<void*>(OpenSCManagerWPatch));
DCHECK(patched == 0);
patched = g_iat_patch_close_service_handle.Patch(
L"dwrite.dll", service_provider_dll, "CloseServiceHandle",
- CloseServiceHandlePatch);
+ reinterpret_cast<void*>(CloseServiceHandlePatch));
DCHECK(patched == 0);
- patched = g_iat_patch_open_service.Patch(L"dwrite.dll", service_provider_dll,
- "OpenServiceW", OpenServiceWPatch);
+ patched = g_iat_patch_open_service.Patch(
+ L"dwrite.dll", service_provider_dll, "OpenServiceW",
+ reinterpret_cast<void*>(OpenServiceWPatch));
DCHECK(patched == 0);
patched = g_iat_patch_start_service.Patch(
- L"dwrite.dll", service_provider_dll, "StartServiceW", StartServiceWPatch);
+ L"dwrite.dll", service_provider_dll, "StartServiceW",
+ reinterpret_cast<void*>(StartServiceWPatch));
DCHECK(patched == 0);
patched = g_iat_patch_nt_connect_port.Patch(
- L"dwrite.dll", "ntdll.dll", "NtAlpcConnectPort", NtALpcConnectPortPatch);
+ L"dwrite.dll", "ntdll.dll", "NtAlpcConnectPort",
+ reinterpret_cast<void*>(NtALpcConnectPortPatch));
DCHECK(patched == 0);
}
diff --git a/chromium/content/child/image_decoder.cc b/chromium/content/child/image_decoder.cc
index 33e5835ddd9..b4d7b3ca6d4 100644
--- a/chromium/content/child/image_decoder.cc
+++ b/chromium/content/child/image_decoder.cc
@@ -5,9 +5,9 @@
#include "content/child/image_decoder.h"
#include "content/public/child/image_decoder_utils.h"
-#include "third_party/WebKit/public/platform/WebData.h"
-#include "third_party/WebKit/public/platform/WebImage.h"
-#include "third_party/WebKit/public/platform/WebSize.h"
+#include "third_party/blink/public/platform/web_data.h"
+#include "third_party/blink/public/platform/web_image.h"
+#include "third_party/blink/public/platform/web_size.h"
#include "third_party/skia/include/core/SkBitmap.h"
using blink::WebData;
diff --git a/chromium/content/child/runtime_features.cc b/chromium/content/child/runtime_features.cc
index 5835127cdbd..03a522caa66 100644
--- a/chromium/content/child/runtime_features.cc
+++ b/chromium/content/child/runtime_features.cc
@@ -18,7 +18,7 @@
#include "media/base/media_switches.h"
#include "services/device/public/cpp/device_features.h"
#include "services/network/public/cpp/features.h"
-#include "third_party/WebKit/public/platform/WebRuntimeFeatures.h"
+#include "third_party/blink/public/platform/web_runtime_features.h"
#include "ui/gfx/switches.h"
#include "ui/gl/gl_switches.h"
#include "ui/native_theme/native_theme_features.h"
@@ -81,10 +81,6 @@ static void SetRuntimeFeatureDefaultsForPlatform() {
#if !defined(OS_MACOSX)
WebRuntimeFeatures::EnableNotificationContentImage(true);
#endif
-
-#if defined(OS_ANDROID)
- WebRuntimeFeatures::EnableDoubleTapToJumpOnVideo(true);
-#endif
}
void SetRuntimeFeaturesDefaultsAndUpdateFromArgs(
@@ -130,9 +126,6 @@ void SetRuntimeFeaturesDefaultsAndUpdateFromArgs(
if (command_line.HasSwitch(switches::kDisableFileSystem))
WebRuntimeFeatures::EnableFileSystem(false);
- if (command_line.HasSwitch(switches::kEnableExperimentalCanvasFeatures))
- WebRuntimeFeatures::EnableExperimentalCanvasFeatures(true);
-
if (!command_line.HasSwitch(switches::kDisableAcceleratedJpegDecoding))
WebRuntimeFeatures::EnableDecodeToYUV(true);
@@ -211,8 +204,11 @@ void SetRuntimeFeaturesDefaultsAndUpdateFromArgs(
if (command_line.HasSwitch(switches::kEnableWebVR))
WebRuntimeFeatures::EnableWebVR(true);
- WebRuntimeFeatures::EnableWebXR(
- base::FeatureList::IsEnabled(features::kWebXr));
+ if (base::FeatureList::IsEnabled(features::kWebXr))
+ WebRuntimeFeatures::EnableWebXR(true);
+
+ if (base::FeatureList::IsEnabled(features::kWebXrGamepadSupport))
+ WebRuntimeFeatures::EnableWebXRGamepadSupport(true);
if (command_line.HasSwitch(switches::kDisablePresentationAPI))
WebRuntimeFeatures::EnablePresentationAPI(false);
@@ -254,10 +250,6 @@ void SetRuntimeFeaturesDefaultsAndUpdateFromArgs(
base::FeatureList::IsEnabled(
features::kFramebustingNeedsSameOriginOrUserGesture));
- WebRuntimeFeatures::EnableFeatureFromString(
- "VibrateRequiresUserGesture",
- base::FeatureList::IsEnabled(features::kVibrateRequiresUserGesture));
-
if (command_line.HasSwitch(switches::kDisableBackgroundTimerThrottling))
WebRuntimeFeatures::EnableTimerThrottlingForBackgroundTabs(false);
@@ -338,6 +330,13 @@ void SetRuntimeFeaturesDefaultsAndUpdateFromArgs(
false);
}
+ if (base::FeatureList::IsEnabled(
+ features::kTurnOff2DAndOpacityCompositorAnimations))
+ WebRuntimeFeatures::EnableTurnOff2DAndOpacityCompositorAnimations(true);
+
+ if (base::FeatureList::IsEnabled(features::kRasterInducingScroll))
+ WebRuntimeFeatures::EnableRasterInducingScroll(true);
+
WebRuntimeFeatures::EnableFeatureFromString(
"AllowContentInitiatedDataUrlNavigations",
base::FeatureList::IsEnabled(
@@ -353,9 +352,8 @@ void SetRuntimeFeaturesDefaultsAndUpdateFromArgs(
WebRuntimeFeatures::EnableAutoplayMutedVideos(true);
}
- if (!base::FeatureList::IsEnabled(features::kWebAuth) &&
- !enableExperimentalWebPlatformFeatures)
- WebRuntimeFeatures::EnableWebAuth(false);
+ WebRuntimeFeatures::EnableWebAuth(
+ base::FeatureList::IsEnabled(features::kWebAuth));
WebRuntimeFeatures::EnableClientPlaceholdersForServerLoFi(
base::GetFieldTrialParamValue("PreviewsClientLoFi",
@@ -401,6 +399,9 @@ void SetRuntimeFeaturesDefaultsAndUpdateFromArgs(
if (base::FeatureList::IsEnabled(features::kKeyboardLockAPI))
WebRuntimeFeatures::EnableFeatureFromString("KeyboardLock", true);
+ if (base::FeatureList::IsEnabled(features::kLazyFrameLoading))
+ WebRuntimeFeatures::EnableLazyFrameLoading(true);
+
// Enable explicitly enabled features, and then disable explicitly disabled
// ones.
for (const std::string& feature :
@@ -421,6 +422,9 @@ void SetRuntimeFeaturesDefaultsAndUpdateFromArgs(
if (base::FeatureList::IsEnabled(features::kStopLoadingInBackground))
WebRuntimeFeatures::EnableStopLoadingInBackground(true);
+ if (base::FeatureList::IsEnabled(features::kStopNonTimersInBackground))
+ WebRuntimeFeatures::EnableStopNonTimersInBackground(true);
+
WebRuntimeFeatures::EnablePWAFullCodeCache(
base::FeatureList::IsEnabled(features::kPWAFullCodeCache));
@@ -433,8 +437,18 @@ void SetRuntimeFeaturesDefaultsAndUpdateFromArgs(
WebRuntimeFeatures::EnableCodeCacheAfterExecute(
base::FeatureList::IsEnabled(features::kCodeCacheAfterExecute));
+ WebRuntimeFeatures::EnableCacheInlineScriptCode(
+ base::FeatureList::IsEnabled(features::kCacheInlineScriptCode));
+
if (base::FeatureList::IsEnabled(features::kUnifiedTouchAdjustment))
WebRuntimeFeatures::EnableUnifiedTouchAdjustment(true);
+
+ // Make srcset on link rel=preload work with SignedHTTPExchange flag too.
+ if (base::FeatureList::IsEnabled(features::kSignedHTTPExchange))
+ WebRuntimeFeatures::EnablePreloadImageSrcSetEnabled(true);
+
+ WebRuntimeFeatures::EnableOffMainThreadWebSocket(
+ base::FeatureList::IsEnabled(features::kOffMainThreadWebSocket));
};
} // namespace content
diff --git a/chromium/content/child/scoped_web_callbacks.h b/chromium/content/child/scoped_web_callbacks.h
index 43a5ef3db59..725548f7784 100644
--- a/chromium/content/child/scoped_web_callbacks.h
+++ b/chromium/content/child/scoped_web_callbacks.h
@@ -11,7 +11,7 @@
#include "base/callback.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
-#include "third_party/WebKit/public/platform/WebCallbacks.h"
+#include "third_party/blink/public/platform/web_callbacks.h"
// A ScopedWebCallbacks is a move-only scoper which helps manage the lifetime of
// a blink::WebCallbacks object. This is particularly useful when you're
diff --git a/chromium/content/child/service_factory.cc b/chromium/content/child/service_factory.cc
index 686d38eb61c..1c1361d759f 100644
--- a/chromium/content/child/service_factory.cc
+++ b/chromium/content/child/service_factory.cc
@@ -7,7 +7,6 @@
#include <utility>
#include "base/bind.h"
-#include "base/memory/ptr_util.h"
#include "content/public/common/content_client.h"
#include "services/service_manager/embedder/embedded_service_runner.h"
diff --git a/chromium/content/child/webfallbackthemeengine_impl.cc b/chromium/content/child/webfallbackthemeengine_impl.cc
index 1a78da27e76..5c091bc0a75 100644
--- a/chromium/content/child/webfallbackthemeengine_impl.cc
+++ b/chromium/content/child/webfallbackthemeengine_impl.cc
@@ -6,8 +6,8 @@
#include "base/macros.h"
#include "skia/ext/platform_canvas.h"
-#include "third_party/WebKit/public/platform/WebRect.h"
-#include "third_party/WebKit/public/platform/WebSize.h"
+#include "third_party/blink/public/platform/web_rect.h"
+#include "third_party/blink/public/platform/web_size.h"
#include "ui/native_theme/native_theme_base.h"
using blink::WebCanvas;
diff --git a/chromium/content/child/webfallbackthemeengine_impl.h b/chromium/content/child/webfallbackthemeengine_impl.h
index 4960d7fd513..53f7b83c2df 100644
--- a/chromium/content/child/webfallbackthemeengine_impl.h
+++ b/chromium/content/child/webfallbackthemeengine_impl.h
@@ -8,7 +8,7 @@
#include <memory>
#include "base/macros.h"
-#include "third_party/WebKit/public/platform/WebFallbackThemeEngine.h"
+#include "third_party/blink/public/platform/web_fallback_theme_engine.h"
namespace content {
diff --git a/chromium/content/child/webthemeengine_impl_android.cc b/chromium/content/child/webthemeengine_impl_android.cc
index a1ce572eb50..a66f7fbce54 100644
--- a/chromium/content/child/webthemeengine_impl_android.cc
+++ b/chromium/content/child/webthemeengine_impl_android.cc
@@ -7,8 +7,8 @@
#include "base/logging.h"
#include "base/sys_info.h"
#include "skia/ext/platform_canvas.h"
-#include "third_party/WebKit/public/platform/WebRect.h"
-#include "third_party/WebKit/public/platform/WebSize.h"
+#include "third_party/blink/public/platform/web_rect.h"
+#include "third_party/blink/public/platform/web_size.h"
#include "ui/native_theme/native_theme.h"
using blink::WebCanvas;
diff --git a/chromium/content/child/webthemeengine_impl_android.h b/chromium/content/child/webthemeengine_impl_android.h
index 833ff9bfced..b17b2d63cdb 100644
--- a/chromium/content/child/webthemeengine_impl_android.h
+++ b/chromium/content/child/webthemeengine_impl_android.h
@@ -5,7 +5,7 @@
#ifndef CONTENT_CHILD_WEBTHEMEENGINE_IMPL_ANDROID_H_
#define CONTENT_CHILD_WEBTHEMEENGINE_IMPL_ANDROID_H_
-#include "third_party/WebKit/public/platform/WebThemeEngine.h"
+#include "third_party/blink/public/platform/web_theme_engine.h"
namespace content {
diff --git a/chromium/content/child/webthemeengine_impl_default.cc b/chromium/content/child/webthemeengine_impl_default.cc
index 232ff4ae9ad..6d898cc534c 100644
--- a/chromium/content/child/webthemeengine_impl_default.cc
+++ b/chromium/content/child/webthemeengine_impl_default.cc
@@ -6,8 +6,8 @@
#include "build/build_config.h"
#include "skia/ext/platform_canvas.h"
-#include "third_party/WebKit/public/platform/WebRect.h"
-#include "third_party/WebKit/public/platform/WebSize.h"
+#include "third_party/blink/public/platform/web_rect.h"
+#include "third_party/blink/public/platform/web_size.h"
#include "ui/native_theme/native_theme.h"
#include "ui/native_theme/overlay_scrollbar_constants_aura.h"
diff --git a/chromium/content/child/webthemeengine_impl_default.h b/chromium/content/child/webthemeengine_impl_default.h
index 7de46aa3709..d3ae6ab2309 100644
--- a/chromium/content/child/webthemeengine_impl_default.h
+++ b/chromium/content/child/webthemeengine_impl_default.h
@@ -8,7 +8,7 @@
#include <stdint.h>
#include "build/build_config.h"
-#include "third_party/WebKit/public/platform/WebThemeEngine.h"
+#include "third_party/blink/public/platform/web_theme_engine.h"
namespace content {
diff --git a/chromium/content/child/webthemeengine_impl_mac.h b/chromium/content/child/webthemeengine_impl_mac.h
index f937361a26e..e63b62f4464 100644
--- a/chromium/content/child/webthemeengine_impl_mac.h
+++ b/chromium/content/child/webthemeengine_impl_mac.h
@@ -5,7 +5,7 @@
#ifndef CONTENT_CHILD_WEBTHEMEENGINE_IMPL_MAC_H_
#define CONTENT_CHILD_WEBTHEMEENGINE_IMPL_MAC_H_
-#include "third_party/WebKit/public/platform/WebThemeEngine.h"
+#include "third_party/blink/public/platform/web_theme_engine.h"
namespace content {
diff --git a/chromium/content/common/BUILD.gn b/chromium/content/common/BUILD.gn
index 6e997330a43..397d9172812 100644
--- a/chromium/content/common/BUILD.gn
+++ b/chromium/content/common/BUILD.gn
@@ -6,9 +6,10 @@ import("features.gni")
import("//build/buildflag_header.gni")
import("//build/config/features.gni")
import("//build/config/ui.gni")
+import("//ipc/features.gni")
import("//media/media_options.gni")
import("//mojo/public/tools/bindings/mojom.gni")
-import("//ppapi/features/features.gni")
+import("//ppapi/buildflags/buildflags.gni")
import("//sandbox/features.gni")
import("//tools/ipc_fuzzer/ipc_fuzzer.gni")
if (is_mac) {
@@ -17,8 +18,8 @@ if (is_mac) {
# For feature flags internal to content. See content/public/common:features
# for feature flags that clients of contents need to know about.
-buildflag_header("features") {
- header = "features.h"
+buildflag_header("buildflags") {
+ header = "buildflags.h"
flags = [
"USE_EXTERNAL_POPUP_MENU=$use_external_popup_menu",
@@ -36,7 +37,6 @@ source_set("common") {
sources = [
"accessibility_messages.h",
"all_messages.h",
- "android/browser_side_navigation_policy_android.cc",
"android/gin_java_bridge_errors.cc",
"android/gin_java_bridge_errors.h",
"android/gin_java_bridge_value.cc",
@@ -65,7 +65,6 @@ source_set("common") {
"browser_plugin/browser_plugin_constants.cc",
"browser_plugin/browser_plugin_constants.h",
"browser_plugin/browser_plugin_messages.h",
- "cache_storage/cache_storage_messages.h",
"cache_storage/cache_storage_types.cc",
"cache_storage/cache_storage_types.h",
"child_process_host_impl.cc",
@@ -96,8 +95,6 @@ source_set("common") {
"content_security_policy_header.h",
"content_switches_internal.cc",
"content_switches_internal.h",
- "cross_site_document_classifier.cc",
- "cross_site_document_classifier.h",
"cursors/webcursor.cc",
"cursors/webcursor.h",
"cursors/webcursor_android.cc",
@@ -130,6 +127,8 @@ source_set("common") {
"font_list_fontconfig.cc",
"font_list_mac.mm",
"font_list_win.cc",
+ "font_loader_dispatcher_mac.cc",
+ "font_loader_dispatcher_mac.h",
"frame_message_enums.h",
"frame_message_structs.cc",
"frame_message_structs.h",
@@ -139,6 +138,8 @@ source_set("common") {
"frame_owner_properties.h",
"frame_replication_state.cc",
"frame_replication_state.h",
+ "frame_resize_params.cc",
+ "frame_resize_params.h",
"gin_java_bridge_messages.h",
"in_process_child_thread_params.cc",
"in_process_child_thread_params.h",
@@ -214,7 +215,6 @@ source_set("common") {
"media/media_stream_controls.h",
"media/media_stream_param_traits.cc",
"media/media_stream_param_traits.h",
- "media/media_stream_track_metrics_host_messages.h",
"media/midi_messages.h",
"media/peer_connection_tracker_messages.h",
"media/surface_view_manager_messages_android.h",
@@ -267,7 +267,6 @@ source_set("common") {
"send_zygote_child_ping_linux.cc",
"service_manager/service_manager_connection_impl.cc",
"service_manager/service_manager_connection_impl.h",
- "service_worker/embedded_worker_messages.h",
"service_worker/service_worker_loader_helpers.cc",
"service_worker/service_worker_loader_helpers.h",
"service_worker/service_worker_messages.h",
@@ -300,8 +299,6 @@ source_set("common") {
"user_agent.cc",
"view_message_enums.h",
"view_messages.h",
- "weak_wrapper_shared_url_loader_factory.cc",
- "weak_wrapper_shared_url_loader_factory.h",
"wrapper_shared_url_loader_factory.cc",
"wrapper_shared_url_loader_factory.h",
"zygote_commands_linux.h",
@@ -320,17 +317,18 @@ source_set("common") {
"//ipc",
"//services/network:network_service",
"//services/service_manager/sandbox",
- "//third_party/WebKit/public:blink_headers",
- "//third_party/WebKit/public/common",
+ "//third_party/blink/public:blink_headers",
+ "//third_party/blink/public/common",
"//ui/accessibility",
]
deps = [
- ":features",
+ ":buildflags",
"//base",
"//base/third_party/dynamic_annotations",
"//build/util:webkit_version",
"//cc/ipc",
"//components/discardable_memory/common",
+ "//components/services/filesystem/public/interfaces",
"//components/tracing",
"//components/tracing:startup_tracing",
"//components/viz/service",
@@ -338,7 +336,7 @@ source_set("common") {
"//content/app/resources",
"//content/public/common:interfaces",
"//content/public/common:service_names",
- "//content/public/common:zygote_features",
+ "//content/public/common:zygote_buildflags",
"//device/base/synchronization",
"//device/bluetooth",
"//gpu",
@@ -355,17 +353,17 @@ source_set("common") {
"//media/base/ipc",
"//media/capture",
"//media/capture/ipc",
- "//media/gpu:features",
+ "//media/gpu:buildflags",
"//media/gpu/ipc/client",
"//media/gpu/ipc/common",
"//media/midi",
"//media/midi:mojo",
- "//mojo/common:common_base",
- "//mojo/edk/system",
+ "//mojo/edk",
+ "//mojo/public/cpp/system",
"//net",
- "//ppapi/features",
+ "//ppapi/buildflags",
"//sandbox",
- "//sandbox:sandbox_features",
+ "//sandbox:sandbox_buildflags",
"//services/network/public/cpp",
"//services/network/public/mojom",
"//services/resource_coordinator/public/cpp:resource_coordinator_cpp",
@@ -532,6 +530,11 @@ mojom("mojo_bindings") {
# indexed_db.mojom uses a native typemap that is not available in Java.
cpp_only = true
+ # imports vs deps check is disabled for this target to work around
+ # windows multiple definitions linker error caused by having
+ # both a direct and an indirect dependency on the same target
+ skip_deps_check = true
+
sources = [
"appcache.mojom",
"associated_interfaces.mojom",
@@ -589,31 +592,49 @@ mojom("mojo_bindings") {
sources += [ "dwrite_font_proxy.mojom" ]
}
+ if (is_mac) {
+ sources += [ "font_loader_mac.mojom" ]
+ }
+
+ enabled_features = []
+ if (enable_ipc_logging) {
+ enabled_features += [ "ipc_logging" ]
+ }
+ if (is_linux || is_chromeos) {
+ enabled_features += [ "supports_thread_priorities" ]
+ }
+
import_dirs = [ "//mojo/services" ]
public_deps = [
- "//components/leveldb/public/interfaces",
+ "//components/services/leveldb/public/interfaces",
"//content/public/common:interfaces",
+ "//content/public/common:resource_type_bindings",
"//ipc:mojom_constants",
"//media/mojo/interfaces",
- "//mojo/common:common_custom_types",
+ "//mojo/public/mojom/base",
"//services/network/public/mojom",
"//services/service_manager/public/mojom",
"//services/ui/public/interfaces",
+ "//services/ui/public/interfaces/ime",
"//services/video_capture/public/mojom",
"//services/viz/public/interfaces",
"//skia/public/interfaces",
- "//third_party/WebKit/public:mojo_bindings",
- "//third_party/WebKit/public/mojom",
+ "//third_party/blink/public:mojo_bindings",
+ "//third_party/blink/public:web_feature_mojo_bindings",
+ "//third_party/blink/public/mojom:mojom_core",
"//ui/base/mojo:mojo_bindings",
+ "//ui/events/mojo:interfaces",
"//ui/gfx/geometry/mojo",
"//ui/gfx/mojo",
+ "//ui/gfx/range/mojo",
+ "//ui/latency/mojo:interfaces",
"//url/mojom:url_mojom_gurl",
"//url/mojom:url_mojom_origin",
]
- overridden_deps = [ "//third_party/WebKit/public/mojom" ]
- component_deps = [ "//third_party/WebKit/public/common" ]
+ overridden_deps = [ "//third_party/blink/public/mojom:mojom_core" ]
+ component_deps = [ "//third_party/blink/public/common" ]
component_output_prefix = "content_common_mojo_bindings"
export_class_attribute = "CONTENT_EXPORT"
diff --git a/chromium/content/common/DEPS b/chromium/content/common/DEPS
index 66e580071ad..17e3223f618 100644
--- a/chromium/content/common/DEPS
+++ b/chromium/content/common/DEPS
@@ -12,77 +12,78 @@ include_rules = [
"+services/service_manager/public/cpp",
"+services/service_manager/sandbox",
"+services/video_capture/public/mojom",
+ "+services/viz/public/cpp",
"+services/viz/public/interfaces",
# No inclusion of WebKit from the browser, other than the ones in
# WebKit/public/{mojom,common}, or the ones that are strictly enum/POD,
# header-only types, and some selected common code.
- "-third_party/WebKit",
- "+third_party/WebKit/public/common",
- "+third_party/WebKit/public/mojom",
- "+third_party/WebKit/public/platform/WebAddressSpace.h",
- "+third_party/WebKit/public/platform/WebContentSecurityPolicy.h",
- "+third_party/WebKit/public/platform/WebDisplayMode.h",
- "+third_party/WebKit/public/platform/WebDragOperation.h",
- "+third_party/WebKit/public/platform/WebFloatPoint.h",
- "+third_party/WebKit/public/platform/WebFloatRect.h",
- "+third_party/WebKit/public/platform/WebFocusType.h",
- "+third_party/WebKit/public/platform/WebFullscreenVideoStatus.h",
- "+third_party/WebKit/public/platform/WebGestureEvent.h",
- "+third_party/WebKit/public/platform/WebHTTPBody.h",
- "+third_party/WebKit/public/platform/WebHistoryScrollRestorationType.h",
- "+third_party/WebKit/public/platform/WebInputEvent.h",
- "+third_party/WebKit/public/platform/WebInsecureRequestPolicy.h",
- "+third_party/WebKit/public/platform/WebIntrinsicSizingInfo.h",
- "+third_party/WebKit/public/platform/WebKeyboardEvent.h",
- "+third_party/WebKit/public/platform/WebMixedContentContextType.h",
- "+third_party/WebKit/public/platform/WebMouseWheelEvent.h",
- "+third_party/WebKit/public/platform/WebPointerProperties.h",
- "+third_party/WebKit/public/platform/WebOriginTrialTokenStatus.h",
- "+third_party/WebKit/public/platform/WebPageVisibilityState.h",
- "+third_party/WebKit/public/platform/WebReferrerPolicy.h",
- "+third_party/WebKit/public/platform/WebScreenInfo.h",
- "+third_party/WebKit/public/platform/WebScrollbarButtonsPlacement.h",
- "+third_party/WebKit/public/platform/WebScrollIntoViewParams.h",
- "+third_party/WebKit/public/platform/WebStorageArea.h",
- "+third_party/WebKit/public/platform/WebSuddenTerminationDisablerType.h",
- "+third_party/WebKit/public/platform/WebTouchEvent.h",
- "+third_party/WebKit/public/platform/linux/WebFallbackFont.h",
- "+third_party/WebKit/public/platform/mac/WebScrollbarTheme.h",
- "+third_party/WebKit/public/platform/modules/bluetooth/web_bluetooth.mojom.h",
- "+third_party/WebKit/public/platform/modules/cache_storage/cache_storage.mojom.h",
- "+third_party/WebKit/public/platform/modules/device_orientation/WebDeviceMotionData.h",
- "+third_party/WebKit/public/platform/modules/device_orientation/WebDeviceOrientationData.h",
- "+third_party/WebKit/public/platform/modules/fetch/fetch_api_request.mojom.h",
- "+third_party/WebKit/public/platform/modules/fetch/fetch_api_response.mojom.h",
- "+third_party/WebKit/public/platform/modules/indexeddb/WebIDBTypes.h",
- "+third_party/WebKit/public/platform/modules/mediasession/media_session.mojom.h",
- "+third_party/WebKit/public/platform/modules/mediastream/media_devices.mojom.h",
- "+third_party/WebKit/public/platform/modules/permissions/permission.mojom.h",
- "+third_party/WebKit/public/platform/modules/permissions/permission_status.mojom.h",
- "+third_party/WebKit/public/platform/modules/presentation/presentation.mojom.h",
- "+third_party/WebKit/public/platform/modules/push_messaging/WebPushError.h",
- "+third_party/WebKit/public/platform/modules/remoteplayback/WebRemotePlaybackAvailability.h",
- "+third_party/WebKit/public/platform/modules/screen_orientation/WebLockOrientationError.h",
- "+third_party/WebKit/public/platform/modules/screen_orientation/WebScreenOrientationLockType.h",
- "+third_party/WebKit/public/platform/modules/screen_orientation/WebScreenOrientationType.h",
- "+third_party/WebKit/public/platform/modules/payments/WebPaymentAppRequest.h",
- "+third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerClientType.h",
- "+third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerError.h",
- "+third_party/WebKit/public/web/WebAXEnums.h",
- "+third_party/WebKit/public/web/WebDeviceEmulationParams.h",
- "+third_party/WebKit/public/web/WebDragStatus.h",
- "+third_party/WebKit/public/web/WebFindOptions.h",
- "+third_party/WebKit/public/web/WebFrameOwnerProperties.h",
- "+third_party/WebKit/public/web/WebFrameSerializerCacheControlPolicy.h",
- "+third_party/WebKit/public/web/WebImeTextSpan.h",
- "+third_party/WebKit/public/web/WebMediaPlayerAction.h",
- "+third_party/WebKit/public/web/WebPluginAction.h",
- "+third_party/WebKit/public/web/WebPopupType.h",
- "+third_party/WebKit/public/web/WebSharedWorkerCreationContextType.h",
- "+third_party/WebKit/public/web/WebSharedWorkerCreationErrors.h",
- "+third_party/WebKit/public/web/WebTextDirection.h",
- "+third_party/WebKit/public/web/WebTreeScopeType.h",
- "+third_party/WebKit/public/web/WebTriggeringEventInfo.h",
- "+third_party/WebKit/public/web/win/WebFontRendering.h",
+ "-third_party/blink",
+ "+third_party/blink/public/common",
+ "+third_party/blink/public/mojom",
+ "+third_party/blink/public/platform/WebAddressSpace.h",
+ "+third_party/blink/public/platform/web_content_security_policy.h",
+ "+third_party/blink/public/platform/web_display_mode.h",
+ "+third_party/blink/public/platform/web_drag_operation.h",
+ "+third_party/blink/public/platform/web_float_point.h",
+ "+third_party/blink/public/platform/web_float_rect.h",
+ "+third_party/blink/public/platform/web_focus_type.h",
+ "+third_party/blink/public/platform/web_fullscreen_video_status.h",
+ "+third_party/blink/public/platform/web_gesture_event.h",
+ "+third_party/blink/public/platform/web_http_body.h",
+ "+third_party/blink/public/platform/web_history_scroll_restoration_type.h",
+ "+third_party/blink/public/platform/web_input_event.h",
+ "+third_party/blink/public/platform/web_insecure_request_policy.h",
+ "+third_party/blink/public/platform/web_intrinsic_sizing_info.h",
+ "+third_party/blink/public/platform/web_keyboard_event.h",
+ "+third_party/blink/public/platform/web_mixed_content_context_type.h",
+ "+third_party/blink/public/platform/web_mouse_wheel_event.h",
+ "+third_party/blink/public/platform/web_pointer_properties.h",
+ "+third_party/blink/public/platform/WebOriginTrialTokenStatus.h",
+ "+third_party/blink/public/platform/WebPageVisibilityState.h",
+ "+third_party/blink/public/platform/web_referrer_policy.h",
+ "+third_party/blink/public/platform/web_screen_info.h",
+ "+third_party/blink/public/platform/web_scrollbar_buttons_placement.h",
+ "+third_party/blink/public/platform/web_scroll_into_view_params.h",
+ "+third_party/blink/public/platform/web_storage_area.h",
+ "+third_party/blink/public/platform/web_sudden_termination_disabler_type.h",
+ "+third_party/blink/public/platform/web_touch_event.h",
+ "+third_party/blink/public/platform/linux/web_fallback_font.h",
+ "+third_party/blink/public/platform/mac/web_scrollbar_theme.h",
+ "+third_party/blink/public/platform/modules/bluetooth/web_bluetooth.mojom.h",
+ "+third_party/blink/public/platform/modules/cache_storage/cache_storage.mojom.h",
+ "+third_party/blink/public/platform/modules/device_orientation/WebDeviceMotionData.h",
+ "+third_party/blink/public/platform/modules/device_orientation/WebDeviceOrientationData.h",
+ "+third_party/blink/public/platform/modules/fetch/fetch_api_request.mojom.h",
+ "+third_party/blink/public/platform/modules/fetch/fetch_api_response.mojom.h",
+ "+third_party/blink/public/platform/modules/indexeddb/web_idb_types.h",
+ "+third_party/blink/public/platform/modules/mediasession/media_session.mojom.h",
+ "+third_party/blink/public/platform/modules/mediastream/media_devices.mojom.h",
+ "+third_party/blink/public/platform/modules/permissions/permission.mojom.h",
+ "+third_party/blink/public/platform/modules/permissions/permission_status.mojom.h",
+ "+third_party/blink/public/platform/modules/presentation/presentation.mojom.h",
+ "+third_party/blink/public/platform/modules/push_messaging/web_push_error.h",
+ "+third_party/blink/public/platform/modules/remoteplayback/web_remote_playback_availability.h",
+ "+third_party/blink/public/platform/modules/screen_orientation/web_lock_orientation_error.h",
+ "+third_party/blink/public/platform/modules/screen_orientation/web_screen_orientation_lock_type.h",
+ "+third_party/blink/public/platform/modules/screen_orientation/web_screen_orientation_type.h",
+ "+third_party/blink/public/platform/modules/payments/WebPaymentAppRequest.h",
+ "+third_party/blink/public/platform/modules/serviceworker/WebServiceWorkerClientType.h",
+ "+third_party/blink/public/platform/modules/serviceworker/web_service_worker_error.h",
+ "+third_party/blink/public/web/web_ax_enums.h",
+ "+third_party/blink/public/web/web_device_emulation_params.h",
+ "+third_party/blink/public/web/web_drag_status.h",
+ "+third_party/blink/public/web/web_find_options.h",
+ "+third_party/blink/public/web/web_frame_owner_properties.h",
+ "+third_party/blink/public/web/web_frame_serializer_cache_control_policy.h",
+ "+third_party/blink/public/web/web_ime_text_span.h",
+ "+third_party/blink/public/web/web_media_player_action.h",
+ "+third_party/blink/public/web/web_plugin_action.h",
+ "+third_party/blink/public/web/web_popup_type.h",
+ "+third_party/blink/public/web/WebSharedWorkerCreationContextType.h",
+ "+third_party/blink/public/web/WebSharedWorkerCreationErrors.h",
+ "+third_party/blink/public/web/web_text_direction.h",
+ "+third_party/blink/public/web/web_tree_scope_type.h",
+ "+third_party/blink/public/web/web_triggering_event_info.h",
+ "+third_party/blink/public/web/win/web_font_rendering.h",
]
diff --git a/chromium/content/common/accessibility_messages.h b/chromium/content/common/accessibility_messages.h
index 2fa64a2fdfb..c97b2ae083f 100644
--- a/chromium/content/common/accessibility_messages.h
+++ b/chromium/content/common/accessibility_messages.h
@@ -9,12 +9,13 @@
#include "content/common/ax_content_node_data.h"
#include "content/common/content_export.h"
+#include "content/common/content_param_traits.h"
#include "content/common/view_message_enums.h"
#include "ipc/ipc_message_macros.h"
#include "ipc/ipc_message_utils.h"
#include "ipc/ipc_param_traits.h"
#include "ipc/param_traits_macros.h"
-#include "third_party/WebKit/public/web/WebAXEnums.h"
+#include "third_party/blink/public/web/web_ax_enums.h"
#include "ui/accessibility/ax_action_data.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/accessibility/ax_relative_bounds.h"
@@ -28,7 +29,7 @@
IPC_ENUM_TRAITS_MAX_VALUE(content::AXContentIntAttribute,
content::AX_CONTENT_INT_ATTRIBUTE_LAST)
-IPC_ENUM_TRAITS_MAX_VALUE(ax::mojom::Action, ax::mojom::Action::kLast)
+IPC_ENUM_TRAITS_MAX_VALUE(ax::mojom::Action, ax::mojom::Action::kMaxValue)
IPC_STRUCT_TRAITS_BEGIN(ui::AXActionData)
IPC_STRUCT_TRAITS_MEMBER(action)
@@ -182,8 +183,9 @@ IPC_MESSAGE_ROUTED0(AccessibilityMsg_FatalError)
// Request a one-time snapshot of the accessibility tree without
// enabling accessibility if it wasn't already enabled. The passed id
// will be returned in the AccessibilityHostMsg_SnapshotResponse message.
-IPC_MESSAGE_ROUTED1(AccessibilityMsg_SnapshotTree,
- int /* callback id */)
+IPC_MESSAGE_ROUTED2(AccessibilityMsg_SnapshotTree,
+ int /* callback id */,
+ ui::AXMode /* ax_mode */)
// Messages sent from the renderer to the browser.
diff --git a/chromium/content/common/all_messages.h b/chromium/content/common/all_messages.h
index 31cc3abb117..be7d1f42c70 100644
--- a/chromium/content/common/all_messages.h
+++ b/chromium/content/common/all_messages.h
@@ -8,7 +8,7 @@
// ipc/ipc_message_start.h to ensure the corresponding message file is
// included here.
//
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#include "content/common/content_message_generator.h"
#if BUILDFLAG(ENABLE_PLUGINS)
diff --git a/chromium/content/common/android/browser_side_navigation_policy_android.cc b/chromium/content/common/android/browser_side_navigation_policy_android.cc
deleted file mode 100644
index a14dddd40f9..00000000000
--- a/chromium/content/common/android/browser_side_navigation_policy_android.cc
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <jni.h>
-
-#include "base/android/scoped_java_ref.h"
-#include "content/public/common/browser_side_navigation_policy.h"
-#include "jni/BrowserSideNavigationPolicy_jni.h"
-
-using base::android::JavaParamRef;
-
-namespace content {
-
-jboolean JNI_BrowserSideNavigationPolicy_IsBrowserSideNavigationEnabled(
- JNIEnv* env,
- const JavaParamRef<jclass>& clazz) {
- return IsBrowserSideNavigationEnabled();
-}
-
-} // namespace content
diff --git a/chromium/content/common/associated_interface_provider_impl.cc b/chromium/content/common/associated_interface_provider_impl.cc
index d58763218d8..ba5ef4044e0 100644
--- a/chromium/content/common/associated_interface_provider_impl.cc
+++ b/chromium/content/common/associated_interface_provider_impl.cc
@@ -12,10 +12,12 @@ namespace content {
class AssociatedInterfaceProviderImpl::LocalProvider
: public mojom::AssociatedInterfaceProvider {
public:
- explicit LocalProvider(mojom::AssociatedInterfaceProviderAssociatedPtr* proxy)
+ LocalProvider(mojom::AssociatedInterfaceProviderAssociatedPtr* proxy,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner)
: associated_interface_provider_binding_(this) {
associated_interface_provider_binding_.Bind(
- mojo::MakeRequestAssociatedWithDedicatedPipe(proxy));
+ mojo::MakeRequestAssociatedWithDedicatedPipe(proxy),
+ std::move(task_runner));
}
~LocalProvider() override {}
@@ -46,13 +48,16 @@ class AssociatedInterfaceProviderImpl::LocalProvider
};
AssociatedInterfaceProviderImpl::AssociatedInterfaceProviderImpl(
- mojom::AssociatedInterfaceProviderAssociatedPtr proxy)
- : proxy_(std::move(proxy)) {
+ mojom::AssociatedInterfaceProviderAssociatedPtr proxy,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner)
+ : proxy_(std::move(proxy)), task_runner_(std::move(task_runner)) {
DCHECK(proxy_.is_bound());
}
-AssociatedInterfaceProviderImpl::AssociatedInterfaceProviderImpl()
- : local_provider_(std::make_unique<LocalProvider>(&proxy_)) {}
+AssociatedInterfaceProviderImpl::AssociatedInterfaceProviderImpl(
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner)
+ : local_provider_(std::make_unique<LocalProvider>(&proxy_, task_runner)),
+ task_runner_(std::move(task_runner)) {}
AssociatedInterfaceProviderImpl::~AssociatedInterfaceProviderImpl() {}
@@ -69,7 +74,7 @@ void AssociatedInterfaceProviderImpl::OverrideBinderForTesting(
if (!local_provider_) {
DCHECK(proxy_.is_bound());
proxy_.reset();
- local_provider_ = std::make_unique<LocalProvider>(&proxy_);
+ local_provider_ = std::make_unique<LocalProvider>(&proxy_, task_runner_);
}
local_provider_->SetBinderForName(name, binder);
}
diff --git a/chromium/content/common/associated_interface_provider_impl.h b/chromium/content/common/associated_interface_provider_impl.h
index b1fca4422ee..91d196c4c90 100644
--- a/chromium/content/common/associated_interface_provider_impl.h
+++ b/chromium/content/common/associated_interface_provider_impl.h
@@ -5,7 +5,7 @@
#ifndef CONTENT_COMMON_ASSOCIATED_INTERFACE_PROVIDER_IMPL_H_
#define CONTENT_COMMON_ASSOCIATED_INTERFACE_PROVIDER_IMPL_H_
-#include "third_party/WebKit/public/common/associated_interfaces/associated_interface_provider.h"
+#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include <stdint.h>
#include <memory>
@@ -19,12 +19,21 @@ class AssociatedInterfaceProviderImpl
: public blink::AssociatedInterfaceProvider {
public:
// Binds this to a remote mojom::AssociatedInterfaceProvider.
+ //
+ // |task_runner| must belong to the same thread. It will be used to dispatch
+ // all callbacks and connection error notification.
explicit AssociatedInterfaceProviderImpl(
- mojom::AssociatedInterfaceProviderAssociatedPtr proxy);
+ mojom::AssociatedInterfaceProviderAssociatedPtr proxy,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner = nullptr);
+
// Constructs a local provider with no remote interfaces. This is useful in
// conjunction with OverrideBinderForTesting(), in test environments where
// there may not be a remote |mojom::AssociatedInterfaceProvider| available.
- AssociatedInterfaceProviderImpl();
+ //
+ // |task_runner| must belong to the same thread. It will be used to dispatch
+ // all callbacks and connection error notification.
+ explicit AssociatedInterfaceProviderImpl(
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner);
~AssociatedInterfaceProviderImpl() override;
// AssociatedInterfaceProvider:
@@ -41,6 +50,7 @@ class AssociatedInterfaceProviderImpl
mojom::AssociatedInterfaceProviderAssociatedPtr proxy_;
std::unique_ptr<LocalProvider> local_provider_;
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
DISALLOW_COPY_AND_ASSIGN(AssociatedInterfaceProviderImpl);
};
diff --git a/chromium/content/common/associated_interface_registry_impl.h b/chromium/content/common/associated_interface_registry_impl.h
index ae28f1994ed..4ee97c1bec4 100644
--- a/chromium/content/common/associated_interface_registry_impl.h
+++ b/chromium/content/common/associated_interface_registry_impl.h
@@ -11,7 +11,7 @@
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "mojo/public/cpp/bindings/scoped_interface_endpoint_handle.h"
-#include "third_party/WebKit/public/common/associated_interfaces/associated_interface_registry.h"
+#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
namespace content {
diff --git a/chromium/content/common/background_fetch/DEPS b/chromium/content/common/background_fetch/DEPS
index c0c3af0fbea..0cf92f853e8 100644
--- a/chromium/content/common/background_fetch/DEPS
+++ b/chromium/content/common/background_fetch/DEPS
@@ -1,3 +1,3 @@
include_rules = [
- "+third_party/WebKit/public/platform/modules/background_fetch/background_fetch.mojom.h",
+ "+third_party/blink/public/platform/modules/background_fetch/background_fetch.mojom.h",
]
diff --git a/chromium/content/common/background_fetch/background_fetch_struct_traits.h b/chromium/content/common/background_fetch/background_fetch_struct_traits.h
index 22ccecbc9fc..aaf094ed9c2 100644
--- a/chromium/content/common/background_fetch/background_fetch_struct_traits.h
+++ b/chromium/content/common/background_fetch/background_fetch_struct_traits.h
@@ -11,7 +11,7 @@
#include "content/common/background_fetch/background_fetch_types.h"
#include "content/common/content_export.h"
#include "mojo/public/cpp/bindings/struct_traits.h"
-#include "third_party/WebKit/public/platform/modules/background_fetch/background_fetch.mojom.h"
+#include "third_party/blink/public/platform/modules/background_fetch/background_fetch.mojom.h"
namespace content {
namespace mojom {
diff --git a/chromium/content/common/background_fetch/background_fetch_types.typemap b/chromium/content/common/background_fetch/background_fetch_types.typemap
index 9fce85f3b10..57d741b2848 100644
--- a/chromium/content/common/background_fetch/background_fetch_types.typemap
+++ b/chromium/content/common/background_fetch/background_fetch_types.typemap
@@ -2,14 +2,14 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
-mojom = "//third_party/WebKit/public/platform/modules/background_fetch/background_fetch.mojom"
+mojom = "//third_party/blink/public/platform/modules/background_fetch/background_fetch.mojom"
public_headers =
[ "//content/common/background_fetch/background_fetch_types.h" ]
traits_headers =
[ "//content/common/background_fetch/background_fetch_struct_traits.h" ]
deps = [
"//mojo/public/cpp/bindings",
- "//third_party/WebKit/public:blink_headers",
+ "//third_party/blink/public:blink_headers",
]
type_mappings = [
"blink.mojom.BackgroundFetchOptions=content::BackgroundFetchOptions",
diff --git a/chromium/content/common/bluetooth/web_bluetooth_device_id.typemap b/chromium/content/common/bluetooth/web_bluetooth_device_id.typemap
index 7f07b52b538..59ed7ecc31c 100644
--- a/chromium/content/common/bluetooth/web_bluetooth_device_id.typemap
+++ b/chromium/content/common/bluetooth/web_bluetooth_device_id.typemap
@@ -3,7 +3,7 @@
# found in the LICENSE file.
mojom =
- "//third_party/WebKit/public/platform/modules/bluetooth/web_bluetooth.mojom"
+ "//third_party/blink/public/platform/modules/bluetooth/web_bluetooth.mojom"
public_headers = [ "//content/common/bluetooth/web_bluetooth_device_id.h" ]
traits_headers =
[ "//content/common/bluetooth/web_bluetooth_device_id_struct_traits.h" ]
diff --git a/chromium/content/common/bluetooth/web_bluetooth_device_id_struct_traits.h b/chromium/content/common/bluetooth/web_bluetooth_device_id_struct_traits.h
index 08b9f11edbf..1ce512bff0a 100644
--- a/chromium/content/common/bluetooth/web_bluetooth_device_id_struct_traits.h
+++ b/chromium/content/common/bluetooth/web_bluetooth_device_id_struct_traits.h
@@ -8,7 +8,7 @@
#include <string>
#include "content/common/bluetooth/web_bluetooth_device_id.h"
-#include "third_party/WebKit/public/platform/modules/bluetooth/web_bluetooth.mojom.h"
+#include "third_party/blink/public/platform/modules/bluetooth/web_bluetooth.mojom.h"
namespace mojo {
diff --git a/chromium/content/common/browser_plugin/browser_plugin_messages.h b/chromium/content/common/browser_plugin/browser_plugin_messages.h
index 80b3ab8b8a0..87991910cd3 100644
--- a/chromium/content/common/browser_plugin/browser_plugin_messages.h
+++ b/chromium/content/common/browser_plugin/browser_plugin_messages.h
@@ -15,15 +15,16 @@
#include "content/common/content_param_traits.h"
#include "content/common/cursors/webcursor.h"
#include "content/common/edit_command.h"
+#include "content/common/frame_resize_params.h"
#include "content/public/common/drop_data.h"
#include "content/public/common/screen_info.h"
#include "ipc/ipc_channel_handle.h"
#include "ipc/ipc_message_macros.h"
#include "ipc/ipc_message_utils.h"
-#include "third_party/WebKit/public/platform/WebDragOperation.h"
-#include "third_party/WebKit/public/platform/WebFocusType.h"
-#include "third_party/WebKit/public/web/WebDragStatus.h"
-#include "third_party/WebKit/public/web/WebImeTextSpan.h"
+#include "third_party/blink/public/platform/web_drag_operation.h"
+#include "third_party/blink/public/platform/web_focus_type.h"
+#include "third_party/blink/public/web/web_drag_status.h"
+#include "third_party/blink/public/web/web_ime_text_span.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
@@ -155,12 +156,10 @@ IPC_MESSAGE_CONTROL1(BrowserPluginHostMsg_UnlockMouse_ACK,
int /* browser_plugin_instance_id */)
// Sent when plugin's position has changed.
-IPC_MESSAGE_CONTROL5(BrowserPluginHostMsg_UpdateResizeParams,
+IPC_MESSAGE_CONTROL3(BrowserPluginHostMsg_UpdateResizeParams,
int /* browser_plugin_instance_id */,
- gfx::Rect /* frame_rect */,
- content::ScreenInfo /* screen_info */,
- uint64_t /* sequence_number */,
- viz::LocalSurfaceId /* local_surface_id */)
+ viz::LocalSurfaceId /* local_surface_id */,
+ content::FrameResizeParams /* resize_params */)
// -----------------------------------------------------------------------------
// These messages are from the browser process to the embedder.
@@ -194,6 +193,18 @@ IPC_MESSAGE_CONTROL2(BrowserPluginMsg_ResizeDueToAutoResize,
int /* browser_plugin_instance_id */,
uint64_t /* sequence_number */)
+// Requests a viz::LocalSurfaceId to enable auto-resize mode from the parent
+// renderer.
+IPC_MESSAGE_CONTROL3(BrowserPluginMsg_EnableAutoResize,
+ int /* browser_plugin_instance_id */,
+ gfx::Size /* min_size */,
+ gfx::Size /* max_size */)
+
+// Requests a viz::LocalSurfaceId to disable auto-resize-mode from the parent
+// renderer.
+IPC_MESSAGE_CONTROL1(BrowserPluginMsg_DisableAutoResize,
+ int /* browser_plugin_instance_id */)
+
// When the guest starts/stops listening to touch events, it needs to notify the
// plugin in the embedder about it.
IPC_MESSAGE_CONTROL2(BrowserPluginMsg_ShouldAcceptTouchEvents,
diff --git a/chromium/content/common/cache_storage/cache_storage.typemap b/chromium/content/common/cache_storage/cache_storage.typemap
index 85db1bb1fb7..b04b8896324 100644
--- a/chromium/content/common/cache_storage/cache_storage.typemap
+++ b/chromium/content/common/cache_storage/cache_storage.typemap
@@ -2,7 +2,7 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
-mojom = "//third_party/WebKit/public/platform/modules/cache_storage/cache_storage.mojom"
+mojom = "//third_party/blink/public/platform/modules/cache_storage/cache_storage.mojom"
public_headers = [
"//content/common/cache_storage/cache_storage_types.h",
"//content/common/service_worker/service_worker_types.h",
diff --git a/chromium/content/common/cache_storage/cache_storage_messages.h b/chromium/content/common/cache_storage/cache_storage_messages.h
deleted file mode 100644
index f739e4bbd75..00000000000
--- a/chromium/content/common/cache_storage/cache_storage_messages.h
+++ /dev/null
@@ -1,196 +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 CONTENT_COMMON_CACHE_STORAGE_CACHE_STORAGE_MESSAGES_H_
-#define CONTENT_COMMON_CACHE_STORAGE_CACHE_STORAGE_MESSAGES_H_
-
-#include <string>
-#include <vector>
-
-#include "base/strings/string16.h"
-#include "content/common/cache_storage/cache_storage_types.h"
-#include "content/common/service_worker/service_worker_types.h"
-#include "ipc/ipc_message_macros.h"
-#include "ipc/ipc_param_traits.h"
-#include "third_party/WebKit/public/platform/modules/cache_storage/cache_storage.mojom.h"
-#include "url/origin.h"
-
-#undef IPC_MESSAGE_EXPORT
-#define IPC_MESSAGE_EXPORT CONTENT_EXPORT
-
-#define IPC_MESSAGE_START CacheStorageMsgStart
-
-// TODO(jsbell): This depends on traits for content::ServiceWorkerResponse
-// which are defined in service_worker_messages.h - correct this implicit
-// cross-dependency.
-
-IPC_STRUCT_TRAITS_BEGIN(content::CacheStorageCacheQueryParams)
- IPC_STRUCT_TRAITS_MEMBER(ignore_search)
- IPC_STRUCT_TRAITS_MEMBER(ignore_method)
- IPC_STRUCT_TRAITS_MEMBER(ignore_vary)
- IPC_STRUCT_TRAITS_MEMBER(cache_name)
-IPC_STRUCT_TRAITS_END()
-
-IPC_ENUM_TRAITS_MAX_VALUE(content::CacheStorageCacheOperationType,
- content::CACHE_STORAGE_CACHE_OPERATION_TYPE_LAST)
-
-IPC_STRUCT_TRAITS_BEGIN(content::CacheStorageBatchOperation)
- IPC_STRUCT_TRAITS_MEMBER(operation_type)
- IPC_STRUCT_TRAITS_MEMBER(request)
- IPC_STRUCT_TRAITS_MEMBER(response)
- IPC_STRUCT_TRAITS_MEMBER(match_params)
-IPC_STRUCT_TRAITS_END()
-
-IPC_ENUM_TRAITS_MAX_VALUE(blink::mojom::CacheStorageError,
- blink::mojom::CacheStorageError::kLast)
-
-//---------------------------------------------------------------------------
-// Messages sent from the child process to the browser.
-
-// CacheStorage operations in the browser.
-IPC_MESSAGE_CONTROL4(CacheStorageHostMsg_CacheStorageHas,
- int /* thread_id */,
- int /* request_id */,
- url::Origin /* origin */,
- base::string16 /* fetch_store_name */)
-
-IPC_MESSAGE_CONTROL4(CacheStorageHostMsg_CacheStorageOpen,
- int /* thread_id */,
- int /* request_id */,
- url::Origin /* origin */,
- base::string16 /* fetch_store_name */)
-
-IPC_MESSAGE_CONTROL4(CacheStorageHostMsg_CacheStorageDelete,
- int /* thread_id */,
- int /* request_id */,
- url::Origin /* origin */,
- base::string16 /* fetch_store_name */)
-
-IPC_MESSAGE_CONTROL3(CacheStorageHostMsg_CacheStorageKeys,
- int /* thread_id */,
- int /* request_id */,
- url::Origin /* origin */)
-
-IPC_MESSAGE_CONTROL5(CacheStorageHostMsg_CacheStorageMatch,
- int /* thread_id */,
- int /* request_id */,
- url::Origin /* origin */,
- content::ServiceWorkerFetchRequest,
- content::CacheStorageCacheQueryParams)
-
-// Cache operations in the browser.
-IPC_MESSAGE_CONTROL5(CacheStorageHostMsg_CacheMatch,
- int /* thread_id */,
- int /* request_id */,
- int /* cache_id */,
- content::ServiceWorkerFetchRequest,
- content::CacheStorageCacheQueryParams)
-
-IPC_MESSAGE_CONTROL5(CacheStorageHostMsg_CacheMatchAll,
- int /* thread_id */,
- int /* request_id */,
- int /* cache_id */,
- content::ServiceWorkerFetchRequest,
- content::CacheStorageCacheQueryParams)
-
-IPC_MESSAGE_CONTROL5(CacheStorageHostMsg_CacheKeys,
- int /* thread_id */,
- int /* request_id */,
- int /* cache_id */,
- content::ServiceWorkerFetchRequest,
- content::CacheStorageCacheQueryParams)
-
-IPC_MESSAGE_CONTROL4(CacheStorageHostMsg_CacheBatch,
- int /* thread_id */,
- int /* request_id */,
- int /* cache_id */,
- std::vector<content::CacheStorageBatchOperation>)
-
-IPC_MESSAGE_CONTROL1(CacheStorageHostMsg_CacheClosed,
- int /* cache_id */)
-
-IPC_MESSAGE_CONTROL1(CacheStorageHostMsg_BlobDataHandled,
- std::string /* uuid */)
-
-//---------------------------------------------------------------------------
-// Messages sent from the browser to the child process.
-//
-// All such messages must includes thread_id as the first int; it is read off
-// by CacheStorageMessageFilter::GetWorkerThreadIdForMessage to route delivery
-// to the appropriate thread.
-
-// Sent at successful completion of CacheStorage operations.
-IPC_MESSAGE_CONTROL2(CacheStorageMsg_CacheStorageHasSuccess,
- int /* thread_id */,
- int /* request_id */)
-IPC_MESSAGE_CONTROL3(CacheStorageMsg_CacheStorageOpenSuccess,
- int /* thread_id */,
- int /* request_id */,
- int /* fetch_store_id */)
-IPC_MESSAGE_CONTROL2(CacheStorageMsg_CacheStorageDeleteSuccess,
- int /* thread_id */,
- int /* request_id */)
-IPC_MESSAGE_CONTROL3(CacheStorageMsg_CacheStorageKeysSuccess,
- int /* thread_id */,
- int /* request_id */,
- std::vector<base::string16> /* keys */)
-IPC_MESSAGE_CONTROL3(CacheStorageMsg_CacheStorageMatchSuccess,
- int /* thread_id */,
- int /* request_id */,
- content::ServiceWorkerResponse)
-
-// Sent at erroneous completion of CacheStorage operations.
-IPC_MESSAGE_CONTROL3(CacheStorageMsg_CacheStorageHasError,
- int /* thread_id */,
- int /* request_id */,
- blink::mojom::CacheStorageError /* reason */)
-IPC_MESSAGE_CONTROL3(CacheStorageMsg_CacheStorageOpenError,
- int /* thread_id */,
- int /* request_id */,
- blink::mojom::CacheStorageError /* reason */)
-IPC_MESSAGE_CONTROL3(CacheStorageMsg_CacheStorageDeleteError,
- int /* thread_id */,
- int /* request_id */,
- blink::mojom::CacheStorageError /* reason */)
-IPC_MESSAGE_CONTROL3(CacheStorageMsg_CacheStorageMatchError,
- int /* thread_id */,
- int /* request_id */,
- blink::mojom::CacheStorageError)
-
-// Sent at successful completion of Cache operations.
-IPC_MESSAGE_CONTROL3(CacheStorageMsg_CacheMatchSuccess,
- int /* thread_id */,
- int /* request_id */,
- content::ServiceWorkerResponse)
-IPC_MESSAGE_CONTROL3(CacheStorageMsg_CacheMatchAllSuccess,
- int /* thread_id */,
- int /* request_id */,
- std::vector<content::ServiceWorkerResponse>)
-IPC_MESSAGE_CONTROL3(CacheStorageMsg_CacheKeysSuccess,
- int /* thread_id */,
- int /* request_id */,
- std::vector<content::ServiceWorkerFetchRequest>)
-IPC_MESSAGE_CONTROL2(CacheStorageMsg_CacheBatchSuccess,
- int /* thread_id */,
- int /* request_id */)
-
-// Sent at erroneous completion of CacheStorage operations.
-IPC_MESSAGE_CONTROL3(CacheStorageMsg_CacheMatchError,
- int /* thread_id */,
- int /* request_id */,
- blink::mojom::CacheStorageError)
-IPC_MESSAGE_CONTROL3(CacheStorageMsg_CacheMatchAllError,
- int /* thread_id */,
- int /* request_id */,
- blink::mojom::CacheStorageError)
-IPC_MESSAGE_CONTROL3(CacheStorageMsg_CacheKeysError,
- int /* thread_id */,
- int /* request_id */,
- blink::mojom::CacheStorageError)
-IPC_MESSAGE_CONTROL3(CacheStorageMsg_CacheBatchError,
- int /* thread_id */,
- int /* request_id */,
- blink::mojom::CacheStorageError)
-
-#endif // CONTENT_COMMON_CACHE_STORAGE_CACHE_STORAGE_MESSAGES_H_
diff --git a/chromium/content/common/cache_storage/cache_storage_mojom_traits.h b/chromium/content/common/cache_storage/cache_storage_mojom_traits.h
index bf4d98cbc1a..764b68d4b7d 100644
--- a/chromium/content/common/cache_storage/cache_storage_mojom_traits.h
+++ b/chromium/content/common/cache_storage/cache_storage_mojom_traits.h
@@ -15,7 +15,7 @@
#include "content/common/service_worker/service_worker_fetch_response_mojom_traits.h"
#include "content/common/service_worker/service_worker_types.h"
#include "mojo/public/cpp/base/string16_mojom_traits.h"
-#include "third_party/WebKit/public/platform/modules/cache_storage/cache_storage.mojom.h"
+#include "third_party/blink/public/platform/modules/cache_storage/cache_storage.mojom.h"
#include "url/gurl.h"
namespace mojo {
diff --git a/chromium/content/common/child_control.mojom b/chromium/content/common/child_control.mojom
index a73a317a3fe..733c85c3df3 100644
--- a/chromium/content/common/child_control.mojom
+++ b/chromium/content/common/child_control.mojom
@@ -9,5 +9,6 @@ interface ChildControl {
ProcessShutdown();
// Tell the child process to begin or end IPC message logging.
+ [EnableIf=ipc_logging]
SetIPCLoggingEnabled(bool on);
};
diff --git a/chromium/content/common/common_param_traits_unittest.cc b/chromium/content/common/common_param_traits_unittest.cc
index 915ca4240df..71b30f65c4d 100644
--- a/chromium/content/common/common_param_traits_unittest.cc
+++ b/chromium/content/common/common_param_traits_unittest.cc
@@ -11,7 +11,6 @@
#include <utility>
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/values.h"
#include "content/common/resource_messages.h"
#include "content/public/common/content_constants.h"
@@ -208,8 +207,9 @@ TEST(IPCMessageTest, SSLInfo) {
EXPECT_TRUE(IPC::ParamTraits<net::SSLInfo>::Read(&msg, &iter, &out));
// Now verify they're equal.
- ASSERT_TRUE(in.cert->Equals(out.cert.get()));
- ASSERT_TRUE(in.unverified_cert->Equals(out.unverified_cert.get()));
+ ASSERT_TRUE(in.cert->EqualsIncludingChain(out.cert.get()));
+ ASSERT_TRUE(
+ in.unverified_cert->EqualsIncludingChain(out.unverified_cert.get()));
ASSERT_EQ(in.security_bits, out.security_bits);
ASSERT_EQ(in.key_exchange_group, out.key_exchange_group);
ASSERT_EQ(in.connection_status, out.connection_status);
diff --git a/chromium/content/common/content_constants_internal.cc b/chromium/content/common/content_constants_internal.cc
index d592169a566..5cd58371095 100644
--- a/chromium/content/common/content_constants_internal.cc
+++ b/chromium/content/common/content_constants_internal.cc
@@ -31,4 +31,6 @@ const int kTraceEventGpuProcessSortIndex = -1;
const int kTraceEventRendererMainThreadSortIndex = -1;
+const char kDoNotTrackHeader[] = "DNT";
+
} // namespace content
diff --git a/chromium/content/common/content_constants_internal.h b/chromium/content/common/content_constants_internal.h
index ea7461ae5fc..efd36e67724 100644
--- a/chromium/content/common/content_constants_internal.h
+++ b/chromium/content/common/content_constants_internal.h
@@ -36,6 +36,9 @@ CONTENT_EXPORT extern const int kTraceEventGpuProcessSortIndex;
// Constants used to organize content threads in about:tracing.
CONTENT_EXPORT extern const int kTraceEventRendererMainThreadSortIndex;
+// HTTP header set in requests to indicate they should be marked DoNotTrack.
+extern const char kDoNotTrackHeader[];
+
} // namespace content
#endif // CONTENT_COMMON_CONTENT_CONSTANTS_INTERNAL_H_
diff --git a/chromium/content/common/content_ipc_logging.cc b/chromium/content/common/content_ipc_logging.cc
index 6c5f4c92d17..9d2a27de33e 100644
--- a/chromium/content/common/content_ipc_logging.cc
+++ b/chromium/content/common/content_ipc_logging.cc
@@ -4,7 +4,7 @@
#include <stdint.h>
-#include "ipc/ipc_features.h"
+#include "ipc/ipc_buildflags.h"
#if BUILDFLAG(IPC_MESSAGE_LOG_ENABLED)
#define IPC_MESSAGE_MACROS_LOG_ENABLED
diff --git a/chromium/content/common/content_message_generator.h b/chromium/content/common/content_message_generator.h
index 604f1a987df..ab5609447eb 100644
--- a/chromium/content/common/content_message_generator.h
+++ b/chromium/content/common/content_message_generator.h
@@ -16,11 +16,6 @@
#error \
"Failed to include content/common/browser_plugin/browser_plugin_messages.h"
#endif
-#undef CONTENT_COMMON_CACHE_STORAGE_CACHE_STORAGE_MESSAGES_H_
-#include "content/common/cache_storage/cache_storage_messages.h"
-#ifndef CONTENT_COMMON_CACHE_STORAGE_CACHE_STORAGE_MESSAGES_H_
-#error "Failed to include content/common/cache_storage/cache_storage_messages.h"
-#endif
#undef CONTENT_COMMON_DOM_STORAGE_DOM_STORAGE_MESSAGES_H_
#include "content/common/dom_storage/dom_storage_messages.h"
#ifndef CONTENT_COMMON_DOM_STORAGE_DOM_STORAGE_MESSAGES_H_
@@ -67,12 +62,6 @@
#ifndef CONTENT_COMMON_MEDIA_MEDIA_PLAYER_DELEGATE_MESSAGES_H_
#error "Failed to include content/common/media/media_player_delegate_messages.h"
#endif
-#undef CONTENT_COMMON_MEDIA_MEDIA_STREAM_TRACK_METRICS_HOST_MESSAGES_H_
-#include "content/common/media/media_stream_track_metrics_host_messages.h"
-#ifndef CONTENT_COMMON_MEDIA_MEDIA_STREAM_TRACK_METRICS_HOST_MESSAGES_H_
-#error \
- "Failed to include content/common/media/media_stream_track_metrics_host_messages.h"
-#endif
#undef CONTENT_COMMON_MEDIA_MIDI_MESSAGES_H_
#include "content/common/media/midi_messages.h"
#ifndef CONTENT_COMMON_MEDIA_MIDI_MESSAGES_H_
@@ -99,12 +88,6 @@
#ifndef CONTENT_COMMON_RESOURCE_MESSAGES_H_
#error "Failed to include content/common/resource_messages.h"
#endif
-#undef CONTENT_COMMON_SERVICE_WORKER_EMBEDDED_WORKER_MESSAGES_H_
-#include "content/common/service_worker/embedded_worker_messages.h"
-#ifndef CONTENT_COMMON_SERVICE_WORKER_EMBEDDED_WORKER_MESSAGES_H_
-#error \
- "Failed to include content/common/service_worker/embedded_worker_messages.h"
-#endif
#undef CONTENT_COMMON_SERVICE_WORKER_SERVICE_WORKER_MESSAGES_H_
#include "content/common/service_worker/service_worker_messages.h"
#ifndef CONTENT_COMMON_SERVICE_WORKER_SERVICE_WORKER_MESSAGES_H_
@@ -126,7 +109,7 @@
#ifndef CONTENT_COMMON_VIEW_MESSAGES_H_
#error "Failed to include content/common/view_messages.h"
#endif
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#undef CONTENT_COMMON_SYNC_COMPOSITOR_MESSAGES_H_
#include "content/common/input/sync_compositor_messages.h"
diff --git a/chromium/content/common/content_param_traits.cc b/chromium/content/common/content_param_traits.cc
index 038d4fc32ac..be32e05f410 100644
--- a/chromium/content/common/content_param_traits.cc
+++ b/chromium/content/common/content_param_traits.cc
@@ -11,9 +11,9 @@
#include "ipc/ipc_mojo_message_helper.h"
#include "ipc/ipc_mojo_param_traits.h"
#include "net/base/ip_endpoint.h"
-#include "third_party/WebKit/public/common/message_port/message_port_channel.h"
-#include "third_party/WebKit/public/common/message_port/transferable_message.h"
-#include "third_party/WebKit/public/mojom/message_port/message_port.mojom.h"
+#include "third_party/blink/public/common/message_port/message_port_channel.h"
+#include "third_party/blink/public/common/message_port/transferable_message.h"
+#include "third_party/blink/public/mojom/message_port/message_port.mojom.h"
#include "ui/accessibility/ax_modes.h"
#include "ui/base/ui_base_features.h"
#include "ui/events/blink/web_input_event_traits.h"
@@ -198,7 +198,7 @@ struct ParamTraits<blink::mojom::SerializedBlobPtr> {
void ParamTraits<scoped_refptr<base::RefCountedData<
blink::TransferableMessage>>>::Write(base::Pickle* m, const param_type& p) {
m->WriteData(reinterpret_cast<const char*>(p->data.encoded_message.data()),
- p->data.encoded_message.length());
+ p->data.encoded_message.size());
WriteParam(m, p->data.blobs);
WriteParam(m, p->data.stack_trace_id);
WriteParam(m, p->data.stack_trace_debugger_id_first);
diff --git a/chromium/content/common/content_param_traits.h b/chromium/content/common/content_param_traits.h
index 0c7396db53e..ffe7fc9edc1 100644
--- a/chromium/content/common/content_param_traits.h
+++ b/chromium/content/common/content_param_traits.h
@@ -18,7 +18,7 @@
#include "content/common/cursors/webcursor.h"
#include "ipc/ipc_mojo_param_traits.h"
#include "storage/common/blob_storage/blob_handle.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/accessibility/ax_modes.h"
namespace blink {
diff --git a/chromium/content/common/content_param_traits_macros.h b/chromium/content/common/content_param_traits_macros.h
index 6ccdc68d8ec..9dd58cf6618 100644
--- a/chromium/content/common/content_param_traits_macros.h
+++ b/chromium/content/common/content_param_traits_macros.h
@@ -16,10 +16,10 @@
#include "content/public/common/request_context_type.h"
#include "content/public/common/resource_type.h"
#include "ipc/ipc_message_macros.h"
-#include "third_party/WebKit/public/mojom/page/page_visibility_state.mojom.h"
-#include "third_party/WebKit/public/platform/WebContentSecurityPolicy.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
-#include "third_party/WebKit/public/web/WebImeTextSpan.h"
+#include "third_party/blink/public/mojom/page/page_visibility_state.mojom.h"
+#include "third_party/blink/public/platform/web_content_security_policy.h"
+#include "third_party/blink/public/platform/web_input_event.h"
+#include "third_party/blink/public/web/web_ime_text_span.h"
#include "ui/gfx/gpu_memory_buffer.h"
#include "ui/gfx/ipc/geometry/gfx_param_traits.h"
@@ -42,16 +42,18 @@ IPC_ENUM_TRAITS_MIN_MAX_VALUE(blink::WebInputEvent::Type,
blink::WebInputEvent::kTypeFirst,
blink::WebInputEvent::kTypeLast)
IPC_ENUM_TRAITS_MAX_VALUE(blink::mojom::PageVisibilityState,
- blink::mojom::PageVisibilityState::kLast)
+ blink::mojom::PageVisibilityState::kMaxValue)
IPC_ENUM_TRAITS_MAX_VALUE(blink::WebImeTextSpan::Type,
blink::WebImeTextSpan::Type::kMisspellingSuggestion)
+IPC_ENUM_TRAITS_MAX_VALUE(ui::mojom::ImeTextSpanThickness,
+ ui::mojom::ImeTextSpanThickness::kThick)
IPC_STRUCT_TRAITS_BEGIN(blink::WebImeTextSpan)
IPC_STRUCT_TRAITS_MEMBER(type)
IPC_STRUCT_TRAITS_MEMBER(start_offset)
IPC_STRUCT_TRAITS_MEMBER(end_offset)
IPC_STRUCT_TRAITS_MEMBER(underline_color)
- IPC_STRUCT_TRAITS_MEMBER(thick)
+ IPC_STRUCT_TRAITS_MEMBER(thickness)
IPC_STRUCT_TRAITS_MEMBER(background_color)
IPC_STRUCT_TRAITS_MEMBER(suggestion_highlight_color)
IPC_STRUCT_TRAITS_MEMBER(suggestions)
diff --git a/chromium/content/common/content_security_policy/csp_source_list_unittest.cc b/chromium/content/common/content_security_policy/csp_source_list_unittest.cc
index 575eed44eb3..2e0838d298c 100644
--- a/chromium/content/common/content_security_policy/csp_source_list_unittest.cc
+++ b/chromium/content/common/content_security_policy/csp_source_list_unittest.cc
@@ -94,10 +94,10 @@ TEST(CSPSourceList, AllowSelfWithUnspecifiedPort) {
false, // allow_star:
std::vector<CSPSource>()); // source_list
- EXPECT_TRUE(Allow(
- source_list,
- GURL("chrome://print/pdf_preview.html?chrome://print/1/0/print.pdf"),
- &context));
+ EXPECT_TRUE(
+ Allow(source_list,
+ GURL("chrome://print/pdf/index.html?chrome://print/1/0/print.pdf"),
+ &context));
}
TEST(CSPSourceList, AllowNone) {
diff --git a/chromium/content/common/content_security_policy_header.h b/chromium/content/common/content_security_policy_header.h
index e4b65d38c88..0184bda4821 100644
--- a/chromium/content/common/content_security_policy_header.h
+++ b/chromium/content/common/content_security_policy_header.h
@@ -8,7 +8,7 @@
#include <string>
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebContentSecurityPolicy.h"
+#include "third_party/blink/public/platform/web_content_security_policy.h"
namespace content {
diff --git a/chromium/content/common/cross_site_document_classifier.cc b/chromium/content/common/cross_site_document_classifier.cc
deleted file mode 100644
index bcb00039346..00000000000
--- a/chromium/content/common/cross_site_document_classifier.cc
+++ /dev/null
@@ -1,369 +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 "content/common/cross_site_document_classifier.h"
-
-#include <stddef.h>
-#include <string>
-
-#include "base/command_line.h"
-#include "base/lazy_instance.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/metrics/histogram_macros.h"
-#include "base/strings/string_piece.h"
-#include "base/strings/string_util.h"
-#include "content/public/common/content_switches.h"
-#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
-#include "net/http/http_response_headers.h"
-#include "services/network/public/cpp/resource_response_info.h"
-
-using base::StringPiece;
-
-namespace content {
-
-namespace {
-
-// MIME types
-const char kTextHtml[] = "text/html";
-const char kTextXml[] = "text/xml";
-const char kAppXml[] = "application/xml";
-const char kAppJson[] = "application/json";
-const char kImageSvg[] = "image/svg+xml";
-const char kTextJson[] = "text/json";
-const char kTextXjson[] = "text/x-json";
-const char kTextPlain[] = "text/plain";
-
-// MIME type suffixes
-const char kJsonSuffix[] = "+json";
-const char kXmlSuffix[] = "+xml";
-
-void AdvancePastWhitespace(StringPiece* data) {
- size_t offset = data->find_first_not_of(" \t\r\n");
- if (offset == base::StringPiece::npos) {
- // |data| was entirely whitespace.
- data->clear();
- } else {
- data->remove_prefix(offset);
- }
-}
-
-// Returns kYes if |data| starts with one of the string patterns in
-// |signatures|, kMaybe if |data| is a prefix of one of the patterns in
-// |signatures|, and kNo otherwise.
-//
-// When kYes is returned, the matching prefix is erased from |data|.
-CrossSiteDocumentClassifier::Result MatchesSignature(
- StringPiece* data,
- const StringPiece signatures[],
- size_t arr_size,
- base::CompareCase compare_case) {
- for (size_t i = 0; i < arr_size; ++i) {
- if (signatures[i].length() <= data->length()) {
- if (base::StartsWith(*data, signatures[i], compare_case)) {
- // When |signatures[i]| is a prefix of |data|, it constitutes a match.
- // Strip the matching characters, and return.
- data->remove_prefix(signatures[i].length());
- return CrossSiteDocumentClassifier::kYes;
- }
- } else {
- if (base::StartsWith(signatures[i], *data, compare_case)) {
- // When |data| is a prefix of |signatures[i]|, that means that
- // subsequent bytes in the stream could cause a match to occur.
- return CrossSiteDocumentClassifier::kMaybe;
- }
- }
- }
- return CrossSiteDocumentClassifier::kNo;
-}
-
-// Returns true if |mime_type == prefix| or if |mime_type| starts with
-// |prefix + '+'|. Returns false otherwise.
-//
-// For example:
-// - MatchesMimeTypePrefix("application/json", "application/json") -> true
-// - MatchesMimeTypePrefix("application/json+foo", "application/json") -> true
-// - MatchesMimeTypePrefix("application/jsonp", "application/json") -> false
-// - MatchesMimeTypePrefix("application/foo", "application/json") -> false
-bool MatchesMimeTypePrefix(base::StringPiece mime_type,
- base::StringPiece prefix) {
- constexpr auto kCaseInsensitive = base::CompareCase::INSENSITIVE_ASCII;
- if (!base::StartsWith(mime_type, prefix, kCaseInsensitive))
- return false;
- DCHECK_GE(mime_type.length(), prefix.length());
-
- if (mime_type.length() == prefix.length()) {
- // Given StartsWith results above, the above condition is our O(1) check if
- // |base::LowerCaseEqualsASCII(mime_type, prefix)|.
- DCHECK(base::LowerCaseEqualsASCII(mime_type, prefix));
- return true;
- }
-
- if (mime_type[prefix.length()] == '+') {
- // Given StartsWith results above, the above condition is our O(1) check if
- // |base::StartsWith(mime_type, prefix + '+', kCaseInsensitive)|.
- DCHECK(base::StartsWith(mime_type, prefix.as_string() + '+',
- kCaseInsensitive));
- return true;
- }
-
- return false;
-}
-
-} // namespace
-
-CrossSiteDocumentMimeType CrossSiteDocumentClassifier::GetCanonicalMimeType(
- base::StringPiece mime_type) {
- // Checking for image/svg+xml early ensures that it won't get classified as
- // CROSS_SITE_DOCUMENT_MIME_TYPE_XML by the presence of the "+xml" suffix.
- if (base::LowerCaseEqualsASCII(mime_type, kImageSvg))
- return CROSS_SITE_DOCUMENT_MIME_TYPE_OTHERS;
-
- if (base::LowerCaseEqualsASCII(mime_type, kTextHtml))
- return CROSS_SITE_DOCUMENT_MIME_TYPE_HTML;
-
- if (base::LowerCaseEqualsASCII(mime_type, kTextPlain))
- return CROSS_SITE_DOCUMENT_MIME_TYPE_PLAIN;
-
- // StartsWith rather than LowerCaseEqualsASCII is used to account both for
- // mime types similar to 1) application/json and to 2)
- // application/json+protobuf.
- constexpr auto kCaseInsensitive = base::CompareCase::INSENSITIVE_ASCII;
- if (MatchesMimeTypePrefix(mime_type, kAppJson) ||
- MatchesMimeTypePrefix(mime_type, kTextJson) ||
- MatchesMimeTypePrefix(mime_type, kTextXjson) ||
- base::EndsWith(mime_type, kJsonSuffix, kCaseInsensitive)) {
- return CROSS_SITE_DOCUMENT_MIME_TYPE_JSON;
- }
-
- if (MatchesMimeTypePrefix(mime_type, kAppXml) ||
- MatchesMimeTypePrefix(mime_type, kTextXml) ||
- base::EndsWith(mime_type, kXmlSuffix, kCaseInsensitive)) {
- return CROSS_SITE_DOCUMENT_MIME_TYPE_XML;
- }
-
- return CROSS_SITE_DOCUMENT_MIME_TYPE_OTHERS;
-}
-
-bool CrossSiteDocumentClassifier::IsBlockableScheme(const GURL& url) {
- // We exclude ftp:// from here. FTP doesn't provide a Content-Type
- // header which our policy depends on, so we cannot protect any
- // document from FTP servers.
- return url.SchemeIs(url::kHttpScheme) || url.SchemeIs(url::kHttpsScheme);
-}
-
-// We don't use Webkit's existing CORS policy implementation since
-// their policy works in terms of origins, not sites. For example,
-// when frame is sub.a.com and it is not allowed to access a document
-// with sub1.a.com. But under Site Isolation, it's allowed.
-bool CrossSiteDocumentClassifier::IsValidCorsHeaderSet(
- const url::Origin& frame_origin,
- const std::string& access_control_origin) {
- // Many websites are sending back "\"*\"" instead of "*". This is
- // non-standard practice, and not supported by Chrome. Refer to
- // CrossOriginAccessControl::passesAccessControlCheck().
-
- // Note that "null" offers no more protection than "*" because it matches any
- // unique origin, such as data URLs. Any origin can thus access it, so don't
- // bother trying to block this case.
-
- // TODO(dsjang): * is not allowed for the response from a request
- // with cookies. This allows for more than what the renderer will
- // eventually be able to receive, so we won't see illegal cross-site
- // documents allowed by this. We have to find a way to see if this
- // response is from a cookie-tagged request or not in the future.
- if (access_control_origin == "*" || access_control_origin == "null")
- return true;
-
- return frame_origin.IsSameOriginWith(
- url::Origin::Create(GURL(access_control_origin)));
-}
-
-// This function is a slight modification of |net::SniffForHTML|.
-CrossSiteDocumentClassifier::Result CrossSiteDocumentClassifier::SniffForHTML(
- StringPiece data) {
- // The content sniffers used by Chrome and Firefox are using "<!--" as one of
- // the HTML signatures, but it also appears in valid JavaScript, considered as
- // well-formed JS by the browser. Since we do not want to block any JS, we
- // exclude it from our HTML signatures. This can weaken our document block
- // policy, but we can break less websites.
- //
- // Note that <body> and <br> are not included below, since <b is a prefix of
- // them.
- //
- // TODO(dsjang): parameterize |net::SniffForHTML| with an option that decides
- // whether to include <!-- or not, so that we can remove this function.
- // TODO(dsjang): Once CrossSiteDocumentClassifier is moved into the browser
- // process, we should do single-thread checking here for the static
- // initializer.
- static const StringPiece kHtmlSignatures[] = {
- StringPiece("<!doctype html"), // HTML5 spec
- StringPiece("<script"), // HTML5 spec, Mozilla
- StringPiece("<html"), // HTML5 spec, Mozilla
- StringPiece("<head"), // HTML5 spec, Mozilla
- StringPiece("<iframe"), // Mozilla
- StringPiece("<h1"), // Mozilla
- StringPiece("<div"), // Mozilla
- StringPiece("<font"), // Mozilla
- StringPiece("<table"), // Mozilla
- StringPiece("<a"), // Mozilla
- StringPiece("<style"), // Mozilla
- StringPiece("<title"), // Mozilla
- StringPiece("<b"), // Mozilla (note: subsumes <body>, <br>)
- StringPiece("<p") // Mozilla
- };
-
- while (data.length() > 0) {
- AdvancePastWhitespace(&data);
-
- Result signature_match =
- MatchesSignature(&data, kHtmlSignatures, arraysize(kHtmlSignatures),
- base::CompareCase::INSENSITIVE_ASCII);
- if (signature_match != kNo)
- return signature_match;
-
- // "<!--" (the HTML comment syntax) is a special case, since it's valid JS
- // as well. Skip over them.
- static const StringPiece kBeginCommentSignature[] = {"<!--"};
- Result comment_match = MatchesSignature(&data, kBeginCommentSignature,
- arraysize(kBeginCommentSignature),
- base::CompareCase::SENSITIVE);
- if (comment_match != kYes)
- return comment_match;
-
- // Look for an end comment.
- static const StringPiece kEndComment = "-->";
- size_t comment_end = data.find(kEndComment);
- if (comment_end == base::StringPiece::npos)
- return kMaybe; // Hit end of data with open comment.
- data.remove_prefix(comment_end + kEndComment.length());
- }
-
- // All of |data| was consumed, without a clear determination.
- return kMaybe;
-}
-
-CrossSiteDocumentClassifier::Result CrossSiteDocumentClassifier::SniffForXML(
- base::StringPiece data) {
- // TODO(dsjang): Once CrossSiteDocumentClassifier is moved into the browser
- // process, we should do single-thread checking here for the static
- // initializer.
- AdvancePastWhitespace(&data);
- static const StringPiece kXmlSignatures[] = {StringPiece("<?xml")};
- return MatchesSignature(&data, kXmlSignatures, arraysize(kXmlSignatures),
- base::CompareCase::SENSITIVE);
-}
-
-CrossSiteDocumentClassifier::Result CrossSiteDocumentClassifier::SniffForJSON(
- base::StringPiece data) {
- // Currently this function looks for an opening brace ('{'), followed by a
- // double-quoted string literal, followed by a colon. Importantly, such a
- // sequence is a Javascript syntax error: although the JSON object syntax is
- // exactly Javascript's object-initializer syntax, a Javascript object-
- // initializer expression is not valid as a standalone Javascript statement.
- //
- // TODO(nick): We have to come up with a better way to sniff JSON. The
- // following are known limitations of this function:
- // https://crbug.com/795470/ Support non-dictionary values (e.g. lists)
- enum {
- kStartState,
- kLeftBraceState,
- kLeftQuoteState,
- kEscapeState,
- kRightQuoteState,
- } state = kStartState;
-
- for (size_t i = 0; i < data.length(); ++i) {
- const char c = data[i];
- if (state != kLeftQuoteState && state != kEscapeState) {
- // Whitespace is ignored (outside of string literals)
- if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
- continue;
- } else {
- // Inside string literals, control characters should result in rejection.
- if ((c >= 0 && c < 32) || c == 127)
- return kNo;
- }
-
- switch (state) {
- case kStartState:
- if (c == '{')
- state = kLeftBraceState;
- else
- return kNo;
- break;
- case kLeftBraceState:
- if (c == '"')
- state = kLeftQuoteState;
- else
- return kNo;
- break;
- case kLeftQuoteState:
- if (c == '"')
- state = kRightQuoteState;
- else if (c == '\\')
- state = kEscapeState;
- break;
- case kEscapeState:
- // Simplification: don't bother rejecting hex escapes.
- state = kLeftQuoteState;
- break;
- case kRightQuoteState:
- if (c == ':')
- return kYes;
- else
- return kNo;
- break;
- }
- }
- return kMaybe;
-}
-
-CrossSiteDocumentClassifier::Result
-CrossSiteDocumentClassifier::SniffForFetchOnlyResource(base::StringPiece data) {
- // kScriptBreakingPrefixes contains prefixes that are conventionally used to
- // prevent a JSON response from becoming a valid Javascript program (an attack
- // vector known as XSSI). The presence of such a prefix is a strong signal
- // that the resource is meant to be consumed only by the fetch API or
- // XMLHttpRequest, and is meant to be protected from use in non-CORS, cross-
- // origin contexts like <script>, <img>, etc.
- //
- // These prefixes work either by inducing a syntax error, or inducing an
- // infinite loop. In either case, the prefix must create a guarantee that no
- // matter what bytes follow it, the entire response would be worthless to
- // execute as a <script>.
- static const StringPiece kScriptBreakingPrefixes[] = {
- // Parser breaker prefix.
- //
- // Built into angular.js (followed by a comma and a newline):
- // https://docs.angularjs.org/api/ng/service/$http
- //
- // Built into the Java Spring framework (followed by a comma and a space):
- // https://goo.gl/xP7FWn
- //
- // Observed on google.com (without a comma, followed by a newline).
- StringPiece(")]}'"),
-
- // Apache struts: https://struts.apache.org/plugins/json/#prefix
- StringPiece("{}&&"),
-
- // Spring framework (historically): https://goo.gl/JYPFAv
- StringPiece("{} &&"),
-
- // Infinite loops.
- StringPiece("for(;;);"), // observed on facebook.com
- StringPiece("while(1);"), StringPiece("for (;;);"),
- StringPiece("while (1);"),
- };
- Result has_parser_breaker = MatchesSignature(
- &data, kScriptBreakingPrefixes, arraysize(kScriptBreakingPrefixes),
- base::CompareCase::SENSITIVE);
- if (has_parser_breaker != kNo)
- return has_parser_breaker;
-
- // A non-empty JSON object also effectively introduces a JS syntax error.
- return SniffForJSON(data);
-}
-
-} // namespace content
diff --git a/chromium/content/common/cross_site_document_classifier.h b/chromium/content/common/cross_site_document_classifier.h
deleted file mode 100644
index b86769a8bca..00000000000
--- a/chromium/content/common/cross_site_document_classifier.h
+++ /dev/null
@@ -1,87 +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 CONTENT_COMMON_CROSS_SITE_DOCUMENT_CLASSIFIER_H_
-#define CONTENT_COMMON_CROSS_SITE_DOCUMENT_CLASSIFIER_H_
-
-#include <string>
-
-#include "base/macros.h"
-#include "base/strings/string_piece_forward.h"
-#include "content/common/content_export.h"
-#include "url/gurl.h"
-#include "url/origin.h"
-
-namespace content {
-
-// CrossSiteDocumentClassifier implements the cross-site document blocking
-// policy (XSDP) for Site Isolation. XSDP will monitor network responses to a
-// renderer and block illegal responses so that a compromised renderer cannot
-// steal private information from other sites.
-
-enum CrossSiteDocumentMimeType {
- // Note that these values are used in histograms, and must not change.
- CROSS_SITE_DOCUMENT_MIME_TYPE_HTML = 0,
- CROSS_SITE_DOCUMENT_MIME_TYPE_XML = 1,
- CROSS_SITE_DOCUMENT_MIME_TYPE_JSON = 2,
- CROSS_SITE_DOCUMENT_MIME_TYPE_PLAIN = 3,
- CROSS_SITE_DOCUMENT_MIME_TYPE_OTHERS = 4,
- CROSS_SITE_DOCUMENT_MIME_TYPE_MAX,
-};
-
-class CONTENT_EXPORT CrossSiteDocumentClassifier {
- public:
- // Three conclusions are possible from sniffing a byte sequence:
- // - No: meaning that the data definitively doesn't match the indicated type.
- // - Yes: meaning that the data definitive does match the indicated type.
- // - Maybe: meaning that if more bytes are appended to the stream, it's
- // possible to get a Yes result. For example, if we are sniffing for a tag
- // like "<html", a kMaybe result would occur if the data contains just
- // "<ht".
- enum Result {
- kNo,
- kMaybe,
- kYes,
- };
-
- // Returns the representative mime type enum value of the mime type of
- // response. For example, this returns the same value for all text/xml mime
- // type families such as application/xml, application/rss+xml.
- static CrossSiteDocumentMimeType GetCanonicalMimeType(
- base::StringPiece mime_type);
-
- // Returns whether this scheme is a target of cross-site document
- // policy(XSDP). This returns true only for http://* and https://* urls.
- static bool IsBlockableScheme(const GURL& frame_origin);
-
- // Returns whether there's a valid CORS header for frame_origin. This is
- // simliar to CrossOriginAccessControl::passesAccessControlCheck(), but we use
- // sites as our security domain, not origins.
- // TODO(dsjang): this must be improved to be more accurate to the actual CORS
- // specification. For now, this works conservatively, allowing XSDs that are
- // not allowed by actual CORS rules by ignoring 1) credentials and 2)
- // methods. Preflight requests don't matter here since they are not used to
- // decide whether to block a document or not on the client side.
- static bool IsValidCorsHeaderSet(const url::Origin& frame_origin,
- const std::string& access_control_origin);
-
- static Result SniffForHTML(base::StringPiece data);
- static Result SniffForXML(base::StringPiece data);
- static Result SniffForJSON(base::StringPiece data);
-
- // Sniff for patterns that indicate |data| only ought to be consumed by XHR()
- // or fetch(). This detects Javascript parser-breaker and particular JS
- // infinite-loop patterns, which are used conventionally as a defense against
- // JSON data exfiltration by means of a <script> tag.
- static Result SniffForFetchOnlyResource(base::StringPiece data);
-
- private:
- CrossSiteDocumentClassifier(); // Not instantiable.
-
- DISALLOW_COPY_AND_ASSIGN(CrossSiteDocumentClassifier);
-};
-
-} // namespace content
-
-#endif // CONTENT_COMMON_CROSS_SITE_DOCUMENT_CLASSIFIER_H_
diff --git a/chromium/content/common/cross_site_document_classifier_unittest.cc b/chromium/content/common/cross_site_document_classifier_unittest.cc
deleted file mode 100644
index 290614b1da5..00000000000
--- a/chromium/content/common/cross_site_document_classifier_unittest.cc
+++ /dev/null
@@ -1,216 +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 <utility>
-#include <vector>
-
-#include "base/strings/string_piece.h"
-#include "content/common/cross_site_document_classifier.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-using base::StringPiece;
-using Result = content::CrossSiteDocumentClassifier::Result;
-
-namespace content {
-
-TEST(CrossSiteDocumentClassifierTest, IsBlockableScheme) {
- GURL data_url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA==");
- GURL ftp_url("ftp://google.com");
- GURL mailto_url("mailto:google@google.com");
- GURL about_url("about:chrome");
- GURL http_url("http://google.com");
- GURL https_url("https://google.com");
-
- EXPECT_FALSE(CrossSiteDocumentClassifier::IsBlockableScheme(data_url));
- EXPECT_FALSE(CrossSiteDocumentClassifier::IsBlockableScheme(ftp_url));
- EXPECT_FALSE(CrossSiteDocumentClassifier::IsBlockableScheme(mailto_url));
- EXPECT_FALSE(CrossSiteDocumentClassifier::IsBlockableScheme(about_url));
- EXPECT_TRUE(CrossSiteDocumentClassifier::IsBlockableScheme(http_url));
- EXPECT_TRUE(CrossSiteDocumentClassifier::IsBlockableScheme(https_url));
-}
-
-TEST(CrossSiteDocumentClassifierTest, IsValidCorsHeaderSet) {
- url::Origin frame_origin = url::Origin::Create(GURL("http://www.google.com"));
-
- EXPECT_TRUE(
- CrossSiteDocumentClassifier::IsValidCorsHeaderSet(frame_origin, "*"));
- EXPECT_FALSE(
- CrossSiteDocumentClassifier::IsValidCorsHeaderSet(frame_origin, "\"*\""));
- EXPECT_FALSE(CrossSiteDocumentClassifier::IsValidCorsHeaderSet(
- frame_origin, "http://mail.google.com"));
- EXPECT_TRUE(CrossSiteDocumentClassifier::IsValidCorsHeaderSet(
- frame_origin, "http://www.google.com"));
- EXPECT_FALSE(CrossSiteDocumentClassifier::IsValidCorsHeaderSet(
- frame_origin, "https://www.google.com"));
- EXPECT_FALSE(CrossSiteDocumentClassifier::IsValidCorsHeaderSet(
- frame_origin, "http://yahoo.com"));
- EXPECT_FALSE(CrossSiteDocumentClassifier::IsValidCorsHeaderSet(
- frame_origin, "www.google.com"));
-}
-
-TEST(CrossSiteDocumentClassifierTest, SniffForHTML) {
- StringPiece html_data(" \t\r\n <HtMladfokadfkado");
- StringPiece comment_html_data(" <!-- this is comment --> <html><body>");
- StringPiece two_comments_html_data(
- "<!-- this is comment -->\n<!-- this is comment --><html><body>");
- StringPiece commented_out_html_tag_data("<!-- <html> <?xml> \n<html>--><b");
- StringPiece mixed_comments_html_data(
- "<!-- this is comment <!-- --> <script></script>");
- StringPiece non_html_data(" var name=window.location;\nadfadf");
- StringPiece comment_js_data(
- " <!-- this is comment\n document.write(1);\n// -->window.open()");
- StringPiece empty_data("");
-
- EXPECT_EQ(Result::kYes, CrossSiteDocumentClassifier::SniffForHTML(html_data));
- EXPECT_EQ(Result::kYes,
- CrossSiteDocumentClassifier::SniffForHTML(comment_html_data));
- EXPECT_EQ(Result::kYes,
- CrossSiteDocumentClassifier::SniffForHTML(two_comments_html_data));
- EXPECT_EQ(Result::kYes, CrossSiteDocumentClassifier::SniffForHTML(
- commented_out_html_tag_data));
- EXPECT_EQ(Result::kYes, CrossSiteDocumentClassifier::SniffForHTML(
- mixed_comments_html_data));
- EXPECT_EQ(Result::kNo,
- CrossSiteDocumentClassifier::SniffForHTML(non_html_data));
- EXPECT_EQ(Result::kNo,
- CrossSiteDocumentClassifier::SniffForHTML(comment_js_data));
-
- // Prefixes of |commented_out_html_tag_data| should be indeterminate.
- StringPiece almost_html = commented_out_html_tag_data;
- while (!almost_html.empty()) {
- almost_html.remove_suffix(1);
- EXPECT_EQ(Result::kMaybe,
- CrossSiteDocumentClassifier::SniffForHTML(almost_html))
- << almost_html;
- }
-}
-
-TEST(CrossSiteDocumentClassifierTest, SniffForXML) {
- StringPiece xml_data(" \t \r \n <?xml version=\"1.0\"?>\n <catalog");
- StringPiece non_xml_data(" var name=window.location;\nadfadf");
- StringPiece empty_data("");
-
- EXPECT_EQ(Result::kYes, CrossSiteDocumentClassifier::SniffForXML(xml_data));
- EXPECT_EQ(Result::kNo,
- CrossSiteDocumentClassifier::SniffForXML(non_xml_data));
-
- // Empty string should be indeterminate.
- EXPECT_EQ(Result::kMaybe,
- CrossSiteDocumentClassifier::SniffForXML(empty_data));
-}
-
-TEST(CrossSiteDocumentClassifierTest, SniffForJSON) {
- StringPiece json_data("\t\t\r\n { \"name\" : \"chrome\", ");
- StringPiece json_corrupt_after_first_key(
- "\t\t\r\n { \"name\" :^^^^!!@#\1\", ");
- StringPiece json_data2("{ \"key \\\" \" \t\t\r\n:");
- StringPiece non_json_data0("\t\t\r\n { name : \"chrome\", ");
- StringPiece non_json_data1("\t\t\r\n foo({ \"name\" : \"chrome\", ");
- StringPiece empty_data("");
-
- EXPECT_EQ(Result::kYes, CrossSiteDocumentClassifier::SniffForJSON(json_data));
- EXPECT_EQ(Result::kYes, CrossSiteDocumentClassifier::SniffForJSON(
- json_corrupt_after_first_key));
-
- EXPECT_EQ(Result::kYes,
- CrossSiteDocumentClassifier::SniffForJSON(json_data2));
-
- // All prefixes prefixes of |json_data2| ought to be indeterminate.
- StringPiece almost_json = json_data2;
- while (!almost_json.empty()) {
- almost_json.remove_suffix(1);
- EXPECT_EQ(Result::kMaybe,
- CrossSiteDocumentClassifier::SniffForJSON(almost_json))
- << almost_json;
- }
-
- EXPECT_EQ(Result::kNo,
- CrossSiteDocumentClassifier::SniffForJSON(non_json_data0));
- EXPECT_EQ(Result::kNo,
- CrossSiteDocumentClassifier::SniffForJSON(non_json_data1));
-
- EXPECT_EQ(Result::kYes,
- CrossSiteDocumentClassifier::SniffForJSON(R"({"" : 1})"))
- << "Empty strings are accepted";
- EXPECT_EQ(Result::kNo,
- CrossSiteDocumentClassifier::SniffForJSON(R"({'' : 1})"))
- << "Single quotes are not accepted";
- EXPECT_EQ(Result::kYes,
- CrossSiteDocumentClassifier::SniffForJSON("{\"\\\"\" : 1}"))
- << "Escaped quotes are recognized";
- EXPECT_EQ(Result::kYes,
- CrossSiteDocumentClassifier::SniffForJSON(R"({"\\\u000a" : 1})"))
- << "Escaped control characters are recognized";
- EXPECT_EQ(Result::kMaybe,
- CrossSiteDocumentClassifier::SniffForJSON(R"({"\\\u00)"))
- << "Incomplete escape results in maybe";
- EXPECT_EQ(Result::kMaybe, CrossSiteDocumentClassifier::SniffForJSON("{\"\\"))
- << "Incomplete escape results in maybe";
- EXPECT_EQ(Result::kMaybe,
- CrossSiteDocumentClassifier::SniffForJSON("{\"\\\""))
- << "Incomplete escape results in maybe";
- EXPECT_EQ(Result::kNo,
- CrossSiteDocumentClassifier::SniffForJSON("{\"\n\" : true}"))
- << "Unescaped control characters are rejected";
- EXPECT_EQ(Result::kNo, CrossSiteDocumentClassifier::SniffForJSON("{}"))
- << "Empty dictionary is not recognized (since it's valid JS too)";
- EXPECT_EQ(Result::kNo,
- CrossSiteDocumentClassifier::SniffForJSON("[true, false, 1, 2]"))
- << "Lists dictionary are not recognized (since they're valid JS too)";
- EXPECT_EQ(Result::kNo, CrossSiteDocumentClassifier::SniffForJSON(R"({":"})"))
- << "A colon character inside a string does not trigger a match";
-}
-
-TEST(CrossSiteDocumentClassifierTest, GetCanonicalMimeType) {
- std::vector<std::pair<const char*, CrossSiteDocumentMimeType>> tests = {
- // Basic tests for things in the original implementation:
- {"text/html", CROSS_SITE_DOCUMENT_MIME_TYPE_HTML},
- {"text/xml", CROSS_SITE_DOCUMENT_MIME_TYPE_XML},
- {"application/rss+xml", CROSS_SITE_DOCUMENT_MIME_TYPE_XML},
- {"application/xml", CROSS_SITE_DOCUMENT_MIME_TYPE_XML},
- {"application/json", CROSS_SITE_DOCUMENT_MIME_TYPE_JSON},
- {"text/json", CROSS_SITE_DOCUMENT_MIME_TYPE_JSON},
- {"text/x-json", CROSS_SITE_DOCUMENT_MIME_TYPE_JSON},
- {"text/plain", CROSS_SITE_DOCUMENT_MIME_TYPE_PLAIN},
-
- // Other mime types:
- {"application/foobar", CROSS_SITE_DOCUMENT_MIME_TYPE_OTHERS},
-
- // Regression tests for https://crbug.com/799155 (prefix/suffix matching):
- {"application/json+protobuf", CROSS_SITE_DOCUMENT_MIME_TYPE_JSON},
- {"text/json+protobuf", CROSS_SITE_DOCUMENT_MIME_TYPE_JSON},
- {"application/activity+json", CROSS_SITE_DOCUMENT_MIME_TYPE_JSON},
- {"text/foobar+xml", CROSS_SITE_DOCUMENT_MIME_TYPE_XML},
- // No match without a '+' character:
- {"application/jsonfoobar", CROSS_SITE_DOCUMENT_MIME_TYPE_OTHERS},
- {"application/foobarjson", CROSS_SITE_DOCUMENT_MIME_TYPE_OTHERS},
- {"application/xmlfoobar", CROSS_SITE_DOCUMENT_MIME_TYPE_OTHERS},
- {"application/foobarxml", CROSS_SITE_DOCUMENT_MIME_TYPE_OTHERS},
-
- // Case-insensitive comparison:
- {"APPLICATION/JSON", CROSS_SITE_DOCUMENT_MIME_TYPE_JSON},
- {"APPLICATION/JSON+PROTOBUF", CROSS_SITE_DOCUMENT_MIME_TYPE_JSON},
- {"APPLICATION/ACTIVITY+JSON", CROSS_SITE_DOCUMENT_MIME_TYPE_JSON},
-
- // Images are allowed cross-site, and SVG is an image, so we should
- // classify SVG as "other" instead of "xml" (even though it technically is
- // an xml document).
- {"image/svg+xml", CROSS_SITE_DOCUMENT_MIME_TYPE_OTHERS},
-
- // Javascript should not be blocked.
- {"application/javascript", CROSS_SITE_DOCUMENT_MIME_TYPE_OTHERS},
- {"application/jsonp", CROSS_SITE_DOCUMENT_MIME_TYPE_OTHERS},
- };
-
- for (const auto& test : tests) {
- const char* input = test.first; // e.g. "text/html"
- CrossSiteDocumentMimeType expected = test.second;
- CrossSiteDocumentMimeType actual =
- CrossSiteDocumentClassifier::GetCanonicalMimeType(input);
- EXPECT_EQ(expected, actual)
- << "when testing with the following input: " << input;
- }
-}
-
-} // namespace content
diff --git a/chromium/content/common/cursors/DEPS b/chromium/content/common/cursors/DEPS
index 240aa48d31c..b2f32dda35c 100644
--- a/chromium/content/common/cursors/DEPS
+++ b/chromium/content/common/cursors/DEPS
@@ -1,5 +1,5 @@
include_rules = [
- "+third_party/WebKit/public/platform",
+ "+third_party/blink/public/platform",
]
specific_include_rules = {
diff --git a/chromium/content/common/cursors/webcursor.cc b/chromium/content/common/cursors/webcursor.cc
index 42584ef2fd3..5d194adf345 100644
--- a/chromium/content/common/cursors/webcursor.cc
+++ b/chromium/content/common/cursors/webcursor.cc
@@ -9,7 +9,7 @@
#include "base/logging.h"
#include "base/pickle.h"
#include "build/build_config.h"
-#include "third_party/WebKit/public/platform/WebImage.h"
+#include "third_party/blink/public/platform/web_image.h"
using blink::WebCursorInfo;
diff --git a/chromium/content/common/cursors/webcursor_android.cc b/chromium/content/common/cursors/webcursor_android.cc
index fc1f67f070e..5d2db8c97b4 100644
--- a/chromium/content/common/cursors/webcursor_android.cc
+++ b/chromium/content/common/cursors/webcursor_android.cc
@@ -5,7 +5,7 @@
#include "content/common/cursors/webcursor.h"
#include "base/logging.h"
-#include "third_party/WebKit/public/platform/WebCursorInfo.h"
+#include "third_party/blink/public/platform/web_cursor_info.h"
namespace content {
diff --git a/chromium/content/common/cursors/webcursor_aura.cc b/chromium/content/common/cursors/webcursor_aura.cc
index f198bad53b4..9a3939ecfc7 100644
--- a/chromium/content/common/cursors/webcursor_aura.cc
+++ b/chromium/content/common/cursors/webcursor_aura.cc
@@ -5,7 +5,7 @@
#include "content/common/cursors/webcursor.h"
#include "base/logging.h"
-#include "third_party/WebKit/public/platform/WebCursorInfo.h"
+#include "third_party/blink/public/platform/web_cursor_info.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/cursor/cursor_util.h"
diff --git a/chromium/content/common/cursors/webcursor_aurawin.cc b/chromium/content/common/cursors/webcursor_aurawin.cc
index 5b320648039..03bf448e054 100644
--- a/chromium/content/common/cursors/webcursor_aurawin.cc
+++ b/chromium/content/common/cursors/webcursor_aurawin.cc
@@ -6,7 +6,7 @@
#include <windows.h>
-#include "third_party/WebKit/public/platform/WebCursorInfo.h"
+#include "third_party/blink/public/platform/web_cursor_info.h"
#include "ui/gfx/icon_util.h"
namespace content {
diff --git a/chromium/content/common/cursors/webcursor_aurax11.cc b/chromium/content/common/cursors/webcursor_aurax11.cc
index 00cc3ae46a0..a856b35368e 100644
--- a/chromium/content/common/cursors/webcursor_aurax11.cc
+++ b/chromium/content/common/cursors/webcursor_aurax11.cc
@@ -6,7 +6,7 @@
#include "base/logging.h"
-#include "third_party/WebKit/public/platform/WebCursorInfo.h"
+#include "third_party/blink/public/platform/web_cursor_info.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/cursor/cursor_loader_x11.h"
#include "ui/base/x/x11_util.h"
diff --git a/chromium/content/common/cursors/webcursor_mac.mm b/chromium/content/common/cursors/webcursor_mac.mm
index a55335de75a..972ed72c97a 100644
--- a/chromium/content/common/cursors/webcursor_mac.mm
+++ b/chromium/content/common/cursors/webcursor_mac.mm
@@ -13,8 +13,8 @@
#include "content/app/resources/grit/content_resources.h"
#include "content/public/common/content_client.h"
#include "skia/ext/skia_utils_mac.h"
-#include "third_party/WebKit/public/platform/WebCursorInfo.h"
-#include "third_party/WebKit/public/platform/WebSize.h"
+#include "third_party/blink/public/platform/web_cursor_info.h"
+#include "third_party/blink/public/platform/web_size.h"
#include "ui/gfx/geometry/point_conversions.h"
#include "ui/gfx/geometry/size_conversions.h"
#include "ui/gfx/image/image.h"
diff --git a/chromium/content/common/cursors/webcursor_ozone.cc b/chromium/content/common/cursors/webcursor_ozone.cc
index 101af76cda1..811d56dcdd2 100644
--- a/chromium/content/common/cursors/webcursor_ozone.cc
+++ b/chromium/content/common/cursors/webcursor_ozone.cc
@@ -4,7 +4,7 @@
#include "content/common/cursors/webcursor.h"
-#include "third_party/WebKit/public/platform/WebCursorInfo.h"
+#include "third_party/blink/public/platform/web_cursor_info.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/cursor/cursor_util.h"
#include "ui/ozone/public/cursor_factory_ozone.h"
diff --git a/chromium/content/common/cursors/webcursor_unittest.cc b/chromium/content/common/cursors/webcursor_unittest.cc
index 6d4afe0922d..5f3d18c85ef 100644
--- a/chromium/content/common/cursors/webcursor_unittest.cc
+++ b/chromium/content/common/cursors/webcursor_unittest.cc
@@ -8,7 +8,7 @@
#include "build/build_config.h"
#include "content/common/cursors/webcursor.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebCursorInfo.h"
+#include "third_party/blink/public/platform/web_cursor_info.h"
#include "third_party/skia/include/core/SkImageInfo.h"
#if defined(OS_WIN)
diff --git a/chromium/content/common/dom_storage/dom_storage_messages.h b/chromium/content/common/dom_storage/dom_storage_messages.h
index 7ed1fbf1c87..ca95369933c 100644
--- a/chromium/content/common/dom_storage/dom_storage_messages.h
+++ b/chromium/content/common/dom_storage/dom_storage_messages.h
@@ -10,7 +10,7 @@
#include "content/common/dom_storage/dom_storage_types.h"
#include "ipc/ipc_message_macros.h"
#include "ipc/ipc_param_traits.h"
-#include "third_party/WebKit/public/platform/WebStorageArea.h"
+#include "third_party/blink/public/platform/web_storage_area.h"
#include "url/gurl.h"
#include "url/ipc/url_param_traits.h"
diff --git a/chromium/content/common/drag_messages.h b/chromium/content/common/drag_messages.h
index 875c7ee1aa0..3f0bb169297 100644
--- a/chromium/content/common/drag_messages.h
+++ b/chromium/content/common/drag_messages.h
@@ -12,7 +12,7 @@
#include "content/common/drag_event_source_info.h"
#include "content/public/common/drop_data.h"
#include "ipc/ipc_message_macros.h"
-#include "third_party/WebKit/public/platform/WebDragOperation.h"
+#include "third_party/blink/public/platform/web_drag_operation.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/vector2d.h"
diff --git a/chromium/content/common/drag_traits.h b/chromium/content/common/drag_traits.h
index 16ea9b1e8fa..3dbe095b665 100644
--- a/chromium/content/common/drag_traits.h
+++ b/chromium/content/common/drag_traits.h
@@ -6,7 +6,7 @@
#include "content/public/common/common_param_traits.h"
#include "content/public/common/drop_data.h"
#include "ipc/ipc_message_macros.h"
-#include "third_party/WebKit/public/platform/WebDragOperation.h"
+#include "third_party/blink/public/platform/web_drag_operation.h"
#include "ui/gfx/geometry/point.h"
#define IPC_MESSAGE_START DragMsgStart
diff --git a/chromium/content/common/dwrite_font_proxy.mojom b/chromium/content/common/dwrite_font_proxy.mojom
index e8605c402a4..1d04c9be888 100644
--- a/chromium/content/common/dwrite_font_proxy.mojom
+++ b/chromium/content/common/dwrite_font_proxy.mojom
@@ -4,8 +4,8 @@
module content.mojom;
-import "mojo/common/file.mojom";
-import "mojo/common/file_path.mojom";
+import "mojo/public/mojom/base/file.mojom";
+import "mojo/public/mojom/base/file_path.mojom";
import "mojo/public/mojom/base/string16.mojom";
struct DWriteStringPair {
@@ -47,8 +47,8 @@ interface DWriteFontProxy {
// contain font data for the font family at the specified index.
[Sync]
GetFontFiles(uint32 family_index)
- => (array<mojo.common.mojom.FilePath> file_paths,
- array<mojo.common.mojom.File> file_handles);
+ => (array<mojo_base.mojom.FilePath> file_paths,
+ array<mojo_base.mojom.File> file_handles);
// Locates a font family that is able to render the specified text using the
// specified style. If successful, the family_index and family_name will
diff --git a/chromium/content/common/file_utilities.mojom b/chromium/content/common/file_utilities.mojom
index 6380261f935..7ab8354141b 100644
--- a/chromium/content/common/file_utilities.mojom
+++ b/chromium/content/common/file_utilities.mojom
@@ -4,12 +4,12 @@
module content.mojom;
-import "mojo/common/file_info.mojom";
-import "mojo/common/file_path.mojom";
+import "mojo/public/mojom/base/file_info.mojom";
+import "mojo/public/mojom/base/file_path.mojom";
// File utilities messages sent from the renderer to the browser.
interface FileUtilitiesHost {
[Sync]
- GetFileInfo(mojo.common.mojom.FilePath path) => (
- mojo.common.mojom.FileInfo? result);
+ GetFileInfo(mojo_base.mojom.FilePath path) => (
+ mojo_base.mojom.FileInfo? result);
};
diff --git a/chromium/content/common/fileapi/file_system_messages.h b/chromium/content/common/fileapi/file_system_messages.h
index dfd43e63c60..9edd48cf161 100644
--- a/chromium/content/common/fileapi/file_system_messages.h
+++ b/chromium/content/common/fileapi/file_system_messages.h
@@ -9,9 +9,12 @@
#include <stdint.h>
+#include <string>
+#include <vector>
+
+#include "components/services/filesystem/public/interfaces/types.mojom.h"
#include "ipc/ipc_message_macros.h"
#include "ipc/ipc_platform_file.h"
-#include "storage/common/fileapi/directory_entry.h"
#include "storage/common/fileapi/file_system_info.h"
#include "storage/common/fileapi/file_system_types.h"
#include "storage/common/quota/quota_limit_type.h"
@@ -21,9 +24,9 @@
#define IPC_MESSAGE_EXPORT CONTENT_EXPORT
#define IPC_MESSAGE_START FileSystemMsgStart
-IPC_STRUCT_TRAITS_BEGIN(storage::DirectoryEntry)
+IPC_STRUCT_TRAITS_BEGIN(filesystem::mojom::DirectoryEntry)
IPC_STRUCT_TRAITS_MEMBER(name)
- IPC_STRUCT_TRAITS_MEMBER(is_directory)
+ IPC_STRUCT_TRAITS_MEMBER(type)
IPC_STRUCT_TRAITS_END()
IPC_STRUCT_TRAITS_BEGIN(storage::FileSystemInfo)
@@ -32,6 +35,8 @@ IPC_STRUCT_TRAITS_BEGIN(storage::FileSystemInfo)
IPC_STRUCT_TRAITS_MEMBER(mount_type)
IPC_STRUCT_TRAITS_END()
+IPC_ENUM_TRAITS_MAX_VALUE(filesystem::mojom::FsFileType,
+ filesystem::mojom::FsFileType::DIRECTORY)
IPC_ENUM_TRAITS_MAX_VALUE(storage::FileSystemType,
storage::FileSystemType::kFileSystemTypeLast)
IPC_ENUM_TRAITS_MAX_VALUE(storage::QuotaLimitType, storage::kQuotaLimitTypeLast)
@@ -59,10 +64,11 @@ IPC_MESSAGE_CONTROL3(FileSystemMsg_DidCreateSnapshotFile,
int /* request_id */,
base::File::Info,
base::FilePath /* true platform path */)
-IPC_MESSAGE_CONTROL3(FileSystemMsg_DidReadDirectory,
- int /* request_id */,
- std::vector<storage::DirectoryEntry> /* entries */,
- bool /* has_more */)
+IPC_MESSAGE_CONTROL3(
+ FileSystemMsg_DidReadDirectory,
+ int /* request_id */,
+ std::vector<filesystem::mojom::DirectoryEntry> /* entries */,
+ bool /* has_more */)
IPC_MESSAGE_CONTROL3(FileSystemMsg_DidWrite,
int /* request_id */,
int64_t /* byte count */,
diff --git a/chromium/content/common/font_list_mac.mm b/chromium/content/common/font_list_mac.mm
index 67d3d856609..64d2210bcb4 100644
--- a/chromium/content/common/font_list_mac.mm
+++ b/chromium/content/common/font_list_mac.mm
@@ -9,7 +9,6 @@
#include <utility>
#include "base/mac/scoped_nsautorelease_pool.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/sys_string_conversions.h"
#include "base/values.h"
diff --git a/chromium/content/common/font_list_win.cc b/chromium/content/common/font_list_win.cc
index 07ecc125142..a05a3bc8112 100644
--- a/chromium/content/common/font_list_win.cc
+++ b/chromium/content/common/font_list_win.cc
@@ -10,7 +10,6 @@
#include <set>
#include <utility>
-#include "base/memory/ptr_util.h"
#include "base/strings/string16.h"
#include "base/values.h"
diff --git a/chromium/content/common/font_loader_dispatcher_mac.cc b/chromium/content/common/font_loader_dispatcher_mac.cc
new file mode 100644
index 00000000000..b91d98f825f
--- /dev/null
+++ b/chromium/content/common/font_loader_dispatcher_mac.cc
@@ -0,0 +1,36 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/common/font_loader_dispatcher_mac.h"
+
+#include <memory>
+#include <utility>
+
+#include "base/strings/string16.h"
+#include "content/common/mac/font_loader.h"
+#include "mojo/public/cpp/bindings/strong_binding.h"
+#include "services/service_manager/public/cpp/bind_source_info.h"
+
+namespace content {
+
+FontLoaderDispatcher::FontLoaderDispatcher() {}
+
+FontLoaderDispatcher::~FontLoaderDispatcher() {}
+
+// static
+void FontLoaderDispatcher::Create(
+ mojom::FontLoaderMacRequest request,
+ const service_manager::BindSourceInfo& source_info) {
+ mojo::MakeStrongBinding(std::make_unique<FontLoaderDispatcher>(),
+ std::move(request));
+}
+
+void FontLoaderDispatcher::LoadFont(
+ const base::string16& font_name,
+ float font_point_size,
+ mojom::FontLoaderMac::LoadFontCallback callback) {
+ FontLoader::LoadFont(font_name, font_point_size, std::move(callback));
+}
+
+} // namespace content
diff --git a/chromium/content/common/font_loader_dispatcher_mac.h b/chromium/content/common/font_loader_dispatcher_mac.h
new file mode 100644
index 00000000000..0c2d8ba81af
--- /dev/null
+++ b/chromium/content/common/font_loader_dispatcher_mac.h
@@ -0,0 +1,39 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_COMMON_FONT_LOADER_DISPATCHER_MAC_H_
+#define CONTENT_COMMON_FONT_LOADER_DISPATCHER_MAC_H_
+
+#include "content/common/font_loader_mac.mojom.h"
+
+namespace service_manager {
+struct BindSourceInfo;
+}
+
+namespace content {
+
+// Dispatches message used for font loading on Mac. This is needed because
+// Mac can't load fonts outside its conventional font locations in sandboxed
+// processes. So the sandboxed process asks the browser process to do this
+// for it.
+class FontLoaderDispatcher : public mojom::FontLoaderMac {
+ public:
+ FontLoaderDispatcher();
+ ~FontLoaderDispatcher() override;
+
+ static void Create(mojom::FontLoaderMacRequest request,
+ const service_manager::BindSourceInfo& source_info);
+
+ private:
+ // mojom::FontLoaderMac
+ void LoadFont(const base::string16& font_name,
+ float font_point_size,
+ mojom::FontLoaderMac::LoadFontCallback callback) override;
+
+ DISALLOW_COPY_AND_ASSIGN(FontLoaderDispatcher);
+};
+
+} // namespace content
+
+#endif // CONTENT_COMMON_FONT_LOADER_DISPATCHER_MAC_H_
diff --git a/chromium/content/common/font_loader_mac.mojom b/chromium/content/common/font_loader_mac.mojom
new file mode 100644
index 00000000000..d14c1f16693
--- /dev/null
+++ b/chromium/content/common/font_loader_mac.mojom
@@ -0,0 +1,14 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+module content.mojom;
+
+import "mojo/public/mojom/base/string16.mojom";
+
+interface FontLoaderMac {
+ // Request the browser to load a font into shared memory for us.
+ [Sync]
+ LoadFont(mojo_base.mojom.String16 font_name, float font_point_size)
+ => (handle<shared_buffer>? font_data, uint32 font_id);
+};
diff --git a/chromium/content/common/frame.mojom b/chromium/content/common/frame.mojom
index e5fbf20747e..99ec7e8d799 100644
--- a/chromium/content/common/frame.mojom
+++ b/chromium/content/common/frame.mojom
@@ -8,16 +8,19 @@ import "content/common/navigation_params.mojom";
import "content/common/service_worker/controller_service_worker.mojom";
import "content/common/url_loader_factory_bundle.mojom";
import "content/public/common/resource_type.mojom";
+import "content/public/common/resource_load_info.mojom";
+import "content/public/common/transferrable_url_loader.mojom";
import "content/public/common/window_container_type.mojom";
-import "mojo/common/unguessable_token.mojom";
import "mojo/public/mojom/base/string16.mojom";
+import "mojo/public/mojom/base/unguessable_token.mojom";
import "services/network/public/mojom/url_loader.mojom";
import "services/service_manager/public/mojom/interface_provider.mojom";
import "services/viz/public/interfaces/compositing/surface_id.mojom";
-import "third_party/WebKit/public/mojom/feature_policy/feature_policy.mojom";
-import "third_party/WebKit/public/platform/referrer.mojom";
-import "third_party/WebKit/public/web/commit_result.mojom";
-import "third_party/WebKit/public/web/window_features.mojom";
+import "third_party/blink/public/mojom/blob/blob_url_store.mojom";
+import "third_party/blink/public/mojom/feature_policy/feature_policy.mojom";
+import "third_party/blink/public/platform/referrer.mojom";
+import "third_party/blink/public/web/commit_result.mojom";
+import "third_party/blink/public/web/window_features.mojom";
import "ui/base/mojo/window_open_disposition.mojom";
import "url/mojom/url.mojom";
import "ui/gfx/geometry/mojo/geometry.mojom";
@@ -86,8 +89,9 @@ interface FrameNavigationControl {
RequestNavigationParams request_params,
network.mojom.URLLoaderClientEndpoints? url_loader_client_endpoints,
URLLoaderFactoryBundle? subresource_loader_factories,
+ array<TransferrableURLLoader>? subresource_overrides,
ControllerServiceWorkerInfo? controller_service_worker_info,
- mojo.common.mojom.UnguessableToken devtools_navigation_token);
+ mojo_base.mojom.UnguessableToken devtools_navigation_token);
// Tells the renderer that a failed navigation is ready to commit.
//
@@ -96,7 +100,7 @@ interface FrameNavigationControl {
// (i.e. flattened HTML, JS, CSS).
//
// When the Network Service is enabled, |subresource_loader_factories| may
- // also be provided by the browser as a a means for the renderer to load
+ // also be provided by the browser as a means for the renderer to load
// subresources where applicable.
CommitFailedNavigation(
CommonNavigationParams common_params,
@@ -219,7 +223,7 @@ struct CreateNewWindowReply {
// attribute them to the context frame.
// |devtools_frame_token| is only defined by the browser and is never
// sent back from the renderer in the control calls.
- mojo.common.mojom.UnguessableToken devtools_main_frame_token;
+ mojo_base.mojom.UnguessableToken devtools_main_frame_token;
};
// An opaque handle that keeps alive the associated render process even after
@@ -264,18 +268,26 @@ interface FrameHost {
DidCommitProvisionalLoadParams params);
// Sent by the renderer to request a navigation.
+ // |blob_url_token| should be non-null when this is a navigation to a blob:
+ // URL. The token will then be used to look up the blob associated with the
+ // blob URL. Without this by the time the navigation code starts fetching
+ // the URL the blob URL might no longer be valid. |blob_url_token| is
+ // not part of BeginNavigationParams because that struct needs to be
+ // cloneable, and thus can't contain mojo interfaces.
+ // If an invalid BlobURLToken is passed in, or if the token doesn't match the
+ // url in |common_params|, the navigation will result in a network error.
BeginNavigation(
CommonNavigationParams common_params,
- BeginNavigationParams begin_params);
+ BeginNavigationParams begin_params,
+ blink.mojom.BlobURLToken? blob_url_token);
// Sent when a subresource response has started.
- SubresourceResponseStarted(
- url.mojom.Url url,
- url.mojom.Url referrer,
- string method,
- ResourceType resource_type,
- string ip,
- uint32 cert_status);
+ // |cert_status| is the bitmask of status info of the SSL certificate. (see
+ // net/cert/cert_status_flags.h).
+ SubresourceResponseStarted(url.mojom.Url url, uint32 cert_status);
+
+ // Sent when a resource load finished, successfully or not.
+ ResourceLoadComplete(ResourceLoadInfo url_load_info);
// Sent when the frame changes its window.name.
DidChangeName(string name, string unique_name);
@@ -316,7 +328,12 @@ interface FrameHost {
// navigation.
FrameSizeChanged(gfx.mojom.Size size);
- // Sent by the renderer to update Picture-in-Picture with SurfaceId information
- // to be used to show content in the Picture-in-Picture window.
- OnUpdatePictureInPictureSurfaceId(viz.mojom.SurfaceId surface_id);
+ // Sent by the renderer to update Picture-in-Picture with SurfaceId and video
+ // size to be used to show content in the Picture-in-Picture window.
+ OnUpdatePictureInPictureSurfaceId(
+ viz.mojom.SurfaceId surface_id,
+ gfx.mojom.Size natural_size);
+
+ // Sent by the renderer to signal that Picture-in-Picture mode has ended.
+ OnExitPictureInPicture();
};
diff --git a/chromium/content/common/frame_messages.h b/chromium/content/common/frame_messages.h
index c06c9d132a3..cf96a19a4e0 100644
--- a/chromium/content/common/frame_messages.h
+++ b/chromium/content/common/frame_messages.h
@@ -19,16 +19,17 @@
#include "build/build_config.h"
#include "components/viz/common/surfaces/surface_id.h"
#include "components/viz/common/surfaces/surface_info.h"
+#include "content/common/buildflags.h"
#include "content/common/content_export.h"
#include "content/common/content_param_traits.h"
#include "content/common/content_security_policy/csp_context.h"
#include "content/common/content_security_policy_header.h"
#include "content/common/download/mhtml_save_status.h"
-#include "content/common/features.h"
#include "content/common/frame_message_enums.h"
#include "content/common/frame_message_structs.h"
#include "content/common/frame_owner_properties.h"
#include "content/common/frame_replication_state.h"
+#include "content/common/frame_resize_params.h"
#include "content/common/navigation_gesture.h"
#include "content/common/navigation_params.h"
#include "content/common/resource_timing_info.h"
@@ -52,21 +53,21 @@
#include "ipc/ipc_message_macros.h"
#include "ipc/ipc_platform_file.h"
#include "mojo/public/cpp/system/message_pipe.h"
-#include "ppapi/features/features.h"
-#include "third_party/WebKit/public/common/feature_policy/feature_policy.h"
-#include "third_party/WebKit/public/common/frame/frame_policy.h"
-#include "third_party/WebKit/public/common/message_port/message_port_channel.h"
-#include "third_party/WebKit/public/common/message_port/transferable_message.h"
-#include "third_party/WebKit/public/platform/WebFocusType.h"
-#include "third_party/WebKit/public/platform/WebInsecureRequestPolicy.h"
-#include "third_party/WebKit/public/platform/WebIntrinsicSizingInfo.h"
-#include "third_party/WebKit/public/platform/WebScrollIntoViewParams.h"
-#include "third_party/WebKit/public/platform/WebSuddenTerminationDisablerType.h"
-#include "third_party/WebKit/public/web/WebFindOptions.h"
-#include "third_party/WebKit/public/web/WebFrameOwnerProperties.h"
-#include "third_party/WebKit/public/web/WebFrameSerializerCacheControlPolicy.h"
-#include "third_party/WebKit/public/web/WebTreeScopeType.h"
-#include "third_party/WebKit/public/web/WebTriggeringEventInfo.h"
+#include "ppapi/buildflags/buildflags.h"
+#include "third_party/blink/public/common/feature_policy/feature_policy.h"
+#include "third_party/blink/public/common/frame/frame_policy.h"
+#include "third_party/blink/public/common/message_port/message_port_channel.h"
+#include "third_party/blink/public/common/message_port/transferable_message.h"
+#include "third_party/blink/public/platform/web_focus_type.h"
+#include "third_party/blink/public/platform/web_insecure_request_policy.h"
+#include "third_party/blink/public/platform/web_intrinsic_sizing_info.h"
+#include "third_party/blink/public/platform/web_scroll_into_view_params.h"
+#include "third_party/blink/public/platform/web_sudden_termination_disabler_type.h"
+#include "third_party/blink/public/web/web_find_options.h"
+#include "third_party/blink/public/web/web_frame_owner_properties.h"
+#include "third_party/blink/public/web/web_frame_serializer_cache_control_policy.h"
+#include "third_party/blink/public/web/web_tree_scope_type.h"
+#include "third_party/blink/public/web/web_triggering_event_info.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/rect_f.h"
#include "ui/gfx/ipc/gfx_param_traits.h"
@@ -88,9 +89,6 @@ using FrameMsg_GetSerializedHtmlWithLocalLinks_UrlMap =
using FrameMsg_GetSerializedHtmlWithLocalLinks_FrameRoutingIdMap =
std::map<int, base::FilePath>;
-using FrameMsg_SerializeAsMHTML_FrameRoutingIdToContentIdMap =
- std::map<int, std::string>;
-
#endif // INTERNAL_CONTENT_COMMON_FRAME_MESSAGES_H_
#undef IPC_MESSAGE_EXPORT
@@ -131,7 +129,7 @@ IPC_ENUM_TRAITS_MAX_VALUE(content::FileChooserParams::Mode,
IPC_ENUM_TRAITS_MAX_VALUE(content::CSPDirective::Name,
content::CSPDirective::NameLast)
IPC_ENUM_TRAITS_MAX_VALUE(blink::mojom::FeaturePolicyFeature,
- blink::mojom::FeaturePolicyFeature::kLastFeature)
+ blink::mojom::FeaturePolicyFeature::kMaxValue)
IPC_ENUM_TRAITS_MAX_VALUE(content::CSPDisposition,
content::CSPDisposition::LAST)
IPC_ENUM_TRAITS_MAX_VALUE(blink::WebTriggeringEventInfo,
@@ -169,6 +167,9 @@ IPC_STRUCT_TRAITS_BEGIN(blink::WebScrollIntoViewParams)
IPC_STRUCT_TRAITS_MEMBER(make_visible_in_visual_viewport)
IPC_STRUCT_TRAITS_MEMBER(behavior)
IPC_STRUCT_TRAITS_MEMBER(is_for_scroll_sequence)
+ IPC_STRUCT_TRAITS_MEMBER(zoom_into_rect)
+ IPC_STRUCT_TRAITS_MEMBER(relative_element_bounds)
+ IPC_STRUCT_TRAITS_MEMBER(relative_caret_bounds)
IPC_STRUCT_TRAITS_END()
IPC_STRUCT_TRAITS_BEGIN(content::ContextMenuParams)
@@ -229,6 +230,16 @@ IPC_STRUCT_TRAITS_BEGIN(content::FrameOwnerProperties)
IPC_STRUCT_TRAITS_MEMBER(required_csp)
IPC_STRUCT_TRAITS_END()
+IPC_STRUCT_TRAITS_BEGIN(content::FrameResizeParams)
+ IPC_STRUCT_TRAITS_MEMBER(screen_info)
+ IPC_STRUCT_TRAITS_MEMBER(auto_resize_enabled)
+ IPC_STRUCT_TRAITS_MEMBER(min_size_for_auto_resize)
+ IPC_STRUCT_TRAITS_MEMBER(max_size_for_auto_resize)
+ IPC_STRUCT_TRAITS_MEMBER(auto_resize_sequence_number)
+ IPC_STRUCT_TRAITS_MEMBER(screen_space_rect)
+ IPC_STRUCT_TRAITS_MEMBER(local_frame_size)
+IPC_STRUCT_TRAITS_END()
+
IPC_STRUCT_TRAITS_BEGIN(blink::FramePolicy)
IPC_STRUCT_TRAITS_MEMBER(sandbox_flags)
IPC_STRUCT_TRAITS_MEMBER(container_policy)
@@ -370,14 +381,14 @@ IPC_STRUCT_BEGIN_WITH_PARENT(FrameHostMsg_DidCommitProvisionalLoad_Params,
// successfully cleared.
IPC_STRUCT_MEMBER(bool, history_list_was_cleared)
- // The routing_id of the render view associated with the navigation.
- // We need to track the RenderViewHost routing_id because of downstream
- // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
- // ResourceDispatcherHostImpl, MediaStreamUIProxy,
- // SpeechRecognitionDispatcherHost and possibly others). They look up the view
- // based on the ID stored in the resource requests. Once those dependencies
- // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
- // client to be based on the routing_id of the RenderFrameHost.
+ // The routing_id of the render view associated with the navigation. We need
+ // to track the RenderViewHost routing_id because of downstream dependencies
+ // (https://crbug.com/392171 DownloadRequestHandle, SaveFileManager,
+ // ResourceDispatcherHostImpl, MediaStreamUIProxy and possibly others). They
+ // look up the view based on the ID stored in the resource requests. Once
+ // those dependencies are unwound or moved to RenderFrameHost
+ // (https://crbug.com/304341) we can move the client to be based on the
+ // routing_id of the RenderFrameHost.
IPC_STRUCT_MEMBER(int, render_view_routing_id)
// Origin of the frame. This will be replicated to any associated
@@ -488,6 +499,7 @@ IPC_STRUCT_TRAITS_BEGIN(content::RequestNavigationParams)
IPC_STRUCT_TRAITS_MEMBER(pending_history_list_offset)
IPC_STRUCT_TRAITS_MEMBER(current_history_list_offset)
IPC_STRUCT_TRAITS_MEMBER(current_history_list_length)
+ IPC_STRUCT_TRAITS_MEMBER(was_discarded)
IPC_STRUCT_TRAITS_MEMBER(is_view_source)
IPC_STRUCT_TRAITS_MEMBER(should_clear_history_list)
IPC_STRUCT_TRAITS_MEMBER(should_create_service_worker)
@@ -503,6 +515,7 @@ IPC_STRUCT_TRAITS_END()
IPC_STRUCT_TRAITS_BEGIN(blink::ParsedFeaturePolicyDeclaration)
IPC_STRUCT_TRAITS_MEMBER(feature)
IPC_STRUCT_TRAITS_MEMBER(matches_all_origins)
+ IPC_STRUCT_TRAITS_MEMBER(matches_opaque_src)
IPC_STRUCT_TRAITS_MEMBER(origins)
IPC_STRUCT_TRAITS_END()
@@ -605,12 +618,6 @@ IPC_STRUCT_BEGIN(FrameMsg_SerializeAsMHTML_Params)
// Whether to detect problems while serializing.
IPC_STRUCT_MEMBER(bool, mhtml_problem_detection)
- // Frame to content-id map.
- // Keys are routing ids of either RenderFrames or RenderFrameProxies.
- // Values are MHTML content-ids - see WebFrameSerializer::generateMHTMLParts.
- IPC_STRUCT_MEMBER(FrameMsg_SerializeAsMHTML_FrameRoutingIdToContentIdMap,
- frame_routing_id_to_content_id)
-
// |digests_of_uris_to_skip| contains digests of uris of MHTML parts that
// should be skipped. This helps deduplicate mhtml parts across frames.
// SECURITY NOTE: Sha256 digests (rather than uris) are used to prevent
@@ -988,6 +995,16 @@ IPC_MESSAGE_ROUTED0(FrameMsg_ClearFocusedElement)
IPC_MESSAGE_ROUTED1(FrameMsg_ResizeDueToAutoResize,
uint64_t /* sequence_number */)
+// Requests a viz::LocalSurfaceId to enable auto-resize mode from the parent
+// renderer.
+IPC_MESSAGE_ROUTED2(FrameMsg_EnableAutoResize,
+ gfx::Size /* min_size */,
+ gfx::Size /* max_size */)
+
+// Requests a viz::LocalSurfaceId to disable auto-resize-mode from the parent
+// renderer.
+IPC_MESSAGE_ROUTED0(FrameMsg_DisableAutoResize)
+
#if defined(OS_ANDROID)
// Request the distance to the nearest find result in a frame from the point at
// (x, y), defined in fractions of the content document's width and height. The
@@ -1122,8 +1139,11 @@ IPC_MESSAGE_ROUTED0(FrameMsg_EnableViewSourceMode)
// ScopedPageLoadDeferrer is on the stack for SwapOut.
IPC_MESSAGE_ROUTED0(FrameMsg_SuppressFurtherDialogs)
+// Notifies the RenderFrame about a user activation from the browser side.
+IPC_MESSAGE_ROUTED0(FrameMsg_NotifyUserActivation)
+
// Tells the frame to consider itself to have received a user gesture (based
-// on a user gesture processed in a different process).
+// on a user gesture processed in a different renderer process).
IPC_MESSAGE_ROUTED0(FrameMsg_SetHasReceivedUserGesture)
// Tells the frame to mark that the previous document on that frame had received
@@ -1403,8 +1423,9 @@ IPC_MESSAGE_ROUTED1(FrameHostMsg_PluginContentOriginAllowed,
// plugin is hung.
//
// On error an empty string and null handles are returned.
-IPC_SYNC_MESSAGE_CONTROL1_3(FrameHostMsg_OpenChannelToPepperPlugin,
+IPC_SYNC_MESSAGE_CONTROL2_3(FrameHostMsg_OpenChannelToPepperPlugin,
base::FilePath /* path */,
+ base::Optional<url::Origin>, /* origin_lock */
IPC::ChannelHandle /* handle to channel */,
base::ProcessId /* plugin_pid */,
int /* plugin_child_id */)
@@ -1477,17 +1498,17 @@ IPC_MESSAGE_ROUTED3(FrameHostMsg_BeforeUnload_ACK,
IPC_MESSAGE_ROUTED0(FrameHostMsg_SwapOut_ACK)
// Tells the browser that a child's resize parameters have changed.
-IPC_MESSAGE_ROUTED5(FrameHostMsg_UpdateResizeParams,
- gfx::Rect /* screen_space_rect */,
- gfx::Size /* local_frame_size */,
- content::ScreenInfo /* screen_info */,
- uint64_t /* sequence_number */,
- viz::SurfaceId /* surface_id */)
+IPC_MESSAGE_ROUTED2(FrameHostMsg_UpdateResizeParams,
+ viz::SurfaceId /* surface_id */,
+ content::FrameResizeParams)
// Sent by a parent frame to update its child's viewport intersection rect for
// use by the IntersectionObserver API.
-IPC_MESSAGE_ROUTED1(FrameHostMsg_UpdateViewportIntersection,
- gfx::Rect /* viewport_intersection */)
+// compositor_rect is dependent on the intersection rect and indicates the
+// area of the child frame that needs to be rastered. It is in physical pixels.
+IPC_MESSAGE_ROUTED2(FrameHostMsg_UpdateViewportIntersection,
+ gfx::Rect /* viewport_intersection */,
+ gfx::Rect /* compositor_visible_rect */)
// Informs the child that the frame has changed visibility.
IPC_MESSAGE_ROUTED1(FrameHostMsg_VisibilityChanged, bool /* visible */)
@@ -1536,22 +1557,21 @@ IPC_MESSAGE_ROUTED2(FrameHostMsg_JavaScriptExecuteResponse,
base::ListValue /* result */)
// A request to run a JavaScript dialog.
-IPC_SYNC_MESSAGE_ROUTED4_2(FrameHostMsg_RunJavaScriptDialog,
+IPC_SYNC_MESSAGE_ROUTED3_2(FrameHostMsg_RunJavaScriptDialog,
base::string16 /* in - alert message */,
base::string16 /* in - default prompt */,
- GURL /* in - originating page URL */,
content::JavaScriptDialogType /* in - type */,
bool /* out - success */,
base::string16 /* out - user_input field */)
// Displays a dialog to confirm that the user wants to navigate away from the
// page. Replies true if yes, and false otherwise. The reply string is ignored,
-// but is included so that we can use OnJavaScriptMessageBoxClosed.
-IPC_SYNC_MESSAGE_ROUTED2_2(FrameHostMsg_RunBeforeUnloadConfirm,
- GURL, /* in - originating frame URL */
- bool /* in - is a reload */,
- bool /* out - success */,
- base::string16 /* out - This is ignored.*/)
+// but is included so that we can use
+// RenderFrameHostImpl::SendJavaScriptDialogReply.
+IPC_SYNC_MESSAGE_ROUTED1_2(FrameHostMsg_RunBeforeUnloadConfirm,
+ bool /* in - is a reload */,
+ bool /* out - success */,
+ base::string16 /* out - This is ignored.*/)
// Notify browser the theme color has been changed.
IPC_MESSAGE_ROUTED1(FrameHostMsg_DidChangeThemeColor,
diff --git a/chromium/content/common/frame_owner_properties.h b/chromium/content/common/frame_owner_properties.h
index 8e9a47cbe12..74ed5d59428 100644
--- a/chromium/content/common/frame_owner_properties.h
+++ b/chromium/content/common/frame_owner_properties.h
@@ -8,8 +8,8 @@
#include <vector>
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/common/feature_policy/feature_policy.h"
-#include "third_party/WebKit/public/web/WebFrameOwnerProperties.h"
+#include "third_party/blink/public/common/feature_policy/feature_policy.h"
+#include "third_party/blink/public/web/web_frame_owner_properties.h"
namespace content {
diff --git a/chromium/content/common/frame_replication_state.cc b/chromium/content/common/frame_replication_state.cc
index 562523614e8..ec6087d92fa 100644
--- a/chromium/content/common/frame_replication_state.cc
+++ b/chromium/content/common/frame_replication_state.cc
@@ -4,8 +4,8 @@
#include "content/common/frame_replication_state.h"
-#include "third_party/WebKit/public/common/frame/sandbox_flags.h"
-#include "third_party/WebKit/public/web/WebTreeScopeType.h"
+#include "third_party/blink/public/common/frame/sandbox_flags.h"
+#include "third_party/blink/public/web/web_tree_scope_type.h"
namespace content {
diff --git a/chromium/content/common/frame_replication_state.h b/chromium/content/common/frame_replication_state.h
index f90c925cb5b..a3e930bfd3f 100644
--- a/chromium/content/common/frame_replication_state.h
+++ b/chromium/content/common/frame_replication_state.h
@@ -10,9 +10,9 @@
#include "content/common/content_export.h"
#include "content/common/content_security_policy_header.h"
-#include "third_party/WebKit/public/common/feature_policy/feature_policy.h"
-#include "third_party/WebKit/public/common/frame/frame_policy.h"
-#include "third_party/WebKit/public/platform/WebInsecureRequestPolicy.h"
+#include "third_party/blink/public/common/feature_policy/feature_policy.h"
+#include "third_party/blink/public/common/frame/frame_policy.h"
+#include "third_party/blink/public/platform/web_insecure_request_policy.h"
#include "url/origin.h"
namespace blink {
diff --git a/chromium/content/common/frame_resize_params.cc b/chromium/content/common/frame_resize_params.cc
new file mode 100644
index 00000000000..fc5059d0fc6
--- /dev/null
+++ b/chromium/content/common/frame_resize_params.cc
@@ -0,0 +1,19 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/common/frame_resize_params.h"
+
+namespace content {
+
+FrameResizeParams::FrameResizeParams()
+ : auto_resize_enabled(false), auto_resize_sequence_number(0u) {}
+
+FrameResizeParams::FrameResizeParams(const FrameResizeParams& other) = default;
+
+FrameResizeParams::~FrameResizeParams() {}
+
+FrameResizeParams& FrameResizeParams::operator=(
+ const FrameResizeParams& other) = default;
+
+} // namespace content
diff --git a/chromium/content/common/frame_resize_params.h b/chromium/content/common/frame_resize_params.h
new file mode 100644
index 00000000000..425590722c0
--- /dev/null
+++ b/chromium/content/common/frame_resize_params.h
@@ -0,0 +1,47 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_COMMON_FRAME_RESIZE_PARAMS_H_
+#define CONTENT_COMMON_FRAME_RESIZE_PARAMS_H_
+
+#include "content/common/content_export.h"
+#include "content/public/common/screen_info.h"
+#include "third_party/blink/public/platform/web_display_mode.h"
+#include "ui/gfx/geometry/size.h"
+
+namespace content {
+
+// TODO(fsamuel): We might want to unify this with content::ResizeParams.
+struct CONTENT_EXPORT FrameResizeParams {
+ FrameResizeParams();
+ FrameResizeParams(const FrameResizeParams& other);
+ ~FrameResizeParams();
+
+ FrameResizeParams& operator=(const FrameResizeParams& other);
+
+ // Information about the screen (dpi, depth, etc..).
+ ScreenInfo screen_info;
+
+ // Whether or not blink should be in auto-resize mode.
+ bool auto_resize_enabled;
+
+ // The minimum size for Blink if auto-resize is enabled.
+ gfx::Size min_size_for_auto_resize;
+
+ // The maximum size for Blink if auto-resize is enabled.
+ gfx::Size max_size_for_auto_resize;
+
+ // This variable is increased after each auto-resize. If the
+ // renderer receives a ResizeParams with stale auto_resize_seqence_number,
+ // then the resize request is dropped.
+ uint64_t auto_resize_sequence_number;
+
+ gfx::Rect screen_space_rect;
+
+ gfx::Size local_frame_size;
+};
+
+} // namespace content
+
+#endif // CONTENT_COMMON_FRAME_RESIZE_PARAMS_H_
diff --git a/chromium/content/common/indexed_db/indexed_db.mojom b/chromium/content/common/indexed_db/indexed_db.mojom
index 47d03ec296b..15edf0ef4cb 100644
--- a/chromium/content/common/indexed_db/indexed_db.mojom
+++ b/chromium/content/common/indexed_db/indexed_db.mojom
@@ -8,10 +8,11 @@
module indexed_db.mojom;
-import "mojo/common/file_path.mojom";
+import "mojo/public/mojom/base/file_path.mojom";
import "mojo/public/mojom/base/string16.mojom";
-import "mojo/common/time.mojom";
-import "third_party/WebKit/public/mojom/blob/blob.mojom";
+import "mojo/public/mojom/base/string16.mojom";
+import "mojo/public/mojom/base/time.mojom";
+import "third_party/blink/public/mojom/blob/blob.mojom";
import "url/mojom/origin.mojom";
enum CursorDirection {
@@ -131,9 +132,9 @@ struct IndexKeys {
};
struct FileInfo {
- mojo.common.mojom.FilePath path;
+ mojo_base.mojom.FilePath path;
mojo_base.mojom.String16 name;
- mojo.common.mojom.Time last_modified;
+ mojo_base.mojom.Time last_modified;
};
struct BlobInfo {
diff --git a/chromium/content/common/indexed_db/indexed_db.typemap b/chromium/content/common/indexed_db/indexed_db.typemap
index 1640ff07cae..aad054c269e 100644
--- a/chromium/content/common/indexed_db/indexed_db.typemap
+++ b/chromium/content/common/indexed_db/indexed_db.typemap
@@ -8,7 +8,7 @@ public_headers = [
"//content/common/indexed_db/indexed_db_key_path.h",
"//content/common/indexed_db/indexed_db_key_range.h",
"//content/common/indexed_db/indexed_db_metadata.h",
- "//third_party/WebKit/public/platform/modules/indexeddb/WebIDBTypes.h",
+ "//third_party/blink/public/platform/modules/indexeddb/web_idb_types.h",
]
traits_headers = [ "//content/common/indexed_db/indexed_db_struct_traits.h" ]
type_mappings = [
diff --git a/chromium/content/common/indexed_db/indexed_db_key.h b/chromium/content/common/indexed_db/indexed_db_key.h
index 5668f1a2f3f..411f1c5fc28 100644
--- a/chromium/content/common/indexed_db/indexed_db_key.h
+++ b/chromium/content/common/indexed_db/indexed_db_key.h
@@ -13,7 +13,7 @@
#include "base/logging.h"
#include "base/strings/string16.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBTypes.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_types.h"
namespace content {
diff --git a/chromium/content/common/indexed_db/indexed_db_key_path.h b/chromium/content/common/indexed_db/indexed_db_key_path.h
index a8431e98dfb..70c67f941f4 100644
--- a/chromium/content/common/indexed_db/indexed_db_key_path.h
+++ b/chromium/content/common/indexed_db/indexed_db_key_path.h
@@ -11,7 +11,7 @@
#include "base/logging.h"
#include "base/strings/string16.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBTypes.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_types.h"
namespace content {
diff --git a/chromium/content/common/indexed_db/indexed_db_key_range.cc b/chromium/content/common/indexed_db/indexed_db_key_range.cc
index f1938bfb2cd..e073e649df4 100644
--- a/chromium/content/common/indexed_db/indexed_db_key_range.cc
+++ b/chromium/content/common/indexed_db/indexed_db_key_range.cc
@@ -5,7 +5,7 @@
#include "content/common/indexed_db/indexed_db_key_range.h"
#include "base/logging.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBTypes.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_types.h"
namespace content {
diff --git a/chromium/content/common/input/event_with_latency_info.h b/chromium/content/common/input/event_with_latency_info.h
index 3ac2bdd3a32..7dc0e8113ce 100644
--- a/chromium/content/common/input/event_with_latency_info.h
+++ b/chromium/content/common/input/event_with_latency_info.h
@@ -8,9 +8,9 @@
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebGestureEvent.h"
-#include "third_party/WebKit/public/platform/WebMouseWheelEvent.h"
-#include "third_party/WebKit/public/platform/WebTouchEvent.h"
+#include "third_party/blink/public/platform/web_gesture_event.h"
+#include "third_party/blink/public/platform/web_mouse_wheel_event.h"
+#include "third_party/blink/public/platform/web_touch_event.h"
#include "ui/events/blink/blink_event_util.h"
#include "ui/events/blink/web_input_event_traits.h"
#include "ui/latency/latency_info.h"
diff --git a/chromium/content/common/input/event_with_latency_info_unittest.cc b/chromium/content/common/input/event_with_latency_info_unittest.cc
index 0e2f6ff5a6e..640e42e71fd 100644
--- a/chromium/content/common/input/event_with_latency_info_unittest.cc
+++ b/chromium/content/common/input/event_with_latency_info_unittest.cc
@@ -7,7 +7,7 @@
#include <limits>
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
using blink::WebGestureEvent;
using blink::WebInputEvent;
@@ -55,8 +55,7 @@ GestureEventWithLatencyInfo CreateGestureEvent(WebInputEvent::Type type,
float y = 0.0f) {
GestureEventWithLatencyInfo gesture(type, WebInputEvent::kNoModifiers,
timestamp, ui::LatencyInfo());
- gesture.event.x = x;
- gesture.event.y = y;
+ gesture.event.SetPositionInWidget(gfx::PointF(x, y));
return gesture;
}
diff --git a/chromium/content/common/input/gesture_event_stream_validator.cc b/chromium/content/common/input/gesture_event_stream_validator.cc
index 5338ce8603d..e5a95ea3385 100644
--- a/chromium/content/common/input/gesture_event_stream_validator.cc
+++ b/chromium/content/common/input/gesture_event_stream_validator.cc
@@ -6,8 +6,8 @@
#include "base/logging.h"
#include "base/strings/stringprintf.h"
-#include "third_party/WebKit/public/platform/WebGestureEvent.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_gesture_event.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/events/blink/web_input_event_traits.h"
using blink::WebInputEvent;
@@ -21,8 +21,10 @@ GestureEventStreamValidator::GestureEventStreamValidator()
GestureEventStreamValidator::~GestureEventStreamValidator() {
}
-bool GestureEventStreamValidator::Validate(const blink::WebGestureEvent& event,
- std::string* error_msg) {
+bool GestureEventStreamValidator::Validate(
+ const blink::WebGestureEvent& event,
+ const bool fling_cancellation_is_deferred,
+ std::string* error_msg) {
DCHECK(error_msg);
error_msg->clear();
if (!WebInputEvent::IsGestureEventType(event.GetType())) {
@@ -31,7 +33,7 @@ bool GestureEventStreamValidator::Validate(const blink::WebGestureEvent& event,
}
switch (event.GetType()) {
case WebInputEvent::kGestureScrollBegin:
- if (scrolling_)
+ if (scrolling_ && !fling_cancellation_is_deferred)
error_msg->append("Scroll begin during scroll\n");
if (pinching_)
error_msg->append("Scroll begin during pinch\n");
@@ -42,7 +44,7 @@ bool GestureEventStreamValidator::Validate(const blink::WebGestureEvent& event,
error_msg->append("Scroll update outside of scroll\n");
break;
case WebInputEvent::kGestureFlingStart:
- if (event.source_device == blink::kWebGestureDeviceTouchscreen &&
+ if (event.SourceDevice() == blink::kWebGestureDeviceTouchscreen &&
!event.data.fling_start.velocity_x &&
!event.data.fling_start.velocity_y) {
error_msg->append("Zero velocity touchscreen fling\n");
@@ -51,7 +53,8 @@ bool GestureEventStreamValidator::Validate(const blink::WebGestureEvent& event,
error_msg->append("Fling start outside of scroll\n");
if (pinching_)
error_msg->append("Flinging while pinching\n");
- scrolling_ = false;
+ // Don't reset scrolling_ since the GSE sent by the fling_controller_ at
+ // the end of the fling resets it.
break;
case WebInputEvent::kGestureScrollEnd:
if (!scrolling_)
@@ -105,10 +108,16 @@ bool GestureEventStreamValidator::Validate(const blink::WebGestureEvent& event,
// 'continuity check', requiring that all events between an initial tap-down
// and whatever terminates the sequence to have the same source device type,
// and that touchpad gestures are only found on ScrollEvents.
- if (event.source_device == blink::kWebGestureDeviceUninitialized)
+ if (event.SourceDevice() == blink::kWebGestureDeviceUninitialized)
error_msg->append("Gesture event source is uninitialized.\n");
return error_msg->empty();
}
+bool GestureEventStreamValidator::Validate(const blink::WebGestureEvent& event,
+ std::string* error_msg) {
+ return Validate(event, /* fling_cancellation_is_deferred = */ false,
+ error_msg);
+}
+
} // namespace content
diff --git a/chromium/content/common/input/gesture_event_stream_validator.h b/chromium/content/common/input/gesture_event_stream_validator.h
index 5d8ae8f3e23..49303e1e159 100644
--- a/chromium/content/common/input/gesture_event_stream_validator.h
+++ b/chromium/content/common/input/gesture_event_stream_validator.h
@@ -24,6 +24,9 @@ class CONTENT_EXPORT GestureEventStreamValidator {
// If |event| is valid for the current stream, returns true.
// Otherwise, returns false with a corresponding error message.
+ bool Validate(const blink::WebGestureEvent& event,
+ const bool fling_cancellation_is_deferred,
+ std::string* error_msg);
bool Validate(const blink::WebGestureEvent& event, std::string* error_msg);
private:
diff --git a/chromium/content/common/input/ime_text_span_conversions.cc b/chromium/content/common/input/ime_text_span_conversions.cc
index 59ef7f35643..cd83e90b704 100644
--- a/chromium/content/common/input/ime_text_span_conversions.cc
+++ b/chromium/content/common/input/ime_text_span_conversions.cc
@@ -38,4 +38,80 @@ ui::ImeTextSpan::Type ConvertWebImeTextSpanTypeToUiType(
return ui::ImeTextSpan::Type::kComposition;
}
+ui::mojom::ImeTextSpanThickness ConvertUiThicknessToUiImeTextSpanThickness(
+ ui::ImeTextSpan::Thickness thickness) {
+ switch (thickness) {
+ case ui::ImeTextSpan::Thickness::kNone:
+ return ui::mojom::ImeTextSpanThickness::kNone;
+ case ui::ImeTextSpan::Thickness::kThin:
+ return ui::mojom::ImeTextSpanThickness::kThin;
+ case ui::ImeTextSpan::Thickness::kThick:
+ return ui::mojom::ImeTextSpanThickness::kThick;
+ }
+
+ NOTREACHED();
+ return ui::mojom::ImeTextSpanThickness::kThin;
+}
+
+ui::ImeTextSpan::Thickness ConvertUiImeTextSpanThicknessToUiThickness(
+ ui::mojom::ImeTextSpanThickness thickness) {
+ switch (thickness) {
+ case ui::mojom::ImeTextSpanThickness::kNone:
+ return ui::ImeTextSpan::Thickness::kNone;
+ case ui::mojom::ImeTextSpanThickness::kThin:
+ return ui::ImeTextSpan::Thickness::kThin;
+ case ui::mojom::ImeTextSpanThickness::kThick:
+ return ui::ImeTextSpan::Thickness::kThick;
+ }
+
+ NOTREACHED();
+ return ui::ImeTextSpan::Thickness::kThin;
+}
+
+blink::WebImeTextSpan ConvertUiImeTextSpanToBlinkImeTextSpan(
+ const ui::ImeTextSpan& ui_ime_text_span) {
+ blink::WebImeTextSpan blink_ime_text_span = blink::WebImeTextSpan(
+ ConvertUiImeTextSpanTypeToWebType(ui_ime_text_span.type),
+ ui_ime_text_span.start_offset, ui_ime_text_span.end_offset,
+ ConvertUiThicknessToUiImeTextSpanThickness(ui_ime_text_span.thickness),
+ ui_ime_text_span.background_color,
+ ui_ime_text_span.suggestion_highlight_color,
+ ui_ime_text_span.suggestions);
+ blink_ime_text_span.underline_color = ui_ime_text_span.underline_color;
+ return blink_ime_text_span;
+}
+
+std::vector<blink::WebImeTextSpan> ConvertUiImeTextSpansToBlinkImeTextSpans(
+ const std::vector<ui::ImeTextSpan>& ui_ime_text_spans) {
+ std::vector<blink::WebImeTextSpan> blink_ime_text_spans;
+ for (const auto& ui_ime_text_span : ui_ime_text_spans) {
+ blink_ime_text_spans.push_back(
+ ConvertUiImeTextSpanToBlinkImeTextSpan(ui_ime_text_span));
+ }
+ return blink_ime_text_spans;
+}
+
+ui::ImeTextSpan ConvertBlinkImeTextSpanToUiImeTextSpan(
+ const blink::WebImeTextSpan& blink_ime_text_span) {
+ ui::ImeTextSpan ui_ime_text_span = ui::ImeTextSpan(
+ ConvertWebImeTextSpanTypeToUiType(blink_ime_text_span.type),
+ blink_ime_text_span.start_offset, blink_ime_text_span.end_offset,
+ ConvertUiImeTextSpanThicknessToUiThickness(blink_ime_text_span.thickness),
+ blink_ime_text_span.background_color,
+ blink_ime_text_span.suggestion_highlight_color,
+ blink_ime_text_span.suggestions);
+ ui_ime_text_span.underline_color = blink_ime_text_span.underline_color;
+ return ui_ime_text_span;
+}
+
+std::vector<ui::ImeTextSpan> ConvertBlinkImeTextSpansToUiImeTextSpans(
+ const std::vector<blink::WebImeTextSpan>& blink_ime_text_spans) {
+ std::vector<ui::ImeTextSpan> ui_ime_text_spans;
+ for (const auto& blink_ime_text_span : blink_ime_text_spans) {
+ ui_ime_text_spans.push_back(
+ ConvertBlinkImeTextSpanToUiImeTextSpan(blink_ime_text_span));
+ }
+ return ui_ime_text_spans;
+}
+
} // namespace content
diff --git a/chromium/content/common/input/ime_text_span_conversions.h b/chromium/content/common/input/ime_text_span_conversions.h
index 50d78de2899..18353d300d7 100644
--- a/chromium/content/common/input/ime_text_span_conversions.h
+++ b/chromium/content/common/input/ime_text_span_conversions.h
@@ -5,7 +5,7 @@
#ifndef CONTENT_COMMON_INPUT_IME_TEXT_SPAN_CONVERSIONS_H_
#define CONTENT_COMMON_INPUT_IME_TEXT_SPAN_CONVERSIONS_H_
-#include "third_party/WebKit/public/web/WebImeTextSpan.h"
+#include "third_party/blink/public/web/web_ime_text_span.h"
#include "ui/base/ime/ime_text_span.h"
namespace content {
@@ -14,6 +14,18 @@ blink::WebImeTextSpan::Type ConvertUiImeTextSpanTypeToWebType(
ui::ImeTextSpan::Type type);
ui::ImeTextSpan::Type ConvertWebImeTextSpanTypeToUiType(
blink::WebImeTextSpan::Type type);
+ui::mojom::ImeTextSpanThickness ConvertUiThicknessToUiImeTextSpanThickness(
+ ui::ImeTextSpan::Thickness thickness);
+ui::ImeTextSpan::Thickness ConvertUiImeTextSpanThicknessToUiThickness(
+ ui::mojom::ImeTextSpanThickness thickness);
+blink::WebImeTextSpan ConvertUiImeTextSpanToBlinkImeTextSpan(
+ const ui::ImeTextSpan&);
+ui::ImeTextSpan ConvertBlinkImeTextSpanToUiImeTextSpan(
+ const blink::WebImeTextSpan&);
+std::vector<blink::WebImeTextSpan> ConvertUiImeTextSpansToBlinkImeTextSpans(
+ const std::vector<ui::ImeTextSpan>&);
+std::vector<ui::ImeTextSpan> ConvertBlinkImeTextSpansToUiImeTextSpans(
+ const std::vector<blink::WebImeTextSpan>&);
} // namespace content
diff --git a/chromium/content/common/input/input_event_ack.h b/chromium/content/common/input/input_event_ack.h
index 5db1a07d443..321c0201a5d 100644
--- a/chromium/content/common/input/input_event_ack.h
+++ b/chromium/content/common/input/input_event_ack.h
@@ -14,7 +14,7 @@
#include "content/common/content_export.h"
#include "content/public/common/input_event_ack_source.h"
#include "content/public/common/input_event_ack_state.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/events/blink/did_overscroll_params.h"
#include "ui/latency/latency_info.h"
diff --git a/chromium/content/common/input/input_event_stream_validator.cc b/chromium/content/common/input/input_event_stream_validator.cc
index 9206718012d..a4299f073bb 100644
--- a/chromium/content/common/input/input_event_stream_validator.cc
+++ b/chromium/content/common/input/input_event_stream_validator.cc
@@ -7,8 +7,8 @@
#include "base/command_line.h"
#include "base/logging.h"
#include "content/public/common/content_switches.h"
-#include "third_party/WebKit/public/platform/WebGestureEvent.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_gesture_event.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/events/blink/web_input_event_traits.h"
using blink::WebInputEvent;
@@ -25,23 +25,28 @@ InputEventStreamValidator::InputEventStreamValidator()
InputEventStreamValidator::~InputEventStreamValidator() {
}
-void InputEventStreamValidator::Validate(const WebInputEvent& event) {
+void InputEventStreamValidator::Validate(
+ const WebInputEvent& event,
+ const bool fling_cancellation_is_deferred /* = false */) {
if (!enabled_)
return;
- DCHECK(ValidateImpl(event, &error_msg_))
+ DCHECK(ValidateImpl(event, fling_cancellation_is_deferred, &error_msg_))
<< error_msg_
<< "\nInvalid Event: " << ui::WebInputEventTraits::ToString(event);
}
-bool InputEventStreamValidator::ValidateImpl(const blink::WebInputEvent& event,
- std::string* error_msg) {
+bool InputEventStreamValidator::ValidateImpl(
+ const blink::WebInputEvent& event,
+ const bool fling_cancellation_is_deferred,
+ std::string* error_msg) {
DCHECK(error_msg);
if (WebInputEvent::IsGestureEventType(event.GetType())) {
const WebGestureEvent& gesture = static_cast<const WebGestureEvent&>(event);
// TODO(jdduke): Validate touchpad gesture streams.
- if (gesture.source_device == blink::kWebGestureDeviceTouchscreen)
- return gesture_validator_.Validate(gesture, error_msg);
+ if (gesture.SourceDevice() == blink::kWebGestureDeviceTouchscreen)
+ return gesture_validator_.Validate(
+ gesture, fling_cancellation_is_deferred, error_msg);
} else if (WebInputEvent::IsTouchEventType(event.GetType())) {
const WebTouchEvent& touch = static_cast<const WebTouchEvent&>(event);
return touch_validator_.Validate(touch, error_msg);
diff --git a/chromium/content/common/input/input_event_stream_validator.h b/chromium/content/common/input/input_event_stream_validator.h
index e2d726e5422..7bf2238ee63 100644
--- a/chromium/content/common/input/input_event_stream_validator.h
+++ b/chromium/content/common/input/input_event_stream_validator.h
@@ -24,10 +24,13 @@ class InputEventStreamValidator {
InputEventStreamValidator();
~InputEventStreamValidator();
- void Validate(const blink::WebInputEvent&);
+ void Validate(const blink::WebInputEvent&,
+ const bool fling_cancellation_is_deferred = false);
private:
- bool ValidateImpl(const blink::WebInputEvent&, std::string* error_msg);
+ bool ValidateImpl(const blink::WebInputEvent&,
+ const bool fling_cancellation_is_deferred,
+ std::string* error_msg);
GestureEventStreamValidator gesture_validator_;
TouchEventStreamValidator touch_validator_;
diff --git a/chromium/content/common/input/input_event_struct_traits.cc b/chromium/content/common/input/input_event_struct_traits.cc
index c6b923ed503..c1e18caff8c 100644
--- a/chromium/content/common/input/input_event_struct_traits.cc
+++ b/chromium/content/common/input/input_event_struct_traits.cc
@@ -6,7 +6,7 @@
#include "base/i18n/char_iterator.h"
#include "content/common/input_messages.h"
-#include "third_party/WebKit/public/platform/WebKeyboardEvent.h"
+#include "third_party/blink/public/platform/web_keyboard_event.h"
#include "ui/latency/mojo/latency_info_struct_traits.h"
namespace mojo {
@@ -111,18 +111,17 @@ bool StructTraits<content::mojom::EventDataView, InputEventUniquePtr>::Read(
if (!event.ReadGestureData<content::mojom::GestureDataPtr>(&gesture_data))
return false;
(*out)->web_event.reset(new blink::WebGestureEvent(
- type, event.modifiers(), event.timestamp_seconds()));
+ type, event.modifiers(), event.timestamp_seconds(),
+ gesture_data->source_device));
blink::WebGestureEvent* gesture_event =
static_cast<blink::WebGestureEvent*>((*out)->web_event.get());
- gesture_event->x = gesture_data->widget_position.x();
- gesture_event->y = gesture_data->widget_position.y();
- gesture_event->global_x = gesture_data->screen_position.x();
- gesture_event->global_y = gesture_data->screen_position.y();
+ gesture_event->SetPositionInWidget(gesture_data->widget_position);
+ gesture_event->SetPositionInScreen(gesture_data->screen_position);
gesture_event->is_source_touch_event_set_non_blocking =
gesture_data->is_source_touch_event_set_non_blocking;
gesture_event->primary_pointer_type = gesture_data->primary_pointer_type;
- gesture_event->source_device = gesture_data->source_device;
+ gesture_event->SetSourceDevice(gesture_data->source_device);
gesture_event->unique_touch_event_id = gesture_data->unique_touch_event_id;
gesture_event->resending_plugin_id = gesture_data->resending_plugin_id;
@@ -395,7 +394,7 @@ StructTraits<content::mojom::EventDataView, InputEventUniquePtr>::gesture_data(
auto gesture_data = content::mojom::GestureData::New();
gesture_data->screen_position = gesture_event->PositionInScreen();
gesture_data->widget_position = gesture_event->PositionInWidget();
- gesture_data->source_device = gesture_event->source_device;
+ gesture_data->source_device = gesture_event->SourceDevice();
gesture_data->is_source_touch_event_set_non_blocking =
gesture_event->is_source_touch_event_set_non_blocking;
gesture_data->primary_pointer_type = gesture_event->primary_pointer_type;
diff --git a/chromium/content/common/input/input_handler.mojom b/chromium/content/common/input/input_handler.mojom
index 200dac42039..b5725e1dbf9 100644
--- a/chromium/content/common/input/input_handler.mojom
+++ b/chromium/content/common/input/input_handler.mojom
@@ -8,7 +8,7 @@ import "content/common/input/synchronous_compositor.mojom";
import "content/common/native_types.mojom";
import "mojo/public/mojom/base/string16.mojom";
import "services/ui/public/interfaces/ime/ime.mojom";
-import "third_party/WebKit/public/web/selection_menu_behavior.mojom";
+import "third_party/blink/public/web/selection_menu_behavior.mojom";
import "ui/events/mojo/event.mojom";
import "ui/events/mojo/event_constants.mojom";
import "ui/gfx/geometry/mojo/geometry.mojom";
@@ -177,6 +177,9 @@ interface WidgetInputHandlerHost {
// Sent by the compositor when a fling animation is stopped.
DidStopFlinging();
+ // Sent by the compositor when a GSB has started scrolling the viewport.
+ DidStartScrollingViewport();
+
// Required for cancelling an ongoing input method composition.
ImeCancelComposition();
diff --git a/chromium/content/common/input/input_param_traits_unittest.cc b/chromium/content/common/input/input_param_traits_unittest.cc
index f00519eaf2b..81d1d69cd85 100644
--- a/chromium/content/common/input/input_param_traits_unittest.cc
+++ b/chromium/content/common/input/input_param_traits_unittest.cc
@@ -10,16 +10,15 @@
#include <utility>
#include <vector>
-#include "base/memory/ptr_util.h"
#include "content/common/input/input_event.h"
#include "content/common/input_messages.h"
#include "ipc/ipc_message.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebGestureEvent.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
-#include "third_party/WebKit/public/platform/WebKeyboardEvent.h"
-#include "third_party/WebKit/public/platform/WebMouseWheelEvent.h"
-#include "third_party/WebKit/public/platform/WebTouchEvent.h"
+#include "third_party/blink/public/platform/web_gesture_event.h"
+#include "third_party/blink/public/platform/web_input_event.h"
+#include "third_party/blink/public/platform/web_keyboard_event.h"
+#include "third_party/blink/public/platform/web_mouse_wheel_event.h"
+#include "third_party/blink/public/platform/web_touch_event.h"
namespace content {
namespace {
@@ -105,7 +104,7 @@ TEST_F(InputParamTraitsTest, InitializedEvents) {
blink::WebInputEvent::kGestureScrollBegin,
blink::WebInputEvent::kNoModifiers,
blink::WebInputEvent::GetStaticTimeStampForTests());
- gesture_event.x = -1;
+ gesture_event.SetPositionInWidget(gfx::PointF(-1, 0));
events.push_back(std::make_unique<InputEvent>(gesture_event, latency));
blink::WebTouchEvent touch_event(
diff --git a/chromium/content/common/input/sync_compositor_messages.h b/chromium/content/common/input/sync_compositor_messages.h
index db37296dc0f..fcfd89e58d0 100644
--- a/chromium/content/common/input/sync_compositor_messages.h
+++ b/chromium/content/common/input/sync_compositor_messages.h
@@ -15,7 +15,7 @@
#include "content/common/content_param_traits.h"
#include "content/public/common/input_event_ack_state.h"
#include "ipc/ipc_message_macros.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/scroll_offset.h"
diff --git a/chromium/content/common/input/synchronous_compositor.mojom b/chromium/content/common/input/synchronous_compositor.mojom
index 5bb8817a2eb..3c139c417cc 100644
--- a/chromium/content/common/input/synchronous_compositor.mojom
+++ b/chromium/content/common/input/synchronous_compositor.mojom
@@ -4,7 +4,7 @@
module content.mojom;
-import "mojo/common/time.mojom";
+import "mojo/public/mojom/base/time.mojom";
import "ui/gfx/geometry/mojo/geometry.mojom";
import "services/viz/public/interfaces/compositing/begin_frame_args.mojom";
import "services/viz/public/interfaces/compositing/compositor_frame.mojom";
@@ -30,7 +30,7 @@ struct SyncCompositorCommonRendererParams;
// because input must be delivered in order with the compositing events.
interface SynchronousCompositor {
// Computes the scroll at given time.
- ComputeScroll(mojo.common.mojom.TimeTicks time);
+ ComputeScroll(mojo_base.mojom.TimeTicks time);
// Hardware draw asynchronously, ReturnFrame will return the result on
// the associated SynchronousCompositorControlHost.
diff --git a/chromium/content/common/input/synthetic_pointer_action_params.cc b/chromium/content/common/input/synthetic_pointer_action_params.cc
index 23a42ec2e1c..a54e974b247 100644
--- a/chromium/content/common/input/synthetic_pointer_action_params.cc
+++ b/chromium/content/common/input/synthetic_pointer_action_params.cc
@@ -27,6 +27,10 @@ unsigned SyntheticPointerActionParams::GetWebMouseEventModifier(
return blink::WebMouseEvent::kMiddleButtonDown;
case SyntheticPointerActionParams::Button::RIGHT:
return blink::WebMouseEvent::kRightButtonDown;
+ case SyntheticPointerActionParams::Button::BACK:
+ return blink::WebMouseEvent::kBackButtonDown;
+ case SyntheticPointerActionParams::Button::FORWARD:
+ return blink::WebMouseEvent::kForwardButtonDown;
}
NOTREACHED();
return blink::WebMouseEvent::kNoModifiers;
@@ -43,9 +47,13 @@ SyntheticPointerActionParams::GetWebMouseEventButton(
return blink::WebMouseEvent::Button::kMiddle;
case SyntheticPointerActionParams::Button::RIGHT:
return blink::WebMouseEvent::Button::kRight;
+ case SyntheticPointerActionParams::Button::BACK:
+ return blink::WebMouseEvent::Button::kBack;
+ case SyntheticPointerActionParams::Button::FORWARD:
+ return blink::WebMouseEvent::Button::kForward;
}
NOTREACHED();
return blink::WebMouseEvent::Button::kNoButton;
}
-} // namespace content \ No newline at end of file
+} // namespace content
diff --git a/chromium/content/common/input/synthetic_pointer_action_params.h b/chromium/content/common/input/synthetic_pointer_action_params.h
index 970cc8c480f..7b30e830d41 100644
--- a/chromium/content/common/input/synthetic_pointer_action_params.h
+++ b/chromium/content/common/input/synthetic_pointer_action_params.h
@@ -10,7 +10,7 @@
#include "content/common/input/input_param_traits.h"
#include "content/common/input/synthetic_gesture_params.h"
#include "content/common/input/synthetic_web_input_event_builders.h"
-#include "third_party/WebKit/public/platform/WebTouchEvent.h"
+#include "third_party/blink/public/platform/web_touch_event.h"
#include "ui/gfx/geometry/point_f.h"
namespace ipc_fuzzer {
@@ -33,7 +33,14 @@ struct CONTENT_EXPORT SyntheticPointerActionParams {
POINTER_ACTION_TYPE_MAX = IDLE
};
- enum class Button { LEFT, MIDDLE, RIGHT, BUTTON_MAX = RIGHT };
+ enum class Button {
+ LEFT,
+ MIDDLE,
+ RIGHT,
+ BACK,
+ FORWARD,
+ BUTTON_MAX = FORWARD
+ };
SyntheticPointerActionParams();
SyntheticPointerActionParams(PointerActionType action_type);
diff --git a/chromium/content/common/input/synthetic_web_input_event_builders.cc b/chromium/content/common/input/synthetic_web_input_event_builders.cc
index da8fa3d92fb..617d0ea12b5 100644
--- a/chromium/content/common/input/synthetic_web_input_event_builders.cc
+++ b/chromium/content/common/input/synthetic_web_input_event_builders.cc
@@ -97,8 +97,8 @@ WebGestureEvent SyntheticWebGestureEventBuilder::Build(
int modifiers) {
DCHECK(WebInputEvent::IsGestureEventType(type));
WebGestureEvent result(type, modifiers,
- ui::EventTimeStampToSeconds(ui::EventTimeForNow()));
- result.source_device = source_device;
+ ui::EventTimeStampToSeconds(ui::EventTimeForNow()),
+ source_device);
if (type == WebInputEvent::kGestureTap ||
type == WebInputEvent::kGestureTapUnconfirmed ||
type == WebInputEvent::kGestureDoubleTap) {
@@ -143,10 +143,8 @@ WebGestureEvent SyntheticWebGestureEventBuilder::BuildPinchUpdate(
WebGestureEvent result =
Build(WebInputEvent::kGesturePinchUpdate, source_device, modifiers);
result.data.pinch_update.scale = scale;
- result.x = anchor_x;
- result.y = anchor_y;
- result.global_x = anchor_x;
- result.global_y = anchor_y;
+ result.SetPositionInWidget(blink::WebFloatPoint(anchor_x, anchor_y));
+ result.SetPositionInScreen(blink::WebFloatPoint(anchor_x, anchor_y));
return result;
}
diff --git a/chromium/content/common/input/synthetic_web_input_event_builders.h b/chromium/content/common/input/synthetic_web_input_event_builders.h
index e34268985c0..3247d0d243d 100644
--- a/chromium/content/common/input/synthetic_web_input_event_builders.h
+++ b/chromium/content/common/input/synthetic_web_input_event_builders.h
@@ -7,11 +7,11 @@
#include "base/time/time.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebGestureEvent.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
-#include "third_party/WebKit/public/platform/WebKeyboardEvent.h"
-#include "third_party/WebKit/public/platform/WebMouseWheelEvent.h"
-#include "third_party/WebKit/public/platform/WebTouchEvent.h"
+#include "third_party/blink/public/platform/web_gesture_event.h"
+#include "third_party/blink/public/platform/web_input_event.h"
+#include "third_party/blink/public/platform/web_keyboard_event.h"
+#include "third_party/blink/public/platform/web_mouse_wheel_event.h"
+#include "third_party/blink/public/platform/web_touch_event.h"
// Provides sensible creation of default WebInputEvents for testing purposes.
diff --git a/chromium/content/common/input/touch_event_stream_validator.cc b/chromium/content/common/input/touch_event_stream_validator.cc
index aa2d2bb1a5a..f6e0abd14a0 100644
--- a/chromium/content/common/input/touch_event_stream_validator.cc
+++ b/chromium/content/common/input/touch_event_stream_validator.cc
@@ -7,7 +7,7 @@
#include "base/logging.h"
#include "base/strings/stringprintf.h"
#include "content/common/input/web_touch_event_traits.h"
-#include "third_party/WebKit/public/platform/WebTouchEvent.h"
+#include "third_party/blink/public/platform/web_touch_event.h"
#include "ui/events/blink/web_input_event_traits.h"
using base::StringPrintf;
diff --git a/chromium/content/common/input/touch_event_stream_validator.h b/chromium/content/common/input/touch_event_stream_validator.h
index ba1757f9c43..0372d8b60b4 100644
--- a/chromium/content/common/input/touch_event_stream_validator.h
+++ b/chromium/content/common/input/touch_event_stream_validator.h
@@ -9,7 +9,7 @@
#include "base/macros.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebTouchEvent.h"
+#include "third_party/blink/public/platform/web_touch_event.h"
namespace content {
diff --git a/chromium/content/common/input/web_touch_event_traits.cc b/chromium/content/common/input/web_touch_event_traits.cc
index e041b2042c5..897d78e5b58 100644
--- a/chromium/content/common/input/web_touch_event_traits.cc
+++ b/chromium/content/common/input/web_touch_event_traits.cc
@@ -7,7 +7,7 @@
#include <stddef.h>
#include "base/logging.h"
-#include "third_party/WebKit/public/platform/WebTouchEvent.h"
+#include "third_party/blink/public/platform/web_touch_event.h"
using blink::WebInputEvent;
using blink::WebTouchEvent;
diff --git a/chromium/content/common/input/web_touch_event_traits.h b/chromium/content/common/input/web_touch_event_traits.h
index 0343eb8fc1c..eac4718d4ff 100644
--- a/chromium/content/common/input/web_touch_event_traits.h
+++ b/chromium/content/common/input/web_touch_event_traits.h
@@ -6,7 +6,7 @@
#define CONTENT_COMMON_INPUT_WEB_TOUCH_EVENT_TRAITS_H_
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
namespace blink {
class WebTouchEvent;
diff --git a/chromium/content/common/input_messages.h b/chromium/content/common/input_messages.h
index 79aad9fc062..89df9cc4f40 100644
--- a/chromium/content/common/input_messages.h
+++ b/chromium/content/common/input_messages.h
@@ -29,8 +29,8 @@
#include "content/public/common/input_event_ack_source.h"
#include "content/public/common/input_event_ack_state.h"
#include "ipc/ipc_message_macros.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
-#include "third_party/WebKit/public/platform/WebPointerProperties.h"
+#include "third_party/blink/public/platform/web_input_event.h"
+#include "third_party/blink/public/platform/web_pointer_properties.h"
#include "ui/events/blink/did_overscroll_params.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
@@ -353,6 +353,9 @@ IPC_MESSAGE_ROUTED1(InputHostMsg_DidOverscroll,
// Sent by the compositor when a fling animation is stopped.
IPC_MESSAGE_ROUTED0(InputHostMsg_DidStopFlinging)
+// Sent by the compositor when a GSB has started scrolling the viewport.
+IPC_MESSAGE_ROUTED0(InputHostMsg_DidStartScrollingViewport)
+
// Acknowledges receipt of a InputMsg_MoveCaret message.
IPC_MESSAGE_ROUTED0(InputHostMsg_MoveCaret_ACK)
diff --git a/chromium/content/common/leveldb_wrapper.mojom b/chromium/content/common/leveldb_wrapper.mojom
index 8640584e445..c2619016289 100644
--- a/chromium/content/common/leveldb_wrapper.mojom
+++ b/chromium/content/common/leveldb_wrapper.mojom
@@ -4,7 +4,7 @@
module content.mojom;
-import "components/leveldb/public/interfaces/leveldb.mojom";
+import "components/services/leveldb/public/interfaces/leveldb.mojom";
// Gives information about changes to a LevelDB database.
// Note that observer methods are called before the callbacks for the
@@ -40,6 +40,9 @@ interface LevelDBWrapperGetAllCallback {
// A wrapper around leveldb that supports giving notifications when values
// change.
+// TODO(dmurph): rename & move LevelDBWrapper to DOMStorageDatabase as the
+// implementation is now tied specifically to that functionality.
+// https://crbug.com/809771
interface LevelDBWrapper {
AddObserver(associated LevelDBObserver observer);
diff --git a/chromium/content/common/mac/attributed_string_coder.h b/chromium/content/common/mac/attributed_string_coder.h
index 5258884744c..7100793b51d 100644
--- a/chromium/content/common/mac/attributed_string_coder.h
+++ b/chromium/content/common/mac/attributed_string_coder.h
@@ -72,6 +72,8 @@ class CONTENT_EXPORT AttributedStringCoder {
public:
explicit EncodedString(base::string16 string);
EncodedString();
+ EncodedString(const EncodedString& other);
+ EncodedString& operator=(const EncodedString& other);
~EncodedString();
// Accessors:
diff --git a/chromium/content/common/mac/attributed_string_coder.mm b/chromium/content/common/mac/attributed_string_coder.mm
index 18d28a03013..34f2d0e228f 100644
--- a/chromium/content/common/mac/attributed_string_coder.mm
+++ b/chromium/content/common/mac/attributed_string_coder.mm
@@ -72,6 +72,12 @@ AttributedStringCoder::EncodedString::EncodedString()
: string_() {
}
+AttributedStringCoder::EncodedString::EncodedString(
+ const EncodedString& other) = default;
+
+AttributedStringCoder::EncodedString& AttributedStringCoder::EncodedString::
+operator=(const EncodedString& other) = default;
+
AttributedStringCoder::EncodedString::~EncodedString() {
}
diff --git a/chromium/content/common/mac/font_loader.h b/chromium/content/common/mac/font_loader.h
index a0d4b61c4fa..02f8196dc1e 100644
--- a/chromium/content/common/mac/font_loader.h
+++ b/chromium/content/common/mac/font_loader.h
@@ -5,11 +5,11 @@
#ifndef CONTENT_COMMON_MAC_FONT_LOADER_H_
#define CONTENT_COMMON_MAC_FONT_LOADER_H_
-#include <memory>
-
#include <CoreGraphics/CoreGraphics.h>
#include <stdint.h>
+#include <memory>
+
#include "base/callback_forward.h"
#include "content/common/content_export.h"
#include "mojo/public/cpp/system/buffer.h"
@@ -27,19 +27,18 @@ class FontLoader {
struct CONTENT_EXPORT ResultInternal {
ResultInternal();
~ResultInternal();
- uint32_t font_data_size = 0;
+
mojo::ScopedSharedBufferHandle font_data;
uint32_t font_id = 0;
};
// Callback for the reporting result of LoadFont().
- // - The first argument is the data size.
// - The ScopedSharedBufferHandle points to a shared memory buffer containing
// the raw data for the font file.
// - The last argument is the font_id: a unique identifier for the on-disk
// file we load for the font.
- using LoadedCallback = base::OnceCallback<
- void(uint32_t, mojo::ScopedSharedBufferHandle, uint32_t)>;
+ using LoadedCallback =
+ base::OnceCallback<void(mojo::ScopedSharedBufferHandle, uint32_t)>;
// Load a font specified by |font| into a shared memory buffer suitable for
// sending over IPC. On failure, zeroes and an invalid handle are reported
diff --git a/chromium/content/common/mac/font_loader.mm b/chromium/content/common/mac/font_loader.mm
index 9cdd80684bf..c802bdb5514 100644
--- a/chromium/content/common/mac/font_loader.mm
+++ b/chromium/content/common/mac/font_loader.mm
@@ -17,7 +17,6 @@
#import "base/mac/foundation_util.h"
#include "base/mac/scoped_cftyperef.h"
#import "base/mac/scoped_nsobject.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/sys_string_conversions.h"
#include "base/task_scheduler/post_task.h"
#include "base/threading/thread_restrictions.h"
@@ -95,8 +94,6 @@ std::unique_ptr<FontLoader::ResultInternal> LoadFontOnFileThread(
return nullptr;
}
- result->font_data_size = font_file_size_32;
-
// Font loading used to call ATSFontGetContainer() and used that as font id.
// ATS is deprecated. CoreText offers up the ATSFontRef typeface ID via
// CTFontGetPlatformFont.
@@ -112,15 +109,12 @@ std::unique_ptr<FontLoader::ResultInternal> LoadFontOnFileThread(
void ReplyOnUIThread(FontLoader::LoadedCallback callback,
std::unique_ptr<FontLoader::ResultInternal> result) {
if (!result) {
- std::move(callback).Run(0, mojo::ScopedSharedBufferHandle(), 0);
+ std::move(callback).Run(mojo::ScopedSharedBufferHandle(), 0);
return;
}
- DCHECK_NE(0u, result->font_data_size);
DCHECK_NE(0u, result->font_id);
-
- std::move(callback).Run(result->font_data_size, std::move(result->font_data),
- result->font_id);
+ std::move(callback).Run(std::move(result->font_data), result->font_id);
}
} // namespace
diff --git a/chromium/content/common/manifest_share_target_util_unittest.cc b/chromium/content/common/manifest_share_target_util_unittest.cc
new file mode 100644
index 00000000000..edfc6767ea7
--- /dev/null
+++ b/chromium/content/common/manifest_share_target_util_unittest.cc
@@ -0,0 +1,266 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include <map>
+#include <utility>
+
+#include "content/public/common/manifest_share_target_util.h"
+#include "testing/gtest/include/gtest/gtest.h"
+#include "url/gurl.h"
+
+namespace content {
+namespace {
+
+constexpr char kTitle[] = "My title";
+constexpr char kText[] = "My text";
+constexpr char kUrlSpec[] = "https://www.google.com/";
+
+} // namespace
+
+TEST(ManifestShareTargetUtilTest, ReplaceUrlPlaceholdersInvalidTemplate) {
+ // Badly nested placeholders.
+ GURL url_template = GURL("http://example.com/?q={");
+ EXPECT_FALSE(ValidateWebShareUrlTemplate(url_template));
+ EXPECT_FALSE(
+ ReplaceWebShareUrlPlaceholders(url_template, "", "", GURL(), nullptr));
+
+ url_template = GURL("http://example.com/?q={title");
+ EXPECT_FALSE(ValidateWebShareUrlTemplate(url_template));
+ EXPECT_FALSE(
+ ReplaceWebShareUrlPlaceholders(url_template, "", "", GURL(), nullptr));
+
+ url_template = GURL("http://example.com/?q={title{text}}");
+ EXPECT_FALSE(ValidateWebShareUrlTemplate(url_template));
+ EXPECT_FALSE(
+ ReplaceWebShareUrlPlaceholders(url_template, "", "", GURL(), nullptr));
+
+ url_template = GURL("http://example.com/?q={title{}");
+ EXPECT_FALSE(ValidateWebShareUrlTemplate(url_template));
+ EXPECT_FALSE(
+ ReplaceWebShareUrlPlaceholders(url_template, "", "", GURL(), nullptr));
+
+ url_template = GURL("http://example.com/?q={{title}}");
+ EXPECT_FALSE(ValidateWebShareUrlTemplate(url_template));
+ EXPECT_FALSE(
+ ReplaceWebShareUrlPlaceholders(url_template, "", "", GURL(), nullptr));
+
+ // Placeholder with non-identifier character.
+ url_template = GURL("http://example.com/?q={title?}");
+ EXPECT_FALSE(ValidateWebShareUrlTemplate(url_template));
+ EXPECT_FALSE(
+ ReplaceWebShareUrlPlaceholders(url_template, "", "", GURL(), nullptr));
+
+ // Placeholder with digit character.
+ url_template = GURL("http://example.com/?q={title1}");
+ EXPECT_TRUE(ValidateWebShareUrlTemplate(url_template));
+ EXPECT_TRUE(
+ ReplaceWebShareUrlPlaceholders(url_template, "", "", GURL(), nullptr));
+
+ // Empty placeholder.
+ url_template = GURL("http://example.com/?q={}");
+ EXPECT_TRUE(ValidateWebShareUrlTemplate(url_template));
+ EXPECT_TRUE(
+ ReplaceWebShareUrlPlaceholders(url_template, "", "", GURL(), nullptr));
+
+ // Invalid placeholder in URL fragment.
+ url_template = GURL("http://example.com/#{title?}");
+ EXPECT_FALSE(ValidateWebShareUrlTemplate(url_template));
+ EXPECT_FALSE(
+ ReplaceWebShareUrlPlaceholders(url_template, "", "", GURL(), nullptr));
+
+ // { in path.
+ url_template = GURL("http://example.com/subpath{/");
+ EXPECT_TRUE(ValidateWebShareUrlTemplate(url_template));
+ EXPECT_TRUE(
+ ReplaceWebShareUrlPlaceholders(url_template, "", "", GURL(), nullptr));
+
+ // Invalid placeholder. Non-empty title, text, share URL and non-empty output
+ // parameter.
+ GURL url_template_filled;
+ url_template = GURL("http://example.com/?q={");
+ EXPECT_FALSE(ReplaceWebShareUrlPlaceholders(url_template, "text", "title",
+ GURL("http://www.google.com"),
+ &url_template_filled));
+}
+
+TEST(ManifestShareTargetUtilTest, ReplaceWebShareUrlPlaceholders) {
+ const GURL kUrl(kUrlSpec);
+
+ // No placeholders.
+ GURL url_template = GURL("http://example.com/?q=a#a");
+ GURL url_template_filled;
+ bool succeeded = ReplaceWebShareUrlPlaceholders(url_template, kTitle, kText,
+ kUrl, &url_template_filled);
+ EXPECT_TRUE(succeeded);
+ EXPECT_EQ(url_template, url_template_filled);
+
+ // One title placeholder.
+ url_template = GURL("http://example.com/#{title}");
+ succeeded = ReplaceWebShareUrlPlaceholders(url_template, kTitle, kText, kUrl,
+ &url_template_filled);
+ EXPECT_TRUE(succeeded);
+ EXPECT_EQ("http://example.com/#My%20title", url_template_filled.spec());
+
+ // One text placeholder.
+ url_template = GURL("http://example.com/#{text}");
+ succeeded = ReplaceWebShareUrlPlaceholders(url_template, kTitle, kText, kUrl,
+ &url_template_filled);
+ EXPECT_TRUE(succeeded);
+ EXPECT_EQ("http://example.com/#My%20text", url_template_filled.spec());
+
+ // One url placeholder.
+ url_template = GURL("http://example.com/#{url}");
+ succeeded = ReplaceWebShareUrlPlaceholders(url_template, kTitle, kText, kUrl,
+ &url_template_filled);
+ EXPECT_TRUE(succeeded);
+ EXPECT_EQ("http://example.com/#https%3A%2F%2Fwww.google.com%2F",
+ url_template_filled.spec());
+
+ // One of each placeholder, in title, text, url order.
+ url_template = GURL("http://example.com/#{title}{text}{url}");
+ succeeded = ReplaceWebShareUrlPlaceholders(url_template, kTitle, kText, kUrl,
+ &url_template_filled);
+ EXPECT_TRUE(succeeded);
+ EXPECT_EQ(
+ "http://example.com/#My%20titleMy%20texthttps%3A%2F%2Fwww.google.com%2F",
+ url_template_filled.spec());
+
+ // One of each placeholder, in url, text, title order.
+ url_template = GURL("http://example.com/#{url}{text}{title}");
+ succeeded = ReplaceWebShareUrlPlaceholders(url_template, kTitle, kText, kUrl,
+ &url_template_filled);
+ EXPECT_TRUE(succeeded);
+ EXPECT_EQ(
+ "http://example.com/#https%3A%2F%2Fwww.google.com%2FMy%20textMy%20title",
+ url_template_filled.spec());
+
+ // Two of each placeholder, some next to each other, others not.
+ url_template =
+ GURL("http://example.com/#{title}{url}{text}{text}{title}{url}");
+ succeeded = ReplaceWebShareUrlPlaceholders(url_template, kTitle, kText, kUrl,
+ &url_template_filled);
+ EXPECT_TRUE(succeeded);
+ EXPECT_EQ(
+ "http://example.com/"
+ "#My%20titlehttps%3A%2F%2Fwww.google.com%2FMy%20textMy%20textMy%"
+ "20titlehttps%3A%2F%2Fwww.google.com%2F",
+ url_template_filled.spec());
+
+ // Placeholders are in a query string, as values. The expected use case.
+ // Two of each placeholder, some next to each other, others not.
+ url_template = GURL(
+ "http://example.com?title={title}&url={url}&text={text}&text={text}&"
+ "title={title}&url={url}");
+ succeeded = ReplaceWebShareUrlPlaceholders(url_template, kTitle, kText, kUrl,
+ &url_template_filled);
+ EXPECT_TRUE(succeeded);
+ EXPECT_EQ(
+ "http://"
+ "example.com/?title=My%20title&url=https%3A%2F%2Fwww.google.com%2F&"
+ "text=My%20text&"
+ "text=My%20text&title=My%20title&url=https%3A%2F%2Fwww.google.com%2F",
+ url_template_filled.spec());
+
+ // Empty placeholder.
+ url_template = GURL("http://example.com/#{}");
+ succeeded = ReplaceWebShareUrlPlaceholders(url_template, kTitle, kText, kUrl,
+ &url_template_filled);
+ EXPECT_TRUE(succeeded);
+ EXPECT_EQ("http://example.com/#", url_template_filled.spec());
+
+ // Unexpected placeholders.
+ url_template = GURL("http://example.com/#{nonexistentplaceholder}");
+ succeeded = ReplaceWebShareUrlPlaceholders(url_template, kTitle, kText, kUrl,
+ &url_template_filled);
+ EXPECT_TRUE(succeeded);
+ EXPECT_EQ("http://example.com/#", url_template_filled.spec());
+
+ // Placeholders should only be replaced in query and fragment.
+ url_template = GURL("http://example.com/subpath{title}/?q={title}#{title}");
+ succeeded = ReplaceWebShareUrlPlaceholders(url_template, kTitle, kText, kUrl,
+ &url_template_filled);
+ EXPECT_TRUE(succeeded);
+ EXPECT_EQ("http://example.com/subpath%7Btitle%7D/?q=My%20title#My%20title",
+ url_template_filled.spec());
+
+ // Braces in the path, which would be invalid, but should parse fine as they
+ // are escaped.
+ url_template = GURL("http://example.com/subpath{/?q={title}");
+ succeeded = ReplaceWebShareUrlPlaceholders(url_template, kTitle, kText, kUrl,
+ &url_template_filled);
+ EXPECT_TRUE(succeeded);
+ EXPECT_EQ("http://example.com/subpath%7B/?q=My%20title",
+ url_template_filled.spec());
+
+ // |url_template| with % escapes.
+ url_template = GURL("http://example.com#%20{title}%20");
+ succeeded = ReplaceWebShareUrlPlaceholders(url_template, kTitle, kText, kUrl,
+ &url_template_filled);
+ EXPECT_TRUE(succeeded);
+ EXPECT_EQ("http://example.com/#%20My%20title%20", url_template_filled.spec());
+}
+
+// Test URL escaping done by ReplaceWebShareUrlPlaceholders().
+TEST(ManifestShareTargetUtilTest, ReplaceWebShareUrlPlaceholders_Escaping) {
+ const GURL kUrl(kUrlSpec);
+ const GURL kUrlTemplate("http://example.com/#{title}");
+
+ // Share data that contains percent escapes.
+ GURL url_template_filled;
+ bool succeeded = ReplaceWebShareUrlPlaceholders(
+ kUrlTemplate, "My%20title", kText, kUrl, &url_template_filled);
+ EXPECT_TRUE(succeeded);
+ EXPECT_EQ("http://example.com/#My%2520title", url_template_filled.spec());
+
+ // Share data that contains placeholders. These should not be replaced.
+ succeeded = ReplaceWebShareUrlPlaceholders(kUrlTemplate, "{title}", kText,
+ kUrl, &url_template_filled);
+ EXPECT_TRUE(succeeded);
+ EXPECT_EQ("http://example.com/#%7Btitle%7D", url_template_filled.spec());
+
+ // All characters that shouldn't be escaped.
+ succeeded = ReplaceWebShareUrlPlaceholders(kUrlTemplate,
+ "-_.!~*'()0123456789"
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyz",
+ kText, kUrl, &url_template_filled);
+ EXPECT_TRUE(succeeded);
+ EXPECT_EQ(
+ "http://example.com/#-_.!~*'()0123456789"
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyz",
+ url_template_filled.spec());
+
+ // All characters that should be escaped.
+ succeeded =
+ ReplaceWebShareUrlPlaceholders(kUrlTemplate, " \"#$%&+,/:;<=>?@[\\]^`{|}",
+ kText, kUrl, &url_template_filled);
+ EXPECT_TRUE(succeeded);
+ EXPECT_EQ(
+ "http://example.com/"
+ "#%20%22%23%24%25%26%2B%2C%2F%3A%3B%3C%3D%3E%3F%40%5B%5C%5D%5E%60%7B%7C%"
+ "7D",
+ url_template_filled.spec());
+
+ // Unicode chars.
+ // U+263B
+ succeeded = ReplaceWebShareUrlPlaceholders(kUrlTemplate, "\xe2\x98\xbb",
+ kText, kUrl, &url_template_filled);
+ EXPECT_TRUE(succeeded);
+ EXPECT_EQ("http://example.com/#%E2%98%BB", url_template_filled.spec());
+
+ // U+00E9
+ succeeded = ReplaceWebShareUrlPlaceholders(kUrlTemplate, "\xc3\xa9", kText,
+ kUrl, &url_template_filled);
+ EXPECT_TRUE(succeeded);
+ EXPECT_EQ("http://example.com/#%C3%A9", url_template_filled.spec());
+
+ // U+1F4A9
+ succeeded = ReplaceWebShareUrlPlaceholders(kUrlTemplate, "\xf0\x9f\x92\xa9",
+ kText, kUrl, &url_template_filled);
+ EXPECT_TRUE(succeeded);
+ EXPECT_EQ("http://example.com/#%F0%9F%92%A9", url_template_filled.spec());
+}
+
+} // namespace content
diff --git a/chromium/content/common/media/media_devices.typemap b/chromium/content/common/media/media_devices.typemap
index 0ffd81ca2f1..2451e202204 100644
--- a/chromium/content/common/media/media_devices.typemap
+++ b/chromium/content/common/media/media_devices.typemap
@@ -2,7 +2,7 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
-mojom = "//third_party/WebKit/public/platform/modules/mediastream/media_devices.mojom"
+mojom = "//third_party/blink/public/platform/modules/mediastream/media_devices.mojom"
public_headers = [ "//content/common/media/media_devices.h" ]
traits_headers = [ "//content/common/media/media_devices_typemap_traits.h" ]
sources = [
@@ -11,4 +11,5 @@ sources = [
type_mappings = [
"blink.mojom.MediaDeviceType=content::MediaDeviceType",
"blink.mojom.MediaDeviceInfo=content::MediaDeviceInfo",
+ "blink.mojom.FacingMode=media::VideoFacingMode",
]
diff --git a/chromium/content/common/media/media_devices_typemap_traits.cc b/chromium/content/common/media/media_devices_typemap_traits.cc
index e265d225411..3a46450496f 100644
--- a/chromium/content/common/media/media_devices_typemap_traits.cc
+++ b/chromium/content/common/media/media_devices_typemap_traits.cc
@@ -48,6 +48,45 @@ bool EnumTraits<blink::mojom::MediaDeviceType, content::MediaDeviceType>::
}
// static
+blink::mojom::FacingMode
+EnumTraits<blink::mojom::FacingMode, media::VideoFacingMode>::ToMojom(
+ media::VideoFacingMode facing_mode) {
+ switch (facing_mode) {
+ case media::MEDIA_VIDEO_FACING_NONE:
+ return blink::mojom::FacingMode::NONE;
+ case media::MEDIA_VIDEO_FACING_USER:
+ return blink::mojom::FacingMode::USER;
+ case media::MEDIA_VIDEO_FACING_ENVIRONMENT:
+ return blink::mojom::FacingMode::ENVIRONMENT;
+ default:
+ break;
+ }
+ NOTREACHED();
+ return blink::mojom::FacingMode::NONE;
+}
+
+// static
+bool EnumTraits<blink::mojom::FacingMode, media::VideoFacingMode>::FromMojom(
+ blink::mojom::FacingMode input,
+ media::VideoFacingMode* out) {
+ switch (input) {
+ case blink::mojom::FacingMode::NONE:
+ *out = media::MEDIA_VIDEO_FACING_NONE;
+ return true;
+ case blink::mojom::FacingMode::USER:
+ *out = media::MEDIA_VIDEO_FACING_USER;
+ return true;
+ case blink::mojom::FacingMode::ENVIRONMENT:
+ *out = media::MEDIA_VIDEO_FACING_ENVIRONMENT;
+ return true;
+ default:
+ break;
+ }
+ NOTREACHED();
+ return false;
+}
+
+// static
bool StructTraits<
blink::mojom::MediaDeviceInfoDataView,
content::MediaDeviceInfo>::Read(blink::mojom::MediaDeviceInfoDataView input,
diff --git a/chromium/content/common/media/media_devices_typemap_traits.h b/chromium/content/common/media/media_devices_typemap_traits.h
index b30cc694de9..b15e8001f6f 100644
--- a/chromium/content/common/media/media_devices_typemap_traits.h
+++ b/chromium/content/common/media/media_devices_typemap_traits.h
@@ -6,7 +6,7 @@
#define CONTENT_COMMON_MEDIA_MEDIA_DEVICES_TYPEMAP_TRAITS_H_
#include "content/common/media/media_devices.h"
-#include "third_party/WebKit/public/platform/modules/mediastream/media_devices.mojom.h"
+#include "third_party/blink/public/platform/modules/mediastream/media_devices.mojom.h"
namespace mojo {
@@ -19,6 +19,14 @@ struct EnumTraits<blink::mojom::MediaDeviceType, content::MediaDeviceType> {
};
template <>
+struct EnumTraits<blink::mojom::FacingMode, media::VideoFacingMode> {
+ static blink::mojom::FacingMode ToMojom(media::VideoFacingMode facing_mode);
+
+ static bool FromMojom(blink::mojom::FacingMode input,
+ media::VideoFacingMode* out);
+};
+
+template <>
struct StructTraits<blink::mojom::MediaDeviceInfoDataView,
content::MediaDeviceInfo> {
static const std::string& device_id(const content::MediaDeviceInfo& info) {
diff --git a/chromium/content/common/media/media_player_delegate_messages.h b/chromium/content/common/media/media_player_delegate_messages.h
index 14824d1c052..7fd75b9430d 100644
--- a/chromium/content/common/media/media_player_delegate_messages.h
+++ b/chromium/content/common/media/media_player_delegate_messages.h
@@ -8,12 +8,15 @@
// IPC messages for interactions between the WebMediaPlayerDelegate in the
// renderer process and MediaWebContentsObserver in the browser process.
+// TODO(apacible): Mojoify MediaPlayerDelegateMsg, then remove this file.
+// https://crbug.com/824965
+
#include <stdint.h>
#include "content/common/content_export.h"
#include "ipc/ipc_message_macros.h"
#include "media/base/media_content_type.h"
-#include "third_party/WebKit/public/platform/WebFullscreenVideoStatus.h"
+#include "third_party/blink/public/platform/web_fullscreen_video_status.h"
#include "ui/gfx/ipc/geometry/gfx_param_traits.h"
#undef IPC_MESSAGE_EXPORT
@@ -83,4 +86,10 @@ IPC_MESSAGE_ROUTED2(MediaPlayerDelegateHostMsg_OnMediaSizeChanged,
int /* delegate_id, distinguishes instances */,
gfx::Size /* new size of video */)
+IPC_MESSAGE_ROUTED1(MediaPlayerDelegateHostMsg_OnPictureInPictureSourceChanged,
+ int /* delegate id */)
+
+IPC_MESSAGE_ROUTED1(MediaPlayerDelegateHostMsg_OnPictureInPictureModeEnded,
+ int /* delegate id */)
+
#endif // CONTENT_COMMON_MEDIA_MEDIA_PLAYER_DELEGATE_MESSAGES_H_
diff --git a/chromium/content/common/media/media_player_messages_android.h b/chromium/content/common/media/media_player_messages_android.h
index b9729bda437..a52e7f8e023 100644
--- a/chromium/content/common/media/media_player_messages_android.h
+++ b/chromium/content/common/media/media_player_messages_android.h
@@ -12,7 +12,7 @@
#include "ipc/ipc_message_macros.h"
#include "media/blink/renderer_media_player_interface.h"
#include "media/gpu/ipc/common/media_param_traits.h"
-#include "third_party/WebKit/public/platform/modules/remoteplayback/WebRemotePlaybackAvailability.h"
+#include "third_party/blink/public/platform/modules/remoteplayback/web_remote_playback_availability.h"
#include "ui/gfx/geometry/rect_f.h"
#include "url/gurl.h"
diff --git a/chromium/content/common/media/media_session.typemap b/chromium/content/common/media/media_session.typemap
index e31ffdddb12..e4b831bd5cb 100644
--- a/chromium/content/common/media/media_session.typemap
+++ b/chromium/content/common/media/media_session.typemap
@@ -2,7 +2,7 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
-mojom = "//third_party/WebKit/public/platform/modules/mediasession/media_session.mojom"
+mojom = "//third_party/blink/public/platform/modules/mediasession/media_session.mojom"
public_headers = [ "//content/public/common/media_metadata.h" ]
traits_headers = [ "//content/common/media/media_session_struct_traits.h" ]
type_mappings = [
diff --git a/chromium/content/common/media/media_session_struct_traits.h b/chromium/content/common/media/media_session_struct_traits.h
index 571f653277e..0cd7c66b1b5 100644
--- a/chromium/content/common/media/media_session_struct_traits.h
+++ b/chromium/content/common/media/media_session_struct_traits.h
@@ -5,7 +5,7 @@
#ifndef CONTENT_COMMON_MEDIA_MEDIA_SESSION_STRUCT_TRAITS_H_
#define CONTENT_COMMON_MEDIA_MEDIA_SESSION_STRUCT_TRAITS_H_
-#include "third_party/WebKit/public/platform/modules/mediasession/media_session.mojom.h"
+#include "third_party/blink/public/platform/modules/mediasession/media_session.mojom.h"
namespace mojo {
diff --git a/chromium/content/common/media/media_stream.mojom b/chromium/content/common/media/media_stream.mojom
index 8477e35009c..483ac0c1253 100644
--- a/chromium/content/common/media/media_stream.mojom
+++ b/chromium/content/common/media/media_stream.mojom
@@ -99,3 +99,13 @@ interface MediaStreamDispatcherHost {
// Tells the browser process that the stream has been started successfully.
OnStreamStarted(string label);
};
+
+// Browser-side interface that is used by the renderer process to notify the
+// addition or deletion of tracks.
+interface MediaStreamTrackMetricsHost {
+ // Adds the track with the specified information to the list of tracks.
+ AddTrack(uint64 id, bool is_audio, bool is_remote);
+
+ // Removes the track with the specified ID from the list of tracks.
+ RemoveTrack(uint64 id);
+};
diff --git a/chromium/content/common/media/media_stream_track_metrics_host_messages.h b/chromium/content/common/media/media_stream_track_metrics_host_messages.h
deleted file mode 100644
index 6f357094512..00000000000
--- a/chromium/content/common/media/media_stream_track_metrics_host_messages.h
+++ /dev/null
@@ -1,25 +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 CONTENT_COMMON_MEDIA_MEDIA_STREAM_TRACK_METRICS_HOST_MESSAGES_H_
-#define CONTENT_COMMON_MEDIA_MEDIA_STREAM_TRACK_METRICS_HOST_MESSAGES_H_
-
-#include <stdint.h>
-
-#include "base/values.h"
-#include "content/common/content_export.h"
-#include "ipc/ipc_message_macros.h"
-
-#undef IPC_MESSAGE_EXPORT
-#define IPC_MESSAGE_EXPORT CONTENT_EXPORT
-#define IPC_MESSAGE_START MediaStreamTrackMetricsHostMsgStart
-
-// Messages sent to MediaStreamTrackMetricsHost.
-IPC_MESSAGE_CONTROL3(MediaStreamTrackMetricsHost_AddTrack,
- uint64_t /* id */,
- bool /* is_audio */,
- bool /* is_remote */)
-IPC_MESSAGE_CONTROL1(MediaStreamTrackMetricsHost_RemoveTrack, uint64_t /* id */)
-
-#endif // CONTENT_COMMON_MEDIA_MEDIA_STREAM_TRACK_METRICS_HOST_MESSAGES_H_
diff --git a/chromium/content/common/media/peer_connection_tracker_messages.h b/chromium/content/common/media/peer_connection_tracker_messages.h
index cb9b5bd89f7..f5821e06ced 100644
--- a/chromium/content/common/media/peer_connection_tracker_messages.h
+++ b/chromium/content/common/media/peer_connection_tracker_messages.h
@@ -15,9 +15,19 @@
#define IPC_MESSAGE_START PeerConnectionTrackerMsgStart
IPC_STRUCT_BEGIN(PeerConnectionInfo)
+ // ID of the peer connection. Unique only within the renderer process.
IPC_STRUCT_MEMBER(int, lid)
+ // Textual ID of the peer connection. It corresponds to RTCPeerConnection.id.
+ // TODO(eladalon): Update comment or remove TODO, depending on whether
+ // RTCPeerconnection.id ends up being standardized or rejected.
+ // https://crbug.com/775415
+ IPC_STRUCT_MEMBER(std::string, peer_connection_id)
+ // Serialized version of RTCConfiguration.
IPC_STRUCT_MEMBER(std::string, rtc_configuration)
+ // Serialized version of blink::WebMediaConstraints.
IPC_STRUCT_MEMBER(std::string, constraints)
+ // The URL of the blink::WebLocalFrame within which this peer connection
+ // lives. Used for debugging purposes (displayed by WebRTC-Internals).
IPC_STRUCT_MEMBER(std::string, url)
IPC_STRUCT_END()
diff --git a/chromium/content/common/native_types.typemap b/chromium/content/common/native_types.typemap
index 8e2f44e0f18..780ba7aa63b 100644
--- a/chromium/content/common/native_types.typemap
+++ b/chromium/content/common/native_types.typemap
@@ -20,13 +20,13 @@ public_headers = [
"//content/public/common/renderer_preferences.h",
"//content/public/common/web_preferences.h",
"//net/base/network_change_notifier.h",
- "//third_party/WebKit/public/platform/WebGestureDevice.h",
- "//third_party/WebKit/public/platform/WebGestureEvent.h",
- "//third_party/WebKit/public/platform/WebInputEvent.h",
- "//third_party/WebKit/public/platform/WebMouseWheelEvent.h",
- "//third_party/WebKit/public/platform/WebPointerProperties.h",
- "//third_party/WebKit/public/platform/WebTouchPoint.h",
- "//third_party/WebKit/public/web/WebPopupType.h",
+ "//third_party/blink/public/platform/web_gesture_device.h",
+ "//third_party/blink/public/platform/web_gesture_event.h",
+ "//third_party/blink/public/platform/web_input_event.h",
+ "//third_party/blink/public/platform/web_mouse_wheel_event.h",
+ "//third_party/blink/public/platform/web_pointer_properties.h",
+ "//third_party/blink/public/platform/web_touch_point.h",
+ "//third_party/blink/public/web/web_popup_type.h",
"//ui/events/blink/did_overscroll_params.h",
"//ui/events/blink/web_input_event_traits.h",
"//ui/latency/ipc/latency_info_param_traits.h",
@@ -47,13 +47,13 @@ public_deps = [
# transitive allowance, so those targets' own public_deps aren't included in
# the set of implied dependencies.
"//cc/ipc",
- "//content/common:features",
+ "//content/common:buildflags",
"//media",
"//media/base/ipc",
"//net",
- "//ppapi/features",
+ "//ppapi/buildflags",
"//services/network/public/cpp",
- "//third_party/WebKit/public/common",
+ "//third_party/blink/public/common",
"//ui/accessibility",
"//ui/base/ime:text_input_types",
"//ui/gfx/ipc",
diff --git a/chromium/content/common/native_types_mac.typemap b/chromium/content/common/native_types_mac.typemap
index 8790e5c7a73..c162fc14e21 100644
--- a/chromium/content/common/native_types_mac.typemap
+++ b/chromium/content/common/native_types_mac.typemap
@@ -5,8 +5,8 @@
mojom = "//content/common/native_types.mojom"
os_whitelist = [ "mac" ]
public_headers = [
- "//third_party/WebKit/public/platform/WebScrollbarButtonsPlacement.h",
- "//third_party/WebKit/public/platform/mac/WebScrollbarTheme.h",
+ "//third_party/blink/public/platform/web_scrollbar_buttons_placement.h",
+ "//third_party/blink/public/platform/mac/web_scrollbar_theme.h",
]
traits_headers = [ "//content/common/view_messages.h" ]
deps = [
@@ -20,7 +20,7 @@ deps = [
"//media",
"//media/base/ipc",
"//net",
- "//third_party/WebKit/public:blink_headers",
+ "//third_party/blink/public:blink_headers",
"//ui/accessibility",
"//ui/base/ime:text_input_types",
"//ui/gfx/ipc",
diff --git a/chromium/content/common/navigation_params.h b/chromium/content/common/navigation_params.h
index 7cf25dc6298..806969a8e25 100644
--- a/chromium/content/common/navigation_params.h
+++ b/chromium/content/common/navigation_params.h
@@ -26,7 +26,7 @@
#include "net/url_request/redirect_info.h"
#include "services/network/public/cpp/resource_request_body.h"
#include "services/network/public/cpp/resource_response_info.h"
-#include "third_party/WebKit/public/platform/WebMixedContentContextType.h"
+#include "third_party/blink/public/platform/web_mixed_content_context_type.h"
#include "ui/base/page_transition_types.h"
#include "url/gurl.h"
#include "url/origin.h"
@@ -268,6 +268,11 @@ struct CONTENT_EXPORT RequestNavigationParams {
int current_history_list_offset = -1;
int current_history_list_length = 0;
+ // Indicates that the tab was previously discarded.
+ // wasDiscarded is exposed on Document after discard, see:
+ // https://github.com/WICG/web-lifecycle
+ bool was_discarded = false;
+
// Indicates whether the navigation is to a view-source:// scheme or not.
// It is a separate boolean as the view-source scheme is stripped from the
// URL before it is sent to the renderer process and the RenderFrame needs
diff --git a/chromium/content/common/navigation_params.mojom b/chromium/content/common/navigation_params.mojom
index 1a2360cf334..d64b842a477 100644
--- a/chromium/content/common/navigation_params.mojom
+++ b/chromium/content/common/navigation_params.mojom
@@ -4,8 +4,8 @@
module content.mojom;
-import "mojo/common/values.mojom";
-import "third_party/WebKit/public/platform/modules/fetch/fetch_api_request.mojom";
+import "mojo/public/mojom/base/values.mojom";
+import "third_party/blink/public/platform/modules/fetch/fetch_api_request.mojom";
import "url/mojom/origin.mojom";
import "url/mojom/url.mojom";
@@ -62,6 +62,6 @@ struct BeginNavigationParams {
// initiator information in DevTools protocol format. See
// https://chromedevtools.github.io/devtools-protocol/tot/Network#type-Initiator
// for details.
- mojo.common.mojom.DictionaryValue? devtools_initiator;
+ mojo_base.mojom.DictionaryValue? devtools_initiator;
};
diff --git a/chromium/content/common/navigation_params.typemap b/chromium/content/common/navigation_params.typemap
index 9bb4cdd679b..036a10c4a90 100644
--- a/chromium/content/common/navigation_params.typemap
+++ b/chromium/content/common/navigation_params.typemap
@@ -4,9 +4,11 @@
mojom = "//content/common/navigation_params.mojom"
public_headers =
- [ "//third_party/WebKit/public/platform/WebMixedContentContextType.h" ]
+ [ "//third_party/blink/public/platform/web_mixed_content_context_type.h" ]
traits_headers = [ "//content/common/resource_messages.h" ]
deps = [
"//content:export",
]
-type_mappings = [ "content.mojom.MixedContentContextType=::blink::WebMixedContentContextType" ]
+type_mappings = [
+ "content.mojom.MixedContentContextType=::blink::WebMixedContentContextType",
+]
diff --git a/chromium/content/common/net/url_fetcher.cc b/chromium/content/common/net/url_fetcher.cc
index ab75940d575..9af15ee5ddb 100644
--- a/chromium/content/common/net/url_fetcher.cc
+++ b/chromium/content/common/net/url_fetcher.cc
@@ -5,7 +5,6 @@
#include "content/public/common/url_fetcher.h"
#include "base/bind.h"
-#include "base/memory/ptr_util.h"
#include "content/common/net/url_request_user_data.h"
#include "net/url_request/url_fetcher.h"
diff --git a/chromium/content/common/notifications/DEPS b/chromium/content/common/notifications/DEPS
index b0398690d37..3855191b858 100644
--- a/chromium/content/common/notifications/DEPS
+++ b/chromium/content/common/notifications/DEPS
@@ -1,3 +1,3 @@
include_rules = [
- "+third_party/WebKit/public/platform/modules/notifications/notification.mojom.h",
+ "+third_party/blink/public/platform/modules/notifications/notification.mojom.h",
]
diff --git a/chromium/content/common/notifications/notification_struct_traits.h b/chromium/content/common/notifications/notification_struct_traits.h
index 83fe6a8a40d..b4ee6075e5f 100644
--- a/chromium/content/common/notifications/notification_struct_traits.h
+++ b/chromium/content/common/notifications/notification_struct_traits.h
@@ -9,11 +9,10 @@
#include "base/strings/string16.h"
#include "content/common/content_export.h"
#include "content/public/common/platform_notification_data.h"
-#include "mojo/common/common_custom_types_struct_traits.h"
#include "mojo/public/cpp/base/string16_mojom_traits.h"
#include "mojo/public/cpp/bindings/struct_traits.h"
#include "skia/public/interfaces/bitmap_skbitmap_struct_traits.h"
-#include "third_party/WebKit/public/platform/modules/notifications/notification.mojom.h"
+#include "third_party/blink/public/platform/modules/notifications/notification.mojom.h"
#include "url/gurl.h"
#include "url/mojom/url_gurl_mojom_traits.h"
diff --git a/chromium/content/common/notifications/notification_struct_traits_unittest.cc b/chromium/content/common/notifications/notification_struct_traits_unittest.cc
index b37e99497ae..1ecf6106af8 100644
--- a/chromium/content/common/notifications/notification_struct_traits_unittest.cc
+++ b/chromium/content/common/notifications/notification_struct_traits_unittest.cc
@@ -13,7 +13,7 @@
#include "content/public/common/platform_notification_data.h"
#include "mojo/public/cpp/test_support/test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/modules/notifications/notification.mojom.h"
+#include "third_party/blink/public/platform/modules/notifications/notification.mojom.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "url/gurl.h"
diff --git a/chromium/content/common/notifications/notification_types.typemap b/chromium/content/common/notifications/notification_types.typemap
index 5ab8b9f13fb..f96161612fc 100644
--- a/chromium/content/common/notifications/notification_types.typemap
+++ b/chromium/content/common/notifications/notification_types.typemap
@@ -2,7 +2,7 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
-mojom = "//third_party/WebKit/public/platform/modules/notifications/notification.mojom"
+mojom = "//third_party/blink/public/platform/modules/notifications/notification.mojom"
public_headers = [
"//content/public/common/notification_resources.h",
"//content/public/common/platform_notification_data.h",
@@ -11,7 +11,7 @@ traits_headers =
[ "//content/common/notifications/notification_struct_traits.h" ]
deps = [
"//mojo/public/cpp/bindings",
- "//third_party/WebKit/public:blink_headers",
+ "//third_party/blink/public:blink_headers",
]
type_mappings = [
"blink.mojom.NotificationData=content::PlatformNotificationData",
diff --git a/chromium/content/common/origin_trials/OWNERS b/chromium/content/common/origin_trials/OWNERS
index ea471dac3a6..47b509bfe3e 100644
--- a/chromium/content/common/origin_trials/OWNERS
+++ b/chromium/content/common/origin_trials/OWNERS
@@ -1,8 +1,8 @@
# This file also covers ownership of the following directories:
# //chrome/common/origin_trials/
# //content/renderer/origin_trials/
-# //third_party/WebKit/common/origin_trials/
-# //third_party/WebKit/public/common/origin_trials/
+# //third_party/blink/common/origin_trials/
+# //third_party/blink/public/common/origin_trials/
# //tools/origin_trials/
chasej@chromium.org
diff --git a/chromium/content/common/origin_trials/trial_policy_impl.cc b/chromium/content/common/origin_trials/trial_policy_impl.cc
index 41f9bbfbe1c..e85ee25b245 100644
--- a/chromium/content/common/origin_trials/trial_policy_impl.cc
+++ b/chromium/content/common/origin_trials/trial_policy_impl.cc
@@ -9,7 +9,7 @@
#include "content/public/common/content_features.h"
#include "content/public/common/origin_trial_policy.h"
#include "content/public/common/origin_util.h"
-#include "third_party/WebKit/public/common/origin_trials/trial_token_validator.h"
+#include "third_party/blink/public/common/origin_trials/trial_token_validator.h"
namespace content {
diff --git a/chromium/content/common/origin_trials/trial_policy_impl.h b/chromium/content/common/origin_trials/trial_policy_impl.h
index 603a7dc30b4..370c5067b31 100644
--- a/chromium/content/common/origin_trials/trial_policy_impl.h
+++ b/chromium/content/common/origin_trials/trial_policy_impl.h
@@ -7,7 +7,7 @@
#include "base/strings/string_piece.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/common/origin_trials/trial_policy.h"
+#include "third_party/blink/public/common/origin_trials/trial_policy.h"
namespace blink {
class TrialTokenValidator;
diff --git a/chromium/content/common/page_messages.h b/chromium/content/common/page_messages.h
index 423a9f1282e..4e8cf807539 100644
--- a/chromium/content/common/page_messages.h
+++ b/chromium/content/common/page_messages.h
@@ -46,10 +46,18 @@ IPC_MESSAGE_ROUTED2(PageMsg_SetHistoryOffsetAndLength,
IPC_MESSAGE_ROUTED1(PageMsg_AudioStateChanged, bool /* is_audio_playing */)
+// Pause and unpause active tasks regarding deferLoading, active javascripts,
+// timer, scheduled task through |blink::WebFrameScheduler|.
+IPC_MESSAGE_ROUTED1(PageMsg_PausePageScheduledTasks, bool /* paused */)
+
// Sent to OOPIF renderers when the main frame's ScreenInfo changes.
IPC_MESSAGE_ROUTED1(PageMsg_UpdateScreenInfo,
content::ScreenInfo /* screen_info */)
+// Sent to all renderers, instructing them to freeze all frames that belongs to
+// this page.
+IPC_MESSAGE_ROUTED0(PageMsg_FreezePage)
+
// -----------------------------------------------------------------------------
// Messages sent from the renderer to the browser.
diff --git a/chromium/content/common/page_state.mojom b/chromium/content/common/page_state.mojom
index 830aae044b8..c1a006a3a5f 100644
--- a/chromium/content/common/page_state.mojom
+++ b/chromium/content/common/page_state.mojom
@@ -5,8 +5,8 @@
module content.history.mojom;
import "mojo/public/mojom/base/string16.mojom";
-import "mojo/common/time.mojom";
-import "third_party/WebKit/public/platform/referrer.mojom";
+import "mojo/public/mojom/base/time.mojom";
+import "third_party/blink/public/platform/referrer.mojom";
import "url/mojom/url.mojom";
import "ui/gfx/geometry/mojo/geometry.mojom";
@@ -37,7 +37,7 @@ struct DEPRECATED_FileSystemFile {
url.mojom.Url filesystem_url@0;
uint64 offset@1;
uint64 length@2;
- mojo.common.mojom.Time modification_time@3;
+ mojo_base.mojom.Time modification_time@3;
};
// Next Ordinal: 4
@@ -45,7 +45,7 @@ struct File {
mojo_base.mojom.String16 path@0;
uint64 offset@1;
uint64 length@2;
- mojo.common.mojom.Time modification_time@3;
+ mojo_base.mojom.Time modification_time@3;
};
// Next Ordinal: 4
diff --git a/chromium/content/common/page_state_serialization.cc b/chromium/content/common/page_state_serialization.cc
index 5af4a897578..4231b01474a 100644
--- a/chromium/content/common/page_state_serialization.cc
+++ b/chromium/content/common/page_state_serialization.cc
@@ -16,10 +16,10 @@
#include "content/common/unique_name_helper.h"
#include "content/public/common/referrer_struct_traits.h"
#include "ipc/ipc_message_utils.h"
-#include "mojo/common/time_struct_traits.h"
#include "mojo/public/cpp/base/string16_mojom_traits.h"
+#include "mojo/public/cpp/base/time_mojom_traits.h"
#include "services/network/public/cpp/resource_request_body.h"
-#include "third_party/WebKit/public/platform/WebHistoryScrollRestorationType.h"
+#include "third_party/blink/public/platform/web_history_scroll_restoration_type.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/gfx/geometry/mojo/geometry_struct_traits.h"
@@ -706,8 +706,11 @@ void WriteResourceRequestBody(const network::ResourceRequestBody& request_body,
case network::DataElement::TYPE_BLOB:
data_element->set_blob_uuid(element.blob_uuid());
break;
- case network::DataElement::TYPE_RAW_FILE:
case network::DataElement::TYPE_DATA_PIPE:
+ NOTIMPLEMENTED();
+ break;
+ case network::DataElement::TYPE_RAW_FILE:
+ case network::DataElement::TYPE_CHUNKED_DATA_PIPE:
case network::DataElement::TYPE_UNKNOWN:
NOTREACHED();
continue;
diff --git a/chromium/content/common/page_state_serialization.h b/chromium/content/common/page_state_serialization.h
index 29a43617dc9..729550b7852 100644
--- a/chromium/content/common/page_state_serialization.h
+++ b/chromium/content/common/page_state_serialization.h
@@ -15,9 +15,9 @@
#include "build/build_config.h"
#include "content/common/content_export.h"
#include "services/network/public/cpp/resource_request_body.h"
-#include "third_party/WebKit/public/platform/WebHTTPBody.h"
-#include "third_party/WebKit/public/platform/WebHistoryScrollRestorationType.h"
-#include "third_party/WebKit/public/platform/WebReferrerPolicy.h"
+#include "third_party/blink/public/platform/web_history_scroll_restoration_type.h"
+#include "third_party/blink/public/platform/web_http_body.h"
+#include "third_party/blink/public/platform/web_referrer_policy.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/point_f.h"
#include "url/gurl.h"
diff --git a/chromium/content/common/pepper_file_util.h b/chromium/content/common/pepper_file_util.h
index 48afdeb7ed7..bded20a9857 100644
--- a/chromium/content/common/pepper_file_util.h
+++ b/chromium/content/common/pepper_file_util.h
@@ -7,8 +7,8 @@
#include "base/files/file.h"
#include "base/sync_socket.h"
+#include "ppapi/buildflags/buildflags.h"
#include "ppapi/c/pp_file_info.h"
-#include "ppapi/features/features.h"
#include "storage/common/fileapi/file_system_types.h"
#if !BUILDFLAG(ENABLE_PLUGINS)
diff --git a/chromium/content/common/pepper_plugin_list.h b/chromium/content/common/pepper_plugin_list.h
index fdf569a42f5..44f3341631b 100644
--- a/chromium/content/common/pepper_plugin_list.h
+++ b/chromium/content/common/pepper_plugin_list.h
@@ -7,7 +7,7 @@
#include <vector>
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#if !BUILDFLAG(ENABLE_PLUGINS)
#error "Plugins should be enabled"
diff --git a/chromium/content/common/pepper_renderer_instance_data.h b/chromium/content/common/pepper_renderer_instance_data.h
index a3445ecee73..23dc106317a 100644
--- a/chromium/content/common/pepper_renderer_instance_data.h
+++ b/chromium/content/common/pepper_renderer_instance_data.h
@@ -5,7 +5,7 @@
#ifndef CONTENT_COMMON_PEPPER_RENDERER_INSTANCE_DATA_H_
#define CONTENT_COMMON_PEPPER_RENDERER_INSTANCE_DATA_H_
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#include "url/gurl.h"
#if !BUILDFLAG(ENABLE_PLUGINS)
diff --git a/chromium/content/common/plugin_list.cc b/chromium/content/common/plugin_list.cc
index 21c69a6d36a..bc350650084 100644
--- a/chromium/content/common/plugin_list.cc
+++ b/chromium/content/common/plugin_list.cc
@@ -114,7 +114,7 @@ void PluginList::LoadPlugins() {
will_load_callback = will_load_plugins_callback_;
}
if (!will_load_callback.is_null())
- will_load_callback.Run();
+ std::move(will_load_callback).Run();
std::vector<base::FilePath> plugin_paths;
GetPluginPathsToLoad(&plugin_paths);
diff --git a/chromium/content/common/plugin_list.h b/chromium/content/common/plugin_list.h
index 0504985133c..59aa05d47c4 100644
--- a/chromium/content/common/plugin_list.h
+++ b/chromium/content/common/plugin_list.h
@@ -18,7 +18,7 @@
#include "build/build_config.h"
#include "content/common/content_export.h"
#include "content/public/common/webplugininfo.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#if !BUILDFLAG(ENABLE_PLUGINS)
#error "Plugins should be enabled"
diff --git a/chromium/content/common/presentation/presentation.typemap b/chromium/content/common/presentation/presentation.typemap
index 33ac3db53a6..e6d6a8c0f1e 100644
--- a/chromium/content/common/presentation/presentation.typemap
+++ b/chromium/content/common/presentation/presentation.typemap
@@ -2,7 +2,7 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
-mojom = "//third_party/WebKit/public/platform/modules/presentation/presentation.mojom"
+mojom = "//third_party/blink/public/platform/modules/presentation/presentation.mojom"
public_headers = [
"//content/public/common/presentation_connection_message.h",
"//content/public/common/presentation_info.h",
diff --git a/chromium/content/common/presentation/presentation_struct_traits.h b/chromium/content/common/presentation/presentation_struct_traits.h
index 08906ba2f02..13d406efedf 100644
--- a/chromium/content/common/presentation/presentation_struct_traits.h
+++ b/chromium/content/common/presentation/presentation_struct_traits.h
@@ -13,7 +13,7 @@
#include "base/strings/string_util.h"
#include "content/public/common/presentation_connection_message.h"
#include "content/public/common/presentation_info.h"
-#include "third_party/WebKit/public/platform/modules/presentation/presentation.mojom.h"
+#include "third_party/blink/public/platform/modules/presentation/presentation.mojom.h"
#include "url/mojom/url.mojom.h"
namespace mojo {
diff --git a/chromium/content/common/push_messaging.mojom b/chromium/content/common/push_messaging.mojom
index 6d9b3f764ae..7966268f95e 100644
--- a/chromium/content/common/push_messaging.mojom
+++ b/chromium/content/common/push_messaging.mojom
@@ -23,7 +23,6 @@ enum PushErrorType {
NOT_FOUND = 4,
NOT_SUPPORTED = 5,
INVALID_STATE = 6,
- LAST = INVALID_STATE
};
interface PushMessaging {
diff --git a/chromium/content/common/push_messaging.typemap b/chromium/content/common/push_messaging.typemap
index 698dc1cb77c..62eaf37df81 100644
--- a/chromium/content/common/push_messaging.typemap
+++ b/chromium/content/common/push_messaging.typemap
@@ -5,7 +5,7 @@
mojom = "//content/common/push_messaging.mojom"
public_headers = [
"//content/public/common/push_subscription_options.h",
- "//third_party/WebKit/public/platform/modules/push_messaging/WebPushError.h",
+ "//third_party/blink/public/platform/modules/push_messaging/web_push_error.h",
]
traits_headers = [ "//content/common/push_messaging_param_traits.h" ]
sources = [
@@ -15,7 +15,7 @@ deps = [
"//content:export",
]
public_deps = [
- "//third_party/WebKit/public:blink_headers",
+ "//third_party/blink/public:blink_headers",
]
type_mappings = [
"content.mojom.PushErrorType=blink::WebPushError::ErrorType",
diff --git a/chromium/content/common/push_messaging_param_traits.cc b/chromium/content/common/push_messaging_param_traits.cc
index d5ae8f5a42b..c28c61778dd 100644
--- a/chromium/content/common/push_messaging_param_traits.cc
+++ b/chromium/content/common/push_messaging_param_traits.cc
@@ -46,8 +46,8 @@ static_assert(blink::WebPushError::ErrorType::kErrorTypeInvalidState ==
static_assert(blink::WebPushError::ErrorType::kErrorTypeLast ==
static_cast<blink::WebPushError::ErrorType>(
- content::mojom::PushErrorType::LAST),
- "PushErrorType enums must match, LAST");
+ content::mojom::PushErrorType::kMaxValue),
+ "PushErrorType enums must match, kMaxValue");
// static
bool StructTraits<content::mojom::PushSubscriptionOptionsDataView,
diff --git a/chromium/content/common/render_frame_metadata.mojom b/chromium/content/common/render_frame_metadata.mojom
index 787a3b7ce88..a2283f9d152 100644
--- a/chromium/content/common/render_frame_metadata.mojom
+++ b/chromium/content/common/render_frame_metadata.mojom
@@ -4,11 +4,27 @@
module content.mojom;
+import "services/viz/public/interfaces/compositing/selection.mojom";
import "ui/gfx/geometry/mojo/geometry.mojom";
// See components/viz/service/quads/render_frame_metadata.h
struct RenderFrameMetadata {
- gfx.mojom.Vector2dF root_scroll_offset;
+ // The background color of a CompositorFrame. It can be used for filling the
+ // content area if the primary surface is unavailable and fallback is not
+ // specified.
+ uint32 root_background_color;
+
+ // Scroll offset of the root layer. This optional parameter is only sent
+ // during tests.
+ gfx.mojom.Vector2dF? root_scroll_offset;
+
+ // Indicates whether the scroll offset of the root layer is at top, i.e.,
+ // whether scroll_offset.y() == 0.
+ bool is_scroll_offset_at_top;
+
+ // Selection region relative to the current viewport. If the selection is
+ // empty or otherwise unused, the bound types will indicate such.
+ viz.mojom.Selection selection;
};
// This interface is provided by the renderer. It can optionally enable
@@ -24,8 +40,8 @@ interface RenderFrameMetadataObserver {
// RenderFrameMetadataObserver::ReportAllFrameSubmissionsForTesting.
interface RenderFrameMetadataObserverClient {
// Notified when RenderFrameMetadata has changed.
- OnRenderFrameMetadataChanged(RenderFrameMetadata metadata);
+ OnRenderFrameMetadataChanged(uint32 frame_token, RenderFrameMetadata metadata);
// Notified on all frame submissions.
- OnFrameSubmissionForTesting();
+ OnFrameSubmissionForTesting(uint32 frame_token);
};
diff --git a/chromium/content/common/render_frame_metadata_struct_traits.cc b/chromium/content/common/render_frame_metadata_struct_traits.cc
index c8c2719f2be..e6129ebf056 100644
--- a/chromium/content/common/render_frame_metadata_struct_traits.cc
+++ b/chromium/content/common/render_frame_metadata_struct_traits.cc
@@ -4,7 +4,9 @@
#include "content/common/render_frame_metadata_struct_traits.h"
+#include "services/viz/public/cpp/compositing/selection_struct_traits.h"
#include "ui/gfx/geometry/mojo/geometry_struct_traits.h"
+#include "ui/gfx/mojo/selection_bound_struct_traits.h"
namespace mojo {
@@ -13,7 +15,10 @@ bool StructTraits<content::mojom::RenderFrameMetadataDataView,
cc::RenderFrameMetadata>::
Read(content::mojom::RenderFrameMetadataDataView data,
cc::RenderFrameMetadata* out) {
- return data.ReadRootScrollOffset(&out->root_scroll_offset);
+ out->root_background_color = data.root_background_color();
+ out->is_scroll_offset_at_top = data.is_scroll_offset_at_top();
+ return data.ReadRootScrollOffset(&out->root_scroll_offset) &&
+ data.ReadSelection(&out->selection);
}
} // namespace mojo
diff --git a/chromium/content/common/render_frame_metadata_struct_traits.h b/chromium/content/common/render_frame_metadata_struct_traits.h
index d19afa008c0..de13e7a88c9 100644
--- a/chromium/content/common/render_frame_metadata_struct_traits.h
+++ b/chromium/content/common/render_frame_metadata_struct_traits.h
@@ -5,6 +5,7 @@
#ifndef CONTENT_COMMON_RENDER_FRAME_METADATA_STRUCT_TRAITS_H_
#define CONTENT_COMMON_RENDER_FRAME_METADATA_STRUCT_TRAITS_H_
+#include "base/optional.h"
#include "cc/trees/render_frame_metadata.h"
#include "content/common/render_frame_metadata.mojom-shared.h"
@@ -13,11 +14,25 @@ namespace mojo {
template <>
struct StructTraits<content::mojom::RenderFrameMetadataDataView,
cc::RenderFrameMetadata> {
- static gfx::Vector2dF root_scroll_offset(
+ static SkColor root_background_color(
+ const cc::RenderFrameMetadata& metadata) {
+ return metadata.root_background_color;
+ }
+
+ static base::Optional<gfx::Vector2dF> root_scroll_offset(
const cc::RenderFrameMetadata& metadata) {
return metadata.root_scroll_offset;
}
+ static bool is_scroll_offset_at_top(const cc::RenderFrameMetadata& metadata) {
+ return metadata.is_scroll_offset_at_top;
+ }
+
+ static const viz::Selection<gfx::SelectionBound>& selection(
+ const cc::RenderFrameMetadata& metadata) {
+ return metadata.selection;
+ }
+
static bool Read(content::mojom::RenderFrameMetadataDataView data,
cc::RenderFrameMetadata* out);
};
diff --git a/chromium/content/common/render_message_filter.mojom b/chromium/content/common/render_message_filter.mojom
index 52092d89fab..15d97f9b140 100644
--- a/chromium/content/common/render_message_filter.mojom
+++ b/chromium/content/common/render_message_filter.mojom
@@ -7,9 +7,8 @@ module content.mojom;
import "content/common/input/input_handler.mojom";
import "content/common/native_types.mojom";
import "content/common/widget.mojom";
-import "mojo/common/thread_priority.mojom";
-import "mojo/public/mojom/base/string16.mojom";
-import "mojo/common/time.mojom";
+import "mojo/public/mojom/base/thread_priority.mojom";
+import "mojo/public/mojom/base/time.mojom";
import "url/mojom/origin.mojom";
import "url/mojom/url.mojom";
@@ -29,12 +28,12 @@ interface RenderMessageFilter {
// Requests that the browser cache |data| associated with |url| and |expected_response_time|.
// TODO(https://crbug.com/779444): Verify or remove |url| and |cache_storage_origin|.
DidGenerateCacheableMetadata(url.mojom.Url url,
- mojo.common.mojom.Time expected_response_time,
+ mojo_base.mojom.Time expected_response_time,
array<uint8> data);
// Requests that the browser cache |data| for the specified CacheStorage entry.
DidGenerateCacheableMetadataInCacheStorage(
- url.mojom.Url url, mojo.common.mojom.Time expected_response_time,
+ url.mojom.Url url, mojo_base.mojom.Time expected_response_time,
array<uint8> data, url.mojom.Origin cache_storage_origin,
string cache_storage_cache_name);
@@ -42,12 +41,7 @@ interface RenderMessageFilter {
[Sync] HasGpuProcess() => (bool has_gpu_process);
// Asks the browser to change the priority of thread.
- // (Linux only, NOP on other platforms.)
+ [EnableIf=supports_thread_priorities]
SetThreadPriority(int32 platform_thread_id,
- mojo.common.mojom.ThreadPriority thread_priority);
-
- // Request that the browser load a font into shared memory for us.
- // TODO(https://crbug.com/676224). Only used for MacOS.
- [Sync] LoadFont(mojo_base.mojom.String16 font_name, float font_point_size)
- => (uint32 buffer_size, handle<shared_buffer>? font_data, uint32 font_id);
+ mojo_base.mojom.ThreadPriority thread_priority);
};
diff --git a/chromium/content/common/render_widget_window_tree_client_factory.mojom b/chromium/content/common/render_widget_window_tree_client_factory.mojom
index 22cc65deeec..0c1ae21b5cc 100644
--- a/chromium/content/common/render_widget_window_tree_client_factory.mojom
+++ b/chromium/content/common/render_widget_window_tree_client_factory.mojom
@@ -4,14 +4,14 @@
module content.mojom;
-import "mojo/common/unguessable_token.mojom";
+import "mojo/public/mojom/base/unguessable_token.mojom";
import "services/ui/public/interfaces/window_tree.mojom";
interface RenderWidgetWindowTreeClient {
// Asks the renderer to create a Window for the frame with the routing id
// |routing_id| and embeds the WindowTreeClient that was previously supplied
// to ScheduleEmbed().
- Embed(uint32 frame_routing_id, mojo.common.mojom.UnguessableToken token);
+ Embed(uint32 frame_routing_id, mojo_base.mojom.UnguessableToken token);
// Called when a render frame has been destroyed. This is sent via mojom
// to handle to ensure there aren't race conditions because of message order
diff --git a/chromium/content/common/renderer.mojom b/chromium/content/common/renderer.mojom
index 0410f53a8ec..05886a72fce 100644
--- a/chromium/content/common/renderer.mojom
+++ b/chromium/content/common/renderer.mojom
@@ -7,8 +7,8 @@ module content.mojom;
import "content/common/native_types.mojom";
import "content/common/service_worker/embedded_worker.mojom";
import "ipc/constants.mojom";
-import "mojo/common/time.mojom";
-import "mojo/common/unguessable_token.mojom";
+import "mojo/public/mojom/base/time.mojom";
+import "mojo/public/mojom/base/unguessable_token.mojom";
import "services/network/public/mojom/network_types.mojom";
import "services/service_manager/public/mojom/interface_provider.mojom";
import "services/service_manager/public/mojom/service.mojom";
@@ -61,7 +61,7 @@ struct CreateViewParams {
// attribute them to the context frame.
// |devtools_main_frame_token| is only defined by the browser and is never
// sent back from the renderer in the control calls.
- mojo.common.mojom.UnguessableToken devtools_main_frame_token;
+ mojo_base.mojom.UnguessableToken devtools_main_frame_token;
// The ID of the proxy object for the main frame in this view. It is only
// used if |swapped_out| is true.
@@ -148,7 +148,7 @@ struct CreateFrameParams {
// attribute them to the context frame.
// |devtools_frame_token| is only defined by the browser and is never
// sent back from the renderer in the control calls.
- mojo.common.mojom.UnguessableToken devtools_frame_token;
+ mojo_base.mojom.UnguessableToken devtools_frame_token;
// When the new frame has a parent, |frame_owner_properties| holds the
// properties of the HTMLFrameOwnerElement from the parent process.
@@ -210,7 +210,7 @@ interface Renderer {
CreateFrameProxy(int32 routing_id, int32 render_view_routing_id,
int32 opener_routing_id, int32 parent_routing_id,
FrameReplicationState replication_state,
- mojo.common.mojom.UnguessableToken devtools_frame_token);
+ mojo_base.mojom.UnguessableToken devtools_frame_token);
// Tells the renderer that the network type has changed so that
// navigator.onLine and navigator.connection can be updated.
@@ -226,8 +226,8 @@ interface Renderer {
// unavailable, it will be set to net::nqe::internal::INVALID_RTT_THROUGHPUT.
OnNetworkQualityChanged(
network.mojom.EffectiveConnectionType effective_connection_type,
- mojo.common.mojom.TimeDelta http_rtt,
- mojo.common.mojom.TimeDelta transport_rtt,
+ mojo_base.mojom.TimeDelta http_rtt,
+ mojo_base.mojom.TimeDelta transport_rtt,
double bandwidth_kbps);
// Tells the renderer to suspend/resume the webkit timers. Only for use on
@@ -248,7 +248,6 @@ interface Renderer {
// Tells the renderer process to enter or leave background mode.
- // TODO(crbug:676224) Make this conditional on IPC_MESSAGE_LOG_ENABLED.
SetProcessBackgrounded(bool background);
// Tells the scheduler about "keep-alive" state which can be due to:
diff --git a/chromium/content/common/resize_params.cc b/chromium/content/common/resize_params.cc
index b30dfc37bd9..5e1fd102f66 100644
--- a/chromium/content/common/resize_params.cc
+++ b/chromium/content/common/resize_params.cc
@@ -7,7 +7,9 @@
namespace content {
ResizeParams::ResizeParams()
- : browser_controls_shrink_blink_size(false),
+ : auto_resize_enabled(false),
+ auto_resize_sequence_number(0u),
+ browser_controls_shrink_blink_size(false),
scroll_focused_node_into_view(false),
top_controls_height(0.f),
bottom_controls_height(0.f),
diff --git a/chromium/content/common/resize_params.h b/chromium/content/common/resize_params.h
index 2bea4764eb5..51c472dd522 100644
--- a/chromium/content/common/resize_params.h
+++ b/chromium/content/common/resize_params.h
@@ -9,7 +9,7 @@
#include "components/viz/common/surfaces/local_surface_id.h"
#include "content/common/content_export.h"
#include "content/public/common/screen_info.h"
-#include "third_party/WebKit/public/platform/WebDisplayMode.h"
+#include "third_party/blink/public/platform/web_display_mode.h"
#include "ui/gfx/geometry/size.h"
namespace content {
@@ -22,6 +22,20 @@ struct CONTENT_EXPORT ResizeParams {
// Information about the screen (dpi, depth, etc..).
ScreenInfo screen_info;
+ // Whether or not blink should be in auto-resize mode.
+ bool auto_resize_enabled;
+
+ // The minimum size for Blink if auto-resize is enabled.
+ gfx::Size min_size_for_auto_resize;
+
+ // The maximum size for Blink if auto-resize is enabled.
+ gfx::Size max_size_for_auto_resize;
+
+ // This variable is increased after each auto-resize. If the
+ // renderer receives a ResizeParams with stale auto_resize_seqence_number,
+ // then the resize request is dropped.
+ uint64_t auto_resize_sequence_number;
+
// The size for the widget in DIPs.
gfx::Size new_size;
diff --git a/chromium/content/common/resource_messages.h b/chromium/content/common/resource_messages.h
index ebc2ab1211c..edcf425d7ea 100644
--- a/chromium/content/common/resource_messages.h
+++ b/chromium/content/common/resource_messages.h
@@ -22,7 +22,7 @@
#include "net/http/http_response_info.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "services/network/public/cpp/network_param_ipc_traits.h"
-#include "third_party/WebKit/public/platform/WebMixedContentContextType.h"
+#include "third_party/blink/public/platform/web_mixed_content_context_type.h"
#ifndef INTERNAL_CONTENT_COMMON_RESOURCE_MESSAGES_H_
#define INTERNAL_CONTENT_COMMON_RESOURCE_MESSAGES_H_
diff --git a/chromium/content/common/sandbox_init_mac.cc b/chromium/content/common/sandbox_init_mac.cc
index eaf4ffaac1a..583e283f276 100644
--- a/chromium/content/common/sandbox_init_mac.cc
+++ b/chromium/content/common/sandbox_init_mac.cc
@@ -4,7 +4,7 @@
#include "content/public/common/sandbox_init.h"
-#include "base/callback.h"
+#include "base/bind.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/logging.h"
@@ -13,6 +13,7 @@
#include "gpu/config/gpu_info.h"
#include "gpu/config/gpu_info_collector.h"
#include "gpu/config/gpu_switches.h"
+#include "gpu/config/gpu_switching.h"
#include "gpu/config/gpu_util.h"
#include "gpu/ipc/common/gpu_preferences_util.h"
#include "media/gpu/vt_video_decode_accelerator_mac.h"
@@ -56,6 +57,10 @@ base::OnceClosure MaybeWrapWithGPUSandboxHook(
gpu_preferences.log_gpu_control_list_decisions, command_line,
nullptr);
gpu::CacheGpuFeatureInfo(gpu_feature_info);
+ if (gpu::SwitchableGPUsSupported(gpu_info, *command_line)) {
+ gpu::InitializeSwitchableGPUs(
+ gpu_feature_info.enabled_gpu_driver_bug_workarounds);
+ }
// Preload either the desktop GL or the osmesa so, depending on the
// --use-gl flag.
gl::init::InitializeGLOneOff();
@@ -70,23 +75,13 @@ base::OnceClosure MaybeWrapWithGPUSandboxHook(
base::Passed(std::move(original)));
}
-// Fill in |sandbox_type| and |allowed_dir| based on the command line, returns
-// false if the current process type doesn't need to be sandboxed or if the
-// sandbox was disabled from the command line.
-bool GetSandboxInfoFromCommandLine(service_manager::SandboxType* sandbox_type,
- base::FilePath* allowed_dir) {
+// Fill in |sandbox_type| based on the command line. Returns false if the
+// current process type doesn't need to be sandboxed or if the sandbox was
+// disabled from the command line.
+bool GetSandboxTypeFromCommandLine(service_manager::SandboxType* sandbox_type) {
DCHECK(sandbox_type);
- DCHECK(allowed_dir);
- *allowed_dir = base::FilePath(); // Empty by default.
auto* command_line = base::CommandLine::ForCurrentProcess();
- std::string process_type =
- command_line->GetSwitchValueASCII(switches::kProcessType);
- if (process_type == switches::kUtilityProcess) {
- *allowed_dir =
- command_line->GetSwitchValuePath(switches::kUtilityProcessAllowedDir);
- }
-
*sandbox_type = service_manager::SandboxTypeFromCommandLine(*command_line);
if (service_manager::IsUnsandboxedSandboxType(*sandbox_type))
return false;
@@ -102,22 +97,19 @@ bool GetSandboxInfoFromCommandLine(service_manager::SandboxType* sandbox_type,
} // namespace
-bool InitializeSandbox(service_manager::SandboxType sandbox_type,
- const base::FilePath& allowed_dir) {
+bool InitializeSandbox(service_manager::SandboxType sandbox_type) {
return service_manager::Sandbox::Initialize(
- sandbox_type, allowed_dir,
+ sandbox_type,
MaybeWrapWithGPUSandboxHook(sandbox_type, base::OnceClosure()));
}
bool InitializeSandbox(base::OnceClosure post_warmup_hook) {
service_manager::SandboxType sandbox_type =
service_manager::SANDBOX_TYPE_INVALID;
- base::FilePath allowed_dir;
- return !GetSandboxInfoFromCommandLine(&sandbox_type, &allowed_dir) ||
+ return !GetSandboxTypeFromCommandLine(&sandbox_type) ||
service_manager::Sandbox::Initialize(
- sandbox_type, allowed_dir,
- MaybeWrapWithGPUSandboxHook(sandbox_type,
- std::move(post_warmup_hook)));
+ sandbox_type, MaybeWrapWithGPUSandboxHook(
+ sandbox_type, std::move(post_warmup_hook)));
}
bool InitializeSandbox() {
diff --git a/chromium/content/common/sandbox_mac_fontloading_unittest.mm b/chromium/content/common/sandbox_mac_fontloading_unittest.mm
index db98aab9a0a..3684f43c790 100644
--- a/chromium/content/common/sandbox_mac_fontloading_unittest.mm
+++ b/chromium/content/common/sandbox_mac_fontloading_unittest.mm
@@ -112,16 +112,19 @@ TEST_F(MacSandboxTest, FontLoadingTest) {
std::unique_ptr<FontLoader::ResultInternal> result =
FontLoader::LoadFontForTesting(base::ASCIIToUTF16("Geeza Pro"), 16);
- EXPECT_GT(result->font_data_size, 0U);
+ ASSERT_TRUE(result);
+ ASSERT_TRUE(result->font_data.is_valid());
+ uint64_t font_data_size = result->font_data->GetSize();
+ EXPECT_GT(font_data_size, 0U);
EXPECT_GT(result->font_id, 0U);
mojo::ScopedSharedBufferMapping mapping =
- result->font_data->Map(result->font_data_size);
+ result->font_data->Map(font_data_size);
ASSERT_TRUE(mapping);
base::WriteFileDescriptor(fileno(temp_file),
static_cast<const char*>(mapping.get()),
- result->font_data_size);
+ font_data_size);
ASSERT_TRUE(RunTestInSandbox(service_manager::SANDBOX_TYPE_RENDERER,
"FontLoadingTestCase",
diff --git a/chromium/content/common/sandbox_mac_unittest_helper.mm b/chromium/content/common/sandbox_mac_unittest_helper.mm
index 999d96eb3c0..b1daac3fbdb 100644
--- a/chromium/content/common/sandbox_mac_unittest_helper.mm
+++ b/chromium/content/common/sandbox_mac_unittest_helper.mm
@@ -11,7 +11,6 @@ extern "C" {
#include <map>
#include <memory>
-#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/process/kill.h"
#include "content/test/test_content_client.h"
@@ -157,7 +156,7 @@ MULTIPROCESS_TEST_MAIN(mac_sandbox_test_runner) {
}
service_manager::SandboxMac::Warmup(sandbox_type);
- if (!service_manager::SandboxMac::Enable(sandbox_type, base::FilePath())) {
+ if (!service_manager::SandboxMac::Enable(sandbox_type)) {
LOG(ERROR) << "Failed to initialize sandbox " << sandbox_type;
return -1;
}
diff --git a/chromium/content/common/service_manager/service_manager_connection_impl.cc b/chromium/content/common/service_manager/service_manager_connection_impl.cc
index ae2e334dacc..49f0da67e49 100644
--- a/chromium/content/common/service_manager/service_manager_connection_impl.cc
+++ b/chromium/content/common/service_manager/service_manager_connection_impl.cc
@@ -13,7 +13,6 @@
#include "base/callback_helpers.h"
#include "base/lazy_instance.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/threading/thread_checker.h"
#include "base/threading/thread_task_runner_handle.h"
diff --git a/chromium/content/common/service_worker/controller_service_worker.mojom b/chromium/content/common/service_worker/controller_service_worker.mojom
index 89c2ea813dc..b08c3a9bcfd 100644
--- a/chromium/content/common/service_worker/controller_service_worker.mojom
+++ b/chromium/content/common/service_worker/controller_service_worker.mojom
@@ -7,11 +7,11 @@ module content.mojom;
import "content/common/service_worker/dispatch_fetch_event_params.mojom";
import "content/common/service_worker/service_worker_event_dispatcher.mojom";
import "content/common/service_worker/service_worker_fetch_response_callback.mojom";
-import "mojo/common/time.mojom";
+import "mojo/public/mojom/base/time.mojom";
import "services/network/public/mojom/url_loader.mojom";
-import "third_party/WebKit/public/mojom/service_worker/service_worker_event_status.mojom";
-import "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom";
-import "third_party/WebKit/public/platform/modules/fetch/fetch_api_request.mojom";
+import "third_party/blink/public/mojom/service_worker/service_worker_event_status.mojom";
+import "third_party/blink/public/mojom/service_worker/service_worker_object.mojom";
+import "third_party/blink/public/platform/modules/fetch/fetch_api_request.mojom";
// S13nServiceWorker:
// Represents a service worker that is a 'controller'.
@@ -41,7 +41,7 @@ interface ControllerServiceWorker {
DispatchFetchEvent(DispatchFetchEventParams params,
ServiceWorkerFetchResponseCallback response_callback)
=> (blink.mojom.ServiceWorkerEventStatus status,
- mojo.common.mojom.Time dispatch_event_time);
+ mojo_base.mojom.Time dispatch_event_time);
// TODO(kinuko): Add DispatchExtendableMessageEvent() as well.
diff --git a/chromium/content/common/service_worker/dispatch_fetch_event_params.mojom b/chromium/content/common/service_worker/dispatch_fetch_event_params.mojom
index 2a1d1360df1..05d50cc0893 100644
--- a/chromium/content/common/service_worker/dispatch_fetch_event_params.mojom
+++ b/chromium/content/common/service_worker/dispatch_fetch_event_params.mojom
@@ -5,7 +5,7 @@
module content.mojom;
import "services/network/public/mojom/url_loader.mojom";
-import "third_party/WebKit/public/mojom/blob/blob.mojom";
+import "third_party/blink/public/mojom/blob/blob.mojom";
// Used for service worker navigation preload, to create
// FetchEvent#preloadResponse.
diff --git a/chromium/content/common/service_worker/embedded_worker.mojom b/chromium/content/common/service_worker/embedded_worker.mojom
index 499899a2b25..1dbda4e6cbc 100644
--- a/chromium/content/common/service_worker/embedded_worker.mojom
+++ b/chromium/content/common/service_worker/embedded_worker.mojom
@@ -9,14 +9,15 @@ import "content/common/service_worker/controller_service_worker.mojom";
import "content/common/service_worker/service_worker_event_dispatcher.mojom";
import "content/common/service_worker/service_worker_provider.mojom";
import "mojo/public/mojom/base/string16.mojom";
-import "mojo/common/time.mojom";
-import "mojo/common/unguessable_token.mojom";
+import "mojo/public/mojom/base/time.mojom";
+import "mojo/public/mojom/base/unguessable_token.mojom";
import "services/service_manager/public/mojom/interface_provider.mojom";
-import "third_party/WebKit/public/mojom/service_worker/service_worker.mojom";
-import "third_party/WebKit/public/mojom/service_worker/service_worker_installed_scripts_manager.mojom";
-import "third_party/WebKit/public/web/console_message.mojom";
-import "third_party/WebKit/public/web/devtools_agent.mojom";
-import "third_party/WebKit/public/web/worker_content_settings_proxy.mojom";
+import "third_party/blink/public/mojom/service_worker/service_worker.mojom";
+import "third_party/blink/public/mojom/service_worker/service_worker_installed_scripts_manager.mojom";
+import "third_party/blink/public/platform/web_feature.mojom";
+import "third_party/blink/public/web/console_message.mojom";
+import "third_party/blink/public/web/devtools_agent.mojom";
+import "third_party/blink/public/web/worker_content_settings_proxy.mojom";
import "url/mojom/url.mojom";
// Parameters to launch a service worker. This is passed from the browser to the
@@ -37,7 +38,7 @@ struct EmbeddedWorkerStartParams {
// The id to talk with the DevTools agent for the worker.
int32 worker_devtools_agent_route_id;
// Unique token identifying this worker for DevTools.
- mojo.common.mojom.UnguessableToken devtools_worker_token;
+ mojo_base.mojom.UnguessableToken devtools_worker_token;
// When true, worker script evaluation is blocked until
// EmbeddedWorkerInstanceClient::ResumeAfterDownload() is called.
bool pause_after_download;
@@ -71,9 +72,9 @@ struct EmbeddedWorkerStartParams {
// Holds timing information about the start worker sequence for UMA.
struct EmbeddedWorkerStartTiming {
// When this Blink instance finished initializing.
- mojo.common.mojom.TimeTicks blink_initialized_time;
+ mojo_base.mojom.TimeTicks blink_initialized_time;
// When the start worker message was received by the renderer.
- mojo.common.mojom.TimeTicks start_worker_received_time;
+ mojo_base.mojom.TimeTicks start_worker_received_time;
};
// EmbeddedWorkerInstanceClient is the renderer-side ("Client") of
@@ -110,6 +111,17 @@ interface EmbeddedWorkerInstanceHost {
// message has been missed, the browser will terminate the service worker.
RequestTermination();
+ // Tells the browser process that this service worker used |feature|, for
+ // UseCounter purposes. The browser process propagates the feature usage bit
+ // to all clients controlled by the service worker. See
+ // https://crbug.com/376039 for background.
+ // Note: Because CountFeature() is possible to be called on the main thread
+ // during service worker startup and is also called on the worker thread after
+ // that, we put it here rather than interface ServiceWorkerHost, so that we
+ // can still keep interface ServiceWorkerHost being used solely on the worker
+ // thread in the renderer process.
+ CountFeature(blink.mojom.WebFeature feature);
+
// Indicates that the worker is ready for inspection.
OnReadyForInspection();
// Indicates that the worker has finished loading the script.
diff --git a/chromium/content/common/service_worker/embedded_worker_messages.h b/chromium/content/common/service_worker/embedded_worker_messages.h
deleted file mode 100644
index be5e5c3e1ff..00000000000
--- a/chromium/content/common/service_worker/embedded_worker_messages.h
+++ /dev/null
@@ -1,25 +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 CONTENT_COMMON_SERVICE_WORKER_EMBEDDED_WORKER_MESSAGES_H_
-#define CONTENT_COMMON_SERVICE_WORKER_EMBEDDED_WORKER_MESSAGES_H_
-
-#include <stdint.h>
-
-#include "ipc/ipc_message.h"
-#include "ipc/ipc_message_macros.h"
-#include "ipc/ipc_param_traits.h"
-
-#undef IPC_MESSAGE_EXPORT
-#define IPC_MESSAGE_EXPORT CONTENT_EXPORT
-
-#define IPC_MESSAGE_START EmbeddedWorkerMsgStart
-
-// Renderer -> Browser message to count an API use. |feature| must be one of the
-// values from blink::UseCounter::Feature enum.
-IPC_MESSAGE_CONTROL2(EmbeddedWorkerHostMsg_CountFeature,
- int64_t /* service_worker_version_id */,
- uint32_t /* feature */)
-
-#endif // CONTENT_COMMON_SERVICE_WORKER_EMBEDDED_WORKER_MESSAGES_H_
diff --git a/chromium/content/common/service_worker/service_worker_container.mojom b/chromium/content/common/service_worker/service_worker_container.mojom
index 055be4d4bab..07dc0255a65 100644
--- a/chromium/content/common/service_worker/service_worker_container.mojom
+++ b/chromium/content/common/service_worker/service_worker_container.mojom
@@ -6,13 +6,19 @@ module content.mojom;
import "content/common/service_worker/controller_service_worker.mojom";
import "mojo/public/mojom/base/string16.mojom";
-import "third_party/WebKit/public/mojom/message_port/message_port.mojom";
-import "third_party/WebKit/public/mojom/service_worker/service_worker_error_type.mojom";
-import "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom";
-import "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom";
-import "third_party/WebKit/public/platform/web_feature.mojom";
+import "third_party/blink/public/mojom/message_port/message_port.mojom";
+import "third_party/blink/public/mojom/service_worker/service_worker_error_type.mojom";
+import "third_party/blink/public/mojom/service_worker/service_worker_object.mojom";
+import "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom";
+import "third_party/blink/public/platform/web_feature.mojom";
import "url/mojom/url.mojom";
+// Used for EnsureControllerServiceWorker() to indicate why a controllee needs
+// a controller ServiceWorker.
+enum ControllerServiceWorkerPurpose {
+ FETCH_SUB_RESOURCE
+};
+
// mojom::ServiceWorkerContainerHost is a browser-side interface. The renderer
// process uses this interface to request the browser process to do operations
// involving service worker registrations.
@@ -56,7 +62,7 @@ interface ServiceWorkerContainerHost {
=> (blink.mojom.ServiceWorkerRegistrationObjectInfo? registration);
// S13nServiceWorker:
- // Gets a Mojo end point to the controller ServiceWorker. This may start a
+ // Returns a Mojo end point to the controller ServiceWorker. This may start a
// service worker instance in a renderer process if the corresponding
// instance is not alive.
// This method must be called only by the controllees.
@@ -64,12 +70,19 @@ interface ServiceWorkerContainerHost {
// connection error of the returned pipe. The detailed error reasons are not
// reported to the controllees, but the browser process is responsible for
// properly handling the failure and recording the reasons.
- GetControllerServiceWorker(ControllerServiceWorker& controller);
+ // |purpose| is used for UMA.
+ EnsureControllerServiceWorker(ControllerServiceWorker& controller,
+ ControllerServiceWorkerPurpose purpose);
// S13nServiceWorker:
// Clones the Mojo end point to the ServiceWorker container host. This is
// used to communicate with the host from dedicated and shared workers.
CloneForWorker(ServiceWorkerContainerHost& container_host_for_worker);
+
+ // Does nothing but calls the callback. Useful for pumping the message pipe
+ // for this interface and associated interfaces: when the callback is called,
+ // you know all incoming messages up to the Ping() call have been received.
+ Ping() => ();
};
// mojom::ServiceWorkerContainer is a renderer-side interface.
diff --git a/chromium/content/common/service_worker/service_worker_event_dispatcher.mojom b/chromium/content/common/service_worker/service_worker_event_dispatcher.mojom
index 815aa49d33a..2d97943541e 100644
--- a/chromium/content/common/service_worker/service_worker_event_dispatcher.mojom
+++ b/chromium/content/common/service_worker/service_worker_event_dispatcher.mojom
@@ -7,13 +7,13 @@ module content.mojom;
import "content/common/service_worker/dispatch_fetch_event_params.mojom";
import "content/common/service_worker/service_worker_fetch_response_callback.mojom";
import "mojo/public/mojom/base/string16.mojom";
-import "mojo/common/time.mojom";
-import "third_party/WebKit/public/platform/modules/fetch/fetch_api_request.mojom";
-import "third_party/WebKit/public/platform/modules/payments/payment_app.mojom";
-import "third_party/WebKit/public/mojom/message_port/message_port.mojom";
-import "third_party/WebKit/public/mojom/service_worker/service_worker_client.mojom";
-import "third_party/WebKit/public/mojom/service_worker/service_worker_event_status.mojom";
-import "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom";
+import "mojo/public/mojom/base/time.mojom";
+import "third_party/blink/public/platform/modules/fetch/fetch_api_request.mojom";
+import "third_party/blink/public/platform/modules/payments/payment_app.mojom";
+import "third_party/blink/public/mojom/message_port/message_port.mojom";
+import "third_party/blink/public/mojom/service_worker/service_worker_client.mojom";
+import "third_party/blink/public/mojom/service_worker/service_worker_event_status.mojom";
+import "third_party/blink/public/mojom/service_worker/service_worker_object.mojom";
import "url/mojom/origin.mojom";
import "url/mojom/url.mojom";
@@ -59,17 +59,17 @@ const int32 kPushEventTimeoutSeconds = 90;
// to dispatch events from the browser-side.
//
// Those events expecting such response
-// (blink.mojom.ServiceWorkerEventStatus, mojo.common.mojom.Time) are considered
+// (blink.mojom.ServiceWorkerEventStatus, mojo_base.mojom.Time) are considered
// 'simple events'. ServiceWorkerVersion::CreateSimpleEventCallback can be used
// to create the callback for these.
interface ServiceWorkerEventDispatcher {
DispatchInstallEvent()
=> (blink.mojom.ServiceWorkerEventStatus status,
bool has_fetch_handler,
- mojo.common.mojom.Time dispatch_event_time);
+ mojo_base.mojom.Time dispatch_event_time);
DispatchActivateEvent()
=> (blink.mojom.ServiceWorkerEventStatus status,
- mojo.common.mojom.Time dispatch_event_time);
+ mojo_base.mojom.Time dispatch_event_time);
// These methods dispatch to the ServiceWorkerGlobalScope the events listed on
// https://wicg.github.io/background-fetch/#service-worker-global-events.
@@ -78,20 +78,20 @@ interface ServiceWorkerEventDispatcher {
// content::BackgroundFetchRegistrationId.
DispatchBackgroundFetchAbortEvent(string developer_id)
=> (blink.mojom.ServiceWorkerEventStatus status,
- mojo.common.mojom.Time dispatch_event_time);
+ mojo_base.mojom.Time dispatch_event_time);
DispatchBackgroundFetchClickEvent(string developer_id,
BackgroundFetchState state)
=> (blink.mojom.ServiceWorkerEventStatus status,
- mojo.common.mojom.Time dispatch_event_time);
+ mojo_base.mojom.Time dispatch_event_time);
DispatchBackgroundFetchFailEvent(string developer_id,
array<BackgroundFetchSettledFetch> fetches)
=> (blink.mojom.ServiceWorkerEventStatus status,
- mojo.common.mojom.Time dispatch_event_time);
+ mojo_base.mojom.Time dispatch_event_time);
DispatchBackgroundFetchedEvent(string developer_id,
string unique_id,
array<BackgroundFetchSettledFetch> fetches)
=> (blink.mojom.ServiceWorkerEventStatus status,
- mojo.common.mojom.Time dispatch_event_time);
+ mojo_base.mojom.Time dispatch_event_time);
// The Dispatch*FetchEvent() callback is called once the event finishes,
// which means the event handler ran and all outstanding respondWith() and
@@ -101,21 +101,21 @@ interface ServiceWorkerEventDispatcher {
DispatchFetchEvent(DispatchFetchEventParams params,
ServiceWorkerFetchResponseCallback response_callback)
=> (blink.mojom.ServiceWorkerEventStatus status,
- mojo.common.mojom.Time dispatch_event_time);
+ mojo_base.mojom.Time dispatch_event_time);
DispatchNotificationClickEvent(string notification_id,
PlatformNotificationData notification_data,
int32 action_index,
mojo_base.mojom.String16? reply)
=> (blink.mojom.ServiceWorkerEventStatus status,
- mojo.common.mojom.Time dispatch_event_time);
+ mojo_base.mojom.Time dispatch_event_time);
DispatchNotificationCloseEvent(string notification_id,
PlatformNotificationData notification_data)
=> (blink.mojom.ServiceWorkerEventStatus status,
- mojo.common.mojom.Time dispatch_event_time);
+ mojo_base.mojom.Time dispatch_event_time);
DispatchPushEvent(PushEventPayload payload)
=> (blink.mojom.ServiceWorkerEventStatus status,
- mojo.common.mojom.Time dispatch_event_time);
+ mojo_base.mojom.Time dispatch_event_time);
// Arguments are passed to the event handler as parameters of SyncEvent.
// Ref: https://wicg.github.io/BackgroundSync/spec/#sync-event
// S13nServiceWorker: |timeout| is the amount of time to allow this event to
@@ -123,29 +123,29 @@ interface ServiceWorkerEventDispatcher {
// Non-S13nServiceWorker: |timeout| is just ignored.
DispatchSyncEvent(string id,
bool last_chance,
- mojo.common.mojom.TimeDelta timeout)
+ mojo_base.mojom.TimeDelta timeout)
=> (blink.mojom.ServiceWorkerEventStatus status,
- mojo.common.mojom.Time dispatch_event_time);
+ mojo_base.mojom.Time dispatch_event_time);
DispatchAbortPaymentEvent(
int32 event_id,
payments.mojom.PaymentHandlerResponseCallback result_of_abort_payment)
=> (blink.mojom.ServiceWorkerEventStatus status,
- mojo.common.mojom.Time dispatch_event_time);
+ mojo_base.mojom.Time dispatch_event_time);
DispatchCanMakePaymentEvent(
int32 event_id,
payments.mojom.CanMakePaymentEventData event_data,
payments.mojom.PaymentHandlerResponseCallback result_of_can_make_payment)
=> (blink.mojom.ServiceWorkerEventStatus status,
- mojo.common.mojom.Time dispatch_event_time);
+ mojo_base.mojom.Time dispatch_event_time);
DispatchPaymentRequestEvent(
int32 payment_request_id,
payments.mojom.PaymentRequestEventData request_data,
payments.mojom.PaymentHandlerResponseCallback response_callback)
=> (blink.mojom.ServiceWorkerEventStatus status,
- mojo.common.mojom.Time dispatch_event_time);
+ mojo_base.mojom.Time dispatch_event_time);
DispatchExtendableMessageEvent(ExtendableMessageEvent event)
=> (blink.mojom.ServiceWorkerEventStatus status,
- mojo.common.mojom.Time dispatch_event_time);
+ mojo_base.mojom.Time dispatch_event_time);
// Pings the service worker to check if it is responsive. If the callback is
// not called within a certain period of time, the browser will terminate the
diff --git a/chromium/content/common/service_worker/service_worker_fetch_request.typemap b/chromium/content/common/service_worker/service_worker_fetch_request.typemap
index b5bf9009c96..013db542c01 100644
--- a/chromium/content/common/service_worker/service_worker_fetch_request.typemap
+++ b/chromium/content/common/service_worker/service_worker_fetch_request.typemap
@@ -3,7 +3,7 @@
# found in the LICENSE file.
mojom =
- "//third_party/WebKit/public/platform/modules/fetch/fetch_api_request.mojom"
+ "//third_party/blink/public/platform/modules/fetch/fetch_api_request.mojom"
public_headers = [
"//content/common/service_worker/service_worker_types.h",
"//content/public/common/request_context_type.h",
diff --git a/chromium/content/common/service_worker/service_worker_fetch_request_mojom_traits.h b/chromium/content/common/service_worker/service_worker_fetch_request_mojom_traits.h
index 449c4ca18ff..55862700585 100644
--- a/chromium/content/common/service_worker/service_worker_fetch_request_mojom_traits.h
+++ b/chromium/content/common/service_worker/service_worker_fetch_request_mojom_traits.h
@@ -9,7 +9,7 @@
#include "content/public/common/referrer.h"
#include "services/network/public/mojom/request_context_frame_type.mojom.h"
#include "storage/common/blob_storage/blob_handle.h"
-#include "third_party/WebKit/public/platform/modules/fetch/fetch_api_request.mojom.h"
+#include "third_party/blink/public/platform/modules/fetch/fetch_api_request.mojom.h"
namespace mojo {
diff --git a/chromium/content/common/service_worker/service_worker_fetch_response.typemap b/chromium/content/common/service_worker/service_worker_fetch_response.typemap
index dac46502d1c..60c7e5d5aa3 100644
--- a/chromium/content/common/service_worker/service_worker_fetch_response.typemap
+++ b/chromium/content/common/service_worker/service_worker_fetch_response.typemap
@@ -2,7 +2,8 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
-mojom = "//third_party/WebKit/public/platform/modules/fetch/fetch_api_response.mojom"
+mojom =
+ "//third_party/blink/public/platform/modules/fetch/fetch_api_response.mojom"
public_headers = [ "//content/common/service_worker/service_worker_types.h" ]
traits_headers = [ "//content/common/service_worker/service_worker_fetch_response_mojom_traits.h" ]
sources = [
diff --git a/chromium/content/common/service_worker/service_worker_fetch_response_callback.mojom b/chromium/content/common/service_worker/service_worker_fetch_response_callback.mojom
index 8b134fcded1..105b2639cac 100644
--- a/chromium/content/common/service_worker/service_worker_fetch_response_callback.mojom
+++ b/chromium/content/common/service_worker/service_worker_fetch_response_callback.mojom
@@ -4,9 +4,9 @@
module content.mojom;
-import "mojo/common/time.mojom";
-import "third_party/WebKit/public/mojom/blob/blob.mojom";
-import "third_party/WebKit/public/mojom/service_worker/service_worker_stream_handle.mojom";
+import "mojo/public/mojom/base/time.mojom";
+import "third_party/blink/public/mojom/blob/blob.mojom";
+import "third_party/blink/public/mojom/service_worker/service_worker_stream_handle.mojom";
[Native]
struct ServiceWorkerResponse;
@@ -18,24 +18,24 @@ struct ServiceWorkerResponse;
interface ServiceWorkerFetchResponseCallback {
// Responds to the request with |response|. The body is empty.
OnResponse(ServiceWorkerResponse response,
- mojo.common.mojom.Time dispatch_event_time);
+ mojo_base.mojom.Time dispatch_event_time);
// Responds to the request with |response|. The body is returned as a blob.
// TODO(kinuko): This should not be necessary once we properly support
// transferring blob within |response|. See crbug.com/75523 for more details.
OnResponseBlob(ServiceWorkerResponse response,
blink.mojom.Blob body_as_blob,
- mojo.common.mojom.Time dispatch_event_time);
+ mojo_base.mojom.Time dispatch_event_time);
// Responds to the request with |response|. The body is provided as a
// non-Mojo Blob via |response.blob_uuid|. The callback is useful for Blob
// lifetime management purposes and is called once the caller is done with
// the Blob. TODO(kinuko): Remove this once MojoBlob is fully shipped.
OnResponseLegacyBlob(ServiceWorkerResponse response,
- mojo.common.mojom.Time dispatch_event_time) => ();
+ mojo_base.mojom.Time dispatch_event_time) => ();
// Responds to the request with |response|. The body is returned as a stream.
OnResponseStream(ServiceWorkerResponse response,
blink.mojom.ServiceWorkerStreamHandle body_as_stream,
- mojo.common.mojom.Time dispatch_event_time);
+ mojo_base.mojom.Time dispatch_event_time);
// Provides no response to the request. The callee should fall back to the
// network.
- OnFallback(mojo.common.mojom.Time dispatch_event_time);
+ OnFallback(mojo_base.mojom.Time dispatch_event_time);
};
diff --git a/chromium/content/common/service_worker/service_worker_fetch_response_mojom_traits.cc b/chromium/content/common/service_worker/service_worker_fetch_response_mojom_traits.cc
index 5a868970ca8..4d615363d26 100644
--- a/chromium/content/common/service_worker/service_worker_fetch_response_mojom_traits.cc
+++ b/chromium/content/common/service_worker/service_worker_fetch_response_mojom_traits.cc
@@ -14,7 +14,7 @@
#include "content/common/service_worker/service_worker_types.h"
#include "content/public/common/referrer_struct_traits.h"
#include "ipc/ipc_message_utils.h"
-#include "mojo/common/time_struct_traits.h"
+#include "mojo/public/cpp/base/time_mojom_traits.h"
#include "url/mojom/url_gurl_mojom_traits.h"
namespace mojo {
diff --git a/chromium/content/common/service_worker/service_worker_fetch_response_mojom_traits.h b/chromium/content/common/service_worker/service_worker_fetch_response_mojom_traits.h
index e5a0f70e4cb..51d7d859813 100644
--- a/chromium/content/common/service_worker/service_worker_fetch_response_mojom_traits.h
+++ b/chromium/content/common/service_worker/service_worker_fetch_response_mojom_traits.h
@@ -10,8 +10,8 @@
#include "base/numerics/safe_conversions.h"
#include "content/common/service_worker/service_worker_types.h"
-#include "third_party/WebKit/public/mojom/blob/blob.mojom.h"
-#include "third_party/WebKit/public/platform/modules/fetch/fetch_api_response.mojom.h"
+#include "third_party/blink/public/mojom/blob/blob.mojom.h"
+#include "third_party/blink/public/platform/modules/fetch/fetch_api_response.mojom.h"
namespace mojo {
diff --git a/chromium/content/common/service_worker/service_worker_loader_helpers.cc b/chromium/content/common/service_worker/service_worker_loader_helpers.cc
index acb16b12daf..0b4912c8982 100644
--- a/chromium/content/common/service_worker/service_worker_loader_helpers.cc
+++ b/chromium/content/common/service_worker/service_worker_loader_helpers.cc
@@ -170,10 +170,7 @@ ServiceWorkerLoaderHelpers::CloneResourceRequestBody(
NOTREACHED();
break;
case network::DataElement::TYPE_DATA_PIPE: {
- network::mojom::DataPipeGetterPtrInfo clone_ptr_info;
- element.data_pipe()->Clone(mojo::MakeRequest(&clone_ptr_info));
- network::mojom::DataPipeGetterPtr clone_ptr(std::move(clone_ptr_info));
- clone->AppendDataPipe(std::move(clone_ptr));
+ clone->AppendDataPipe(element.CloneDataPipeGetter());
break;
}
case network::DataElement::TYPE_RAW_FILE:
@@ -181,6 +178,10 @@ ServiceWorkerLoaderHelpers::CloneResourceRequestBody(
element.offset(), element.length(),
element.expected_modification_time());
break;
+ case network::DataElement::TYPE_CHUNKED_DATA_PIPE:
+ NOTREACHED() << "There should be no chunked data pipes going through "
+ "ServiceWorker";
+ break;
case network::DataElement::TYPE_BLOB:
NOTREACHED() << "There should be no blob elements in NetworkService";
break;
diff --git a/chromium/content/common/service_worker/service_worker_loader_helpers.h b/chromium/content/common/service_worker/service_worker_loader_helpers.h
index 27e1a02f31d..3654e07fcfe 100644
--- a/chromium/content/common/service_worker/service_worker_loader_helpers.h
+++ b/chromium/content/common/service_worker/service_worker_loader_helpers.h
@@ -9,7 +9,7 @@
#include "content/common/service_worker/service_worker_types.h"
#include "net/http/http_request_headers.h"
#include "net/url_request/redirect_info.h"
-#include "third_party/WebKit/public/mojom/blob/blob.mojom.h"
+#include "third_party/blink/public/mojom/blob/blob.mojom.h"
namespace network {
class ResourceRequestBody;
diff --git a/chromium/content/common/service_worker/service_worker_messages.h b/chromium/content/common/service_worker/service_worker_messages.h
index aceea652a86..9c6dd91051c 100644
--- a/chromium/content/common/service_worker/service_worker_messages.h
+++ b/chromium/content/common/service_worker/service_worker_messages.h
@@ -19,9 +19,7 @@
#include "ipc/ipc_message_macros.h"
#include "ipc/ipc_param_traits.h"
#include "services/network/public/mojom/fetch_api.mojom.h"
-#include "third_party/WebKit/public/common/message_port/message_port_channel.h"
-#include "third_party/WebKit/public/common/message_port/transferable_message.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerError.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_error.h"
#undef IPC_MESSAGE_EXPORT
#define IPC_MESSAGE_EXPORT CONTENT_EXPORT
@@ -29,13 +27,13 @@
#define IPC_MESSAGE_START ServiceWorkerMsgStart
IPC_ENUM_TRAITS_MAX_VALUE(blink::mojom::ServiceWorkerErrorType,
- blink::mojom::ServiceWorkerErrorType::kLast)
+ blink::mojom::ServiceWorkerErrorType::kMaxValue)
IPC_ENUM_TRAITS_MAX_VALUE(blink::mojom::ServiceWorkerState,
- blink::mojom::ServiceWorkerState::kLast)
+ blink::mojom::ServiceWorkerState::kMaxValue)
IPC_ENUM_TRAITS_MAX_VALUE(blink::mojom::ServiceWorkerResponseError,
- blink::mojom::ServiceWorkerResponseError::kLast)
+ blink::mojom::ServiceWorkerResponseError::kMaxValue)
IPC_STRUCT_TRAITS_BEGIN(content::ServiceWorkerFetchRequest)
IPC_STRUCT_TRAITS_MEMBER(mode)
@@ -79,16 +77,6 @@ IPC_STRUCT_TRAITS_BEGIN(content::PushEventPayload)
IPC_STRUCT_TRAITS_END()
//---------------------------------------------------------------------------
-// Messages sent from the child process to the browser.
-
-// Sends MessageEvent to a client (renderer->browser).
-IPC_MESSAGE_ROUTED2(
- ServiceWorkerHostMsg_PostMessageToClient,
- std::string /* uuid */,
- scoped_refptr<
- base::RefCountedData<blink::TransferableMessage>> /* message */)
-
-//---------------------------------------------------------------------------
// Messages sent from the browser to the child process.
//
// NOTE: All ServiceWorkerMsg messages not sent via EmbeddedWorker must have
diff --git a/chromium/content/common/service_worker/service_worker_provider.mojom b/chromium/content/common/service_worker/service_worker_provider.mojom
index 3b3e306e383..de8bda5821d 100644
--- a/chromium/content/common/service_worker/service_worker_provider.mojom
+++ b/chromium/content/common/service_worker/service_worker_provider.mojom
@@ -7,14 +7,24 @@ module content.mojom;
import "content/common/service_worker/service_worker_container.mojom";
import "services/network/public/mojom/url_loader_factory.mojom";
import "services/service_manager/public/mojom/interface_provider.mojom";
-import "third_party/WebKit/public/mojom/service_worker/service_worker_provider_type.mojom";
-import "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom";
+import "third_party/blink/public/mojom/service_worker/service_worker_provider_type.mojom";
+import "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom";
// The name of the InterfaceProviderSpec in service manifests used by the
// frame tree to expose service-worker-specific interfaces between renderer
// and browser.
const string kNavigation_ServiceWorkerSpec = "navigation:service_worker";
+// S13nServiceWorker:
+// Sent from the browser process to the renderer. Contains parameteres for the
+// constructor of ServiceWorkerNetworkProvider used for starting a shared
+// worker.
+struct ServiceWorkerProviderInfoForSharedWorker {
+ int32 provider_id;
+ associated ServiceWorkerContainerHost host_ptr_info;
+ associated ServiceWorkerContainer& client_request;
+};
+
// Sent from the browser process to the renderer. Contains parameters for the
// constructor of ServiceWorkerNetworkProvider used for starting a service
// worker.
@@ -27,7 +37,7 @@ struct ServiceWorkerProviderInfoForStartWorker {
associated ServiceWorkerContainerHost host_ptr_info;
associated ServiceWorkerContainer& client_request;
- // For servicified service worker only.
+ // S13nServiceWorker:
// The loader to use for loading the worker's main script and
// importScripts().
associated network.mojom.URLLoaderFactory? script_loader_factory_ptr_info;
diff --git a/chromium/content/common/service_worker/service_worker_provider_host_info.h b/chromium/content/common/service_worker/service_worker_provider_host_info.h
index 809286643be..d7ebeb3228c 100644
--- a/chromium/content/common/service_worker/service_worker_provider_host_info.h
+++ b/chromium/content/common/service_worker/service_worker_provider_host_info.h
@@ -7,7 +7,7 @@
#include "content/common/service_worker/service_worker_container.mojom.h"
#include "content/common/service_worker/service_worker_types.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_provider_type.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_provider_type.mojom.h"
namespace content {
@@ -56,14 +56,14 @@ struct CONTENT_EXPORT ServiceWorkerProviderHostInfo {
// Mojo endpoint to send a message from the renderer to the browser. This
// will be associated with ServiceWorkerDisptacherHost. |host_request| should
- // be valid when ServiceWorkerProviderHostInfo is passed to any Mojo methods.
+ // be valid when ServiceWorkerProviderHostInfo is passed to any Mojo method.
// After used to create the ServiceWorkerProviderHost, this will be invalid.
mojom::ServiceWorkerContainerHostAssociatedRequest host_request;
// Mojo endpoint to send a message from the browser to the renderer. This
- // will be associated with ServiceWorkerDisptacherHost. |client_ptr_info|
+ // will be associated with ServiceWorkerDispatcherHost. |client_ptr_info|
// should be valid when ServiceWorkerProviderHostInfo is passed to any Mojo
- // methods.
+ // method.
// After used to create the ServiceWorkerProviderHost, this will be invalid.
mojom::ServiceWorkerContainerAssociatedPtrInfo client_ptr_info;
diff --git a/chromium/content/common/service_worker/service_worker_provider_struct_traits.h b/chromium/content/common/service_worker/service_worker_provider_struct_traits.h
index d9aa94bb56a..20316209d9d 100644
--- a/chromium/content/common/service_worker/service_worker_provider_struct_traits.h
+++ b/chromium/content/common/service_worker/service_worker_provider_struct_traits.h
@@ -6,7 +6,7 @@
#define CONTENT_COMMON_SERVICE_WORKER_SERVICE_WORKER_PROVIDER_STRUCT_TRAITS_H_
#include "content/common/service_worker/service_worker_provider.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_provider_type.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_provider_type.mojom.h"
namespace mojo {
diff --git a/chromium/content/common/service_worker/service_worker_types.cc b/chromium/content/common/service_worker/service_worker_types.cc
index 632db938939..4f93a652e54 100644
--- a/chromium/content/common/service_worker/service_worker_types.cc
+++ b/chromium/content/common/service_worker/service_worker_types.cc
@@ -19,8 +19,19 @@ const char kServiceWorkerGetRegistrationErrorPrefix[] =
"Failed to get a ServiceWorkerRegistration: ";
const char kServiceWorkerGetRegistrationsErrorPrefix[] =
"Failed to get ServiceWorkerRegistration objects: ";
-const char kFetchScriptError[] =
+const char kServiceWorkerFetchScriptError[] =
"An unknown error occurred when fetching the script.";
+const char kServiceWorkerBadHTTPResponseError[] =
+ "A bad HTTP response code (%d) was received when fetching the script.";
+const char kServiceWorkerSSLError[] =
+ "An SSL certificate error occurred when fetching the script.";
+const char kServiceWorkerBadMIMEError[] =
+ "The script has an unsupported MIME type ('%s').";
+const char kServiceWorkerNoMIMEError[] =
+ "The script does not have a MIME type.";
+const char kServiceWorkerRedirectError[] =
+ "The script resource is behind a redirect, which is disallowed.";
+const char kServiceWorkerAllowed[] = "Service-Worker-Allowed";
ServiceWorkerFetchRequest::ServiceWorkerFetchRequest() = default;
diff --git a/chromium/content/common/service_worker/service_worker_types.h b/chromium/content/common/service_worker/service_worker_types.h
index ab84fa9d335..bf4983a15ce 100644
--- a/chromium/content/common/service_worker/service_worker_types.h
+++ b/chromium/content/common/service_worker/service_worker_types.h
@@ -19,12 +19,12 @@
#include "content/public/common/request_context_type.h"
#include "services/network/public/mojom/fetch_api.mojom.h"
#include "services/network/public/mojom/request_context_frame_type.mojom.h"
-#include "third_party/WebKit/public/mojom/page/page_visibility_state.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_client.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_state.mojom.h"
-#include "third_party/WebKit/public/platform/modules/fetch/fetch_api_request.mojom.h"
+#include "third_party/blink/public/mojom/page/page_visibility_state.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_client.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_state.mojom.h"
+#include "third_party/blink/public/platform/modules/fetch/fetch_api_request.mojom.h"
#include "url/gurl.h"
// This file is to have common definitions that are to be shared by
@@ -46,7 +46,13 @@ extern const char kServiceWorkerUpdateErrorPrefix[];
extern const char kServiceWorkerUnregisterErrorPrefix[];
extern const char kServiceWorkerGetRegistrationErrorPrefix[];
extern const char kServiceWorkerGetRegistrationsErrorPrefix[];
-extern const char kFetchScriptError[];
+extern const char kServiceWorkerFetchScriptError[];
+extern const char kServiceWorkerBadHTTPResponseError[];
+extern const char kServiceWorkerSSLError[];
+extern const char kServiceWorkerBadMIMEError[];
+extern const char kServiceWorkerNoMIMEError[];
+extern const char kServiceWorkerRedirectError[];
+extern const char kServiceWorkerAllowed[];
// Constants for invalid identifiers.
static const int kInvalidEmbeddedWorkerThreadId = -1;
diff --git a/chromium/content/common/service_worker/service_worker_utils.h b/chromium/content/common/service_worker/service_worker_utils.h
index 8afa7dc5bb2..9df6f6668ae 100644
--- a/chromium/content/common/service_worker/service_worker_utils.h
+++ b/chromium/content/common/service_worker/service_worker_utils.h
@@ -13,7 +13,7 @@
#include "content/public/common/content_switches.h"
#include "content/public/common/resource_type.h"
#include "net/http/http_request_headers.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_error_type.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_error_type.mojom.h"
#include "url/gurl.h"
namespace content {
diff --git a/chromium/content/common/shared_worker/shared_worker.mojom b/chromium/content/common/shared_worker/shared_worker.mojom
index ca8229bb7cd..c7539c4f154 100644
--- a/chromium/content/common/shared_worker/shared_worker.mojom
+++ b/chromium/content/common/shared_worker/shared_worker.mojom
@@ -4,7 +4,7 @@
module content.mojom;
-import "third_party/WebKit/public/web/devtools_agent.mojom";
+import "third_party/blink/public/web/devtools_agent.mojom";
// Interface used by the host to control the shared worker.
interface SharedWorker {
diff --git a/chromium/content/common/shared_worker/shared_worker_client.mojom b/chromium/content/common/shared_worker/shared_worker_client.mojom
index 0ff30a396fe..9e2c6fc12c0 100644
--- a/chromium/content/common/shared_worker/shared_worker_client.mojom
+++ b/chromium/content/common/shared_worker/shared_worker_client.mojom
@@ -4,8 +4,8 @@
module content.mojom;
-import "third_party/WebKit/public/platform/web_feature.mojom";
-import "third_party/WebKit/public/web/shared_worker_creation_context_type.mojom";
+import "third_party/blink/public/mojom/shared_worker/shared_worker_creation_context_type.mojom";
+import "third_party/blink/public/platform/web_feature.mojom";
// An interface used by clients (e.g., the renderer where "new SharedWorker()"
// was invoked) to observe events from a shared worker.
diff --git a/chromium/content/common/shared_worker/shared_worker_connector.mojom b/chromium/content/common/shared_worker/shared_worker_connector.mojom
index f0b663fb786..39cd78c7450 100644
--- a/chromium/content/common/shared_worker/shared_worker_connector.mojom
+++ b/chromium/content/common/shared_worker/shared_worker_connector.mojom
@@ -6,7 +6,7 @@ module content.mojom;
import "content/common/shared_worker/shared_worker_client.mojom";
import "content/common/shared_worker/shared_worker_info.mojom";
-import "third_party/WebKit/public/web/shared_worker_creation_context_type.mojom";
+import "third_party/blink/public/mojom/shared_worker/shared_worker_creation_context_type.mojom";
// This interface is exposed to enable a client to create and connect to a
// shared worker.
diff --git a/chromium/content/common/shared_worker/shared_worker_factory.mojom b/chromium/content/common/shared_worker/shared_worker_factory.mojom
index ef8dffb7ae0..13c068af65a 100644
--- a/chromium/content/common/shared_worker/shared_worker_factory.mojom
+++ b/chromium/content/common/shared_worker/shared_worker_factory.mojom
@@ -4,12 +4,14 @@
module content.mojom;
+import "content/common/service_worker/service_worker_provider.mojom";
import "content/common/shared_worker/shared_worker.mojom";
import "content/common/shared_worker/shared_worker_host.mojom";
import "content/common/shared_worker/shared_worker_info.mojom";
-import "mojo/common/unguessable_token.mojom";
+import "mojo/public/mojom/base/unguessable_token.mojom";
+import "services/network/public/mojom/url_loader_factory.mojom";
import "services/service_manager/public/mojom/interface_provider.mojom";
-import "third_party/WebKit/public/web/worker_content_settings_proxy.mojom";
+import "third_party/blink/public/web/worker_content_settings_proxy.mojom";
// The name of the InterfaceProviderSpec in service manifests used by the
// frame tree to expose shared-worker-specific interfaces between renderer and
@@ -27,8 +29,30 @@ interface SharedWorkerFactory {
CreateSharedWorker(
SharedWorkerInfo info,
bool pause_on_start,
- mojo.common.mojom.UnguessableToken devtools_worker_token,
+ mojo_base.mojom.UnguessableToken devtools_worker_token,
blink.mojom.WorkerContentSettingsProxy content_settings,
+
+ // S13nServiceWorker:
+ // The info about the host in the browser process that provides support
+ // for this shared worker to be a service worker client. Null when
+ // S13nServiceWorker is disabled.
+ ServiceWorkerProviderInfoForSharedWorker? service_worker_provider_info,
+
+ // S13nServiceWorker:
+ // The URLLoaderFactory to use to request the shared worker's script
+ // (just the main script resource; importScripts() should go through the
+ // usual loader or the controller service worker if appropriate).
+ //
+ // Null when S13nServiceWorker is disabled.
+ //
+ // It doesn't really need to be associated, but a similar associated
+ // interface ptr is sent for service worker startup, so making this
+ // associated too simplifies code on the renderer, as
+ // ServiceWorkerNetworkProvider::script_loader_factory_ can be an
+ // associated interface ptr used for both service worker and shared
+ // worker execution contexts.
+ associated network.mojom.URLLoaderFactory? script_loader_factory_ptr_info,
+
SharedWorkerHost host,
SharedWorker& shared_worker,
service_manager.mojom.InterfaceProvider interface_provider);
diff --git a/chromium/content/common/shared_worker/shared_worker_host.mojom b/chromium/content/common/shared_worker/shared_worker_host.mojom
index 1a893fac15d..58e6082b5ca 100644
--- a/chromium/content/common/shared_worker/shared_worker_host.mojom
+++ b/chromium/content/common/shared_worker/shared_worker_host.mojom
@@ -4,7 +4,7 @@
module content.mojom;
-import "third_party/WebKit/public/platform/web_feature.mojom";
+import "third_party/blink/public/platform/web_feature.mojom";
// Each shared worker has a corresponding host. The host controls the lifetime
// of the shared worker. This interface is used by the shared worker to talk to
diff --git a/chromium/content/common/shared_worker/shared_worker_info.mojom b/chromium/content/common/shared_worker/shared_worker_info.mojom
index eec393499f5..38782d71ee1 100644
--- a/chromium/content/common/shared_worker/shared_worker_info.mojom
+++ b/chromium/content/common/shared_worker/shared_worker_info.mojom
@@ -4,8 +4,8 @@
module content.mojom;
-import "third_party/WebKit/public/mojom/net/ip_address_space.mojom";
-import "third_party/WebKit/public/platform/content_security_policy.mojom";
+import "third_party/blink/public/mojom/net/ip_address_space.mojom";
+import "third_party/blink/public/platform/content_security_policy.mojom";
import "url/mojom/url.mojom";
// Meta data that is necessary to create a new shared worker context. This
diff --git a/chromium/content/common/single_request_url_loader_factory.cc b/chromium/content/common/single_request_url_loader_factory.cc
index 9bbe28c4611..1a3828903af 100644
--- a/chromium/content/common/single_request_url_loader_factory.cc
+++ b/chromium/content/common/single_request_url_loader_factory.cc
@@ -8,7 +8,6 @@
#include <utility>
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/sequenced_task_runner.h"
#include "base/threading/sequenced_task_runner_handle.h"
@@ -57,14 +56,14 @@ class SingleRequestURLLoaderFactory::HandlerState
};
class SingleRequestURLLoaderFactory::FactoryInfo
- : public SharedURLLoaderFactoryInfo {
+ : public network::SharedURLLoaderFactoryInfo {
public:
explicit FactoryInfo(scoped_refptr<HandlerState> state)
: state_(std::move(state)) {}
~FactoryInfo() override = default;
// SharedURLLoaderFactoryInfo:
- scoped_refptr<SharedURLLoaderFactory> CreateFactory() override {
+ scoped_refptr<network::SharedURLLoaderFactory> CreateFactory() override {
return new SingleRequestURLLoaderFactory(std::move(state_));
}
@@ -89,7 +88,7 @@ void SingleRequestURLLoaderFactory::CreateLoaderAndStart(
state_->HandleRequest(std::move(loader), std::move(client));
}
-std::unique_ptr<SharedURLLoaderFactoryInfo>
+std::unique_ptr<network::SharedURLLoaderFactoryInfo>
SingleRequestURLLoaderFactory::Clone() {
return std::make_unique<FactoryInfo>(state_);
}
diff --git a/chromium/content/common/single_request_url_loader_factory.h b/chromium/content/common/single_request_url_loader_factory.h
index 44673b26896..0250e786be4 100644
--- a/chromium/content/common/single_request_url_loader_factory.h
+++ b/chromium/content/common/single_request_url_loader_factory.h
@@ -5,7 +5,7 @@
#ifndef CONTENT_COMMON_SINGLE_REQUEST_URL_LOADER_FACTORY_H_
#define CONTENT_COMMON_SINGLE_REQUEST_URL_LOADER_FACTORY_H_
-#include "content/public/common/shared_url_loader_factory.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "base/memory/ref_counted.h"
#include "services/network/public/mojom/url_loader.mojom.h"
@@ -15,7 +15,7 @@ namespace content {
// An implementation of SharedURLLoaderFactory which handles only a single
// request. It's an error to call CreateLoaderAndStart() more than a total of
// one time across this object or any of its clones.
-class SingleRequestURLLoaderFactory : public SharedURLLoaderFactory {
+class SingleRequestURLLoaderFactory : public network::SharedURLLoaderFactory {
public:
using RequestHandler =
base::OnceCallback<void(network::mojom::URLLoaderRequest,
@@ -32,7 +32,7 @@ class SingleRequestURLLoaderFactory : public SharedURLLoaderFactory {
network::mojom::URLLoaderClientPtr client,
const net::MutableNetworkTrafficAnnotationTag&
traffic_annotation) override;
- std::unique_ptr<SharedURLLoaderFactoryInfo> Clone() override;
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo> Clone() override;
private:
class FactoryInfo;
diff --git a/chromium/content/common/speech_recognition_messages.h b/chromium/content/common/speech_recognition_messages.h
index e9d7f0693e4..a7843381fac 100644
--- a/chromium/content/common/speech_recognition_messages.h
+++ b/chromium/content/common/speech_recognition_messages.h
@@ -49,8 +49,8 @@ IPC_STRUCT_TRAITS_END()
// Used to start a speech recognition session.
IPC_STRUCT_BEGIN(SpeechRecognitionHostMsg_StartRequest_Params)
- // The render view requesting speech recognition.
- IPC_STRUCT_MEMBER(int, render_view_id)
+ // The render frame requesting speech recognition.
+ IPC_STRUCT_MEMBER(int, render_frame_id)
// Unique ID associated with the JS object making the calls.
IPC_STRUCT_MEMBER(int, request_id)
// Language to use for speech recognition.
@@ -73,25 +73,25 @@ IPC_MESSAGE_CONTROL1(SpeechRecognitionHostMsg_StartRequest,
SpeechRecognitionHostMsg_StartRequest_Params)
// Requests the speech recognition service to abort speech recognition on
-// behalf of the given |render_view_id| and |request_id|. If there are no
-// sessions associated with the |request_id| in the render view, this call
+// behalf of the given |render_frame_id| and |request_id|. If there are no
+// sessions associated with the |request_id| in the render frame, this call
// does nothing.
IPC_MESSAGE_CONTROL2(SpeechRecognitionHostMsg_AbortRequest,
- int /* render_view_id */,
+ int /* render_frame_id */,
int /* request_id */)
// Requests the speech recognition service to abort all speech recognitions on
-// behalf of the given |render_view_id|. If speech recognition is not happening
-// or is happening on behalf of some other render view, this call does nothing.
+// behalf of the given |render_frame_id|. If speech recognition is not happening
+// or is happening on behalf of some other render frame, this call does nothing.
IPC_MESSAGE_CONTROL1(SpeechRecognitionHostMsg_AbortAllRequests,
- int /* render_view_id */)
+ int /* render_frame_id */)
// Requests the speech recognition service to stop audio capture on behalf of
-// the given |render_view_id|. Any audio recorded so far will be fed to the
+// the given |render_frame_id|. Any audio recorded so far will be fed to the
// speech recognizer. If speech recognition is not happening nor or is
-// happening on behalf of some other render view, this call does nothing.
+// happening on behalf of some other render frame, this call does nothing.
IPC_MESSAGE_CONTROL2(SpeechRecognitionHostMsg_StopCaptureRequest,
- int /* render_view_id */,
+ int /* render_frame_id */,
int /* request_id */)
// Browser -> Renderer messages.
diff --git a/chromium/content/common/throttling_url_loader.cc b/chromium/content/common/throttling_url_loader.cc
index fc8c82159cb..0d0ba0268bf 100644
--- a/chromium/content/common/throttling_url_loader.cc
+++ b/chromium/content/common/throttling_url_loader.cc
@@ -60,6 +60,20 @@ class ThrottlingURLLoader::ForwardingThrottleDelegate
loader_->ResumeReadingBodyFromNet(throttle_);
}
+ void InterceptResponse(
+ network::mojom::URLLoaderPtr new_loader,
+ network::mojom::URLLoaderClientRequest new_client_request,
+ network::mojom::URLLoaderPtr* original_loader,
+ network::mojom::URLLoaderClientRequest* original_client_request)
+ override {
+ if (!loader_)
+ return;
+
+ ScopedDelegateCall scoped_delegate_call(this);
+ loader_->InterceptResponse(std::move(new_loader),
+ std::move(new_client_request), original_loader,
+ original_client_request);
+ }
void Detach() { loader_ = nullptr; }
private:
@@ -95,7 +109,7 @@ class ThrottlingURLLoader::ForwardingThrottleDelegate
};
ThrottlingURLLoader::StartInfo::StartInfo(
- scoped_refptr<SharedURLLoaderFactory> in_url_loader_factory,
+ scoped_refptr<network::SharedURLLoaderFactory> in_url_loader_factory,
int32_t in_routing_id,
int32_t in_request_id,
uint32_t in_options,
@@ -112,10 +126,8 @@ ThrottlingURLLoader::StartInfo::~StartInfo() = default;
ThrottlingURLLoader::ResponseInfo::ResponseInfo(
const network::ResourceResponseHead& in_response_head,
- const base::Optional<net::SSLInfo>& in_ssl_info,
network::mojom::DownloadedTempFilePtr in_downloaded_file)
: response_head(in_response_head),
- ssl_info(in_ssl_info),
downloaded_file(std::move(in_downloaded_file)) {}
ThrottlingURLLoader::ResponseInfo::~ResponseInfo() = default;
@@ -136,7 +148,7 @@ ThrottlingURLLoader::PriorityInfo::~PriorityInfo() = default;
// static
std::unique_ptr<ThrottlingURLLoader> ThrottlingURLLoader::CreateLoaderAndStart(
- scoped_refptr<SharedURLLoaderFactory> factory,
+ scoped_refptr<network::SharedURLLoaderFactory> factory,
std::vector<std::unique_ptr<URLLoaderThrottle>> throttles,
int32_t routing_id,
int32_t request_id,
@@ -205,7 +217,7 @@ ThrottlingURLLoader::ThrottlingURLLoader(
}
void ThrottlingURLLoader::Start(
- scoped_refptr<SharedURLLoaderFactory> factory,
+ scoped_refptr<network::SharedURLLoaderFactory> factory,
int32_t routing_id,
int32_t request_id,
uint32_t options,
@@ -242,7 +254,7 @@ void ThrottlingURLLoader::Start(
}
void ThrottlingURLLoader::StartNow(
- SharedURLLoaderFactory* factory,
+ network::SharedURLLoaderFactory* factory,
int32_t routing_id,
int32_t request_id,
uint32_t options,
@@ -296,7 +308,6 @@ void ThrottlingURLLoader::StopDeferringForThrottle(
void ThrottlingURLLoader::OnReceiveResponse(
const network::ResourceResponseHead& response_head,
- const base::Optional<net::SSLInfo>& ssl_info,
network::mojom::DownloadedTempFilePtr downloaded_file) {
DCHECK_EQ(DEFERRED_NONE, deferred_stage_);
DCHECK(!loader_cancelled_);
@@ -316,13 +327,13 @@ void ThrottlingURLLoader::OnReceiveResponse(
if (deferred) {
deferred_stage_ = DEFERRED_RESPONSE;
response_info_ = std::make_unique<ResponseInfo>(
- response_head, ssl_info, std::move(downloaded_file));
+ response_head, std::move(downloaded_file));
client_binding_.PauseIncomingMethodCallProcessing();
return;
}
}
- forwarding_client_->OnReceiveResponse(response_head, ssl_info,
+ forwarding_client_->OnReceiveResponse(response_head,
std::move(downloaded_file));
}
@@ -454,19 +465,21 @@ void ThrottlingURLLoader::Resume() {
}
case DEFERRED_REDIRECT: {
client_binding_.ResumeIncomingMethodCallProcessing();
- forwarding_client_->OnReceiveRedirect(redirect_info_->redirect_info,
- redirect_info_->response_head);
// TODO(dhausknecht) at this point we do not actually know if we commit to
// the redirect or if it will be cancelled. FollowRedirect would be a more
// suitable place to set this URL but there we do not have the data.
response_url_ = redirect_info_->redirect_info.new_url;
+ forwarding_client_->OnReceiveRedirect(redirect_info_->redirect_info,
+ redirect_info_->response_head);
+ // Note: |this| may be deleted here.
break;
}
case DEFERRED_RESPONSE: {
client_binding_.ResumeIncomingMethodCallProcessing();
forwarding_client_->OnReceiveResponse(
- response_info_->response_head, response_info_->ssl_info,
+ response_info_->response_head,
std::move(response_info_->downloaded_file));
+ // Note: |this| may be deleted here.
break;
}
default:
@@ -498,6 +511,24 @@ void ThrottlingURLLoader::ResumeReadingBodyFromNet(
url_loader_->ResumeReadingBodyFromNet();
}
+void ThrottlingURLLoader::InterceptResponse(
+ network::mojom::URLLoaderPtr new_loader,
+ network::mojom::URLLoaderClientRequest new_client_request,
+ network::mojom::URLLoaderPtr* original_loader,
+ network::mojom::URLLoaderClientRequest* original_client_request) {
+ response_intercepted_ = true;
+
+ if (original_loader)
+ *original_loader = std::move(url_loader_);
+ url_loader_ = std::move(new_loader);
+
+ if (original_client_request)
+ *original_client_request = client_binding_.Unbind();
+ client_binding_.Bind(std::move(new_client_request));
+ client_binding_.set_connection_error_handler(base::BindOnce(
+ &ThrottlingURLLoader::OnClientConnectionError, base::Unretained(this)));
+}
+
void ThrottlingURLLoader::DisconnectClient(base::StringPiece custom_reason) {
client_binding_.Close();
diff --git a/chromium/content/common/throttling_url_loader.h b/chromium/content/common/throttling_url_loader.h
index 54e48644751..af9f50ebead 100644
--- a/chromium/content/common/throttling_url_loader.h
+++ b/chromium/content/common/throttling_url_loader.h
@@ -14,9 +14,9 @@
#include "base/threading/thread_task_runner_handle.h"
#include "content/common/content_export.h"
#include "content/common/possibly_associated_interface_ptr.h"
-#include "content/public/common/shared_url_loader_factory.h"
#include "content/public/common/url_loader_throttle.h"
#include "mojo/public/cpp/bindings/binding.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/mojom/url_loader.mojom.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
@@ -38,7 +38,7 @@ class CONTENT_EXPORT ThrottlingURLLoader
// note that the request may not start immediately since it could be deferred
// by throttles.
static std::unique_ptr<ThrottlingURLLoader> CreateLoaderAndStart(
- scoped_refptr<SharedURLLoaderFactory> factory,
+ scoped_refptr<network::SharedURLLoaderFactory> factory,
std::vector<std::unique_ptr<URLLoaderThrottle>> throttles,
int32_t routing_id,
int32_t request_id,
@@ -62,6 +62,8 @@ class CONTENT_EXPORT ThrottlingURLLoader
forwarding_client_ = client;
}
+ bool response_intercepted() const { return response_intercepted_; }
+
private:
class ForwardingThrottleDelegate;
@@ -70,14 +72,14 @@ class CONTENT_EXPORT ThrottlingURLLoader
network::mojom::URLLoaderClient* client,
const net::NetworkTrafficAnnotationTag& traffic_annotation);
- void Start(scoped_refptr<SharedURLLoaderFactory> factory,
+ void Start(scoped_refptr<network::SharedURLLoaderFactory> factory,
int32_t routing_id,
int32_t request_id,
uint32_t options,
network::ResourceRequest* url_request,
scoped_refptr<base::SingleThreadTaskRunner> task_runner);
- void StartNow(SharedURLLoaderFactory* factory,
+ void StartNow(network::SharedURLLoaderFactory* factory,
int32_t routing_id,
int32_t request_id,
uint32_t options,
@@ -100,7 +102,6 @@ class CONTENT_EXPORT ThrottlingURLLoader
// network::mojom::URLLoaderClient implementation:
void OnReceiveResponse(
const network::ResourceResponseHead& response_head,
- const base::Optional<net::SSLInfo>& ssl_info,
network::mojom::DownloadedTempFilePtr downloaded_file) override;
void OnReceiveRedirect(
const net::RedirectInfo& redirect_info,
@@ -122,6 +123,11 @@ class CONTENT_EXPORT ThrottlingURLLoader
void SetPriority(net::RequestPriority priority);
void PauseReadingBodyFromNet(URLLoaderThrottle* throttle);
void ResumeReadingBodyFromNet(URLLoaderThrottle* throttle);
+ void InterceptResponse(
+ network::mojom::URLLoaderPtr new_loader,
+ network::mojom::URLLoaderClientRequest new_client_request,
+ network::mojom::URLLoaderPtr* original_loader,
+ network::mojom::URLLoaderClientRequest* original_client_request);
// Disconnects the client connection and releases the URLLoader.
void DisconnectClient(base::StringPiece custom_description);
@@ -164,15 +170,16 @@ class CONTENT_EXPORT ThrottlingURLLoader
network::mojom::URLLoaderPtr url_loader_;
struct StartInfo {
- StartInfo(scoped_refptr<SharedURLLoaderFactory> in_url_loader_factory,
- int32_t in_routing_id,
- int32_t in_request_id,
- uint32_t in_options,
- network::ResourceRequest* in_url_request,
- scoped_refptr<base::SingleThreadTaskRunner> in_task_runner);
+ StartInfo(
+ scoped_refptr<network::SharedURLLoaderFactory> in_url_loader_factory,
+ int32_t in_routing_id,
+ int32_t in_request_id,
+ uint32_t in_options,
+ network::ResourceRequest* in_url_request,
+ scoped_refptr<base::SingleThreadTaskRunner> in_task_runner);
~StartInfo();
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory;
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory;
int32_t routing_id;
int32_t request_id;
uint32_t options;
@@ -186,12 +193,10 @@ class CONTENT_EXPORT ThrottlingURLLoader
struct ResponseInfo {
ResponseInfo(const network::ResourceResponseHead& in_response_head,
- const base::Optional<net::SSLInfo>& in_ssl_info,
network::mojom::DownloadedTempFilePtr in_downloaded_file);
~ResponseInfo();
network::ResourceResponseHead response_head;
- base::Optional<net::SSLInfo> ssl_info;
network::mojom::DownloadedTempFilePtr downloaded_file;
};
// Set if response is deferred.
@@ -226,6 +231,8 @@ class CONTENT_EXPORT ThrottlingURLLoader
// The latest request URL from where we expect a response
GURL response_url_;
+ bool response_intercepted_ = false;
+
base::WeakPtrFactory<ThrottlingURLLoader> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(ThrottlingURLLoader);
diff --git a/chromium/content/common/throttling_url_loader_unittest.cc b/chromium/content/common/throttling_url_loader_unittest.cc
index e6a0c8fe7ae..b7a22c10b4f 100644
--- a/chromium/content/common/throttling_url_loader_unittest.cc
+++ b/chromium/content/common/throttling_url_loader_unittest.cc
@@ -7,9 +7,9 @@
#include "base/macros.h"
#include "base/run_loop.h"
#include "base/test/scoped_task_environment.h"
-#include "content/common/weak_wrapper_shared_url_loader_factory.h"
#include "content/public/common/browser_side_navigation_policy.h"
#include "content/public/common/url_loader_throttle.h"
+#include "content/public/common/weak_wrapper_shared_url_loader_factory.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "services/network/public/mojom/url_loader.mojom.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
@@ -37,7 +37,7 @@ class TestURLLoaderFactory : public network::mojom::URLLoaderFactory,
mojo::Binding<network::mojom::URLLoader>& url_loader_binding() {
return url_loader_binding_;
}
- scoped_refptr<SharedURLLoaderFactory> shared_factory() {
+ scoped_refptr<network::SharedURLLoaderFactory> shared_factory() {
return shared_factory_;
}
@@ -54,8 +54,7 @@ class TestURLLoaderFactory : public network::mojom::URLLoaderFactory,
}
void NotifyClientOnReceiveResponse() {
- client_ptr_->OnReceiveResponse(network::ResourceResponseHead(),
- base::nullopt, nullptr);
+ client_ptr_->OnReceiveResponse(network::ResourceResponseHead(), nullptr);
}
void NotifyClientOnReceiveRedirect() {
@@ -135,7 +134,13 @@ class TestURLLoaderClient : public network::mojom::URLLoaderClient {
size_t on_complete_called() const { return on_complete_called_; }
- void set_on_received_response_callback(const base::Closure& callback) {
+ void set_on_received_redirect_callback(
+ const base::RepeatingClosure& callback) {
+ on_received_redirect_callback_ = callback;
+ }
+
+ void set_on_received_response_callback(
+ const base::RepeatingClosure& callback) {
on_received_response_callback_ = callback;
}
@@ -148,7 +153,6 @@ class TestURLLoaderClient : public network::mojom::URLLoaderClient {
// network::mojom::URLLoaderClient implementation:
void OnReceiveResponse(
const network::ResourceResponseHead& response_head,
- const base::Optional<net::SSLInfo>& ssl_info,
network::mojom::DownloadedTempFilePtr downloaded_file) override {
on_received_response_called_++;
if (on_received_response_callback_)
@@ -158,6 +162,8 @@ class TestURLLoaderClient : public network::mojom::URLLoaderClient {
const net::RedirectInfo& redirect_info,
const network::ResourceResponseHead& response_head) override {
on_received_redirect_called_++;
+ if (on_received_redirect_callback_)
+ on_received_redirect_callback_.Run();
}
void OnDataDownloaded(int64_t data_len, int64_t encoded_data_len) override {}
void OnUploadProgress(int64_t current_position,
@@ -177,7 +183,8 @@ class TestURLLoaderClient : public network::mojom::URLLoaderClient {
size_t on_received_redirect_called_ = 0;
size_t on_complete_called_ = 0;
- base::Closure on_received_response_callback_;
+ base::RepeatingClosure on_received_redirect_callback_;
+ base::RepeatingClosure on_received_response_callback_;
OnCompleteCallback on_complete_callback_;
DISALLOW_COPY_AND_ASSIGN(TestURLLoaderClient);
@@ -614,7 +621,7 @@ TEST_F(ThrottlingURLLoaderTest, ResumeNoOpIfNotDeferred) {
});
throttle_->set_will_start_request_callback(resume_callback);
throttle_->set_will_redirect_request_callback(resume_callback);
- throttle_->set_will_process_response_callback(resume_callback);
+ throttle_->set_will_process_response_callback(std::move(resume_callback));
base::RunLoop run_loop;
client_.set_on_complete_callback(base::Bind(
@@ -906,7 +913,8 @@ TEST_F(ThrottlingURLLoaderTest, PauseResumeReadingBodyFromNet) {
EXPECT_EQ(1u, factory_.resume_reading_body_from_net_called());
}
-TEST_F(ThrottlingURLLoaderTest, DestroyingThrottlingURLLoaderInDelegateCall) {
+TEST_F(ThrottlingURLLoaderTest,
+ DestroyingThrottlingURLLoaderInDelegateCall_Response) {
base::RunLoop run_loop1;
throttle_->set_will_process_response_callback(base::Bind(
[](const base::Closure& quit_closure,
@@ -955,5 +963,54 @@ TEST_F(ThrottlingURLLoaderTest, DestroyingThrottlingURLLoaderInDelegateCall) {
EXPECT_EQ(nullptr, throttle_);
}
+// Regression test for crbug.com/833292.
+TEST_F(ThrottlingURLLoaderTest,
+ DestroyingThrottlingURLLoaderInDelegateCall_Redirect) {
+ base::RunLoop run_loop1;
+ throttle_->set_will_redirect_request_callback(base::BindRepeating(
+ [](const base::RepeatingClosure& quit_closure,
+ URLLoaderThrottle::Delegate* delegate, bool* defer) {
+ *defer = true;
+ quit_closure.Run();
+ },
+ run_loop1.QuitClosure()));
+
+ base::RunLoop run_loop2;
+ client_.set_on_received_redirect_callback(base::BindRepeating(
+ [](ThrottlingURLLoaderTest* test,
+ const base::RepeatingClosure& quit_closure) {
+ // Destroy the ThrottlingURLLoader while inside a delegate call from a
+ // throttle.
+ test->loader().reset();
+
+ // The throttle should stay alive.
+ EXPECT_NE(nullptr, test->throttle());
+
+ quit_closure.Run();
+ },
+ base::Unretained(this), run_loop2.QuitClosure()));
+
+ CreateLoaderAndStart();
+
+ factory_.NotifyClientOnReceiveRedirect();
+
+ run_loop1.Run();
+
+ EXPECT_EQ(1u, throttle_->will_start_request_called());
+ EXPECT_EQ(1u, throttle_->will_redirect_request_called());
+ EXPECT_EQ(0u, throttle_->will_process_response_called());
+
+ throttle_->delegate()->Resume();
+ run_loop2.Run();
+
+ // The ThrottlingURLLoader should be gone.
+ EXPECT_EQ(nullptr, loader_);
+ // The throttle should stay alive and destroyed later.
+ EXPECT_NE(nullptr, throttle_);
+
+ scoped_task_environment_.RunUntilIdle();
+ EXPECT_EQ(nullptr, throttle_);
+}
+
} // namespace
} // namespace content
diff --git a/chromium/content/common/unique_name_helper.cc b/chromium/content/common/unique_name_helper.cc
index 8aed7052e21..676e4412ded 100644
--- a/chromium/content/common/unique_name_helper.cc
+++ b/chromium/content/common/unique_name_helper.cc
@@ -248,15 +248,16 @@ std::string UniqueNameHelper::UpdateLegacyNameFromV24(
// tree and go down from there, it is impossible for a frame path to contain
// a unique name (which needs a replacement) that has not already been seen
// and inserted into |replacements|.
- size_t index = 0;
for (const auto& replacement : *replacements) {
+ // Note: this find() call should only start searching from immediately
+ // after the most recent replacement, to guarantee each section of the
+ // name is only replaced once. But it was accidentally omitted from the
+ // initial version of the migration code.
size_t next_index = legacy_name.find(replacement.old_name);
if (next_index == std::string::npos)
continue;
legacy_name.replace(next_index, replacement.old_name.size(),
replacement.new_name);
- index = next_index -
- (replacement.old_name.size() - replacement.new_name.size());
}
return legacy_name;
}
diff --git a/chromium/content/common/unique_name_helper_unittest.cc b/chromium/content/common/unique_name_helper_unittest.cc
index 753a416813c..bb196c2551a 100644
--- a/chromium/content/common/unique_name_helper_unittest.cc
+++ b/chromium/content/common/unique_name_helper_unittest.cc
@@ -9,7 +9,6 @@
#include <vector>
#include "base/auto_reset.h"
-#include "base/memory/ptr_util.h"
#include "base/optional.h"
#include "base/strings/nullable_string16.h"
#include "base/strings/string_piece.h"
diff --git a/chromium/content/common/url_loader_factory_bundle.cc b/chromium/content/common/url_loader_factory_bundle.cc
index 378b4e07ea2..e3d31d68690 100644
--- a/chromium/content/common/url_loader_factory_bundle.cc
+++ b/chromium/content/common/url_loader_factory_bundle.cc
@@ -20,7 +20,7 @@ URLLoaderFactoryBundleInfo::URLLoaderFactoryBundleInfo(
URLLoaderFactoryBundleInfo::~URLLoaderFactoryBundleInfo() = default;
-scoped_refptr<SharedURLLoaderFactory>
+scoped_refptr<network::SharedURLLoaderFactory>
URLLoaderFactoryBundleInfo::CreateFactory() {
auto other = std::make_unique<URLLoaderFactoryBundleInfo>();
other->default_factory_info_ = std::move(default_factory_info_);
@@ -78,7 +78,8 @@ void URLLoaderFactoryBundle::CreateLoaderAndStart(
traffic_annotation);
}
-std::unique_ptr<SharedURLLoaderFactoryInfo> URLLoaderFactoryBundle::Clone() {
+std::unique_ptr<network::SharedURLLoaderFactoryInfo>
+URLLoaderFactoryBundle::Clone() {
network::mojom::URLLoaderFactoryPtrInfo default_factory_info;
if (default_factory_)
default_factory_->Clone(mojo::MakeRequest(&default_factory_info));
diff --git a/chromium/content/common/url_loader_factory_bundle.h b/chromium/content/common/url_loader_factory_bundle.h
index 235bf8182de..3db8f4fc096 100644
--- a/chromium/content/common/url_loader_factory_bundle.h
+++ b/chromium/content/common/url_loader_factory_bundle.h
@@ -10,7 +10,7 @@
#include "base/macros.h"
#include "content/common/content_export.h"
-#include "content/public/common/shared_url_loader_factory.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
class GURL;
@@ -20,7 +20,7 @@ namespace content {
// Holds the internal state of a URLLoaderFactoryBundle in a form that is safe
// to pass across sequences.
class CONTENT_EXPORT URLLoaderFactoryBundleInfo
- : public SharedURLLoaderFactoryInfo {
+ : public network::SharedURLLoaderFactoryInfo {
public:
URLLoaderFactoryBundleInfo();
URLLoaderFactoryBundleInfo(
@@ -40,7 +40,7 @@ class CONTENT_EXPORT URLLoaderFactoryBundleInfo
protected:
// SharedURLLoaderFactoryInfo implementation.
- scoped_refptr<SharedURLLoaderFactory> CreateFactory() override;
+ scoped_refptr<network::SharedURLLoaderFactory> CreateFactory() override;
network::mojom::URLLoaderFactoryPtrInfo default_factory_info_;
std::map<std::string, network::mojom::URLLoaderFactoryPtrInfo>
@@ -51,7 +51,8 @@ class CONTENT_EXPORT URLLoaderFactoryBundleInfo
// Encapsulates a collection of URLLoaderFactoryPtrs which can be usd to acquire
// loaders for various types of resource requests.
-class CONTENT_EXPORT URLLoaderFactoryBundle : public SharedURLLoaderFactory {
+class CONTENT_EXPORT URLLoaderFactoryBundle
+ : public network::SharedURLLoaderFactory {
public:
URLLoaderFactoryBundle();
@@ -81,7 +82,7 @@ class CONTENT_EXPORT URLLoaderFactoryBundle : public SharedURLLoaderFactory {
const net::MutableNetworkTrafficAnnotationTag&
traffic_annotation) override;
- std::unique_ptr<SharedURLLoaderFactoryInfo> Clone() override;
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo> Clone() override;
// The |info| contains replacement factories for a subset of the existing
// bundle.
diff --git a/chromium/content/common/url_schemes.cc b/chromium/content/common/url_schemes.cc
index c951b551a8a..a269e1de2cb 100644
--- a/chromium/content/common/url_schemes.cc
+++ b/chromium/content/common/url_schemes.cc
@@ -6,8 +6,9 @@
#include <string.h>
-#include <algorithm>
+#include <iterator>
+#include "base/no_destructor.h"
#include "base/strings/string_util.h"
#include "content/public/common/content_client.h"
#include "content/public/common/url_constants.h"
@@ -17,15 +18,6 @@
namespace content {
namespace {
-// These lists are lazily initialized below and are leaked on shutdown to
-// prevent any destructors from being called that will slow us down or cause
-// problems.
-std::vector<std::string>* savable_schemes = nullptr;
-// Note we store url::Origins here instead of strings to deal with
-// canonicalization.
-std::vector<url::Origin>* secure_origins = nullptr;
-std::vector<std::string>* service_worker_schemes = nullptr;
-
const char* const kDefaultSavableSchemes[] = {
url::kHttpScheme,
url::kHttpsScheme,
@@ -37,21 +29,41 @@ const char* const kDefaultSavableSchemes[] = {
url::kDataScheme
};
+// These lists are lazily initialized below and are leaked on shutdown to
+// prevent any destructors from being called that will slow us down or cause
+// problems.
+std::vector<std::string>& GetMutableSavableSchemes() {
+ static base::NoDestructor<std::vector<std::string>> schemes;
+ return *schemes;
+}
+
+// Note we store url::Origins here instead of strings to deal with
+// canonicalization.
+std::vector<url::Origin>& GetMutableSecureOrigins() {
+ static base::NoDestructor<std::vector<url::Origin>> origins;
+ return *origins;
+}
+
+std::vector<std::string>& GetMutableServiceWorkerSchemes() {
+ static base::NoDestructor<std::vector<std::string>> schemes;
+ return *schemes;
+}
+
} // namespace
void RegisterContentSchemes(bool lock_schemes) {
ContentClient::Schemes schemes;
GetContentClient()->AddAdditionalSchemes(&schemes);
- url::AddStandardScheme(kChromeDevToolsScheme, url::SCHEME_WITHOUT_PORT);
- url::AddStandardScheme(kChromeUIScheme, url::SCHEME_WITHOUT_PORT);
- url::AddStandardScheme(kGuestScheme, url::SCHEME_WITHOUT_PORT);
+ url::AddStandardScheme(kChromeDevToolsScheme, url::SCHEME_WITH_HOST);
+ url::AddStandardScheme(kChromeUIScheme, url::SCHEME_WITH_HOST);
+ url::AddStandardScheme(kGuestScheme, url::SCHEME_WITH_HOST);
for (auto& scheme : schemes.standard_schemes)
- url::AddStandardScheme(scheme.c_str(), url::SCHEME_WITHOUT_PORT);
+ url::AddStandardScheme(scheme.c_str(), url::SCHEME_WITH_HOST);
for (auto& scheme : schemes.referrer_schemes)
- url::AddReferrerScheme(scheme.c_str(), url::SCHEME_WITHOUT_PORT);
+ url::AddReferrerScheme(scheme.c_str(), url::SCHEME_WITH_HOST);
schemes.secure_schemes.push_back(kChromeUIScheme);
schemes.secure_schemes.push_back(kChromeErrorScheme);
@@ -86,34 +98,28 @@ void RegisterContentSchemes(bool lock_schemes) {
url::LockSchemeRegistries();
// Combine the default savable schemes with the additional ones given.
- delete savable_schemes;
- savable_schemes = new std::vector<std::string>;
- for (auto* default_scheme : kDefaultSavableSchemes)
- savable_schemes->push_back(default_scheme);
- savable_schemes->insert(savable_schemes->end(),
- schemes.savable_schemes.begin(),
- schemes.savable_schemes.end());
-
- delete service_worker_schemes;
- service_worker_schemes = new std::vector<std::string>;
- *service_worker_schemes = std::move(schemes.service_worker_schemes);
-
- delete secure_origins;
- secure_origins = new std::vector<url::Origin>;
- *secure_origins = std::move(schemes.secure_origins);
- network::cors::legacy::RegisterSecureOrigins(*secure_origins);
+ GetMutableSavableSchemes().assign(std::begin(kDefaultSavableSchemes),
+ std::end(kDefaultSavableSchemes));
+ GetMutableSavableSchemes().insert(GetMutableSavableSchemes().end(),
+ schemes.savable_schemes.begin(),
+ schemes.savable_schemes.end());
+
+ GetMutableServiceWorkerSchemes() = std::move(schemes.service_worker_schemes);
+
+ GetMutableSecureOrigins() = std::move(schemes.secure_origins);
+ network::cors::legacy::RegisterSecureOrigins(GetSecureOrigins());
}
const std::vector<std::string>& GetSavableSchemes() {
- return *savable_schemes;
+ return GetMutableSavableSchemes();
}
const std::vector<url::Origin>& GetSecureOrigins() {
- return *secure_origins;
+ return GetMutableSecureOrigins();
}
const std::vector<std::string>& GetServiceWorkerSchemes() {
- return *service_worker_schemes;
+ return GetMutableServiceWorkerSchemes();
}
} // namespace content
diff --git a/chromium/content/common/view_messages.h b/chromium/content/common/view_messages.h
index 7e83d1783a5..1f619836b51 100644
--- a/chromium/content/common/view_messages.h
+++ b/chromium/content/common/view_messages.h
@@ -44,17 +44,17 @@
#include "media/base/ipc/media_param_traits.h"
#include "media/capture/ipc/capture_param_traits.h"
#include "net/base/network_change_notifier.h"
-#include "ppapi/features/features.h"
-#include "third_party/WebKit/public/platform/WebDisplayMode.h"
-#include "third_party/WebKit/public/platform/WebFloatPoint.h"
-#include "third_party/WebKit/public/platform/WebFloatRect.h"
-#include "third_party/WebKit/public/platform/WebIntrinsicSizingInfo.h"
-#include "third_party/WebKit/public/platform/modules/screen_orientation/WebScreenOrientationType.h"
-#include "third_party/WebKit/public/web/WebDeviceEmulationParams.h"
-#include "third_party/WebKit/public/web/WebMediaPlayerAction.h"
-#include "third_party/WebKit/public/web/WebPluginAction.h"
-#include "third_party/WebKit/public/web/WebPopupType.h"
-#include "third_party/WebKit/public/web/WebTextDirection.h"
+#include "ppapi/buildflags/buildflags.h"
+#include "third_party/blink/public/platform/modules/screen_orientation/web_screen_orientation_type.h"
+#include "third_party/blink/public/platform/web_display_mode.h"
+#include "third_party/blink/public/platform/web_float_point.h"
+#include "third_party/blink/public/platform/web_float_rect.h"
+#include "third_party/blink/public/platform/web_intrinsic_sizing_info.h"
+#include "third_party/blink/public/web/web_device_emulation_params.h"
+#include "third_party/blink/public/web/web_media_player_action.h"
+#include "third_party/blink/public/web/web_plugin_action.h"
+#include "third_party/blink/public/web/web_popup_type.h"
+#include "third_party/blink/public/web/web_text_direction.h"
#include "ui/base/ime/text_input_mode.h"
#include "ui/base/ime/text_input_type.h"
#include "ui/base/ui_base_types.h"
@@ -69,8 +69,8 @@
#include "ui/gfx/ipc/skia/gfx_skia_param_traits.h"
#if defined(OS_MACOSX)
-#include "third_party/WebKit/public/platform/WebScrollbarButtonsPlacement.h"
-#include "third_party/WebKit/public/platform/mac/WebScrollbarTheme.h"
+#include "third_party/blink/public/platform/mac/web_scrollbar_theme.h"
+#include "third_party/blink/public/platform/web_scrollbar_buttons_placement.h"
#endif
#undef IPC_MESSAGE_EXPORT
@@ -162,6 +162,10 @@ IPC_STRUCT_TRAITS_END()
IPC_STRUCT_TRAITS_BEGIN(content::ResizeParams)
IPC_STRUCT_TRAITS_MEMBER(screen_info)
+ IPC_STRUCT_TRAITS_MEMBER(auto_resize_enabled)
+ IPC_STRUCT_TRAITS_MEMBER(min_size_for_auto_resize)
+ IPC_STRUCT_TRAITS_MEMBER(max_size_for_auto_resize)
+ IPC_STRUCT_TRAITS_MEMBER(auto_resize_sequence_number)
IPC_STRUCT_TRAITS_MEMBER(new_size)
IPC_STRUCT_TRAITS_MEMBER(compositor_viewport_pixel_size)
IPC_STRUCT_TRAITS_MEMBER(browser_controls_shrink_blink_size)
@@ -343,19 +347,6 @@ IPC_MESSAGE_ROUTED0(ViewMsg_Close)
// rect so that we don't have to fetch it every time WebKit asks for it.
IPC_MESSAGE_ROUTED1(ViewMsg_Resize, content::ResizeParams /* params */)
-// Tells the widget to use the provided viz::LocalSurfaceId to submit
-// CompositorFrames for autosize.
-// TODO(fsamuel): Replace these parameters with ResizeParams eventually. After
-// surface sync is on by default everywhere, ResizeParams should be renamed to
-// SynchronizedVisualParams.
-IPC_MESSAGE_ROUTED(ViewMsg_SetLocalSurfaceIdForAutoResize,
- uint64_t /* sequence_number */,
- gfx::Size /* min_size */,
- gfx::Size /* max_size */,
- content::ScreenInfo /* screen_info */,
- uint32_t /* content_source_id */,
- viz::LocalSurfaceId /* local_surface_id */)
-
// Enables device emulation. See WebDeviceEmulationParams for description.
IPC_MESSAGE_ROUTED1(ViewMsg_EnableDeviceEmulation,
blink::WebDeviceEmulationParams /* params */)
@@ -445,16 +436,6 @@ IPC_MESSAGE_ROUTED0(ViewMsg_Move_ACK)
// Used to instruct the RenderView to send back updates to the preferred size.
IPC_MESSAGE_ROUTED0(ViewMsg_EnablePreferredSizeChangedMode)
-// Used to instruct the RenderView to automatically resize and send back
-// updates for the new size.
-IPC_MESSAGE_ROUTED2(ViewMsg_EnableAutoResize,
- gfx::Size /* min_size */,
- gfx::Size /* max_size */)
-
-// Used to instruct the RenderView to disalbe automatically resize.
-IPC_MESSAGE_ROUTED1(ViewMsg_DisableAutoResize,
- gfx::Size /* new_size */)
-
// Changes the text direction of the currently selected input field (if any).
IPC_MESSAGE_ROUTED1(ViewMsg_SetTextDirection,
blink::WebTextDirection /* direction */)
@@ -525,9 +506,6 @@ IPC_MESSAGE_ROUTED3(ViewMsg_ResolveTapDisambiguation,
gfx::Point /* tap_viewport_offset */,
bool /* is_long_press */)
-// Fetches complete rendered content of a web page as plain text.
-IPC_MESSAGE_ROUTED0(ViewMsg_GetRenderedText)
-
IPC_MESSAGE_ROUTED0(ViewMsg_SelectWordAroundCaret)
// Sent by the browser to ask the renderer to redraw. Robust to events that can
@@ -536,9 +514,11 @@ IPC_MESSAGE_ROUTED0(ViewMsg_SelectWordAroundCaret)
IPC_MESSAGE_ROUTED1(ViewMsg_ForceRedraw,
ui::LatencyInfo /* latency_info */)
-// Sets the viewport intersection on the widget for an out-of-process iframe.
-IPC_MESSAGE_ROUTED1(ViewMsg_SetViewportIntersection,
- gfx::Rect /* viewport_intersection */)
+// Sets the viewport intersection and compositor raster area on the widget for
+// an out-of-process iframe.
+IPC_MESSAGE_ROUTED2(ViewMsg_SetViewportIntersection,
+ gfx::Rect /* viewport_intersection */,
+ gfx::Rect /* compositor_visible_rect */)
// Sets the inert bit on an out-of-process iframe.
IPC_MESSAGE_ROUTED1(ViewMsg_SetIsInert, bool /* inert */)
@@ -760,18 +740,6 @@ IPC_MESSAGE_ROUTED3(ViewHostMsg_SelectWordAroundCaretAck,
int /* start_adjust */,
int /* end_adjust */)
-#if defined(OS_ANDROID)
-// Notifies that an unhandled tap has occurred at the specified x,y position
-// and that the UI may need to be triggered.
-IPC_MESSAGE_ROUTED2(ViewHostMsg_ShowUnhandledTapUIIfNeeded,
- int /* x */,
- int /* y */)
-
-#elif defined(OS_MACOSX)
-// Receives content of a web page as plain text.
-IPC_MESSAGE_ROUTED1(ViewMsg_GetRenderedTextCompleted, std::string)
-#endif
-
// Adding a new message? Stick to the sort order above: first platform
// independent ViewMsg, then ifdefs for platform specific ViewMsg, then platform
// independent ViewHostMsg, then ifdefs for platform specific ViewHostMsg.
diff --git a/chromium/content/common/wrapper_shared_url_loader_factory.cc b/chromium/content/common/wrapper_shared_url_loader_factory.cc
index 5c595d67fde..370d3ab507e 100644
--- a/chromium/content/common/wrapper_shared_url_loader_factory.cc
+++ b/chromium/content/common/wrapper_shared_url_loader_factory.cc
@@ -17,7 +17,7 @@ WrapperSharedURLLoaderFactoryInfo::WrapperSharedURLLoaderFactoryInfo(
WrapperSharedURLLoaderFactoryInfo::~WrapperSharedURLLoaderFactoryInfo() =
default;
-scoped_refptr<SharedURLLoaderFactory>
+scoped_refptr<network::SharedURLLoaderFactory>
WrapperSharedURLLoaderFactoryInfo::CreateFactory() {
return base::MakeRefCounted<WrapperSharedURLLoaderFactory>(
std::move(factory_ptr_info_));
diff --git a/chromium/content/common/wrapper_shared_url_loader_factory.h b/chromium/content/common/wrapper_shared_url_loader_factory.h
index 371c3fbbde1..fd1bc0871b8 100644
--- a/chromium/content/common/wrapper_shared_url_loader_factory.h
+++ b/chromium/content/common/wrapper_shared_url_loader_factory.h
@@ -7,8 +7,8 @@
#include "content/common/content_export.h"
#include "content/common/possibly_associated_interface_ptr.h"
-#include "content/public/common/shared_url_loader_factory.h"
#include "mojo/public/cpp/bindings/interface_request.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
namespace content {
@@ -16,7 +16,7 @@ namespace content {
// A SharedURLLoaderFactoryInfo implementation that wraps a
// network::mojom::URLLoaderFactoryPtrInfo.
class CONTENT_EXPORT WrapperSharedURLLoaderFactoryInfo
- : public SharedURLLoaderFactoryInfo {
+ : public network::SharedURLLoaderFactoryInfo {
public:
WrapperSharedURLLoaderFactoryInfo();
explicit WrapperSharedURLLoaderFactoryInfo(
@@ -26,7 +26,7 @@ class CONTENT_EXPORT WrapperSharedURLLoaderFactoryInfo
private:
// SharedURLLoaderFactoryInfo implementation.
- scoped_refptr<SharedURLLoaderFactory> CreateFactory() override;
+ scoped_refptr<network::SharedURLLoaderFactory> CreateFactory() override;
network::mojom::URLLoaderFactoryPtrInfo factory_ptr_info_;
};
@@ -34,7 +34,8 @@ class CONTENT_EXPORT WrapperSharedURLLoaderFactoryInfo
// A SharedURLLoaderFactory implementation that wraps a
// PtrTemplateType<network::mojom::URLLoaderFactory>.
template <template <typename> class PtrTemplateType>
-class WrapperSharedURLLoaderFactoryBase : public SharedURLLoaderFactory {
+class WrapperSharedURLLoaderFactoryBase
+ : public network::SharedURLLoaderFactory {
public:
using PtrType = PtrTemplateType<network::mojom::URLLoaderFactory>;
using PtrInfoType = typename PtrType::PtrInfoType;
@@ -61,7 +62,7 @@ class WrapperSharedURLLoaderFactoryBase : public SharedURLLoaderFactory {
std::move(client), traffic_annotation);
}
- std::unique_ptr<SharedURLLoaderFactoryInfo> Clone() override {
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo> Clone() override {
network::mojom::URLLoaderFactoryPtrInfo factory_ptr_info;
if (factory_ptr_)
factory_ptr_->Clone(mojo::MakeRequest(&factory_ptr_info));
diff --git a/chromium/content/gpu/BUILD.gn b/chromium/content/gpu/BUILD.gn
index 5504b503440..3e858724af3 100644
--- a/chromium/content/gpu/BUILD.gn
+++ b/chromium/content/gpu/BUILD.gn
@@ -66,9 +66,9 @@ target(link_target_type, "gpu_sources") {
"//gpu/ipc/common:gpu_preferences_util",
"//gpu/ipc/service",
"//ipc",
- "//media:media_features",
+ "//media:media_buildflags",
"//media/gpu",
- "//media/mojo:features",
+ "//media/mojo:buildflags",
# TODO(jrummell): As //media/gpu/ipc/service is a source_set in a
# component build, determine if it should not be included here.
diff --git a/chromium/content/gpu/gpu_child_thread.cc b/chromium/content/gpu/gpu_child_thread.cc
index 880b387d411..861c2f856c3 100644
--- a/chromium/content/gpu/gpu_child_thread.cc
+++ b/chromium/content/gpu/gpu_child_thread.cc
@@ -275,7 +275,7 @@ void GpuChildThread::OnGpuServiceConnection(viz::GpuServiceImpl* gpu_service) {
service_factory_.reset(new GpuServiceFactory(
gpu_service->gpu_preferences(),
gpu_service->media_gpu_channel_manager()->AsWeakPtr(),
- overlay_factory_cb));
+ std::move(overlay_factory_cb)));
if (GetContentClient()->gpu()) { // NULL in tests.
GetContentClient()->gpu()->GpuServiceInitialized(
@@ -285,6 +285,13 @@ void GpuChildThread::OnGpuServiceConnection(viz::GpuServiceImpl* gpu_service) {
release_pending_requests_closure_.Run();
}
+void GpuChildThread::PostCompositorThreadCreated(
+ base::SingleThreadTaskRunner* task_runner) {
+ auto* gpu_client = GetContentClient()->gpu();
+ if (gpu_client)
+ gpu_client->PostCompositorThreadCreated(task_runner);
+}
+
void GpuChildThread::BindServiceFactoryRequest(
service_manager::mojom::ServiceFactoryRequest request) {
DVLOG(1) << "GPU: Binding service_manager::mojom::ServiceFactoryRequest";
diff --git a/chromium/content/gpu/gpu_child_thread.h b/chromium/content/gpu/gpu_child_thread.h
index b848b2d32c7..417035ddcb0 100644
--- a/chromium/content/gpu/gpu_child_thread.h
+++ b/chromium/content/gpu/gpu_child_thread.h
@@ -77,6 +77,8 @@ class GpuChildThread : public ChildThreadImpl,
// viz::VizMainImpl::Delegate:
void OnInitializationFailed() override;
void OnGpuServiceConnection(viz::GpuServiceImpl* gpu_service) override;
+ void PostCompositorThreadCreated(
+ base::SingleThreadTaskRunner* task_runner) override;
void BindServiceFactoryRequest(
service_manager::mojom::ServiceFactoryRequest request);
diff --git a/chromium/content/gpu/gpu_main.cc b/chromium/content/gpu/gpu_main.cc
index 115f871094b..d9c8b6d8c61 100644
--- a/chromium/content/gpu/gpu_main.cc
+++ b/chromium/content/gpu/gpu_main.cc
@@ -41,7 +41,7 @@
#include "gpu/ipc/service/gpu_config.h"
#include "gpu/ipc/service/gpu_init.h"
#include "gpu/ipc/service/gpu_watchdog_thread.h"
-#include "media/gpu/features.h"
+#include "media/gpu/buildflags.h"
#include "third_party/angle/src/gpu_info_util/SystemInfo.h"
#include "third_party/skia/include/core/SkGraphics.h"
#include "ui/events/platform/platform_event_source.h"
diff --git a/chromium/content/gpu/gpu_sandbox_hook_linux.cc b/chromium/content/gpu/gpu_sandbox_hook_linux.cc
index 4713f522325..cd914e2f992 100644
--- a/chromium/content/gpu/gpu_sandbox_hook_linux.cc
+++ b/chromium/content/gpu/gpu_sandbox_hook_linux.cc
@@ -18,7 +18,7 @@
#include "build/build_config.h"
#include "build/buildflag.h"
#include "content/public/common/content_switches.h"
-#include "media/gpu/features.h"
+#include "media/gpu/buildflags.h"
#include "sandbox/linux/bpf_dsl/policy.h"
#include "sandbox/linux/syscall_broker/broker_command.h"
#include "sandbox/linux/syscall_broker/broker_file_permission.h"
diff --git a/chromium/content/gpu/gpu_service_factory.cc b/chromium/content/gpu/gpu_service_factory.cc
index a4ec06a54cf..15a97fc0693 100644
--- a/chromium/content/gpu/gpu_service_factory.cc
+++ b/chromium/content/gpu/gpu_service_factory.cc
@@ -45,10 +45,10 @@ void GpuServiceFactory::RegisterServices(ServiceMap* services) {
#endif // BUILDFLAG(ENABLE_LIBRARY_CDMS)
service_manager::EmbeddedServiceInfo info;
- info.factory =
- base::BindRepeating(&media::CreateGpuMediaService, gpu_preferences_,
- task_runner_, media_gpu_channel_manager_,
- android_overlay_factory_cb_, cdm_proxy_factory_cb);
+ info.factory = base::BindRepeating(
+ &media::CreateGpuMediaService, gpu_preferences_, task_runner_,
+ media_gpu_channel_manager_, android_overlay_factory_cb_,
+ std::move(cdm_proxy_factory_cb));
// This service will host audio/video decoders, and if these decoding
// operations are blocked, user may hear audio glitch or see video freezing,
// hence "user blocking".
diff --git a/chromium/content/gpu/gpu_service_factory.h b/chromium/content/gpu/gpu_service_factory.h
index bfda11207af..ec30ff722e2 100644
--- a/chromium/content/gpu/gpu_service_factory.h
+++ b/chromium/content/gpu/gpu_service_factory.h
@@ -12,7 +12,7 @@
#include "content/child/service_factory.h"
#include "gpu/command_buffer/service/gpu_preferences.h"
#include "media/base/android_overlay_mojo_factory.h"
-#include "media/mojo/features.h"
+#include "media/mojo/buildflags.h"
namespace media {
class MediaGpuChannelManager;
diff --git a/chromium/content/ppapi_plugin/BUILD.gn b/chromium/content/ppapi_plugin/BUILD.gn
index 3ed5cf06738..b34b076bfbb 100644
--- a/chromium/content/ppapi_plugin/BUILD.gn
+++ b/chromium/content/ppapi_plugin/BUILD.gn
@@ -2,7 +2,7 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
-import("//ppapi/features/features.gni")
+import("//ppapi/buildflags/buildflags.gni")
assert(enable_plugins, "PPAPI plugins must be enabled.")
@@ -56,7 +56,7 @@ source_set("ppapi_plugin_sources") {
"//content/public/child:child_sources",
"//content/public/common:common_sources",
"//gin",
- "//media:media_features",
+ "//media:media_buildflags",
"//ppapi/c",
"//ppapi/proxy",
"//ppapi/proxy:ipc",
@@ -64,7 +64,7 @@ source_set("ppapi_plugin_sources") {
"//sandbox",
"//services/service_manager/public/mojom",
"//skia",
- "//third_party/WebKit/public:blink",
+ "//third_party/blink/public:blink",
"//third_party/icu",
"//ui/base",
"//ui/gfx",
diff --git a/chromium/content/ppapi_plugin/ppapi_blink_platform_impl.cc b/chromium/content/ppapi_plugin/ppapi_blink_platform_impl.cc
index bf3c786b509..a6e5823a51d 100644
--- a/chromium/content/ppapi_plugin/ppapi_blink_platform_impl.cc
+++ b/chromium/content/ppapi_plugin/ppapi_blink_platform_impl.cc
@@ -15,15 +15,15 @@
#include "content/child/child_thread_impl.h"
#include "ppapi/proxy/plugin_globals.h"
#include "ppapi/shared_impl/proxy_lock.h"
-#include "third_party/WebKit/public/platform/WebStorageNamespace.h"
-#include "third_party/WebKit/public/platform/WebString.h"
+#include "third_party/blink/public/platform/web_storage_namespace.h"
+#include "third_party/blink/public/platform/web_string.h"
#if defined(OS_MACOSX)
-#include "third_party/WebKit/public/platform/mac/WebSandboxSupport.h"
+#include "third_party/blink/public/platform/mac/web_sandbox_support.h"
#elif defined(OS_POSIX) && !defined(OS_ANDROID)
#include "content/child/child_process_sandbox_support_impl_linux.h"
-#include "third_party/WebKit/public/platform/linux/WebFallbackFont.h"
-#include "third_party/WebKit/public/platform/linux/WebSandboxSupport.h"
+#include "third_party/blink/public/platform/linux/web_fallback_font.h"
+#include "third_party/blink/public/platform/linux/web_sandbox_support.h"
#include "third_party/icu/source/common/unicode/utf16.h"
#endif
@@ -40,7 +40,7 @@ namespace content {
class PpapiBlinkPlatformImpl::SandboxSupport : public WebSandboxSupport {
public:
- virtual ~SandboxSupport() {}
+ ~SandboxSupport() override {}
#if defined(OS_MACOSX)
bool LoadFont(CTFontRef srcFont, CGFontRef* out, uint32_t* fontID) override;
diff --git a/chromium/content/ppapi_plugin/ppapi_plugin_main.cc b/chromium/content/ppapi_plugin/ppapi_plugin_main.cc
index 7224ebea2ef..3f59e25585d 100644
--- a/chromium/content/ppapi_plugin/ppapi_plugin_main.cc
+++ b/chromium/content/ppapi_plugin/ppapi_plugin_main.cc
@@ -32,7 +32,7 @@
#include "base/win/windows_version.h"
#include "content/child/dwrite_font_proxy/dwrite_font_proxy_init_impl_win.h"
#include "sandbox/win/src/sandbox.h"
-#include "third_party/WebKit/public/web/win/WebFontRendering.h"
+#include "third_party/blink/public/web/win/web_font_rendering.h"
#include "third_party/skia/include/ports/SkTypeface_win.h"
#include "ui/gfx/font_render_params.h"
#include "ui/gfx/win/direct_write.h"
diff --git a/chromium/content/ppapi_plugin/ppapi_thread.cc b/chromium/content/ppapi_plugin/ppapi_thread.cc
index 2f8a0176805..fb51dcfac2d 100644
--- a/chromium/content/ppapi_plugin/ppapi_thread.cc
+++ b/chromium/content/ppapi_plugin/ppapi_thread.cc
@@ -15,7 +15,6 @@
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/memory/discardable_memory_allocator.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/rand_util.h"
@@ -42,7 +41,7 @@
#include "ipc/ipc_platform_file.h"
#include "ipc/ipc_sync_channel.h"
#include "ipc/ipc_sync_message_filter.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "ppapi/c/dev/ppp_network_state_dev.h"
#include "ppapi/c/pp_errors.h"
#include "ppapi/c/ppp.h"
@@ -53,7 +52,7 @@
#include "ppapi/proxy/resource_reply_thread_registrar.h"
#include "services/service_manager/public/cpp/connector.h"
#include "services/ui/public/interfaces/constants.mojom.h"
-#include "third_party/WebKit/public/web/WebKit.h"
+#include "third_party/blink/public/web/blink.h"
#include "ui/base/ui_base_features.h"
#include "ui/base/ui_base_switches.h"
#include "ui/base/ui_features.h"
@@ -64,14 +63,7 @@
#include "sandbox/win/src/sandbox.h"
#endif
-#if BUILDFLAG(ENABLE_CDM_HOST_VERIFICATION)
-#include "media/cdm/cdm_host_file.h"
-#include "media/cdm/cdm_host_files.h"
-#endif
-
#if defined(OS_WIN)
-const char kWidevineCdmAdapterFileName[] = "widevinecdmadapter.dll";
-
extern sandbox::TargetServices* g_target_services;
// Used by EnumSystemLocales for warming up.
@@ -353,36 +345,6 @@ void PpapiThread::OnLoadPlugin(const base::FilePath& path,
}
}
-#if BUILDFLAG(ENABLE_CDM_HOST_VERIFICATION)
- // Use a local instance of CdmHostFiles so that if we return early for any
- // error, all files will be closed automatically.
- media::CdmHostFiles cdm_host_files;
- auto cdm_status = media::CdmHostFiles::Status::kNotCalled;
-
- // Open CDM host files before the process is sandboxed.
- if (!is_broker_ && media::IsCdm(path)) {
- std::vector<media::CdmHostFilePath> cdm_host_file_paths;
- GetContentClient()->AddContentDecryptionModules(nullptr,
- &cdm_host_file_paths);
- cdm_host_files.InitializeWithAdapter(path, cdm_host_file_paths);
-
-#if defined(OS_WIN)
- // On Windows, initialize CDM host verification unsandboxed. On other
- // platforms, this is called sandboxed below.
- cdm_status =
- cdm_host_files.InitVerificationWithAdapter(library.get(), path);
- // Ignore other failures for backward compatibility, e.g. when using an old
- // CDM which doesn't implement the verification API.
- if (cdm_status == media::CdmHostFiles::Status::kInitVerificationFailed) {
- LOG(WARNING) << "CDM host verification failed.";
- // TODO(xhwang): Add a new load result if needed.
- ReportLoadResult(path, INIT_FAILED);
- return;
- }
-#endif // defined(OS_WIN)
- }
-#endif // BUILDFLAG(ENABLE_CDM_HOST_VERIFICATION)
-
#if defined(OS_WIN)
// If code subsequently tries to exit using abort(), force a crash (since
// otherwise these would be silent terminations and fly under the radar).
@@ -392,13 +354,10 @@ void PpapiThread::OnLoadPlugin(const base::FilePath& path,
// can be loaded. TODO(cpu): consider changing to the loading style of
// regular plugins.
if (g_target_services) {
- // Let Flash and Widevine CDM adapter load DXVA before lockdown.
- if (permissions.HasPermission(ppapi::PERMISSION_FLASH) ||
- path.BaseName().MaybeAsASCII() == kWidevineCdmAdapterFileName) {
+ if (permissions.HasPermission(ppapi::PERMISSION_FLASH)) {
+ // Let Flash load DXVA before lockdown.
LoadLibraryA("dxva2.dll");
- }
- if (permissions.HasPermission(ppapi::PERMISSION_FLASH)) {
base::CPU cpu;
if (cpu.vendor_name() == "AuthenticAMD") {
// The AMD crypto acceleration is only AMD Bulldozer and above.
@@ -407,7 +366,7 @@ void PpapiThread::OnLoadPlugin(const base::FilePath& path,
#else
LoadLibraryA("amdhcp32.dll");
#endif
- }
+ }
}
// Cause advapi32 to load before the sandbox is turned on.
@@ -459,27 +418,6 @@ void PpapiThread::OnLoadPlugin(const base::FilePath& path,
}
#endif
-#if BUILDFLAG(ENABLE_CDM_HOST_VERIFICATION)
- if (!is_broker_ && media::IsCdm(path)) {
-#if !defined(OS_WIN)
- // Now we are sandboxed, initialize CDM host verification.
- cdm_status =
- cdm_host_files.InitVerificationWithAdapter(library.get(), path);
- // Ignore other failures for backward compatibility, e.g. when using an
- // old CDM which doesn't implement the verification API.
- if (cdm_status == media::CdmHostFiles::Status::kInitVerificationFailed) {
- LOG(WARNING) << "CDM host verification failed.";
- // TODO(xhwang): Add a new load result if needed.
- ReportLoadResult(path, INIT_FAILED);
- return;
- }
-#endif // !defined(OS_WIN)
- UMA_HISTOGRAM_ENUMERATION("Media.EME.CdmHostVerificationStatus",
- cdm_status,
- media::CdmHostFiles::Status::kStatusCount);
- }
-#endif // BUILDFLAG(ENABLE_CDM_HOST_VERIFICATION)
-
int32_t init_error = plugin_entry_points_.initialize_module(
local_pp_module_, &ppapi::proxy::PluginDispatcher::GetBrowserInterface);
if (init_error != PP_OK) {
diff --git a/chromium/content/public/android/BUILD.gn b/chromium/content/public/android/BUILD.gn
index 8ee00ba7142..cae8e5cb0a8 100644
--- a/chromium/content/public/android/BUILD.gn
+++ b/chromium/content/public/android/BUILD.gn
@@ -4,7 +4,7 @@
import("//build/config/android/config.gni")
import("//build/config/android/rules.gni")
-import("//device/vr/features/features.gni")
+import("//device/vr/buildflags/buildflags.gni")
android_aidl("common_aidl") {
interface_file = "java/src/org/chromium/content/common/common.aidl"
@@ -38,7 +38,6 @@ android_library("content_java") {
"//components/download/public/common:public_java",
"//device/bluetooth:java",
"//device/gamepad:java",
- "//device/sensors:java",
"//device/usb:java",
"//media/base/android:media_java",
"//media/capture/content/android:screen_capture_java",
@@ -47,6 +46,7 @@ android_library("content_java") {
"//media/mojo/interfaces:interfaces_java",
"//mojo/android:system_java",
"//mojo/common:common_custom_types_java",
+ "//mojo/public/java:base_java",
"//mojo/public/java:bindings_java",
"//mojo/public/java:system_java",
"//net/android:net_java",
@@ -56,10 +56,10 @@ android_library("content_java") {
"//services/service_manager/public/mojom:mojom_java",
"//services/shape_detection:shape_detection_java",
"//services/shape_detection/public/mojom:mojom_java",
- "//third_party/WebKit/public:android_mojo_bindings_java",
- "//third_party/WebKit/public:blink_headers_java",
- "//third_party/WebKit/public/mojom:mojom_java",
"//third_party/android_tools:android_support_annotations_java",
+ "//third_party/blink/public:android_mojo_bindings_java",
+ "//third_party/blink/public:blink_headers_java",
+ "//third_party/blink/public/mojom:mojom_core_java",
"//third_party/jsr-305:jsr_305_javalib",
"//ui/android:ui_java",
"//ui/gfx/geometry/mojo:mojo_java",
@@ -132,12 +132,12 @@ android_library("content_java") {
"java/src/org/chromium/content/browser/JavascriptInterface.java",
"java/src/org/chromium/content/browser/JoystickHandler.java",
"java/src/org/chromium/content/browser/LauncherThread.java",
- "java/src/org/chromium/content/browser/MediaResourceGetter.java",
"java/src/org/chromium/content/browser/MediaSessionImpl.java",
"java/src/org/chromium/content/browser/MemoryMonitorAndroid.java",
"java/src/org/chromium/content/browser/MotionEventSynthesizer.java",
"java/src/org/chromium/content/browser/NfcHost.java",
"java/src/org/chromium/content/browser/PepperPluginManager.java",
+ "java/src/org/chromium/content/browser/PopupController.java",
"java/src/org/chromium/content/browser/PopupZoomer.java",
"java/src/org/chromium/content/browser/PositionObserver.java",
"java/src/org/chromium/content/browser/RenderCoordinates.java",
@@ -156,6 +156,7 @@ android_library("content_java") {
"java/src/org/chromium/content/browser/accessibility/WebContentsAccessibilityImpl.java",
"java/src/org/chromium/content/browser/accessibility/captioning/CaptioningBridgeFactory.java",
"java/src/org/chromium/content/browser/accessibility/captioning/CaptioningChangeDelegate.java",
+ "java/src/org/chromium/content/browser/accessibility/captioning/CaptioningController.java",
"java/src/org/chromium/content/browser/accessibility/captioning/CaptioningStyle.java",
"java/src/org/chromium/content/browser/accessibility/captioning/EmptyCaptioningBridge.java",
"java/src/org/chromium/content/browser/accessibility/captioning/KitKatCaptioningBridge.java",
@@ -207,12 +208,12 @@ android_library("content_java") {
"java/src/org/chromium/content/browser/picker/WeekPickerDialog.java",
"java/src/org/chromium/content/browser/remoteobjects/RemoteObjectAuditorImpl.java",
"java/src/org/chromium/content/browser/remoteobjects/RemoteObjectImpl.java",
+ "java/src/org/chromium/content/browser/selection/AdditionalMenuItemProvider.java",
"java/src/org/chromium/content/browser/selection/FloatingActionModeCallback.java",
"java/src/org/chromium/content/browser/selection/FloatingPastePopupMenu.java",
"java/src/org/chromium/content/browser/selection/HandleViewResources.java",
"java/src/org/chromium/content/browser/selection/LGEmailActionModeWorkaround.java",
"java/src/org/chromium/content/browser/selection/LegacyPastePopupMenu.java",
- "java/src/org/chromium/content/browser/selection/MenuDescriptor.java",
"java/src/org/chromium/content/browser/selection/PastePopupMenu.java",
"java/src/org/chromium/content/browser/selection/SelectionEventProxyImpl.java",
"java/src/org/chromium/content/browser/selection/SelectionIndicesConverter.java",
@@ -231,7 +232,6 @@ android_library("content_java") {
"java/src/org/chromium/content_public/browser/ActionModeCallbackHelper.java",
"java/src/org/chromium/content_public/browser/ChildProcessUtils.java",
"java/src/org/chromium/content_public/browser/InputMethodManagerWrapper.java",
- "java/src/org/chromium/content_public/browser/ContentBitmapCallback.java",
"java/src/org/chromium/content_public/browser/ContentViewCore.java",
"java/src/org/chromium/content_public/browser/GestureListenerManager.java",
"java/src/org/chromium/content_public/browser/GestureStateListener.java",
@@ -260,7 +260,6 @@ android_library("content_java") {
"java/src/org/chromium/content_public/browser/WebContentsInternals.java",
"java/src/org/chromium/content_public/browser/WebContentsObserver.java",
"java/src/org/chromium/content_public/browser/WebContentsStatics.java",
- "java/src/org/chromium/content_public/common/BrowserSideNavigationPolicy.java",
"java/src/org/chromium/content_public/common/ContentProcessInfo.java",
"java/src/org/chromium/content_public/common/ContentUrlConstants.java",
"java/src/org/chromium/content_public/common/MediaMetadata.java",
@@ -323,7 +322,7 @@ java_strings_grd("content_strings_grd") {
java_cpp_enum("content_public_android_java_enums_srcjar") {
sources = [
- "//content/browser/android/content_view_core.cc",
+ "//content/browser/android/select_popup.cc",
"//content/public/browser/android/child_process_importance.h",
"//content/public/browser/android/motion_event_action.h",
"//content/public/browser/invalidate_type.h",
@@ -366,7 +365,6 @@ generate_jni("content_jni_headers") {
"java/src/org/chromium/content/browser/InterstitialPageDelegateAndroid.java",
"java/src/org/chromium/content/browser/JavascriptInjectorImpl.java",
"java/src/org/chromium/content/browser/LauncherThread.java",
- "java/src/org/chromium/content/browser/MediaResourceGetter.java",
"java/src/org/chromium/content/browser/MediaSessionImpl.java",
"java/src/org/chromium/content/browser/MemoryMonitorAndroid.java",
"java/src/org/chromium/content/browser/NfcHost.java",
@@ -376,12 +374,14 @@ generate_jni("content_jni_headers") {
"java/src/org/chromium/content/browser/TapDisambiguator.java",
"java/src/org/chromium/content/browser/TracingControllerAndroid.java",
"java/src/org/chromium/content/browser/accessibility/WebContentsAccessibilityImpl.java",
+ "java/src/org/chromium/content/browser/accessibility/captioning/CaptioningController.java",
"java/src/org/chromium/content/browser/androidoverlay/AndroidOverlayProviderImpl.java",
"java/src/org/chromium/content/browser/androidoverlay/DialogOverlayImpl.java",
"java/src/org/chromium/content/browser/framehost/NavigationControllerImpl.java",
"java/src/org/chromium/content/browser/framehost/RenderFrameHostImpl.java",
"java/src/org/chromium/content/browser/input/DateTimeChooserAndroid.java",
"java/src/org/chromium/content/browser/input/ImeAdapterImpl.java",
+ "java/src/org/chromium/content/browser/input/SelectPopup.java",
"java/src/org/chromium/content/browser/input/SuggestionInfo.java",
"java/src/org/chromium/content/browser/input/TextSuggestionHost.java",
"java/src/org/chromium/content/browser/selection/HandleViewResources.java",
@@ -390,7 +390,6 @@ generate_jni("content_jni_headers") {
"java/src/org/chromium/content/browser/webcontents/WebContentsImpl.java",
"java/src/org/chromium/content/browser/webcontents/WebContentsObserverProxy.java",
"java/src/org/chromium/content_public/browser/LoadUrlParams.java",
- "java/src/org/chromium/content_public/common/BrowserSideNavigationPolicy.java",
"java/src/org/chromium/content_public/common/MediaMetadata.java",
"java/src/org/chromium/content_public/common/ResourceRequestBody.java",
"java/src/org/chromium/content_public/common/UseZoomForDSFPolicy.java",
@@ -410,7 +409,7 @@ android_library("content_javatests") {
srcjar_deps = [
"//content/shell/android:content_javatests_aidl",
- "//third_party/WebKit/public:blink_cursor_type_java_enums_srcjar",
+ "//third_party/blink/public:blink_cursor_type_java_enums_srcjar",
]
deps = [
@@ -428,10 +427,10 @@ android_library("content_javatests") {
"//media/capture/video/android:capture_java",
"//media/mojo/interfaces:interfaces_java",
"//mojo/android:system_java",
- "//mojo/common:common_custom_types_java",
"//mojo/public/interfaces/bindings/tests:test_interfaces_java",
"//mojo/public/java:bindings_java",
"//mojo/public/java:system_java",
+ "//mojo/public/mojom/base:base_java",
"//net/android:net_java",
"//net/android:net_java_test_support",
"//third_party/android_support_test_runner:rules_java",
@@ -469,7 +468,6 @@ android_library("content_javatests") {
"javatests/src/org/chromium/content/browser/JavaBridgeCoercionTest.java",
"javatests/src/org/chromium/content/browser/JavaBridgeFieldsTest.java",
"javatests/src/org/chromium/content/browser/JavaBridgeReturnValuesTest.java",
- "javatests/src/org/chromium/content/browser/MediaResourceGetterTest.java",
"javatests/src/org/chromium/content/browser/MediaSessionTest.java",
"javatests/src/org/chromium/content/browser/NavigationTest.java",
"javatests/src/org/chromium/content/browser/PopupZoomerTest.java",
@@ -523,7 +521,6 @@ junit_binary("content_junit_tests") {
"junit/src/org/chromium/content/browser/input/ThreadedInputConnectionTest.java",
"junit/src/org/chromium/content/browser/picker/DateDialogNormalizerTest.java",
"junit/src/org/chromium/content/browser/remoteobjects/RemoteObjectImplTest.java",
- "junit/src/org/chromium/content/browser/selection/MenuDescriptorTest.java",
"junit/src/org/chromium/content/browser/selection/SelectionPopupControllerTest.java",
"junit/src/org/chromium/content/browser/selection/SmartSelectionMetricsLoggerTest.java",
]
@@ -535,7 +532,7 @@ junit_binary("content_junit_tests") {
"//base:base_junit_test_support",
"//media/mojo/interfaces:interfaces_java",
"//mojo/public/java:bindings_java",
- "//third_party/WebKit/public:android_mojo_bindings_java",
+ "//third_party/blink/public:android_mojo_bindings_java",
"//ui/android:ui_java",
"//ui/gfx/geometry/mojo:mojo_java",
]
diff --git a/chromium/content/public/app/BUILD.gn b/chromium/content/public/app/BUILD.gn
index cbf8c652d41..004f301cbd7 100644
--- a/chromium/content/public/app/BUILD.gn
+++ b/chromium/content/public/app/BUILD.gn
@@ -183,6 +183,7 @@ service_manifest("packaged_services_manifest") {
name = "content_packaged_services"
source = "mojo/content_packaged_services_manifest.json"
packaged_services = [
+ "//components/services/heap_profiling:manifest",
"//media/mojo/services:cdm_manifest",
"//media/mojo/services:media_manifest",
"//services/audio:manifest",
diff --git a/chromium/content/public/app/mojo/content_browser_manifest.json b/chromium/content/public/app/mojo/content_browser_manifest.json
index 5a217fa9b74..7e3b765742a 100644
--- a/chromium/content/public/app/mojo/content_browser_manifest.json
+++ b/chromium/content/public/app/mojo/content_browser_manifest.json
@@ -18,6 +18,9 @@
"font_cache": [
"content::mojom::FontCacheWin"
],
+ "font_loader": [
+ "content::mojom::FontLoaderMac"
+ ],
"gpu": [
"discardable_memory::mojom::DiscardableSharedMemoryManager",
"media::mojom::AndroidOverlayProvider"
@@ -42,6 +45,7 @@
"content::mojom::FieldTrialRecorder",
"content::mojom::FileUtilitiesHost",
"content::mojom::FrameSinkProvider",
+ "content::mojom::MediaStreamTrackMetricsHost",
"content::mojom::MemoryCoordinatorHandle",
"content::mojom::PeerConnectionTrackerHost",
"content::mojom::PushMessaging",
@@ -133,6 +137,7 @@
"autofill::mojom::PasswordManagerDriver",
"blink::mojom::BackgroundFetchService",
"blink::mojom::BudgetService",
+ "blink::mojom::CacheStorage",
"blink::mojom::ColorChooserFactory",
"blink::mojom::DedicatedWorkerFactory",
"blink::mojom::LockManager",
@@ -147,8 +152,8 @@
"blink::mojom::PresentationService",
"blink::mojom::QuotaDispatcherHost",
"blink::mojom::TextSuggestionHost",
+ "blink::mojom::UnhandledTapNotifier",
"blink::mojom::WebBluetoothService",
- "blink::mojom::WebSocket",
// TODO(beng): figure out how to overlay test interfaces like this.
"content::mojom::BrowserTarget",
@@ -177,6 +182,7 @@
"media::mojom::RemoterFactory",
"media::mojom::Renderer",
"network::mojom::RestrictedCookieManager",
+ "network::mojom::WebSocket",
"password_manager::mojom::CredentialManager",
"payments::mojom::PaymentManager",
"payments::mojom::PaymentRequest",
@@ -185,7 +191,8 @@
"shape_detection::mojom::FaceDetectionProvider",
"shape_detection::mojom::TextDetection",
"ui::mojom::Gpu",
- "webauth::mojom::Authenticator"
+ "webauth::mojom::Authenticator",
+ "webauth::test::mojom::VirtualAuthenticatorManager"
]
},
"requires": {
@@ -196,10 +203,12 @@
"provides": {
"renderer": [
"blink::mojom::BudgetService",
+ "blink::mojom::CacheStorage",
"blink::mojom::LockManager",
"blink::mojom::NotificationService",
"blink::mojom::PermissionService",
"blink::mojom::QuotaDispatcherHost",
+ "network::mojom::WebSocket",
"payments::mojom::PaymentManager",
"shape_detection::mojom::BarcodeDetection",
"shape_detection::mojom::FaceDetectionProvider",
@@ -212,12 +221,13 @@
"renderer": [
"blink::mojom::BackgroundFetchService",
"blink::mojom::BudgetService",
+ "blink::mojom::CacheStorage",
"blink::mojom::LockManager",
"blink::mojom::NotificationService",
"blink::mojom::PermissionService",
"blink::mojom::QuotaDispatcherHost",
- "blink::mojom::WebSocket",
"network::mojom::RestrictedCookieManager",
+ "network::mojom::WebSocket",
"payments::mojom::PaymentManager",
"shape_detection::mojom::BarcodeDetection",
"shape_detection::mojom::FaceDetectionProvider",
@@ -229,11 +239,12 @@
"provides": {
"renderer": [
"blink::mojom::BudgetService",
+ "blink::mojom::CacheStorage",
"blink::mojom::LockManager",
"blink::mojom::NotificationService",
"blink::mojom::PermissionService",
"blink::mojom::QuotaDispatcherHost",
- "blink::mojom::WebSocket",
+ "network::mojom::WebSocket",
"payments::mojom::PaymentManager",
"shape_detection::mojom::BarcodeDetection",
"shape_detection::mojom::FaceDetectionProvider",
diff --git a/chromium/content/public/app/mojo/content_renderer_manifest.json b/chromium/content/public/app/mojo/content_renderer_manifest.json
index e8d2800c343..9c5f03aad42 100644
--- a/chromium/content/public/app/mojo/content_renderer_manifest.json
+++ b/chromium/content/public/app/mojo/content_renderer_manifest.json
@@ -31,6 +31,7 @@
"content_browser": [
"dwrite_font_proxy",
"field_trials",
+ "font_loader",
"renderer"
],
"metrics": [ "url_keyed_metrics" ],
@@ -92,14 +93,6 @@
"path": "assets/natives_blob.bin",
"platform": "android"
}
- ],
- "v8_snapshot_32_data" : [{
- "path": "assets/snapshot_blob_32.bin",
- "platform": "android"
- }],
- "v8_snapshot_64_data" : [{
- "path": "assets/snapshot_blob_64.bin",
- "platform": "android"
- }]
+ ]
}
}
diff --git a/chromium/content/public/app/mojo/content_utility_manifest.json b/chromium/content/public/app/mojo/content_utility_manifest.json
index 7676e217d8f..e5cc53c978e 100644
--- a/chromium/content/public/app/mojo/content_utility_manifest.json
+++ b/chromium/content/public/app/mojo/content_utility_manifest.json
@@ -43,14 +43,6 @@
"path": "assets/natives_blob.bin",
"platform": "android"
}
- ],
- "v8_snapshot_32_data" : [{
- "path": "assets/snapshot_blob_32.bin",
- "platform": "android"
- }],
- "v8_snapshot_64_data" : [{
- "path": "assets/snapshot_blob_64.bin",
- "platform": "android"
- }]
+ ]
}
}
diff --git a/chromium/content/public/app/mojo/context_snapshot_manifest.json b/chromium/content/public/app/mojo/context_snapshot_manifest.json
index 9cf904bfe73..88497508111 100644
--- a/chromium/content/public/app/mojo/context_snapshot_manifest.json
+++ b/chromium/content/public/app/mojo/context_snapshot_manifest.json
@@ -3,7 +3,14 @@
"v8_context_snapshot_data" : [{
"path": "v8_context_snapshot.bin",
"platform": "linux"
+ }],
+ "v8_snapshot_32_data" : [{
+ "path": "assets/v8_context_snapshot_32.bin",
+ "platform": "android"
+ }],
+ "v8_snapshot_64_data" : [{
+ "path": "assets/v8_context_snapshot_64.bin",
+ "platform": "android"
}]
}
}
-
diff --git a/chromium/content/public/app/mojo/snapshot_blob_manifest.json b/chromium/content/public/app/mojo/snapshot_blob_manifest.json
index a9202b05959..552e18a9363 100644
--- a/chromium/content/public/app/mojo/snapshot_blob_manifest.json
+++ b/chromium/content/public/app/mojo/snapshot_blob_manifest.json
@@ -3,6 +3,14 @@
"v8_snapshot_data" : [{
"path": "snapshot_blob.bin",
"platform": "linux"
+ }],
+ "v8_snapshot_32_data" : [{
+ "path": "assets/snapshot_blob_32.bin",
+ "platform": "android"
+ }],
+ "v8_snapshot_64_data" : [{
+ "path": "assets/snapshot_blob_64.bin",
+ "platform": "android"
}]
}
}
diff --git a/chromium/content/public/browser/BUILD.gn b/chromium/content/public/browser/BUILD.gn
index 63ee6a83cc9..9646d6b0555 100644
--- a/chromium/content/public/browser/BUILD.gn
+++ b/chromium/content/public/browser/BUILD.gn
@@ -84,6 +84,7 @@ jumbo_source_set("browser_sources") {
"cdm_registry.h",
"certificate_request_result_type.h",
"child_process_data.h",
+ "child_process_launcher_utils.h",
"child_process_security_policy.h",
"client_certificate_delegate.h",
"color_chooser.h",
@@ -142,9 +143,11 @@ jumbo_source_set("browser_sources") {
"keyboard_event_processing_result.h",
"load_notification_details.h",
"local_storage_usage_info.h",
+ "login_delegate.h",
"manifest_icon_downloader.h",
"manifest_icon_selector.h",
"media_capture_devices.h",
+ "media_controller.h",
"media_device_id.cc",
"media_device_id.h",
"media_request_state.h",
@@ -180,6 +183,7 @@ jumbo_source_set("browser_sources") {
"notification_service.h",
"notification_source.h",
"notification_types.h",
+ "overlay_window.h",
"overscroll_configuration.h",
"page_navigator.cc",
"page_navigator.h",
@@ -188,6 +192,7 @@ jumbo_source_set("browser_sources") {
"pepper_vpn_provider_resource_host_proxy.h",
"permission_manager.h",
"permission_type.h",
+ "picture_in_picture_window_controller.h",
"platform_notification_context.h",
"platform_notification_service.h",
"plugin_data_remover.h",
@@ -219,7 +224,6 @@ jumbo_source_set("browser_sources") {
"resource_dispatcher_host.h",
"resource_dispatcher_host_delegate.cc",
"resource_dispatcher_host_delegate.h",
- "resource_dispatcher_host_login_delegate.h",
"resource_hints.h",
"resource_request_info.h",
"resource_throttle.cc",
@@ -239,6 +243,8 @@ jumbo_source_set("browser_sources") {
"session_storage_usage_info.h",
"shared_worker_service.h",
"site_instance.h",
+ "site_isolation_policy.cc",
+ "site_isolation_policy.h",
"speech_recognition_event_listener.h",
"speech_recognition_manager.h",
"speech_recognition_manager_delegate.h",
@@ -265,9 +271,6 @@ jumbo_source_set("browser_sources") {
"tracing_delegate.h",
"url_data_source.cc",
"url_data_source.h",
- "utility_process_host.h",
- "utility_process_host_client.h",
- "utility_process_mojo_client.h",
"video_capture_device_launcher.h",
"visibility.h",
"vpn_service_proxy.h",
@@ -285,12 +288,16 @@ jumbo_source_set("browser_sources") {
"web_contents_view_delegate.cc",
"web_contents_view_delegate.h",
"web_drag_dest_delegate.h",
+ "web_package_context.h",
"web_ui.h",
"web_ui_controller.cc",
"web_ui_controller.h",
"web_ui_controller_factory.h",
"web_ui_data_source.h",
"web_ui_message_handler.h",
+ "web_ui_url_loader_factory.h",
+ "webrtc_event_logger.cc",
+ "webrtc_event_logger.h",
"websocket_handshake_request_info.h",
"webvr_service_provider.cc",
"webvr_service_provider.h",
@@ -319,7 +326,7 @@ jumbo_source_set("browser_sources") {
# We expose storage headers for quota and blob storage context in the public API.
"//storage/browser",
- "//third_party/WebKit/public:mojo_bindings",
+ "//third_party/blink/public:mojo_bindings",
]
deps = [
"//cc",
@@ -345,7 +352,7 @@ jumbo_source_set("browser_sources") {
"//content/browser",
]
- if (is_posix) {
+ if (is_posix || is_fuchsia) {
sources += [ "posix_file_descriptor_info.h" ]
}
diff --git a/chromium/content/public/browser/android/synchronous_compositor.h b/chromium/content/public/browser/android/synchronous_compositor.h
index c9f604704a9..a086271d7fa 100644
--- a/chromium/content/public/browser/android/synchronous_compositor.h
+++ b/chromium/content/public/browser/android/synchronous_compositor.h
@@ -79,12 +79,6 @@ class CONTENT_EXPORT SynchronousCompositor {
// |viewport_size| is the current size to improve results during resize.
// |viewport_rect_for_tile_priority| and |transform_for_tile_priority| are
// used to customize the tiling decisions of compositor.
- virtual Frame DemandDrawHw(
- const gfx::Size& viewport_size,
- const gfx::Rect& viewport_rect_for_tile_priority,
- const gfx::Transform& transform_for_tile_priority) = 0;
-
- // Same as DemandDrawHw, but uses asynchronous IPC messages.
virtual scoped_refptr<FrameFuture> DemandDrawHwAsync(
const gfx::Size& viewport_size,
const gfx::Rect& viewport_rect_for_tile_priority,
diff --git a/chromium/content/public/browser/appcache_service.h b/chromium/content/public/browser/appcache_service.h
index cfe7263839e..a6b83ee3ca8 100644
--- a/chromium/content/public/browser/appcache_service.h
+++ b/chromium/content/public/browser/appcache_service.h
@@ -13,6 +13,7 @@
#include "content/common/content_export.h"
#include "content/public/common/appcache_info.h"
#include "net/base/completion_callback.h"
+#include "url/origin.h"
namespace content {
@@ -21,7 +22,7 @@ struct CONTENT_EXPORT AppCacheInfoCollection
: public base::RefCountedThreadSafe<AppCacheInfoCollection> {
AppCacheInfoCollection();
- std::map<GURL, AppCacheInfoVector> infos_by_origin;
+ std::map<url::Origin, AppCacheInfoVector> infos_by_origin;
private:
friend class base::RefCountedThreadSafe<AppCacheInfoCollection>;
diff --git a/chromium/content/public/browser/background_fetch_delegate.h b/chromium/content/public/browser/background_fetch_delegate.h
index 8b6670062f1..6830505d4f0 100644
--- a/chromium/content/public/browser/background_fetch_delegate.h
+++ b/chromium/content/public/browser/background_fetch_delegate.h
@@ -9,12 +9,18 @@
#include <string>
#include <vector>
+#include "base/callback_forward.h"
#include "base/files/file_path.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "content/common/content_export.h"
class GURL;
+class SkBitmap;
+
+namespace gfx {
+class Size;
+}
namespace net {
class HttpRequestHeaders;
@@ -35,6 +41,8 @@ struct BackgroundFetchResult;
// BackgroundFetchDelegateProxy.
class CONTENT_EXPORT BackgroundFetchDelegate {
public:
+ using GetIconDisplaySizeCallback = base::OnceCallback<void(const gfx::Size&)>;
+
// Client interface that a BackgroundFetchDelegate would use to signal the
// progress of a background fetch.
class Client {
@@ -74,6 +82,9 @@ class CONTENT_EXPORT BackgroundFetchDelegate {
virtual ~BackgroundFetchDelegate();
+ // Gets size of the icon to display with the Background Fetch UI.
+ virtual void GetIconDisplaySize(GetIconDisplaySizeCallback callback) = 0;
+
// Creates a new download grouping identified by |job_unique_id|. Further
// downloads started by DownloadUrl will also use this |job_unique_id| so that
// a notification can be updated with the current status. If the download was
@@ -84,6 +95,7 @@ class CONTENT_EXPORT BackgroundFetchDelegate {
const std::string& job_unique_id,
const std::string& title,
const url::Origin& origin,
+ const SkBitmap& icon,
int completed_parts,
int total_parts,
const std::vector<std::string>& current_guids) = 0;
diff --git a/chromium/content/public/browser/blob_handle.h b/chromium/content/public/browser/blob_handle.h
index debbe2afe3d..eb106fc035c 100644
--- a/chromium/content/public/browser/blob_handle.h
+++ b/chromium/content/public/browser/blob_handle.h
@@ -6,7 +6,7 @@
#define CONTENT_PUBLIC_BROWSER_BLOB_HANDLE_H_
#include <string>
-#include "third_party/WebKit/public/mojom/blob/blob.mojom.h"
+#include "third_party/blink/public/mojom/blob/blob.mojom.h"
namespace content {
diff --git a/chromium/content/public/browser/browser_context.h b/chromium/content/public/browser/browser_context.h
index 9edd7b1d912..ddb42286696 100644
--- a/chromium/content/public/browser/browser_context.h
+++ b/chromium/content/public/browser/browser_context.h
@@ -15,7 +15,6 @@
#include "base/callback_forward.h"
#include "base/containers/hash_tables.h"
-#include "base/memory/linked_ptr.h"
#include "base/supports_user_data.h"
#include "content/common/content_export.h"
#include "net/url_request/url_request_interceptor.h"
@@ -81,7 +80,7 @@ class SSLHostStateDelegate;
// content.
using ProtocolHandlerMap =
std::map<std::string,
- linked_ptr<net::URLRequestJobFactory::ProtocolHandler>>;
+ std::unique_ptr<net::URLRequestJobFactory::ProtocolHandler>>;
// A owning vector of protocol interceptors.
using URLRequestInterceptorScopedVector =
@@ -319,6 +318,7 @@ class CONTENT_EXPORT BrowserContext : public base::SupportsUserData {
private:
const std::string media_device_id_salt_;
+ bool was_notify_will_be_destroyed_called_ = false;
};
} // namespace content
diff --git a/chromium/content/public/browser/browser_ipc_logging.h b/chromium/content/public/browser/browser_ipc_logging.h
index bcbd0b171ad..a893e6a9d51 100644
--- a/chromium/content/public/browser/browser_ipc_logging.h
+++ b/chromium/content/public/browser/browser_ipc_logging.h
@@ -6,7 +6,7 @@
#define CONTENT_PUBLIC_BROWSER_BROWSER_IPC_LOGGING_H_
#include "content/common/content_export.h"
-#include "ipc/ipc_features.h"
+#include "ipc/ipc_buildflags.h"
namespace content {
diff --git a/chromium/content/public/browser/browser_message_filter.cc b/chromium/content/public/browser/browser_message_filter.cc
index 1b08c55b05c..8f10336a9a9 100644
--- a/chromium/content/public/browser/browser_message_filter.cc
+++ b/chromium/content/public/browser/browser_message_filter.cc
@@ -174,7 +174,7 @@ void BrowserMessageFilter::ShutdownForBadMessage() {
}
ChildProcessLauncher::TerminateProcess(
- peer_process_, content::RESULT_CODE_KILLED_BAD_MESSAGE, false);
+ peer_process_, content::RESULT_CODE_KILLED_BAD_MESSAGE);
// Report a crash, since none will be generated by the killed renderer.
base::debug::DumpWithoutCrashing();
diff --git a/chromium/content/public/browser/browser_plugin_guest_manager.cc b/chromium/content/public/browser/browser_plugin_guest_manager.cc
index 6db83291ad9..81a843b246a 100644
--- a/chromium/content/public/browser/browser_plugin_guest_manager.cc
+++ b/chromium/content/public/browser/browser_plugin_guest_manager.cc
@@ -12,9 +12,8 @@ WebContents* BrowserPluginGuestManager::GetGuestByInstanceID(
return nullptr;
}
-bool BrowserPluginGuestManager::ForEachGuest(
- WebContents* embedder_web_contents,
- const GuestCallback& callback) {
+bool BrowserPluginGuestManager::ForEachGuest(WebContents* embedder_web_contents,
+ const GuestCallback& callback) {
return false;
}
diff --git a/chromium/content/public/browser/browser_plugin_guest_manager.h b/chromium/content/public/browser/browser_plugin_guest_manager.h
index c809c0ff7e5..4e1019c316d 100644
--- a/chromium/content/public/browser/browser_plugin_guest_manager.h
+++ b/chromium/content/public/browser/browser_plugin_guest_manager.h
@@ -26,7 +26,7 @@ class CONTENT_EXPORT BrowserPluginGuestManager {
// Iterates over all WebContents belonging to a given |embedder_web_contents|,
// calling |callback| for each. If one of the callbacks returns true, then
// the iteration exits early.
- typedef base::Callback<bool(WebContents*)> GuestCallback;
+ using GuestCallback = base::RepeatingCallback<bool(WebContents*)>;
virtual bool ForEachGuest(WebContents* embedder_web_contents,
const GuestCallback& callback);
diff --git a/chromium/content/public/browser/browser_thread.h b/chromium/content/public/browser/browser_thread.h
index a4bdf199823..5d439726026 100644
--- a/chromium/content/public/browser/browser_thread.h
+++ b/chromium/content/public/browser/browser_thread.h
@@ -13,16 +13,12 @@
#include "base/location.h"
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ref_counted.h"
+#include "base/memory/scoped_refptr.h"
#include "base/single_thread_task_runner.h"
#include "base/task_runner_util.h"
#include "base/time/time.h"
#include "content/common/content_export.h"
-
-namespace base {
-class MessageLoop;
-class Thread;
-}
+#include "content/public/browser/browser_thread.h"
namespace content {
@@ -67,17 +63,12 @@ class CONTENT_EXPORT BrowserThread {
// The main thread in the browser.
UI,
- // Used to launch and terminate Chrome processes.
- PROCESS_LAUNCHER,
-
// This is the thread that processes non-blocking IO, i.e. IPC and network.
- // Blocking IO should happen in TaskScheduler.
+ // Blocking I/O should happen in TaskScheduler.
IO,
- // NOTE: do not add new threads here that are only used by a small number of
- // files. Instead you should just use a Thread class and pass its
- // task runner around. Named threads there are only for threads that
- // are used in many places.
+ // NOTE: do not add new threads here. Instead you should just use
+ // base::Create*TaskRunnerWithTraits.
// This identifier does not represent a thread. Instead it counts the
// number of well-known threads. Insert new well-known threads before this
@@ -181,11 +172,6 @@ class CONTENT_EXPORT BrowserThread {
// thread. To DCHECK this, use the DCHECK_CURRENTLY_ON() macro above.
static bool CurrentlyOn(ID identifier) WARN_UNUSED_RESULT;
- // Callable on any thread. Returns whether the threads message loop is valid.
- // If this returns false it means the thread is in the process of shutting
- // down.
- static bool IsMessageLoopValid(ID identifier) WARN_UNUSED_RESULT;
-
// If the current message loop is one of the known threads, returns true and
// sets identifier to its ID. Otherwise returns false.
static bool GetCurrentThreadIdentifier(ID* identifier) WARN_UNUSED_RESULT;
@@ -197,16 +183,12 @@ class CONTENT_EXPORT BrowserThread {
// Sets the delegate for BrowserThread::IO.
//
- // This only supports the IO thread as it doesn't work for potentially
- // redirected threads (ref. http://crbug.com/653916) and also doesn't make
- // sense for the UI thread.
- //
// Only one delegate may be registered at a time. The delegate may be
// unregistered by providing a nullptr pointer.
//
- // If the caller unregisters the delegate before CleanUp has been called, it
- // must perform its own locking to ensure the delegate is not deleted while
- // unregistering.
+ // The delegate can only be registered through this call before
+ // BrowserThreadImpl(BrowserThread::IO) is created and unregistered after
+ // it was destroyed and its underlying thread shutdown.
static void SetIOThreadDelegate(BrowserThreadDelegate* delegate);
// Use these templates in conjunction with RefCountedThreadSafe or scoped_ptr
diff --git a/chromium/content/public/browser/browser_thread_delegate.h b/chromium/content/public/browser/browser_thread_delegate.h
index 696b76d807e..3eb823c3249 100644
--- a/chromium/content/public/browser/browser_thread_delegate.h
+++ b/chromium/content/public/browser/browser_thread_delegate.h
@@ -5,22 +5,20 @@
#ifndef CONTENT_PUBLIC_BROWSER_BROWSER_THREAD_DELEGATE_H_
#define CONTENT_PUBLIC_BROWSER_BROWSER_THREAD_DELEGATE_H_
+#include "content/common/content_export.h"
+
namespace content {
-// BrowserThread::SetDelegate was deprecated, this is now only used by
-// BrowserThread::SetIOThreadDelegate.
-//
-// When registered as such, it will schedule to run Init() before the message
-// loop begins and receive a CleanUp call right after the message loop ends (and
-// before the BrowserThread has done its own clean-up).
+// A Delegate for content embedders to perform extra initialization/cleanup on
+// BrowserThread::IO.
class BrowserThreadDelegate {
public:
virtual ~BrowserThreadDelegate() = default;
- // Called prior to starting the message loop
+ // Called prior to completing initialization of BrowserThread::IO.
virtual void Init() = 0;
- // Called just after the message loop ends.
+ // Called during teardown of BrowserThread::IO.
virtual void CleanUp() = 0;
};
diff --git a/chromium/content/public/browser/browsing_data_filter_builder.h b/chromium/content/public/browser/browsing_data_filter_builder.h
index e5d49fe8356..1d75cd40e94 100644
--- a/chromium/content/public/browser/browsing_data_filter_builder.h
+++ b/chromium/content/public/browser/browsing_data_filter_builder.h
@@ -13,6 +13,7 @@
#include "base/callback_forward.h"
#include "content/common/content_export.h"
+#include "services/network/public/mojom/network_service.mojom.h"
class GURL;
@@ -69,6 +70,11 @@ class CONTENT_EXPORT BrowsingDataFilterBuilder {
virtual base::RepeatingCallback<bool(const GURL&)>
BuildGeneralFilter() const = 0;
+ // Builds a filter that can be used with the network service, more precisely
+ // with NetworkContext.ClearHttpCache().
+ virtual network::mojom::ClearCacheUrlFilterPtr BuildClearCacheUrlFilter()
+ const = 0;
+
// Builds a filter that matches cookies whose sources are in the whitelist,
// or aren't in the blacklist.
virtual base::RepeatingCallback<bool(const net::CanonicalCookie& pattern)>
diff --git a/chromium/content/public/browser/child_process_launcher_utils.h b/chromium/content/public/browser/child_process_launcher_utils.h
new file mode 100644
index 00000000000..1b9d4545ab6
--- /dev/null
+++ b/chromium/content/public/browser/child_process_launcher_utils.h
@@ -0,0 +1,24 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_PUBLIC_BROWSER_CHILD_PROCESS_LAUNCHER_UTILS_H_
+#define CONTENT_PUBLIC_BROWSER_CHILD_PROCESS_LAUNCHER_UTILS_H_
+
+#include "content/common/content_export.h"
+
+namespace base {
+class SingleThreadTaskRunner;
+}
+
+namespace content {
+
+// The caller must take a reference to the returned TaskRunner pointer if it
+// wants to use the pointer directly.
+CONTENT_EXPORT base::SingleThreadTaskRunner* GetProcessLauncherTaskRunner();
+
+CONTENT_EXPORT bool CurrentlyOnProcessLauncherTaskRunner();
+
+} // namespace content
+
+#endif // CONTENT_PUBLIC_BROWSER_CHILD_PROCESS_LAUNCHER_UTILES_H_
diff --git a/chromium/content/public/browser/content_browser_client.cc b/chromium/content/public/browser/content_browser_client.cc
index 37e2d88e28e..f6ae6d1d445 100644
--- a/chromium/content/public/browser/content_browser_client.cc
+++ b/chromium/content/public/browser/content_browser_client.cc
@@ -12,17 +12,17 @@
#include "base/logging.h"
#include "build/build_config.h"
#include "content/public/browser/client_certificate_delegate.h"
+#include "content/public/browser/login_delegate.h"
#include "content/public/browser/memory_coordinator_delegate.h"
#include "content/public/browser/navigation_ui_data.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/browser/page_navigator.h"
-#include "content/public/browser/resource_dispatcher_host_login_delegate.h"
#include "content/public/browser/vpn_service_proxy.h"
#include "content/public/common/url_loader_throttle.h"
#include "device/geolocation/public/cpp/location_provider.h"
#include "media/audio/audio_manager.h"
#include "media/base/cdm_factory.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "mojo/public/cpp/bindings/associated_interface_ptr.h"
#include "net/ssl/client_cert_identity.h"
#include "net/ssl/client_cert_store.h"
@@ -82,6 +82,12 @@ bool ContentBrowserClient::ShouldUseProcessPerSite(
return false;
}
+bool ContentBrowserClient::ShouldUseSpareRenderProcessHost(
+ BrowserContext* browser_context,
+ const GURL& site_url) {
+ return true;
+}
+
bool ContentBrowserClient::DoesSiteRequireDedicatedProcess(
BrowserContext* browser_context,
const GURL& effective_site_url) {
@@ -93,11 +99,8 @@ bool ContentBrowserClient::ShouldLockToOrigin(BrowserContext* browser_context,
return true;
}
-bool ContentBrowserClient::ShouldBypassDocumentBlocking(
- const url::Origin& initiator,
- const GURL& url,
- ResourceType resource_type) {
- return false;
+const char* ContentBrowserClient::GetInitatorSchemeBypassingDocumentBlocking() {
+ return nullptr;
}
void ContentBrowserClient::GetAdditionalViewSourceSchemes(
@@ -181,6 +184,13 @@ ContentBrowserClient::GetOriginsRequiringDedicatedProcess() {
return std::vector<url::Origin>();
}
+bool ContentBrowserClient::ShouldEnableStrictSiteIsolation() {
+ // By default --site-per-process is turned off for //content embedders.
+ // This ensures that embedders like ChromeCast and/or Opera are not forced
+ // into --site-per-process.
+ return false;
+}
+
bool ContentBrowserClient::IsFileAccessAllowed(
const base::FilePath& path,
const base::FilePath& absolute_path,
@@ -263,7 +273,7 @@ void ContentBrowserClient::AllowWorkerFileSystem(
ResourceContext* context,
const std::vector<std::pair<int, int> >& render_frames,
base::Callback<void(bool)> callback) {
- callback.Run(true);
+ std::move(callback).Run(true);
}
bool ContentBrowserClient::AllowWorkerIndexedDB(
@@ -623,8 +633,9 @@ bool ContentBrowserClient::ShouldOverrideUrlLoading(
bool has_user_gesture,
bool is_redirect,
bool is_main_frame,
- ui::PageTransition transition) {
- return false;
+ ui::PageTransition transition,
+ bool* ignore_navigation) {
+ return true;
}
#endif
@@ -672,12 +683,16 @@ void ContentBrowserClient::ShouldReturnAttestationForWebauthnRPID(
std::move(callback).Run(true);
}
+bool ContentBrowserClient::IsFocused(content::WebContents* web_contents) {
+ return true;
+}
+
std::unique_ptr<net::ClientCertStore>
ContentBrowserClient::CreateClientCertStore(ResourceContext* resource_context) {
return nullptr;
}
-ResourceDispatcherHostLoginDelegate* ContentBrowserClient::CreateLoginDelegate(
+scoped_refptr<LoginDelegate> ContentBrowserClient::CreateLoginDelegate(
net::AuthChallengeInfo* auth_info,
content::ResourceRequestInfo::WebContentsGetter web_contents_getter,
bool is_main_frame,
@@ -688,4 +703,21 @@ ResourceDispatcherHostLoginDelegate* ContentBrowserClient::CreateLoginDelegate(
return nullptr;
}
+bool ContentBrowserClient::HandleExternalProtocol(
+ const GURL& url,
+ ResourceRequestInfo::WebContentsGetter web_contents_getter,
+ int child_id,
+ NavigationUIData* navigation_data,
+ bool is_main_frame,
+ ui::PageTransition page_transition,
+ bool has_user_gesture) {
+ return true;
+}
+
+std::unique_ptr<OverlayWindow>
+ContentBrowserClient::CreateWindowForPictureInPicture(
+ PictureInPictureWindowController* controller) {
+ return nullptr;
+}
+
} // namespace content
diff --git a/chromium/content/public/browser/content_browser_client.h b/chromium/content/public/browser/content_browser_client.h
index 5373ee07b5c..63cb3851db0 100644
--- a/chromium/content/public/browser/content_browser_client.h
+++ b/chromium/content/public/browser/content_browser_client.h
@@ -20,6 +20,7 @@
#include "build/build_config.h"
#include "content/public/browser/certificate_request_result_type.h"
#include "content/public/browser/navigation_throttle.h"
+#include "content/public/browser/overlay_window.h"
#include "content/public/browser/resource_request_info.h"
#include "content/public/common/content_client.h"
#include "content/public/common/media_stream_request.h"
@@ -28,7 +29,7 @@
#include "content/public/common/window_container_type.mojom.h"
#include "device/usb/public/mojom/chooser_service.mojom.h"
#include "device/usb/public/mojom/device_manager.mojom.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "media/mojo/interfaces/remoting.mojom.h"
#include "net/base/mime_util.h"
#include "net/cookies/canonical_cookie.h"
@@ -39,9 +40,9 @@
#include "services/service_manager/sandbox/sandbox_type.h"
#include "storage/browser/fileapi/file_system_context.h"
#include "storage/browser/quota/quota_manager.h"
-#include "third_party/WebKit/public/common/associated_interfaces/associated_interface_registry.h"
-#include "third_party/WebKit/public/mojom/page/page_visibility_state.mojom.h"
-#include "third_party/WebKit/public/web/window_features.mojom.h"
+#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
+#include "third_party/blink/public/mojom/page/page_visibility_state.mojom.h"
+#include "third_party/blink/public/web/window_features.mojom.h"
#include "ui/base/page_transition_types.h"
#include "ui/base/window_open_disposition.h"
@@ -138,6 +139,7 @@ class BrowserURLHandler;
class ClientCertificateDelegate;
class ControllerPresentationServiceDelegate;
class DevToolsManagerDelegate;
+class LoginDelegate;
class MediaObserver;
class MemoryCoordinatorDelegate;
class NavigationHandle;
@@ -149,7 +151,6 @@ class RenderFrameHost;
class RenderProcessHost;
class RenderViewHost;
class ResourceContext;
-class ResourceDispatcherHostLoginDelegate;
class SiteInstance;
class SpeechRecognitionManagerDelegate;
class StoragePartition;
@@ -240,6 +241,19 @@ class CONTENT_EXPORT ContentBrowserClient {
virtual bool ShouldUseProcessPerSite(BrowserContext* browser_context,
const GURL& effective_url);
+ // Returns whether a spare RenderProcessHost should be used for navigating to
+ // the specified site URL.
+ //
+ // Using the spare RenderProcessHost is advisable, because it can improve
+ // performance of a navigation that requires a new process. On the other
+ // hand, sometimes the spare RenderProcessHost cannot be used - for example
+ // some embedders might override
+ // ContentBrowserClient::AppendExtraCommandLineSwitches and add some cmdline
+ // switches at navigation time (and this won't work for the spare, because the
+ // spare RenderProcessHost is launched ahead of time).
+ virtual bool ShouldUseSpareRenderProcessHost(BrowserContext* browser_context,
+ const GURL& site_url);
+
// Returns true if site isolation should be enabled for |effective_site_url|.
// This call allows the embedder to supplement the site isolation policy
// enforced by the content layer. Will only be called if the content layer
@@ -257,12 +271,10 @@ class CONTENT_EXPORT ContentBrowserClient {
virtual bool ShouldLockToOrigin(BrowserContext* browser_context,
const GURL& effective_url);
- // Returns true if the |initiator| origin should be allowed to receive a
- // document at |url|, bypassing the usual blocking logic. Defaults to false.
- // This is called on the IO thread.
- virtual bool ShouldBypassDocumentBlocking(const url::Origin& initiator,
- const GURL& url,
- ResourceType resource_type);
+ // Returns the scheme of request initiator that should be ignored by
+ // cross-origin read blocking. nullptr can be returned to indicate that no
+ // exceptions should be granted based on initiator's scheme.
+ virtual const char* GetInitatorSchemeBypassingDocumentBlocking();
// Returns a list additional WebUI schemes, if any. These additional schemes
// act as aliases to the chrome: scheme. The additional schemes may or may
@@ -358,10 +370,17 @@ class CONTENT_EXPORT ContentBrowserClient {
// current SiteInstance, if it does not yet have a site.
virtual bool ShouldAssignSiteForURL(const GURL& url);
- // Allows the embedder to provide a list of origins that require a dedicated
- // process.
+ // Allows the embedder to programmatically provide some origins that should be
+ // opted into --isolate-origins mode of Site Isolation.
virtual std::vector<url::Origin> GetOriginsRequiringDedicatedProcess();
+ // Allows the embedder to programmatically opt into --site-per-process mode of
+ // Site Isolation.
+ //
+ // Note that for correctness, the same value should be consistently returned.
+ // See also https://crbug.com/825369
+ virtual bool ShouldEnableStrictSiteIsolation();
+
// Indicates whether a file path should be accessible via file URL given a
// request from a browser context which lives within |profile_path|.
virtual bool IsFileAccessAllowed(const base::FilePath& path,
@@ -1019,6 +1038,14 @@ class CONTENT_EXPORT ContentBrowserClient {
#if defined(OS_ANDROID)
// Only used by Android WebView.
+ // Returns:
+ // true - The check was successfully performed without throwing a
+ // Java exception. |*ignore_navigation| is set to the
+ // result of the check in this case.
+ // false - A Java exception was thrown. It is no longer safe to
+ // make JNI calls, because of the uncleared exception.
+ // Callers should return to the message loop as soon as
+ // possible, so that the exception can be rethrown.
virtual bool ShouldOverrideUrlLoading(int frame_tree_node_id,
bool browser_initiated,
const GURL& gurl,
@@ -1026,7 +1053,8 @@ class CONTENT_EXPORT ContentBrowserClient {
bool has_user_gesture,
bool is_redirect,
bool is_main_frame,
- ui::PageTransition transition);
+ ui::PageTransition transition,
+ bool* ignore_navigation);
#endif
// Called on IO or UI thread to determine whether or not to allow load and
@@ -1092,12 +1120,20 @@ class CONTENT_EXPORT ContentBrowserClient {
const url::Origin& origin,
base::OnceCallback<void(bool)> callback);
+ // Returns whether |web_contents| is the active tab in the focused window.
+ // As an example, webauthn uses this because it doesn't want to allow
+ // authenticator operations to be triggered by background tabs.
+ //
+ // Note that the default implementation of this function, and the
+ // implementation in ChromeContentBrowserClient for Android, return |true| so
+ // that testing is possible.
+ virtual bool IsFocused(content::WebContents* web_contents);
+
// Get platform ClientCertStore. May return nullptr.
virtual std::unique_ptr<net::ClientCertStore> CreateClientCertStore(
ResourceContext* resource_context);
- // Creates a ResourceDispatcherHostLoginDelegate that asks the user for a
- // username and password.
+ // Creates a LoginDelegate that asks the user for a username and password.
// Caller owns the returned pointer.
// |first_auth_attempt| is needed by AwHttpAuthHandler constructor.
// |auth_required_callback| is used to transfer auth credentials to
@@ -1105,7 +1141,7 @@ class CONTENT_EXPORT ContentBrowserClient {
// is base::nullopt if the request should be cancelled; otherwise
// the credentials will be used to respond to the auth challenge. This
// callback should be called on the IO thread task runner.
- virtual ResourceDispatcherHostLoginDelegate* CreateLoginDelegate(
+ virtual scoped_refptr<LoginDelegate> CreateLoginDelegate(
net::AuthChallengeInfo* auth_info,
content::ResourceRequestInfo::WebContentsGetter web_contents_getter,
bool is_main_frame,
@@ -1113,6 +1149,30 @@ class CONTENT_EXPORT ContentBrowserClient {
bool first_auth_attempt,
const base::Callback<void(const base::Optional<net::AuthCredentials>&)>&
auth_required_callback);
+
+ // Launches the url for the given tab. Returns true if an attempt to handle
+ // the url was made, e.g. by launching an app. Note that this does not
+ // guarantee that the app successfully handled it.
+ // If this is a navigation request, then |child_id| will be
+ // ChildProcessHost::kInvalidUniqueID and |navigation_ui_data| will valid.
+ // Otherwise child_id will be the process id and |navigation_ui_data| will be
+ // nullptr.
+ virtual bool HandleExternalProtocol(
+ const GURL& url,
+ ResourceRequestInfo::WebContentsGetter web_contents_getter,
+ int child_id,
+ NavigationUIData* navigation_data,
+ bool is_main_frame,
+ ui::PageTransition page_transition,
+ bool has_user_gesture);
+
+ // Creates an OverlayWindow to be used for Picture-in-Picture. This window
+ // will house the content shown when in Picture-in-Picture mode. This will
+ // return a new OverlayWindow.
+ // May return nullptr if embedder does not support this functionality. The
+ // default implementation provides nullptr OverlayWindow.
+ virtual std::unique_ptr<OverlayWindow> CreateWindowForPictureInPicture(
+ PictureInPictureWindowController* controller);
};
} // namespace content
diff --git a/chromium/content/public/browser/devtools_agent_host.h b/chromium/content/public/browser/devtools_agent_host.h
index c90e0b8fa16..a6e78f907cd 100644
--- a/chromium/content/public/browser/devtools_agent_host.h
+++ b/chromium/content/public/browser/devtools_agent_host.h
@@ -115,6 +115,12 @@ class CONTENT_EXPORT DevToolsAgentHost
// Attaches |client| to this agent host to start debugging.
virtual void AttachClient(DevToolsAgentHostClient* client) = 0;
+ // Attaches |client| to this agent host to start debugging.
+ // This client will be restricted in certain ways. For example,
+ // it will be detached when attempting to debug WebUI pages.
+ // Returns |true| on success.
+ virtual bool AttachRestrictedClient(DevToolsAgentHostClient* client) = 0;
+
// Attaches |client| to this agent host to start debugging. Disconnects
// any existing clients.
virtual void ForceAttachClient(DevToolsAgentHostClient* client) = 0;
diff --git a/chromium/content/public/browser/devtools_manager_delegate.cc b/chromium/content/public/browser/devtools_manager_delegate.cc
index 0bef515cba7..9d659510a10 100644
--- a/chromium/content/public/browser/devtools_manager_delegate.cc
+++ b/chromium/content/public/browser/devtools_manager_delegate.cc
@@ -42,14 +42,6 @@ bool DevToolsManagerDelegate::HandleCommand(DevToolsAgentHost* agent_host,
return false;
}
-bool DevToolsManagerDelegate::HandleAsyncCommand(
- DevToolsAgentHost* agent_host,
- DevToolsAgentHostClient* client,
- base::DictionaryValue* command,
- const CommandCallback& callback) {
- return false;
-}
-
std::string DevToolsManagerDelegate::GetDiscoveryPageHTML() {
return std::string();
}
diff --git a/chromium/content/public/browser/devtools_manager_delegate.h b/chromium/content/public/browser/devtools_manager_delegate.h
index 2af6d6545ba..b0f44feed19 100644
--- a/chromium/content/public/browser/devtools_manager_delegate.h
+++ b/chromium/content/public/browser/devtools_manager_delegate.h
@@ -54,14 +54,6 @@ class CONTENT_EXPORT DevToolsManagerDelegate {
DevToolsAgentHostClient* client,
base::DictionaryValue* command);
- // Returns true if the command has been handled, false otherwise.
- using CommandCallback =
- base::Callback<void(std::unique_ptr<base::DictionaryValue> response)>;
- virtual bool HandleAsyncCommand(DevToolsAgentHost* agent_host,
- DevToolsAgentHostClient* client,
- base::DictionaryValue* command,
- const CommandCallback& callback);
-
// Should return discovery page HTML that should list available tabs
// and provide attach links.
virtual std::string GetDiscoveryPageHTML();
diff --git a/chromium/content/public/browser/download_manager.cc b/chromium/content/public/browser/download_manager.cc
index be1dab65c51..9f59617811c 100644
--- a/chromium/content/public/browser/download_manager.cc
+++ b/chromium/content/public/browser/download_manager.cc
@@ -5,7 +5,6 @@
#include "content/public/browser/download_manager.h"
#include "components/download/public/common/download_task_runner.h"
-#include "content/browser/byte_stream.h"
namespace content {
@@ -14,18 +13,4 @@ scoped_refptr<base::SequencedTaskRunner> DownloadManager::GetTaskRunner() {
return download::GetDownloadTaskRunner();
}
-DownloadManager::InputStream::InputStream(
- std::unique_ptr<ByteStreamReader> stream_reader)
- : stream_reader_(std::move(stream_reader)) {}
-
-DownloadManager::InputStream::InputStream(
- download::mojom::DownloadStreamHandlePtr stream_handle)
- : stream_handle_(std::move(stream_handle)) {}
-
-DownloadManager::InputStream::~InputStream() = default;
-
-bool DownloadManager::InputStream::IsEmpty() const {
- return !stream_reader_.get() && stream_handle_.is_null();
-}
-
} // namespace content
diff --git a/chromium/content/public/browser/download_manager.h b/chromium/content/public/browser/download_manager.h
index 82b861f3e5a..e9480a681d8 100644
--- a/chromium/content/public/browser/download_manager.h
+++ b/chromium/content/public/browser/download_manager.h
@@ -40,6 +40,7 @@
#include "components/download/public/common/download_item.h"
#include "components/download/public/common/download_stream.mojom.h"
#include "components/download/public/common/download_url_parameters.h"
+#include "components/download/public/common/input_stream.h"
#include "content/common/content_export.h"
#include "net/base/net_errors.h"
#include "storage/browser/blob/blob_data_handle.h"
@@ -50,10 +51,13 @@ namespace download {
struct DownloadCreateInfo;
} // namespace download
+namespace network {
+class SharedURLLoaderFactory;
+} // namespace network
+
namespace content {
class BrowserContext;
-class ByteStreamReader;
class DownloadManagerDelegate;
// Browser's download manager: manages all downloads and destination view.
@@ -91,6 +95,12 @@ class CONTENT_EXPORT DownloadManager : public base::SupportsUserData::Data {
virtual void OnDownloadCreated(DownloadManager* manager,
download::DownloadItem* item) {}
+ // Called when the download manager intercepted a download navigation but
+ // didn't create the download item. Possible reasons:
+ // 1. |delegate| is null.
+ // 2. |delegate| doesn't allow the download.
+ virtual void OnDownloadDropped(DownloadManager* manager) {}
+
// Called when the download manager has finished loading the data.
virtual void OnManagerInitialized() {}
@@ -108,27 +118,15 @@ class CONTENT_EXPORT DownloadManager : public base::SupportsUserData::Data {
// clearing |downloads| first.
virtual void GetAllDownloads(DownloadVector* downloads) = 0;
- // InputStream to read after the download starts. Only one of them could be
- // available at the same time.
- struct CONTENT_EXPORT InputStream {
- explicit InputStream(std::unique_ptr<ByteStreamReader> stream_reader);
- explicit InputStream(
- download::mojom::DownloadStreamHandlePtr stream_handle);
- ~InputStream();
-
- bool IsEmpty() const;
-
- std::unique_ptr<ByteStreamReader> stream_reader_;
- download::mojom::DownloadStreamHandlePtr stream_handle_;
- };
-
// Called by a download source (Currently DownloadResourceHandler)
// to initiate the non-source portions of a download.
- // Returns the id assigned to the download. If the DownloadCreateInfo
- // specifies an id, that id will be used.
+ // If the DownloadCreateInfo specifies an id, that id will be used.
+ // If |shared_url_loader_factory| is provided, it can be used to issue
+ // parallel download requests.
virtual void StartDownload(
std::unique_ptr<download::DownloadCreateInfo> info,
- std::unique_ptr<InputStream> stream,
+ std::unique_ptr<download::InputStream> stream,
+ scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory,
const download::DownloadUrlParameters::OnStartedCallback& on_started) = 0;
// Remove downloads whose URLs match the |url_filter| and are within
diff --git a/chromium/content/public/browser/gpu_data_manager.h b/chromium/content/public/browser/gpu_data_manager.h
index fb7e3695022..ebe6ba517c6 100644
--- a/chromium/content/public/browser/gpu_data_manager.h
+++ b/chromium/content/public/browser/gpu_data_manager.h
@@ -12,8 +12,6 @@
#include "base/process/process.h"
#include "content/common/content_export.h"
-class GURL;
-
namespace gpu {
struct GPUInfo;
struct VideoMemoryUsageStats;
@@ -36,9 +34,8 @@ class GpuDataManager {
// This indicator might change because we could collect more GPU info or
// because the GPU blacklist could be updated.
- // If this returns false, any further GPU access, including launching GPU
- // process, establish GPU channel, and GPU info collection, should be
- // blocked.
+ // If this returns false, any further GPU access, including establishing GPU
+ // channel, and GPU info collection, should be blocked.
// Can be called on any thread.
// If |reason| is not nullptr and GPU access is blocked, upon return, |reason|
// contains a description of the reason why GPU access is blocked.
@@ -59,10 +56,6 @@ class GpuDataManager {
virtual void AddObserver(GpuDataManagerObserver* observer) = 0;
virtual void RemoveObserver(GpuDataManagerObserver* observer) = 0;
- // Allows a given domain previously blocked from accessing 3D APIs
- // to access them again.
- virtual void UnblockDomainFrom3DAPIs(const GURL& url) = 0;
-
virtual void DisableHardwareAcceleration() = 0;
// Whether a GPU is in use (as opposed to a software renderer).
diff --git a/chromium/content/public/browser/gpu_data_manager_observer.h b/chromium/content/public/browser/gpu_data_manager_observer.h
index 79e0d6adfa3..8543752d4dc 100644
--- a/chromium/content/public/browser/gpu_data_manager_observer.h
+++ b/chromium/content/public/browser/gpu_data_manager_observer.h
@@ -7,9 +7,6 @@
#include "base/process/kill.h"
#include "content/common/content_export.h"
-#include "content/public/common/three_d_api_types.h"
-
-class GURL;
namespace content {
@@ -20,13 +17,6 @@ class CONTENT_EXPORT GpuDataManagerObserver {
// Called for any observers whenever there is a GPU info update.
virtual void OnGpuInfoUpdate() {}
- // Indicates that client 3D APIs (Pepper 3D, WebGL) were just blocked on the
- // given page, specifically because the GPU was reset recently.
- virtual void DidBlock3DAPIs(const GURL& top_origin_url,
- int render_process_id,
- int render_frame_id,
- ThreeDAPIType requester) {}
-
// Called for any observer when the GPU process crashed.
virtual void OnGpuProcessCrashed(base::TerminationStatus exit_code) {}
diff --git a/chromium/content/public/browser/gpu_utils.cc b/chromium/content/public/browser/gpu_utils.cc
index 7c093ddb4b5..b2fd38514cb 100644
--- a/chromium/content/public/browser/gpu_utils.cc
+++ b/chromium/content/public/browser/gpu_utils.cc
@@ -13,7 +13,7 @@
#include "gpu/command_buffer/service/gpu_switches.h"
#include "gpu/command_buffer/service/service_utils.h"
#include "gpu/config/gpu_switches.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "ui/gl/gl_switches.h"
namespace {
diff --git a/chromium/content/public/browser/resource_dispatcher_host_login_delegate.h b/chromium/content/public/browser/login_delegate.h
index a6b3b2b0ba1..edda802becb 100644
--- a/chromium/content/public/browser/resource_dispatcher_host_login_delegate.h
+++ b/chromium/content/public/browser/login_delegate.h
@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef CONTENT_PUBLIC_BROWSER_RESOURCE_DISPATCHER_HOST_LOGIN_DELEGATE_H_
-#define CONTENT_PUBLIC_BROWSER_RESOURCE_DISPATCHER_HOST_LOGIN_DELEGATE_H_
+#ifndef CONTENT_PUBLIC_BROWSER_LOGIN_DELEGATE_H_
+#define CONTENT_PUBLIC_BROWSER_LOGIN_DELEGATE_H_
#include "base/memory/ref_counted.h"
#include "content/common/content_export.h"
@@ -15,18 +15,18 @@ namespace content {
// method. If the user cancels, the login delegate should call the URLRequest's
// CancelAuth instead. And in either case, it must make a call to
// ResourceDispatcherHost::ClearLoginDelegateForRequest.
-class CONTENT_EXPORT ResourceDispatcherHostLoginDelegate
- : public base::RefCountedThreadSafe<ResourceDispatcherHostLoginDelegate> {
+class CONTENT_EXPORT LoginDelegate
+ : public base::RefCountedThreadSafe<LoginDelegate> {
public:
// Notify the login delegate that the request was cancelled.
// This function can only be called from the IO thread.
virtual void OnRequestCancelled() = 0;
protected:
- friend class base::RefCountedThreadSafe<ResourceDispatcherHostLoginDelegate>;
- virtual ~ResourceDispatcherHostLoginDelegate() {}
+ friend class base::RefCountedThreadSafe<LoginDelegate>;
+ virtual ~LoginDelegate() {}
};
-} // public content
+} // namespace content
-#endif // CONTENT_PUBLIC_BROWSER_RESOURCE_DISPATCHER_HOST_LOGIN_DELEGATE_H_
+#endif // CONTENT_PUBLIC_BROWSER_LOGIN_DELEGATE_H_
diff --git a/chromium/content/public/browser/media_controller.h b/chromium/content/public/browser/media_controller.h
new file mode 100644
index 00000000000..707a109e469
--- /dev/null
+++ b/chromium/content/public/browser/media_controller.h
@@ -0,0 +1,44 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_PUBLIC_BROWSER_MEDIA_CONTROLLER_H_
+#define CONTENT_PUBLIC_BROWSER_MEDIA_CONTROLLER_H_
+
+#include "base/time/time.h"
+
+namespace content {
+
+// High level interface that allows a controller to issue simple media commands.
+// Modeled after the media_router.mojom.MediaController interface.
+// State changes will be signaled via the MediaStatusObserver interface.
+// TODO(tguilbert): Add MediaStatusObserver interface.
+class MediaController {
+ public:
+ virtual ~MediaController() = default;
+
+ // Starts playing the media if it is paused. Is a no-op if not supported by
+ // the media or the media is already playing.
+ virtual void Play() = 0;
+
+ // Pauses the media if it is playing. Is a no-op if not supported by the media
+ // or the media is already paused.
+ virtual void Pause() = 0;
+
+ // Mutes the media if |mute| is true, and unmutes it if false. Is a no-op if
+ // not supported by the media.
+ virtual void SetMute(bool mute) = 0;
+
+ // Changes the current volume of the media, with 1 being the highest and 0
+ // being the lowest/no sound. Does not change the (un)muted state of the
+ // media. Is a no-op if not supported by the media.
+ virtual void SetVolume(float volume) = 0;
+
+ // Sets the current playback position. |time| must be less than or equal to
+ // the duration of the media. Is a no-op if the media doesn't support seeking.
+ virtual void Seek(base::TimeDelta time) = 0;
+};
+
+} // namespace content
+
+#endif // CONTENT_PUBLIC_BROWSER_MEDIA_CONTROLLER_H_
diff --git a/chromium/content/public/browser/media_session.h b/chromium/content/public/browser/media_session.h
index 1a5ce982549..12a6468b47d 100644
--- a/chromium/content/public/browser/media_session.h
+++ b/chromium/content/public/browser/media_session.h
@@ -70,6 +70,9 @@ class MediaSession {
// Tell the media session a user action has performed.
virtual void DidReceiveAction(blink::mojom::MediaSessionAction action) = 0;
+ // Set the volume multiplier applied during ducking.
+ virtual void SetDuckingVolumeMultiplier(double multiplier) = 0;
+
// Let the media session start ducking such that the volume multiplier is
// reduced.
virtual void StartDucking() = 0;
diff --git a/chromium/content/public/browser/native_web_keyboard_event.h b/chromium/content/public/browser/native_web_keyboard_event.h
index c73624f45c3..32b4a0d3e69 100644
--- a/chromium/content/public/browser/native_web_keyboard_event.h
+++ b/chromium/content/public/browser/native_web_keyboard_event.h
@@ -10,7 +10,7 @@
#include "base/time/time.h"
#include "build/build_config.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebKeyboardEvent.h"
+#include "third_party/blink/public/platform/web_keyboard_event.h"
#include "ui/gfx/native_widget_types.h"
#if defined(OS_ANDROID)
diff --git a/chromium/content/public/browser/navigation_handle.cc b/chromium/content/public/browser/navigation_handle.cc
index f8c4740ef27..a109ce3e70f 100644
--- a/chromium/content/public/browser/navigation_handle.cc
+++ b/chromium/content/public/browser/navigation_handle.cc
@@ -52,7 +52,7 @@ NavigationHandle::CreateNavigationHandleForTesting(
is_form_submission, // is_form_submission
base::nullopt, // suggested_filename
nullptr, // navigation_ui_data
- method, resource_request_body, Referrer(),
+ method, net::HttpRequestHeaders(), resource_request_body, Referrer(),
false, // has_user_gesture
transition);
handle_impl->set_render_frame_host(rfhi);
diff --git a/chromium/content/public/browser/navigation_handle.h b/chromium/content/public/browser/navigation_handle.h
index e46c8288da7..28e3bf684ee 100644
--- a/chromium/content/public/browser/navigation_handle.h
+++ b/chromium/content/public/browser/navigation_handle.h
@@ -13,6 +13,7 @@
#include "content/public/browser/reload_type.h"
#include "content/public/browser/restore_type.h"
#include "content/public/common/referrer.h"
+#include "content/public/common/transferrable_url_loader.mojom.h"
#include "net/base/host_port_pair.h"
#include "net/base/net_errors.h"
#include "net/http/http_response_info.h"
@@ -22,6 +23,7 @@
class GURL;
namespace net {
+class HttpRequestHeaders;
class HttpResponseHeaders;
} // namespace net
@@ -222,6 +224,9 @@ class CONTENT_EXPORT NavigationHandle {
// Returns the remote address of the socket which fetched this resource.
virtual net::HostPortPair GetSocketAddress() = 0;
+ // Returns the headers used for this request.
+ virtual const net::HttpRequestHeaders& GetRequestHeaders() = 0;
+
// Returns the response headers for the request, or nullptr if there aren't
// any response headers or they have not been received yet. The response
// headers may change during the navigation (e.g. after encountering a server
@@ -317,6 +322,9 @@ class CONTENT_EXPORT NavigationHandle {
// ResourceDispatcherHostDelegate::GetNavigationData during commit. This will
// be a clone of the NavigationData.
virtual NavigationData* GetNavigationData() = 0;
+
+ virtual void RegisterSubresourceOverride(
+ mojom::TransferrableURLLoaderPtr transferrable_loader) = 0;
};
} // namespace content
diff --git a/chromium/content/public/browser/notification_types.h b/chromium/content/public/browser/notification_types.h
index 1a68aad37dc..75826c37889 100644
--- a/chromium/content/public/browser/notification_types.h
+++ b/chromium/content/public/browser/notification_types.h
@@ -5,12 +5,17 @@
#ifndef CONTENT_PUBLIC_BROWSER_NOTIFICATION_TYPES_H_
#define CONTENT_PUBLIC_BROWSER_NOTIFICATION_TYPES_H_
-// This file describes various types used to describe and filter notifications
-// that pass through the NotificationService.
-//
-// Only notifications that are fired from the content module should be here. We
-// should never have a notification that is fired by the embedder and listened
-// to by content.
+// **
+// ** NOTICE
+// **
+// ** The notification system is deprecated, obsolete, and is slowly being
+// ** removed. See https://crbug.com/268984 and https://crbug.com/170921.
+// **
+// ** Please don't add any new notification types, and please help migrate
+// ** existing uses of the notification types below to use the Observer and
+// ** Callback patterns.
+// **
+
namespace content {
enum NotificationType {
@@ -67,14 +72,6 @@ enum NotificationType {
// WebContents ---------------------------------------------------------------
- // This notification is sent when a render view host has connected to a
- // renderer process. The source is a Source<WebContents> with a pointer to
- // the WebContents. A WEB_CONTENTS_DISCONNECTED notification is
- // guaranteed before the source pointer becomes junk. No details are
- // expected.
- // DEPRECATED: Use WebContentsObserver::RenderViewReady()
- NOTIFICATION_WEB_CONTENTS_CONNECTED,
-
// This message is sent after a WebContents is disconnected from the
// renderer process. The source is a Source<WebContents> with a pointer to
// the WebContents (the pointer is usable). No details are expected.
@@ -94,21 +91,25 @@ enum NotificationType {
// A RenderViewHost was created for a WebContents. The source is the
// associated WebContents, and the details is the RenderViewHost
// pointer.
+ // DEPRECATED: Use WebContentsObserver::RenderViewCreated()
NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED,
// Indicates that a RenderProcessHost was created and its handle is now
// available. The source will be the RenderProcessHost that corresponds to
// the process.
+ // DEPRECATED: Use RenderProcessHostObserver::RenderProcessReady()
NOTIFICATION_RENDERER_PROCESS_CREATED,
// Indicates that a RenderProcessHost is destructing. The source will be the
// RenderProcessHost that corresponds to the process.
+ // DEPRECATED: Use RenderProcessHostObserver::RenderProcessHostDestroyed()
NOTIFICATION_RENDERER_PROCESS_TERMINATED,
// Indicates that a render process was closed (meaning it exited, but the
// RenderProcessHost might be reused). The source will be the corresponding
// RenderProcessHost. The details will be a RendererClosedDetails struct.
// This may get sent along with RENDERER_PROCESS_TERMINATED.
+ // DEPRECATED: Use RenderProcessHostObserver::RenderProcessExited()
NOTIFICATION_RENDERER_PROCESS_CLOSED,
// Indicates that a RenderWidgetHost has become unresponsive for a period of
@@ -145,4 +146,15 @@ enum NotificationType {
} // namespace content
+// **
+// ** NOTICE
+// **
+// ** The notification system is deprecated, obsolete, and is slowly being
+// ** removed. See https://crbug.com/268984 and https://crbug.com/170921.
+// **
+// ** Please don't add any new notification types, and please help migrate
+// ** existing uses of the notification types below to use the Observer and
+// ** Callback patterns.
+// **
+
#endif // CONTENT_PUBLIC_BROWSER_NOTIFICATION_TYPES_H_
diff --git a/chromium/content/public/browser/overlay_window.h b/chromium/content/public/browser/overlay_window.h
new file mode 100644
index 00000000000..d8cf4cfec00
--- /dev/null
+++ b/chromium/content/public/browser/overlay_window.h
@@ -0,0 +1,54 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_PUBLIC_BROWSER_OVERLAY_WINDOW_H_
+#define CONTENT_PUBLIC_BROWSER_OVERLAY_WINDOW_H_
+
+#include <memory>
+
+#include "ui/gfx/native_widget_types.h"
+
+namespace gfx {
+class Rect;
+class Size;
+}
+
+namespace ui {
+class Layer;
+}
+
+namespace content {
+
+class PictureInPictureWindowController;
+
+// This window will always float above other windows. The intention is to show
+// content perpetually while the user is still interacting with the other
+// browser windows.
+class OverlayWindow {
+ public:
+ OverlayWindow() = default;
+ virtual ~OverlayWindow() = default;
+
+ // Returns a created OverlayWindow. This is defined in the platform-specific
+ // implementation for the class.
+ static std::unique_ptr<OverlayWindow> Create(
+ PictureInPictureWindowController* controller);
+
+ virtual bool IsActive() const = 0;
+ virtual void Show() = 0;
+ virtual void Close() = 0;
+ virtual bool IsVisible() const = 0;
+ virtual bool IsAlwaysOnTop() const = 0;
+ virtual ui::Layer* GetLayer() = 0;
+ // Retrieves the window's current bounds, including its window.
+ virtual gfx::Rect GetBounds() const = 0;
+ virtual void UpdateVideoSize(const gfx::Size& natural_size) = 0;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(OverlayWindow);
+};
+
+} // namespace content
+
+#endif // CONTENT_PUBLIC_BROWSER_OVERLAY_WINDOW_H_
diff --git a/chromium/content/public/browser/overscroll_configuration.h b/chromium/content/public/browser/overscroll_configuration.h
index 2f593f5b8a8..1cfca76392c 100644
--- a/chromium/content/public/browser/overscroll_configuration.h
+++ b/chromium/content/public/browser/overscroll_configuration.h
@@ -12,20 +12,32 @@ namespace content {
class CONTENT_EXPORT OverscrollConfig {
public:
- // Determines overscroll history navigation mode according to its
- // corresponding flag.
- enum class Mode {
- // Overscroll history navigation is disabled.
+ // Determines overscroll history navigation mode according to
+ // --overscroll-history-navigation flag.
+ enum class HistoryNavigationMode {
+ // History navigation is disabled.
kDisabled,
- // Overscroll history navigation is enabled and uses the UI with parallax
- // effect and screenshots.
+ // History navigation is enabled and uses the UI with parallax effect and
+ // screenshots.
kParallaxUi,
- // Overscroll history navigation is enabled and uses the simplified UI.
+ // History navigation is enabled and uses the simplified UI.
kSimpleUi,
};
+ // Determines pull-to-refresh mode according to --pull-to-refresh flag.
+ enum class PullToRefreshMode {
+ // Pull-to-refresh is disabled.
+ kDisabled,
+
+ // Pull-to-refresh is enabled for both touchscreen and touchpad.
+ kEnabled,
+
+ // Pull-to-refresh is enabled only for touchscreen.
+ kEnabledTouchschreen,
+ };
+
// Specifies an overscroll controller threshold.
enum class Threshold {
// Threshold to complete touchpad overscroll, in terms of the percentage of
@@ -43,17 +55,31 @@ class CONTENT_EXPORT OverscrollConfig {
kStartTouchscreen,
};
- static Mode GetMode();
+ static HistoryNavigationMode GetHistoryNavigationMode();
+ static PullToRefreshMode GetPullToRefreshMode();
static float GetThreshold(Threshold threshold);
+ static bool TouchpadOverscrollHistoryNavigationEnabled();
+
private:
- friend class ScopedOverscrollMode;
+ friend class ScopedHistoryNavigationMode;
+ friend class ScopedPullToRefreshMode;
+ friend class OverscrollControllerTest;
+
+ // Helper functions used by |ScopedHistoryNavigationMode| to set and reset
+ // mode in tests.
+ static void SetHistoryNavigationMode(HistoryNavigationMode mode);
+ static void ResetHistoryNavigationMode();
+
+ // Helper functions used by |ScopedPullToRefreshMode| to set and reset mode in
+ // tests.
+ static void SetPullToRefreshMode(PullToRefreshMode mode);
+ static void ResetPullToRefreshMode();
- // Helper functions used by |ScopedOverscrollMode| to set and reset mode in
+ // Helper functions to reset TouchpadOverscrollHistoryNavigationEnabled in
// tests.
- static void SetMode(Mode mode);
- static void ResetMode();
+ static void ResetTouchpadOverscrollHistoryNavigationEnabled();
DISALLOW_IMPLICIT_CONSTRUCTORS(OverscrollConfig);
};
diff --git a/chromium/content/public/browser/page_navigator.cc b/chromium/content/public/browser/page_navigator.cc
index 2bc432e34b3..c16b60276b8 100644
--- a/chromium/content/public/browser/page_navigator.cc
+++ b/chromium/content/public/browser/page_navigator.cc
@@ -20,7 +20,8 @@ OpenURLParams::OpenURLParams(const GURL& url,
is_renderer_initiated(is_renderer_initiated),
should_replace_current_entry(false),
user_gesture(!is_renderer_initiated),
- started_from_context_menu(false) {}
+ started_from_context_menu(false),
+ open_app_window_if_possible(false) {}
OpenURLParams::OpenURLParams(const GURL& url,
const Referrer& referrer,
@@ -37,7 +38,8 @@ OpenURLParams::OpenURLParams(const GURL& url,
is_renderer_initiated(is_renderer_initiated),
should_replace_current_entry(false),
user_gesture(!is_renderer_initiated),
- started_from_context_menu(started_from_context_menu) {}
+ started_from_context_menu(started_from_context_menu),
+ open_app_window_if_possible(false) {}
OpenURLParams::OpenURLParams(const GURL& url,
const Referrer& referrer,
@@ -54,7 +56,8 @@ OpenURLParams::OpenURLParams(const GURL& url,
is_renderer_initiated(is_renderer_initiated),
should_replace_current_entry(false),
user_gesture(!is_renderer_initiated),
- started_from_context_menu(false) {}
+ started_from_context_menu(false),
+ open_app_window_if_possible(false) {}
OpenURLParams::OpenURLParams()
: uses_post(false),
@@ -64,7 +67,8 @@ OpenURLParams::OpenURLParams()
is_renderer_initiated(false),
should_replace_current_entry(false),
user_gesture(true),
- started_from_context_menu(false) {}
+ started_from_context_menu(false),
+ open_app_window_if_possible(false) {}
OpenURLParams::OpenURLParams(const OpenURLParams& other) = default;
diff --git a/chromium/content/public/browser/page_navigator.h b/chromium/content/public/browser/page_navigator.h
index c42304c06d8..a7572a8b7b8 100644
--- a/chromium/content/public/browser/page_navigator.h
+++ b/chromium/content/public/browser/page_navigator.h
@@ -21,7 +21,7 @@
#include "content/public/common/referrer.h"
#include "ipc/ipc_message.h"
#include "services/network/public/cpp/resource_request_body.h"
-#include "third_party/WebKit/public/web/WebTriggeringEventInfo.h"
+#include "third_party/blink/public/web/web_triggering_event_info.h"
#include "ui/base/page_transition_types.h"
#include "ui/base/window_open_disposition.h"
#include "url/gurl.h"
@@ -113,6 +113,10 @@ struct CONTENT_EXPORT OpenURLParams {
// that attribute.
base::Optional<std::string> suggested_filename;
+ // Indicates that the navigation should happen in an app window if
+ // possible, i.e. if an app for the URL is installed.
+ bool open_app_window_if_possible;
+
private:
OpenURLParams();
};
diff --git a/chromium/content/public/browser/payment_app_provider.h b/chromium/content/public/browser/payment_app_provider.h
index cb504dab8d7..8e13ae5638e 100644
--- a/chromium/content/public/browser/payment_app_provider.h
+++ b/chromium/content/public/browser/payment_app_provider.h
@@ -13,7 +13,9 @@
#include "base/callback_forward.h"
#include "content/common/content_export.h"
#include "content/public/browser/stored_payment_app.h"
-#include "third_party/WebKit/public/platform/modules/payments/payment_app.mojom.h"
+#include "third_party/blink/public/platform/modules/payments/payment_app.mojom.h"
+
+class SkBitmap;
namespace content {
@@ -51,10 +53,11 @@ class CONTENT_EXPORT PaymentAppProvider {
WebContents* web_contents,
payments::mojom::PaymentRequestEventDataPtr event_data,
const std::string& app_name,
+ const SkBitmap& app_icon,
const std::string& sw_js_url,
const std::string& sw_scope,
bool sw_use_cache,
- const std::vector<std::string>& enabled_methods,
+ const std::string& method,
InvokePaymentAppCallback callback) = 0;
virtual void CanMakePayment(
BrowserContext* browser_context,
@@ -65,6 +68,13 @@ class CONTENT_EXPORT PaymentAppProvider {
int64_t registration_id,
PaymentEventResultCallback callback) = 0;
+ // Set opened window for payment handler. Note that we maintain at most one
+ // opened window for payment handler at any moment in a browser context. The
+ // previously opened window in the same browser context will be closed after
+ // calling this interface.
+ virtual void SetOpenedWindow(WebContents* web_contents) = 0;
+ virtual void CloseOpenedWindow(BrowserContext* browser_context) = 0;
+
protected:
virtual ~PaymentAppProvider() {}
};
diff --git a/chromium/content/public/browser/permission_manager.h b/chromium/content/public/browser/permission_manager.h
index 364da65e661..f96a3ca325a 100644
--- a/chromium/content/public/browser/permission_manager.h
+++ b/chromium/content/public/browser/permission_manager.h
@@ -6,7 +6,7 @@
#define CONTENT_PUBLIC_BROWSER_PERMISSION_MANAGER_H_
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/modules/permissions/permission_status.mojom.h"
+#include "third_party/blink/public/platform/modules/permissions/permission_status.mojom.h"
class GURL;
@@ -60,12 +60,23 @@ class CONTENT_EXPORT PermissionManager {
// Returns the permission status of a given requesting_origin/embedding_origin
// tuple. This is not taking a RenderFrameHost because the call might happen
- // outside of a frame context.
+ // outside of a frame context. Prefer GetPermissionStatusForFrame (below)
+ // whenever possible.
virtual blink::mojom::PermissionStatus GetPermissionStatus(
PermissionType permission,
const GURL& requesting_origin,
const GURL& embedding_origin) = 0;
+ // Returns the permission status for a given frame. Use this over
+ // GetPermissionStatus whenever possible.
+ // TODO(raymes): Currently we still pass the |requesting_origin| as a separate
+ // parameter because we can't yet guarantee that it matches the last committed
+ // origin of the RenderFrameHost. See https://crbug.com/698985.
+ virtual blink::mojom::PermissionStatus GetPermissionStatusForFrame(
+ PermissionType permission,
+ RenderFrameHost* render_frame_host,
+ const GURL& requesting_origin) = 0;
+
// Sets the permission back to its default for the requesting_origin/
// embedding_origin tuple.
virtual void ResetPermission(PermissionType permission,
diff --git a/chromium/content/public/browser/picture_in_picture_window_controller.h b/chromium/content/public/browser/picture_in_picture_window_controller.h
new file mode 100644
index 00000000000..e5c6b2a8447
--- /dev/null
+++ b/chromium/content/public/browser/picture_in_picture_window_controller.h
@@ -0,0 +1,53 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_PUBLIC_BROWSER_PICTURE_IN_PICTURE_WINDOW_CONTROLLER_H_
+#define CONTENT_PUBLIC_BROWSER_PICTURE_IN_PICTURE_WINDOW_CONTROLLER_H_
+
+#include "content/common/content_export.h"
+
+namespace gfx {
+class Size;
+} // namespace gfx
+
+namespace viz {
+class SurfaceId;
+} // namespace viz
+
+namespace content {
+class OverlayWindow;
+class WebContents;
+
+// Interface for Picture in Picture window controllers. This is currently tied
+// to a WebContents |initiator| and created when a Picture in Picture window is
+// to be shown. This allows creation of a single window for the initiator
+// WebContents.
+class PictureInPictureWindowController {
+ public:
+ // Gets a reference to the controller associated with |initiator| and creates
+ // one if it does not exist. The returned pointer is guaranteed to be
+ // non-null.
+ CONTENT_EXPORT static PictureInPictureWindowController*
+ GetOrCreateForWebContents(WebContents* initiator);
+
+ virtual ~PictureInPictureWindowController() = default;
+
+ virtual void Show() = 0;
+ virtual void Close() = 0;
+ virtual void EmbedSurface(const viz::SurfaceId& surface_id,
+ const gfx::Size& natural_size) = 0;
+ virtual OverlayWindow* GetWindowForTesting() = 0;
+
+ // Commands.
+ virtual void TogglePlayPause() = 0;
+
+ protected:
+ // Use PictureInPictureWindowController::GetOrCreateForWebContents() to
+ // create an instance.
+ PictureInPictureWindowController() = default;
+};
+
+} // namespace content
+
+#endif // CONTENT_PUBLIC_BROWSER_PICTURE_IN_PICTURE_WINDOW_CONTROLLER_H_
diff --git a/chromium/content/public/browser/platform_notification_service.h b/chromium/content/public/browser/platform_notification_service.h
index 71b8f2d61d4..53fc4eb4393 100644
--- a/chromium/content/public/browser/platform_notification_service.h
+++ b/chromium/content/public/browser/platform_notification_service.h
@@ -14,7 +14,7 @@
#include "base/callback_forward.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/modules/permissions/permission_status.mojom.h"
+#include "third_party/blink/public/platform/modules/permissions/permission_status.mojom.h"
class GURL;
diff --git a/chromium/content/public/browser/plugin_service.h b/chromium/content/public/browser/plugin_service.h
index ac05c13b1df..27021d64244 100644
--- a/chromium/content/public/browser/plugin_service.h
+++ b/chromium/content/public/browser/plugin_service.h
@@ -35,22 +35,21 @@ struct WebPluginInfo;
// thread. This is an asynchronous wrapper around the PluginList interface for
// querying plugin information. This must be used instead of that to avoid
// doing expensive disk operations on the IO/UI threads.
-class PluginService {
+class CONTENT_EXPORT PluginService {
public:
using GetPluginsCallback =
base::OnceCallback<void(const std::vector<WebPluginInfo>&)>;
// Returns the PluginService singleton.
- CONTENT_EXPORT static PluginService* GetInstance();
+ static PluginService* GetInstance();
// Tells all the renderer processes associated with the given browser context
// to throw away their cache of the plugin list, and optionally also reload
// all the pages with plugins. If |browser_context| is nullptr, purges the
// cache in all renderers.
// NOTE: can only be called on the UI thread.
- CONTENT_EXPORT static void PurgePluginListCache(
- BrowserContext* browser_context,
- bool reload_pages);
+ static void PurgePluginListCache(BrowserContext* browser_context,
+ bool reload_pages);
virtual ~PluginService() {}
@@ -132,6 +131,12 @@ class PluginService {
// Returns true iff PPAPI "dev channel" methods are supported.
virtual bool PpapiDevChannelSupported(BrowserContext* browser_context,
const GURL& document_url) = 0;
+
+ // Determine the number of PPAPI processes currently tracked by the service.
+ // Exposed primarily for testing purposes.
+ virtual int CountPpapiPluginProcessesForProfile(
+ const base::FilePath& plugin_path,
+ const base::FilePath& profile_data_directory) = 0;
};
} // namespace content
diff --git a/chromium/content/public/browser/presentation_screen_availability_listener.h b/chromium/content/public/browser/presentation_screen_availability_listener.h
index ef27d7666a6..46e2c86ebaf 100644
--- a/chromium/content/public/browser/presentation_screen_availability_listener.h
+++ b/chromium/content/public/browser/presentation_screen_availability_listener.h
@@ -8,7 +8,7 @@
#include <string>
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/modules/presentation/presentation.mojom.h"
+#include "third_party/blink/public/platform/modules/presentation/presentation.mojom.h"
#include "url/gurl.h"
namespace content {
diff --git a/chromium/content/public/browser/presentation_service_delegate.h b/chromium/content/public/browser/presentation_service_delegate.h
index 7072c26fa55..63ff87336bf 100644
--- a/chromium/content/public/browser/presentation_service_delegate.h
+++ b/chromium/content/public/browser/presentation_service_delegate.h
@@ -12,9 +12,10 @@
#include "base/callback.h"
#include "content/common/content_export.h"
+#include "content/public/browser/media_controller.h"
#include "content/public/common/presentation_connection_message.h"
#include "content/public/common/presentation_info.h"
-#include "third_party/WebKit/public/platform/modules/presentation/presentation.mojom.h"
+#include "third_party/blink/public/platform/modules/presentation/presentation.mojom.h"
namespace content {
@@ -168,6 +169,15 @@ class CONTENT_EXPORT ControllerPresentationServiceDelegate
int render_frame_id,
const std::string& presentation_id) = 0;
+ // Gets a MediaController for a given presentation ID.
+ // |render_process_id|, |render_frame_id|: ID of originating frame.
+ // |presentation_id|: The ID of the presentation for which we want a
+ // Controller.
+ virtual std::unique_ptr<MediaController> GetMediaController(
+ int render_process_id,
+ int render_frame_id,
+ const std::string& presentation_id) = 0;
+
// Continuously listen for state changes for a PresentationConnection in a
// frame.
// |render_process_id|, |render_frame_id|: ID of frame.
diff --git a/chromium/content/public/browser/provision_fetcher_impl.cc b/chromium/content/public/browser/provision_fetcher_impl.cc
index 2cbef6dafb6..77dab1fa220 100644
--- a/chromium/content/public/browser/provision_fetcher_impl.cc
+++ b/chromium/content/public/browser/provision_fetcher_impl.cc
@@ -4,7 +4,6 @@
#include "content/public/browser/provision_fetcher_impl.h"
-#include "base/memory/ptr_util.h"
#include "content/public/browser/provision_fetcher_factory.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "net/url_request/url_request_context_getter.h"
diff --git a/chromium/content/public/browser/push_messaging_service.cc b/chromium/content/public/browser/push_messaging_service.cc
index afab62268e2..72225f7210a 100644
--- a/chromium/content/public/browser/push_messaging_service.cc
+++ b/chromium/content/public/browser/push_messaging_service.cc
@@ -56,7 +56,7 @@ void ClearPushSubscriptionIdOnIO(
service_worker_context->ClearRegistrationUserData(
service_worker_registration_id, {kPushRegistrationIdServiceWorkerKey},
- base::Bind(&CallClosureFromIO, callback));
+ base::BindOnce(&CallClosureFromIO, callback));
}
void StorePushSubscriptionOnIOForTesting(
@@ -72,7 +72,7 @@ void StorePushSubscriptionOnIOForTesting(
service_worker_registration_id, origin,
{{kPushRegistrationIdServiceWorkerKey, subscription_id},
{kPushSenderIdServiceWorkerKey, sender_id}},
- base::Bind(&CallClosureFromIO, callback));
+ base::BindOnce(&CallClosureFromIO, callback));
}
scoped_refptr<ServiceWorkerContextWrapper> GetServiceWorkerContext(
diff --git a/chromium/content/public/browser/render_frame_host.h b/chromium/content/public/browser/render_frame_host.h
index e2edb70ab14..4a3ea81bca5 100644
--- a/chromium/content/public/browser/render_frame_host.h
+++ b/chromium/content/public/browser/render_frame_host.h
@@ -15,8 +15,8 @@
#include "content/public/common/file_chooser_params.h"
#include "ipc/ipc_listener.h"
#include "ipc/ipc_sender.h"
-#include "third_party/WebKit/public/mojom/page/page_visibility_state.mojom.h"
-#include "third_party/WebKit/public/platform/WebSuddenTerminationDisablerType.h"
+#include "third_party/blink/public/mojom/page/page_visibility_state.mojom.h"
+#include "third_party/blink/public/platform/web_sudden_termination_disabler_type.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/native_widget_types.h"
#include "url/gurl.h"
@@ -70,11 +70,6 @@ class CONTENT_EXPORT RenderFrameHost : public IPC::Listener,
// is present only to support Android WebView and must not be used in other
// configurations.
static void AllowInjectingJavaScriptForAndroidWebView();
-
- // Temporary hack to enable data URLs on Android Webview until PlzNavigate
- // ships.
- static void AllowDataUrlNavigationForAndroidWebView();
- static bool IsDataUrlNavigationAllowedForAndroidWebView();
#endif
// Returns a RenderFrameHost given its accessibility tree ID.
diff --git a/chromium/content/public/browser/render_process_host.h b/chromium/content/public/browser/render_process_host.h
index e63b5ac7e68..30213bbbf09 100644
--- a/chromium/content/public/browser/render_process_host.h
+++ b/chromium/content/public/browser/render_process_host.h
@@ -11,7 +11,6 @@
#include <list>
#include "base/containers/id_map.h"
-#include "base/memory/ptr_util.h"
#include "base/process/kill.h"
#include "base/process/process_handle.h"
#include "base/supports_user_data.h"
@@ -20,9 +19,13 @@
#include "content/public/common/bind_interface_helpers.h"
#include "ipc/ipc_channel_proxy.h"
#include "ipc/ipc_sender.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "ui/gfx/native_widget_types.h"
+#if defined(OS_ANDROID)
+#include "content/public/browser/android/child_process_importance.h"
+#endif
+
class GURL;
namespace base {
@@ -68,6 +71,28 @@ class CONTENT_EXPORT RenderProcessHost : public IPC::Sender,
public:
using iterator = base::IDMap<RenderProcessHost*>::iterator;
+ // Priority (or on Android, the importance) that a client contributes to this
+ // RenderProcessHost. Eg a RenderProcessHost with a visible client has higher
+ // priority / importance than a RenderProcessHost with hidden clients only.
+ struct Priority {
+ bool is_hidden;
+ unsigned int frame_depth;
+#if defined(OS_ANDROID)
+ ChildProcessImportance importance;
+#endif
+ };
+
+ // Interface for a client that contributes Priority to this
+ // RenderProcessHost. Clients can call UpdateClientPriority when their
+ // Priority changes.
+ class PriorityClient {
+ public:
+ virtual Priority GetPriority() = 0;
+
+ protected:
+ virtual ~PriorityClient() {}
+ };
+
// Details for RENDERER_PROCESS_CLOSED notifications.
struct RendererClosedDetails {
RendererClosedDetails(base::TerminationStatus status,
@@ -126,11 +151,15 @@ class CONTENT_EXPORT RenderProcessHost : public IPC::Sender,
// will be reported as well.
virtual void ShutdownForBadMessage(CrashReportMode crash_report_mode) = 0;
- // Track the count of visible widgets. Called by listeners to register and
- // unregister visibility.
- virtual void WidgetRestored() = 0;
- virtual void WidgetHidden() = 0;
- virtual int VisibleWidgetCount() const = 0;
+ // Recompute Priority state. PriorityClient should call this when their
+ // individual priority changes.
+ virtual void UpdateClientPriority(PriorityClient* client) = 0;
+
+ // Number of visible (ie |!is_hidden|) PriorityClients.
+ virtual int VisibleClientCount() const = 0;
+
+ // Get computed frame depth from PriorityClients.
+ virtual unsigned int GetFrameDepthForTesting() const = 0;
virtual RendererAudioOutputStreamFactoryContext*
GetRendererAudioOutputStreamFactoryContext() = 0;
@@ -150,12 +179,11 @@ class CONTENT_EXPORT RenderProcessHost : public IPC::Sender,
virtual StoragePartition* GetStoragePartition() const = 0;
// Try to shut down the associated renderer process without running unload
- // handlers, etc, giving it the specified exit code. If |wait| is true, wait
- // for the process to be actually terminated before returning. Returns true
+ // handlers, etc, giving it the specified exit code. Returns true
// if it was able to shut down. On Windows, this must not be called before
// RenderProcessReady was called on a RenderProcessHostObserver, otherwise
// RenderProcessExited may never be called.
- virtual bool Shutdown(int exit_code, bool wait) = 0;
+ virtual bool Shutdown(int exit_code) = 0;
// Try to shut down the associated renderer process as fast as possible.
// If a non-zero |page_count| value is provided, then a fast shutdown will
@@ -234,12 +262,8 @@ class CONTENT_EXPORT RenderProcessHost : public IPC::Sender,
virtual void RemoveWidget(RenderWidgetHost* widget) = 0;
#if defined(OS_ANDROID)
- // Called by an already added widget when its importance changes.
- virtual void UpdateWidgetImportance(ChildProcessImportance old_value,
- ChildProcessImportance new_value) = 0;
-
// Return the highest importance of all widgets in this process.
- virtual ChildProcessImportance ComputeEffectiveImportance() = 0;
+ virtual ChildProcessImportance GetEffectiveImportance() = 0;
#endif
// Sets a flag indicating that the process can be abnormally terminated.
@@ -289,6 +313,10 @@ class CONTENT_EXPORT RenderProcessHost : public IPC::Sender,
bool incoming,
bool outgoing,
const WebRtcRtpPacketCallback& packet_callback) = 0;
+
+ // Start/stop event log output from WebRTC on this RPH for the peer connection
+ // identified locally within the RPH using the ID |lid|.
+ virtual void SetWebRtcEventLogOutput(int lid, bool enabled) = 0;
#endif
// Tells the ResourceDispatcherHost to resume a deferred navigation without
@@ -319,6 +347,11 @@ class CONTENT_EXPORT RenderProcessHost : public IPC::Sender,
// Returns true if this process currently has backgrounded priority.
virtual bool IsProcessBackgrounded() const = 0;
+ enum class KeepAliveClientType {
+ kServiceWorker = 0,
+ kSharedWorker = 1,
+ kFetch = 2,
+ };
// "Keep alive ref count" represents the number of the customers of this
// render process who wish the renderer process to be alive. While the ref
// count is positive, |this| object will keep the renderer process alive,
@@ -340,8 +373,8 @@ class CONTENT_EXPORT RenderProcessHost : public IPC::Sender,
// When a fetch request with keepalive flag
// (https://fetch.spec.whatwg.org/#request-keepalive-flag) specified is
// pending, it wishes the renderer process to be kept alive.
- virtual void IncrementKeepAliveRefCount() = 0;
- virtual void DecrementKeepAliveRefCount() = 0;
+ virtual void IncrementKeepAliveRefCount(KeepAliveClientType) = 0;
+ virtual void DecrementKeepAliveRefCount(KeepAliveClientType) = 0;
// Sets keep alive ref counts to zero. Called when the browser context will be
// destroyed so this RenderProcessHost can immediately die.
@@ -427,9 +460,11 @@ class CONTENT_EXPORT RenderProcessHost : public IPC::Sender,
// The spare RenderProcessHost is meant to be created in a situation where a
// navigation is imminent and it is unlikely an existing RenderProcessHost
// will be used, for example in a cross-site navigation when a Service Worker
- // will need to be started.
- static void WarmupSpareRenderProcessHost(
- content::BrowserContext* browser_context);
+ // will need to be started. Note that if ContentBrowserClient opts into
+ // strict site isolation (via ShouldEnableStrictSiteIsolation), then the
+ // //content layer will maintain a warm spare process host at all times
+ // (without a need for separate calls to WarmupSpareRenderProcessHost).
+ static void WarmupSpareRenderProcessHost(BrowserContext* browser_context);
// Flag to run the renderer in process. This is primarily
// for debugging purposes. When running "in process", the
@@ -468,15 +503,6 @@ class CONTENT_EXPORT RenderProcessHost : public IPC::Sender,
static bool ShouldTryToUseExistingProcessHost(
content::BrowserContext* browser_context, const GURL& site_url);
- // Get an existing RenderProcessHost associated with the given browser
- // context, if possible. The renderer process is chosen randomly from
- // suitable renderers that share the same context and type (determined by the
- // site url).
- // Returns nullptr if no suitable renderer process is available, in which case
- // the caller is free to create a new renderer.
- static RenderProcessHost* GetExistingProcessHost(
- content::BrowserContext* browser_context, const GURL& site_url);
-
// Overrides the default heuristic for limiting the max renderer process
// count. This is useful for unit testing process limit behaviors. It is
// also used to allow a command line parameter to configure the max number of
@@ -492,6 +518,9 @@ class CONTENT_EXPORT RenderProcessHost : public IPC::Sender,
using AnalyzeHungRendererFunction = void (*)(const base::Process& renderer);
static void SetHungRendererAnalysisFunction(
AnalyzeHungRendererFunction analyze_hung_renderer);
+
+ // Counts current RenderProcessHost(s), ignoring the spare process.
+ static int GetCurrentRenderProcessCountForTesting();
};
} // namespace content
diff --git a/chromium/content/public/browser/render_process_host_observer.h b/chromium/content/public/browser/render_process_host_observer.h
index 660a4b59cda..3aeec100526 100644
--- a/chromium/content/public/browser/render_process_host_observer.h
+++ b/chromium/content/public/browser/render_process_host_observer.h
@@ -19,7 +19,7 @@ class CONTENT_EXPORT RenderProcessHostObserver {
public:
// This method is invoked when the process was launched and the channel was
// connected. This is the earliest time it is safe to call Shutdown on the
- // RenderProcessHost and get RenderProcessExited notifications.
+ // RenderProcessHost.
virtual void RenderProcessReady(RenderProcessHost* host) {}
// This method is invoked when the process when the process could shut down
diff --git a/chromium/content/public/browser/render_view_host.h b/chromium/content/public/browser/render_view_host.h
index 322f3cedf33..b42a63674ce 100644
--- a/chromium/content/public/browser/render_view_host.h
+++ b/chromium/content/public/browser/render_view_host.h
@@ -13,7 +13,7 @@
#include "content/public/common/page_zoom.h"
#include "ipc/ipc_sender.h"
#include "mojo/public/cpp/system/core.h"
-#include "third_party/WebKit/public/platform/WebDragOperation.h"
+#include "third_party/blink/public/platform/web_drag_operation.h"
namespace base {
class FilePath;
@@ -95,14 +95,6 @@ class CONTENT_EXPORT RenderViewHost : public IPC::Sender {
// threshold.
virtual void DisableScrollbarsForThreshold(const gfx::Size& size) = 0;
- // Instructs the RenderView to automatically resize and send back updates
- // for the new size.
- virtual void EnableAutoResize(const gfx::Size& min_size,
- const gfx::Size& max_size) = 0;
-
- // Turns off auto-resize and gives a new size that the view should be.
- virtual void DisableAutoResize(const gfx::Size& new_size) = 0;
-
// Instructs the RenderView to send back updates to the preferred size.
virtual void EnablePreferredSizeMode() = 0;
diff --git a/chromium/content/public/browser/render_widget_host.h b/chromium/content/public/browser/render_widget_host.h
index e7358505998..d0ea640fac2 100644
--- a/chromium/content/public/browser/render_widget_host.h
+++ b/chromium/content/public/browser/render_widget_host.h
@@ -15,10 +15,10 @@
#include "content/public/common/input_event_ack_state.h"
#include "ipc/ipc_channel.h"
#include "ipc/ipc_sender.h"
-#include "third_party/WebKit/public/platform/WebDragOperation.h"
-#include "third_party/WebKit/public/platform/WebGestureEvent.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
-#include "third_party/WebKit/public/web/WebTextDirection.h"
+#include "third_party/blink/public/platform/web_drag_operation.h"
+#include "third_party/blink/public/platform/web_gesture_event.h"
+#include "third_party/blink/public/platform/web_input_event.h"
+#include "third_party/blink/public/web/web_text_direction.h"
#include "ui/surface/transport_dib.h"
namespace blink {
diff --git a/chromium/content/public/browser/render_widget_host_view.h b/chromium/content/public/browser/render_widget_host_view.h
index 71f3b3cc9e8..1ced1c489b4 100644
--- a/chromium/content/public/browser/render_widget_host_view.h
+++ b/chromium/content/public/browser/render_widget_host_view.h
@@ -5,12 +5,12 @@
#ifndef CONTENT_PUBLIC_BROWSER_RENDER_WIDGET_HOST_VIEW_H_
#define CONTENT_PUBLIC_BROWSER_RENDER_WIDGET_HOST_VIEW_H_
-#include <memory>
-
+#include "base/containers/flat_set.h"
+#include "base/optional.h"
#include "base/strings/string16.h"
#include "build/build_config.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/gfx/geometry/point_conversions.h"
@@ -22,10 +22,22 @@ class Rect;
class Size;
}
+namespace mojo {
+template <class T>
+class InterfacePtr;
+}
+
namespace ui {
class TextInputClient;
}
+namespace viz {
+namespace mojom {
+class FrameSinkVideoCapturer;
+using FrameSinkVideoCapturerPtr = mojo::InterfacePtr<FrameSinkVideoCapturer>;
+} // namespace mojom
+} // namespace viz
+
namespace content {
class RenderWidgetHost;
@@ -59,12 +71,20 @@ class CONTENT_EXPORT RenderWidgetHostView {
// Tells the View to size itself to the specified size.
virtual void SetSize(const gfx::Size& size) = 0;
+ // Instructs the View to automatically resize and send back updates
+ // for the new size.
+ virtual void EnableAutoResize(const gfx::Size& min_size,
+ const gfx::Size& max_size) = 0;
+
+ // Turns off auto-resize and gives a new size that the view should be.
+ virtual void DisableAutoResize(const gfx::Size& new_size) = 0;
+
// Tells the View to size and move itself to the specified size and point in
// screen space.
virtual void SetBounds(const gfx::Rect& rect) = 0;
- // Retrieves the last known scroll position.
- virtual gfx::Vector2dF GetLastScrollOffset() const = 0;
+ // Indicates whether the scroll offset of the view is at top.
+ virtual bool IsScrollOffsetAtTop() const = 0;
// Sets a flag that indicates if it is in virtual reality mode.
virtual void SetIsInVR(bool is_in_vr) = 0;
@@ -116,9 +136,7 @@ class CONTENT_EXPORT RenderWidgetHostView {
// Indicates if the view is currently occluded (e.g, not visible because it's
// covered up by other windows), and as a result the view's renderer may be
- // suspended. If Show() is called on a view then its state should be re-set to
- // being un-occluded (an explicit WasUnOccluded call will not be made for
- // that). These calls are not necessarily made in pairs.
+ // suspended. Calling Show()/Hide() overrides the state set by these methods.
virtual void WasUnOccluded() = 0;
virtual void WasOccluded() = 0;
@@ -151,6 +169,12 @@ class CONTENT_EXPORT RenderWidgetHostView {
// Returns true if the mouse pointer is currently locked.
virtual bool IsMouseLocked() = 0;
+ // Start/Stop intercepting future system keyboard events.
+ virtual bool LockKeyboard(base::Optional<base::flat_set<int>> keys) = 0;
+ virtual void UnlockKeyboard() = 0;
+ // Returns true if keyboard lock is active.
+ virtual bool IsKeyboardLocked() = 0;
+
// Retrives the size of the viewport for the visible region. May be smaller
// than the view size if a portion of the view is obstructed (e.g. by a
// virtual keyboard).
@@ -167,7 +191,7 @@ class CONTENT_EXPORT RenderWidgetHostView {
// Copies the given subset of the view's surface, optionally scales it, and
// returns the result as a bitmap via the provided callback. This is meant for
// one-off snapshots. For continuous video capture of the surface, please use
- // viz::FrameSinkManager::CreateVideoCapturer() instead.
+ // CreateVideoCapturer() instead.
//
// |src_rect| is either the subset of the view's surface, in view coordinates,
// or empty to indicate that all of it should be copied. This is NOT the same
@@ -190,13 +214,16 @@ class CONTENT_EXPORT RenderWidgetHostView {
const gfx::Size& output_size,
base::OnceCallback<void(const SkBitmap&)> callback) = 0;
+ // Creates a video capturer, which will allow the caller to receive a stream
+ // of media::VideoFrames captured from this view. The capturer is configured
+ // to target this view, so there is no need to call ChangeTarget() before
+ // Start(). See viz.mojom.FrameSinkVideoCapturer for documentation.
+ virtual viz::mojom::FrameSinkVideoCapturerPtr CreateVideoCapturer() = 0;
+
// Notification that a node was touched.
- // The |location_dips_screen| parameter contains the location where the touch
- // occurred in DIPs in screen coordinates.
// The |editable| parameter indicates if the node is editable, for e.g.
// an input field, etc.
- virtual void FocusedNodeTouched(const gfx::Point& location_dips_screen,
- bool editable) = 0;
+ virtual void FocusedNodeTouched(bool editable) = 0;
// Informs the view that its associated render widget has frames to draw and
// wants to have BeginFrame messages sent to it. This should only be called
@@ -222,15 +249,13 @@ class CONTENT_EXPORT RenderWidgetHostView {
// Brings up the dictionary showing a definition for the selected text.
virtual void ShowDefinitionForSelection() = 0;
- // Returns |true| if Mac OS X text to speech is supported.
- virtual bool SupportsSpeech() const = 0;
// Tells the view to speak the currently selected text.
virtual void SpeakSelection() = 0;
- // Returns |true| if text is currently being spoken by Mac OS X.
- virtual bool IsSpeaking() const = 0;
- // Stops speaking, if it is currently in progress.
- virtual void StopSpeaking() = 0;
#endif // defined(OS_MACOSX)
+
+ // Indicates that this view should show the contents of |view| if it doesn't
+ // have anything to show.
+ virtual void TakeFallbackContentFrom(RenderWidgetHostView* view) = 0;
};
} // namespace content
diff --git a/chromium/content/public/browser/render_widget_host_view_mac_delegate.h b/chromium/content/public/browser/render_widget_host_view_mac_delegate.h
index da0360ceeed..1de4530f0cb 100644
--- a/chromium/content/public/browser/render_widget_host_view_mac_delegate.h
+++ b/chromium/content/public/browser/render_widget_host_view_mac_delegate.h
@@ -27,22 +27,6 @@ struct DidOverscrollParams;
@class NSEvent;
@protocol RenderWidgetHostViewMacDelegate
-@optional
-// Notification that the view is gone.
-- (void)viewGone:(NSView*)view;
-
-// Handle an event. All incoming key and mouse events flow through this delegate
-// method if implemented. Return YES if the event is fully handled, or NO if
-// normal processing should take place.
-- (BOOL)handleEvent:(NSEvent*)event;
-
-// Provides validation of user interface items. If the return value is NO, then
-// the delegate is unaware of that item and |valid| is undefined. Otherwise,
-// |valid| contains the validity of the specified item.
-- (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item
- isValidItem:(BOOL*)valid;
-
-@required
// Notification of when a gesture begins/ends.
- (void)beginGestureWithEvent:(NSEvent*)event;
- (void)endGestureWithEvent:(NSEvent*)event;
@@ -62,6 +46,26 @@ struct DidOverscrollParams;
- (void)rendererHandledGestureScrollEvent:(const blink::WebGestureEvent&)event
consumed:(BOOL)consumed;
- (void)rendererHandledOverscrollEvent:(const ui::DidOverscrollParams&)params;
+
+@optional
+// Notification that the view is gone.
+- (void)viewGone:(NSView*)view;
+
+// Handle an event. All incoming key and mouse events flow through this delegate
+// method if implemented. Return YES if the event is fully handled, or NO if
+// normal processing should take place.
+- (BOOL)handleEvent:(NSEvent*)event;
+
+// Provides validation of user interface items. If the return value is NO, then
+// the delegate is unaware of that item and |valid| is undefined. Otherwise,
+// |valid| contains the validity of the specified item.
+- (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item
+ isValidItem:(BOOL*)valid;
+
+- (void)becomeFirstResponder;
+- (void)resignFirstResponder;
+
+- (void)windowDidBecomeKey;
@end
#endif // CONTENT_PUBLIC_BROWSER_RENDER_WIDGET_HOST_VIEW_MAC_DELEGATE_H_
diff --git a/chromium/content/public/browser/resource_dispatcher_host_delegate.cc b/chromium/content/public/browser/resource_dispatcher_host_delegate.cc
index 4addf92613c..838ec2e1295 100644
--- a/chromium/content/public/browser/resource_dispatcher_host_delegate.cc
+++ b/chromium/content/public/browser/resource_dispatcher_host_delegate.cc
@@ -35,12 +35,6 @@ void ResourceDispatcherHostDelegate::DownloadStarting(
bool is_new_request,
std::vector<std::unique_ptr<ResourceThrottle>>* throttles) {}
-bool ResourceDispatcherHostDelegate::HandleExternalProtocol(
- const GURL& url,
- ResourceRequestInfo* info) {
- return true;
-}
-
bool ResourceDispatcherHostDelegate::ShouldInterceptResourceAsStream(
net::URLRequest* request,
const std::string& mime_type,
diff --git a/chromium/content/public/browser/resource_dispatcher_host_delegate.h b/chromium/content/public/browser/resource_dispatcher_host_delegate.h
index 2d904ad485f..8a11639fba0 100644
--- a/chromium/content/public/browser/resource_dispatcher_host_delegate.h
+++ b/chromium/content/public/browser/resource_dispatcher_host_delegate.h
@@ -65,12 +65,6 @@ class CONTENT_EXPORT ResourceDispatcherHostDelegate {
bool is_new_request,
std::vector<std::unique_ptr<ResourceThrottle>>* throttles);
- // Launches the url for the given tab. Returns true if an attempt to handle
- // the url was made, e.g. by launching an app. Note that this does not
- // guarantee that the app successfully handled it.
- virtual bool HandleExternalProtocol(const GURL& url,
- ResourceRequestInfo* info);
-
// Returns true and sets |origin| if a Stream should be created for the
// resource. If true is returned, a new Stream will be created and
// OnStreamCreated() will be called with a StreamHandle instance for the
diff --git a/chromium/content/public/browser/resource_request_info.h b/chromium/content/public/browser/resource_request_info.h
index f58248c55fd..6e05dd71c37 100644
--- a/chromium/content/public/browser/resource_request_info.h
+++ b/chromium/content/public/browser/resource_request_info.h
@@ -12,7 +12,7 @@
#include "content/public/browser/navigation_ui_data.h"
#include "content/public/common/previews_state.h"
#include "content/public/common/resource_type.h"
-#include "third_party/WebKit/public/platform/WebReferrerPolicy.h"
+#include "third_party/blink/public/platform/web_referrer_policy.h"
#include "ui/base/page_transition_types.h"
namespace net {
@@ -175,8 +175,16 @@ class ResourceRequestInfo {
// UI thread at the beginning of navigation.
virtual NavigationUIData* GetNavigationUIData() const = 0;
- // Whether this request was canceled by DevTools.
- virtual bool CanceledByDevTools() const = 0;
+ enum class DevToolsStatus {
+ kCanceled,
+ // DevTools can internally handle a redirect, so the url request may
+ // appear never done. Mark these cases.
+ kCanceledAsRedirect,
+ kNotCanceled,
+ };
+
+ // If and why this request was canceled by DevTools.
+ virtual DevToolsStatus GetDevToolsStatus() const = 0;
// When the client of a request decides to cancel it, it may optionally
// provide an application-defined description of the canncellation reason.
diff --git a/chromium/content/public/browser/screen_orientation_delegate.h b/chromium/content/public/browser/screen_orientation_delegate.h
index 06822a18c3a..6862cc4145e 100644
--- a/chromium/content/public/browser/screen_orientation_delegate.h
+++ b/chromium/content/public/browser/screen_orientation_delegate.h
@@ -7,7 +7,7 @@
#include "base/macros.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/modules/screen_orientation/WebScreenOrientationLockType.h"
+#include "third_party/blink/public/platform/modules/screen_orientation/web_screen_orientation_lock_type.h"
namespace content {
diff --git a/chromium/content/public/browser/security_style_explanation.h b/chromium/content/public/browser/security_style_explanation.h
index bdf826ff196..022c81349ad 100644
--- a/chromium/content/public/browser/security_style_explanation.h
+++ b/chromium/content/public/browser/security_style_explanation.h
@@ -9,7 +9,7 @@
#include "content/common/content_export.h"
#include "net/cert/x509_certificate.h"
-#include "third_party/WebKit/public/platform/WebMixedContentContextType.h"
+#include "third_party/blink/public/platform/web_mixed_content_context_type.h"
namespace content {
diff --git a/chromium/content/public/browser/security_style_explanations.h b/chromium/content/public/browser/security_style_explanations.h
index 981970b1b57..b3026dd49de 100644
--- a/chromium/content/public/browser/security_style_explanations.h
+++ b/chromium/content/public/browser/security_style_explanations.h
@@ -9,7 +9,7 @@
#include "content/common/content_export.h"
#include "content/public/browser/security_style_explanation.h"
-#include "third_party/WebKit/public/platform/WebSecurityStyle.h"
+#include "third_party/blink/public/platform/web_security_style.h"
namespace content {
diff --git a/chromium/content/public/browser/service_worker_context.h b/chromium/content/public/browser/service_worker_context.h
index cc17352bade..9d47e82a744 100644
--- a/chromium/content/public/browser/service_worker_context.h
+++ b/chromium/content/public/browser/service_worker_context.h
@@ -11,7 +11,7 @@
#include "base/callback_forward.h"
#include "content/public/browser/service_worker_usage_info.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
#include "url/gurl.h"
namespace content {
diff --git a/chromium/content/browser/site_isolation_policy.cc b/chromium/content/public/browser/site_isolation_policy.cc
index 97e9518f43b..aa1599deaae 100644
--- a/chromium/content/browser/site_isolation_policy.cc
+++ b/chromium/content/public/browser/site_isolation_policy.cc
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "content/browser/site_isolation_policy.h"
+#include "content/public/browser/site_isolation_policy.h"
#include <algorithm>
#include <iterator>
@@ -36,15 +36,23 @@ bool SiteIsolationPolicy::UseDedicatedProcessesForAllSites() {
return false;
}
- // The feature needs to be checked last, because checking the feature
- // activates the field trial and assigns the client either to a control or an
- // experiment group.
- return base::FeatureList::IsEnabled(features::kSitePerProcess);
+ // The switches above needs to be checked first, because if the
+ // ContentBrowserClient consults a base::Feature, then it will activate the
+ // field trial and assigns the client either to a control or an experiment
+ // group - such assignment should be final.
+ return GetContentClient() &&
+ GetContentClient()->browser()->ShouldEnableStrictSiteIsolation();
}
// static
SiteIsolationPolicy::CrossSiteDocumentBlockingEnabledState
SiteIsolationPolicy::IsCrossSiteDocumentBlockingEnabled() {
+ // --disable-web-security also disables cross-origin response blocking (CORB).
+ if (base::CommandLine::ForCurrentProcess()->HasSwitch(
+ switches::kDisableWebSecurity)) {
+ return XSDB_DISABLED;
+ }
+
if (base::FeatureList::IsEnabled(
::features::kCrossSiteDocumentBlockingAlways)) {
return XSDB_ENABLED_UNCONDITIONALLY;
@@ -71,12 +79,15 @@ bool SiteIsolationPolicy::IsTopDocumentIsolationEnabled() {
// The feature needs to be checked last, because checking the feature
// activates the field trial and assigns the client either to a control or an
- // experiment group.
+ // experiment group - such assignment should be final.
return base::FeatureList::IsEnabled(::features::kTopDocumentIsolation);
}
// static
bool SiteIsolationPolicy::AreIsolatedOriginsEnabled() {
+ // NOTE: Because it is possible for --isolate-origins to be isolating origins
+ // at a finer-than-site granularity, we do not suppress --isolate-origins when
+ // --site-per-process is also enabled.
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kIsolateOrigins)) {
return true;
@@ -89,11 +100,24 @@ bool SiteIsolationPolicy::AreIsolatedOriginsEnabled() {
// The feature needs to be checked last, because checking the feature
// activates the field trial and assigns the client either to a control or an
- // experiment group.
+ // experiment group - such assignment should be final.
return base::FeatureList::IsEnabled(features::kIsolateOrigins);
}
// static
+
+bool SiteIsolationPolicy::ShouldPdfCompositorBeEnabledForOopifs() {
+ // TODO(weili): We only create pdf compositor client and use pdf compositor
+ // service when site-per-process or isolate-origins flag/feature is enabled,
+ // or top-document-isolation feature is enabled. This may not cover all cases
+ // where OOPIF is used such as isolate-extensions, but should be good for
+ // feature testing purpose. Eventually, we will remove this check and use pdf
+ // compositor service by default for printing.
+ return AreIsolatedOriginsEnabled() || IsTopDocumentIsolationEnabled() ||
+ UseDedicatedProcessesForAllSites();
+}
+
+// static
std::vector<url::Origin>
SiteIsolationPolicy::GetIsolatedOriginsFromEnvironment() {
std::string cmdline_arg =
@@ -114,7 +138,7 @@ SiteIsolationPolicy::GetIsolatedOriginsFromEnvironment() {
// The feature needs to be checked last, because checking the feature
// activates the field trial and assigns the client either to a control or an
- // experiment group.
+ // experiment group - such assignment should be final.
if (base::FeatureList::IsEnabled(features::kIsolateOrigins)) {
std::string field_trial_arg = base::GetFieldTrialParamValueByFeature(
features::kIsolateOrigins,
diff --git a/chromium/content/browser/site_isolation_policy.h b/chromium/content/public/browser/site_isolation_policy.h
index cfaa35dd83c..06e13c0d98a 100644
--- a/chromium/content/browser/site_isolation_policy.h
+++ b/chromium/content/public/browser/site_isolation_policy.h
@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef CONTENT_BROWSER_SITE_ISOLATION_POLICY_H_
-#define CONTENT_BROWSER_SITE_ISOLATION_POLICY_H_
+#ifndef CONTENT_PUBLIC_BROWSER_SITE_ISOLATION_POLICY_H_
+#define CONTENT_PUBLIC_BROWSER_SITE_ISOLATION_POLICY_H_
#include <vector>
@@ -43,6 +43,10 @@ class CONTENT_EXPORT SiteIsolationPolicy {
// Returns true if isolated origins feature is enabled.
static bool AreIsolatedOriginsEnabled();
+ // Returns true if the PDF compositor should be enabled to allow out-of-
+ // process iframes (OOPIF's) to print properly.
+ static bool ShouldPdfCompositorBeEnabledForOopifs();
+
// Returns the origins to isolate. See also AreIsolatedOriginsEnabled.
// This list applies globally to the whole browser in all profiles.
static std::vector<url::Origin> GetIsolatedOrigins();
@@ -70,4 +74,4 @@ class CONTENT_EXPORT SiteIsolationPolicy {
} // namespace content
-#endif // CONTENT_BROWSER_SITE_ISOLATION_POLICY_H_
+#endif // CONTENT_PUBLIC_BROWSER_SITE_ISOLATION_POLICY_H_
diff --git a/chromium/content/browser/site_isolation_policy_unittest.cc b/chromium/content/public/browser/site_isolation_policy_unittest.cc
index a60ec5d6c36..a3ed6c16cff 100644
--- a/chromium/content/browser/site_isolation_policy_unittest.cc
+++ b/chromium/content/public/browser/site_isolation_policy_unittest.cc
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "content/browser/site_isolation_policy.h"
+#include "content/public/browser/site_isolation_policy.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
diff --git a/chromium/content/public/browser/speech_recognition_manager.h b/chromium/content/public/browser/speech_recognition_manager.h
index 4e6e9b7efb4..8c6040ef98c 100644
--- a/chromium/content/public/browser/speech_recognition_manager.h
+++ b/chromium/content/public/browser/speech_recognition_manager.h
@@ -42,19 +42,15 @@ class SpeechRecognitionManager {
virtual int CreateSession(const SpeechRecognitionSessionConfig& config) = 0;
// Starts/restarts recognition for an existing session, after performing a
- // premilinary check on the delegate (CheckRecognitionIsAllowed).
+ // preliminary check on the delegate (CheckRecognitionIsAllowed).
virtual void StartSession(int session_id) = 0;
// Aborts recognition for an existing session, without providing any result.
virtual void AbortSession(int session_id) = 0;
- // Aborts all sessions for a given render process,
- // without providing any result.
- virtual void AbortAllSessionsForRenderProcess(int render_process_id) = 0;
-
- // Aborts all sessions for a given RenderView, without providing any result.
- virtual void AbortAllSessionsForRenderView(int render_process_id,
- int render_view_id) = 0;
+ // Aborts all sessions for a given RenderFrame, without providing any result.
+ virtual void AbortAllSessionsForRenderFrame(int render_process_id,
+ int render_frame_id) = 0;
// Stops audio capture for an existing session. The audio captured before the
// call will be processed, possibly ending up with a result.
@@ -69,10 +65,10 @@ class SpeechRecognitionManager {
virtual SpeechRecognitionSessionContext GetSessionContext(
int session_id) const = 0;
- // Looks-up an existing session from the context tuple
- // {render_view_id, render_view_id, request_id}.
+ // Looks up an existing session from the context tuple
+ // {render_process_id, render_frame_id, request_id}.
virtual int GetSession(int render_process_id,
- int render_view_id,
+ int render_frame_id,
int request_id) const = 0;
protected:
diff --git a/chromium/content/public/browser/speech_recognition_session_context.cc b/chromium/content/public/browser/speech_recognition_session_context.cc
index 1e4ae1cfed5..ebcb190fb81 100644
--- a/chromium/content/public/browser/speech_recognition_session_context.cc
+++ b/chromium/content/public/browser/speech_recognition_session_context.cc
@@ -10,13 +10,10 @@ namespace content {
SpeechRecognitionSessionContext::SpeechRecognitionSessionContext()
: render_process_id(0),
- render_view_id(0),
- render_frame_id(0),
- guest_render_view_id(MSG_ROUTING_NONE),
+ render_frame_id(MSG_ROUTING_NONE),
embedder_render_process_id(0),
- embedder_render_view_id(MSG_ROUTING_NONE),
- request_id(0) {
-}
+ embedder_render_frame_id(MSG_ROUTING_NONE),
+ request_id(0) {}
SpeechRecognitionSessionContext::SpeechRecognitionSessionContext(
const SpeechRecognitionSessionContext& other) = default;
diff --git a/chromium/content/public/browser/speech_recognition_session_context.h b/chromium/content/public/browser/speech_recognition_session_context.h
index 997d6b5d4ff..b0cfb8e6b3d 100644
--- a/chromium/content/public/browser/speech_recognition_session_context.h
+++ b/chromium/content/public/browser/speech_recognition_session_context.h
@@ -18,33 +18,21 @@ namespace content {
// elements involved with it (e.g., the page element that requested the
// recognition). The manager keeps this struct attached to the recognition
// session during all the session lifetime, making its contents available to
-// clients (In this regard, see SpeechRecognitionManager::GetSessionContext and
-// SpeechRecognitionManager::LookupSessionByContext methods).
+// clients. (In this regard, see SpeechRecognitionManager::GetSessionContext().)
struct CONTENT_EXPORT SpeechRecognitionSessionContext {
SpeechRecognitionSessionContext();
SpeechRecognitionSessionContext(const SpeechRecognitionSessionContext& other);
~SpeechRecognitionSessionContext();
int render_process_id;
- int render_view_id;
int render_frame_id;
- // Browser plugin guest's render view id, if this context represents a speech
- // recognition request from an embedder on behalf of the guest. This is used
- // for input tag where speech bubble is to be shown.
- //
- // TODO(lazyboy): Right now showing bubble from guest does not work, we fall
- // back to embedder instead, fix this and use
- // embedder_render_process_id/embedder_render_view_id similar to Web Speech
- // API below.
- int guest_render_view_id;
-
- // The pair (|embedder_render_process_id|, |embedder_render_view_id|)
+ // The pair (|embedder_render_process_id|, |embedder_render_frame_id|)
// represents a Browser plugin guest's embedder. This is filled in if the
// session is from a guest Web Speech API. We use these to check if the
// embedder (app) is permitted to use audio.
int embedder_render_process_id;
- int embedder_render_view_id;
+ int embedder_render_frame_id;
// The request id provided by the originating SpeechRecognitionDispatcher.
int request_id;
diff --git a/chromium/content/public/browser/storage_partition.h b/chromium/content/public/browser/storage_partition.h
index 55c298e02b5..ec12926fcbb 100644
--- a/chromium/content/public/browser/storage_partition.h
+++ b/chromium/content/public/browser/storage_partition.h
@@ -13,8 +13,8 @@
#include "base/files/file_path.h"
#include "base/time/time.h"
#include "content/common/content_export.h"
-#include "content/public/common/shared_url_loader_factory.h"
#include "net/cookies/cookie_store.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
class GURL;
@@ -56,6 +56,7 @@ class IndexedDBContext;
class PlatformNotificationContext;
class ServiceWorkerContext;
class SharedWorkerService;
+class WebPackageContext;
#if !defined(OS_ANDROID)
class HostZoomLevelContext;
@@ -75,14 +76,19 @@ class CONTENT_EXPORT StoragePartition {
virtual net::URLRequestContextGetter* GetURLRequestContext() = 0;
virtual net::URLRequestContextGetter* GetMediaURLRequestContext() = 0;
virtual network::mojom::NetworkContext* GetNetworkContext() = 0;
- // Returns a pointer to a URLLoaderFactory/CookieManager owned by the
- // storage partition. Prefer to use this instead of creating a new
+ // Returns a pointer/info to a URLLoaderFactory/CookieManager owned by
+ // the storage partition. Prefer to use this instead of creating a new
// URLLoaderFactory when issuing requests from the Browser process, to
// share resources and preserve ordering.
+ // The returned info from |GetURLLoaderFactoryForBrowserProcessIOThread()|
+ // must be consumed on the IO thread to get the actual factory, and is safe to
+ // use after StoragePartition has gone.
// The returned SharedURLLoaderFactory can be held on and will work across
// network process restarts.
- virtual scoped_refptr<SharedURLLoaderFactory>
+ virtual scoped_refptr<network::SharedURLLoaderFactory>
GetURLLoaderFactoryForBrowserProcess() = 0;
+ virtual std::unique_ptr<network::SharedURLLoaderFactoryInfo>
+ GetURLLoaderFactoryForBrowserProcessIOThread() = 0;
virtual network::mojom::CookieManager*
GetCookieManagerForBrowserProcess() = 0;
virtual storage::QuotaManager* GetQuotaManager() = 0;
@@ -100,6 +106,7 @@ class CONTENT_EXPORT StoragePartition {
virtual ZoomLevelDelegate* GetZoomLevelDelegate() = 0;
#endif // !defined(OS_ANDROID)
virtual PlatformNotificationContext* GetPlatformNotificationContext() = 0;
+ virtual WebPackageContext* GetWebPackageContext() = 0;
enum : uint32_t {
REMOVE_DATA_MASK_APPCACHE = 1 << 0,
diff --git a/chromium/content/public/browser/stored_payment_app.h b/chromium/content/public/browser/stored_payment_app.h
index 359b3257aea..55ccba8765d 100644
--- a/chromium/content/public/browser/stored_payment_app.h
+++ b/chromium/content/public/browser/stored_payment_app.h
@@ -57,6 +57,11 @@ struct CONTENT_EXPORT StoredPaymentApp {
// A list of one or more enabled payment methods in this payment app.
std::vector<std::string> enabled_methods;
+ // A flag indicates whether this app has explicitly verified payment methods,
+ // like listed as default application or supported origin in the payment
+ // methods' manifest.
+ bool has_explicitly_verified_methods = false;
+
// A list of capabilities in this payment app.
// |capabilities| is non-empty only if |enabled_methods| contains "basic-card"
// for now and these |capabilities| apply only to the "basic-card" instrument,
diff --git a/chromium/content/public/browser/touch_selection_controller_client_manager.h b/chromium/content/public/browser/touch_selection_controller_client_manager.h
index 01460afe153..8d037d954ef 100644
--- a/chromium/content/public/browser/touch_selection_controller_client_manager.h
+++ b/chromium/content/public/browser/touch_selection_controller_client_manager.h
@@ -55,7 +55,7 @@ class CONTENT_EXPORT TouchSelectionControllerClientManager {
virtual void InvalidateClient(ui::TouchSelectionControllerClient* client) = 0;
// Provides direct access to the TouchSelectionController that will be used
- // with all clients accessing this manager. Always returns non-null value.
+ // with all clients accessing this manager. May return null values on Android.
virtual ui::TouchSelectionController* GetTouchSelectionController() = 0;
// The following two functions allow clients (or their owners, etc.) to
diff --git a/chromium/content/public/browser/utility_process_host.h b/chromium/content/public/browser/utility_process_host.h
deleted file mode 100644
index 376a3c29fd5..00000000000
--- a/chromium/content/public/browser/utility_process_host.h
+++ /dev/null
@@ -1,88 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_PUBLIC_BROWSER_UTILITY_PROCESS_HOST_H_
-#define CONTENT_PUBLIC_BROWSER_UTILITY_PROCESS_HOST_H_
-
-#include "base/environment.h"
-#include "base/process/launch.h"
-#include "base/threading/thread.h"
-#include "build/build_config.h"
-#include "content/common/content_export.h"
-#include "content/public/common/bind_interface_helpers.h"
-#include "ipc/ipc_sender.h"
-#include "mojo/public/cpp/bindings/interface_ptr.h"
-#include "mojo/public/cpp/bindings/interface_request.h"
-#include "mojo/public/cpp/system/message_pipe.h"
-#include "services/service_manager/sandbox/sandbox_type.h"
-
-namespace base {
-class FilePath;
-class SequencedTaskRunner;
-}
-
-namespace content {
-class BrowserMessageFilter;
-class UtilityProcessHostClient;
-struct ChildProcessData;
-
-// This class acts as the browser-side host to a utility child process. A
-// utility process is a short-lived process that is created to run a specific
-// task. This class lives solely on the IO thread.
-// If you need a single method call in the process, use StartFooBar(p).
-// If you need multiple batches of work to be done in the process, use
-// StartBatchMode(), then multiple calls to StartFooBar(p), then finish with
-// EndBatchMode().
-// If you need to bind Mojo interfaces, use Start() to start the child
-// process and then call BindInterface().
-//
-// Note: If your class keeps a ptr to an object of this type, grab a weak ptr to
-// avoid a use after free since this object is deleted synchronously but the
-// client notification is asynchronous. See http://crbug.com/108871.
-class UtilityProcessHost : public IPC::Sender {
- public:
- // Used to create a utility process. |client| is optional. If supplied it will
- // be notified of incoming messages from the utility process.
- // |client_task_runner| is required if |client| is supplied and is the task
- // runner upon which |client| will be invoked.
- CONTENT_EXPORT static UtilityProcessHost* Create(
- const scoped_refptr<UtilityProcessHostClient>& client,
- const scoped_refptr<base::SequencedTaskRunner>& client_task_runner);
-
- ~UtilityProcessHost() override {}
-
- virtual base::WeakPtr<UtilityProcessHost> AsWeakPtr() = 0;
-
- // Allows a directory to be opened through the sandbox, in case it's needed by
- // the operation.
- virtual void SetExposedDir(const base::FilePath& dir) = 0;
-
- // Make the process run with a specific sandbox type, or unsandboxed if
- // SANDBOX_TYPE_NO_SANDBOX is specified.
- virtual void SetSandboxType(service_manager::SandboxType sandbox_type) = 0;
-
- // Returns information about the utility child process.
- virtual const ChildProcessData& GetData() = 0;
-
-#if defined(OS_POSIX)
- virtual void SetEnv(const base::EnvironmentMap& env) = 0;
-#endif
-
- // Starts the utility process.
- virtual bool Start() = 0;
-
- // Bind an interface exposed by the utility process.
- virtual void BindInterface(const std::string& interface_name,
- mojo::ScopedMessagePipeHandle interface_pipe) = 0;
-
- // Set the name of the process to appear in the task manager.
- virtual void SetName(const base::string16& name) = 0;
-
- // Adds an IPC message filter.
- virtual void AddFilter(BrowserMessageFilter* filter) = 0;
-};
-
-}; // namespace content
-
-#endif // CONTENT_PUBLIC_BROWSER_UTILITY_PROCESS_HOST_H_
diff --git a/chromium/content/public/browser/utility_process_mojo_client.h b/chromium/content/public/browser/utility_process_mojo_client.h
deleted file mode 100644
index f38a1a66c8a..00000000000
--- a/chromium/content/public/browser/utility_process_mojo_client.h
+++ /dev/null
@@ -1,185 +0,0 @@
-// Copyright 2016 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_PUBLIC_BROWSER_UTILITY_PROCESS_MOJO_CLIENT_H_
-#define CONTENT_PUBLIC_BROWSER_UTILITY_PROCESS_MOJO_CLIENT_H_
-
-#include <string>
-
-#include "base/callback.h"
-#include "base/files/file_path.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/strings/string16.h"
-#include "base/threading/thread_checker.h"
-#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/utility_process_host.h"
-#include "content/public/browser/utility_process_host_client.h"
-#include "mojo/public/cpp/bindings/interface_ptr.h"
-#include "services/service_manager/public/cpp/interface_provider.h"
-
-namespace content {
-
-// Implements a client to a Mojo service running on a utility process. Takes
-// care of starting the utility process and connecting to the remote Mojo
-// service. The utility process is terminated in the destructor.
-// Note: This class is not thread-safe. It is bound to the
-// SingleThreadTaskRunner it is created on.
-template <class MojoInterface>
-class UtilityProcessMojoClient {
- public:
- explicit UtilityProcessMojoClient(const base::string16& process_name) {
- helper_.reset(new Helper(process_name));
- }
-
- ~UtilityProcessMojoClient() {
- BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, helper_.release());
- }
-
- // Sets the error callback. A valid callback must be set before calling
- // Start().
- void set_error_callback(const base::Closure& error_callback) {
- error_callback_ = error_callback;
- }
-
- // Allows a directory to be opened through the utility process sandbox.
- void set_exposed_directory(const base::FilePath& directory) {
- DCHECK(!start_called_);
- DCHECK(!directory.empty());
- helper_->set_exposed_directory(directory);
- }
-
- // Disables the sandbox in the utility process.
- void set_disable_sandbox() {
- DCHECK(!start_called_);
- helper_->set_disable_sandbox();
- }
-
-#if defined(OS_WIN)
- // Allows the utility process to run with elevated privileges.
- void set_run_elevated() {
- DCHECK(!start_called_);
- helper_->set_run_elevated();
- }
-#endif // defined(OS_WIN)
-
- // Starts the utility process and connects to the remote Mojo service.
- void Start() {
- DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
- DCHECK(error_callback_);
- DCHECK(!start_called_);
-
- start_called_ = true;
-
- auto request = MakeRequest(&service_);
- service_.set_connection_error_handler(error_callback_);
- helper_->Start(MojoInterface::Name_, request.PassMessagePipe());
- }
-
- // Returns the Mojo service used to make calls to the utility process.
- MojoInterface* service() WARN_UNUSED_RESULT {
- DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
- DCHECK(start_called_);
-
- return service_.get();
- }
-
- private:
- // Helper class that takes care of managing the lifetime of the utility
- // process on the IO thread.
- class Helper {
- public:
- explicit Helper(const base::string16& process_name)
- : process_name_(process_name) {}
-
- ~Helper() {
- DCHECK_CURRENTLY_ON(BrowserThread::IO);
-
- // |utility_host_| manages its own lifetime but this forces the process to
- // terminate if it's still alive.
- delete utility_host_.get();
- }
-
- // Starts the utility process on the IO thread.
- void Start(const std::string& mojo_interface_name,
- mojo::ScopedMessagePipeHandle interface_pipe) {
- BrowserThread::PostTask(
- BrowserThread::IO, FROM_HERE,
- base::BindOnce(&Helper::StartOnIOThread, base::Unretained(this),
- mojo_interface_name, std::move(interface_pipe)));
- }
-
- void set_exposed_directory(const base::FilePath& directory) {
- exposed_directory_ = directory;
- }
-
- void set_disable_sandbox() { disable_sandbox_ = true; }
-
-#if defined(OS_WIN)
- void set_run_elevated() {
- disable_sandbox_ = true;
- run_elevated_ = true;
- }
-#endif // defined(OS_WIN)
-
- private:
- // Starts the utility process and binds the specified interface.
- void StartOnIOThread(const std::string& interface_name,
- mojo::ScopedMessagePipeHandle interface_pipe) {
- DCHECK_CURRENTLY_ON(BrowserThread::IO);
-
- utility_host_ = UtilityProcessHost::Create(nullptr, nullptr)->AsWeakPtr();
- utility_host_->SetName(process_name_);
-
- if (!exposed_directory_.empty())
- utility_host_->SetExposedDir(exposed_directory_);
-
- if (disable_sandbox_)
- utility_host_->SetSandboxType(service_manager::SANDBOX_TYPE_NO_SANDBOX);
-#if defined(OS_WIN)
- if (run_elevated_) {
- DCHECK(disable_sandbox_);
- utility_host_->SetSandboxType(
- service_manager::SANDBOX_TYPE_NO_SANDBOX_AND_ELEVATED_PRIVILEGES);
- }
-#endif // defined(OS_WIN)
-
- utility_host_->Start();
-
- utility_host_->BindInterface(interface_name, std::move(interface_pipe));
- }
-
- // Properties of the utility process.
- base::string16 process_name_;
- base::FilePath exposed_directory_;
- bool disable_sandbox_ = false;
-#if defined(OS_WIN)
- bool run_elevated_ = false;
-#endif // defined(OS_WIN)
-
- // Must only be accessed on the IO thread.
- base::WeakPtr<UtilityProcessHost> utility_host_;
-
- DISALLOW_COPY_AND_ASSIGN(Helper);
- };
-
- std::unique_ptr<Helper> helper_;
-
- // Called when a connection error happens or if the process didn't start.
- base::Closure error_callback_;
-
- mojo::InterfacePtr<MojoInterface> service_;
-
- // Enforce calling Start() before getting the service.
- bool start_called_ = false;
-
- // Checks that this class is always accessed from the same thread.
- SEQUENCE_CHECKER(sequence_checker_);
-
- DISALLOW_COPY_AND_ASSIGN(UtilityProcessMojoClient);
-};
-
-} // namespace content
-
-#endif // CONTENT_PUBLIC_BROWSER_UTILITY_PROCESS_MOJO_CLIENT_H_
diff --git a/chromium/content/public/browser/web_contents.h b/chromium/content/public/browser/web_contents.h
index 6e2186917ea..423362cb245 100644
--- a/chromium/content/public/browser/web_contents.h
+++ b/chromium/content/public/browser/web_contents.h
@@ -29,8 +29,9 @@
#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_ui.h"
#include "content/public/common/stop_find_action.h"
-#include "third_party/WebKit/public/common/frame/sandbox_flags.h"
+#include "third_party/blink/public/common/frame/sandbox_flags.h"
#include "third_party/skia/include/core/SkColor.h"
+#include "ui/accessibility/ax_modes.h"
#include "ui/accessibility/ax_tree_update.h"
#include "ui/base/window_open_disposition.h"
#include "ui/gfx/geometry/rect.h"
@@ -299,10 +300,11 @@ class WebContents : public PageNavigator,
virtual RenderWidgetHostView* GetTopLevelRenderWidgetHostView() = 0;
// Request a one-time snapshot of the accessibility tree without changing
- // the accessibility mode.
- using AXTreeSnapshotCallback = base::Callback<void(const ui::AXTreeUpdate&)>;
- virtual void RequestAXTreeSnapshot(
- const AXTreeSnapshotCallback& callback) = 0;
+ // the accessibility mode. |ax_mode| is the accessibility mode to use.
+ using AXTreeSnapshotCallback =
+ base::OnceCallback<void(const ui::AXTreeUpdate&)>;
+ virtual void RequestAXTreeSnapshot(AXTreeSnapshotCallback callback,
+ ui::AXMode ax_mode) = 0;
// Causes the current page to be closed, including running its onunload event
// handler.
@@ -321,7 +323,10 @@ class WebContents : public PageNavigator,
virtual WebUI* GetCommittedWebUI() const = 0;
// Allows overriding the user agent used for NavigationEntries it owns.
- virtual void SetUserAgentOverride(const std::string& override) = 0;
+ // |override_in_new_tabs| is set when we are overriding user agent for new
+ // tabs.
+ virtual void SetUserAgentOverride(const std::string& override,
+ bool override_in_new_tabs) = 0;
virtual const std::string& GetUserAgentOverride() const = 0;
// Set the accessibility mode so that accessibility events are forwarded
@@ -379,6 +384,17 @@ class WebContents : public PageNavigator,
// Returns the character encoding of the page.
virtual const std::string& GetEncoding() const = 0;
+ // Indicates that the tab was previously discarded.
+ // wasDiscarded is exposed on Document after discard, see:
+ // https://github.com/WICG/web-lifecycle
+ // When a tab is discarded, WebContents sets was_discarded on its
+ // root FrameTreeNode.
+ // In addition, when a child frame is created, this bit is passed on from
+ // parent to child.
+ // When a navigation request is created, was_discarded is passed on to the
+ // request and reset to false in FrameTreeNode.
+ virtual void SetWasDiscarded(bool was_discarded) = 0;
+
// Internal state ------------------------------------------------------------
// Indicates whether the WebContents is being captured (e.g., for screenshots
@@ -430,11 +446,10 @@ class WebContents : public PageNavigator,
virtual void WasShown() = 0;
virtual void WasHidden() = 0;
- // Invoked when the WebContents becomes occluded/unoccluded. An occluded
- // WebContents isn't painted on the screen, except in a window switching
- // feature (e.g. Alt-Tab).
+ // Invoked when the WebContents becomes occluded. An occluded WebContents
+ // isn't painted on the screen, except in a window switching feature (e.g.
+ // Alt-Tab).
virtual void WasOccluded() = 0;
- virtual void WasUnOccluded() = 0;
// Returns the visibility of the WebContents' view.
virtual Visibility GetVisibility() const = 0;
@@ -465,11 +480,18 @@ class WebContents : public PageNavigator,
// Invoked when visible security state changes.
virtual void DidChangeVisibleSecurityState() = 0;
+ // Notify this WebContents that the preferences have changed. This will send
+ // an IPC to all the renderer processes associated with this WebContents.
+ virtual void NotifyPreferencesChanged() = 0;
+
// Commands ------------------------------------------------------------------
// Stop any pending navigation.
virtual void Stop() = 0;
+ // Freeze the current page.
+ virtual void FreezePage() = 0;
+
// Creates a new WebContents with the same state as this one. The returned
// heap-allocated pointer is owned by the caller.
virtual WebContents* Clone() = 0;
@@ -596,9 +618,11 @@ class WebContents : public PageNavigator,
// provided, is used to make a request to the URL rather than using cache.
// Format of |headers| is a new line separated list of key value pairs:
// "<key1>: <value1>\r\n<key2>: <value2>".
- virtual void SaveFrameWithHeaders(const GURL& url,
- const Referrer& referrer,
- const std::string& headers) = 0;
+ virtual void SaveFrameWithHeaders(
+ const GURL& url,
+ const Referrer& referrer,
+ const std::string& headers,
+ const base::string16& suggested_filename) = 0;
// Generate an MHTML representation of the current page in the given file.
// If |use_binary_encoding| is specified, a Content-Transfer-Encoding value of
@@ -607,7 +631,7 @@ class WebContents : public PageNavigator,
// not the recommended encoding for shareable content.
virtual void GenerateMHTML(
const MHTMLGenerationParams& params,
- const base::Callback<void(int64_t /* size of the file */)>& callback) = 0;
+ base::OnceCallback<void(int64_t /* size of the file */)> callback) = 0;
// Returns the contents MIME type after a navigation.
virtual const std::string& GetContentsMimeType() const = 0;
@@ -626,10 +650,11 @@ class WebContents : public PageNavigator,
// WebContentsDelegate.
virtual void SystemDragEnded(RenderWidgetHost* source_rwh) = 0;
- // Notification the user has made a gesture while focus was on the
- // page. This is used to avoid uninitiated user downloads (aka carpet
- // bombing), see DownloadRequestLimiter for details.
- virtual void UserGestureDone() = 0;
+ // The user initiated navigation to this page (as opposed to a navigation that
+ // could have been triggered without user interaction). Used to avoid
+ // uninitiated user downloads (aka carpet bombing), see DownloadRequestLimiter
+ // for details.
+ virtual void NavigatedByUser() = 0;
// Indicates if this tab was explicitly closed by the user (control-w, close
// tab menu item...). This is false for actions that indirectly close the tab,
@@ -653,6 +678,10 @@ class WebContents : public PageNavigator,
// locked.
virtual bool GotResponseToLockMouseRequest(bool allowed) = 0;
+ // Called when the response to a keyboard mouse lock request has arrived.
+ // Returns false if the request is no longer valid, otherwise true.
+ virtual bool GotResponseToKeyboardLockRequest(bool allowed) = 0;
+
// Called when the user has selected a color in the color chooser.
virtual void DidChooseColorInColorChooser(SkColor color) = 0;
@@ -686,17 +715,16 @@ class WebContents : public PageNavigator,
// Returns the WakeLockContext accociated with this WebContents.
virtual device::mojom::WakeLockContext* GetWakeLockContext() = 0;
- typedef base::Callback<void(
- int, /* id */
- int, /* HTTP status code */
- const GURL&, /* image_url */
+ using ImageDownloadCallback = base::OnceCallback<void(
+ int, /* id */
+ int, /* HTTP status code */
+ const GURL&, /* image_url */
const std::vector<SkBitmap>&, /* bitmaps */
/* The sizes in pixel of the bitmaps before they were resized due to the
max bitmap size passed to DownloadImage(). Each entry in the bitmaps
vector corresponds to an entry in the sizes vector. If a bitmap was
resized, there should be a single returned bitmap. */
- const std::vector<gfx::Size>&)>
- ImageDownloadCallback;
+ const std::vector<gfx::Size>&)>;
// Sends a request to download the given image |url| and returns the unique
// id of the download request. When the download is finished, |callback| will
@@ -713,7 +741,7 @@ class WebContents : public PageNavigator,
bool is_favicon,
uint32_t max_bitmap_size,
bool bypass_cache,
- const ImageDownloadCallback& callback) = 0;
+ ImageDownloadCallback callback) = 0;
// Returns true if the WebContents is responsible for displaying a subframe
// in a different process from its parent page.
@@ -741,11 +769,11 @@ class WebContents : public PageNavigator,
// The callback invoked when the renderer responds to a request for the main
// frame document's manifest. The url will be empty if the document specifies
// no manifest, and the manifest will be empty if any other failures occurred.
- typedef base::Callback<void(const GURL&, const Manifest&)>
- GetManifestCallback;
+ using GetManifestCallback =
+ base::OnceCallback<void(const GURL&, const Manifest&)>;
// Requests the manifest URL and the Manifest of the main frame's document.
- virtual void GetManifest(const GetManifestCallback& callback) = 0;
+ virtual void GetManifest(GetManifestCallback callback) = 0;
// Returns whether the renderer is in fullscreen mode.
virtual bool IsFullscreenForCurrentTab() const = 0;
@@ -786,6 +814,20 @@ class WebContents : public PageNavigator,
// Tells the WebContents whether the context menu is showing.
virtual void SetShowingContextMenu(bool showing) = 0;
+ // Pause and unpause scheduled tasks in the page of blink. This function will
+ // suspend page loadings and all background processing like active javascript,
+ // and timers through |blink::Page::SetPaused|. If you want to resume the
+ // paused state, you have to call this function with |false| argument again.
+ // The function with |false| should be called after calling it with |true|. If
+ // not, assertion will happen.
+ //
+ // WARNING: This only pauses the activities in the particular page in the
+ // renderer process, but may indirectly block or break other pages when they
+ // wait for the common backend (e.g. storage) in the browser process.
+ // TODO(gyuyoung): https://crbug.com/822564 - Make this feature safer and fix
+ // bugs.
+ virtual void PausePageScheduledTasks(bool paused) = 0;
+
#if defined(OS_ANDROID)
CONTENT_EXPORT static WebContents* FromJavaWebContents(
const base::android::JavaRef<jobject>& jweb_contents_android);
diff --git a/chromium/content/public/browser/web_contents_binding_set.h b/chromium/content/public/browser/web_contents_binding_set.h
index fe92574340e..4ec3c211110 100644
--- a/chromium/content/public/browser/web_contents_binding_set.h
+++ b/chromium/content/public/browser/web_contents_binding_set.h
@@ -10,7 +10,6 @@
#include "base/callback.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "content/common/content_export.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
diff --git a/chromium/content/public/browser/web_contents_delegate.cc b/chromium/content/public/browser/web_contents_delegate.cc
index ed99743acac..a30f195a3a0 100644
--- a/chromium/content/public/browser/web_contents_delegate.cc
+++ b/chromium/content/public/browser/web_contents_delegate.cc
@@ -173,7 +173,7 @@ void WebContentsDelegate::RequestMediaAccessPermission(
}
bool WebContentsDelegate::CheckMediaAccessPermission(
- WebContents* web_contents,
+ RenderFrameHost* render_frame_host,
const GURL& security_origin,
MediaStreamType type) {
LOG(ERROR) << "WebContentsDelegate::CheckMediaAccessPermission: "
@@ -270,6 +270,9 @@ bool WebContentsDelegate::DoBrowserControlsShrinkBlinkSize() const {
}
void WebContentsDelegate::UpdatePictureInPictureSurfaceId(
- viz::SurfaceId surface_id) {}
+ const viz::SurfaceId& surface_id,
+ const gfx::Size& natural_size) {}
+
+void WebContentsDelegate::ExitPictureInPicture() {}
} // namespace content
diff --git a/chromium/content/public/browser/web_contents_delegate.h b/chromium/content/public/browser/web_contents_delegate.h
index 6f0c02b02dc..28cf408db3b 100644
--- a/chromium/content/public/browser/web_contents_delegate.h
+++ b/chromium/content/public/browser/web_contents_delegate.h
@@ -21,10 +21,10 @@
#include "content/public/common/media_stream_request.h"
#include "content/public/common/previews_state.h"
#include "content/public/common/window_container_type.mojom.h"
-#include "third_party/WebKit/public/mojom/color_chooser/color_chooser.mojom.h"
-#include "third_party/WebKit/public/platform/WebDisplayMode.h"
-#include "third_party/WebKit/public/platform/WebDragOperation.h"
-#include "third_party/WebKit/public/platform/WebSecurityStyle.h"
+#include "third_party/blink/public/mojom/color_chooser/color_chooser.mojom.h"
+#include "third_party/blink/public/platform/web_display_mode.h"
+#include "third_party/blink/public/platform/web_drag_operation.h"
+#include "third_party/blink/public/platform/web_security_style.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/base/window_open_disposition.h"
#include "ui/gfx/geometry/rect_f.h"
@@ -454,6 +454,14 @@ class CONTENT_EXPORT WebContentsDelegate {
// Notification that the page has lost the mouse lock.
virtual void LostMouseLock() {}
+ // Requests keyboard lock. Once the request is approved or rejected,
+ // GotResponseToKeyboardLockRequest() will be called on |web_contents|.
+ virtual void RequestKeyboardLock(WebContents* web_contents,
+ bool esc_key_locked) {}
+
+ // Notification that the keyboard lock request has been canceled.
+ virtual void CancelKeyboardLockRequest(WebContents* web_contents) {}
+
// Asks permission to use the camera and/or microphone. If permission is
// granted, a call should be made to |callback| with the devices. If the
// request is denied, a call should be made to |callback| with an empty list
@@ -467,7 +475,7 @@ class CONTENT_EXPORT WebContentsDelegate {
// Checks if we have permission to access the microphone or camera. Note that
// this does not query the user. |type| must be MEDIA_DEVICE_AUDIO_CAPTURE
// or MEDIA_DEVICE_VIDEO_CAPTURE.
- virtual bool CheckMediaAccessPermission(WebContents* web_contents,
+ virtual bool CheckMediaAccessPermission(RenderFrameHost* render_frame_host,
const GURL& security_origin,
MediaStreamType type);
@@ -556,8 +564,9 @@ class CONTENT_EXPORT WebContentsDelegate {
virtual bool DoBrowserControlsShrinkBlinkSize() const;
// Give WebContentsDelegates the opportunity to adjust the previews state.
- virtual void AdjustPreviewsStateForNavigation(PreviewsState* previews_state) {
- }
+ virtual void AdjustPreviewsStateForNavigation(
+ content::WebContents* web_contents,
+ PreviewsState* previews_state) {}
// Requests to print an out-of-process subframe for the specified WebContents.
// |rect| is the rectangular area where its content resides in its parent
@@ -572,8 +581,13 @@ class CONTENT_EXPORT WebContentsDelegate {
}
// Updates the Picture-in-Picture controller with the relevant viz::SurfaceId
- // of the video to be in Picture-in-Picture mode.
- virtual void UpdatePictureInPictureSurfaceId(viz::SurfaceId surface_id);
+ // and natural size of the video to be in Picture-in-Picture mode.
+ virtual void UpdatePictureInPictureSurfaceId(const viz::SurfaceId& surface_id,
+ const gfx::Size& natural_size);
+
+ // Updates the Picture-in-Picture controller with a signal that
+ // Picture-in-Picture mode has ended.
+ virtual void ExitPictureInPicture();
protected:
virtual ~WebContentsDelegate();
diff --git a/chromium/content/public/browser/web_contents_observer.h b/chromium/content/public/browser/web_contents_observer.h
index ca08f2f34b5..a0acf0a102d 100644
--- a/chromium/content/public/browser/web_contents_observer.h
+++ b/chromium/content/public/browser/web_contents_observer.h
@@ -16,11 +16,12 @@
#include "content/public/browser/reload_type.h"
#include "content/public/browser/visibility.h"
#include "content/public/common/frame_navigate_params.h"
+#include "content/public/common/resource_load_info.mojom.h"
#include "content/public/common/resource_type.h"
#include "ipc/ipc_listener.h"
#include "mojo/public/cpp/system/message_pipe.h"
#include "services/service_manager/public/cpp/bind_source_info.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/base/page_transition_types.h"
#include "ui/base/window_open_disposition.h"
@@ -255,13 +256,10 @@ class CONTENT_EXPORT WebContentsObserver : public IPC::Listener {
const std::string& mime_type,
ResourceType resource_type) {}
- // This method is invoked when a response has been received for a subresource
- // request.
- virtual void SubresourceResponseStarted(const GURL& url,
- const GURL& referrer,
- const std::string& method,
- ResourceType resource_type,
- const std::string& ip) {}
+ // This method is invoked when a resource has been loaded, successfully or
+ // not.
+ virtual void ResourceLoadComplete(
+ const mojom::ResourceLoadInfo& resource_load_info) {}
// This method is invoked when a new non-pending navigation entry is created.
// This corresponds to one NavigationController entry being created
diff --git a/chromium/content/public/browser/web_package_context.h b/chromium/content/public/browser/web_package_context.h
new file mode 100644
index 00000000000..94305626b3d
--- /dev/null
+++ b/chromium/content/public/browser/web_package_context.h
@@ -0,0 +1,31 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_PUBLIC_BROWSER_WEB_PACKAGE_CONTEXT_H_
+#define CONTENT_PUBLIC_BROWSER_WEB_PACKAGE_CONTEXT_H_
+
+#include "base/optional.h"
+#include "base/time/time.h"
+
+namespace content {
+
+// This class will represent the per-StoragePartition WebPackage related data.
+// Currently this class has only one method for testing.
+class WebPackageContext {
+ public:
+ // Changes the time which will be used to verify SignedHTTPExchange. This
+ // method is for testing. Must be called on IO thread.
+ // Need call this method again in the end of the test with nullopt time to
+ // reset the the verification time overriding.
+ virtual void SetSignedExchangeVerificationTimeForTesting(
+ base::Optional<base::Time> time) = 0;
+
+ protected:
+ WebPackageContext() {}
+ virtual ~WebPackageContext() {}
+};
+
+} // namespace content
+
+#endif // CONTENT_PUBLIC_BROWSER_WEB_PACKAGE_CONTEXT_H_
diff --git a/chromium/content/public/browser/web_ui.h b/chromium/content/public/browser/web_ui.h
index 76bd6a5f458..4d320806901 100644
--- a/chromium/content/public/browser/web_ui.h
+++ b/chromium/content/public/browser/web_ui.h
@@ -9,6 +9,7 @@
#include "base/callback.h"
#include "base/strings/string16.h"
+#include "base/strings/string_piece.h"
#include "content/common/content_export.h"
#include "ui/base/page_transition_types.h"
@@ -71,8 +72,8 @@ class CONTENT_EXPORT WebUI {
// Used by WebUIMessageHandlers. If the given message is already registered,
// the call has no effect.
- typedef base::Callback<void(const base::ListValue*)> MessageCallback;
- virtual void RegisterMessageCallback(const std::string& message,
+ using MessageCallback = base::RepeatingCallback<void(const base::ListValue*)>;
+ virtual void RegisterMessageCallback(base::StringPiece message,
const MessageCallback& callback) = 0;
// This is only needed if an embedder overrides handling of a WebUIMessage and
diff --git a/chromium/content/public/browser/web_ui_data_source.h b/chromium/content/public/browser/web_ui_data_source.h
index a1a6c97905b..4adac767d9c 100644
--- a/chromium/content/public/browser/web_ui_data_source.h
+++ b/chromium/content/public/browser/web_ui_data_source.h
@@ -13,6 +13,7 @@
#include "base/callback.h"
#include "base/strings/string16.h"
+#include "base/strings/string_piece.h"
#include "content/common/content_export.h"
namespace base {
@@ -44,33 +45,33 @@ class WebUIDataSource {
std::unique_ptr<base::DictionaryValue> update);
// Adds a string keyed to its name to our dictionary.
- virtual void AddString(const std::string& name,
+ virtual void AddString(base::StringPiece name,
const base::string16& value) = 0;
// Adds a string keyed to its name to our dictionary.
- virtual void AddString(const std::string& name, const std::string& value) = 0;
+ virtual void AddString(base::StringPiece name, const std::string& value) = 0;
// Adds a localized string with resource |ids| keyed to its name to our
// dictionary.
- virtual void AddLocalizedString(const std::string& name, int ids) = 0;
+ virtual void AddLocalizedString(base::StringPiece name, int ids) = 0;
// Add strings from |localized_strings| to our dictionary.
virtual void AddLocalizedStrings(
const base::DictionaryValue& localized_strings) = 0;
// Adds a boolean keyed to its name to our dictionary.
- virtual void AddBoolean(const std::string& name, bool value) = 0;
+ virtual void AddBoolean(base::StringPiece name, bool value) = 0;
// Adds a signed 32-bit integer keyed to its name to our dictionary. Larger
// integers may not be exactly representable in JavaScript. See
// MAX_SAFE_INTEGER in /v8/src/globals.h.
- virtual void AddInteger(const std::string& name, int32_t value) = 0;
+ virtual void AddInteger(base::StringPiece name, int32_t value) = 0;
// Sets the path which will return the JSON strings.
- virtual void SetJsonPath(const std::string& path) = 0;
+ virtual void SetJsonPath(base::StringPiece path) = 0;
// Adds a mapping between a path name and a resource to return.
- virtual void AddResourcePath(const std::string& path, int resource_id) = 0;
+ virtual void AddResourcePath(base::StringPiece path, int resource_id) = 0;
// Sets the resource to returned when no other paths match.
virtual void SetDefaultResource(int resource_id) = 0;
diff --git a/chromium/content/public/browser/web_ui_url_loader_factory.h b/chromium/content/public/browser/web_ui_url_loader_factory.h
new file mode 100644
index 00000000000..b26c467ca8b
--- /dev/null
+++ b/chromium/content/public/browser/web_ui_url_loader_factory.h
@@ -0,0 +1,27 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_PUBLIC_BROWSER_WEB_UI_URL_LOADER_FACTORY_H_
+#define CONTENT_PUBLIC_BROWSER_WEB_UI_URL_LOADER_FACTORY_H_
+
+#include <memory>
+#include <string>
+
+#include "base/containers/flat_set.h"
+#include "content/common/content_export.h"
+#include "services/network/public/mojom/url_loader_factory.mojom.h"
+
+namespace content {
+class RenderFrameHost;
+
+// Create a URLLoaderFactory for loading resources matching the specified
+// |scheme| and also from a "pseudo host" matching one in |allowed_hosts|.
+CONTENT_EXPORT std::unique_ptr<network::mojom::URLLoaderFactory>
+CreateWebUIURLLoader(RenderFrameHost* render_frame_host,
+ const std::string& scheme,
+ base::flat_set<std::string> allowed_hosts);
+
+} // namespace content
+
+#endif // CONTENT_PUBLIC_BROWSER_WEB_UI_URL_LOADER_FACTORY_H_
diff --git a/chromium/content/public/browser/webrtc_event_logger.cc b/chromium/content/public/browser/webrtc_event_logger.cc
new file mode 100644
index 00000000000..e61c7b20c4e
--- /dev/null
+++ b/chromium/content/public/browser/webrtc_event_logger.cc
@@ -0,0 +1,29 @@
+// Copyright (c) 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/public/browser/webrtc_event_logger.h"
+
+#include "base/logging.h"
+
+namespace content {
+
+WebRtcEventLogger* g_webrtc_event_logger = nullptr;
+
+WebRtcEventLogger* WebRtcEventLogger::Get() {
+ return g_webrtc_event_logger;
+}
+
+WebRtcEventLogger::WebRtcEventLogger() {
+ DCHECK(!g_webrtc_event_logger);
+ g_webrtc_event_logger = this;
+ // Checking that g_webrtc_event_logger was never set before, in a way that
+ // would not interfere with unit tests, is overkill.
+}
+
+WebRtcEventLogger::~WebRtcEventLogger() {
+ DCHECK_EQ(g_webrtc_event_logger, this);
+ g_webrtc_event_logger = nullptr;
+}
+
+} // namespace content
diff --git a/chromium/content/public/browser/webrtc_event_logger.h b/chromium/content/public/browser/webrtc_event_logger.h
new file mode 100644
index 00000000000..84d68719a82
--- /dev/null
+++ b/chromium/content/public/browser/webrtc_event_logger.h
@@ -0,0 +1,151 @@
+// Copyright (c) 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_PUBLIC_BROWSER_WEBRTC_EVENT_LOGGER_H_
+#define CONTENT_PUBLIC_BROWSER_WEBRTC_EVENT_LOGGER_H_
+
+#include <string>
+
+#include "base/callback.h"
+#include "base/files/file_path.h"
+#include "content/common/content_export.h"
+
+class WebRTCInternalsIntegrationBrowserTest;
+
+namespace content {
+
+class BrowserContext;
+
+// Interface for a logger of WebRTC events, which the embedding application may
+// subclass and instantiate. Only one instance may ever be created, and it must
+// live until the embedding application terminates.
+class CONTENT_EXPORT WebRtcEventLogger {
+ public:
+ // Get the only instance of WebRtcEventLogger, if one was instantiated, or
+ // nullptr otherwise.
+ static WebRtcEventLogger* Get();
+
+ // The embedding application may leak or destroy on shutdown. Either way,
+ // it may only be done on shutdown. It's up to the embedding application to
+ // only destroy at a time during shutdown when it is guaranteed that tasks
+ // posted earlier with a reference to the WebRtcEventLogger object, will
+ // not execute.
+ virtual ~WebRtcEventLogger();
+
+ // TODO(eladalon): Change from using BrowserContext to using Profile.
+ // https://crbug.com/775415
+
+ // Enables WebRTC event logging for a given BrowserContext:
+ // * Pending logs from previous sessions become eligible to be uploaded.
+ // * New logs for active peer connections *may* be recorded. (This does *not*
+ // start logging; it just makes it possible.)
+ // This function would typically be called during a BrowserContext's
+ // initialization.
+ // This function must not be called for an off-the-records BrowserContext.
+ // Local-logging is not associated with BrowserContexts, and is allowed even
+ // if EnableForBrowserContext is not called. That is, even for incognito mode.
+ virtual void EnableForBrowserContext(
+ const BrowserContext* browser_context,
+ base::OnceClosure reply = base::OnceClosure()) = 0;
+
+ // Disables WebRTC event logging for a given BrowserContext. New remote-bound
+ // WebRTC event logs will no longer be created for this BrowserContext.
+ // This would typically be called when a BrowserContext is destroyed. One must
+ // therefore be careful note to call any of BrowserContext's virtual methods.
+ // TODO(eladalon): After changing to a Profile-centered interface, change this
+ // to not even receive a pointer. https://crbug.com/775415
+ virtual void DisableForBrowserContext(
+ const BrowserContext* browser_context,
+ base::OnceClosure reply = base::OnceClosure()) = 0;
+
+ // Call this to let the logger know when a PeerConnection was created.
+ // |peer_connection_id| should be a non-empty, relatively short (i.e.
+ // inexpensive to store) identifier, by which the peer connection may later
+ // be identified. The identifier is assumed to be unique (within the
+ // renderer process).
+ // If a reply callback is given, it will be posted back to BrowserThread::UI,
+ // with true if and only if the operation was successful (failure is only
+ // possible if a peer connection with this exact key was previously added,
+ // but not removed).
+ virtual void PeerConnectionAdded(int render_process_id,
+ int lid,
+ const std::string& peer_connection_id,
+ base::OnceCallback<void(bool)> reply =
+ base::OnceCallback<void(bool)>()) = 0;
+
+ // Call this to let the logger know when a PeerConnection was closed.
+ // If a reply callback is given, it will be posted back to BrowserThread::UI,
+ // with true if and only if the operation was successful (failure is only
+ // possible if a peer connection with this key was not previously added,
+ // or if it has since already been removed).
+ virtual void PeerConnectionRemoved(int render_process_id,
+ int lid,
+ base::OnceCallback<void(bool)> reply =
+ base::OnceCallback<void(bool)>()) = 0;
+
+ // Call this to let the logger know when a PeerConnection was stopped.
+ // Closing of a peer connection is an irreversible action. Its distinction
+ // from the removal event is that it may happen before the peer connection has
+ // been garbage collected.
+ virtual void PeerConnectionStopped(int render_process_id,
+ int lid,
+ base::OnceCallback<void(bool)> reply =
+ base::OnceCallback<void(bool)>()) = 0;
+
+ // Enable local logging of WebRTC events.
+ // Local logging is distinguished from remote logging, in that local logs are
+ // kept in response to explicit user input, are saved to a specific location,
+ // and are never removed by the application.
+ // If a reply callback is given, it will be posted back to BrowserThread::UI,
+ // with true if and only if local logging was *not* already on.
+ // Note #1: An illegal file path, or one where we don't have the necessary
+ // permissions, does not cause a |false| reply, since even when we have the
+ // permissions, we're not guaranteed to keep them, and some files might be
+ // legal while others aren't due to additional restrictions (number of files,
+ // length of filename, etc.).
+ // Note #2: If the number of currently active peer connections exceeds the
+ // maximum number of local log files, there is no guarantee about which PCs
+ // will get a local log file associated (specifically, we do *not* guarantee
+ // it would be either the oldest or the newest).
+ virtual void EnableLocalLogging(const base::FilePath& base_path,
+ base::OnceCallback<void(bool)> reply =
+ base::OnceCallback<void(bool)>()) = 0;
+
+ // Disable local logging of WebRTC events.
+ // Any active local logs are stopped. Peer connections added after this call
+ // will not get a local log associated with them (unless local logging is
+ // once again enabled).
+ virtual void DisableLocalLogging(base::OnceCallback<void(bool)> reply =
+ base::OnceCallback<void(bool)>()) = 0;
+
+ // Called when a new log fragment is sent from the renderer. This will
+ // potentially be written to a local WebRTC event log, a remote-bound log
+ // intended for upload, or both.
+ // If a reply callback is given, it will be posted back to BrowserThread::UI
+ // with a pair of bools, the first bool associated with local logging and the
+ // second bool associated with remote-bound logging. Each bool assumes the
+ // value true if and only if the message was written in its entirety into
+ // a local/remote-bound log file.
+ virtual void OnWebRtcEventLogWrite(
+ int render_process_id,
+ int lid,
+ const std::string& message,
+ base::OnceCallback<void(std::pair<bool, bool>)> reply =
+ base::OnceCallback<void(std::pair<bool, bool>)>()) = 0;
+
+ protected:
+ friend WebRTCInternalsIntegrationBrowserTest; // (PostNullTaskForTesting)
+
+ WebRtcEventLogger();
+
+ // Allows tests to synchronize with internal task queues (if such exist in
+ // the subclass). This allows tests to only examine products (such as log
+ // files) at a time when, if the program is behaving as expected, they would
+ // be guaranteed to be ready.
+ virtual void PostNullTaskForTesting(base::OnceClosure reply) = 0;
+};
+
+} // namespace content
+
+#endif // CONTENT_PUBLIC_BROWSER_WEBRTC_EVENT_LOGGER_H_
diff --git a/chromium/content/public/browser/webrtc_log.h b/chromium/content/public/browser/webrtc_log.h
index 16fefc7f7ba..0cc7ab8cc05 100644
--- a/chromium/content/public/browser/webrtc_log.h
+++ b/chromium/content/public/browser/webrtc_log.h
@@ -10,7 +10,7 @@
#include "base/callback_forward.h"
#include "base/macros.h"
#include "content/common/content_export.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#if !BUILDFLAG(ENABLE_WEBRTC)
#error "WebRTC not enabled."
diff --git a/chromium/content/public/child/BUILD.gn b/chromium/content/public/child/BUILD.gn
index 25529f6fdfb..296eca953d4 100644
--- a/chromium/content/public/child/BUILD.gn
+++ b/chromium/content/public/child/BUILD.gn
@@ -3,7 +3,7 @@
# found in the LICENSE file.
import("//build/config/jumbo.gni")
-import("//ppapi/features/features.gni")
+import("//ppapi/buildflags/buildflags.gni")
# See //content/BUILD.gn for how this works.
group("child") {
diff --git a/chromium/content/public/child/child_thread.h b/chromium/content/public/child/child_thread.h
index 17309b2bf2c..c094e402c63 100644
--- a/chromium/content/public/child/child_thread.h
+++ b/chromium/content/public/child/child_thread.h
@@ -14,6 +14,8 @@
#if defined(OS_WIN)
#include <windows.h>
+#elif defined(OS_MACOSX)
+#include "mojo/public/cpp/system/buffer.h"
#endif
namespace base {
@@ -39,15 +41,6 @@ class CONTENT_EXPORT ChildThread : public IPC::Sender {
~ChildThread() override {}
-#if defined(OS_WIN)
- // Request that the given font be loaded by the browser so it's cached by the
- // OS. Please see ChildProcessHost::PreCacheFont for details.
- virtual void PreCacheFont(const LOGFONT& log_font) = 0;
-
- // Release cached font.
- virtual void ReleaseCachedFonts() = 0;
-#endif
-
// Sends over a base::UserMetricsAction to be recorded by user metrics as
// an action. Once a new user metric is added, run
// tools/metrics/actions/extract_actions.py
@@ -80,6 +73,21 @@ class CONTENT_EXPORT ChildThread : public IPC::Sender {
// Tells the child process that a field trial was activated.
virtual void SetFieldTrialGroup(const std::string& trial_name,
const std::string& group_name) = 0;
+
+#if defined(OS_WIN)
+ // Request that the given font be loaded by the browser so it's cached by the
+ // OS. Please see ChildProcessHost::PreCacheFont for details.
+ virtual void PreCacheFont(const LOGFONT& log_font) = 0;
+
+ // Release cached font.
+ virtual void ReleaseCachedFonts() = 0;
+#elif defined(OS_MACOSX)
+ // Load specified font into shared memory.
+ virtual bool LoadFont(const base::string16& font_name,
+ float font_point_size,
+ mojo::ScopedSharedBufferHandle* out_font_data,
+ uint32_t* out_font_id) = 0;
+#endif
};
} // namespace content
diff --git a/chromium/content/public/common/BUILD.gn b/chromium/content/public/common/BUILD.gn
index bd1681124ed..67588799001 100644
--- a/chromium/content/public/common/BUILD.gn
+++ b/chromium/content/public/common/BUILD.gn
@@ -10,7 +10,7 @@ import("//build/config/ui.gni")
import("//content/public/common/zygote_features.gni")
import("//media/media_options.gni")
import("//mojo/public/tools/bindings/mojom.gni")
-import("//ppapi/features/features.gni")
+import("//ppapi/buildflags/buildflags.gni")
import("//third_party/webrtc/webrtc.gni")
# See //content/BUILD.gn for how this works.
@@ -82,7 +82,7 @@ source_set("static_switches") {
# Deps required by the above headers.
deps = [
- "//media:media_features",
+ "//media:media_buildflags",
]
}
@@ -158,6 +158,8 @@ jumbo_source_set("common_sources") {
"main_function_params.h",
"manifest.cc",
"manifest.h",
+ "manifest_share_target_util.cc",
+ "manifest_share_target_util.h",
"manifest_util.cc",
"manifest_util.h",
"media_metadata.cc",
@@ -215,8 +217,6 @@ jumbo_source_set("common_sources") {
"screen_orientation_values.h",
"send_zygote_child_ping_linux.h",
"service_manager_connection.h",
- "shared_url_loader_factory.cc",
- "shared_url_loader_factory.h",
"simple_connection_filter.cc",
"simple_connection_filter.h",
"socket_permission_request.h",
@@ -237,6 +237,8 @@ jumbo_source_set("common_sources") {
"use_zoom_for_dsf_policy.cc",
"use_zoom_for_dsf_policy.h",
"user_agent.h",
+ "weak_wrapper_shared_url_loader_factory.cc",
+ "weak_wrapper_shared_url_loader_factory.h",
"web_preferences.cc",
"web_preferences.h",
"webplugininfo.cc",
@@ -255,10 +257,11 @@ jumbo_source_set("common_sources") {
public_deps = [
":interfaces",
":service_names",
+ ":zygote_buildflags",
"//content/common",
"//ipc",
"//media/capture:capture_base",
- "//mojo/edk/system",
+ "//mojo/edk",
"//mojo/public/cpp/bindings",
"//net",
"//services/network:network_service",
@@ -266,28 +269,27 @@ jumbo_source_set("common_sources") {
"//services/service_manager/embedder",
"//services/service_manager/public/cpp",
"//services/service_manager/public/mojom",
- "//third_party/WebKit/public:blink_headers",
- "//third_party/WebKit/public:mojo_bindings",
+ "//third_party/blink/public:blink_headers",
+ "//third_party/blink/public:mojo_bindings",
"//ui/accessibility",
"//ui/surface",
"//url/ipc:url_ipc",
]
deps = [
":content_descriptor_keys",
- ":zygote_features",
# This looks needless as we have //content/common in public_deps, but it's
# needed because of allow_circular_includes_from.
"//content/common:mojo_bindings",
"//media",
"//mojo/common",
+ "//ppapi/buildflags",
"//ppapi/c",
- "//ppapi/features",
"//services/network/public/cpp",
"//services/service_manager/public/cpp",
"//skia",
"//storage/common",
- "//third_party/WebKit/public/common",
+ "//third_party/blink/public/common",
"//third_party/icu",
"//ui/accessibility",
"//ui/base",
@@ -332,16 +334,16 @@ jumbo_source_set("common_sources") {
}
}
-buildflag_header("features") {
- header = "features.h"
+buildflag_header("buildflags") {
+ header = "buildflags.h"
flags = [ "RTC_USE_H264=$rtc_use_h264" ]
}
source_set("feature_h264_with_openh264_ffmpeg") {
deps = [
- ":features",
+ ":buildflags",
"//base",
- "//media:media_features",
+ "//media:media_buildflags",
]
sources = [
"feature_h264_with_openh264_ffmpeg.cc",
@@ -349,8 +351,8 @@ source_set("feature_h264_with_openh264_ffmpeg") {
]
}
-buildflag_header("zygote_features") {
- header = "zygote_features.h"
+buildflag_header("zygote_buildflags") {
+ header = "zygote_buildflags.h"
flags = [ "USE_ZYGOTE_HANDLE=$use_zygote_handle" ]
}
@@ -361,13 +363,22 @@ mojom("interfaces") {
"//content/common/*",
"//chrome/common:mojo_bindings",
"//chrome/common:mojo_bindings_blink",
+ "//extensions/common:mojo",
+ "//extensions/common:mojo_blink",
]
+ # imports vs deps check is disabled for this target to work around
+ # windows multiple definitions linker error caused by having
+ # both a direct and an indirect dependency on the same target
+ skip_deps_check = true
+
sources = [
"appcache_info.mojom",
"fullscreen_video_element.mojom",
"push_messaging_status.mojom",
+ "resource_load_info.mojom",
"resource_usage_reporter.mojom",
+ "transferrable_url_loader.mojom",
"webplugininfo.mojom",
"window_container_type.mojom",
]
diff --git a/chromium/content/public/common/appcache_info.h b/chromium/content/public/common/appcache_info.h
index eb3ecb92dd8..ae8df73180b 100644
--- a/chromium/content/public/common/appcache_info.h
+++ b/chromium/content/public/common/appcache_info.h
@@ -12,7 +12,7 @@
#include "base/time/time.h"
#include "content/common/content_export.h"
#include "content/public/common/appcache_info.mojom.h"
-#include "third_party/WebKit/public/platform/WebApplicationCacheHost.h"
+#include "third_party/blink/public/platform/web_application_cache_host.h"
#include "url/gurl.h"
namespace content {
diff --git a/chromium/content/public/common/appcache_info.mojom b/chromium/content/public/common/appcache_info.mojom
index 1226f3729eb..21d04ecad5e 100644
--- a/chromium/content/public/common/appcache_info.mojom
+++ b/chromium/content/public/common/appcache_info.mojom
@@ -4,7 +4,7 @@
module content.mojom;
-import "mojo/common/time.mojom";
+import "mojo/public/mojom/base/time.mojom";
import "url/mojom/url.mojom";
const int64 kAppCacheNoCacheId = 0;
@@ -22,9 +22,9 @@ enum AppCacheStatus {
struct AppCacheInfo {
url.mojom.Url manifest_url;
- mojo.common.mojom.Time creation_time;
- mojo.common.mojom.Time last_update_time;
- mojo.common.mojom.Time last_access_time;
+ mojo_base.mojom.Time creation_time;
+ mojo_base.mojom.Time last_update_time;
+ mojo_base.mojom.Time last_access_time;
int64 cache_id;
int64 group_id;
AppCacheStatus status;
diff --git a/chromium/content/public/common/browser_side_navigation_policy.cc b/chromium/content/public/common/browser_side_navigation_policy.cc
index defb5852aa6..c71206145eb 100644
--- a/chromium/content/public/common/browser_side_navigation_policy.cc
+++ b/chromium/content/public/common/browser_side_navigation_policy.cc
@@ -7,6 +7,7 @@
#include "base/command_line.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
+#include "services/network/public/cpp/features.h"
namespace content {
@@ -23,7 +24,10 @@ bool IsNavigationMojoResponseEnabled() {
return false;
return base::FeatureList::IsEnabled(features::kNavigationMojoResponse) ||
- base::FeatureList::IsEnabled(features::kSignedHTTPExchange);
+ base::FeatureList::IsEnabled(
+ features::kServiceWorkerServicification) ||
+ base::FeatureList::IsEnabled(features::kSignedHTTPExchange) ||
+ base::FeatureList::IsEnabled(network::features::kNetworkService);
}
} // namespace content
diff --git a/chromium/content/public/common/common_param_traits_macros.h b/chromium/content/public/common/common_param_traits_macros.h
index 6b1fa1ceb55..3b72878d946 100644
--- a/chromium/content/public/common/common_param_traits_macros.h
+++ b/chromium/content/public/common/common_param_traits_macros.h
@@ -16,15 +16,15 @@
#include "ipc/ipc_message_macros.h"
#include "net/base/network_change_notifier.h"
#include "services/network/public/cpp/network_param_ipc_traits.h"
-#include "third_party/WebKit/public/platform/WebHistoryScrollRestorationType.h"
-#include "third_party/WebKit/public/platform/WebPoint.h"
-#include "third_party/WebKit/public/platform/WebRect.h"
-#include "third_party/WebKit/public/platform/WebReferrerPolicy.h"
-#include "third_party/WebKit/public/platform/WebSecurityStyle.h"
-#include "third_party/WebKit/public/platform/WebURLRequest.h"
-#include "third_party/WebKit/public/platform/modules/permissions/permission_status.mojom.h"
-#include "third_party/WebKit/public/web/WebFrameSerializerCacheControlPolicy.h"
-#include "third_party/WebKit/public/web/window_features.mojom.h"
+#include "third_party/blink/public/platform/modules/permissions/permission_status.mojom.h"
+#include "third_party/blink/public/platform/web_history_scroll_restoration_type.h"
+#include "third_party/blink/public/platform/web_point.h"
+#include "third_party/blink/public/platform/web_rect.h"
+#include "third_party/blink/public/platform/web_referrer_policy.h"
+#include "third_party/blink/public/platform/web_security_style.h"
+#include "third_party/blink/public/platform/web_url_request.h"
+#include "third_party/blink/public/web/web_frame_serializer_cache_control_policy.h"
+#include "third_party/blink/public/web/window_features.mojom.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/accessibility/ax_relative_bounds.h"
#include "ui/accessibility/ax_tree_update.h"
@@ -130,6 +130,7 @@ IPC_STRUCT_TRAITS_BEGIN(content::WebPreferences)
IPC_STRUCT_TRAITS_MEMBER(application_cache_enabled)
IPC_STRUCT_TRAITS_MEMBER(tabs_to_links)
IPC_STRUCT_TRAITS_MEMBER(history_entry_requires_user_gesture)
+ IPC_STRUCT_TRAITS_MEMBER(disable_pushstate_throttle)
IPC_STRUCT_TRAITS_MEMBER(hyperlink_auditing_enabled)
IPC_STRUCT_TRAITS_MEMBER(allow_universal_access_from_file_urls)
IPC_STRUCT_TRAITS_MEMBER(allow_file_access_from_file_urls)
@@ -180,6 +181,7 @@ IPC_STRUCT_TRAITS_BEGIN(content::WebPreferences)
IPC_STRUCT_TRAITS_MEMBER(viewport_meta_enabled)
IPC_STRUCT_TRAITS_MEMBER(shrinks_viewport_contents_to_fit)
IPC_STRUCT_TRAITS_MEMBER(viewport_style)
+ IPC_STRUCT_TRAITS_MEMBER(smooth_scroll_for_find_enabled)
IPC_STRUCT_TRAITS_MEMBER(main_frame_resizes_are_orientation_changes)
IPC_STRUCT_TRAITS_MEMBER(initialize_at_minimum_page_scale)
IPC_STRUCT_TRAITS_MEMBER(smart_insert_delete_enabled)
@@ -199,7 +201,6 @@ IPC_STRUCT_TRAITS_BEGIN(content::WebPreferences)
IPC_STRUCT_TRAITS_MEMBER(force_enable_zoom)
IPC_STRUCT_TRAITS_MEMBER(fullscreen_supported)
IPC_STRUCT_TRAITS_MEMBER(double_tap_to_zoom_enabled)
- IPC_STRUCT_TRAITS_MEMBER(picture_in_picture_enabled)
IPC_STRUCT_TRAITS_MEMBER(media_playback_gesture_whitelist_scope)
IPC_STRUCT_TRAITS_MEMBER(default_video_poster_url)
IPC_STRUCT_TRAITS_MEMBER(support_deprecated_target_density_dpi)
@@ -214,7 +215,7 @@ IPC_STRUCT_TRAITS_BEGIN(content::WebPreferences)
IPC_STRUCT_TRAITS_MEMBER(clobber_user_agent_initial_scale_quirk)
IPC_STRUCT_TRAITS_MEMBER(ignore_main_frame_overflow_hidden_quirk)
IPC_STRUCT_TRAITS_MEMBER(report_screen_size_in_physical_pixels_quirk)
- IPC_STRUCT_TRAITS_MEMBER(resue_global_for_unowned_main_frame)
+ IPC_STRUCT_TRAITS_MEMBER(reuse_global_for_unowned_main_frame)
IPC_STRUCT_TRAITS_MEMBER(spellcheck_enabled_by_default)
IPC_STRUCT_TRAITS_MEMBER(video_fullscreen_orientation_lock_enabled)
IPC_STRUCT_TRAITS_MEMBER(video_rotate_to_fullscreen_enabled)
@@ -234,6 +235,7 @@ IPC_STRUCT_TRAITS_BEGIN(content::WebPreferences)
IPC_STRUCT_TRAITS_MEMBER(do_not_update_selection_on_mutating_selection_range)
IPC_STRUCT_TRAITS_MEMBER(autoplay_policy)
IPC_STRUCT_TRAITS_MEMBER(low_priority_iframes_threshold)
+ IPC_STRUCT_TRAITS_MEMBER(picture_in_picture_enabled)
IPC_STRUCT_TRAITS_END()
IPC_STRUCT_TRAITS_BEGIN(blink::mojom::WindowFeatures)
@@ -251,23 +253,23 @@ IPC_STRUCT_TRAITS_BEGIN(blink::mojom::WindowFeatures)
IPC_STRUCT_TRAITS_MEMBER(scrollbars_visible)
IPC_STRUCT_TRAITS_END()
-IPC_ENUM_TRAITS_MAX_VALUE(ax::mojom::Event, ax::mojom::Event::kLast)
-IPC_ENUM_TRAITS_MAX_VALUE(ax::mojom::Role, ax::mojom::Role::kLast)
+IPC_ENUM_TRAITS_MAX_VALUE(ax::mojom::Event, ax::mojom::Event::kMaxValue)
+IPC_ENUM_TRAITS_MAX_VALUE(ax::mojom::Role, ax::mojom::Role::kMaxValue)
IPC_ENUM_TRAITS_MAX_VALUE(ax::mojom::BoolAttribute,
- ax::mojom::BoolAttribute::kLast)
+ ax::mojom::BoolAttribute::kMaxValue)
IPC_ENUM_TRAITS_MAX_VALUE(ax::mojom::FloatAttribute,
- ax::mojom::FloatAttribute::kLast)
+ ax::mojom::FloatAttribute::kMaxValue)
IPC_ENUM_TRAITS_MAX_VALUE(ax::mojom::IntAttribute,
- ax::mojom::IntAttribute::kLast)
+ ax::mojom::IntAttribute::kMaxValue)
IPC_ENUM_TRAITS_MAX_VALUE(ax::mojom::IntListAttribute,
- ax::mojom::IntListAttribute::kLast)
+ ax::mojom::IntListAttribute::kMaxValue)
IPC_ENUM_TRAITS_MAX_VALUE(ax::mojom::StringListAttribute,
- ax::mojom::StringListAttribute::kLast)
+ ax::mojom::StringListAttribute::kMaxValue)
IPC_ENUM_TRAITS_MAX_VALUE(ax::mojom::StringAttribute,
- ax::mojom::StringAttribute::kLast)
+ ax::mojom::StringAttribute::kMaxValue)
IPC_ENUM_TRAITS_MAX_VALUE(ax::mojom::TextAffinity,
- ax::mojom::TextAffinity::kLast)
-IPC_ENUM_TRAITS_MAX_VALUE(ax::mojom::EventFrom, ax::mojom::EventFrom::kLast)
+ ax::mojom::TextAffinity::kMaxValue)
+IPC_ENUM_TRAITS_MAX_VALUE(ax::mojom::EventFrom, ax::mojom::EventFrom::kMaxValue)
IPC_STRUCT_TRAITS_BEGIN(ui::AXRelativeBounds)
IPC_STRUCT_TRAITS_MEMBER(offset_container_id)
diff --git a/chromium/content/public/common/content_features.cc b/chromium/content/public/common/content_features.cc
index c9758711efb..50c3617648a 100644
--- a/chromium/content/public/common/content_features.cc
+++ b/chromium/content/public/common/content_features.cc
@@ -36,27 +36,30 @@ const base::Feature kAsmJsToWebAssembly{"AsmJsToWebAssembly",
const base::Feature kAsyncWheelEvents{"AsyncWheelEvents",
base::FEATURE_ENABLED_BY_DEFAULT};
+// Allows swipe left/right from touchpad change browser navigation. Currently
+// only enabled by default on CrOS.
+const base::Feature kTouchpadOverscrollHistoryNavigation {
+ "TouchpadOverscrollHistoryNavigation",
+#if defined(OS_CHROMEOS)
+ base::FEATURE_ENABLED_BY_DEFAULT
+#else
+ base::FEATURE_DISABLED_BY_DEFAULT
+#endif
+};
+
// Block subresource requests whose URLs contain embedded credentials (e.g.
// `https://user:pass@example.com/resource`).
const base::Feature kBlockCredentialedSubresources{
"BlockCredentialedSubresources", base::FEATURE_ENABLED_BY_DEFAULT};
-// Puts save-data header in the holdback mode. This disables sending of
-// save-data header to origins, and to the renderer processes within Chrome.
-const base::Feature kDataSaverHoldback{"DataSaverHoldback",
- base::FEATURE_DISABLED_BY_DEFAULT};
-
// Enables brotli "Accept-Encoding" advertising and "Content-Encoding" support.
// Brotli format specification: http://www.ietf.org/id/draft-alakuijala-brotli
const base::Feature kBrotliEncoding{"brotli-encoding",
base::FEATURE_ENABLED_BY_DEFAULT};
-// Browser side navigation (aka PlzNavigate) is using blob URLs to deliver
-// the body of the main resource to the renderer process. When enabled, the
-// NavigationMojoResponse feature replaces this mechanism by a Mojo DataPipe.
-// Design doc: https://goo.gl/Rrrc7n.
-const base::Feature kNavigationMojoResponse{"NavigationMojoResponse",
- base::FEATURE_ENABLED_BY_DEFAULT};
+// Enables code caching for inline scripts.
+const base::Feature kCacheInlineScriptCode{"CacheInlineScriptCode",
+ base::FEATURE_DISABLED_BY_DEFAULT};
// If Canvas2D Image Chromium is allowed, this feature controls whether it is
// enabled.
@@ -74,6 +77,10 @@ const base::Feature kCanvas2DImageChromium {
const base::Feature kCheckerImaging{"CheckerImaging",
base::FEATURE_DISABLED_BY_DEFAULT};
+// Enables code caching after executing the script.
+const base::Feature kCodeCacheAfterExecute{"CodeCacheAfterExecute",
+ base::FEATURE_ENABLED_BY_DEFAULT};
+
// Enables the compositing of fixed position content that is opaque and can
// preserve LCD text.
const base::Feature kCompositeOpaqueFixedPosition{
@@ -84,9 +91,6 @@ const base::Feature kCompositeOpaqueFixedPosition{
const base::Feature kCompositeOpaqueScrollers{"CompositeOpaqueScrollers",
base::FEATURE_ENABLED_BY_DEFAULT};
-const base::Feature kCompositorImageAnimation{"CompositorImageAnimation",
- base::FEATURE_ENABLED_BY_DEFAULT};
-
// Enables handling touch events in compositor using impl side touch action
// knowledge.
const base::Feature kCompositorTouchAction{"CompositorTouchAction",
@@ -102,15 +106,20 @@ const base::Feature kCrossSiteDocumentBlockingAlways{
const base::Feature kCrossSiteDocumentBlockingIfIsolating{
"CrossSiteDocumentBlockingIfIsolating", base::FEATURE_ENABLED_BY_DEFAULT};
-// Enables exposing back/forward mouse buttons to the renderer and the web.
-const base::Feature kExtendedMouseButtons{"ExtendedMouseButtons",
- base::FEATURE_DISABLED_BY_DEFAULT};
+// Puts save-data header in the holdback mode. This disables sending of
+// save-data header to origins, and to the renderer processes within Chrome.
+const base::Feature kDataSaverHoldback{"DataSaverHoldback",
+ base::FEATURE_DISABLED_BY_DEFAULT};
// Throttle tasks in Blink background timer queues based on CPU budgets
// for the background tab. Bug: https://crbug.com/639852.
const base::Feature kExpensiveBackgroundTimerThrottling{
"ExpensiveBackgroundTimerThrottling", base::FEATURE_ENABLED_BY_DEFAULT};
+// Enables exposing back/forward mouse buttons to the renderer and the web.
+const base::Feature kExtendedMouseButtons{"ExtendedMouseButtons",
+ base::FEATURE_ENABLED_BY_DEFAULT};
+
// Enables a blink::FontCache optimization that reuses a font to serve different
// size of font.
const base::Feature kFontCacheScaling{"FontCacheScaling",
@@ -126,6 +135,11 @@ const base::Feature kFramebustingNeedsSameOriginOrUserGesture{
// Enables extended Gamepad API features like motion tracking and haptics.
const base::Feature kGamepadExtensions{"GamepadExtensions",
base::FEATURE_DISABLED_BY_DEFAULT};
+// When WebXR Device API is enabled, exposes VR controllers as Gamepads and
+// enables additional Gamepad attributes for use with WebXR Device API. Each
+// XRInputSource will have a corresponding Gamepad instance.
+const base::Feature kWebXrGamepadSupport{"WebXRGamepadSupport",
+ base::FEATURE_DISABLED_BY_DEFAULT};
// Causes the implementations of guests (inner WebContents) to use
// out-of-process iframes.
@@ -136,23 +150,42 @@ const base::Feature kGuestViewCrossProcessFrames{
const base::Feature kHeapCompaction{"HeapCompaction",
base::FEATURE_DISABLED_BY_DEFAULT};
+// Enables/disables the Image Capture API.
+const base::Feature kImageCaptureAPI{"ImageCaptureAPI",
+ base::FEATURE_ENABLED_BY_DEFAULT};
+
+// Alternative to switches::kIsolateOrigins, for turning on origin isolation.
+// List of origins to isolate has to be specified via
+// kIsolateOriginsFieldTrialParamName.
+const base::Feature kIsolateOrigins{"IsolateOrigins",
+ base::FEATURE_DISABLED_BY_DEFAULT};
+const char kIsolateOriginsFieldTrialParamName[] = "OriginsList";
+
// Enables an API which allows websites to capture reserved keys in fullscreen.
// Defined by w3c here: https://w3c.github.io/keyboard-lock/
const base::Feature kKeyboardLockAPI{"KeyboardLockAPI",
base::FEATURE_DISABLED_BY_DEFAULT};
+const base::Feature kLazyFrameLoading{"LazyFrameLoading",
+ base::FEATURE_DISABLED_BY_DEFAULT};
+
// Enable lazy initialization of the media controls.
const base::Feature kLazyInitializeMediaControls{
"LazyInitializeMediaControls", base::FEATURE_ENABLED_BY_DEFAULT};
// Enables lazily parsing css properties for performance.
const base::Feature kLazyParseCSS{"LazyParseCSS",
- base::FEATURE_DISABLED_BY_DEFAULT};
+ base::FEATURE_ENABLED_BY_DEFAULT};
// Enables lowering the priority of the resources in iframes.
const base::Feature kLowPriorityIframes{"LowPriorityIframes",
base::FEATURE_DISABLED_BY_DEFAULT};
+// An experiment forcing events to be non-blocking when the main thread is
+// deemed unresponsive. See https://crbug.com/599609.
+const base::Feature kMainThreadBusyScrollIntervention{
+ "MainThreadBusyScrollIntervention", base::FEATURE_DISABLED_BY_DEFAULT};
+
// If this feature is enabled, media-device enumerations use a cache that is
// invalidated upon notifications sent by base::SystemMonitor. If disabled, the
// cache is considered invalid on every enumeration request.
@@ -172,17 +205,13 @@ const base::Feature kMediaDevicesSystemMonitorCache {
const base::Feature kMemoryCoordinator{"MemoryCoordinator",
base::FEATURE_DISABLED_BY_DEFAULT};
-// If the network service is enabled, runs it in process.
-const base::Feature kNetworkServiceInProcess{"NetworkServiceInProcess",
- base::FEATURE_DISABLED_BY_DEFAULT};
+// ES6 Modules dynamic imports.
+const base::Feature kModuleScriptsDynamicImport{
+ "ModuleScriptsDynamicImport", base::FEATURE_ENABLED_BY_DEFAULT};
-// Kill switch for Web Notification content images.
-const base::Feature kNotificationContentImage{"NotificationContentImage",
- base::FEATURE_ENABLED_BY_DEFAULT};
-// An experiment forcing events to be non-blocking when the main thread is
-// deemed unresponsive. See crbug.com/599609.
-const base::Feature kMainThreadBusyScrollIntervention{
- "MainThreadBusyScrollIntervention", base::FEATURE_DISABLED_BY_DEFAULT};
+// ES6 Modules import.meta.url.
+const base::Feature kModuleScriptsImportMetaUrl{
+ "ModuleScriptsImportMetaUrl", base::FEATURE_ENABLED_BY_DEFAULT};
// Mojo-based Input Event routing.
const base::Feature kMojoInputMessages{"MojoInputMessages",
@@ -202,18 +231,29 @@ const base::Feature kMojoVideoCapture {
#endif
};
-// ES6 Modules dynamic imports.
-const base::Feature kModuleScriptsDynamicImport{
- "ModuleScriptsDynamicImport", base::FEATURE_ENABLED_BY_DEFAULT};
+// Browser side navigation (aka PlzNavigate) is using blob URLs to deliver
+// the body of the main resource to the renderer process. When enabled, the
+// NavigationMojoResponse feature replaces this mechanism by a Mojo DataPipe.
+// Design doc: https://goo.gl/Rrrc7n.
+const base::Feature kNavigationMojoResponse{"NavigationMojoResponse",
+ base::FEATURE_ENABLED_BY_DEFAULT};
-// ES6 Modules import.meta.url.
-const base::Feature kModuleScriptsImportMetaUrl{
- "ModuleScriptsImportMetaUrl", base::FEATURE_ENABLED_BY_DEFAULT};
+// If the network service is enabled, runs it in process.
+const base::Feature kNetworkServiceInProcess{"NetworkServiceInProcess",
+ base::FEATURE_DISABLED_BY_DEFAULT};
+
+// Kill switch for Web Notification content images.
+const base::Feature kNotificationContentImage{"NotificationContentImage",
+ base::FEATURE_ENABLED_BY_DEFAULT};
// Use Mojo IPC for notifications.
const base::Feature kNotificationsWithMojo{"NotificationsWithMojo",
base::FEATURE_DISABLED_BY_DEFAULT};
+// Off-main-thread WebSocket. See https://crbug.com/825740
+const base::Feature kOffMainThreadWebSocket{"OffMainThreadWebSocket",
+ base::FEATURE_DISABLED_BY_DEFAULT};
+
// Origin Manifest. See crbug.com/751996
const base::Feature kOriginManifest{"OriginManifest",
base::FEATURE_DISABLED_BY_DEFAULT};
@@ -222,16 +262,6 @@ const base::Feature kOriginManifest{"OriginManifest",
const base::Feature kOriginTrials{"OriginTrials",
base::FEATURE_ENABLED_BY_DEFAULT};
-// Whether a download can be handled by parallel jobs.
-const base::Feature kParallelDownloading {
- "ParallelDownloading",
-#if defined(OS_ANDROID)
- base::FEATURE_ENABLED_BY_DEFAULT
-#else
- base::FEATURE_DISABLED_BY_DEFAULT
-#endif
-};
-
// Whether document level event listeners should default 'passive' to true.
const base::Feature kPassiveDocumentEventListeners{
"PassiveDocumentEventListeners", base::FEATURE_ENABLED_BY_DEFAULT};
@@ -241,6 +271,21 @@ const base::Feature kPassiveDocumentEventListeners{
const base::Feature kPassiveEventListenersDueToFling{
"PassiveEventListenersDueToFling", base::FEATURE_ENABLED_BY_DEFAULT};
+// Whether PDF files should be rendered in diffent processes based on origin.
+const base::Feature kPdfIsolation = {"PdfIsolation",
+ base::FEATURE_DISABLED_BY_DEFAULT};
+
+// If Pepper 3D Image Chromium is allowed, this feature controls whether it is
+// enabled.
+const base::Feature kPepper3DImageChromium {
+ "Pepper3DImageChromium",
+#if defined(OS_MACOSX)
+ base::FEATURE_ENABLED_BY_DEFAULT
+#else
+ base::FEATURE_DISABLED_BY_DEFAULT
+#endif
+};
+
// Enables Purge+Throttle on platforms except Android and MacOS.
// (Android) Purge+Throttle depends on TabManager, but TabManager doesn't
// support Android. Enable after Android is supported.
@@ -255,29 +300,18 @@ const base::Feature kPurgeAndSuspend {
#endif
};
-// If Pepper 3D Image Chromium is allowed, this feature controls whether it is
-// enabled.
-const base::Feature kPepper3DImageChromium {
- "Pepper3DImageChromium",
-#if defined(OS_MACOSX)
- base::FEATURE_ENABLED_BY_DEFAULT
-#else
- base::FEATURE_DISABLED_BY_DEFAULT
-#endif
-};
-
// Generate V8 full code cache for PWAs.
const base::Feature kPWAFullCodeCache{"PWAFullCodeCache",
- base::FEATURE_DISABLED_BY_DEFAULT};
+ base::FEATURE_ENABLED_BY_DEFAULT};
+
+// Enable raster-inducing scroll.
+const base::Feature kRasterInducingScroll{"RasterInducingScroll",
+ base::FEATURE_DISABLED_BY_DEFAULT};
// Throttle Blink's rendering pipeline based on frame visibility.
const base::Feature kRenderingPipelineThrottling{
"RenderingPipelineThrottling", base::FEATURE_ENABLED_BY_DEFAULT};
-// Collect renderer peak memory usage during page loads.
-const base::Feature kReportRendererPeakMemoryStats{
- "ReportRendererPeakMemoryStats", base::FEATURE_DISABLED_BY_DEFAULT};
-
// When loading CSS from a 'file:' URL, require a CSS-like file extension.
const base::Feature kRequireCSSExtensionForFile{
"RequireCSSExtensionForFile", base::FEATURE_ENABLED_BY_DEFAULT};
@@ -316,7 +350,7 @@ const base::Feature kServiceWorkerPaymentApps{
// Generate V8 full code cache of service worker scripts.
const base::Feature kServiceWorkerScriptFullCodeCache{
- "ServiceWorkerScriptFullCodeCache", base::FEATURE_DISABLED_BY_DEFAULT};
+ "ServiceWorkerScriptFullCodeCache", base::FEATURE_ENABLED_BY_DEFAULT};
// Establish direct connection from clients to the service worker.
const base::Feature kServiceWorkerServicification{
@@ -336,14 +370,15 @@ const base::Feature kSignedHTTPExchange{"SignedHTTPExchange",
const base::Feature kSignInProcessIsolation{"sign-in-process-isolation",
base::FEATURE_ENABLED_BY_DEFAULT};
-// Alternative to switches::kSitePerProcess, for turning on full site isolation.
-// Launch bug: https://crbug.com/739418.
-const base::Feature kSitePerProcess{"site-per-process",
- base::FEATURE_DISABLED_BY_DEFAULT};
-
// Slimming Paint V1.75. See http://crbug.com/771643.
const base::Feature kSlimmingPaintV175{"SlimmingPaintV175",
- base::FEATURE_DISABLED_BY_DEFAULT};
+ base::FEATURE_ENABLED_BY_DEFAULT};
+
+// Controls whether SpareRenderProcessHostManager tries to always have a warm
+// spare renderer process around for the most recently requested BrowserContext.
+// This feature is only consulted in site-per-process mode.
+const base::Feature kSpareRendererForSitePerProcess{
+ "SpareRendererForSitePerProcess", base::FEATURE_ENABLED_BY_DEFAULT};
// Stop scheduler task queues in background after allowed grace time.
const base::Feature kStopInBackground {
@@ -360,16 +395,15 @@ const base::Feature kStopInBackground {
const base::Feature kStopLoadingInBackground{"stop-loading-in-background",
base::FEATURE_DISABLED_BY_DEFAULT};
+// Stop non-timer task queues in background, on Android,
+// after allowed grace time. Launch bug: https://crbug.com/822954.
+const base::Feature kStopNonTimersInBackground{
+ "stop-non-timers-in-background", base::FEATURE_DISABLED_BY_DEFAULT};
+
// Throttle Blink timers in out-of-view cross origin frames.
const base::Feature kTimerThrottlingForHiddenFrames{
"TimerThrottlingForHiddenFrames", base::FEATURE_ENABLED_BY_DEFAULT};
-// An experimental simple user-activation model where the user gesture state is
-// tracked through a frame-based state instead of the gesture tokens we use
-// today.
-const base::Feature kUserActivationV2{"UserActivationV2",
- base::FEATURE_DISABLED_BY_DEFAULT};
-
// Groups all out-of-process iframes to a different process from the process of
// the top document. This is a performance isolation mode. Launch bug:
// https://crbug.com/595987.
@@ -405,9 +439,31 @@ const base::Feature kUseMojoAudioInputStreamFactory{
const base::Feature kUseMojoAudioOutputStreamFactory{
"UseMojoAudioOutputStreamFactory", base::FEATURE_ENABLED_BY_DEFAULT};
-// Controls whether vibrate requires user gesture.
-const base::Feature kVibrateRequiresUserGesture{
- "VibrateRequiresUserGesture", base::FEATURE_ENABLED_BY_DEFAULT};
+// An experimental simple user-activation model where the user gesture state is
+// tracked through a frame-based state instead of the gesture tokens we use
+// today.
+const base::Feature kUserActivationV2{"UserActivationV2",
+ base::FEATURE_DISABLED_BY_DEFAULT};
+
+// Use RenderWidgetHostView::CreateVideoCapturer instead of
+// RenderWidgetHostView::CopyFromSurface to obtain a stream of snapshots
+// captured from the renderer for DevTools performance timeline and eyedropper
+// tool.
+const base::Feature kUseVideoCaptureApiForDevToolsSnapshots{
+ "UseVideoCaptureApiForDevToolsSnapshots",
+ base::FEATURE_DISABLED_BY_DEFAULT};
+
+// Enables to use a snapshot file in creating V8 contexts.
+const base::Feature kV8ContextSnapshot{"V8ContextSnapshot",
+ base::FEATURE_ENABLED_BY_DEFAULT};
+
+// Enables future V8 VM features
+const base::Feature kV8VmFuture{"V8VmFuture",
+ base::FEATURE_DISABLED_BY_DEFAULT};
+
+// Controls whether editing web input fields is enabled in VR.
+const base::Feature kVrWebInputEditing{"VrWebInputEditing",
+ base::FEATURE_ENABLED_BY_DEFAULT};
// Enable WebAssembly structured cloning.
// http://webassembly.org/
@@ -422,10 +478,37 @@ const base::Feature kWebAssemblyStreaming{"WebAssemblyStreaming",
const base::Feature kWebAssemblyTrapHandler{"WebAssemblyTrapHandler",
base::FEATURE_DISABLED_BY_DEFAULT};
+// Controls whether the visibility of a WebContents can be OCCLUDED. When
+// disabled, an occluded WebContents behaves exactly like a VISIBLE WebContents.
+const base::Feature kWebContentsOcclusion {
+ "WebContentsOcclusion",
+#if defined(OS_MACOSX) || defined(OS_CHROMEOS)
+ base::FEATURE_ENABLED_BY_DEFAULT
+#else
+ base::FEATURE_DISABLED_BY_DEFAULT
+#endif
+};
+
// Controls whether the WebAuthentication API is enabled:
// https://w3c.github.io/webauthn
-const base::Feature kWebAuth{"WebAuthentication",
- base::FEATURE_DISABLED_BY_DEFAULT};
+const base::Feature kWebAuth {
+ "WebAuthentication",
+#if defined(OS_ANDROID)
+ base::FEATURE_DISABLED_BY_DEFAULT
+#else
+ base::FEATURE_ENABLED_BY_DEFAULT
+#endif
+};
+
+// Controls whether BLE authenticators can be used via the WebAuthentication
+// API. https://w3c.github.io/webauthn
+const base::Feature kWebAuthBle{"WebAuthenticationBle",
+ base::FEATURE_DISABLED_BY_DEFAULT};
+
+// Controls whether CTAP2 authenticators can be used via the WebAuthentication
+// API. https://w3c.github.io/webauthn
+const base::Feature kWebAuthCtap2{"WebAuthenticationCtap2",
+ base::FEATURE_DISABLED_BY_DEFAULT};
// If WebGL Image Chromium is allowed, this feature controls whether it is
// enabled.
@@ -436,6 +519,16 @@ const base::Feature kWebGLImageChromium{"WebGLImageChromium",
const base::Feature kWebPayments{"WebPayments",
base::FEATURE_ENABLED_BY_DEFAULT};
+// Informs the WebRTC Acoustic Echo Canceler (AEC) that echo path loss is
+// bounded.
+const base::Feature kWebRtcAecBoundedErlSetup{
+ "WebRtcAecBoundedErlSetup", base::FEATURE_DISABLED_BY_DEFAULT};
+
+// Informs the WebRTC Acoustic Echo Canceler (AEC) that the playout and
+// capture is done using different clocks.
+const base::Feature kWebRtcAecClockDriftSetup{
+ "WebRtcAecClockDriftSetup", base::FEATURE_DISABLED_BY_DEFAULT};
+
// Makes WebRTC use ECDSA certs by default (i.e., when no cert type was
// specified in JS).
const base::Feature kWebRtcEcdsaDefault{"WebRTC-EnableWebRtcEcdsa",
@@ -470,42 +563,14 @@ const base::Feature kWebRtcScreenshareSwEncoding{
const base::Feature kWebRtcUseEchoCanceller3{"WebRtcUseEchoCanceller3",
base::FEATURE_DISABLED_BY_DEFAULT};
-// Informs the WebRTC Acoustic Echo Canceler (AEC) that echo path loss is
-// bounded.
-const base::Feature kWebRtcAecBoundedErlSetup{
- "WebRtcAecBoundedErlSetup", base::FEATURE_DISABLED_BY_DEFAULT};
-
-// Informs the WebRTC Acoustic Echo Canceler (AEC) that the playout and
-// capture is done using different clocks.
-const base::Feature kWebRtcAecClockDriftSetup{
- "WebRtcAecClockDriftSetup", base::FEATURE_DISABLED_BY_DEFAULT};
-
// Use GpuMemoryBuffer backed VideoFrames in media streams.
const base::Feature kWebRtcUseGpuMemoryBufferVideoFrames{
- "WebRTC-UseGpuMemoryBufferVideoFrames", base::FEATURE_DISABLED_BY_DEFAULT};
+ "WebRTC-UseGpuMemoryBufferVideoFrames", base::FEATURE_ENABLED_BY_DEFAULT};
// Controls whether the WebUSB API is enabled:
// https://wicg.github.io/webusb
const base::Feature kWebUsb{"WebUSB", base::FEATURE_ENABLED_BY_DEFAULT};
-// Enables/disables the Image Capture API.
-const base::Feature kImageCaptureAPI{"ImageCaptureAPI",
- base::FEATURE_ENABLED_BY_DEFAULT};
-
-// Alternative to switches::kIsolateOrigins, for turning on origin isolation.
-// List of origins to isolate has to be specified via
-// kIsolateOriginsFieldTrialParamName.
-const base::Feature kIsolateOrigins{"IsolateOrigins",
- base::FEATURE_DISABLED_BY_DEFAULT};
-const char kIsolateOriginsFieldTrialParamName[] = "OriginsList";
-
-const base::Feature kKeepAliveRendererForKeepaliveRequests{
- "KeepAliveRendererForKeepaliveRequests", base::FEATURE_ENABLED_BY_DEFAULT};
-
-// Controls whether editing web input fields is enabled in VR.
-const base::Feature kVrWebInputEditing{"VrWebInputEditing",
- base::FEATURE_ENABLED_BY_DEFAULT};
-
// Controls whether WebVR VSync-aligned render loop timing is enabled.
const base::Feature kWebVrVsyncAlign{"WebVrVsyncAlign",
base::FEATURE_ENABLED_BY_DEFAULT};
@@ -513,22 +578,14 @@ const base::Feature kWebVrVsyncAlign{"WebVrVsyncAlign",
// Controls whether the WebXR Device API is enabled.
const base::Feature kWebXr{"WebXR", base::FEATURE_DISABLED_BY_DEFAULT};
+// Enables access to raycasting against estimated XR scene geometry.
+const base::Feature kWebXrHitTest{"WebXRHitTest",
+ base::FEATURE_DISABLED_BY_DEFAULT};
+
// Controls whether the orientation sensor based device is enabled.
const base::Feature kWebXrOrientationSensorDevice{
"WebXROrientationSensorDevice", base::FEATURE_DISABLED_BY_DEFAULT};
-#if defined(OS_ANDROID)
-// Controls whether an override for the WebXR presentation render path is
-// enabled. The param value specifies the requested specific render path. This
-// is combined with a runtime capability check, the option is ignored if the
-// requested render path is unsupported.
-const base::Feature kWebXrRenderPath{"WebXrRenderPath",
- base::FEATURE_DISABLED_BY_DEFAULT};
-const char kWebXrRenderPathParamName[] = "RenderPath";
-const char kWebXrRenderPathParamValueClientWait[] = "ClientWait";
-const char kWebXrRenderPathParamValueGpuFence[] = "GpuFence";
-#endif // defined(OS_ANDROID)
-
// Enabled "work stealing" in the script runner.
const base::Feature kWorkStealingInScriptRunner{
"WorkStealingInScriptRunner", base::FEATURE_DISABLED_BY_DEFAULT};
@@ -546,6 +603,17 @@ const base::Feature kHideIncorrectlySizedFullscreenFrames{
// Controls whether the WebNFC API is enabled:
// https://w3c.github.io/web-nfc/
const base::Feature kWebNfc{"WebNFC", base::FEATURE_DISABLED_BY_DEFAULT};
+
+// Controls whether an override for the WebXR presentation render path is
+// enabled. The param value specifies the requested specific render path. This
+// is combined with a runtime capability check, the option is ignored if the
+// requested render path is unsupported.
+const base::Feature kWebXrRenderPath{"WebXrRenderPath",
+ base::FEATURE_DISABLED_BY_DEFAULT};
+const char kWebXrRenderPathParamName[] = "RenderPath";
+const char kWebXrRenderPathParamValueClientWait[] = "ClientWait";
+const char kWebXrRenderPathParamValueGpuFence[] = "GpuFence";
+const char kWebXrRenderPathParamValueSharedBuffer[] = "SharedBuffer";
#endif // defined(OS_ANDROID)
#if defined(OS_MACOSX)
@@ -559,18 +627,6 @@ const base::Feature kMacV2Sandbox{"MacV2Sandbox",
base::FEATURE_DISABLED_BY_DEFAULT};
#endif // defined(OS_MACOSX)
-// Enables V8 background compilation
-const base::Feature kV8BackgroundCompile{"V8BackgroundCompile",
- base::FEATURE_DISABLED_BY_DEFAULT};
-
-// Enables to use a snapshot file in creating V8 contexts.
-const base::Feature kV8ContextSnapshot{"V8ContextSnapshot",
- base::FEATURE_ENABLED_BY_DEFAULT};
-
-// Enables future V8 VM features
-const base::Feature kV8VmFuture{"V8VmFuture",
- base::FEATURE_DISABLED_BY_DEFAULT};
-
bool IsVideoCaptureServiceEnabledForOutOfProcess() {
#if defined(OS_ANDROID)
return false;
@@ -591,8 +647,4 @@ bool IsVideoCaptureServiceEnabledForBrowserProcess() {
#endif
}
-// Enables code caching after executing the script.
-const base::Feature kCodeCacheAfterExecute{"CodeCacheAfterExecute",
- base::FEATURE_ENABLED_BY_DEFAULT};
-
} // namespace features
diff --git a/chromium/content/public/common/content_features.h b/chromium/content/public/common/content_features.h
index da03e97c2b4..e3eed28171b 100644
--- a/chromium/content/public/common/content_features.h
+++ b/chromium/content/public/common/content_features.h
@@ -23,19 +23,19 @@ CONTENT_EXPORT extern const base::Feature kArrayPrototypeValues;
CONTENT_EXPORT extern const base::Feature kAsmJsToWebAssembly;
CONTENT_EXPORT extern const base::Feature kAsyncWheelEvents;
CONTENT_EXPORT extern const base::Feature kBlockCredentialedSubresources;
-CONTENT_EXPORT extern const base::Feature kDataSaverHoldback;
CONTENT_EXPORT extern const base::Feature kBrotliEncoding;
-CONTENT_EXPORT extern const base::Feature kNavigationMojoResponse;
+CONTENT_EXPORT extern const base::Feature kCacheInlineScriptCode;
CONTENT_EXPORT extern const base::Feature kCanvas2DImageChromium;
CONTENT_EXPORT extern const base::Feature kCheckerImaging;
+CONTENT_EXPORT extern const base::Feature kCodeCacheAfterExecute;
CONTENT_EXPORT extern const base::Feature kCompositeOpaqueFixedPosition;
CONTENT_EXPORT extern const base::Feature kCompositeOpaqueScrollers;
-CONTENT_EXPORT extern const base::Feature kCompositorImageAnimation;
CONTENT_EXPORT extern const base::Feature kCompositorTouchAction;
CONTENT_EXPORT extern const base::Feature kCrossSiteDocumentBlockingAlways;
CONTENT_EXPORT extern const base::Feature kCrossSiteDocumentBlockingIfIsolating;
-CONTENT_EXPORT extern const base::Feature kExtendedMouseButtons;
+CONTENT_EXPORT extern const base::Feature kDataSaverHoldback;
CONTENT_EXPORT extern const base::Feature kExpensiveBackgroundTimerThrottling;
+CONTENT_EXPORT extern const base::Feature kExtendedMouseButtons;
CONTENT_EXPORT extern const base::Feature kFontCacheScaling;
CONTENT_EXPORT extern const base::Feature
kFramebustingNeedsSameOriginOrUserGesture;
@@ -45,33 +45,34 @@ CONTENT_EXPORT extern const base::Feature kHeapCompaction;
CONTENT_EXPORT extern const base::Feature kImageCaptureAPI;
CONTENT_EXPORT extern const base::Feature kIsolateOrigins;
CONTENT_EXPORT extern const char kIsolateOriginsFieldTrialParamName[];
-CONTENT_EXPORT extern const base::Feature
- kKeepAliveRendererForKeepaliveRequests;
CONTENT_EXPORT extern const base::Feature kKeyboardLockAPI;
+CONTENT_EXPORT extern const base::Feature kLazyFrameLoading;
CONTENT_EXPORT extern const base::Feature kLazyInitializeMediaControls;
CONTENT_EXPORT extern const base::Feature kLazyParseCSS;
CONTENT_EXPORT extern const base::Feature kLowPriorityIframes;
+CONTENT_EXPORT extern const base::Feature kMainThreadBusyScrollIntervention;
CONTENT_EXPORT extern const base::Feature kMediaDevicesSystemMonitorCache;
CONTENT_EXPORT extern const base::Feature kMemoryCoordinator;
-CONTENT_EXPORT extern const base::Feature kNetworkServiceInProcess;
-CONTENT_EXPORT extern const base::Feature kNotificationContentImage;
-CONTENT_EXPORT extern const base::Feature kMainThreadBusyScrollIntervention;
+CONTENT_EXPORT extern const base::Feature kModuleScriptsDynamicImport;
+CONTENT_EXPORT extern const base::Feature kModuleScriptsImportMetaUrl;
CONTENT_EXPORT extern const base::Feature kMojoInputMessages;
CONTENT_EXPORT extern const base::Feature kMojoSessionStorage;
CONTENT_EXPORT extern const base::Feature kMojoVideoCapture;
-CONTENT_EXPORT extern const base::Feature kModuleScriptsDynamicImport;
-CONTENT_EXPORT extern const base::Feature kModuleScriptsImportMetaUrl;
+CONTENT_EXPORT extern const base::Feature kNavigationMojoResponse;
+CONTENT_EXPORT extern const base::Feature kNetworkServiceInProcess;
+CONTENT_EXPORT extern const base::Feature kNotificationContentImage;
CONTENT_EXPORT extern const base::Feature kNotificationsWithMojo;
+CONTENT_EXPORT extern const base::Feature kOffMainThreadWebSocket;
CONTENT_EXPORT extern const base::Feature kOriginManifest;
CONTENT_EXPORT extern const base::Feature kOriginTrials;
-CONTENT_EXPORT extern const base::Feature kParallelDownloading;
CONTENT_EXPORT extern const base::Feature kPassiveDocumentEventListeners;
CONTENT_EXPORT extern const base::Feature kPassiveEventListenersDueToFling;
+CONTENT_EXPORT extern const base::Feature kPdfIsolation;
CONTENT_EXPORT extern const base::Feature kPepper3DImageChromium;
CONTENT_EXPORT extern const base::Feature kPurgeAndSuspend;
CONTENT_EXPORT extern const base::Feature kPWAFullCodeCache;
+CONTENT_EXPORT extern const base::Feature kRasterInducingScroll;
CONTENT_EXPORT extern const base::Feature kRenderingPipelineThrottling;
-CONTENT_EXPORT extern const base::Feature kReportRendererPeakMemoryStats;
CONTENT_EXPORT extern const base::Feature kRequireCSSExtensionForFile;
CONTENT_EXPORT extern const base::Feature kResourceLoadScheduler;
CONTENT_EXPORT extern const base::Feature kRootLayerScrolling;
@@ -79,21 +80,23 @@ CONTENT_EXPORT extern const base::Feature
kRunVideoCaptureServiceInBrowserProcess;
CONTENT_EXPORT extern const base::Feature kScrollAnchoring;
CONTENT_EXPORT extern const base::Feature kScrollAnchorSerialization;
-CONTENT_EXPORT
-extern const base::Feature kSendBeaconThrowForBlobWithNonSimpleType;
+CONTENT_EXPORT extern const base::Feature
+ kSendBeaconThrowForBlobWithNonSimpleType;
CONTENT_EXPORT extern const base::Feature kServiceWorkerPaymentApps;
CONTENT_EXPORT extern const base::Feature kServiceWorkerScriptFullCodeCache;
CONTENT_EXPORT extern const base::Feature kServiceWorkerServicification;
CONTENT_EXPORT extern const base::Feature kSharedArrayBuffer;
CONTENT_EXPORT extern const base::Feature kSignedHTTPExchange;
CONTENT_EXPORT extern const base::Feature kSignInProcessIsolation;
-CONTENT_EXPORT extern const base::Feature kSitePerProcess;
CONTENT_EXPORT extern const base::Feature kSlimmingPaintV175;
+CONTENT_EXPORT extern const base::Feature kSpareRendererForSitePerProcess;
CONTENT_EXPORT extern const base::Feature kStopInBackground;
CONTENT_EXPORT extern const base::Feature kStopLoadingInBackground;
+CONTENT_EXPORT extern const base::Feature kStopNonTimersInBackground;
CONTENT_EXPORT extern const base::Feature kTimerThrottlingForHiddenFrames;
CONTENT_EXPORT extern const base::Feature kTopDocumentIsolation;
CONTENT_EXPORT extern const base::Feature kTouchpadAndWheelScrollLatching;
+CONTENT_EXPORT extern const base::Feature kTouchpadOverscrollHistoryNavigation;
CONTENT_EXPORT extern const base::Feature
kTurnOff2DAndOpacityCompositorAnimations;
CONTENT_EXPORT extern const base::Feature kUnifiedTouchAdjustment;
@@ -101,16 +104,18 @@ CONTENT_EXPORT extern const base::Feature kUseFeaturePolicyForPermissions;
CONTENT_EXPORT extern const base::Feature kUseMojoAudioInputStreamFactory;
CONTENT_EXPORT extern const base::Feature kUseMojoAudioOutputStreamFactory;
CONTENT_EXPORT extern const base::Feature kUserActivationV2;
+CONTENT_EXPORT extern const base::Feature
+ kUseVideoCaptureApiForDevToolsSnapshots;
CONTENT_EXPORT extern const base::Feature kV8ContextSnapshot;
-CONTENT_EXPORT extern const base::Feature kV8BackgroundCompile;
CONTENT_EXPORT extern const base::Feature kV8VmFuture;
CONTENT_EXPORT extern const base::Feature kVrWebInputEditing;
-CONTENT_EXPORT extern const base::Feature kCodeCacheAfterExecute;
-CONTENT_EXPORT extern const base::Feature kVibrateRequiresUserGesture;
CONTENT_EXPORT extern const base::Feature kWebAssembly;
CONTENT_EXPORT extern const base::Feature kWebAssemblyStreaming;
CONTENT_EXPORT extern const base::Feature kWebAssemblyTrapHandler;
CONTENT_EXPORT extern const base::Feature kWebAuth;
+CONTENT_EXPORT extern const base::Feature kWebAuthBle;
+CONTENT_EXPORT extern const base::Feature kWebContentsOcclusion;
+CONTENT_EXPORT extern const base::Feature kWebAuthCtap2;
CONTENT_EXPORT extern const base::Feature kWebGLImageChromium;
CONTENT_EXPORT extern const base::Feature kWebPayments;
CONTENT_EXPORT extern const base::Feature kWebRtcAecBoundedErlSetup;
@@ -125,20 +130,20 @@ CONTENT_EXPORT extern const base::Feature kWebRtcUseGpuMemoryBufferVideoFrames;
CONTENT_EXPORT extern const base::Feature kWebUsb;
CONTENT_EXPORT extern const base::Feature kWebVrVsyncAlign;
CONTENT_EXPORT extern const base::Feature kWebXr;
+CONTENT_EXPORT extern const base::Feature kWebXrGamepadSupport;
+CONTENT_EXPORT extern const base::Feature kWebXrHitTest;
CONTENT_EXPORT extern const base::Feature kWebXrOrientationSensorDevice;
-#if defined(OS_ANDROID)
-CONTENT_EXPORT extern const base::Feature kWebXrRenderPath;
-CONTENT_EXPORT extern const char kWebXrRenderPathParamName[];
-CONTENT_EXPORT extern const char kWebXrRenderPathParamValueClientWait[];
-CONTENT_EXPORT extern const char kWebXrRenderPathParamValueGpuFence[];
-#endif // defined(OS_ANDROID)
CONTENT_EXPORT extern const base::Feature kWorkStealingInScriptRunner;
#if defined(OS_ANDROID)
CONTENT_EXPORT extern const base::Feature kAndroidAutofillAccessibility;
CONTENT_EXPORT extern const base::Feature kHideIncorrectlySizedFullscreenFrames;
-CONTENT_EXPORT extern const base::Feature kImeThread;
CONTENT_EXPORT extern const base::Feature kWebNfc;
+CONTENT_EXPORT extern const base::Feature kWebXrRenderPath;
+CONTENT_EXPORT extern const char kWebXrRenderPathParamName[];
+CONTENT_EXPORT extern const char kWebXrRenderPathParamValueClientWait[];
+CONTENT_EXPORT extern const char kWebXrRenderPathParamValueGpuFence[];
+CONTENT_EXPORT extern const char kWebXrRenderPathParamValueSharedBuffer[];
#endif // defined(OS_ANDROID)
#if defined(OS_MACOSX)
diff --git a/chromium/content/public/common/content_switches.cc b/chromium/content/public/common/content_switches.cc
index cd3c6bdb837..97e443b8fd7 100644
--- a/chromium/content/public/common/content_switches.cc
+++ b/chromium/content/public/common/content_switches.cc
@@ -1,11 +1,11 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/public/common/content_switches.h"
#include "build/build_config.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
namespace switches {
@@ -176,6 +176,10 @@ const char kDisableGpuSandbox[] = "disable-gpu-sandbox";
// messages.
const char kDisableGpuWatchdog[] = "disable-gpu-watchdog";
+// Disallow image animations to be reset to the beginning to avoid skipping
+// many frames. Only effective if compositor image animations are enabled.
+const char kDisableImageAnimationResync[] = "disable-image-animation-resync";
+
// Suppresses hang monitor dialogs in renderer processes. This may allow slow
// unload handlers on a page to prevent the tab from closing, but the Task
// Manager can be used to terminate the offending process in this case.
@@ -192,9 +196,6 @@ const char kDisableKillAfterBadIPC[] = "disable-kill-after-bad-ipc";
// Disables LCD text.
const char kDisableLCDText[] = "disable-lcd-text";
-// Disables distance field text.
-const char kDisableDistanceFieldText[] = "disable-distance-field-text";
-
// Disable LocalStorage.
const char kDisableLocalStorage[] = "disable-local-storage";
@@ -242,6 +243,9 @@ const char kDisablePreferCompositingToLCDText[] =
// Disables the Presentation API.
const char kDisablePresentationAPI[] = "disable-presentation-api";
+// Disables throttling of history.pushState/replaceState calls.
+const char kDisablePushStateThrottle[] = "disable-pushstate-throttle";
+
// Disables RGBA_4444 textures.
const char kDisableRGBA4444Textures[] = "disable-rgba-4444-textures";
@@ -331,10 +335,6 @@ const char kDumpBlinkRuntimeCallStats[] = "dump-blink-runtime-call-stats";
// Enables LCD text.
const char kEnableLCDText[] = "enable-lcd-text";
-// Enables using signed distance fields when rendering text.
-// Only valid if GPU rasterization is enabled as well.
-const char kEnableDistanceFieldText[] = "enable-distance-field-text";
-
// Enable the creation of compositing layers when it would prevent LCD text.
const char kEnablePreferCompositingToLCDText[] =
"enable-prefer-compositing-to-lcd-text";
@@ -349,14 +349,6 @@ const char kEnableBackgroundFetchPersistence[] =
// features.
const char kEnableBlinkFeatures[] = "enable-blink-features";
-// Enable animating of images in the compositor instead of blink.
-const char kEnableCompositorImageAnimations[] =
- "enable-compositor-image-animations";
-
-// Enable experimental canvas features, e.g. canvas 2D context attributes
-const char kEnableExperimentalCanvasFeatures[] =
- "enable-experimental-canvas-features";
-
// Enables Web Platform features that are in development.
const char kEnableExperimentalWebPlatformFeatures[] =
"enable-experimental-web-platform-features";
@@ -469,6 +461,10 @@ const char kEnableVtune[] = "enable-vtune-support";
// Enable Vulkan support, must also have ENABLE_VULKAN defined.
const char kEnableVulkan[] = "enable-vulkan";
+// Enable the Web Authentication Testing API.
+// https://w3c.github.io/webauthn
+const char kEnableWebAuthTestingAPI[] = "enable-web-authentication-testing-api";
+
// Enables WebGL extensions not yet approved by the community.
const char kEnableWebGLDraftExtensions[] = "enable-webgl-draft-extensions";
@@ -582,6 +578,18 @@ const char kLogFile[] = "log-file";
const char kMainFrameResizesAreOrientationChanges[] =
"main-frame-resizes-are-orientation-changes";
+// Specifies the maximum cache size per an origin for the ApplicationCache.
+// The default value is 5MB.
+const char kMaxAppCacheOriginCacheSizeMb[] =
+ "max-appcache-origin-cache-size-mb";
+
+// Specifies the maximum disk cache size for the ApplicationCache. The default
+// value is 250MB.
+const char kMaxAppCacheDiskCacheSizeMb[] = "max-appcache-disk-cache-size-mb";
+
+// Sets the maximium decoded image size limitation.
+const char kMaxDecodedImageSizeMb[] = "max-decoded-image-size-mb";
+
// Sets the width and height above which a composited layer will get tiled.
const char kMaxUntiledLayerHeight[] = "max-untiled-layer-height";
const char kMaxUntiledLayerWidth[] = "max-untiled-layer-width";
@@ -699,7 +707,8 @@ const char kProxyServer[] = "proxy-server";
// Enables or disables pull-to-refresh gesture in response to vertical
// overscroll.
-// Set the value to '1' to enable the feature, and set to '0' to disable.
+// Set the value to '0' to disable the feature, set to '1' to enable it for both
+// touchpad and touchscreen, and set to '2' to enable it only for touchscreen.
// Defaults to disabled.
const char kPullToRefresh[] = "pull-to-refresh";
@@ -775,12 +784,6 @@ const char kSitePerProcess[] = "site-per-process";
// Disables enabling site isolation (i.e., --site-per-process) via field trial.
const char kDisableSiteIsolationTrials[] = "disable-site-isolation-trials";
-// Skips reencoding bitmaps as PNGs when the encoded data is unavailable
-// during SKP capture. This allows for obtaining an accurate sample of
-// the types of images on the web, rather than being weighted towards PNGs
-// that we have encoded ourselves.
-const char kSkipReencodingOnSKPCapture[] = "skip-reencoding-on-skp-capture";
-
// Specifies if the browser should start in fullscreen mode, like if the user
// had pressed F11 right after startup.
const char kStartFullscreen[] = "start-fullscreen";
@@ -792,6 +795,15 @@ const char kStartFullscreen[] = "start-fullscreen";
const char kStatsCollectionController[] =
"enable-stats-collection-bindings";
+// Specifies the max number of bytes that should be used by the skia font cache.
+// If the cache needs to allocate more, skia will purge previous entries.
+const char kSkiaFontCacheLimitMb[] = "skia-font-cache-limit-mb";
+
+// Specifies the max number of bytes that should be used by the skia resource
+// cache. The previous entries are purged from the cache when the memory useage
+// exceeds this limit.
+const char kSkiaResourceCacheLimitMb[] = "skia-resource-cache-limit-mb";
+
// Type of the current test harness ("browser" or "ui").
const char kTestType[] = "test-type";
@@ -833,10 +845,6 @@ const char kUtilityCmdPrefix[] = "utility-cmd-prefix";
// Causes the process to run as a utility subprocess.
const char kUtilityProcess[] = "utility";
-// When utility process is sandboxed, there is still access to one directory.
-// This flag specifies the directory that can be accessed.
-const char kUtilityProcessAllowedDir[] = "utility-allowed-dir";
-
// Causes the utility process to display a dialog on launch.
const char kUtilityStartupDialog[] = "utility-startup-dialog";
diff --git a/chromium/content/public/common/content_switches.h b/chromium/content/public/common/content_switches.h
index 9d2949e0aeb..a1ccec7e81f 100644
--- a/chromium/content/public/common/content_switches.h
+++ b/chromium/content/public/common/content_switches.h
@@ -9,7 +9,7 @@
#include "build/build_config.h"
#include "content/common/content_export.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
namespace switches {
@@ -44,7 +44,6 @@ CONTENT_EXPORT extern const char kDisableBackgroundTimerThrottling[];
CONTENT_EXPORT extern const char kDisableBlinkFeatures[];
CONTENT_EXPORT extern const char kDisableCompositorUkmForTests[];
CONTENT_EXPORT extern const char kDisableDatabases[];
-CONTENT_EXPORT extern const char kDisableDistanceFieldText[];
CONTENT_EXPORT extern const char kDisableDisplayList2dCanvas[];
extern const char kDisableDomainBlockingFor3DAPIs[];
CONTENT_EXPORT extern const char kDisableWebGL[];
@@ -61,6 +60,7 @@ CONTENT_EXPORT extern const char kDisableGpuMemoryBufferVideoFrames[];
extern const char kDisableGpuProcessCrashLimit[];
CONTENT_EXPORT extern const char kDisableGpuSandbox[];
CONTENT_EXPORT extern const char kDisableGpuWatchdog[];
+CONTENT_EXPORT extern const char kDisableImageAnimationResync[];
CONTENT_EXPORT extern const char kDisableJavaScriptHarmonyShipping[];
CONTENT_EXPORT extern const char kDisableLowLatencyDxva[];
CONTENT_EXPORT extern const char kDisableLowResTiling[];
@@ -82,6 +82,7 @@ CONTENT_EXPORT extern const char kDisablePepper3DImageChromium[];
CONTENT_EXPORT extern const char kDisablePermissionsAPI[];
CONTENT_EXPORT extern const char kDisablePinch[];
CONTENT_EXPORT extern const char kDisablePresentationAPI[];
+CONTENT_EXPORT extern const char kDisablePushStateThrottle[];
CONTENT_EXPORT extern const char kDisableRGBA4444Textures[];
CONTENT_EXPORT extern const char kDisableReadingFromCanvas[];
extern const char kDisableRemoteFonts[];
@@ -111,10 +112,7 @@ CONTENT_EXPORT extern const char kEnableAutomation[];
CONTENT_EXPORT extern const char kEnablePreferCompositingToLCDText[];
CONTENT_EXPORT extern const char kEnableBlinkFeatures[];
CONTENT_EXPORT extern const char kEnableBackgroundFetchPersistence[];
-CONTENT_EXPORT extern const char kEnableCompositorImageAnimations[];
CONTENT_EXPORT extern const char kEnableDisplayList2dCanvas[];
-CONTENT_EXPORT extern const char kEnableDistanceFieldText[];
-CONTENT_EXPORT extern const char kEnableExperimentalCanvasFeatures[];
CONTENT_EXPORT extern const char kEnableExperimentalWebPlatformFeatures[];
CONTENT_EXPORT extern const char kEnableGpuMemoryBufferCompositorResources[];
CONTENT_EXPORT extern const char kEnableGpuMemoryBufferVideoFrames[];
@@ -145,6 +143,7 @@ CONTENT_EXPORT extern const char kEnableUseZoomForDSF[];
CONTENT_EXPORT extern const char kEnableViewport[];
CONTENT_EXPORT extern const char kEnableVtune[];
CONTENT_EXPORT extern const char kEnableVulkan[];
+CONTENT_EXPORT extern const char kEnableWebAuthTestingAPI[];
CONTENT_EXPORT extern const char kEnableWebGLDraftExtensions[];
CONTENT_EXPORT extern const char kEnableWebGLImageChromium[];
CONTENT_EXPORT extern const char kEnableWebVR[];
@@ -173,6 +172,9 @@ CONTENT_EXPORT extern const char kLogGpuControlListDecisions[];
CONTENT_EXPORT extern const char kLoggingLevel[];
CONTENT_EXPORT extern const char kLogFile[];
CONTENT_EXPORT extern const char kMainFrameResizesAreOrientationChanges[];
+extern const char kMaxAppCacheOriginCacheSizeMb[];
+extern const char kMaxAppCacheDiskCacheSizeMb[];
+extern const char kMaxDecodedImageSizeMb[];
extern const char kMaxUntiledLayerHeight[];
extern const char kMaxUntiledLayerWidth[];
CONTENT_EXPORT extern const char kMessageLoopTypeUi[];
@@ -215,9 +217,10 @@ extern const char kShowPaintRects[];
CONTENT_EXPORT extern const char kSingleProcess[];
CONTENT_EXPORT extern const char kSitePerProcess[];
CONTENT_EXPORT extern const char kDisableSiteIsolationTrials[];
-extern const char kSkipReencodingOnSKPCapture[];
CONTENT_EXPORT extern const char kStartFullscreen[];
CONTENT_EXPORT extern const char kStatsCollectionController[];
+extern const char kSkiaFontCacheLimitMb[];
+extern const char kSkiaResourceCacheLimitMb[];
CONTENT_EXPORT extern const char kTestType[];
CONTENT_EXPORT extern const char kTouchEventFeatureDetection[];
CONTENT_EXPORT extern const char kTouchEventFeatureDetectionAuto[];
@@ -230,7 +233,6 @@ CONTENT_EXPORT extern const char kUseMobileUserAgent[];
CONTENT_EXPORT extern const char kUseMockCertVerifierForTesting[];
extern const char kUtilityCmdPrefix[];
CONTENT_EXPORT extern const char kUtilityProcess[];
-extern const char kUtilityProcessAllowedDir[];
CONTENT_EXPORT extern const char kUtilityStartupDialog[];
CONTENT_EXPORT extern const char kV8CacheOptions[];
CONTENT_EXPORT extern const char kValidateInputEventStream[];
diff --git a/chromium/content/public/common/context_menu_params.h b/chromium/content/public/common/context_menu_params.h
index a05a75c3457..37a7424b309 100644
--- a/chromium/content/public/common/context_menu_params.h
+++ b/chromium/content/public/common/context_menu_params.h
@@ -15,8 +15,8 @@
#include "build/build_config.h"
#include "content/common/content_export.h"
#include "content/public/common/menu_item.h"
-#include "third_party/WebKit/public/platform/WebReferrerPolicy.h"
-#include "third_party/WebKit/public/web/WebContextMenuData.h"
+#include "third_party/blink/public/platform/web_referrer_policy.h"
+#include "third_party/blink/public/web/web_context_menu_data.h"
#include "ui/base/ui_base_types.h"
#include "ui/gfx/geometry/rect.h"
#include "url/gurl.h"
diff --git a/chromium/content/public/common/cursor_info.h b/chromium/content/public/common/cursor_info.h
index ac56545bfcb..eb054682a0c 100644
--- a/chromium/content/public/common/cursor_info.h
+++ b/chromium/content/public/common/cursor_info.h
@@ -7,7 +7,7 @@
#include "build/build_config.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebCursorInfo.h"
+#include "third_party/blink/public/platform/web_cursor_info.h"
#include "third_party/skia/include/core/SkBitmap.h"
namespace content {
diff --git a/chromium/content/public/common/drop_data.h b/chromium/content/public/common/drop_data.h
index 0993d854af2..eaeafcc0288 100644
--- a/chromium/content/public/common/drop_data.h
+++ b/chromium/content/public/common/drop_data.h
@@ -20,7 +20,7 @@
#include "base/strings/nullable_string16.h"
#include "content/common/content_export.h"
#include "ipc/ipc_message.h"
-#include "third_party/WebKit/public/platform/WebReferrerPolicy.h"
+#include "third_party/blink/public/platform/web_referrer_policy.h"
#include "ui/base/dragdrop/file_info.h"
#include "url/gurl.h"
diff --git a/chromium/content/public/common/feature_h264_with_openh264_ffmpeg.h b/chromium/content/public/common/feature_h264_with_openh264_ffmpeg.h
index 2ee9bf84a66..28ac3885b07 100644
--- a/chromium/content/public/common/feature_h264_with_openh264_ffmpeg.h
+++ b/chromium/content/public/common/feature_h264_with_openh264_ffmpeg.h
@@ -6,8 +6,8 @@
#define CONTENT_PUBLIC_COMMON_FEATURE_H264_WITH_OPENH264_FFMPEG_H_
#include "base/feature_list.h"
-#include "content/public/common/features.h"
-#include "media/media_features.h"
+#include "content/public/common/buildflags.h"
+#include "media/media_buildflags.h"
namespace content {
diff --git a/chromium/content/public/common/font_cache_win.mojom b/chromium/content/public/common/font_cache_win.mojom
index 46fa04c9784..a6d269a09fe 100644
--- a/chromium/content/public/common/font_cache_win.mojom
+++ b/chromium/content/public/common/font_cache_win.mojom
@@ -4,7 +4,7 @@
module content.mojom;
-import "mojo/common/logfont_win.mojom";
+import "mojo/public/mojom/base/logfont_win.mojom";
// Messages sent from child processes to the browser on Windows only. This file
// will not be built on other platforms.
@@ -13,7 +13,7 @@ interface FontCacheWin {
// OS. This must wait for the browser to finish to guarantee the font has been
// cached. See ChildProcessHost::PreCacheFont() for details.
[Sync]
- PreCacheFont(mojo.common.mojom.LOGFONT log_font) => ();
+ PreCacheFont(mojo_base.mojom.LOGFONT log_font) => ();
// Release the cached fonts.
ReleaseCachedFonts();
diff --git a/chromium/content/public/common/manifest.h b/chromium/content/public/common/manifest.h
index 6ff768c21e2..e00110ff2e0 100644
--- a/chromium/content/public/common/manifest.h
+++ b/chromium/content/public/common/manifest.h
@@ -14,8 +14,8 @@
#include "base/strings/nullable_string16.h"
#include "base/strings/string16.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebDisplayMode.h"
-#include "third_party/WebKit/public/platform/modules/screen_orientation/WebScreenOrientationLockType.h"
+#include "third_party/blink/public/platform/modules/screen_orientation/web_screen_orientation_lock_type.h"
+#include "third_party/blink/public/platform/web_display_mode.h"
#include "ui/gfx/geometry/size.h"
#include "url/gurl.h"
@@ -66,8 +66,8 @@ struct CONTENT_EXPORT Manifest {
~ShareTarget();
// The URL template that contains placeholders to be replaced with shared
- // data. Null if the parsing failed.
- base::NullableString16 url_template;
+ // data. Empty if the parsing failed.
+ GURL url_template;
};
// Structure representing a related application.
diff --git a/chromium/content/public/common/manifest.typemap b/chromium/content/public/common/manifest.typemap
index b2cdec5eb53..4b27a5b76b7 100644
--- a/chromium/content/public/common/manifest.typemap
+++ b/chromium/content/public/common/manifest.typemap
@@ -2,7 +2,7 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
-mojom = "//third_party/WebKit/public/platform/modules/manifest/manifest.mojom"
+mojom = "//third_party/blink/public/platform/modules/manifest/manifest.mojom"
public_headers = [ "//content/public/common/manifest.h" ]
traits_headers = [ "//content/public/common/manifest_struct_traits.h" ]
sources = [
diff --git a/chromium/content/public/common/manifest_share_target_util.cc b/chromium/content/public/common/manifest_share_target_util.cc
new file mode 100644
index 00000000000..ada0a39b654
--- /dev/null
+++ b/chromium/content/public/common/manifest_share_target_util.cc
@@ -0,0 +1,127 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/public/common/manifest_share_target_util.h"
+
+#include <map>
+
+#include "base/strings/strcat.h"
+#include "base/strings/string_util.h"
+#include "net/base/escape.h"
+#include "url/gurl.h"
+
+namespace content {
+namespace {
+
+// Determines whether a character is allowed in a URL template placeholder.
+bool IsIdentifier(char c) {
+ return base::IsAsciiAlpha(c) || base::IsAsciiDigit(c) || c == '-' || c == '_';
+}
+
+// Returns to |out| the result of running the "replace placeholders"
+// algorithm on |url_template|. The algorithm is specified at
+// https://wicg.github.io/web-share-target/#dfn-replace-placeholders
+// Does not copy any string data. The resulting vector can be concatenated
+// together with base::StrCat to produce the final string.
+bool ReplacePlaceholders(base::StringPiece template_string,
+ const std::map<base::StringPiece, std::string>& data,
+ std::vector<base::StringPiece>* out) {
+ DCHECK(out);
+
+ bool last_saw_open = false;
+ size_t start_index_to_copy = 0;
+ for (size_t i = 0; i < template_string.size(); ++i) {
+ if (last_saw_open) {
+ if (template_string[i] == '}') {
+ base::StringPiece placeholder = template_string.substr(
+ start_index_to_copy + 1, i - 1 - start_index_to_copy);
+ auto it = data.find(placeholder);
+ if (it != data.end()) {
+ // Replace the placeholder text with the parameter value.
+ out->push_back(it->second);
+ }
+
+ last_saw_open = false;
+ start_index_to_copy = i + 1;
+ } else if (!IsIdentifier(template_string[i])) {
+ // Error: Non-identifier character seen after open.
+ return false;
+ }
+ } else {
+ if (template_string[i] == '}') {
+ // Error: Saw close, with no corresponding open.
+ return false;
+ } else if (template_string[i] == '{') {
+ out->push_back(template_string.substr(start_index_to_copy,
+ i - start_index_to_copy));
+
+ last_saw_open = true;
+ start_index_to_copy = i;
+ }
+ }
+ }
+ if (last_saw_open) {
+ // Error: Saw open that was never closed.
+ return false;
+ }
+ out->push_back(template_string.substr(
+ start_index_to_copy, template_string.size() - start_index_to_copy));
+ return true;
+}
+
+} // namespace
+
+bool ValidateWebShareUrlTemplate(const GURL& url_template) {
+ return ReplaceWebShareUrlPlaceholders(url_template, /*title=*/"", /*text=*/"",
+ /*share_url=*/GURL(),
+ /*url_template_filled=*/nullptr);
+}
+
+bool ReplaceWebShareUrlPlaceholders(const GURL& url_template,
+ base::StringPiece title,
+ base::StringPiece text,
+ const GURL& share_url,
+ GURL* url_template_filled) {
+ constexpr char kTitlePlaceholder[] = "title";
+ constexpr char kTextPlaceholder[] = "text";
+ constexpr char kUrlPlaceholder[] = "url";
+ std::map<base::StringPiece, std::string> replacements;
+ replacements[kTitlePlaceholder] = net::EscapeQueryParamValue(title, false);
+ replacements[kTextPlaceholder] = net::EscapeQueryParamValue(text, false);
+ replacements[kUrlPlaceholder] =
+ net::EscapeQueryParamValue(share_url.spec(), false);
+
+ std::vector<base::StringPiece> new_query_split;
+ std::vector<base::StringPiece> new_ref_split;
+ if (!ReplacePlaceholders(url_template.query_piece(), replacements,
+ &new_query_split) ||
+ !ReplacePlaceholders(url_template.ref_piece(), replacements,
+ &new_ref_split)) {
+ return false;
+ }
+
+ // Early-return optimization, since ReplaceWebShareUrlPlaceholders() is called
+ // at manifest parse time just to get the success boolean, ignoring the
+ // result.
+ if (!url_template_filled)
+ return true;
+
+ // Ensure that the replacements are not deleted prior to
+ // GURL::ReplaceComponents() being called. GURL::Replacements::SetQueryStr()
+ // does not make a copy.
+ std::string new_query = base::StrCat(new_query_split);
+ std::string new_ref = base::StrCat(new_ref_split);
+
+ // Check whether |url_template| has a query in order to preserve the '?' in
+ // a URL with an empty query. e.g. http://www.google.com/?
+ GURL::Replacements url_replacements;
+ if (url_template.has_query())
+ url_replacements.SetQueryStr(new_query);
+ if (url_template.has_ref())
+ url_replacements.SetRefStr(new_ref);
+ *url_template_filled = url_template.ReplaceComponents(url_replacements);
+ return true;
+}
+
+} // namespace content
diff --git a/chromium/content/public/common/manifest_share_target_util.h b/chromium/content/public/common/manifest_share_target_util.h
new file mode 100644
index 00000000000..ee46b28b363
--- /dev/null
+++ b/chromium/content/public/common/manifest_share_target_util.h
@@ -0,0 +1,37 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_PUBLIC_COMMON_MANIFEST_SHARE_TARGET_UTIL_H_
+#define CONTENT_PUBLIC_COMMON_MANIFEST_SHARE_TARGET_UTIL_H_
+
+#include <string>
+
+#include "base/strings/string_piece.h"
+#include "content/common/content_export.h"
+
+class GURL;
+
+namespace content {
+
+// Determines whether |url_template| is valid; that is, whether
+// ReplaceWebShareUrlPlaceholders() would succeed for the given template.
+CONTENT_EXPORT bool ValidateWebShareUrlTemplate(const GURL& url_template);
+
+// Writes to |url_template_filled|, a copy of |url_template| with all
+// instances of "{title}", "{text}", and "{url}" in the query and fragment
+// parts of the URL replaced with |title|, |text|, and |url| respectively.
+// Replaces instances of "{X}" where "X" is any string besides "title",
+// "text", and "url", with an empty string, for forwards compatibility.
+// Returns false, if there are badly nested placeholders.
+// This includes any case in which two "{" occur before a "}", or a "}"
+// occurs with no preceding "{".
+CONTENT_EXPORT bool ReplaceWebShareUrlPlaceholders(const GURL& url_template,
+ base::StringPiece title,
+ base::StringPiece text,
+ const GURL& share_url,
+ GURL* url_template_filled);
+
+} // namespace content
+
+#endif // CONTENT_PUBLIC_COMMON_MANIFEST_SHARE_TARGET_UTIL_H_
diff --git a/chromium/content/public/common/manifest_struct_traits.cc b/chromium/content/public/common/manifest_struct_traits.cc
index e67c4eb302d..2dfe11bc1df 100644
--- a/chromium/content/public/common/manifest_struct_traits.cc
+++ b/chromium/content/public/common/manifest_struct_traits.cc
@@ -5,8 +5,8 @@
#include "content/public/common/manifest_struct_traits.h"
#include "mojo/public/cpp/base/string16_mojom_traits.h"
-#include "third_party/WebKit/public/platform/WebDisplayModeStructTraits.h"
-#include "third_party/WebKit/public/platform/modules/screen_orientation/WebScreenOrientationEnumTraits.h"
+#include "third_party/blink/public/platform/modules/screen_orientation/web_screen_orientation_enum_traits.h"
+#include "third_party/blink/public/platform/web_display_mode_struct_traits.h"
#include "ui/gfx/geometry/mojo/geometry_struct_traits.h"
#include "url/mojom/url_gurl_mojom_traits.h"
@@ -147,11 +147,7 @@ bool StructTraits<blink::mojom::ManifestShareTargetDataView,
content::Manifest::ShareTarget>::
Read(blink::mojom::ManifestShareTargetDataView data,
content::Manifest::ShareTarget* out) {
- TruncatedString16 string;
- if (!data.ReadUrlTemplate(&string))
- return false;
- out->url_template = base::NullableString16(std::move(string.string));
- return true;
+ return data.ReadUrlTemplate(&out->url_template);
}
} // namespace mojo
diff --git a/chromium/content/public/common/manifest_struct_traits.h b/chromium/content/public/common/manifest_struct_traits.h
index 1c195d65a10..f816251fb1d 100644
--- a/chromium/content/public/common/manifest_struct_traits.h
+++ b/chromium/content/public/common/manifest_struct_traits.h
@@ -8,7 +8,7 @@
#include "content/public/common/manifest.h"
#include "mojo/public/cpp/bindings/struct_traits.h"
-#include "third_party/WebKit/public/platform/modules/manifest/manifest.mojom-shared.h"
+#include "third_party/blink/public/platform/modules/manifest/manifest.mojom-shared.h"
namespace mojo {
namespace internal {
@@ -142,9 +142,8 @@ struct StructTraits<blink::mojom::ManifestRelatedApplicationDataView,
template <>
struct StructTraits<blink::mojom::ManifestShareTargetDataView,
content::Manifest::ShareTarget> {
- static base::Optional<base::StringPiece16> url_template(
- const content::Manifest::ShareTarget& m) {
- return internal::TruncateNullableString16(m.url_template);
+ static const GURL& url_template(const content::Manifest::ShareTarget& m) {
+ return m.url_template;
}
static bool Read(blink::mojom::ManifestShareTargetDataView data,
content::Manifest::ShareTarget* out);
diff --git a/chromium/content/public/common/manifest_util.h b/chromium/content/public/common/manifest_util.h
index c40b76d3b6c..1ebe834a3e5 100644
--- a/chromium/content/public/common/manifest_util.h
+++ b/chromium/content/public/common/manifest_util.h
@@ -8,8 +8,8 @@
#include <string>
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebDisplayMode.h"
-#include "third_party/WebKit/public/platform/modules/screen_orientation/WebScreenOrientationLockType.h"
+#include "third_party/blink/public/platform/modules/screen_orientation/web_screen_orientation_lock_type.h"
+#include "third_party/blink/public/platform/web_display_mode.h"
namespace content {
diff --git a/chromium/content/public/common/menu_item.h b/chromium/content/public/common/menu_item.h
index e3cea30a799..d67aef245c7 100644
--- a/chromium/content/public/common/menu_item.h
+++ b/chromium/content/public/common/menu_item.h
@@ -9,7 +9,7 @@
#include "base/strings/string16.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/web/WebMenuItemInfo.h"
+#include "third_party/blink/public/web/web_menu_item_info.h"
namespace content {
diff --git a/chromium/content/public/common/mhtml_generation_params.h b/chromium/content/public/common/mhtml_generation_params.h
index 22dea97c044..01c3fb77537 100644
--- a/chromium/content/public/common/mhtml_generation_params.h
+++ b/chromium/content/public/common/mhtml_generation_params.h
@@ -7,7 +7,7 @@
#include "base/files/file_path.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/web/WebFrameSerializerCacheControlPolicy.h"
+#include "third_party/blink/public/web/web_frame_serializer_cache_control_policy.h"
namespace content {
diff --git a/chromium/content/public/common/pepper_plugin_info.h b/chromium/content/public/common/pepper_plugin_info.h
index 7a6e82e5973..753bff723ad 100644
--- a/chromium/content/public/common/pepper_plugin_info.h
+++ b/chromium/content/public/common/pepper_plugin_info.h
@@ -13,9 +13,9 @@
#include "base/files/file_path.h"
#include "content/common/content_export.h"
#include "content/public/common/webplugininfo.h"
+#include "ppapi/buildflags/buildflags.h"
#include "ppapi/c/pp_module.h"
#include "ppapi/c/ppb.h"
-#include "ppapi/features/features.h"
#if !BUILDFLAG(ENABLE_PLUGINS)
#error "Plugins should be enabled"
diff --git a/chromium/content/public/common/presentation_connection_message.cc b/chromium/content/public/common/presentation_connection_message.cc
index e4170f02d3b..d8c0e583f8b 100644
--- a/chromium/content/public/common/presentation_connection_message.cc
+++ b/chromium/content/public/common/presentation_connection_message.cc
@@ -21,11 +21,8 @@ PresentationConnectionMessage::PresentationConnectionMessage(
PresentationConnectionMessage::PresentationConnectionMessage(
const PresentationConnectionMessage& other) = default;
-// Note: "move constructor noexcept = default" currently does not compile on
-// Windows and Android (crbug.com/706963).
PresentationConnectionMessage::PresentationConnectionMessage(
- PresentationConnectionMessage&& other) noexcept
- : message(std::move(other.message)), data(std::move(other.data)) {}
+ PresentationConnectionMessage&& other) noexcept = default;
PresentationConnectionMessage::~PresentationConnectionMessage() {}
diff --git a/chromium/content/public/common/previews_state.h b/chromium/content/public/common/previews_state.h
index e28a5c18464..8fce0d16bcd 100644
--- a/chromium/content/public/common/previews_state.h
+++ b/chromium/content/public/common/previews_state.h
@@ -6,7 +6,7 @@
#define CONTENT_PUBLIC_COMMON_PREVIEWS_STATE_H_
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebURLRequest.h"
+#include "third_party/blink/public/platform/web_url_request.h"
#define STATIC_ASSERT_PREVIEWS_ENUM(a, b) \
static_assert(static_cast<int>(a) == static_cast<int>(b), \
diff --git a/chromium/content/public/common/push_messaging_status.mojom b/chromium/content/public/common/push_messaging_status.mojom
index d2eeb060067..b4a7d957dc3 100644
--- a/chromium/content/public/common/push_messaging_status.mojom
+++ b/chromium/content/public/common/push_messaging_status.mojom
@@ -29,12 +29,9 @@ enum PushDeliveryStatus {
// The message was delivered, but the Service Worker timed out processing it.
TIMEOUT = 7,
- // NOTE: Do not renumber these as that would confuse interpretation of
- // previously logged data. When making changes, also update the enum list
- // in tools/metrics/histograms/histograms.xml to keep it in sync, and
- // update LAST below.
-
- LAST = TIMEOUT
+ // NOTE: Do not renumber or delete these as that would confuse interpretation
+ // of previously logged data. When making changes, also update the enum list
+ // in tools/metrics/histograms/histograms.xml to keep it in sync.
};
// Push getregistration success/error codes for internal use & reporting in UMA.
@@ -68,12 +65,9 @@ enum PushGetRegistrationStatus {
// Getting the registration failed because there was no live service worker.
NO_LIVE_SERVICE_WORKER = 8,
- // NOTE: Do not renumber these as that would confuse interpretation of
- // previously logged data. When making changes, also update the enum list
- // in tools/metrics/histograms/histograms.xml to keep it in sync, and
- // update LAST below.
-
- LAST = NO_LIVE_SERVICE_WORKER
+ // NOTE: Do not renumber or delete these as that would confuse interpretation
+ // of previously logged data. When making changes, also update the enum list
+ // in tools/metrics/histograms/histograms.xml to keep it in sync.
};
// Push registration success/error codes for internal use & reporting in UMA.
@@ -142,12 +136,9 @@ enum PushRegistrationStatus {
// happen when a subscription is invalidated by the push service.
SUCCESS_NEW_SUBSCRIPTION_FROM_PUSH_SERVICE = 16,
- // NOTE: Do not renumber these as that would confuse interpretation of
- // previously logged data. When making changes, also update the enum list
- // in tools/metrics/histograms/histograms.xml to keep it in sync, and
- // update LAST below.
-
- LAST = SUCCESS_NEW_SUBSCRIPTION_FROM_PUSH_SERVICE
+ // NOTE: Do not renumber or delete these as that would confuse interpretation
+ // of previously logged data. When making changes, also update the enum list
+ // in tools/metrics/histograms/histograms.xml to keep it in sync.
};
// Push unregistration reason for reporting in UMA. Enum values can be added,
@@ -187,12 +178,9 @@ enum PushUnregistrationReason {
// The Service Worker database got wiped, most likely due to corruption.
SERVICE_WORKER_DATABASE_WIPED = 10,
- // NOTE: Do not renumber these as that would confuse interpretation of
- // previously logged data. When making changes, also update the enum list
- // in tools/metrics/histograms/histograms.xml to keep it in sync, and
- // update LAST below.
-
- LAST = SERVICE_WORKER_DATABASE_WIPED
+ // NOTE: Do not renumber or delete these as that would confuse interpretation
+ // of previously logged data. When making changes, also update the enum list
+ // in tools/metrics/histograms/histograms.xml to keep it in sync.
};
@@ -225,12 +213,9 @@ enum PushUnregistrationStatus {
// Unregistration failed due to a network error.
NETWORK_ERROR = 7,
- // NOTE: Do not renumber these as that would confuse interpretation of
- // previously logged data. When making changes, also update the enum list
- // in tools/metrics/histograms/histograms.xml to keep it in sync, and
- // update LAST below.
-
- LAST = NETWORK_ERROR
+ // NOTE: Do not renumber or delete these as that would confuse interpretation
+ // of previously logged data. When making changes, also update the enum list
+ // in tools/metrics/histograms/histograms.xml to keep it in sync.
};
// Push message user visible tracking for reporting in UMA. Enum values can be
@@ -253,10 +238,7 @@ enum PushUserVisibleStatus {
// has run out of grace, so we had to show the user a generic notification.
REQUIRED_BUT_NOT_SHOWN_GRACE_EXCEEDED = 4,
- // NOTE: Do not renumber these as that would confuse interpretation of
- // previously logged data. When making changes, also update the enum list
- // in tools/metrics/histograms/histograms.xml to keep it in sync, and
- // update LAST below.
-
- LAST = REQUIRED_BUT_NOT_SHOWN_GRACE_EXCEEDED
+ // NOTE: Do not renumber or delete these as that would confuse interpretation
+ // of previously logged data. When making changes, also update the enum list
+ // in tools/metrics/histograms/histograms.xml to keep it in sync.
};
diff --git a/chromium/content/public/common/referrer.h b/chromium/content/public/common/referrer.h
index 184551a2a73..c3199ca5b13 100644
--- a/chromium/content/public/common/referrer.h
+++ b/chromium/content/public/common/referrer.h
@@ -8,7 +8,7 @@
#include "base/logging.h"
#include "content/common/content_export.h"
#include "net/url_request/url_request.h"
-#include "third_party/WebKit/public/platform/WebReferrerPolicy.h"
+#include "third_party/blink/public/platform/web_referrer_policy.h"
#include "url/gurl.h"
namespace content {
diff --git a/chromium/content/public/common/referrer.typemap b/chromium/content/public/common/referrer.typemap
index 7c6703cde0e..2edceadd64c 100644
--- a/chromium/content/public/common/referrer.typemap
+++ b/chromium/content/public/common/referrer.typemap
@@ -2,7 +2,7 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
-mojom = "//third_party/WebKit/public/platform/referrer.mojom"
+mojom = "//third_party/blink/public/platform/referrer.mojom"
public_headers = [ "//content/public/common/referrer.h" ]
traits_headers = [ "//content/public/common/referrer_struct_traits.h" ]
sources = [
diff --git a/chromium/content/public/common/referrer_struct_traits.h b/chromium/content/public/common/referrer_struct_traits.h
index 142aaee5057..a84b0594176 100644
--- a/chromium/content/public/common/referrer_struct_traits.h
+++ b/chromium/content/public/common/referrer_struct_traits.h
@@ -7,8 +7,8 @@
#include "content/common/content_export.h"
#include "content/public/common/referrer.h"
-#include "third_party/WebKit/public/platform/ReferrerPolicyEnumTraits.h"
-#include "third_party/WebKit/public/platform/referrer.mojom.h"
+#include "third_party/blink/public/platform/referrer.mojom.h"
+#include "third_party/blink/public/platform/referrer_policy_enum_traits.h"
namespace mojo {
diff --git a/chromium/content/public/common/resource_load_info.mojom b/chromium/content/public/common/resource_load_info.mojom
new file mode 100644
index 00000000000..c6926fdacaa
--- /dev/null
+++ b/chromium/content/public/common/resource_load_info.mojom
@@ -0,0 +1,51 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+module content.mojom;
+
+import "content/public/common/resource_type.mojom";
+import "mojo/public/mojom/base/time.mojom";
+import "net/interfaces/ip_address.mojom";
+import "url/mojom/url.mojom";
+
+// Information pertaining to resource loading.
+// This will be passed to ResourceResponse callback methods.
+struct ResourceLoadInfo {
+ // An ID that uniquely identifies this request.
+ int64 request_id;
+
+ // The URL of the response.
+ url.mojom.Url url;
+
+ // The response referrer.
+ url.mojom.Url referrer;
+
+ // The original URL is the URL used to initialize the subresource request, and
+ // it may differ from |url| if the request was redirected.
+ url.mojom.Url original_url;
+
+ // The request method used to fetch this response.
+ string method;
+
+ // The resource type.
+ ResourceType resource_type;
+
+ // The mime type.
+ string mime_type;
+
+ // The host IP.
+ net.interfaces.IPAddress? ip;
+
+ // True if the response was fetched from the network cache.
+ bool was_cached;
+
+ // True if the request accessed the network in the process of retrieving data.
+ bool network_accessed;
+
+ // The network error code, net::OK if no error happened.
+ int32 net_error;
+
+ // The time at which the request was started.
+ mojo_base.mojom.TimeTicks request_start;
+};
diff --git a/chromium/content/public/common/resource_usage_reporter_type_converters.h b/chromium/content/public/common/resource_usage_reporter_type_converters.h
index 2d32d599bc6..fd84192072e 100644
--- a/chromium/content/public/common/resource_usage_reporter_type_converters.h
+++ b/chromium/content/public/common/resource_usage_reporter_type_converters.h
@@ -8,7 +8,7 @@
#include "content/common/content_export.h"
#include "content/public/common/resource_usage_reporter.mojom.h"
#include "mojo/public/cpp/bindings/type_converter.h"
-#include "third_party/WebKit/public/platform/WebCache.h"
+#include "third_party/blink/public/platform/web_cache.h"
namespace mojo {
diff --git a/chromium/content/public/common/sandbox_init.h b/chromium/content/public/common/sandbox_init.h
index b05b0332b9c..55041eaa4d2 100644
--- a/chromium/content/public/common/sandbox_init.h
+++ b/chromium/content/public/common/sandbox_init.h
@@ -19,7 +19,6 @@
namespace base {
class CommandLine;
-class FilePath;
}
namespace sandbox {
@@ -65,8 +64,8 @@ CONTENT_EXPORT sandbox::ResultCode StartSandboxedProcess(
// Returns true if the sandbox was initialized succesfully, false if an error
// occurred. If process_type isn't one that needs sandboxing, no action is
// taken and true is always returned.
-CONTENT_EXPORT bool InitializeSandbox(service_manager::SandboxType sandbox_type,
- const base::FilePath& allowed_path);
+CONTENT_EXPORT bool InitializeSandbox(
+ service_manager::SandboxType sandbox_type);
// Initialize the sandbox for renderer, gpu, utility, worker, and plugin
// processes, depending on the command line flags. For the browser process which
diff --git a/chromium/content/public/common/sandboxed_process_launcher_delegate.cc b/chromium/content/public/common/sandboxed_process_launcher_delegate.cc
index b7e61e5ed0c..2574f49e44b 100644
--- a/chromium/content/public/common/sandboxed_process_launcher_delegate.cc
+++ b/chromium/content/public/common/sandboxed_process_launcher_delegate.cc
@@ -5,7 +5,7 @@
#include "content/public/common/sandboxed_process_launcher_delegate.h"
#include "build/build_config.h"
-#include "content/public/common/zygote_features.h"
+#include "content/public/common/zygote_buildflags.h"
#if BUILDFLAG(USE_ZYGOTE_HANDLE)
#include "content/public/common/zygote_handle.h"
diff --git a/chromium/content/public/common/sandboxed_process_launcher_delegate.h b/chromium/content/public/common/sandboxed_process_launcher_delegate.h
index 6af3c287438..80043c88767 100644
--- a/chromium/content/public/common/sandboxed_process_launcher_delegate.h
+++ b/chromium/content/public/common/sandboxed_process_launcher_delegate.h
@@ -10,7 +10,7 @@
#include "base/process/process.h"
#include "build/build_config.h"
#include "content/common/content_export.h"
-#include "content/public/common/zygote_features.h"
+#include "content/public/common/zygote_buildflags.h"
#include "services/service_manager/sandbox/sandbox_delegate.h"
#include "services/service_manager/sandbox/sandbox_type.h"
diff --git a/chromium/content/public/common/shared_url_loader_factory.cc b/chromium/content/public/common/shared_url_loader_factory.cc
deleted file mode 100644
index 194e3281526..00000000000
--- a/chromium/content/public/common/shared_url_loader_factory.cc
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/public/common/shared_url_loader_factory.h"
-
-namespace content {
-
-// static
-scoped_refptr<SharedURLLoaderFactory> SharedURLLoaderFactory::Create(
- std::unique_ptr<SharedURLLoaderFactoryInfo> info) {
- return info->CreateFactory();
-}
-
-SharedURLLoaderFactory::~SharedURLLoaderFactory() = default;
-
-void SharedURLLoaderFactory::Clone(
- network::mojom::URLLoaderFactoryRequest request) {
- NOTREACHED() << "Don't call SharedURLLoaderFactory Clone method from "
- "URLLoaderFactory interface as that the loses type safety "
- "that SharedURLLoaderFactory gives. Instead call Clone().";
-}
-
-SharedURLLoaderFactoryInfo::SharedURLLoaderFactoryInfo() = default;
-
-SharedURLLoaderFactoryInfo::~SharedURLLoaderFactoryInfo() = default;
-
-} // namespace content
diff --git a/chromium/content/public/common/shared_url_loader_factory.h b/chromium/content/public/common/shared_url_loader_factory.h
deleted file mode 100644
index e987b173e02..00000000000
--- a/chromium/content/public/common/shared_url_loader_factory.h
+++ /dev/null
@@ -1,68 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_PUBLIC_COMMON_SHARED_URL_LOADER_FACTORY_H_
-#define CONTENT_PUBLIC_COMMON_SHARED_URL_LOADER_FACTORY_H_
-
-#include <memory>
-
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "content/common/content_export.h"
-#include "net/traffic_annotation/network_traffic_annotation.h"
-#include "services/network/public/cpp/resource_request.h"
-#include "services/network/public/mojom/url_loader_factory.mojom.h"
-
-namespace content {
-
-class SharedURLLoaderFactoryInfo;
-
-// This is a ref-counted C++ interface to replace raw mojom::URLLoaderFactory
-// pointers and various factory getters.
-// A SharedURLLoaderFactory instance is supposed to be used on a single
-// sequence. To use it on a different sequence, use Clone() and pass the
-// resulting SharedURLLoaderFactoryInfo instance to the target sequence. On the
-// target sequence, call SharedURLLoaderFactory::Create() to convert the info
-// instance to a new SharedURLLoaderFactory.
-class CONTENT_EXPORT SharedURLLoaderFactory
- : public base::RefCounted<SharedURLLoaderFactory>,
- public network::mojom::URLLoaderFactory {
- public:
- static scoped_refptr<SharedURLLoaderFactory> Create(
- std::unique_ptr<SharedURLLoaderFactoryInfo> info);
-
- // network::mojom::URLLoaderFactory
- void Clone(network::mojom::URLLoaderFactoryRequest request) final;
-
- virtual std::unique_ptr<SharedURLLoaderFactoryInfo> Clone() = 0;
-
- protected:
- friend class base::RefCounted<SharedURLLoaderFactory>;
- ~SharedURLLoaderFactory() override;
-};
-
-// SharedURLLoaderFactoryInfo contains necessary information to construct a
-// SharedURLLoaderFactory. It is not sequence safe but can be passed across
-// sequences. Please see the comments of SharedURLLoaderFactory for how this
-// class is used.
-class CONTENT_EXPORT SharedURLLoaderFactoryInfo {
- public:
- SharedURLLoaderFactoryInfo();
- virtual ~SharedURLLoaderFactoryInfo();
-
- protected:
- friend class SharedURLLoaderFactory;
-
- // Creates a SharedURLLoaderFactory. It should only be called by
- // SharedURLLoaderFactory::Create(), which makes sense that CreateFactory() is
- // never called multiple times for each SharedURLLoaderFactoryInfo instance.
- virtual scoped_refptr<SharedURLLoaderFactory> CreateFactory() = 0;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(SharedURLLoaderFactoryInfo);
-};
-
-} // namespace content
-
-#endif // CONTENT_PUBLIC_COMMON_SHARED_URL_LOADER_FACTORY_H_
diff --git a/chromium/content/public/common/storage_quota_params.h b/chromium/content/public/common/storage_quota_params.h
index 0f48ec81e36..2cad3dc0146 100644
--- a/chromium/content/public/common/storage_quota_params.h
+++ b/chromium/content/public/common/storage_quota_params.h
@@ -9,7 +9,7 @@
#include "content/common/content_export.h"
#include "ipc/ipc_message.h"
-#include "third_party/WebKit/public/mojom/quota/quota_types.mojom.h"
+#include "third_party/blink/public/mojom/quota/quota_types.mojom.h"
#include "url/gurl.h"
namespace content {
diff --git a/chromium/content/public/common/transferrable_url_loader.mojom b/chromium/content/public/common/transferrable_url_loader.mojom
new file mode 100644
index 00000000000..ce53a098ea5
--- /dev/null
+++ b/chromium/content/public/common/transferrable_url_loader.mojom
@@ -0,0 +1,17 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+module content.mojom;
+
+import "services/network/public/mojom/url_loader.mojom";
+import "url/mojom/url.mojom";
+
+// Used to transfer a URLLoader when after OnReceiveResponse() has been called
+// on the URLLoaderClient.
+struct TransferrableURLLoader {
+ url.mojom.Url url;
+ network.mojom.URLLoader url_loader;
+ network.mojom.URLLoaderClient& url_loader_client;
+ network.mojom.URLResponseHead head;
+};
diff --git a/chromium/content/public/common/url_constants.cc b/chromium/content/public/common/url_constants.cc
index 4bfbb922a1d..ece77d53898 100644
--- a/chromium/content/public/common/url_constants.cc
+++ b/chromium/content/public/common/url_constants.cc
@@ -57,15 +57,19 @@ const char kChromeUIPpapiFlashHangURL[] = "chrome://ppapiflashhang/";
#if defined(OS_ANDROID)
const char kChromeUIGpuJavaCrashURL[] = "chrome://gpu-java-crash/";
#endif
-#if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
+#if defined(ADDRESS_SANITIZER)
const char kChromeUICrashHeapOverflowURL[] = "chrome://crash/heap-overflow";
const char kChromeUICrashHeapUnderflowURL[] = "chrome://crash/heap-underflow";
const char kChromeUICrashUseAfterFreeURL[] = "chrome://crash/use-after-free";
-#endif
-#if defined(SYZYASAN)
+
+#if defined(OS_WIN)
const char kChromeUICrashCorruptHeapBlockURL[] =
"chrome://crash/corrupt-heap-block";
const char kChromeUICrashCorruptHeapURL[] = "chrome://crash/corrupt-heap";
+#endif // OS_WIN
+#endif // ADDRESS_SANITIZER
+
+#if DCHECK_IS_ON()
const char kChromeUICrashDcheckURL[] = "chrome://crash/dcheck";
#endif
diff --git a/chromium/content/public/common/url_constants.h b/chromium/content/public/common/url_constants.h
index f51416fb103..67009beda0d 100644
--- a/chromium/content/public/common/url_constants.h
+++ b/chromium/content/public/common/url_constants.h
@@ -5,6 +5,7 @@
#ifndef CONTENT_PUBLIC_COMMON_URL_CONSTANTS_H_
#define CONTENT_PUBLIC_COMMON_URL_CONSTANTS_H_
+#include "base/logging.h"
#include "build/build_config.h"
#include "content/common/content_export.h"
#include "url/url_constants.h"
@@ -66,14 +67,17 @@ CONTENT_EXPORT extern const char kChromeUIPpapiFlashHangURL[];
#if defined(OS_ANDROID)
CONTENT_EXPORT extern const char kChromeUIGpuJavaCrashURL[];
#endif
-#if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
+#if defined(ADDRESS_SANITIZER)
CONTENT_EXPORT extern const char kChromeUICrashHeapOverflowURL[];
CONTENT_EXPORT extern const char kChromeUICrashHeapUnderflowURL[];
CONTENT_EXPORT extern const char kChromeUICrashUseAfterFreeURL[];
-#endif
-#if defined(SYZYASAN)
+#if defined(OS_WIN)
CONTENT_EXPORT extern const char kChromeUICrashCorruptHeapBlockURL[];
CONTENT_EXPORT extern const char kChromeUICrashCorruptHeapURL[];
+#endif // OS_WIN
+#endif // ADDRESS_SANITIZER
+
+#if DCHECK_IS_ON()
CONTENT_EXPORT extern const char kChromeUICrashDcheckURL[];
#endif
diff --git a/chromium/content/public/common/url_loader_throttle.cc b/chromium/content/public/common/url_loader_throttle.cc
index af525cc1e6e..b2743344720 100644
--- a/chromium/content/public/common/url_loader_throttle.cc
+++ b/chromium/content/public/common/url_loader_throttle.cc
@@ -12,6 +12,14 @@ void URLLoaderThrottle::Delegate::SetPriority(net::RequestPriority priority) {}
void URLLoaderThrottle::Delegate::PauseReadingBodyFromNet() {}
void URLLoaderThrottle::Delegate::ResumeReadingBodyFromNet() {}
+void URLLoaderThrottle::Delegate::InterceptResponse(
+ network::mojom::URLLoaderPtr new_loader,
+ network::mojom::URLLoaderClientRequest new_client_request,
+ network::mojom::URLLoaderPtr* original_loader,
+ network::mojom::URLLoaderClientRequest* original_client_request) {
+ NOTIMPLEMENTED();
+}
+
URLLoaderThrottle::Delegate::~Delegate() {}
URLLoaderThrottle::~URLLoaderThrottle() {}
diff --git a/chromium/content/public/common/url_loader_throttle.h b/chromium/content/public/common/url_loader_throttle.h
index 7fd342a00c6..73a1ae2d0a6 100644
--- a/chromium/content/public/common/url_loader_throttle.h
+++ b/chromium/content/public/common/url_loader_throttle.h
@@ -8,6 +8,7 @@
#include "base/strings/string_piece.h"
#include "content/common/content_export.h"
#include "content/public/common/resource_type.h"
+#include "content/public/common/transferrable_url_loader.mojom.h"
#include "net/base/request_priority.h"
class GURL;
@@ -58,6 +59,14 @@ class CONTENT_EXPORT URLLoaderThrottle {
virtual void PauseReadingBodyFromNet();
virtual void ResumeReadingBodyFromNet();
+ // Replaces the URLLoader and URLLoaderClient endpoints held by the
+ // ThrottlingURLLoader instance.
+ virtual void InterceptResponse(
+ network::mojom::URLLoaderPtr new_loader,
+ network::mojom::URLLoaderClientRequest new_client_request,
+ network::mojom::URLLoaderPtr* original_loader,
+ network::mojom::URLLoaderClientRequest* original_client_request);
+
protected:
virtual ~Delegate();
};
diff --git a/chromium/content/public/common/url_utils.cc b/chromium/content/public/common/url_utils.cc
index 7954cfe66cb..e14b5d9c7d6 100644
--- a/chromium/content/public/common/url_utils.cc
+++ b/chromium/content/public/common/url_utils.cc
@@ -4,6 +4,7 @@
#include "content/public/common/url_utils.h"
+#include "base/logging.h"
#include "build/build_config.h"
#include "content/common/url_schemes.h"
#include "content/public/common/browser_side_navigation_policy.h"
@@ -81,7 +82,7 @@ bool IsRendererDebugURL(const GURL& url) {
return true;
}
-#if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
+#if defined(ADDRESS_SANITIZER)
if (url == kChromeUICrashHeapOverflowURL ||
url == kChromeUICrashHeapUnderflowURL ||
url == kChromeUICrashUseAfterFreeURL) {
@@ -89,9 +90,14 @@ bool IsRendererDebugURL(const GURL& url) {
}
#endif
-#if defined(SYZYASAN)
+#if DCHECK_IS_ON()
+ if (url == kChromeUICrashDcheckURL)
+ return true;
+#endif
+
+#if defined(OS_WIN) && defined(ADDRESS_SANITIZER)
if (url == kChromeUICrashCorruptHeapBlockURL ||
- url == kChromeUICrashCorruptHeapURL || url == kChromeUICrashDcheckURL) {
+ url == kChromeUICrashCorruptHeapURL) {
return true;
}
#endif
diff --git a/chromium/content/common/weak_wrapper_shared_url_loader_factory.cc b/chromium/content/public/common/weak_wrapper_shared_url_loader_factory.cc
index c53bddcf5d5..bd99c1e1914 100644
--- a/chromium/content/common/weak_wrapper_shared_url_loader_factory.cc
+++ b/chromium/content/public/common/weak_wrapper_shared_url_loader_factory.cc
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "content/common/weak_wrapper_shared_url_loader_factory.h"
+#include "content/public/common/weak_wrapper_shared_url_loader_factory.h"
#include "content/common/wrapper_shared_url_loader_factory.h"
#include "mojo/public/cpp/bindings/interface_request.h"
@@ -32,7 +32,7 @@ void WeakWrapperSharedURLLoaderFactory::CreateLoaderAndStart(
traffic_annotation);
}
-std::unique_ptr<SharedURLLoaderFactoryInfo>
+std::unique_ptr<network::SharedURLLoaderFactoryInfo>
WeakWrapperSharedURLLoaderFactory::Clone() {
network::mojom::URLLoaderFactoryPtrInfo factory_ptr_info;
if (factory_ptr_)
diff --git a/chromium/content/common/weak_wrapper_shared_url_loader_factory.h b/chromium/content/public/common/weak_wrapper_shared_url_loader_factory.h
index 37d7dc9c49b..0bbf213f914 100644
--- a/chromium/content/common/weak_wrapper_shared_url_loader_factory.h
+++ b/chromium/content/public/common/weak_wrapper_shared_url_loader_factory.h
@@ -2,11 +2,11 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef CONTENT_COMMON_WEAK_WRAPPER_SHARED_URL_LOADER_FACTORY_H_
-#define CONTENT_COMMON_WEAK_WRAPPER_SHARED_URL_LOADER_FACTORY_H_
+#ifndef CONTENT_PUBLIC_COMMON_WEAK_WRAPPER_SHARED_URL_LOADER_FACTORY_H_
+#define CONTENT_PUBLIC_COMMON_WEAK_WRAPPER_SHARED_URL_LOADER_FACTORY_H_
#include "content/common/content_export.h"
-#include "content/public/common/shared_url_loader_factory.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
namespace content {
@@ -14,7 +14,7 @@ namespace content {
// A SharedURLLoaderFactory implementation that wraps a raw
// mojom::URLLoaderFactory pointer.
class CONTENT_EXPORT WeakWrapperSharedURLLoaderFactory
- : public SharedURLLoaderFactory {
+ : public network::SharedURLLoaderFactory {
public:
explicit WeakWrapperSharedURLLoaderFactory(
network::mojom::URLLoaderFactory* factory_ptr);
@@ -33,7 +33,7 @@ class CONTENT_EXPORT WeakWrapperSharedURLLoaderFactory
const net::MutableNetworkTrafficAnnotationTag&
traffic_annotation) override;
- std::unique_ptr<SharedURLLoaderFactoryInfo> Clone() override;
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo> Clone() override;
private:
~WeakWrapperSharedURLLoaderFactory() override;
@@ -44,4 +44,4 @@ class CONTENT_EXPORT WeakWrapperSharedURLLoaderFactory
} // namespace content
-#endif // CONTENT_COMMON_WEAK_WRAPPER_URL_LOADER_FACTORY_H_
+#endif // CONTENT_PUBLIC_COMMON_WEAK_WRAPPER_SHARED_URL_LOADER_FACTORY_H_
diff --git a/chromium/content/public/common/web_preferences.cc b/chromium/content/public/common/web_preferences.cc
index e147056305c..53bc2c0a971 100644
--- a/chromium/content/public/common/web_preferences.cc
+++ b/chromium/content/public/common/web_preferences.cc
@@ -7,7 +7,7 @@
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
-#include "third_party/WebKit/public/web/WebSettings.h"
+#include "third_party/blink/public/web/web_settings.h"
using blink::WebSettings;
@@ -30,7 +30,12 @@ STATIC_ASSERT_ENUM(V8_CACHE_OPTIONS_DEFAULT,
WebSettings::kV8CacheOptionsDefault);
STATIC_ASSERT_ENUM(V8_CACHE_OPTIONS_NONE, WebSettings::kV8CacheOptionsNone);
STATIC_ASSERT_ENUM(V8_CACHE_OPTIONS_CODE, WebSettings::kV8CacheOptionsCode);
-STATIC_ASSERT_ENUM(V8_CACHE_OPTIONS_LAST, WebSettings::kV8CacheOptionsCode);
+STATIC_ASSERT_ENUM(V8_CACHE_OPTIONS_CODE_WITHOUT_HEAT_CHECK,
+ WebSettings::kV8CacheOptionsCodeWithoutHeatCheck);
+STATIC_ASSERT_ENUM(V8_CACHE_OPTIONS_FULLCODE_WITHOUT_HEAT_CHECK,
+ WebSettings::kV8CacheOptionsFullCodeWithoutHeatCheck);
+STATIC_ASSERT_ENUM(V8_CACHE_OPTIONS_LAST,
+ WebSettings::kV8CacheOptionsFullCodeWithoutHeatCheck);
STATIC_ASSERT_ENUM(SavePreviousDocumentResources::NEVER,
WebSettings::SavePreviousDocumentResources::kNever);
@@ -90,6 +95,7 @@ WebPreferences::WebPreferences()
application_cache_enabled(false),
tabs_to_links(true),
history_entry_requires_user_gesture(false),
+ disable_pushstate_throttle(false),
hyperlink_auditing_enabled(true),
allow_universal_access_from_file_urls(false),
allow_file_access_from_file_urls(false),
@@ -150,11 +156,13 @@ WebPreferences::WebPreferences()
shrinks_viewport_contents_to_fit(true),
viewport_style(ViewportStyle::MOBILE),
always_show_context_menu_on_touch(false),
+ smooth_scroll_for_find_enabled(true),
#else
viewport_meta_enabled(false),
shrinks_viewport_contents_to_fit(false),
viewport_style(ViewportStyle::DEFAULT),
always_show_context_menu_on_touch(true),
+ smooth_scroll_for_find_enabled(false),
#endif
main_frame_resizes_are_orientation_changes(false),
initialize_at_minimum_page_scale(true),
@@ -194,7 +202,7 @@ WebPreferences::WebPreferences()
clobber_user_agent_initial_scale_quirk(false),
ignore_main_frame_overflow_hidden_quirk(false),
report_screen_size_in_physical_pixels_quirk(false),
- resue_global_for_unowned_main_frame(false),
+ reuse_global_for_unowned_main_frame(false),
spellcheck_enabled_by_default(true),
video_fullscreen_orientation_lock_enabled(false),
video_rotate_to_fullscreen_enabled(false),
@@ -220,7 +228,8 @@ WebPreferences::WebPreferences()
media_controls_enabled(true),
do_not_update_selection_on_mutating_selection_range(false),
autoplay_policy(AutoplayPolicy::kDocumentUserActivationRequired),
- low_priority_iframes_threshold(net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN) {
+ low_priority_iframes_threshold(net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN),
+ picture_in_picture_enabled(false) {
standard_font_family_map[kCommonScript] =
base::ASCIIToUTF16("Times New Roman");
fixed_font_family_map[kCommonScript] = base::ASCIIToUTF16("Courier New");
diff --git a/chromium/content/public/common/web_preferences.h b/chromium/content/public/common/web_preferences.h
index 43606a755fa..e4fc39c60fd 100644
--- a/chromium/content/public/common/web_preferences.h
+++ b/chromium/content/public/common/web_preferences.h
@@ -40,7 +40,9 @@ enum V8CacheOptions {
V8_CACHE_OPTIONS_DEFAULT,
V8_CACHE_OPTIONS_NONE,
V8_CACHE_OPTIONS_CODE,
- V8_CACHE_OPTIONS_LAST = V8_CACHE_OPTIONS_CODE
+ V8_CACHE_OPTIONS_CODE_WITHOUT_HEAT_CHECK,
+ V8_CACHE_OPTIONS_FULLCODE_WITHOUT_HEAT_CHECK,
+ V8_CACHE_OPTIONS_LAST = V8_CACHE_OPTIONS_FULLCODE_WITHOUT_HEAT_CHECK
};
// ImageAnimationPolicy is used for controlling image animation
@@ -121,6 +123,7 @@ struct CONTENT_EXPORT WebPreferences {
bool application_cache_enabled;
bool tabs_to_links;
bool history_entry_requires_user_gesture;
+ bool disable_pushstate_throttle;
bool hyperlink_auditing_enabled;
bool allow_universal_access_from_file_urls;
bool allow_file_access_from_file_urls;
@@ -180,6 +183,7 @@ struct CONTENT_EXPORT WebPreferences {
bool shrinks_viewport_contents_to_fit;
ViewportStyle viewport_style;
bool always_show_context_menu_on_touch;
+ bool smooth_scroll_for_find_enabled;
bool main_frame_resizes_are_orientation_changes;
bool initialize_at_minimum_page_scale;
bool smart_insert_delete_enabled;
@@ -219,7 +223,6 @@ struct CONTENT_EXPORT WebPreferences {
bool force_enable_zoom;
bool fullscreen_supported;
bool double_tap_to_zoom_enabled;
- bool picture_in_picture_enabled;
std::string media_playback_gesture_whitelist_scope;
GURL default_video_poster_url;
bool support_deprecated_target_density_dpi;
@@ -236,7 +239,7 @@ struct CONTENT_EXPORT WebPreferences {
bool report_screen_size_in_physical_pixels_quirk;
// Used by Android_WebView only to support legacy apps that inject script into
// a top-level initial empty document and expect it to persist on navigation.
- bool resue_global_for_unowned_main_frame;
+ bool reuse_global_for_unowned_main_frame;
// Specifies default setting for spellcheck when the spellcheck attribute is
// not explicitly specified.
bool spellcheck_enabled_by_default;
@@ -290,6 +293,9 @@ struct CONTENT_EXPORT WebPreferences {
// lowest priority.
net::EffectiveConnectionType low_priority_iframes_threshold;
+ // Whether Picture-in-Picture is enabled.
+ bool picture_in_picture_enabled;
+
// We try to keep the default values the same as the default values in
// chrome, except for the cases where it would require lots of extra work for
// the embedder to use the same default value.
diff --git a/chromium/content/public/common/webplugininfo.cc b/chromium/content/public/common/webplugininfo.cc
index c984ff1734b..ee4439f3a32 100644
--- a/chromium/content/public/common/webplugininfo.cc
+++ b/chromium/content/public/common/webplugininfo.cc
@@ -36,28 +36,11 @@ WebPluginInfo::WebPluginInfo()
pepper_permissions(0) {
}
-WebPluginInfo::WebPluginInfo(const WebPluginInfo& rhs)
- : name(rhs.name),
- path(rhs.path),
- version(rhs.version),
- desc(rhs.desc),
- mime_types(rhs.mime_types),
- type(rhs.type),
- pepper_permissions(rhs.pepper_permissions) {
-}
+WebPluginInfo::WebPluginInfo(const WebPluginInfo& rhs) = default;
WebPluginInfo::~WebPluginInfo() {}
-WebPluginInfo& WebPluginInfo::operator=(const WebPluginInfo& rhs) {
- name = rhs.name;
- path = rhs.path;
- version = rhs.version;
- desc = rhs.desc;
- mime_types = rhs.mime_types;
- type = rhs.type;
- pepper_permissions = rhs.pepper_permissions;
- return *this;
-}
+WebPluginInfo& WebPluginInfo::operator=(const WebPluginInfo& rhs) = default;
WebPluginInfo::WebPluginInfo(const base::string16& fake_name,
const base::FilePath& fake_path,
diff --git a/chromium/content/public/common/webplugininfo.h b/chromium/content/public/common/webplugininfo.h
index e1560e5b086..2735b5d458f 100644
--- a/chromium/content/public/common/webplugininfo.h
+++ b/chromium/content/public/common/webplugininfo.h
@@ -12,6 +12,7 @@
#include "base/files/file_path.h"
#include "content/common/content_export.h"
+#include "third_party/skia/include/core/SkColor.h"
namespace base {
class Version;
@@ -57,6 +58,8 @@ struct CONTENT_EXPORT WebPluginInfo {
PLUGIN_TYPE_BROWSER_PLUGIN
};
+ static constexpr SkColor kDefaultBackgroundColor = SkColorSetRGB(38, 38, 38);
+
WebPluginInfo();
WebPluginInfo(const WebPluginInfo& rhs);
~WebPluginInfo();
@@ -98,6 +101,9 @@ struct CONTENT_EXPORT WebPluginInfo {
// When type is PLUGIN_TYPE_PEPPER_* this indicates the permission bits.
int32_t pepper_permissions;
+
+ // The color to use as the background before the plugin loads.
+ SkColor background_color = kDefaultBackgroundColor;
};
} // namespace content
diff --git a/chromium/content/public/common/webplugininfo.typemap b/chromium/content/public/common/webplugininfo.typemap
index 6083ceeab09..d08406027fd 100644
--- a/chromium/content/public/common/webplugininfo.typemap
+++ b/chromium/content/public/common/webplugininfo.typemap
@@ -7,6 +7,7 @@ public_headers = [ "//content/public/common/webplugininfo.h" ]
traits_headers = [ "//content/public/common/webplugininfo_param_traits.h" ]
public_deps = [
"//ipc",
+ "//skia",
]
type_mappings = [ "content.mojom.WebPluginInfo=content::WebPluginInfo" ]
diff --git a/chromium/content/public/common/webplugininfo_param_traits.h b/chromium/content/public/common/webplugininfo_param_traits.h
index 27182e84b28..85ebcee096e 100644
--- a/chromium/content/public/common/webplugininfo_param_traits.h
+++ b/chromium/content/public/common/webplugininfo_param_traits.h
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// Multiply included file.
+// no-include-guard-because-multiply-included
#include "content/public/common/webplugininfo.h"
#include "ipc/ipc_message_macros.h"
@@ -30,4 +30,5 @@ IPC_STRUCT_TRAITS_BEGIN(content::WebPluginInfo)
IPC_STRUCT_TRAITS_MEMBER(mime_types)
IPC_STRUCT_TRAITS_MEMBER(type)
IPC_STRUCT_TRAITS_MEMBER(pepper_permissions)
+ IPC_STRUCT_TRAITS_MEMBER(background_color)
IPC_STRUCT_TRAITS_END()
diff --git a/chromium/content/public/common/zygote_features.gni b/chromium/content/public/common/zygote_features.gni
index bab19f16de5..c7580b35ff3 100644
--- a/chromium/content/public/common/zygote_features.gni
+++ b/chromium/content/public/common/zygote_features.gni
@@ -2,4 +2,4 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
-use_zygote_handle = is_posix && !is_android && !is_mac && !is_fuchsia
+use_zygote_handle = is_posix && !is_android && !is_mac
diff --git a/chromium/content/public/common/zygote_handle.h b/chromium/content/public/common/zygote_handle.h
index dfa962881e2..5c21c883072 100644
--- a/chromium/content/public/common/zygote_handle.h
+++ b/chromium/content/public/common/zygote_handle.h
@@ -10,7 +10,7 @@
#include "base/files/scoped_file.h"
#include "build/build_config.h"
#include "content/common/content_export.h"
-#include "content/public/common/zygote_features.h"
+#include "content/public/common/zygote_buildflags.h"
#if !BUILDFLAG(USE_ZYGOTE_HANDLE)
#error "Can not use zygote handles without USE_ZYGOTE_HANDLE"
diff --git a/chromium/content/public/gpu/content_gpu_client.h b/chromium/content/public/gpu/content_gpu_client.h
index 9f3d75df33a..1fd10b0d0b0 100644
--- a/chromium/content/public/gpu/content_gpu_client.h
+++ b/chromium/content/public/gpu/content_gpu_client.h
@@ -11,7 +11,7 @@
#include "base/metrics/field_trial.h"
#include "base/single_thread_task_runner.h"
#include "content/public/common/content_client.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "services/service_manager/public/cpp/binder_registry.h"
namespace gpu {
@@ -42,9 +42,11 @@ class CONTENT_EXPORT ContentGpuClient {
virtual void GpuServiceInitialized(
const gpu::GpuPreferences& gpu_preferences) {}
- // Called right after the IO thread is created.
+ // Called right after the IO/compositor thread is created.
virtual void PostIOThreadCreated(
base::SingleThreadTaskRunner* io_task_runner) {}
+ virtual void PostCompositorThreadCreated(
+ base::SingleThreadTaskRunner* task_runner) {}
// Allows client to supply a SyncPointManager instance instead of having
// content internally create one.
diff --git a/chromium/content/public/renderer/BUILD.gn b/chromium/content/public/renderer/BUILD.gn
index 1094933ab06..004fc2e6fa3 100644
--- a/chromium/content/public/renderer/BUILD.gn
+++ b/chromium/content/public/renderer/BUILD.gn
@@ -5,7 +5,7 @@
import("//build/config/features.gni")
import("//build/config/jumbo.gni")
import("//media/media_options.gni")
-import("//ppapi/features/features.gni")
+import("//ppapi/buildflags/buildflags.gni")
# See //content/BUILD.gn for how this works.
group("renderer") {
@@ -91,10 +91,10 @@ target(link_target_type, "renderer_sources") {
"//media/capture",
"//media/gpu/ipc/client",
"//net",
+ "//ppapi/buildflags",
"//ppapi/c",
- "//ppapi/features",
"//skia",
- "//third_party/WebKit/public:blink_headers",
+ "//third_party/blink/public:blink_headers",
"//third_party/widevine/cdm:headers",
"//ui/base",
"//ui/base/ime",
@@ -128,8 +128,8 @@ target(link_target_type, "renderer_sources") {
"webrtc_log_message_delegate.h",
]
deps += [
+ "//content/public/common:buildflags",
"//content/public/common:feature_h264_with_openh264_ffmpeg",
- "//content/public/common:features",
"//third_party/webrtc_overrides",
]
}
diff --git a/chromium/content/public/renderer/associated_resource_fetcher.h b/chromium/content/public/renderer/associated_resource_fetcher.h
index 1da76660298..a8be013563e 100644
--- a/chromium/content/public/renderer/associated_resource_fetcher.h
+++ b/chromium/content/public/renderer/associated_resource_fetcher.h
@@ -9,8 +9,8 @@
#include "base/callback.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebURLRequest.h"
-#include "third_party/WebKit/public/platform/modules/fetch/fetch_api_request.mojom.h"
+#include "third_party/blink/public/platform/modules/fetch/fetch_api_request.mojom.h"
+#include "third_party/blink/public/platform/web_url_request.h"
class GURL;
diff --git a/chromium/content/public/renderer/content_renderer_client.cc b/chromium/content/public/renderer/content_renderer_client.cc
index f70362c1961..5bfd2922492 100644
--- a/chromium/content/public/renderer/content_renderer_client.cc
+++ b/chromium/content/public/renderer/content_renderer_client.cc
@@ -6,12 +6,12 @@
#include "content/public/renderer/media_stream_renderer_factory.h"
#include "media/base/renderer_factory.h"
-#include "third_party/WebKit/public/platform/WebAudioDevice.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamCenter.h"
-#include "third_party/WebKit/public/platform/WebRTCPeerConnectionHandler.h"
-#include "third_party/WebKit/public/platform/WebSocketHandshakeThrottle.h"
-#include "third_party/WebKit/public/platform/WebSpeechSynthesizer.h"
-#include "third_party/WebKit/public/platform/modules/webmidi/WebMIDIAccessor.h"
+#include "third_party/blink/public/platform/modules/webmidi/web_midi_accessor.h"
+#include "third_party/blink/public/platform/web_audio_device.h"
+#include "third_party/blink/public/platform/web_media_stream_center.h"
+#include "third_party/blink/public/platform/web_rtc_peer_connection_handler.h"
+#include "third_party/blink/public/platform/web_socket_handshake_throttle.h"
+#include "third_party/blink/public/platform/web_speech_synthesizer.h"
#include "ui/gfx/icc_profile.h"
#include "url/gurl.h"
@@ -89,6 +89,9 @@ ContentRendererClient::OverrideSpeechSynthesizer(
return nullptr;
}
+void ContentRendererClient::PostIOThreadCreated(
+ base::SingleThreadTaskRunner* io_thread_task_runner) {}
+
void ContentRendererClient::PostCompositorThreadCreated(
base::SingleThreadTaskRunner* compositor_thread_task_runner) {}
@@ -131,13 +134,12 @@ bool ContentRendererClient::ShouldFork(blink::WebLocalFrame* frame,
return false;
}
-bool ContentRendererClient::WillSendRequest(
- blink::WebLocalFrame* frame,
- ui::PageTransition transition_type,
- const blink::WebURL& url,
- GURL* new_url) {
- return false;
-}
+void ContentRendererClient::WillSendRequest(blink::WebLocalFrame* frame,
+ ui::PageTransition transition_type,
+ const blink::WebURL& url,
+ const url::Origin* initiator_origin,
+ GURL* new_url,
+ bool* attach_same_site_cookies) {}
bool ContentRendererClient::IsPrefetchOnly(
RenderFrame* render_frame,
@@ -170,6 +172,11 @@ bool ContentRendererClient::IsExternalPepperPlugin(
return false;
}
+bool ContentRendererClient::IsOriginIsolatedPepperPlugin(
+ const base::FilePath& plugin_path) {
+ return false;
+}
+
bool ContentRendererClient::AllowPepperMediaStreamAPI(const GURL& url) {
return false;
}
@@ -208,10 +215,6 @@ bool ContentRendererClient::ShouldReportDetailedMessageForSource(
return false;
}
-bool ContentRendererClient::ShouldGatherSiteIsolationStats() const {
- return true;
-}
-
std::unique_ptr<blink::WebContentSettingsClient>
ContentRendererClient::CreateWorkerContentSettingsClient(
RenderFrame* render_frame) {
@@ -233,6 +236,7 @@ bool ContentRendererClient::IsPluginAllowedToUseDevChannelAPIs() {
BrowserPluginDelegate* ContentRendererClient::CreateBrowserPluginDelegate(
RenderFrame* render_frame,
+ const WebPluginInfo& info,
const std::string& mime_type,
const GURL& original_url) {
return nullptr;
diff --git a/chromium/content/public/renderer/content_renderer_client.h b/chromium/content/public/renderer/content_renderer_client.h
index 34aed4fd356..a68f00aec37 100644
--- a/chromium/content/public/renderer/content_renderer_client.h
+++ b/chromium/content/public/renderer/content_renderer_client.h
@@ -13,6 +13,7 @@
#include <vector>
#include "base/callback_forward.h"
+#include "base/files/file_path.h"
#include "base/memory/ref_counted.h"
#include "base/strings/string16.h"
#include "base/task_scheduler/task_scheduler.h"
@@ -21,10 +22,10 @@
#include "content/public/renderer/url_loader_throttle_provider.h"
#include "media/base/decode_capabilities.h"
#include "services/service_manager/public/mojom/service.mojom.h"
-#include "third_party/WebKit/public/mojom/page/page_visibility_state.mojom.h"
-#include "third_party/WebKit/public/platform/WebContentSettingsClient.h"
-#include "third_party/WebKit/public/web/WebNavigationPolicy.h"
-#include "third_party/WebKit/public/web/WebNavigationType.h"
+#include "third_party/blink/public/mojom/page/page_visibility_state.mojom.h"
+#include "third_party/blink/public/platform/web_content_settings_client.h"
+#include "third_party/blink/public/web/web_navigation_policy.h"
+#include "third_party/blink/public/web/web_navigation_type.h"
#include "ui/base/page_transition_types.h"
#include "v8/include/v8.h"
@@ -33,6 +34,7 @@ class SkBitmap;
namespace base {
class FilePath;
+class SingleThreadTaskRunner;
}
namespace blink {
@@ -65,6 +67,7 @@ class BrowserPluginDelegate;
class MediaStreamRendererFactory;
class RenderFrame;
class RenderView;
+struct WebPluginInfo;
// Embedder API for participating in renderer logic.
class CONTENT_EXPORT ContentRendererClient {
@@ -106,6 +109,7 @@ class CONTENT_EXPORT ContentRendererClient {
// Creates a delegate for browser plugin.
virtual BrowserPluginDelegate* CreateBrowserPluginDelegate(
RenderFrame* render_frame,
+ const WebPluginInfo& info,
const std::string& mime_type,
const GURL& original_url);
@@ -143,6 +147,13 @@ class CONTENT_EXPORT ContentRendererClient {
std::string* error_html,
base::string16* error_description) {}
+ // Returns as |error_description| a brief description of the error that
+ // ocurred. The out parameter may be not written to in certain cases (lack of
+ // information on the error code)
+ virtual void GetErrorDescription(const blink::WebURLRequest& failed_request,
+ const blink::WebURLError& error,
+ base::string16* error_description) {}
+
// Allows the embedder to control when media resources are loaded. Embedders
// can run |closure| immediately if they don't wish to defer media resource
// loading. If |has_played_media_before| is true, the render frame has
@@ -179,6 +190,11 @@ class CONTENT_EXPORT ContentRendererClient {
virtual std::unique_ptr<blink::WebSpeechSynthesizer>
OverrideSpeechSynthesizer(blink::WebSpeechSynthesizerClient* client);
+ // Called on the main-thread immediately after the io thread is
+ // created.
+ virtual void PostIOThreadCreated(
+ base::SingleThreadTaskRunner* io_thread_task_runner);
+
// Called on the main-thread immediately after the compositor thread is
// created.
virtual void PostCompositorThreadCreated(
@@ -228,12 +244,18 @@ class CONTENT_EXPORT ContentRendererClient {
bool* send_referrer);
// Notifies the embedder that the given frame is requesting the resource at
- // |url|. If the function returns true, the url is changed to |new_url|.
- virtual bool WillSendRequest(
- blink::WebLocalFrame* frame,
- ui::PageTransition transition_type,
- const blink::WebURL& url,
- GURL* new_url);
+ // |url|. If the function returns a valid |new_url|, the request must be
+ // updated to use it. The |attach_same_site_cookies| output parameter
+ // determines whether SameSite cookies should be attached to the request.
+ // TODO(nasko): When moved over to Network Service, find a way to perform
+ // this check on the browser side, so untrusted renderer processes cannot
+ // influence whether SameSite cookies are attached.
+ virtual void WillSendRequest(blink::WebLocalFrame* frame,
+ ui::PageTransition transition_type,
+ const blink::WebURL& url,
+ const url::Origin* initiator_origin,
+ GURL* new_url,
+ bool* attach_same_site_cookies);
// Returns true if the request is associated with a document that is in
// ""prefetch only" mode, and will not be rendered.
@@ -253,6 +275,12 @@ class CONTENT_EXPORT ContentRendererClient {
// startup steps).
virtual bool IsExternalPepperPlugin(const std::string& module_name);
+ // Returns true if the given Pepper plugin should process content from
+ // different origins in different PPAPI processes. This is generally a
+ // worthwhile precaution when the plugin provides an active scripting
+ // language.
+ virtual bool IsOriginIsolatedPepperPlugin(const base::FilePath& plugin_path);
+
// Returns true if the page at |url| can use Pepper MediaStream APIs.
virtual bool AllowPepperMediaStreamAPI(const GURL& url);
@@ -286,11 +314,6 @@ class CONTENT_EXPORT ContentRendererClient {
virtual bool ShouldReportDetailedMessageForSource(
const base::string16& source) const;
- // Returns true if we should gather stats during resource loads as if the
- // cross-site document blocking policy were enabled. Does not actually block
- // any pages.
- virtual bool ShouldGatherSiteIsolationStats() const;
-
// Creates a permission client for in-renderer worker.
virtual std::unique_ptr<blink::WebContentSettingsClient>
CreateWorkerContentSettingsClient(RenderFrame* render_frame);
diff --git a/chromium/content/public/renderer/document_state.h b/chromium/content/public/renderer/document_state.h
index b4c5a38f354..b1548b97051 100644
--- a/chromium/content/public/renderer/document_state.h
+++ b/chromium/content/public/renderer/document_state.h
@@ -13,7 +13,7 @@
#include "base/time/time.h"
#include "content/common/content_export.h"
#include "net/http/http_response_info.h"
-#include "third_party/WebKit/public/web/WebDocumentLoader.h"
+#include "third_party/blink/public/web/web_document_loader.h"
#include "url/gurl.h"
namespace content {
diff --git a/chromium/content/public/renderer/media_stream_audio_sink.cc b/chromium/content/public/renderer/media_stream_audio_sink.cc
index 89453f1111d..059223cd881 100644
--- a/chromium/content/public/renderer/media_stream_audio_sink.cc
+++ b/chromium/content/public/renderer/media_stream_audio_sink.cc
@@ -6,8 +6,8 @@
#include "base/logging.h"
#include "content/renderer/media/stream/media_stream_audio_track.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
namespace content {
diff --git a/chromium/content/public/renderer/media_stream_sink.h b/chromium/content/public/renderer/media_stream_sink.h
index 04cba96b596..a9135e988e7 100644
--- a/chromium/content/public/renderer/media_stream_sink.h
+++ b/chromium/content/public/renderer/media_stream_sink.h
@@ -7,8 +7,8 @@
#include "base/compiler_specific.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
namespace content {
diff --git a/chromium/content/public/renderer/media_stream_utils.cc b/chromium/content/public/renderer/media_stream_utils.cc
index 6dff8386580..1aeea995d84 100644
--- a/chromium/content/public/renderer/media_stream_utils.cc
+++ b/chromium/content/public/renderer/media_stream_utils.cc
@@ -18,9 +18,9 @@
#include "content/renderer/media/stream/media_stream_video_track.h"
#include "media/base/audio_capturer_source.h"
#include "media/capture/video_capturer_source.h"
-#include "third_party/WebKit/public/platform/WebMediaStream.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
+#include "third_party/blink/public/platform/web_media_stream.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/web/web_media_stream_registry.h"
namespace content {
@@ -92,6 +92,8 @@ bool AddAudioTrackToMediaStream(
blink::WebMediaStreamSource::Capabilities capabilities;
capabilities.device_id = track_id;
capabilities.echo_cancellation = std::vector<bool>({false});
+ capabilities.auto_gain_control = std::vector<bool>({false});
+ capabilities.noise_suppression = std::vector<bool>({false});
web_media_stream_source.SetCapabilities(capabilities);
blink::WebMediaStreamTrack web_media_stream_track;
diff --git a/chromium/content/public/renderer/media_stream_video_sink.h b/chromium/content/public/renderer/media_stream_video_sink.h
index 4cb3271ea7a..7334b5d1d4a 100644
--- a/chromium/content/public/renderer/media_stream_video_sink.h
+++ b/chromium/content/public/renderer/media_stream_video_sink.h
@@ -13,7 +13,7 @@
#include "content/common/media/video_capture.h"
#include "content/public/renderer/media_stream_sink.h"
#include "media/capture/video_capturer_source.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
namespace content {
diff --git a/chromium/content/public/renderer/render_frame.h b/chromium/content/public/renderer/render_frame.h
index adbeb1a0bd5..b1c8604d292 100644
--- a/chromium/content/public/renderer/render_frame.h
+++ b/chromium/content/public/renderer/render_frame.h
@@ -17,13 +17,13 @@
#include "content/public/common/previews_state.h"
#include "ipc/ipc_listener.h"
#include "ipc/ipc_sender.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
#include "services/service_manager/public/cpp/binder_registry.h"
-#include "third_party/WebKit/public/mojom/page/page_visibility_state.mojom.h"
-#include "third_party/WebKit/public/platform/TaskType.h"
-#include "third_party/WebKit/public/web/WebNavigationPolicy.h"
-#include "third_party/WebKit/public/web/WebTriggeringEventInfo.h"
+#include "third_party/blink/public/mojom/page/page_visibility_state.mojom.h"
+#include "third_party/blink/public/platform/task_type.h"
+#include "third_party/blink/public/web/web_navigation_policy.h"
+#include "third_party/blink/public/web/web_triggering_event_info.h"
#include "ui/accessibility/ax_modes.h"
namespace blink {
@@ -40,6 +40,10 @@ class Range;
class Size;
}
+namespace network {
+class SharedURLLoaderFactory;
+}
+
namespace service_manager {
class InterfaceProvider;
}
@@ -54,7 +58,6 @@ class PluginInstanceThrottler;
class RenderAccessibility;
class RenderFrameVisitor;
class RenderView;
-class SharedURLLoaderFactory;
struct ContextMenuParams;
struct WebPluginInfo;
struct WebPreferences;
@@ -262,7 +265,8 @@ class CONTENT_EXPORT RenderFrame : public IPC::Listener,
// Set the accessibility mode to force creation of RenderAccessibility.
virtual void SetAccessibilityModeForTest(ui::AXMode new_mode) = 0;
- virtual scoped_refptr<SharedURLLoaderFactory> GetURLLoaderFactory() = 0;
+ virtual scoped_refptr<network::SharedURLLoaderFactory>
+ GetURLLoaderFactory() = 0;
protected:
~RenderFrame() override {}
diff --git a/chromium/content/public/renderer/render_frame_observer.h b/chromium/content/public/renderer/render_frame_observer.h
index aa77b86eee9..74a031ad10c 100644
--- a/chromium/content/public/renderer/render_frame_observer.h
+++ b/chromium/content/public/renderer/render_frame_observer.h
@@ -14,11 +14,11 @@
#include "ipc/ipc_listener.h"
#include "ipc/ipc_sender.h"
#include "mojo/public/cpp/system/message_pipe.h"
-#include "third_party/WebKit/public/platform/WebLoadingBehaviorFlag.h"
-#include "third_party/WebKit/public/platform/WebVector.h"
-#include "third_party/WebKit/public/platform/web_client_hints_types.mojom.h"
-#include "third_party/WebKit/public/platform/web_feature.mojom.h"
-#include "third_party/WebKit/public/web/WebMeaningfulLayout.h"
+#include "third_party/blink/public/platform/web_client_hints_types.mojom.h"
+#include "third_party/blink/public/platform/web_feature.mojom.h"
+#include "third_party/blink/public/platform/web_loading_behavior_flag.h"
+#include "third_party/blink/public/platform/web_vector.h"
+#include "third_party/blink/public/web/web_meaningful_layout.h"
#include "v8/include/v8.h"
namespace blink {
@@ -117,9 +117,11 @@ class CONTENT_EXPORT RenderFrameObserver : public IPC::Listener,
virtual void DidObserveLoadingBehavior(
blink::WebLoadingBehaviorFlag behavior) {}
- // Notification when the renderer observes a new feature usage during a page
- // load. This is used for UseCounter feature metrics.
+ // Notification when the renderer observes a new use counter usage during a
+ // page load. This is used for UseCounter metrics.
virtual void DidObserveNewFeatureUsage(blink::mojom::WebFeature feature) {}
+ virtual void DidObserveNewCssPropertyUsage(int css_property,
+ bool is_animated) {}
// Called when the focused node has changed to |node|.
virtual void FocusedNodeChanged(const blink::WebNode& node) {}
diff --git a/chromium/content/public/renderer/request_peer.h b/chromium/content/public/renderer/request_peer.h
index 74d267b68c3..3b8d3fa2983 100644
--- a/chromium/content/public/renderer/request_peer.h
+++ b/chromium/content/public/renderer/request_peer.h
@@ -11,6 +11,7 @@
#include <string>
#include "content/common/content_export.h"
+#include "mojo/public/cpp/system/data_pipe.h"
namespace net {
struct RedirectInfo;
@@ -69,6 +70,13 @@ class CONTENT_EXPORT RequestPeer {
virtual void OnReceivedResponse(
const network::ResourceResponseInfo& info) = 0;
+ // Called when the response body becomes available. This method is only called
+ // if |pass_response_pipe_to_peer| was set to true when calling StartAsync.
+ // TODO(mek): Deprecate OnReceivedData in favor of this method, and always use
+ // this codepath.
+ virtual void OnStartLoadingResponseBody(
+ mojo::ScopedDataPipeConsumerHandle body) = 0;
+
// Called when a chunk of response data is downloaded. This method may be
// called multiple times or not at all if an error occurs. This method is
// only called if RequestInfo::download_to_file was set to true, and in
diff --git a/chromium/content/public/renderer/resource_fetcher.h b/chromium/content/public/renderer/resource_fetcher.h
index 35579354fd7..aabd44a609b 100644
--- a/chromium/content/public/renderer/resource_fetcher.h
+++ b/chromium/content/public/renderer/resource_fetcher.h
@@ -10,8 +10,7 @@
#include "base/callback.h"
#include "content/common/content_export.h"
-#include "content/public/common/shared_url_loader_factory.h"
-#include "third_party/WebKit/public/platform/WebURLRequest.h"
+#include "third_party/blink/public/platform/web_url_request.h"
class GURL;
@@ -28,6 +27,10 @@ namespace net {
struct NetworkTrafficAnnotationTag;
}
+namespace network {
+class SharedURLLoaderFactory;
+}
+
namespace content {
// Interface to download resources asynchronously. Specified callback will be
@@ -62,7 +65,7 @@ class CONTENT_EXPORT ResourceFetcher {
virtual void Start(
blink::WebLocalFrame* frame,
blink::WebURLRequest::RequestContext request_context,
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory,
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
const net::NetworkTrafficAnnotationTag& annotation_tag,
Callback callback,
size_t maximum_download_size = kDefaultMaximumDownloadSize) = 0;
diff --git a/chromium/content/public/renderer/url_loader_throttle_provider.h b/chromium/content/public/renderer/url_loader_throttle_provider.h
index 342661b4094..07cdaa412d3 100644
--- a/chromium/content/public/renderer/url_loader_throttle_provider.h
+++ b/chromium/content/public/renderer/url_loader_throttle_provider.h
@@ -11,7 +11,7 @@
#include "content/common/content_export.h"
#include "content/public/common/resource_type.h"
#include "content/public/common/url_loader_throttle.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
+#include "third_party/blink/public/platform/web_url_request.h"
namespace content {
@@ -33,7 +33,7 @@ class CONTENT_EXPORT URLLoaderThrottleProvider {
// service workers, |render_frame_id| should be set to MSG_ROUTING_NONE.
virtual std::vector<std::unique_ptr<URLLoaderThrottle>> CreateThrottles(
int render_frame_id,
- const blink::WebURL& url,
+ const blink::WebURLRequest& request,
ResourceType resource_type) = 0;
};
diff --git a/chromium/content/public/renderer/window_features_converter.h b/chromium/content/public/renderer/window_features_converter.h
index 45c620b1e3b..dbc78a7ddc1 100644
--- a/chromium/content/public/renderer/window_features_converter.h
+++ b/chromium/content/public/renderer/window_features_converter.h
@@ -6,8 +6,8 @@
#define CONTENT_PUBLIC_RENDERER_WINDOW_FEATURES_CONVERTER_H_
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/web/WebWindowFeatures.h"
-#include "third_party/WebKit/public/web/window_features.mojom.h"
+#include "third_party/blink/public/web/web_window_features.h"
+#include "third_party/blink/public/web/window_features.mojom.h"
namespace content {
diff --git a/chromium/content/public/utility/utility_thread.h b/chromium/content/public/utility/utility_thread.h
index 6d1c36271f0..f17e367044a 100644
--- a/chromium/content/public/utility/utility_thread.h
+++ b/chromium/content/public/utility/utility_thread.h
@@ -5,8 +5,13 @@
#ifndef CONTENT_PUBLIC_UTILITY_UTILITY_THREAD_H_
#define CONTENT_PUBLIC_UTILITY_UTILITY_THREAD_H_
+#include "build/build_config.h"
#include "content/public/child/child_thread.h"
+namespace service_manager {
+class Connector;
+}
+
namespace content {
class CONTENT_EXPORT UtilityThread : virtual public ChildThread {
@@ -23,6 +28,20 @@ class CONTENT_EXPORT UtilityThread : virtual public ChildThread {
// Initializes blink if it hasn't already been initialized.
virtual void EnsureBlinkInitialized() = 0;
+
+#if defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_FUCHSIA)
+ // Initializes blink with web sandbox support.
+ virtual void EnsureBlinkInitializedWithSandboxSupport() = 0;
+#endif
+
+#if defined(OS_MACOSX)
+ // Initializes a connection to FontLoaderMac service.
+ // Generic utility processes don't possess the content_browser's font_loader
+ // capability to access the interface. Specialized utility processes, such as
+ // pdf_compositor service, do require it.
+ virtual void InitializeFontLoaderMac(
+ service_manager::Connector* connector) = 0;
+#endif
};
} // namespace content
diff --git a/chromium/content/renderer/BUILD.gn b/chromium/content/renderer/BUILD.gn
index e18c0a3b79c..e90c9c2a023 100644
--- a/chromium/content/renderer/BUILD.gn
+++ b/chromium/content/renderer/BUILD.gn
@@ -9,8 +9,8 @@ import("//build/config/ui.gni")
import("//build/split_static_library.gni")
import("//content/common/features.gni")
import("//media/media_options.gni")
-import("//ppapi/features/features.gni")
-import("//printing/features/features.gni")
+import("//ppapi/buildflags/buildflags.gni")
+import("//printing/buildflags/buildflags.gni")
import("//third_party/webrtc/webrtc.gni")
import("//tools/ipc_fuzzer/ipc_fuzzer.gni")
@@ -27,6 +27,7 @@ target(link_target_type, "renderer") {
":for_content_tests",
"//content/app:*",
"//content/public/renderer:renderer_sources",
+ "//content/renderer:audio_decoder_fuzzer",
]
sources = [
@@ -67,10 +68,6 @@ target(link_target_type, "renderer") {
"browser_plugin/browser_plugin.h",
"browser_plugin/browser_plugin_manager.cc",
"browser_plugin/browser_plugin_manager.h",
- "cache_storage/cache_storage_dispatcher.cc",
- "cache_storage/cache_storage_dispatcher.h",
- "cache_storage/cache_storage_message_filter.cc",
- "cache_storage/cache_storage_message_filter.h",
"cache_storage/webserviceworkercachestorage_impl.cc",
"cache_storage/webserviceworkercachestorage_impl.h",
"categorized_worker_pool.cc",
@@ -243,8 +240,6 @@ target(link_target_type, "renderer") {
"loader/resource_dispatcher.h",
"loader/shared_memory_data_consumer_handle.cc",
"loader/shared_memory_data_consumer_handle.h",
- "loader/site_isolation_stats_gatherer.cc",
- "loader/site_isolation_stats_gatherer.h",
"loader/sync_load_context.cc",
"loader/sync_load_context.h",
"loader/sync_load_response.cc",
@@ -300,13 +295,6 @@ target(link_target_type, "renderer") {
"media/audio_renderer_sink_cache.h",
"media/audio_renderer_sink_cache_impl.cc",
"media/audio_renderer_sink_cache_impl.h",
- "media/cdm/pepper_cdm_wrapper.h",
- "media/cdm/pepper_cdm_wrapper_impl.cc",
- "media/cdm/pepper_cdm_wrapper_impl.h",
- "media/cdm/ppapi_decryptor.cc",
- "media/cdm/ppapi_decryptor.h",
- "media/cdm/render_cdm_factory.cc",
- "media/cdm/render_cdm_factory.h",
"media/gpu/gpu_video_accelerator_factories_impl.cc",
"media/gpu/gpu_video_accelerator_factories_impl.h",
"media/media_factory.cc",
@@ -547,24 +535,23 @@ target(link_target_type, "renderer") {
"//content:resources",
"//content/child",
"//content/common",
- "//content/common:features",
+ "//content/common:buildflags",
"//content/gpu:gpu_sources",
"//content/public/child:child_sources",
+ "//content/public/common:buildflags",
"//content/public/common:feature_h264_with_openh264_ffmpeg",
- "//content/public/common:features",
"//content/public/common:service_names",
"//crypto:platform",
"//device/base/synchronization",
"//device/gamepad/public/cpp:shared_with_blink",
"//device/gamepad/public/mojom",
- "//device/sensors/public/cpp:shared_with_blink",
"//device/usb/public/mojom",
"//gin",
"//gpu",
"//gpu/command_buffer/client:gles2_interface",
"//gpu/command_buffer/client:raster_interface",
"//media",
- "//media:media_features",
+ "//media:media_buildflags",
"//media/blink",
"//media/capture",
"//media/gpu",
@@ -572,15 +559,15 @@ target(link_target_type, "renderer") {
"//media/gpu/ipc/common",
"//media/midi",
"//media/midi:mojo",
- "//media/mojo:features",
+ "//media/mojo:buildflags",
"//media/mojo/clients",
"//media/mojo/interfaces",
"//media/mojo/interfaces:remoting",
"//mojo/common",
"//mojo/public/cpp/bindings",
"//net",
- "//ppapi/features",
- "//printing/features",
+ "//ppapi/buildflags",
+ "//printing/buildflags",
"//sandbox",
"//services/device/public/cpp/generic_sensor",
"//services/device/public/mojom",
@@ -592,11 +579,11 @@ target(link_target_type, "renderer") {
"//services/ui/public/cpp/gpu",
"//skia",
"//storage/common",
- "//third_party/WebKit/public:blink",
- "//third_party/WebKit/public:features",
- "//third_party/WebKit/public:media_devices_mojo_bindings",
- "//third_party/WebKit/public:mojo_bindings",
- "//third_party/WebKit/public/common",
+ "//third_party/blink/public:blink",
+ "//third_party/blink/public:buildflags",
+ "//third_party/blink/public:media_devices_mojo_bindings",
+ "//third_party/blink/public:mojo_bindings",
+ "//third_party/blink/public/common",
"//third_party/boringssl",
"//third_party/icu",
"//third_party/libyuv",
@@ -765,6 +752,8 @@ target(link_target_type, "renderer") {
"media/webrtc/rtc_data_channel_handler.h",
"media/webrtc/rtc_dtmf_sender_handler.cc",
"media/webrtc/rtc_dtmf_sender_handler.h",
+ "media/webrtc/rtc_error.cc",
+ "media/webrtc/rtc_error.h",
"media/webrtc/rtc_event_log_output_sink.h",
"media/webrtc/rtc_event_log_output_sink_proxy.cc",
"media/webrtc/rtc_event_log_output_sink_proxy.h",
@@ -772,6 +761,8 @@ target(link_target_type, "renderer") {
"media/webrtc/rtc_peer_connection_handler.h",
"media/webrtc/rtc_rtp_contributing_source.cc",
"media/webrtc/rtc_rtp_contributing_source.h",
+ "media/webrtc/rtc_rtp_parameters.cc",
+ "media/webrtc/rtc_rtp_parameters.h",
"media/webrtc/rtc_rtp_receiver.cc",
"media/webrtc/rtc_rtp_receiver.h",
"media/webrtc/rtc_rtp_sender.cc",
@@ -947,8 +938,6 @@ target(link_target_type, "renderer") {
sources += [
"pepper/audio_helper.cc",
"pepper/audio_helper.h",
- "pepper/content_decryptor_delegate.cc",
- "pepper/content_decryptor_delegate.h",
"pepper/content_renderer_pepper_host_factory.cc",
"pepper/content_renderer_pepper_host_factory.h",
"pepper/event_conversion.cc",
@@ -1094,16 +1083,6 @@ target(link_target_type, "renderer") {
]
}
- if (!enable_library_cdms) {
- sources -= [
- "media/cdm/pepper_cdm_wrapper.h",
- "media/cdm/pepper_cdm_wrapper_impl.cc",
- "media/cdm/pepper_cdm_wrapper_impl.h",
- "media/cdm/ppapi_decryptor.cc",
- "media/cdm/ppapi_decryptor.h",
- ]
- }
-
if (enable_basic_printing || enable_print_preview) {
deps += [ "//printing" ]
}
@@ -1116,7 +1095,7 @@ target(link_target_type, "renderer") {
}
if (is_linux || is_android) {
- deps += [ "//sandbox:sandbox_features" ]
+ deps += [ "//sandbox:sandbox_buildflags" ]
}
if (use_ozone) {
@@ -1142,3 +1121,15 @@ group("for_content_tests") {
]
}
}
+
+fuzzer_test("audio_decoder_fuzzer") {
+ sources = [
+ "media/audio_decoder_fuzzer.cpp",
+ ]
+ deps = [
+ "//content/public/renderer:renderer_sources",
+ "//content/renderer:renderer",
+ "//content/test:test_support",
+ ]
+ seed_corpus = "//media/test/data"
+}
diff --git a/chromium/content/renderer/DEPS b/chromium/content/renderer/DEPS
index ff0dfefa0d6..340b6b17d9b 100644
--- a/chromium/content/renderer/DEPS
+++ b/chromium/content/renderer/DEPS
@@ -15,7 +15,6 @@ include_rules = [
"+device/base/synchronization",
"+device/gamepad/public/cpp",
"+device/gamepad/public/mojom",
- "+device/sensors/public",
"+device/usb/public",
"+gin",
"+jingle/glue",
@@ -24,7 +23,7 @@ include_rules = [
"-storage/browser",
"+third_party/hyphen/hyphen.h",
"+third_party/webrtc_overrides",
- "+third_party/WebKit/public/common",
+ "+third_party/blink/public/common",
"+v8/include",
"+v8/src/third_party/vtune",
]
diff --git a/chromium/content/renderer/PRESUBMIT.py b/chromium/content/renderer/PRESUBMIT.py
new file mode 100644
index 00000000000..7fecab9b13a
--- /dev/null
+++ b/chromium/content/renderer/PRESUBMIT.py
@@ -0,0 +1,48 @@
+# Copyright 2018 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+"""Presubmit script for content/renderer
+
+See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
+for more details about the presubmit API built into depot_tools.
+"""
+
+import re
+
+def _FilterFile(affected_file):
+ """Return true if the file could contain code requiring a presubmit check."""
+ return affected_file.LocalPath().endswith(
+ ('.h', '.cc', '.cpp', '.cxx', '.mm'))
+
+def _CheckForUseOfGlobalTaskRunnerGetter(input_api, output_api):
+ """Check that base::ThreadTaskRunnerHandle::Get() or
+ base::SequencedTaskRunnerHandle::Get() is not used."""
+
+ problems = []
+ getter_re = input_api.re.compile(
+ r'(^|\b)base::(Thread|Sequenced)TaskRunnerHandle::Get\(\)')
+ for f in input_api.AffectedSourceFiles(_FilterFile):
+ for line_number, line in f.ChangedContents():
+ if getter_re.search(line):
+ problems.append('%s:%d' % (f, line_number))
+
+ if problems:
+ return [output_api.PresubmitError(
+ 'base::ThreadTaskRunnerHandle::Get() and'
+ ' base::SequencedTaskRunnerHandle::Get() are deprecated in renderer;'
+ ' please use RenderFrame::GetTaskRunner for production code and'
+ ' blink::scheduler::Get*TaskRunnerForTesting for tests. Please reach'
+ ' out to scheduler-dev@ if you have any questions.', problems)]
+ return []
+
+def _CommonCheck(input_api, output_api):
+ results = []
+ results.extend(_CheckForUseOfGlobalTaskRunnerGetter(input_api, output_api))
+ return results
+
+def CheckChangeOnUpload(input_api, output_api):
+ return _CommonCheck(input_api, output_api)
+
+def CheckChangeOnCommit(input_api, output_api):
+ return _CommonCheck(input_api, output_api)
diff --git a/chromium/content/renderer/PRESUBMIT_test.py b/chromium/content/renderer/PRESUBMIT_test.py
new file mode 100755
index 00000000000..691c0249368
--- /dev/null
+++ b/chromium/content/renderer/PRESUBMIT_test.py
@@ -0,0 +1,36 @@
+#!/usr/bin/env python
+# Copyright 2018 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+import os
+import sys
+import unittest
+
+import PRESUBMIT
+
+sys.path.append(
+ os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))
+from PRESUBMIT_test_mocks import (MockInputApi, MockOutputApi, MockAffectedFile)
+
+class GetTest(unittest.TestCase):
+ def testNewUsageThreadTaskRunnerHandleGet(self):
+ diff = ['scoped_refptr<SingleThreadTaskRunner> task_runner =',
+ ' base::ThreadTaskRunnerHandle::Get()']
+ input_api = MockInputApi()
+ input_api.files = [MockAffectedFile('content/renderer/foo.cc', diff)]
+ errors = PRESUBMIT._CheckForUseOfGlobalTaskRunnerGetter(input_api,
+ MockOutputApi())
+ self.assertEqual(1, len(errors))
+
+ def testNewUsageSequencedTaskRunnerHandleGet(self):
+ diff = ['scoped_refptr<SequencedThreadTaskRunner> task_runner =',
+ ' base::SequencedTaskRunnerHandle::Get()']
+ input_api = MockInputApi()
+ input_api.files = [MockAffectedFile('content/renderer/foo.cc', diff)]
+ errors = PRESUBMIT._CheckForUseOfGlobalTaskRunnerGetter(input_api,
+ MockOutputApi())
+ self.assertEqual(1, len(errors))
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/chromium/content/renderer/accessibility/aom_content_ax_tree.cc b/chromium/content/renderer/accessibility/aom_content_ax_tree.cc
index 668df0fd645..1ff0d05ba56 100644
--- a/chromium/content/renderer/accessibility/aom_content_ax_tree.cc
+++ b/chromium/content/renderer/accessibility/aom_content_ax_tree.cc
@@ -8,7 +8,7 @@
#include "content/common/ax_content_node_data.h"
#include "content/renderer/accessibility/render_accessibility_impl.h"
-#include "third_party/WebKit/public/web/WebAXEnums.h"
+#include "third_party/blink/public/web/web_ax_enums.h"
#include "ui/accessibility/ax_enum_util.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node.h"
@@ -24,6 +24,8 @@ ax::mojom::BoolAttribute GetCorrespondingAXAttribute(
return ax::mojom::BoolAttribute::kBusy;
case blink::WebAOMBoolAttribute::AOM_ATTR_MODAL:
return ax::mojom::BoolAttribute::kModal;
+ case blink::WebAOMBoolAttribute::AOM_ATTR_SELECTED:
+ return ax::mojom::BoolAttribute::kSelected;
default:
return ax::mojom::BoolAttribute::kNone;
}
@@ -111,8 +113,6 @@ ax::mojom::State GetCorrespondingStateFlag(blink::WebAOMBoolAttribute attr) {
return ax::mojom::State::kMultiselectable;
case blink::WebAOMBoolAttribute::AOM_ATTR_REQUIRED:
return ax::mojom::State::kRequired;
- case blink::WebAOMBoolAttribute::AOM_ATTR_SELECTED:
- return ax::mojom::State::kSelected;
default:
return ax::mojom::State::kNone;
}
@@ -127,8 +127,8 @@ AomContentAxTree::AomContentAxTree(RenderFrameImpl* render_frame)
bool AomContentAxTree::ComputeAccessibilityTree() {
AXContentTreeUpdate content_tree_update;
- RenderAccessibilityImpl::SnapshotAccessibilityTree(render_frame_,
- &content_tree_update);
+ RenderAccessibilityImpl::SnapshotAccessibilityTree(
+ render_frame_, &content_tree_update, ui::kAXModeComplete);
// Hack to convert between AXContentNodeData and AXContentTreeData to just
// AXNodeData and AXTreeData to preserve content specific attributes while
diff --git a/chromium/content/renderer/accessibility/aom_content_ax_tree.h b/chromium/content/renderer/accessibility/aom_content_ax_tree.h
index 48c1ea8c39d..1c5205c4b63 100644
--- a/chromium/content/renderer/accessibility/aom_content_ax_tree.h
+++ b/chromium/content/renderer/accessibility/aom_content_ax_tree.h
@@ -7,11 +7,11 @@
#include <stdint.h>
-#include "third_party/WebKit/public/platform/WebComputedAXTree.h"
+#include "third_party/blink/public/platform/web_computed_ax_tree.h"
#include "base/macros.h"
#include "content/renderer/render_frame_impl.h"
-#include "third_party/WebKit/public/platform/WebString.h"
+#include "third_party/blink/public/platform/web_string.h"
#include "ui/accessibility/ax_tree.h"
namespace content {
diff --git a/chromium/content/renderer/accessibility/blink_ax_enum_conversion.cc b/chromium/content/renderer/accessibility/blink_ax_enum_conversion.cc
index b1ddcad5186..86439122101 100644
--- a/chromium/content/renderer/accessibility/blink_ax_enum_conversion.cc
+++ b/chromium/content/renderer/accessibility/blink_ax_enum_conversion.cc
@@ -44,14 +44,13 @@ void AXStateFromBlink(const blink::WebAXObject& o, ui::AXNodeData* dst) {
if (o.IsRequired())
dst->AddState(ax::mojom::State::kRequired);
- if (o.IsSelected() != blink::kWebAXSelectedStateUndefined)
- dst->AddState(ax::mojom::State::kSelectable);
-
if (o.IsEditable())
dst->AddState(ax::mojom::State::kEditable);
- if (o.IsSelected() == blink::kWebAXSelectedStateTrue)
- dst->AddState(ax::mojom::State::kSelected);
+ if (o.IsSelected() != blink::kWebAXSelectedStateUndefined) {
+ dst->AddBoolAttribute(ax::mojom::BoolAttribute::kSelected,
+ o.IsSelected() == blink::kWebAXSelectedStateTrue);
+ }
if (o.IsRichlyEditable())
dst->AddState(ax::mojom::State::kRichlyEditable);
diff --git a/chromium/content/renderer/accessibility/blink_ax_enum_conversion.h b/chromium/content/renderer/accessibility/blink_ax_enum_conversion.h
index 61349c36e35..18b471b02ab 100644
--- a/chromium/content/renderer/accessibility/blink_ax_enum_conversion.h
+++ b/chromium/content/renderer/accessibility/blink_ax_enum_conversion.h
@@ -7,7 +7,7 @@
#include <stdint.h>
-#include "third_party/WebKit/public/web/WebAXObject.h"
+#include "third_party/blink/public/web/web_ax_object.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node_data.h"
diff --git a/chromium/content/renderer/accessibility/blink_ax_tree_source.cc b/chromium/content/renderer/accessibility/blink_ax_tree_source.cc
index 326b5841a84..173d360e2b6 100644
--- a/chromium/content/renderer/accessibility/blink_ax_tree_source.cc
+++ b/chromium/content/renderer/accessibility/blink_ax_tree_source.cc
@@ -21,22 +21,22 @@
#include "content/renderer/render_frame_impl.h"
#include "content/renderer/render_frame_proxy.h"
#include "content/renderer/render_view_impl.h"
-#include "third_party/WebKit/public/platform/WebFloatRect.h"
-#include "third_party/WebKit/public/platform/WebRect.h"
-#include "third_party/WebKit/public/platform/WebSize.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebVector.h"
-#include "third_party/WebKit/public/web/WebAXEnums.h"
-#include "third_party/WebKit/public/web/WebAXObject.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebElement.h"
-#include "third_party/WebKit/public/web/WebFormControlElement.h"
-#include "third_party/WebKit/public/web/WebFrame.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebNode.h"
-#include "third_party/WebKit/public/web/WebPlugin.h"
-#include "third_party/WebKit/public/web/WebPluginContainer.h"
-#include "third_party/WebKit/public/web/WebView.h"
+#include "third_party/blink/public/platform/web_float_rect.h"
+#include "third_party/blink/public/platform/web_rect.h"
+#include "third_party/blink/public/platform/web_size.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_vector.h"
+#include "third_party/blink/public/web/web_ax_enums.h"
+#include "third_party/blink/public/web/web_ax_object.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_element.h"
+#include "third_party/blink/public/web/web_form_control_element.h"
+#include "third_party/blink/public/web/web_frame.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_node.h"
+#include "third_party/blink/public/web/web_plugin.h"
+#include "third_party/blink/public/web/web_plugin_container.h"
+#include "third_party/blink/public/web/web_view.h"
#include "ui/accessibility/ax_enum_util.h"
using base::ASCIIToUTF16;
@@ -911,20 +911,6 @@ void BlinkAXTreeSource::SerializeNode(WebAXObject src,
dst->AddIntAttribute(ax::mojom::IntAttribute::kTextSelEnd,
src.SelectionEnd());
}
-
-#if defined(OS_CHROMEOS)
- // This attribute will soon be deprecated; see crbug.com/669134.
- WebVector<int> src_line_breaks;
- src.LineBreaks(src_line_breaks);
- if (src_line_breaks.size()) {
- std::vector<int32_t> line_breaks;
- line_breaks.reserve(src_line_breaks.size());
- for (size_t i = 0; i < src_line_breaks.size(); ++i)
- line_breaks.push_back(src_line_breaks[i]);
- dst->AddIntListAttribute(ax::mojom::IntListAttribute::kLineBreaks,
- line_breaks);
- }
-#endif // defined OS_CHROMEOS
}
// ARIA role.
diff --git a/chromium/content/renderer/accessibility/blink_ax_tree_source.h b/chromium/content/renderer/accessibility/blink_ax_tree_source.h
index aff91a721e1..4447c4eb800 100644
--- a/chromium/content/renderer/accessibility/blink_ax_tree_source.h
+++ b/chromium/content/renderer/accessibility/blink_ax_tree_source.h
@@ -10,8 +10,8 @@
#include <set>
#include "content/common/ax_content_node_data.h"
-#include "third_party/WebKit/public/web/WebAXObject.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
+#include "third_party/blink/public/web/web_ax_object.h"
+#include "third_party/blink/public/web/web_document.h"
#include "ui/accessibility/ax_modes.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/accessibility/ax_tree_source.h"
diff --git a/chromium/content/renderer/accessibility/render_accessibility_impl.cc b/chromium/content/renderer/accessibility/render_accessibility_impl.cc
index 3005ed0f47a..28fd14d2b5c 100644
--- a/chromium/content/renderer/accessibility/render_accessibility_impl.cc
+++ b/chromium/content/renderer/accessibility/render_accessibility_impl.cc
@@ -19,15 +19,15 @@
#include "content/renderer/accessibility/blink_ax_enum_conversion.h"
#include "content/renderer/render_frame_impl.h"
#include "content/renderer/render_view_impl.h"
-#include "third_party/WebKit/public/platform/TaskType.h"
-#include "third_party/WebKit/public/platform/WebFloatRect.h"
-#include "third_party/WebKit/public/web/WebAXObject.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebInputElement.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebSettings.h"
-#include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
-#include "third_party/WebKit/public/web/WebView.h"
+#include "third_party/blink/public/platform/task_type.h"
+#include "third_party/blink/public/platform/web_float_rect.h"
+#include "third_party/blink/public/web/web_ax_object.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_input_element.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_settings.h"
+#include "third_party/blink/public/web/web_user_gesture_indicator.h"
+#include "third_party/blink/public/web/web_view.h"
#include "ui/accessibility/ax_enum_util.h"
#include "ui/accessibility/ax_node.h"
@@ -59,7 +59,8 @@ const size_t kMaxSnapshotNodeCount = 5000;
// static
void RenderAccessibilityImpl::SnapshotAccessibilityTree(
RenderFrameImpl* render_frame,
- AXContentTreeUpdate* response) {
+ AXContentTreeUpdate* response,
+ ui::AXMode ax_mode) {
TRACE_EVENT0("accessibility",
"RenderAccessibilityImpl::SnapshotAccessibilityTree");
@@ -73,10 +74,7 @@ void RenderAccessibilityImpl::SnapshotAccessibilityTree(
WebAXObject root = context.Root();
if (!root.UpdateLayoutAndCheckValidity())
return;
- BlinkAXTreeSource tree_source(
- render_frame, ui::AXMode::kNativeAPIs | ui::AXMode::kWebContents |
- ui::AXMode::kInlineTextBoxes |
- ui::AXMode::kScreenReader | ui::AXMode::kHTML);
+ BlinkAXTreeSource tree_source(render_frame, ax_mode);
tree_source.SetRoot(root);
ScopedFreezeBlinkAXTreeSource freeze(&tree_source);
BlinkAXTreeSerializer serializer(&tree_source);
@@ -450,6 +448,12 @@ void RenderAccessibilityImpl::SendPendingAccessibilityEvents() {
event_msg.id = event.id;
event_msg.event_from = event.event_from;
event_msg.action_request_id = event.action_request_id;
+
+ // If there's a plugin, force the tree data to be generated in every
+ // message so the plugin can merge its own tree data changes.
+ if (plugin_tree_source_)
+ event_msg.update.has_tree_data = true;
+
if (!serializer_.SerializeChanges(obj, &event_msg.update)) {
VLOG(1) << "Failed to serialize one accessibility event.";
continue;
@@ -755,6 +759,9 @@ void RenderAccessibilityImpl::AddPluginTreeToUpdate(
break;
}
}
+
+ if (plugin_tree_source_->GetTreeData(&update->tree_data))
+ update->has_tree_data = true;
}
void RenderAccessibilityImpl::ScrollPlugin(int id_to_make_visible) {
diff --git a/chromium/content/renderer/accessibility/render_accessibility_impl.h b/chromium/content/renderer/accessibility/render_accessibility_impl.h
index 47f569df527..3d3563a7ffc 100644
--- a/chromium/content/renderer/accessibility/render_accessibility_impl.h
+++ b/chromium/content/renderer/accessibility/render_accessibility_impl.h
@@ -14,7 +14,7 @@
#include "content/public/renderer/render_accessibility.h"
#include "content/public/renderer/render_frame_observer.h"
#include "content/renderer/accessibility/blink_ax_tree_source.h"
-#include "third_party/WebKit/public/web/WebAXObject.h"
+#include "third_party/blink/public/web/web_ax_object.h"
#include "ui/accessibility/ax_relative_bounds.h"
#include "ui/accessibility/ax_tree.h"
#include "ui/accessibility/ax_tree_serializer.h"
@@ -61,9 +61,9 @@ class CONTENT_EXPORT RenderAccessibilityImpl
public:
// Request a one-time snapshot of the accessibility tree without
// enabling accessibility if it wasn't already enabled.
- static void SnapshotAccessibilityTree(
- RenderFrameImpl* render_frame,
- AXContentTreeUpdate* response);
+ static void SnapshotAccessibilityTree(RenderFrameImpl* render_frame,
+ AXContentTreeUpdate* response,
+ ui::AXMode ax_mode);
RenderAccessibilityImpl(RenderFrameImpl* render_frame, ui::AXMode mode);
~RenderAccessibilityImpl() override;
diff --git a/chromium/content/renderer/accessibility/render_accessibility_impl_browsertest.cc b/chromium/content/renderer/accessibility/render_accessibility_impl_browsertest.cc
index a60aaaac420..07978a44eec 100644
--- a/chromium/content/renderer/accessibility/render_accessibility_impl_browsertest.cc
+++ b/chromium/content/renderer/accessibility/render_accessibility_impl_browsertest.cc
@@ -17,11 +17,11 @@
#include "content/renderer/render_frame_impl.h"
#include "content/renderer/render_view_impl.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebSize.h"
-#include "third_party/WebKit/public/web/WebAXObject.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebView.h"
+#include "third_party/blink/public/platform/web_size.h"
+#include "third_party/blink/public/web/web_ax_object.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_view.h"
#include "ui/accessibility/ax_node_data.h"
using blink::WebAXObject;
diff --git a/chromium/content/renderer/android/disambiguation_popup_helper.cc b/chromium/content/renderer/android/disambiguation_popup_helper.cc
index 19f2c563ff8..485732fda5c 100644
--- a/chromium/content/renderer/android/disambiguation_popup_helper.cc
+++ b/chromium/content/renderer/android/disambiguation_popup_helper.cc
@@ -8,7 +8,7 @@
#include <algorithm>
-#include "third_party/WebKit/public/platform/WebRect.h"
+#include "third_party/blink/public/platform/web_rect.h"
#include "ui/gfx/geometry/size_conversions.h"
using blink::WebRect;
diff --git a/chromium/content/renderer/android/disambiguation_popup_helper.h b/chromium/content/renderer/android/disambiguation_popup_helper.h
index ae9ef807920..e2824bd4cba 100644
--- a/chromium/content/renderer/android/disambiguation_popup_helper.h
+++ b/chromium/content/renderer/android/disambiguation_popup_helper.h
@@ -6,7 +6,7 @@
#define CONTENT_RENDERER_ANDROID_DISAMBIGUATION_POPUP_HELPER_H_
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebVector.h"
+#include "third_party/blink/public/platform/web_vector.h"
namespace gfx {
class Rect;
diff --git a/chromium/content/renderer/android/disambiguation_popup_helper_unittest.cc b/chromium/content/renderer/android/disambiguation_popup_helper_unittest.cc
index 81bc53c2b81..679a8e26543 100644
--- a/chromium/content/renderer/android/disambiguation_popup_helper_unittest.cc
+++ b/chromium/content/renderer/android/disambiguation_popup_helper_unittest.cc
@@ -7,8 +7,8 @@
#include <stddef.h>
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebRect.h"
-#include "third_party/WebKit/public/platform/WebVector.h"
+#include "third_party/blink/public/platform/web_rect.h"
+#include "third_party/blink/public/platform/web_vector.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/geometry/size_conversions.h"
diff --git a/chromium/content/renderer/android/renderer_date_time_picker.cc b/chromium/content/renderer/android/renderer_date_time_picker.cc
index 6b898640ec1..52092de080b 100644
--- a/chromium/content/renderer/android/renderer_date_time_picker.cc
+++ b/chromium/content/renderer/android/renderer_date_time_picker.cc
@@ -10,10 +10,10 @@
#include "content/common/date_time_suggestion.h"
#include "content/common/view_messages.h"
#include "content/renderer/render_view_impl.h"
-#include "third_party/WebKit/public/web/WebDateTimeChooserCompletion.h"
-#include "third_party/WebKit/public/web/WebDateTimeChooserParams.h"
-#include "third_party/WebKit/public/web/WebDateTimeInputType.h"
-#include "third_party/WebKit/public/web/WebDateTimeSuggestion.h"
+#include "third_party/blink/public/web/web_date_time_chooser_completion.h"
+#include "third_party/blink/public/web/web_date_time_chooser_params.h"
+#include "third_party/blink/public/web/web_date_time_input_type.h"
+#include "third_party/blink/public/web/web_date_time_suggestion.h"
#include "ui/base/ime/text_input_type.h"
using blink::WebString;
diff --git a/chromium/content/renderer/android/renderer_date_time_picker.h b/chromium/content/renderer/android/renderer_date_time_picker.h
index 49ae39077bf..583619f8de0 100644
--- a/chromium/content/renderer/android/renderer_date_time_picker.h
+++ b/chromium/content/renderer/android/renderer_date_time_picker.h
@@ -7,7 +7,7 @@
#include "base/macros.h"
#include "content/public/renderer/render_view_observer.h"
-#include "third_party/WebKit/public/web/WebDateTimeChooserParams.h"
+#include "third_party/blink/public/web/web_date_time_chooser_params.h"
namespace blink {
class WebDateTimeChooserCompletion;
diff --git a/chromium/content/renderer/android/synchronous_compositor_filter.cc b/chromium/content/renderer/android/synchronous_compositor_filter.cc
index 44ca976eaab..d7db19946e8 100644
--- a/chromium/content/renderer/android/synchronous_compositor_filter.cc
+++ b/chromium/content/renderer/android/synchronous_compositor_filter.cc
@@ -7,7 +7,6 @@
#include <utility>
#include "base/callback.h"
-#include "base/memory/ptr_util.h"
#include "base/stl_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/common/input/sync_compositor_messages.h"
diff --git a/chromium/content/renderer/android/synchronous_layer_tree_frame_sink.cc b/chromium/content/renderer/android/synchronous_layer_tree_frame_sink.cc
index b631c520df6..f942bf9dd1d 100644
--- a/chromium/content/renderer/android/synchronous_layer_tree_frame_sink.cc
+++ b/chromium/content/renderer/android/synchronous_layer_tree_frame_sink.cc
@@ -10,7 +10,6 @@
#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/threading/thread_task_runner_handle.h"
#include "cc/trees/layer_tree_frame_sink_client.h"
diff --git a/chromium/content/renderer/appcache/appcache_frontend_impl.cc b/chromium/content/renderer/appcache/appcache_frontend_impl.cc
index 09b60975619..20afc6b86e9 100644
--- a/chromium/content/renderer/appcache/appcache_frontend_impl.cc
+++ b/chromium/content/renderer/appcache/appcache_frontend_impl.cc
@@ -6,7 +6,7 @@
#include "base/logging.h"
#include "content/renderer/appcache/web_application_cache_host_impl.h"
-#include "third_party/WebKit/public/web/WebConsoleMessage.h"
+#include "third_party/blink/public/web/web_console_message.h"
using blink::WebApplicationCacheHost;
using blink::WebConsoleMessage;
diff --git a/chromium/content/renderer/appcache/web_application_cache_host_impl.cc b/chromium/content/renderer/appcache/web_application_cache_host_impl.cc
index a1c6a45fd12..ef2969aaa1c 100644
--- a/chromium/content/renderer/appcache/web_application_cache_host_impl.cc
+++ b/chromium/content/renderer/appcache/web_application_cache_host_impl.cc
@@ -11,10 +11,10 @@
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "content/public/common/browser_side_navigation_policy.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
-#include "third_party/WebKit/public/platform/WebURLRequest.h"
-#include "third_party/WebKit/public/platform/WebURLResponse.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_url.h"
+#include "third_party/blink/public/platform/web_url_request.h"
+#include "third_party/blink/public/platform/web_url_response.h"
using blink::WebApplicationCacheHost;
using blink::WebApplicationCacheHostClient;
diff --git a/chromium/content/renderer/appcache/web_application_cache_host_impl.h b/chromium/content/renderer/appcache/web_application_cache_host_impl.h
index 9c604b58eb2..d847549469c 100644
--- a/chromium/content/renderer/appcache/web_application_cache_host_impl.h
+++ b/chromium/content/renderer/appcache/web_application_cache_host_impl.h
@@ -9,10 +9,10 @@
#include "content/common/appcache_interfaces.h"
#include "mojo/public/cpp/system/message_pipe.h"
-#include "third_party/WebKit/public/platform/WebApplicationCacheHost.h"
-#include "third_party/WebKit/public/platform/WebApplicationCacheHostClient.h"
-#include "third_party/WebKit/public/platform/WebURLResponse.h"
-#include "third_party/WebKit/public/platform/WebVector.h"
+#include "third_party/blink/public/platform/web_application_cache_host.h"
+#include "third_party/blink/public/platform/web_application_cache_host_client.h"
+#include "third_party/blink/public/platform/web_url_response.h"
+#include "third_party/blink/public/platform/web_vector.h"
#include "url/gurl.h"
namespace content {
diff --git a/chromium/content/renderer/blink_platform_audio_hardware_browsertest.cc b/chromium/content/renderer/blink_platform_audio_hardware_browsertest.cc
index e17f4be1385..42a9fbbc7ee 100644
--- a/chromium/content/renderer/blink_platform_audio_hardware_browsertest.cc
+++ b/chromium/content/renderer/blink_platform_audio_hardware_browsertest.cc
@@ -3,7 +3,7 @@
// found in the LICENSE file.
#include "content/public/test/render_view_test.h"
-#include "third_party/WebKit/public/platform/Platform.h"
+#include "third_party/blink/public/platform/platform.h"
namespace content {
diff --git a/chromium/content/renderer/blob_storage/webblobregistry_impl.cc b/chromium/content/renderer/blob_storage/webblobregistry_impl.cc
index 3469292e530..aefbf0d321e 100644
--- a/chromium/content/renderer/blob_storage/webblobregistry_impl.cc
+++ b/chromium/content/renderer/blob_storage/webblobregistry_impl.cc
@@ -8,8 +8,8 @@
#include "base/trace_event/trace_event.h"
#include "content/child/thread_safe_sender.h"
#include "content/common/fileapi/webblob_messages.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_url.h"
using blink::WebString;
using blink::WebURL;
diff --git a/chromium/content/renderer/blob_storage/webblobregistry_impl.h b/chromium/content/renderer/blob_storage/webblobregistry_impl.h
index 9747657bc0b..1abb9730cd8 100644
--- a/chromium/content/renderer/blob_storage/webblobregistry_impl.h
+++ b/chromium/content/renderer/blob_storage/webblobregistry_impl.h
@@ -6,7 +6,7 @@
#define CONTENT_RENDERER_BLOB_STORAGE_WEBBLOBREGISTRY_IMPL_H_
#include "base/memory/ref_counted.h"
-#include "third_party/WebKit/public/platform/WebBlobRegistry.h"
+#include "third_party/blink/public/platform/web_blob_registry.h"
namespace content {
class ThreadSafeSender;
diff --git a/chromium/content/renderer/bmp_image_decoder_unittest.cc b/chromium/content/renderer/bmp_image_decoder_unittest.cc
index a8a679e633d..d2cd74b60fd 100644
--- a/chromium/content/renderer/bmp_image_decoder_unittest.cc
+++ b/chromium/content/renderer/bmp_image_decoder_unittest.cc
@@ -5,7 +5,7 @@
#include <stdint.h>
#include "content/test/image_decoder_test.h"
-#include "third_party/WebKit/public/web/WebImageDecoder.h"
+#include "third_party/blink/public/web/web_image_decoder.h"
class BMPImageDecoderTest : public ImageDecoderTest {
public:
diff --git a/chromium/content/renderer/browser_plugin/browser_plugin.cc b/chromium/content/renderer/browser_plugin/browser_plugin.cc
index 973f835727b..c5fe59a5237 100644
--- a/chromium/content/renderer/browser_plugin/browser_plugin.cc
+++ b/chromium/content/renderer/browser_plugin/browser_plugin.cc
@@ -22,6 +22,7 @@
#include "components/viz/common/surfaces/surface_info.h"
#include "content/common/browser_plugin/browser_plugin_constants.h"
#include "content/common/browser_plugin/browser_plugin_messages.h"
+#include "content/common/frame_messages.h"
#include "content/common/view_messages.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_switches.h"
@@ -34,17 +35,17 @@
#include "content/renderer/drop_data_builder.h"
#include "content/renderer/render_thread_impl.h"
#include "content/renderer/sad_plugin.h"
-#include "third_party/WebKit/public/platform/WebCoalescedInputEvent.h"
-#include "third_party/WebKit/public/platform/WebGestureEvent.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
-#include "third_party/WebKit/public/platform/WebMouseWheelEvent.h"
-#include "third_party/WebKit/public/platform/WebRect.h"
-#include "third_party/WebKit/public/web/WebAXObject.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebElement.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebPluginContainer.h"
-#include "third_party/WebKit/public/web/WebView.h"
+#include "third_party/blink/public/platform/web_coalesced_input_event.h"
+#include "third_party/blink/public/platform/web_gesture_event.h"
+#include "third_party/blink/public/platform/web_input_event.h"
+#include "third_party/blink/public/platform/web_mouse_wheel_event.h"
+#include "third_party/blink/public/platform/web_rect.h"
+#include "third_party/blink/public/web/web_ax_object.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_element.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_plugin_container.h"
+#include "third_party/blink/public/web/web_view.h"
#include "ui/base/ui_base_features.h"
#include "ui/events/keycodes/keyboard_codes.h"
@@ -123,6 +124,8 @@ bool BrowserPlugin::OnMessageReceived(const IPC::Message& message) {
IPC_MESSAGE_HANDLER(BrowserPluginMsg_Attach_ACK, OnAttachACK)
IPC_MESSAGE_HANDLER(BrowserPluginMsg_GuestGone, OnGuestGone)
IPC_MESSAGE_HANDLER(BrowserPluginMsg_GuestReady, OnGuestReady)
+ IPC_MESSAGE_HANDLER(BrowserPluginMsg_EnableAutoResize, OnEnableAutoResize)
+ IPC_MESSAGE_HANDLER(BrowserPluginMsg_DisableAutoResize, OnDisableAutoResize)
IPC_MESSAGE_HANDLER(BrowserPluginMsg_ResizeDueToAutoResize,
OnResizeDueToAutoResize)
IPC_MESSAGE_HANDLER(BrowserPluginMsg_SetCursor, OnSetCursor)
@@ -145,11 +148,12 @@ void BrowserPlugin::OnSetChildFrameSurface(
return;
if (!enable_surface_synchronization_) {
- compositing_helper_->SetPrimarySurfaceId(surface_info.id(),
- frame_rect().size());
+ compositing_helper_->SetPrimarySurfaceId(
+ surface_info.id(), screen_space_rect().size(),
+ cc::DeadlinePolicy::UseDefaultDeadline());
}
compositing_helper_->SetFallbackSurfaceId(surface_info.id(),
- frame_rect().size());
+ screen_space_rect().size());
}
void BrowserPlugin::UpdateDOMAttribute(const std::string& attribute_name,
@@ -168,7 +172,7 @@ void BrowserPlugin::Attach() {
BrowserPluginHostMsg_Attach_Params attach_params;
attach_params.focused = ShouldGuestBeFocused();
attach_params.visible = visible_;
- attach_params.frame_rect = frame_rect();
+ attach_params.frame_rect = screen_space_rect();
attach_params.is_full_page_plugin = false;
if (Container()) {
blink::WebLocalFrame* frame = Container()->GetDocument().GetFrame();
@@ -221,7 +225,7 @@ void BrowserPlugin::Detach() {
}
const viz::LocalSurfaceId& BrowserPlugin::GetLocalSurfaceId() const {
- return parent_local_surface_id_allocator_.last_known_local_surface_id();
+ return parent_local_surface_id_allocator_.GetCurrentLocalSurfaceId();
}
#if defined(USE_AURA)
@@ -248,10 +252,18 @@ void BrowserPlugin::CreateMusWindowAndEmbed(
void BrowserPlugin::WasResized() {
bool size_changed = !sent_resize_params_ ||
- sent_resize_params_->frame_rect.size() !=
- pending_resize_params_.frame_rect.size() ||
- sent_resize_params_->sequence_number !=
- pending_resize_params_.sequence_number;
+ sent_resize_params_->auto_resize_enabled !=
+ pending_resize_params_.auto_resize_enabled ||
+ sent_resize_params_->min_size_for_auto_resize !=
+ pending_resize_params_.min_size_for_auto_resize ||
+ sent_resize_params_->max_size_for_auto_resize !=
+ pending_resize_params_.max_size_for_auto_resize ||
+ sent_resize_params_->local_frame_size !=
+ pending_resize_params_.local_frame_size ||
+ sent_resize_params_->screen_space_rect.size() !=
+ pending_resize_params_.screen_space_rect.size() ||
+ sent_resize_params_->auto_resize_sequence_number !=
+ pending_resize_params_.auto_resize_sequence_number;
bool synchronized_params_changed =
!sent_resize_params_ || size_changed ||
@@ -261,26 +273,28 @@ void BrowserPlugin::WasResized() {
parent_local_surface_id_allocator_.GenerateId();
if (enable_surface_synchronization_ && frame_sink_id_.is_valid()) {
+ // TODO(vmpstr): When capture_sequence_number is available, the deadline
+ // should be infinite if the sequence number has changed.
compositing_helper_->SetPrimarySurfaceId(
viz::SurfaceId(frame_sink_id_, GetLocalSurfaceId()),
- frame_rect().size());
+ screen_space_rect().size(), cc::DeadlinePolicy::UseDefaultDeadline());
}
- bool position_changed =
- !sent_resize_params_ || sent_resize_params_->frame_rect.origin() !=
- pending_resize_params_.frame_rect.origin();
+ bool position_changed = !sent_resize_params_ ||
+ sent_resize_params_->screen_space_rect.origin() !=
+ pending_resize_params_.screen_space_rect.origin();
bool resize_params_changed = synchronized_params_changed || position_changed;
if (resize_params_changed && attached()) {
// Let the browser know about the updated view rect.
BrowserPluginManager::Get()->Send(
- new BrowserPluginHostMsg_UpdateResizeParams(
- browser_plugin_instance_id_, frame_rect(), screen_info(),
- auto_size_sequence_number(), GetLocalSurfaceId()));
+ new BrowserPluginHostMsg_UpdateResizeParams(browser_plugin_instance_id_,
+ GetLocalSurfaceId(),
+ pending_resize_params_));
}
if (delegate_ && size_changed)
- delegate_->DidResizeElement(frame_rect().size());
+ delegate_->DidResizeElement(screen_space_rect().size());
if (resize_params_changed && attached())
sent_resize_params_ = pending_resize_params_;
@@ -314,7 +328,7 @@ void BrowserPlugin::OnAttachACK(
void BrowserPlugin::OnGuestGone(int browser_plugin_instance_id) {
guest_crashed_ = true;
- compositing_helper_->ChildFrameGone(frame_rect().size(),
+ compositing_helper_->ChildFrameGone(screen_space_rect().size(),
screen_info().device_scale_factor);
}
@@ -328,7 +342,21 @@ void BrowserPlugin::OnGuestReady(int browser_plugin_instance_id,
void BrowserPlugin::OnResizeDueToAutoResize(int browser_plugin_instance_id,
uint64_t sequence_number) {
- pending_resize_params_.sequence_number = sequence_number;
+ pending_resize_params_.auto_resize_sequence_number = sequence_number;
+ WasResized();
+}
+
+void BrowserPlugin::OnEnableAutoResize(int browser_plugin_instance_id,
+ const gfx::Size& min_size,
+ const gfx::Size& max_size) {
+ pending_resize_params_.auto_resize_enabled = true;
+ pending_resize_params_.min_size_for_auto_resize = min_size;
+ pending_resize_params_.max_size_for_auto_resize = max_size;
+ WasResized();
+}
+
+void BrowserPlugin::OnDisableAutoResize(int browser_plugin_instance_id) {
+ pending_resize_params_.auto_resize_enabled = false;
WasResized();
}
@@ -384,8 +412,9 @@ void BrowserPlugin::OnShouldAcceptTouchEvents(int browser_plugin_instance_id,
gfx::Rect BrowserPlugin::FrameRectInPixels() const {
const float device_scale_factor = GetDeviceScaleFactor();
return gfx::Rect(
- gfx::ScaleToFlooredPoint(frame_rect().origin(), device_scale_factor),
- gfx::ScaleToCeiledSize(frame_rect().size(), device_scale_factor));
+ gfx::ScaleToFlooredPoint(screen_space_rect().origin(),
+ device_scale_factor),
+ gfx::ScaleToCeiledSize(screen_space_rect().size(), device_scale_factor));
}
float BrowserPlugin::GetDeviceScaleFactor() const {
@@ -416,7 +445,7 @@ void BrowserPlugin::ScreenInfoChanged(const ScreenInfo& screen_info) {
pending_resize_params_.screen_info = screen_info;
if (guest_crashed_) {
// Update the sad page to match the current ScreenInfo.
- compositing_helper_->ChildFrameGone(frame_rect().size(),
+ compositing_helper_->ChildFrameGone(screen_space_rect().size(),
screen_info.device_scale_factor);
return;
}
@@ -537,7 +566,7 @@ void BrowserPlugin::UpdateGeometry(const WebRect& plugin_rect_in_viewport,
// If this local root belongs to an OOPIF, on the browser side we will have to
// consider the displacement of the child frame in root window.
embedding_render_widget_->ConvertViewportToWindow(&rect_in_css);
- gfx::Rect frame_rect = rect_in_css;
+ gfx::Rect screen_space_rect = rect_in_css;
if (!ready_) {
if (delegate_)
@@ -545,10 +574,10 @@ void BrowserPlugin::UpdateGeometry(const WebRect& plugin_rect_in_viewport,
ready_ = true;
}
- pending_resize_params_.frame_rect = frame_rect;
+ pending_resize_params_.screen_space_rect = screen_space_rect;
if (guest_crashed_) {
// Update the sad page to match the current ScreenInfo.
- compositing_helper_->ChildFrameGone(frame_rect.size(),
+ compositing_helper_->ChildFrameGone(screen_space_rect.size(),
screen_info().device_scale_factor);
return;
}
@@ -783,7 +812,7 @@ void BrowserPlugin::OnMusEmbeddedFrameSurfaceChanged(
return;
compositing_helper_->SetFallbackSurfaceId(surface_info.id(),
- frame_rect().size());
+ screen_space_rect().size());
}
void BrowserPlugin::OnMusEmbeddedFrameSinkIdAllocated(
diff --git a/chromium/content/renderer/browser_plugin/browser_plugin.h b/chromium/content/renderer/browser_plugin/browser_plugin.h
index 65dc203fc55..a123a1bf87f 100644
--- a/chromium/content/renderer/browser_plugin/browser_plugin.h
+++ b/chromium/content/renderer/browser_plugin/browser_plugin.h
@@ -5,7 +5,7 @@
#ifndef CONTENT_RENDERER_BROWSER_PLUGIN_BROWSER_PLUGIN_H_
#define CONTENT_RENDERER_BROWSER_PLUGIN_BROWSER_PLUGIN_H_
-#include "third_party/WebKit/public/web/WebPlugin.h"
+#include "third_party/blink/public/web/web_plugin.h"
#include <memory>
@@ -16,14 +16,15 @@
#include "components/viz/common/surfaces/frame_sink_id.h"
#include "components/viz/common/surfaces/local_surface_id.h"
#include "components/viz/common/surfaces/parent_local_surface_id_allocator.h"
+#include "content/common/frame_resize_params.h"
#include "content/public/common/screen_info.h"
#include "content/renderer/child_frame_compositor.h"
#include "content/renderer/mouse_lock_dispatcher.h"
#include "content/renderer/render_view_impl.h"
-#include "third_party/WebKit/public/web/WebDragStatus.h"
-#include "third_party/WebKit/public/web/WebImeTextSpan.h"
-#include "third_party/WebKit/public/web/WebInputMethodController.h"
-#include "third_party/WebKit/public/web/WebNode.h"
+#include "third_party/blink/public/web/web_drag_status.h"
+#include "third_party/blink/public/web/web_ime_text_span.h"
+#include "third_party/blink/public/web/web_input_method_controller.h"
+#include "third_party/blink/public/web/web_node.h"
#if defined(USE_AURA)
#include "content/renderer/mus/mus_embedded_frame_delegate.h"
@@ -163,8 +164,8 @@ class CONTENT_EXPORT BrowserPlugin : public blink::WebPlugin,
~BrowserPlugin() override;
- const gfx::Rect& frame_rect() const {
- return pending_resize_params_.frame_rect;
+ const gfx::Rect& screen_space_rect() const {
+ return pending_resize_params_.screen_space_rect;
}
gfx::Rect FrameRectInPixels() const;
float GetDeviceScaleFactor() const;
@@ -174,7 +175,7 @@ class CONTENT_EXPORT BrowserPlugin : public blink::WebPlugin,
}
uint64_t auto_size_sequence_number() const {
- return pending_resize_params_.sequence_number;
+ return pending_resize_params_.auto_resize_sequence_number;
}
void UpdateInternalInstanceId();
@@ -193,6 +194,10 @@ class CONTENT_EXPORT BrowserPlugin : public blink::WebPlugin,
void OnGuestReady(int instance_id, const viz::FrameSinkId& frame_sink_id);
void OnResizeDueToAutoResize(int browser_plugin_instance_id,
uint64_t sequence_number);
+ void OnEnableAutoResize(int browser_plugin_instance_id,
+ const gfx::Size& min_size,
+ const gfx::Size& max_size);
+ void OnDisableAutoResize(int browser_plugin_instance_id);
void OnSetChildFrameSurface(int instance_id,
const viz::SurfaceInfo& surface_info);
void OnSetContentsOpaque(int instance_id, bool opaque);
@@ -252,19 +257,12 @@ class CONTENT_EXPORT BrowserPlugin : public blink::WebPlugin,
bool enable_surface_synchronization_ = false;
- // TODO(fsamuel): We might want to unify this with content::ResizeParams.
- struct ResizeParams {
- gfx::Rect frame_rect;
- ScreenInfo screen_info;
- uint64_t sequence_number = 0lu;
- };
-
// The last ResizeParams sent to the browser process, if any.
- base::Optional<ResizeParams> sent_resize_params_;
+ base::Optional<FrameResizeParams> sent_resize_params_;
// The current set of ResizeParams. This may or may not match
// |sent_resize_params_|.
- ResizeParams pending_resize_params_;
+ FrameResizeParams pending_resize_params_;
// We call lifetime managing methods on |delegate_|, but we do not directly
// own this. The delegate destroys itself.
diff --git a/chromium/content/renderer/browser_render_view_browsertest.cc b/chromium/content/renderer/browser_render_view_browsertest.cc
index 4d4a316affb..88a0573dac3 100644
--- a/chromium/content/renderer/browser_render_view_browsertest.cc
+++ b/chromium/content/renderer/browser_render_view_browsertest.cc
@@ -37,9 +37,9 @@
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebURLError.h"
-#include "third_party/WebKit/public/platform/WebURLRequest.h"
-#include "third_party/WebKit/public/web/WebFrame.h"
+#include "third_party/blink/public/platform/web_url_error.h"
+#include "third_party/blink/public/platform/web_url_request.h"
+#include "third_party/blink/public/web/web_frame.h"
namespace content {
@@ -129,7 +129,7 @@ void ClearCache(net::URLRequestContextGetter* getter,
// of scope.
if (net::OK == cache->GetBackend(backend_ptr, backend_callback)) {
// The call completed synchronously, so GetBackend didn't run the callback.
- backend_callback.Run(net::OK);
+ std::move(backend_callback).Run(net::OK);
}
}
diff --git a/chromium/content/renderer/cache_storage/cache_storage_dispatcher.cc b/chromium/content/renderer/cache_storage/cache_storage_dispatcher.cc
deleted file mode 100644
index 2154f955168..00000000000
--- a/chromium/content/renderer/cache_storage/cache_storage_dispatcher.cc
+++ /dev/null
@@ -1,670 +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 "content/renderer/cache_storage/cache_storage_dispatcher.h"
-
-#include <stddef.h>
-
-#include <map>
-#include <memory>
-#include <string>
-#include <utility>
-
-#include "base/lazy_instance.h"
-#include "base/logging.h"
-#include "base/metrics/histogram_macros.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/threading/thread_local.h"
-#include "content/child/thread_safe_sender.h"
-#include "content/common/cache_storage/cache_storage_messages.h"
-#include "content/public/common/content_features.h"
-#include "content/public/common/referrer.h"
-#include "content/public/renderer/render_thread.h"
-#include "content/renderer/service_worker/service_worker_type_util.h"
-#include "storage/common/blob_storage/blob_handle.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerCache.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerRequest.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerResponse.h"
-#include "url/origin.h"
-
-
-namespace content {
-
-using base::TimeTicks;
-using blink::mojom::CacheStorageError;
-using blink::WebServiceWorkerCacheStorage;
-using blink::WebServiceWorkerRequest;
-using blink::WebString;
-
-static base::LazyInstance<base::ThreadLocalPointer<CacheStorageDispatcher>>::
- Leaky g_cache_storage_dispatcher_tls = LAZY_INSTANCE_INITIALIZER;
-
-namespace {
-
-CacheStorageDispatcher* const kDeletedCacheStorageDispatcherMarker =
- reinterpret_cast<CacheStorageDispatcher*>(0x1);
-
-ServiceWorkerFetchRequest FetchRequestFromWebRequest(
- const blink::WebServiceWorkerRequest& web_request) {
- ServiceWorkerHeaderMap headers;
- GetServiceWorkerHeaderMapFromWebRequest(web_request, &headers);
-
- return ServiceWorkerFetchRequest(
- web_request.Url(), web_request.Method().Ascii(), headers,
- Referrer(web_request.ReferrerUrl(), web_request.GetReferrerPolicy()),
- web_request.IsReload());
-}
-
-void PopulateWebRequestFromFetchRequest(
- const ServiceWorkerFetchRequest& request,
- blink::WebServiceWorkerRequest* web_request) {
- web_request->SetURL(request.url);
- web_request->SetMethod(WebString::FromASCII(request.method));
- for (ServiceWorkerHeaderMap::const_iterator i = request.headers.begin(),
- end = request.headers.end();
- i != end; ++i) {
- web_request->SetHeader(WebString::FromASCII(i->first),
- WebString::FromASCII(i->second));
- }
- web_request->SetReferrer(WebString::FromASCII(request.referrer.url.spec()),
- request.referrer.policy);
- web_request->SetIsReload(request.is_reload);
-}
-
-blink::WebVector<blink::WebServiceWorkerRequest> WebRequestsFromRequests(
- const std::vector<ServiceWorkerFetchRequest>& requests) {
- blink::WebVector<blink::WebServiceWorkerRequest> web_requests(
- requests.size());
- for (size_t i = 0; i < requests.size(); ++i)
- PopulateWebRequestFromFetchRequest(requests[i], &(web_requests[i]));
- return web_requests;
-}
-
-CacheStorageCacheQueryParams QueryParamsFromWebQueryParams(
- const blink::WebServiceWorkerCache::QueryParams& web_query_params) {
- CacheStorageCacheQueryParams query_params;
- query_params.ignore_search = web_query_params.ignore_search;
- query_params.ignore_method = web_query_params.ignore_method;
- query_params.ignore_vary = web_query_params.ignore_vary;
- query_params.cache_name =
- blink::WebString::ToNullableString16(web_query_params.cache_name);
- return query_params;
-}
-
-CacheStorageCacheOperationType CacheOperationTypeFromWebCacheOperationType(
- blink::WebServiceWorkerCache::OperationType operation_type) {
- switch (operation_type) {
- case blink::WebServiceWorkerCache::kOperationTypePut:
- return CACHE_STORAGE_CACHE_OPERATION_TYPE_PUT;
- case blink::WebServiceWorkerCache::kOperationTypeDelete:
- return CACHE_STORAGE_CACHE_OPERATION_TYPE_DELETE;
- default:
- return CACHE_STORAGE_CACHE_OPERATION_TYPE_UNDEFINED;
- }
-}
-
-CacheStorageBatchOperation BatchOperationFromWebBatchOperation(
- const blink::WebServiceWorkerCache::BatchOperation& web_operation) {
- CacheStorageBatchOperation operation;
- operation.operation_type =
- CacheOperationTypeFromWebCacheOperationType(web_operation.operation_type);
- operation.request = FetchRequestFromWebRequest(web_operation.request);
- operation.response =
- GetServiceWorkerResponseFromWebResponse(web_operation.response);
- operation.match_params =
- QueryParamsFromWebQueryParams(web_operation.match_params);
- return operation;
-}
-
-template <typename T>
-void ClearCallbacksMapWithErrors(T* callbacks_map) {
- typename T::iterator iter(callbacks_map);
- while (!iter.IsAtEnd()) {
- iter.GetCurrentValue()->OnError(CacheStorageError::kErrorNotFound);
- callbacks_map->Remove(iter.GetCurrentKey());
- iter.Advance();
- }
-}
-
-} // namespace
-
-// The WebCache object is the Chromium side implementation of the Blink
-// WebServiceWorkerCache API. Most of its methods delegate directly to the
-// ServiceWorkerStorage object, which is able to assign unique IDs as well
-// as have a lifetime longer than the requests.
-class CacheStorageDispatcher::WebCache : public blink::WebServiceWorkerCache {
- public:
- WebCache(base::WeakPtr<CacheStorageDispatcher> dispatcher, int cache_id)
- : dispatcher_(dispatcher), cache_id_(cache_id) {}
-
- ~WebCache() override {
- if (dispatcher_)
- dispatcher_->OnWebCacheDestruction(cache_id_);
- }
-
- // From blink::WebServiceWorkerCache:
- void DispatchMatch(std::unique_ptr<CacheMatchCallbacks> callbacks,
- const blink::WebServiceWorkerRequest& request,
- const QueryParams& query_params) override {
- if (!dispatcher_)
- return;
- dispatcher_->dispatchMatchForCache(cache_id_, std::move(callbacks), request,
- query_params);
- }
- void DispatchMatchAll(std::unique_ptr<CacheWithResponsesCallbacks> callbacks,
- const blink::WebServiceWorkerRequest& request,
- const QueryParams& query_params) override {
- if (!dispatcher_)
- return;
- dispatcher_->dispatchMatchAllForCache(cache_id_, std::move(callbacks),
- request, query_params);
- }
- void DispatchKeys(std::unique_ptr<CacheWithRequestsCallbacks> callbacks,
- const blink::WebServiceWorkerRequest& request,
- const QueryParams& query_params) override {
- if (!dispatcher_)
- return;
- dispatcher_->dispatchKeysForCache(cache_id_, std::move(callbacks), request,
- query_params);
- }
- void DispatchBatch(
- std::unique_ptr<CacheBatchCallbacks> callbacks,
- const blink::WebVector<BatchOperation>& batch_operations) override {
- if (!dispatcher_)
- return;
- dispatcher_->dispatchBatchForCache(cache_id_, std::move(callbacks),
- batch_operations);
- }
-
- private:
- const base::WeakPtr<CacheStorageDispatcher> dispatcher_;
- const int cache_id_;
-};
-
-CacheStorageDispatcher::CacheStorageDispatcher(
- ThreadSafeSender* thread_safe_sender)
- : thread_safe_sender_(thread_safe_sender), weak_factory_(this) {
- g_cache_storage_dispatcher_tls.Pointer()->Set(this);
-}
-
-CacheStorageDispatcher::~CacheStorageDispatcher() {
- ClearCallbacksMapWithErrors(&has_callbacks_);
- ClearCallbacksMapWithErrors(&open_callbacks_);
- ClearCallbacksMapWithErrors(&delete_callbacks_);
- ClearCallbacksMapWithErrors(&keys_callbacks_);
- ClearCallbacksMapWithErrors(&match_callbacks_);
-
- ClearCallbacksMapWithErrors(&cache_match_callbacks_);
- ClearCallbacksMapWithErrors(&cache_match_all_callbacks_);
- ClearCallbacksMapWithErrors(&cache_keys_callbacks_);
- ClearCallbacksMapWithErrors(&cache_batch_callbacks_);
-
- g_cache_storage_dispatcher_tls.Pointer()->Set(
- kDeletedCacheStorageDispatcherMarker);
-}
-
-CacheStorageDispatcher* CacheStorageDispatcher::ThreadSpecificInstance(
- ThreadSafeSender* thread_safe_sender) {
- if (g_cache_storage_dispatcher_tls.Pointer()->Get() ==
- kDeletedCacheStorageDispatcherMarker) {
- NOTREACHED() << "Re-instantiating TLS CacheStorageDispatcher.";
- g_cache_storage_dispatcher_tls.Pointer()->Set(nullptr);
- }
- if (g_cache_storage_dispatcher_tls.Pointer()->Get())
- return g_cache_storage_dispatcher_tls.Pointer()->Get();
-
- CacheStorageDispatcher* dispatcher =
- new CacheStorageDispatcher(thread_safe_sender);
- if (WorkerThread::GetCurrentId())
- WorkerThread::AddObserver(dispatcher);
- return dispatcher;
-}
-
-void CacheStorageDispatcher::WillStopCurrentWorkerThread() {
- delete this;
-}
-
-bool CacheStorageDispatcher::Send(IPC::Message* msg) {
- return thread_safe_sender_->Send(msg);
-}
-
-bool CacheStorageDispatcher::OnMessageReceived(const IPC::Message& message) {
- bool handled = true;
- IPC_BEGIN_MESSAGE_MAP(CacheStorageDispatcher, message)
- IPC_MESSAGE_HANDLER(CacheStorageMsg_CacheStorageHasSuccess,
- OnCacheStorageHasSuccess)
- IPC_MESSAGE_HANDLER(CacheStorageMsg_CacheStorageOpenSuccess,
- OnCacheStorageOpenSuccess)
- IPC_MESSAGE_HANDLER(CacheStorageMsg_CacheStorageDeleteSuccess,
- OnCacheStorageDeleteSuccess)
- IPC_MESSAGE_HANDLER(CacheStorageMsg_CacheStorageKeysSuccess,
- OnCacheStorageKeysSuccess)
- IPC_MESSAGE_HANDLER(CacheStorageMsg_CacheStorageMatchSuccess,
- OnCacheStorageMatchSuccess)
- IPC_MESSAGE_HANDLER(CacheStorageMsg_CacheStorageHasError,
- OnCacheStorageHasError)
- IPC_MESSAGE_HANDLER(CacheStorageMsg_CacheStorageOpenError,
- OnCacheStorageOpenError)
- IPC_MESSAGE_HANDLER(CacheStorageMsg_CacheStorageDeleteError,
- OnCacheStorageDeleteError)
- IPC_MESSAGE_HANDLER(CacheStorageMsg_CacheStorageMatchError,
- OnCacheStorageMatchError)
- IPC_MESSAGE_HANDLER(CacheStorageMsg_CacheMatchSuccess,
- OnCacheMatchSuccess)
- IPC_MESSAGE_HANDLER(CacheStorageMsg_CacheMatchAllSuccess,
- OnCacheMatchAllSuccess)
- IPC_MESSAGE_HANDLER(CacheStorageMsg_CacheKeysSuccess, OnCacheKeysSuccess)
- IPC_MESSAGE_HANDLER(CacheStorageMsg_CacheBatchSuccess,
- OnCacheBatchSuccess)
- IPC_MESSAGE_HANDLER(CacheStorageMsg_CacheMatchError, OnCacheMatchError)
- IPC_MESSAGE_HANDLER(CacheStorageMsg_CacheMatchAllError,
- OnCacheMatchAllError)
- IPC_MESSAGE_HANDLER(CacheStorageMsg_CacheKeysError, OnCacheKeysError)
- IPC_MESSAGE_HANDLER(CacheStorageMsg_CacheBatchError, OnCacheBatchError)
- IPC_MESSAGE_UNHANDLED(handled = false)
- IPC_END_MESSAGE_MAP()
-
- return handled;
-}
-
-void CacheStorageDispatcher::OnCacheStorageHasSuccess(int thread_id,
- int request_id) {
- DCHECK_EQ(thread_id, CurrentWorkerId());
- UMA_HISTOGRAM_TIMES("ServiceWorkerCache.CacheStorage.Has",
- TimeTicks::Now() - has_times_[request_id]);
- WebServiceWorkerCacheStorage::CacheStorageCallbacks* callbacks =
- has_callbacks_.Lookup(request_id);
- callbacks->OnSuccess();
- has_callbacks_.Remove(request_id);
- has_times_.erase(request_id);
-}
-
-void CacheStorageDispatcher::OnCacheStorageOpenSuccess(int thread_id,
- int request_id,
- int cache_id) {
- DCHECK_EQ(thread_id, CurrentWorkerId());
- std::unique_ptr<WebCache> web_cache(
- new WebCache(weak_factory_.GetWeakPtr(), cache_id));
- web_caches_.AddWithID(web_cache.get(), cache_id);
- UMA_HISTOGRAM_TIMES("ServiceWorkerCache.CacheStorage.Open",
- TimeTicks::Now() - open_times_[request_id]);
- WebServiceWorkerCacheStorage::CacheStorageWithCacheCallbacks* callbacks =
- open_callbacks_.Lookup(request_id);
- callbacks->OnSuccess(std::move(web_cache));
- open_callbacks_.Remove(request_id);
- open_times_.erase(request_id);
-}
-
-void CacheStorageDispatcher::OnCacheStorageDeleteSuccess(int thread_id,
- int request_id) {
- DCHECK_EQ(thread_id, CurrentWorkerId());
- UMA_HISTOGRAM_TIMES("ServiceWorkerCache.CacheStorage.Delete",
- TimeTicks::Now() - delete_times_[request_id]);
- WebServiceWorkerCacheStorage::CacheStorageCallbacks* callbacks =
- delete_callbacks_.Lookup(request_id);
- callbacks->OnSuccess();
- delete_callbacks_.Remove(request_id);
- delete_times_.erase(request_id);
-}
-
-void CacheStorageDispatcher::OnCacheStorageKeysSuccess(
- int thread_id,
- int request_id,
- const std::vector<base::string16>& keys) {
- DCHECK_EQ(thread_id, CurrentWorkerId());
- blink::WebVector<blink::WebString> web_keys(keys.size());
- std::transform(
- keys.begin(), keys.end(), web_keys.begin(),
- [](const base::string16& s) { return WebString::FromUTF16(s); });
- UMA_HISTOGRAM_TIMES("ServiceWorkerCache.CacheStorage.Keys",
- TimeTicks::Now() - keys_times_[request_id]);
- WebServiceWorkerCacheStorage::CacheStorageKeysCallbacks* callbacks =
- keys_callbacks_.Lookup(request_id);
- callbacks->OnSuccess(web_keys);
- keys_callbacks_.Remove(request_id);
- keys_times_.erase(request_id);
-}
-
-void CacheStorageDispatcher::OnCacheStorageMatchSuccess(
- int thread_id,
- int request_id,
- const ServiceWorkerResponse& response) {
- DCHECK_EQ(thread_id, CurrentWorkerId());
- blink::WebServiceWorkerResponse web_response;
- PopulateWebResponseFromResponse(response, &web_response);
-
- UMA_HISTOGRAM_TIMES("ServiceWorkerCache.CacheStorage.Match",
- TimeTicks::Now() - match_times_[request_id]);
- WebServiceWorkerCacheStorage::CacheStorageMatchCallbacks* callbacks =
- match_callbacks_.Lookup(request_id);
- callbacks->OnSuccess(web_response);
- match_callbacks_.Remove(request_id);
- match_times_.erase(request_id);
-}
-
-void CacheStorageDispatcher::OnCacheStorageHasError(int thread_id,
- int request_id,
- CacheStorageError reason) {
- DCHECK_EQ(thread_id, CurrentWorkerId());
- WebServiceWorkerCacheStorage::CacheStorageCallbacks* callbacks =
- has_callbacks_.Lookup(request_id);
- callbacks->OnError(reason);
- has_callbacks_.Remove(request_id);
- has_times_.erase(request_id);
-}
-
-void CacheStorageDispatcher::OnCacheStorageOpenError(int thread_id,
- int request_id,
- CacheStorageError reason) {
- DCHECK_EQ(thread_id, CurrentWorkerId());
- WebServiceWorkerCacheStorage::CacheStorageWithCacheCallbacks* callbacks =
- open_callbacks_.Lookup(request_id);
- callbacks->OnError(reason);
- open_callbacks_.Remove(request_id);
- open_times_.erase(request_id);
-}
-
-void CacheStorageDispatcher::OnCacheStorageDeleteError(
- int thread_id,
- int request_id,
- CacheStorageError reason) {
- DCHECK_EQ(thread_id, CurrentWorkerId());
- WebServiceWorkerCacheStorage::CacheStorageCallbacks* callbacks =
- delete_callbacks_.Lookup(request_id);
- callbacks->OnError(reason);
- delete_callbacks_.Remove(request_id);
- delete_times_.erase(request_id);
-}
-
-void CacheStorageDispatcher::OnCacheStorageMatchError(
- int thread_id,
- int request_id,
- CacheStorageError reason) {
- DCHECK_EQ(thread_id, CurrentWorkerId());
- WebServiceWorkerCacheStorage::CacheStorageMatchCallbacks* callbacks =
- match_callbacks_.Lookup(request_id);
- callbacks->OnError(reason);
- match_callbacks_.Remove(request_id);
- match_times_.erase(request_id);
-}
-
-void CacheStorageDispatcher::OnCacheMatchSuccess(
- int thread_id,
- int request_id,
- const ServiceWorkerResponse& response) {
- DCHECK_EQ(thread_id, CurrentWorkerId());
- blink::WebServiceWorkerResponse web_response;
- PopulateWebResponseFromResponse(response, &web_response);
-
- UMA_HISTOGRAM_TIMES("ServiceWorkerCache.Cache.Match",
- TimeTicks::Now() - cache_match_times_[request_id]);
- blink::WebServiceWorkerCache::CacheMatchCallbacks* callbacks =
- cache_match_callbacks_.Lookup(request_id);
- callbacks->OnSuccess(web_response);
- cache_match_callbacks_.Remove(request_id);
- cache_match_times_.erase(request_id);
-}
-
-void CacheStorageDispatcher::OnCacheMatchAllSuccess(
- int thread_id,
- int request_id,
- const std::vector<ServiceWorkerResponse>& responses) {
- DCHECK_EQ(thread_id, CurrentWorkerId());
-
- UMA_HISTOGRAM_TIMES("ServiceWorkerCache.Cache.MatchAll",
- TimeTicks::Now() - cache_match_all_times_[request_id]);
- blink::WebServiceWorkerCache::CacheWithResponsesCallbacks* callbacks =
- cache_match_all_callbacks_.Lookup(request_id);
- callbacks->OnSuccess(WebResponsesFromResponses(responses));
- cache_match_all_callbacks_.Remove(request_id);
- cache_match_all_times_.erase(request_id);
-}
-
-void CacheStorageDispatcher::OnCacheKeysSuccess(
- int thread_id,
- int request_id,
- const std::vector<ServiceWorkerFetchRequest>& requests) {
- DCHECK_EQ(thread_id, CurrentWorkerId());
-
- UMA_HISTOGRAM_TIMES("ServiceWorkerCache.Cache.Keys",
- TimeTicks::Now() - cache_keys_times_[request_id]);
- blink::WebServiceWorkerCache::CacheWithRequestsCallbacks* callbacks =
- cache_keys_callbacks_.Lookup(request_id);
- callbacks->OnSuccess(WebRequestsFromRequests(requests));
- cache_keys_callbacks_.Remove(request_id);
- cache_keys_times_.erase(request_id);
-}
-
-void CacheStorageDispatcher::OnCacheBatchSuccess(
- int thread_id,
- int request_id) {
- DCHECK_EQ(thread_id, CurrentWorkerId());
-
- UMA_HISTOGRAM_TIMES("ServiceWorkerCache.Cache.Batch",
- TimeTicks::Now() - cache_batch_times_[request_id]);
- blink::WebServiceWorkerCache::CacheBatchCallbacks* callbacks =
- cache_batch_callbacks_.Lookup(request_id);
- callbacks->OnSuccess();
- cache_batch_callbacks_.Remove(request_id);
- cache_batch_times_.erase(request_id);
-}
-
-void CacheStorageDispatcher::OnCacheMatchError(int thread_id,
- int request_id,
- CacheStorageError reason) {
- DCHECK_EQ(thread_id, CurrentWorkerId());
- blink::WebServiceWorkerCache::CacheMatchCallbacks* callbacks =
- cache_match_callbacks_.Lookup(request_id);
- callbacks->OnError(reason);
- cache_match_callbacks_.Remove(request_id);
- cache_match_times_.erase(request_id);
-}
-
-void CacheStorageDispatcher::OnCacheMatchAllError(int thread_id,
- int request_id,
- CacheStorageError reason) {
- DCHECK_EQ(thread_id, CurrentWorkerId());
- blink::WebServiceWorkerCache::CacheWithResponsesCallbacks* callbacks =
- cache_match_all_callbacks_.Lookup(request_id);
- callbacks->OnError(reason);
- cache_match_all_callbacks_.Remove(request_id);
- cache_match_all_times_.erase(request_id);
-}
-
-void CacheStorageDispatcher::OnCacheKeysError(int thread_id,
- int request_id,
- CacheStorageError reason) {
- DCHECK_EQ(thread_id, CurrentWorkerId());
- blink::WebServiceWorkerCache::CacheWithRequestsCallbacks* callbacks =
- cache_keys_callbacks_.Lookup(request_id);
- callbacks->OnError(reason);
- cache_keys_callbacks_.Remove(request_id);
- cache_keys_times_.erase(request_id);
-}
-
-void CacheStorageDispatcher::OnCacheBatchError(int thread_id,
- int request_id,
- CacheStorageError reason) {
- DCHECK_EQ(thread_id, CurrentWorkerId());
- blink::WebServiceWorkerCache::CacheBatchCallbacks* callbacks =
- cache_batch_callbacks_.Lookup(request_id);
- callbacks->OnError(CacheStorageError(reason));
- cache_batch_callbacks_.Remove(request_id);
- cache_batch_times_.erase(request_id);
-}
-
-void CacheStorageDispatcher::dispatchHas(
- std::unique_ptr<WebServiceWorkerCacheStorage::CacheStorageCallbacks>
- callbacks,
- const url::Origin& origin,
- const blink::WebString& cacheName) {
- int request_id = has_callbacks_.Add(std::move(callbacks));
- has_times_[request_id] = base::TimeTicks::Now();
- Send(new CacheStorageHostMsg_CacheStorageHas(CurrentWorkerId(), request_id,
- origin, cacheName.Utf16()));
-}
-
-void CacheStorageDispatcher::dispatchOpen(
- std::unique_ptr<
- WebServiceWorkerCacheStorage::CacheStorageWithCacheCallbacks> callbacks,
- const url::Origin& origin,
- const blink::WebString& cacheName) {
- int request_id = open_callbacks_.Add(std::move(callbacks));
- open_times_[request_id] = base::TimeTicks::Now();
- Send(new CacheStorageHostMsg_CacheStorageOpen(CurrentWorkerId(), request_id,
- origin, cacheName.Utf16()));
-}
-
-void CacheStorageDispatcher::dispatchDelete(
- std::unique_ptr<WebServiceWorkerCacheStorage::CacheStorageCallbacks>
- callbacks,
- const url::Origin& origin,
- const blink::WebString& cacheName) {
- int request_id = delete_callbacks_.Add(std::move(callbacks));
- delete_times_[request_id] = base::TimeTicks::Now();
- Send(new CacheStorageHostMsg_CacheStorageDelete(CurrentWorkerId(), request_id,
- origin, cacheName.Utf16()));
-}
-
-void CacheStorageDispatcher::dispatchKeys(
- std::unique_ptr<WebServiceWorkerCacheStorage::CacheStorageKeysCallbacks>
- callbacks,
- const url::Origin& origin) {
- int request_id = keys_callbacks_.Add(std::move(callbacks));
- keys_times_[request_id] = base::TimeTicks::Now();
- Send(new CacheStorageHostMsg_CacheStorageKeys(CurrentWorkerId(), request_id,
- origin));
-}
-
-void CacheStorageDispatcher::dispatchMatch(
- std::unique_ptr<WebServiceWorkerCacheStorage::CacheStorageMatchCallbacks>
- callbacks,
- const url::Origin& origin,
- const blink::WebServiceWorkerRequest& request,
- const blink::WebServiceWorkerCache::QueryParams& query_params) {
- int request_id = match_callbacks_.Add(std::move(callbacks));
- match_times_[request_id] = base::TimeTicks::Now();
- Send(new CacheStorageHostMsg_CacheStorageMatch(
- CurrentWorkerId(), request_id, origin,
- FetchRequestFromWebRequest(request),
- QueryParamsFromWebQueryParams(query_params)));
-}
-
-void CacheStorageDispatcher::dispatchMatchForCache(
- int cache_id,
- std::unique_ptr<blink::WebServiceWorkerCache::CacheMatchCallbacks>
- callbacks,
- const blink::WebServiceWorkerRequest& request,
- const blink::WebServiceWorkerCache::QueryParams& query_params) {
- int request_id = cache_match_callbacks_.Add(std::move(callbacks));
- cache_match_times_[request_id] = base::TimeTicks::Now();
-
- Send(new CacheStorageHostMsg_CacheMatch(
- CurrentWorkerId(), request_id, cache_id,
- FetchRequestFromWebRequest(request),
- QueryParamsFromWebQueryParams(query_params)));
-}
-
-void CacheStorageDispatcher::dispatchMatchAllForCache(
- int cache_id,
- std::unique_ptr<blink::WebServiceWorkerCache::CacheWithResponsesCallbacks>
- callbacks,
- const blink::WebServiceWorkerRequest& request,
- const blink::WebServiceWorkerCache::QueryParams& query_params) {
- int request_id = cache_match_all_callbacks_.Add(std::move(callbacks));
- cache_match_all_times_[request_id] = base::TimeTicks::Now();
-
- Send(new CacheStorageHostMsg_CacheMatchAll(
- CurrentWorkerId(), request_id, cache_id,
- FetchRequestFromWebRequest(request),
- QueryParamsFromWebQueryParams(query_params)));
-}
-
-void CacheStorageDispatcher::dispatchKeysForCache(
- int cache_id,
- std::unique_ptr<blink::WebServiceWorkerCache::CacheWithRequestsCallbacks>
- callbacks,
- const blink::WebServiceWorkerRequest& request,
- const blink::WebServiceWorkerCache::QueryParams& query_params) {
- int request_id = cache_keys_callbacks_.Add(std::move(callbacks));
- cache_keys_times_[request_id] = base::TimeTicks::Now();
-
- Send(new CacheStorageHostMsg_CacheKeys(
- CurrentWorkerId(), request_id, cache_id,
- FetchRequestFromWebRequest(request),
- QueryParamsFromWebQueryParams(query_params)));
-}
-
-void CacheStorageDispatcher::dispatchBatchForCache(
- int cache_id,
- std::unique_ptr<blink::WebServiceWorkerCache::CacheBatchCallbacks>
- callbacks,
- const blink::WebVector<blink::WebServiceWorkerCache::BatchOperation>&
- web_operations) {
- int request_id = cache_batch_callbacks_.Add(std::move(callbacks));
- cache_batch_times_[request_id] = base::TimeTicks::Now();
-
- std::vector<CacheStorageBatchOperation> operations;
- operations.reserve(web_operations.size());
- for (size_t i = 0; i < web_operations.size(); ++i) {
- operations.push_back(
- BatchOperationFromWebBatchOperation(web_operations[i]));
- }
-
- Send(new CacheStorageHostMsg_CacheBatch(CurrentWorkerId(), request_id,
- cache_id, operations));
-}
-
-void CacheStorageDispatcher::OnWebCacheDestruction(int cache_id) {
- web_caches_.Remove(cache_id);
- Send(new CacheStorageHostMsg_CacheClosed(cache_id));
-}
-
-void CacheStorageDispatcher::PopulateWebResponseFromResponse(
- const ServiceWorkerResponse& response,
- blink::WebServiceWorkerResponse* web_response) {
- web_response->SetURLList(response.url_list);
- web_response->SetStatus(response.status_code);
- web_response->SetStatusText(WebString::FromASCII(response.status_text));
- web_response->SetResponseType(response.response_type);
- web_response->SetResponseTime(response.response_time);
- web_response->SetCacheStorageCacheName(
- response.is_in_cache_storage
- ? blink::WebString::FromUTF8(response.cache_storage_cache_name)
- : blink::WebString());
- blink::WebVector<blink::WebString> headers(
- response.cors_exposed_header_names.size());
- std::transform(response.cors_exposed_header_names.begin(),
- response.cors_exposed_header_names.end(), headers.begin(),
- [](const std::string& s) { return WebString::FromLatin1(s); });
- web_response->SetCorsExposedHeaderNames(headers);
-
- for (const auto& i : response.headers) {
- web_response->SetHeader(WebString::FromASCII(i.first),
- WebString::FromASCII(i.second));
- }
-
- if (!response.blob_uuid.empty()) {
- DCHECK(response.blob);
- mojo::ScopedMessagePipeHandle blob_pipe;
- if (response.blob)
- blob_pipe = response.blob->Clone().PassInterface().PassHandle();
- web_response->SetBlob(blink::WebString::FromUTF8(response.blob_uuid),
- response.blob_size, std::move(blob_pipe));
- // Let the host know that it can release its reference to the blob.
- Send(new CacheStorageHostMsg_BlobDataHandled(response.blob_uuid));
- }
-}
-
-blink::WebVector<blink::WebServiceWorkerResponse>
-CacheStorageDispatcher::WebResponsesFromResponses(
- const std::vector<ServiceWorkerResponse>& responses) {
- blink::WebVector<blink::WebServiceWorkerResponse> web_responses(
- responses.size());
- for (size_t i = 0; i < responses.size(); ++i)
- PopulateWebResponseFromResponse(responses[i], &(web_responses[i]));
- return web_responses;
-}
-
-} // namespace content
diff --git a/chromium/content/renderer/cache_storage/cache_storage_dispatcher.h b/chromium/content/renderer/cache_storage/cache_storage_dispatcher.h
deleted file mode 100644
index 6130bf8bc21..00000000000
--- a/chromium/content/renderer/cache_storage/cache_storage_dispatcher.h
+++ /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.
-
-#ifndef CONTENT_RENDERER_CACHE_STORAGE_CACHE_STORAGE_DISPATCHER_H_
-#define CONTENT_RENDERER_CACHE_STORAGE_CACHE_STORAGE_DISPATCHER_H_
-
-#include <stdint.h>
-
-#include <memory>
-#include <vector>
-
-#include "base/containers/id_map.h"
-#include "base/macros.h"
-#include "base/memory/weak_ptr.h"
-#include "base/strings/string16.h"
-#include "base/time/time.h"
-#include "content/public/renderer/worker_thread.h"
-#include "ipc/ipc_message.h"
-#include "third_party/WebKit/public/platform/modules/cache_storage/cache_storage.mojom.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerCache.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerCacheStorage.h"
-
-namespace url {
-class Origin;
-}
-
-namespace content {
-
-class ThreadSafeSender;
-struct ServiceWorkerFetchRequest;
-struct ServiceWorkerResponse;
-
-// Handle the Cache Storage messaging for this context thread. The
-// main thread and each worker thread have their own instances.
-class CacheStorageDispatcher : public WorkerThread::Observer {
- public:
- explicit CacheStorageDispatcher(ThreadSafeSender* thread_safe_sender);
- ~CacheStorageDispatcher() override;
-
- // |thread_safe_sender| needs to be passed in because if the call leads to
- // construction it will be needed.
- static CacheStorageDispatcher* ThreadSpecificInstance(
- ThreadSafeSender* thread_safe_sender);
-
- // WorkerThread::Observer implementation.
- void WillStopCurrentWorkerThread() override;
-
- bool Send(IPC::Message* msg);
-
- // ServiceWorkerScriptContext calls our OnMessageReceived directly.
- bool OnMessageReceived(const IPC::Message& message);
-
- // Message handlers for CacheStorage messages from the browser process.
- void OnCacheStorageHasSuccess(int thread_id, int request_id);
- void OnCacheStorageOpenSuccess(int thread_id, int request_id, int cache_id);
- void OnCacheStorageDeleteSuccess(int thread_id, int request_id);
- void OnCacheStorageKeysSuccess(int thread_id,
- int request_id,
- const std::vector<base::string16>& keys);
- void OnCacheStorageMatchSuccess(int thread_id,
- int request_id,
- const ServiceWorkerResponse& response);
-
- void OnCacheStorageHasError(int thread_id,
- int request_id,
- blink::mojom::CacheStorageError reason);
- void OnCacheStorageOpenError(int thread_id,
- int request_id,
- blink::mojom::CacheStorageError reason);
- void OnCacheStorageDeleteError(int thread_id,
- int request_id,
- blink::mojom::CacheStorageError reason);
- void OnCacheStorageMatchError(int thread_id,
- int request_id,
- blink::mojom::CacheStorageError reason);
-
- // Message handlers for Cache messages from the browser process.
- void OnCacheMatchSuccess(int thread_id,
- int request_id,
- const ServiceWorkerResponse& response);
- void OnCacheMatchAllSuccess(
- int thread_id,
- int request_id,
- const std::vector<ServiceWorkerResponse>& response);
- void OnCacheKeysSuccess(
- int thread_id,
- int request_id,
- const std::vector<ServiceWorkerFetchRequest>& response);
- void OnCacheBatchSuccess(int thread_id,
- int request_id);
-
- void OnCacheMatchError(int thread_id,
- int request_id,
- blink::mojom::CacheStorageError reason);
- void OnCacheMatchAllError(int thread_id,
- int request_id,
- blink::mojom::CacheStorageError reason);
- void OnCacheKeysError(int thread_id,
- int request_id,
- blink::mojom::CacheStorageError reason);
- void OnCacheBatchError(int thread_id,
- int request_id,
- blink::mojom::CacheStorageError reason);
-
- // TODO(jsbell): These are only called by WebServiceWorkerCacheStorageImpl
- // and should be renamed to match Chromium conventions. crbug.com/439389
- void dispatchHas(
- std::unique_ptr<
- blink::WebServiceWorkerCacheStorage::CacheStorageCallbacks> callbacks,
- const url::Origin& origin,
- const blink::WebString& cacheName);
- void dispatchOpen(
- std::unique_ptr<
- blink::WebServiceWorkerCacheStorage::CacheStorageWithCacheCallbacks>
- callbacks,
- const url::Origin& origin,
- const blink::WebString& cacheName);
- void dispatchDelete(
- std::unique_ptr<
- blink::WebServiceWorkerCacheStorage::CacheStorageCallbacks> callbacks,
- const url::Origin& origin,
- const blink::WebString& cacheName);
- void dispatchKeys(
- std::unique_ptr<
- blink::WebServiceWorkerCacheStorage::CacheStorageKeysCallbacks>
- callbacks,
- const url::Origin& origin);
- void dispatchMatch(
- std::unique_ptr<
- blink::WebServiceWorkerCacheStorage::CacheStorageMatchCallbacks>
- callbacks,
- const url::Origin& origin,
- const blink::WebServiceWorkerRequest& request,
- const blink::WebServiceWorkerCache::QueryParams& query_params);
-
- // These methods are used by WebCache to forward events to the browser
- // process.
- void dispatchMatchForCache(
- int cache_id,
- std::unique_ptr<blink::WebServiceWorkerCache::CacheMatchCallbacks>
- callbacks,
- const blink::WebServiceWorkerRequest& request,
- const blink::WebServiceWorkerCache::QueryParams& query_params);
- void dispatchMatchAllForCache(
- int cache_id,
- std::unique_ptr<blink::WebServiceWorkerCache::CacheWithResponsesCallbacks>
- callbacks,
- const blink::WebServiceWorkerRequest& request,
- const blink::WebServiceWorkerCache::QueryParams& query_params);
- void dispatchKeysForCache(
- int cache_id,
- std::unique_ptr<blink::WebServiceWorkerCache::CacheWithRequestsCallbacks>
- callbacks,
- const blink::WebServiceWorkerRequest& request,
- const blink::WebServiceWorkerCache::QueryParams& query_params);
- void dispatchBatchForCache(
- int cache_id,
- std::unique_ptr<blink::WebServiceWorkerCache::CacheBatchCallbacks>
- callbacks,
- const blink::WebVector<blink::WebServiceWorkerCache::BatchOperation>&
- batch_operations);
-
- void OnWebCacheDestruction(int cache_id);
-
- private:
- class WebCache;
-
- using CallbacksMap = base::IDMap<std::unique_ptr<
- blink::WebServiceWorkerCacheStorage::CacheStorageCallbacks>>;
- using WithCacheCallbacksMap = base::IDMap<std::unique_ptr<
- blink::WebServiceWorkerCacheStorage::CacheStorageWithCacheCallbacks>>;
- using KeysCallbacksMap = base::IDMap<std::unique_ptr<
- blink::WebServiceWorkerCacheStorage::CacheStorageKeysCallbacks>>;
- using StorageMatchCallbacksMap = base::IDMap<std::unique_ptr<
- blink::WebServiceWorkerCacheStorage::CacheStorageMatchCallbacks>>;
-
- using TimeMap = base::hash_map<int32_t, base::TimeTicks>;
-
- using MatchCallbacksMap = base::IDMap<
- std::unique_ptr<blink::WebServiceWorkerCache::CacheMatchCallbacks>>;
- using WithResponsesCallbacksMap = base::IDMap<std::unique_ptr<
- blink::WebServiceWorkerCache::CacheWithResponsesCallbacks>>;
- using WithRequestsCallbacksMap = base::IDMap<std::unique_ptr<
- blink::WebServiceWorkerCache::CacheWithRequestsCallbacks>>;
- using BatchCallbacksMap = base::IDMap<
- std::unique_ptr<blink::WebServiceWorkerCache::CacheBatchCallbacks>>;
-
- static int32_t CurrentWorkerId() { return WorkerThread::GetCurrentId(); }
-
- void PopulateWebResponseFromResponse(
- const ServiceWorkerResponse& response,
- blink::WebServiceWorkerResponse* web_response);
-
- blink::WebVector<blink::WebServiceWorkerResponse> WebResponsesFromResponses(
- const std::vector<ServiceWorkerResponse>& responses);
-
- scoped_refptr<ThreadSafeSender> thread_safe_sender_;
-
- CallbacksMap has_callbacks_;
- WithCacheCallbacksMap open_callbacks_;
- CallbacksMap delete_callbacks_;
- KeysCallbacksMap keys_callbacks_;
- StorageMatchCallbacksMap match_callbacks_;
-
- TimeMap has_times_;
- TimeMap open_times_;
- TimeMap delete_times_;
- TimeMap keys_times_;
- TimeMap match_times_;
-
- // The individual caches created under this CacheStorage object.
- base::IDMap<WebCache*> web_caches_;
-
- // These ID maps are held in the CacheStorage object rather than the Cache
- // object to ensure that the IDs are unique.
- MatchCallbacksMap cache_match_callbacks_;
- WithResponsesCallbacksMap cache_match_all_callbacks_;
- WithRequestsCallbacksMap cache_keys_callbacks_;
- BatchCallbacksMap cache_batch_callbacks_;
-
- TimeMap cache_match_times_;
- TimeMap cache_match_all_times_;
- TimeMap cache_keys_times_;
- TimeMap cache_batch_times_;
-
- base::WeakPtrFactory<CacheStorageDispatcher> weak_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(CacheStorageDispatcher);
-};
-
-} // namespace content
-
-#endif // CONTENT_RENDERER_CACHE_STORAGE_CACHE_STORAGE_DISPATCHER_H_
diff --git a/chromium/content/renderer/cache_storage/cache_storage_message_filter.cc b/chromium/content/renderer/cache_storage/cache_storage_message_filter.cc
deleted file mode 100644
index 5f7fad404ff..00000000000
--- a/chromium/content/renderer/cache_storage/cache_storage_message_filter.cc
+++ /dev/null
@@ -1,38 +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 "content/renderer/cache_storage/cache_storage_message_filter.h"
-
-#include "content/child/thread_safe_sender.h"
-#include "content/common/cache_storage/cache_storage_messages.h"
-#include "content/renderer/cache_storage/cache_storage_dispatcher.h"
-
-namespace content {
-
-CacheStorageMessageFilter::CacheStorageMessageFilter(
- ThreadSafeSender* thread_safe_sender)
- : WorkerThreadMessageFilter(thread_safe_sender) {
-}
-
-CacheStorageMessageFilter::~CacheStorageMessageFilter() {
-}
-
-bool CacheStorageMessageFilter::ShouldHandleMessage(
- const IPC::Message& msg) const {
- return IPC_MESSAGE_CLASS(msg) == CacheStorageMsgStart;
-}
-
-void CacheStorageMessageFilter::OnFilteredMessageReceived(
- const IPC::Message& msg) {
- CacheStorageDispatcher::ThreadSpecificInstance(thread_safe_sender())
- ->OnMessageReceived(msg);
-}
-
-bool CacheStorageMessageFilter::GetWorkerThreadIdForMessage(
- const IPC::Message& msg,
- int* ipc_thread_id) {
- return base::PickleIterator(msg).ReadInt(ipc_thread_id);
-}
-
-} // namespace content
diff --git a/chromium/content/renderer/cache_storage/cache_storage_message_filter.h b/chromium/content/renderer/cache_storage/cache_storage_message_filter.h
deleted file mode 100644
index 6527594a58a..00000000000
--- a/chromium/content/renderer/cache_storage/cache_storage_message_filter.h
+++ /dev/null
@@ -1,33 +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 CONTENT_RENDERER_SERVICE_WORKER_CACHE_STORAGE_MESSAGE_FILTER_H_
-#define CONTENT_RENDERER_SERVICE_WORKER_CACHE_STORAGE_MESSAGE_FILTER_H_
-
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "content/renderer/worker_thread_message_filter.h"
-
-namespace content {
-
-class CacheStorageMessageFilter : public WorkerThreadMessageFilter {
- public:
- explicit CacheStorageMessageFilter(ThreadSafeSender* thread_safe_sender);
-
- protected:
- ~CacheStorageMessageFilter() override;
-
- private:
- // WorkerThreadMessageFilter:
- bool ShouldHandleMessage(const IPC::Message& msg) const override;
- void OnFilteredMessageReceived(const IPC::Message& msg) override;
- bool GetWorkerThreadIdForMessage(const IPC::Message& msg,
- int* ipc_thread_id) override;
-
- DISALLOW_COPY_AND_ASSIGN(CacheStorageMessageFilter);
-};
-
-} // namespace content
-
-#endif // CONTENT_RENDERER_SERVICE_WORKER_CACHE_STORAGE_MESSAGE_FILTER_H_
diff --git a/chromium/content/renderer/cache_storage/webserviceworkercachestorage_impl.cc b/chromium/content/renderer/cache_storage/webserviceworkercachestorage_impl.cc
index be2467e14b0..d6d31794194 100644
--- a/chromium/content/renderer/cache_storage/webserviceworkercachestorage_impl.cc
+++ b/chromium/content/renderer/cache_storage/webserviceworkercachestorage_impl.cc
@@ -4,63 +4,478 @@
#include "content/renderer/cache_storage/webserviceworkercachestorage_impl.h"
+#include <algorithm>
+#include <map>
#include <memory>
+#include <string>
#include <utility>
+#include "base/logging.h"
+#include "base/metrics/histogram_macros.h"
+#include "base/strings/utf_string_conversions.h"
+#include "base/threading/thread_local.h"
+#include "content/child/child_thread_impl.h"
#include "content/child/thread_safe_sender.h"
-#include "content/renderer/cache_storage/cache_storage_dispatcher.h"
-#include "third_party/WebKit/public/platform/WebHTTPHeaderVisitor.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerCache.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerRequest.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerResponse.h"
+#include "content/public/common/content_features.h"
+#include "content/public/common/referrer.h"
+#include "content/public/common/service_names.mojom.h"
+#include "content/public/renderer/render_thread.h"
+#include "content/renderer/service_worker/service_worker_type_util.h"
+#include "mojo/public/cpp/bindings/callback_helpers.h"
+#include "services/service_manager/public/cpp/connector.h"
+#include "services/service_manager/public/cpp/interface_provider.h"
+#include "storage/common/blob_storage/blob_handle.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_cache.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_request.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_response.h"
+#include "third_party/blink/public/platform/web_string.h"
+
+namespace content {
using base::TimeTicks;
+using blink::mojom::CacheStorageError;
+using blink::WebServiceWorkerRequest;
+using blink::WebString;
-namespace content {
+namespace {
-WebServiceWorkerCacheStorageImpl::WebServiceWorkerCacheStorageImpl(
- ThreadSafeSender* thread_safe_sender,
- const url::Origin& origin)
- : thread_safe_sender_(thread_safe_sender), origin_(origin) {}
+ServiceWorkerFetchRequest FetchRequestFromWebRequest(
+ const WebServiceWorkerRequest& web_request) {
+ ServiceWorkerHeaderMap headers;
+ GetServiceWorkerHeaderMapFromWebRequest(web_request, &headers);
+
+ return ServiceWorkerFetchRequest(
+ web_request.Url(), web_request.Method().Ascii(), headers,
+ Referrer(web_request.ReferrerUrl(), web_request.GetReferrerPolicy()),
+ web_request.IsReload());
+}
+
+void PopulateWebRequestFromFetchRequest(
+ const ServiceWorkerFetchRequest& request,
+ WebServiceWorkerRequest* web_request) {
+ web_request->SetURL(request.url);
+ web_request->SetMethod(WebString::FromASCII(request.method));
+ for (const auto& header : request.headers) {
+ web_request->SetHeader(WebString::FromASCII(header.first),
+ WebString::FromASCII(header.second));
+ }
+ web_request->SetReferrer(WebString::FromASCII(request.referrer.url.spec()),
+ request.referrer.policy);
+ web_request->SetIsReload(request.is_reload);
+}
-WebServiceWorkerCacheStorageImpl::~WebServiceWorkerCacheStorageImpl() {
+blink::WebVector<WebServiceWorkerRequest> WebRequestsFromRequests(
+ const std::vector<ServiceWorkerFetchRequest>& requests) {
+ blink::WebVector<WebServiceWorkerRequest> web_requests(requests.size());
+ for (size_t i = 0; i < requests.size(); ++i)
+ PopulateWebRequestFromFetchRequest(requests[i], &(web_requests[i]));
+ return web_requests;
}
+CacheStorageCacheQueryParams QueryParamsFromWebQueryParams(
+ const blink::WebServiceWorkerCache::QueryParams& web_query_params) {
+ CacheStorageCacheQueryParams query_params;
+ query_params.ignore_search = web_query_params.ignore_search;
+ query_params.ignore_method = web_query_params.ignore_method;
+ query_params.ignore_vary = web_query_params.ignore_vary;
+ query_params.cache_name =
+ WebString::ToNullableString16(web_query_params.cache_name);
+ return query_params;
+}
+
+CacheStorageCacheOperationType CacheOperationTypeFromWebCacheOperationType(
+ blink::WebServiceWorkerCache::OperationType operation_type) {
+ switch (operation_type) {
+ case blink::WebServiceWorkerCache::kOperationTypePut:
+ return CACHE_STORAGE_CACHE_OPERATION_TYPE_PUT;
+ case blink::WebServiceWorkerCache::kOperationTypeDelete:
+ return CACHE_STORAGE_CACHE_OPERATION_TYPE_DELETE;
+ default:
+ return CACHE_STORAGE_CACHE_OPERATION_TYPE_UNDEFINED;
+ }
+}
+
+CacheStorageBatchOperation BatchOperationFromWebBatchOperation(
+ const blink::WebServiceWorkerCache::BatchOperation& web_operation) {
+ CacheStorageBatchOperation operation;
+ operation.operation_type =
+ CacheOperationTypeFromWebCacheOperationType(web_operation.operation_type);
+ operation.request = FetchRequestFromWebRequest(web_operation.request);
+ operation.response =
+ GetServiceWorkerResponseFromWebResponse(web_operation.response);
+ operation.match_params =
+ QueryParamsFromWebQueryParams(web_operation.match_params);
+ return operation;
+}
+
+} // namespace
+
+// Class to outlive WebCache, we need to keep the ref (and callbacks) around
+// even after WebCache is dropped as some consumers like
+// InspectorCacheStorageAgent expects to be called back without holding a
+// reference to it. CacheRef is ref-counted and the callback holds a reference
+// to it to keep it alive until the callback is called.
+class WebServiceWorkerCacheStorageImpl::CacheRef
+ : public base::RefCounted<CacheRef> {
+ public:
+ using CacheBatchCallbacks = blink::WebServiceWorkerCache::CacheBatchCallbacks;
+ using CacheMatchCallbacks = blink::WebServiceWorkerCache::CacheMatchCallbacks;
+ using CacheWithResponsesCallbacks =
+ blink::WebServiceWorkerCache::CacheWithResponsesCallbacks;
+ using CacheWithRequestsCallbacks =
+ blink::WebServiceWorkerCache::CacheWithRequestsCallbacks;
+
+ CacheRef(base::WeakPtr<WebServiceWorkerCacheStorageImpl> dispatcher,
+ blink::mojom::CacheStorageCacheAssociatedPtrInfo cache_ptr_info)
+ : dispatcher_(std::move(dispatcher)) {
+ cache_ptr_.Bind(std::move(cache_ptr_info));
+ }
+
+ void DispatchMatch(
+ std::unique_ptr<CacheMatchCallbacks> callbacks,
+ const WebServiceWorkerRequest& request,
+ const blink::WebServiceWorkerCache::QueryParams& query_params) {
+ cache_ptr_->Match(FetchRequestFromWebRequest(request),
+ QueryParamsFromWebQueryParams(query_params),
+ base::BindOnce(&CacheRef::CacheMatchCallback, this,
+ std::move(callbacks), TimeTicks::Now()));
+ }
+
+ void DispatchMatchAll(
+ std::unique_ptr<CacheWithResponsesCallbacks> callbacks,
+ const WebServiceWorkerRequest& request,
+ const blink::WebServiceWorkerCache::QueryParams& query_params) {
+ cache_ptr_->MatchAll(
+ FetchRequestFromWebRequest(request),
+ QueryParamsFromWebQueryParams(query_params),
+ base::BindOnce(&CacheRef::CacheMatchAllCallback, this,
+ std::move(callbacks), TimeTicks::Now()));
+ }
+
+ void DispatchKeys(
+ std::unique_ptr<CacheWithRequestsCallbacks> callbacks,
+ const WebServiceWorkerRequest& request,
+ const blink::WebServiceWorkerCache::QueryParams& query_params) {
+ cache_ptr_->Keys(FetchRequestFromWebRequest(request),
+ QueryParamsFromWebQueryParams(query_params),
+ base::BindOnce(&CacheRef::CacheKeysCallback, this,
+ std::move(callbacks)));
+ }
+
+ void DispatchBatch(
+ std::unique_ptr<CacheBatchCallbacks> callbacks,
+ const blink::WebVector<blink::WebServiceWorkerCache::BatchOperation>&
+ batch_operations) {
+ std::vector<CacheStorageBatchOperation> operations;
+ operations.reserve(batch_operations.size());
+ for (size_t i = 0; i < batch_operations.size(); ++i) {
+ operations.push_back(
+ BatchOperationFromWebBatchOperation(batch_operations[i]));
+ }
+ cache_ptr_->Batch(operations,
+ base::BindOnce(&CacheRef::BatchCallback, this,
+ std::move(callbacks), TimeTicks::Now()));
+ }
+
+ private:
+ friend class base::RefCounted<CacheRef>;
+
+ ~CacheRef() = default;
+
+ void CacheMatchCallback(std::unique_ptr<CacheMatchCallbacks> callbacks,
+ base::TimeTicks start_time,
+ blink::mojom::MatchResultPtr result) {
+ if (result->is_status() &&
+ result->get_status() != CacheStorageError::kSuccess) {
+ callbacks->OnError(result->get_status());
+ } else if (!dispatcher_) {
+ callbacks->OnError(CacheStorageError::kErrorNotFound);
+ } else {
+ blink::WebServiceWorkerResponse web_response;
+ dispatcher_->PopulateWebResponseFromResponse(result->get_response(),
+ &web_response);
+
+ UMA_HISTOGRAM_TIMES("ServiceWorkerCache.Cache.Match",
+ TimeTicks::Now() - start_time);
+ callbacks->OnSuccess(web_response);
+ }
+ }
+
+ void CacheMatchAllCallback(
+ std::unique_ptr<CacheWithResponsesCallbacks> callbacks,
+ base::TimeTicks start_time,
+ blink::mojom::MatchAllResultPtr result) {
+ if (result->is_status() &&
+ result->get_status() != CacheStorageError::kSuccess) {
+ callbacks->OnError(result->get_status());
+ } else if (!dispatcher_) {
+ callbacks->OnError(CacheStorageError::kErrorNotFound);
+ } else {
+ UMA_HISTOGRAM_TIMES("ServiceWorkerCache.Cache.MatchAll",
+ TimeTicks::Now() - start_time);
+ callbacks->OnSuccess(
+ dispatcher_->WebResponsesFromResponses(result->get_responses()));
+ }
+ }
+
+ void CacheKeysCallback(std::unique_ptr<CacheWithRequestsCallbacks> callbacks,
+ blink::mojom::CacheKeysResultPtr result) {
+ if (result->is_status() &&
+ result->get_status() != CacheStorageError::kSuccess) {
+ callbacks->OnError(result->get_status());
+ } else {
+ callbacks->OnSuccess(WebRequestsFromRequests(result->get_keys()));
+ }
+ }
+
+ void BatchCallback(std::unique_ptr<CacheBatchCallbacks> callbacks,
+ base::TimeTicks start_time,
+ CacheStorageError error) {
+ if (error == CacheStorageError::kSuccess) {
+ UMA_HISTOGRAM_TIMES("ServiceWorkerCache.Cache.Batch",
+ TimeTicks::Now() - start_time);
+ callbacks->OnSuccess();
+ } else {
+ callbacks->OnError(error);
+ }
+ }
+
+ blink::mojom::CacheStorageCacheAssociatedPtr cache_ptr_;
+ base::WeakPtr<WebServiceWorkerCacheStorageImpl> dispatcher_;
+};
+
+// The WebCache object is the Chromium side implementation of the Blink
+// WebServiceWorkerCache API. It only delegates the client calls to CacheRef
+// object, which have a lifetime longer than the WebCache. WebCache is owned by
+// the script-facing caller. CacheRef outlives WebCache to guarantee callback
+// responses are invoked, regardless of script-facing keeping WebCache instance
+// alive.
+class WebServiceWorkerCacheStorageImpl::WebCache
+ : public blink::WebServiceWorkerCache {
+ public:
+ WebCache(scoped_refptr<CacheRef> cache_ref)
+ : cache_ref_(std::move(cache_ref)) {}
+
+ ~WebCache() override = default;
+
+ // From blink::WebServiceWorkerCache:
+ void DispatchMatch(std::unique_ptr<CacheMatchCallbacks> callbacks,
+ const WebServiceWorkerRequest& request,
+ const QueryParams& query_params) override {
+ cache_ref_->DispatchMatch(std::move(callbacks), std::move(request),
+ std::move(query_params));
+ }
+
+ void DispatchMatchAll(std::unique_ptr<CacheWithResponsesCallbacks> callbacks,
+ const WebServiceWorkerRequest& request,
+ const QueryParams& query_params) override {
+ cache_ref_->DispatchMatchAll(std::move(callbacks), std::move(request),
+ std::move(query_params));
+ }
+
+ void DispatchKeys(std::unique_ptr<CacheWithRequestsCallbacks> callbacks,
+ const WebServiceWorkerRequest& request,
+ const QueryParams& query_params) override {
+ cache_ref_->DispatchKeys(std::move(callbacks), std::move(request),
+ std::move(query_params));
+ }
+
+ void DispatchBatch(
+ std::unique_ptr<CacheBatchCallbacks> callbacks,
+ const blink::WebVector<blink::WebServiceWorkerCache::BatchOperation>&
+ batch_operations) override {
+ cache_ref_->DispatchBatch(std::move(callbacks),
+ std::move(batch_operations));
+ }
+
+ private:
+ scoped_refptr<CacheRef> cache_ref_;
+
+ DISALLOW_COPY_AND_ASSIGN(WebCache);
+};
+
+WebServiceWorkerCacheStorageImpl::WebServiceWorkerCacheStorageImpl(
+ service_manager::InterfaceProvider* provider)
+ : weak_factory_(this) {
+ // Sets up the Mojo InterfacePtr to send IPCs to browser process.
+ provider->GetInterface(mojo::MakeRequest(&cache_storage_ptr_));
+}
+
+WebServiceWorkerCacheStorageImpl::~WebServiceWorkerCacheStorageImpl() = default;
+
void WebServiceWorkerCacheStorageImpl::DispatchHas(
std::unique_ptr<CacheStorageCallbacks> callbacks,
- const blink::WebString& cacheName) {
- GetDispatcher()->dispatchHas(std::move(callbacks), origin_, cacheName);
+ const WebString& cacheName) {
+ GetCacheStorage().Has(
+ cacheName.Utf16(),
+ base::BindOnce(
+ &WebServiceWorkerCacheStorageImpl::OnCacheStorageHasCallback,
+ weak_factory_.GetWeakPtr(), std::move(callbacks),
+ base::TimeTicks::Now()));
+}
+
+void WebServiceWorkerCacheStorageImpl::OnCacheStorageHasCallback(
+ std::unique_ptr<CacheStorageCallbacks> callbacks,
+ base::TimeTicks start_time,
+ CacheStorageError result) {
+ if (result == CacheStorageError::kSuccess) {
+ UMA_HISTOGRAM_TIMES("ServiceWorkerCache.CacheStorage.Has",
+ TimeTicks::Now() - start_time);
+ callbacks->OnSuccess();
+ } else {
+ callbacks->OnError(result);
+ }
}
void WebServiceWorkerCacheStorageImpl::DispatchOpen(
std::unique_ptr<CacheStorageWithCacheCallbacks> callbacks,
- const blink::WebString& cacheName) {
- GetDispatcher()->dispatchOpen(std::move(callbacks), origin_, cacheName);
+ const WebString& cacheName) {
+ GetCacheStorage().Open(
+ cacheName.Utf16(),
+ base::BindOnce(
+ &WebServiceWorkerCacheStorageImpl::OnCacheStorageOpenCallback,
+ weak_factory_.GetWeakPtr(), std::move(callbacks),
+ base::TimeTicks::Now()));
+}
+
+void WebServiceWorkerCacheStorageImpl::OnCacheStorageOpenCallback(
+ std::unique_ptr<CacheStorageWithCacheCallbacks> callbacks,
+ base::TimeTicks start_time,
+ blink::mojom::OpenResultPtr result) {
+ if (result->is_status() &&
+ result->get_status() != CacheStorageError::kSuccess) {
+ callbacks->OnError(result->get_status());
+ } else {
+ std::unique_ptr<WebCache> web_cache =
+ std::make_unique<WebCache>(base::MakeRefCounted<CacheRef>(
+ weak_factory_.GetWeakPtr(), std::move(result->get_cache())));
+
+ UMA_HISTOGRAM_TIMES("ServiceWorkerCache.CacheStorage.Open",
+ TimeTicks::Now() - start_time);
+ callbacks->OnSuccess(std::move(web_cache));
+ }
}
void WebServiceWorkerCacheStorageImpl::DispatchDelete(
std::unique_ptr<CacheStorageCallbacks> callbacks,
- const blink::WebString& cacheName) {
- GetDispatcher()->dispatchDelete(std::move(callbacks), origin_, cacheName);
+ const WebString& cacheName) {
+ GetCacheStorage().Delete(
+ cacheName.Utf16(),
+ base::BindOnce(
+ &WebServiceWorkerCacheStorageImpl::CacheStorageDeleteCallback,
+ weak_factory_.GetWeakPtr(), std::move(callbacks),
+ base::TimeTicks::Now()));
+}
+
+void WebServiceWorkerCacheStorageImpl::CacheStorageDeleteCallback(
+ std::unique_ptr<CacheStorageCallbacks> callbacks,
+ base::TimeTicks start_time,
+ CacheStorageError result) {
+ if (result == CacheStorageError::kSuccess) {
+ UMA_HISTOGRAM_TIMES("ServiceWorkerCache.CacheStorage.Delete",
+ TimeTicks::Now() - start_time);
+ callbacks->OnSuccess();
+ } else {
+ callbacks->OnError(result);
+ }
}
void WebServiceWorkerCacheStorageImpl::DispatchKeys(
std::unique_ptr<CacheStorageKeysCallbacks> callbacks) {
- GetDispatcher()->dispatchKeys(std::move(callbacks), origin_);
+ GetCacheStorage().Keys(
+ base::BindOnce(&WebServiceWorkerCacheStorageImpl::KeysCallback,
+ weak_factory_.GetWeakPtr(), std::move(callbacks),
+ base::TimeTicks::Now()));
+}
+
+void WebServiceWorkerCacheStorageImpl::KeysCallback(
+ std::unique_ptr<CacheStorageKeysCallbacks> callbacks,
+ base::TimeTicks start_time,
+ const std::vector<base::string16>& keys) {
+ blink::WebVector<WebString> web_keys(keys.size());
+ std::transform(
+ keys.begin(), keys.end(), web_keys.begin(),
+ [](const base::string16& s) { return WebString::FromUTF16(s); });
+ UMA_HISTOGRAM_TIMES("ServiceWorkerCache.CacheStorage.Keys",
+ TimeTicks::Now() - start_time);
+ callbacks->OnSuccess(web_keys);
}
void WebServiceWorkerCacheStorageImpl::DispatchMatch(
std::unique_ptr<CacheStorageMatchCallbacks> callbacks,
- const blink::WebServiceWorkerRequest& request,
+ const WebServiceWorkerRequest& request,
const blink::WebServiceWorkerCache::QueryParams& query_params) {
- GetDispatcher()->dispatchMatch(std::move(callbacks), origin_, request,
- query_params);
+ GetCacheStorage().Match(
+ FetchRequestFromWebRequest(request),
+ QueryParamsFromWebQueryParams(query_params),
+ base::BindOnce(
+ &WebServiceWorkerCacheStorageImpl::OnCacheStorageMatchCallback,
+ weak_factory_.GetWeakPtr(), std::move(callbacks),
+ base::TimeTicks::Now()));
+}
+
+void WebServiceWorkerCacheStorageImpl::OnCacheStorageMatchCallback(
+ std::unique_ptr<CacheStorageMatchCallbacks> callbacks,
+ base::TimeTicks start_time,
+ blink::mojom::MatchResultPtr result) {
+ if (result->is_status() &&
+ result->get_status() != CacheStorageError::kSuccess) {
+ callbacks->OnError(result->get_status());
+ } else {
+ UMA_HISTOGRAM_TIMES("ServiceWorkerCache.CacheStorage.Match",
+ TimeTicks::Now() - start_time);
+ blink::WebServiceWorkerResponse web_response;
+ PopulateWebResponseFromResponse(result->get_response(), &web_response);
+
+ callbacks->OnSuccess(web_response);
+ }
+}
+
+blink::mojom::CacheStorage&
+WebServiceWorkerCacheStorageImpl::GetCacheStorage() {
+ return *cache_storage_ptr_;
+}
+
+void WebServiceWorkerCacheStorageImpl::PopulateWebResponseFromResponse(
+ const ServiceWorkerResponse& response,
+ blink::WebServiceWorkerResponse* web_response) {
+ web_response->SetURLList(response.url_list);
+ web_response->SetStatus(response.status_code);
+ web_response->SetStatusText(WebString::FromASCII(response.status_text));
+ web_response->SetResponseType(response.response_type);
+ web_response->SetResponseTime(response.response_time);
+ web_response->SetCacheStorageCacheName(
+ response.is_in_cache_storage
+ ? WebString::FromUTF8(response.cache_storage_cache_name)
+ : WebString());
+ blink::WebVector<WebString> headers(
+ response.cors_exposed_header_names.size());
+ std::transform(response.cors_exposed_header_names.begin(),
+ response.cors_exposed_header_names.end(), headers.begin(),
+ [](const std::string& s) { return WebString::FromLatin1(s); });
+ web_response->SetCorsExposedHeaderNames(headers);
+
+ for (const auto& i : response.headers) {
+ web_response->SetHeader(WebString::FromASCII(i.first),
+ WebString::FromASCII(i.second));
+ }
+
+ if (!response.blob_uuid.empty()) {
+ DCHECK(response.blob);
+ web_response->SetBlob(WebString::FromUTF8(response.blob_uuid),
+ response.blob_size,
+ response.blob->Clone().PassInterface().PassHandle());
+ }
}
-CacheStorageDispatcher* WebServiceWorkerCacheStorageImpl::GetDispatcher()
- const {
- return CacheStorageDispatcher::ThreadSpecificInstance(
- thread_safe_sender_.get());
+blink::WebVector<blink::WebServiceWorkerResponse>
+WebServiceWorkerCacheStorageImpl::WebResponsesFromResponses(
+ const std::vector<ServiceWorkerResponse>& responses) {
+ blink::WebVector<blink::WebServiceWorkerResponse> web_responses(
+ responses.size());
+ for (size_t i = 0; i < responses.size(); ++i)
+ PopulateWebResponseFromResponse(responses[i], &(web_responses[i]));
+ return web_responses;
}
} // namespace content
diff --git a/chromium/content/renderer/cache_storage/webserviceworkercachestorage_impl.h b/chromium/content/renderer/cache_storage/webserviceworkercachestorage_impl.h
index f7243567cc7..de4bc018e58 100644
--- a/chromium/content/renderer/cache_storage/webserviceworkercachestorage_impl.h
+++ b/chromium/content/renderer/cache_storage/webserviceworkercachestorage_impl.h
@@ -5,35 +5,44 @@
#ifndef CONTENT_RENDERER_SERVICE_WORKER_WEB_SERVICE_WORKER_CACHE_STORAGE_IMPL_H_
#define CONTENT_RENDERER_SERVICE_WORKER_WEB_SERVICE_WORKER_CACHE_STORAGE_IMPL_H_
+#include <stdint.h>
+
#include <memory>
+#include <vector>
+#include "base/containers/id_map.h"
#include "base/macros.h"
-#include "content/child/thread_safe_sender.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerCache.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerCacheStorage.h"
-#include "url/origin.h"
+#include "base/memory/weak_ptr.h"
+#include "base/strings/string16.h"
+#include "base/time/time.h"
+#include "services/service_manager/public/cpp/interface_provider.h"
+#include "third_party/blink/public/platform/modules/cache_storage/cache_storage.mojom.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_cache.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_cache_storage.h"
+#include "third_party/blink/public/platform/web_string.h"
namespace content {
-
-class CacheStorageDispatcher;
-class ThreadSafeSender;
+struct ServiceWorkerResponse;
// This corresponds to an instance of the script-facing CacheStorage object.
// One exists per script execution context (window, worker) and has an origin
// which provides a namespace for the caches. Script calls to the CacheStorage
-// object are routed through here to the (per-thread) dispatcher then on to
-// the browser, with the origin added to the call parameters. Cache instances
-// returned by open() calls are minted by and implemented within the code of
-// the CacheStorageDispatcher, and include routing information.
+// object are routed through here via Mojo interface then on to the browser,
+// with the origin managed at binding time on browser side. Cache instances
+// returned by open() calls return a WebCache to script-facing caller which can
+// dispatch calls to browser via CacheRef. WebCache is owned by script-facing
+// caller and CacheRef is owned by WebServiceWorkerCacheStorageImpl. CacheRef is
+// destroyed once WebCache has been destroyed and there are no pending
+// callbacks.
class WebServiceWorkerCacheStorageImpl
: public blink::WebServiceWorkerCacheStorage {
public:
- WebServiceWorkerCacheStorageImpl(ThreadSafeSender* thread_safe_sender,
- const url::Origin& origin);
+ explicit WebServiceWorkerCacheStorageImpl(
+ service_manager::InterfaceProvider* provider);
+
~WebServiceWorkerCacheStorageImpl() override;
- // From WebServiceWorkerCacheStorage:
+ // From WebServiceWorkerCacheStorage interface to script-facing:
void DispatchHas(std::unique_ptr<CacheStorageCallbacks> callbacks,
const blink::WebString& cacheName) override;
void DispatchOpen(std::unique_ptr<CacheStorageWithCacheCallbacks> callbacks,
@@ -47,12 +56,44 @@ class WebServiceWorkerCacheStorageImpl
const blink::WebServiceWorkerRequest& request,
const blink::WebServiceWorkerCache::QueryParams& query_params) override;
+ // Message handlers for CacheStorage messages from the browser process.
+ // And callbacks called by Mojo implementation on browser process.
+ void OnCacheStorageHasCallback(
+ std::unique_ptr<CacheStorageCallbacks> callbacks,
+ base::TimeTicks start_time,
+ blink::mojom::CacheStorageError result);
+ void OnCacheStorageOpenCallback(
+ std::unique_ptr<CacheStorageWithCacheCallbacks> callbacks,
+ base::TimeTicks start_time,
+ blink::mojom::OpenResultPtr result);
+ void CacheStorageDeleteCallback(
+ std::unique_ptr<CacheStorageCallbacks> callbacks,
+ base::TimeTicks start_time,
+ blink::mojom::CacheStorageError result);
+ void KeysCallback(std::unique_ptr<CacheStorageKeysCallbacks> callbacks,
+ base::TimeTicks start_time,
+ const std::vector<base::string16>& keys);
+ void OnCacheStorageMatchCallback(
+ std::unique_ptr<CacheStorageMatchCallbacks> callbacks,
+ base::TimeTicks start_time,
+ blink::mojom::MatchResultPtr result);
+
private:
- // Helper to return the thread-specific dispatcher.
- CacheStorageDispatcher* GetDispatcher() const;
+ class WebCache;
+ class CacheRef;
+
+ void PopulateWebResponseFromResponse(
+ const ServiceWorkerResponse& response,
+ blink::WebServiceWorkerResponse* web_response);
+
+ blink::WebVector<blink::WebServiceWorkerResponse> WebResponsesFromResponses(
+ const std::vector<ServiceWorkerResponse>& responses);
+
+ blink::mojom::CacheStorage& GetCacheStorage();
+
+ blink::mojom::CacheStoragePtr cache_storage_ptr_;
- scoped_refptr<ThreadSafeSender> thread_safe_sender_;
- const url::Origin origin_;
+ base::WeakPtrFactory<WebServiceWorkerCacheStorageImpl> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(WebServiceWorkerCacheStorageImpl);
};
diff --git a/chromium/content/renderer/child_frame_compositing_helper.cc b/chromium/content/renderer/child_frame_compositing_helper.cc
index 08717a420e9..620cab062a4 100644
--- a/chromium/content/renderer/child_frame_compositing_helper.cc
+++ b/chromium/content/renderer/child_frame_compositing_helper.cc
@@ -72,7 +72,8 @@ void ChildFrameCompositingHelper::ChildFrameGone(
void ChildFrameCompositingHelper::SetPrimarySurfaceId(
const viz::SurfaceId& surface_id,
- const gfx::Size& frame_size_in_dip) {
+ const gfx::Size& frame_size_in_dip,
+ const cc::DeadlinePolicy& deadline) {
if (primary_surface_id_ == surface_id)
return;
@@ -80,10 +81,10 @@ void ChildFrameCompositingHelper::SetPrimarySurfaceId(
surface_layer_ = cc::SurfaceLayer::Create();
surface_layer_->SetMasksToBounds(true);
+ surface_layer_->SetHitTestable(true);
surface_layer_->SetBackgroundColor(SK_ColorTRANSPARENT);
- surface_layer_->SetPrimarySurfaceId(surface_id,
- cc::DeadlinePolicy::UseDefaultDeadline());
+ surface_layer_->SetPrimarySurfaceId(surface_id, deadline);
surface_layer_->SetFallbackSurfaceId(fallback_surface_id_);
std::unique_ptr<cc_blink::WebLayerImpl> layer(
@@ -110,7 +111,8 @@ void ChildFrameCompositingHelper::SetFallbackSurfaceId(
fallback_surface_id_ = surface_id;
if (!surface_layer_) {
- SetPrimarySurfaceId(surface_id, frame_size_in_dip);
+ SetPrimarySurfaceId(surface_id, frame_size_in_dip,
+ cc::DeadlinePolicy::UseDefaultDeadline());
return;
}
diff --git a/chromium/content/renderer/child_frame_compositing_helper.h b/chromium/content/renderer/child_frame_compositing_helper.h
index 2c67f03621d..7a0541734e8 100644
--- a/chromium/content/renderer/child_frame_compositing_helper.h
+++ b/chromium/content/renderer/child_frame_compositing_helper.h
@@ -36,7 +36,8 @@ class CONTENT_EXPORT ChildFrameCompositingHelper {
virtual ~ChildFrameCompositingHelper();
void SetPrimarySurfaceId(const viz::SurfaceId& surface_id,
- const gfx::Size& frame_size_in_dip);
+ const gfx::Size& frame_size_in_dip,
+ const cc::DeadlinePolicy& deadline);
void SetFallbackSurfaceId(const viz::SurfaceId& surface_id,
const gfx::Size& frame_size_in_dip);
void UpdateVisibility(bool visible);
diff --git a/chromium/content/renderer/clipboard_utils.cc b/chromium/content/renderer/clipboard_utils.cc
index 521342609fb..8324300097b 100644
--- a/chromium/content/renderer/clipboard_utils.cc
+++ b/chromium/content/renderer/clipboard_utils.cc
@@ -6,8 +6,8 @@
#include "base/strings/utf_string_conversions.h"
#include "net/base/escape.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_url.h"
namespace content {
diff --git a/chromium/content/renderer/content_security_policy_util.h b/chromium/content/renderer/content_security_policy_util.h
index 46a9a39579e..6ef7ab183f9 100644
--- a/chromium/content/renderer/content_security_policy_util.h
+++ b/chromium/content/renderer/content_security_policy_util.h
@@ -7,7 +7,7 @@
#include "content/common/content_security_policy/content_security_policy.h"
#include "content/common/content_security_policy/csp_context.h"
-#include "third_party/WebKit/public/platform/WebContentSecurityPolicyStruct.h"
+#include "third_party/blink/public/platform/web_content_security_policy_struct.h"
namespace content {
diff --git a/chromium/content/renderer/cursor_utils.cc b/chromium/content/renderer/cursor_utils.cc
index fe40ae3ef57..ccdb7bceddf 100644
--- a/chromium/content/renderer/cursor_utils.cc
+++ b/chromium/content/renderer/cursor_utils.cc
@@ -6,7 +6,7 @@
#include "build/build_config.h"
#include "content/common/cursors/webcursor.h"
-#include "third_party/WebKit/public/platform/WebCursorInfo.h"
+#include "third_party/blink/public/platform/web_cursor_info.h"
using blink::WebCursorInfo;
diff --git a/chromium/content/renderer/device_sensors/device_motion_event_pump.cc b/chromium/content/renderer/device_sensors/device_motion_event_pump.cc
index 6e26062d999..e19341cd04f 100644
--- a/chromium/content/renderer/device_sensors/device_motion_event_pump.cc
+++ b/chromium/content/renderer/device_sensors/device_motion_event_pump.cc
@@ -10,13 +10,15 @@
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_thread.h"
#include "content/renderer/render_thread_impl.h"
-#include "device/sensors/public/cpp/motion_data.h"
+#include "services/device/public/cpp/generic_sensor/motion_data.h"
#include "services/device/public/mojom/sensor.mojom.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "ui/gfx/geometry/angle_conversions.h"
namespace content {
+template class DeviceSensorEventPump<blink::WebDeviceMotionListener>;
+
DeviceMotionEventPump::DeviceMotionEventPump(RenderThread* thread)
: DeviceSensorEventPump<blink::WebDeviceMotionListener>(thread),
accelerometer_(this, device::mojom::SensorType::ACCELEROMETER),
diff --git a/chromium/content/renderer/device_sensors/device_motion_event_pump.h b/chromium/content/renderer/device_sensors/device_motion_event_pump.h
index 8b778245713..e7bb8e6026e 100644
--- a/chromium/content/renderer/device_sensors/device_motion_event_pump.h
+++ b/chromium/content/renderer/device_sensors/device_motion_event_pump.h
@@ -7,7 +7,7 @@
#include "base/macros.h"
#include "content/renderer/device_sensors/device_sensor_event_pump.h"
-#include "third_party/WebKit/public/platform/modules/device_orientation/WebDeviceMotionListener.h"
+#include "third_party/blink/public/platform/modules/device_orientation/web_device_motion_listener.h"
namespace device {
class MotionData;
diff --git a/chromium/content/renderer/device_sensors/device_motion_event_pump_unittest.cc b/chromium/content/renderer/device_sensors/device_motion_event_pump_unittest.cc
index 9ec7c65b913..6cf54ed49fa 100644
--- a/chromium/content/renderer/device_sensors/device_motion_event_pump_unittest.cc
+++ b/chromium/content/renderer/device_sensors/device_motion_event_pump_unittest.cc
@@ -15,18 +15,20 @@
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "content/public/test/test_utils.h"
-#include "content/renderer/device_sensors/fake_sensor_and_provider.h"
-#include "device/sensors/public/cpp/motion_data.h"
#include "mojo/public/cpp/bindings/interface_request.h"
+#include "services/device/public/cpp/generic_sensor/motion_data.h"
+#include "services/device/public/cpp/test/fake_sensor_and_provider.h"
#include "services/device/public/mojom/sensor.mojom.h"
#include "services/device/public/mojom/sensor_provider.mojom.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/modules/device_orientation/WebDeviceMotionListener.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/modules/device_orientation/web_device_motion_listener.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
#include "ui/gfx/geometry/angle_conversions.h"
namespace content {
+using device::FakeSensorProvider;
+
class MockDeviceMotionListener : public blink::WebDeviceMotionListener {
public:
MockDeviceMotionListener()
@@ -216,9 +218,9 @@ TEST_F(DeviceMotionEventPumpTest, AllSensorsAreActive) {
ExpectAllThreeSensorsStateToBe(DeviceMotionEventPump::SensorState::ACTIVE);
- sensor_provider()->SetAccelerometerData(1, 2, 3);
- sensor_provider()->SetLinearAccelerationSensorData(4, 5, 6);
- sensor_provider()->SetGyroscopeData(7, 8, 9);
+ sensor_provider()->UpdateAccelerometerData(1, 2, 3);
+ sensor_provider()->UpdateLinearAccelerationSensorData(4, 5, 6);
+ sensor_provider()->UpdateGyroscopeData(7, 8, 9);
FireEvent();
@@ -262,8 +264,8 @@ TEST_F(DeviceMotionEventPumpTest, TwoSensorsAreActive) {
DeviceMotionEventPump::SensorState::NOT_INITIALIZED);
ExpectGyroscopeStateToBe(DeviceMotionEventPump::SensorState::ACTIVE);
- sensor_provider()->SetAccelerometerData(1, 2, 3);
- sensor_provider()->SetGyroscopeData(7, 8, 9);
+ sensor_provider()->UpdateAccelerometerData(1, 2, 3);
+ sensor_provider()->UpdateGyroscopeData(7, 8, 9);
FireEvent();
@@ -302,9 +304,9 @@ TEST_F(DeviceMotionEventPumpTest, SomeSensorDataFieldsNotAvailable) {
ExpectAllThreeSensorsStateToBe(DeviceMotionEventPump::SensorState::ACTIVE);
- sensor_provider()->SetAccelerometerData(NAN, 2, 3);
- sensor_provider()->SetLinearAccelerationSensorData(4, NAN, 6);
- sensor_provider()->SetGyroscopeData(7, 8, NAN);
+ sensor_provider()->UpdateAccelerometerData(NAN, 2, 3);
+ sensor_provider()->UpdateLinearAccelerationSensorData(4, NAN, 6);
+ sensor_provider()->UpdateGyroscopeData(7, 8, NAN);
FireEvent();
@@ -379,15 +381,15 @@ TEST_F(DeviceMotionEventPumpTest,
FireEvent();
EXPECT_FALSE(listener()->did_change_device_motion());
- sensor_provider()->SetAccelerometerData(1, 2, 3);
+ sensor_provider()->UpdateAccelerometerData(1, 2, 3);
FireEvent();
EXPECT_FALSE(listener()->did_change_device_motion());
- sensor_provider()->SetLinearAccelerationSensorData(4, 5, 6);
+ sensor_provider()->UpdateLinearAccelerationSensorData(4, 5, 6);
FireEvent();
EXPECT_FALSE(listener()->did_change_device_motion());
- sensor_provider()->SetGyroscopeData(7, 8, 9);
+ sensor_provider()->UpdateGyroscopeData(7, 8, 9);
FireEvent();
// Event is fired only after all the available sensors have data.
EXPECT_TRUE(listener()->did_change_device_motion());
@@ -410,9 +412,9 @@ TEST_F(DeviceMotionEventPumpTest, PumpThrottlesEventRate) {
ExpectAllThreeSensorsStateToBe(DeviceMotionEventPump::SensorState::ACTIVE);
- sensor_provider()->SetAccelerometerData(1, 2, 3);
- sensor_provider()->SetLinearAccelerationSensorData(4, 5, 6);
- sensor_provider()->SetGyroscopeData(7, 8, 9);
+ sensor_provider()->UpdateAccelerometerData(1, 2, 3);
+ sensor_provider()->UpdateLinearAccelerationSensorData(4, 5, 6);
+ sensor_provider()->UpdateGyroscopeData(7, 8, 9);
blink::scheduler::GetSingleThreadTaskRunnerForTesting()->PostDelayedTask(
FROM_HERE, base::MessageLoop::QuitWhenIdleClosure(),
diff --git a/chromium/content/renderer/device_sensors/device_orientation_event_pump.cc b/chromium/content/renderer/device_sensors/device_orientation_event_pump.cc
index cd203f8ac3b..f2c7d89f96b 100644
--- a/chromium/content/renderer/device_sensors/device_orientation_event_pump.cc
+++ b/chromium/content/renderer/device_sensors/device_orientation_event_pump.cc
@@ -41,6 +41,8 @@ bool IsSignificantlyDifferent(const device::OrientationData& data1,
namespace content {
+template class DeviceSensorEventPump<blink::WebDeviceOrientationListener>;
+
const double DeviceOrientationEventPump::kOrientationThreshold = 0.1;
DeviceOrientationEventPump::DeviceOrientationEventPump(RenderThread* thread,
diff --git a/chromium/content/renderer/device_sensors/device_orientation_event_pump.h b/chromium/content/renderer/device_sensors/device_orientation_event_pump.h
index 0b36df90c28..6ec081eb5e4 100644
--- a/chromium/content/renderer/device_sensors/device_orientation_event_pump.h
+++ b/chromium/content/renderer/device_sensors/device_orientation_event_pump.h
@@ -7,8 +7,8 @@
#include "base/macros.h"
#include "content/renderer/device_sensors/device_sensor_event_pump.h"
-#include "device/sensors/public/cpp/orientation_data.h"
-#include "third_party/WebKit/public/platform/modules/device_orientation/WebDeviceOrientationListener.h"
+#include "services/device/public/cpp/generic_sensor/orientation_data.h"
+#include "third_party/blink/public/platform/modules/device_orientation/web_device_orientation_listener.h"
namespace content {
diff --git a/chromium/content/renderer/device_sensors/device_orientation_event_pump_unittest.cc b/chromium/content/renderer/device_sensors/device_orientation_event_pump_unittest.cc
index f3df8cc5e41..a445b6af3a3 100644
--- a/chromium/content/renderer/device_sensors/device_orientation_event_pump_unittest.cc
+++ b/chromium/content/renderer/device_sensors/device_orientation_event_pump_unittest.cc
@@ -12,14 +12,14 @@
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "content/public/test/test_utils.h"
-#include "content/renderer/device_sensors/fake_sensor_and_provider.h"
-#include "device/sensors/public/cpp/orientation_data.h"
#include "mojo/public/cpp/bindings/interface_request.h"
+#include "services/device/public/cpp/generic_sensor/orientation_data.h"
+#include "services/device/public/cpp/test/fake_sensor_and_provider.h"
#include "services/device/public/mojom/sensor.mojom.h"
#include "services/device/public/mojom/sensor_provider.mojom.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/modules/device_orientation/WebDeviceOrientationListener.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/modules/device_orientation/web_device_orientation_listener.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
namespace {
@@ -29,6 +29,8 @@ constexpr double kEpsilon = 1e-8;
namespace content {
+using device::FakeSensorProvider;
+
class MockDeviceOrientationListener
: public blink::WebDeviceOrientationListener {
public:
@@ -344,7 +346,7 @@ TEST_F(DeviceOrientationEventPumpTest, SensorIsActive) {
ExpectRelativeOrientationSensorStateToBe(
DeviceOrientationEventPump::SensorState::ACTIVE);
- sensor_provider()->SetRelativeOrientationSensorData(
+ sensor_provider()->UpdateRelativeOrientationSensorData(
1 /* alpha */, 2 /* beta */, 3 /* gamma */);
FireEvent();
@@ -379,7 +381,7 @@ TEST_F(DeviceOrientationEventPumpTest, SensorIsActiveWithSensorFallback) {
ExpectAbsoluteOrientationSensorStateToBe(
DeviceOrientationEventPump::SensorState::ACTIVE);
- sensor_provider()->SetAbsoluteOrientationSensorData(
+ sensor_provider()->UpdateAbsoluteOrientationSensorData(
4 /* alpha */, 5 /* beta */, 6 /* gamma */);
FireEvent();
@@ -415,7 +417,7 @@ TEST_F(DeviceOrientationEventPumpTest, SomeSensorDataFieldsNotAvailable) {
ExpectRelativeOrientationSensorStateToBe(
DeviceOrientationEventPump::SensorState::ACTIVE);
- sensor_provider()->SetRelativeOrientationSensorData(
+ sensor_provider()->UpdateRelativeOrientationSensorData(
NAN /* alpha */, 2 /* beta */, 3 /* gamma */);
FireEvent();
@@ -448,7 +450,7 @@ TEST_F(DeviceOrientationEventPumpTest,
ExpectAbsoluteOrientationSensorStateToBe(
DeviceOrientationEventPump::SensorState::ACTIVE);
- sensor_provider()->SetAbsoluteOrientationSensorData(
+ sensor_provider()->UpdateAbsoluteOrientationSensorData(
4 /* alpha */, NAN /* beta */, 6 /* gamma */);
FireEvent();
@@ -556,7 +558,7 @@ TEST_F(DeviceOrientationEventPumpTest, UpdateRespectsOrientationThreshold) {
ExpectRelativeOrientationSensorStateToBe(
DeviceOrientationEventPump::SensorState::ACTIVE);
- sensor_provider()->SetRelativeOrientationSensorData(
+ sensor_provider()->UpdateRelativeOrientationSensorData(
1 /* alpha */, 2 /* beta */, 3 /* gamma */);
FireEvent();
@@ -576,7 +578,7 @@ TEST_F(DeviceOrientationEventPumpTest, UpdateRespectsOrientationThreshold) {
listener()->set_did_change_device_orientation(false);
- sensor_provider()->SetRelativeOrientationSensorData(
+ sensor_provider()->UpdateRelativeOrientationSensorData(
1 + DeviceOrientationEventPump::kOrientationThreshold / 2.0 /* alpha */,
2 /* beta */, 3 /* gamma */);
@@ -595,7 +597,7 @@ TEST_F(DeviceOrientationEventPumpTest, UpdateRespectsOrientationThreshold) {
listener()->set_did_change_device_orientation(false);
- sensor_provider()->SetRelativeOrientationSensorData(
+ sensor_provider()->UpdateRelativeOrientationSensorData(
1 + DeviceOrientationEventPump::kOrientationThreshold /* alpha */,
2 /* beta */, 3 /* gamma */);
@@ -631,7 +633,7 @@ TEST_F(DeviceOrientationEventPumpTest,
ExpectAbsoluteOrientationSensorStateToBe(
DeviceOrientationEventPump::SensorState::ACTIVE);
- sensor_provider()->SetAbsoluteOrientationSensorData(
+ sensor_provider()->UpdateAbsoluteOrientationSensorData(
4 /* alpha */, 5 /* beta */, 6 /* gamma */);
FireEvent();
@@ -654,7 +656,7 @@ TEST_F(DeviceOrientationEventPumpTest,
listener()->set_did_change_device_orientation(false);
- sensor_provider()->SetAbsoluteOrientationSensorData(
+ sensor_provider()->UpdateAbsoluteOrientationSensorData(
4 /* alpha */,
5 + DeviceOrientationEventPump::kOrientationThreshold / 2.0 /* beta */,
6 /* gamma */);
@@ -674,7 +676,7 @@ TEST_F(DeviceOrientationEventPumpTest,
listener()->set_did_change_device_orientation(false);
- sensor_provider()->SetAbsoluteOrientationSensorData(
+ sensor_provider()->UpdateAbsoluteOrientationSensorData(
4 /* alpha */,
5 + DeviceOrientationEventPump::kOrientationThreshold +
kEpsilon /* beta */,
@@ -845,7 +847,7 @@ TEST_F(DeviceAbsoluteOrientationEventPumpTest, SensorIsActive) {
ExpectAbsoluteOrientationSensorStateToBe(
DeviceOrientationEventPump::SensorState::ACTIVE);
- sensor_provider()->SetAbsoluteOrientationSensorData(
+ sensor_provider()->UpdateAbsoluteOrientationSensorData(
4 /* alpha */, 5 /* beta */, 6 /* gamma */);
FireEvent();
@@ -875,7 +877,7 @@ TEST_F(DeviceAbsoluteOrientationEventPumpTest,
ExpectAbsoluteOrientationSensorStateToBe(
DeviceOrientationEventPump::SensorState::ACTIVE);
- sensor_provider()->SetAbsoluteOrientationSensorData(
+ sensor_provider()->UpdateAbsoluteOrientationSensorData(
4 /* alpha */, NAN /* beta */, 6 /* gamma */);
FireEvent();
@@ -948,7 +950,7 @@ TEST_F(DeviceAbsoluteOrientationEventPumpTest,
ExpectAbsoluteOrientationSensorStateToBe(
DeviceOrientationEventPump::SensorState::ACTIVE);
- sensor_provider()->SetAbsoluteOrientationSensorData(
+ sensor_provider()->UpdateAbsoluteOrientationSensorData(
4 /* alpha */, 5 /* beta */, 6 /* gamma */);
FireEvent();
@@ -966,7 +968,7 @@ TEST_F(DeviceAbsoluteOrientationEventPumpTest,
listener()->set_did_change_device_orientation(false);
- sensor_provider()->SetAbsoluteOrientationSensorData(
+ sensor_provider()->UpdateAbsoluteOrientationSensorData(
4 /* alpha */,
5 + DeviceOrientationEventPump::kOrientationThreshold / 2.0 /* beta */,
6 /* gamma */);
@@ -986,7 +988,7 @@ TEST_F(DeviceAbsoluteOrientationEventPumpTest,
listener()->set_did_change_device_orientation(false);
- sensor_provider()->SetAbsoluteOrientationSensorData(
+ sensor_provider()->UpdateAbsoluteOrientationSensorData(
4 /* alpha */,
5 + DeviceOrientationEventPump::kOrientationThreshold +
kEpsilon /* beta */,
diff --git a/chromium/content/renderer/device_sensors/device_sensor_event_pump.h b/chromium/content/renderer/device_sensors/device_sensor_event_pump.h
index b6a63f6b588..98d846bc08e 100644
--- a/chromium/content/renderer/device_sensors/device_sensor_event_pump.h
+++ b/chromium/content/renderer/device_sensors/device_sensor_event_pump.h
@@ -26,9 +26,9 @@
#include "services/device/public/cpp/generic_sensor/sensor_traits.h"
#include "services/device/public/mojom/constants.mojom.h"
#include "services/device/public/mojom/sensor_provider.mojom.h"
-#include "third_party/WebKit/public/platform/modules/device_orientation/WebDeviceMotionListener.h"
-#include "third_party/WebKit/public/platform/modules/device_orientation/WebDeviceOrientationListener.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "third_party/blink/public/platform/modules/device_orientation/web_device_motion_listener.h"
+#include "third_party/blink/public/platform/modules/device_orientation/web_device_orientation_listener.h"
+#include "third_party/blink/public/web/web_local_frame.h"
namespace content {
@@ -324,10 +324,6 @@ class CONTENT_EXPORT DeviceSensorEventPump
DISALLOW_COPY_AND_ASSIGN(DeviceSensorEventPump);
};
-
-template class DeviceSensorEventPump<blink::WebDeviceMotionListener>;
-template class DeviceSensorEventPump<blink::WebDeviceOrientationListener>;
-
} // namespace content
#endif // CONTENT_RENDERER_DEVICE_SENSORS_DEVICE_SENSOR_EVENT_PUMP_H_
diff --git a/chromium/content/renderer/device_sensors/fake_sensor_and_provider.cc b/chromium/content/renderer/device_sensors/fake_sensor_and_provider.cc
deleted file mode 100644
index 84e29b5fc45..00000000000
--- a/chromium/content/renderer/device_sensors/fake_sensor_and_provider.cc
+++ /dev/null
@@ -1,241 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/renderer/device_sensors/fake_sensor_and_provider.h"
-
-#include <memory>
-#include <utility>
-
-#include "base/logging.h"
-#include "base/time/time.h"
-#include "mojo/public/cpp/bindings/interface_request.h"
-#include "mojo/public/cpp/bindings/strong_binding.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace content {
-
-FakeSensor::FakeSensor(device::mojom::SensorType sensor_type)
- : sensor_type_(sensor_type) {
- shared_buffer_handle_ = mojo::SharedBufferHandle::Create(
- sizeof(device::SensorReadingSharedBuffer) *
- static_cast<uint64_t>(device::mojom::SensorType::LAST));
-
- if (!shared_buffer_handle_.is_valid())
- return;
-
- // Create read/write mapping now, to ensure it is kept writable
- // after the region is sealed read-only on Android.
- shared_buffer_mapping_ = shared_buffer_handle_->MapAtOffset(
- device::mojom::SensorInitParams::kReadBufferSizeForTests,
- GetBufferOffset());
-}
-
-FakeSensor::~FakeSensor() = default;
-
-void FakeSensor::AddConfiguration(
- const device::PlatformSensorConfiguration& configuration,
- AddConfigurationCallback callback) {
- std::move(callback).Run(true);
-}
-
-void FakeSensor::GetDefaultConfiguration(
- GetDefaultConfigurationCallback callback) {
- std::move(callback).Run(GetDefaultConfiguration());
-}
-
-void FakeSensor::RemoveConfiguration(
- const device::PlatformSensorConfiguration& configuration) {}
-
-void FakeSensor::Suspend() {}
-
-void FakeSensor::Resume() {}
-
-void FakeSensor::ConfigureReadingChangeNotifications(bool enabled) {
- reading_notification_enabled_ = enabled;
-}
-
-device::PlatformSensorConfiguration FakeSensor::GetDefaultConfiguration() {
- return device::PlatformSensorConfiguration(60 /* frequency */);
-}
-
-device::mojom::ReportingMode FakeSensor::GetReportingMode() {
- return device::mojom::ReportingMode::ON_CHANGE;
-}
-
-double FakeSensor::GetMaximumSupportedFrequency() {
- return 60.0;
-}
-
-double FakeSensor::GetMinimumSupportedFrequency() {
- return 1.0;
-}
-
-device::mojom::SensorClientRequest FakeSensor::GetClient() {
- return mojo::MakeRequest(&client_);
-}
-
-mojo::ScopedSharedBufferHandle FakeSensor::GetSharedBufferHandle() {
- return shared_buffer_handle_->Clone(
- mojo::SharedBufferHandle::AccessMode::READ_ONLY);
-}
-
-uint64_t FakeSensor::GetBufferOffset() {
- return device::SensorReadingSharedBuffer::GetOffset(sensor_type_);
-}
-
-void FakeSensor::SetReading(device::SensorReading reading) {
- reading_ = reading;
- SensorReadingChanged();
-}
-
-void FakeSensor::SensorReadingChanged() {
- if (!shared_buffer_mapping_.get())
- return;
-
- auto* buffer = static_cast<device::SensorReadingSharedBuffer*>(
- shared_buffer_mapping_.get());
-
- auto& seqlock = buffer->seqlock.value();
- seqlock.WriteBegin();
- buffer->reading = reading_;
- seqlock.WriteEnd();
-
- if (client_ && reading_notification_enabled_)
- client_->SensorReadingChanged();
-}
-
-FakeSensorProvider::FakeSensorProvider() : binding_(this) {}
-
-FakeSensorProvider::~FakeSensorProvider() = default;
-
-void FakeSensorProvider::GetSensor(device::mojom::SensorType type,
- GetSensorCallback callback) {
- std::unique_ptr<FakeSensor> sensor;
-
- switch (type) {
- case device::mojom::SensorType::ACCELEROMETER:
- if (accelerometer_is_available_) {
- sensor = std::make_unique<FakeSensor>(
- device::mojom::SensorType::ACCELEROMETER);
- accelerometer_ = sensor.get();
- }
- break;
- case device::mojom::SensorType::LINEAR_ACCELERATION:
- if (linear_acceleration_sensor_is_available_) {
- sensor = std::make_unique<FakeSensor>(
- device::mojom::SensorType::LINEAR_ACCELERATION);
- linear_acceleration_sensor_ = sensor.get();
- }
- break;
- case device::mojom::SensorType::GYROSCOPE:
- if (gyroscope_is_available_) {
- sensor =
- std::make_unique<FakeSensor>(device::mojom::SensorType::GYROSCOPE);
- gyroscope_ = sensor.get();
- }
- break;
- case device::mojom::SensorType::RELATIVE_ORIENTATION_EULER_ANGLES:
- if (relative_orientation_sensor_is_available_) {
- sensor = std::make_unique<FakeSensor>(
- device::mojom::SensorType::RELATIVE_ORIENTATION_EULER_ANGLES);
- relative_orientation_sensor_ = sensor.get();
- }
- break;
- case device::mojom::SensorType::ABSOLUTE_ORIENTATION_EULER_ANGLES:
- if (absolute_orientation_sensor_is_available_) {
- sensor = std::make_unique<FakeSensor>(
- device::mojom::SensorType::ABSOLUTE_ORIENTATION_EULER_ANGLES);
- absolute_orientation_sensor_ = sensor.get();
- }
- break;
- default:
- NOTIMPLEMENTED();
- }
-
- if (sensor) {
- auto init_params = device::mojom::SensorInitParams::New();
- init_params->client_request = sensor->GetClient();
- init_params->memory = sensor->GetSharedBufferHandle();
- init_params->buffer_offset = sensor->GetBufferOffset();
- init_params->default_configuration = sensor->GetDefaultConfiguration();
- init_params->maximum_frequency = sensor->GetMaximumSupportedFrequency();
- init_params->minimum_frequency = sensor->GetMinimumSupportedFrequency();
-
- mojo::MakeStrongBinding(std::move(sensor),
- mojo::MakeRequest(&init_params->sensor));
- std::move(callback).Run(device::mojom::SensorCreationResult::SUCCESS,
- std::move(init_params));
- } else {
- std::move(callback).Run(
- device::mojom::SensorCreationResult::ERROR_NOT_AVAILABLE, nullptr);
- }
-}
-
-void FakeSensorProvider::Bind(device::mojom::SensorProviderRequest request) {
- DCHECK(!binding_.is_bound());
- binding_.Bind(std::move(request));
-}
-
-void FakeSensorProvider::SetAccelerometerData(double x, double y, double z) {
- device::SensorReading reading;
- reading.raw.timestamp =
- (base::TimeTicks::Now() - base::TimeTicks()).InSecondsF();
- reading.accel.x = x;
- reading.accel.y = y;
- reading.accel.z = z;
- EXPECT_TRUE(accelerometer_);
- accelerometer_->SetReading(reading);
-}
-
-void FakeSensorProvider::SetLinearAccelerationSensorData(double x,
- double y,
- double z) {
- device::SensorReading reading;
- reading.raw.timestamp =
- (base::TimeTicks::Now() - base::TimeTicks()).InSecondsF();
- reading.accel.x = x;
- reading.accel.y = y;
- reading.accel.z = z;
- EXPECT_TRUE(linear_acceleration_sensor_);
- linear_acceleration_sensor_->SetReading(reading);
-}
-
-void FakeSensorProvider::SetGyroscopeData(double x, double y, double z) {
- device::SensorReading reading;
- reading.raw.timestamp =
- (base::TimeTicks::Now() - base::TimeTicks()).InSecondsF();
- reading.gyro.x = x;
- reading.gyro.y = y;
- reading.gyro.z = z;
- EXPECT_TRUE(gyroscope_);
- gyroscope_->SetReading(reading);
-}
-
-void FakeSensorProvider::SetRelativeOrientationSensorData(double alpha,
- double beta,
- double gamma) {
- device::SensorReading reading;
- reading.raw.timestamp =
- (base::TimeTicks::Now() - base::TimeTicks()).InSecondsF();
- reading.orientation_euler.x = beta;
- reading.orientation_euler.y = gamma;
- reading.orientation_euler.z = alpha;
- EXPECT_TRUE(relative_orientation_sensor_);
- relative_orientation_sensor_->SetReading(reading);
-}
-
-void FakeSensorProvider::SetAbsoluteOrientationSensorData(double alpha,
- double beta,
- double gamma) {
- device::SensorReading reading;
- reading.raw.timestamp =
- (base::TimeTicks::Now() - base::TimeTicks()).InSecondsF();
- reading.orientation_euler.x = beta;
- reading.orientation_euler.y = gamma;
- reading.orientation_euler.z = alpha;
- EXPECT_TRUE(absolute_orientation_sensor_);
- absolute_orientation_sensor_->SetReading(reading);
-}
-
-} // namespace content
diff --git a/chromium/content/renderer/device_sensors/fake_sensor_and_provider.h b/chromium/content/renderer/device_sensors/fake_sensor_and_provider.h
deleted file mode 100644
index fb934e3713e..00000000000
--- a/chromium/content/renderer/device_sensors/fake_sensor_and_provider.h
+++ /dev/null
@@ -1,136 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_RENDERER_DEVICE_SENSORS_FAKE_SENSOR_AND_PROVIDER_H_
-#define CONTENT_RENDERER_DEVICE_SENSORS_FAKE_SENSOR_AND_PROVIDER_H_
-
-#include "base/macros.h"
-#include "mojo/public/cpp/bindings/binding.h"
-#include "mojo/public/cpp/system/buffer.h"
-#include "services/device/public/cpp/generic_sensor/sensor_reading.h"
-#include "services/device/public/mojom/sensor.mojom.h"
-#include "services/device/public/mojom/sensor_provider.mojom.h"
-
-// TODO(juncai): Move this file in a new
-// //services/device/public/cpp/generic_sensor:test_support source_set and
-// share it with device_sensor_browsertest.cc and generic_sensor_browsertest.cc.
-
-namespace content {
-
-class FakeSensor : public device::mojom::Sensor {
- public:
- FakeSensor(device::mojom::SensorType sensor_type);
- ~FakeSensor() override;
-
- // device::mojom::Sensor:
- void AddConfiguration(
- const device::PlatformSensorConfiguration& configuration,
- AddConfigurationCallback callback) override;
- void GetDefaultConfiguration(
- GetDefaultConfigurationCallback callback) override;
- void RemoveConfiguration(
- const device::PlatformSensorConfiguration& configuration) override;
- void Suspend() override;
- void Resume() override;
- void ConfigureReadingChangeNotifications(bool enabled) override;
-
- device::PlatformSensorConfiguration GetDefaultConfiguration();
-
- device::mojom::ReportingMode GetReportingMode();
-
- double GetMaximumSupportedFrequency();
-
- double GetMinimumSupportedFrequency();
-
- device::mojom::SensorClientRequest GetClient();
-
- mojo::ScopedSharedBufferHandle GetSharedBufferHandle();
-
- uint64_t GetBufferOffset();
-
- void SetReading(device::SensorReading reading);
-
- private:
- void SensorReadingChanged();
-
- device::mojom::SensorType sensor_type_;
- bool reading_notification_enabled_ = true;
- mojo::ScopedSharedBufferHandle shared_buffer_handle_;
- mojo::ScopedSharedBufferMapping shared_buffer_mapping_;
- device::mojom::SensorClientPtr client_;
- device::SensorReading reading_;
-
- DISALLOW_COPY_AND_ASSIGN(FakeSensor);
-};
-
-class FakeSensorProvider : public device::mojom::SensorProvider {
- public:
- FakeSensorProvider();
- ~FakeSensorProvider() override;
-
- // device::mojom::sensorProvider:
- void GetSensor(device::mojom::SensorType type,
- GetSensorCallback callback) override;
-
- void Bind(device::mojom::SensorProviderRequest request);
-
- void set_accelerometer_is_available(bool accelerometer_is_available) {
- accelerometer_is_available_ = accelerometer_is_available;
- }
-
- void set_linear_acceleration_sensor_is_available(
- bool linear_acceleration_sensor_is_available) {
- linear_acceleration_sensor_is_available_ =
- linear_acceleration_sensor_is_available;
- }
-
- void set_gyroscope_is_available(bool gyroscope_is_available) {
- gyroscope_is_available_ = gyroscope_is_available;
- }
-
- void set_relative_orientation_sensor_is_available(
- bool relative_orientation_sensor_is_available) {
- relative_orientation_sensor_is_available_ =
- relative_orientation_sensor_is_available;
- }
-
- void set_absolute_orientation_sensor_is_available(
- bool absolute_orientation_sensor_is_available) {
- absolute_orientation_sensor_is_available_ =
- absolute_orientation_sensor_is_available;
- }
-
- void SetAccelerometerData(double x, double y, double z);
-
- void SetLinearAccelerationSensorData(double x, double y, double z);
-
- void SetGyroscopeData(double x, double y, double z);
-
- void SetRelativeOrientationSensorData(double alpha,
- double beta,
- double gamma);
-
- void SetAbsoluteOrientationSensorData(double alpha,
- double beta,
- double gamma);
-
- private:
- FakeSensor* accelerometer_ = nullptr;
- FakeSensor* linear_acceleration_sensor_ = nullptr;
- FakeSensor* gyroscope_ = nullptr;
- FakeSensor* relative_orientation_sensor_ = nullptr;
- FakeSensor* absolute_orientation_sensor_ = nullptr;
- bool accelerometer_is_available_ = true;
- bool linear_acceleration_sensor_is_available_ = true;
- bool gyroscope_is_available_ = true;
- bool relative_orientation_sensor_is_available_ = true;
- bool absolute_orientation_sensor_is_available_ = true;
- mojo::Binding<device::mojom::SensorProvider> binding_;
-
- DISALLOW_COPY_AND_ASSIGN(FakeSensorProvider);
-};
-
-} // namespace content
-
-#endif // CONTENT_RENDERER_DEVICE_SENSORS_FAKE_SENSOR_AND_PROVIDER_H_
diff --git a/chromium/content/renderer/devtools/render_widget_screen_metrics_emulator.h b/chromium/content/renderer/devtools/render_widget_screen_metrics_emulator.h
index 2e67325389a..3497fe04752 100644
--- a/chromium/content/renderer/devtools/render_widget_screen_metrics_emulator.h
+++ b/chromium/content/renderer/devtools/render_widget_screen_metrics_emulator.h
@@ -8,7 +8,7 @@
#include <memory>
#include "content/common/resize_params.h"
-#include "third_party/WebKit/public/web/WebDeviceEmulationParams.h"
+#include "third_party/blink/public/web/web_device_emulation_params.h"
namespace gfx {
class Rect;
diff --git a/chromium/content/renderer/dom_automation_controller.cc b/chromium/content/renderer/dom_automation_controller.cc
index 60d29f63540..4e7f80bf361 100644
--- a/chromium/content/renderer/dom_automation_controller.cc
+++ b/chromium/content/renderer/dom_automation_controller.cc
@@ -11,8 +11,8 @@
#include "content/renderer/v8_value_converter_impl.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
-#include "third_party/WebKit/public/web/WebKit.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "third_party/blink/public/web/blink.h"
+#include "third_party/blink/public/web/web_local_frame.h"
namespace content {
diff --git a/chromium/content/renderer/dom_serializer_browsertest.cc b/chromium/content/renderer/dom_serializer_browsertest.cc
index 10747d222dc..c91dd9293d9 100644
--- a/chromium/content/renderer/dom_serializer_browsertest.cc
+++ b/chromium/content/renderer/dom_serializer_browsertest.cc
@@ -29,20 +29,20 @@
#include "content/shell/browser/shell.h"
#include "net/base/filename_util.h"
#include "net/url_request/url_request_context.h"
-#include "third_party/WebKit/public/platform/WebData.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
-#include "third_party/WebKit/public/platform/WebVector.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebElement.h"
-#include "third_party/WebKit/public/web/WebElementCollection.h"
-#include "third_party/WebKit/public/web/WebFrameContentDumper.h"
-#include "third_party/WebKit/public/web/WebFrameSerializer.h"
-#include "third_party/WebKit/public/web/WebFrameSerializerClient.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebMetaElement.h"
-#include "third_party/WebKit/public/web/WebNode.h"
-#include "third_party/WebKit/public/web/WebView.h"
+#include "third_party/blink/public/platform/web_data.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_url.h"
+#include "third_party/blink/public/platform/web_vector.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_element.h"
+#include "third_party/blink/public/web/web_element_collection.h"
+#include "third_party/blink/public/web/web_frame_content_dumper.h"
+#include "third_party/blink/public/web/web_frame_serializer.h"
+#include "third_party/blink/public/web/web_frame_serializer_client.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_meta_element.h"
+#include "third_party/blink/public/web/web_node.h"
+#include "third_party/blink/public/web/web_view.h"
using blink::WebData;
using blink::WebDocument;
diff --git a/chromium/content/renderer/dom_storage/DEPS b/chromium/content/renderer/dom_storage/DEPS
index b1259df127b..48915ca750d 100644
--- a/chromium/content/renderer/dom_storage/DEPS
+++ b/chromium/content/renderer/dom_storage/DEPS
@@ -1,13 +1,14 @@
specific_include_rules = {
'local_storage\.*': [
"-content/renderer",
- "+components/leveldb/public/interfaces",
+ "+components/services/leveldb/public/interfaces",
"+content/common/dom_storage/dom_storage_map.h",
"+content/renderer/dom_storage/local_storage_cached_area.h",
"+content/renderer/dom_storage/local_storage_cached_areas.h",
"+content/renderer/dom_storage/local_storage_area.h",
"+content/renderer/dom_storage/local_storage_namespace.h",
"+content/renderer/dom_storage/mock_leveldb_wrapper.h",
+ "+content/renderer/dom_storage/webstoragenamespace_impl.h",
"+content/renderer/render_thread_impl.h",
],
}
diff --git a/chromium/content/renderer/dom_storage/dom_storage_cached_area.cc b/chromium/content/renderer/dom_storage/dom_storage_cached_area.cc
index 805470f059a..f21e958f7d7 100644
--- a/chromium/content/renderer/dom_storage/dom_storage_cached_area.cc
+++ b/chromium/content/renderer/dom_storage/dom_storage_cached_area.cc
@@ -11,7 +11,7 @@
#include "build/build_config.h"
#include "content/common/dom_storage/dom_storage_map.h"
#include "content/renderer/dom_storage/dom_storage_proxy.h"
-#include "third_party/WebKit/public/platform/scheduler/renderer/renderer_scheduler.h"
+#include "third_party/blink/public/platform/scheduler/web_main_thread_scheduler.h"
namespace content {
@@ -19,12 +19,12 @@ DOMStorageCachedArea::DOMStorageCachedArea(
const std::string& namespace_id,
const GURL& origin,
DOMStorageProxy* proxy,
- blink::scheduler::RendererScheduler* renderer_scheduler)
+ blink::scheduler::WebMainThreadScheduler* main_thread_scheduler)
: ignore_all_mutations_(false),
namespace_id_(namespace_id),
origin_(origin),
proxy_(proxy),
- renderer_scheduler_(renderer_scheduler),
+ main_thread_scheduler_(main_thread_scheduler),
weak_factory_(this) {}
DOMStorageCachedArea::~DOMStorageCachedArea() {}
@@ -73,13 +73,14 @@ bool DOMStorageCachedArea::SetItem(int connection_id,
// Ignore mutations to 'key' until OnSetItemComplete.
blink::WebScopedVirtualTimePauser virtual_time_pauser =
- renderer_scheduler_->CreateWebScopedVirtualTimePauser();
- virtual_time_pauser.PauseVirtualTime(true);
+ main_thread_scheduler_->CreateWebScopedVirtualTimePauser(
+ "DOMStorageCachedArea");
+ virtual_time_pauser.PauseVirtualTime();
ignore_key_mutations_[key]++;
proxy_->SetItem(connection_id, key, value, old_value, page_url,
- base::Bind(&DOMStorageCachedArea::OnSetItemComplete,
- weak_factory_.GetWeakPtr(), key,
- base::Passed(std::move(virtual_time_pauser))));
+ base::BindOnce(&DOMStorageCachedArea::OnSetItemComplete,
+ weak_factory_.GetWeakPtr(), key,
+ std::move(virtual_time_pauser)));
return true;
}
@@ -100,14 +101,15 @@ void DOMStorageCachedArea::RemoveItem(int connection_id,
// Ignore mutations to 'key' until OnRemoveItemComplete.
blink::WebScopedVirtualTimePauser virtual_time_pauser =
- renderer_scheduler_->CreateWebScopedVirtualTimePauser();
- virtual_time_pauser.PauseVirtualTime(true);
+ main_thread_scheduler_->CreateWebScopedVirtualTimePauser(
+ "DOMStorageCachedArea");
+ virtual_time_pauser.PauseVirtualTime();
ignore_key_mutations_[key]++;
proxy_->RemoveItem(connection_id, key,
base::NullableString16(old_value, false), page_url,
- base::Bind(&DOMStorageCachedArea::OnRemoveItemComplete,
- weak_factory_.GetWeakPtr(), key,
- base::Passed(std::move(virtual_time_pauser))));
+ base::BindOnce(&DOMStorageCachedArea::OnRemoveItemComplete,
+ weak_factory_.GetWeakPtr(), key,
+ std::move(virtual_time_pauser)));
}
void DOMStorageCachedArea::Clear(int connection_id, const GURL& page_url) {
@@ -117,13 +119,14 @@ void DOMStorageCachedArea::Clear(int connection_id, const GURL& page_url) {
// Ignore all mutations until OnClearComplete time.
blink::WebScopedVirtualTimePauser virtual_time_pauser =
- renderer_scheduler_->CreateWebScopedVirtualTimePauser();
- virtual_time_pauser.PauseVirtualTime(true);
+ main_thread_scheduler_->CreateWebScopedVirtualTimePauser(
+ "DOMStorageCachedArea");
+ virtual_time_pauser.PauseVirtualTime();
ignore_all_mutations_ = true;
proxy_->ClearArea(connection_id, page_url,
- base::Bind(&DOMStorageCachedArea::OnClearComplete,
- weak_factory_.GetWeakPtr(),
- base::Passed(std::move(virtual_time_pauser))));
+ base::BindOnce(&DOMStorageCachedArea::OnClearComplete,
+ weak_factory_.GetWeakPtr(),
+ std::move(virtual_time_pauser)));
}
void DOMStorageCachedArea::ApplyMutation(
@@ -182,10 +185,9 @@ void DOMStorageCachedArea::Prime(int connection_id) {
ignore_all_mutations_ = true;
DOMStorageValuesMap values;
base::TimeTicks before = base::TimeTicks::Now();
- proxy_->LoadArea(connection_id,
- &values,
- base::Bind(&DOMStorageCachedArea::OnLoadComplete,
- weak_factory_.GetWeakPtr()));
+ proxy_->LoadArea(connection_id, &values,
+ base::BindOnce(&DOMStorageCachedArea::OnLoadComplete,
+ weak_factory_.GetWeakPtr()));
base::TimeDelta time_to_prime = base::TimeTicks::Now() - before;
// Keeping this histogram named the same (without the ForRenderer suffix)
// to maintain histogram continuity.
diff --git a/chromium/content/renderer/dom_storage/dom_storage_cached_area.h b/chromium/content/renderer/dom_storage/dom_storage_cached_area.h
index 4e3971002b1..a7ebb1dd0c2 100644
--- a/chromium/content/renderer/dom_storage/dom_storage_cached_area.h
+++ b/chromium/content/renderer/dom_storage/dom_storage_cached_area.h
@@ -14,12 +14,12 @@
#include "base/memory/weak_ptr.h"
#include "base/strings/nullable_string16.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebScopedVirtualTimePauser.h"
+#include "third_party/blink/public/platform/web_scoped_virtual_time_pauser.h"
#include "url/gurl.h"
namespace blink {
namespace scheduler {
-class RendererScheduler;
+class WebMainThreadScheduler;
}
} // namespace blink
@@ -37,10 +37,11 @@ class DOMStorageProxy;
class CONTENT_EXPORT DOMStorageCachedArea
: public base::RefCounted<DOMStorageCachedArea> {
public:
- DOMStorageCachedArea(const std::string& namespace_id,
- const GURL& origin,
- DOMStorageProxy* proxy,
- blink::scheduler::RendererScheduler* renderer_scheduler);
+ DOMStorageCachedArea(
+ const std::string& namespace_id,
+ const GURL& origin,
+ DOMStorageProxy* proxy,
+ blink::scheduler::WebMainThreadScheduler* main_thread_scheduler);
const std::string& namespace_id() const { return namespace_id_; }
const GURL& origin() const { return origin_; }
@@ -101,7 +102,10 @@ class CONTENT_EXPORT DOMStorageCachedArea
GURL origin_;
scoped_refptr<DOMStorageMap> map_;
scoped_refptr<DOMStorageProxy> proxy_;
- blink::scheduler::RendererScheduler* renderer_scheduler_; // NOT OWNED
+
+ // Not owned.
+ blink::scheduler::WebMainThreadScheduler* main_thread_scheduler_;
+
base::WeakPtrFactory<DOMStorageCachedArea> weak_factory_;
};
diff --git a/chromium/content/renderer/dom_storage/dom_storage_cached_area_unittest.cc b/chromium/content/renderer/dom_storage/dom_storage_cached_area_unittest.cc
index 3a9dd025391..1c0afc9434d 100644
--- a/chromium/content/renderer/dom_storage/dom_storage_cached_area_unittest.cc
+++ b/chromium/content/renderer/dom_storage/dom_storage_cached_area_unittest.cc
@@ -13,7 +13,7 @@
#include "base/strings/utf_string_conversions.h"
#include "content/renderer/dom_storage/dom_storage_proxy.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/scheduler/test/fake_renderer_scheduler.h"
+#include "third_party/blink/public/platform/scheduler/test/fake_renderer_scheduler.h"
namespace content {
@@ -29,8 +29,8 @@ class MockProxy : public DOMStorageProxy {
void LoadArea(int connection_id,
DOMStorageValuesMap* values,
- const CompletionCallback& callback) override {
- pending_callbacks_.push_back(callback);
+ CompletionCallback callback) override {
+ pending_callbacks_.push_back(std::move(callback));
observed_load_area_ = true;
observed_connection_id_ = connection_id;
*values = load_area_return_values_;
@@ -41,8 +41,8 @@ class MockProxy : public DOMStorageProxy {
const base::string16& value,
const base::NullableString16& old_value,
const GURL& page_url,
- const CompletionCallback& callback) override {
- pending_callbacks_.push_back(callback);
+ CompletionCallback callback) override {
+ pending_callbacks_.push_back(std::move(callback));
observed_set_item_ = true;
observed_connection_id_ = connection_id;
observed_key_ = key;
@@ -54,8 +54,8 @@ class MockProxy : public DOMStorageProxy {
const base::string16& key,
const base::NullableString16& old_value,
const GURL& page_url,
- const CompletionCallback& callback) override {
- pending_callbacks_.push_back(callback);
+ CompletionCallback callback) override {
+ pending_callbacks_.push_back(std::move(callback));
observed_remove_item_ = true;
observed_connection_id_ = connection_id;
observed_key_ = key;
@@ -64,8 +64,8 @@ class MockProxy : public DOMStorageProxy {
void ClearArea(int connection_id,
const GURL& page_url,
- const CompletionCallback& callback) override {
- pending_callbacks_.push_back(callback);
+ CompletionCallback callback) override {
+ pending_callbacks_.push_back(std::move(callback));
observed_clear_area_ = true;
observed_connection_id_ = connection_id;
observed_page_url_ = page_url;
@@ -91,7 +91,7 @@ class MockProxy : public DOMStorageProxy {
void CompleteOnePendingCallback(bool success) {
ASSERT_TRUE(!pending_callbacks_.empty());
- pending_callbacks_.front().Run(success);
+ std::move(pending_callbacks_.front()).Run(success);
pending_callbacks_.pop_front();
}
@@ -130,7 +130,7 @@ class DOMStorageCachedAreaTest : public testing::Test {
const GURL kPageUrl;
void SetUp() override {
- renderer_scheduler_ =
+ main_thread_scheduler_ =
std::make_unique<blink::scheduler::FakeRendererScheduler>();
mock_proxy_ = new MockProxy();
}
@@ -160,14 +160,15 @@ class DOMStorageCachedAreaTest : public testing::Test {
protected:
base::MessageLoop message_loop_; // Needed to construct a RendererScheduler.
- std::unique_ptr<blink::scheduler::RendererScheduler> renderer_scheduler_;
+ std::unique_ptr<blink::scheduler::WebMainThreadScheduler>
+ main_thread_scheduler_;
scoped_refptr<MockProxy> mock_proxy_;
};
TEST_F(DOMStorageCachedAreaTest, Basics) {
EXPECT_TRUE(mock_proxy_->HasOneRef());
scoped_refptr<DOMStorageCachedArea> cached_area = new DOMStorageCachedArea(
- kNamespaceId, kOrigin, mock_proxy_.get(), renderer_scheduler_.get());
+ kNamespaceId, kOrigin, mock_proxy_.get(), main_thread_scheduler_.get());
EXPECT_EQ(kNamespaceId, cached_area->namespace_id());
EXPECT_EQ(kOrigin, cached_area->origin());
EXPECT_FALSE(mock_proxy_->HasOneRef());
@@ -192,7 +193,7 @@ TEST_F(DOMStorageCachedAreaTest, Basics) {
TEST_F(DOMStorageCachedAreaTest, Getters) {
const int kConnectionId = 7;
scoped_refptr<DOMStorageCachedArea> cached_area = new DOMStorageCachedArea(
- kNamespaceId, kOrigin, mock_proxy_.get(), renderer_scheduler_.get());
+ kNamespaceId, kOrigin, mock_proxy_.get(), main_thread_scheduler_.get());
// GetLength, we expect to see one call to load in the proxy.
EXPECT_FALSE(IsPrimed(cached_area.get()));
@@ -227,7 +228,7 @@ TEST_F(DOMStorageCachedAreaTest, Getters) {
TEST_F(DOMStorageCachedAreaTest, Setters) {
const int kConnectionId = 7;
scoped_refptr<DOMStorageCachedArea> cached_area = new DOMStorageCachedArea(
- kNamespaceId, kOrigin, mock_proxy_.get(), renderer_scheduler_.get());
+ kNamespaceId, kOrigin, mock_proxy_.get(), main_thread_scheduler_.get());
// SetItem, we expect a call to load followed by a call to set item
// in the proxy.
@@ -282,7 +283,7 @@ TEST_F(DOMStorageCachedAreaTest, Setters) {
TEST_F(DOMStorageCachedAreaTest, MutationsAreIgnoredUntilLoadCompletion) {
const int kConnectionId = 7;
scoped_refptr<DOMStorageCachedArea> cached_area = new DOMStorageCachedArea(
- kNamespaceId, kOrigin, mock_proxy_.get(), renderer_scheduler_.get());
+ kNamespaceId, kOrigin, mock_proxy_.get(), main_thread_scheduler_.get());
EXPECT_TRUE(cached_area->GetItem(kConnectionId, kKey).is_null());
EXPECT_TRUE(IsPrimed(cached_area.get()));
EXPECT_TRUE(IsIgnoringAllMutations(cached_area.get()));
@@ -305,7 +306,7 @@ TEST_F(DOMStorageCachedAreaTest, MutationsAreIgnoredUntilLoadCompletion) {
TEST_F(DOMStorageCachedAreaTest, MutationsAreIgnoredUntilClearCompletion) {
const int kConnectionId = 4;
scoped_refptr<DOMStorageCachedArea> cached_area = new DOMStorageCachedArea(
- kNamespaceId, kOrigin, mock_proxy_.get(), renderer_scheduler_.get());
+ kNamespaceId, kOrigin, mock_proxy_.get(), main_thread_scheduler_.get());
cached_area->Clear(kConnectionId, kPageUrl);
EXPECT_TRUE(IsIgnoringAllMutations(cached_area.get()));
mock_proxy_->CompleteOnePendingCallback(true);
@@ -327,7 +328,7 @@ TEST_F(DOMStorageCachedAreaTest, MutationsAreIgnoredUntilClearCompletion) {
TEST_F(DOMStorageCachedAreaTest, KeyMutationsAreIgnoredUntilCompletion) {
const int kConnectionId = 8;
scoped_refptr<DOMStorageCachedArea> cached_area = new DOMStorageCachedArea(
- kNamespaceId, kOrigin, mock_proxy_.get(), renderer_scheduler_.get());
+ kNamespaceId, kOrigin, mock_proxy_.get(), main_thread_scheduler_.get());
// SetItem
EXPECT_TRUE(cached_area->SetItem(kConnectionId, kKey, kValue, kPageUrl));
diff --git a/chromium/content/renderer/dom_storage/dom_storage_dispatcher.cc b/chromium/content/renderer/dom_storage/dom_storage_dispatcher.cc
index 1842a2fcf73..0a8b4befde3 100644
--- a/chromium/content/renderer/dom_storage/dom_storage_dispatcher.cc
+++ b/chromium/content/renderer/dom_storage/dom_storage_dispatcher.cc
@@ -17,9 +17,9 @@
#include "content/renderer/dom_storage/webstoragenamespace_impl.h"
#include "content/renderer/render_thread_impl.h"
#include "ipc/message_filter.h"
-#include "third_party/WebKit/public/platform/Platform.h"
-#include "third_party/WebKit/public/web/WebKit.h"
-#include "third_party/WebKit/public/web/WebStorageEventDispatcher.h"
+#include "third_party/blink/public/platform/platform.h"
+#include "third_party/blink/public/web/blink.h"
+#include "third_party/blink/public/web/web_storage_event_dispatcher.h"
namespace content {
@@ -110,21 +110,21 @@ class DomStorageDispatcher::ProxyImpl : public DOMStorageProxy {
// DOMStorageProxy interface for use by DOMStorageCachedArea.
void LoadArea(int connection_id,
DOMStorageValuesMap* values,
- const CompletionCallback& callback) override;
+ CompletionCallback callback) override;
void SetItem(int connection_id,
const base::string16& key,
const base::string16& value,
const base::NullableString16& old_value,
const GURL& page_url,
- const CompletionCallback& callback) override;
+ CompletionCallback callback) override;
void RemoveItem(int connection_id,
const base::string16& key,
const base::NullableString16& old_value,
const GURL& page_url,
- const CompletionCallback& callback) override;
+ CompletionCallback callback) override;
void ClearArea(int connection_id,
const GURL& page_url,
- const CompletionCallback& callback) override;
+ CompletionCallback callback) override;
private:
// Struct to hold references to our contained areas and
@@ -141,7 +141,7 @@ class DomStorageDispatcher::ProxyImpl : public DOMStorageProxy {
~ProxyImpl() override {}
- void PushPendingCallback(const CompletionCallback& callback) {
+ void PushPendingCallback(CompletionCallback callback) {
// Terminate the renderer if an excessive number of calls are made,
// This is indicative of script in an infinite loop or being malicious.
// It's better to crash intentionally than by running the system OOM
@@ -154,11 +154,11 @@ class DomStorageDispatcher::ProxyImpl : public DOMStorageProxy {
// to more reliably commit changes during shutdown.
if (pending_callbacks_.empty())
blink::Platform::Current()->SuddenTerminationChanged(false);
- pending_callbacks_.push_back(callback);
+ pending_callbacks_.push_back(std::move(callback));
}
CompletionCallback PopPendingCallback() {
- CompletionCallback callback = pending_callbacks_.front();
+ CompletionCallback callback = std::move(pending_callbacks_.front());
pending_callbacks_.pop_front();
if (pending_callbacks_.empty())
blink::Platform::Current()->SuddenTerminationChanged(true);
@@ -199,7 +199,7 @@ DOMStorageCachedArea* DomStorageDispatcher::ProxyImpl::OpenCachedArea(
}
scoped_refptr<DOMStorageCachedArea> area = new DOMStorageCachedArea(
namespace_id, origin, this,
- content::RenderThreadImpl::current()->GetRendererScheduler());
+ content::RenderThreadImpl::current()->GetWebMainThreadScheduler());
cached_areas_[key] = CachedAreaHolder(area.get(), 1);
return area.get();
}
@@ -238,10 +238,10 @@ void DomStorageDispatcher::ProxyImpl::Shutdown() {
pending_callbacks_.clear();
}
-void DomStorageDispatcher::ProxyImpl::LoadArea(
- int connection_id, DOMStorageValuesMap* values,
- const CompletionCallback& callback) {
- PushPendingCallback(callback);
+void DomStorageDispatcher::ProxyImpl::LoadArea(int connection_id,
+ DOMStorageValuesMap* values,
+ CompletionCallback callback) {
+ PushPendingCallback(std::move(callback));
throttling_filter_->SendThrottled(new DOMStorageHostMsg_LoadStorageArea(
connection_id, values));
}
@@ -252,8 +252,8 @@ void DomStorageDispatcher::ProxyImpl::SetItem(
const base::string16& value,
const base::NullableString16& old_value,
const GURL& page_url,
- const CompletionCallback& callback) {
- PushPendingCallback(callback);
+ CompletionCallback callback) {
+ PushPendingCallback(std::move(callback));
throttling_filter_->SendThrottled(new DOMStorageHostMsg_SetItem(
connection_id, key, value, old_value, page_url));
}
@@ -263,16 +263,16 @@ void DomStorageDispatcher::ProxyImpl::RemoveItem(
const base::string16& key,
const base::NullableString16& old_value,
const GURL& page_url,
- const CompletionCallback& callback) {
- PushPendingCallback(callback);
+ CompletionCallback callback) {
+ PushPendingCallback(std::move(callback));
throttling_filter_->SendThrottled(new DOMStorageHostMsg_RemoveItem(
connection_id, key, old_value, page_url));
}
void DomStorageDispatcher::ProxyImpl::ClearArea(int connection_id,
- const GURL& page_url,
- const CompletionCallback& callback) {
- PushPendingCallback(callback);
+ const GURL& page_url,
+ CompletionCallback callback) {
+ PushPendingCallback(std::move(callback));
throttling_filter_->SendThrottled(new DOMStorageHostMsg_Clear(
connection_id, page_url));
}
diff --git a/chromium/content/renderer/dom_storage/dom_storage_proxy.h b/chromium/content/renderer/dom_storage/dom_storage_proxy.h
index 8fbd361b2c2..9434567a443 100644
--- a/chromium/content/renderer/dom_storage/dom_storage_proxy.h
+++ b/chromium/content/renderer/dom_storage/dom_storage_proxy.h
@@ -17,28 +17,28 @@ namespace content {
// Abstract interface for cached area, renderer to browser communications.
class DOMStorageProxy : public base::RefCounted<DOMStorageProxy> {
public:
- typedef base::Callback<void(bool)> CompletionCallback;
+ typedef base::OnceCallback<void(bool)> CompletionCallback;
virtual void LoadArea(int connection_id,
DOMStorageValuesMap* values,
- const CompletionCallback& callback) = 0;
+ CompletionCallback callback) = 0;
virtual void SetItem(int connection_id,
const base::string16& key,
const base::string16& value,
const base::NullableString16& old_value,
const GURL& page_url,
- const CompletionCallback& callback) = 0;
+ CompletionCallback callback) = 0;
virtual void RemoveItem(int connection_id,
const base::string16& key,
const base::NullableString16& old_value,
const GURL& page_url,
- const CompletionCallback& callback) = 0;
+ CompletionCallback callback) = 0;
virtual void ClearArea(int connection_id,
const GURL& page_url,
- const CompletionCallback& callback) = 0;
+ CompletionCallback callback) = 0;
protected:
friend class base::RefCounted<DOMStorageProxy>;
diff --git a/chromium/content/renderer/dom_storage/local_storage_area.cc b/chromium/content/renderer/dom_storage/local_storage_area.cc
index 30cc50039f0..af5fe91bcc8 100644
--- a/chromium/content/renderer/dom_storage/local_storage_area.cc
+++ b/chromium/content/renderer/dom_storage/local_storage_area.cc
@@ -6,7 +6,7 @@
#include "base/rand_util.h"
#include "base/strings/string_number_conversions.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
+#include "third_party/blink/public/platform/web_url.h"
using blink::WebString;
using blink::WebURL;
diff --git a/chromium/content/renderer/dom_storage/local_storage_area.h b/chromium/content/renderer/dom_storage/local_storage_area.h
index 3bc52a2a941..55967276a12 100644
--- a/chromium/content/renderer/dom_storage/local_storage_area.h
+++ b/chromium/content/renderer/dom_storage/local_storage_area.h
@@ -8,7 +8,7 @@
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "content/renderer/dom_storage/local_storage_cached_area.h"
-#include "third_party/WebKit/public/platform/WebStorageArea.h"
+#include "third_party/blink/public/platform/web_storage_area.h"
namespace content {
diff --git a/chromium/content/renderer/dom_storage/local_storage_cached_area.cc b/chromium/content/renderer/dom_storage/local_storage_cached_area.cc
index 22f1a9c9375..def0d2b96a2 100644
--- a/chromium/content/renderer/dom_storage/local_storage_cached_area.cc
+++ b/chromium/content/renderer/dom_storage/local_storage_cached_area.cc
@@ -16,10 +16,11 @@
#include "content/common/storage_partition_service.mojom.h"
#include "content/renderer/dom_storage/local_storage_area.h"
#include "content/renderer/dom_storage/local_storage_cached_areas.h"
+#include "content/renderer/dom_storage/webstoragenamespace_impl.h"
#include "content/renderer/render_thread_impl.h"
#include "mojo/public/cpp/bindings/strong_associated_binding.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
-#include "third_party/WebKit/public/web/WebStorageEventDispatcher.h"
+#include "third_party/blink/public/platform/web_url.h"
+#include "third_party/blink/public/web/web_storage_event_dispatcher.h"
namespace content {
@@ -32,20 +33,21 @@ enum class StorageFormat : uint8_t { UTF16 = 0, Latin1 = 1 };
class GetAllCallback : public mojom::LevelDBWrapperGetAllCallback {
public:
static mojom::LevelDBWrapperGetAllCallbackAssociatedPtrInfo CreateAndBind(
- const base::Callback<void(bool)>& callback) {
+ base::OnceCallback<void(bool)> callback) {
mojom::LevelDBWrapperGetAllCallbackAssociatedPtrInfo ptr_info;
auto request = mojo::MakeRequest(&ptr_info);
mojo::MakeStrongAssociatedBinding(
- base::WrapUnique(new GetAllCallback(callback)), std::move(request));
+ base::WrapUnique(new GetAllCallback(std::move(callback))),
+ std::move(request));
return ptr_info;
}
private:
- explicit GetAllCallback(const base::Callback<void(bool)>& callback)
- : m_callback(callback) {}
- void Complete(bool success) override { m_callback.Run(success); }
+ explicit GetAllCallback(base::OnceCallback<void(bool)> callback)
+ : m_callback(std::move(callback)) {}
+ void Complete(bool success) override { std::move(m_callback).Run(success); }
- base::Callback<void(bool)> m_callback;
+ base::OnceCallback<void(bool)> m_callback;
};
} // namespace
@@ -72,20 +74,22 @@ LocalStorageCachedArea::LocalStorageCachedArea(
const url::Origin& origin,
mojom::SessionStorageNamespace* session_namespace,
LocalStorageCachedAreas* cached_areas,
- blink::scheduler::RendererScheduler* renderer_scheduler)
+ blink::scheduler::WebMainThreadScheduler* main_thread_scheduler)
: namespace_id_(namespace_id),
origin_(origin),
binding_(this),
cached_areas_(cached_areas),
- renderer_scheduler_(renderer_scheduler),
+ main_thread_scheduler_(main_thread_scheduler),
weak_factory_(this) {
DCHECK(!namespace_id_.empty());
mojom::LevelDBWrapperAssociatedPtrInfo wrapper_ptr_info;
session_namespace->OpenArea(origin_, mojo::MakeRequest(&wrapper_ptr_info));
- leveldb_.Bind(std::move(wrapper_ptr_info));
+ leveldb_.Bind(std::move(wrapper_ptr_info),
+ main_thread_scheduler->IPCTaskRunner());
mojom::LevelDBObserverAssociatedPtrInfo ptr_info;
- binding_.Bind(mojo::MakeRequest(&ptr_info));
+ binding_.Bind(mojo::MakeRequest(&ptr_info),
+ main_thread_scheduler->IPCTaskRunner());
leveldb_->AddObserver(std::move(ptr_info));
}
@@ -93,19 +97,21 @@ LocalStorageCachedArea::LocalStorageCachedArea(
const url::Origin& origin,
mojom::StoragePartitionService* storage_partition_service,
LocalStorageCachedAreas* cached_areas,
- blink::scheduler::RendererScheduler* renderer_scheduler)
+ blink::scheduler::WebMainThreadScheduler* main_thread_scheduler)
: origin_(origin),
binding_(this),
cached_areas_(cached_areas),
- renderer_scheduler_(renderer_scheduler),
+ main_thread_scheduler_(main_thread_scheduler),
weak_factory_(this) {
DCHECK(namespace_id_.empty());
mojom::LevelDBWrapperPtrInfo wrapper_ptr_info;
storage_partition_service->OpenLocalStorage(
origin_, mojo::MakeRequest(&wrapper_ptr_info));
- leveldb_.Bind(std::move(wrapper_ptr_info));
+ leveldb_.Bind(std::move(wrapper_ptr_info),
+ main_thread_scheduler->IPCTaskRunner());
mojom::LevelDBObserverAssociatedPtrInfo ptr_info;
- binding_.Bind(mojo::MakeRequest(&ptr_info));
+ binding_.Bind(mojo::MakeRequest(&ptr_info),
+ main_thread_scheduler->IPCTaskRunner());
leveldb_->AddObserver(std::move(ptr_info));
}
@@ -156,8 +162,9 @@ bool LocalStorageCachedArea::SetItem(const base::string16& key,
String16ToUint8Vector(old_nullable_value.string(), is_session_storage);
blink::WebScopedVirtualTimePauser virtual_time_pauser =
- renderer_scheduler_->CreateWebScopedVirtualTimePauser();
- virtual_time_pauser.PauseVirtualTime(true);
+ main_thread_scheduler_->CreateWebScopedVirtualTimePauser(
+ "LocalStorageCachedArea");
+ virtual_time_pauser.PauseVirtualTime();
leveldb_->Put(String16ToUint8Vector(key, is_session_storage),
String16ToUint8Vector(value, is_session_storage),
optional_old_value, PackSource(page_url, storage_area_id),
@@ -188,8 +195,9 @@ void LocalStorageCachedArea::RemoveItem(const base::string16& key,
optional_old_value = String16ToUint8Vector(old_value, is_session_storage);
blink::WebScopedVirtualTimePauser virtual_time_pauser =
- renderer_scheduler_->CreateWebScopedVirtualTimePauser();
- virtual_time_pauser.PauseVirtualTime(true);
+ main_thread_scheduler_->CreateWebScopedVirtualTimePauser(
+ "LocalStorageCachedArea");
+ virtual_time_pauser.PauseVirtualTime();
leveldb_->Delete(String16ToUint8Vector(key, is_session_storage),
optional_old_value, PackSource(page_url, storage_area_id),
base::BindOnce(&LocalStorageCachedArea::OnRemoveItemComplete,
@@ -205,8 +213,9 @@ void LocalStorageCachedArea::Clear(const GURL& page_url,
ignore_all_mutations_ = true;
blink::WebScopedVirtualTimePauser virtual_time_pauser =
- renderer_scheduler_->CreateWebScopedVirtualTimePauser();
- virtual_time_pauser.PauseVirtualTime(true);
+ main_thread_scheduler_->CreateWebScopedVirtualTimePauser(
+ "LocalStorageCachedArea");
+ virtual_time_pauser.PauseVirtualTime();
leveldb_->DeleteAll(PackSource(page_url, storage_area_id),
base::BindOnce(&LocalStorageCachedArea::OnClearComplete,
weak_factory_.GetWeakPtr(),
@@ -341,11 +350,21 @@ void LocalStorageCachedArea::KeyDeleted(const std::vector<uint8_t>& key,
map_->RemoveItem(key_string, nullptr);
}
- blink::WebStorageEventDispatcher::DispatchLocalStorageEvent(
- blink::WebString::FromUTF16(key_string),
- blink::WebString::FromUTF16(
- Uint8VectorToString16(old_value, IsSessionStorage())),
- blink::WebString(), origin_.GetURL(), page_url, originating_area);
+ if (IsSessionStorage()) {
+ WebStorageNamespaceImpl session_namespace_for_event_dispatch(namespace_id_);
+ blink::WebStorageEventDispatcher::DispatchSessionStorageEvent(
+ blink::WebString::FromUTF16(key_string),
+ blink::WebString::FromUTF16(
+ Uint8VectorToString16(old_value, IsSessionStorage())),
+ blink::WebString(), origin_.GetURL(), page_url,
+ session_namespace_for_event_dispatch, originating_area);
+ } else {
+ blink::WebStorageEventDispatcher::DispatchLocalStorageEvent(
+ blink::WebString::FromUTF16(key_string),
+ blink::WebString::FromUTF16(
+ Uint8VectorToString16(old_value, IsSessionStorage())),
+ blink::WebString(), origin_.GetURL(), page_url, originating_area);
+ }
}
void LocalStorageCachedArea::AllDeleted(const std::string& source) {
@@ -372,9 +391,18 @@ void LocalStorageCachedArea::AllDeleted(const std::string& source) {
}
}
- blink::WebStorageEventDispatcher::DispatchLocalStorageEvent(
- blink::WebString(), blink::WebString(), blink::WebString(),
- origin_.GetURL(), page_url, originating_area);
+ if (IsSessionStorage()) {
+ WebStorageNamespaceImpl session_namespace_for_event_dispatch(namespace_id_);
+ blink::WebStorageEventDispatcher::DispatchSessionStorageEvent(
+ blink::WebString(), blink::WebString(), blink::WebString(),
+ origin_.GetURL(), page_url, session_namespace_for_event_dispatch,
+ originating_area);
+
+ } else {
+ blink::WebStorageEventDispatcher::DispatchLocalStorageEvent(
+ blink::WebString(), blink::WebString(), blink::WebString(),
+ origin_.GetURL(), page_url, originating_area);
+ }
}
void LocalStorageCachedArea::ShouldSendOldValueOnMutations(bool value) {
@@ -412,11 +440,21 @@ void LocalStorageCachedArea::KeyAddedOrChanged(
}
}
- blink::WebStorageEventDispatcher::DispatchLocalStorageEvent(
- blink::WebString::FromUTF16(key_string),
- blink::WebString::FromUTF16(old_value),
- blink::WebString::FromUTF16(new_value_string), origin_.GetURL(), page_url,
- originating_area);
+ if (IsSessionStorage()) {
+ WebStorageNamespaceImpl session_namespace_for_event_dispatch(namespace_id_);
+ blink::WebStorageEventDispatcher::DispatchSessionStorageEvent(
+ blink::WebString::FromUTF16(key_string),
+ blink::WebString::FromUTF16(old_value),
+ blink::WebString::FromUTF16(new_value_string), origin_.GetURL(),
+ page_url, session_namespace_for_event_dispatch, originating_area);
+
+ } else {
+ blink::WebStorageEventDispatcher::DispatchLocalStorageEvent(
+ blink::WebString::FromUTF16(key_string),
+ blink::WebString::FromUTF16(old_value),
+ blink::WebString::FromUTF16(new_value_string), origin_.GetURL(),
+ page_url, originating_area);
+ }
}
void LocalStorageCachedArea::EnsureLoaded() {
@@ -428,8 +466,8 @@ void LocalStorageCachedArea::EnsureLoaded() {
leveldb::mojom::DatabaseError status = leveldb::mojom::DatabaseError::OK;
std::vector<content::mojom::KeyValuePtr> data;
leveldb_->GetAll(GetAllCallback::CreateAndBind(
- base::Bind(&LocalStorageCachedArea::OnGetAllComplete,
- weak_factory_.GetWeakPtr())),
+ base::BindOnce(&LocalStorageCachedArea::OnGetAllComplete,
+ weak_factory_.GetWeakPtr())),
&status, &data);
DOMStorageValuesMap values;
diff --git a/chromium/content/renderer/dom_storage/local_storage_cached_area.h b/chromium/content/renderer/dom_storage/local_storage_cached_area.h
index fb9c0e05b2d..315f8972b46 100644
--- a/chromium/content/renderer/dom_storage/local_storage_cached_area.h
+++ b/chromium/content/renderer/dom_storage/local_storage_cached_area.h
@@ -15,13 +15,13 @@
#include "content/common/leveldb_wrapper.mojom.h"
#include "content/common/possibly_associated_interface_ptr.h"
#include "mojo/public/cpp/bindings/associated_binding.h"
-#include "third_party/WebKit/public/platform/WebScopedVirtualTimePauser.h"
+#include "third_party/blink/public/platform/web_scoped_virtual_time_pauser.h"
#include "url/gurl.h"
#include "url/origin.h"
namespace blink {
namespace scheduler {
-class RendererScheduler;
+class WebMainThreadScheduler;
}
} // namespace blink
@@ -52,12 +52,12 @@ class CONTENT_EXPORT LocalStorageCachedArea
const url::Origin& origin,
mojom::SessionStorageNamespace* session_namespace,
LocalStorageCachedAreas* cached_areas,
- blink::scheduler::RendererScheduler* renderer_schedule);
+ blink::scheduler::WebMainThreadScheduler* main_thread_scheduler);
LocalStorageCachedArea(
const url::Origin& origin,
mojom::StoragePartitionService* storage_partition_service,
LocalStorageCachedAreas* cached_areas,
- blink::scheduler::RendererScheduler* renderer_schedule);
+ blink::scheduler::WebMainThreadScheduler* main_thread_scheduler);
// These correspond to blink::WebStorageArea.
unsigned GetLength();
@@ -144,7 +144,10 @@ class CONTENT_EXPORT LocalStorageCachedArea
mojo::AssociatedBinding<mojom::LevelDBObserver> binding_;
LocalStorageCachedAreas* cached_areas_;
std::map<std::string, LocalStorageArea*> areas_;
- blink::scheduler::RendererScheduler* renderer_scheduler_; // NOT OWNED
+
+ // Not owned.
+ blink::scheduler::WebMainThreadScheduler* main_thread_scheduler_;
+
base::WeakPtrFactory<LocalStorageCachedArea> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(LocalStorageCachedArea);
diff --git a/chromium/content/renderer/dom_storage/local_storage_cached_area_unittest.cc b/chromium/content/renderer/dom_storage/local_storage_cached_area_unittest.cc
index ae6406a6d32..98ca9ec2d85 100644
--- a/chromium/content/renderer/dom_storage/local_storage_cached_area_unittest.cc
+++ b/chromium/content/renderer/dom_storage/local_storage_cached_area_unittest.cc
@@ -15,7 +15,7 @@
#include "content/renderer/dom_storage/local_storage_cached_areas.h"
#include "content/renderer/dom_storage/mock_leveldb_wrapper.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/scheduler/test/fake_renderer_scheduler.h"
+#include "third_party/blink/public/platform/scheduler/test/fake_renderer_scheduler.h"
namespace content {
@@ -75,7 +75,7 @@ class LocalStorageCachedAreaTest : public testing::Test {
protected:
TestBrowserThreadBundle test_browser_thread_bundle_;
MockLevelDBWrapper mock_leveldb_wrapper_;
- std::unique_ptr<blink::scheduler::RendererScheduler> renderer_scheduler_;
+ std::unique_ptr<blink::scheduler::WebMainThreadScheduler> renderer_scheduler_;
LocalStorageCachedAreas cached_areas_;
};
diff --git a/chromium/content/renderer/dom_storage/local_storage_cached_areas.cc b/chromium/content/renderer/dom_storage/local_storage_cached_areas.cc
index 2e20d2c0c96..b8aeaab96b8 100644
--- a/chromium/content/renderer/dom_storage/local_storage_cached_areas.cc
+++ b/chromium/content/renderer/dom_storage/local_storage_cached_areas.cc
@@ -22,25 +22,26 @@ constexpr const char kLocalStorageNamespaceId[] = "";
LocalStorageCachedAreas::LocalStorageCachedAreas(
mojom::StoragePartitionService* storage_partition_service,
- blink::scheduler::RendererScheduler* renderer_scheduler)
+ blink::scheduler::WebMainThreadScheduler* main_thread_scheduler)
: storage_partition_service_(storage_partition_service),
total_cache_limit_(base::SysInfo::IsLowEndDevice()
? kTotalCacheLimitInBytesLowEnd
: kTotalCacheLimitInBytes),
- renderer_scheduler_(renderer_scheduler) {}
+ main_thread_scheduler_(main_thread_scheduler) {}
LocalStorageCachedAreas::~LocalStorageCachedAreas() {}
scoped_refptr<LocalStorageCachedArea> LocalStorageCachedAreas::GetCachedArea(
const url::Origin& origin) {
- return GetCachedArea(kLocalStorageNamespaceId, origin, renderer_scheduler_);
+ return GetCachedArea(kLocalStorageNamespaceId, origin,
+ main_thread_scheduler_);
}
scoped_refptr<LocalStorageCachedArea>
LocalStorageCachedAreas::GetSessionStorageArea(const std::string& namespace_id,
const url::Origin& origin) {
DCHECK_NE(namespace_id, kLocalStorageNamespaceId);
- return GetCachedArea(namespace_id, origin, renderer_scheduler_);
+ return GetCachedArea(namespace_id, origin, main_thread_scheduler_);
}
void LocalStorageCachedAreas::CloneNamespace(
@@ -80,14 +81,14 @@ void LocalStorageCachedAreas::ClearAreasIfNeeded() {
scoped_refptr<LocalStorageCachedArea> LocalStorageCachedAreas::GetCachedArea(
const std::string& namespace_id,
const url::Origin& origin,
- blink::scheduler::RendererScheduler* scheduler) {
+ blink::scheduler::WebMainThreadScheduler* scheduler) {
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
enum class CacheMetrics {
kMiss = 0, // Area not in cache.
kHit = 1, // Area with refcount = 0 loaded from cache.
kUnused = 2, // Cache was not used. Area had refcount > 0.
- kMaxValue
+ kMaxValue = kUnused,
};
auto namespace_it = cached_namespaces_.find(namespace_id);
@@ -110,13 +111,10 @@ scoped_refptr<LocalStorageCachedArea> LocalStorageCachedAreas::GetCachedArea(
result = cache_it->second;
}
}
- if (namespace_id == kLocalStorageNamespaceId) {
- UMA_HISTOGRAM_ENUMERATION("LocalStorage.RendererAreaCacheHit", metric,
- CacheMetrics::kMaxValue);
- } else {
- LOCAL_HISTOGRAM_ENUMERATION("SessionStorage.RendererAreaCacheHit", metric,
- CacheMetrics::kMaxValue);
- }
+ if (namespace_id == kLocalStorageNamespaceId)
+ UMA_HISTOGRAM_ENUMERATION("LocalStorage.RendererAreaCacheHit", metric);
+ else
+ LOCAL_HISTOGRAM_ENUMERATION("SessionStorage.RendererAreaCacheHit", metric);
if (!result) {
ClearAreasIfNeeded();
diff --git a/chromium/content/renderer/dom_storage/local_storage_cached_areas.h b/chromium/content/renderer/dom_storage/local_storage_cached_areas.h
index 3ad7bcd35bf..53ad4de71ce 100644
--- a/chromium/content/renderer/dom_storage/local_storage_cached_areas.h
+++ b/chromium/content/renderer/dom_storage/local_storage_cached_areas.h
@@ -17,7 +17,7 @@
namespace blink {
namespace scheduler {
-class RendererScheduler;
+class WebMainThreadScheduler;
}
} // namespace blink
@@ -37,7 +37,7 @@ class CONTENT_EXPORT LocalStorageCachedAreas {
public:
LocalStorageCachedAreas(
mojom::StoragePartitionService* storage_partition_service,
- blink::scheduler::RendererScheduler* renderer_schedule);
+ blink::scheduler::WebMainThreadScheduler* main_thread_scheduler);
~LocalStorageCachedAreas();
// Returns, creating if necessary, a cached storage area for the given origin.
@@ -61,7 +61,7 @@ class CONTENT_EXPORT LocalStorageCachedAreas {
scoped_refptr<LocalStorageCachedArea> GetCachedArea(
const std::string& namespace_id,
const url::Origin& origin,
- blink::scheduler::RendererScheduler* scheduler);
+ blink::scheduler::WebMainThreadScheduler* scheduler);
mojom::StoragePartitionService* const storage_partition_service_;
@@ -86,7 +86,8 @@ class CONTENT_EXPORT LocalStorageCachedAreas {
base::flat_map<std::string, DOMStorageNamespace> cached_namespaces_;
size_t total_cache_limit_;
- blink::scheduler::RendererScheduler* renderer_scheduler_; // NOT OWNED
+ // Not owned.
+ blink::scheduler::WebMainThreadScheduler* main_thread_scheduler_;
DISALLOW_COPY_AND_ASSIGN(LocalStorageCachedAreas);
};
diff --git a/chromium/content/renderer/dom_storage/local_storage_cached_areas_unittest.cc b/chromium/content/renderer/dom_storage/local_storage_cached_areas_unittest.cc
index 05c58668fbd..b07311bb138 100644
--- a/chromium/content/renderer/dom_storage/local_storage_cached_areas_unittest.cc
+++ b/chromium/content/renderer/dom_storage/local_storage_cached_areas_unittest.cc
@@ -8,7 +8,7 @@
#include "base/test/scoped_task_environment.h"
#include "content/renderer/dom_storage/local_storage_cached_area.h"
#include "content/renderer/dom_storage/mock_leveldb_wrapper.h"
-#include "third_party/WebKit/public/platform/scheduler/test/fake_renderer_scheduler.h"
+#include "third_party/blink/public/platform/scheduler/test/fake_renderer_scheduler.h"
namespace content {
diff --git a/chromium/content/renderer/dom_storage/local_storage_namespace.cc b/chromium/content/renderer/dom_storage/local_storage_namespace.cc
index 778b1a926cf..d493cc4a3f1 100644
--- a/chromium/content/renderer/dom_storage/local_storage_namespace.cc
+++ b/chromium/content/renderer/dom_storage/local_storage_namespace.cc
@@ -6,8 +6,8 @@
#include "content/renderer/dom_storage/local_storage_area.h"
#include "content/renderer/dom_storage/local_storage_cached_areas.h"
-#include "third_party/WebKit/public/platform/URLConversion.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
+#include "third_party/blink/public/platform/url_conversion.h"
+#include "third_party/blink/public/platform/web_url.h"
#include "url/gurl.h"
#include "url/origin.h"
diff --git a/chromium/content/renderer/dom_storage/local_storage_namespace.h b/chromium/content/renderer/dom_storage/local_storage_namespace.h
index 43b97e88c5c..65fc4f17956 100644
--- a/chromium/content/renderer/dom_storage/local_storage_namespace.h
+++ b/chromium/content/renderer/dom_storage/local_storage_namespace.h
@@ -6,8 +6,8 @@
#define CONTENT_RENDERER_DOM_STORAGE_LOCAL_STORAGE_NAMESPACE_H_
#include "base/macros.h"
-#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
-#include "third_party/WebKit/public/platform/WebStorageNamespace.h"
+#include "third_party/blink/public/platform/web_security_origin.h"
+#include "third_party/blink/public/platform/web_storage_namespace.h"
namespace content {
class LocalStorageCachedAreas;
diff --git a/chromium/content/renderer/dom_storage/session_web_storage_namespace_impl.cc b/chromium/content/renderer/dom_storage/session_web_storage_namespace_impl.cc
index 16572289491..8745849d9b3 100644
--- a/chromium/content/renderer/dom_storage/session_web_storage_namespace_impl.cc
+++ b/chromium/content/renderer/dom_storage/session_web_storage_namespace_impl.cc
@@ -6,8 +6,8 @@
#include "content/renderer/dom_storage/local_storage_area.h"
#include "content/renderer/dom_storage/local_storage_cached_areas.h"
-#include "third_party/WebKit/public/platform/URLConversion.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
+#include "third_party/blink/public/platform/url_conversion.h"
+#include "third_party/blink/public/platform/web_url.h"
#include "url/gurl.h"
#include "url/origin.h"
diff --git a/chromium/content/renderer/dom_storage/session_web_storage_namespace_impl.h b/chromium/content/renderer/dom_storage/session_web_storage_namespace_impl.h
index 5f1ee80e49d..d69b8f3e490 100644
--- a/chromium/content/renderer/dom_storage/session_web_storage_namespace_impl.h
+++ b/chromium/content/renderer/dom_storage/session_web_storage_namespace_impl.h
@@ -6,8 +6,8 @@
#define CONTENT_RENDERER_DOM_STORAGE_SESSION_WEB_STORAGE_NAMESPACE_IMPL_H_
#include "base/macros.h"
-#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
-#include "third_party/WebKit/public/platform/WebStorageNamespace.h"
+#include "third_party/blink/public/platform/web_security_origin.h"
+#include "third_party/blink/public/platform/web_storage_namespace.h"
namespace content {
class LocalStorageCachedAreas;
diff --git a/chromium/content/renderer/dom_storage/webstoragearea_impl.cc b/chromium/content/renderer/dom_storage/webstoragearea_impl.cc
index 49bda101f46..e47617f860d 100644
--- a/chromium/content/renderer/dom_storage/webstoragearea_impl.cc
+++ b/chromium/content/renderer/dom_storage/webstoragearea_impl.cc
@@ -12,7 +12,7 @@
#include "content/renderer/dom_storage/dom_storage_cached_area.h"
#include "content/renderer/dom_storage/dom_storage_dispatcher.h"
#include "content/renderer/render_thread_impl.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
+#include "third_party/blink/public/platform/web_url.h"
using blink::WebString;
using blink::WebURL;
diff --git a/chromium/content/renderer/dom_storage/webstoragearea_impl.h b/chromium/content/renderer/dom_storage/webstoragearea_impl.h
index 1d1b4733af2..ca47ab4e485 100644
--- a/chromium/content/renderer/dom_storage/webstoragearea_impl.h
+++ b/chromium/content/renderer/dom_storage/webstoragearea_impl.h
@@ -9,8 +9,8 @@
#include <stdint.h>
#include "base/memory/ref_counted.h"
-#include "third_party/WebKit/public/platform/WebStorageArea.h"
-#include "third_party/WebKit/public/platform/WebString.h"
+#include "third_party/blink/public/platform/web_storage_area.h"
+#include "third_party/blink/public/platform/web_string.h"
class GURL;
diff --git a/chromium/content/renderer/dom_storage/webstoragenamespace_impl.cc b/chromium/content/renderer/dom_storage/webstoragenamespace_impl.cc
index 6b9006e54a8..377d7961a16 100644
--- a/chromium/content/renderer/dom_storage/webstoragenamespace_impl.cc
+++ b/chromium/content/renderer/dom_storage/webstoragenamespace_impl.cc
@@ -7,8 +7,8 @@
#include "base/logging.h"
#include "content/common/dom_storage/dom_storage_types.h"
#include "content/renderer/dom_storage/webstoragearea_impl.h"
-#include "third_party/WebKit/public/platform/URLConversion.h"
-#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
+#include "third_party/blink/public/platform/url_conversion.h"
+#include "third_party/blink/public/platform/web_security_origin.h"
#include "url/gurl.h"
#include "url/origin.h"
diff --git a/chromium/content/renderer/dom_storage/webstoragenamespace_impl.h b/chromium/content/renderer/dom_storage/webstoragenamespace_impl.h
index f7015714294..b4b522b798c 100644
--- a/chromium/content/renderer/dom_storage/webstoragenamespace_impl.h
+++ b/chromium/content/renderer/dom_storage/webstoragenamespace_impl.h
@@ -8,7 +8,7 @@
#include <stdint.h>
#include <string>
-#include "third_party/WebKit/public/platform/WebStorageNamespace.h"
+#include "third_party/blink/public/platform/web_storage_namespace.h"
namespace content {
diff --git a/chromium/content/renderer/drop_data_builder.cc b/chromium/content/renderer/drop_data_builder.cc
index f0b7fecfdfa..2ecac5cf788 100644
--- a/chromium/content/renderer/drop_data_builder.cc
+++ b/chromium/content/renderer/drop_data_builder.cc
@@ -8,11 +8,11 @@
#include "base/strings/string_util.h"
#include "content/public/common/drop_data.h"
-#include "third_party/WebKit/public/platform/FilePathConversion.h"
-#include "third_party/WebKit/public/platform/URLConversion.h"
-#include "third_party/WebKit/public/platform/WebDragData.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebVector.h"
+#include "third_party/blink/public/platform/file_path_conversion.h"
+#include "third_party/blink/public/platform/url_conversion.h"
+#include "third_party/blink/public/platform/web_drag_data.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_vector.h"
#include "ui/base/clipboard/clipboard.h"
using blink::WebDragData;
diff --git a/chromium/content/renderer/effective_connection_type_helper.cc b/chromium/content/renderer/effective_connection_type_helper.cc
index 23086c68bdd..50442822b57 100644
--- a/chromium/content/renderer/effective_connection_type_helper.cc
+++ b/chromium/content/renderer/effective_connection_type_helper.cc
@@ -4,6 +4,8 @@
#include "content/renderer/effective_connection_type_helper.h"
+#include "third_party/blink/public/common/client_hints/client_hints.h"
+
namespace content {
#define STATIC_ASSERT_ENUM(a, b) \
@@ -25,6 +27,17 @@ STATIC_ASSERT_ENUM(net::EFFECTIVE_CONNECTION_TYPE_4G,
#undef STATIC_ASSERT_ENUM
+static_assert(net::EFFECTIVE_CONNECTION_TYPE_4G + 1 ==
+ net::EFFECTIVE_CONNECTION_TYPE_LAST,
+ "When adding a new effective connection type, "
+ "WebEffectiveConnectionType.h should be updated too");
+
+static_assert(static_cast<int>(blink::WebEffectiveConnectionType::kType4G) +
+ 1 ==
+ net::EFFECTIVE_CONNECTION_TYPE_LAST,
+ "When adding a new effective connection type, "
+ "WebEffectiveConnectionType.h should be updated too");
+
blink::WebEffectiveConnectionType
EffectiveConnectionTypeToWebEffectiveConnectionType(
net::EffectiveConnectionType net_type) {
diff --git a/chromium/content/renderer/effective_connection_type_helper.h b/chromium/content/renderer/effective_connection_type_helper.h
index caf5b7d50a3..2b156ed242a 100644
--- a/chromium/content/renderer/effective_connection_type_helper.h
+++ b/chromium/content/renderer/effective_connection_type_helper.h
@@ -6,7 +6,7 @@
#define CONTENT_RENDERER_EFFECTIVE_CONNECTION_TYPE_HELPER_H_
#include "net/nqe/effective_connection_type.h"
-#include "third_party/WebKit/public/platform/WebEffectiveConnectionType.h"
+#include "third_party/blink/public/platform/web_effective_connection_type.h"
namespace content {
diff --git a/chromium/content/renderer/external_popup_menu.cc b/chromium/content/renderer/external_popup_menu.cc
index a4964ae252a..c61530a96d4 100644
--- a/chromium/content/renderer/external_popup_menu.cc
+++ b/chromium/content/renderer/external_popup_menu.cc
@@ -10,8 +10,8 @@
#include "content/common/frame_messages.h"
#include "content/renderer/menu_item_builder.h"
#include "content/renderer/render_frame_impl.h"
-#include "third_party/WebKit/public/platform/WebRect.h"
-#include "third_party/WebKit/public/web/WebExternalPopupMenuClient.h"
+#include "third_party/blink/public/platform/web_rect.h"
+#include "third_party/blink/public/web/web_external_popup_menu_client.h"
namespace content {
diff --git a/chromium/content/renderer/external_popup_menu.h b/chromium/content/renderer/external_popup_menu.h
index 79b97a10683..8b25066507c 100644
--- a/chromium/content/renderer/external_popup_menu.h
+++ b/chromium/content/renderer/external_popup_menu.h
@@ -9,9 +9,9 @@
#include "base/macros.h"
#include "build/build_config.h"
-#include "content/common/features.h"
-#include "third_party/WebKit/public/web/WebExternalPopupMenu.h"
-#include "third_party/WebKit/public/web/WebPopupMenuInfo.h"
+#include "content/common/buildflags.h"
+#include "third_party/blink/public/web/web_external_popup_menu.h"
+#include "third_party/blink/public/web/web_popup_menu_info.h"
#include "ui/gfx/geometry/point_f.h"
namespace blink {
diff --git a/chromium/content/renderer/external_popup_menu_browsertest.cc b/chromium/content/renderer/external_popup_menu_browsertest.cc
index 942a6a82505..d3cff681551 100644
--- a/chromium/content/renderer/external_popup_menu_browsertest.cc
+++ b/chromium/content/renderer/external_popup_menu_browsertest.cc
@@ -11,8 +11,8 @@
#include "content/renderer/render_frame_impl.h"
#include "content/renderer/render_view_impl.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebSize.h"
-#include "third_party/WebKit/public/web/WebView.h"
+#include "third_party/blink/public/platform/web_size.h"
+#include "third_party/blink/public/web/web_view.h"
// Tests for the external select popup menu (Mac specific).
diff --git a/chromium/content/renderer/fetchers/associated_resource_fetcher_impl.cc b/chromium/content/renderer/fetchers/associated_resource_fetcher_impl.cc
index c21fa04915e..6e43922b7ac 100644
--- a/chromium/content/renderer/fetchers/associated_resource_fetcher_impl.cc
+++ b/chromium/content/renderer/fetchers/associated_resource_fetcher_impl.cc
@@ -10,19 +10,19 @@
#include "base/macros.h"
#include "base/strings/string_util.h"
#include "base/time/time.h"
-#include "third_party/WebKit/public/platform/Platform.h"
-#include "third_party/WebKit/public/platform/WebHTTPBody.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
-#include "third_party/WebKit/public/platform/WebURLError.h"
-#include "third_party/WebKit/public/platform/WebURLRequest.h"
-#include "third_party/WebKit/public/platform/WebURLResponse.h"
-#include "third_party/WebKit/public/web/WebAssociatedURLLoader.h"
-#include "third_party/WebKit/public/web/WebAssociatedURLLoaderClient.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebKit.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebSecurityPolicy.h"
+#include "third_party/blink/public/platform/platform.h"
+#include "third_party/blink/public/platform/web_http_body.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_url.h"
+#include "third_party/blink/public/platform/web_url_error.h"
+#include "third_party/blink/public/platform/web_url_request.h"
+#include "third_party/blink/public/platform/web_url_response.h"
+#include "third_party/blink/public/web/blink.h"
+#include "third_party/blink/public/web/web_associated_url_loader.h"
+#include "third_party/blink/public/web/web_associated_url_loader_client.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_security_policy.h"
namespace content {
@@ -63,8 +63,9 @@ class AssociatedResourceFetcherImpl::ClientImpl
// Take a reference to the callback as running the callback may lead to our
// destruction.
Callback callback = callback_;
- callback.Run(status_ == LOAD_FAILED ? blink::WebURLResponse() : response_,
- status_ == LOAD_FAILED ? std::string() : data_);
+ std::move(callback).Run(
+ status_ == LOAD_FAILED ? blink::WebURLResponse() : response_,
+ status_ == LOAD_FAILED ? std::string() : data_);
}
// WebAssociatedURLLoaderClient methods:
diff --git a/chromium/content/renderer/fetchers/associated_resource_fetcher_impl.h b/chromium/content/renderer/fetchers/associated_resource_fetcher_impl.h
index d4af8f3303f..260573928dc 100644
--- a/chromium/content/renderer/fetchers/associated_resource_fetcher_impl.h
+++ b/chromium/content/renderer/fetchers/associated_resource_fetcher_impl.h
@@ -13,8 +13,8 @@
#include "base/macros.h"
#include "base/timer/timer.h"
#include "content/public/renderer/associated_resource_fetcher.h"
-#include "third_party/WebKit/public/platform/WebURLRequest.h"
-#include "third_party/WebKit/public/web/WebAssociatedURLLoaderOptions.h"
+#include "third_party/blink/public/platform/web_url_request.h"
+#include "third_party/blink/public/web/web_associated_url_loader_options.h"
class GURL;
diff --git a/chromium/content/renderer/fetchers/manifest_fetcher.cc b/chromium/content/renderer/fetchers/manifest_fetcher.cc
index f17095d674d..855f420d36a 100644
--- a/chromium/content/renderer/fetchers/manifest_fetcher.cc
+++ b/chromium/content/renderer/fetchers/manifest_fetcher.cc
@@ -8,9 +8,9 @@
#include "base/logging.h"
#include "content/public/renderer/associated_resource_fetcher.h"
#include "services/network/public/mojom/request_context_frame_type.mojom.h"
-#include "third_party/WebKit/public/platform/WebURLRequest.h"
-#include "third_party/WebKit/public/web/WebAssociatedURLLoaderOptions.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "third_party/blink/public/platform/web_url_request.h"
+#include "third_party/blink/public/web/web_associated_url_loader_options.h"
+#include "third_party/blink/public/web/web_local_frame.h"
namespace content {
@@ -54,7 +54,7 @@ void ManifestFetcher::OnLoadComplete(const blink::WebURLResponse& response,
completed_ = true;
Callback callback = callback_;
- callback.Run(response, data);
+ std::move(callback).Run(response, data);
}
} // namespace content
diff --git a/chromium/content/renderer/fetchers/manifest_fetcher.h b/chromium/content/renderer/fetchers/manifest_fetcher.h
index e8313096d02..ef48c184dc2 100644
--- a/chromium/content/renderer/fetchers/manifest_fetcher.h
+++ b/chromium/content/renderer/fetchers/manifest_fetcher.h
@@ -11,7 +11,7 @@
#include "base/callback.h"
#include "base/macros.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebURLResponse.h"
+#include "third_party/blink/public/platform/web_url_response.h"
class GURL;
diff --git a/chromium/content/renderer/fetchers/multi_resolution_image_resource_fetcher.cc b/chromium/content/renderer/fetchers/multi_resolution_image_resource_fetcher.cc
index a9232a77937..81e681eb2e0 100644
--- a/chromium/content/renderer/fetchers/multi_resolution_image_resource_fetcher.cc
+++ b/chromium/content/renderer/fetchers/multi_resolution_image_resource_fetcher.cc
@@ -9,9 +9,9 @@
#include "content/child/image_decoder.h"
#include "content/public/renderer/associated_resource_fetcher.h"
#include "services/network/public/mojom/request_context_frame_type.mojom.h"
-#include "third_party/WebKit/public/platform/WebURLResponse.h"
-#include "third_party/WebKit/public/web/WebAssociatedURLLoaderOptions.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "third_party/blink/public/platform/web_url_response.h"
+#include "third_party/blink/public/web/web_associated_url_loader_options.h"
+#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/geometry/size.h"
@@ -28,8 +28,8 @@ MultiResolutionImageResourceFetcher::MultiResolutionImageResourceFetcher(
int id,
WebURLRequest::RequestContext request_context,
blink::mojom::FetchCacheMode cache_mode,
- const Callback& callback)
- : callback_(callback),
+ Callback callback)
+ : callback_(std::move(callback)),
id_(id),
http_status_code_(0),
image_url_(image_url) {
@@ -73,17 +73,15 @@ void MultiResolutionImageResourceFetcher::OnURLFetchComplete(
// If we get here, it means no image from server or couldn't decode the
// response as an image. The delegate will see an empty vector.
- // Take a reference to the callback as running the callback may lead to our
- // destruction.
- Callback callback = callback_;
- callback.Run(this, bitmaps);
+ // Take local ownership of the callback as running the callback may lead to
+ // our destruction.
+ base::ResetAndReturn(&callback_).Run(this, bitmaps);
}
void MultiResolutionImageResourceFetcher::OnRenderFrameDestruct() {
- // Take a reference to the callback as running the callback may lead to our
- // destruction.
- Callback callback = callback_;
- callback.Run(this, std::vector<SkBitmap>());
+ // Take local ownership of the callback as running the callback may lead to
+ // our destruction.
+ base::ResetAndReturn(&callback_).Run(this, std::vector<SkBitmap>());
}
} // namespace content
diff --git a/chromium/content/renderer/fetchers/multi_resolution_image_resource_fetcher.h b/chromium/content/renderer/fetchers/multi_resolution_image_resource_fetcher.h
index e748c3ffcf4..06117ee0339 100644
--- a/chromium/content/renderer/fetchers/multi_resolution_image_resource_fetcher.h
+++ b/chromium/content/renderer/fetchers/multi_resolution_image_resource_fetcher.h
@@ -11,8 +11,8 @@
#include "base/callback.h"
#include "base/macros.h"
-#include "third_party/WebKit/public/platform/WebURLRequest.h"
-#include "third_party/WebKit/public/platform/modules/fetch/fetch_api_request.mojom-shared.h"
+#include "third_party/blink/public/platform/modules/fetch/fetch_api_request.mojom-shared.h"
+#include "third_party/blink/public/platform/web_url_request.h"
#include "url/gurl.h"
class SkBitmap;
@@ -30,8 +30,8 @@ class AssociatedResourceFetcher;
// an image. Useful for favicons.
class MultiResolutionImageResourceFetcher {
public:
- typedef base::Callback<void(MultiResolutionImageResourceFetcher*,
- const std::vector<SkBitmap>&)> Callback;
+ using Callback = base::OnceCallback<void(MultiResolutionImageResourceFetcher*,
+ const std::vector<SkBitmap>&)>;
MultiResolutionImageResourceFetcher(
const GURL& image_url,
@@ -39,7 +39,7 @@ class MultiResolutionImageResourceFetcher {
int id,
blink::WebURLRequest::RequestContext request_context,
blink::mojom::FetchCacheMode cache_mode,
- const Callback& callback);
+ Callback callback);
virtual ~MultiResolutionImageResourceFetcher();
diff --git a/chromium/content/renderer/fetchers/resource_fetcher_browsertest.cc b/chromium/content/renderer/fetchers/resource_fetcher_browsertest.cc
index 52c000cc303..33f4cb394e2 100644
--- a/chromium/content/renderer/fetchers/resource_fetcher_browsertest.cc
+++ b/chromium/content/renderer/fetchers/resource_fetcher_browsertest.cc
@@ -24,9 +24,10 @@
#include "content/shell/browser/shell.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
-#include "third_party/WebKit/public/platform/WebURLResponse.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebView.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
+#include "third_party/blink/public/platform/web_url_response.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_view.h"
using blink::WebURLRequest;
using blink::WebURLResponse;
diff --git a/chromium/content/renderer/fetchers/resource_fetcher_impl.cc b/chromium/content/renderer/fetchers/resource_fetcher_impl.cc
index 2beed5fe795..41046213d13 100644
--- a/chromium/content/renderer/fetchers/resource_fetcher_impl.cc
+++ b/chromium/content/renderer/fetchers/resource_fetcher_impl.cc
@@ -8,7 +8,6 @@
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "content/public/common/referrer.h"
#include "content/public/renderer/render_frame.h"
#include "content/renderer/loader/resource_dispatcher.h"
@@ -18,13 +17,14 @@
#include "net/http/http_request_headers.h"
#include "net/url_request/url_request_context.h"
#include "services/network/public/cpp/resource_request_body.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
-#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
-#include "third_party/WebKit/public/platform/WebURLResponse.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "third_party/blink/public/platform/web_security_origin.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_url.h"
+#include "third_party/blink/public/platform/web_url_response.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_local_frame.h"
namespace {
@@ -66,7 +66,7 @@ class ResourceFetcherImpl::ClientImpl : public network::mojom::URLLoaderClient {
}
void Start(const network::ResourceRequest& request,
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory,
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
const net::NetworkTrafficAnnotationTag& annotation_tag,
scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
status_ = Status::kStarted;
@@ -175,7 +175,6 @@ class ResourceFetcherImpl::ClientImpl : public network::mojom::URLLoaderClient {
// network::mojom::URLLoaderClient overrides:
void OnReceiveResponse(
const network::ResourceResponseHead& response_head,
- const base::Optional<net::SSLInfo>& ssl_info,
network::mojom::DownloadedTempFilePtr downloaded_file) override {
DCHECK_EQ(Status::kStarted, status_);
// Existing callers need URL and HTTP status code. URL is already set in
@@ -288,7 +287,7 @@ void ResourceFetcherImpl::SetHeader(const std::string& header,
void ResourceFetcherImpl::Start(
blink::WebLocalFrame* frame,
blink::WebURLRequest::RequestContext request_context,
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory,
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
const net::NetworkTrafficAnnotationTag& annotation_tag,
Callback callback,
size_t maximum_download_size) {
@@ -304,7 +303,7 @@ void ResourceFetcherImpl::Start(
<< "GETs can't have bodies.";
}
- request_.request_context = request_context;
+ request_.fetch_request_context_type = request_context;
request_.site_for_cookies = frame->GetDocument().SiteForCookies();
if (!frame->GetDocument().GetSecurityOrigin().IsNull()) {
request_.request_initiator =
diff --git a/chromium/content/renderer/fetchers/resource_fetcher_impl.h b/chromium/content/renderer/fetchers/resource_fetcher_impl.h
index 7953119b901..04d71b9bfcc 100644
--- a/chromium/content/renderer/fetchers/resource_fetcher_impl.h
+++ b/chromium/content/renderer/fetchers/resource_fetcher_impl.h
@@ -15,7 +15,7 @@
#include "content/public/renderer/resource_fetcher.h"
#include "net/http/http_request_headers.h"
#include "services/network/public/cpp/resource_request.h"
-#include "third_party/WebKit/public/platform/WebURLRequest.h"
+#include "third_party/blink/public/platform/web_url_request.h"
class GURL;
@@ -33,7 +33,7 @@ class ResourceFetcherImpl : public ResourceFetcher {
void SetHeader(const std::string& header, const std::string& value) override;
void Start(blink::WebLocalFrame* frame,
blink::WebURLRequest::RequestContext request_context,
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory,
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
const net::NetworkTrafficAnnotationTag& annotation_tag,
Callback callback,
size_t maximum_download_size) override;
diff --git a/chromium/content/renderer/file_info_util.cc b/chromium/content/renderer/file_info_util.cc
index 94aa0183889..85ca2cfe359 100644
--- a/chromium/content/renderer/file_info_util.cc
+++ b/chromium/content/renderer/file_info_util.cc
@@ -5,7 +5,7 @@
#include "content/renderer/file_info_util.h"
#include "base/logging.h"
-#include "third_party/WebKit/public/platform/WebFileInfo.h"
+#include "third_party/blink/public/platform/web_file_info.h"
namespace content {
diff --git a/chromium/content/renderer/fileapi/file_system_dispatcher.cc b/chromium/content/renderer/fileapi/file_system_dispatcher.cc
index b2f2ad37280..77d8e5b82d7 100644
--- a/chromium/content/renderer/fileapi/file_system_dispatcher.cc
+++ b/chromium/content/renderer/fileapi/file_system_dispatcher.cc
@@ -5,12 +5,14 @@
#include "content/renderer/fileapi/file_system_dispatcher.h"
#include <memory>
+#include <utility>
#include "base/callback.h"
#include "base/files/file_util.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/process/process.h"
+#include "components/services/filesystem/public/interfaces/types.mojom.h"
#include "content/child/child_thread_impl.h"
#include "content/common/fileapi/file_system_messages.h"
#include "storage/common/fileapi/file_system_info.h"
@@ -19,15 +21,6 @@ namespace content {
class FileSystemDispatcher::CallbackDispatcher {
public:
- typedef CallbackDispatcher self;
- typedef FileSystemDispatcher::StatusCallback StatusCallback;
- typedef FileSystemDispatcher::MetadataCallback MetadataCallback;
- typedef FileSystemDispatcher::ReadDirectoryCallback ReadDirectoryCallback;
- typedef FileSystemDispatcher::OpenFileSystemCallback OpenFileSystemCallback;
- typedef FileSystemDispatcher::ResolveURLCallback ResolveURLCallback;
- typedef FileSystemDispatcher::WriteCallback WriteCallback;
- typedef FileSystemDispatcher::OpenFileCallback OpenFileCallback;
-
static std::unique_ptr<CallbackDispatcher> Create(
const StatusCallback& callback) {
auto dispatcher = base::WrapUnique(new CallbackDispatcher);
@@ -86,9 +79,7 @@ class FileSystemDispatcher::CallbackDispatcher {
~CallbackDispatcher() {}
- void DidSucceed() {
- status_callback_.Run(base::File::FILE_OK);
- }
+ void DidSucceed() { status_callback_.Run(base::File::FILE_OK); }
void DidFail(base::File::Error error_code) {
error_callback_.Run(error_code);
@@ -106,8 +97,9 @@ class FileSystemDispatcher::CallbackDispatcher {
snapshot_callback_.Run(file_info, platform_path, request_id);
}
- void DidReadDirectory(const std::vector<storage::DirectoryEntry>& entries,
- bool has_more) {
+ void DidReadDirectory(
+ const std::vector<filesystem::mojom::DirectoryEntry>& entries,
+ bool has_more) {
directory_callback_.Run(entries, has_more);
}
@@ -376,7 +368,7 @@ void FileSystemDispatcher::OnDidCreateSnapshotFile(
void FileSystemDispatcher::OnDidReadDirectory(
int request_id,
- const std::vector<storage::DirectoryEntry>& entries,
+ const std::vector<filesystem::mojom::DirectoryEntry>& entries,
bool has_more) {
CallbackDispatcher* dispatcher = dispatchers_.Lookup(request_id);
DCHECK(dispatcher);
diff --git a/chromium/content/renderer/fileapi/file_system_dispatcher.h b/chromium/content/renderer/fileapi/file_system_dispatcher.h
index 39ac857178d..676e471113c 100644
--- a/chromium/content/renderer/fileapi/file_system_dispatcher.h
+++ b/chromium/content/renderer/fileapi/file_system_dispatcher.h
@@ -7,6 +7,7 @@
#include <stdint.h>
+#include <memory>
#include <string>
#include <vector>
@@ -14,6 +15,7 @@
#include "base/containers/id_map.h"
#include "base/macros.h"
#include "base/process/process.h"
+#include "components/services/filesystem/public/interfaces/types.mojom.h"
#include "ipc/ipc_listener.h"
#include "ipc/ipc_platform_file.h"
#include "storage/common/fileapi/file_system_types.h"
@@ -24,7 +26,6 @@ class FilePath;
}
namespace storage {
-struct DirectoryEntry;
struct FileSystemInfo;
}
@@ -38,21 +39,24 @@ namespace content {
class FileSystemDispatcher : public IPC::Listener {
public:
typedef base::Callback<void(base::File::Error error)> StatusCallback;
+ typedef base::Callback<void(const base::File::Info& file_info)>
+ MetadataCallback;
+ typedef base::Callback<void(const base::File::Info& file_info,
+ const base::FilePath& platform_path,
+ int request_id)>
+ CreateSnapshotFileCallback;
+
typedef base::Callback<void(
- const base::File::Info& file_info)> MetadataCallback;
- typedef base::Callback<void(
- const base::File::Info& file_info,
- const base::FilePath& platform_path,
- int request_id)> CreateSnapshotFileCallback;
- typedef base::Callback<
- void(const std::vector<storage::DirectoryEntry>& entries, bool has_more)>
+ const std::vector<filesystem::mojom::DirectoryEntry>& entries,
+ bool has_more)>
ReadDirectoryCallback;
- typedef base::Callback<void(
- const std::string& name,
- const GURL& root)> OpenFileSystemCallback;
+ typedef base::Callback<void(const std::string& name, const GURL& root)>
+ OpenFileSystemCallback;
typedef base::Callback<void(const storage::FileSystemInfo& info,
const base::FilePath& file_path,
- bool is_directory)> ResolveURLCallback;
+ bool is_directory)>
+ ResolveURLCallback;
+
typedef base::Callback<void(int64_t bytes, bool complete)> WriteCallback;
typedef base::Callback<void(base::PlatformFile file,
int file_open_id,
@@ -78,9 +82,7 @@ class FileSystemDispatcher : public IPC::Listener {
void Copy(const GURL& src_path,
const GURL& dest_path,
const StatusCallback& callback);
- void Remove(const GURL& path,
- bool recursive,
- const StatusCallback& callback);
+ void Remove(const GURL& path, bool recursive, const StatusCallback& callback);
void ReadMetadata(const GURL& path,
const MetadataCallback& success_callback,
const StatusCallback& error_callback);
@@ -107,8 +109,7 @@ class FileSystemDispatcher : public IPC::Listener {
int* request_id_out,
const WriteCallback& success_callback,
const StatusCallback& error_callback);
- void Cancel(int request_id_to_cancel,
- const StatusCallback& callback);
+ void Cancel(int request_id_to_cancel, const StatusCallback& callback);
void TouchFile(const GURL& file_path,
const base::Time& last_access_time,
const base::Time& last_modified_time,
@@ -138,9 +139,10 @@ class FileSystemDispatcher : public IPC::Listener {
void OnDidCreateSnapshotFile(int request_id,
const base::File::Info& file_info,
const base::FilePath& platform_path);
- void OnDidReadDirectory(int request_id,
- const std::vector<storage::DirectoryEntry>& entries,
- bool has_more);
+ void OnDidReadDirectory(
+ int request_id,
+ const std::vector<filesystem::mojom::DirectoryEntry>& entries,
+ bool has_more);
void OnDidFail(int request_id, base::File::Error error_code);
void OnDidWrite(int request_id, int64_t bytes, bool complete);
diff --git a/chromium/content/renderer/fileapi/webfilesystem_impl.cc b/chromium/content/renderer/fileapi/webfilesystem_impl.cc
index 1ec25c920cc..f5969dc7f1d 100644
--- a/chromium/content/renderer/fileapi/webfilesystem_impl.cc
+++ b/chromium/content/renderer/fileapi/webfilesystem_impl.cc
@@ -5,7 +5,9 @@
#include "content/renderer/fileapi/webfilesystem_impl.h"
#include <stddef.h>
+#include <string>
#include <tuple>
+#include <vector>
#include "base/bind.h"
#include "base/lazy_instance.h"
@@ -15,18 +17,18 @@
#include "base/synchronization/waitable_event.h"
#include "base/threading/thread_local.h"
#include "base/threading/thread_task_runner_handle.h"
+#include "components/services/filesystem/public/interfaces/types.mojom.h"
#include "content/common/fileapi/file_system_messages.h"
#include "content/renderer/file_info_util.h"
#include "content/renderer/fileapi/file_system_dispatcher.h"
#include "content/renderer/fileapi/webfilewriter_impl.h"
#include "content/renderer/render_thread_impl.h"
-#include "storage/common/fileapi/directory_entry.h"
#include "storage/common/fileapi/file_system_util.h"
-#include "third_party/WebKit/public/platform/FilePathConversion.h"
-#include "third_party/WebKit/public/platform/WebFileInfo.h"
-#include "third_party/WebKit/public/platform/WebFileSystemCallbacks.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
+#include "third_party/blink/public/platform/file_path_conversion.h"
+#include "third_party/blink/public/platform/web_file_info.h"
+#include "third_party/blink/public/platform/web_file_system_callbacks.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_url.h"
#include "url/gurl.h"
using blink::WebFileInfo;
@@ -137,14 +139,16 @@ void DidReadMetadata(const base::File::Info& file_info,
callbacks->DidReadMetadata(web_file_info);
}
-void DidReadDirectory(const std::vector<storage::DirectoryEntry>& entries,
- bool has_more,
- WebFileSystemCallbacks* callbacks) {
+void DidReadDirectory(
+ const std::vector<filesystem::mojom::DirectoryEntry>& entries,
+ bool has_more,
+ WebFileSystemCallbacks* callbacks) {
WebVector<WebFileSystemEntry> file_system_entries(entries.size());
for (size_t i = 0; i < entries.size(); ++i) {
file_system_entries[i].name =
blink::FilePathToWebString(base::FilePath(entries[i].name));
- file_system_entries[i].is_directory = entries[i].is_directory;
+ file_system_entries[i].is_directory =
+ entries[i].type == filesystem::mojom::FsFileType::DIRECTORY;
}
callbacks->DidReadDirectory(file_system_entries, has_more);
}
@@ -279,7 +283,7 @@ void ReadDirectoryCallbackAdapter(
const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
int callbacks_id,
WaitableCallbackResults* waitable_results,
- const std::vector<storage::DirectoryEntry>& entries,
+ const std::vector<filesystem::mojom::DirectoryEntry>& entries,
bool has_more) {
CallbackFileSystemCallbacks(
task_runner, callbacks_id, waitable_results,
diff --git a/chromium/content/renderer/fileapi/webfilesystem_impl.h b/chromium/content/renderer/fileapi/webfilesystem_impl.h
index c42b5d2555d..97f92a5d70d 100644
--- a/chromium/content/renderer/fileapi/webfilesystem_impl.h
+++ b/chromium/content/renderer/fileapi/webfilesystem_impl.h
@@ -12,7 +12,7 @@
#include "base/memory/ref_counted.h"
#include "base/threading/thread_checker.h"
#include "content/public/renderer/worker_thread.h"
-#include "third_party/WebKit/public/platform/WebFileSystem.h"
+#include "third_party/blink/public/platform/web_file_system.h"
namespace base {
class SingleThreadTaskRunner;
diff --git a/chromium/content/renderer/fileapi/webfilewriter_base.cc b/chromium/content/renderer/fileapi/webfilewriter_base.cc
index c264b8f4e9c..edce76d8e37 100644
--- a/chromium/content/renderer/fileapi/webfilewriter_base.cc
+++ b/chromium/content/renderer/fileapi/webfilewriter_base.cc
@@ -6,9 +6,9 @@
#include "base/logging.h"
#include "storage/common/fileapi/file_system_util.h"
-#include "third_party/WebKit/public/platform/WebFileError.h"
-#include "third_party/WebKit/public/platform/WebFileWriterClient.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
+#include "third_party/blink/public/platform/web_file_error.h"
+#include "third_party/blink/public/platform/web_file_writer_client.h"
+#include "third_party/blink/public/platform/web_url.h"
using storage::FileErrorToWebFileError;
diff --git a/chromium/content/renderer/fileapi/webfilewriter_base.h b/chromium/content/renderer/fileapi/webfilewriter_base.h
index d721275ddb2..4c28e91e297 100644
--- a/chromium/content/renderer/fileapi/webfilewriter_base.h
+++ b/chromium/content/renderer/fileapi/webfilewriter_base.h
@@ -9,7 +9,7 @@
#include "base/files/file.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebFileWriter.h"
+#include "third_party/blink/public/platform/web_file_writer.h"
#include "url/gurl.h"
namespace blink {
diff --git a/chromium/content/renderer/fileapi/webfilewriter_base_unittest.cc b/chromium/content/renderer/fileapi/webfilewriter_base_unittest.cc
index 9fa99582ee8..baff9ae88d1 100644
--- a/chromium/content/renderer/fileapi/webfilewriter_base_unittest.cc
+++ b/chromium/content/renderer/fileapi/webfilewriter_base_unittest.cc
@@ -13,9 +13,9 @@
#include "base/message_loop/message_loop.h"
#include "base/strings/utf_string_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebFileError.h"
-#include "third_party/WebKit/public/platform/WebFileWriterClient.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
+#include "third_party/blink/public/platform/web_file_error.h"
+#include "third_party/blink/public/platform/web_file_writer_client.h"
+#include "third_party/blink/public/platform/web_url.h"
#include "url/gurl.h"
namespace content {
diff --git a/chromium/content/renderer/frame_blame_context.cc b/chromium/content/renderer/frame_blame_context.cc
index f6cf609cf02..096f10dedbe 100644
--- a/chromium/content/renderer/frame_blame_context.cc
+++ b/chromium/content/renderer/frame_blame_context.cc
@@ -7,8 +7,8 @@
#include "base/trace_event/trace_event_argument.h"
#include "content/renderer/render_frame_impl.h"
#include "content/renderer/top_level_blame_context.h"
-#include "third_party/WebKit/public/platform/Platform.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "third_party/blink/public/platform/platform.h"
+#include "third_party/blink/public/web/web_local_frame.h"
namespace content {
namespace {
diff --git a/chromium/content/renderer/frame_owner_properties.cc b/chromium/content/renderer/frame_owner_properties.cc
index a9906cdcb4b..66df968b837 100644
--- a/chromium/content/renderer/frame_owner_properties.cc
+++ b/chromium/content/renderer/frame_owner_properties.cc
@@ -7,8 +7,8 @@
#include <algorithm>
#include <iterator>
-#include "third_party/WebKit/public/common/feature_policy/feature_policy.h"
-#include "third_party/WebKit/public/platform/modules/permissions/permission.mojom.h"
+#include "third_party/blink/public/common/feature_policy/feature_policy.h"
+#include "third_party/blink/public/platform/modules/permissions/permission.mojom.h"
namespace content {
diff --git a/chromium/content/renderer/frame_owner_properties.h b/chromium/content/renderer/frame_owner_properties.h
index 05205c2c753..f562fe70e32 100644
--- a/chromium/content/renderer/frame_owner_properties.h
+++ b/chromium/content/renderer/frame_owner_properties.h
@@ -6,7 +6,7 @@
#define CONTENT_RENDERER_FRAME_OWNER_PROPERTIES_H_
#include "content/common/frame_owner_properties.h"
-#include "third_party/WebKit/public/web/WebFrameOwnerProperties.h"
+#include "third_party/blink/public/web/web_frame_owner_properties.h"
namespace content {
diff --git a/chromium/content/renderer/gamepad_shared_memory_reader.cc b/chromium/content/renderer/gamepad_shared_memory_reader.cc
index daee4fe36da..fe68df67ae3 100644
--- a/chromium/content/renderer/gamepad_shared_memory_reader.cc
+++ b/chromium/content/renderer/gamepad_shared_memory_reader.cc
@@ -11,8 +11,8 @@
#include "content/renderer/renderer_blink_platform_impl.h"
#include "ipc/ipc_sync_message_filter.h"
#include "services/service_manager/public/cpp/connector.h"
-#include "third_party/WebKit/public/platform/WebGamepadListener.h"
-#include "third_party/WebKit/public/platform/WebPlatformEventListener.h"
+#include "third_party/blink/public/platform/web_gamepad_listener.h"
+#include "third_party/blink/public/platform/web_platform_event_listener.h"
namespace content {
diff --git a/chromium/content/renderer/gin_browsertest.cc b/chromium/content/renderer/gin_browsertest.cc
index 097dfe2fb1c..cddd0f70f78 100644
--- a/chromium/content/renderer/gin_browsertest.cc
+++ b/chromium/content/renderer/gin_browsertest.cc
@@ -11,9 +11,9 @@
#include "gin/per_isolate_data.h"
#include "gin/wrappable.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/web/WebKit.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebView.h"
+#include "third_party/blink/public/web/blink.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_view.h"
namespace content {
diff --git a/chromium/content/renderer/gpu/OWNERS b/chromium/content/renderer/gpu/OWNERS
index 47457af208d..83153f27529 100644
--- a/chromium/content/renderer/gpu/OWNERS
+++ b/chromium/content/renderer/gpu/OWNERS
@@ -4,4 +4,7 @@ kbr@chromium.org
piman@chromium.org
vmpstr@chromium.org
+# For surface synchronization
+fsamuel@chromium.org
+
# COMPONENT: Internals>Compositing
diff --git a/chromium/content/renderer/gpu/actions_parser.cc b/chromium/content/renderer/gpu/actions_parser.cc
index 8094caf0ab2..5cb285a0974 100644
--- a/chromium/content/renderer/gpu/actions_parser.cc
+++ b/chromium/content/renderer/gpu/actions_parser.cc
@@ -5,7 +5,6 @@
#include "content/renderer/gpu/actions_parser.h"
#include "base/format_macros.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/stringprintf.h"
#include "base/values.h"
#include "components/viz/common/frame_sinks/begin_frame_args.h"
@@ -47,6 +46,10 @@ SyntheticPointerActionParams::Button ToSyntheticMouseButton(
return SyntheticPointerActionParams::Button::MIDDLE;
if (button == "right")
return SyntheticPointerActionParams::Button::RIGHT;
+ if (button == "back")
+ return SyntheticPointerActionParams::Button::BACK;
+ if (button == "forward")
+ return SyntheticPointerActionParams::Button::FORWARD;
NOTREACHED() << "Unexpected button";
return SyntheticPointerActionParams::Button();
}
@@ -210,7 +213,8 @@ bool ActionsParser::ParseAction(
"actions[%d].actions.button is not a string", action_index_);
return false;
} else if (button_name != "left" && button_name != "middle" &&
- button_name != "right") {
+ button_name != "right" && button_name != "back" &&
+ button_name != "forward") {
error_message_ = base::StringPrintf(
"actions[%d].actions.button is an unsupported button", action_index_);
return false;
diff --git a/chromium/content/renderer/gpu/compositor_dependencies.h b/chromium/content/renderer/gpu/compositor_dependencies.h
index 536de2a111d..4fc1825ead3 100644
--- a/chromium/content/renderer/gpu/compositor_dependencies.h
+++ b/chromium/content/renderer/gpu/compositor_dependencies.h
@@ -22,7 +22,7 @@ class UkmRecorderFactory;
namespace blink {
namespace scheduler {
-class RendererScheduler;
+class WebMainThreadScheduler;
}
}
@@ -33,7 +33,6 @@ class CompositorDependencies {
virtual bool IsGpuRasterizationForced() = 0;
virtual int GetGpuRasterizationMSAASampleCount() = 0;
virtual bool IsLcdTextEnabled() = 0;
- virtual bool IsDistanceFieldTextEnabled() = 0;
virtual bool IsZeroCopyEnabled() = 0;
virtual bool IsPartialRasterEnabled() = 0;
virtual bool IsGpuMemoryBufferCompositorResourcesEnabled() = 0;
@@ -44,7 +43,8 @@ class CompositorDependencies {
// compositor thread).
virtual scoped_refptr<base::SingleThreadTaskRunner>
GetCompositorImplThreadTaskRunner() = 0;
- virtual blink::scheduler::RendererScheduler* GetRendererScheduler() = 0;
+ virtual blink::scheduler::WebMainThreadScheduler*
+ GetWebMainThreadScheduler() = 0;
virtual cc::TaskGraphRunner* GetTaskGraphRunner() = 0;
virtual bool IsThreadedAnimationEnabled() = 0;
virtual bool IsScrollAnimatorEnabled() = 0;
diff --git a/chromium/content/renderer/gpu/frame_swap_message_queue.cc b/chromium/content/renderer/gpu/frame_swap_message_queue.cc
index ba0f87b4416..1d4e9746815 100644
--- a/chromium/content/renderer/gpu/frame_swap_message_queue.cc
+++ b/chromium/content/renderer/gpu/frame_swap_message_queue.cc
@@ -12,7 +12,6 @@
#include "base/containers/hash_tables.h"
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/stl_util.h"
#include "ipc/ipc_message.h"
@@ -208,10 +207,6 @@ void FrameSwapMessageQueue::TransferMessages(
source->clear();
}
-uint32_t FrameSwapMessageQueue::AllocateFrameToken() {
- return ++last_used_frame_token_;
-}
-
void FrameSwapMessageQueue::NotifyFramesAreDiscarded(
bool frames_are_discarded) {
DCHECK_CALLED_ON_VALID_THREAD(impl_thread_checker_);
diff --git a/chromium/content/renderer/gpu/frame_swap_message_queue.h b/chromium/content/renderer/gpu/frame_swap_message_queue.h
index 1a1dd748f4e..54ad846aa3b 100644
--- a/chromium/content/renderer/gpu/frame_swap_message_queue.h
+++ b/chromium/content/renderer/gpu/frame_swap_message_queue.h
@@ -97,8 +97,6 @@ class CONTENT_EXPORT FrameSwapMessageQueue
std::vector<std::unique_ptr<IPC::Message>>* source,
std::vector<IPC::Message>* dest);
- uint32_t AllocateFrameToken();
-
int32_t routing_id() const { return routing_id_; }
void NotifyFramesAreDiscarded(bool frames_are_discarded);
@@ -115,7 +113,6 @@ class CONTENT_EXPORT FrameSwapMessageQueue
std::unique_ptr<FrameSwapMessageSubQueue> visual_state_queue_;
std::unique_ptr<FrameSwapMessageSubQueue> swap_queue_;
std::vector<std::unique_ptr<IPC::Message>> next_drain_messages_;
- uint32_t last_used_frame_token_ = 0;
int32_t routing_id_ = 0;
bool frames_are_discarded_ = false;
THREAD_CHECKER(impl_thread_checker_);
diff --git a/chromium/content/renderer/gpu/frame_swap_message_queue_unittest.cc b/chromium/content/renderer/gpu/frame_swap_message_queue_unittest.cc
index 10efd7194f9..ce18fba26b2 100644
--- a/chromium/content/renderer/gpu/frame_swap_message_queue_unittest.cc
+++ b/chromium/content/renderer/gpu/frame_swap_message_queue_unittest.cc
@@ -6,7 +6,6 @@
#include <utility>
-#include "base/memory/ptr_util.h"
#include "ipc/ipc_message.h"
#include "testing/gtest/include/gtest/gtest.h"
diff --git a/chromium/content/renderer/gpu/gpu_benchmarking_extension.cc b/chromium/content/renderer/gpu/gpu_benchmarking_extension.cc
index 07dd309695b..ddf4a1e1f00 100644
--- a/chromium/content/renderer/gpu/gpu_benchmarking_extension.cc
+++ b/chromium/content/renderer/gpu/gpu_benchmarking_extension.cc
@@ -16,7 +16,6 @@
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/string_number_conversions.h"
#include "cc/layers/layer.h"
#include "cc/paint/skia_paint_canvas.h"
@@ -43,19 +42,17 @@
#include "gpu/config/gpu_driver_bug_workaround_type.h"
#include "gpu/ipc/common/gpu_messages.h"
#include "services/service_manager/public/cpp/interface_provider.h"
-#include "third_party/WebKit/public/platform/WebMouseEvent.h"
-#include "third_party/WebKit/public/web/WebImageCache.h"
-#include "third_party/WebKit/public/web/WebKit.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebPrintParams.h"
-#include "third_party/WebKit/public/web/WebSettings.h"
-#include "third_party/WebKit/public/web/WebView.h"
+#include "third_party/blink/public/platform/web_mouse_event.h"
+#include "third_party/blink/public/web/blink.h"
+#include "third_party/blink/public/web/web_image_cache.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_print_params.h"
+#include "third_party/blink/public/web/web_settings.h"
+#include "third_party/blink/public/web/web_view.h"
#include "third_party/skia/include/core/SkData.h"
#include "third_party/skia/include/core/SkGraphics.h"
#include "third_party/skia/include/core/SkPicture.h"
#include "third_party/skia/include/core/SkPictureRecorder.h"
-#include "third_party/skia/include/core/SkSerialProcs.h"
-#include "third_party/skia/include/core/SkStream.h"
// Note that headers in third_party/skia/src are fragile. This is
// an experimental, fragile, and diagnostic-only document type.
#include "third_party/skia/src/utils/SkMultiPictureDocument.h"
@@ -108,20 +105,7 @@ class SkPictureSerializer {
SkFILEWStream file(filepath.c_str());
DCHECK(file.isValid());
- SkSerialProcs procs;
- procs.fImageProc = [](SkImage* image, void*) {
- auto data = image->refEncodedData();
- if (!data) {
- const base::CommandLine& commandLine =
- *base::CommandLine::ForCurrentProcess();
- if (commandLine.HasSwitch(switches::kSkipReencodingOnSKPCapture)) {
- data = SkData::MakeEmpty();
- }
- // else data is null, which triggers skia's default PNG encode
- }
- return data;
- };
- auto data = picture->serialize(&procs);
+ auto data = picture->serialize();
file.write(data->data(), data->size());
file.fsync();
}
@@ -985,8 +969,12 @@ bool GpuBenchmarking::PointerActionSequence(gin::Arguments* args) {
// Get all the pointer actions from the user input and wrap them into a
// SyntheticPointerActionListParams object.
ActionsParser actions_parser(value.get());
- if (!actions_parser.ParsePointerActionSequence())
+ if (!actions_parser.ParsePointerActionSequence()) {
+ // TODO(dtapuska): Throw an error here, some layout tests start
+ // failing when this is done though.
+ // args->ThrowTypeError(actions_parser.error_message());
return false;
+ }
if (!GetOptionalArg(args, &callback)) {
args->ThrowError();
diff --git a/chromium/content/renderer/gpu/queue_message_swap_promise.cc b/chromium/content/renderer/gpu/queue_message_swap_promise.cc
index b045b8345a9..199ddfa4402 100644
--- a/chromium/content/renderer/gpu/queue_message_swap_promise.cc
+++ b/chromium/content/renderer/gpu/queue_message_swap_promise.cc
@@ -7,6 +7,7 @@
#include <memory>
#include "base/command_line.h"
+#include "cc/trees/frame_token_allocator.h"
#include "content/common/view_messages.h"
#include "content/public/common/content_switches.h"
#include "content/public/renderer/render_thread.h"
@@ -46,7 +47,9 @@ void QueueMessageSwapPromise::DidActivate() {
// The OutputSurface will take care of the Drain+Send.
}
-void QueueMessageSwapPromise::WillSwap(viz::CompositorFrameMetadata* metadata) {
+void QueueMessageSwapPromise::WillSwap(
+ viz::CompositorFrameMetadata* metadata,
+ cc::FrameTokenAllocator* frame_token_allocator) {
#if DCHECK_IS_ON()
DCHECK(!completed_);
#endif
@@ -61,7 +64,7 @@ void QueueMessageSwapPromise::WillSwap(viz::CompositorFrameMetadata* metadata) {
std::vector<IPC::Message> messages_to_send;
FrameSwapMessageQueue::TransferMessages(&messages, &messages_to_send);
if (!messages_to_send.empty()) {
- metadata->frame_token = message_queue_->AllocateFrameToken();
+ metadata->frame_token = frame_token_allocator->GetOrAllocateFrameToken();
message_sender_->Send(new ViewHostMsg_FrameSwapMessages(
message_queue_->routing_id(), metadata->frame_token,
messages_to_send));
diff --git a/chromium/content/renderer/gpu/queue_message_swap_promise.h b/chromium/content/renderer/gpu/queue_message_swap_promise.h
index f888f2f9b5e..392ac6da142 100644
--- a/chromium/content/renderer/gpu/queue_message_swap_promise.h
+++ b/chromium/content/renderer/gpu/queue_message_swap_promise.h
@@ -27,7 +27,8 @@ class QueueMessageSwapPromise : public cc::SwapPromise {
~QueueMessageSwapPromise() override;
void DidActivate() override;
- void WillSwap(viz::CompositorFrameMetadata* metadata) override;
+ void WillSwap(viz::CompositorFrameMetadata* metadata,
+ cc::FrameTokenAllocator* frame_token_allocator) override;
void DidSwap() override;
DidNotSwapAction DidNotSwap(DidNotSwapReason reason) override;
diff --git a/chromium/content/renderer/gpu/queue_message_swap_promise_unittest.cc b/chromium/content/renderer/gpu/queue_message_swap_promise_unittest.cc
index eb1b54cc273..828148017c4 100644
--- a/chromium/content/renderer/gpu/queue_message_swap_promise_unittest.cc
+++ b/chromium/content/renderer/gpu/queue_message_swap_promise_unittest.cc
@@ -12,6 +12,7 @@
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/test/scoped_task_environment.h"
+#include "cc/trees/frame_token_allocator.h"
#include "cc/trees/swap_promise.h"
#include "content/common/view_messages.h"
#include "content/renderer/gpu/frame_swap_message_queue.h"
@@ -145,7 +146,7 @@ class QueueMessageSwapPromiseTest : public testing::Test {
for (const auto& promise : promises_) {
if (promise.get()) {
promise->DidActivate();
- promise->WillSwap(&dummy_metadata_);
+ promise->WillSwap(&dummy_metadata_, &dummy_frame_token_allocator_);
promise->DidSwap();
}
}
@@ -161,6 +162,7 @@ class QueueMessageSwapPromiseTest : public testing::Test {
std::vector<IPC::Message> messages_;
std::vector<std::unique_ptr<cc::SwapPromise>> promises_;
viz::CompositorFrameMetadata dummy_metadata_;
+ cc::FrameTokenAllocator dummy_frame_token_allocator_;
cc::RenderFrameMetadata dummy_render_frame_metadata_;
private:
@@ -178,7 +180,7 @@ TEST_F(QueueMessageSwapPromiseTest, NextSwapPolicySchedulesMessageForNextSwap) {
ASSERT_TRUE(promises_[0].get());
promises_[0]->DidActivate();
- promises_[0]->WillSwap(&dummy_metadata_);
+ promises_[0]->WillSwap(&dummy_metadata_, &dummy_frame_token_allocator_);
promises_[0]->DidSwap();
EXPECT_TRUE(DirectSendMessages().empty());
@@ -283,7 +285,7 @@ TEST_F(QueueMessageSwapPromiseTest, VisualStateSwapPromiseDidActivate) {
QueueMessages(data, arraysize(data));
promises_[0]->DidActivate();
- promises_[0]->WillSwap(&dummy_metadata_);
+ promises_[0]->WillSwap(&dummy_metadata_, &dummy_frame_token_allocator_);
promises_[0]->DidSwap();
ASSERT_FALSE(promises_[1].get());
std::vector<std::unique_ptr<IPC::Message>> messages;
diff --git a/chromium/content/renderer/gpu/render_widget_compositor.cc b/chromium/content/renderer/gpu/render_widget_compositor.cc
index 36dcd9927d1..9d0ebcbcdc8 100644
--- a/chromium/content/renderer/gpu/render_widget_compositor.cc
+++ b/chromium/content/renderer/gpu/render_widget_compositor.cc
@@ -17,7 +17,6 @@
#include "base/command_line.h"
#include "base/location.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/numerics/safe_conversions.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
@@ -68,13 +67,13 @@
#include "gpu/command_buffer/service/gpu_switches.h"
#include "media/base/media_switches.h"
#include "services/ui/public/cpp/gpu/context_provider_command_buffer.h"
-#include "third_party/WebKit/public/platform/WebCompositeAndReadbackAsyncCallback.h"
-#include "third_party/WebKit/public/platform/WebLayoutAndPaintAsyncCallback.h"
-#include "third_party/WebKit/public/platform/WebRuntimeFeatures.h"
-#include "third_party/WebKit/public/platform/WebSize.h"
-#include "third_party/WebKit/public/platform/scheduler/renderer/renderer_scheduler.h"
-#include "third_party/WebKit/public/web/WebKit.h"
-#include "third_party/WebKit/public/web/WebSelection.h"
+#include "third_party/blink/public/platform/scheduler/web_main_thread_scheduler.h"
+#include "third_party/blink/public/platform/web_composite_and_readback_async_callback.h"
+#include "third_party/blink/public/platform/web_layout_and_paint_async_callback.h"
+#include "third_party/blink/public/platform/web_runtime_features.h"
+#include "third_party/blink/public/platform/web_size.h"
+#include "third_party/blink/public/web/blink.h"
+#include "third_party/blink/public/web/web_selection.h"
#include "third_party/skia/include/core/SkImage.h"
#include "ui/base/ui_base_switches.h"
#include "ui/gfx/switches.h"
@@ -101,6 +100,9 @@ using blink::WebOverscrollBehavior;
namespace content {
namespace {
+const base::Feature kUnpremultiplyAndDitherLowBitDepthTiles = {
+ "UnpremultiplyAndDitherLowBitDepthTiles", base::FEATURE_ENABLED_BY_DEFAULT};
+
using ReportTimeCallback =
base::Callback<void(WebLayerTreeView::SwapResult, double)>;
@@ -117,7 +119,8 @@ class ReportTimeSwapPromise : public cc::SwapPromise {
~ReportTimeSwapPromise() override;
void DidActivate() override {}
- void WillSwap(viz::CompositorFrameMetadata* metadata) override {}
+ void WillSwap(viz::CompositorFrameMetadata* metadata,
+ cc::FrameTokenAllocator* frame_token_allocator) override {}
void DidSwap() override;
DidNotSwapAction DidNotSwap(DidNotSwapReason reason) override;
@@ -189,39 +192,37 @@ bool GetSwitchValueAsInt(const base::CommandLine& command_line,
}
}
-cc::LayerSelectionBound ConvertWebSelectionBound(
- const WebSelection& web_selection,
- bool is_start) {
+gfx::SelectionBound::Type ConvertFromWebSelectionBoundType(
+ blink::WebSelectionBound::Type type) {
+ if (type == blink::WebSelectionBound::Type::kSelectionLeft)
+ return gfx::SelectionBound::Type::LEFT;
+ if (type == blink::WebSelectionBound::Type::kSelectionRight)
+ return gfx::SelectionBound::Type::RIGHT;
+ // if WebSelection is not a range (caret or none),
+ // The type of gfx::SelectionBound should be CENTER.
+ DCHECK_EQ(type, blink::WebSelectionBound::Type::kCaret);
+ return gfx::SelectionBound::Type::CENTER;
+}
+
+cc::LayerSelectionBound ConvertFromWebSelectionBound(
+ const blink::WebSelectionBound& bound) {
cc::LayerSelectionBound cc_bound;
- if (web_selection.IsNone())
- return cc_bound;
-
- const blink::WebSelectionBound& web_bound =
- is_start ? web_selection.Start() : web_selection.end();
- DCHECK(web_bound.layer_id);
- cc_bound.type = gfx::SelectionBound::CENTER;
- if (web_selection.IsRange()) {
- if (is_start) {
- cc_bound.type = web_bound.is_text_direction_rtl
- ? gfx::SelectionBound::RIGHT
- : gfx::SelectionBound::LEFT;
- } else {
- cc_bound.type = web_bound.is_text_direction_rtl
- ? gfx::SelectionBound::LEFT
- : gfx::SelectionBound::RIGHT;
- }
- }
- cc_bound.layer_id = web_bound.layer_id;
- cc_bound.edge_top = gfx::Point(web_bound.edge_top_in_layer);
- cc_bound.edge_bottom = gfx::Point(web_bound.edge_bottom_in_layer);
- cc_bound.hidden = web_bound.hidden;
+ DCHECK(bound.layer_id);
+
+ cc_bound.type = ConvertFromWebSelectionBoundType(bound.type);
+ cc_bound.layer_id = bound.layer_id;
+ cc_bound.edge_top = gfx::Point(bound.edge_top_in_layer);
+ cc_bound.edge_bottom = gfx::Point(bound.edge_bottom_in_layer);
+ cc_bound.hidden = bound.hidden;
return cc_bound;
}
-cc::LayerSelection ConvertWebSelection(const WebSelection& web_selection) {
+cc::LayerSelection ConvertFromWebSelection(const WebSelection& web_selection) {
+ if (web_selection.IsNone())
+ return cc::LayerSelection();
cc::LayerSelection cc_selection;
- cc_selection.start = ConvertWebSelectionBound(web_selection, true);
- cc_selection.end = ConvertWebSelectionBound(web_selection, false);
+ cc_selection.start = ConvertFromWebSelectionBound(web_selection.Start());
+ cc_selection.end = ConvertFromWebSelectionBound(web_selection.end());
return cc_selection;
}
@@ -416,8 +417,6 @@ cc::LayerTreeSettings RenderWidgetCompositor::GenerateLayerTreeSettings(
compositor_deps->IsGpuRasterizationForced();
settings.can_use_lcd_text = compositor_deps->IsLcdTextEnabled();
- settings.use_distance_field_text =
- compositor_deps->IsDistanceFieldTextEnabled();
settings.use_zero_copy = compositor_deps->IsZeroCopyEnabled();
settings.use_partial_raster = compositor_deps->IsPartialRasterEnabled();
settings.enable_elastic_overscroll =
@@ -552,6 +551,17 @@ cc::LayerTreeSettings RenderWidgetCompositor::GenerateLayerTreeSettings(
base::SysInfo::AmountOfPhysicalMemoryMB() <= 512 &&
!using_synchronous_compositor) {
settings.preferred_tile_format = viz::RGBA_4444;
+
+ // If we are going to unpremultiply and dither these tiles, we need to
+ // allocate an additional RGBA_8888 intermediate for each tile
+ // rasterization when rastering to RGBA_4444 to allow for dithering.
+ // Setting a reasonable sized max tile size allows this intermediate to
+ // be consistently reused.
+ if (base::FeatureList::IsEnabled(
+ kUnpremultiplyAndDitherLowBitDepthTiles)) {
+ settings.max_gpu_raster_tile_size = gfx::Size(512, 256);
+ settings.unpremultiply_and_dither_low_bit_depth_tiles = true;
+ }
}
}
@@ -590,8 +600,8 @@ cc::LayerTreeSettings RenderWidgetCompositor::GenerateLayerTreeSettings(
settings.enable_latency_recovery = false;
}
- settings.enable_image_animations =
- cmd.HasSwitch(switches::kEnableCompositorImageAnimations);
+ settings.enable_image_animation_resync =
+ !cmd.HasSwitch(switches::kDisableImageAnimationResync);
settings.always_request_presentation_time =
cmd.HasSwitch(cc::switches::kAlwaysRequestPresentationTime);
@@ -777,6 +787,11 @@ void RenderWidgetCompositor::SetViewportSizeAndScale(
device_viewport_size, device_scale_factor, local_surface_id);
}
+void RenderWidgetCompositor::SetViewportVisibleRect(
+ const gfx::Rect& visible_rect) {
+ layer_tree_host_->SetViewportVisibleRect(visible_rect);
+}
+
viz::FrameSinkId RenderWidgetCompositor::GetFrameSinkId() {
return frame_sink_id_;
}
@@ -899,7 +914,7 @@ void RenderWidgetCompositor::ClearViewportLayers() {
void RenderWidgetCompositor::RegisterSelection(
const blink::WebSelection& selection) {
- layer_tree_host_->RegisterSelection(ConvertWebSelection(selection));
+ layer_tree_host_->RegisterSelection(ConvertFromWebSelection(selection));
}
void RenderWidgetCompositor::ClearSelection() {
@@ -1176,18 +1191,18 @@ void RenderWidgetCompositor::WillBeginMainFrame() {
void RenderWidgetCompositor::DidBeginMainFrame() {}
void RenderWidgetCompositor::BeginMainFrame(const viz::BeginFrameArgs& args) {
- compositor_deps_->GetRendererScheduler()->WillBeginFrame(args);
+ compositor_deps_->GetWebMainThreadScheduler()->WillBeginFrame(args);
double frame_time_sec = (args.frame_time - base::TimeTicks()).InSecondsF();
delegate_->BeginMainFrame(frame_time_sec);
}
void RenderWidgetCompositor::BeginMainFrameNotExpectedSoon() {
- compositor_deps_->GetRendererScheduler()->BeginFrameNotExpectedSoon();
+ compositor_deps_->GetWebMainThreadScheduler()->BeginFrameNotExpectedSoon();
}
void RenderWidgetCompositor::BeginMainFrameNotExpectedUntil(
base::TimeTicks time) {
- compositor_deps_->GetRendererScheduler()->BeginMainFrameNotExpectedUntil(
+ compositor_deps_->GetWebMainThreadScheduler()->BeginMainFrameNotExpectedUntil(
time);
}
@@ -1246,7 +1261,7 @@ void RenderWidgetCompositor::WillCommit() {
void RenderWidgetCompositor::DidCommit() {
delegate_->DidCommitCompositorFrame();
- compositor_deps_->GetRendererScheduler()->DidCommitFrameToCompositor();
+ compositor_deps_->GetWebMainThreadScheduler()->DidCommitFrameToCompositor();
}
void RenderWidgetCompositor::DidCommitAndDrawFrame() {
diff --git a/chromium/content/renderer/gpu/render_widget_compositor.h b/chromium/content/renderer/gpu/render_widget_compositor.h
index e101b788e8b..8b145362d61 100644
--- a/chromium/content/renderer/gpu/render_widget_compositor.h
+++ b/chromium/content/renderer/gpu/render_widget_compositor.h
@@ -23,7 +23,7 @@
#include "content/common/render_frame_metadata.mojom.h"
#include "content/renderer/gpu/compositor_dependencies.h"
#include "services/metrics/public/cpp/ukm_recorder.h"
-#include "third_party/WebKit/public/platform/WebLayerTreeView.h"
+#include "third_party/blink/public/platform/web_layer_tree_view.h"
#include "ui/gfx/geometry/rect.h"
namespace base {
@@ -124,6 +124,7 @@ class CONTENT_EXPORT RenderWidgetCompositor
void SetViewportSizeAndScale(const gfx::Size& device_viewport_size,
float device_scale_factor,
const viz::LocalSurfaceId& local_surface_id);
+ void SetViewportVisibleRect(const gfx::Rect& visible_rect);
void SetURLForUkm(const GURL& url);
// WebLayerTreeView implementation.
diff --git a/chromium/content/renderer/gpu/render_widget_compositor_unittest.cc b/chromium/content/renderer/gpu/render_widget_compositor_unittest.cc
index 9cf5f6fee22..1258707c011 100644
--- a/chromium/content/renderer/gpu/render_widget_compositor_unittest.cc
+++ b/chromium/content/renderer/gpu/render_widget_compositor_unittest.cc
@@ -8,7 +8,6 @@
#include "base/location.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
@@ -26,7 +25,7 @@
#include "gpu/GLES2/gl2extchromium.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
using testing::AllOf;
using testing::Field;
diff --git a/chromium/content/renderer/history_entry.cc b/chromium/content/renderer/history_entry.cc
index a95f235dc6b..7d321185935 100644
--- a/chromium/content/renderer/history_entry.cc
+++ b/chromium/content/renderer/history_entry.cc
@@ -37,8 +37,7 @@
#include <algorithm>
-#include "base/memory/ptr_util.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "third_party/blink/public/web/web_local_frame.h"
using blink::WebFrame;
using blink::WebHistoryItem;
diff --git a/chromium/content/renderer/history_entry.h b/chromium/content/renderer/history_entry.h
index f12f8c85e07..a8272f98969 100644
--- a/chromium/content/renderer/history_entry.h
+++ b/chromium/content/renderer/history_entry.h
@@ -42,8 +42,8 @@
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebURLRequest.h"
-#include "third_party/WebKit/public/web/WebHistoryItem.h"
+#include "third_party/blink/public/platform/web_url_request.h"
+#include "third_party/blink/public/web/web_history_item.h"
namespace content {
diff --git a/chromium/content/renderer/history_serialization.cc b/chromium/content/renderer/history_serialization.cc
index 81793d3ed24..2d618233e5b 100644
--- a/chromium/content/renderer/history_serialization.cc
+++ b/chromium/content/renderer/history_serialization.cc
@@ -12,14 +12,14 @@
#include "content/public/common/page_state.h"
#include "content/renderer/history_entry.h"
#include "content/renderer/loader/web_url_request_util.h"
-#include "third_party/WebKit/public/platform/WebData.h"
-#include "third_party/WebKit/public/platform/WebFloatPoint.h"
-#include "third_party/WebKit/public/platform/WebHTTPBody.h"
-#include "third_party/WebKit/public/platform/WebPoint.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebVector.h"
-#include "third_party/WebKit/public/web/WebHistoryItem.h"
-#include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
+#include "third_party/blink/public/platform/web_data.h"
+#include "third_party/blink/public/platform/web_float_point.h"
+#include "third_party/blink/public/platform/web_http_body.h"
+#include "third_party/blink/public/platform/web_point.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_vector.h"
+#include "third_party/blink/public/web/web_history_item.h"
+#include "third_party/blink/public/web/web_serialized_script_value.h"
using blink::WebData;
using blink::WebHTTPBody;
diff --git a/chromium/content/renderer/ico_image_decoder_unittest.cc b/chromium/content/renderer/ico_image_decoder_unittest.cc
index 42813799976..b3bca197a02 100644
--- a/chromium/content/renderer/ico_image_decoder_unittest.cc
+++ b/chromium/content/renderer/ico_image_decoder_unittest.cc
@@ -4,7 +4,7 @@
#include "base/files/file_path.h"
#include "content/test/image_decoder_test.h"
-#include "third_party/WebKit/public/web/WebImageDecoder.h"
+#include "third_party/blink/public/web/web_image_decoder.h"
using blink::WebImageDecoder;
diff --git a/chromium/content/renderer/image_capture/image_capture_frame_grabber.cc b/chromium/content/renderer/image_capture/image_capture_frame_grabber.cc
index b49d2b5a6ba..c5e6515bb19 100644
--- a/chromium/content/renderer/image_capture/image_capture_frame_grabber.cc
+++ b/chromium/content/renderer/image_capture/image_capture_frame_grabber.cc
@@ -9,9 +9,9 @@
#include "media/base/video_frame.h"
#include "media/base/video_util.h"
#include "skia/ext/platform_canvas.h"
-#include "third_party/WebKit/public/platform/WebCallbacks.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
+#include "third_party/blink/public/platform/web_callbacks.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
#include "third_party/libyuv/include/libyuv.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/core/SkSurface.h"
@@ -75,7 +75,7 @@ void ImageCaptureFrameGrabber::SingleShotFrameHandler::OnVideoFrameOnIOThread(
SkPixmap pixmap;
if (!skia::GetWritablePixels(surface->getCanvas(), &pixmap)) {
DLOG(ERROR) << "Error trying to map SkSurface's pixels";
- callback.Run(sk_sp<SkImage>());
+ std::move(callback).Run(sk_sp<SkImage>());
return;
}
@@ -103,7 +103,7 @@ void ImageCaptureFrameGrabber::SingleShotFrameHandler::OnVideoFrameOnIOThread(
pixmap.height());
}
- callback.Run(surface->makeImageSnapshot());
+ std::move(callback).Run(surface->makeImageSnapshot());
}
ImageCaptureFrameGrabber::ImageCaptureFrameGrabber()
diff --git a/chromium/content/renderer/image_capture/image_capture_frame_grabber.h b/chromium/content/renderer/image_capture/image_capture_frame_grabber.h
index e64afd28b51..99356ce9a24 100644
--- a/chromium/content/renderer/image_capture/image_capture_frame_grabber.h
+++ b/chromium/content/renderer/image_capture/image_capture_frame_grabber.h
@@ -12,7 +12,7 @@
#include "content/child/scoped_web_callbacks.h"
#include "content/common/content_export.h"
#include "content/public/renderer/media_stream_video_sink.h"
-#include "third_party/WebKit/public/platform/WebImageCaptureFrameGrabber.h"
+#include "third_party/blink/public/platform/web_image_capture_frame_grabber.h"
namespace blink {
class WebMediaStreamTrack;
diff --git a/chromium/content/renderer/image_downloader/image_downloader_base.cc b/chromium/content/renderer/image_downloader/image_downloader_base.cc
index 9167646ce8b..19dda4fcef9 100644
--- a/chromium/content/renderer/image_downloader/image_downloader_base.cc
+++ b/chromium/content/renderer/image_downloader/image_downloader_base.cc
@@ -9,15 +9,14 @@
#include "base/bind.h"
#include "base/location.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "content/child/image_decoder.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_thread.h"
#include "content/renderer/fetchers/multi_resolution_image_resource_fetcher.h"
#include "net/base/data_url.h"
-#include "third_party/WebKit/public/platform/WebURLRequest.h"
-#include "third_party/WebKit/public/platform/modules/fetch/fetch_api_request.mojom-shared.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "third_party/blink/public/platform/modules/fetch/fetch_api_request.mojom-shared.h"
+#include "third_party/blink/public/platform/web_url_request.h"
+#include "third_party/blink/public/web/web_local_frame.h"
#include "ui/gfx/favicon_size.h"
#include "ui/gfx/geometry/size.h"
#include "url/url_constants.h"
@@ -62,28 +61,27 @@ ImageDownloaderBase::~ImageDownloaderBase() {
void ImageDownloaderBase::DownloadImage(const GURL& image_url,
bool is_favicon,
bool bypass_cache,
- const DownloadCallback& callback) {
+ DownloadCallback callback) {
+ if (!image_url.SchemeIs(url::kDataScheme)) {
+ FetchImage(image_url, is_favicon, bypass_cache, std::move(callback));
+ // Will complete asynchronously via ImageDownloaderBase::DidFetchImage.
+ return;
+ }
+
std::vector<SkBitmap> result_images;
+ SkBitmap data_image = ImageFromDataUrl(image_url);
- if (image_url.SchemeIs(url::kDataScheme)) {
- SkBitmap data_image = ImageFromDataUrl(image_url);
- // Drop null or empty SkBitmap.
- if (!data_image.drawsNothing())
- result_images.push_back(data_image);
- } else {
- if (FetchImage(image_url, is_favicon, bypass_cache, callback)) {
- // Will complete asynchronously via ImageDownloaderBase::DidFetchImage
- return;
- }
- }
+ // Drop null or empty SkBitmap.
+ if (!data_image.drawsNothing())
+ result_images.push_back(data_image);
- callback.Run(0, result_images);
+ std::move(callback).Run(0, result_images);
}
-bool ImageDownloaderBase::FetchImage(const GURL& image_url,
+void ImageDownloaderBase::FetchImage(const GURL& image_url,
bool is_favicon,
bool bypass_cache,
- const DownloadCallback& callback) {
+ DownloadCallback callback) {
blink::WebLocalFrame* frame = render_frame()->GetWebFrame();
DCHECK(frame);
@@ -95,13 +93,12 @@ bool ImageDownloaderBase::FetchImage(const GURL& image_url,
: WebURLRequest::kRequestContextImage,
bypass_cache ? blink::mojom::FetchCacheMode::kBypassCache
: blink::mojom::FetchCacheMode::kDefault,
- base::Bind(&ImageDownloaderBase::DidFetchImage,
- base::Unretained(this), callback)));
- return true;
+ base::BindOnce(&ImageDownloaderBase::DidFetchImage,
+ base::Unretained(this), std::move(callback))));
}
void ImageDownloaderBase::DidFetchImage(
- const DownloadCallback& callback,
+ DownloadCallback callback,
MultiResolutionImageResourceFetcher* fetcher,
const std::vector<SkBitmap>& images) {
int32_t http_status_code = fetcher->http_status_code();
@@ -121,7 +118,7 @@ void ImageDownloaderBase::DidFetchImage(
}
// |this| may be destructed after callback is run.
- callback.Run(http_status_code, images);
+ std::move(callback).Run(http_status_code, images);
}
void ImageDownloaderBase::OnDestruct() {
diff --git a/chromium/content/renderer/image_downloader/image_downloader_base.h b/chromium/content/renderer/image_downloader/image_downloader_base.h
index c444bc3cb84..0c479fef5ec 100644
--- a/chromium/content/renderer/image_downloader/image_downloader_base.h
+++ b/chromium/content/renderer/image_downloader/image_downloader_base.h
@@ -28,13 +28,13 @@ class ImageDownloaderBase : public RenderFrameObserver,
~ImageDownloaderBase() override;
using DownloadCallback =
- base::Callback<void(int32_t, const std::vector<SkBitmap>&)>;
- // Request to aynchronously download an image. When done, |callback| will be
+ base::OnceCallback<void(int32_t, const std::vector<SkBitmap>&)>;
+ // Request to asynchronously download an image. When done, |callback| will be
// called.
void DownloadImage(const GURL& url,
bool is_favicon,
bool bypass_cache,
- const DownloadCallback& callback);
+ DownloadCallback callback);
protected:
// RenderFrameObserver implementation.
@@ -42,19 +42,18 @@ class ImageDownloaderBase : public RenderFrameObserver,
private:
// Requests to fetch an image. When done, the image downloader is notified by
- // way of DidFetchImage. Returns true if the request was successfully started,
- // false otherwise. If the image is a favicon, cookies will not be sent nor
- // accepted during download. If the image has multiple frames, all frames are
- // returned.
- bool FetchImage(const GURL& image_url,
+ // way of DidFetchImage. If the image is a favicon, cookies will not be sent
+ // nor accepted during download. If the image has multiple frames, all frames
+ // are returned.
+ void FetchImage(const GURL& image_url,
bool is_favicon,
bool bypass_cache,
- const DownloadCallback& callback);
+ DownloadCallback callback);
// This callback is triggered when FetchImage completes, either
- // succesfully or with a failure. See FetchImage for more
+ // successfully or with a failure. See FetchImage for more
// details.
- void DidFetchImage(const DownloadCallback& callback,
+ void DidFetchImage(DownloadCallback callback,
MultiResolutionImageResourceFetcher* fetcher,
const std::vector<SkBitmap>& images);
diff --git a/chromium/content/renderer/image_downloader/image_downloader_impl.cc b/chromium/content/renderer/image_downloader/image_downloader_impl.cc
index 6a70cc48a18..f20ad653cf1 100644
--- a/chromium/content/renderer/image_downloader/image_downloader_impl.cc
+++ b/chromium/content/renderer/image_downloader/image_downloader_impl.cc
@@ -119,8 +119,9 @@ void ImageDownloaderImpl::DownloadImage(const GURL& image_url,
ImageDownloaderBase::DownloadImage(
image_url, is_favicon, bypass_cache,
- base::Bind(&ImageDownloaderImpl::DidDownloadImage, base::Unretained(this),
- max_bitmap_size, base::Passed(&callback)));
+ base::BindOnce(&ImageDownloaderImpl::DidDownloadImage,
+ base::Unretained(this), max_bitmap_size,
+ std::move(callback)));
}
void ImageDownloaderImpl::DidDownloadImage(
diff --git a/chromium/content/renderer/image_downloader/single_image_downloader.cc b/chromium/content/renderer/image_downloader/single_image_downloader.cc
index 760b2148720..682e3ee491f 100644
--- a/chromium/content/renderer/image_downloader/single_image_downloader.cc
+++ b/chromium/content/renderer/image_downloader/single_image_downloader.cc
@@ -24,8 +24,9 @@ void SingleImageDownloader::DownloadImage(
new ImageDownloaderBase(render_frame.get()));
ImageDownloaderBase* image_downloader_ptr = image_downloader.get();
image_downloader_ptr->DownloadImage(
- url, false, false, base::Bind(&SingleImageDownloader::DidDownloadImage,
- base::Passed(&image_downloader), cb));
+ url, false, false,
+ base::BindOnce(&SingleImageDownloader::DidDownloadImage,
+ std::move(image_downloader), cb));
}
// Static
diff --git a/chromium/content/renderer/in_process_renderer_thread.cc b/chromium/content/renderer/in_process_renderer_thread.cc
index d16d789e8c7..e6a3a5d9e22 100644
--- a/chromium/content/renderer/in_process_renderer_thread.cc
+++ b/chromium/content/renderer/in_process_renderer_thread.cc
@@ -47,7 +47,7 @@ void InProcessRendererThread::Init() {
CHECK(!render_process_);
#endif
render_process_ = RenderProcessImpl::Create();
- RenderThreadImpl::Create(params_);
+ RenderThreadImpl::Create(params_, message_loop());
}
void InProcessRendererThread::CleanUp() {
diff --git a/chromium/content/renderer/indexed_db/indexed_db_callbacks_impl.cc b/chromium/content/renderer/indexed_db/indexed_db_callbacks_impl.cc
index 294a9ace23f..3c4baafbdcc 100644
--- a/chromium/content/renderer/indexed_db/indexed_db_callbacks_impl.cc
+++ b/chromium/content/renderer/indexed_db/indexed_db_callbacks_impl.cc
@@ -10,11 +10,11 @@
#include "content/renderer/indexed_db/indexed_db_key_builders.h"
#include "content/renderer/indexed_db/webidbcursor_impl.h"
#include "content/renderer/indexed_db/webidbdatabase_impl.h"
-#include "third_party/WebKit/public/platform/FilePathConversion.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBCallbacks.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBDatabaseError.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBMetadata.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBValue.h"
+#include "third_party/blink/public/platform/file_path_conversion.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_callbacks.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_error.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_metadata.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_value.h"
using blink::WebBlobInfo;
using blink::WebData;
diff --git a/chromium/content/renderer/indexed_db/indexed_db_database_callbacks_impl.cc b/chromium/content/renderer/indexed_db/indexed_db_database_callbacks_impl.cc
index bf655162559..08f03791791 100644
--- a/chromium/content/renderer/indexed_db/indexed_db_database_callbacks_impl.cc
+++ b/chromium/content/renderer/indexed_db/indexed_db_database_callbacks_impl.cc
@@ -11,9 +11,9 @@
#include "content/renderer/indexed_db/indexed_db_callbacks_impl.h"
#include "content/renderer/indexed_db/indexed_db_dispatcher.h"
#include "content/renderer/indexed_db/indexed_db_key_builders.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBDatabaseCallbacks.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBDatabaseError.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBObservation.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_callbacks.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_error.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_observation.h"
using blink::WebVector;
using blink::WebIDBDatabaseCallbacks;
diff --git a/chromium/content/renderer/indexed_db/indexed_db_dispatcher.cc b/chromium/content/renderer/indexed_db/indexed_db_dispatcher.cc
index 2beba1daad7..5af2a9aec44 100644
--- a/chromium/content/renderer/indexed_db/indexed_db_dispatcher.cc
+++ b/chromium/content/renderer/indexed_db/indexed_db_dispatcher.cc
@@ -12,8 +12,8 @@
#include "content/renderer/indexed_db/indexed_db_key_builders.h"
#include "content/renderer/indexed_db/webidbcursor_impl.h"
#include "ipc/ipc_channel.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBDatabaseCallbacks.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBObservation.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_callbacks.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_observation.h"
using blink::WebIDBKey;
using blink::WebIDBObservation;
diff --git a/chromium/content/renderer/indexed_db/indexed_db_dispatcher.h b/chromium/content/renderer/indexed_db/indexed_db_dispatcher.h
index 633698203b4..71ea1cf67ba 100644
--- a/chromium/content/renderer/indexed_db/indexed_db_dispatcher.h
+++ b/chromium/content/renderer/indexed_db/indexed_db_dispatcher.h
@@ -17,8 +17,8 @@
#include "content/renderer/indexed_db/indexed_db_callbacks_impl.h"
#include "content/renderer/indexed_db/indexed_db_database_callbacks_impl.h"
#include "ipc/ipc_sync_message_filter.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBCallbacks.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBTypes.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_callbacks.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_types.h"
#include "url/origin.h"
namespace content {
diff --git a/chromium/content/renderer/indexed_db/indexed_db_key_builders.cc b/chromium/content/renderer/indexed_db/indexed_db_key_builders.cc
index bf0af1249d1..657655fe7b5 100644
--- a/chromium/content/renderer/indexed_db/indexed_db_key_builders.cc
+++ b/chromium/content/renderer/indexed_db/indexed_db_key_builders.cc
@@ -11,12 +11,12 @@
#include <vector>
#include "base/logging.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebVector.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBKey.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBKeyPath.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBKeyRange.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBTypes.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_key.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_key_path.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_key_range.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_types.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_vector.h"
using blink::WebIDBKey;
using blink::WebIDBKeyRange;
diff --git a/chromium/content/renderer/indexed_db/indexed_db_key_builders.h b/chromium/content/renderer/indexed_db/indexed_db_key_builders.h
index c3a212bddad..7462d8dc7fd 100644
--- a/chromium/content/renderer/indexed_db/indexed_db_key_builders.h
+++ b/chromium/content/renderer/indexed_db/indexed_db_key_builders.h
@@ -10,7 +10,7 @@
#include "content/common/indexed_db/indexed_db_key.h"
#include "content/common/indexed_db/indexed_db_key_path.h"
#include "content/common/indexed_db/indexed_db_key_range.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBKey.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_key.h"
namespace blink {
diff --git a/chromium/content/renderer/indexed_db/mock_webidbcallbacks.h b/chromium/content/renderer/indexed_db/mock_webidbcallbacks.h
index 523cbb570ae..aa59e310a73 100644
--- a/chromium/content/renderer/indexed_db/mock_webidbcallbacks.h
+++ b/chromium/content/renderer/indexed_db/mock_webidbcallbacks.h
@@ -7,12 +7,12 @@
#include "base/macros.h"
#include "testing/gmock/include/gmock/gmock.h"
-#include "third_party/WebKit/public/platform/WebBlobInfo.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBCallbacks.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBDatabaseError.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBMetadata.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBValue.h"
-#include "third_party/WebKit/public/web/WebHeap.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_callbacks.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_error.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_metadata.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_value.h"
+#include "third_party/blink/public/platform/web_blob_info.h"
+#include "third_party/blink/public/web/web_heap.h"
namespace content {
diff --git a/chromium/content/renderer/indexed_db/webidbcursor_impl.cc b/chromium/content/renderer/indexed_db/webidbcursor_impl.cc
index 57ed3b3679b..62811b6fd76 100644
--- a/chromium/content/renderer/indexed_db/webidbcursor_impl.cc
+++ b/chromium/content/renderer/indexed_db/webidbcursor_impl.cc
@@ -9,11 +9,10 @@
#include <string>
#include <vector>
-#include "base/memory/ptr_util.h"
#include "content/renderer/indexed_db/indexed_db_dispatcher.h"
#include "content/renderer/indexed_db/indexed_db_key_builders.h"
#include "mojo/public/cpp/bindings/strong_associated_binding.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBValue.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_value.h"
using blink::WebBlobInfo;
using blink::WebData;
@@ -28,7 +27,8 @@ namespace content {
class WebIDBCursorImpl::IOThreadHelper {
public:
- IOThreadHelper();
+ explicit IOThreadHelper(
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner);
~IOThreadHelper();
void Bind(CursorAssociatedPtrInfo cursor_info);
@@ -46,6 +46,7 @@ class WebIDBCursorImpl::IOThreadHelper {
std::unique_ptr<IndexedDBCallbacksImpl> callbacks);
indexed_db::mojom::CursorAssociatedPtr cursor_;
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
DISALLOW_COPY_AND_ASSIGN(IOThreadHelper);
};
@@ -56,7 +57,7 @@ WebIDBCursorImpl::WebIDBCursorImpl(
scoped_refptr<base::SingleThreadTaskRunner> io_runner,
scoped_refptr<base::SingleThreadTaskRunner> callback_runner)
: transaction_id_(transaction_id),
- helper_(new IOThreadHelper()),
+ helper_(new IOThreadHelper(io_runner)),
io_runner_(std::move(io_runner)),
callback_runner_(std::move(callback_runner)),
continue_count_(0),
@@ -250,13 +251,15 @@ void WebIDBCursorImpl::ResetPrefetchCache() {
pending_onsuccess_callbacks_ = 0;
}
-WebIDBCursorImpl::IOThreadHelper::IOThreadHelper() {}
+WebIDBCursorImpl::IOThreadHelper::IOThreadHelper(
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner)
+ : task_runner_(std::move(task_runner)) {}
WebIDBCursorImpl::IOThreadHelper::~IOThreadHelper() {}
void WebIDBCursorImpl::IOThreadHelper::Bind(
CursorAssociatedPtrInfo cursor_info) {
- cursor_.Bind(std::move(cursor_info));
+ cursor_.Bind(std::move(cursor_info), task_runner_);
}
void WebIDBCursorImpl::IOThreadHelper::Advance(
diff --git a/chromium/content/renderer/indexed_db/webidbcursor_impl.h b/chromium/content/renderer/indexed_db/webidbcursor_impl.h
index a668f9a7db4..3a6778ed013 100644
--- a/chromium/content/renderer/indexed_db/webidbcursor_impl.h
+++ b/chromium/content/renderer/indexed_db/webidbcursor_impl.h
@@ -16,10 +16,10 @@
#include "content/common/content_export.h"
#include "content/common/indexed_db/indexed_db.mojom.h"
#include "content/common/indexed_db/indexed_db_key.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBCallbacks.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBCursor.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBKey.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBValue.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_callbacks.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_cursor.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_key.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_value.h"
namespace base {
class SingleThreadTaskRunner;
diff --git a/chromium/content/renderer/indexed_db/webidbcursor_impl_unittest.cc b/chromium/content/renderer/indexed_db/webidbcursor_impl_unittest.cc
index 30b752551b0..eec2bbac8f4 100644
--- a/chromium/content/renderer/indexed_db/webidbcursor_impl_unittest.cc
+++ b/chromium/content/renderer/indexed_db/webidbcursor_impl_unittest.cc
@@ -11,7 +11,6 @@
#include "base/guid.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/test/scoped_task_environment.h"
#include "base/threading/thread_task_runner_handle.h"
@@ -22,8 +21,8 @@
#include "content/renderer/indexed_db/mock_webidbcallbacks.h"
#include "mojo/public/cpp/bindings/associated_binding.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebData.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/web_data.h"
using blink::WebBlobInfo;
using blink::WebData;
diff --git a/chromium/content/renderer/indexed_db/webidbdatabase_impl.cc b/chromium/content/renderer/indexed_db/webidbdatabase_impl.cc
index 8766e3687c7..711dc4aee37 100644
--- a/chromium/content/renderer/indexed_db/webidbdatabase_impl.cc
+++ b/chromium/content/renderer/indexed_db/webidbdatabase_impl.cc
@@ -17,14 +17,14 @@
#include "content/renderer/indexed_db/indexed_db_dispatcher.h"
#include "content/renderer/indexed_db/indexed_db_key_builders.h"
#include "mojo/public/cpp/bindings/strong_associated_binding.h"
-#include "third_party/WebKit/public/platform/FilePathConversion.h"
-#include "third_party/WebKit/public/platform/WebBlobInfo.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebVector.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBDatabaseError.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBDatabaseException.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBKeyPath.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBMetadata.h"
+#include "third_party/blink/public/platform/file_path_conversion.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_error.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_exception.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_key_path.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_metadata.h"
+#include "third_party/blink/public/platform/web_blob_info.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_vector.h"
using blink::WebBlobInfo;
using blink::WebIDBCallbacks;
@@ -64,7 +64,8 @@ std::vector<content::IndexedDBIndexKeys> ConvertWebIndexKeys(
class WebIDBDatabaseImpl::IOThreadHelper {
public:
- IOThreadHelper();
+ explicit IOThreadHelper(
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner);
~IOThreadHelper();
void Bind(DatabaseAssociatedPtrInfo database_info);
@@ -158,6 +159,7 @@ class WebIDBDatabaseImpl::IOThreadHelper {
std::unique_ptr<IndexedDBCallbacksImpl> callbacks);
indexed_db::mojom::DatabaseAssociatedPtr database_;
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
DISALLOW_COPY_AND_ASSIGN(IOThreadHelper);
};
@@ -166,7 +168,7 @@ WebIDBDatabaseImpl::WebIDBDatabaseImpl(
DatabaseAssociatedPtrInfo database_info,
scoped_refptr<base::SingleThreadTaskRunner> io_runner,
scoped_refptr<base::SingleThreadTaskRunner> callback_runner)
- : helper_(new IOThreadHelper()),
+ : helper_(new IOThreadHelper(io_runner)),
io_runner_(std::move(io_runner)),
callback_runner_(std::move(callback_runner)) {
io_runner_->PostTask(FROM_HERE, base::BindOnce(&IOThreadHelper::Bind,
@@ -525,13 +527,15 @@ void WebIDBDatabaseImpl::Commit(long long transaction_id) {
base::Unretained(helper_), transaction_id));
}
-WebIDBDatabaseImpl::IOThreadHelper::IOThreadHelper() {}
+WebIDBDatabaseImpl::IOThreadHelper::IOThreadHelper(
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner)
+ : task_runner_(std::move(task_runner)) {}
WebIDBDatabaseImpl::IOThreadHelper::~IOThreadHelper() {}
void WebIDBDatabaseImpl::IOThreadHelper::Bind(
DatabaseAssociatedPtrInfo database_info) {
- database_.Bind(std::move(database_info));
+ database_.Bind(std::move(database_info), task_runner_);
}
void WebIDBDatabaseImpl::IOThreadHelper::CreateObjectStore(
diff --git a/chromium/content/renderer/indexed_db/webidbdatabase_impl.h b/chromium/content/renderer/indexed_db/webidbdatabase_impl.h
index 2dd5ada9f4b..dfe7649639f 100644
--- a/chromium/content/renderer/indexed_db/webidbdatabase_impl.h
+++ b/chromium/content/renderer/indexed_db/webidbdatabase_impl.h
@@ -14,9 +14,9 @@
#include "content/common/content_export.h"
#include "content/common/indexed_db/indexed_db.mojom.h"
#include "content/common/indexed_db/indexed_db_constants.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBCursor.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBDatabase.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBTypes.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_cursor.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_types.h"
namespace blink {
class WebBlobInfo;
diff --git a/chromium/content/renderer/indexed_db/webidbdatabase_impl_unittest.cc b/chromium/content/renderer/indexed_db/webidbdatabase_impl_unittest.cc
index 244daba55b7..31b31f6bf3e 100644
--- a/chromium/content/renderer/indexed_db/webidbdatabase_impl_unittest.cc
+++ b/chromium/content/renderer/indexed_db/webidbdatabase_impl_unittest.cc
@@ -15,10 +15,10 @@
#include "content/renderer/indexed_db/mock_webidbcallbacks.h"
#include "content/renderer/indexed_db/webidbdatabase_impl.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebBlobInfo.h"
-#include "third_party/WebKit/public/platform/WebData.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
-#include "third_party/WebKit/public/web/WebHeap.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/web_blob_info.h"
+#include "third_party/blink/public/platform/web_data.h"
+#include "third_party/blink/public/web/web_heap.h"
using blink::WebBlobInfo;
using blink::WebData;
diff --git a/chromium/content/renderer/indexed_db/webidbfactory_impl.cc b/chromium/content/renderer/indexed_db/webidbfactory_impl.cc
index d84706baf99..753c35a361f 100644
--- a/chromium/content/renderer/indexed_db/webidbfactory_impl.cc
+++ b/chromium/content/renderer/indexed_db/webidbfactory_impl.cc
@@ -10,8 +10,8 @@
#include "content/renderer/storage_util.h"
#include "ipc/ipc_sync_channel.h"
#include "mojo/public/cpp/bindings/strong_associated_binding.h"
-#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
-#include "third_party/WebKit/public/platform/WebString.h"
+#include "third_party/blink/public/platform/web_security_origin.h"
+#include "third_party/blink/public/platform/web_string.h"
using blink::WebIDBCallbacks;
using blink::WebIDBDatabase;
diff --git a/chromium/content/renderer/indexed_db/webidbfactory_impl.h b/chromium/content/renderer/indexed_db/webidbfactory_impl.h
index 13df6e05986..5195900dd61 100644
--- a/chromium/content/renderer/indexed_db/webidbfactory_impl.h
+++ b/chromium/content/renderer/indexed_db/webidbfactory_impl.h
@@ -8,9 +8,9 @@
#include "base/memory/ref_counted.h"
#include "base/single_thread_task_runner.h"
#include "content/common/indexed_db/indexed_db.mojom.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBCallbacks.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBDatabaseCallbacks.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBFactory.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_callbacks.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_callbacks.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_factory.h"
namespace blink {
class WebSecurityOrigin;
diff --git a/chromium/content/renderer/input/frame_input_handler_impl.cc b/chromium/content/renderer/input/frame_input_handler_impl.cc
index 45bba34d500..9b82d364e8d 100644
--- a/chromium/content/renderer/input/frame_input_handler_impl.cc
+++ b/chromium/content/renderer/input/frame_input_handler_impl.cc
@@ -16,8 +16,8 @@
#include "content/renderer/render_thread_impl.h"
#include "content/renderer/render_view_impl.h"
#include "content/renderer/render_widget.h"
-#include "third_party/WebKit/public/web/WebInputMethodController.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "third_party/blink/public/web/web_input_method_controller.h"
+#include "third_party/blink/public/web/web_local_frame.h"
namespace content {
@@ -80,19 +80,9 @@ void FrameInputHandlerImpl::SetCompositionFromExistingText(
return;
ImeEventGuard guard(render_frame_->GetRenderWidget());
- std::vector<blink::WebImeTextSpan> ime_text_spans;
- for (const auto& ime_text_span : ui_ime_text_spans) {
- blink::WebImeTextSpan blink_ime_text_span(
- ConvertUiImeTextSpanTypeToWebType(ime_text_span.type),
- ime_text_span.start_offset, ime_text_span.end_offset,
- ime_text_span.underline_color, ime_text_span.thick,
- ime_text_span.background_color,
- ime_text_span.suggestion_highlight_color, ime_text_span.suggestions);
- ime_text_spans.push_back(blink_ime_text_span);
- }
- render_frame_->GetWebFrame()->SetCompositionFromExistingText(start, end,
- ime_text_spans);
+ render_frame_->GetWebFrame()->SetCompositionFromExistingText(
+ start, end, ConvertUiImeTextSpansToBlinkImeTextSpans(ui_ime_text_spans));
}
void FrameInputHandlerImpl::ExtendSelectionAndDelete(int32_t before,
diff --git a/chromium/content/renderer/input/input_event_filter.cc b/chromium/content/renderer/input/input_event_filter.cc
index 13fe23edec1..60eeab1818d 100644
--- a/chromium/content/renderer/input/input_event_filter.cc
+++ b/chromium/content/renderer/input/input_event_filter.cc
@@ -11,7 +11,6 @@
#include "base/bind.h"
#include "base/debug/crash_logging.h"
#include "base/location.h"
-#include "base/memory/ptr_util.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/trace_event/trace_event.h"
@@ -87,6 +86,11 @@ void InputEventFilter::DidStopFlinging(int routing_id) {
SendMessage(std::make_unique<InputHostMsg_DidStopFlinging>(routing_id));
}
+void InputEventFilter::DidStartScrollingViewport(int routing_id) {
+ SendMessage(
+ std::make_unique<InputHostMsg_DidStartScrollingViewport>(routing_id));
+}
+
void InputEventFilter::QueueClosureForMainThreadEventQueue(
int routing_id,
const base::Closure& closure) {
diff --git a/chromium/content/renderer/input/input_event_filter.h b/chromium/content/renderer/input/input_event_filter.h
index ae0ab45897c..d09f6a102c8 100644
--- a/chromium/content/renderer/input/input_event_filter.h
+++ b/chromium/content/renderer/input/input_event_filter.h
@@ -16,7 +16,7 @@
#include "content/renderer/input/input_handler_manager_client.h"
#include "content/renderer/input/main_thread_event_queue.h"
#include "ipc/message_filter.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
namespace base {
class SingleThreadTaskRunner;
@@ -73,6 +73,7 @@ class CONTENT_EXPORT InputEventFilter : public InputHandlerManagerClient,
void DidOverscroll(int routing_id,
const ui::DidOverscrollParams& params) override;
void DidStopFlinging(int routing_id) override;
+ void DidStartScrollingViewport(int routing_id) override;
void DispatchNonBlockingEventToMainThread(
int routing_id,
ui::WebScopedInputEvent event,
diff --git a/chromium/content/renderer/input/input_event_filter_unittest.cc b/chromium/content/renderer/input/input_event_filter_unittest.cc
index a3cf3f68bce..05aa374836a 100644
--- a/chromium/content/renderer/input/input_event_filter_unittest.cc
+++ b/chromium/content/renderer/input/input_event_filter_unittest.cc
@@ -11,7 +11,6 @@
#include "base/bind.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/test/scoped_task_environment.h"
#include "base/test/test_simple_task_runner.h"
@@ -27,7 +26,7 @@
#include "ipc/ipc_test_sink.h"
#include "ipc/message_filter.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/scheduler/test/mock_renderer_scheduler.h"
+#include "third_party/blink/public/platform/scheduler/test/mock_renderer_scheduler.h"
#include "ui/events/blink/web_input_event_traits.h"
using blink::WebInputEvent;
diff --git a/chromium/content/renderer/input/input_handler_manager.cc b/chromium/content/renderer/input/input_handler_manager.cc
index f21b297e57e..e164e177d0e 100644
--- a/chromium/content/renderer/input/input_handler_manager.cc
+++ b/chromium/content/renderer/input/input_handler_manager.cc
@@ -15,14 +15,14 @@
#include "content/renderer/input/input_event_filter.h"
#include "content/renderer/input/input_handler_manager_client.h"
#include "content/renderer/input/input_handler_wrapper.h"
-#include "third_party/WebKit/public/platform/scheduler/renderer/renderer_scheduler.h"
+#include "third_party/blink/public/platform/scheduler/web_main_thread_scheduler.h"
#include "ui/events/blink/did_overscroll_params.h"
#include "ui/events/blink/input_handler_proxy.h"
#include "ui/events/blink/web_input_event_traits.h"
using blink::WebInputEvent;
using ui::InputHandlerProxy;
-using blink::scheduler::RendererScheduler;
+using blink::scheduler::WebMainThreadScheduler;
namespace content {
@@ -50,11 +50,11 @@ InputHandlerManager::InputHandlerManager(
const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
InputHandlerManagerClient* client,
SynchronousInputHandlerProxyClient* sync_handler_client,
- blink::scheduler::RendererScheduler* renderer_scheduler)
+ blink::scheduler::WebMainThreadScheduler* main_thread_scheduler)
: task_runner_(task_runner),
client_(client),
synchronous_handler_proxy_client_(sync_handler_client),
- renderer_scheduler_(renderer_scheduler),
+ main_thread_scheduler_(main_thread_scheduler),
weak_ptr_factory_(this) {
DCHECK(client_);
client_->SetInputHandlerManager(this);
@@ -244,15 +244,15 @@ void InputHandlerManager::DidHandleInputEventAndOverscroll(
InputEventDispositionToAck(event_disposition);
switch (input_event_ack_state) {
case INPUT_EVENT_ACK_STATE_CONSUMED:
- renderer_scheduler_->DidHandleInputEventOnCompositorThread(
- *input_event,
- RendererScheduler::InputEventState::EVENT_CONSUMED_BY_COMPOSITOR);
+ main_thread_scheduler_->DidHandleInputEventOnCompositorThread(
+ *input_event, WebMainThreadScheduler::InputEventState::
+ EVENT_CONSUMED_BY_COMPOSITOR);
break;
case INPUT_EVENT_ACK_STATE_NOT_CONSUMED:
case INPUT_EVENT_ACK_STATE_SET_NON_BLOCKING_DUE_TO_FLING:
- renderer_scheduler_->DidHandleInputEventOnCompositorThread(
- *input_event,
- RendererScheduler::InputEventState::EVENT_FORWARDED_TO_MAIN_THREAD);
+ main_thread_scheduler_->DidHandleInputEventOnCompositorThread(
+ *input_event, WebMainThreadScheduler::InputEventState::
+ EVENT_FORWARDED_TO_MAIN_THREAD);
break;
default:
break;
@@ -271,7 +271,11 @@ void InputHandlerManager::DidStopFlinging(int routing_id) {
}
void InputHandlerManager::DidAnimateForInput() {
- renderer_scheduler_->DidAnimateForInputOnCompositorThread();
+ main_thread_scheduler_->DidAnimateForInputOnCompositorThread();
+}
+
+void InputHandlerManager::DidStartScrollingViewport(int routing_id) {
+ client_->DidStartScrollingViewport(routing_id);
}
void InputHandlerManager::DispatchNonBlockingEventToMainThread(
diff --git a/chromium/content/renderer/input/input_handler_manager.h b/chromium/content/renderer/input/input_handler_manager.h
index 40e32e671d2..0412791f3e7 100644
--- a/chromium/content/renderer/input/input_handler_manager.h
+++ b/chromium/content/renderer/input/input_handler_manager.h
@@ -29,7 +29,7 @@ class WebMouseWheelEvent;
namespace blink {
namespace scheduler {
-class RendererScheduler;
+class WebMainThreadScheduler;
}
}
@@ -59,7 +59,7 @@ class CONTENT_EXPORT InputHandlerManager {
const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
InputHandlerManagerClient* client,
SynchronousInputHandlerProxyClient* sync_handler_client,
- blink::scheduler::RendererScheduler* renderer_scheduler);
+ blink::scheduler::WebMainThreadScheduler* main_thread_scheduler);
virtual ~InputHandlerManager();
// Callable from the main thread only.
@@ -110,6 +110,9 @@ class CONTENT_EXPORT InputHandlerManager {
void DidAnimateForInput();
// Called from the compositor's thread.
+ void DidStartScrollingViewport(int routing_id);
+
+ // Called from the compositor's thread.
void DispatchNonBlockingEventToMainThread(
int routing_id,
ui::WebScopedInputEvent event,
@@ -160,7 +163,9 @@ class CONTENT_EXPORT InputHandlerManager {
InputHandlerManagerClient* const client_;
// May be null.
SynchronousInputHandlerProxyClient* const synchronous_handler_proxy_client_;
- blink::scheduler::RendererScheduler* const renderer_scheduler_; // Not owned.
+
+ // Not owned.
+ blink::scheduler::WebMainThreadScheduler* const main_thread_scheduler_;
base::WeakPtrFactory<InputHandlerManager> weak_ptr_factory_;
};
diff --git a/chromium/content/renderer/input/input_handler_manager_client.h b/chromium/content/renderer/input/input_handler_manager_client.h
index c155b0a3320..7793a656c17 100644
--- a/chromium/content/renderer/input/input_handler_manager_client.h
+++ b/chromium/content/renderer/input/input_handler_manager_client.h
@@ -11,7 +11,7 @@
#include "cc/input/touch_action.h"
#include "content/common/content_export.h"
#include "content/public/common/input_event_ack_state.h"
-#include "third_party/WebKit/public/platform/WebInputEventResult.h"
+#include "third_party/blink/public/platform/web_input_event_result.h"
#include "ui/events/blink/web_input_event_traits.h"
#include "ui/gfx/geometry/vector2d_f.h"
@@ -50,6 +50,7 @@ class CONTENT_EXPORT InputHandlerManagerClient {
virtual void DidOverscroll(int routing_id,
const ui::DidOverscrollParams& params) = 0;
virtual void DidStopFlinging(int routing_id) = 0;
+ virtual void DidStartScrollingViewport(int routing_id) = 0;
virtual void DispatchNonBlockingEventToMainThread(
int routing_id,
ui::WebScopedInputEvent event,
diff --git a/chromium/content/renderer/input/input_handler_wrapper.cc b/chromium/content/renderer/input/input_handler_wrapper.cc
index 4e5ed8bfb53..55dd6040b5e 100644
--- a/chromium/content/renderer/input/input_handler_wrapper.cc
+++ b/chromium/content/renderer/input/input_handler_wrapper.cc
@@ -10,7 +10,7 @@
#include "content/public/common/content_switches.h"
#include "content/renderer/input/input_event_filter.h"
#include "content/renderer/input/input_handler_manager.h"
-#include "third_party/WebKit/public/platform/Platform.h"
+#include "third_party/blink/public/platform/platform.h"
#include "ui/events/blink/did_overscroll_params.h"
namespace content {
@@ -88,6 +88,10 @@ void InputHandlerWrapper::DidAnimateForInput() {
input_handler_manager_->DidAnimateForInput();
}
+void InputHandlerWrapper::DidStartScrollingViewport() {
+ input_handler_manager_->DidStartScrollingViewport(routing_id_);
+}
+
void InputHandlerWrapper::GenerateScrollBeginAndSendToMainThread(
const blink::WebGestureEvent& update_event) {
DCHECK_EQ(update_event.GetType(), blink::WebInputEvent::kGestureScrollUpdate);
diff --git a/chromium/content/renderer/input/input_handler_wrapper.h b/chromium/content/renderer/input/input_handler_wrapper.h
index e5ddaad794c..3f6484f1ca8 100644
--- a/chromium/content/renderer/input/input_handler_wrapper.h
+++ b/chromium/content/renderer/input/input_handler_wrapper.h
@@ -55,6 +55,7 @@ class InputHandlerWrapper : public ui::InputHandlerProxyClient {
const cc::OverscrollBehavior& overscroll_behavior) override;
void DidStopFlinging() override;
void DidAnimateForInput() override;
+ void DidStartScrollingViewport() override;
void GenerateScrollBeginAndSendToMainThread(
const blink::WebGestureEvent& update_event) override;
void SetWhiteListedTouchAction(
diff --git a/chromium/content/renderer/input/main_thread_event_queue.cc b/chromium/content/renderer/input/main_thread_event_queue.cc
index b14c6a1c4dd..9fcfca7d741 100644
--- a/chromium/content/renderer/input/main_thread_event_queue.cc
+++ b/chromium/content/renderer/input/main_thread_event_queue.cc
@@ -97,13 +97,6 @@ class QueuedWebInputEvent : public ScopedWebInputEventWithLatencyInfo,
bool IsWebInputEvent() const override { return true; }
void Dispatch(MainThreadEventQueue* queue) override {
- // Report the coalesced count only for continuous events; otherwise
- // the zero value would be dominated by non-continuous events.
- if (IsContinuousEvent()) {
- UMA_HISTOGRAM_COUNTS_1000("Event.MainThreadEventQueue.CoalescedCount",
- coalescedCount());
- }
-
HandledEventCallback callback =
base::BindOnce(&QueuedWebInputEvent::HandledEvent,
base::Unretained(this), base::RetainedRef(queue));
@@ -133,11 +126,11 @@ class QueuedWebInputEvent : public ScopedWebInputEventWithLatencyInfo,
}
size_t num_events_handled = 1 + blocking_coalesced_callbacks_.size();
- if (queue->renderer_scheduler_) {
+ if (queue->main_thread_scheduler_) {
// TODO(dtapuska): Change the scheduler API to take into account number of
// events processed.
for (size_t i = 0; i < num_events_handled; ++i) {
- queue->renderer_scheduler_->DidHandleInputEventOnMainThread(
+ queue->main_thread_scheduler_->DidHandleInputEventOnMainThread(
event(), ack_result == INPUT_EVENT_ACK_STATE_CONSUMED
? blink::WebInputEventResult::kHandledApplication
: blink::WebInputEventResult::kNotHandled);
@@ -214,7 +207,7 @@ MainThreadEventQueue::SharedState::~SharedState() {}
MainThreadEventQueue::MainThreadEventQueue(
MainThreadEventQueueClient* client,
const scoped_refptr<base::SingleThreadTaskRunner>& main_task_runner,
- blink::scheduler::RendererScheduler* renderer_scheduler,
+ blink::scheduler::WebMainThreadScheduler* main_thread_scheduler,
bool allow_raf_aligned_input)
: client_(client),
last_touch_start_forced_nonblocking_due_to_fling_(false),
@@ -226,7 +219,7 @@ MainThreadEventQueue::MainThreadEventQueue(
needs_low_latency_(false),
allow_raf_aligned_input_(allow_raf_aligned_input),
main_task_runner_(main_task_runner),
- renderer_scheduler_(renderer_scheduler),
+ main_thread_scheduler_(main_thread_scheduler),
use_raf_fallback_timer_(true) {
if (enable_non_blocking_due_to_main_thread_responsiveness_flag_) {
std::string group = base::FieldTrialList::FindFullName(
@@ -302,7 +295,7 @@ void MainThreadEventQueue::HandleEvent(
if (enable_non_blocking_due_to_main_thread_responsiveness_flag_ &&
touch_event->dispatch_type == blink::WebInputEvent::kBlocking) {
bool passive_due_to_unresponsive_main =
- renderer_scheduler_->MainThreadSeemsUnresponsive(
+ main_thread_scheduler_->MainThreadSeemsUnresponsive(
main_thread_responsiveness_threshold_);
if (passive_due_to_unresponsive_main) {
touch_event->dispatch_type = blink::WebInputEvent::
diff --git a/chromium/content/renderer/input/main_thread_event_queue.h b/chromium/content/renderer/input/main_thread_event_queue.h
index 509609b119e..ba7c4100ab7 100644
--- a/chromium/content/renderer/input/main_thread_event_queue.h
+++ b/chromium/content/renderer/input/main_thread_event_queue.h
@@ -15,8 +15,8 @@
#include "content/public/common/input_event_ack_state.h"
#include "content/renderer/input/main_thread_event_queue_task_list.h"
#include "content/renderer/input/scoped_web_input_event_with_latency_info.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
-#include "third_party/WebKit/public/platform/scheduler/renderer/renderer_scheduler.h"
+#include "third_party/blink/public/platform/scheduler/web_main_thread_scheduler.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#include "ui/events/blink/did_overscroll_params.h"
#include "ui/events/blink/web_input_event_traits.h"
#include "ui/latency/latency_info.h"
@@ -84,7 +84,7 @@ class CONTENT_EXPORT MainThreadEventQueue
MainThreadEventQueue(
MainThreadEventQueueClient* client,
const scoped_refptr<base::SingleThreadTaskRunner>& main_task_runner,
- blink::scheduler::RendererScheduler* renderer_scheduler,
+ blink::scheduler::WebMainThreadScheduler* main_thread_scheduler,
bool allow_raf_aligned_input);
// Called once the compositor has handled |event| and indicated that it is
@@ -153,7 +153,7 @@ class CONTENT_EXPORT MainThreadEventQueue
SharedState shared_state_;
scoped_refptr<base::SingleThreadTaskRunner> main_task_runner_;
- blink::scheduler::RendererScheduler* renderer_scheduler_;
+ blink::scheduler::WebMainThreadScheduler* main_thread_scheduler_;
base::OneShotTimer raf_fallback_timer_;
bool use_raf_fallback_timer_;
diff --git a/chromium/content/renderer/input/main_thread_event_queue_task.h b/chromium/content/renderer/input/main_thread_event_queue_task.h
index f41552a280b..7702e79d9a7 100644
--- a/chromium/content/renderer/input/main_thread_event_queue_task.h
+++ b/chromium/content/renderer/input/main_thread_event_queue_task.h
@@ -6,8 +6,8 @@
#define CONTENT_RENDERER_INPUT_MAIN_THREAD_EVENT_QUEUE_TASK_H_
#include "content/public/common/input_event_ack_state.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
-#include "third_party/WebKit/public/platform/scheduler/renderer/renderer_scheduler.h"
+#include "third_party/blink/public/platform/scheduler/web_main_thread_scheduler.h"
+#include "third_party/blink/public/platform/web_input_event.h"
namespace content {
diff --git a/chromium/content/renderer/input/main_thread_event_queue_unittest.cc b/chromium/content/renderer/input/main_thread_event_queue_unittest.cc
index aa33593c59f..d20c99eee70 100644
--- a/chromium/content/renderer/input/main_thread_event_queue_unittest.cc
+++ b/chromium/content/renderer/input/main_thread_event_queue_unittest.cc
@@ -13,7 +13,6 @@
#include "base/metrics/field_trial.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
-#include "base/test/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/test_simple_task_runner.h"
#include "build/build_config.h"
@@ -21,7 +20,7 @@
#include "content/renderer/input/main_thread_event_queue.h"
#include "content/renderer/render_thread_impl.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/scheduler/test/mock_renderer_scheduler.h"
+#include "third_party/blink/public/platform/scheduler/test/mock_renderer_scheduler.h"
using blink::WebInputEvent;
using blink::WebMouseEvent;
@@ -44,9 +43,6 @@ namespace {
// Simulate a 16ms frame signal.
const base::TimeDelta kFrameInterval = base::TimeDelta::FromMilliseconds(16);
-const char* kCoalescedCountHistogram =
- "Event.MainThreadEventQueue.CoalescedCount";
-
} // namespace
class HandledTask {
@@ -251,8 +247,6 @@ class MainThreadEventQueueTest : public testing::Test,
};
TEST_F(MainThreadEventQueueTest, NonBlockingWheel) {
- base::HistogramTester histogram_tester;
-
WebMouseWheelEvent kEvents[4] = {
SyntheticWebMouseWheelEventBuilder::Build(10, 10, 0, 53, 0, false),
SyntheticWebMouseWheelEventBuilder::Build(20, 20, 0, 53, 0, false),
@@ -346,13 +340,9 @@ TEST_F(MainThreadEventQueueTest, NonBlockingWheel) {
WebInputEvent::DispatchType::kListenersNonBlockingPassive;
EXPECT_EQ(coalesced_event, *coalesced_wheel_event1);
}
-
- histogram_tester.ExpectUniqueSample(kCoalescedCountHistogram, 1, 2);
}
TEST_F(MainThreadEventQueueTest, NonBlockingTouch) {
- base::HistogramTester histogram_tester;
-
EXPECT_CALL(renderer_scheduler_,
DidHandleInputEventOnMainThread(testing::_, testing::_))
.Times(3);
@@ -446,13 +436,9 @@ TEST_F(MainThreadEventQueueTest, NonBlockingTouch) {
WebInputEvent::DispatchType::kListenersNonBlockingPassive;
EXPECT_EQ(coalesced_event, *coalesced_touch_event1);
}
-
- histogram_tester.ExpectBucketCount(kCoalescedCountHistogram, 0, 1);
- histogram_tester.ExpectBucketCount(kCoalescedCountHistogram, 1, 1);
}
TEST_F(MainThreadEventQueueTest, BlockingTouch) {
- base::HistogramTester histogram_tester;
SyntheticWebTouchEvent kEvents[4];
kEvents[0].PressPoint(10, 10);
kEvents[1].PressPoint(10, 10);
@@ -503,7 +489,6 @@ TEST_F(MainThreadEventQueueTest, BlockingTouch) {
EXPECT_THAT(GetAndResetCallbackResults(),
testing::Each(ReceivedCallback(
CallbackReceivedState::kCalledWhileHandlingEvent, false)));
- histogram_tester.ExpectUniqueSample(kCoalescedCountHistogram, 2, 2);
}
TEST_F(MainThreadEventQueueTest, InterleavedEvents) {
diff --git a/chromium/content/renderer/input/render_widget_input_handler.cc b/chromium/content/renderer/input/render_widget_input_handler.cc
index ab2968bbb44..fb0305ccf5e 100644
--- a/chromium/content/renderer/input/render_widget_input_handler.cc
+++ b/chromium/content/renderer/input/render_widget_input_handler.cc
@@ -25,18 +25,18 @@
#include "content/renderer/render_frame_proxy.h"
#include "content/renderer/render_thread_impl.h"
#include "content/renderer/render_widget.h"
-#include "third_party/WebKit/public/platform/WebFloatPoint.h"
-#include "third_party/WebKit/public/platform/WebFloatSize.h"
-#include "third_party/WebKit/public/platform/WebGestureEvent.h"
-#include "third_party/WebKit/public/platform/WebKeyboardEvent.h"
-#include "third_party/WebKit/public/platform/WebMouseWheelEvent.h"
-#include "third_party/WebKit/public/platform/WebPointerEvent.h"
-#include "third_party/WebKit/public/platform/WebTouchEvent.h"
-#include "third_party/WebKit/public/platform/scheduler/renderer/renderer_scheduler.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebFrameWidget.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebNode.h"
+#include "third_party/blink/public/platform/scheduler/web_main_thread_scheduler.h"
+#include "third_party/blink/public/platform/web_float_point.h"
+#include "third_party/blink/public/platform/web_float_size.h"
+#include "third_party/blink/public/platform/web_gesture_event.h"
+#include "third_party/blink/public/platform/web_keyboard_event.h"
+#include "third_party/blink/public/platform/web_mouse_wheel_event.h"
+#include "third_party/blink/public/platform/web_pointer_event.h"
+#include "third_party/blink/public/platform/web_touch_event.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_frame_widget.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_node.h"
#include "ui/events/blink/web_input_event_traits.h"
#include "ui/gfx/geometry/dip_util.h"
#include "ui/gfx/geometry/point_conversions.h"
@@ -320,7 +320,7 @@ void RenderWidgetInputHandler::HandleInputEvent(
if (RenderThreadImpl::current()) {
swap_latency_info.set_expected_queueing_time_on_dispatch(
RenderThreadImpl::current()
- ->GetRendererScheduler()
+ ->GetWebMainThreadScheduler()
->MostRecentExpectedQueueingTime());
}
@@ -415,7 +415,7 @@ void RenderWidgetInputHandler::HandleInputEvent(
input_event.GetType() == WebInputEvent::kGestureScrollUpdate) {
const WebGestureEvent& gesture_event =
static_cast<const WebGestureEvent&>(input_event);
- if (gesture_event.source_device == blink::kWebGestureDeviceTouchpad) {
+ if (gesture_event.SourceDevice() == blink::kWebGestureDeviceTouchpad) {
gfx::Vector2dF latest_overscroll_delta =
event_overscroll ? event_overscroll->latest_overscroll_delta
: gfx::Vector2dF();
diff --git a/chromium/content/renderer/input/render_widget_input_handler.h b/chromium/content/renderer/input/render_widget_input_handler.h
index f54975e8702..ade4fffbffe 100644
--- a/chromium/content/renderer/input/render_widget_input_handler.h
+++ b/chromium/content/renderer/input/render_widget_input_handler.h
@@ -12,7 +12,7 @@
#include "content/common/input/input_event_ack.h"
#include "content/common/input/input_event_dispatch_type.h"
#include "content/renderer/input/main_thread_event_queue.h"
-#include "third_party/WebKit/public/platform/WebCoalescedInputEvent.h"
+#include "third_party/blink/public/platform/web_coalesced_input_event.h"
#include "ui/base/ui_base_types.h"
#include "ui/events/blink/did_overscroll_params.h"
diff --git a/chromium/content/renderer/input/render_widget_input_handler_delegate.h b/chromium/content/renderer/input/render_widget_input_handler_delegate.h
index b9ae5181ef4..8d3e7d4bed2 100644
--- a/chromium/content/renderer/input/render_widget_input_handler_delegate.h
+++ b/chromium/content/renderer/input/render_widget_input_handler_delegate.h
@@ -9,7 +9,7 @@
#include "content/common/content_export.h"
#include "content/common/input/input_event_ack.h"
-#include "third_party/WebKit/public/platform/WebInputEventResult.h"
+#include "third_party/blink/public/platform/web_input_event_result.h"
namespace blink {
class WebGestureEvent;
diff --git a/chromium/content/renderer/input/scoped_web_input_event_with_latency_info.h b/chromium/content/renderer/input/scoped_web_input_event_with_latency_info.h
index 566b31be217..590e9023200 100644
--- a/chromium/content/renderer/input/scoped_web_input_event_with_latency_info.h
+++ b/chromium/content/renderer/input/scoped_web_input_event_with_latency_info.h
@@ -8,10 +8,10 @@
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebCoalescedInputEvent.h"
-#include "third_party/WebKit/public/platform/WebGestureEvent.h"
-#include "third_party/WebKit/public/platform/WebMouseWheelEvent.h"
-#include "third_party/WebKit/public/platform/WebTouchEvent.h"
+#include "third_party/blink/public/platform/web_coalesced_input_event.h"
+#include "third_party/blink/public/platform/web_gesture_event.h"
+#include "third_party/blink/public/platform/web_mouse_wheel_event.h"
+#include "third_party/blink/public/platform/web_touch_event.h"
#include "ui/events/blink/blink_event_util.h"
#include "ui/events/blink/web_input_event_traits.h"
#include "ui/latency/latency_info.h"
diff --git a/chromium/content/renderer/input/widget_input_handler_impl.cc b/chromium/content/renderer/input/widget_input_handler_impl.cc
index 2d0b1d26d10..dd01e03a9f1 100644
--- a/chromium/content/renderer/input/widget_input_handler_impl.cc
+++ b/chromium/content/renderer/input/widget_input_handler_impl.cc
@@ -15,31 +15,16 @@
#include "content/renderer/input/widget_input_handler_manager.h"
#include "content/renderer/render_thread_impl.h"
#include "content/renderer/render_widget.h"
-#include "third_party/WebKit/public/platform/Platform.h"
-#include "third_party/WebKit/public/platform/WebCoalescedInputEvent.h"
-#include "third_party/WebKit/public/platform/WebKeyboardEvent.h"
-#include "third_party/WebKit/public/platform/scheduler/renderer/renderer_scheduler.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "third_party/blink/public/platform/platform.h"
+#include "third_party/blink/public/platform/scheduler/web_main_thread_scheduler.h"
+#include "third_party/blink/public/platform/web_coalesced_input_event.h"
+#include "third_party/blink/public/platform/web_keyboard_event.h"
+#include "third_party/blink/public/web/web_local_frame.h"
namespace content {
namespace {
-std::vector<blink::WebImeTextSpan> ConvertUIImeTextSpansToBlinkImeTextSpans(
- const std::vector<ui::ImeTextSpan>& ui_ime_text_spans) {
- std::vector<blink::WebImeTextSpan> ime_text_spans;
- for (const auto& ime_text_span : ui_ime_text_spans) {
- blink::WebImeTextSpan blink_ime_text_span(
- ConvertUiImeTextSpanTypeToWebType(ime_text_span.type),
- ime_text_span.start_offset, ime_text_span.end_offset,
- ime_text_span.underline_color, ime_text_span.thick,
- ime_text_span.background_color,
- ime_text_span.suggestion_highlight_color, ime_text_span.suggestions);
- ime_text_spans.push_back(blink_ime_text_span);
- }
- return ime_text_spans;
-}
-
void RunClosureIfNotSwappedOut(base::WeakPtr<RenderWidget> render_widget,
base::OnceClosure closure) {
// Input messages must not be processed if the RenderWidget is in swapped out
@@ -111,7 +96,7 @@ void WidgetInputHandlerImpl::ImeSetComposition(
int32_t end) {
RunOnMainThread(
base::BindOnce(&RenderWidget::OnImeSetComposition, render_widget_, text,
- ConvertUIImeTextSpansToBlinkImeTextSpans(ime_text_spans),
+ ConvertUiImeTextSpansToBlinkImeTextSpans(ime_text_spans),
range, start, end));
}
@@ -122,7 +107,7 @@ void WidgetInputHandlerImpl::ImeCommitText(
int32_t relative_cursor_position) {
RunOnMainThread(
base::BindOnce(&RenderWidget::OnImeCommitText, render_widget_, text,
- ConvertUIImeTextSpansToBlinkImeTextSpans(ime_text_spans),
+ ConvertUiImeTextSpansToBlinkImeTextSpans(ime_text_spans),
range, relative_cursor_position));
}
@@ -146,15 +131,15 @@ void WidgetInputHandlerImpl::RequestCompositionUpdates(bool immediate_request,
void WidgetInputHandlerImpl::DispatchEvent(
std::unique_ptr<content::InputEvent> event,
DispatchEventCallback callback) {
- if (!event || !event->web_event) {
- return;
- }
+ TRACE_EVENT0("input", "WidgetInputHandlerImpl::DispatchEvent");
input_handler_manager_->DispatchEvent(std::move(event), std::move(callback));
}
void WidgetInputHandlerImpl::DispatchNonBlockingEvent(
std::unique_ptr<content::InputEvent> event) {
- DispatchEvent(std::move(event), DispatchEventCallback());
+ TRACE_EVENT0("input", "WidgetInputHandlerImpl::DispatchNonBlockingEvent");
+ input_handler_manager_->DispatchEvent(std::move(event),
+ DispatchEventCallback());
}
void WidgetInputHandlerImpl::AttachSynchronousCompositor(
diff --git a/chromium/content/renderer/input/widget_input_handler_manager.cc b/chromium/content/renderer/input/widget_input_handler_manager.cc
index 901295da141..7d07ba3de40 100644
--- a/chromium/content/renderer/input/widget_input_handler_manager.cc
+++ b/chromium/content/renderer/input/widget_input_handler_manager.cc
@@ -15,11 +15,11 @@
#include "content/renderer/input/widget_input_handler_impl.h"
#include "content/renderer/render_thread_impl.h"
#include "content/renderer/render_widget.h"
-#include "third_party/WebKit/public/platform/Platform.h"
-#include "third_party/WebKit/public/platform/WebCoalescedInputEvent.h"
-#include "third_party/WebKit/public/platform/WebKeyboardEvent.h"
-#include "third_party/WebKit/public/platform/scheduler/renderer/renderer_scheduler.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "third_party/blink/public/platform/platform.h"
+#include "third_party/blink/public/platform/scheduler/web_main_thread_scheduler.h"
+#include "third_party/blink/public/platform/web_coalesced_input_event.h"
+#include "third_party/blink/public/platform/web_keyboard_event.h"
+#include "third_party/blink/public/web/web_local_frame.h"
#include "ui/events/base_event_utils.h"
#if defined(OS_ANDROID)
@@ -104,11 +104,11 @@ class SynchronousCompositorProxyRegistry
scoped_refptr<WidgetInputHandlerManager> WidgetInputHandlerManager::Create(
base::WeakPtr<RenderWidget> render_widget,
scoped_refptr<base::SingleThreadTaskRunner> compositor_task_runner,
- blink::scheduler::RendererScheduler* renderer_scheduler) {
+ blink::scheduler::WebMainThreadScheduler* main_thread_scheduler) {
scoped_refptr<WidgetInputHandlerManager> manager =
new WidgetInputHandlerManager(std::move(render_widget),
std::move(compositor_task_runner),
- renderer_scheduler);
+ main_thread_scheduler);
manager->Init();
return manager;
}
@@ -116,9 +116,9 @@ scoped_refptr<WidgetInputHandlerManager> WidgetInputHandlerManager::Create(
WidgetInputHandlerManager::WidgetInputHandlerManager(
base::WeakPtr<RenderWidget> render_widget,
scoped_refptr<base::SingleThreadTaskRunner> compositor_task_runner,
- blink::scheduler::RendererScheduler* renderer_scheduler)
+ blink::scheduler::WebMainThreadScheduler* main_thread_scheduler)
: render_widget_(render_widget),
- renderer_scheduler_(renderer_scheduler),
+ main_thread_scheduler_(main_thread_scheduler),
input_event_queue_(render_widget->GetInputEventQueue()),
main_thread_task_runner_(base::ThreadTaskRunnerHandle::Get()),
compositor_task_runner_(std::move(compositor_task_runner)) {
@@ -241,7 +241,14 @@ void WidgetInputHandlerManager::DidStopFlinging() {
}
void WidgetInputHandlerManager::DidAnimateForInput() {
- renderer_scheduler_->DidAnimateForInputOnCompositorThread();
+ main_thread_scheduler_->DidAnimateForInputOnCompositorThread();
+}
+
+void WidgetInputHandlerManager::DidStartScrollingViewport() {
+ mojom::WidgetInputHandlerHost* host = GetWidgetInputHandlerHost();
+ if (!host)
+ return;
+ host->DidStartScrollingViewport();
}
void WidgetInputHandlerManager::GenerateScrollBeginAndSendToMainThread(
@@ -432,15 +439,15 @@ void WidgetInputHandlerManager::DidHandleInputEventAndOverscroll(
InputEventAckState ack_state = InputEventDispositionToAck(event_disposition);
switch (ack_state) {
case INPUT_EVENT_ACK_STATE_CONSUMED:
- renderer_scheduler_->DidHandleInputEventOnCompositorThread(
- *input_event, blink::scheduler::RendererScheduler::InputEventState::
- EVENT_CONSUMED_BY_COMPOSITOR);
+ main_thread_scheduler_->DidHandleInputEventOnCompositorThread(
+ *input_event, blink::scheduler::WebMainThreadScheduler::
+ InputEventState::EVENT_CONSUMED_BY_COMPOSITOR);
break;
case INPUT_EVENT_ACK_STATE_NOT_CONSUMED:
case INPUT_EVENT_ACK_STATE_SET_NON_BLOCKING_DUE_TO_FLING:
- renderer_scheduler_->DidHandleInputEventOnCompositorThread(
- *input_event, blink::scheduler::RendererScheduler::InputEventState::
- EVENT_FORWARDED_TO_MAIN_THREAD);
+ main_thread_scheduler_->DidHandleInputEventOnCompositorThread(
+ *input_event, blink::scheduler::WebMainThreadScheduler::
+ InputEventState::EVENT_FORWARDED_TO_MAIN_THREAD);
break;
default:
break;
diff --git a/chromium/content/renderer/input/widget_input_handler_manager.h b/chromium/content/renderer/input/widget_input_handler_manager.h
index 0335ed759e2..2102159c579 100644
--- a/chromium/content/renderer/input/widget_input_handler_manager.h
+++ b/chromium/content/renderer/input/widget_input_handler_manager.h
@@ -16,7 +16,7 @@
namespace blink {
namespace scheduler {
-class RendererScheduler;
+class WebMainThreadScheduler;
}; // namespace scheduler
}; // namespace blink
@@ -35,7 +35,7 @@ class CONTENT_EXPORT WidgetInputHandlerManager
static scoped_refptr<WidgetInputHandlerManager> Create(
base::WeakPtr<RenderWidget> render_widget,
scoped_refptr<base::SingleThreadTaskRunner> compositor_task_runner,
- blink::scheduler::RendererScheduler* renderer_scheduler);
+ blink::scheduler::WebMainThreadScheduler* main_thread_scheduler);
void AddAssociatedInterface(
mojom::WidgetInputHandlerAssociatedRequest interface_request,
mojom::WidgetInputHandlerHostPtr host);
@@ -61,6 +61,7 @@ class CONTENT_EXPORT WidgetInputHandlerManager
const cc::OverscrollBehavior& overscroll_behavior) override;
void DidStopFlinging() override;
void DidAnimateForInput() override;
+ void DidStartScrollingViewport() override;
void GenerateScrollBeginAndSendToMainThread(
const blink::WebGestureEvent& update_event) override;
void SetWhiteListedTouchAction(
@@ -96,7 +97,7 @@ class CONTENT_EXPORT WidgetInputHandlerManager
WidgetInputHandlerManager(
base::WeakPtr<RenderWidget> render_widget,
scoped_refptr<base::SingleThreadTaskRunner> compositor_task_runner,
- blink::scheduler::RendererScheduler* renderer_scheduler);
+ blink::scheduler::WebMainThreadScheduler* main_thread_scheduler);
void Init();
void InitOnCompositorThread(
const base::WeakPtr<cc::InputHandler>& input_handler,
@@ -127,7 +128,7 @@ class CONTENT_EXPORT WidgetInputHandlerManager
// Only valid to be called on the main thread.
base::WeakPtr<RenderWidget> render_widget_;
- blink::scheduler::RendererScheduler* renderer_scheduler_;
+ blink::scheduler::WebMainThreadScheduler* main_thread_scheduler_;
// InputHandlerProxy is only interacted with on the compositor
// thread.
diff --git a/chromium/content/renderer/installedapp/related_apps_fetcher.cc b/chromium/content/renderer/installedapp/related_apps_fetcher.cc
index 2e18b202cb2..a7d3091f831 100644
--- a/chromium/content/renderer/installedapp/related_apps_fetcher.cc
+++ b/chromium/content/renderer/installedapp/related_apps_fetcher.cc
@@ -6,10 +6,10 @@
#include "base/bind.h"
#include "content/public/common/manifest.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/modules/installedapp/WebRelatedApplication.h"
-#include "third_party/WebKit/public/platform/modules/manifest/manifest.mojom.h"
-#include "third_party/WebKit/public/platform/modules/manifest/manifest_manager.mojom.h"
+#include "third_party/blink/public/platform/modules/installedapp/web_related_application.h"
+#include "third_party/blink/public/platform/modules/manifest/manifest.mojom.h"
+#include "third_party/blink/public/platform/modules/manifest/manifest_manager.mojom.h"
+#include "third_party/blink/public/platform/web_string.h"
namespace content {
diff --git a/chromium/content/renderer/installedapp/related_apps_fetcher.h b/chromium/content/renderer/installedapp/related_apps_fetcher.h
index d97f3463088..73fbfc15f95 100644
--- a/chromium/content/renderer/installedapp/related_apps_fetcher.h
+++ b/chromium/content/renderer/installedapp/related_apps_fetcher.h
@@ -9,7 +9,7 @@
#include "base/compiler_specific.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/modules/installedapp/WebRelatedAppsFetcher.h"
+#include "third_party/blink/public/platform/modules/installedapp/web_related_apps_fetcher.h"
namespace blink {
namespace mojom {
diff --git a/chromium/content/renderer/internal_document_state_data.cc b/chromium/content/renderer/internal_document_state_data.cc
index 72d99be7aba..2360f2144b3 100644
--- a/chromium/content/renderer/internal_document_state_data.cc
+++ b/chromium/content/renderer/internal_document_state_data.cc
@@ -6,7 +6,7 @@
#include "base/memory/ptr_util.h"
#include "content/public/renderer/document_state.h"
-#include "third_party/WebKit/public/web/WebDocumentLoader.h"
+#include "third_party/blink/public/web/web_document_loader.h"
namespace content {
diff --git a/chromium/content/renderer/internal_document_state_data.h b/chromium/content/renderer/internal_document_state_data.h
index 2c01d0b5c44..1705e537a65 100644
--- a/chromium/content/renderer/internal_document_state_data.h
+++ b/chromium/content/renderer/internal_document_state_data.h
@@ -10,7 +10,7 @@
#include "base/macros.h"
#include "base/supports_user_data.h"
-#include "third_party/WebKit/public/platform/modules/fetch/fetch_api_request.mojom-shared.h"
+#include "third_party/blink/public/platform/modules/fetch/fetch_api_request.mojom-shared.h"
#include "url/gurl.h"
namespace blink {
diff --git a/chromium/content/renderer/java/gin_java_bridge_dispatcher.cc b/chromium/content/renderer/java/gin_java_bridge_dispatcher.cc
index a7a9a449887..b491262ab43 100644
--- a/chromium/content/renderer/java/gin_java_bridge_dispatcher.cc
+++ b/chromium/content/renderer/java/gin_java_bridge_dispatcher.cc
@@ -10,8 +10,8 @@
#include "content/common/gin_java_bridge_messages.h"
#include "content/public/renderer/render_frame.h"
#include "content/renderer/java/gin_java_bridge_object.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebView.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_view.h"
namespace content {
diff --git a/chromium/content/renderer/java/gin_java_bridge_object.cc b/chromium/content/renderer/java/gin_java_bridge_object.cc
index d747e3c0d3a..a9599aea0d3 100644
--- a/chromium/content/renderer/java/gin_java_bridge_object.cc
+++ b/chromium/content/renderer/java/gin_java_bridge_object.cc
@@ -8,8 +8,8 @@
#include "content/public/renderer/render_thread.h"
#include "content/renderer/java/gin_java_function_invocation_helper.h"
#include "gin/function_template.h"
-#include "third_party/WebKit/public/web/WebKit.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "third_party/blink/public/web/blink.h"
+#include "third_party/blink/public/web/web_local_frame.h"
namespace content {
diff --git a/chromium/content/renderer/java/gin_java_function_invocation_helper.cc b/chromium/content/renderer/java/gin_java_function_invocation_helper.cc
index c1c14685e13..39f9253a391 100644
--- a/chromium/content/renderer/java/gin_java_function_invocation_helper.cc
+++ b/chromium/content/renderer/java/gin_java_function_invocation_helper.cc
@@ -6,7 +6,6 @@
#include <utility>
-#include "base/memory/ptr_util.h"
#include "base/values.h"
#include "content/common/android/gin_java_bridge_errors.h"
#include "content/common/android/gin_java_bridge_value.h"
diff --git a/chromium/content/renderer/loader/child_url_loader_factory_bundle.cc b/chromium/content/renderer/loader/child_url_loader_factory_bundle.cc
index 08d0a9dc06b..feb92de61a6 100644
--- a/chromium/content/renderer/loader/child_url_loader_factory_bundle.cc
+++ b/chromium/content/renderer/loader/child_url_loader_factory_bundle.cc
@@ -5,14 +5,98 @@
#include "content/renderer/loader/child_url_loader_factory_bundle.h"
#include "base/logging.h"
+#include "mojo/public/cpp/bindings/strong_binding.h"
#include "url/gurl.h"
#include "url/url_constants.h"
namespace content {
+namespace {
+
+class URLLoaderRelay : public network::mojom::URLLoaderClient,
+ public network::mojom::URLLoader {
+ public:
+ URLLoaderRelay(network::mojom::URLLoaderPtr loader_sink,
+ network::mojom::URLLoaderClientRequest client_source,
+ network::mojom::URLLoaderClientPtr client_sink)
+ : loader_sink_(std::move(loader_sink)),
+ client_source_binding_(this, std::move(client_source)),
+ client_sink_(std::move(client_sink)) {}
+
+ // network::mojom::URLLoader implementation:
+ void FollowRedirect() override { loader_sink_->FollowRedirect(); }
+
+ void ProceedWithResponse() override { loader_sink_->ProceedWithResponse(); }
+
+ void SetPriority(net::RequestPriority priority,
+ int32_t intra_priority_value) override {
+ loader_sink_->SetPriority(priority, intra_priority_value);
+ }
+
+ void PauseReadingBodyFromNet() override {
+ loader_sink_->PauseReadingBodyFromNet();
+ }
+
+ void ResumeReadingBodyFromNet() override {
+ loader_sink_->ResumeReadingBodyFromNet();
+ }
+
+ // network::mojom::URLLoaderClient implementation:
+ void OnReceiveResponse(
+ const network::ResourceResponseHead& head,
+ network::mojom::DownloadedTempFilePtr downloaded_file) override {
+ client_sink_->OnReceiveResponse(head, std::move(downloaded_file));
+ }
+
+ void OnReceiveRedirect(const net::RedirectInfo& redirect_info,
+ const network::ResourceResponseHead& head) override {
+ client_sink_->OnReceiveRedirect(redirect_info, head);
+ }
+
+ void OnDataDownloaded(int64_t data_length, int64_t encoded_length) override {
+ client_sink_->OnDataDownloaded(data_length, encoded_length);
+ }
+
+ void OnUploadProgress(int64_t current_position,
+ int64_t total_size,
+ OnUploadProgressCallback callback) override {
+ client_sink_->OnUploadProgress(current_position, total_size,
+ std::move(callback));
+ }
+
+ void OnReceiveCachedMetadata(const std::vector<uint8_t>& data) override {
+ client_sink_->OnReceiveCachedMetadata(data);
+ }
+
+ void OnTransferSizeUpdated(int32_t transfer_size_diff) override {
+ client_sink_->OnTransferSizeUpdated(transfer_size_diff);
+ }
+
+ void OnStartLoadingResponseBody(
+ mojo::ScopedDataPipeConsumerHandle body) override {
+ client_sink_->OnStartLoadingResponseBody(std::move(body));
+ }
+
+ void OnComplete(const network::URLLoaderCompletionStatus& status) override {
+ client_sink_->OnComplete(status);
+ }
+
+ private:
+ network::mojom::URLLoaderPtr loader_sink_;
+ mojo::Binding<network::mojom::URLLoaderClient> client_source_binding_;
+ network::mojom::URLLoaderClientPtr client_sink_;
+};
+
+} // namespace
+
ChildURLLoaderFactoryBundleInfo::ChildURLLoaderFactoryBundleInfo() = default;
ChildURLLoaderFactoryBundleInfo::ChildURLLoaderFactoryBundleInfo(
+ std::unique_ptr<URLLoaderFactoryBundleInfo> base_info)
+ : URLLoaderFactoryBundleInfo(std::move(base_info->default_factory_info()),
+ std::move(base_info->factories_info())) {}
+
+ChildURLLoaderFactoryBundleInfo::ChildURLLoaderFactoryBundleInfo(
network::mojom::URLLoaderFactoryPtrInfo default_factory_info,
std::map<std::string, network::mojom::URLLoaderFactoryPtrInfo>
factories_info,
@@ -23,7 +107,7 @@ ChildURLLoaderFactoryBundleInfo::ChildURLLoaderFactoryBundleInfo(
ChildURLLoaderFactoryBundleInfo::~ChildURLLoaderFactoryBundleInfo() = default;
-scoped_refptr<SharedURLLoaderFactory>
+scoped_refptr<network::SharedURLLoaderFactory>
ChildURLLoaderFactoryBundleInfo::CreateFactory() {
auto other = std::make_unique<ChildURLLoaderFactoryBundleInfo>();
other->default_factory_info_ = std::move(default_factory_info_);
@@ -39,7 +123,7 @@ ChildURLLoaderFactoryBundle::ChildURLLoaderFactoryBundle() = default;
ChildURLLoaderFactoryBundle::ChildURLLoaderFactoryBundle(
std::unique_ptr<ChildURLLoaderFactoryBundleInfo> info) {
- Update(std::move(info));
+ Update(std::move(info), base::nullopt);
}
ChildURLLoaderFactoryBundle::ChildURLLoaderFactoryBundle(
@@ -75,6 +159,24 @@ void ChildURLLoaderFactoryBundle::CreateLoaderAndStart(
const network::ResourceRequest& request,
network::mojom::URLLoaderClientPtr client,
const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) {
+ auto override_iter = subresource_overrides_.find(request.url);
+ if (override_iter != subresource_overrides_.end()) {
+ mojom::TransferrableURLLoaderPtr transferrable_loader =
+ std::move(override_iter->second);
+ subresource_overrides_.erase(override_iter);
+
+ client->OnReceiveResponse(transferrable_loader->head, nullptr);
+ mojo::MakeStrongBinding(
+ std::make_unique<URLLoaderRelay>(
+ network::mojom::URLLoaderPtr(
+ std::move(transferrable_loader->url_loader)),
+ std::move(transferrable_loader->url_loader_client),
+ std::move(client)),
+ std::move(loader));
+
+ return;
+ }
+
network::mojom::URLLoaderFactory* factory_ptr = GetFactoryForURL(request.url);
factory_ptr->CreateLoaderAndStart(std::move(loader), routing_id, request_id,
@@ -82,7 +184,7 @@ void ChildURLLoaderFactoryBundle::CreateLoaderAndStart(
traffic_annotation);
}
-std::unique_ptr<SharedURLLoaderFactoryInfo>
+std::unique_ptr<network::SharedURLLoaderFactoryInfo>
ChildURLLoaderFactoryBundle::Clone() {
InitDefaultBlobFactoryIfNecessary();
InitDirectNetworkFactoryIfNecessary();
@@ -104,18 +206,29 @@ ChildURLLoaderFactoryBundle::Clone() {
mojo::MakeRequest(&direct_network_factory_info));
}
+ // Currently there is no need to override subresources from workers,
+ // therefore |subresource_overrides| are not shared with the clones.
+
return std::make_unique<ChildURLLoaderFactoryBundleInfo>(
std::move(default_factory_info), std::move(factories_info),
std::move(direct_network_factory_info));
}
void ChildURLLoaderFactoryBundle::Update(
- std::unique_ptr<ChildURLLoaderFactoryBundleInfo> info) {
+ std::unique_ptr<ChildURLLoaderFactoryBundleInfo> info,
+ base::Optional<std::vector<mojom::TransferrableURLLoaderPtr>>
+ subresource_overrides) {
if (info->direct_network_factory_info()) {
direct_network_factory_.Bind(
std::move(info->direct_network_factory_info()));
}
URLLoaderFactoryBundle::Update(std::move(info));
+
+ if (subresource_overrides) {
+ for (auto& element : *subresource_overrides) {
+ subresource_overrides_[element->url] = std::move(element);
+ }
+ }
}
bool ChildURLLoaderFactoryBundle::IsHostChildURLLoaderFactoryBundle() const {
diff --git a/chromium/content/renderer/loader/child_url_loader_factory_bundle.h b/chromium/content/renderer/loader/child_url_loader_factory_bundle.h
index 2e884253e60..922cca480bb 100644
--- a/chromium/content/renderer/loader/child_url_loader_factory_bundle.h
+++ b/chromium/content/renderer/loader/child_url_loader_factory_bundle.h
@@ -9,6 +9,7 @@
#include "content/common/content_export.h"
#include "content/common/possibly_associated_interface_ptr.h"
#include "content/common/url_loader_factory_bundle.h"
+#include "content/public/common/transferrable_url_loader.mojom.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
namespace content {
@@ -22,6 +23,8 @@ class CONTENT_EXPORT ChildURLLoaderFactoryBundleInfo
PossiblyAssociatedInterfacePtrInfo<network::mojom::URLLoaderFactory>;
ChildURLLoaderFactoryBundleInfo();
+ explicit ChildURLLoaderFactoryBundleInfo(
+ std::unique_ptr<URLLoaderFactoryBundleInfo> base_info);
ChildURLLoaderFactoryBundleInfo(
network::mojom::URLLoaderFactoryPtrInfo default_factory_info,
std::map<std::string, network::mojom::URLLoaderFactoryPtrInfo>
@@ -35,7 +38,7 @@ class CONTENT_EXPORT ChildURLLoaderFactoryBundleInfo
protected:
// URLLoaderFactoryBundleInfo overrides.
- scoped_refptr<SharedURLLoaderFactory> CreateFactory() override;
+ scoped_refptr<network::SharedURLLoaderFactory> CreateFactory() override;
PossiblyAssociatedURLLoaderFactoryPtrInfo direct_network_factory_info_;
@@ -78,11 +81,13 @@ class CONTENT_EXPORT ChildURLLoaderFactoryBundle
const net::MutableNetworkTrafficAnnotationTag&
traffic_annotation) override;
- std::unique_ptr<SharedURLLoaderFactoryInfo> Clone() override;
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo> Clone() override;
std::unique_ptr<ChildURLLoaderFactoryBundleInfo> PassInterface();
- void Update(std::unique_ptr<ChildURLLoaderFactoryBundleInfo> info);
+ void Update(std::unique_ptr<ChildURLLoaderFactoryBundleInfo> info,
+ base::Optional<std::vector<mojom::TransferrableURLLoaderPtr>>
+ subresource_overrides);
virtual bool IsHostChildURLLoaderFactoryBundle() const;
@@ -96,6 +101,8 @@ class CONTENT_EXPORT ChildURLLoaderFactoryBundle
PossiblyAssociatedFactoryGetterCallback direct_network_factory_getter_;
PossiblyAssociatedURLLoaderFactoryPtr direct_network_factory_;
+ std::map<GURL, mojom::TransferrableURLLoaderPtr> subresource_overrides_;
+
FactoryGetterCallback default_blob_factory_getter_;
};
diff --git a/chromium/content/renderer/loader/ftp_directory_listing_response_delegate.cc b/chromium/content/renderer/loader/ftp_directory_listing_response_delegate.cc
index fb99d337070..981242e3919 100644
--- a/chromium/content/renderer/loader/ftp_directory_listing_response_delegate.cc
+++ b/chromium/content/renderer/loader/ftp_directory_listing_response_delegate.cc
@@ -21,9 +21,9 @@
#include "net/base/escape.h"
#include "net/base/net_errors.h"
#include "net/ftp/ftp_directory_listing_parser.h"
-#include "net/net_features.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
-#include "third_party/WebKit/public/platform/WebURLLoaderClient.h"
+#include "net/net_buildflags.h"
+#include "third_party/blink/public/platform/web_url.h"
+#include "third_party/blink/public/platform/web_url_loader_client.h"
using blink::WebURLLoader;
using blink::WebURLLoaderClient;
diff --git a/chromium/content/renderer/loader/ftp_directory_listing_response_delegate.h b/chromium/content/renderer/loader/ftp_directory_listing_response_delegate.h
index d98d2b7ffe4..19212cc9fc6 100644
--- a/chromium/content/renderer/loader/ftp_directory_listing_response_delegate.h
+++ b/chromium/content/renderer/loader/ftp_directory_listing_response_delegate.h
@@ -11,7 +11,7 @@
#include <string>
#include "base/macros.h"
-#include "third_party/WebKit/public/platform/WebURLResponse.h"
+#include "third_party/blink/public/platform/web_url_response.h"
namespace blink {
class WebURLLoader;
diff --git a/chromium/content/renderer/loader/request_extra_data.cc b/chromium/content/renderer/loader/request_extra_data.cc
index b9fce63a076..3b523978f38 100644
--- a/chromium/content/renderer/loader/request_extra_data.cc
+++ b/chromium/content/renderer/loader/request_extra_data.cc
@@ -24,7 +24,8 @@ RequestExtraData::RequestExtraData()
is_for_no_state_prefetch_(false),
download_to_network_cache_only_(false),
block_mixed_plugin_content_(false),
- navigation_initiated_by_renderer_(false) {}
+ navigation_initiated_by_renderer_(false),
+ attach_same_site_cookies_(false) {}
RequestExtraData::~RequestExtraData() {
}
@@ -43,6 +44,7 @@ void RequestExtraData::CopyToResourceRequest(
request->originated_from_service_worker = originated_from_service_worker_;
request->initiated_in_secure_context = initiated_in_secure_context_;
+ request->attach_same_site_cookies = attach_same_site_cookies_;
}
} // namespace content
diff --git a/chromium/content/renderer/loader/request_extra_data.h b/chromium/content/renderer/loader/request_extra_data.h
index d32c610e93a..8d458507d5e 100644
--- a/chromium/content/renderer/loader/request_extra_data.h
+++ b/chromium/content/renderer/loader/request_extra_data.h
@@ -13,11 +13,10 @@
#include "content/common/navigation_params.h"
#include "content/public/common/url_loader_throttle.h"
#include "content/renderer/loader/web_url_loader_impl.h"
-#include "third_party/WebKit/public/mojom/page/page_visibility_state.mojom.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebURLRequest.h"
+#include "third_party/blink/public/mojom/page/page_visibility_state.mojom.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_url_request.h"
#include "ui/base/page_transition_types.h"
-#include "url/origin.h"
namespace network {
struct ResourceRequest;
@@ -43,10 +42,6 @@ class CONTENT_EXPORT RequestExtraData : public blink::WebURLRequest::ExtraData {
void set_is_main_frame(bool is_main_frame) {
is_main_frame_ = is_main_frame;
}
- url::Origin frame_origin() const { return frame_origin_; }
- void set_frame_origin(const url::Origin& frame_origin) {
- frame_origin_ = frame_origin;
- }
void set_allow_download(bool allow_download) {
allow_download_ = allow_download;
}
@@ -145,6 +140,13 @@ class CONTENT_EXPORT RequestExtraData : public blink::WebURLRequest::ExtraData {
navigation_initiated_by_renderer_ = navigation_by_renderer;
}
+ // Determines whether SameSite cookies will be attached to the request
+ // even when the request looks cross-site.
+ bool attach_same_site_cookies() const { return attach_same_site_cookies_; }
+ void set_attach_same_site_cookies(bool attach) {
+ attach_same_site_cookies_ = attach;
+ }
+
std::vector<std::unique_ptr<URLLoaderThrottle>> TakeURLLoaderThrottles() {
return std::move(url_loader_throttles_);
}
@@ -159,7 +161,6 @@ class CONTENT_EXPORT RequestExtraData : public blink::WebURLRequest::ExtraData {
blink::mojom::PageVisibilityState visibility_state_;
int render_frame_id_;
bool is_main_frame_;
- url::Origin frame_origin_;
bool allow_download_;
ui::PageTransition transition_type_;
bool should_replace_current_entry_;
@@ -176,6 +177,7 @@ class CONTENT_EXPORT RequestExtraData : public blink::WebURLRequest::ExtraData {
bool download_to_network_cache_only_;
bool block_mixed_plugin_content_;
bool navigation_initiated_by_renderer_;
+ bool attach_same_site_cookies_;
std::vector<std::unique_ptr<URLLoaderThrottle>> url_loader_throttles_;
DISALLOW_COPY_AND_ASSIGN(RequestExtraData);
diff --git a/chromium/content/renderer/loader/resource_dispatcher.cc b/chromium/content/renderer/loader/resource_dispatcher.cc
index c29ac8509c0..55c99a21928 100644
--- a/chromium/content/renderer/loader/resource_dispatcher.cc
+++ b/chromium/content/renderer/loader/resource_dispatcher.cc
@@ -14,7 +14,6 @@
#include "base/debug/alias.h"
#include "base/debug/stack_trace.h"
#include "base/files/file_path.h"
-#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/string_util.h"
@@ -24,19 +23,21 @@
#include "content/common/inter_process_time_ticks_converter.h"
#include "content/common/navigation_params.h"
#include "content/common/throttling_url_loader.h"
+#include "content/public/common/resource_load_info.mojom.h"
#include "content/public/common/resource_type.h"
#include "content/public/renderer/fixed_received_data.h"
#include "content/public/renderer/request_peer.h"
#include "content/public/renderer/resource_dispatcher_delegate.h"
#include "content/renderer/loader/request_extra_data.h"
-#include "content/renderer/loader/site_isolation_stats_gatherer.h"
#include "content/renderer/loader/sync_load_context.h"
#include "content/renderer/loader/sync_load_response.h"
#include "content/renderer/loader/url_loader_client_impl.h"
#include "content/renderer/render_frame_impl.h"
+#include "content/renderer/render_thread_impl.h"
#include "net/base/load_flags.h"
#include "net/base/net_errors.h"
#include "net/base/request_priority.h"
+#include "net/cert/cert_status_flags.h"
#include "net/http/http_response_headers.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/cpp/resource_request.h"
@@ -74,19 +75,37 @@ void NotifySubresourceStarted(
scoped_refptr<base::SingleThreadTaskRunner> thread_task_runner,
int render_frame_id,
const GURL& url,
- const GURL& referrer,
- const std::string& method,
- ResourceType resource_type,
- const std::string& ip,
- uint32_t cert_status) {
+ net::CertStatus cert_status) {
if (!thread_task_runner)
return;
if (!thread_task_runner->BelongsToCurrentThread()) {
thread_task_runner->PostTask(
FROM_HERE, base::BindOnce(NotifySubresourceStarted, thread_task_runner,
- render_frame_id, url, referrer, method,
- resource_type, ip, cert_status));
+ render_frame_id, url, cert_status));
+ return;
+ }
+
+ RenderFrameImpl* render_frame =
+ RenderFrameImpl::FromRoutingID(render_frame_id);
+ if (!render_frame)
+ return;
+
+ render_frame->GetFrameHost()->SubresourceResponseStarted(url, cert_status);
+}
+
+void NotifyResourceLoadComplete(
+ scoped_refptr<base::SingleThreadTaskRunner> thread_task_runner,
+ int render_frame_id,
+ mojom::ResourceLoadInfoPtr resource_load_info) {
+ if (!thread_task_runner)
+ return;
+
+ if (!thread_task_runner->BelongsToCurrentThread()) {
+ thread_task_runner->PostTask(
+ FROM_HERE,
+ base::BindOnce(NotifyResourceLoadComplete, thread_task_runner,
+ render_frame_id, std::move(resource_load_info)));
return;
}
@@ -95,8 +114,8 @@ void NotifySubresourceStarted(
if (!render_frame)
return;
- render_frame->GetFrameHost()->SubresourceResponseStarted(
- url, referrer, method, resource_type, ip, cert_status);
+ render_frame->GetFrameHost()->ResourceLoadComplete(
+ std::move(resource_load_info));
}
} // namespace
@@ -151,21 +170,22 @@ void ResourceDispatcher::OnReceivedResponse(
request_info->peer = std::move(new_peer);
}
+ if (!response_head.socket_address.host().empty()) {
+ ignore_result(request_info->parsed_ip.AssignFromIPLiteral(
+ response_head.socket_address.host()));
+ }
+
+ request_info->mime_type = response_head.mime_type;
+ request_info->network_accessed = response_head.network_accessed;
if (!IsResourceTypeFrame(request_info->resource_type)) {
- NotifySubresourceStarted(
- RenderThreadImpl::DeprecatedGetMainTaskRunner(),
- request_info->render_frame_id, request_info->response_url,
- request_info->response_referrer, request_info->response_method,
- request_info->resource_type, response_head.socket_address.host(),
- response_head.cert_status);
+ NotifySubresourceStarted(RenderThreadImpl::DeprecatedGetMainTaskRunner(),
+ request_info->render_frame_id,
+ request_info->response_url,
+ response_head.cert_status);
}
network::ResourceResponseInfo renderer_response_info;
ToResourceResponseInfo(*request_info, response_head, &renderer_response_info);
- request_info->site_isolation_metadata =
- SiteIsolationStatsGatherer::OnReceivedResponse(
- request_info->frame_origin, request_info->response_url,
- request_info->resource_type, renderer_response_info);
request_info->peer->OnReceivedResponse(renderer_response_info);
}
@@ -182,6 +202,16 @@ void ResourceDispatcher::OnReceivedCachedMetadata(
}
}
+void ResourceDispatcher::OnStartLoadingResponseBody(
+ int request_id,
+ mojo::ScopedDataPipeConsumerHandle body) {
+ PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
+ if (!request_info)
+ return;
+
+ request_info->peer->OnStartLoadingResponseBody(std::move(body));
+}
+
void ResourceDispatcher::OnDownloadedData(int request_id,
int data_len,
int encoded_data_length) {
@@ -212,8 +242,7 @@ void ResourceDispatcher::OnReceivedRedirect(
request_info = GetPendingRequestInfo(request_id);
if (!request_info)
return;
- // We update the response_url here so that we can send it to
- // SiteIsolationStatsGatherer later when OnReceivedResponse is called.
+ // We update the response_url here for tracking/stats use later.
request_info->response_url = redirect_info.new_url;
request_info->response_method = redirect_info.new_method;
request_info->response_referrer = GURL(redirect_info.new_referrer);
@@ -246,6 +275,24 @@ void ResourceDispatcher::OnRequestComplete(
request_info->buffer.reset();
request_info->buffer_size = 0;
+ auto resource_load_info = mojom::ResourceLoadInfo::New();
+ resource_load_info->url = request_info->response_url;
+ resource_load_info->original_url = request_info->url;
+ resource_load_info->referrer = request_info->response_referrer;
+ resource_load_info->method = request_info->response_method;
+ resource_load_info->resource_type = request_info->resource_type;
+ resource_load_info->request_id = request_id;
+ if (request_info->parsed_ip.IsValid())
+ resource_load_info->ip = request_info->parsed_ip;
+ resource_load_info->mime_type = request_info->mime_type;
+ resource_load_info->network_accessed = request_info->network_accessed;
+ resource_load_info->was_cached = status.exists_in_cache;
+ resource_load_info->net_error = status.error_code;
+ resource_load_info->request_start = request_info->request_start;
+ NotifyResourceLoadComplete(RenderThreadImpl::DeprecatedGetMainTaskRunner(),
+ request_info->render_frame_id,
+ std::move(resource_load_info));
+
RequestPeer* peer = request_info->peer.get();
if (delegate_) {
@@ -268,6 +315,17 @@ void ResourceDispatcher::OnRequestComplete(
peer->OnCompletedRequest(renderer_status);
}
+network::mojom::DownloadedTempFilePtr
+ResourceDispatcher::TakeDownloadedTempFile(int request_id) {
+ PendingRequestMap::iterator it = pending_requests_.find(request_id);
+ if (it == pending_requests_.end())
+ return nullptr;
+ PendingRequestInfo* request_info = it->second.get();
+ if (!request_info->url_loader_client)
+ return nullptr;
+ return request_info->url_loader_client->TakeDownloadedTempFile();
+}
+
bool ResourceDispatcher::RemovePendingRequest(
int request_id,
scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
@@ -349,7 +407,6 @@ ResourceDispatcher::PendingRequestInfo::PendingRequestInfo(
std::unique_ptr<RequestPeer> peer,
ResourceType resource_type,
int render_frame_id,
- const url::Origin& frame_origin,
const GURL& request_url,
const std::string& method,
const GURL& referrer,
@@ -358,7 +415,6 @@ ResourceDispatcher::PendingRequestInfo::PendingRequestInfo(
resource_type(resource_type),
render_frame_id(render_frame_id),
url(request_url),
- frame_origin(frame_origin),
response_url(request_url),
response_method(method),
response_referrer(referrer),
@@ -371,17 +427,19 @@ ResourceDispatcher::PendingRequestInfo::~PendingRequestInfo() {
void ResourceDispatcher::StartSync(
std::unique_ptr<network::ResourceRequest> request,
int routing_id,
- const url::Origin& frame_origin,
const net::NetworkTrafficAnnotationTag& traffic_annotation,
SyncLoadResponse* response,
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory,
- std::vector<std::unique_ptr<URLLoaderThrottle>> throttles) {
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
+ std::vector<std::unique_ptr<URLLoaderThrottle>> throttles,
+ double timeout,
+ blink::mojom::BlobRegistryPtrInfo download_to_blob_registry) {
CheckSchemeForReferrerPolicy(*request);
- std::unique_ptr<SharedURLLoaderFactoryInfo> factory_info =
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo> factory_info =
url_loader_factory->Clone();
- base::WaitableEvent event(base::WaitableEvent::ResetPolicy::MANUAL,
- base::WaitableEvent::InitialState::NOT_SIGNALED);
+ base::WaitableEvent completed_event(
+ base::WaitableEvent::ResetPolicy::MANUAL,
+ base::WaitableEvent::InitialState::NOT_SIGNALED);
// Prepare the configured throttles for use on a separate thread.
for (const auto& throttle : throttles)
@@ -396,23 +454,24 @@ void ResourceDispatcher::StartSync(
task_runner->PostTask(
FROM_HERE,
base::BindOnce(&SyncLoadContext::StartAsyncWithWaitableEvent,
- std::move(request), routing_id, task_runner, frame_origin,
+ std::move(request), routing_id, task_runner,
traffic_annotation, std::move(factory_info),
std::move(throttles), base::Unretained(response),
- base::Unretained(&event)));
-
- event.Wait();
+ base::Unretained(&completed_event),
+ base::Unretained(terminate_sync_load_event_), timeout,
+ std::move(download_to_blob_registry)));
+ completed_event.Wait();
}
int ResourceDispatcher::StartAsync(
std::unique_ptr<network::ResourceRequest> request,
int routing_id,
scoped_refptr<base::SingleThreadTaskRunner> loading_task_runner,
- const url::Origin& frame_origin,
const net::NetworkTrafficAnnotationTag& traffic_annotation,
bool is_sync,
+ bool pass_response_pipe_to_peer,
std::unique_ptr<RequestPeer> peer,
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory,
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
std::vector<std::unique_ptr<URLLoaderThrottle>> throttles,
network::mojom::URLLoaderClientEndpointsPtr url_loader_client_endpoints,
base::OnceClosure* continue_navigation_function) {
@@ -422,7 +481,7 @@ int ResourceDispatcher::StartAsync(
int request_id = MakeRequestID();
pending_requests_[request_id] = std::make_unique<PendingRequestInfo>(
std::move(peer), static_cast<ResourceType>(request->resource_type),
- request->render_frame_id, frame_origin, request->url, request->method,
+ request->render_frame_id, request->url, request->method,
request->referrer, request->download_to_file);
if (url_loader_client_endpoints) {
@@ -441,6 +500,9 @@ int ResourceDispatcher::StartAsync(
std::unique_ptr<URLLoaderClientImpl> client(
new URLLoaderClientImpl(request_id, this, loading_task_runner));
+ if (pass_response_pipe_to_peer)
+ client->SetPassResponsePipeToDispatcher(true);
+
uint32_t options = network::mojom::kURLLoadOptionNone;
// TODO(jam): use this flag for ResourceDispatcherHost code path once
// MojoLoading is the only IPC code path.
@@ -534,7 +596,7 @@ void ResourceDispatcher::ContinueForNavigation(
// the request. ResourceResponseHead can be empty here because we
// pull the StreamOverride's one in
// WebURLLoaderImpl::Context::OnReceivedResponse.
- client_ptr->OnReceiveResponse(network::ResourceResponseHead(), base::nullopt,
+ client_ptr->OnReceiveResponse(network::ResourceResponseHead(),
network::mojom::DownloadedTempFilePtr());
// TODO(clamy): Move the replaying of redirects from WebURLLoaderImpl here.
diff --git a/chromium/content/renderer/loader/resource_dispatcher.h b/chromium/content/renderer/loader/resource_dispatcher.h
index 44de7552def..af1364a8799 100644
--- a/chromium/content/renderer/loader/resource_dispatcher.h
+++ b/chromium/content/renderer/loader/resource_dispatcher.h
@@ -23,15 +23,19 @@
#include "base/time/time.h"
#include "content/common/content_export.h"
#include "content/public/common/resource_type.h"
-#include "content/public/common/shared_url_loader_factory.h"
#include "content/public/common/url_loader_throttle.h"
#include "mojo/public/cpp/system/data_pipe.h"
#include "net/base/request_priority.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/mojom/url_loader.mojom.h"
-#include "third_party/WebKit/public/platform/WebURLRequest.h"
+#include "third_party/blink/public/mojom/blob/blob_registry.mojom.h"
+#include "third_party/blink/public/platform/web_url_request.h"
#include "url/gurl.h"
-#include "url/origin.h"
+
+namespace base {
+class WaitableEvent;
+}
namespace net {
struct RedirectInfo;
@@ -50,7 +54,6 @@ class URLLoaderFactory;
namespace content {
class RequestPeer;
class ResourceDispatcherDelegate;
-struct SiteIsolationResponseMetaData;
struct SyncLoadResponse;
class ThrottlingURLLoader;
class URLLoaderClientImpl;
@@ -82,14 +85,18 @@ class CONTENT_EXPORT ResourceDispatcher {
//
// |routing_id| is used to associated the bridge with a frame's network
// context.
+ // |timeout| (in seconds) is used to abort the sync request on timeouts.
+ // If |download_to_blob_registry| is not null, it is used to redirect the
+ // download to a blob, using StartAsync's |pass_response_pipe_to_peer| flag.
virtual void StartSync(
std::unique_ptr<network::ResourceRequest> request,
int routing_id,
- const url::Origin& frame_origin,
const net::NetworkTrafficAnnotationTag& traffic_annotation,
SyncLoadResponse* response,
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory,
- std::vector<std::unique_ptr<URLLoaderThrottle>> throttles);
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
+ std::vector<std::unique_ptr<URLLoaderThrottle>> throttles,
+ double timeout,
+ blink::mojom::BlobRegistryPtrInfo download_to_blob_registry);
// Call this method to initiate the request. If this method succeeds, then
// the peer's methods will be called asynchronously to report various events.
@@ -98,21 +105,28 @@ class CONTENT_EXPORT ResourceDispatcher {
// |routing_id| is used to associated the bridge with a frame's network
// context.
//
+ // If |pass_response_pipe_to_peer| is true, the raw datapipe containing the
+ // response body is passed on to |peer| without any extra processing. If it
+ // is set to false instead OnReceivedData is called on the |peer| whenever a
+ // chunk of data is available.
+ //
// You need to pass a non-null |loading_task_runner| to specify task queue to
// execute loading tasks on.
virtual int StartAsync(
std::unique_ptr<network::ResourceRequest> request,
int routing_id,
scoped_refptr<base::SingleThreadTaskRunner> loading_task_runner,
- const url::Origin& frame_origin,
const net::NetworkTrafficAnnotationTag& traffic_annotation,
bool is_sync,
+ bool pass_response_pipe_to_peer,
std::unique_ptr<RequestPeer> peer,
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory,
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
std::vector<std::unique_ptr<URLLoaderThrottle>> throttles,
network::mojom::URLLoaderClientEndpointsPtr url_loader_client_endpoints,
base::OnceClosure* continue_navigation_function);
+ network::mojom::DownloadedTempFilePtr TakeDownloadedTempFile(int request_id);
+
// Removes a request from the |pending_requests_| list, returning true if the
// request was found and removed.
bool RemovePendingRequest(
@@ -144,6 +158,15 @@ class CONTENT_EXPORT ResourceDispatcher {
void OnTransferSizeUpdated(int request_id, int32_t transfer_size_diff);
+ // This is used only when |this| is created for a worker thread.
+ // Sets |terminate_sync_load_event_| which will be signaled from the main
+ // thread when the worker thread is being terminated so that the sync requests
+ // requested on the worker thread can be aborted.
+ void set_terminate_sync_load_event(
+ base::WaitableEvent* terminate_sync_load_event) {
+ terminate_sync_load_event_ = terminate_sync_load_event;
+ }
+
private:
friend class URLLoaderClientImpl;
friend class URLResponseBodyConsumer;
@@ -153,7 +176,6 @@ class CONTENT_EXPORT ResourceDispatcher {
PendingRequestInfo(std::unique_ptr<RequestPeer> peer,
ResourceType resource_type,
int render_frame_id,
- const url::Origin& frame_origin,
const GURL& request_url,
const std::string& method,
const GURL& referrer,
@@ -167,8 +189,6 @@ class CONTENT_EXPORT ResourceDispatcher {
bool is_deferred = false;
// Original requested url.
GURL url;
- // The security origin of the frame that initiates this request.
- url::Origin frame_origin;
// The url, method and referrer of the latest response even in case of
// redirection.
GURL response_url;
@@ -180,8 +200,10 @@ class CONTENT_EXPORT ResourceDispatcher {
base::TimeTicks response_start;
base::TimeTicks completion_time;
linked_ptr<base::SharedMemory> buffer;
- std::unique_ptr<SiteIsolationResponseMetaData> site_isolation_metadata;
int buffer_size;
+ net::IPAddress parsed_ip;
+ bool network_accessed = false;
+ std::string mime_type;
// For mojo loading.
std::unique_ptr<ThrottlingURLLoader> url_loader;
@@ -206,6 +228,8 @@ class CONTENT_EXPORT ResourceDispatcher {
const net::RedirectInfo& redirect_info,
const network::ResourceResponseHead& response_head,
scoped_refptr<base::SingleThreadTaskRunner> task_runner);
+ void OnStartLoadingResponseBody(int request_id,
+ mojo::ScopedDataPipeConsumerHandle body);
void OnDownloadedData(int request_id, int data_len, int encoded_data_length);
void OnRequestComplete(int request_id,
const network::URLLoaderCompletionStatus& status);
@@ -228,6 +252,8 @@ class CONTENT_EXPORT ResourceDispatcher {
ResourceDispatcherDelegate* delegate_;
+ base::WaitableEvent* terminate_sync_load_event_ = nullptr;
+
base::WeakPtrFactory<ResourceDispatcher> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(ResourceDispatcher);
diff --git a/chromium/content/renderer/loader/resource_dispatcher_unittest.cc b/chromium/content/renderer/loader/resource_dispatcher_unittest.cc
index 5f1a87e6b6b..32b18cfc520 100644
--- a/chromium/content/renderer/loader/resource_dispatcher_unittest.cc
+++ b/chromium/content/renderer/loader/resource_dispatcher_unittest.cc
@@ -14,15 +14,14 @@
#include <vector>
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/shared_memory.h"
#include "base/message_loop/message_loop.h"
#include "base/process/process_handle.h"
#include "base/run_loop.h"
#include "base/test/scoped_feature_list.h"
#include "content/common/appcache_interfaces.h"
-#include "content/common/weak_wrapper_shared_url_loader_factory.h"
#include "content/public/common/content_features.h"
+#include "content/public/common/weak_wrapper_shared_url_loader_factory.h"
#include "content/public/renderer/fixed_received_data.h"
#include "content/public/renderer/request_peer.h"
#include "content/public/renderer/resource_dispatcher_delegate.h"
@@ -37,8 +36,8 @@
#include "services/network/public/cpp/url_loader_completion_status.h"
#include "services/network/public/mojom/request_context_frame_type.mojom.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebReferrerPolicy.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/web_referrer_policy.h"
#include "url/gurl.h"
namespace content {
@@ -85,7 +84,7 @@ class ResourceDispatcherTest : public testing::Test,
head.headers = new net::HttpResponseHeaders(raw_headers);
head.mime_type = kTestPageMimeType;
head.charset = kTestPageCharset;
- client->OnReceiveResponse(head, {}, {});
+ client->OnReceiveResponse(head, {});
}
std::unique_ptr<network::ResourceRequest> CreateResourceRequest() {
@@ -116,8 +115,8 @@ class ResourceDispatcherTest : public testing::Test,
new TestRequestPeer(dispatcher(), peer_context));
int request_id = dispatcher()->StartAsync(
std::move(request), 0,
- blink::scheduler::GetSingleThreadTaskRunnerForTesting(), url::Origin(),
- TRAFFIC_ANNOTATION_FOR_TESTS, false, std::move(peer),
+ blink::scheduler::GetSingleThreadTaskRunnerForTesting(),
+ TRAFFIC_ANNOTATION_FOR_TESTS, false, false, std::move(peer),
base::MakeRefCounted<WeakWrapperSharedURLLoaderFactory>(this),
std::vector<std::unique_ptr<URLLoaderThrottle>>(),
network::mojom::URLLoaderClientEndpointsPtr(),
@@ -181,6 +180,9 @@ class TestResourceDispatcherDelegate : public ResourceDispatcherDelegate {
response_info_ = info;
}
+ void OnStartLoadingResponseBody(
+ mojo::ScopedDataPipeConsumerHandle body) override {}
+
void OnDownloadedData(int len, int encoded_data_length) override {}
void OnReceivedData(std::unique_ptr<ReceivedData> data) override {
@@ -322,7 +324,7 @@ class TimeConversionTest : public ResourceDispatcherTest {
ASSERT_EQ(1u, loader_and_clients_.size());
auto client = std::move(loader_and_clients_[0].second);
loader_and_clients_.clear();
- client->OnReceiveResponse(response_head, {}, {});
+ client->OnReceiveResponse(response_head, {});
}
const network::ResourceResponseInfo& response_info() const {
diff --git a/chromium/content/renderer/loader/shared_memory_data_consumer_handle.h b/chromium/content/renderer/loader/shared_memory_data_consumer_handle.h
index 7f68865c69a..b1d7076442a 100644
--- a/chromium/content/renderer/loader/shared_memory_data_consumer_handle.h
+++ b/chromium/content/renderer/loader/shared_memory_data_consumer_handle.h
@@ -14,7 +14,7 @@
#include "base/memory/ref_counted.h"
#include "content/common/content_export.h"
#include "content/public/renderer/request_peer.h"
-#include "third_party/WebKit/public/platform/WebDataConsumerHandle.h"
+#include "third_party/blink/public/platform/web_data_consumer_handle.h"
namespace content {
diff --git a/chromium/content/renderer/loader/shared_memory_data_consumer_handle_unittest.cc b/chromium/content/renderer/loader/shared_memory_data_consumer_handle_unittest.cc
index 0cc0ac3174f..777deb6c681 100644
--- a/chromium/content/renderer/loader/shared_memory_data_consumer_handle_unittest.cc
+++ b/chromium/content/renderer/loader/shared_memory_data_consumer_handle_unittest.cc
@@ -15,7 +15,6 @@
#include "base/callback.h"
#include "base/location.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
@@ -26,7 +25,7 @@
#include "content/public/renderer/fixed_received_data.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
namespace content {
diff --git a/chromium/content/renderer/loader/site_isolation_stats_gatherer.cc b/chromium/content/renderer/loader/site_isolation_stats_gatherer.cc
deleted file mode 100644
index d713b83cbd5..00000000000
--- a/chromium/content/renderer/loader/site_isolation_stats_gatherer.cc
+++ /dev/null
@@ -1,256 +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 "content/renderer/loader/site_isolation_stats_gatherer.h"
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include "base/macros.h"
-#include "base/metrics/histogram_macros.h"
-#include "base/strings/string_piece.h"
-#include "base/strings/string_util.h"
-#include "net/http/http_response_headers.h"
-#include "services/network/public/cpp/resource_response_info.h"
-
-namespace content {
-
-namespace {
-
-// The gathering of UMA stats for site isolation is deactivated by default, and
-// only activated in renderer processes.
-static bool g_stats_gathering_enabled = false;
-
-bool IsYes(CrossSiteDocumentClassifier::Result result) {
- return result == CrossSiteDocumentClassifier::Result::kYes;
-}
-
-bool IsRenderableStatusCode(int status_code) {
- // Chrome only uses the content of a response with one of these status codes
- // for CSS/JavaScript. For images, Chrome just ignores status code.
- const int renderable_status_code[] = {
- 200, 201, 202, 203, 206, 300, 301, 302, 303, 305, 306, 307};
- for (size_t i = 0; i < arraysize(renderable_status_code); ++i) {
- if (renderable_status_code[i] == status_code)
- return true;
- }
- return false;
-}
-
-void IncrementHistogramCount(const std::string& name) {
- // The default value of min, max, bucket_count are copied from histogram.h.
- base::HistogramBase* histogram_pointer = base::Histogram::FactoryGet(
- name, 1, 100000, 50, base::HistogramBase::kUmaTargetedHistogramFlag);
- histogram_pointer->Add(1);
-}
-
-void IncrementHistogramEnum(const std::string& name,
- uint32_t sample,
- uint32_t boundary_value) {
- // The default value of min, max, bucket_count are copied from histogram.h.
- base::HistogramBase* histogram_pointer = base::LinearHistogram::FactoryGet(
- name, 1, boundary_value, boundary_value + 1,
- base::HistogramBase::kUmaTargetedHistogramFlag);
- histogram_pointer->Add(sample);
-}
-
-void HistogramCountBlockedResponse(
- const std::string& bucket_prefix,
- const std::unique_ptr<SiteIsolationResponseMetaData>& resp_data,
- bool nosniff_block) {
- std::string block_label(nosniff_block ? ".NoSniffBlocked" : ".Blocked");
- IncrementHistogramCount(bucket_prefix + block_label);
-
- // The content is blocked if it is sniffed as HTML/JSON/XML. When
- // the blocked response is with an error status code, it is not
- // disruptive for the following reasons : 1) the blocked content is
- // not a binary object (such as an image) since it is sniffed as
- // text; 2) then, this blocking only breaks the renderer behavior
- // only if it is either JavaScript or CSS. However, the renderer
- // doesn't use the contents of JS/CSS with unaffected status code
- // (e.g, 404). 3) the renderer is expected not to use the cross-site
- // document content for purposes other than JS/CSS (e.g, XHR).
- bool renderable_status_code =
- IsRenderableStatusCode(resp_data->http_status_code);
-
- if (renderable_status_code) {
- IncrementHistogramEnum(
- bucket_prefix + block_label + ".RenderableStatusCode2",
- resp_data->resource_type, RESOURCE_TYPE_LAST_TYPE);
- } else {
- IncrementHistogramCount(bucket_prefix + block_label +
- ".NonRenderableStatusCode");
- }
-}
-
-void HistogramCountNotBlockedResponse(const std::string& bucket_prefix,
- bool sniffed_as_js) {
- IncrementHistogramCount(bucket_prefix + ".NotBlocked");
- if (sniffed_as_js)
- IncrementHistogramCount(bucket_prefix + ".NotBlocked.MaybeJS");
-}
-
-} // namespace
-
-SiteIsolationResponseMetaData::SiteIsolationResponseMetaData() {
-}
-
-void SiteIsolationStatsGatherer::SetEnabled(bool enabled) {
- g_stats_gathering_enabled = enabled;
-}
-
-std::unique_ptr<SiteIsolationResponseMetaData>
-SiteIsolationStatsGatherer::OnReceivedResponse(
- const url::Origin& frame_origin,
- const GURL& response_url,
- ResourceType resource_type,
- const network::ResourceResponseInfo& info) {
- if (!g_stats_gathering_enabled)
- return nullptr;
-
- UMA_HISTOGRAM_COUNTS("SiteIsolation.AllResponses", 1);
-
- // See if this is for navigation. If it is, don't block it, under the
- // assumption that we will put it in an appropriate process.
- if (IsResourceTypeFrame(resource_type))
- return nullptr;
-
- if (!CrossSiteDocumentClassifier::IsBlockableScheme(response_url))
- return nullptr;
-
- if (frame_origin.IsSameOriginWith(url::Origin::Create(response_url)))
- return nullptr;
-
- CrossSiteDocumentMimeType canonical_mime_type =
- CrossSiteDocumentClassifier::GetCanonicalMimeType(info.mime_type);
-
- if (canonical_mime_type == CROSS_SITE_DOCUMENT_MIME_TYPE_OTHERS)
- return nullptr;
-
- // Every CORS request should have the Access-Control-Allow-Origin header even
- // if it is preceded by a pre-flight request. Therefore, if this is a CORS
- // request, it has this header. response.httpHeaderField() internally uses
- // case-insensitive matching for the header name.
- std::string access_control_origin;
-
- // We can use a case-insensitive header name for EnumerateHeader().
- info.headers->EnumerateHeader(nullptr, "access-control-allow-origin",
- &access_control_origin);
- if (CrossSiteDocumentClassifier::IsValidCorsHeaderSet(
- frame_origin, access_control_origin)) {
- return nullptr;
- }
-
- // Real XSD data collection starts from here.
- std::string no_sniff;
- info.headers->EnumerateHeader(nullptr, "x-content-type-options", &no_sniff);
-
- std::unique_ptr<SiteIsolationResponseMetaData> resp_data(
- new SiteIsolationResponseMetaData);
- resp_data->response_url = response_url;
- resp_data->resource_type = resource_type;
- resp_data->canonical_mime_type = canonical_mime_type;
- resp_data->http_status_code = info.headers->response_code();
- resp_data->no_sniff = base::LowerCaseEqualsASCII(no_sniff, "nosniff");
-
- return resp_data;
-}
-
-bool SiteIsolationStatsGatherer::OnReceivedFirstChunk(
- const std::unique_ptr<SiteIsolationResponseMetaData>& resp_data,
- const char* raw_data,
- int raw_length) {
- if (!g_stats_gathering_enabled)
- return false;
-
- DCHECK(resp_data.get());
-
- base::StringPiece data(raw_data, raw_length);
-
- // Record the length of the first received chunk of data to see if it's enough
- // for sniffing.
- UMA_HISTOGRAM_COUNTS("SiteIsolation.XSD.DataLength", raw_length);
-
- // Record the number of cross-site document responses with a specific mime
- // type (text/html, text/xml, etc).
- UMA_HISTOGRAM_ENUMERATION("SiteIsolation.XSD.MimeType",
- resp_data->canonical_mime_type,
- CROSS_SITE_DOCUMENT_MIME_TYPE_MAX);
-
- // Store the result of cross-site document blocking analysis.
- bool would_block = false;
- bool sniffed_as_js = SniffForJS(data);
-
- // Record the number of responses whose content is sniffed for what its mime
- // type claims it to be. For example, we apply a HTML sniffer for a document
- // tagged with text/html here. Whenever this check becomes true, we'll block
- // the response.
- if (resp_data->canonical_mime_type != CROSS_SITE_DOCUMENT_MIME_TYPE_PLAIN) {
- std::string bucket_prefix;
- bool sniffed_as_target_document = false;
- if (resp_data->canonical_mime_type == CROSS_SITE_DOCUMENT_MIME_TYPE_HTML) {
- bucket_prefix = "SiteIsolation.XSD.HTML";
- sniffed_as_target_document =
- IsYes(CrossSiteDocumentClassifier::SniffForHTML(data));
- } else if (resp_data->canonical_mime_type ==
- CROSS_SITE_DOCUMENT_MIME_TYPE_XML) {
- bucket_prefix = "SiteIsolation.XSD.XML";
- sniffed_as_target_document =
- IsYes(CrossSiteDocumentClassifier::SniffForXML(data));
- } else if (resp_data->canonical_mime_type ==
- CROSS_SITE_DOCUMENT_MIME_TYPE_JSON) {
- bucket_prefix = "SiteIsolation.XSD.JSON";
- sniffed_as_target_document =
- IsYes(CrossSiteDocumentClassifier::SniffForJSON(data));
- } else {
- NOTREACHED() << "Not a blockable mime type: "
- << resp_data->canonical_mime_type;
- }
-
- if (sniffed_as_target_document) {
- would_block = true;
- HistogramCountBlockedResponse(bucket_prefix, resp_data, false);
- } else {
- if (resp_data->no_sniff) {
- would_block = true;
- HistogramCountBlockedResponse(bucket_prefix, resp_data, true);
- } else {
- HistogramCountNotBlockedResponse(bucket_prefix, sniffed_as_js);
- }
- }
- } else {
- // This block is for plain text documents. We apply our HTML, XML,
- // and JSON sniffer to a text document in the order, and block it
- // if any of them succeeds in sniffing.
- std::string bucket_prefix;
- if (IsYes(CrossSiteDocumentClassifier::SniffForHTML(data)))
- bucket_prefix = "SiteIsolation.XSD.Plain.HTML";
- else if (IsYes(CrossSiteDocumentClassifier::SniffForXML(data)))
- bucket_prefix = "SiteIsolation.XSD.Plain.XML";
- else if (IsYes(CrossSiteDocumentClassifier::SniffForJSON(data)))
- bucket_prefix = "SiteIsolation.XSD.Plain.JSON";
-
- if (bucket_prefix.size() > 0) {
- would_block = true;
- HistogramCountBlockedResponse(bucket_prefix, resp_data, false);
- } else if (resp_data->no_sniff) {
- would_block = true;
- HistogramCountBlockedResponse("SiteIsolation.XSD.Plain", resp_data, true);
- } else {
- HistogramCountNotBlockedResponse("SiteIsolation.XSD.Plain",
- sniffed_as_js);
- }
- }
-
- return would_block;
-}
-
-bool SiteIsolationStatsGatherer::SniffForJS(base::StringPiece data) {
- // The purpose of this function is to try to see if there's any possibility
- // that this data can be JavaScript (superset of JS). Search for "var " for JS
- // detection. This is a real hack and should only be used for stats gathering.
- return data.find("var ") != base::StringPiece::npos;
-}
-
-} // namespace content
diff --git a/chromium/content/renderer/loader/site_isolation_stats_gatherer.h b/chromium/content/renderer/loader/site_isolation_stats_gatherer.h
deleted file mode 100644
index 1c25f539401..00000000000
--- a/chromium/content/renderer/loader/site_isolation_stats_gatherer.h
+++ /dev/null
@@ -1,102 +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 CONTENT_RENDERER_LOADER_SITE_ISOLATION_STATS_GATHERER_H_
-#define CONTENT_RENDERER_LOADER_SITE_ISOLATION_STATS_GATHERER_H_
-
-#include <memory>
-#include <string>
-
-#include "base/gtest_prod_util.h"
-#include "base/macros.h"
-#include "base/strings/string_piece.h"
-#include "content/common/content_export.h"
-#include "content/common/cross_site_document_classifier.h"
-#include "content/public/common/resource_type.h"
-#include "url/gurl.h"
-#include "url/origin.h"
-
-namespace network {
-struct ResourceResponseInfo;
-}
-
-namespace content {
-
-// SiteIsolationStatsGatherer monitors responses to gather various UMA stats to
-// see the compatibility impact of actual deployment of the policy. The UMA stat
-// categories SiteIsolationStatsGatherer gathers are as follows:
-//
-// SiteIsolation.AllResponses : # of all network responses.
-// SiteIsolation.XSD.DataLength : the length of the first packet of a response.
-// SiteIsolation.XSD.MimeType (enum):
-// # of responses from other sites, tagged with a document mime type.
-// 0:HTML, 1:XML, 2:JSON, 3:Plain, 4:Others
-// SiteIsolation.XSD.[%MIMETYPE].Blocked :
-// blocked # of cross-site document responses grouped by sniffed MIME type.
-// SiteIsolation.XSD.[%MIMETYPE].Blocked.RenderableStatusCode2 :
-// # of responses with renderable status code,
-// out of SiteIsolation.XSD.[%MIMETYPE].Blocked.
-// SiteIsolation.XSD.[%MIMETYPE].Blocked.NonRenderableStatusCode :
-// # of responses with non-renderable status code,
-// out of SiteIsolation.XSD.[%MIMETYPE].Blocked.
-// SiteIsolation.XSD.[%MIMETYPE].NoSniffBlocked.RenderableStatusCode2 :
-// # of responses failed to be sniffed for its MIME type, but blocked by
-// "X-Content-Type-Options: nosniff" header, and with renderable status code
-// out of SiteIsolation.XSD.[%MIMETYPE].Blocked.
-// SiteIsolation.XSD.[%MIMETYPE].NoSniffBlocked.NonRenderableStatusCode :
-// # of responses failed to be sniffed for its MIME type, but blocked by
-// "X-Content-Type-Options: nosniff" header, and with non-renderable status
-// code out of SiteIsolation.XSD.[%MIMETYPE].Blocked.
-// SiteIsolation.XSD.[%MIMETYPE].NotBlocked :
-// # of responses, but not blocked due to failure of mime sniffing.
-// SiteIsolation.XSD.[%MIMETYPE].NotBlocked.MaybeJS :
-// # of responses that are plausibly sniffed to be JavaScript.
-
-struct SiteIsolationResponseMetaData {
- SiteIsolationResponseMetaData();
-
- GURL response_url;
- ResourceType resource_type;
- CrossSiteDocumentMimeType canonical_mime_type;
- int http_status_code;
- bool no_sniff;
-};
-
-class CONTENT_EXPORT SiteIsolationStatsGatherer {
- public:
- // Set activation flag for the UMA data collection for this renderer process.
- static void SetEnabled(bool enabled);
-
- // Returns any bookkeeping data about the HTTP header information for the
- // request identified by |request_id|. Any data returned should then be
- // passed to OnReceivedFirstChunk() with the first data chunk.
- static std::unique_ptr<SiteIsolationResponseMetaData> OnReceivedResponse(
- const url::Origin& frame_origin,
- const GURL& response_url,
- ResourceType resource_type,
- const network::ResourceResponseInfo& info);
-
- // Examines the first chunk of network data in case response_url is registered
- // as a cross-site document by OnReceivedResponse(). This records various
- // kinds of UMA data stats. This function is called only if the length of
- // received data is non-zero.
- static bool OnReceivedFirstChunk(
- const std::unique_ptr<SiteIsolationResponseMetaData>& resp_data,
- const char* payload,
- int length);
-
- private:
- FRIEND_TEST_ALL_PREFIXES(SiteIsolationStatsGathererTest, SniffForJS);
-
- SiteIsolationStatsGatherer(); // Not instantiable.
-
- // Imprecise JS sniffing; only appropriate for collecting UMA stat.
- static bool SniffForJS(base::StringPiece data);
-
- DISALLOW_COPY_AND_ASSIGN(SiteIsolationStatsGatherer);
-};
-
-} // namespace content
-
-#endif // CONTENT_RENDERER_LOADER_SITE_ISOLATION_STATS_GATHERER_H_
diff --git a/chromium/content/renderer/loader/site_isolation_stats_gatherer_browsertest.cc b/chromium/content/renderer/loader/site_isolation_stats_gatherer_browsertest.cc
deleted file mode 100644
index 124eea57bce..00000000000
--- a/chromium/content/renderer/loader/site_isolation_stats_gatherer_browsertest.cc
+++ /dev/null
@@ -1,207 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "base/command_line.h"
-#include "base/macros.h"
-#include "base/strings/pattern.h"
-#include "base/strings/string_util.h"
-#include "base/strings/stringprintf.h"
-#include "base/test/histogram_tester.h"
-#include "content/public/common/content_switches.h"
-#include "content/public/common/resource_type.h"
-#include "content/public/test/browser_test_utils.h"
-#include "content/public/test/content_browser_test.h"
-#include "content/public/test/content_browser_test_utils.h"
-#include "content/public/test/test_utils.h"
-#include "content/shell/browser/shell.h"
-#include "net/test/embedded_test_server/embedded_test_server.h"
-#include "services/network/public/cpp/network_switches.h"
-#include "testing/gmock/include/gmock/gmock.h"
-
-namespace content {
-
-// These tests simulate exploited renderer processes, which can fetch arbitrary
-// resources from other websites, not constrained by the Same Origin Policy. We
-// are trying to verify that the renderer cannot fetch any cross-site document
-// responses even when the Same Origin Policy is turned off inside the renderer.
-class SiteIsolationStatsGathererBrowserTest : public ContentBrowserTest {
- public:
- SiteIsolationStatsGathererBrowserTest() {}
- ~SiteIsolationStatsGathererBrowserTest() override {}
-
- void SetUpCommandLine(base::CommandLine* command_line) override {
- // EmbeddedTestServer::InitializeAndListen() initializes its |base_url_|
- // which is required below. This cannot invoke Start() however as that kicks
- // off the "EmbeddedTestServer IO Thread" which then races with
- // initialization in ContentBrowserTest::SetUp(), http://crbug.com/674545.
- ASSERT_TRUE(embedded_test_server()->InitializeAndListen());
-
- // Add a host resolver rule to map all outgoing requests to the test server.
- // This allows us to use "real" hostnames in URLs, which we can use to
- // create arbitrary SiteInstances.
- command_line->AppendSwitchASCII(
- network::switches::kHostResolverRules,
- "MAP * " + embedded_test_server()->host_port_pair().ToString() +
- ",EXCLUDE localhost");
-
- // Since we assume exploited renderer process, it can bypass the same origin
- // policy at will. Simulate that by passing the disable-web-security flag.
- command_line->AppendSwitch(switches::kDisableWebSecurity);
- }
-
- void SetUpOnMainThread() override {
- // Complete the manual Start() after ContentBrowserTest's own
- // initialization, ref. comment on InitializeAndListen() above.
- embedded_test_server()->StartAcceptingConnections();
- }
-
- void InspectHistograms(const base::HistogramTester& histograms,
- bool should_be_blocked,
- const std::string& resource_name) {
- std::string bucket;
- int mime_type = 0; // Hardcoded because histogram enums mustn't change.
- if (base::MatchPattern(resource_name, "*.html")) {
- bucket = "HTML";
- mime_type = 0;
- } else if (base::MatchPattern(resource_name, "*.xml")) {
- bucket = "XML";
- mime_type = 1;
- } else if (base::MatchPattern(resource_name, "*.json")) {
- bucket = "JSON";
- mime_type = 2;
- } else if (base::MatchPattern(resource_name, "*.txt")) {
- bucket = "Plain";
- mime_type = 3;
- if (base::MatchPattern(resource_name, "json*")) {
- bucket += ".JSON";
- } else if (base::MatchPattern(resource_name, "html*")) {
- bucket += ".HTML";
- } else if (base::MatchPattern(resource_name, "xml*")) {
- bucket += ".XML";
- }
- } else {
- FAIL();
- }
- FetchHistogramsFromChildProcesses();
-
- // A few histograms are incremented unconditionally.
- histograms.ExpectUniqueSample("SiteIsolation.AllResponses", 1, 1);
- base::HistogramTester::CountsMap expected_metrics;
- expected_metrics["SiteIsolation.XSD.DataLength"] = 1;
- expected_metrics["SiteIsolation.XSD.MimeType"] = 1;
-
- // Determine the appropriate conditionally-incremented histograms.
- std::string base = "SiteIsolation.XSD." + bucket;
- if (should_be_blocked) {
- expected_metrics[base + ".Blocked"] = 1;
- expected_metrics[base + ".Blocked.RenderableStatusCode2"] = 1;
- } else {
- expected_metrics[base + ".NotBlocked"] = 1;
- if (base::MatchPattern(resource_name, "*js.*")) {
- expected_metrics[base + ".NotBlocked.MaybeJS"] = 1;
- }
- }
- // This metric from the browser process also records start and stop actions
- // for the blocking logic, even though blocking is disabled in the browser
- // process when this test runs.
- expected_metrics["SiteIsolation.XSD.Browser.Action"] = 2;
-
- // Make sure that the expected metrics, and only those metrics, were
- // incremented.
- EXPECT_THAT(histograms.GetTotalCountsForPrefix("SiteIsolation.XSD."),
- testing::ContainerEq(expected_metrics))
- << "For resource_name=" << resource_name
- << ", should_be_blocked=" << should_be_blocked;
-
- EXPECT_THAT(histograms.GetAllSamples("SiteIsolation.XSD.MimeType"),
- testing::ElementsAre(base::Bucket(mime_type, 1)))
- << "The wrong mime type bucket was incremented.";
- if (should_be_blocked) {
- static_assert(13 == RESOURCE_TYPE_XHR, "Histogram enums mustn't change.");
- EXPECT_THAT(
- histograms.GetAllSamples(base + ".Blocked.RenderableStatusCode2"),
- testing::ElementsAre(base::Bucket(RESOURCE_TYPE_XHR, 1)))
- << "The wrong RenderableStatusCode2 bucket was incremented.";
- }
- }
-
- private:
- DISALLOW_COPY_AND_ASSIGN(SiteIsolationStatsGathererBrowserTest);
-};
-
-IN_PROC_BROWSER_TEST_F(SiteIsolationStatsGathererBrowserTest,
- CrossSiteDocumentBlockingForMimeType) {
- // This test is disabled in --site-per-process, since the documents are
- // blocked before arriving in the renderer process and thus the existing
- // histograms do not work.
- if (AreAllSitesIsolatedForTesting())
- return;
-
- // Load a page that issues illegal cross-site document requests to bar.com.
- // The page uses XHR to request HTML/XML/JSON documents from bar.com, and
- // inspects if any of them were successfully received. Currently, on illegal
- // access, the XHR requests should succeed, but the UMA histograms should
- // record that they would have been blocked. This test is only possible since
- // we run the browser without the same origin policy.
- GURL foo("http://foo.com/cross_site_document_blocking/request.html");
-
- EXPECT_TRUE(NavigateToURL(shell(), foo));
-
- // Flush out existing histogram activity.
- FetchHistogramsFromChildProcesses();
-
- // The following are files under content/test/data/site_isolation. All
- // should be disallowed for cross site XHR under the document blocking policy.
- const char* blocked_resources[] = {
- "comment_valid.html", "html.txt", "html4_dtd.html", "html4_dtd.txt",
- "html5_dtd.html", "html5_dtd.txt", "json.txt", "valid.html",
- "valid.json", "valid.xml", "xml.txt"};
-
- for (const char* resource : blocked_resources) {
- SCOPED_TRACE(base::StringPrintf("... while testing page: %s", resource));
- base::HistogramTester histograms;
-
- bool was_blocked;
- ASSERT_TRUE(ExecuteScriptAndExtractBool(
- shell(), base::StringPrintf("sendRequest('%s');", resource),
- &was_blocked));
- ASSERT_FALSE(was_blocked);
-
- InspectHistograms(histograms, true, resource);
- }
-
- // These files should be allowed for XHR under the document blocking policy.
- const char* allowed_resources[] = {"js.html", "comment_js.html", "js.xml",
- "js.json", "js.txt", "img.html",
- "img.xml", "img.json", "img.txt"};
- for (const char* resource : allowed_resources) {
- SCOPED_TRACE(base::StringPrintf("... while testing page: %s", resource));
- base::HistogramTester histograms;
-
- bool was_blocked;
- ASSERT_TRUE(ExecuteScriptAndExtractBool(
- shell(), base::StringPrintf("sendRequest('%s');", resource),
- &was_blocked));
- ASSERT_FALSE(was_blocked);
-
- InspectHistograms(histograms, false, resource);
- }
-}
-
-IN_PROC_BROWSER_TEST_F(SiteIsolationStatsGathererBrowserTest,
- CrossSiteDocumentBlockingForDifferentTargets) {
- // This webpage loads a cross-site HTML page in different targets such as
- // <img>,<link>,<embed>, etc. Since the requested document is blocked, and one
- // character string (' ') is returned instead, this tests that the renderer
- // does not crash even when it receives a response body which is " ", whose
- // length is different from what's described in "content-length" for such
- // different targets.
-
- // TODO(nick): Split up these cases, and add positive assertions here about
- // what actually happens in these various resource-block cases.
- GURL foo("http://foo.com/cross_site_document_blocking/request_target.html");
- EXPECT_TRUE(NavigateToURL(shell(), foo));
-}
-
-} // namespace content
diff --git a/chromium/content/renderer/loader/site_isolation_stats_gatherer_unittest.cc b/chromium/content/renderer/loader/site_isolation_stats_gatherer_unittest.cc
deleted file mode 100644
index f34659c993c..00000000000
--- a/chromium/content/renderer/loader/site_isolation_stats_gatherer_unittest.cc
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "base/strings/string_piece.h"
-#include "content/renderer/loader/site_isolation_stats_gatherer.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-using base::StringPiece;
-
-namespace content {
-
-TEST(SiteIsolationStatsGathererTest, SniffForJS) {
- StringPiece basic_js_data("var a = 4");
- StringPiece js_data("\t\t\r\n var a = 4");
- StringPiece json_data("\t\t\r\n { \"name\" : \"chrome\", ");
- StringPiece empty_data("");
-
- EXPECT_TRUE(SiteIsolationStatsGatherer::SniffForJS(js_data));
- EXPECT_FALSE(SiteIsolationStatsGatherer::SniffForJS(json_data));
-
- // Basic bounds check.
- EXPECT_FALSE(SiteIsolationStatsGatherer::SniffForJS(empty_data));
-}
-
-} // namespace content
diff --git a/chromium/content/renderer/loader/sync_load_context.cc b/chromium/content/renderer/loader/sync_load_context.cc
index 70c9ead0abf..fc94a225897 100644
--- a/chromium/content/renderer/loader/sync_load_context.cc
+++ b/chromium/content/renderer/loader/sync_load_context.cc
@@ -21,19 +21,24 @@ void SyncLoadContext::StartAsyncWithWaitableEvent(
std::unique_ptr<network::ResourceRequest> request,
int routing_id,
scoped_refptr<base::SingleThreadTaskRunner> loading_task_runner,
- const url::Origin& frame_origin,
const net::NetworkTrafficAnnotationTag& traffic_annotation,
- std::unique_ptr<SharedURLLoaderFactoryInfo> url_loader_factory_info,
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo>
+ url_loader_factory_info,
std::vector<std::unique_ptr<URLLoaderThrottle>> throttles,
SyncLoadResponse* response,
- base::WaitableEvent* event) {
- auto* context =
- new SyncLoadContext(request.get(), std::move(url_loader_factory_info),
- response, event, loading_task_runner);
-
+ base::WaitableEvent* completed_event,
+ base::WaitableEvent* abort_event,
+ double timeout,
+ blink::mojom::BlobRegistryPtrInfo download_to_blob_registry) {
+ bool download_to_blob = download_to_blob_registry.is_valid();
+ auto* context = new SyncLoadContext(
+ request.get(), std::move(url_loader_factory_info), response,
+ completed_event, abort_event, timeout,
+ std::move(download_to_blob_registry), loading_task_runner);
context->request_id_ = context->resource_dispatcher_->StartAsync(
std::move(request), routing_id, std::move(loading_task_runner),
- frame_origin, traffic_annotation, true /* is_sync */,
+ traffic_annotation, true /* is_sync */,
+ download_to_blob /* pass_response_pipe_to_peer */,
base::WrapUnique(context), context->url_loader_factory_,
std::move(throttles), network::mojom::URLLoaderClientEndpointsPtr(),
nullptr /* continue_for_navigation */);
@@ -41,13 +46,29 @@ void SyncLoadContext::StartAsyncWithWaitableEvent(
SyncLoadContext::SyncLoadContext(
network::ResourceRequest* request,
- std::unique_ptr<SharedURLLoaderFactoryInfo> url_loader_factory,
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo> url_loader_factory,
SyncLoadResponse* response,
- base::WaitableEvent* event,
+ base::WaitableEvent* completed_event,
+ base::WaitableEvent* abort_event,
+ double timeout,
+ blink::mojom::BlobRegistryPtrInfo download_to_blob_registry,
scoped_refptr<base::SingleThreadTaskRunner> task_runner)
- : response_(response), event_(event), task_runner_(std::move(task_runner)) {
+ : response_(response),
+ completed_event_(completed_event),
+ download_to_blob_registry_(std::move(download_to_blob_registry)),
+ task_runner_(std::move(task_runner)) {
url_loader_factory_ =
- SharedURLLoaderFactory::Create(std::move(url_loader_factory));
+ network::SharedURLLoaderFactory::Create(std::move(url_loader_factory));
+ if (abort_event) {
+ abort_watcher_.StartWatching(
+ abort_event,
+ base::BindOnce(&SyncLoadContext::OnAbort, base::Unretained(this)),
+ task_runner_);
+ }
+ if (timeout) {
+ timeout_timer_.Start(FROM_HERE, base::TimeDelta::FromSecondsD(timeout),
+ this, &SyncLoadContext::OnTimeout);
+ }
// Constructs a new ResourceDispatcher specifically for this request.
resource_dispatcher_ = std::make_unique<ResourceDispatcher>();
@@ -64,10 +85,12 @@ void SyncLoadContext::OnUploadProgress(uint64_t position, uint64_t size) {}
bool SyncLoadContext::OnReceivedRedirect(
const net::RedirectInfo& redirect_info,
const network::ResourceResponseInfo& info) {
+ DCHECK(!Completed());
if (redirect_info.new_url.GetOrigin() != response_->url.GetOrigin()) {
LOG(ERROR) << "Cross origin redirect denied";
response_->error_code = net::ERR_ABORTED;
- event_->Signal();
+
+ CompleteRequest(false /* remove_pending_request */);
// Returning false here will cause the request to be cancelled and this
// object deleted.
@@ -80,24 +103,32 @@ bool SyncLoadContext::OnReceivedRedirect(
void SyncLoadContext::OnReceivedResponse(
const network::ResourceResponseInfo& info) {
- response_->headers = info.headers;
- response_->mime_type = info.mime_type;
- response_->charset = info.charset;
- response_->request_time = info.request_time;
- response_->response_time = info.response_time;
- response_->load_timing = info.load_timing;
- response_->raw_request_response_info = info.raw_request_response_info;
- response_->download_file_path = info.download_file_path;
- response_->socket_address = info.socket_address;
+ DCHECK(!Completed());
+ response_->info = info;
+}
+
+void SyncLoadContext::OnStartLoadingResponseBody(
+ mojo::ScopedDataPipeConsumerHandle body) {
+ DCHECK(download_to_blob_registry_);
+ DCHECK(!blob_response_started_);
+
+ blob_response_started_ = true;
+
+ download_to_blob_registry_->RegisterFromStream(
+ response_->info.mime_type, "",
+ std::max<int64_t>(0, response_->info.content_length), std::move(body),
+ nullptr,
+ base::BindOnce(&SyncLoadContext::OnFinishCreatingBlob,
+ base::Unretained(this)));
}
void SyncLoadContext::OnDownloadedData(int len, int encoded_data_length) {
- // This method is only called when RequestInfo::download_to_file is true which
- // is not allowed when processing a synchronous request.
- NOTREACHED();
+ downloaded_file_length_ =
+ (downloaded_file_length_ ? *downloaded_file_length_ : 0) + len;
}
void SyncLoadContext::OnReceivedData(std::unique_ptr<ReceivedData> data) {
+ DCHECK(!Completed());
response_->data.append(data->payload(), data->length());
}
@@ -105,15 +136,68 @@ void SyncLoadContext::OnTransferSizeUpdated(int transfer_size_diff) {}
void SyncLoadContext::OnCompletedRequest(
const network::URLLoaderCompletionStatus& status) {
+ DCHECK(!Completed());
response_->error_code = status.error_code;
+ response_->extended_error_code = status.extended_error_code;
if (status.cors_error_status)
response_->cors_error = status.cors_error_status->cors_error;
- response_->encoded_data_length = status.encoded_data_length;
- response_->encoded_body_length = status.encoded_body_length;
- event_->Signal();
+ response_->info.encoded_data_length = status.encoded_data_length;
+ response_->info.encoded_body_length = status.encoded_body_length;
+ response_->downloaded_file_length = downloaded_file_length_;
+ // Need to pass |downloaded_tmp_file| to the caller thread. Otherwise the blob
+ // creation in ResourceResponse::SetDownloadedFilePath() fails.
+ response_->downloaded_tmp_file =
+ resource_dispatcher_->TakeDownloadedTempFile(request_id_);
+ DCHECK_EQ(!response_->downloaded_file_length,
+ !response_->downloaded_tmp_file);
+ if (blob_response_started_ && !blob_finished_) {
+ request_completed_ = true;
+ return;
+ }
+ CompleteRequest(true /* remove_pending_request */);
+}
+
+void SyncLoadContext::OnFinishCreatingBlob(
+ blink::mojom::SerializedBlobPtr blob) {
+ DCHECK(!Completed());
+ blob_finished_ = true;
+ response_->downloaded_blob = std::move(blob);
+ if (request_completed_)
+ CompleteRequest(true /* remove_pending_request */);
+}
+
+void SyncLoadContext::OnAbort(base::WaitableEvent* event) {
+ DCHECK(!Completed());
+ response_->error_code = net::ERR_ABORTED;
+ CompleteRequest(true /* remove_pending_request */);
+}
+
+void SyncLoadContext::OnTimeout() {
+ // OnTimeout() must not be called after CompleteRequest() was called, because
+ // the OneShotTimer must have been stopped.
+ DCHECK(!Completed());
+ response_->error_code = net::ERR_TIMED_OUT;
+ CompleteRequest(true /* remove_pending_request */);
+}
+
+void SyncLoadContext::CompleteRequest(bool remove_pending_request) {
+ abort_watcher_.StopWatching();
+ timeout_timer_.AbandonAndStop();
+
+ completed_event_->Signal();
+
+ completed_event_ = nullptr;
+ response_ = nullptr;
+
+ if (remove_pending_request) {
+ // This will indirectly cause this object to be deleted.
+ resource_dispatcher_->RemovePendingRequest(request_id_, task_runner_);
+ }
+}
- // This will indirectly cause this object to be deleted.
- resource_dispatcher_->RemovePendingRequest(request_id_, task_runner_);
+bool SyncLoadContext::Completed() const {
+ DCHECK_EQ(!completed_event_, !response_);
+ return !response_;
}
} // namespace content
diff --git a/chromium/content/renderer/loader/sync_load_context.h b/chromium/content/renderer/loader/sync_load_context.h
index 53b6704f668..b0b474405a3 100644
--- a/chromium/content/renderer/loader/sync_load_context.h
+++ b/chromium/content/renderer/loader/sync_load_context.h
@@ -6,19 +6,19 @@
#define CONTENT_RENDERER_LOADER_SYNC_LOAD_CONTEXT_H_
#include "base/macros.h"
-#include "content/public/common/shared_url_loader_factory.h"
+#include "base/optional.h"
+#include "base/synchronization/waitable_event_watcher.h"
+#include "base/timer/timer.h"
#include "content/public/renderer/request_peer.h"
#include "content/renderer/loader/resource_dispatcher.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
+#include "third_party/blink/public/mojom/blob/blob_registry.mojom.h"
namespace base {
class WaitableEvent;
}
-namespace url {
-class Origin;
-}
-
namespace network {
struct ResourceRequest;
}
@@ -32,54 +32,87 @@ struct SyncLoadResponse;
class SyncLoadContext : public RequestPeer {
public:
// Begins a new asynchronous request on whatever sequence this method is
- // called on. |event| will be signalled when the request is complete and
- // |response| will be populated with the response data.
+ // called on. |completed_event| will be signalled when the request is complete
+ // and |response| will be populated with the response data. |abort_event|
+ // will be signalled from the main thread to abort the sync request on a
+ // worker thread when the worker thread is being terminated.
+ // If |download_to_blob_registry| is not null, it is used to redirect the
+ // download to a blob, with the resulting blob populated in |response|.
static void StartAsyncWithWaitableEvent(
std::unique_ptr<network::ResourceRequest> request,
int routing_id,
scoped_refptr<base::SingleThreadTaskRunner> loading_task_runner,
- const url::Origin& frame_origin,
const net::NetworkTrafficAnnotationTag& traffic_annotation,
- std::unique_ptr<SharedURLLoaderFactoryInfo> url_loader_factory_info,
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo>
+ url_loader_factory_info,
std::vector<std::unique_ptr<URLLoaderThrottle>> throttles,
SyncLoadResponse* response,
- base::WaitableEvent* event);
+ base::WaitableEvent* completed_event,
+ base::WaitableEvent* abort_event,
+ double timeout,
+ blink::mojom::BlobRegistryPtrInfo download_to_blob_registry);
+
+ ~SyncLoadContext() override;
+ private:
SyncLoadContext(
network::ResourceRequest* request,
- std::unique_ptr<SharedURLLoaderFactoryInfo> url_loader_factory,
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo> url_loader_factory,
SyncLoadResponse* response,
- base::WaitableEvent* event,
+ base::WaitableEvent* completed_event,
+ base::WaitableEvent* abort_event,
+ double timeout,
+ blink::mojom::BlobRegistryPtrInfo download_to_blob_registry,
scoped_refptr<base::SingleThreadTaskRunner> task_runner);
- ~SyncLoadContext() override;
-
- private:
// RequestPeer implementation:
void OnUploadProgress(uint64_t position, uint64_t size) override;
bool OnReceivedRedirect(const net::RedirectInfo& redirect_info,
const network::ResourceResponseInfo& info) override;
void OnReceivedResponse(const network::ResourceResponseInfo& info) override;
+ void OnStartLoadingResponseBody(
+ mojo::ScopedDataPipeConsumerHandle body) override;
void OnDownloadedData(int len, int encoded_data_length) override;
void OnReceivedData(std::unique_ptr<ReceivedData> data) override;
void OnTransferSizeUpdated(int transfer_size_diff) override;
void OnCompletedRequest(
const network::URLLoaderCompletionStatus& status) override;
+ void OnFinishCreatingBlob(blink::mojom::SerializedBlobPtr blob);
+
+ void OnAbort(base::WaitableEvent* event);
+ void OnTimeout();
+
+ void CompleteRequest(bool remove_pending_request);
+ bool Completed() const;
+
// This raw pointer will remain valid for the lifetime of this object because
// it remains on the stack until |event_| is signaled.
+ // Set to null after CompleteRequest() is called.
SyncLoadResponse* response_;
// This event is signaled when the request is complete.
- base::WaitableEvent* event_;
+ // Set to null after CompleteRequest() is called.
+ base::WaitableEvent* completed_event_;
// State necessary to run a request on an independent thread.
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory_;
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
std::unique_ptr<ResourceDispatcher> resource_dispatcher_;
+ // State for downloading to a blob.
+ blink::mojom::BlobRegistryPtr download_to_blob_registry_;
+ bool blob_response_started_ = false;
+ bool blob_finished_ = false;
+ bool request_completed_ = false;
+
int request_id_;
scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
+ base::Optional<int64_t> downloaded_file_length_;
+
+ base::WaitableEventWatcher abort_watcher_;
+ base::OneShotTimer timeout_timer_;
+
DISALLOW_COPY_AND_ASSIGN(SyncLoadContext);
};
diff --git a/chromium/content/renderer/loader/sync_load_response.cc b/chromium/content/renderer/loader/sync_load_response.cc
index a9e8ee12ded..d3a5ef8d1a8 100644
--- a/chromium/content/renderer/loader/sync_load_response.cc
+++ b/chromium/content/renderer/loader/sync_load_response.cc
@@ -8,6 +8,11 @@ namespace content {
SyncLoadResponse::SyncLoadResponse() {}
+SyncLoadResponse::SyncLoadResponse(SyncLoadResponse&& other) = default;
+
SyncLoadResponse::~SyncLoadResponse() {}
+SyncLoadResponse& SyncLoadResponse::operator=(SyncLoadResponse&& other) =
+ default;
+
} // namespace content
diff --git a/chromium/content/renderer/loader/sync_load_response.h b/chromium/content/renderer/loader/sync_load_response.h
index 049f2a287d0..bd46a9b14a9 100644
--- a/chromium/content/renderer/loader/sync_load_response.h
+++ b/chromium/content/renderer/loader/sync_load_response.h
@@ -11,18 +11,28 @@
#include "content/common/content_export.h"
#include "services/network/public/cpp/resource_response_info.h"
#include "services/network/public/mojom/cors.mojom.h"
+#include "services/network/public/mojom/url_loader.mojom.h"
+#include "third_party/blink/public/mojom/blob/serialized_blob.mojom.h"
#include "url/gurl.h"
namespace content {
// See the SyncLoad method. (The name of this struct is not
// suffixed with "Info" because it also contains the response data.)
-struct CONTENT_EXPORT SyncLoadResponse : network::ResourceResponseInfo {
+struct CONTENT_EXPORT SyncLoadResponse {
SyncLoadResponse();
+ SyncLoadResponse(SyncLoadResponse&& other);
~SyncLoadResponse();
+ SyncLoadResponse& operator=(SyncLoadResponse&& other);
+
+ network::ResourceResponseInfo info;
+
// The response error code.
- int error_code = 0;
+ int error_code;
+
+ // The response extended error code.
+ int extended_error_code = 0;
// Optional CORS error details.
base::Optional<network::mojom::CORSError> cors_error;
@@ -33,6 +43,11 @@ struct CONTENT_EXPORT SyncLoadResponse : network::ResourceResponseInfo {
// The response data.
std::string data;
+
+ // Used for blob response type XMLHttpRequest.
+ base::Optional<int64_t> downloaded_file_length;
+ network::mojom::DownloadedTempFilePtr downloaded_tmp_file;
+ blink::mojom::SerializedBlobPtr downloaded_blob;
};
} // namespace content
diff --git a/chromium/content/renderer/loader/test_request_peer.cc b/chromium/content/renderer/loader/test_request_peer.cc
index 775eb437186..42b46e16e41 100644
--- a/chromium/content/renderer/loader/test_request_peer.cc
+++ b/chromium/content/renderer/loader/test_request_peer.cc
@@ -7,7 +7,7 @@
#include "content/renderer/loader/resource_dispatcher.h"
#include "net/url_request/redirect_info.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
namespace content {
@@ -46,6 +46,13 @@ void TestRequestPeer::OnReceivedResponse(
}
}
+void TestRequestPeer::OnStartLoadingResponseBody(
+ mojo::ScopedDataPipeConsumerHandle body) {
+ EXPECT_TRUE(context_->received_response);
+ EXPECT_FALSE(context_->cancelled);
+ EXPECT_FALSE(context_->complete);
+}
+
void TestRequestPeer::OnDownloadedData(int len, int encoded_data_length) {
EXPECT_TRUE(context_->received_response);
EXPECT_FALSE(context_->cancelled);
diff --git a/chromium/content/renderer/loader/test_request_peer.h b/chromium/content/renderer/loader/test_request_peer.h
index 9fe5cf96958..06e3a24e7c0 100644
--- a/chromium/content/renderer/loader/test_request_peer.h
+++ b/chromium/content/renderer/loader/test_request_peer.h
@@ -37,6 +37,8 @@ class TestRequestPeer : public RequestPeer {
bool OnReceivedRedirect(const net::RedirectInfo& redirect_info,
const network::ResourceResponseInfo& info) override;
void OnReceivedResponse(const network::ResourceResponseInfo& info) override;
+ void OnStartLoadingResponseBody(
+ mojo::ScopedDataPipeConsumerHandle body) override;
void OnDownloadedData(int len, int encoded_data_length) override;
void OnReceivedData(std::unique_ptr<ReceivedData> data) override;
void OnTransferSizeUpdated(int transfer_size_diff) override;
diff --git a/chromium/content/renderer/loader/tracked_child_url_loader_factory_bundle.cc b/chromium/content/renderer/loader/tracked_child_url_loader_factory_bundle.cc
index c970d9aec49..75485fe551a 100644
--- a/chromium/content/renderer/loader/tracked_child_url_loader_factory_bundle.cc
+++ b/chromium/content/renderer/loader/tracked_child_url_loader_factory_bundle.cc
@@ -25,7 +25,7 @@ TrackedChildURLLoaderFactoryBundleInfo::TrackedChildURLLoaderFactoryBundleInfo(
TrackedChildURLLoaderFactoryBundleInfo::
~TrackedChildURLLoaderFactoryBundleInfo() = default;
-scoped_refptr<SharedURLLoaderFactory>
+scoped_refptr<network::SharedURLLoaderFactory>
TrackedChildURLLoaderFactoryBundleInfo::CreateFactory() {
auto other = std::make_unique<TrackedChildURLLoaderFactoryBundleInfo>();
other->default_factory_info_ = std::move(default_factory_info_);
@@ -43,7 +43,7 @@ TrackedChildURLLoaderFactoryBundle::TrackedChildURLLoaderFactoryBundle(
std::unique_ptr<TrackedChildURLLoaderFactoryBundleInfo> info) {
DCHECK(info->main_thread_host_bundle());
main_thread_host_bundle_ = std::move(info->main_thread_host_bundle());
- Update(std::move(info));
+ Update(std::move(info), base::nullopt);
AddObserverOnMainThread();
}
@@ -51,7 +51,7 @@ TrackedChildURLLoaderFactoryBundle::~TrackedChildURLLoaderFactoryBundle() {
RemoveObserverOnMainThread();
};
-std::unique_ptr<SharedURLLoaderFactoryInfo>
+std::unique_ptr<network::SharedURLLoaderFactoryInfo>
TrackedChildURLLoaderFactoryBundle::Clone() {
auto info = base::WrapUnique(static_cast<ChildURLLoaderFactoryBundleInfo*>(
ChildURLLoaderFactoryBundle::Clone().release()));
@@ -96,30 +96,33 @@ void TrackedChildURLLoaderFactoryBundle::RemoveObserverOnMainThread() {
}
void TrackedChildURLLoaderFactoryBundle::OnUpdate(
- std::unique_ptr<SharedURLLoaderFactoryInfo> info) {
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo> info) {
Update(base::WrapUnique(
- static_cast<ChildURLLoaderFactoryBundleInfo*>(info.release())));
+ static_cast<ChildURLLoaderFactoryBundleInfo*>(info.release())),
+ base::nullopt);
}
// -----------------------------------------------------------------------------
-HostChildURLLoaderFactoryBundle::HostChildURLLoaderFactoryBundle()
- : observer_list_(std::make_unique<ObserverList>()) {
+HostChildURLLoaderFactoryBundle::HostChildURLLoaderFactoryBundle(
+ scoped_refptr<base::SequencedTaskRunner> task_runner)
+ : observer_list_(std::make_unique<ObserverList>()),
+ task_runner_(std::move(task_runner)) {
DCHECK(RenderThread::Get()) << "HostChildURLLoaderFactoryBundle should live "
"on the main renderer thread";
}
HostChildURLLoaderFactoryBundle::~HostChildURLLoaderFactoryBundle() = default;
-std::unique_ptr<SharedURLLoaderFactoryInfo>
+std::unique_ptr<network::SharedURLLoaderFactoryInfo>
HostChildURLLoaderFactoryBundle::Clone() {
auto info = base::WrapUnique(static_cast<ChildURLLoaderFactoryBundleInfo*>(
ChildURLLoaderFactoryBundle::Clone().release()));
DCHECK(base::SequencedTaskRunnerHandle::IsSet());
auto main_thread_host_bundle_clone = std::make_unique<
- TrackedChildURLLoaderFactoryBundle::HostPtrAndTaskRunner>(
- AsWeakPtr(), base::SequencedTaskRunnerHandle::Get());
+ TrackedChildURLLoaderFactoryBundle::HostPtrAndTaskRunner>(AsWeakPtr(),
+ task_runner_);
return std::make_unique<TrackedChildURLLoaderFactoryBundleInfo>(
std::move(info->default_factory_info()),
@@ -142,7 +145,7 @@ void HostChildURLLoaderFactoryBundle::UpdateThisAndAllClones(
partial_bundle->Clone());
}
- Update(partial_bundle->PassInterface());
+ Update(partial_bundle->PassInterface(), base::nullopt);
}
bool HostChildURLLoaderFactoryBundle::IsHostChildURLLoaderFactoryBundle()
@@ -167,7 +170,7 @@ void HostChildURLLoaderFactoryBundle::RemoveObserver(
void HostChildURLLoaderFactoryBundle::NotifyUpdateOnMainOrWorkerThread(
ObserverPtrAndTaskRunner* observer_bundle,
- std::unique_ptr<SharedURLLoaderFactoryInfo> update_info) {
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo> update_info) {
observer_bundle->second->PostTask(
FROM_HERE,
base::BindOnce(&TrackedChildURLLoaderFactoryBundle::OnUpdate,
diff --git a/chromium/content/renderer/loader/tracked_child_url_loader_factory_bundle.h b/chromium/content/renderer/loader/tracked_child_url_loader_factory_bundle.h
index 8d2a49380cd..aaa4289f50c 100644
--- a/chromium/content/renderer/loader/tracked_child_url_loader_factory_bundle.h
+++ b/chromium/content/renderer/loader/tracked_child_url_loader_factory_bundle.h
@@ -36,7 +36,7 @@ class CONTENT_EXPORT TrackedChildURLLoaderFactoryBundleInfo
protected:
// ChildURLLoaderFactoryBundleInfo overrides.
- scoped_refptr<SharedURLLoaderFactory> CreateFactory() override;
+ scoped_refptr<network::SharedURLLoaderFactory> CreateFactory() override;
std::unique_ptr<HostPtrAndTaskRunner> main_thread_host_bundle_;
@@ -66,7 +66,7 @@ class CONTENT_EXPORT TrackedChildURLLoaderFactoryBundle
// ChildURLLoaderFactoryBundle overrides.
// Returns |std::unique_ptr<TrackedChildURLLoaderFactoryBundleInfo>|.
- std::unique_ptr<SharedURLLoaderFactoryInfo> Clone() override;
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo> Clone() override;
private:
friend class HostChildURLLoaderFactoryBundle;
@@ -83,7 +83,7 @@ class CONTENT_EXPORT TrackedChildURLLoaderFactoryBundle
void RemoveObserverOnMainThread();
// Callback method to receive updates from the host bundle.
- void OnUpdate(std::unique_ptr<SharedURLLoaderFactoryInfo> info);
+ void OnUpdate(std::unique_ptr<network::SharedURLLoaderFactoryInfo> info);
// |WeakPtr| and |TaskRunner| of the host bundle. Can be copied and passed
// across sequences.
@@ -107,11 +107,12 @@ class CONTENT_EXPORT HostChildURLLoaderFactoryBundle
std::unordered_map<TrackedChildURLLoaderFactoryBundle*,
std::unique_ptr<ObserverPtrAndTaskRunner>>;
- HostChildURLLoaderFactoryBundle();
+ explicit HostChildURLLoaderFactoryBundle(
+ scoped_refptr<base::SequencedTaskRunner> task_runner);
// ChildURLLoaderFactoryBundle overrides.
// Returns |std::unique_ptr<TrackedChildURLLoaderFactoryBundleInfo>|.
- std::unique_ptr<SharedURLLoaderFactoryInfo> Clone() override;
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo> Clone() override;
bool IsHostChildURLLoaderFactoryBundle() const override;
// Update this bundle with |info|, and post cloned |info| to tracked bundles.
@@ -140,11 +141,13 @@ class CONTENT_EXPORT HostChildURLLoaderFactoryBundle
// tracked bundle has been destroyed.
void NotifyUpdateOnMainOrWorkerThread(
ObserverPtrAndTaskRunner* observer_bundle,
- std::unique_ptr<SharedURLLoaderFactoryInfo> update_info);
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo> update_info);
// Contains |WeakPtr| and |TaskRunner| to tracked bundles.
std::unique_ptr<ObserverList> observer_list_ = nullptr;
+ scoped_refptr<base::SequencedTaskRunner> task_runner_;
+
DISALLOW_COPY_AND_ASSIGN(HostChildURLLoaderFactoryBundle);
};
diff --git a/chromium/content/renderer/loader/url_loader_client_impl.cc b/chromium/content/renderer/loader/url_loader_client_impl.cc
index 71c67f89bce..9b237d2ae52 100644
--- a/chromium/content/renderer/loader/url_loader_client_impl.cc
+++ b/chromium/content/renderer/loader/url_loader_client_impl.cc
@@ -225,15 +225,15 @@ void URLLoaderClientImpl::FlushDeferredMessages() {
void URLLoaderClientImpl::Bind(
network::mojom::URLLoaderClientEndpointsPtr endpoints) {
- url_loader_.Bind(std::move(endpoints->url_loader));
- url_loader_client_binding_.Bind(std::move(endpoints->url_loader_client));
+ url_loader_.Bind(std::move(endpoints->url_loader), task_runner_);
+ url_loader_client_binding_.Bind(std::move(endpoints->url_loader_client),
+ task_runner_);
url_loader_client_binding_.set_connection_error_handler(base::BindOnce(
&URLLoaderClientImpl::OnConnectionClosed, weak_factory_.GetWeakPtr()));
}
void URLLoaderClientImpl::OnReceiveResponse(
const network::ResourceResponseHead& response_head,
- const base::Optional<net::SSLInfo>& ssl_info,
network::mojom::DownloadedTempFilePtr downloaded_file) {
has_received_response_ = true;
downloaded_file_ = std::move(downloaded_file);
@@ -306,6 +306,13 @@ void URLLoaderClientImpl::OnStartLoadingResponseBody(
mojo::ScopedDataPipeConsumerHandle body) {
DCHECK(!body_consumer_);
DCHECK(has_received_response_);
+
+ if (pass_response_pipe_to_dispatcher_) {
+ resource_dispatcher_->OnStartLoadingResponseBody(request_id_,
+ std::move(body));
+ return;
+ }
+
body_consumer_ = new URLResponseBodyConsumer(
request_id_, resource_dispatcher_, std::move(body), task_runner_);
@@ -331,6 +338,11 @@ void URLLoaderClientImpl::OnComplete(
body_consumer_->OnComplete(status);
}
+network::mojom::DownloadedTempFilePtr
+URLLoaderClientImpl::TakeDownloadedTempFile() {
+ return std::move(downloaded_file_);
+}
+
bool URLLoaderClientImpl::NeedsStoringMessage() const {
return is_deferred_ || deferred_messages_.size() > 0;
}
diff --git a/chromium/content/renderer/loader/url_loader_client_impl.h b/chromium/content/renderer/loader/url_loader_client_impl.h
index d42044af045..96712b00667 100644
--- a/chromium/content/renderer/loader/url_loader_client_impl.h
+++ b/chromium/content/renderer/loader/url_loader_client_impl.h
@@ -47,9 +47,17 @@ class CONTENT_EXPORT URLLoaderClientImpl final
// Unsets |is_deferred_|.
void UnsetDefersLoading();
- // Disaptches the messages received after SetDefersLoading is called.
+ // Dispatches the messages received after SetDefersLoading is called.
void FlushDeferredMessages();
+ // If set to true, this causes the raw datapipe containing the response body
+ // to be passed on to the ResourceDispatcher. Otherwise a
+ // URLResponseBodyConsumer is created that passes individual chunks of data
+ // from teh body to the dispatcher.
+ void SetPassResponsePipeToDispatcher(bool pass_pipe) {
+ pass_response_pipe_to_dispatcher_ = true;
+ }
+
// Binds this instance to the given URLLoaderClient endpoints so that it can
// start getting the mojo calls from the given loader. This is used only for
// the main resource loading when NavigationMojoResponse and/or NetworkService
@@ -62,7 +70,6 @@ class CONTENT_EXPORT URLLoaderClientImpl final
// network::mojom::URLLoaderClient implementation
void OnReceiveResponse(
const network::ResourceResponseHead& response_head,
- const base::Optional<net::SSLInfo>& ssl_info,
network::mojom::DownloadedTempFilePtr downloaded_file) override;
void OnReceiveRedirect(
const net::RedirectInfo& redirect_info,
@@ -77,6 +84,9 @@ class CONTENT_EXPORT URLLoaderClientImpl final
mojo::ScopedDataPipeConsumerHandle body) override;
void OnComplete(const network::URLLoaderCompletionStatus& status) override;
+ // Takes |downloaded_file_|.
+ network::mojom::DownloadedTempFilePtr TakeDownloadedTempFile();
+
private:
class DeferredMessage;
class DeferredOnReceiveResponse;
@@ -97,6 +107,7 @@ class CONTENT_EXPORT URLLoaderClientImpl final
bool has_received_response_ = false;
bool has_received_complete_ = false;
bool is_deferred_ = false;
+ bool pass_response_pipe_to_dispatcher_ = false;
int32_t accumulated_transfer_size_diff_during_deferred_ = 0;
ResourceDispatcher* const resource_dispatcher_;
scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
diff --git a/chromium/content/renderer/loader/url_loader_client_impl_unittest.cc b/chromium/content/renderer/loader/url_loader_client_impl_unittest.cc
index b71a08ed8b7..9c00707535e 100644
--- a/chromium/content/renderer/loader/url_loader_client_impl_unittest.cc
+++ b/chromium/content/renderer/loader/url_loader_client_impl_unittest.cc
@@ -5,10 +5,9 @@
#include "content/renderer/loader/url_loader_client_impl.h"
#include <vector>
-#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
-#include "content/common/weak_wrapper_shared_url_loader_factory.h"
+#include "content/public/common/weak_wrapper_shared_url_loader_factory.h"
#include "content/renderer/loader/resource_dispatcher.h"
#include "content/renderer/loader/test_request_peer.h"
#include "mojo/public/cpp/bindings/binding.h"
@@ -17,7 +16,7 @@
#include "net/url_request/redirect_info.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
namespace content {
@@ -27,8 +26,8 @@ class URLLoaderClientImplTest : public ::testing::Test,
URLLoaderClientImplTest() : dispatcher_(new ResourceDispatcher()) {
request_id_ = dispatcher_->StartAsync(
std::make_unique<network::ResourceRequest>(), 0,
- blink::scheduler::GetSingleThreadTaskRunnerForTesting(), url::Origin(),
- TRAFFIC_ANNOTATION_FOR_TESTS, false,
+ blink::scheduler::GetSingleThreadTaskRunnerForTesting(),
+ TRAFFIC_ANNOTATION_FOR_TESTS, false, false,
std::make_unique<TestRequestPeer>(dispatcher_.get(),
&request_peer_context_),
base::MakeRefCounted<WeakWrapperSharedURLLoaderFactory>(this),
@@ -79,7 +78,7 @@ class URLLoaderClientImplTest : public ::testing::Test,
TEST_F(URLLoaderClientImplTest, OnReceiveResponse) {
network::ResourceResponseHead response_head;
- url_loader_client_->OnReceiveResponse(response_head, base::nullopt, nullptr);
+ url_loader_client_->OnReceiveResponse(response_head, nullptr);
EXPECT_FALSE(request_peer_context_.received_response);
base::RunLoop().RunUntilIdle();
@@ -89,7 +88,7 @@ TEST_F(URLLoaderClientImplTest, OnReceiveResponse) {
TEST_F(URLLoaderClientImplTest, ResponseBody) {
network::ResourceResponseHead response_head;
- url_loader_client_->OnReceiveResponse(response_head, base::nullopt, nullptr);
+ url_loader_client_->OnReceiveResponse(response_head, nullptr);
EXPECT_FALSE(request_peer_context_.received_response);
base::RunLoop().RunUntilIdle();
@@ -122,7 +121,7 @@ TEST_F(URLLoaderClientImplTest, OnReceiveRedirect) {
TEST_F(URLLoaderClientImplTest, OnDataDownloaded) {
network::ResourceResponseHead response_head;
- url_loader_client_->OnReceiveResponse(response_head, base::nullopt, nullptr);
+ url_loader_client_->OnReceiveResponse(response_head, nullptr);
url_loader_client_->OnDataDownloaded(8, 13);
url_loader_client_->OnDataDownloaded(2, 1);
@@ -140,7 +139,7 @@ TEST_F(URLLoaderClientImplTest, OnReceiveCachedMetadata) {
std::vector<uint8_t> metadata;
metadata.push_back('a');
- url_loader_client_->OnReceiveResponse(response_head, base::nullopt, nullptr);
+ url_loader_client_->OnReceiveResponse(response_head, nullptr);
url_loader_client_->OnReceiveCachedMetadata(metadata);
EXPECT_FALSE(request_peer_context_.received_response);
@@ -154,7 +153,7 @@ TEST_F(URLLoaderClientImplTest, OnReceiveCachedMetadata) {
TEST_F(URLLoaderClientImplTest, OnTransferSizeUpdated) {
network::ResourceResponseHead response_head;
- url_loader_client_->OnReceiveResponse(response_head, base::nullopt, nullptr);
+ url_loader_client_->OnReceiveResponse(response_head, nullptr);
url_loader_client_->OnTransferSizeUpdated(4);
url_loader_client_->OnTransferSizeUpdated(4);
@@ -169,7 +168,7 @@ TEST_F(URLLoaderClientImplTest, OnCompleteWithoutResponseBody) {
network::ResourceResponseHead response_head;
network::URLLoaderCompletionStatus status;
- url_loader_client_->OnReceiveResponse(response_head, base::nullopt, nullptr);
+ url_loader_client_->OnReceiveResponse(response_head, nullptr);
url_loader_client_->OnComplete(status);
EXPECT_FALSE(request_peer_context_.received_response);
@@ -183,7 +182,7 @@ TEST_F(URLLoaderClientImplTest, OnCompleteWithResponseBody) {
network::ResourceResponseHead response_head;
network::URLLoaderCompletionStatus status;
- url_loader_client_->OnReceiveResponse(response_head, base::nullopt, nullptr);
+ url_loader_client_->OnReceiveResponse(response_head, nullptr);
mojo::DataPipe data_pipe(DataPipeOptions());
url_loader_client_->OnStartLoadingResponseBody(
std::move(data_pipe.consumer_handle));
@@ -217,7 +216,7 @@ TEST_F(URLLoaderClientImplTest, OnCompleteShouldBeTheLastMessage) {
network::ResourceResponseHead response_head;
network::URLLoaderCompletionStatus status;
- url_loader_client_->OnReceiveResponse(response_head, base::nullopt, nullptr);
+ url_loader_client_->OnReceiveResponse(response_head, nullptr);
mojo::DataPipe data_pipe(DataPipeOptions());
url_loader_client_->OnStartLoadingResponseBody(
std::move(data_pipe.consumer_handle));
@@ -249,7 +248,7 @@ TEST_F(URLLoaderClientImplTest, CancelOnReceiveResponse) {
network::ResourceResponseHead response_head;
network::URLLoaderCompletionStatus status;
- url_loader_client_->OnReceiveResponse(response_head, base::nullopt, nullptr);
+ url_loader_client_->OnReceiveResponse(response_head, nullptr);
mojo::DataPipe data_pipe(DataPipeOptions());
url_loader_client_->OnStartLoadingResponseBody(
std::move(data_pipe.consumer_handle));
@@ -278,7 +277,7 @@ TEST_F(URLLoaderClientImplTest, CancelOnReceiveData) {
ASSERT_EQ(MOJO_RESULT_OK, result);
EXPECT_EQ(5u, size);
- url_loader_client_->OnReceiveResponse(response_head, base::nullopt, nullptr);
+ url_loader_client_->OnReceiveResponse(response_head, nullptr);
url_loader_client_->OnStartLoadingResponseBody(
std::move(data_pipe.consumer_handle));
url_loader_client_->OnComplete(status);
@@ -299,7 +298,7 @@ TEST_F(URLLoaderClientImplTest, Defer) {
network::ResourceResponseHead response_head;
network::URLLoaderCompletionStatus status;
- url_loader_client_->OnReceiveResponse(response_head, base::nullopt, nullptr);
+ url_loader_client_->OnReceiveResponse(response_head, nullptr);
url_loader_client_->OnComplete(status);
EXPECT_FALSE(request_peer_context_.received_response);
@@ -324,7 +323,7 @@ TEST_F(URLLoaderClientImplTest, DeferWithResponseBody) {
network::ResourceResponseHead response_head;
network::URLLoaderCompletionStatus status;
- url_loader_client_->OnReceiveResponse(response_head, base::nullopt, nullptr);
+ url_loader_client_->OnReceiveResponse(response_head, nullptr);
mojo::DataPipe data_pipe(DataPipeOptions());
uint32_t size = 5;
MojoResult result = data_pipe.producer_handle->WriteData(
@@ -365,7 +364,7 @@ TEST_F(URLLoaderClientImplTest, DeferWithTransferSizeUpdated) {
network::ResourceResponseHead response_head;
network::URLLoaderCompletionStatus status;
- url_loader_client_->OnReceiveResponse(response_head, base::nullopt, nullptr);
+ url_loader_client_->OnReceiveResponse(response_head, nullptr);
mojo::DataPipe data_pipe(DataPipeOptions());
uint32_t size = 5;
MojoResult result = data_pipe.producer_handle->WriteData(
@@ -413,7 +412,7 @@ TEST_F(URLLoaderClientImplTest, SetDeferredDuringFlushingDeferredMessage) {
network::URLLoaderCompletionStatus status;
url_loader_client_->OnReceiveRedirect(redirect_info, response_head);
- url_loader_client_->OnReceiveResponse(response_head, base::nullopt, nullptr);
+ url_loader_client_->OnReceiveResponse(response_head, nullptr);
mojo::DataPipe data_pipe(DataPipeOptions());
uint32_t size = 5;
MojoResult result = data_pipe.producer_handle->WriteData(
@@ -474,7 +473,7 @@ TEST_F(URLLoaderClientImplTest,
network::ResourceResponseHead response_head;
network::URLLoaderCompletionStatus status;
- url_loader_client_->OnReceiveResponse(response_head, base::nullopt, nullptr);
+ url_loader_client_->OnReceiveResponse(response_head, nullptr);
url_loader_client_->OnTransferSizeUpdated(4);
url_loader_client_->OnComplete(status);
@@ -523,7 +522,7 @@ TEST_F(URLLoaderClientImplTest, CancelOnReceiveDataWhileFlushing) {
ASSERT_EQ(MOJO_RESULT_OK, result);
EXPECT_EQ(5u, size);
- url_loader_client_->OnReceiveResponse(response_head, base::nullopt, nullptr);
+ url_loader_client_->OnReceiveResponse(response_head, nullptr);
url_loader_client_->OnStartLoadingResponseBody(
std::move(data_pipe.consumer_handle));
url_loader_client_->OnComplete(status);
diff --git a/chromium/content/renderer/loader/url_response_body_consumer.cc b/chromium/content/renderer/loader/url_response_body_consumer.cc
index 0379b99a275..f5ac29b5ee6 100644
--- a/chromium/content/renderer/loader/url_response_body_consumer.cc
+++ b/chromium/content/renderer/loader/url_response_body_consumer.cc
@@ -7,10 +7,8 @@
#include "base/auto_reset.h"
#include "base/bind.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "content/public/renderer/request_peer.h"
#include "content/renderer/loader/resource_dispatcher.h"
-#include "content/renderer/loader/site_isolation_stats_gatherer.h"
#include "services/network/public/cpp/url_loader_completion_status.h"
namespace content {
@@ -148,15 +146,6 @@ void URLResponseBodyConsumer::OnReadable(MojoResult unused) {
resource_dispatcher_->GetPendingRequestInfo(request_id_);
DCHECK(request_info);
- // Check whether this response data is compliant with our cross-site
- // document blocking policy. We only do this for the first chunk of data.
- if (request_info->site_isolation_metadata.get()) {
- SiteIsolationStatsGatherer::OnReceivedFirstChunk(
- request_info->site_isolation_metadata,
- static_cast<const char*>(buffer), available);
- request_info->site_isolation_metadata.reset();
- }
-
request_info->peer->OnReceivedData(std::make_unique<ReceivedData>(
static_cast<const char*>(buffer), available, this));
}
diff --git a/chromium/content/renderer/loader/url_response_body_consumer_unittest.cc b/chromium/content/renderer/loader/url_response_body_consumer_unittest.cc
index c7a6630f14f..49cb00b247c 100644
--- a/chromium/content/renderer/loader/url_response_body_consumer_unittest.cc
+++ b/chromium/content/renderer/loader/url_response_body_consumer_unittest.cc
@@ -7,11 +7,10 @@
#include "base/bind.h"
#include "base/callback_forward.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
-#include "content/common/weak_wrapper_shared_url_loader_factory.h"
+#include "content/public/common/weak_wrapper_shared_url_loader_factory.h"
#include "content/public/renderer/request_peer.h"
#include "content/renderer/loader/request_extra_data.h"
#include "content/renderer/loader/resource_dispatcher.h"
@@ -21,7 +20,7 @@
#include "services/network/public/cpp/url_loader_completion_status.h"
#include "services/network/public/mojom/request_context_frame_type.mojom.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
#include "url/gurl.h"
#include "url/origin.h"
@@ -50,6 +49,11 @@ class TestRequestPeer : public RequestPeer {
ADD_FAILURE() << "OnReceivedResponse should not be called.";
}
+ void OnStartLoadingResponseBody(
+ mojo::ScopedDataPipeConsumerHandle body) override {
+ ADD_FAILURE() << "OnStartLoadingResponseBody should not be called.";
+ }
+
void OnDownloadedData(int len, int encoded_data_length) override {
ADD_FAILURE() << "OnDownloadedData should not be called.";
}
@@ -150,8 +154,9 @@ class URLResponseBodyConsumerTest : public ::testing::Test {
TestRequestPeer::Context* context) {
return dispatcher_->StartAsync(
std::move(request), 0,
- blink::scheduler::GetSingleThreadTaskRunnerForTesting(), url::Origin(),
+ blink::scheduler::GetSingleThreadTaskRunnerForTesting(),
TRAFFIC_ANNOTATION_FOR_TESTS, false,
+ false /* pass_response_pipe_to_peer */,
std::make_unique<TestRequestPeer>(context, message_loop_.task_runner()),
base::MakeRefCounted<WeakWrapperSharedURLLoaderFactory>(&factory_),
std::vector<std::unique_ptr<URLLoaderThrottle>>(),
diff --git a/chromium/content/renderer/loader/web_data_consumer_handle_impl.h b/chromium/content/renderer/loader/web_data_consumer_handle_impl.h
index 740e80c7553..83427b1149e 100644
--- a/chromium/content/renderer/loader/web_data_consumer_handle_impl.h
+++ b/chromium/content/renderer/loader/web_data_consumer_handle_impl.h
@@ -12,7 +12,7 @@
#include "content/common/content_export.h"
#include "mojo/public/cpp/system/data_pipe.h"
#include "mojo/public/cpp/system/simple_watcher.h"
-#include "third_party/WebKit/public/platform/WebDataConsumerHandle.h"
+#include "third_party/blink/public/platform/web_data_consumer_handle.h"
namespace content {
diff --git a/chromium/content/renderer/loader/web_data_consumer_handle_impl_unittest.cc b/chromium/content/renderer/loader/web_data_consumer_handle_impl_unittest.cc
index 91e49c1a2bc..b01e4800a3d 100644
--- a/chromium/content/renderer/loader/web_data_consumer_handle_impl_unittest.cc
+++ b/chromium/content/renderer/loader/web_data_consumer_handle_impl_unittest.cc
@@ -14,7 +14,6 @@
#include "base/bind.h"
#include "base/location.h"
-#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
@@ -23,7 +22,7 @@
#include "base/threading/thread_task_runner_handle.h"
#include "mojo/public/cpp/system/data_pipe.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
namespace content {
diff --git a/chromium/content/renderer/loader/web_url_loader_impl.cc b/chromium/content/renderer/loader/web_url_loader_impl.cc
index 718af1ef082..0c2ed0fbdce 100644
--- a/chromium/content/renderer/loader/web_url_loader_impl.cc
+++ b/chromium/content/renderer/loader/web_url_loader_impl.cc
@@ -16,7 +16,6 @@
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/optional.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
@@ -47,27 +46,31 @@
#include "net/cert/cert_status_flags.h"
#include "net/cert/ct_sct_to_string.h"
#include "net/cert/x509_certificate.h"
+#include "net/cert/x509_util.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_util.h"
#include "net/ssl/ssl_cipher_suite_names.h"
#include "net/ssl/ssl_connection_status_flags.h"
+#include "net/ssl/ssl_info.h"
#include "net/url_request/url_request_data_job.h"
#include "services/network/loader_util.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/mojom/request_context_frame_type.mojom.h"
#include "services/network/public/mojom/url_loader.mojom.h"
-#include "third_party/WebKit/public/common/mime_util/mime_util.h"
-#include "third_party/WebKit/public/platform/FilePathConversion.h"
-#include "third_party/WebKit/public/platform/WebHTTPLoadInfo.h"
-#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
-#include "third_party/WebKit/public/platform/WebSecurityStyle.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
-#include "third_party/WebKit/public/platform/WebURLError.h"
-#include "third_party/WebKit/public/platform/WebURLLoadTiming.h"
-#include "third_party/WebKit/public/platform/WebURLLoaderClient.h"
-#include "third_party/WebKit/public/platform/WebURLRequest.h"
-#include "third_party/WebKit/public/platform/WebURLResponse.h"
-#include "third_party/WebKit/public/web/WebSecurityPolicy.h"
+#include "third_party/blink/public/common/mime_util/mime_util.h"
+#include "third_party/blink/public/platform/file_path_conversion.h"
+#include "third_party/blink/public/platform/interface_provider.h"
+#include "third_party/blink/public/platform/platform.h"
+#include "third_party/blink/public/platform/web_http_load_info.h"
+#include "third_party/blink/public/platform/web_security_origin.h"
+#include "third_party/blink/public/platform/web_security_style.h"
+#include "third_party/blink/public/platform/web_url.h"
+#include "third_party/blink/public/platform/web_url_error.h"
+#include "third_party/blink/public/platform/web_url_load_timing.h"
+#include "third_party/blink/public/platform/web_url_loader_client.h"
+#include "third_party/blink/public/platform/web_url_request.h"
+#include "third_party/blink/public/platform/web_url_response.h"
+#include "third_party/blink/public/web/web_security_policy.h"
#include "third_party/boringssl/src/include/openssl/ssl.h"
using base::Time;
@@ -245,6 +248,12 @@ blink::WebURLResponse::SignedCertificateTimestamp NetSCTToBlinkSCT(
sct_and_status.sct->signature.signature_data.length())));
}
+WebString CryptoBufferAsWebString(const CRYPTO_BUFFER* buffer) {
+ base::StringPiece sp = net::x509_util::CryptoBufferAsStringPiece(buffer);
+ return blink::WebString::FromLatin1(
+ reinterpret_cast<const blink::WebLChar*>(sp.begin()), sp.size());
+}
+
void SetSecurityStyleAndDetails(const GURL& url,
const network::ResourceResponseInfo& info,
WebURLResponse* response,
@@ -261,42 +270,47 @@ void SetSecurityStyleAndDetails(const GURL& url,
// The resource loader does not provide a guarantee that requests always have
// security info (such as a certificate) attached. Use WebSecurityStyleUnknown
// in this case where there isn't enough information to be useful.
- if (info.certificate.empty()) {
+ if (!info.ssl_info.has_value()) {
response->SetSecurityStyle(blink::kWebSecurityStyleUnknown);
return;
}
- int ssl_version =
- net::SSLConnectionStatusToVersion(info.ssl_connection_status);
- const char* protocol;
- net::SSLVersionToString(&protocol, ssl_version);
-
- const char* key_exchange;
- const char* cipher;
- const char* mac;
- bool is_aead;
- bool is_tls13;
- uint16_t cipher_suite =
- net::SSLConnectionStatusToCipherSuite(info.ssl_connection_status);
- net::SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, &is_aead,
- &is_tls13, cipher_suite);
- if (key_exchange == nullptr) {
- DCHECK(is_tls13);
- key_exchange = "";
- }
-
- if (mac == nullptr) {
- DCHECK(is_aead);
- mac = "";
- }
+ const net::SSLInfo& ssl_info = *info.ssl_info;
+ const char* protocol = "";
+ const char* key_exchange = "";
+ const char* cipher = "";
+ const char* mac = "";
const char* key_exchange_group = "";
- if (info.ssl_key_exchange_group != 0) {
- // Historically the field was named 'curve' rather than 'group'.
- key_exchange_group = SSL_get_curve_name(info.ssl_key_exchange_group);
- if (!key_exchange_group) {
- NOTREACHED();
- key_exchange_group = "";
+
+ if (ssl_info.connection_status) {
+ int ssl_version =
+ net::SSLConnectionStatusToVersion(ssl_info.connection_status);
+ net::SSLVersionToString(&protocol, ssl_version);
+
+ bool is_aead;
+ bool is_tls13;
+ uint16_t cipher_suite =
+ net::SSLConnectionStatusToCipherSuite(ssl_info.connection_status);
+ net::SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, &is_aead,
+ &is_tls13, cipher_suite);
+ if (key_exchange == nullptr) {
+ DCHECK(is_tls13);
+ key_exchange = "";
+ }
+
+ if (mac == nullptr) {
+ DCHECK(is_aead);
+ mac = "";
+ }
+
+ if (ssl_info.key_exchange_group != 0) {
+ // Historically the field was named 'curve' rather than 'group'.
+ key_exchange_group = SSL_get_curve_name(ssl_info.key_exchange_group);
+ if (!key_exchange_group) {
+ NOTREACHED();
+ key_exchange_group = "";
+ }
}
}
@@ -304,15 +318,12 @@ void SetSecurityStyleAndDetails(const GURL& url,
GetSecurityStyleForResource(url, info.cert_status));
blink::WebURLResponse::SignedCertificateTimestampList sct_list(
- info.signed_certificate_timestamps.size());
+ ssl_info.signed_certificate_timestamps.size());
for (size_t i = 0; i < sct_list.size(); ++i)
- sct_list[i] = NetSCTToBlinkSCT(info.signed_certificate_timestamps[i]);
+ sct_list[i] = NetSCTToBlinkSCT(ssl_info.signed_certificate_timestamps[i]);
- scoped_refptr<net::X509Certificate> cert(
- net::X509Certificate::CreateFromBytes(info.certificate[0].data(),
- info.certificate[0].size()));
- if (!cert) {
+ if (!ssl_info.cert) {
NOTREACHED();
response->SetSecurityStyle(blink::kWebSecurityStyleUnknown);
return;
@@ -320,7 +331,7 @@ void SetSecurityStyleAndDetails(const GURL& url,
std::vector<std::string> san_dns;
std::vector<std::string> san_ip;
- cert->GetSubjectAltName(&san_dns, &san_ip);
+ ssl_info.cert->GetSubjectAltName(&san_dns, &san_ip);
blink::WebVector<blink::WebString> web_san(san_dns.size() + san_ip.size());
std::transform(
san_dns.begin(), san_dns.end(), web_san.begin(),
@@ -332,19 +343,20 @@ void SetSecurityStyleAndDetails(const GURL& url,
return blink::WebString::FromLatin1(ip.ToString());
});
- blink::WebVector<blink::WebString> web_cert(info.certificate.size());
- std::transform(
- info.certificate.begin(), info.certificate.end(), web_cert.begin(),
- [](const std::string& h) { return blink::WebString::FromLatin1(h); });
+ blink::WebVector<blink::WebString> web_cert;
+ web_cert.reserve(ssl_info.cert->intermediate_buffers().size() + 1);
+ web_cert.emplace_back(CryptoBufferAsWebString(ssl_info.cert->cert_buffer()));
+ for (const auto& cert : ssl_info.cert->intermediate_buffers())
+ web_cert.emplace_back(CryptoBufferAsWebString(cert.get()));
blink::WebURLResponse::WebSecurityDetails webSecurityDetails(
WebString::FromASCII(protocol), WebString::FromASCII(key_exchange),
WebString::FromASCII(key_exchange_group), WebString::FromASCII(cipher),
WebString::FromASCII(mac),
- WebString::FromUTF8(cert->subject().common_name), web_san,
- WebString::FromUTF8(cert->issuer().common_name),
- cert->valid_start().ToDoubleT(), cert->valid_expiry().ToDoubleT(),
- web_cert, sct_list);
+ WebString::FromUTF8(ssl_info.cert->subject().common_name), web_san,
+ WebString::FromUTF8(ssl_info.cert->issuer().common_name),
+ ssl_info.cert->valid_start().ToDoubleT(),
+ ssl_info.cert->valid_expiry().ToDoubleT(), web_cert, sct_list);
response->SetSecurityDetails(webSecurityDetails);
}
@@ -359,7 +371,7 @@ StreamOverrideParameters::~StreamOverrideParameters() {
WebURLLoaderFactoryImpl::WebURLLoaderFactoryImpl(
base::WeakPtr<ResourceDispatcher> resource_dispatcher,
- scoped_refptr<SharedURLLoaderFactory> loader_factory)
+ scoped_refptr<network::SharedURLLoaderFactory> loader_factory)
: resource_dispatcher_(std::move(resource_dispatcher)),
loader_factory_(std::move(loader_factory)) {}
@@ -399,7 +411,7 @@ class WebURLLoaderImpl::Context : public base::RefCounted<Context> {
Context(WebURLLoaderImpl* loader,
ResourceDispatcher* resource_dispatcher,
scoped_refptr<base::SingleThreadTaskRunner> task_runner,
- scoped_refptr<SharedURLLoaderFactory> factory,
+ scoped_refptr<network::SharedURLLoaderFactory> factory,
mojom::KeepAliveHandlePtr keep_alive_handle);
ResourceDispatcher* resource_dispatcher() { return resource_dispatcher_; }
@@ -421,6 +433,7 @@ class WebURLLoaderImpl::Context : public base::RefCounted<Context> {
bool OnReceivedRedirect(const net::RedirectInfo& redirect_info,
const network::ResourceResponseInfo& info);
void OnReceivedResponse(const network::ResourceResponseInfo& info);
+ void OnStartLoadingResponseBody(mojo::ScopedDataPipeConsumerHandle body);
void OnDownloadedData(int len, int encoded_data_length);
void OnReceivedData(std::unique_ptr<ReceivedData> data);
void OnTransferSizeUpdated(int transfer_size_diff);
@@ -463,7 +476,7 @@ class WebURLLoaderImpl::Context : public base::RefCounted<Context> {
DeferState defers_loading_;
int request_id_;
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory_;
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
};
// A thin wrapper class for Context to ensure its lifetime while it is
@@ -480,6 +493,8 @@ class WebURLLoaderImpl::RequestPeerImpl : public RequestPeer {
bool OnReceivedRedirect(const net::RedirectInfo& redirect_info,
const network::ResourceResponseInfo& info) override;
void OnReceivedResponse(const network::ResourceResponseInfo& info) override;
+ void OnStartLoadingResponseBody(
+ mojo::ScopedDataPipeConsumerHandle body) override;
void OnDownloadedData(int len, int encoded_data_length) override;
void OnReceivedData(std::unique_ptr<ReceivedData> data) override;
void OnTransferSizeUpdated(int transfer_size_diff) override;
@@ -505,6 +520,8 @@ class WebURLLoaderImpl::SinkPeer : public RequestPeer {
return true;
}
void OnReceivedResponse(const network::ResourceResponseInfo& info) override {}
+ void OnStartLoadingResponseBody(
+ mojo::ScopedDataPipeConsumerHandle body) override {}
void OnDownloadedData(int len, int encoded_data_length) override {}
void OnReceivedData(std::unique_ptr<ReceivedData> data) override {}
void OnTransferSizeUpdated(int transfer_size_diff) override {}
@@ -526,7 +543,7 @@ WebURLLoaderImpl::Context::Context(
WebURLLoaderImpl* loader,
ResourceDispatcher* resource_dispatcher,
scoped_refptr<base::SingleThreadTaskRunner> task_runner,
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory,
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
mojom::KeepAliveHandlePtr keep_alive_handle_ptr)
: loader_(loader),
use_stream_on_response_(false),
@@ -604,7 +621,7 @@ void WebURLLoaderImpl::Context::Start(const WebURLRequest& request,
// This is a sync load. Do the work now.
sync_load_response->url = url_;
sync_load_response->error_code =
- GetInfoFromDataURL(sync_load_response->url, sync_load_response,
+ GetInfoFromDataURL(sync_load_response->url, &sync_load_response->info,
&sync_load_response->data);
} else {
task_runner_->PostTask(FROM_HERE,
@@ -737,11 +754,16 @@ void WebURLLoaderImpl::Context::Start(const WebURLRequest& request,
if (sync_load_response) {
DCHECK(defers_loading_ == NOT_DEFERRING);
+ blink::mojom::BlobRegistryPtrInfo download_to_blob_registry;
+ if (request.PassResponsePipeToClient()) {
+ blink::Platform::Current()->GetInterfaceProvider()->GetInterface(
+ MakeRequest(&download_to_blob_registry));
+ }
resource_dispatcher_->StartSync(
std::move(resource_request), request.RequestorID(),
- extra_data->frame_origin(), GetTrafficAnnotationTag(request),
- sync_load_response, url_loader_factory_,
- extra_data->TakeURLLoaderThrottles());
+ GetTrafficAnnotationTag(request), sync_load_response,
+ url_loader_factory_, extra_data->TakeURLLoaderThrottles(),
+ request.TimeoutInterval(), std::move(download_to_blob_registry));
return;
}
@@ -760,8 +782,8 @@ void WebURLLoaderImpl::Context::Start(const WebURLRequest& request,
base::OnceClosure continue_navigation_function;
request_id_ = resource_dispatcher_->StartAsync(
std::move(resource_request), request.RequestorID(), task_runner_,
- extra_data->frame_origin(), GetTrafficAnnotationTag(request),
- false /* is_sync */, std::move(peer), url_loader_factory_,
+ GetTrafficAnnotationTag(request), false /* is_sync */,
+ request.PassResponsePipeToClient(), std::move(peer), url_loader_factory_,
extra_data->TakeURLLoaderThrottles(),
std::move(url_loader_client_endpoints), &continue_navigation_function);
extra_data->set_continue_navigation_function(
@@ -893,6 +915,12 @@ void WebURLLoaderImpl::Context::OnReceivedResponse(
}
}
+void WebURLLoaderImpl::Context::OnStartLoadingResponseBody(
+ mojo::ScopedDataPipeConsumerHandle body) {
+ if (client_)
+ client_->DidStartLoadingResponseBody(std::move(body));
+}
+
void WebURLLoaderImpl::Context::OnDownloadedData(int len,
int encoded_data_length) {
if (client_)
@@ -968,7 +996,8 @@ void WebURLLoaderImpl::Context::OnCompletedRequest(
client_->DidFail(
status.cors_error_status
? WebURLError(*status.cors_error_status, has_copy_in_cache, url_)
- : WebURLError(status.error_code, has_copy_in_cache,
+ : WebURLError(status.error_code, status.extended_error_code,
+ has_copy_in_cache,
WebURLError::IsWebSecurityViolation::kFalse, url_),
total_transfer_size, encoded_body_size, status.decoded_body_length);
} else {
@@ -1015,7 +1044,7 @@ bool WebURLLoaderImpl::Context::CanHandleDataURLRequestLocally(
// The fast paths for data URL, Start() and HandleDataURL(), don't support
// the downloadToFile option.
- if (request.DownloadToFile())
+ if (request.DownloadToFile() || request.PassResponsePipeToClient())
return false;
// Data url requests from object tags may need to be intercepted as streams
@@ -1105,6 +1134,11 @@ void WebURLLoaderImpl::RequestPeerImpl::OnReceivedResponse(
context_->OnReceivedResponse(info);
}
+void WebURLLoaderImpl::RequestPeerImpl::OnStartLoadingResponseBody(
+ mojo::ScopedDataPipeConsumerHandle body) {
+ context_->OnStartLoadingResponseBody(std::move(body));
+}
+
void WebURLLoaderImpl::RequestPeerImpl::OnDownloadedData(
int len,
int encoded_data_length) {
@@ -1141,7 +1175,7 @@ void WebURLLoaderImpl::RequestPeerImpl::OnCompletedRequest(
WebURLLoaderImpl::WebURLLoaderImpl(
ResourceDispatcher* resource_dispatcher,
scoped_refptr<base::SingleThreadTaskRunner> task_runner,
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory)
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory)
: WebURLLoaderImpl(resource_dispatcher,
std::move(task_runner),
std::move(url_loader_factory),
@@ -1150,7 +1184,7 @@ WebURLLoaderImpl::WebURLLoaderImpl(
WebURLLoaderImpl::WebURLLoaderImpl(
ResourceDispatcher* resource_dispatcher,
scoped_refptr<base::SingleThreadTaskRunner> task_runner,
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory,
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
mojom::KeepAliveHandlePtr keep_alive_handle)
: context_(new Context(this,
resource_dispatcher,
@@ -1298,12 +1332,15 @@ void WebURLLoaderImpl::PopulateURLResponse(
}
}
-void WebURLLoaderImpl::LoadSynchronously(const WebURLRequest& request,
- WebURLResponse& response,
- base::Optional<WebURLError>& error,
- WebData& data,
- int64_t& encoded_data_length,
- int64_t& encoded_body_length) {
+void WebURLLoaderImpl::LoadSynchronously(
+ const WebURLRequest& request,
+ WebURLResponse& response,
+ base::Optional<WebURLError>& error,
+ WebData& data,
+ int64_t& encoded_data_length,
+ int64_t& encoded_body_length,
+ base::Optional<int64_t>& downloaded_file_length,
+ blink::WebBlobInfo& downloaded_blob) {
TRACE_EVENT0("loading", "WebURLLoaderImpl::loadSynchronously");
SyncLoadResponse sync_load_response;
context_->Start(request, &sync_load_response);
@@ -1326,16 +1363,25 @@ void WebURLLoaderImpl::LoadSynchronously(const WebURLRequest& request,
error_code == net::ERR_ABORTED
? WebURLError::IsWebSecurityViolation::kTrue
: WebURLError::IsWebSecurityViolation::kFalse;
- error = WebURLError(error_code, WebURLError::HasCopyInCache::kFalse,
+ error = WebURLError(error_code, sync_load_response.extended_error_code,
+ WebURLError::HasCopyInCache::kFalse,
is_web_security_violation, final_url);
}
return;
}
- PopulateURLResponse(final_url, sync_load_response, &response,
+ PopulateURLResponse(final_url, sync_load_response.info, &response,
request.ReportRawHeaders());
- encoded_data_length = sync_load_response.encoded_data_length;
- encoded_body_length = sync_load_response.encoded_body_length;
+ encoded_data_length = sync_load_response.info.encoded_data_length;
+ encoded_body_length = sync_load_response.info.encoded_body_length;
+ downloaded_file_length = sync_load_response.downloaded_file_length;
+ if (sync_load_response.downloaded_blob) {
+ downloaded_blob = blink::WebBlobInfo(
+ WebString::FromLatin1(sync_load_response.downloaded_blob->uuid),
+ WebString::FromLatin1(sync_load_response.downloaded_blob->content_type),
+ sync_load_response.downloaded_blob->size,
+ sync_load_response.downloaded_blob->blob.PassHandle());
+ }
data.Assign(sync_load_response.data.data(), sync_load_response.data.size());
}
diff --git a/chromium/content/renderer/loader/web_url_loader_impl.h b/chromium/content/renderer/loader/web_url_loader_impl.h
index 1986f56a4ac..147130d926e 100644
--- a/chromium/content/renderer/loader/web_url_loader_impl.h
+++ b/chromium/content/renderer/loader/web_url_loader_impl.h
@@ -12,14 +12,14 @@
#include "base/memory/ref_counted.h"
#include "content/common/content_export.h"
#include "content/common/frame.mojom.h"
-#include "content/public/common/shared_url_loader_factory.h"
#include "mojo/public/cpp/system/data_pipe.h"
#include "net/url_request/redirect_info.h"
#include "services/network/public/cpp/resource_response.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/mojom/url_loader.mojom.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
-#include "third_party/WebKit/public/platform/WebURLLoader.h"
-#include "third_party/WebKit/public/platform/WebURLLoaderFactory.h"
+#include "third_party/blink/public/platform/web_url_loader.h"
+#include "third_party/blink/public/platform/web_url_loader_factory.h"
#include "url/gurl.h"
namespace base {
@@ -56,8 +56,9 @@ struct CONTENT_EXPORT StreamOverrideParameters {
class CONTENT_EXPORT WebURLLoaderFactoryImpl
: public blink::WebURLLoaderFactory {
public:
- WebURLLoaderFactoryImpl(base::WeakPtr<ResourceDispatcher> resource_dispatcher,
- scoped_refptr<SharedURLLoaderFactory> loader_factory);
+ WebURLLoaderFactoryImpl(
+ base::WeakPtr<ResourceDispatcher> resource_dispatcher,
+ scoped_refptr<network::SharedURLLoaderFactory> loader_factory);
~WebURLLoaderFactoryImpl() override;
// Creates a test-only factory which can be used only for data URLs.
@@ -69,21 +70,23 @@ class CONTENT_EXPORT WebURLLoaderFactoryImpl
private:
base::WeakPtr<ResourceDispatcher> resource_dispatcher_;
- scoped_refptr<SharedURLLoaderFactory> loader_factory_;
+ scoped_refptr<network::SharedURLLoaderFactory> loader_factory_;
DISALLOW_COPY_AND_ASSIGN(WebURLLoaderFactoryImpl);
};
class CONTENT_EXPORT WebURLLoaderImpl : public blink::WebURLLoader {
public:
- WebURLLoaderImpl(ResourceDispatcher* resource_dispatcher,
- scoped_refptr<base::SingleThreadTaskRunner> task_runner,
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory);
+ WebURLLoaderImpl(
+ ResourceDispatcher* resource_dispatcher,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner,
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory);
// When non-null |keep_alive_handle| is specified, this loader prolongs
// this render process's lifetime.
- WebURLLoaderImpl(ResourceDispatcher* resource_dispatcher,
- scoped_refptr<base::SingleThreadTaskRunner> task_runner,
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory,
- mojom::KeepAliveHandlePtr keep_alive_handle);
+ WebURLLoaderImpl(
+ ResourceDispatcher* resource_dispatcher,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner,
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
+ mojom::KeepAliveHandlePtr keep_alive_handle);
~WebURLLoaderImpl() override;
static void PopulateURLResponse(const blink::WebURL& url,
@@ -96,7 +99,9 @@ class CONTENT_EXPORT WebURLLoaderImpl : public blink::WebURLLoader {
base::Optional<blink::WebURLError>& error,
blink::WebData& data,
int64_t& encoded_data_length,
- int64_t& encoded_body_length) override;
+ int64_t& encoded_body_length,
+ base::Optional<int64_t>& downloaded_file_length,
+ blink::WebBlobInfo& downloaded_blob) override;
void LoadAsynchronously(const blink::WebURLRequest& request,
blink::WebURLLoaderClient* client) override;
void Cancel() override;
diff --git a/chromium/content/renderer/loader/web_url_loader_impl_unittest.cc b/chromium/content/renderer/loader/web_url_loader_impl_unittest.cc
index 350aea17522..a573dee34d4 100644
--- a/chromium/content/renderer/loader/web_url_loader_impl_unittest.cc
+++ b/chromium/content/renderer/loader/web_url_loader_impl_unittest.cc
@@ -12,15 +12,14 @@
#include "base/command_line.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/time/default_tick_clock.h"
#include "base/time/time.h"
-#include "content/common/weak_wrapper_shared_url_loader_factory.h"
#include "content/public/common/content_switches.h"
+#include "content/public/common/weak_wrapper_shared_url_loader_factory.h"
#include "content/public/renderer/fixed_received_data.h"
#include "content/public/renderer/request_peer.h"
#include "content/renderer/loader/request_extra_data.h"
@@ -38,12 +37,12 @@
#include "services/network/public/cpp/resource_response_info.h"
#include "services/network/public/mojom/request_context_frame_type.mojom.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebURLError.h"
-#include "third_party/WebKit/public/platform/WebURLLoaderClient.h"
-#include "third_party/WebKit/public/platform/WebURLRequest.h"
-#include "third_party/WebKit/public/platform/WebURLResponse.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_url_error.h"
+#include "third_party/blink/public/platform/web_url_loader_client.h"
+#include "third_party/blink/public/platform/web_url_request.h"
+#include "third_party/blink/public/platform/web_url_response.h"
#include "url/gurl.h"
#include "url/origin.h"
@@ -73,28 +72,29 @@ class TestResourceDispatcher : public ResourceDispatcher {
void StartSync(
std::unique_ptr<network::ResourceRequest> request,
int routing_id,
- const url::Origin& frame_origin,
const net::NetworkTrafficAnnotationTag& traffic_annotation,
SyncLoadResponse* response,
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory,
- std::vector<std::unique_ptr<URLLoaderThrottle>> throttles) override {
- *response = sync_load_response_;
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
+ std::vector<std::unique_ptr<URLLoaderThrottle>> throttles,
+ double timeout,
+ blink::mojom::BlobRegistryPtrInfo download_to_blob_registry) override {
+ *response = std::move(sync_load_response_);
}
int StartAsync(
std::unique_ptr<network::ResourceRequest> request,
int routing_id,
scoped_refptr<base::SingleThreadTaskRunner> loading_task_runner,
- const url::Origin& frame_origin,
const net::NetworkTrafficAnnotationTag& traffic_annotation,
bool is_sync,
+ bool pass_response_pipe_to_peer,
std::unique_ptr<RequestPeer> peer,
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory,
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
std::vector<std::unique_ptr<URLLoaderThrottle>> throttles,
network::mojom::URLLoaderClientEndpointsPtr url_loader_client_endpoints,
base::OnceClosure* continue_navigation_function) override {
EXPECT_FALSE(peer_);
- if (sync_load_response_.encoded_body_length != -1)
+ if (sync_load_response_.info.encoded_body_length != -1)
EXPECT_TRUE(is_sync);
peer_ = std::move(peer);
url_ = request->url;
@@ -121,8 +121,8 @@ class TestResourceDispatcher : public ResourceDispatcher {
}
bool defers_loading() const { return defers_loading_; }
- void set_sync_load_response(const SyncLoadResponse& sync_load_response) {
- sync_load_response_ = sync_load_response;
+ void set_sync_load_response(SyncLoadResponse&& sync_load_response) {
+ sync_load_response_ = std::move(sync_load_response);
}
private:
@@ -700,11 +700,14 @@ TEST_F(WebURLLoaderImplTest, ResponseCert) {
base::StringPiece cert1_der =
net::x509_util::CryptoBufferAsStringPiece(certs[1]->cert_buffer());
- network::ResourceResponseInfo info;
+ net::SSLInfo ssl_info;
+ ssl_info.cert =
+ net::X509Certificate::CreateFromDERCertChain({cert0_der, cert1_der});
net::SSLConnectionStatusSetVersion(net::SSL_CONNECTION_VERSION_TLS1_2,
- &info.ssl_connection_status);
- info.certificate.emplace_back(cert0_der);
- info.certificate.emplace_back(cert1_der);
+ &ssl_info.connection_status);
+
+ network::ResourceResponseInfo info;
+ info.ssl_info = ssl_info;
blink::WebURLResponse web_url_response;
WebURLLoaderImpl::PopulateURLResponse(url, info, &web_url_response, true);
@@ -736,10 +739,12 @@ TEST_F(WebURLLoaderImplTest, ResponseCertWithNoSANs) {
base::StringPiece cert0_der =
net::x509_util::CryptoBufferAsStringPiece(certs[0]->cert_buffer());
- network::ResourceResponseInfo info;
+ net::SSLInfo ssl_info;
net::SSLConnectionStatusSetVersion(net::SSL_CONNECTION_VERSION_TLS1_2,
- &info.ssl_connection_status);
- info.certificate.emplace_back(cert0_der);
+ &ssl_info.connection_status);
+ ssl_info.cert = certs[0];
+ network::ResourceResponseInfo info;
+ info.ssl_info = ssl_info;
blink::WebURLResponse web_url_response;
WebURLLoaderImpl::PopulateURLResponse(url, info, &web_url_response, true);
@@ -772,20 +777,25 @@ TEST_F(WebURLLoaderImplTest, SyncLengths) {
sync_load_response.url = url;
sync_load_response.data = kBodyData;
ASSERT_EQ(17u, sync_load_response.data.size());
- sync_load_response.encoded_body_length = kEncodedBodyLength;
- sync_load_response.encoded_data_length = kEncodedDataLength;
- dispatcher()->set_sync_load_response(sync_load_response);
+ sync_load_response.info.encoded_body_length = kEncodedBodyLength;
+ sync_load_response.info.encoded_data_length = kEncodedDataLength;
+ dispatcher()->set_sync_load_response(std::move(sync_load_response));
blink::WebURLResponse response;
base::Optional<blink::WebURLError> error;
blink::WebData data;
int64_t encoded_data_length = 0;
int64_t encoded_body_length = 0;
+ base::Optional<int64_t> downloaded_file_length;
+ blink::WebBlobInfo downloaded_blob;
client()->loader()->LoadSynchronously(
- request, response, error, data, encoded_data_length, encoded_body_length);
+ request, response, error, data, encoded_data_length, encoded_body_length,
+ downloaded_file_length, downloaded_blob);
EXPECT_EQ(kEncodedBodyLength, encoded_body_length);
EXPECT_EQ(kEncodedDataLength, encoded_data_length);
+ EXPECT_FALSE(downloaded_file_length);
+ EXPECT_TRUE(downloaded_blob.Uuid().IsNull());
}
} // namespace
diff --git a/chromium/content/renderer/loader/web_url_request_util.cc b/chromium/content/renderer/loader/web_url_request_util.cc
index f41221cdc69..13ff3603eba 100644
--- a/chromium/content/renderer/loader/web_url_request_util.cc
+++ b/chromium/content/renderer/loader/web_url_request_util.cc
@@ -24,16 +24,15 @@
#include "services/network/public/mojom/request_context_frame_type.mojom.h"
#include "services/service_manager/public/cpp/connector.h"
#include "services/service_manager/public/cpp/interface_provider.h"
-#include "third_party/WebKit/public/mojom/blob/blob.mojom.h"
-#include "third_party/WebKit/public/mojom/blob/blob_registry.mojom.h"
-#include "third_party/WebKit/public/platform/FilePathConversion.h"
-#include "third_party/WebKit/public/platform/Platform.h"
-#include "third_party/WebKit/public/platform/WebData.h"
-#include "third_party/WebKit/public/platform/WebHTTPHeaderVisitor.h"
-#include "third_party/WebKit/public/platform/WebMixedContent.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebThread.h"
-#include "third_party/WebKit/public/platform/modules/fetch/fetch_api_request.mojom-shared.h"
+#include "third_party/blink/public/mojom/blob/blob.mojom.h"
+#include "third_party/blink/public/platform/file_path_conversion.h"
+#include "third_party/blink/public/platform/modules/fetch/fetch_api_request.mojom-shared.h"
+#include "third_party/blink/public/platform/platform.h"
+#include "third_party/blink/public/platform/web_data.h"
+#include "third_party/blink/public/platform/web_http_header_visitor.h"
+#include "third_party/blink/public/platform/web_mixed_content.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_thread.h"
using blink::mojom::FetchCacheMode;
using blink::WebData;
@@ -106,94 +105,6 @@ class HeaderFlattener : public blink::WebHTTPHeaderVisitor {
std::string buffer_;
};
-// Vends data pipes to read a Blob. It stays alive until all Mojo connections
-// close.
-class DataPipeGetter : public network::mojom::DataPipeGetter {
- public:
- DataPipeGetter(blink::mojom::BlobPtr blob,
- network::mojom::DataPipeGetterRequest request) {
- // If a sync XHR is doing the upload, then the main thread will be blocked.
- // So we must bind on a background thread, otherwise the methods below will
- // never be called and the process will hang.
- scoped_refptr<base::SingleThreadTaskRunner> task_runner =
- base::CreateSingleThreadTaskRunnerWithTraits(
- {base::TaskPriority::USER_VISIBLE,
- base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN});
- task_runner->PostTask(
- FROM_HERE,
- base::BindOnce(&DataPipeGetter::BindInternal, base::Unretained(this),
- blob.PassInterface(), std::move(request)));
- }
- ~DataPipeGetter() override = default;
-
- private:
- class BlobReaderClient : public blink::mojom::BlobReaderClient {
- public:
- explicit BlobReaderClient(ReadCallback callback)
- : callback_(std::move(callback)) {
- DCHECK(!callback_.is_null());
- }
- ~BlobReaderClient() override = default;
-
- // blink::mojom::BlobReaderClient implementation:
- void OnCalculatedSize(uint64_t total_size,
- uint64_t expected_content_size) override {
- // Check if null since it's conceivable OnComplete() was already called
- // with error.
- if (!callback_.is_null())
- std::move(callback_).Run(net::OK, total_size);
- }
- void OnComplete(int32_t status, uint64_t data_length) override {
- // Check if null since OnCalculatedSize() may have already been called
- // and an error occurred later.
- if (!callback_.is_null() && status != net::OK) {
- // On error, signal failure immediately. On success, OnCalculatedSize()
- // is guaranteed to be called, and the result will be signaled from
- // there.
- std::move(callback_).Run(status, 0);
- }
- }
-
- private:
- ReadCallback callback_;
-
- DISALLOW_COPY_AND_ASSIGN(BlobReaderClient);
- };
-
- void BindInternal(blink::mojom::BlobPtrInfo blob,
- network::mojom::DataPipeGetterRequest request) {
- bindings_.set_connection_error_handler(base::BindRepeating(
- &DataPipeGetter::OnConnectionError, base::Unretained(this)));
- bindings_.AddBinding(this, std::move(request));
- blob_.Bind(std::move(blob));
- }
-
- void OnConnectionError() {
- if (bindings_.empty())
- delete this;
- }
-
- // network::mojom::DataPipeGetter implementation:
- void Read(mojo::ScopedDataPipeProducerHandle handle,
- ReadCallback callback) override {
- blink::mojom::BlobReaderClientPtr blob_reader_client_ptr;
- mojo::MakeStrongBinding(
- std::make_unique<BlobReaderClient>(std::move(callback)),
- mojo::MakeRequest(&blob_reader_client_ptr));
- blob_->ReadAll(std::move(handle), std::move(blob_reader_client_ptr));
- }
-
- void Clone(network::mojom::DataPipeGetterRequest request) override {
- bindings_.AddBinding(this, std::move(request));
- }
-
- private:
- blink::mojom::BlobPtr blob_;
- mojo::BindingSet<network::mojom::DataPipeGetter> bindings_;
-
- DISALLOW_COPY_AND_ASSIGN(DataPipeGetter);
-};
-
} // namespace
ResourceType WebURLRequestContextToResourceType(
@@ -337,12 +248,6 @@ std::string GetWebURLRequestHeadersAsString(
int GetLoadFlagsForWebURLRequest(const WebURLRequest& request) {
int load_flags = net::LOAD_NORMAL;
- // Although EV status is irrelevant to sub-frames and sub-resources, we have
- // to perform EV certificate verification on all resources because an HTTP
- // keep-alive connection created to load a sub-frame or a sub-resource could
- // be reused to load a main frame.
- load_flags |= net::LOAD_VERIFY_EV_CERT;
-
GURL url = request.Url();
switch (request.GetCacheMode()) {
case FetchCacheMode::kNoStore:
@@ -415,15 +320,13 @@ WebHTTPBody GetWebHTTPBodyForRequestBody(
// Append the cloned data pipe to the |http_body|. This might not be
// needed for all callsites today but it respects the constness of
// |input|, as opposed to moving the data pipe out of |input|.
- network::mojom::DataPipeGetterPtr cloned_data_pipe_getter;
- const_cast<network::mojom::DataPipeGetterPtr&>(element.data_pipe())
- ->Clone(mojo::MakeRequest(&cloned_data_pipe_getter));
http_body.AppendDataPipe(
- cloned_data_pipe_getter.PassInterface().PassHandle());
+ element.CloneDataPipeGetter().PassInterface().PassHandle());
break;
}
case network::DataElement::TYPE_UNKNOWN:
case network::DataElement::TYPE_RAW_FILE:
+ case network::DataElement::TYPE_CHUNKED_DATA_PIPE:
NOTREACHED();
break;
}
@@ -446,19 +349,12 @@ scoped_refptr<network::ResourceRequestBody> GetRequestBodyForWebURLRequest(
return GetRequestBodyForWebHTTPBody(request.HttpBody());
}
-void GetBlobRegistry(blink::mojom::BlobRegistryRequest request) {
- ChildThreadImpl::current()->GetConnector()->BindInterface(
- mojom::kBrowserServiceName, std::move(request));
-}
-
scoped_refptr<network::ResourceRequestBody> GetRequestBodyForWebHTTPBody(
const blink::WebHTTPBody& httpBody) {
scoped_refptr<network::ResourceRequestBody> request_body =
new network::ResourceRequestBody();
size_t i = 0;
WebHTTPBody::Element element;
- // TODO(jam): cache this somewhere so we don't request it each time?
- blink::mojom::BlobRegistryPtr blob_registry;
while (httpBody.ElementAt(i++, element)) {
switch (element.type) {
case WebHTTPBody::Element::kTypeData:
@@ -484,29 +380,13 @@ scoped_refptr<network::ResourceRequestBody> GetRequestBodyForWebHTTPBody(
break;
case WebHTTPBody::Element::kTypeBlob: {
if (base::FeatureList::IsEnabled(network::features::kNetworkService)) {
- if (!blob_registry.is_bound()) {
- if (ChildThreadImpl::current()) {
- ChildThreadImpl::current()->GetConnector()->BindInterface(
- mojom::kBrowserServiceName, MakeRequest(&blob_registry));
- } else {
- // TODO(sammc): We should use per-frame / per-worker
- // InterfaceProvider instead (crbug.com/734210).
- blink::Platform::Current()
- ->MainThread()
- ->GetTaskRunner()
- ->PostTask(FROM_HERE,
- base::BindOnce(&GetBlobRegistry,
- MakeRequest(&blob_registry)));
- }
- }
- blink::mojom::BlobPtr blob_ptr;
- blob_registry->GetBlobFromUUID(MakeRequest(&blob_ptr),
- element.blob_uuid.Utf8());
+ DCHECK(element.optional_blob_handle.is_valid());
+ blink::mojom::BlobPtr blob_ptr(
+ blink::mojom::BlobPtrInfo(std::move(element.optional_blob_handle),
+ blink::mojom::Blob::Version_));
network::mojom::DataPipeGetterPtr data_pipe_getter_ptr;
- // Object deletes itself.
- new DataPipeGetter(std::move(blob_ptr),
- MakeRequest(&data_pipe_getter_ptr));
+ blob_ptr->AsDataPipeGetter(MakeRequest(&data_pipe_getter_ptr));
request_body->AppendDataPipe(std::move(data_pipe_getter_ptr));
} else {
diff --git a/chromium/content/renderer/loader/web_url_request_util.h b/chromium/content/renderer/loader/web_url_request_util.h
index ac622e47eef..dd42dcb240e 100644
--- a/chromium/content/renderer/loader/web_url_request_util.h
+++ b/chromium/content/renderer/loader/web_url_request_util.h
@@ -13,8 +13,8 @@
#include "net/http/http_request_headers.h"
#include "services/network/public/cpp/resource_request_body.h"
#include "services/network/public/mojom/request_context_frame_type.mojom.h"
-#include "third_party/WebKit/public/platform/WebMixedContentContextType.h"
-#include "third_party/WebKit/public/platform/WebURLRequest.h"
+#include "third_party/blink/public/platform/web_mixed_content_context_type.h"
+#include "third_party/blink/public/platform/web_url_request.h"
namespace blink {
class WebHTTPBody;
diff --git a/chromium/content/renderer/loader/weburlresponse_extradata_impl.h b/chromium/content/renderer/loader/weburlresponse_extradata_impl.h
index 0827cfb9247..5d857655774 100644
--- a/chromium/content/renderer/loader/weburlresponse_extradata_impl.h
+++ b/chromium/content/renderer/loader/weburlresponse_extradata_impl.h
@@ -13,7 +13,7 @@
#include "content/public/common/previews_state.h"
#include "net/http/http_response_info.h"
#include "net/nqe/effective_connection_type.h"
-#include "third_party/WebKit/public/platform/WebURLResponse.h"
+#include "third_party/blink/public/platform/web_url_response.h"
namespace content {
diff --git a/chromium/content/renderer/manifest/manifest_change_notifier.cc b/chromium/content/renderer/manifest/manifest_change_notifier.cc
index 7da910dae83..8e2a94bb4c7 100644
--- a/chromium/content/renderer/manifest/manifest_change_notifier.cc
+++ b/chromium/content/renderer/manifest/manifest_change_notifier.cc
@@ -9,9 +9,9 @@
#include "base/bind.h"
#include "content/public/renderer/render_frame.h"
#include "content/renderer/manifest/manifest_manager.h"
-#include "third_party/WebKit/public/common/associated_interfaces/associated_interface_provider.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_local_frame.h"
namespace content {
@@ -38,7 +38,7 @@ void ManifestChangeNotifier::DidChangeManifest() {
// of this notification and the favicon URL reporting.
if (!render_frame()->GetWebFrame()->IsLoading()) {
render_frame()
- ->GetTaskRunner(blink::TaskType::kUnspecedLoading)
+ ->GetTaskRunner(blink::TaskType::kInternalLoading)
->PostTask(FROM_HERE,
base::BindOnce(&ManifestChangeNotifier::ReportManifestChange,
weak_factory_.GetWeakPtr()));
diff --git a/chromium/content/renderer/manifest/manifest_manager.cc b/chromium/content/renderer/manifest/manifest_manager.cc
index 7a33fbec001..32868f6bf99 100644
--- a/chromium/content/renderer/manifest/manifest_manager.cc
+++ b/chromium/content/renderer/manifest/manifest_manager.cc
@@ -12,11 +12,11 @@
#include "content/renderer/fetchers/manifest_fetcher.h"
#include "content/renderer/manifest/manifest_parser.h"
#include "content/renderer/manifest/manifest_uma_util.h"
-#include "third_party/WebKit/public/common/associated_interfaces/associated_interface_provider.h"
-#include "third_party/WebKit/public/platform/WebURLResponse.h"
-#include "third_party/WebKit/public/web/WebConsoleMessage.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
+#include "third_party/blink/public/platform/web_url_response.h"
+#include "third_party/blink/public/web/web_console_message.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_local_frame.h"
namespace content {
diff --git a/chromium/content/renderer/manifest/manifest_manager.h b/chromium/content/renderer/manifest/manifest_manager.h
index 1d5997f7735..b6799d46643 100644
--- a/chromium/content/renderer/manifest/manifest_manager.h
+++ b/chromium/content/renderer/manifest/manifest_manager.h
@@ -15,7 +15,7 @@
#include "content/public/common/manifest.h"
#include "content/public/renderer/render_frame_observer.h"
#include "mojo/public/cpp/bindings/binding_set.h"
-#include "third_party/WebKit/public/platform/modules/manifest/manifest_manager.mojom.h"
+#include "third_party/blink/public/platform/modules/manifest/manifest_manager.mojom.h"
class GURL;
diff --git a/chromium/content/renderer/manifest/manifest_parser.cc b/chromium/content/renderer/manifest/manifest_parser.cc
index faf66e6d451..3f4a29fb8b9 100644
--- a/chromium/content/renderer/manifest/manifest_parser.cc
+++ b/chromium/content/renderer/manifest/manifest_parser.cc
@@ -7,7 +7,6 @@
#include <stddef.h>
#include "base/json/json_reader.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/nullable_string16.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
@@ -15,13 +14,14 @@
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "content/public/common/manifest.h"
+#include "content/public/common/manifest_share_target_util.h"
#include "content/public/common/manifest_util.h"
#include "content/renderer/manifest/manifest_uma_util.h"
-#include "third_party/WebKit/public/platform/WebColor.h"
-#include "third_party/WebKit/public/platform/WebIconSizesParser.h"
-#include "third_party/WebKit/public/platform/WebSize.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/web/WebCSSParser.h"
+#include "third_party/blink/public/platform/web_color.h"
+#include "third_party/blink/public/platform/web_icon_sizes_parser.h"
+#include "third_party/blink/public/platform/web_size.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/web/web_css_parser.h"
#include "ui/gfx/geometry/size.h"
namespace content {
@@ -347,9 +347,18 @@ std::vector<Manifest::Icon> ManifestParser::ParseIcons(
return icons;
}
-base::NullableString16 ManifestParser::ParseShareTargetURLTemplate(
+GURL ManifestParser::ParseShareTargetURLTemplate(
const base::DictionaryValue& share_target) {
- return ParseString(share_target, "url_template", Trim);
+ GURL url_template = ParseURL(share_target, "url_template", manifest_url_,
+ ParseURLOriginRestrictions::kSameOriginOnly);
+ if (!ValidateWebShareUrlTemplate(url_template)) {
+ AddErrorInfo(
+ "property 'url_template' ignored. Placeholders have incorrect "
+ "syntax.");
+ return GURL();
+ }
+
+ return url_template;
}
base::Optional<Manifest::ShareTarget> ManifestParser::ParseShareTarget(
@@ -362,9 +371,8 @@ base::Optional<Manifest::ShareTarget> ManifestParser::ParseShareTarget(
dictionary.GetDictionary("share_target", &share_target_dict);
share_target.url_template = ParseShareTargetURLTemplate(*share_target_dict);
- if (share_target.url_template.is_null()) {
+ if (share_target.url_template.is_empty())
return base::nullopt;
- }
return base::Optional<Manifest::ShareTarget>(share_target);
}
diff --git a/chromium/content/renderer/manifest/manifest_parser.h b/chromium/content/renderer/manifest/manifest_parser.h
index 30972b9086c..7e0cb7dfae2 100644
--- a/chromium/content/renderer/manifest/manifest_parser.h
+++ b/chromium/content/renderer/manifest/manifest_parser.h
@@ -15,7 +15,7 @@
#include "base/strings/string_piece.h"
#include "content/common/content_export.h"
#include "content/public/common/manifest.h"
-#include "third_party/WebKit/public/platform/modules/manifest/manifest.mojom.h"
+#include "third_party/blink/public/platform/modules/manifest/manifest.mojom.h"
class GURL;
@@ -158,10 +158,8 @@ class CONTENT_EXPORT ManifestParser {
// Parses the 'url_template' field of a Share Target, as defined in:
// https://github.com/WICG/web-share-target/blob/master/docs/interface.md
- // Returns the parsed string if any, or a null string if the field was not
- // present, or didn't contain a string.
- base::NullableString16 ParseShareTargetURLTemplate(
- const base::DictionaryValue& share_target);
+ // Returns the parsed GURL if any, or an empty GURL if the parsing failed.
+ GURL ParseShareTargetURLTemplate(const base::DictionaryValue& share_target);
// Parses the 'share_target' field of a Manifest, as defined in:
// https://github.com/WICG/web-share-target/blob/master/docs/interface.md
@@ -178,7 +176,7 @@ class CONTENT_EXPORT ManifestParser {
// Parses the 'url' field of a related application, as defined in:
// https://w3c.github.io/manifest/#dfn-steps-for-processing-the-url-member-of-an-application
- // Returns the paresed GURL if any, an empty GURL if the parsing failed.
+ // Returns the parsed GURL if any, an empty GURL if the parsing failed.
GURL ParseRelatedApplicationURL(const base::DictionaryValue& application);
// Parses the 'id' field of a related application, as defined in:
diff --git a/chromium/content/renderer/manifest/manifest_parser_unittest.cc b/chromium/content/renderer/manifest/manifest_parser_unittest.cc
index df2da1014f2..db1768db351 100644
--- a/chromium/content/renderer/manifest/manifest_parser_unittest.cc
+++ b/chromium/content/renderer/manifest/manifest_parser_unittest.cc
@@ -1005,13 +1005,17 @@ TEST_F(ManifestParserTest, ShareTargetParseRules) {
}
TEST_F(ManifestParserTest, ShareTargetUrlTemplateParseRules) {
+ GURL manifest_url = GURL("https://foo.com/manifest.json");
+ GURL document_url = GURL("https://foo.com/index.html");
+
// Contains share_target and url_template, but url_template is empty.
{
- Manifest manifest =
- ParseManifest("{ \"share_target\": { \"url_template\": \"\" } }");
+ Manifest manifest = ParseManifestWithURLs(
+ "{ \"share_target\": { \"url_template\": \"\" } }", manifest_url,
+ document_url);
ASSERT_TRUE(manifest.share_target.has_value());
- EXPECT_TRUE(base::EqualsASCII(
- manifest.share_target.value().url_template.string(), ""));
+ EXPECT_EQ(manifest.share_target.value().url_template.spec(),
+ manifest_url.spec());
EXPECT_FALSE(manifest.IsEmpty());
EXPECT_EQ(0u, GetErrorCount());
}
@@ -1019,7 +1023,8 @@ TEST_F(ManifestParserTest, ShareTargetUrlTemplateParseRules) {
// Don't parse if property isn't a string.
{
Manifest manifest =
- ParseManifest("{ \"share_target\": { \"url_template\": {} } }");
+ ParseManifestWithURLs("{ \"share_target\": { \"url_template\": {} } }",
+ manifest_url, document_url);
EXPECT_FALSE(manifest.share_target.has_value());
EXPECT_TRUE(manifest.IsEmpty());
EXPECT_EQ(1u, GetErrorCount());
@@ -1030,7 +1035,8 @@ TEST_F(ManifestParserTest, ShareTargetUrlTemplateParseRules) {
// Don't parse if property isn't a string.
{
Manifest manifest =
- ParseManifest("{ \"share_target\": { \"url_template\": 42 } }");
+ ParseManifestWithURLs("{ \"share_target\": { \"url_template\": 42 } }",
+ manifest_url, document_url);
EXPECT_FALSE(manifest.share_target.has_value());
EXPECT_TRUE(manifest.IsEmpty());
EXPECT_EQ(1u, GetErrorCount());
@@ -1038,15 +1044,41 @@ TEST_F(ManifestParserTest, ShareTargetUrlTemplateParseRules) {
errors()[0]);
}
+ // Don't parse if property isn't a valid URL.
+ {
+ Manifest manifest = ParseManifestWithURLs(
+ "{ \"share_target\": { \"url_template\": \"https://foo.com:a\" } "
+ "}",
+ manifest_url, document_url);
+ EXPECT_FALSE(manifest.share_target.has_value());
+ EXPECT_TRUE(manifest.IsEmpty());
+ EXPECT_EQ(1u, GetErrorCount());
+ EXPECT_EQ("property 'url_template' ignored, URL is invalid.", errors()[0]);
+ }
+
+ // Fail parsing if url_template is at a different origin than the Web
+ // Manifest.
+ {
+ Manifest manifest = ParseManifestWithURLs(
+ "{ \"share_target\": { \"url_template\": \"https://foo2.com/\" } }",
+ manifest_url, document_url);
+ EXPECT_FALSE(manifest.share_target.has_value());
+ EXPECT_TRUE(manifest.IsEmpty());
+ EXPECT_EQ(1u, GetErrorCount());
+ EXPECT_EQ(
+ "property 'url_template' ignored, should be same origin as document.",
+ errors()[0]);
+ }
+
// Smoke test: Contains share_target and url_template, and url_template is
// valid template.
{
- Manifest manifest = ParseManifest(
- "{ \"share_target\": {\"url_template\": \"share/?title={title}\" } }");
+ Manifest manifest = ParseManifestWithURLs(
+ "{ \"share_target\": {\"url_template\": \"share/?title={title}\" } }",
+ manifest_url, document_url);
ASSERT_TRUE(manifest.share_target.has_value());
- EXPECT_TRUE(
- base::EqualsASCII(manifest.share_target.value().url_template.string(),
- "share/?title={title}"));
+ EXPECT_EQ(manifest.share_target.value().url_template.spec(),
+ "https://foo.com/share/?title={title}");
EXPECT_FALSE(manifest.IsEmpty());
EXPECT_EQ(0u, GetErrorCount());
}
@@ -1054,12 +1086,56 @@ TEST_F(ManifestParserTest, ShareTargetUrlTemplateParseRules) {
// Smoke test: Contains share_target and url_template, and url_template is
// invalid template.
{
- Manifest manifest = ParseManifest(
- "{ \"share_target\": {\"url_template\": \"share/?title={title\" } }");
+ Manifest manifest = ParseManifestWithURLs(
+ "{ \"share_target\": {\"url_template\": \"share/?title={title\" } }",
+ manifest_url, document_url);
+ ASSERT_FALSE(manifest.share_target.has_value());
+ EXPECT_TRUE(manifest.IsEmpty());
+ EXPECT_EQ(1u, GetErrorCount());
+ EXPECT_EQ(
+ "property 'url_template' ignored. Placeholders have incorrect "
+ "syntax.",
+ errors()[0]);
+ }
+
+ // Smoke test: Contains share_target and url_template, and url_template
+ // contains unknown placeholder.
+ {
+ Manifest manifest = ParseManifestWithURLs(
+ "{ \"share_target\": {\"url_template\": \"share/?title={abcxyz}\" } }",
+ manifest_url, document_url);
+ ASSERT_TRUE(manifest.share_target.has_value());
+ EXPECT_EQ(manifest.share_target.value().url_template.spec(),
+ "https://foo.com/share/?title={abcxyz}");
+ EXPECT_FALSE(manifest.IsEmpty());
+ EXPECT_EQ(0u, GetErrorCount());
+ }
+
+ // Smoke test: Contains share_target and url_template, and url_template has
+ // '{' and '}' in path, query and fragment. Only '{' and '}' in path should be
+ // escaped.
+ {
+ Manifest manifest = ParseManifestWithURLs(
+ "{ \"share_target\": {\"url_template\": "
+ "\"share/a{text}/?title={title}#{frag}\" } }",
+ manifest_url, document_url);
+ ASSERT_TRUE(manifest.share_target.has_value());
+ EXPECT_EQ(manifest.share_target.value().url_template.spec(),
+ "https://foo.com/share/a%7Btext%7D/?title={title}#{frag}");
+ EXPECT_FALSE(manifest.IsEmpty());
+ EXPECT_EQ(0u, GetErrorCount());
+ }
+
+ // Smoke test: Contains share_target and url_template. url_template is
+ // valid template and is absolute.
+ {
+ Manifest manifest = ParseManifestWithURLs(
+ "{ \"share_target\": { \"url_template\": \"https://foo.com/#{text}\" } "
+ "}",
+ manifest_url, document_url);
ASSERT_TRUE(manifest.share_target.has_value());
- EXPECT_TRUE(
- base::EqualsASCII(manifest.share_target.value().url_template.string(),
- "share/?title={title"));
+ EXPECT_EQ(manifest.share_target.value().url_template.spec(),
+ "https://foo.com/#{text}");
EXPECT_FALSE(manifest.IsEmpty());
EXPECT_EQ(0u, GetErrorCount());
}
diff --git a/chromium/content/renderer/media/android/media_player_renderer_client_factory.cc b/chromium/content/renderer/media/android/media_player_renderer_client_factory.cc
index 3289a72ab3b..b34fc6b1412 100644
--- a/chromium/content/renderer/media/android/media_player_renderer_client_factory.cc
+++ b/chromium/content/renderer/media/android/media_player_renderer_client_factory.cc
@@ -4,7 +4,6 @@
#include "content/renderer/media/android/media_player_renderer_client_factory.h"
-#include "base/memory/ptr_util.h"
#include "content/renderer/media/android/media_player_renderer_client.h"
#include "media/mojo/clients/mojo_renderer.h"
diff --git a/chromium/content/renderer/media/android/renderer_media_player_manager.cc b/chromium/content/renderer/media/android/renderer_media_player_manager.cc
index 9bd3c0abd18..72ae5491082 100644
--- a/chromium/content/renderer/media/android/renderer_media_player_manager.cc
+++ b/chromium/content/renderer/media/android/renderer_media_player_manager.cc
@@ -9,7 +9,7 @@
#include "content/public/common/renderer_preferences.h"
#include "content/renderer/render_view_impl.h"
#include "media/base/media_switches.h"
-#include "third_party/WebKit/public/platform/modules/remoteplayback/WebRemotePlaybackAvailability.h"
+#include "third_party/blink/public/platform/modules/remoteplayback/web_remote_playback_availability.h"
#include "ui/gfx/geometry/rect_f.h"
namespace content {
@@ -94,9 +94,7 @@ void RendererMediaPlayerManager::Pause(
routing_id(), player_id, is_media_related_action));
}
-void RendererMediaPlayerManager::Seek(
- int player_id,
- const base::TimeDelta& time) {
+void RendererMediaPlayerManager::Seek(int player_id, base::TimeDelta time) {
Send(new MediaPlayerHostMsg_Seek(routing_id(), player_id, time));
}
@@ -154,17 +152,15 @@ void RendererMediaPlayerManager::OnMediaBufferingUpdate(int player_id,
player->OnBufferingUpdate(percent);
}
-void RendererMediaPlayerManager::OnSeekRequest(
- int player_id,
- const base::TimeDelta& time_to_seek) {
+void RendererMediaPlayerManager::OnSeekRequest(int player_id,
+ base::TimeDelta time_to_seek) {
media::RendererMediaPlayerInterface* player = GetMediaPlayer(player_id);
if (player)
player->OnSeekRequest(time_to_seek);
}
-void RendererMediaPlayerManager::OnSeekCompleted(
- int player_id,
- const base::TimeDelta& current_time) {
+void RendererMediaPlayerManager::OnSeekCompleted(int player_id,
+ base::TimeDelta current_time) {
media::RendererMediaPlayerInterface* player = GetMediaPlayer(player_id);
if (player)
player->OnSeekComplete(current_time);
diff --git a/chromium/content/renderer/media/android/renderer_media_player_manager.h b/chromium/content/renderer/media/android/renderer_media_player_manager.h
index 6c48bed765f..d8b2a58d6f0 100644
--- a/chromium/content/renderer/media/android/renderer_media_player_manager.h
+++ b/chromium/content/renderer/media/android/renderer_media_player_manager.h
@@ -55,7 +55,7 @@ class RendererMediaPlayerManager :
void Pause(int player_id, bool is_media_related_action) override;
// Performs seek on the player.
- void Seek(int player_id, const base::TimeDelta& time) override;
+ void Seek(int player_id, base::TimeDelta time) override;
// Sets the player volume.
void SetVolume(int player_id, double volume) override;
@@ -100,9 +100,8 @@ class RendererMediaPlayerManager :
bool success);
void OnMediaPlaybackCompleted(int player_id);
void OnMediaBufferingUpdate(int player_id, int percent);
- void OnSeekRequest(int player_id, const base::TimeDelta& time_to_seek);
- void OnSeekCompleted(int player_id,
- const base::TimeDelta& current_timestamp);
+ void OnSeekRequest(int player_id, base::TimeDelta time_to_seek);
+ void OnSeekCompleted(int player_id, base::TimeDelta current_timestamp);
void OnMediaError(int player_id, int error);
void OnVideoSizeChanged(int player_id, int width, int height);
void OnTimeUpdate(int player_id,
diff --git a/chromium/content/renderer/media/android/stream_texture_factory.cc b/chromium/content/renderer/media/android/stream_texture_factory.cc
index ec052f50562..5e982601dab 100644
--- a/chromium/content/renderer/media/android/stream_texture_factory.cc
+++ b/chromium/content/renderer/media/android/stream_texture_factory.cc
@@ -5,7 +5,6 @@
#include "content/renderer/media/android/stream_texture_factory.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "gpu/command_buffer/client/gles2_interface.h"
#include "gpu/ipc/client/command_buffer_proxy_impl.h"
#include "gpu/ipc/client/gpu_channel_host.h"
diff --git a/chromium/content/renderer/media/android/stream_texture_wrapper_impl_unittest.cc b/chromium/content/renderer/media/android/stream_texture_wrapper_impl_unittest.cc
index 51f9e45d8c3..2dcfa75332c 100644
--- a/chromium/content/renderer/media/android/stream_texture_wrapper_impl_unittest.cc
+++ b/chromium/content/renderer/media/android/stream_texture_wrapper_impl_unittest.cc
@@ -8,7 +8,7 @@
#include "base/test/scoped_task_environment.h"
#include "base/threading/thread_task_runner_handle.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
namespace content {
diff --git a/chromium/content/renderer/media/audio_decoder.cc b/chromium/content/renderer/media/audio_decoder.cc
index 5fcc4ecfed7..bb90a36a243 100644
--- a/chromium/content/renderer/media/audio_decoder.cc
+++ b/chromium/content/renderer/media/audio_decoder.cc
@@ -14,8 +14,8 @@
#include "media/base/limits.h"
#include "media/filters/audio_file_reader.h"
#include "media/filters/in_memory_url_protocol.h"
-#include "media/media_features.h"
-#include "third_party/WebKit/public/platform/WebAudioBus.h"
+#include "media/media_buildflags.h"
+#include "third_party/blink/public/platform/web_audio_bus.h"
using media::AudioBus;
using media::AudioFileReader;
diff --git a/chromium/content/renderer/media/audio_decoder_fuzzer.cpp b/chromium/content/renderer/media/audio_decoder_fuzzer.cpp
new file mode 100644
index 00000000000..dec7fe8d9a1
--- /dev/null
+++ b/chromium/content/renderer/media/audio_decoder_fuzzer.cpp
@@ -0,0 +1,45 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/renderer/media/audio_decoder.h"
+
+#include "base/at_exit.h"
+#include "base/command_line.h"
+#include "base/logging.h"
+#include "content/public/test/blink_test_environment.h"
+#include "media/base/media.h"
+#include "third_party/blink/public/platform/web_audio_bus.h"
+
+struct Environment {
+ Environment() {
+ base::CommandLine::Init(0, nullptr);
+ content::SetUpBlinkTestEnvironment();
+
+ // Suppress WARNING messages from the debug build.
+ logging::SetMinLogLevel(logging::LOG_FATAL);
+
+ // This is needed to suppress noisy log messages from ffmpeg.
+ media::InitializeMediaLibrary();
+ }
+
+ base::AtExitManager at_exit;
+};
+
+Environment* env = new Environment();
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+ // Larger inputs are likely to trigger timeouts and OOMs which would not be
+ // considered as valid bugs.
+ if (size > 8 * 1024)
+ return 0;
+
+ blink::WebAudioBus web_audio_bus;
+ bool success = content::DecodeAudioFileData(
+ &web_audio_bus, reinterpret_cast<const char*>(data), size);
+
+ if (!success)
+ return 0;
+
+ return 0;
+}
diff --git a/chromium/content/renderer/media/audio_input_ipc_factory.cc b/chromium/content/renderer/media/audio_input_ipc_factory.cc
index 6ddfdcd7afd..2b67390af9c 100644
--- a/chromium/content/renderer/media/audio_input_ipc_factory.cc
+++ b/chromium/content/renderer/media/audio_input_ipc_factory.cc
@@ -7,7 +7,6 @@
#include <utility>
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/sequenced_task_runner.h"
#include "content/common/media/renderer_audio_input_stream_factory.mojom.h"
#include "content/renderer/media/audio_input_message_filter.h"
diff --git a/chromium/content/renderer/media/audio_output_ipc_factory.cc b/chromium/content/renderer/media/audio_output_ipc_factory.cc
index ad9862b35da..8281bf4e185 100644
--- a/chromium/content/renderer/media/audio_output_ipc_factory.cc
+++ b/chromium/content/renderer/media/audio_output_ipc_factory.cc
@@ -7,7 +7,6 @@
#include <utility>
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/single_thread_task_runner.h"
#include "content/renderer/media/audio_message_filter.h"
#include "content/renderer/media/mojo_audio_output_ipc.h"
@@ -39,7 +38,8 @@ AudioOutputIPCFactory::CreateAudioOutputIPC(int frame_id) const {
// Unretained is safe due to the contract at the top of the header file.
return std::make_unique<MojoAudioOutputIPC>(
base::BindRepeating(&AudioOutputIPCFactory::GetRemoteFactory,
- base::Unretained(this), frame_id));
+ base::Unretained(this), frame_id),
+ io_task_runner_);
}
return audio_message_filter_->CreateAudioOutputIPC(frame_id);
}
diff --git a/chromium/content/renderer/media/audio_renderer_sink_cache.h b/chromium/content/renderer/media/audio_renderer_sink_cache.h
index 25ab762e8b2..b4d7db98405 100644
--- a/chromium/content/renderer/media/audio_renderer_sink_cache.h
+++ b/chromium/content/renderer/media/audio_renderer_sink_cache.h
@@ -5,8 +5,10 @@
#ifndef CONTENT_RENDERER_MEDIA_AUDIO_RENDERER_SINK_CACHE_H_
#define CONTENT_RENDERER_MEDIA_AUDIO_RENDERER_SINK_CACHE_H_
+#include <memory>
#include <string>
+#include "base/memory/scoped_refptr.h"
#include "content/common/content_export.h"
#include "media/base/output_device_info.h"
diff --git a/chromium/content/renderer/media/audio_renderer_sink_cache_impl.cc b/chromium/content/renderer/media/audio_renderer_sink_cache_impl.cc
index 03e8f9ffbf5..8b909f48a21 100644
--- a/chromium/content/renderer/media/audio_renderer_sink_cache_impl.cc
+++ b/chromium/content/renderer/media/audio_renderer_sink_cache_impl.cc
@@ -2,6 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
+#include "content/renderer/media/audio_renderer_sink_cache_impl.h"
+
#include <algorithm>
#include <memory>
#include <utility>
@@ -13,7 +15,6 @@
#include "base/synchronization/lock.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/renderer/media/audio_device_factory.h"
-#include "content/renderer/media/audio_renderer_sink_cache_impl.h"
#include "media/audio/audio_device_description.h"
#include "media/base/audio_renderer_sink.h"
#include "url/origin.h"
diff --git a/chromium/content/renderer/media/audio_renderer_sink_cache_impl.h b/chromium/content/renderer/media/audio_renderer_sink_cache_impl.h
index 0ea02da24d0..8fa3a709917 100644
--- a/chromium/content/renderer/media/audio_renderer_sink_cache_impl.h
+++ b/chromium/content/renderer/media/audio_renderer_sink_cache_impl.h
@@ -10,6 +10,8 @@
#include <string>
#include <vector>
+#include "base/callback.h"
+#include "base/memory/weak_ptr.h"
#include "base/single_thread_task_runner.h"
#include "base/synchronization/lock.h"
#include "base/time/time.h"
diff --git a/chromium/content/renderer/media/audio_renderer_sink_cache_unittest.cc b/chromium/content/renderer/media/audio_renderer_sink_cache_unittest.cc
index b8be9d8e22b..feebf4b5db9 100644
--- a/chromium/content/renderer/media/audio_renderer_sink_cache_unittest.cc
+++ b/chromium/content/renderer/media/audio_renderer_sink_cache_unittest.cc
@@ -2,23 +2,21 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include <array>
+#include "content/renderer/media/audio_renderer_sink_cache_impl.h"
+
+#include <utility>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/logging.h"
-#include "base/message_loop/message_loop.h"
-#include "base/test/test_simple_task_runner.h"
-#include "base/test/test_timeouts.h"
+#include "base/test/scoped_task_environment.h"
#include "base/threading/thread.h"
-#include "content/renderer/media/audio_renderer_sink_cache_impl.h"
#include "media/audio/audio_device_description.h"
#include "media/base/audio_parameters.h"
#include "media/base/mock_audio_renderer_sink.h"
-#include "media/base/test_helpers.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "url/gurl.h"
+#include "url/origin.h"
namespace content {
@@ -29,17 +27,20 @@ const char kAnotherDeviceId[] = "another-device-id";
const char kUnhealthyDeviceId[] = "i-am-sick";
const int kNonZeroSessionId = 1;
const int kRenderFrameId = 124;
-const int kDeleteTimeoutMs = 500;
+constexpr base::TimeDelta kDeleteTimeout =
+ base::TimeDelta::FromMilliseconds(500);
} // namespace
class AudioRendererSinkCacheTest : public testing::Test {
public:
AudioRendererSinkCacheTest()
- : cache_(new AudioRendererSinkCacheImpl(
- message_loop_.task_runner(),
+ : task_env_(base::test::ScopedTaskEnvironment::MainThreadType::MOCK_TIME,
+ base::test::ScopedTaskEnvironment::ExecutionMode::QUEUED),
+ cache_(std::make_unique<AudioRendererSinkCacheImpl>(
+ task_env_.GetMainThreadTaskRunner(),
base::BindRepeating(&AudioRendererSinkCacheTest::CreateSink,
base::Unretained(this)),
- base::TimeDelta::FromMilliseconds(kDeleteTimeoutMs))) {}
+ kDeleteTimeout)) {}
void GetSink(int render_frame_id,
const std::string& device_id,
@@ -48,25 +49,9 @@ class AudioRendererSinkCacheTest : public testing::Test {
*sink = cache_->GetSink(render_frame_id, device_id, security_origin).get();
}
- void GetRandomSinkInfo(int frame) {
- // Get info and check if memory is not corrupted.
- EXPECT_EQ(kDefaultDeviceId,
- cache_->GetSinkInfo(frame, 0, kDefaultDeviceId, url::Origin())
- .device_id());
- }
-
- void GetRandomSink(int frame, base::TimeDelta sleep_timeout) {
- scoped_refptr<media::AudioRendererSink> sink =
- cache_->GetSink(frame, kDefaultDeviceId, url::Origin()).get();
- ExpectToStop(sink.get());
- base::PlatformThread::Sleep(sleep_timeout);
- cache_->ReleaseSink(sink.get());
- sink->Stop(); // Call a method to make the object is not corrupted.
- }
-
protected:
int sink_count() {
- DCHECK(message_loop_.task_runner()->BelongsToCurrentThread());
+ DCHECK(task_env_.GetMainThreadTaskRunner()->BelongsToCurrentThread());
return cache_->GetCacheSizeForTesting();
}
@@ -75,18 +60,12 @@ class AudioRendererSinkCacheTest : public testing::Test {
int session_id,
const std::string& device_id,
const url::Origin& security_origin) {
- return new media::MockAudioRendererSink(
+ return new testing::NiceMock<media::MockAudioRendererSink>(
device_id, (device_id == kUnhealthyDeviceId)
? media::OUTPUT_DEVICE_STATUS_ERROR_INTERNAL
: media::OUTPUT_DEVICE_STATUS_OK);
}
- void ExpectToStop(media::AudioRendererSink* sink) {
- // Sink must be stoped before deletion.
- EXPECT_CALL(*static_cast<media::MockAudioRendererSink*>(sink), Stop())
- .Times(1);
- }
-
void ExpectNotToStop(media::AudioRendererSink* sink) {
// The sink must be stoped before deletion.
EXPECT_CALL(*static_cast<media::MockAudioRendererSink*>(sink), Stop())
@@ -95,21 +74,20 @@ class AudioRendererSinkCacheTest : public testing::Test {
// Posts the task to the specified thread and runs current message loop until
// the task is completed.
- void PostAndRunUntilDone(const base::Thread& thread, base::OnceClosure task) {
- media::WaitableMessageLoopEvent event;
- thread.task_runner()->PostTaskAndReply(FROM_HERE, std::move(task),
- event.GetClosure());
- // Runs the loop and waits for the thread to call event's closure.
- event.RunAndWait();
- }
+ void PostAndWaitUntilDone(const base::Thread& thread,
+ base::OnceClosure task) {
+ base::WaitableEvent e{base::WaitableEvent::ResetPolicy::MANUAL,
+ base::WaitableEvent::InitialState::NOT_SIGNALED};
- void WaitOnAnotherThread(const base::Thread& thread, int timeout_ms) {
- PostAndRunUntilDone(
- thread, base::BindOnce(base::IgnoreResult(&base::PlatformThread::Sleep),
- base::TimeDelta::FromMilliseconds(timeout_ms)));
+ thread.task_runner()->PostTask(FROM_HERE, std::move(task));
+ thread.task_runner()->PostTask(
+ FROM_HERE,
+ base::BindOnce(&base::WaitableEvent::Signal, base::Unretained(&e)));
+
+ e.Wait();
}
- base::MessageLoop message_loop_;
+ base::test::ScopedTaskEnvironment task_env_;
std::unique_ptr<AudioRendererSinkCacheImpl> cache_;
private:
@@ -201,14 +179,9 @@ TEST_F(AudioRendererSinkCacheTest, GetDeviceInfo) {
}
// Verify that the sink created with GetSinkInfo() is deleted if unused.
-// The test produces 2 "Uninteresting mock" warnings for
-// MockAudioRendererSink::Stop().
TEST_F(AudioRendererSinkCacheTest, GarbageCollection) {
EXPECT_EQ(0, sink_count());
- base::Thread thread("timeout_thread");
- thread.Start();
-
media::OutputDeviceInfo device_info =
cache_->GetSinkInfo(kRenderFrameId, 0, kDefaultDeviceId, url::Origin());
EXPECT_EQ(1, sink_count());
@@ -217,8 +190,9 @@ TEST_F(AudioRendererSinkCacheTest, GarbageCollection) {
cache_->GetSinkInfo(kRenderFrameId, 0, kAnotherDeviceId, url::Origin());
EXPECT_EQ(2, sink_count());
- // 100 ms more than garbage collection timeout.
- WaitOnAnotherThread(thread, kDeleteTimeoutMs + 100);
+ // Wait for garbage collection. Doesn't actually sleep, just advances the mock
+ // clock.
+ task_env_.FastForwardBy(kDeleteTimeout);
// All the sinks should be garbage-collected by now.
EXPECT_EQ(0, sink_count());
@@ -229,17 +203,14 @@ TEST_F(AudioRendererSinkCacheTest, GarbageCollection) {
TEST_F(AudioRendererSinkCacheTest, NoGarbageCollectionForUsedSink) {
EXPECT_EQ(0, sink_count());
- base::Thread thread("timeout_thread");
- thread.Start();
-
media::OutputDeviceInfo device_info =
cache_->GetSinkInfo(kRenderFrameId, 0, kDefaultDeviceId, url::Origin());
EXPECT_EQ(1, sink_count());
- // Wait significantly less than grabage collection timeout.
- int wait_a_bit = 100;
- DCHECK_GT(kDeleteTimeoutMs, wait_a_bit * 2);
- WaitOnAnotherThread(thread, wait_a_bit);
+ // Wait less than garbage collection timeout.
+ base::TimeDelta wait_a_bit =
+ kDeleteTimeout - base::TimeDelta::FromMilliseconds(1);
+ task_env_.FastForwardBy(wait_a_bit);
// Sink is not deleted yet.
EXPECT_EQ(1, sink_count());
@@ -251,7 +222,7 @@ TEST_F(AudioRendererSinkCacheTest, NoGarbageCollectionForUsedSink) {
EXPECT_EQ(1, sink_count());
// Wait more to hit garbage collection timeout.
- WaitOnAnotherThread(thread, kDeleteTimeoutMs);
+ task_env_.FastForwardBy(kDeleteTimeout);
// The sink is still in place.
EXPECT_EQ(1, sink_count());
@@ -277,7 +248,7 @@ TEST_F(AudioRendererSinkCacheTest, UnhealthySinkIsStopped) {
kUnhealthyDeviceId, media::OUTPUT_DEVICE_STATUS_ERROR_INTERNAL);
cache_ = std::make_unique<AudioRendererSinkCacheImpl>(
- message_loop_.task_runner(),
+ task_env_.GetMainThreadTaskRunner(),
base::BindRepeating(
[](scoped_refptr<media::AudioRendererSink> sink, int render_frame_id,
int session_id, const std::string& device_id,
@@ -289,7 +260,7 @@ TEST_F(AudioRendererSinkCacheTest, UnhealthySinkIsStopped) {
return sink;
},
sink),
- base::TimeDelta::FromMilliseconds(kDeleteTimeoutMs));
+ kDeleteTimeout);
EXPECT_CALL(*sink, Stop());
@@ -305,7 +276,7 @@ TEST_F(AudioRendererSinkCacheTest, UnhealthySinkUsingSessionIdIsStopped) {
kUnhealthyDeviceId, media::OUTPUT_DEVICE_STATUS_ERROR_INTERNAL);
cache_ = std::make_unique<AudioRendererSinkCacheImpl>(
- message_loop_.task_runner(),
+ task_env_.GetMainThreadTaskRunner(),
base::BindRepeating(
[](scoped_refptr<media::AudioRendererSink> sink, int render_frame_id,
int session_id, const std::string& device_id,
@@ -317,7 +288,7 @@ TEST_F(AudioRendererSinkCacheTest, UnhealthySinkUsingSessionIdIsStopped) {
return sink;
},
sink),
- base::TimeDelta::FromMilliseconds(kDeleteTimeoutMs));
+ kDeleteTimeout);
EXPECT_CALL(*sink, Stop());
@@ -327,8 +298,6 @@ TEST_F(AudioRendererSinkCacheTest, UnhealthySinkUsingSessionIdIsStopped) {
// Verify that cache works fine if a sink scheduled for deletion is acquired and
// released before deletion timeout elapses.
-// The test produces one "Uninteresting mock" warning for
-// MockAudioRendererSink::Stop().
TEST_F(AudioRendererSinkCacheTest, ReleaseSinkBeforeScheduledDeletion) {
EXPECT_EQ(0, sink_count());
@@ -353,8 +322,7 @@ TEST_F(AudioRendererSinkCacheTest, ReleaseSinkBeforeScheduledDeletion) {
cache_->GetSinkInfo(kRenderFrameId, 0, kAnotherDeviceId, url::Origin());
EXPECT_EQ(1, sink_count()); // This sink is scheduled for deletion now.
- // 100 ms more than garbage collection timeout.
- WaitOnAnotherThread(thread, kDeleteTimeoutMs + 100);
+ task_env_.FastForwardBy(kDeleteTimeout);
// Nothing crashed and the second sink deleted on schedule.
EXPECT_EQ(0, sink_count());
@@ -372,7 +340,7 @@ TEST_F(AudioRendererSinkCacheTest, MultithreadedAccess) {
thread2.Start();
// Request device information on the first thread.
- PostAndRunUntilDone(
+ PostAndWaitUntilDone(
thread1, base::BindOnce(
base::IgnoreResult(&AudioRendererSinkCacheImpl::GetSinkInfo),
base::Unretained(cache_.get()), kRenderFrameId, 0,
@@ -383,16 +351,16 @@ TEST_F(AudioRendererSinkCacheTest, MultithreadedAccess) {
// Request the sink on the second thread.
media::AudioRendererSink* sink;
- PostAndRunUntilDone(thread2,
- base::BindOnce(&AudioRendererSinkCacheTest::GetSink,
- base::Unretained(this), kRenderFrameId,
- kDefaultDeviceId, url::Origin(), &sink));
+ PostAndWaitUntilDone(thread2,
+ base::BindOnce(&AudioRendererSinkCacheTest::GetSink,
+ base::Unretained(this), kRenderFrameId,
+ kDefaultDeviceId, url::Origin(), &sink));
EXPECT_EQ(kDefaultDeviceId, sink->GetOutputDeviceInfo().device_id());
EXPECT_EQ(1, sink_count());
// Request device information on the first thread again.
- PostAndRunUntilDone(
+ PostAndWaitUntilDone(
thread1, base::BindOnce(
base::IgnoreResult(&AudioRendererSinkCacheImpl::GetSinkInfo),
base::Unretained(cache_.get()), kRenderFrameId, 0,
@@ -400,7 +368,7 @@ TEST_F(AudioRendererSinkCacheTest, MultithreadedAccess) {
EXPECT_EQ(1, sink_count());
// Release the sink on the second thread.
- PostAndRunUntilDone(
+ PostAndWaitUntilDone(
thread2,
base::BindOnce(&AudioRendererSinkCache::ReleaseSink,
base::Unretained(cache_.get()), base::RetainedRef(sink)));
@@ -408,45 +376,4 @@ TEST_F(AudioRendererSinkCacheTest, MultithreadedAccess) {
EXPECT_EQ(0, sink_count());
}
-// Intensive parallell access to the cache. Produces a ton of "Uninteresting
-// mock" warnings for Stop() calls - this is fine.
-TEST_F(AudioRendererSinkCacheTest, SmokeTest) {
- const int kExperimentSize = 1000;
- const int kSinkCount = 10;
- const int kThreadCount = 3;
-
- // Sleep no more than (kDeleteTimeoutMs * 3) in total per thread.
- const base::TimeDelta kSleepTimeout =
- base::TimeDelta::FromMilliseconds(kDeleteTimeoutMs * 3 / kExperimentSize);
-
- srand(42); // Does not matter.
-
- std::array<std::unique_ptr<base::Thread>, kThreadCount> threads;
- for (int i = 0; i < kThreadCount; ++i) {
- threads[i].reset(new base::Thread(std::to_string(i)));
- threads[i]->Start();
- }
-
- for (int i = 0; i < kExperimentSize; ++i) {
- for (auto& thread : threads) {
- thread->task_runner()->PostTask(
- FROM_HERE,
- base::BindOnce(&AudioRendererSinkCacheTest::GetRandomSinkInfo,
- base::Unretained(this), rand() % kSinkCount));
- thread->task_runner()->PostTask(
- FROM_HERE, base::BindOnce(&AudioRendererSinkCacheTest::GetRandomSink,
- base::Unretained(this), rand() % kSinkCount,
- kSleepTimeout));
- }
- }
-
- // Wait for completion of all the tasks posted to at least one thread.
- media::WaitableMessageLoopEvent loop_event(
- TestTimeouts::action_max_timeout());
- threads[kThreadCount - 1]->task_runner()->PostTaskAndReply(
- FROM_HERE, base::DoNothing(), loop_event.GetClosure());
- // Runs the loop and waits for the thread to call event's closure.
- loop_event.RunAndWait();
-}
-
} // namespace content
diff --git a/chromium/content/renderer/media/cdm/pepper_cdm_wrapper.h b/chromium/content/renderer/media/cdm/pepper_cdm_wrapper.h
deleted file mode 100644
index b92543996e3..00000000000
--- a/chromium/content/renderer/media/cdm/pepper_cdm_wrapper.h
+++ /dev/null
@@ -1,51 +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 CONTENT_RENDERER_MEDIA_CDM_PEPPER_CDM_WRAPPER_H_
-#define CONTENT_RENDERER_MEDIA_CDM_PEPPER_CDM_WRAPPER_H_
-
-#include "media/media_features.h"
-
-#if !BUILDFLAG(ENABLE_LIBRARY_CDMS)
-#error This file should only be included when ENABLE_LIBRARY_CDMS is defined
-#endif
-
-#include <memory>
-#include <string>
-
-#include "base/callback.h"
-#include "base/macros.h"
-
-namespace url {
-class Origin;
-}
-
-namespace content {
-class ContentDecryptorDelegate;
-
-// PepperCdmWrapper provides access to the Pepper CDM instance.
-class PepperCdmWrapper {
- public:
- virtual ~PepperCdmWrapper() {}
-
- // Returns the ContentDecryptorDelegate* associated with this plugin.
- virtual ContentDecryptorDelegate* GetCdmDelegate() = 0;
-
- protected:
- PepperCdmWrapper() {}
-
- private:
- DISALLOW_COPY_AND_ASSIGN(PepperCdmWrapper);
-};
-
-// Callback used to create a PepperCdmWrapper. This may return null if the
-// Pepper CDM can not be created.
-typedef base::Callback<std::unique_ptr<PepperCdmWrapper>(
- const std::string& pluginType,
- const url::Origin& security_origin)>
- CreatePepperCdmCB;
-
-} // namespace content
-
-#endif // CONTENT_RENDERER_MEDIA_CDM_PEPPER_CDM_WRAPPER_H_
diff --git a/chromium/content/renderer/media/cdm/pepper_cdm_wrapper_impl.cc b/chromium/content/renderer/media/cdm/pepper_cdm_wrapper_impl.cc
deleted file mode 100644
index 97b5d423c1c..00000000000
--- a/chromium/content/renderer/media/cdm/pepper_cdm_wrapper_impl.cc
+++ /dev/null
@@ -1,98 +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 "media/media_features.h"
-
-#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
-#include "content/renderer/media/cdm/pepper_cdm_wrapper_impl.h"
-
-#include <utility>
-
-#include "content/renderer/pepper/pepper_plugin_instance_impl.h"
-#include "content/renderer/pepper/pepper_webplugin_impl.h"
-#include "third_party/WebKit/public/platform/URLConversion.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebElement.h"
-#include "third_party/WebKit/public/web/WebFrame.h"
-#include "third_party/WebKit/public/web/WebHelperPlugin.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebPlugin.h"
-#include "third_party/WebKit/public/web/WebPluginContainer.h"
-#include "third_party/WebKit/public/web/WebView.h"
-#include "url/origin.h"
-
-namespace content {
-
-void WebHelperPluginDeleter::operator()(blink::WebHelperPlugin* plugin) const {
- plugin->Destroy();
-}
-
-std::unique_ptr<PepperCdmWrapper> PepperCdmWrapperImpl::Create(
- blink::WebLocalFrame* frame,
- const std::string& pluginType,
- const url::Origin& security_origin) {
- DCHECK(frame);
-
- // The frame security origin could be different from the origin where the CDM
- // creation was initiated, e.g. due to navigation.
- // Note: The code will continue after navigation to the "same" origin, even
- // though the CDM is no longer necessary.
- // TODO: Consider avoiding this possibility entirely. http://crbug.com/575236
- const url::Origin frame_security_origin(frame->GetSecurityOrigin());
- if (!security_origin.IsSameOriginWith(frame_security_origin)) {
- LOG(ERROR) << "Frame has a different origin than the EME call.";
- return std::unique_ptr<PepperCdmWrapper>();
- }
-
- ScopedHelperPlugin helper_plugin(blink::WebHelperPlugin::Create(
- blink::WebString::FromUTF8(pluginType), frame));
- if (!helper_plugin)
- return std::unique_ptr<PepperCdmWrapper>();
-
- blink::WebPlugin* plugin = helper_plugin->GetPlugin();
- DCHECK(!plugin->IsPlaceholder()); // Prevented by Blink.
-
- // Only Pepper plugins are supported, so it must ultimately be a ppapi object.
- PepperWebPluginImpl* ppapi_plugin = static_cast<PepperWebPluginImpl*>(plugin);
- scoped_refptr<PepperPluginInstanceImpl> plugin_instance =
- ppapi_plugin->instance();
- if (!plugin_instance.get())
- return std::unique_ptr<PepperCdmWrapper>();
-
- CHECK(security_origin.IsSameOriginWith(
- plugin_instance->container()->GetDocument().GetSecurityOrigin()))
- << "Pepper instance has a different origin than the EME call.";
-
- if (!plugin_instance->GetContentDecryptorDelegate())
- return std::unique_ptr<PepperCdmWrapper>();
-
- return std::unique_ptr<PepperCdmWrapper>(
- new PepperCdmWrapperImpl(std::move(helper_plugin), plugin_instance));
-}
-
-PepperCdmWrapperImpl::PepperCdmWrapperImpl(
- ScopedHelperPlugin helper_plugin,
- const scoped_refptr<PepperPluginInstanceImpl>& plugin_instance)
- : helper_plugin_(std::move(helper_plugin)),
- plugin_instance_(plugin_instance) {
- DCHECK(helper_plugin_);
- DCHECK(plugin_instance_.get());
- // Plugin must be a CDM.
- DCHECK(plugin_instance_->GetContentDecryptorDelegate());
-}
-
-PepperCdmWrapperImpl::~PepperCdmWrapperImpl() {
- // Destroy the nested objects in reverse order.
- plugin_instance_ = nullptr;
- helper_plugin_.reset();
-}
-
-ContentDecryptorDelegate* PepperCdmWrapperImpl::GetCdmDelegate() {
- return plugin_instance_->GetContentDecryptorDelegate();
-}
-
-} // namespace content
-
-#endif // BUILDFLAG(ENABLE_LIBRARY_CDMS)
diff --git a/chromium/content/renderer/media/cdm/pepper_cdm_wrapper_impl.h b/chromium/content/renderer/media/cdm/pepper_cdm_wrapper_impl.h
deleted file mode 100644
index 34d972d03cc..00000000000
--- a/chromium/content/renderer/media/cdm/pepper_cdm_wrapper_impl.h
+++ /dev/null
@@ -1,78 +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 CONTENT_RENDERER_MEDIA_CDM_PEPPER_CDM_WRAPPER_IMPL_H_
-#define CONTENT_RENDERER_MEDIA_CDM_PEPPER_CDM_WRAPPER_IMPL_H_
-
-#include "media/media_features.h"
-
-#if !BUILDFLAG(ENABLE_LIBRARY_CDMS)
-#error This file should only be included when ENABLE_LIBRARY_CDMS is defined
-#endif
-
-#include <memory>
-
-#include "base/callback.h"
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "content/renderer/media/cdm/pepper_cdm_wrapper.h"
-
-namespace blink {
-class WebHelperPlugin;
-class WebLocalFrame;
-}
-
-namespace url {
-class Origin;
-}
-
-namespace content {
-
-class ContentDecryptorDelegate;
-class PepperPluginInstanceImpl;
-
-// Deleter for blink::WebHelperPlugin.
-struct WebHelperPluginDeleter {
- void operator()(blink::WebHelperPlugin* plugin) const;
-};
-
-// Implements a wrapper on blink::WebHelperPlugin so that the plugin gets
-// destroyed properly. It owns all the objects derived from WebHelperPlugin
-// (WebPlugin, PepperPluginInstanceImpl, ContentDecryptionDelegate), and will
-// free them as necessary when this wrapper is destroyed. In particular, it
-// takes a reference to PepperPluginInstanceImpl so it won't go away until
-// this object is destroyed.
-//
-// Implemented so that lower layers in Chromium don't need to be aware of
-// blink:: objects.
-class PepperCdmWrapperImpl : public PepperCdmWrapper {
- public:
- static std::unique_ptr<PepperCdmWrapper> Create(
- blink::WebLocalFrame* frame,
- const std::string& pluginType,
- const url::Origin& security_origin);
-
- ~PepperCdmWrapperImpl() override;
-
- // Returns the ContentDecryptorDelegate* associated with this plugin.
- ContentDecryptorDelegate* GetCdmDelegate() override;
-
- private:
- typedef std::unique_ptr<blink::WebHelperPlugin, WebHelperPluginDeleter>
- ScopedHelperPlugin;
-
- // Takes ownership of |helper_plugin| and |plugin_instance|.
- PepperCdmWrapperImpl(
- ScopedHelperPlugin helper_plugin,
- const scoped_refptr<PepperPluginInstanceImpl>& plugin_instance);
-
- ScopedHelperPlugin helper_plugin_;
- scoped_refptr<PepperPluginInstanceImpl> plugin_instance_;
-
- DISALLOW_COPY_AND_ASSIGN(PepperCdmWrapperImpl);
-};
-
-} // namespace content
-
-#endif // CONTENT_RENDERER_MEDIA_CDM_PEPPER_CDM_WRAPPER_IMPL_H_
diff --git a/chromium/content/renderer/media/cdm/ppapi_decryptor.cc b/chromium/content/renderer/media/cdm/ppapi_decryptor.cc
deleted file mode 100644
index ffcb3e964ba..00000000000
--- a/chromium/content/renderer/media/cdm/ppapi_decryptor.cc
+++ /dev/null
@@ -1,472 +0,0 @@
-// Copyright 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/renderer/media/cdm/ppapi_decryptor.h"
-
-#include <string>
-#include <utility>
-
-#include "base/bind.h"
-#include "base/location.h"
-#include "base/logging.h"
-#include "base/single_thread_task_runner.h"
-#include "base/threading/thread_task_runner_handle.h"
-#include "base/trace_event/trace_event.h"
-#include "content/renderer/pepper/content_decryptor_delegate.h"
-#include "content/renderer/pepper/pepper_plugin_instance_impl.h"
-#include "media/base/audio_decoder_config.h"
-#include "media/base/cdm_initialized_promise.h"
-#include "media/base/cdm_key_information.h"
-#include "media/base/data_buffer.h"
-#include "media/base/decoder_buffer.h"
-#include "media/base/key_systems.h"
-#include "media/base/video_decoder_config.h"
-#include "media/base/video_frame.h"
-#include "url/origin.h"
-
-namespace content {
-
-void PpapiDecryptor::Create(
- const std::string& key_system,
- const url::Origin& security_origin,
- bool allow_distinctive_identifier,
- bool allow_persistent_state,
- const CreatePepperCdmCB& create_pepper_cdm_cb,
- const media::SessionMessageCB& session_message_cb,
- const media::SessionClosedCB& session_closed_cb,
- const media::SessionKeysChangeCB& session_keys_change_cb,
- const media::SessionExpirationUpdateCB& session_expiration_update_cb,
- const media::CdmCreatedCB& cdm_created_cb) {
- std::string plugin_type = media::GetPepperType(key_system);
- DCHECK(!plugin_type.empty());
-
- std::unique_ptr<PepperCdmWrapper> pepper_cdm_wrapper;
- {
- TRACE_EVENT0("media", "PpapiDecryptor::CreatePepperCDM");
- pepper_cdm_wrapper = create_pepper_cdm_cb.Run(plugin_type, security_origin);
- }
-
- if (!pepper_cdm_wrapper) {
- std::string message =
- "Unable to create the CDM for the key system " + key_system + ".";
- DLOG(ERROR) << message;
- base::ThreadTaskRunnerHandle::Get()->PostTask(
- FROM_HERE, base::BindOnce(cdm_created_cb, nullptr, message));
- return;
- }
-
- scoped_refptr<PpapiDecryptor> ppapi_decryptor(new PpapiDecryptor(
- std::move(pepper_cdm_wrapper), session_message_cb, session_closed_cb,
- session_keys_change_cb, session_expiration_update_cb));
-
- // |ppapi_decryptor| ownership is passed to the promise.
- std::unique_ptr<media::CdmInitializedPromise> promise(
- new media::CdmInitializedPromise(cdm_created_cb, ppapi_decryptor));
-
- ppapi_decryptor->InitializeCdm(key_system, allow_distinctive_identifier,
- allow_persistent_state, std::move(promise));
-}
-
-PpapiDecryptor::PpapiDecryptor(
- std::unique_ptr<PepperCdmWrapper> pepper_cdm_wrapper,
- const media::SessionMessageCB& session_message_cb,
- const media::SessionClosedCB& session_closed_cb,
- const media::SessionKeysChangeCB& session_keys_change_cb,
- const media::SessionExpirationUpdateCB& session_expiration_update_cb)
- : pepper_cdm_wrapper_(std::move(pepper_cdm_wrapper)),
- session_message_cb_(session_message_cb),
- session_closed_cb_(session_closed_cb),
- session_keys_change_cb_(session_keys_change_cb),
- session_expiration_update_cb_(session_expiration_update_cb),
- render_task_runner_(base::ThreadTaskRunnerHandle::Get()),
- weak_ptr_factory_(this) {
- DCHECK(pepper_cdm_wrapper_.get());
- DCHECK(!session_message_cb_.is_null());
- DCHECK(!session_closed_cb_.is_null());
- DCHECK(!session_keys_change_cb.is_null());
- DCHECK(!session_expiration_update_cb.is_null());
-}
-
-PpapiDecryptor::~PpapiDecryptor() {
- pepper_cdm_wrapper_.reset();
-}
-
-void PpapiDecryptor::InitializeCdm(
- const std::string& key_system,
- bool allow_distinctive_identifier,
- bool allow_persistent_state,
- std::unique_ptr<media::SimpleCdmPromise> promise) {
- base::WeakPtr<PpapiDecryptor> weak_this = weak_ptr_factory_.GetWeakPtr();
- CdmDelegate()->Initialize(
- key_system, allow_distinctive_identifier, allow_persistent_state,
- base::Bind(&PpapiDecryptor::OnSessionMessage, weak_this),
- base::Bind(&PpapiDecryptor::OnSessionClosed, weak_this),
- base::Bind(&PpapiDecryptor::OnSessionKeysChange, weak_this),
- base::Bind(&PpapiDecryptor::OnSessionExpirationUpdate, weak_this),
- base::Bind(&PpapiDecryptor::OnFatalPluginError, weak_this),
- std::move(promise));
-}
-
-void PpapiDecryptor::SetServerCertificate(
- const std::vector<uint8_t>& certificate,
- std::unique_ptr<media::SimpleCdmPromise> promise) {
- DVLOG(2) << __func__;
- DCHECK(render_task_runner_->BelongsToCurrentThread());
-
- if (!CdmDelegate()) {
- promise->reject(media::CdmPromise::Exception::INVALID_STATE_ERROR, 0,
- "CDM has failed.");
- return;
- }
-
- CdmDelegate()->SetServerCertificate(certificate, std::move(promise));
-}
-
-void PpapiDecryptor::GetStatusForPolicy(
- media::HdcpVersion min_hdcp_version,
- std::unique_ptr<media::KeyStatusCdmPromise> promise) {
- DVLOG(2) << __func__;
- DCHECK(render_task_runner_->BelongsToCurrentThread());
-
- if (!CdmDelegate()) {
- promise->reject(media::CdmPromise::Exception::INVALID_STATE_ERROR, 0,
- "CDM has failed.");
- return;
- }
-
- CdmDelegate()->GetStatusForPolicy(min_hdcp_version, std::move(promise));
-}
-
-void PpapiDecryptor::CreateSessionAndGenerateRequest(
- media::CdmSessionType session_type,
- media::EmeInitDataType init_data_type,
- const std::vector<uint8_t>& init_data,
- std::unique_ptr<media::NewSessionCdmPromise> promise) {
- DVLOG(2) << __func__;
- DCHECK(render_task_runner_->BelongsToCurrentThread());
-
- if (!CdmDelegate()) {
- promise->reject(media::CdmPromise::Exception::INVALID_STATE_ERROR, 0,
- "CDM has failed.");
- return;
- }
-
- CdmDelegate()->CreateSessionAndGenerateRequest(session_type, init_data_type,
- init_data, std::move(promise));
-}
-
-void PpapiDecryptor::LoadSession(
- media::CdmSessionType session_type,
- const std::string& session_id,
- std::unique_ptr<media::NewSessionCdmPromise> promise) {
- DVLOG(2) << __func__;
- DCHECK(render_task_runner_->BelongsToCurrentThread());
-
- if (!CdmDelegate()) {
- promise->reject(media::CdmPromise::Exception::INVALID_STATE_ERROR, 0,
- "CDM has failed.");
- return;
- }
- CdmDelegate()->LoadSession(session_type, session_id, std::move(promise));
-}
-
-void PpapiDecryptor::UpdateSession(
- const std::string& session_id,
- const std::vector<uint8_t>& response,
- std::unique_ptr<media::SimpleCdmPromise> promise) {
- DVLOG(2) << __func__;
- DCHECK(render_task_runner_->BelongsToCurrentThread());
-
- if (!CdmDelegate()) {
- promise->reject(media::CdmPromise::Exception::INVALID_STATE_ERROR, 0,
- "CDM has failed.");
- return;
- }
- CdmDelegate()->UpdateSession(session_id, response, std::move(promise));
-}
-
-void PpapiDecryptor::CloseSession(
- const std::string& session_id,
- std::unique_ptr<media::SimpleCdmPromise> promise) {
- DVLOG(2) << __func__;
- DCHECK(render_task_runner_->BelongsToCurrentThread());
-
- if (!CdmDelegate()) {
- promise->reject(media::CdmPromise::Exception::INVALID_STATE_ERROR, 0,
- "CDM has failed.");
- return;
- }
-
- CdmDelegate()->CloseSession(session_id, std::move(promise));
-}
-
-void PpapiDecryptor::RemoveSession(
- const std::string& session_id,
- std::unique_ptr<media::SimpleCdmPromise> promise) {
- DVLOG(2) << __func__;
- DCHECK(render_task_runner_->BelongsToCurrentThread());
-
- if (!CdmDelegate()) {
- promise->reject(media::CdmPromise::Exception::INVALID_STATE_ERROR, 0,
- "CDM has failed.");
- return;
- }
-
- CdmDelegate()->RemoveSession(session_id, std::move(promise));
-}
-
-media::CdmContext* PpapiDecryptor::GetCdmContext() {
- return this;
-}
-
-media::Decryptor* PpapiDecryptor::GetDecryptor() {
- base::AutoLock auto_lock(lock_);
- return had_fatal_plugin_error_ ? nullptr : this;
-}
-
-int PpapiDecryptor::GetCdmId() const {
- return kInvalidCdmId;
-}
-
-void PpapiDecryptor::RegisterNewKeyCB(StreamType stream_type,
- const NewKeyCB& new_key_cb) {
- if (!render_task_runner_->BelongsToCurrentThread()) {
- render_task_runner_->PostTask(
- FROM_HERE, base::BindOnce(&PpapiDecryptor::RegisterNewKeyCB,
- weak_ptr_factory_.GetWeakPtr(), stream_type,
- new_key_cb));
- return;
- }
-
- DVLOG(3) << __func__ << " - stream_type: " << stream_type;
- switch (stream_type) {
- case kAudio:
- new_audio_key_cb_ = new_key_cb;
- break;
- case kVideo:
- new_video_key_cb_ = new_key_cb;
- break;
- default:
- NOTREACHED();
- }
-}
-
-void PpapiDecryptor::Decrypt(
- StreamType stream_type,
- const scoped_refptr<media::DecoderBuffer>& encrypted,
- const DecryptCB& decrypt_cb) {
- if (!render_task_runner_->BelongsToCurrentThread()) {
- render_task_runner_->PostTask(
- FROM_HERE,
- base::BindOnce(&PpapiDecryptor::Decrypt, weak_ptr_factory_.GetWeakPtr(),
- stream_type, encrypted, decrypt_cb));
- return;
- }
-
- // TODO(xhwang): If the buffer is not encrypted, return it directly.
-
- DVLOG(3) << __func__ << " - stream_type: " << stream_type;
- if (!CdmDelegate() ||
- !CdmDelegate()->Decrypt(stream_type, encrypted, decrypt_cb)) {
- decrypt_cb.Run(kError, nullptr);
- }
-}
-
-void PpapiDecryptor::CancelDecrypt(StreamType stream_type) {
- if (!render_task_runner_->BelongsToCurrentThread()) {
- render_task_runner_->PostTask(
- FROM_HERE, base::BindOnce(&PpapiDecryptor::CancelDecrypt,
- weak_ptr_factory_.GetWeakPtr(), stream_type));
- return;
- }
-
- DVLOG(1) << __func__ << " - stream_type: " << stream_type;
- if (CdmDelegate())
- CdmDelegate()->CancelDecrypt(stream_type);
-}
-
-void PpapiDecryptor::InitializeAudioDecoder(
- const media::AudioDecoderConfig& config,
- const DecoderInitCB& init_cb) {
- if (!render_task_runner_->BelongsToCurrentThread()) {
- render_task_runner_->PostTask(
- FROM_HERE,
- base::BindOnce(&PpapiDecryptor::InitializeAudioDecoder,
- weak_ptr_factory_.GetWeakPtr(), config, init_cb));
- return;
- }
-
- DVLOG(2) << __func__;
- DCHECK(config.IsValidConfig());
-
- audio_decoder_init_cb_ = init_cb;
- if (!CdmDelegate() ||
- !CdmDelegate()->InitializeAudioDecoder(
- config, base::Bind(&PpapiDecryptor::OnDecoderInitialized,
- weak_ptr_factory_.GetWeakPtr(), kAudio))) {
- base::ResetAndReturn(&audio_decoder_init_cb_).Run(false);
- return;
- }
-}
-
-void PpapiDecryptor::InitializeVideoDecoder(
- const media::VideoDecoderConfig& config,
- const DecoderInitCB& init_cb) {
- if (!render_task_runner_->BelongsToCurrentThread()) {
- render_task_runner_->PostTask(
- FROM_HERE,
- base::BindOnce(&PpapiDecryptor::InitializeVideoDecoder,
- weak_ptr_factory_.GetWeakPtr(), config, init_cb));
- return;
- }
-
- DVLOG(2) << __func__;
- DCHECK(config.IsValidConfig());
-
- video_decoder_init_cb_ = init_cb;
- if (!CdmDelegate() ||
- !CdmDelegate()->InitializeVideoDecoder(
- config, base::Bind(&PpapiDecryptor::OnDecoderInitialized,
- weak_ptr_factory_.GetWeakPtr(), kVideo))) {
- base::ResetAndReturn(&video_decoder_init_cb_).Run(false);
- return;
- }
-}
-
-void PpapiDecryptor::DecryptAndDecodeAudio(
- const scoped_refptr<media::DecoderBuffer>& encrypted,
- const AudioDecodeCB& audio_decode_cb) {
- if (!render_task_runner_->BelongsToCurrentThread()) {
- render_task_runner_->PostTask(
- FROM_HERE, base::BindOnce(&PpapiDecryptor::DecryptAndDecodeAudio,
- weak_ptr_factory_.GetWeakPtr(), encrypted,
- audio_decode_cb));
- return;
- }
-
- DVLOG(3) << __func__;
- if (!CdmDelegate() ||
- !CdmDelegate()->DecryptAndDecodeAudio(encrypted, audio_decode_cb)) {
- audio_decode_cb.Run(kError, AudioFrames());
- }
-}
-
-void PpapiDecryptor::DecryptAndDecodeVideo(
- const scoped_refptr<media::DecoderBuffer>& encrypted,
- const VideoDecodeCB& video_decode_cb) {
- if (!render_task_runner_->BelongsToCurrentThread()) {
- render_task_runner_->PostTask(
- FROM_HERE, base::BindOnce(&PpapiDecryptor::DecryptAndDecodeVideo,
- weak_ptr_factory_.GetWeakPtr(), encrypted,
- video_decode_cb));
- return;
- }
-
- DVLOG(3) << __func__;
- if (!CdmDelegate() ||
- !CdmDelegate()->DecryptAndDecodeVideo(encrypted, video_decode_cb)) {
- video_decode_cb.Run(kError, nullptr);
- }
-}
-
-void PpapiDecryptor::ResetDecoder(StreamType stream_type) {
- if (!render_task_runner_->BelongsToCurrentThread()) {
- render_task_runner_->PostTask(
- FROM_HERE, base::BindOnce(&PpapiDecryptor::ResetDecoder,
- weak_ptr_factory_.GetWeakPtr(), stream_type));
- return;
- }
-
- DVLOG(2) << __func__ << " - stream_type: " << stream_type;
- if (CdmDelegate())
- CdmDelegate()->ResetDecoder(stream_type);
-}
-
-void PpapiDecryptor::DeinitializeDecoder(StreamType stream_type) {
- if (!render_task_runner_->BelongsToCurrentThread()) {
- render_task_runner_->PostTask(
- FROM_HERE, base::BindOnce(&PpapiDecryptor::DeinitializeDecoder,
- weak_ptr_factory_.GetWeakPtr(), stream_type));
- return;
- }
-
- DVLOG(2) << __func__ << " - stream_type: " << stream_type;
- if (CdmDelegate())
- CdmDelegate()->DeinitializeDecoder(stream_type);
-}
-
-void PpapiDecryptor::OnDecoderInitialized(StreamType stream_type,
- bool success) {
- DCHECK(render_task_runner_->BelongsToCurrentThread());
- switch (stream_type) {
- case kAudio:
- DCHECK(!audio_decoder_init_cb_.is_null());
- base::ResetAndReturn(&audio_decoder_init_cb_).Run(success);
- break;
- case kVideo:
- DCHECK(!video_decoder_init_cb_.is_null());
- base::ResetAndReturn(&video_decoder_init_cb_).Run(success);
- break;
- default:
- NOTREACHED();
- }
-}
-
-void PpapiDecryptor::OnSessionMessage(const std::string& session_id,
- media::CdmMessageType message_type,
- const std::vector<uint8_t>& message) {
- DCHECK(render_task_runner_->BelongsToCurrentThread());
- session_message_cb_.Run(session_id, message_type, message);
-}
-
-void PpapiDecryptor::OnSessionKeysChange(const std::string& session_id,
- bool has_additional_usable_key,
- media::CdmKeysInfo keys_info) {
- DVLOG(2) << __func__ << ": " << has_additional_usable_key;
- DCHECK(render_task_runner_->BelongsToCurrentThread());
-
- // TODO(jrummell): Handling resume playback should be done in the media
- // player, not in the Decryptors. http://crbug.com/413413.
- if (has_additional_usable_key)
- AttemptToResumePlayback();
-
- session_keys_change_cb_.Run(session_id, has_additional_usable_key,
- std::move(keys_info));
-}
-
-void PpapiDecryptor::OnSessionExpirationUpdate(const std::string& session_id,
- base::Time new_expiry_time) {
- DCHECK(render_task_runner_->BelongsToCurrentThread());
- session_expiration_update_cb_.Run(session_id, new_expiry_time);
-}
-
-void PpapiDecryptor::OnSessionClosed(const std::string& session_id) {
- DCHECK(render_task_runner_->BelongsToCurrentThread());
- session_closed_cb_.Run(session_id);
-}
-
-void PpapiDecryptor::AttemptToResumePlayback() {
- if (!new_audio_key_cb_.is_null())
- new_audio_key_cb_.Run();
-
- if (!new_video_key_cb_.is_null())
- new_video_key_cb_.Run();
-}
-
-void PpapiDecryptor::OnFatalPluginError() {
- DVLOG(1) << __func__;
- DCHECK(render_task_runner_->BelongsToCurrentThread());
- pepper_cdm_wrapper_.reset();
-
- base::AutoLock auto_lock(lock_);
- had_fatal_plugin_error_ = true;
-}
-
-ContentDecryptorDelegate* PpapiDecryptor::CdmDelegate() {
- DCHECK(render_task_runner_->BelongsToCurrentThread());
- return (pepper_cdm_wrapper_) ? pepper_cdm_wrapper_->GetCdmDelegate()
- : nullptr;
-}
-
-} // namespace content
diff --git a/chromium/content/renderer/media/cdm/ppapi_decryptor.h b/chromium/content/renderer/media/cdm/ppapi_decryptor.h
deleted file mode 100644
index 524bad5f1da..00000000000
--- a/chromium/content/renderer/media/cdm/ppapi_decryptor.h
+++ /dev/null
@@ -1,168 +0,0 @@
-// Copyright 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_RENDERER_MEDIA_CDM_PPAPI_DECRYPTOR_H_
-#define CONTENT_RENDERER_MEDIA_CDM_PPAPI_DECRYPTOR_H_
-
-#include <stdint.h>
-
-#include <string>
-#include <vector>
-
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/memory/weak_ptr.h"
-#include "base/synchronization/lock.h"
-#include "content/renderer/media/cdm/pepper_cdm_wrapper.h"
-#include "media/base/cdm_context.h"
-#include "media/base/cdm_factory.h"
-#include "media/base/content_decryption_module.h"
-#include "media/base/decryptor.h"
-#include "media/base/video_decoder_config.h"
-
-namespace base {
-class SingleThreadTaskRunner;
-}
-
-namespace url {
-class Origin;
-}
-
-namespace content {
-class ContentDecryptorDelegate;
-
-// PpapiDecryptor implements media::ContentDecryptionModule and media::Decryptor
-// and forwards all calls to the PluginInstance.
-// This class should always be created & destroyed on the main renderer thread.
-class PpapiDecryptor : public media::ContentDecryptionModule,
- public media::CdmContext,
- public media::Decryptor {
- public:
- static void Create(
- const std::string& key_system,
- const url::Origin& security_origin,
- bool allow_distinctive_identifier,
- bool allow_persistent_state,
- const CreatePepperCdmCB& create_pepper_cdm_cb,
- const media::SessionMessageCB& session_message_cb,
- const media::SessionClosedCB& session_closed_cb,
- const media::SessionKeysChangeCB& session_keys_change_cb,
- const media::SessionExpirationUpdateCB& session_expiration_update_cb,
- const media::CdmCreatedCB& cdm_created_cb);
-
- // media::ContentDecryptionModule implementation.
- void SetServerCertificate(
- const std::vector<uint8_t>& certificate,
- std::unique_ptr<media::SimpleCdmPromise> promise) override;
- void GetStatusForPolicy(
- media::HdcpVersion min_hdcp_version,
- std::unique_ptr<media::KeyStatusCdmPromise> promise) override;
- void CreateSessionAndGenerateRequest(
- media::CdmSessionType session_type,
- media::EmeInitDataType init_data_type,
- const std::vector<uint8_t>& init_data,
- std::unique_ptr<media::NewSessionCdmPromise> promise) override;
- void LoadSession(
- media::CdmSessionType session_type,
- const std::string& session_id,
- std::unique_ptr<media::NewSessionCdmPromise> promise) override;
- void UpdateSession(const std::string& session_id,
- const std::vector<uint8_t>& response,
- std::unique_ptr<media::SimpleCdmPromise> promise) override;
- void CloseSession(const std::string& session_id,
- std::unique_ptr<media::SimpleCdmPromise> promise) override;
- void RemoveSession(const std::string& session_id,
- std::unique_ptr<media::SimpleCdmPromise> promise) override;
- CdmContext* GetCdmContext() override;
-
- // media::CdmContext implementation.
- Decryptor* GetDecryptor() override;
- int GetCdmId() const override;
-
- // media::Decryptor implementation.
- void RegisterNewKeyCB(StreamType stream_type,
- const NewKeyCB& key_added_cb) override;
- void Decrypt(StreamType stream_type,
- const scoped_refptr<media::DecoderBuffer>& encrypted,
- const DecryptCB& decrypt_cb) override;
- void CancelDecrypt(StreamType stream_type) override;
- void InitializeAudioDecoder(const media::AudioDecoderConfig& config,
- const DecoderInitCB& init_cb) override;
- void InitializeVideoDecoder(const media::VideoDecoderConfig& config,
- const DecoderInitCB& init_cb) override;
- void DecryptAndDecodeAudio(
- const scoped_refptr<media::DecoderBuffer>& encrypted,
- const AudioDecodeCB& audio_decode_cb) override;
- void DecryptAndDecodeVideo(
- const scoped_refptr<media::DecoderBuffer>& encrypted,
- const VideoDecodeCB& video_decode_cb) override;
- void ResetDecoder(StreamType stream_type) override;
- void DeinitializeDecoder(StreamType stream_type) override;
-
- private:
- PpapiDecryptor(
- std::unique_ptr<PepperCdmWrapper> pepper_cdm_wrapper,
- const media::SessionMessageCB& session_message_cb,
- const media::SessionClosedCB& session_closed_cb,
- const media::SessionKeysChangeCB& session_keys_change_cb,
- const media::SessionExpirationUpdateCB& session_expiration_update_cb);
-
- ~PpapiDecryptor() override;
-
- void InitializeCdm(const std::string& key_system,
- bool allow_distinctive_identifier,
- bool allow_persistent_state,
- std::unique_ptr<media::SimpleCdmPromise> promise);
-
- void OnDecoderInitialized(StreamType stream_type, bool success);
-
- // Callbacks for |plugin_cdm_delegate_| to fire session events.
- void OnSessionMessage(const std::string& session_id,
- media::CdmMessageType message_type,
- const std::vector<uint8_t>& message);
- void OnSessionKeysChange(const std::string& session_id,
- bool has_additional_usable_key,
- media::CdmKeysInfo keys_info);
- void OnSessionExpirationUpdate(const std::string& session_id,
- base::Time new_expiry_time);
- void OnSessionClosed(const std::string& session_id);
-
- void AttemptToResumePlayback();
-
- // Callback to notify that a fatal error happened in |plugin_cdm_delegate_|.
- // The error is terminal and |plugin_cdm_delegate_| should not be used after
- // this call.
- void OnFatalPluginError();
-
- ContentDecryptorDelegate* CdmDelegate();
-
- // Hold a reference of the Pepper CDM wrapper to make sure the plugin lives
- // as long as needed.
- std::unique_ptr<PepperCdmWrapper> pepper_cdm_wrapper_;
-
- // Callbacks for firing session events.
- media::SessionMessageCB session_message_cb_;
- media::SessionClosedCB session_closed_cb_;
- media::SessionKeysChangeCB session_keys_change_cb_;
- media::SessionExpirationUpdateCB session_expiration_update_cb_;
-
- scoped_refptr<base::SingleThreadTaskRunner> render_task_runner_;
-
- DecoderInitCB audio_decoder_init_cb_;
- DecoderInitCB video_decoder_init_cb_;
- NewKeyCB new_audio_key_cb_;
- NewKeyCB new_video_key_cb_;
-
- base::Lock lock_; // Protects |had_fatal_plugin_error_|.
- bool had_fatal_plugin_error_ = false;
-
- // NOTE: Weak pointers must be invalidated before all other member variables.
- base::WeakPtrFactory<PpapiDecryptor> weak_ptr_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(PpapiDecryptor);
-};
-
-} // namespace content
-
-#endif // CONTENT_RENDERER_MEDIA_CDM_PPAPI_DECRYPTOR_H_
diff --git a/chromium/content/renderer/media/cdm/render_cdm_factory.cc b/chromium/content/renderer/media/cdm/render_cdm_factory.cc
deleted file mode 100644
index 249640c5cf3..00000000000
--- a/chromium/content/renderer/media/cdm/render_cdm_factory.cc
+++ /dev/null
@@ -1,83 +0,0 @@
-// Copyright 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/renderer/media/cdm/render_cdm_factory.h"
-
-#include <memory>
-
-#include "base/bind.h"
-#include "base/location.h"
-#include "base/logging.h"
-#include "base/single_thread_task_runner.h"
-#include "base/threading/thread_task_runner_handle.h"
-#include "media/base/cdm_config.h"
-#include "media/base/cdm_promise.h"
-#include "media/base/content_decryption_module.h"
-#include "media/base/key_systems.h"
-#include "media/cdm/aes_decryptor.h"
-#include "media/media_features.h"
-#include "url/origin.h"
-
-#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
-#include "content/renderer/media/cdm/ppapi_decryptor.h"
-#endif // BUILDFLAG(ENABLE_LIBRARY_CDMS)
-
-namespace content {
-
-#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
-RenderCdmFactory::RenderCdmFactory(
- const CreatePepperCdmCB& create_pepper_cdm_cb)
- : create_pepper_cdm_cb_(create_pepper_cdm_cb) {}
-#else
-RenderCdmFactory::RenderCdmFactory() {}
-#endif // BUILDFLAG(ENABLE_LIBRARY_CDMS)
-
-RenderCdmFactory::~RenderCdmFactory() {
- DCHECK(thread_checker_.CalledOnValidThread());
-}
-
-void RenderCdmFactory::Create(
- const std::string& key_system,
- const url::Origin& security_origin,
- const media::CdmConfig& cdm_config,
- const media::SessionMessageCB& session_message_cb,
- const media::SessionClosedCB& session_closed_cb,
- const media::SessionKeysChangeCB& session_keys_change_cb,
- const media::SessionExpirationUpdateCB& session_expiration_update_cb,
- const media::CdmCreatedCB& cdm_created_cb) {
- DCHECK(thread_checker_.CalledOnValidThread());
-
- if (security_origin.unique()) {
- base::ThreadTaskRunnerHandle::Get()->PostTask(
- FROM_HERE, base::BindOnce(cdm_created_cb, nullptr, "Invalid origin."));
- return;
- }
-
- if (media::CanUseAesDecryptor(key_system)) {
- DCHECK(!cdm_config.allow_distinctive_identifier);
- DCHECK(!cdm_config.allow_persistent_state);
- scoped_refptr<media::ContentDecryptionModule> cdm(new media::AesDecryptor(
- session_message_cb, session_closed_cb, session_keys_change_cb,
- session_expiration_update_cb));
- base::ThreadTaskRunnerHandle::Get()->PostTask(
- FROM_HERE, base::BindOnce(cdm_created_cb, cdm, ""));
- return;
- }
-
-#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
- DCHECK(!cdm_config.use_hw_secure_codecs);
- PpapiDecryptor::Create(
- key_system, security_origin, cdm_config.allow_distinctive_identifier,
- cdm_config.allow_persistent_state, create_pepper_cdm_cb_,
- session_message_cb, session_closed_cb, session_keys_change_cb,
- session_expiration_update_cb, cdm_created_cb);
-#else
- // No possible CDM to create, so fail the request.
- base::ThreadTaskRunnerHandle::Get()->PostTask(
- FROM_HERE,
- base::Bind(cdm_created_cb, nullptr, "Key system not supported."));
-#endif // BUILDFLAG(ENABLE_LIBRARY_CDMS)
-}
-
-} // namespace content
diff --git a/chromium/content/renderer/media/cdm/render_cdm_factory.h b/chromium/content/renderer/media/cdm/render_cdm_factory.h
deleted file mode 100644
index f1223fc0118..00000000000
--- a/chromium/content/renderer/media/cdm/render_cdm_factory.h
+++ /dev/null
@@ -1,57 +0,0 @@
-// Copyright 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_RENDERER_MEDIA_CDM_RENDER_CDM_FACTORY_H_
-#define CONTENT_RENDERER_MEDIA_CDM_RENDER_CDM_FACTORY_H_
-
-#include <memory>
-#include <string>
-
-#include "base/macros.h"
-#include "base/threading/thread_checker.h"
-#include "media/base/cdm_factory.h"
-#include "media/media_features.h"
-
-#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
-#include "content/renderer/media/cdm/pepper_cdm_wrapper.h"
-#endif
-
-namespace content {
-
-// CdmFactory implementation in content/renderer. This class is not thread safe
-// and should only be used on one thread.
-class RenderCdmFactory : public media::CdmFactory {
- public:
-#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
- explicit RenderCdmFactory(const CreatePepperCdmCB& create_pepper_cdm_cb);
-#else
- RenderCdmFactory();
-#endif // BUILDFLAG(ENABLE_LIBRARY_CDMS)
-
- ~RenderCdmFactory() override;
-
- // CdmFactory implementation.
- void Create(
- const std::string& key_system,
- const url::Origin& security_origin,
- const media::CdmConfig& cdm_config,
- const media::SessionMessageCB& session_message_cb,
- const media::SessionClosedCB& session_closed_cb,
- const media::SessionKeysChangeCB& session_keys_change_cb,
- const media::SessionExpirationUpdateCB& session_expiration_update_cb,
- const media::CdmCreatedCB& cdm_created_cb) override;
-
- private:
-#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
- CreatePepperCdmCB create_pepper_cdm_cb_;
-#endif
-
- base::ThreadChecker thread_checker_;
-
- DISALLOW_COPY_AND_ASSIGN(RenderCdmFactory);
-};
-
-} // namespace content
-
-#endif // CONTENT_RENDERER_MEDIA_CDM_RENDER_CDM_FACTORY_H_
diff --git a/chromium/content/renderer/media/gpu/gpu_video_accelerator_factories_impl.cc b/chromium/content/renderer/media/gpu/gpu_video_accelerator_factories_impl.cc
index 5c688e198ae..11c82f8538e 100644
--- a/chromium/content/renderer/media/gpu/gpu_video_accelerator_factories_impl.cc
+++ b/chromium/content/renderer/media/gpu/gpu_video_accelerator_factories_impl.cc
@@ -78,8 +78,8 @@ GpuVideoAcceleratorFactoriesImpl::GpuVideoAcceleratorFactoriesImpl(
: main_thread_task_runner_(main_thread_task_runner),
task_runner_(task_runner),
gpu_channel_host_(std::move(gpu_channel_host)),
- context_provider_refptr_(context_provider),
- context_provider_(context_provider.get()),
+ context_provider_(context_provider),
+ context_provider_lost_(false),
enable_gpu_memory_buffer_video_frames_(
enable_gpu_memory_buffer_video_frames),
video_accelerator_enabled_(enable_video_accelerator),
@@ -89,6 +89,11 @@ GpuVideoAcceleratorFactoriesImpl::GpuVideoAcceleratorFactoriesImpl(
DCHECK(main_thread_task_runner_);
DCHECK(gpu_channel_host_);
+ task_runner->PostTask(
+ FROM_HERE,
+ base::BindOnce(&GpuVideoAcceleratorFactoriesImpl::BindContextToTaskRunner,
+ base::Unretained(this)));
+
task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&GpuVideoAcceleratorFactoriesImpl::
@@ -98,24 +103,21 @@ GpuVideoAcceleratorFactoriesImpl::GpuVideoAcceleratorFactoriesImpl(
GpuVideoAcceleratorFactoriesImpl::~GpuVideoAcceleratorFactoriesImpl() {}
+void GpuVideoAcceleratorFactoriesImpl::BindContextToTaskRunner() {
+ DCHECK(task_runner_->BelongsToCurrentThread());
+ DCHECK(context_provider_);
+ if (context_provider_->BindToCurrentThread() !=
+ gpu::ContextResult::kSuccess) {
+ ReleaseContextProvider();
+ }
+}
+
bool GpuVideoAcceleratorFactoriesImpl::CheckContextLost() {
DCHECK(task_runner_->BelongsToCurrentThread());
if (context_provider_) {
- bool release_context_provider = false;
- {
- viz::ContextProvider::ScopedContextLock lock(context_provider_);
- if (lock.ContextGL()->GetGraphicsResetStatusKHR() != GL_NO_ERROR) {
- context_provider_ = nullptr;
- release_context_provider = true;
- }
- }
- if (release_context_provider) {
- // Drop the reference on the main thread.
- main_thread_task_runner_->PostTask(
- FROM_HERE,
- base::BindOnce(
- &GpuVideoAcceleratorFactoriesImpl::ReleaseContextProvider,
- base::Unretained(this)));
+ if (context_provider_->ContextGL()->GetGraphicsResetStatusKHR() !=
+ GL_NO_ERROR) {
+ ReleaseContextProvider();
}
}
return !context_provider_;
@@ -190,8 +192,7 @@ bool GpuVideoAcceleratorFactoriesImpl::CreateTextures(
if (CheckContextLost())
return false;
- viz::ContextProvider::ScopedContextLock lock(context_provider_);
- gpu::gles2::GLES2Interface* gles2 = lock.ContextGL();
+ gpu::gles2::GLES2Interface* gles2 = context_provider_->ContextGL();
texture_ids->resize(count);
texture_mailboxes->resize(count);
gles2->GenTextures(count, &texture_ids->at(0));
@@ -226,17 +227,14 @@ void GpuVideoAcceleratorFactoriesImpl::DeleteTexture(uint32_t texture_id) {
if (CheckContextLost())
return;
- viz::ContextProvider::ScopedContextLock lock(context_provider_);
- gpu::gles2::GLES2Interface* gles2 = lock.ContextGL();
+ gpu::gles2::GLES2Interface* gles2 = context_provider_->ContextGL();
gles2->DeleteTextures(1, &texture_id);
DCHECK_EQ(gles2->GetError(), static_cast<GLenum>(GL_NO_ERROR));
}
gpu::SyncToken GpuVideoAcceleratorFactoriesImpl::CreateSyncToken() {
- viz::ContextProvider::ScopedContextLock lock(context_provider_);
- gpu::gles2::GLES2Interface* gl = lock.ContextGL();
gpu::SyncToken sync_token;
- gl->GenSyncTokenCHROMIUM(sync_token.GetData());
+ context_provider_->ContextGL()->GenSyncTokenCHROMIUM(sync_token.GetData());
return sync_token;
}
@@ -246,8 +244,7 @@ void GpuVideoAcceleratorFactoriesImpl::WaitSyncToken(
if (CheckContextLost())
return;
- viz::ContextProvider::ScopedContextLock lock(context_provider_);
- gpu::gles2::GLES2Interface* gles2 = lock.ContextGL();
+ gpu::gles2::GLES2Interface* gles2 = context_provider_->ContextGL();
gles2->WaitSyncTokenCHROMIUM(sync_token.GetConstData());
// Callers expect the WaitSyncToken to affect the next IPCs. Make sure to
@@ -260,9 +257,7 @@ void GpuVideoAcceleratorFactoriesImpl::ShallowFlushCHROMIUM() {
if (CheckContextLost())
return;
- viz::ContextProvider::ScopedContextLock lock(context_provider_);
- gpu::gles2::GLES2Interface* gles2 = lock.ContextGL();
- gles2->ShallowFlushCHROMIUM();
+ context_provider_->ContextGL()->ShallowFlushCHROMIUM();
}
std::unique_ptr<gfx::GpuMemoryBuffer>
@@ -291,7 +286,6 @@ GpuVideoAcceleratorFactoriesImpl::VideoFrameOutputFormat(size_t bit_depth) {
DCHECK(task_runner_->BelongsToCurrentThread());
if (CheckContextLost())
return media::GpuVideoAcceleratorFactories::OutputFormat::UNDEFINED;
- viz::ContextProvider::ScopedContextLock lock(context_provider_);
auto capabilities = context_provider_->ContextCapabilities();
if (bit_depth > 8) {
// If high bit depth rendering is enabled, bail here, otherwise try and use
@@ -329,24 +323,8 @@ GpuVideoAcceleratorFactoriesImpl::VideoFrameOutputFormat(size_t bit_depth) {
return media::GpuVideoAcceleratorFactories::OutputFormat::UNDEFINED;
}
-namespace {
-class ScopedGLContextLockImpl
- : public media::GpuVideoAcceleratorFactories::ScopedGLContextLock {
- public:
- ScopedGLContextLockImpl(viz::ContextProvider* context_provider)
- : lock_(context_provider) {}
- gpu::gles2::GLES2Interface* ContextGL() override { return lock_.ContextGL(); }
-
- private:
- viz::ContextProvider::ScopedContextLock lock_;
-};
-} // namespace
-
-std::unique_ptr<media::GpuVideoAcceleratorFactories::ScopedGLContextLock>
-GpuVideoAcceleratorFactoriesImpl::GetGLContextLock() {
- if (CheckContextLost())
- return nullptr;
- return std::make_unique<ScopedGLContextLockImpl>(context_provider_);
+gpu::gles2::GLES2Interface* GpuVideoAcceleratorFactoriesImpl::ContextGL() {
+ return CheckContextLost() ? nullptr : context_provider_->ContextGL();
}
std::unique_ptr<base::SharedMemory>
@@ -378,7 +356,7 @@ GpuVideoAcceleratorFactoriesImpl::GetVideoEncodeAcceleratorSupportedProfiles() {
viz::ContextProvider*
GpuVideoAcceleratorFactoriesImpl::GetMediaContextProvider() {
- return CheckContextLost() ? nullptr : context_provider_;
+ return CheckContextLost() ? nullptr : context_provider_.get();
}
void GpuVideoAcceleratorFactoriesImpl::SetRenderingColorSpace(
@@ -386,17 +364,9 @@ void GpuVideoAcceleratorFactoriesImpl::SetRenderingColorSpace(
rendering_color_space_ = color_space;
}
-void GpuVideoAcceleratorFactoriesImpl::ReleaseContextProvider() {
+bool GpuVideoAcceleratorFactoriesImpl::CheckContextProviderLost() {
DCHECK(main_thread_task_runner_->BelongsToCurrentThread());
- RecordContextProviderPhaseUmaEnum(
- ContextProviderPhase::CONTEXT_PROVIDER_RELEASED);
- context_provider_refptr_ = nullptr;
-}
-
-scoped_refptr<ui::ContextProviderCommandBuffer>
-GpuVideoAcceleratorFactoriesImpl::ContextProviderMainThread() {
- DCHECK(main_thread_task_runner_->BelongsToCurrentThread());
- return context_provider_refptr_;
+ return context_provider_lost_;
}
void GpuVideoAcceleratorFactoriesImpl::
@@ -405,7 +375,25 @@ void GpuVideoAcceleratorFactoriesImpl::
unbound_vea_provider) {
DCHECK(task_runner_->BelongsToCurrentThread());
DCHECK(!vea_provider_.is_bound());
- vea_provider_.Bind(std::move(unbound_vea_provider));
+ vea_provider_.Bind(std::move(unbound_vea_provider), task_runner_);
+}
+
+void GpuVideoAcceleratorFactoriesImpl::ReleaseContextProvider() {
+ DCHECK(task_runner_->BelongsToCurrentThread());
+
+ main_thread_task_runner_->PostTask(
+ FROM_HERE,
+ base::BindOnce(&GpuVideoAcceleratorFactoriesImpl::SetContextProviderLost,
+ base::Unretained(this)));
+
+ context_provider_ = nullptr;
+ RecordContextProviderPhaseUmaEnum(
+ ContextProviderPhase::CONTEXT_PROVIDER_RELEASED);
+}
+
+void GpuVideoAcceleratorFactoriesImpl::SetContextProviderLost() {
+ DCHECK(main_thread_task_runner_->BelongsToCurrentThread());
+ context_provider_lost_ = true;
}
} // namespace content
diff --git a/chromium/content/renderer/media/gpu/gpu_video_accelerator_factories_impl.h b/chromium/content/renderer/media/gpu/gpu_video_accelerator_factories_impl.h
index c3d7209de2d..066ee94cf41 100644
--- a/chromium/content/renderer/media/gpu/gpu_video_accelerator_factories_impl.h
+++ b/chromium/content/renderer/media/gpu/gpu_video_accelerator_factories_impl.h
@@ -46,6 +46,8 @@ namespace content {
// The GpuVideoAcceleratorFactoriesImpl can be constructed on any thread,
// but subsequent calls to all public methods of the class must be called from
// the |task_runner_|, as provided during construction.
+// |context_provider| should not support locking and will be bound to
+// |task_runner_| where all the operations on the context should also happen.
class CONTENT_EXPORT GpuVideoAcceleratorFactoriesImpl
: public media::GpuVideoAcceleratorFactories {
public:
@@ -89,8 +91,9 @@ class CONTENT_EXPORT GpuVideoAcceleratorFactoriesImpl
bool ShouldUseGpuMemoryBuffersForVideoFrames() const override;
unsigned ImageTextureTarget(gfx::BufferFormat format) override;
OutputFormat VideoFrameOutputFormat(size_t bit_depth) override;
- std::unique_ptr<media::GpuVideoAcceleratorFactories::ScopedGLContextLock>
- GetGLContextLock() override;
+
+ gpu::gles2::GLES2Interface* ContextGL() override;
+ void BindContextToTaskRunner();
bool CheckContextLost();
std::unique_ptr<base::SharedMemory> CreateSharedMemory(size_t size) override;
scoped_refptr<base::SingleThreadTaskRunner> GetTaskRunner() override;
@@ -104,8 +107,7 @@ class CONTENT_EXPORT GpuVideoAcceleratorFactoriesImpl
void SetRenderingColorSpace(const gfx::ColorSpace& color_space) override;
- void ReleaseContextProvider();
- scoped_refptr<ui::ContextProviderCommandBuffer> ContextProviderMainThread();
+ bool CheckContextProviderLost();
~GpuVideoAcceleratorFactoriesImpl() override;
@@ -123,16 +125,19 @@ class CONTENT_EXPORT GpuVideoAcceleratorFactoriesImpl
void BindVideoEncodeAcceleratorProviderOnTaskRunner(
media::mojom::VideoEncodeAcceleratorProviderPtrInfo unbound_vea_provider);
+ void ReleaseContextProvider();
+ void SetContextProviderLost();
+
const scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner_;
const scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
const scoped_refptr<gpu::GpuChannelHost> gpu_channel_host_;
- // Shared pointer to a shared context provider that should be accessed
- // and set only on the main thread.
- scoped_refptr<ui::ContextProviderCommandBuffer> context_provider_refptr_;
-
- // Raw pointer to a context provider accessed from the media thread.
- ui::ContextProviderCommandBuffer* context_provider_;
+ // Shared pointer to a shared context provider. It is initially set on main
+ // thread, but all subsequent access and destruction should happen only on the
+ // media thread.
+ scoped_refptr<ui::ContextProviderCommandBuffer> context_provider_;
+ // Signals if |context_provider_| is alive on the media thread.
+ bool context_provider_lost_;
base::UnguessableToken channel_token_;
diff --git a/chromium/content/renderer/media/media_factory.cc b/chromium/content/renderer/media/media_factory.cc
index 47a8f8c7454..59043b29fe8 100644
--- a/chromium/content/renderer/media/media_factory.cc
+++ b/chromium/content/renderer/media/media_factory.cc
@@ -30,17 +30,17 @@
#include "media/blink/webencryptedmediaclient_impl.h"
#include "media/blink/webmediaplayer_impl.h"
#include "media/filters/context_3d.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "media/renderers/default_renderer_factory.h"
#include "media/video/gpu_video_accelerator_factories.h"
#include "mojo/public/cpp/bindings/associated_interface_ptr.h"
#include "services/service_manager/public/cpp/connect.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "services/ui/public/cpp/gpu/context_provider_command_buffer.h"
-#include "third_party/WebKit/public/platform/WebSurfaceLayerBridge.h"
-#include "third_party/WebKit/public/platform/WebVideoFrameSubmitter.h"
-#include "third_party/WebKit/public/web/WebKit.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "third_party/blink/public/platform/web_surface_layer_bridge.h"
+#include "third_party/blink/public/platform/web_video_frame_submitter.h"
+#include "third_party/blink/public/web/blink.h"
+#include "third_party/blink/public/web/web_local_frame.h"
#include "url/origin.h"
#if defined(OS_ANDROID)
@@ -71,16 +71,7 @@
#if BUILDFLAG(ENABLE_MEDIA_REMOTING)
#include "media/remoting/courier_renderer_factory.h" // nogncheck
-#include "media/remoting/remoting_cdm_controller.h" // nogncheck
-#include "media/remoting/remoting_cdm_factory.h" // nogncheck
#include "media/remoting/renderer_controller.h" // nogncheck
-#include "media/remoting/shared_session.h" // nogncheck
-#include "media/remoting/sink_availability_observer.h" // nogncheck
-#endif
-
-#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
-#include "content/renderer/media/cdm/pepper_cdm_wrapper_impl.h"
-#include "content/renderer/media/cdm/render_cdm_factory.h"
#endif
namespace {
@@ -146,19 +137,6 @@ void MediaFactory::SetupMojo() {
remote_interfaces_ = render_frame_->GetRemoteInterfaces();
DCHECK(remote_interfaces_);
-
-#if BUILDFLAG(ENABLE_MEDIA_REMOTING)
- // Create the SinkAvailabilityObserver to monitor the remoting sink
- // availablity.
- media::mojom::RemotingSourcePtr remoting_source;
- auto remoting_source_request = mojo::MakeRequest(&remoting_source);
- media::mojom::RemoterPtr remoter;
- GetRemoterFactory()->Create(std::move(remoting_source),
- mojo::MakeRequest(&remoter));
- remoting_sink_observer_ =
- std::make_unique<media::remoting::SinkAvailabilityObserver>(
- std::move(remoting_source_request), std::move(remoter));
-#endif // BUILDFLAG(ENABLE_MEDIA_REMOTING)
}
#if defined(OS_ANDROID)
@@ -328,7 +306,9 @@ blink::WebMediaPlayer* MediaFactory::CreateMediaPlayer(
use_surface_layer_for_video,
base::BindRepeating(
&RenderFrameImpl::OnPictureInPictureSurfaceIdUpdated,
- base::Unretained(render_frame_))));
+ base::Unretained(render_frame_)),
+ base::BindRepeating(&RenderFrameImpl::OnExitPictureInPicture,
+ base::Unretained(render_frame_))));
std::unique_ptr<media::VideoFrameCompositor> vfc =
std::make_unique<media::VideoFrameCompositor>(
@@ -372,11 +352,11 @@ MediaFactory::CreateRendererFactorySelector(
#if defined(OS_ANDROID)
DCHECK(remote_interfaces_);
- // The only MojoRendererService that is registered at the RenderFrameHost
- // level uses the MediaPlayerRenderer as its underlying media::Renderer.
auto mojo_media_player_renderer_factory =
std::make_unique<media::MojoRendererFactory>(
- media::MojoRendererFactory::GetGpuFactoriesCB(), remote_interfaces_);
+ media::mojom::HostedRendererType::kMediaPlayer,
+ media::MojoRendererFactory::GetGpuFactoriesCB(),
+ GetMediaInterfaceFactory());
// Always give |factory_selector| a MediaPlayerRendererClient factory. WMPI
// might fallback to it if the final redirected URL is an HLS url.
@@ -406,6 +386,7 @@ MediaFactory::CreateRendererFactorySelector(
factory_selector->AddFactory(
media::RendererFactorySelector::FactoryType::MOJO,
std::make_unique<media::MojoRendererFactory>(
+ media::mojom::HostedRendererType::kDefault,
base::Bind(&RenderThreadImpl::GetGpuFactories,
base::Unretained(render_thread)),
GetMediaInterfaceFactory()));
@@ -434,9 +415,8 @@ MediaFactory::CreateRendererFactorySelector(
GetRemoterFactory()->Create(std::move(remoting_source),
mojo::MakeRequest(&remoter));
using RemotingController = media::remoting::RendererController;
- std::unique_ptr<RemotingController> remoting_controller(
- new RemotingController(new media::remoting::SharedSession(
- std::move(remoting_source_request), std::move(remoter))));
+ auto remoting_controller = std::make_unique<RemotingController>(
+ std::move(remoting_source_request), std::move(remoter));
*out_media_observer = remoting_controller->GetWeakPtr();
auto courier_factory =
@@ -538,31 +518,12 @@ media::mojom::RemoterFactory* MediaFactory::GetRemoterFactory() {
#endif
media::CdmFactory* MediaFactory::GetCdmFactory() {
- blink::WebLocalFrame* web_frame = render_frame_->GetWebFrame();
- DCHECK(web_frame);
-
if (cdm_factory_)
return cdm_factory_.get();
-#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
- static_assert(
- BUILDFLAG(ENABLE_MOJO_CDM),
- "Mojo CDM should always be enabled when library CDM is enabled");
- if (base::FeatureList::IsEnabled(media::kMojoCdm)) {
- cdm_factory_.reset(new media::MojoCdmFactory(GetMediaInterfaceFactory()));
- } else {
- cdm_factory_.reset(new RenderCdmFactory(
- base::Bind(&PepperCdmWrapperImpl::Create, web_frame)));
- }
-#elif BUILDFLAG(ENABLE_MOJO_CDM)
+#if BUILDFLAG(ENABLE_MOJO_CDM)
cdm_factory_.reset(new media::MojoCdmFactory(GetMediaInterfaceFactory()));
-#endif // BUILDFLAG(ENABLE_LIBRARY_CDMS)
-
-#if BUILDFLAG(ENABLE_MEDIA_REMOTING)
- cdm_factory_.reset(new media::remoting::RemotingCdmFactory(
- std::move(cdm_factory_), GetRemoterFactory(),
- std::move(remoting_sink_observer_)));
-#endif // BUILDFLAG(ENABLE_MEDIA_REMOTING)
+#endif // BUILDFLAG(ENABLE_MOJO_CDM)
return cdm_factory_.get();
}
diff --git a/chromium/content/renderer/media/media_factory.h b/chromium/content/renderer/media/media_factory.h
index f63ba994be0..406b172666c 100644
--- a/chromium/content/renderer/media/media_factory.h
+++ b/chromium/content/renderer/media/media_factory.h
@@ -12,13 +12,13 @@
#include "media/base/renderer_factory_selector.h"
#include "media/base/routing_token_callback.h"
#include "media/blink/url_index.h"
-#include "media/media_features.h"
-#include "media/mojo/features.h"
+#include "media/media_buildflags.h"
+#include "media/mojo/buildflags.h"
#include "media/mojo/interfaces/remoting.mojom.h"
-#include "third_party/WebKit/public/platform/WebMediaPlayerSource.h"
-#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
-#include "third_party/WebKit/public/platform/WebSetSinkIdCallbacks.h"
-#include "third_party/WebKit/public/platform/WebString.h"
+#include "third_party/blink/public/platform/web_media_player_source.h"
+#include "third_party/blink/public/platform/web_security_origin.h"
+#include "third_party/blink/public/platform/web_set_sink_id_callbacks.h"
+#include "third_party/blink/public/platform/web_string.h"
#if BUILDFLAG(ENABLE_MOJO_MEDIA)
#include "media/mojo/interfaces/interface_factory.mojom.h" // nogncheck
@@ -49,9 +49,6 @@ class WebEncryptedMediaClientImpl;
#if defined(OS_ANDROID)
class RendererMediaPlayerManager;
#endif
-namespace remoting {
-class SinkAvailabilityObserver;
-}
}
namespace service_manager {
@@ -197,14 +194,6 @@ class MediaFactory {
// Lazy-bound pointer to the RemoterFactory service in the browser
// process. Always use the GetRemoterFactory() accessor instead of this.
media::mojom::RemoterFactoryPtr remoter_factory_;
-
- // An observer for the remoting sink availability that is used by
- // media::RemotingCdmFactory to initialize media::RemotingSourceImpl. Created
- // in the constructor of RenderFrameImpl to make sure
- // media::RemotingSourceImpl be intialized with correct availability info.
- // Own by media::RemotingCdmFactory after it is created.
- std::unique_ptr<media::remoting::SinkAvailabilityObserver>
- remoting_sink_observer_;
#endif
};
diff --git a/chromium/content/renderer/media/media_interface_factory.cc b/chromium/content/renderer/media/media_interface_factory.cc
index f2ea09f981a..77c72875eec 100644
--- a/chromium/content/renderer/media/media_interface_factory.cc
+++ b/chromium/content/renderer/media/media_interface_factory.cc
@@ -52,18 +52,19 @@ void MediaInterfaceFactory::CreateVideoDecoder(
}
void MediaInterfaceFactory::CreateRenderer(
- const std::string& audio_device_id,
+ media::mojom::HostedRendererType type,
+ const std::string& type_specific_id,
media::mojom::RendererRequest request) {
if (!task_runner_->BelongsToCurrentThread()) {
task_runner_->PostTask(
FROM_HERE,
- base::BindOnce(&MediaInterfaceFactory::CreateRenderer, weak_this_,
- audio_device_id, std::move(request)));
+ base::BindOnce(&MediaInterfaceFactory::CreateRenderer, weak_this_, type,
+ type_specific_id, std::move(request)));
return;
}
DVLOG(1) << __func__;
- GetMediaInterfaceFactory()->CreateRenderer(audio_device_id,
+ GetMediaInterfaceFactory()->CreateRenderer(type, type_specific_id,
std::move(request));
}
diff --git a/chromium/content/renderer/media/media_interface_factory.h b/chromium/content/renderer/media/media_interface_factory.h
index 02cd30e6e28..ee4a33d2953 100644
--- a/chromium/content/renderer/media/media_interface_factory.h
+++ b/chromium/content/renderer/media/media_interface_factory.h
@@ -32,7 +32,8 @@ class CONTENT_EXPORT MediaInterfaceFactory
// media::mojom::InterfaceFactory implementation.
void CreateAudioDecoder(media::mojom::AudioDecoderRequest request) final;
void CreateVideoDecoder(media::mojom::VideoDecoderRequest request) final;
- void CreateRenderer(const std::string& audio_device_id,
+ void CreateRenderer(media::mojom::HostedRendererType type,
+ const std::string& type_specific_id,
media::mojom::RendererRequest request) final;
void CreateCdm(const std::string& key_system,
media::mojom::ContentDecryptionModuleRequest request) final;
diff --git a/chromium/content/renderer/media/media_permission_dispatcher.cc b/chromium/content/renderer/media/media_permission_dispatcher.cc
index 64edff8c1c3..b22e0987284 100644
--- a/chromium/content/renderer/media/media_permission_dispatcher.cc
+++ b/chromium/content/renderer/media/media_permission_dispatcher.cc
@@ -9,7 +9,7 @@
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "media/base/bind_to_current_loop.h"
-#include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
+#include "third_party/blink/public/web/web_user_gesture_indicator.h"
#include "url/gurl.h"
namespace {
@@ -151,7 +151,8 @@ void MediaPermissionDispatcher::OnPermissionStatus(
PermissionStatusCB permission_status_cb = iter->second;
requests_.erase(iter);
- permission_status_cb.Run(status == blink::mojom::PermissionStatus::GRANTED);
+ std::move(permission_status_cb)
+ .Run(status == blink::mojom::PermissionStatus::GRANTED);
}
void MediaPermissionDispatcher::OnConnectionError() {
diff --git a/chromium/content/renderer/media/media_permission_dispatcher.h b/chromium/content/renderer/media/media_permission_dispatcher.h
index 64e7867c2a2..5660721131c 100644
--- a/chromium/content/renderer/media/media_permission_dispatcher.h
+++ b/chromium/content/renderer/media/media_permission_dispatcher.h
@@ -15,7 +15,7 @@
#include "base/memory/weak_ptr.h"
#include "content/common/content_export.h"
#include "media/base/media_permission.h"
-#include "third_party/WebKit/public/platform/modules/permissions/permission.mojom.h"
+#include "third_party/blink/public/platform/modules/permissions/permission.mojom.h"
namespace base {
class SingleThreadTaskRunner;
diff --git a/chromium/content/renderer/media/midi/midi_message_filter.h b/chromium/content/renderer/media/midi/midi_message_filter.h
index 23101df446f..1e830088c11 100644
--- a/chromium/content/renderer/media/midi/midi_message_filter.h
+++ b/chromium/content/renderer/media/midi/midi_message_filter.h
@@ -17,7 +17,7 @@
#include "ipc/message_filter.h"
#include "media/midi/midi_port_info.h"
#include "media/midi/midi_service.mojom.h"
-#include "third_party/WebKit/public/platform/modules/webmidi/WebMIDIAccessorClient.h"
+#include "third_party/blink/public/platform/modules/webmidi/web_midi_accessor_client.h"
namespace base {
class SingleThreadTaskRunner;
diff --git a/chromium/content/renderer/media/midi/renderer_webmidiaccessor_impl.h b/chromium/content/renderer/media/midi/renderer_webmidiaccessor_impl.h
index 622ef44e9c7..aeeb38d9afc 100644
--- a/chromium/content/renderer/media/midi/renderer_webmidiaccessor_impl.h
+++ b/chromium/content/renderer/media/midi/renderer_webmidiaccessor_impl.h
@@ -9,8 +9,8 @@
#include "base/compiler_specific.h"
#include "base/macros.h"
-#include "third_party/WebKit/public/platform/modules/webmidi/WebMIDIAccessor.h"
-#include "third_party/WebKit/public/platform/modules/webmidi/WebMIDIAccessorClient.h"
+#include "third_party/blink/public/platform/modules/webmidi/web_midi_accessor.h"
+#include "third_party/blink/public/platform/modules/webmidi/web_midi_accessor_client.h"
namespace content {
diff --git a/chromium/content/renderer/media/mojo_audio_input_ipc.cc b/chromium/content/renderer/media/mojo_audio_input_ipc.cc
index 108fd7c76e5..a346a8442e8 100644
--- a/chromium/content/renderer/media/mojo_audio_input_ipc.cc
+++ b/chromium/content/renderer/media/mojo_audio_input_ipc.cc
@@ -7,6 +7,7 @@
#include <utility>
#include "base/bind_helpers.h"
+#include "base/metrics/histogram_macros.h"
#include "media/audio/audio_device_description.h"
#include "mojo/public/cpp/system/platform_handle.h"
@@ -39,6 +40,7 @@ void MojoAudioInputIPC::CreateStream(media::AudioInputIPCDelegate* delegate,
factory_client_binding_.set_connection_error_handler(base::BindOnce(
&media::AudioInputIPCDelegate::OnError, base::Unretained(delegate_)));
+ stream_creation_start_time_ = base::TimeTicks::Now();
stream_creator_.Run(std::move(client), session_id, params,
automatic_gain_control, total_segments);
}
@@ -75,6 +77,9 @@ void MojoAudioInputIPC::StreamCreated(
DCHECK(!stream_);
DCHECK(!stream_client_binding_.is_bound());
+ UMA_HISTOGRAM_TIMES("Media.Audio.Render.InputDeviceStreamCreationTime",
+ base::TimeTicks::Now() - stream_creation_start_time_);
+
stream_ = std::move(stream);
stream_client_binding_.Bind(std::move(stream_client_request));
diff --git a/chromium/content/renderer/media/mojo_audio_input_ipc.h b/chromium/content/renderer/media/mojo_audio_input_ipc.h
index 329846b6213..9b1533be68c 100644
--- a/chromium/content/renderer/media/mojo_audio_input_ipc.h
+++ b/chromium/content/renderer/media/mojo_audio_input_ipc.h
@@ -11,6 +11,7 @@
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/sequence_checker.h"
+#include "base/time/time.h"
#include "content/common/content_export.h"
#include "content/common/media/renderer_audio_input_stream_factory.mojom.h"
#include "media/audio/audio_input_ipc.h"
@@ -68,6 +69,8 @@ class CONTENT_EXPORT MojoAudioInputIPC
mojo::Binding<RendererAudioInputStreamFactoryClient> factory_client_binding_;
media::AudioInputIPCDelegate* delegate_ = nullptr;
+ base::TimeTicks stream_creation_start_time_;
+
base::WeakPtrFactory<MojoAudioInputIPC> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(MojoAudioInputIPC);
diff --git a/chromium/content/renderer/media/mojo_audio_output_ipc.cc b/chromium/content/renderer/media/mojo_audio_output_ipc.cc
index d6a0d6d936c..5a4c8671499 100644
--- a/chromium/content/renderer/media/mojo_audio_output_ipc.cc
+++ b/chromium/content/renderer/media/mojo_audio_output_ipc.cc
@@ -6,7 +6,7 @@
#include <utility>
-#include "base/threading/sequenced_task_runner_handle.h"
+#include "base/metrics/histogram_macros.h"
#include "media/audio/audio_device_description.h"
#include "mojo/public/cpp/bindings/callback_helpers.h"
#include "mojo/public/cpp/system/platform_handle.h"
@@ -21,12 +21,13 @@ void TrivialAuthorizedCallback(media::OutputDeviceStatus,
} // namespace
-MojoAudioOutputIPC::MojoAudioOutputIPC(FactoryAccessorCB factory_accessor)
+MojoAudioOutputIPC::MojoAudioOutputIPC(
+ FactoryAccessorCB factory_accessor,
+ scoped_refptr<base::SingleThreadTaskRunner> io_task_runner)
: factory_accessor_(std::move(factory_accessor)),
binding_(this),
- weak_factory_(this) {
- DETACH_FROM_THREAD(thread_checker_);
-}
+ io_task_runner_(std::move(io_task_runner)),
+ weak_factory_(this) {}
MojoAudioOutputIPC::~MojoAudioOutputIPC() {
DCHECK(!AuthorizationRequested() && !StreamCreationRequested())
@@ -41,7 +42,7 @@ void MojoAudioOutputIPC::RequestDeviceAuthorization(
int session_id,
const std::string& device_id,
const url::Origin& security_origin) {
- DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
+ DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
DCHECK(delegate);
DCHECK(!delegate_);
DCHECK(!AuthorizationRequested());
@@ -63,7 +64,7 @@ void MojoAudioOutputIPC::RequestDeviceAuthorization(
void MojoAudioOutputIPC::CreateStream(media::AudioOutputIPCDelegate* delegate,
const media::AudioParameters& params) {
- DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
+ DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
DCHECK(delegate);
DCHECK(!StreamCreationRequested());
if (!AuthorizationRequested()) {
@@ -80,6 +81,7 @@ void MojoAudioOutputIPC::CreateStream(media::AudioOutputIPCDelegate* delegate,
DCHECK_EQ(delegate_, delegate);
// Since the creation callback won't fire if the provider binding is gone
// and |this| owns |stream_provider_|, unretained is safe.
+ stream_creation_start_time_ = base::TimeTicks::Now();
media::mojom::AudioOutputStreamClientPtr client_ptr;
binding_.Bind(mojo::MakeRequest(&client_ptr));
stream_provider_->Acquire(mojo::MakeRequest(&stream_), std::move(client_ptr),
@@ -94,19 +96,19 @@ void MojoAudioOutputIPC::CreateStream(media::AudioOutputIPCDelegate* delegate,
}
void MojoAudioOutputIPC::PlayStream() {
- DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
+ DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
DCHECK(stream_.is_bound());
stream_->Play();
}
void MojoAudioOutputIPC::PauseStream() {
- DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
+ DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
DCHECK(stream_.is_bound());
stream_->Pause();
}
void MojoAudioOutputIPC::CloseStream() {
- DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
+ DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
stream_provider_.reset();
stream_.reset();
binding_.Close();
@@ -117,13 +119,13 @@ void MojoAudioOutputIPC::CloseStream() {
}
void MojoAudioOutputIPC::SetVolume(double volume) {
- DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
+ DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
DCHECK(stream_.is_bound());
stream_->SetVolume(volume);
}
void MojoAudioOutputIPC::OnError() {
- DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
+ DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
DCHECK(delegate_);
delegate_->OnError();
}
@@ -138,7 +140,7 @@ bool MojoAudioOutputIPC::StreamCreationRequested() {
media::mojom::AudioOutputStreamProviderRequest
MojoAudioOutputIPC::MakeProviderRequest() {
- DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
+ DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
DCHECK(!AuthorizationRequested());
media::mojom::AudioOutputStreamProviderRequest request =
mojo::MakeRequest(&stream_provider_);
@@ -161,7 +163,7 @@ void MojoAudioOutputIPC::DoRequestDeviceAuthorization(
int session_id,
const std::string& device_id,
AuthorizationCB callback) {
- DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
+ DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
auto* factory = factory_accessor_.Run();
if (!factory) {
LOG(ERROR) << "MojoAudioOutputIPC failed to acquire factory";
@@ -172,7 +174,7 @@ void MojoAudioOutputIPC::DoRequestDeviceAuthorization(
// when the factory is destroyed before reply, i.e. calling
// OnDeviceAuthorized with ERROR_INTERNAL in the normal case.
// The AudioOutputIPCDelegate will call CloseStream as necessary.
- base::SequencedTaskRunnerHandle::Get()->PostTask(
+ io_task_runner_->PostTask(
FROM_HERE,
base::BindOnce([](AuthorizationCB cb) {}, std::move(callback)));
return;
@@ -188,16 +190,19 @@ void MojoAudioOutputIPC::ReceivedDeviceAuthorization(
media::OutputDeviceStatus status,
const media::AudioParameters& params,
const std::string& device_id) const {
- DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
+ DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
DCHECK(delegate_);
delegate_->OnDeviceAuthorized(status, params, device_id);
}
void MojoAudioOutputIPC::StreamCreated(
media::mojom::AudioDataPipePtr data_pipe) {
- DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
+ DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
DCHECK(delegate_);
+ UMA_HISTOGRAM_TIMES("Media.Audio.Render.OutputDeviceStreamCreationTime",
+ base::TimeTicks::Now() - stream_creation_start_time_);
+
base::PlatformFile socket_handle;
auto result =
mojo::UnwrapPlatformFile(std::move(data_pipe->socket), &socket_handle);
diff --git a/chromium/content/renderer/media/mojo_audio_output_ipc.h b/chromium/content/renderer/media/mojo_audio_output_ipc.h
index 7d15855b576..a38363bc0aa 100644
--- a/chromium/content/renderer/media/mojo_audio_output_ipc.h
+++ b/chromium/content/renderer/media/mojo_audio_output_ipc.h
@@ -10,7 +10,7 @@
#include "base/callback_helpers.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
-#include "base/threading/thread_checker.h"
+#include "base/time/time.h"
#include "content/common/content_export.h"
#include "content/common/media/renderer_audio_output_stream_factory.mojom.h"
#include "media/audio/audio_output_ipc.h"
@@ -31,7 +31,9 @@ class CONTENT_EXPORT MojoAudioOutputIPC
// |factory_accessor| is required to provide a
// RendererAudioOutputStreamFactory* if IPC is possible.
- explicit MojoAudioOutputIPC(FactoryAccessorCB factory_accessor);
+ MojoAudioOutputIPC(
+ FactoryAccessorCB factory_accessor,
+ scoped_refptr<base::SingleThreadTaskRunner> io_task_runner);
~MojoAudioOutputIPC() override;
@@ -73,12 +75,13 @@ class CONTENT_EXPORT MojoAudioOutputIPC
const FactoryAccessorCB factory_accessor_;
- THREAD_CHECKER(thread_checker_);
-
mojo::Binding<media::mojom::AudioOutputStreamClient> binding_;
media::mojom::AudioOutputStreamProviderPtr stream_provider_;
media::mojom::AudioOutputStreamPtr stream_;
media::AudioOutputIPCDelegate* delegate_ = nullptr;
+ scoped_refptr<base::SingleThreadTaskRunner> io_task_runner_;
+
+ base::TimeTicks stream_creation_start_time_;
// To make sure we don't send an "authorization completed" callback for a
// stream after it's closed, we use this weak factory.
diff --git a/chromium/content/renderer/media/mojo_audio_output_ipc_unittest.cc b/chromium/content/renderer/media/mojo_audio_output_ipc_unittest.cc
index 431a881dc7e..8782f3ad04f 100644
--- a/chromium/content/renderer/media/mojo_audio_output_ipc_unittest.cc
+++ b/chromium/content/renderer/media/mojo_audio_output_ipc_unittest.cc
@@ -19,6 +19,7 @@
#include "mojo/public/cpp/system/platform_handle.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
#include "url/origin.h"
using testing::_;
@@ -205,7 +206,9 @@ TEST(MojoAudioOutputIPC, AuthorizeWithoutFactory_CallsAuthorizedWithError) {
StrictMock<MockDelegate> delegate;
std::unique_ptr<media::AudioOutputIPC> ipc =
- std::make_unique<MojoAudioOutputIPC>(NullAccessor());
+ std::make_unique<MojoAudioOutputIPC>(
+ NullAccessor(),
+ blink::scheduler::GetSingleThreadTaskRunnerForTesting());
ipc->RequestDeviceAuthorization(&delegate, kSessionId, kDeviceId, Origin());
@@ -224,7 +227,9 @@ TEST(MojoAudioOutputIPC,
StrictMock<MockDelegate> delegate;
std::unique_ptr<media::AudioOutputIPC> ipc =
- std::make_unique<MojoAudioOutputIPC>(NullAccessor());
+ std::make_unique<MojoAudioOutputIPC>(
+ NullAccessor(),
+ blink::scheduler::GetSingleThreadTaskRunnerForTesting());
ipc->CreateStream(&delegate, Params());
@@ -240,7 +245,9 @@ TEST(MojoAudioOutputIPC, DeviceAuthorized_Propagates) {
StrictMock<MockDelegate> delegate;
const std::unique_ptr<media::AudioOutputIPC> ipc =
- std::make_unique<MojoAudioOutputIPC>(stream_factory.GetAccessor());
+ std::make_unique<MojoAudioOutputIPC>(
+ stream_factory.GetAccessor(),
+ blink::scheduler::GetSingleThreadTaskRunnerForTesting());
stream_factory.PrepareProviderForAuthorization(
kSessionId, kDeviceId, std::make_unique<TestStreamProvider>(nullptr));
@@ -262,7 +269,9 @@ TEST(MojoAudioOutputIPC, OnDeviceCreated_Propagates) {
StrictMock<MockDelegate> delegate;
const std::unique_ptr<media::AudioOutputIPC> ipc =
- std::make_unique<MojoAudioOutputIPC>(stream_factory.GetAccessor());
+ std::make_unique<MojoAudioOutputIPC>(
+ stream_factory.GetAccessor(),
+ blink::scheduler::GetSingleThreadTaskRunnerForTesting());
stream_factory.PrepareProviderForAuthorization(
kSessionId, kDeviceId, std::make_unique<TestStreamProvider>(&stream));
@@ -286,7 +295,9 @@ TEST(MojoAudioOutputIPC,
StrictMock<MockStream> stream;
StrictMock<MockDelegate> delegate;
const std::unique_ptr<media::AudioOutputIPC> ipc =
- std::make_unique<MojoAudioOutputIPC>(stream_factory.GetAccessor());
+ std::make_unique<MojoAudioOutputIPC>(
+ stream_factory.GetAccessor(),
+ blink::scheduler::GetSingleThreadTaskRunnerForTesting());
// Note: This call implicitly EXPECTs that authorization is requested,
// and constructing the TestStreamProvider with a |&stream| EXPECTs that the
@@ -312,7 +323,9 @@ TEST(MojoAudioOutputIPC, IsReusable) {
StrictMock<MockDelegate> delegate;
const std::unique_ptr<media::AudioOutputIPC> ipc =
- std::make_unique<MojoAudioOutputIPC>(stream_factory.GetAccessor());
+ std::make_unique<MojoAudioOutputIPC>(
+ stream_factory.GetAccessor(),
+ blink::scheduler::GetSingleThreadTaskRunnerForTesting());
for (int i = 0; i < 5; ++i) {
stream_factory.PrepareProviderForAuthorization(
@@ -341,7 +354,9 @@ TEST(MojoAudioOutputIPC, IsReusableAfterError) {
StrictMock<MockDelegate> delegate;
const std::unique_ptr<media::AudioOutputIPC> ipc =
- std::make_unique<MojoAudioOutputIPC>(stream_factory.GetAccessor());
+ std::make_unique<MojoAudioOutputIPC>(
+ stream_factory.GetAccessor(),
+ blink::scheduler::GetSingleThreadTaskRunnerForTesting());
stream_factory.PrepareProviderForAuthorization(
kSessionId, kDeviceId, std::make_unique<TestStreamProvider>(nullptr));
@@ -391,7 +406,9 @@ TEST(MojoAudioOutputIPC, DeviceNotAuthorized_Propagates) {
StrictMock<MockDelegate> delegate;
std::unique_ptr<media::AudioOutputIPC> ipc =
- std::make_unique<MojoAudioOutputIPC>(stream_factory.GetAccessor());
+ std::make_unique<MojoAudioOutputIPC>(
+ stream_factory.GetAccessor(),
+ blink::scheduler::GetSingleThreadTaskRunnerForTesting());
stream_factory.RefuseNextRequest(kSessionId, kDeviceId);
ipc->RequestDeviceAuthorization(&delegate, kSessionId, kDeviceId, Origin());
@@ -420,7 +437,9 @@ TEST(MojoAudioOutputIPC,
StrictMock<MockDelegate> delegate;
std::unique_ptr<media::AudioOutputIPC> ipc =
- std::make_unique<MojoAudioOutputIPC>(stream_factory.GetAccessor());
+ std::make_unique<MojoAudioOutputIPC>(
+ stream_factory.GetAccessor(),
+ blink::scheduler::GetSingleThreadTaskRunnerForTesting());
ipc->RequestDeviceAuthorization(&delegate, kSessionId, kDeviceId, Origin());
@@ -450,7 +469,9 @@ TEST(MojoAudioOutputIPC,
StrictMock<MockDelegate> delegate;
const std::unique_ptr<media::AudioOutputIPC> ipc =
- std::make_unique<MojoAudioOutputIPC>(stream_factory.GetAccessor());
+ std::make_unique<MojoAudioOutputIPC>(
+ stream_factory.GetAccessor(),
+ blink::scheduler::GetSingleThreadTaskRunnerForTesting());
ipc->RequestDeviceAuthorization(&delegate, kSessionId, kDeviceId, Origin());
@@ -475,7 +496,9 @@ TEST(MojoAudioOutputIPC, AuthorizeNoClose_DCHECKs) {
kSessionId, kDeviceId, std::make_unique<TestStreamProvider>(nullptr));
std::unique_ptr<media::AudioOutputIPC> ipc =
- std::make_unique<MojoAudioOutputIPC>(stream_factory.GetAccessor());
+ std::make_unique<MojoAudioOutputIPC>(
+ stream_factory.GetAccessor(),
+ blink::scheduler::GetSingleThreadTaskRunnerForTesting());
ipc->RequestDeviceAuthorization(&delegate, kSessionId, kDeviceId, Origin());
EXPECT_DCHECK_DEATH(ipc.reset());
@@ -495,7 +518,9 @@ TEST(MojoAudioOutputIPC, CreateNoClose_DCHECKs) {
std::make_unique<TestStreamProvider>(&stream));
std::unique_ptr<media::AudioOutputIPC> ipc =
- std::make_unique<MojoAudioOutputIPC>(stream_factory.GetAccessor());
+ std::make_unique<MojoAudioOutputIPC>(
+ stream_factory.GetAccessor(),
+ blink::scheduler::GetSingleThreadTaskRunnerForTesting());
ipc->CreateStream(&delegate, Params());
EXPECT_DCHECK_DEATH(ipc.reset());
@@ -511,7 +536,9 @@ TEST(MojoAudioOutputIPC, Play_Plays) {
StrictMock<MockDelegate> delegate;
const std::unique_ptr<media::AudioOutputIPC> ipc =
- std::make_unique<MojoAudioOutputIPC>(stream_factory.GetAccessor());
+ std::make_unique<MojoAudioOutputIPC>(
+ stream_factory.GetAccessor(),
+ blink::scheduler::GetSingleThreadTaskRunnerForTesting());
stream_factory.PrepareProviderForAuthorization(
kSessionId, kDeviceId, std::make_unique<TestStreamProvider>(&stream));
@@ -537,7 +564,9 @@ TEST(MojoAudioOutputIPC, Pause_Pauses) {
StrictMock<MockDelegate> delegate;
const std::unique_ptr<media::AudioOutputIPC> ipc =
- std::make_unique<MojoAudioOutputIPC>(stream_factory.GetAccessor());
+ std::make_unique<MojoAudioOutputIPC>(
+ stream_factory.GetAccessor(),
+ blink::scheduler::GetSingleThreadTaskRunnerForTesting());
stream_factory.PrepareProviderForAuthorization(
kSessionId, kDeviceId, std::make_unique<TestStreamProvider>(&stream));
@@ -563,7 +592,9 @@ TEST(MojoAudioOutputIPC, SetVolume_SetsVolume) {
StrictMock<MockDelegate> delegate;
const std::unique_ptr<media::AudioOutputIPC> ipc =
- std::make_unique<MojoAudioOutputIPC>(stream_factory.GetAccessor());
+ std::make_unique<MojoAudioOutputIPC>(
+ stream_factory.GetAccessor(),
+ blink::scheduler::GetSingleThreadTaskRunnerForTesting());
stream_factory.PrepareProviderForAuthorization(
kSessionId, kDeviceId, std::make_unique<TestStreamProvider>(&stream));
diff --git a/chromium/content/renderer/media/pepper/pepper_to_video_track_adapter.cc b/chromium/content/renderer/media/pepper/pepper_to_video_track_adapter.cc
index bfd94565234..d768c2954da 100644
--- a/chromium/content/renderer/media/pepper/pepper_to_video_track_adapter.cc
+++ b/chromium/content/renderer/media/pepper/pepper_to_video_track_adapter.cc
@@ -20,9 +20,9 @@
#include "content/renderer/render_thread_impl.h"
#include "media/base/video_frame_pool.h"
#include "media/capture/video_capture_types.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
-#include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
+#include "third_party/blink/public/platform/web_url.h"
+#include "third_party/blink/public/web/web_media_stream_registry.h"
#include "third_party/libyuv/include/libyuv/convert.h"
#include "url/gurl.h"
diff --git a/chromium/content/renderer/media/pepper/pepper_to_video_track_adapter_unittest.cc b/chromium/content/renderer/media/pepper/pepper_to_video_track_adapter_unittest.cc
index cf39c9ff07a..9f8eb121f4c 100644
--- a/chromium/content/renderer/media/pepper/pepper_to_video_track_adapter_unittest.cc
+++ b/chromium/content/renderer/media/pepper/pepper_to_video_track_adapter_unittest.cc
@@ -16,9 +16,9 @@
#include "content/test/ppapi_unittest.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/web/WebHeap.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/web/web_heap.h"
using ::testing::_;
@@ -89,7 +89,8 @@ TEST_F(PepperToVideoTrackAdapterTest, PutFrame) {
base::RunLoop run_loop;
base::Closure quit_closure = run_loop.QuitClosure();
- EXPECT_CALL(sink, OnVideoFrame()).WillOnce(RunClosure(quit_closure));
+ EXPECT_CALL(sink, OnVideoFrame())
+ .WillOnce(RunClosure(std::move(quit_closure)));
frame_writer->PutFrame(image.get(), 10);
run_loop.Run();
// Run all pending tasks to let the the test clean up before the test ends.
diff --git a/chromium/content/renderer/media/pepper/video_track_to_pepper_adapter.cc b/chromium/content/renderer/media/pepper/video_track_to_pepper_adapter.cc
index 130e35eb3d8..6787c2ea278 100644
--- a/chromium/content/renderer/media/pepper/video_track_to_pepper_adapter.cc
+++ b/chromium/content/renderer/media/pepper/video_track_to_pepper_adapter.cc
@@ -15,9 +15,9 @@
#include "content/renderer/media/stream/media_stream_registry_interface.h"
#include "media/base/bind_to_current_loop.h"
#include "media/capture/video_capture_types.h"
-#include "third_party/WebKit/public/platform/WebMediaStream.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
-#include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
+#include "third_party/blink/public/platform/web_media_stream.h"
+#include "third_party/blink/public/platform/web_url.h"
+#include "third_party/blink/public/web/web_media_stream_registry.h"
#include "url/gurl.h"
namespace content {
diff --git a/chromium/content/renderer/media/pepper/video_track_to_pepper_adapter.h b/chromium/content/renderer/media/pepper/video_track_to_pepper_adapter.h
index 0bde5fb9c54..732ec6225f2 100644
--- a/chromium/content/renderer/media/pepper/video_track_to_pepper_adapter.h
+++ b/chromium/content/renderer/media/pepper/video_track_to_pepper_adapter.h
@@ -14,7 +14,7 @@
#include "base/threading/thread_checker.h"
#include "content/common/content_export.h"
#include "media/base/video_frame.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
namespace content {
diff --git a/chromium/content/renderer/media/pepper/video_track_to_pepper_adapter_unittest.cc b/chromium/content/renderer/media/pepper/video_track_to_pepper_adapter_unittest.cc
index fb2ec2ce3b3..2edaed60628 100644
--- a/chromium/content/renderer/media/pepper/video_track_to_pepper_adapter_unittest.cc
+++ b/chromium/content/renderer/media/pepper/video_track_to_pepper_adapter_unittest.cc
@@ -10,7 +10,7 @@
#include "content/renderer/media/stream/mock_media_stream_registry.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/web/WebHeap.h"
+#include "third_party/blink/public/web/web_heap.h"
namespace content {
diff --git a/chromium/content/renderer/media/render_media_log.cc b/chromium/content/renderer/media/render_media_log.cc
index 6d85af8ac0a..380f66397c5 100644
--- a/chromium/content/renderer/media/render_media_log.cc
+++ b/chromium/content/renderer/media/render_media_log.cc
@@ -184,7 +184,7 @@ void RenderMediaLog::SendQueuedMediaEvents() {
RenderThread::Get()->Send(new ViewHostMsg_MediaLogEvents(events_to_send));
}
-void RenderMediaLog::SetTickClockForTesting(base::TickClock* tick_clock) {
+void RenderMediaLog::SetTickClockForTesting(const base::TickClock* tick_clock) {
base::AutoLock auto_lock(lock_);
tick_clock_ = tick_clock;
last_ipc_send_time_ = tick_clock_->NowTicks();
diff --git a/chromium/content/renderer/media/render_media_log.h b/chromium/content/renderer/media/render_media_log.h
index e964388a903..e3110a8a5a3 100644
--- a/chromium/content/renderer/media/render_media_log.h
+++ b/chromium/content/renderer/media/render_media_log.h
@@ -44,7 +44,7 @@ class CONTENT_EXPORT RenderMediaLog : public media::MediaLog {
void RecordRapporWithSecurityOrigin(const std::string& metric) override;
// Will reset |last_ipc_send_time_| with the value of NowTicks().
- void SetTickClockForTesting(base::TickClock* tick_clock);
+ void SetTickClockForTesting(const base::TickClock* tick_clock);
void SetTaskRunnerForTesting(
const scoped_refptr<base::SingleThreadTaskRunner>& task_runner);
@@ -63,7 +63,7 @@ class CONTENT_EXPORT RenderMediaLog : public media::MediaLog {
// sequence for throttled send on |task_runner_| and coherent retrieval by
// GetErrorMessage().
mutable base::Lock lock_;
- base::TickClock* tick_clock_;
+ const base::TickClock* tick_clock_;
base::TimeTicks last_ipc_send_time_;
std::vector<media::MediaLogEvent> queued_media_events_;
diff --git a/chromium/content/renderer/media/render_media_log_unittest.cc b/chromium/content/renderer/media/render_media_log_unittest.cc
index 1a47e85c5f9..9f5d15d5daa 100644
--- a/chromium/content/renderer/media/render_media_log_unittest.cc
+++ b/chromium/content/renderer/media/render_media_log_unittest.cc
@@ -12,7 +12,7 @@
#include "content/public/test/mock_render_thread.h"
#include "content/renderer/media/render_media_log.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
namespace content {
diff --git a/chromium/content/renderer/media/renderer_webaudiodevice_impl.cc b/chromium/content/renderer/media/renderer_webaudiodevice_impl.cc
index 4e022cca01b..4a5d7103819 100644
--- a/chromium/content/renderer/media/renderer_webaudiodevice_impl.cc
+++ b/chromium/content/renderer/media/renderer_webaudiodevice_impl.cc
@@ -17,8 +17,8 @@
#include "content/renderer/render_thread_impl.h"
#include "media/base/audio_timestamp_helper.h"
#include "media/base/silent_sink_suspender.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebView.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_view.h"
using blink::WebAudioDevice;
using blink::WebAudioLatencyHint;
diff --git a/chromium/content/renderer/media/renderer_webaudiodevice_impl.h b/chromium/content/renderer/media/renderer_webaudiodevice_impl.h
index 4b887a8bef0..5edabfb3421 100644
--- a/chromium/content/renderer/media/renderer_webaudiodevice_impl.h
+++ b/chromium/content/renderer/media/renderer_webaudiodevice_impl.h
@@ -13,8 +13,8 @@
#include "content/common/content_export.h"
#include "media/base/audio_parameters.h"
#include "media/base/audio_renderer_sink.h"
-#include "third_party/WebKit/public/platform/WebAudioDevice.h"
-#include "third_party/WebKit/public/platform/WebAudioLatencyHint.h"
+#include "third_party/blink/public/platform/web_audio_device.h"
+#include "third_party/blink/public/platform/web_audio_latency_hint.h"
#include "url/origin.h"
namespace base {
diff --git a/chromium/content/renderer/media/renderer_webmediaplayer_delegate.cc b/chromium/content/renderer/media/renderer_webmediaplayer_delegate.cc
index f773ac550cc..2004df38223 100644
--- a/chromium/content/renderer/media/renderer_webmediaplayer_delegate.cc
+++ b/chromium/content/renderer/media/renderer_webmediaplayer_delegate.cc
@@ -15,8 +15,8 @@
#include "content/public/renderer/content_renderer_client.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_thread.h"
-#include "third_party/WebKit/public/platform/WebFullscreenVideoStatus.h"
-#include "third_party/WebKit/public/web/WebScopedUserGesture.h"
+#include "third_party/blink/public/platform/web_fullscreen_video_status.h"
+#include "third_party/blink/public/web/web_scoped_user_gesture.h"
#include "ui/gfx/geometry/size.h"
#if defined(OS_ANDROID)
@@ -47,7 +47,8 @@ RendererWebMediaPlayerDelegate::RendererWebMediaPlayerDelegate(
#if defined(OS_ANDROID)
// On Android, due to the instability of the OS level media components, we
// consider all pre-KitKat devices to be potentially buggy.
- is_jelly_bean_ |= base::android::BuildInfo::GetInstance()->sdk_int() <= 18;
+ is_jelly_bean_ |= base::android::BuildInfo::GetInstance()->sdk_int() <=
+ base::android::SDK_VERSION_JELLY_BEAN_MR2;
#endif
idle_cleanup_timer_.SetTaskRunner(
@@ -116,6 +117,18 @@ void RendererWebMediaPlayerDelegate::DidPlayerMutedStatusChange(int delegate_id,
delegate_id, muted));
}
+void RendererWebMediaPlayerDelegate::DidPictureInPictureSourceChange(
+ int delegate_id) {
+ Send(new MediaPlayerDelegateHostMsg_OnPictureInPictureSourceChanged(
+ routing_id(), delegate_id));
+}
+
+void RendererWebMediaPlayerDelegate::DidPictureInPictureModeEnd(
+ int delegate_id) {
+ Send(new MediaPlayerDelegateHostMsg_OnPictureInPictureModeEnded(routing_id(),
+ delegate_id));
+}
+
void RendererWebMediaPlayerDelegate::DidPause(int player_id) {
DVLOG(2) << __func__ << "(" << player_id << ")";
DCHECK(id_map_.Lookup(player_id));
@@ -242,7 +255,7 @@ bool RendererWebMediaPlayerDelegate::OnMessageReceived(
void RendererWebMediaPlayerDelegate::SetIdleCleanupParamsForTesting(
base::TimeDelta idle_timeout,
base::TimeDelta idle_cleanup_interval,
- base::TickClock* tick_clock,
+ const base::TickClock* tick_clock,
bool is_jelly_bean) {
idle_cleanup_interval_ = idle_cleanup_interval;
idle_timeout_ = idle_timeout;
diff --git a/chromium/content/renderer/media/renderer_webmediaplayer_delegate.h b/chromium/content/renderer/media/renderer_webmediaplayer_delegate.h
index 8f1fcbeffd6..913e1444e0b 100644
--- a/chromium/content/renderer/media/renderer_webmediaplayer_delegate.h
+++ b/chromium/content/renderer/media/renderer_webmediaplayer_delegate.h
@@ -65,6 +65,8 @@ class CONTENT_EXPORT RendererWebMediaPlayerDelegate
blink::WebFullscreenVideoStatus fullscreen_video_status) override;
void DidPlayerSizeChange(int delegate_id, const gfx::Size& size) override;
void DidPlayerMutedStatusChange(int delegate_id, bool muted) override;
+ void DidPictureInPictureSourceChange(int delegate_id) override;
+ void DidPictureInPictureModeEnd(int delegate_id) override;
// content::RenderFrameObserver overrides.
void WasHidden() override;
@@ -77,7 +79,7 @@ class CONTENT_EXPORT RendererWebMediaPlayerDelegate
// will cause the idle timer to run with each run of the message loop.
void SetIdleCleanupParamsForTesting(base::TimeDelta idle_timeout,
base::TimeDelta idle_cleanup_interval,
- base::TickClock* tick_clock,
+ const base::TickClock* tick_clock,
bool is_jelly_bean);
bool IsIdleCleanupTimerRunningForTesting() const;
@@ -142,7 +144,7 @@ class CONTENT_EXPORT RendererWebMediaPlayerDelegate
// Clock used for calculating when players have become stale. May be
// overridden for testing.
- base::TickClock* tick_clock_;
+ const base::TickClock* tick_clock_;
#if defined(OS_ANDROID)
bool was_playing_background_video_ = false;
diff --git a/chromium/content/renderer/media/renderer_webmediaplayer_delegate_browsertest.cc b/chromium/content/renderer/media/renderer_webmediaplayer_delegate_browsertest.cc
index f5d3145ad11..e1565a1d0fa 100644
--- a/chromium/content/renderer/media/renderer_webmediaplayer_delegate_browsertest.cc
+++ b/chromium/content/renderer/media/renderer_webmediaplayer_delegate_browsertest.cc
@@ -19,7 +19,7 @@
#include "content/renderer/render_process.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
using testing::NiceMock;
using testing::Return;
diff --git a/chromium/content/renderer/media/stream/apply_constraints_processor.cc b/chromium/content/renderer/media/stream/apply_constraints_processor.cc
index 706c05c3b9c..41adbb2084b 100644
--- a/chromium/content/renderer/media/stream/apply_constraints_processor.cc
+++ b/chromium/content/renderer/media/stream/apply_constraints_processor.cc
@@ -20,31 +20,13 @@
#include "content/renderer/media/stream/media_stream_source.h"
#include "content/renderer/media/stream/media_stream_video_source.h"
#include "content/renderer/media/stream/media_stream_video_track.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
-#include "third_party/WebKit/public/platform/WebString.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
+#include "third_party/blink/public/platform/web_string.h"
namespace content {
namespace {
-blink::mojom::FacingMode GetMojoFacingMode(
- const blink::WebMediaStreamTrack::FacingMode facing_mode) {
- switch (facing_mode) {
- case blink::WebMediaStreamTrack::FacingMode::kUser:
- return blink::mojom::FacingMode::USER;
- case blink::WebMediaStreamTrack::FacingMode::kEnvironment:
- return blink::mojom::FacingMode::ENVIRONMENT;
- case blink::WebMediaStreamTrack::FacingMode::kLeft:
- return blink::mojom::FacingMode::LEFT;
- case blink::WebMediaStreamTrack::FacingMode::kRight:
- return blink::mojom::FacingMode::RIGHT;
- case blink::WebMediaStreamTrack::FacingMode::kNone:
- return blink::mojom::FacingMode::NONE;
- }
- NOTREACHED();
- return blink::mojom::FacingMode::NONE;
-}
-
void RequestFailed(blink::WebApplyConstraintsRequest request,
const blink::WebString& constraint,
const blink::WebString& message) {
@@ -58,8 +40,10 @@ void RequestSucceeded(blink::WebApplyConstraintsRequest request) {
} // namespace
ApplyConstraintsProcessor::ApplyConstraintsProcessor(
- MediaDevicesDispatcherCallback media_devices_dispatcher_cb)
+ MediaDevicesDispatcherCallback media_devices_dispatcher_cb,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner)
: media_devices_dispatcher_cb_(std::move(media_devices_dispatcher_cb)),
+ task_runner_(std::move(task_runner)),
weak_factory_(this) {}
ApplyConstraintsProcessor::~ApplyConstraintsProcessor() {
@@ -263,10 +247,9 @@ VideoCaptureSettings ApplyConstraintsProcessor::SelectVideoSettings(
blink::mojom::VideoInputDeviceCapabilities::New();
device_capabilities->device_id =
current_request_.Track().Source().Id().Ascii();
- device_capabilities->facing_mode = GetMojoFacingMode(
- GetCurrentVideoSource()
- ? ToWebFacingMode(GetCurrentVideoSource()->device().video_facing)
- : blink::WebMediaStreamTrack::FacingMode::kNone);
+ device_capabilities->facing_mode =
+ GetCurrentVideoSource() ? GetCurrentVideoSource()->device().video_facing
+ : media::MEDIA_VIDEO_FACING_NONE;
device_capabilities->formats = std::move(formats);
DCHECK(video_source_->GetCurrentCaptureParams());
@@ -327,7 +310,7 @@ bool ApplyConstraintsProcessor::AbortIfVideoRequestStateInvalid() {
}
void ApplyConstraintsProcessor::ApplyConstraintsSucceeded() {
- base::SequencedTaskRunnerHandle::Get()->PostTask(
+ task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&ApplyConstraintsProcessor::CleanupRequest,
weak_factory_.GetWeakPtr(),
@@ -337,7 +320,7 @@ void ApplyConstraintsProcessor::ApplyConstraintsSucceeded() {
void ApplyConstraintsProcessor::ApplyConstraintsFailed(
const char* failed_constraint_name) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
- base::SequencedTaskRunnerHandle::Get()->PostTask(
+ task_runner_->PostTask(
FROM_HERE,
base::BindOnce(
&ApplyConstraintsProcessor::CleanupRequest,
@@ -351,7 +334,7 @@ void ApplyConstraintsProcessor::ApplyConstraintsFailed(
void ApplyConstraintsProcessor::CannotApplyConstraints(
const blink::WebString& message) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
- base::SequencedTaskRunnerHandle::Get()->PostTask(
+ task_runner_->PostTask(
FROM_HERE, base::BindOnce(&ApplyConstraintsProcessor::CleanupRequest,
weak_factory_.GetWeakPtr(),
base::BindOnce(&RequestFailed, current_request_,
diff --git a/chromium/content/renderer/media/stream/apply_constraints_processor.h b/chromium/content/renderer/media/stream/apply_constraints_processor.h
index 66ddd1f3c97..08087cc8b51 100644
--- a/chromium/content/renderer/media/stream/apply_constraints_processor.h
+++ b/chromium/content/renderer/media/stream/apply_constraints_processor.h
@@ -12,8 +12,8 @@
#include "content/common/content_export.h"
#include "content/renderer/media/stream/media_stream_constraints_util.h"
#include "media/capture/video_capture_types.h"
-#include "third_party/WebKit/public/platform/modules/mediastream/media_devices.mojom.h"
-#include "third_party/WebKit/public/web/WebApplyConstraintsRequest.h"
+#include "third_party/blink/public/platform/modules/mediastream/media_devices.mojom.h"
+#include "third_party/blink/public/web/web_apply_constraints_request.h"
namespace blink {
class WebString;
@@ -34,7 +34,8 @@ class CONTENT_EXPORT ApplyConstraintsProcessor {
using MediaDevicesDispatcherCallback = base::RepeatingCallback<
const blink::mojom::MediaDevicesDispatcherHostPtr&()>;
ApplyConstraintsProcessor(
- MediaDevicesDispatcherCallback media_devices_dispatcher_cb);
+ MediaDevicesDispatcherCallback media_devices_dispatcher_cb,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner);
~ApplyConstraintsProcessor();
// Starts processing of |request|. When processing of |request| is complete,
@@ -84,6 +85,8 @@ class CONTENT_EXPORT ApplyConstraintsProcessor {
MediaDevicesDispatcherCallback media_devices_dispatcher_cb_;
SEQUENCE_CHECKER(sequence_checker_);
+ const scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
+
base::WeakPtrFactory<ApplyConstraintsProcessor> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(ApplyConstraintsProcessor);
diff --git a/chromium/content/renderer/media/stream/media_stream_audio_processor_options.h b/chromium/content/renderer/media/stream/media_stream_audio_processor_options.h
index d9ff656e1ea..95240ed833c 100644
--- a/chromium/content/renderer/media/stream/media_stream_audio_processor_options.h
+++ b/chromium/content/renderer/media/stream/media_stream_audio_processor_options.h
@@ -14,7 +14,7 @@
#include "content/common/content_export.h"
#include "content/public/common/media_stream_request.h"
#include "media/base/audio_point.h"
-#include "third_party/WebKit/public/platform/WebMediaConstraints.h"
+#include "third_party/blink/public/platform/web_media_constraints.h"
#include "third_party/webrtc/api/mediastreaminterface.h"
#include "third_party/webrtc/media/base/mediachannel.h"
#include "third_party/webrtc/modules/audio_processing/include/audio_processing.h"
diff --git a/chromium/content/renderer/media/stream/media_stream_audio_processor_unittest.cc b/chromium/content/renderer/media/stream/media_stream_audio_processor_unittest.cc
index 9c43317ccb2..36146788a5a 100644
--- a/chromium/content/renderer/media/stream/media_stream_audio_processor_unittest.cc
+++ b/chromium/content/renderer/media/stream/media_stream_audio_processor_unittest.cc
@@ -14,6 +14,7 @@
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/aligned_memory.h"
+#include "base/message_loop/message_loop.h"
#include "base/path_service.h"
#include "base/test/scoped_task_environment.h"
#include "base/threading/thread_task_runner_handle.h"
@@ -27,8 +28,8 @@
#include "media/base/audio_parameters.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebMediaConstraints.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/web_media_constraints.h"
#include "third_party/webrtc/api/mediastreaminterface.h"
#include "third_party/webrtc/rtc_base/refcountedobject.h"
diff --git a/chromium/content/renderer/media/stream/media_stream_audio_source.cc b/chromium/content/renderer/media/stream/media_stream_audio_source.cc
index 6ca6aa42547..b11dd241ed6 100644
--- a/chromium/content/renderer/media/stream/media_stream_audio_source.cc
+++ b/chromium/content/renderer/media/stream/media_stream_audio_source.cc
@@ -8,8 +8,8 @@
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/renderer/media/stream/media_stream_audio_track.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/WebString.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/platform/web_string.h"
namespace content {
diff --git a/chromium/content/renderer/media/stream/media_stream_audio_source.h b/chromium/content/renderer/media/stream/media_stream_audio_source.h
index ce58253ef7a..c8f1a87244a 100644
--- a/chromium/content/renderer/media/stream/media_stream_audio_source.h
+++ b/chromium/content/renderer/media/stream/media_stream_audio_source.h
@@ -14,8 +14,8 @@
#include "content/common/content_export.h"
#include "content/renderer/media/stream/media_stream_audio_deliverer.h"
#include "content/renderer/media/stream/media_stream_source.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
namespace base {
class SingleThreadTaskRunner;
diff --git a/chromium/content/renderer/media/stream/media_stream_audio_track.cc b/chromium/content/renderer/media/stream/media_stream_audio_track.cc
index 48580c06c9f..b5d24af6dc4 100644
--- a/chromium/content/renderer/media/stream/media_stream_audio_track.cc
+++ b/chromium/content/renderer/media/stream/media_stream_audio_track.cc
@@ -11,7 +11,7 @@
#include "base/logging.h"
#include "content/public/renderer/media_stream_audio_sink.h"
#include "media/base/audio_bus.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
namespace content {
diff --git a/chromium/content/renderer/media/stream/media_stream_audio_unittest.cc b/chromium/content/renderer/media/stream/media_stream_audio_unittest.cc
index ab2899ec685..bf1a301e1f9 100644
--- a/chromium/content/renderer/media/stream/media_stream_audio_unittest.cc
+++ b/chromium/content/renderer/media/stream/media_stream_audio_unittest.cc
@@ -17,8 +17,8 @@
#include "media/base/audio_bus.h"
#include "media/base/audio_parameters.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/web/WebHeap.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/web/web_heap.h"
namespace content {
diff --git a/chromium/content/renderer/media/stream/media_stream_center.cc b/chromium/content/renderer/media/stream/media_stream_center.cc
index ab26e3bad4c..f2972e9353a 100644
--- a/chromium/content/renderer/media/stream/media_stream_center.cc
+++ b/chromium/content/renderer/media/stream/media_stream_center.cc
@@ -19,13 +19,13 @@
#include "content/renderer/media/stream/media_stream_video_track.h"
#include "content/renderer/media/stream/webaudio_media_stream_source.h"
#include "content/renderer/media/webrtc_local_audio_source_provider.h"
-#include "third_party/WebKit/public/platform/WebMediaConstraints.h"
-#include "third_party/WebKit/public/platform/WebMediaStream.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamCenterClient.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
-#include "third_party/WebKit/public/platform/WebVector.h"
-#include "third_party/WebKit/public/web/WebFrame.h"
+#include "third_party/blink/public/platform/web_media_constraints.h"
+#include "third_party/blink/public/platform/web_media_stream.h"
+#include "third_party/blink/public/platform/web_media_stream_center_client.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
+#include "third_party/blink/public/platform/web_vector.h"
+#include "third_party/blink/public/web/web_frame.h"
using blink::WebFrame;
using blink::WebView;
@@ -55,6 +55,8 @@ void CreateNativeAudioMediaStreamTrack(
blink::WebMediaStreamSource::Capabilities capabilities;
capabilities.device_id = source.Id();
capabilities.echo_cancellation = std::vector<bool>({false});
+ capabilities.auto_gain_control = std::vector<bool>({false});
+ capabilities.noise_suppression = std::vector<bool>({false});
source.SetCapabilities(capabilities);
}
diff --git a/chromium/content/renderer/media/stream/media_stream_center.h b/chromium/content/renderer/media/stream/media_stream_center.h
index 6c795935937..c057c16e9f5 100644
--- a/chromium/content/renderer/media/stream/media_stream_center.h
+++ b/chromium/content/renderer/media/stream/media_stream_center.h
@@ -10,9 +10,9 @@
#include "base/compiler_specific.h"
#include "base/macros.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebMediaStream.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamCenter.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
+#include "third_party/blink/public/platform/web_media_stream.h"
+#include "third_party/blink/public/platform/web_media_stream_center.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
namespace blink {
class WebAudioSourceProvider;
diff --git a/chromium/content/renderer/media/stream/media_stream_constraints_util.cc b/chromium/content/renderer/media/stream/media_stream_constraints_util.cc
index a07d52e3a02..bcc96ef27ce 100644
--- a/chromium/content/renderer/media/stream/media_stream_constraints_util.cc
+++ b/chromium/content/renderer/media/stream/media_stream_constraints_util.cc
@@ -11,7 +11,7 @@
#include "base/strings/utf_string_conversions.h"
#include "content/renderer/media/stream/media_stream_constraints_util_sets.h"
#include "content/renderer/media/stream/media_stream_constraints_util_video_device.h"
-#include "third_party/WebKit/public/platform/WebString.h"
+#include "third_party/blink/public/platform/web_string.h"
namespace content {
diff --git a/chromium/content/renderer/media/stream/media_stream_constraints_util.h b/chromium/content/renderer/media/stream/media_stream_constraints_util.h
index a9a7a35606f..fcd85ec2588 100644
--- a/chromium/content/renderer/media/stream/media_stream_constraints_util.h
+++ b/chromium/content/renderer/media/stream/media_stream_constraints_util.h
@@ -13,9 +13,9 @@
#include "content/renderer/media/stream/video_track_adapter.h"
#include "media/base/video_facing.h"
#include "media/capture/video_capture_types.h"
-#include "third_party/WebKit/public/platform/WebMediaConstraints.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/modules/mediastream/media_devices.mojom.h"
+#include "third_party/blink/public/platform/modules/mediastream/media_devices.mojom.h"
+#include "third_party/blink/public/platform/web_media_constraints.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
#include "third_party/webrtc/api/optional.h"
namespace content {
diff --git a/chromium/content/renderer/media/stream/media_stream_constraints_util_audio.cc b/chromium/content/renderer/media/stream/media_stream_constraints_util_audio.cc
index a958b79722b..80cce4b79a4 100644
--- a/chromium/content/renderer/media/stream/media_stream_constraints_util_audio.cc
+++ b/chromium/content/renderer/media/stream/media_stream_constraints_util_audio.cc
@@ -16,8 +16,8 @@
#include "content/renderer/media/stream/media_stream_video_source.h"
#include "content/renderer/media/stream/processed_local_audio_source.h"
#include "media/base/limits.h"
-#include "third_party/WebKit/public/platform/WebMediaConstraints.h"
-#include "third_party/WebKit/public/platform/WebString.h"
+#include "third_party/blink/public/platform/web_media_constraints.h"
+#include "third_party/blink/public/platform/web_string.h"
namespace content {
diff --git a/chromium/content/renderer/media/stream/media_stream_constraints_util_audio.h b/chromium/content/renderer/media/stream/media_stream_constraints_util_audio.h
index 85aa293494d..b6f8d4837e2 100644
--- a/chromium/content/renderer/media/stream/media_stream_constraints_util_audio.h
+++ b/chromium/content/renderer/media/stream/media_stream_constraints_util_audio.h
@@ -10,7 +10,7 @@
#include "content/common/content_export.h"
#include "content/renderer/media/stream/media_stream_constraints_util.h"
-#include "third_party/WebKit/public/platform/modules/mediastream/media_devices.mojom.h"
+#include "third_party/blink/public/platform/modules/mediastream/media_devices.mojom.h"
namespace blink {
class WebMediaConstraints;
diff --git a/chromium/content/renderer/media/stream/media_stream_constraints_util_audio_unittest.cc b/chromium/content/renderer/media/stream/media_stream_constraints_util_audio_unittest.cc
index 5a4c2a57d56..0fc9a21d9a3 100644
--- a/chromium/content/renderer/media/stream/media_stream_constraints_util_audio_unittest.cc
+++ b/chromium/content/renderer/media/stream/media_stream_constraints_util_audio_unittest.cc
@@ -18,9 +18,9 @@
#include "content/renderer/media/stream/processed_local_audio_source.h"
#include "content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebMediaConstraints.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/modules/mediastream/media_devices.mojom.h"
+#include "third_party/blink/public/platform/modules/mediastream/media_devices.mojom.h"
+#include "third_party/blink/public/platform/web_media_constraints.h"
+#include "third_party/blink/public/platform/web_string.h"
namespace content {
diff --git a/chromium/content/renderer/media/stream/media_stream_constraints_util_sets.cc b/chromium/content/renderer/media/stream/media_stream_constraints_util_sets.cc
index aca5de6467e..9ce80b68a18 100644
--- a/chromium/content/renderer/media/stream/media_stream_constraints_util_sets.cc
+++ b/chromium/content/renderer/media/stream/media_stream_constraints_util_sets.cc
@@ -7,7 +7,7 @@
#include <cmath>
#include "content/renderer/media/stream/media_stream_constraints_util.h"
-#include "third_party/WebKit/public/platform/WebMediaConstraints.h"
+#include "third_party/blink/public/platform/web_media_constraints.h"
namespace content {
diff --git a/chromium/content/renderer/media/stream/media_stream_constraints_util_video_content.cc b/chromium/content/renderer/media/stream/media_stream_constraints_util_video_content.cc
index 01ba790a137..dfa2734c8a5 100644
--- a/chromium/content/renderer/media/stream/media_stream_constraints_util_video_content.cc
+++ b/chromium/content/renderer/media/stream/media_stream_constraints_util_video_content.cc
@@ -13,8 +13,8 @@
#include "content/renderer/media/stream/media_stream_constraints_util_sets.h"
#include "content/renderer/media/stream/media_stream_video_source.h"
#include "media/base/limits.h"
-#include "third_party/WebKit/public/platform/WebMediaConstraints.h"
-#include "third_party/WebKit/public/platform/WebString.h"
+#include "third_party/blink/public/platform/web_media_constraints.h"
+#include "third_party/blink/public/platform/web_string.h"
namespace content {
@@ -28,8 +28,6 @@ static_assert(kMaxScreenCastDimension * kMaxScreenCastDimension <
const int kDefaultScreenCastWidth = 2880;
const int kDefaultScreenCastHeight = 1800;
-const double kDefaultScreenCastAspectRatio =
- static_cast<double>(kDefaultScreenCastWidth) / kDefaultScreenCastHeight;
static_assert(kDefaultScreenCastWidth <= kMaxScreenCastDimension,
"Invalid kDefaultScreenCastWidth");
static_assert(kDefaultScreenCastHeight <= kMaxScreenCastDimension,
@@ -260,28 +258,30 @@ int ClampToValidScreenCastDimension(int value) {
VideoCaptureSettings SelectResultFromCandidates(
const VideoContentCaptureCandidates& candidates,
const blink::WebMediaTrackConstraintSet& basic_constraint_set,
- const std::string& stream_source) {
+ const std::string& stream_source,
+ int screen_width,
+ int screen_height) {
std::string device_id = SelectDeviceIDFromCandidates(
candidates.device_id_set(), basic_constraint_set);
// If a maximum width or height is explicitly given, use them as default.
// If only one of them is given, use the default aspect ratio to determine the
// other default value.
- // TODO(guidou): Use native screen-capture resolution as default.
- // http://crbug.com/257097
- int default_height = kDefaultScreenCastHeight;
- int default_width = kDefaultScreenCastWidth;
+ int default_width = screen_width;
+ int default_height = screen_height;
+ double default_aspect_ratio =
+ static_cast<double>(default_width) / default_height;
if (candidates.has_explicit_max_height() &&
candidates.has_explicit_max_width()) {
default_height = candidates.resolution_set().max_height();
default_width = candidates.resolution_set().max_width();
} else if (candidates.has_explicit_max_height()) {
default_height = candidates.resolution_set().max_height();
- default_width = static_cast<int>(
- std::round(default_height * kDefaultScreenCastAspectRatio));
+ default_width =
+ static_cast<int>(std::round(default_height * default_aspect_ratio));
} else if (candidates.has_explicit_max_width()) {
default_width = candidates.resolution_set().max_width();
- default_height = static_cast<int>(
- std::round(default_width / kDefaultScreenCastAspectRatio));
+ default_height =
+ static_cast<int>(std::round(default_width / default_aspect_ratio));
}
// When the given maximum values are large, the computed values using default
// aspect ratio may fall out of range. Ensure the defaults are in the valid
@@ -344,7 +344,9 @@ VideoCaptureSettings UnsatisfiedConstraintsResult(
VideoCaptureSettings SelectSettingsVideoContentCapture(
const blink::WebMediaConstraints& constraints,
- const std::string& stream_source) {
+ const std::string& stream_source,
+ int screen_width,
+ int screen_height) {
VideoContentCaptureCandidates candidates;
candidates.set_resolution_set(ScreenCastResolutionCapabilities());
@@ -363,7 +365,7 @@ VideoCaptureSettings SelectSettingsVideoContentCapture(
DCHECK(!candidates.IsEmpty());
return SelectResultFromCandidates(candidates, constraints.Basic(),
- stream_source);
+ stream_source, screen_width, screen_height);
}
} // namespace content
diff --git a/chromium/content/renderer/media/stream/media_stream_constraints_util_video_content.h b/chromium/content/renderer/media/stream/media_stream_constraints_util_video_content.h
index ab8c4ca1d22..75e989191d3 100644
--- a/chromium/content/renderer/media/stream/media_stream_constraints_util_video_content.h
+++ b/chromium/content/renderer/media/stream/media_stream_constraints_util_video_content.h
@@ -21,7 +21,6 @@ CONTENT_EXPORT extern const int kMinScreenCastDimension;
CONTENT_EXPORT extern const int kMaxScreenCastDimension;
CONTENT_EXPORT extern const int kDefaultScreenCastWidth;
CONTENT_EXPORT extern const int kDefaultScreenCastHeight;
-CONTENT_EXPORT extern const double kDefaultScreenCastAspectRatio;
CONTENT_EXPORT extern const double kMaxScreenCastFrameRate;
CONTENT_EXPORT extern const double kDefaultScreenCastFrameRate;
@@ -30,7 +29,9 @@ CONTENT_EXPORT extern const double kDefaultScreenCastFrameRate;
// for content video capture based on the given |constraints|.
VideoCaptureSettings CONTENT_EXPORT
SelectSettingsVideoContentCapture(const blink::WebMediaConstraints& constraints,
- const std::string& stream_source);
+ const std::string& stream_source,
+ int screen_width,
+ int screen_height);
} // namespace content
diff --git a/chromium/content/renderer/media/stream/media_stream_constraints_util_video_content_unittest.cc b/chromium/content/renderer/media/stream/media_stream_constraints_util_video_content_unittest.cc
index ae3e4f3212e..b8c888f6c13 100644
--- a/chromium/content/renderer/media/stream/media_stream_constraints_util_video_content_unittest.cc
+++ b/chromium/content/renderer/media/stream/media_stream_constraints_util_video_content_unittest.cc
@@ -11,12 +11,15 @@
#include "content/renderer/media/stream/mock_constraint_factory.h"
#include "media/base/limits.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebMediaConstraints.h"
+#include "third_party/blink/public/platform/web_media_constraints.h"
namespace content {
namespace {
+const double kDefaultScreenCastAspectRatio =
+ static_cast<double>(kDefaultScreenCastWidth) / kDefaultScreenCastHeight;
+
void CheckNonResolutionDefaults(const VideoCaptureSettings& result) {
EXPECT_EQ(kDefaultScreenCastFrameRate, result.FrameRate());
EXPECT_EQ(base::Optional<double>(), result.min_frame_rate());
@@ -61,7 +64,9 @@ class MediaStreamConstraintsUtilVideoContentTest : public testing::Test {
std::string(kMediaStreamSourceScreen)) {
blink::WebMediaConstraints constraints =
constraint_factory_.CreateWebMediaConstraints();
- return SelectSettingsVideoContentCapture(constraints, stream_source);
+ return SelectSettingsVideoContentCapture(constraints, stream_source,
+ kDefaultScreenCastWidth,
+ kDefaultScreenCastHeight);
}
MockConstraintFactory constraint_factory_;
diff --git a/chromium/content/renderer/media/stream/media_stream_constraints_util_video_device.cc b/chromium/content/renderer/media/stream/media_stream_constraints_util_video_device.cc
index 61ea8e82c72..a4642cd38be 100644
--- a/chromium/content/renderer/media/stream/media_stream_constraints_util_video_device.cc
+++ b/chromium/content/renderer/media/stream/media_stream_constraints_util_video_device.cc
@@ -14,8 +14,8 @@
#include "content/renderer/media/stream/media_stream_constraints_util_sets.h"
#include "content/renderer/media/stream/media_stream_video_source.h"
#include "media/base/limits.h"
-#include "third_party/WebKit/public/platform/WebMediaConstraints.h"
-#include "third_party/WebKit/public/platform/WebString.h"
+#include "third_party/blink/public/platform/web_media_constraints.h"
+#include "third_party/blink/public/platform/web_string.h"
namespace content {
@@ -33,16 +33,12 @@ const double kMinSourceAspectRatio = 0.05;
const char kVideoKindColor[] = "color";
const char kVideoKindDepth[] = "depth";
-blink::WebString ToWebString(blink::mojom::FacingMode facing_mode) {
+blink::WebString ToWebString(media::VideoFacingMode facing_mode) {
switch (facing_mode) {
- case blink::mojom::FacingMode::USER:
+ case media::MEDIA_VIDEO_FACING_USER:
return blink::WebString::FromASCII("user");
- case blink::mojom::FacingMode::ENVIRONMENT:
+ case media::MEDIA_VIDEO_FACING_ENVIRONMENT:
return blink::WebString::FromASCII("environment");
- case blink::mojom::FacingMode::LEFT:
- return blink::WebString::FromASCII("left");
- case blink::mojom::FacingMode::RIGHT:
- return blink::WebString::FromASCII("right");
default:
return blink::WebString::FromASCII("");
}
@@ -52,7 +48,7 @@ struct Candidate {
public:
Candidate(const std::string& device_id,
const media::VideoCaptureFormat& format,
- blink::mojom::FacingMode facing_mode,
+ media::VideoFacingMode facing_mode,
media::PowerLineFrequency power_line_frequency,
const base::Optional<bool>& noise_reduction)
: device_id_(device_id),
@@ -77,7 +73,7 @@ struct Candidate {
// Accessors.
const media::VideoCaptureFormat& format() const { return format_; }
const std::string& device_id() const { return device_id_; }
- blink::mojom::FacingMode facing_mode() const { return facing_mode_; }
+ media::VideoFacingMode facing_mode() const { return facing_mode_; }
media::PowerLineFrequency power_line_frequency() const {
return power_line_frequency_;
}
@@ -88,7 +84,7 @@ struct Candidate {
private:
std::string device_id_;
media::VideoCaptureFormat format_;
- blink::mojom::FacingMode facing_mode_;
+ media::VideoFacingMode facing_mode_;
media::PowerLineFrequency power_line_frequency_;
base::Optional<bool> noise_reduction_;
};
@@ -433,7 +429,7 @@ double NoiseReductionConstraintSourceDistance(
// characteristics that have a fixed value.
double DeviceSourceDistance(
const std::string& device_id,
- blink::mojom::FacingMode facing_mode,
+ media::VideoFacingMode facing_mode,
const blink::WebMediaTrackConstraintSet& constraint_set,
const char** failed_constraint_name) {
return StringConstraintSourceDistance(blink::WebString::FromASCII(device_id),
diff --git a/chromium/content/renderer/media/stream/media_stream_constraints_util_video_device.h b/chromium/content/renderer/media/stream/media_stream_constraints_util_video_device.h
index 505749f65c8..cfd1e96908c 100644
--- a/chromium/content/renderer/media/stream/media_stream_constraints_util_video_device.h
+++ b/chromium/content/renderer/media/stream/media_stream_constraints_util_video_device.h
@@ -12,7 +12,7 @@
#include "content/common/content_export.h"
#include "content/renderer/media/stream/media_stream_constraints_util.h"
#include "media/capture/video_capture_types.h"
-#include "third_party/WebKit/public/platform/modules/mediastream/media_devices.mojom.h"
+#include "third_party/blink/public/platform/modules/mediastream/media_devices.mojom.h"
namespace blink {
class WebString;
diff --git a/chromium/content/renderer/media/stream/media_stream_constraints_util_video_device_unittest.cc b/chromium/content/renderer/media/stream/media_stream_constraints_util_video_device_unittest.cc
index c5f75956461..9ba2bc4fb95 100644
--- a/chromium/content/renderer/media/stream/media_stream_constraints_util_video_device_unittest.cc
+++ b/chromium/content/renderer/media/stream/media_stream_constraints_util_video_device_unittest.cc
@@ -12,7 +12,7 @@
#include "content/renderer/media/stream/mock_constraint_factory.h"
#include "media/base/limits.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebMediaConstraints.h"
+#include "third_party/blink/public/platform/web_media_constraints.h"
namespace content {
@@ -73,7 +73,7 @@ class MediaStreamConstraintsUtilVideoDeviceTest : public testing::Test {
blink::mojom::VideoInputDeviceCapabilitiesPtr device =
blink::mojom::VideoInputDeviceCapabilities::New();
device->device_id = kDeviceID1;
- device->facing_mode = blink::mojom::FacingMode::NONE;
+ device->facing_mode = media::MEDIA_VIDEO_FACING_NONE;
device->formats = {
media::VideoCaptureFormat(gfx::Size(200, 200), 40.0f,
media::PIXEL_FORMAT_I420),
@@ -88,7 +88,7 @@ class MediaStreamConstraintsUtilVideoDeviceTest : public testing::Test {
// A low-resolution device.
device = blink::mojom::VideoInputDeviceCapabilities::New();
device->device_id = kDeviceID2;
- device->facing_mode = blink::mojom::FacingMode::ENVIRONMENT;
+ device->facing_mode = media::MEDIA_VIDEO_FACING_ENVIRONMENT;
device->formats = {
media::VideoCaptureFormat(gfx::Size(40, 30), 20.0f,
media::PIXEL_FORMAT_I420),
@@ -108,7 +108,7 @@ class MediaStreamConstraintsUtilVideoDeviceTest : public testing::Test {
// A high-resolution device.
device = blink::mojom::VideoInputDeviceCapabilities::New();
device->device_id = kDeviceID3;
- device->facing_mode = blink::mojom::FacingMode::USER;
+ device->facing_mode = media::MEDIA_VIDEO_FACING_USER;
device->formats = {
media::VideoCaptureFormat(gfx::Size(600, 400), 10.0f,
media::PIXEL_FORMAT_I420),
@@ -139,7 +139,7 @@ class MediaStreamConstraintsUtilVideoDeviceTest : public testing::Test {
// A depth capture device.
device = blink::mojom::VideoInputDeviceCapabilities::New();
device->device_id = kDeviceID4;
- device->facing_mode = blink::mojom::FacingMode::ENVIRONMENT;
+ device->facing_mode = media::MEDIA_VIDEO_FACING_ENVIRONMENT;
device->formats = {media::VideoCaptureFormat(gfx::Size(640, 480), 30.0f,
media::PIXEL_FORMAT_Y16)};
capabilities_.device_capabilities.push_back(std::move(device));
@@ -148,7 +148,7 @@ class MediaStreamConstraintsUtilVideoDeviceTest : public testing::Test {
// be supported if no constraints are placed on the frame rate.
device = blink::mojom::VideoInputDeviceCapabilities::New();
device->device_id = kDeviceID5;
- device->facing_mode = blink::mojom::FacingMode::NONE;
+ device->facing_mode = media::MEDIA_VIDEO_FACING_NONE;
device->formats = {
media::VideoCaptureFormat(
gfx::Size(MediaStreamVideoSource::kDefaultWidth,
@@ -385,7 +385,7 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest,
blink::mojom::VideoInputDeviceCapabilitiesPtr device =
blink::mojom::VideoInputDeviceCapabilities::New();
device->device_id = kDeviceID1;
- device->facing_mode = blink::mojom::FacingMode::NONE;
+ device->facing_mode = media::MEDIA_VIDEO_FACING_NONE;
device->formats = {
media::VideoCaptureFormat(gfx::Size(200, 200), 40.0f,
media::PIXEL_FORMAT_I420),
@@ -445,7 +445,7 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, MandatoryFacingMode) {
// Only the low-res device supports environment facing mode. Should select
// default settings for everything else.
EXPECT_EQ(low_res_device_->device_id, result.device_id());
- EXPECT_EQ(blink::mojom::FacingMode::ENVIRONMENT,
+ EXPECT_EQ(media::MEDIA_VIDEO_FACING_ENVIRONMENT,
low_res_device_->facing_mode);
EXPECT_EQ(*low_res_closest_format_, result.Format());
EXPECT_EQ(media::PowerLineFrequency::FREQUENCY_DEFAULT,
@@ -459,7 +459,7 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, MandatoryFacingMode) {
// Only the high-res device supports user facing mode. Should select default
// settings for everything else.
EXPECT_EQ(high_res_device_->device_id, result.device_id());
- EXPECT_EQ(blink::mojom::FacingMode::USER, high_res_device_->facing_mode);
+ EXPECT_EQ(media::MEDIA_VIDEO_FACING_USER, high_res_device_->facing_mode);
EXPECT_EQ(*high_res_closest_format_, result.Format());
EXPECT_EQ(media::PowerLineFrequency::FREQUENCY_DEFAULT,
result.PowerLineFrequency());
diff --git a/chromium/content/renderer/media/stream/media_stream_device_observer_unittest.cc b/chromium/content/renderer/media/stream/media_stream_device_observer_unittest.cc
index 8a5948bfd2f..f0bbab260c4 100644
--- a/chromium/content/renderer/media/stream/media_stream_device_observer_unittest.cc
+++ b/chromium/content/renderer/media/stream/media_stream_device_observer_unittest.cc
@@ -32,7 +32,7 @@ class MediaStreamDeviceObserverTest : public ::testing::Test {
observer_->AddStream(label, device);
}
- quit_closure.Run();
+ std::move(quit_closure).Run();
}
protected:
diff --git a/chromium/content/renderer/media/stream/media_stream_registry_interface.h b/chromium/content/renderer/media/stream/media_stream_registry_interface.h
index 294b04b713f..c804e53ca9e 100644
--- a/chromium/content/renderer/media/stream/media_stream_registry_interface.h
+++ b/chromium/content/renderer/media/stream/media_stream_registry_interface.h
@@ -7,7 +7,7 @@
#include <string>
-#include "third_party/WebKit/public/platform/WebMediaStream.h"
+#include "third_party/blink/public/platform/web_media_stream.h"
namespace content {
diff --git a/chromium/content/renderer/media/stream/media_stream_renderer_factory_impl.cc b/chromium/content/renderer/media/stream/media_stream_renderer_factory_impl.cc
index 8e64b66a685..1034558ddde 100644
--- a/chromium/content/renderer/media/stream/media_stream_renderer_factory_impl.cc
+++ b/chromium/content/renderer/media/stream/media_stream_renderer_factory_impl.cc
@@ -14,7 +14,7 @@
#include "content/renderer/media/webrtc/webrtc_audio_renderer.h"
#include "content/renderer/media/webrtc_logging.h"
#include "content/renderer/render_thread_impl.h"
-#include "third_party/WebKit/public/platform/WebMediaStream.h"
+#include "third_party/blink/public/platform/web_media_stream.h"
#include "third_party/webrtc/api/mediastreaminterface.h"
namespace content {
diff --git a/chromium/content/renderer/media/stream/media_stream_source.h b/chromium/content/renderer/media/stream/media_stream_source.h
index 35d07339e04..ca0796068d8 100644
--- a/chromium/content/renderer/media/stream/media_stream_source.h
+++ b/chromium/content/renderer/media/stream/media_stream_source.h
@@ -10,7 +10,7 @@
#include "base/threading/thread_checker.h"
#include "content/common/content_export.h"
#include "content/public/common/media_stream_request.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
namespace content {
diff --git a/chromium/content/renderer/media/stream/media_stream_track.h b/chromium/content/renderer/media/stream/media_stream_track.h
index 60a3b4d417c..866d124fe17 100644
--- a/chromium/content/renderer/media/stream/media_stream_track.h
+++ b/chromium/content/renderer/media/stream/media_stream_track.h
@@ -13,7 +13,7 @@
#include "base/threading/thread_checker.h"
#include "content/common/content_export.h"
#include "media/base/audio_parameters.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
namespace content {
diff --git a/chromium/content/renderer/media/stream/media_stream_video_capturer_source.cc b/chromium/content/renderer/media/stream/media_stream_video_capturer_source.cc
index 2819f7943a7..f6f5a83efa1 100644
--- a/chromium/content/renderer/media/stream/media_stream_video_capturer_source.cc
+++ b/chromium/content/renderer/media/stream/media_stream_video_capturer_source.cc
@@ -23,7 +23,7 @@
#include "media/base/video_frame.h"
#include "media/capture/video_capturer_source.h"
#include "services/service_manager/public/cpp/interface_provider.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "third_party/blink/public/web/web_local_frame.h"
namespace content {
diff --git a/chromium/content/renderer/media/stream/media_stream_video_capturer_source_unittest.cc b/chromium/content/renderer/media/stream/media_stream_video_capturer_source_unittest.cc
index e50fa27c9d4..715cda93b18 100644
--- a/chromium/content/renderer/media/stream/media_stream_video_capturer_source_unittest.cc
+++ b/chromium/content/renderer/media/stream/media_stream_video_capturer_source_unittest.cc
@@ -18,8 +18,8 @@
#include "media/base/bind_to_current_loop.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
-#include "third_party/WebKit/public/web/WebHeap.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/web/web_heap.h"
using ::testing::_;
using ::testing::InSequence;
diff --git a/chromium/content/renderer/media/stream/media_stream_video_renderer_sink.h b/chromium/content/renderer/media/stream/media_stream_video_renderer_sink.h
index 16ac7e0286d..1d6f11af642 100644
--- a/chromium/content/renderer/media/stream/media_stream_video_renderer_sink.h
+++ b/chromium/content/renderer/media/stream/media_stream_video_renderer_sink.h
@@ -12,7 +12,7 @@
#include "content/common/media/video_capture.h"
#include "content/public/renderer/media_stream_video_renderer.h"
#include "content/public/renderer/media_stream_video_sink.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
#include "ui/gfx/geometry/size.h"
namespace base {
diff --git a/chromium/content/renderer/media/stream/media_stream_video_renderer_sink_unittest.cc b/chromium/content/renderer/media/stream/media_stream_video_renderer_sink_unittest.cc
index 655667bb696..8d2f432c53f 100644
--- a/chromium/content/renderer/media/stream/media_stream_video_renderer_sink_unittest.cc
+++ b/chromium/content/renderer/media/stream/media_stream_video_renderer_sink_unittest.cc
@@ -19,8 +19,8 @@
#include "media/base/video_frame.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/web/WebHeap.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/web/web_heap.h"
using ::testing::_;
using ::testing::AtLeast;
diff --git a/chromium/content/renderer/media/stream/media_stream_video_source.h b/chromium/content/renderer/media/stream/media_stream_video_source.h
index 1d3682f12ca..f29a1b1528f 100644
--- a/chromium/content/renderer/media/stream/media_stream_video_source.h
+++ b/chromium/content/renderer/media/stream/media_stream_video_source.h
@@ -20,9 +20,9 @@
#include "content/renderer/media/stream/secure_display_link_tracker.h"
#include "media/base/video_frame.h"
#include "media/capture/video_capture_types.h"
-#include "third_party/WebKit/public/platform/WebMediaConstraints.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
+#include "third_party/blink/public/platform/web_media_constraints.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
namespace content {
diff --git a/chromium/content/renderer/media/stream/media_stream_video_source_unittest.cc b/chromium/content/renderer/media/stream/media_stream_video_source_unittest.cc
index cdf513903f0..ebbbf191ad5 100644
--- a/chromium/content/renderer/media/stream/media_stream_video_source_unittest.cc
+++ b/chromium/content/renderer/media/stream/media_stream_video_source_unittest.cc
@@ -21,7 +21,7 @@
#include "media/base/limits.h"
#include "media/base/video_frame.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/web/WebHeap.h"
+#include "third_party/blink/public/web/web_heap.h"
using ::testing::_;
using ::testing::DoAll;
@@ -158,7 +158,8 @@ class MediaStreamVideoSourceTest : public ::testing::Test {
MockMediaStreamVideoSink* sink) {
base::RunLoop run_loop;
base::Closure quit_closure = run_loop.QuitClosure();
- EXPECT_CALL(*sink, OnVideoFrame()).WillOnce(RunClosure(quit_closure));
+ EXPECT_CALL(*sink, OnVideoFrame())
+ .WillOnce(RunClosure(std::move(quit_closure)));
scoped_refptr<media::VideoFrame> frame =
media::VideoFrame::CreateBlackFrame(gfx::Size(width, height));
mock_source()->DeliverVideoFrame(frame);
@@ -180,7 +181,8 @@ class MediaStreamVideoSourceTest : public ::testing::Test {
base::RunLoop run_loop;
base::Closure quit_closure = run_loop.QuitClosure();
EXPECT_CALL(*sink1, OnVideoFrame());
- EXPECT_CALL(*sink2, OnVideoFrame()).WillOnce(RunClosure(quit_closure));
+ EXPECT_CALL(*sink2, OnVideoFrame())
+ .WillOnce(RunClosure(std::move(quit_closure)));
scoped_refptr<media::VideoFrame> frame =
media::VideoFrame::CreateBlackFrame(gfx::Size(width, height));
mock_source()->DeliverVideoFrame(frame);
@@ -419,7 +421,8 @@ TEST_F(MediaStreamVideoSourceTest, MutedSource) {
base::Closure quit_closure = run_loop.QuitClosure();
bool muted_state = false;
EXPECT_CALL(*mock_source(), DoSetMutedState(_))
- .WillOnce(DoAll(SaveArg<0>(&muted_state), RunClosure(quit_closure)));
+ .WillOnce(
+ DoAll(SaveArg<0>(&muted_state), RunClosure(std::move(quit_closure))));
run_loop.Run();
EXPECT_EQ(muted_state, true);
@@ -429,7 +432,8 @@ TEST_F(MediaStreamVideoSourceTest, MutedSource) {
base::RunLoop run_loop2;
base::Closure quit_closure2 = run_loop2.QuitClosure();
EXPECT_CALL(*mock_source(), DoSetMutedState(_))
- .WillOnce(DoAll(SaveArg<0>(&muted_state), RunClosure(quit_closure2)));
+ .WillOnce(DoAll(SaveArg<0>(&muted_state),
+ RunClosure(std::move(quit_closure2))));
DeliverVideoFrameAndWaitForRenderer(640, 480, &sink);
run_loop2.Run();
diff --git a/chromium/content/renderer/media/stream/media_stream_video_track.cc b/chromium/content/renderer/media/stream/media_stream_video_track.cc
index 7b42fc25550..5a30ba62c91 100644
--- a/chromium/content/renderer/media/stream/media_stream_video_track.cc
+++ b/chromium/content/renderer/media/stream/media_stream_video_track.cc
@@ -10,7 +10,6 @@
#include "base/bind.h"
#include "base/location.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
diff --git a/chromium/content/renderer/media/stream/media_stream_video_track.h b/chromium/content/renderer/media/stream/media_stream_video_track.h
index 478d6c5387b..09bc143c180 100644
--- a/chromium/content/renderer/media/stream/media_stream_video_track.h
+++ b/chromium/content/renderer/media/stream/media_stream_video_track.h
@@ -17,7 +17,7 @@
#include "content/renderer/media/stream/media_stream_track.h"
#include "content/renderer/media/stream/media_stream_video_source.h"
#include "content/renderer/media/stream/secure_display_link_tracker.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
namespace content {
diff --git a/chromium/content/renderer/media/stream/media_stream_video_track_unittest.cc b/chromium/content/renderer/media/stream/media_stream_video_track_unittest.cc
index 5723f4864ff..19a5ec9d0c6 100644
--- a/chromium/content/renderer/media/stream/media_stream_video_track_unittest.cc
+++ b/chromium/content/renderer/media/stream/media_stream_video_track_unittest.cc
@@ -18,7 +18,7 @@
#include "content/renderer/media/stream/video_track_adapter.h"
#include "media/base/video_frame.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/web/WebHeap.h"
+#include "third_party/blink/public/web/web_heap.h"
namespace content {
@@ -49,7 +49,8 @@ class MediaStreamVideoTrackTest : public ::testing::Test {
void DeliverVideoFrameAndWaitForRenderer(MockMediaStreamVideoSink* sink) {
base::RunLoop run_loop;
base::Closure quit_closure = run_loop.QuitClosure();
- EXPECT_CALL(*sink, OnVideoFrame()).WillOnce(RunClosure(quit_closure));
+ EXPECT_CALL(*sink, OnVideoFrame())
+ .WillOnce(RunClosure(std::move(quit_closure)));
const scoped_refptr<media::VideoFrame> frame =
media::VideoFrame::CreateColorFrame(
gfx::Size(MediaStreamVideoSource::kDefaultWidth,
@@ -278,7 +279,8 @@ TEST_F(MediaStreamVideoTrackTest, CheckTrackRequestsFrame) {
MockMediaStreamVideoSink sink;
base::RunLoop run_loop;
base::Closure quit_closure = run_loop.QuitClosure();
- EXPECT_CALL(sink, OnVideoFrame()).WillOnce(RunClosure(quit_closure));
+ EXPECT_CALL(sink, OnVideoFrame())
+ .WillOnce(RunClosure(std::move(quit_closure)));
sink.ConnectToTrack(track);
run_loop.Run();
EXPECT_EQ(1, sink.number_of_frames());
diff --git a/chromium/content/renderer/media/stream/mock_constraint_factory.h b/chromium/content/renderer/media/stream/mock_constraint_factory.h
index 20659529e1b..d721c6cdb88 100644
--- a/chromium/content/renderer/media/stream/mock_constraint_factory.h
+++ b/chromium/content/renderer/media/stream/mock_constraint_factory.h
@@ -9,7 +9,7 @@
#include <vector>
#include "base/macros.h"
-#include "third_party/WebKit/public/platform/WebMediaConstraints.h"
+#include "third_party/blink/public/platform/web_media_constraints.h"
namespace content {
diff --git a/chromium/content/renderer/media/stream/mock_media_stream_registry.cc b/chromium/content/renderer/media/stream/mock_media_stream_registry.cc
index c31fc10dc96..a3c084e5b99 100644
--- a/chromium/content/renderer/media/stream/mock_media_stream_registry.cc
+++ b/chromium/content/renderer/media/stream/mock_media_stream_registry.cc
@@ -11,10 +11,10 @@
#include "content/renderer/media/stream/media_stream_video_track.h"
#include "content/renderer/media/stream/mock_media_stream_video_source.h"
#include "content/renderer/media/stream/video_track_adapter.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebVector.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_vector.h"
namespace content {
diff --git a/chromium/content/renderer/media/stream/processed_local_audio_source.h b/chromium/content/renderer/media/stream/processed_local_audio_source.h
index 42be2a4aef1..149c1d7de6b 100644
--- a/chromium/content/renderer/media/stream/processed_local_audio_source.h
+++ b/chromium/content/renderer/media/stream/processed_local_audio_source.h
@@ -15,7 +15,7 @@
#include "content/renderer/media/stream/media_stream_audio_processor.h"
#include "content/renderer/media/stream/media_stream_audio_source.h"
#include "media/base/audio_capturer_source.h"
-#include "third_party/WebKit/public/platform/WebMediaConstraints.h"
+#include "third_party/blink/public/platform/web_media_constraints.h"
namespace media {
class AudioBus;
diff --git a/chromium/content/renderer/media/stream/processed_local_audio_source_unittest.cc b/chromium/content/renderer/media/stream/processed_local_audio_source_unittest.cc
index 7ced179dfb4..c14fde2937c 100644
--- a/chromium/content/renderer/media/stream/processed_local_audio_source_unittest.cc
+++ b/chromium/content/renderer/media/stream/processed_local_audio_source_unittest.cc
@@ -18,8 +18,8 @@
#include "media/base/audio_parameters.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebMediaConstraints.h"
-#include "third_party/WebKit/public/web/WebHeap.h"
+#include "third_party/blink/public/platform/web_media_constraints.h"
+#include "third_party/blink/public/web/web_heap.h"
using ::testing::_;
using ::testing::AtLeast;
diff --git a/chromium/content/renderer/media/stream/remote_media_stream_track_adapter.cc b/chromium/content/renderer/media/stream/remote_media_stream_track_adapter.cc
index da35517c5e3..72b0c2f9edb 100644
--- a/chromium/content/renderer/media/stream/remote_media_stream_track_adapter.cc
+++ b/chromium/content/renderer/media/stream/remote_media_stream_track_adapter.cc
@@ -92,6 +92,8 @@ void RemoteAudioTrackAdapter::InitializeWebAudioTrack() {
blink::WebMediaStreamSource::Capabilities capabilities;
capabilities.device_id = blink::WebString::FromUTF8(id());
capabilities.echo_cancellation = std::vector<bool>({false});
+ capabilities.auto_gain_control = std::vector<bool>({false});
+ capabilities.noise_suppression = std::vector<bool>({false});
web_track()->Source().SetCapabilities(capabilities);
source->ConnectToTrack(*(web_track()));
diff --git a/chromium/content/renderer/media/stream/remote_media_stream_track_adapter.h b/chromium/content/renderer/media/stream/remote_media_stream_track_adapter.h
index 7cefaae71fd..a7fda93516d 100644
--- a/chromium/content/renderer/media/stream/remote_media_stream_track_adapter.h
+++ b/chromium/content/renderer/media/stream/remote_media_stream_track_adapter.h
@@ -12,8 +12,8 @@
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "base/single_thread_task_runner.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
#include "third_party/webrtc/api/mediastreaminterface.h"
namespace content {
diff --git a/chromium/content/renderer/media/stream/track_audio_renderer.h b/chromium/content/renderer/media/stream/track_audio_renderer.h
index f85eb08921a..358b43e97e9 100644
--- a/chromium/content/renderer/media/stream/track_audio_renderer.h
+++ b/chromium/content/renderer/media/stream/track_audio_renderer.h
@@ -21,7 +21,7 @@
#include "content/public/renderer/media_stream_audio_renderer.h"
#include "content/public/renderer/media_stream_audio_sink.h"
#include "media/base/audio_renderer_sink.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
namespace media {
class AudioBus;
diff --git a/chromium/content/renderer/media/stream/user_media_client_impl.cc b/chromium/content/renderer/media/stream/user_media_client_impl.cc
index 7efc556881e..bee0a486739 100644
--- a/chromium/content/renderer/media/stream/user_media_client_impl.cc
+++ b/chromium/content/renderer/media/stream/user_media_client_impl.cc
@@ -10,25 +10,23 @@
#include <utility>
#include "base/location.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/stringprintf.h"
#include "base/task_runner.h"
-#include "base/threading/sequenced_task_runner_handle.h"
-#include "content/public/renderer/render_frame.h"
#include "content/renderer/media/stream/apply_constraints_processor.h"
#include "content/renderer/media/stream/media_stream_device_observer.h"
#include "content/renderer/media/stream/media_stream_video_track.h"
#include "content/renderer/media/webrtc/peer_connection_tracker.h"
#include "content/renderer/media/webrtc/webrtc_uma_histograms.h"
#include "content/renderer/media/webrtc_logging.h"
+#include "content/renderer/render_frame_impl.h"
#include "content/renderer/render_thread_impl.h"
#include "services/service_manager/public/cpp/interface_provider.h"
-#include "third_party/WebKit/public/platform/WebMediaConstraints.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
-#include "third_party/WebKit/public/web/WebUserMediaRequest.h"
+#include "third_party/blink/public/platform/web_media_constraints.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_user_gesture_indicator.h"
+#include "third_party/blink/public/web/web_user_media_request.h"
namespace content {
namespace {
@@ -87,21 +85,24 @@ UserMediaClientImpl::Request::MoveUserMediaRequest() {
}
UserMediaClientImpl::UserMediaClientImpl(
- RenderFrame* render_frame,
- std::unique_ptr<UserMediaProcessor> user_media_processor)
+ RenderFrameImpl* render_frame,
+ std::unique_ptr<UserMediaProcessor> user_media_processor,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner)
: RenderFrameObserver(render_frame),
user_media_processor_(std::move(user_media_processor)),
apply_constraints_processor_(new ApplyConstraintsProcessor(
base::BindRepeating(&UserMediaClientImpl::GetMediaDevicesDispatcher,
- base::Unretained(this)))),
+ base::Unretained(this)),
+ std::move(task_runner))),
weak_factory_(this) {}
// base::Unretained(this) is safe here because |this| owns
// |user_media_processor_|.
UserMediaClientImpl::UserMediaClientImpl(
- RenderFrame* render_frame,
+ RenderFrameImpl* render_frame,
PeerConnectionDependencyFactory* dependency_factory,
- std::unique_ptr<MediaStreamDeviceObserver> media_stream_device_observer)
+ std::unique_ptr<MediaStreamDeviceObserver> media_stream_device_observer,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner)
: UserMediaClientImpl(
render_frame,
std::make_unique<UserMediaProcessor>(
@@ -110,7 +111,8 @@ UserMediaClientImpl::UserMediaClientImpl(
std::move(media_stream_device_observer),
base::BindRepeating(
&UserMediaClientImpl::GetMediaDevicesDispatcher,
- base::Unretained(this)))) {}
+ base::Unretained(this))),
+ std::move(task_runner)) {}
UserMediaClientImpl::~UserMediaClientImpl() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
@@ -125,7 +127,7 @@ void UserMediaClientImpl::RequestUserMedia(
// Save histogram data so we can see how much GetUserMedia is used.
// The histogram counts the number of calls to the JS API
// webGetUserMedia.
- UpdateWebRTCMethodCount(WEBKIT_GET_USER_MEDIA);
+ UpdateWebRTCMethodCount(blink::WebRTCAPIName::kGetUserMedia);
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(!web_request.IsNull());
DCHECK(web_request.Audio() || web_request.Video());
@@ -217,10 +219,12 @@ void UserMediaClientImpl::CurrentRequestCompleted() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
is_processing_request_ = false;
if (!pending_request_infos_.empty()) {
- base::SequencedTaskRunnerHandle::Get()->PostTask(
- FROM_HERE,
- base::BindOnce(&UserMediaClientImpl::MaybeProcessNextRequestInfo,
- weak_factory_.GetWeakPtr()));
+ render_frame()
+ ->GetTaskRunner(blink::TaskType::kInternalMedia)
+ ->PostTask(
+ FROM_HERE,
+ base::BindOnce(&UserMediaClientImpl::MaybeProcessNextRequestInfo,
+ weak_factory_.GetWeakPtr()));
}
}
diff --git a/chromium/content/renderer/media/stream/user_media_client_impl.h b/chromium/content/renderer/media/stream/user_media_client_impl.h
index aa6ae570dcc..e7b8c3b30fc 100644
--- a/chromium/content/renderer/media/stream/user_media_client_impl.h
+++ b/chromium/content/renderer/media/stream/user_media_client_impl.h
@@ -16,10 +16,10 @@
#include "content/common/media/media_devices.h"
#include "content/public/renderer/render_frame_observer.h"
#include "content/renderer/media/stream/user_media_processor.h"
-#include "third_party/WebKit/public/platform/modules/mediastream/media_devices.mojom.h"
-#include "third_party/WebKit/public/web/WebApplyConstraintsRequest.h"
-#include "third_party/WebKit/public/web/WebUserMediaClient.h"
-#include "third_party/WebKit/public/web/WebUserMediaRequest.h"
+#include "third_party/blink/public/platform/modules/mediastream/media_devices.mojom.h"
+#include "third_party/blink/public/web/web_apply_constraints_request.h"
+#include "third_party/blink/public/web/web_user_media_client.h"
+#include "third_party/blink/public/web/web_user_media_request.h"
namespace content {
@@ -38,11 +38,13 @@ class CONTENT_EXPORT UserMediaClientImpl : public RenderFrameObserver,
// the free store. http://crbug.com/764293
// |render_frame| and |dependency_factory| must outlive this instance.
UserMediaClientImpl(
- RenderFrame* render_frame,
+ RenderFrameImpl* render_frame,
PeerConnectionDependencyFactory* dependency_factory,
- std::unique_ptr<MediaStreamDeviceObserver> media_stream_device_observer);
- UserMediaClientImpl(RenderFrame* render_frame,
- std::unique_ptr<UserMediaProcessor> user_media_processor);
+ std::unique_ptr<MediaStreamDeviceObserver> media_stream_device_observer,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner);
+ UserMediaClientImpl(RenderFrameImpl* render_frame,
+ std::unique_ptr<UserMediaProcessor> user_media_processor,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner);
~UserMediaClientImpl() override;
MediaStreamDeviceObserver* media_stream_device_observer() const {
diff --git a/chromium/content/renderer/media/stream/user_media_client_impl_unittest.cc b/chromium/content/renderer/media/stream/user_media_client_impl_unittest.cc
index 9c51b480c04..c0b5acbd3ec 100644
--- a/chromium/content/renderer/media/stream/user_media_client_impl_unittest.cc
+++ b/chromium/content/renderer/media/stream/user_media_client_impl_unittest.cc
@@ -30,13 +30,13 @@
#include "media/audio/audio_device_description.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebMediaStream.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebVector.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
-#include "third_party/WebKit/public/web/WebHeap.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/web_media_stream.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_vector.h"
+#include "third_party/blink/public/web/web_heap.h"
using testing::_;
@@ -149,7 +149,6 @@ const char kFakeAudioInputDeviceId1[] = "fake_audio_input 1";
const char kFakeAudioInputDeviceId2[] = "fake_audio_input 2";
const char kFakeVideoInputDeviceId1[] = "fake_video_input 1";
const char kFakeVideoInputDeviceId2[] = "fake_video_input 2";
-const char kFakeAudioOutputDeviceId1[] = "fake_audio_output 1";
class MockMediaDevicesDispatcherHost
: public blink::mojom::MediaDevicesDispatcherHost {
@@ -158,25 +157,9 @@ class MockMediaDevicesDispatcherHost
void EnumerateDevices(bool request_audio_input,
bool request_video_input,
bool request_audio_output,
+ bool request_video_input_capabilities,
EnumerateDevicesCallback callback) override {
- std::vector<std::vector<MediaDeviceInfo>> result(NUM_MEDIA_DEVICE_TYPES);
- if (request_audio_input) {
- result[MEDIA_DEVICE_TYPE_AUDIO_INPUT].push_back(MediaDeviceInfo(
- kFakeAudioInputDeviceId1, "Fake Audio Input 1", "fake_group 1"));
- result[MEDIA_DEVICE_TYPE_AUDIO_INPUT].push_back(MediaDeviceInfo(
- kFakeAudioInputDeviceId2, "Fake Audio Input 2", "fake_group 2"));
- }
- if (request_video_input) {
- result[MEDIA_DEVICE_TYPE_VIDEO_INPUT].push_back(
- MediaDeviceInfo(kFakeVideoInputDeviceId1, "Fake Video Input 1", ""));
- result[MEDIA_DEVICE_TYPE_VIDEO_INPUT].push_back(
- MediaDeviceInfo(kFakeVideoInputDeviceId2, "Fake Video Input 2", ""));
- }
- if (request_audio_output) {
- result[MEDIA_DEVICE_TYPE_AUDIO_OUTPUT].push_back(MediaDeviceInfo(
- kFakeAudioOutputDeviceId1, "Fake Audio Input 1", "fake_group 1"));
- }
- std::move(callback).Run(result);
+ NOTREACHED();
}
void GetVideoInputCapabilities(
@@ -184,7 +167,7 @@ class MockMediaDevicesDispatcherHost
blink::mojom::VideoInputDeviceCapabilitiesPtr device =
blink::mojom::VideoInputDeviceCapabilities::New();
device->device_id = kFakeVideoInputDeviceId1;
- device->facing_mode = blink::mojom::FacingMode::USER;
+ device->facing_mode = media::MEDIA_VIDEO_FACING_USER;
if (!video_source_ || !video_source_->IsRunning() ||
!video_source_->GetCurrentFormat()) {
device->formats.push_back(media::VideoCaptureFormat(
@@ -201,7 +184,7 @@ class MockMediaDevicesDispatcherHost
device = blink::mojom::VideoInputDeviceCapabilities::New();
device->device_id = kFakeVideoInputDeviceId2;
- device->facing_mode = blink::mojom::FacingMode::ENVIRONMENT;
+ device->facing_mode = media::MEDIA_VIDEO_FACING_ENVIRONMENT;
device->formats.push_back(media::VideoCaptureFormat(
gfx::Size(640, 480), 30.0f, media::PIXEL_FORMAT_I420));
result.push_back(std::move(device));
@@ -345,8 +328,7 @@ class UserMediaProcessorUnderTest : public UserMediaProcessor {
MediaStreamAudioSource* CreateAudioSource(
const MediaStreamDevice& device,
- const MediaStreamSource::ConstraintsCallback& source_ready,
- bool* has_sw_echo_cancellation) override {
+ const MediaStreamSource::ConstraintsCallback& source_ready) override {
MediaStreamAudioSource* source;
if (create_source_that_fails_) {
class FailedAtLifeAudioSource : public MediaStreamAudioSource {
@@ -372,7 +354,6 @@ class UserMediaProcessorUnderTest : public UserMediaProcessor {
source_ready, source));
}
- *has_sw_echo_cancellation = false;
return source;
}
@@ -413,7 +394,10 @@ class UserMediaClientImplUnderTest : public UserMediaClientImpl {
public:
UserMediaClientImplUnderTest(UserMediaProcessor* user_media_processor,
RequestState* state)
- : UserMediaClientImpl(nullptr, base::WrapUnique(user_media_processor)),
+ : UserMediaClientImpl(
+ nullptr,
+ base::WrapUnique(user_media_processor),
+ blink::scheduler::GetSingleThreadTaskRunnerForTesting()),
state_(state) {}
void RequestUserMediaForTest(
diff --git a/chromium/content/renderer/media/stream/user_media_processor.cc b/chromium/content/renderer/media/stream/user_media_processor.cc
index 77135fb2e04..2a5c2ad894a 100644
--- a/chromium/content/renderer/media/stream/user_media_processor.cc
+++ b/chromium/content/renderer/media/stream/user_media_processor.cc
@@ -11,14 +11,12 @@
#include "base/location.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/stringprintf.h"
#include "base/task_runner.h"
#include "base/task_runner_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/common/media/media_stream_controls.h"
-#include "content/public/renderer/render_frame.h"
#include "content/renderer/media/stream/local_media_stream_audio_source.h"
#include "content/renderer/media/stream/media_stream_audio_processor.h"
#include "content/renderer/media/stream/media_stream_audio_source.h"
@@ -34,14 +32,17 @@
#include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
#include "content/renderer/media/webrtc/webrtc_uma_histograms.h"
#include "content/renderer/media/webrtc_logging.h"
+#include "content/renderer/render_frame_impl.h"
+#include "content/renderer/render_widget.h"
#include "media/base/audio_parameters.h"
#include "media/capture/video_capture_types.h"
#include "services/service_manager/public/cpp/interface_provider.h"
-#include "third_party/WebKit/public/platform/WebMediaConstraints.h"
-#include "third_party/WebKit/public/platform/WebMediaStream.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
-#include "third_party/WebKit/public/platform/WebString.h"
+#include "third_party/blink/public/platform/web_media_constraints.h"
+#include "third_party/blink/public/platform/web_media_stream.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "ui/gfx/geometry/size.h"
#include "url/origin.h"
namespace content {
@@ -96,14 +97,27 @@ bool IsValidVideoContentSource(const std::string& source) {
source == kMediaStreamSourceScreen;
}
-void SurfaceHardwareEchoCancellationSetting(
- blink::WebMediaStreamSource* source) {
+void SurfaceAudioProcessingSettings(blink::WebMediaStreamSource* source) {
MediaStreamAudioSource* source_impl =
static_cast<MediaStreamAudioSource*>(source->GetExtraData());
media::AudioParameters params = source_impl->GetAudioParameters();
- if (params.IsValid() &&
- (params.effects() & media::AudioParameters::ECHO_CANCELLER))
- source->SetEchoCancellation(true);
+ bool hw_echo_cancellation =
+ params.IsValid() &&
+ (params.effects() & media::AudioParameters::ECHO_CANCELLER);
+
+ bool sw_echo_cancellation = false, auto_gain_control = false,
+ noise_supression = false;
+ if (ProcessedLocalAudioSource* processed_source =
+ ProcessedLocalAudioSource::From(source_impl)) {
+ AudioProcessingProperties properties =
+ processed_source->audio_processing_properties();
+ sw_echo_cancellation = properties.enable_sw_echo_cancellation;
+ auto_gain_control = properties.goog_auto_gain_control;
+ noise_supression = properties.goog_noise_suppression;
+ }
+ source->SetAudioProcessingProperties(
+ hw_echo_cancellation || sw_echo_cancellation, auto_gain_control,
+ noise_supression);
}
} // namespace
@@ -183,13 +197,14 @@ class UserMediaProcessor::RequestInfo
video_devices_ = std::move(video_devices);
}
- void AddVideoFormats(const std::string& device_id,
- media::VideoCaptureFormats formats) {
+ void AddNativeVideoFormats(const std::string& device_id,
+ media::VideoCaptureFormats formats) {
video_formats_map_[device_id] = std::move(formats);
}
// Do not store or delete the returned pointer.
- media::VideoCaptureFormats* GetVideoFormats(const std::string& device_id) {
+ media::VideoCaptureFormats* GetNativeVideoFormats(
+ const std::string& device_id) {
auto it = video_formats_map_.find(device_id);
CHECK(it != video_formats_map_.end());
return &it->second;
@@ -342,7 +357,7 @@ void UserMediaProcessor::RequestInfo::OnAudioSourceStarted(
}
UserMediaProcessor::UserMediaProcessor(
- RenderFrame* render_frame,
+ RenderFrameImpl* render_frame,
PeerConnectionDependencyFactory* dependency_factory,
std::unique_ptr<MediaStreamDeviceObserver> media_stream_device_observer,
MediaDevicesDispatcherCallback media_devices_dispatcher_cb)
@@ -557,9 +572,11 @@ void UserMediaProcessor::SelectVideoDeviceSettings(
void UserMediaProcessor::SelectVideoContentSettings() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(current_request_info_);
+ gfx::Size screen_size = GetScreenSize();
VideoCaptureSettings settings = SelectSettingsVideoContentCapture(
current_request_info_->web_request().VideoConstraints(),
- current_request_info_->stream_controls()->video.stream_source);
+ current_request_info_->stream_controls()->video.stream_source,
+ screen_size.width(), screen_size.height());
if (!settings.HasValue()) {
blink::WebString failed_constraint_name =
blink::WebString::FromASCII(settings.failed_constraint_name());
@@ -639,10 +656,13 @@ void UserMediaProcessor::OnStreamGenerated(
}
if (current_request_info_->is_video_content_capture()) {
+ media::VideoCaptureFormat format =
+ current_request_info_->video_capture_settings().Format();
for (const auto& video_device : video_devices) {
- current_request_info_->AddVideoFormats(
+ current_request_info_->AddNativeVideoFormats(
video_device.id,
- {current_request_info_->video_capture_settings().Format()});
+ {media::VideoCaptureFormat(GetScreenSize(), format.frame_rate,
+ format.pixel_format)});
}
StartTracks(label);
return;
@@ -670,11 +690,21 @@ void UserMediaProcessor::GotAllVideoInputFormatsForDevice(
if (!IsCurrentRequestInfo(web_request))
return;
- current_request_info_->AddVideoFormats(device_id, formats);
+ current_request_info_->AddNativeVideoFormats(device_id, formats);
if (current_request_info_->CanStartTracks())
StartTracks(label);
}
+gfx::Size UserMediaProcessor::GetScreenSize() {
+ gfx::Size screen_size(kDefaultScreenCastWidth, kDefaultScreenCastHeight);
+ if (render_frame_) { // Can be null in tests.
+ blink::WebScreenInfo info =
+ render_frame_->GetRenderWidget()->GetScreenInfo();
+ screen_size = gfx::Size(info.rect.width, info.rect.height);
+ }
+ return screen_size;
+}
+
void UserMediaProcessor::OnStreamGeneratedForCancelledRequest(
const MediaStreamDevices& audio_devices,
const MediaStreamDevices& video_devices) {
@@ -780,8 +810,8 @@ blink::WebMediaStreamSource UserMediaProcessor::InitializeVideoSourceObject(
weak_factory_.GetWeakPtr())));
source.SetCapabilities(ComputeCapabilitiesForVideoSource(
blink::WebString::FromUTF8(device.id),
- *current_request_info_->GetVideoFormats(device.id), device.video_facing,
- current_request_info_->is_video_device_capture()));
+ *current_request_info_->GetNativeVideoFormats(device.id),
+ device.video_facing, current_request_info_->is_video_device_capture()));
local_sources_.push_back(source);
}
return source;
@@ -816,34 +846,25 @@ blink::WebMediaStreamSource UserMediaProcessor::InitializeAudioSourceObject(
&UserMediaProcessor::OnAudioSourceStartedOnAudioThread,
base::ThreadTaskRunnerHandle::Get(), weak_factory_.GetWeakPtr());
- bool has_sw_echo_cancellation = false;
MediaStreamAudioSource* const audio_source =
- CreateAudioSource(device, source_ready, &has_sw_echo_cancellation);
+ CreateAudioSource(device, std::move(source_ready));
audio_source->SetStopCallback(base::Bind(
&UserMediaProcessor::OnLocalSourceStopped, weak_factory_.GetWeakPtr()));
- std::vector<bool> echo_cancellation;
- echo_cancellation.push_back(true);
- echo_cancellation.push_back(false);
blink::WebMediaStreamSource::Capabilities capabilities;
- capabilities.echo_cancellation = echo_cancellation;
+ capabilities.echo_cancellation = {true, false};
+ capabilities.auto_gain_control = {true, false};
+ capabilities.noise_suppression = {true, false};
capabilities.device_id = blink::WebString::FromUTF8(device.id);
source.SetExtraData(audio_source); // Takes ownership.
source.SetCapabilities(capabilities);
- // At this point it is known if software echo cancellation will be used, but
- // final audio parameters for the source are not set yet, so it is not yet
- // known if hardware echo cancellation will actually be used. That information
- // is known and surfaced in CreateAudioTracks(), after the track is connected
- // to the source.
- source.SetEchoCancellation(has_sw_echo_cancellation);
return source;
}
MediaStreamAudioSource* UserMediaProcessor::CreateAudioSource(
const MediaStreamDevice& device,
- const MediaStreamSource::ConstraintsCallback& source_ready,
- bool* has_sw_echo_cancellation) {
+ const MediaStreamSource::ConstraintsCallback& source_ready) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(current_request_info_);
@@ -857,7 +878,6 @@ MediaStreamAudioSource* UserMediaProcessor::CreateAudioSource(
if (IsScreenCaptureMediaType(device.type) ||
!MediaStreamAudioProcessor::WouldModifyAudio(
audio_processing_properties)) {
- *has_sw_echo_cancellation = false;
return new LocalMediaStreamAudioSource(
render_frame_->GetRoutingID(), device, stream_controls->hotword_enabled,
stream_controls->disable_local_echo, source_ready);
@@ -865,8 +885,6 @@ MediaStreamAudioSource* UserMediaProcessor::CreateAudioSource(
// The audio device is not associated with screen capture and also requires
// processing.
- *has_sw_echo_cancellation =
- audio_processing_properties.enable_sw_echo_cancellation;
return new ProcessedLocalAudioSource(
render_frame_->GetRoutingID(), device, stream_controls->hotword_enabled,
stream_controls->disable_local_echo, audio_processing_properties,
@@ -947,9 +965,9 @@ void UserMediaProcessor::CreateAudioTracks(
(*webkit_tracks)[i].Initialize(source);
current_request_info_->StartAudioTrack((*webkit_tracks)[i], is_pending);
// At this point the source has started, and its audio parameters have been
- // set. From the parameters, it is known if hardware echo cancellation is
- // being used. If this is the case, let |source| know.
- SurfaceHardwareEchoCancellationSetting(&source);
+ // set. Thus, all audio processing properties are known and can be surfaced
+ // to |source|.
+ SurfaceAudioProcessingSettings(&source);
}
}
diff --git a/chromium/content/renderer/media/stream/user_media_processor.h b/chromium/content/renderer/media/stream/user_media_processor.h
index de3eff05905..5e29c9b9f01 100644
--- a/chromium/content/renderer/media/stream/user_media_processor.h
+++ b/chromium/content/renderer/media/stream/user_media_processor.h
@@ -19,9 +19,13 @@
#include "content/common/media/media_stream.mojom.h"
#include "content/renderer/media/stream/media_stream_dispatcher_eventhandler.h"
#include "content/renderer/media/stream/media_stream_source.h"
-#include "third_party/WebKit/public/platform/WebVector.h"
-#include "third_party/WebKit/public/platform/modules/mediastream/media_devices.mojom.h"
-#include "third_party/WebKit/public/web/WebUserMediaRequest.h"
+#include "third_party/blink/public/platform/modules/mediastream/media_devices.mojom.h"
+#include "third_party/blink/public/platform/web_vector.h"
+#include "third_party/blink/public/web/web_user_media_request.h"
+
+namespace gfx {
+class Size;
+}
namespace blink {
class WebMediaStream;
@@ -38,7 +42,7 @@ class MediaStreamDeviceObserver;
class MediaStreamVideoSource;
class PeerConnectionDependencyFactory;
class VideoCaptureSettings;
-class RenderFrame;
+class RenderFrameImpl;
// TODO(guidou): Add |request_id| and |is_processing_user_gesture| to
// blink::WebUserMediaRequest and remove this struct.
@@ -65,7 +69,7 @@ class CONTENT_EXPORT UserMediaProcessor
const blink::mojom::MediaDevicesDispatcherHostPtr&()>;
// |render_frame| and |dependency_factory| must outlive this instance.
UserMediaProcessor(
- RenderFrame* render_frame,
+ RenderFrameImpl* render_frame,
PeerConnectionDependencyFactory* dependency_factory,
std::unique_ptr<MediaStreamDeviceObserver> media_stream_device_observer,
MediaDevicesDispatcherCallback media_devices_dispatcher_cb);
@@ -127,8 +131,7 @@ class CONTENT_EXPORT UserMediaProcessor
// http://crbug.com/764293
virtual MediaStreamAudioSource* CreateAudioSource(
const MediaStreamDevice& device,
- const MediaStreamSource::ConstraintsCallback& source_ready,
- bool* has_sw_echo_cancellation);
+ const MediaStreamSource::ConstraintsCallback& source_ready);
virtual MediaStreamVideoSource* CreateVideoSource(
const MediaStreamDevice& device,
const MediaStreamSource::SourceStoppedCallback& stop_callback);
@@ -153,6 +156,8 @@ class CONTENT_EXPORT UserMediaProcessor
const std::string& device_id,
const media::VideoCaptureFormats& formats);
+ gfx::Size GetScreenSize();
+
void OnStreamGenerationFailed(int request_id,
MediaStreamRequestResult result);
@@ -293,7 +298,7 @@ class CONTENT_EXPORT UserMediaProcessor
MediaDevicesDispatcherCallback media_devices_dispatcher_cb_;
base::OnceClosure request_completed_cb_;
- RenderFrame* const render_frame_;
+ RenderFrameImpl* const render_frame_;
SEQUENCE_CHECKER(sequence_checker_);
diff --git a/chromium/content/renderer/media/stream/video_track_adapter.cc b/chromium/content/renderer/media/stream/video_track_adapter.cc
index 141f58f1a30..28727ef7b1c 100644
--- a/chromium/content/renderer/media/stream/video_track_adapter.cc
+++ b/chromium/content/renderer/media/stream/video_track_adapter.cc
@@ -430,7 +430,7 @@ void VideoTrackAdapter::AddTrackOnIO(
adapters_.push_back(adapter);
}
- adapter->AddCallback(track, frame_callback);
+ adapter->AddCallback(track, std::move(frame_callback));
}
void VideoTrackAdapter::RemoveTrack(const MediaStreamVideoTrack* track) {
@@ -461,7 +461,7 @@ void VideoTrackAdapter::StartFrameMonitoring(
io_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&VideoTrackAdapter::StartFrameMonitoringOnIO, this,
- bound_on_muted_callback, source_frame_rate));
+ std::move(bound_on_muted_callback), source_frame_rate));
}
void VideoTrackAdapter::StopFrameMonitoring() {
diff --git a/chromium/content/renderer/media/stream/webaudio_media_stream_source.h b/chromium/content/renderer/media/stream/webaudio_media_stream_source.h
index e3940369530..951f8682399 100644
--- a/chromium/content/renderer/media/stream/webaudio_media_stream_source.h
+++ b/chromium/content/renderer/media/stream/webaudio_media_stream_source.h
@@ -11,9 +11,9 @@
#include "content/renderer/media/stream/media_stream_audio_source.h"
#include "media/base/audio_bus.h"
#include "media/base/audio_push_fifo.h"
-#include "third_party/WebKit/public/platform/WebAudioDestinationConsumer.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/WebVector.h"
+#include "third_party/blink/public/platform/web_audio_destination_consumer.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/platform/web_vector.h"
namespace content {
diff --git a/chromium/content/renderer/media/stream/webmediaplayer_ms.cc b/chromium/content/renderer/media/stream/webmediaplayer_ms.cc
index eb9c79435c9..0ded108e9bb 100644
--- a/chromium/content/renderer/media/stream/webmediaplayer_ms.cc
+++ b/chromium/content/renderer/media/stream/webmediaplayer_ms.cc
@@ -12,7 +12,6 @@
#include "base/bind.h"
#include "base/callback.h"
#include "base/threading/thread_task_runner_handle.h"
-#include "build/build_config.h"
#include "cc/blink/web_layer_impl.h"
#include "cc/layers/video_frame_provider_client_impl.h"
#include "cc/layers/video_layer.h"
@@ -37,11 +36,11 @@
#include "media/blink/webmediaplayer_util.h"
#include "media/video/gpu_memory_buffer_video_frame_pool.h"
#include "services/ui/public/cpp/gpu/context_provider_command_buffer.h"
-#include "third_party/WebKit/public/platform/WebMediaPlayerClient.h"
-#include "third_party/WebKit/public/platform/WebMediaPlayerSource.h"
-#include "third_party/WebKit/public/platform/WebRect.h"
-#include "third_party/WebKit/public/platform/WebSize.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "third_party/blink/public/platform/web_media_player_client.h"
+#include "third_party/blink/public/platform/web_media_player_source.h"
+#include "third_party/blink/public/platform/web_rect.h"
+#include "third_party/blink/public/platform/web_size.h"
+#include "third_party/blink/public/web/web_local_frame.h"
namespace {
enum class RendererReloadAction {
@@ -49,10 +48,21 @@ enum class RendererReloadAction {
REMOVE_RENDERER,
NEW_RENDERER
};
+
} // namespace
namespace content {
+#if defined(OS_WIN)
+// Since we do not have native GMB support in Windows, using GMBs can cause a
+// CPU regression. This is more apparent and can have adverse affects in lower
+// resolution content which are defined by these thresholds, see
+// https://crbug.com/835752.
+// static
+const gfx::Size WebMediaPlayerMS::kUseGpuMemoryBufferVideoFramesMinResolution =
+ gfx::Size(1920, 1080);
+#endif // defined(OS_WIN)
+
// FrameDeliverer is responsible for delivering frames received on
// the IO thread by calling of EnqueueFrame() method of |compositor_|.
//
@@ -72,6 +82,7 @@ class WebMediaPlayerMS::FrameDeliverer {
player_(player),
enqueue_frame_cb_(enqueue_frame_cb),
media_task_runner_(media_task_runner),
+ weak_factory_for_pool_(this),
weak_factory_(this) {
io_thread_checker_.DetachFromThread();
@@ -87,6 +98,7 @@ class WebMediaPlayerMS::FrameDeliverer {
~FrameDeliverer() {
DCHECK(io_thread_checker_.CalledOnValidThread());
if (gpu_memory_buffer_pool_) {
+ DropCurrentPoolTasks();
media_task_runner_->DeleteSoon(FROM_HERE,
gpu_memory_buffer_pool_.release());
}
@@ -95,38 +107,76 @@ class WebMediaPlayerMS::FrameDeliverer {
void OnVideoFrame(scoped_refptr<media::VideoFrame> frame) {
DCHECK(io_thread_checker_.CalledOnValidThread());
+// On Android, stop passing frames.
#if defined(OS_ANDROID)
if (render_frame_suspended_)
return;
#endif // defined(OS_ANDROID)
if (!gpu_memory_buffer_pool_) {
- FrameReady(frame);
+ EnqueueFrame(std::move(frame));
return;
}
- // |gpu_memory_buffer_pool_| deletion is going to be posted to
- // |media_task_runner_|. base::Unretained() usage is fine since
- // |gpu_memory_buffer_pool_| outlives the task.
+#if defined(OS_WIN)
+ const bool skip_creating_gpu_memory_buffer =
+ frame->visible_rect().width() <
+ kUseGpuMemoryBufferVideoFramesMinResolution.width() ||
+ frame->visible_rect().height() <
+ kUseGpuMemoryBufferVideoFramesMinResolution.height();
+#else
+ const bool skip_creating_gpu_memory_buffer = false;
+#endif // defined(OS_WIN)
+
+ // If |render_frame_suspended_|, we can keep passing the frames to keep the
+ // latest frame in compositor up to date. However, creating GMB backed
+ // frames is unnecessary, because the frames are not going to be shown for
+ // the time period.
+ if (render_frame_suspended_ || skip_creating_gpu_memory_buffer) {
+ EnqueueFrame(std::move(frame));
+ // If there are any existing MaybeCreateHardwareFrame() calls, we do not
+ // want those frames to be placed after the current one, so just drop
+ // them.
+ DropCurrentPoolTasks();
+ return;
+ }
+
+ // |gpu_memory_buffer_pool_| deletion is going to be posted to
+ // |media_task_runner_|. base::Unretained() usage is fine since
+ // |gpu_memory_buffer_pool_| outlives the task.
media_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(
&media::GpuMemoryBufferVideoFramePool::MaybeCreateHardwareFrame,
base::Unretained(gpu_memory_buffer_pool_.get()), frame,
- media::BindToCurrentLoop(base::BindRepeating(
- &FrameDeliverer::FrameReady, weak_factory_.GetWeakPtr()))));
+ media::BindToCurrentLoop(
+ base::BindOnce(&FrameDeliverer::EnqueueFrame,
+ weak_factory_for_pool_.GetWeakPtr()))));
+ }
+
+ void SetRenderFrameSuspended(bool render_frame_suspended) {
+ DCHECK(io_thread_checker_.CalledOnValidThread());
+ render_frame_suspended_ = render_frame_suspended;
+ }
+
+ MediaStreamVideoRenderer::RepaintCB GetRepaintCallback() {
+ return base::Bind(&FrameDeliverer::OnVideoFrame,
+ weak_factory_.GetWeakPtr());
}
- void FrameReady(const scoped_refptr<media::VideoFrame>& frame) {
+ private:
+ friend class WebMediaPlayerMS;
+
+ void EnqueueFrame(const scoped_refptr<media::VideoFrame>& frame) {
DCHECK(io_thread_checker_.CalledOnValidThread());
base::TimeTicks render_time;
if (frame->metadata()->GetTimeTicks(
media::VideoFrameMetadata::REFERENCE_TIME, &render_time)) {
- TRACE_EVENT1("webmediaplayerms", "FrameReady", "Ideal Render Instant",
+ TRACE_EVENT1("media", "EnqueueFrame", "Ideal Render Instant",
render_time.ToInternalValue());
} else {
- TRACE_EVENT0("webmediaplayerms", "FrameReady");
+ TRACE_EVENT0("media", "EnqueueFrame");
}
const bool is_opaque = media::IsOpaque(frame->format());
@@ -159,28 +209,27 @@ class WebMediaPlayerMS::FrameDeliverer {
enqueue_frame_cb_.Run(frame);
}
-#if defined(OS_ANDROID)
- void SetRenderFrameSuspended(bool render_frame_suspended) {
+ void DropCurrentPoolTasks() {
DCHECK(io_thread_checker_.CalledOnValidThread());
- render_frame_suspended_ = render_frame_suspended;
- }
-#endif // defined(OS_ANDROID)
+ DCHECK(gpu_memory_buffer_pool_);
- MediaStreamVideoRenderer::RepaintCB GetRepaintCallback() {
- return base::Bind(&FrameDeliverer::OnVideoFrame,
- weak_factory_.GetWeakPtr());
- }
+ if (!weak_factory_for_pool_.HasWeakPtrs())
+ return;
- private:
- friend class WebMediaPlayerMS;
+ // |gpu_memory_buffer_pool_| deletion is going to be posted to
+ // |media_task_runner_|. base::Unretained() usage is fine since
+ // |gpu_memory_buffer_pool_| outlives the task.
+ media_task_runner_->PostTask(
+ FROM_HERE,
+ base::BindOnce(&media::GpuMemoryBufferVideoFramePool::Abort,
+ base::Unretained(gpu_memory_buffer_pool_.get())));
+ weak_factory_for_pool_.InvalidateWeakPtrs();
+ }
bool last_frame_opaque_;
media::VideoRotation last_frame_rotation_;
bool received_first_frame_;
-
-#if defined(OS_ANDROID)
bool render_frame_suspended_ = false;
-#endif // defined(OS_ANDROID)
const scoped_refptr<base::SingleThreadTaskRunner> main_task_runner_;
const base::WeakPtr<WebMediaPlayerMS> player_;
@@ -193,6 +242,7 @@ class WebMediaPlayerMS::FrameDeliverer {
// Used for DCHECKs to ensure method calls are executed on the correct thread.
base::ThreadChecker io_thread_checker_;
+ base::WeakPtrFactory<FrameDeliverer> weak_factory_for_pool_;
base::WeakPtrFactory<FrameDeliverer> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(FrameDeliverer);
@@ -554,6 +604,12 @@ void WebMediaPlayerMS::EnterPictureInPicture() {
// WebMediaPlayerMS. See http://crbug/746182.
}
+void WebMediaPlayerMS::ExitPictureInPicture() {
+ NOTIMPLEMENTED();
+ // TODO(apacible): Implement after video in surfaces is supported for
+ // WebMediaPlayerMS. See http://crbug/746182.
+}
+
void WebMediaPlayerMS::SetSinkId(
const blink::WebString& sink_id,
const blink::WebSecurityOrigin& security_origin,
@@ -736,27 +792,29 @@ size_t WebMediaPlayerMS::VideoDecodedByteCount() const {
}
void WebMediaPlayerMS::OnFrameHidden() {
-#if defined(OS_ANDROID)
DCHECK(thread_checker_.CalledOnValidThread());
-
- // Method called when the RenderFrame is sent to background and suspended
- // (android). Substitute the displayed VideoFrame with a copy to avoid
- // holding on to it unnecessarily.
- //
- // During undoable tab closures OnHidden() may be called back to back, so we
- // can't rely on |render_frame_suspended_| being false here.
+ // This method is called when the RenderFrame is sent to background or
+ // suspended. During undoable tab closures OnHidden() may be called back to
+ // back, so we can't rely on |render_frame_suspended_| being false here.
if (frame_deliverer_) {
io_task_runner_->PostTask(
- FROM_HERE, base::Bind(&FrameDeliverer::SetRenderFrameSuspended,
- base::Unretained(frame_deliverer_.get()), true));
+ FROM_HERE,
+ base::BindOnce(&FrameDeliverer::SetRenderFrameSuspended,
+ base::Unretained(frame_deliverer_.get()), true));
}
+// On Android, substitute the displayed VideoFrame with a copy to avoid holding
+// onto it unnecessarily.
+#if defined(OS_ANDROID)
if (!paused_)
compositor_->ReplaceCurrentFrameWithACopy();
#endif // defined(OS_ANDROID)
}
void WebMediaPlayerMS::OnFrameClosed() {
+ DCHECK(thread_checker_.CalledOnValidThread());
+
+// On Android, pause the video completely for this time period.
#if defined(OS_ANDROID)
if (!paused_) {
Pause();
@@ -764,26 +822,29 @@ void WebMediaPlayerMS::OnFrameClosed() {
}
delegate_->PlayerGone(delegate_id_);
+#endif // defined(OS_ANDROID)
if (frame_deliverer_) {
io_task_runner_->PostTask(
- FROM_HERE, base::Bind(&FrameDeliverer::SetRenderFrameSuspended,
- base::Unretained(frame_deliverer_.get()), true));
+ FROM_HERE,
+ base::BindOnce(&FrameDeliverer::SetRenderFrameSuspended,
+ base::Unretained(frame_deliverer_.get()), true));
}
-#endif // defined(OS_ANDROID)
}
void WebMediaPlayerMS::OnFrameShown() {
-#if defined(OS_ANDROID)
DCHECK(thread_checker_.CalledOnValidThread());
if (frame_deliverer_) {
io_task_runner_->PostTask(
- FROM_HERE, base::Bind(&FrameDeliverer::SetRenderFrameSuspended,
- base::Unretained(frame_deliverer_.get()), false));
+ FROM_HERE,
+ base::BindOnce(&FrameDeliverer::SetRenderFrameSuspended,
+ base::Unretained(frame_deliverer_.get()), false));
}
- // Resume playback on visibility. play() clears |should_play_upon_shown_|.
+// On Android, resume playback on visibility. play() clears
+// |should_play_upon_shown_|.
+#if defined(OS_ANDROID)
if (should_play_upon_shown_)
Play();
#endif // defined(OS_ANDROID)
@@ -829,7 +890,7 @@ bool WebMediaPlayerMS::CopyVideoTextureToPlatformTexture(
bool flip_y,
int already_uploaded_id,
VideoFrameUploadMetadata* out_metadata) {
- TRACE_EVENT0("webmediaplayerms", "copyVideoTextureToPlatformTexture");
+ TRACE_EVENT0("media", "copyVideoTextureToPlatformTexture");
DCHECK(thread_checker_.CalledOnValidThread());
scoped_refptr<media::VideoFrame> video_frame =
@@ -864,7 +925,7 @@ bool WebMediaPlayerMS::TexImageImpl(TexImageFunctionID functionID,
int zoffset,
bool flip_y,
bool premultiply_alpha) {
- TRACE_EVENT0("webmediaplayerms", "texImageImpl");
+ TRACE_EVENT0("media", "texImageImpl");
DCHECK(thread_checker_.CalledOnValidThread());
const scoped_refptr<media::VideoFrame> video_frame =
diff --git a/chromium/content/renderer/media/stream/webmediaplayer_ms.h b/chromium/content/renderer/media/stream/webmediaplayer_ms.h
index b2770e2880b..00274face0d 100644
--- a/chromium/content/renderer/media/stream/webmediaplayer_ms.h
+++ b/chromium/content/renderer/media/stream/webmediaplayer_ms.h
@@ -13,13 +13,14 @@
#include "base/single_thread_task_runner.h"
#include "base/synchronization/lock.h"
#include "base/threading/thread_checker.h"
+#include "build/build_config.h"
#include "content/common/content_export.h"
#include "media/blink/webmediaplayer_delegate.h"
#include "media/blink/webmediaplayer_util.h"
#include "media/renderers/paint_canvas_video_renderer.h"
#include "media/video/gpu_video_accelerator_factories.h"
-#include "third_party/WebKit/public/platform/WebMediaPlayer.h"
-#include "third_party/WebKit/public/platform/WebMediaStream.h"
+#include "third_party/blink/public/platform/web_media_player.h"
+#include "third_party/blink/public/platform/web_media_stream.h"
#include "url/origin.h"
namespace blink {
@@ -99,6 +100,7 @@ class CONTENT_EXPORT WebMediaPlayerMS
void SetRate(double rate) override;
void SetVolume(double volume) override;
void EnterPictureInPicture() override;
+ void ExitPictureInPicture() override;
void SetSinkId(const blink::WebString& sink_id,
const blink::WebSecurityOrigin& security_origin,
blink::WebSetSinkIdCallbacks* web_callback) override;
@@ -197,6 +199,10 @@ class CONTENT_EXPORT WebMediaPlayerMS
private:
friend class WebMediaPlayerMSTest;
+#if defined(OS_WIN)
+ static const gfx::Size kUseGpuMemoryBufferVideoFramesMinResolution;
+#endif // defined(OS_WIN)
+
void OnFirstFrameReceived(media::VideoRotation video_rotation,
bool is_opaque);
void OnOpacityChanged(bool is_opaque);
diff --git a/chromium/content/renderer/media/stream/webmediaplayer_ms_compositor.cc b/chromium/content/renderer/media/stream/webmediaplayer_ms_compositor.cc
index e8e8d6f7093..148ba05ca54 100644
--- a/chromium/content/renderer/media/stream/webmediaplayer_ms_compositor.cc
+++ b/chromium/content/renderer/media/stream/webmediaplayer_ms_compositor.cc
@@ -6,6 +6,7 @@
#include <stdint.h>
#include <string>
+#include <utility>
#include "base/command_line.h"
#include "base/hash.h"
@@ -22,9 +23,9 @@
#include "media/renderers/paint_canvas_video_renderer.h"
#include "services/ui/public/cpp/gpu/context_provider_command_buffer.h"
#include "skia/ext/platform_canvas.h"
-#include "third_party/WebKit/public/platform/WebMediaStream.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
+#include "third_party/blink/public/platform/web_media_stream.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
#include "third_party/libyuv/include/libyuv/convert.h"
#include "third_party/libyuv/include/libyuv/planar_functions.h"
#include "third_party/libyuv/include/libyuv/video_common.h"
@@ -137,7 +138,8 @@ WebMediaPlayerMSCompositor::WebMediaPlayerMSCompositor(
last_render_length_(base::TimeDelta::FromSecondsD(1.0 / 60.0)),
total_frame_count_(0),
dropped_frame_count_(0),
- stopped_(true) {
+ stopped_(true),
+ render_started_(!stopped_) {
main_message_loop_ = base::MessageLoop::current();
blink::WebVector<blink::WebMediaStreamTrack> video_tracks;
@@ -209,6 +211,9 @@ void WebMediaPlayerMSCompositor::EnqueueFrame(
scoped_refptr<media::VideoFrame> frame) {
DCHECK(io_task_runner_->BelongsToCurrentThread());
base::AutoLock auto_lock(current_frame_lock_);
+ TRACE_EVENT_INSTANT1("media", "WebMediaPlayerMSCompositor::EnqueueFrame",
+ TRACE_EVENT_SCOPE_THREAD, "Timestamp",
+ frame->timestamp().InMicroseconds());
++total_frame_count_;
// With algorithm off, just let |current_frame_| hold the incoming |frame|.
@@ -267,9 +272,9 @@ bool WebMediaPlayerMSCompositor::UpdateCurrentFrame(
base::TimeTicks deadline_max) {
DCHECK(compositor_task_runner_->BelongsToCurrentThread());
- TRACE_EVENT_BEGIN2("webmediaplayerms", "UpdateCurrentFrame",
- "Actual Render Begin", deadline_min.ToInternalValue(),
- "Actual Render End", deadline_max.ToInternalValue());
+ TRACE_EVENT_BEGIN2("media", "UpdateCurrentFrame", "Actual Render Begin",
+ deadline_min.ToInternalValue(), "Actual Render End",
+ deadline_max.ToInternalValue());
if (stopped_)
return false;
@@ -287,9 +292,8 @@ bool WebMediaPlayerMSCompositor::UpdateCurrentFrame(
"sophisticated video rendering algorithm.";
}
- TRACE_EVENT_END2("webmediaplayerms", "UpdateCurrentFrame",
- "Ideal Render Instant", render_time.ToInternalValue(),
- "Serial", serial_);
+ TRACE_EVENT_END2("media", "UpdateCurrentFrame", "Ideal Render Instant",
+ render_time.ToInternalValue(), "Serial", serial_);
return !current_frame_used_by_compositor_;
}
@@ -302,6 +306,12 @@ bool WebMediaPlayerMSCompositor::HasCurrentFrame() {
scoped_refptr<media::VideoFrame> WebMediaPlayerMSCompositor::GetCurrentFrame() {
DVLOG(3) << __func__;
base::AutoLock auto_lock(current_frame_lock_);
+ TRACE_EVENT_INSTANT1("media", "WebMediaPlayerMSCompositor::GetCurrentFrame",
+ TRACE_EVENT_SCOPE_THREAD, "Timestamp",
+ current_frame_->timestamp().InMicroseconds());
+ if (!render_started_)
+ return nullptr;
+
current_frame_used_by_compositor_ = true;
return current_frame_;
}
@@ -314,11 +324,18 @@ scoped_refptr<media::VideoFrame>
WebMediaPlayerMSCompositor::GetCurrentFrameWithoutUpdatingStatistics() {
DVLOG(3) << __func__;
base::AutoLock auto_lock(current_frame_lock_);
+ if (!render_started_)
+ return nullptr;
+
return current_frame_;
}
void WebMediaPlayerMSCompositor::StartRendering() {
DCHECK(thread_checker_.CalledOnValidThread());
+ {
+ base::AutoLock auto_lock(current_frame_lock_);
+ render_started_ = true;
+ }
compositor_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&WebMediaPlayerMSCompositor::StartRenderingInternal,
@@ -397,6 +414,9 @@ void WebMediaPlayerMSCompositor::Render(base::TimeTicks deadline_min,
void WebMediaPlayerMSCompositor::SetCurrentFrame(
const scoped_refptr<media::VideoFrame>& frame) {
current_frame_lock_.AssertAcquired();
+ TRACE_EVENT_INSTANT1("media", "WebMediaPlayerMSCompositor::SetCurrentFrame",
+ TRACE_EVENT_SCOPE_THREAD, "Timestamp",
+ frame->timestamp().InMicroseconds());
if (!current_frame_used_by_compositor_)
++dropped_frame_count_;
diff --git a/chromium/content/renderer/media/stream/webmediaplayer_ms_compositor.h b/chromium/content/renderer/media/stream/webmediaplayer_ms_compositor.h
index a76eedf58bf..fc0b4980c22 100644
--- a/chromium/content/renderer/media/stream/webmediaplayer_ms_compositor.h
+++ b/chromium/content/renderer/media/stream/webmediaplayer_ms_compositor.h
@@ -166,11 +166,12 @@ class CONTENT_EXPORT WebMediaPlayerMSCompositor
size_t dropped_frame_count_;
bool stopped_;
+ bool render_started_;
std::map<base::TimeDelta, base::TimeTicks> timestamps_to_clock_times_;
// |current_frame_lock_| protects |current_frame_used_by_compositor_|,
- // |current_frame_|, and |rendering_frame_buffer_|.
+ // |current_frame_|, |rendering_frame_buffer_|, and |render_started_|.
base::Lock current_frame_lock_;
DISALLOW_COPY_AND_ASSIGN(WebMediaPlayerMSCompositor);
diff --git a/chromium/content/renderer/media/stream/webmediaplayer_ms_unittest.cc b/chromium/content/renderer/media/stream/webmediaplayer_ms_unittest.cc
index e5f00a6488d..9ee03566248 100644
--- a/chromium/content/renderer/media/stream/webmediaplayer_ms_unittest.cc
+++ b/chromium/content/renderer/media/stream/webmediaplayer_ms_unittest.cc
@@ -8,6 +8,7 @@
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
+#include "build/build_config.h"
#include "content/public/renderer/media_stream_renderer_factory.h"
#include "content/renderer/media/stream/webmediaplayer_ms.h"
#include "content/renderer/media/stream/webmediaplayer_ms_compositor.h"
@@ -16,11 +17,11 @@
#include "media/base/video_frame.h"
#include "media/video/mock_gpu_memory_buffer_video_frame_pool.h"
#include "media/video/mock_gpu_video_accelerator_factories.h"
-#include "third_party/WebKit/public/platform/WebFullscreenVideoStatus.h"
-#include "third_party/WebKit/public/platform/WebLayer.h"
-#include "third_party/WebKit/public/platform/WebMediaPlayer.h"
-#include "third_party/WebKit/public/platform/WebMediaPlayerClient.h"
-#include "third_party/WebKit/public/platform/WebMediaPlayerSource.h"
+#include "third_party/blink/public/platform/web_fullscreen_video_status.h"
+#include "third_party/blink/public/platform/web_layer.h"
+#include "third_party/blink/public/platform/web_media_player.h"
+#include "third_party/blink/public/platform/web_media_player_client.h"
+#include "third_party/blink/public/platform/web_media_player_source.h"
namespace content {
@@ -72,6 +73,14 @@ class FakeWebMediaPlayerDelegate
EXPECT_EQ(delegate_id_, delegate_id);
}
+ void DidPictureInPictureSourceChange(int delegate_id) override {
+ EXPECT_EQ(delegate_id_, delegate_id);
+ }
+
+ void DidPictureInPictureModeEnd(int delegate_id) override {
+ EXPECT_EQ(delegate_id_, delegate_id);
+ }
+
void DidPause(int delegate_id) override {
EXPECT_EQ(delegate_id_, delegate_id);
EXPECT_TRUE(playing_);
@@ -163,6 +172,7 @@ class MockMediaStreamVideoRenderer : public MediaStreamVideoRenderer {
const base::Closure& error_cb,
const MediaStreamVideoRenderer::RepaintCB& repaint_cb)
: started_(false),
+ standard_size_(kStandardWidth, kStandardHeight),
task_runner_(task_runner),
message_loop_controller_(message_loop_controller),
error_cb_(error_cb),
@@ -185,6 +195,9 @@ class MockMediaStreamVideoRenderer : public MediaStreamVideoRenderer {
bool Started() { return started_; }
bool Paused() { return paused_; }
+ void set_standard_size(const gfx::Size& size) { standard_size_ = size; }
+ const gfx::Size& get_standard_size() { return standard_size_; }
+
private:
~MockMediaStreamVideoRenderer() override {}
@@ -197,6 +210,7 @@ class MockMediaStreamVideoRenderer : public MediaStreamVideoRenderer {
bool started_;
bool paused_;
+ gfx::Size standard_size_;
const scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
ReusableMessageLoopEvent* const message_loop_controller_;
@@ -238,8 +252,8 @@ void MockMediaStreamVideoRenderer::Start() {
started_ = true;
paused_ = false;
task_runner_->PostTask(
- FROM_HERE, base::BindOnce(&MockMediaStreamVideoRenderer::InjectFrame,
- base::Unretained(this)));
+ FROM_HERE,
+ base::BindOnce(&MockMediaStreamVideoRenderer::InjectFrame, this));
}
void MockMediaStreamVideoRenderer::Stop() {
@@ -269,11 +283,12 @@ void MockMediaStreamVideoRenderer::QueueFrames(
bool odd_size_frame,
int double_size_index,
media::VideoRotation rotation) {
- gfx::Size standard_size = gfx::Size(kStandardWidth, kStandardHeight);
+ gfx::Size standard_size = standard_size_;
for (size_t i = 0; i < timestamp_or_frame_type.size(); i++) {
const int token = timestamp_or_frame_type[i];
if (static_cast<int>(i) == double_size_index) {
- standard_size = gfx::Size(kStandardWidth * 2, kStandardHeight * 2);
+ standard_size =
+ gfx::Size(standard_size_.width() * 2, standard_size_.height() * 2);
}
if (token < static_cast<int>(FrameType::MIN_TYPE)) {
CHECK(false) << "Unrecognized frame type: " << token;
@@ -347,8 +362,7 @@ void MockMediaStreamVideoRenderer::InjectFrame() {
task_runner_->PostDelayedTask(
FROM_HERE,
- base::BindOnce(&MockMediaStreamVideoRenderer::InjectFrame,
- base::Unretained(this)),
+ base::BindOnce(&MockMediaStreamVideoRenderer::InjectFrame, this),
delay_till_next_generated_frame_);
// This will pause the |message_loop_|, and the purpose is to allow the main
@@ -543,6 +557,11 @@ class WebMediaPlayerMSTest
}
void SetGpuMemoryBufferVideoForTesting() {
+#if defined(OS_WIN)
+ render_factory_->provider()->set_standard_size(
+ WebMediaPlayerMS::kUseGpuMemoryBufferVideoFramesMinResolution);
+#endif // defined(OS_WIN)
+
player_->SetGpuMemoryBufferVideoForTesting(
new media::MockGpuMemoryBufferVideoFramePool(&frame_ready_cbs_));
}
@@ -556,6 +575,7 @@ class WebMediaPlayerMSTest
void(blink::WebMediaPlayer::NetworkState));
MOCK_METHOD1(DoReadyStateChanged, void(blink::WebMediaPlayer::ReadyState));
MOCK_METHOD1(CheckSizeChanged, void(gfx::Size));
+ MOCK_CONST_METHOD0(CouldPlayIfEnoughData, bool());
base::MessageLoop message_loop_;
MockRenderFactory* render_factory_;
@@ -1077,8 +1097,7 @@ TEST_F(WebMediaPlayerMSTest, CreateHardwareFrames) {
blink::WebMediaPlayer::kReadyStateHaveMetadata));
EXPECT_CALL(*this, DoReadyStateChanged(
blink::WebMediaPlayer::kReadyStateHaveEnoughData));
- EXPECT_CALL(*this,
- CheckSizeChanged(gfx::Size(kStandardWidth, kStandardHeight)));
+ EXPECT_CALL(*this, CheckSizeChanged(provider->get_standard_size()));
std::move(frame_ready_cbs_[0]).Run();
message_loop_controller_.RunAndWaitForStatus(
media::PipelineStatus::PIPELINE_OK);
@@ -1091,6 +1110,66 @@ TEST_F(WebMediaPlayerMSTest, CreateHardwareFrames) {
EXPECT_CALL(*this, DoStopRendering());
}
+// Hidden and closed trigger different events on Android and this test doesn't
+// cover that, see HiddenPlayerTests for specifics.
+#if !defined(OS_ANDROID)
+// Tests that GpuMemoryBufferVideoFramePool is not called when page is hidden.
+TEST_F(WebMediaPlayerMSTest, StopsCreatingHardwareFramesWhenHiddenOrClosed) {
+ MockMediaStreamVideoRenderer* provider = LoadAndGetFrameProvider(true);
+ SetGpuMemoryBufferVideoForTesting();
+
+ const int kTestBrake = static_cast<int>(FrameType::TEST_BRAKE);
+ static int tokens[] = {0, kTestBrake};
+ std::vector<int> timestamps(tokens, tokens + sizeof(tokens) / sizeof(int));
+ provider->QueueFrames(timestamps);
+ EXPECT_CALL(*this, DoSetWebLayer(true));
+ EXPECT_CALL(*this, DoStartRendering());
+ EXPECT_CALL(*this, DoReadyStateChanged(
+ blink::WebMediaPlayer::kReadyStateHaveMetadata));
+ EXPECT_CALL(*this, DoReadyStateChanged(
+ blink::WebMediaPlayer::kReadyStateHaveEnoughData));
+ EXPECT_CALL(*this, CheckSizeChanged(provider->get_standard_size()));
+ message_loop_controller_.RunAndWaitForStatus(
+ media::PipelineStatus::PIPELINE_OK);
+ ASSERT_EQ(1u, frame_ready_cbs_.size());
+ frame_ready_cbs_.clear();
+
+ // Hidden should stop passing frames to GpuMemoryBufferVideoFramePool.
+ player_->OnFrameHidden();
+ provider->QueueFrames(timestamps, false);
+ message_loop_controller_.RunAndWaitForStatus(
+ media::PipelineStatus::PIPELINE_OK);
+ ASSERT_EQ(0u, frame_ready_cbs_.size());
+
+ // Shown should resume passing frames to GpuMemoryBufferVideoFramePool.
+ player_->OnFrameShown();
+ provider->QueueFrames(timestamps, false);
+ message_loop_controller_.RunAndWaitForStatus(
+ media::PipelineStatus::PIPELINE_OK);
+ ASSERT_EQ(1u, frame_ready_cbs_.size());
+ frame_ready_cbs_.clear();
+
+ // Hidden should stop passing frames to GpuMemoryBufferVideoFramePool.
+ player_->OnFrameClosed();
+ provider->QueueFrames(timestamps, false);
+ message_loop_controller_.RunAndWaitForStatus(
+ media::PipelineStatus::PIPELINE_OK);
+ ASSERT_EQ(0u, frame_ready_cbs_.size());
+
+ // Shown should resume passing frames to GpuMemoryBufferVideoFramePool.
+ player_->OnFrameShown();
+ provider->QueueFrames(timestamps, false);
+ message_loop_controller_.RunAndWaitForStatus(
+ media::PipelineStatus::PIPELINE_OK);
+ ASSERT_EQ(1u, frame_ready_cbs_.size());
+
+ testing::Mock::VerifyAndClearExpectations(this);
+
+ EXPECT_CALL(*this, DoSetWebLayer(false));
+ EXPECT_CALL(*this, DoStopRendering());
+}
+#endif // !defined(OS_ANDROID)
+
#if defined(OS_ANDROID)
TEST_F(WebMediaPlayerMSTest, HiddenPlayerTests) {
LoadAndGetFrameProvider(true);
diff --git a/chromium/content/renderer/media/video_capture_impl.cc b/chromium/content/renderer/media/video_capture_impl.cc
index e411ea8ab4e..30f013e2805 100644
--- a/chromium/content/renderer/media/video_capture_impl.cc
+++ b/chromium/content/renderer/media/video_capture_impl.cc
@@ -288,7 +288,7 @@ void VideoCaptureImpl::OnBufferReady(int32_t buffer_id,
base::TimeTicks reference_time;
media::VideoFrameMetadata frame_metadata;
- frame_metadata.MergeInternalValuesFrom(*info->metadata);
+ frame_metadata.MergeInternalValuesFrom(info->metadata);
const bool success = frame_metadata.GetTimeTicks(
media::VideoFrameMetadata::REFERENCE_TIME, &reference_time);
DCHECK(success);
@@ -332,7 +332,7 @@ void VideoCaptureImpl::OnBufferReady(int32_t buffer_id,
&VideoCaptureImpl::OnClientBufferFinished, weak_factory_.GetWeakPtr(),
buffer_id, std::move(buffer)))));
- frame->metadata()->MergeInternalValuesFrom(*info->metadata);
+ frame->metadata()->MergeInternalValuesFrom(info->metadata);
// TODO(qiangchen): Dive into the full code path to let frame metadata hold
// reference time rather than using an extra parameter.
diff --git a/chromium/content/renderer/media/video_capture_impl.h b/chromium/content/renderer/media/video_capture_impl.h
index eef1ecc540b..be95e4c275a 100644
--- a/chromium/content/renderer/media/video_capture_impl.h
+++ b/chromium/content/renderer/media/video_capture_impl.h
@@ -16,7 +16,7 @@
#include "content/common/content_export.h"
#include "content/common/media/video_capture.h"
#include "media/base/video_frame.h"
-#include "media/capture/mojo/video_capture.mojom.h"
+#include "media/capture/mojom/video_capture.mojom.h"
#include "media/capture/video_capture_types.h"
#include "mojo/public/cpp/bindings/binding.h"
diff --git a/chromium/content/renderer/media/video_capture_impl_manager_unittest.cc b/chromium/content/renderer/media/video_capture_impl_manager_unittest.cc
index fbd62cd3982..f5f3e612b07 100644
--- a/chromium/content/renderer/media/video_capture_impl_manager_unittest.cc
+++ b/chromium/content/renderer/media/video_capture_impl_manager_unittest.cc
@@ -7,7 +7,6 @@
#include "base/bind.h"
#include "base/callback.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/run_loop.h"
#include "base/test/scoped_task_environment.h"
@@ -15,7 +14,7 @@
#include "content/renderer/media/video_capture_impl.h"
#include "content/renderer/media/video_capture_impl_manager.h"
#include "media/base/bind_to_current_loop.h"
-#include "media/capture/mojo/video_capture.mojom.h"
+#include "media/capture/mojom/video_capture.mojom.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -149,7 +148,8 @@ class VideoCaptureImplManagerTest : public ::testing::Test,
.Times(kNumClients - 1)
.RetiresOnSaturation();
}
- EXPECT_CALL(*this, OnStarted(_)).WillOnce(RunClosure(quit_closure))
+ EXPECT_CALL(*this, OnStarted(_))
+ .WillOnce(RunClosure(std::move(quit_closure)))
.RetiresOnSaturation();
std::array<base::Closure, kNumClients> stop_callbacks;
media::VideoCaptureParams params;
@@ -170,7 +170,8 @@ class VideoCaptureImplManagerTest : public ::testing::Test,
base::Closure quit_closure = BindToCurrentLoop(run_loop.QuitClosure());
EXPECT_CALL(*this, OnStopped(_)).Times(kNumClients - 1)
.RetiresOnSaturation();
- EXPECT_CALL(*this, OnStopped(_)).WillOnce(RunClosure(quit_closure))
+ EXPECT_CALL(*this, OnStopped(_))
+ .WillOnce(RunClosure(std::move(quit_closure)))
.RetiresOnSaturation();
for (const auto& stop_callback : *stop_callbacks)
stop_callback.Run();
@@ -252,7 +253,8 @@ TEST_F(VideoCaptureImplManagerTest, SuspendAndResumeSessions) {
base::Closure quit_closure = BindToCurrentLoop(run_loop.QuitClosure());
EXPECT_CALL(*this, OnPaused(0)).Times(1).RetiresOnSaturation();
EXPECT_CALL(*this, OnPaused(1)).Times(1).RetiresOnSaturation();
- EXPECT_CALL(*this, OnPaused(2)).WillOnce(RunClosure(quit_closure))
+ EXPECT_CALL(*this, OnPaused(2))
+ .WillOnce(RunClosure(std::move(quit_closure)))
.RetiresOnSaturation();
manager_->SuspendDevices(video_devices, true);
run_loop.Run();
@@ -264,7 +266,8 @@ TEST_F(VideoCaptureImplManagerTest, SuspendAndResumeSessions) {
base::Closure quit_closure = BindToCurrentLoop(run_loop.QuitClosure());
EXPECT_CALL(*this, OnResumed(0)).Times(1).RetiresOnSaturation();
EXPECT_CALL(*this, OnResumed(1)).Times(1).RetiresOnSaturation();
- EXPECT_CALL(*this, OnResumed(2)).WillOnce(RunClosure(quit_closure))
+ EXPECT_CALL(*this, OnResumed(2))
+ .WillOnce(RunClosure(std::move(quit_closure)))
.RetiresOnSaturation();
manager_->SuspendDevices(video_devices, false);
run_loop.Run();
@@ -275,7 +278,8 @@ TEST_F(VideoCaptureImplManagerTest, SuspendAndResumeSessions) {
{
base::RunLoop run_loop;
base::Closure quit_closure = BindToCurrentLoop(run_loop.QuitClosure());
- EXPECT_CALL(*this, OnPaused(0)).WillOnce(RunClosure(quit_closure))
+ EXPECT_CALL(*this, OnPaused(0))
+ .WillOnce(RunClosure(std::move(quit_closure)))
.RetiresOnSaturation();
manager_->Suspend(0);
run_loop.Run();
@@ -287,7 +291,8 @@ TEST_F(VideoCaptureImplManagerTest, SuspendAndResumeSessions) {
base::RunLoop run_loop;
base::Closure quit_closure = BindToCurrentLoop(run_loop.QuitClosure());
EXPECT_CALL(*this, OnPaused(1)).Times(1).RetiresOnSaturation();
- EXPECT_CALL(*this, OnPaused(2)).WillOnce(RunClosure(quit_closure))
+ EXPECT_CALL(*this, OnPaused(2))
+ .WillOnce(RunClosure(std::move(quit_closure)))
.RetiresOnSaturation();
manager_->SuspendDevices(video_devices, true);
run_loop.Run();
@@ -306,7 +311,8 @@ TEST_F(VideoCaptureImplManagerTest, SuspendAndResumeSessions) {
base::Closure quit_closure = BindToCurrentLoop(run_loop.QuitClosure());
EXPECT_CALL(*this, OnResumed(0)).Times(1).RetiresOnSaturation();
EXPECT_CALL(*this, OnResumed(1)).Times(1).RetiresOnSaturation();
- EXPECT_CALL(*this, OnResumed(2)).WillOnce(RunClosure(quit_closure))
+ EXPECT_CALL(*this, OnResumed(2))
+ .WillOnce(RunClosure(std::move(quit_closure)))
.RetiresOnSaturation();
manager_->SuspendDevices(video_devices, false);
run_loop.Run();
diff --git a/chromium/content/renderer/media/video_capture_impl_unittest.cc b/chromium/content/renderer/media/video_capture_impl_unittest.cc
index d48c8415569..f32e1484847 100644
--- a/chromium/content/renderer/media/video_capture_impl_unittest.cc
+++ b/chromium/content/renderer/media/video_capture_impl_unittest.cc
@@ -9,7 +9,7 @@
#include "base/test/scoped_task_environment.h"
#include "content/child/child_process.h"
#include "content/renderer/media/video_capture_impl.h"
-#include "media/capture/mojo/video_capture.mojom.h"
+#include "media/capture/mojom/video_capture.mojom.h"
#include "mojo/public/cpp/system/platform_handle.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -158,7 +158,7 @@ class VideoCaptureImplTest : public ::testing::Test {
const base::TimeTicks now = base::TimeTicks::Now();
media::VideoFrameMetadata frame_metadata;
frame_metadata.SetTimeTicks(media::VideoFrameMetadata::REFERENCE_TIME, now);
- info->metadata = frame_metadata.CopyInternalValues();
+ info->metadata = frame_metadata.GetInternalValues().Clone();
info->timestamp = now - base::TimeTicks();
info->pixel_format = media::PIXEL_FORMAT_I420;
diff --git a/chromium/content/renderer/media/web_media_element_source_utils.cc b/chromium/content/renderer/media/web_media_element_source_utils.cc
index 1224e7539ba..94502c53e98 100644
--- a/chromium/content/renderer/media/web_media_element_source_utils.cc
+++ b/chromium/content/renderer/media/web_media_element_source_utils.cc
@@ -4,9 +4,9 @@
#include "content/renderer/media/web_media_element_source_utils.h"
-#include "third_party/WebKit/public/platform/WebMediaPlayerSource.h"
-#include "third_party/WebKit/public/platform/WebMediaStream.h"
-#include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
+#include "third_party/blink/public/platform/web_media_player_source.h"
+#include "third_party/blink/public/platform/web_media_stream.h"
+#include "third_party/blink/public/web/web_media_stream_registry.h"
namespace content {
diff --git a/chromium/content/renderer/media/webrtc/media_stream_remote_video_source.cc b/chromium/content/renderer/media/webrtc/media_stream_remote_video_source.cc
index 8b56e8ee8e1..8e82dd62ac2 100644
--- a/chromium/content/renderer/media/webrtc/media_stream_remote_video_source.cc
+++ b/chromium/content/renderer/media/webrtc/media_stream_remote_video_source.cc
@@ -103,15 +103,16 @@ void MediaStreamRemoteVideoSource::RemoteVideoSourceDelegate::OnFrame(
const base::TimeTicks render_time =
base::TimeTicks() + incoming_timestamp + time_diff_;
- TRACE_EVENT1("webrtc", "RemoteVideoSourceDelegate::RenderFrame",
- "Ideal Render Instant", render_time.ToInternalValue());
-
CHECK_NE(media::kNoTimestamp, incoming_timestamp);
if (start_timestamp_ == media::kNoTimestamp)
start_timestamp_ = incoming_timestamp;
const base::TimeDelta elapsed_timestamp =
incoming_timestamp - start_timestamp_;
+ TRACE_EVENT2("webrtc", "RemoteVideoSourceDelegate::RenderFrame",
+ "Ideal Render Instant", render_time.ToInternalValue(),
+ "Timestamp", elapsed_timestamp.InMicroseconds());
+
scoped_refptr<media::VideoFrame> video_frame;
scoped_refptr<webrtc::VideoFrameBuffer> buffer(
incoming_frame.video_frame_buffer());
diff --git a/chromium/content/renderer/media/webrtc/media_stream_remote_video_source.h b/chromium/content/renderer/media/webrtc/media_stream_remote_video_source.h
index 156f630e669..494b11b8f45 100644
--- a/chromium/content/renderer/media/webrtc/media_stream_remote_video_source.h
+++ b/chromium/content/renderer/media/webrtc/media_stream_remote_video_source.h
@@ -12,7 +12,7 @@
#include "base/single_thread_task_runner.h"
#include "content/common/content_export.h"
#include "content/renderer/media/stream/media_stream_video_source.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
#include "third_party/webrtc/api/mediastreaminterface.h"
namespace content {
diff --git a/chromium/content/renderer/media/webrtc/media_stream_remote_video_source_unittest.cc b/chromium/content/renderer/media/webrtc/media_stream_remote_video_source_unittest.cc
index cddbd1af0b6..a3bb09cf1f1 100644
--- a/chromium/content/renderer/media/webrtc/media_stream_remote_video_source_unittest.cc
+++ b/chromium/content/renderer/media/webrtc/media_stream_remote_video_source_unittest.cc
@@ -19,8 +19,8 @@
#include "content/renderer/media/webrtc/track_observer.h"
#include "media/base/video_frame.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
-#include "third_party/WebKit/public/web/WebHeap.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/web/web_heap.h"
#include "third_party/webrtc/api/video/i420_buffer.h"
namespace content {
@@ -163,8 +163,8 @@ TEST_F(MediaStreamRemoteVideoSourceTest, StartTrack) {
track->AddSink(&sink, sink.GetDeliverFrameCB(), false);
base::RunLoop run_loop;
base::Closure quit_closure = run_loop.QuitClosure();
- EXPECT_CALL(sink, OnVideoFrame()).WillOnce(
- RunClosure(quit_closure));
+ EXPECT_CALL(sink, OnVideoFrame())
+ .WillOnce(RunClosure(std::move(quit_closure)));
rtc::scoped_refptr<webrtc::I420Buffer> buffer(
new rtc::RefCountedObject<webrtc::I420Buffer>(320, 240));
diff --git a/chromium/content/renderer/media/webrtc/media_stream_track_metrics.cc b/chromium/content/renderer/media/webrtc/media_stream_track_metrics.cc
index e340bd0b928..e84c5e83b71 100644
--- a/chromium/content/renderer/media/webrtc/media_stream_track_metrics.cc
+++ b/chromium/content/renderer/media/webrtc/media_stream_track_metrics.cc
@@ -10,8 +10,10 @@
#include "base/md5.h"
#include "base/threading/thread_task_runner_handle.h"
-#include "content/common/media/media_stream_track_metrics_host_messages.h"
+#include "content/child/child_thread_impl.h"
+#include "content/public/common/service_names.mojom.h"
#include "content/renderer/render_thread_impl.h"
+#include "services/service_manager/public/cpp/connector.h"
#include "third_party/webrtc/api/mediastreaminterface.h"
using webrtc::AudioTrackVector;
@@ -351,16 +353,13 @@ void MediaStreamTrackMetrics::SendLifetimeMessage(const std::string& track_id,
// |of a unit test.
if (render_thread) {
if (event == CONNECTED) {
- RenderThreadImpl::current()->Send(
- new MediaStreamTrackMetricsHost_AddTrack(
- MakeUniqueId(track_id, stream_type),
- track_type == AUDIO_TRACK,
- stream_type == RECEIVED_STREAM));
+ GetMediaStreamTrackMetricsHost()->AddTrack(
+ MakeUniqueId(track_id, stream_type), track_type == AUDIO_TRACK,
+ stream_type == RECEIVED_STREAM);
} else {
DCHECK_EQ(DISCONNECTED, event);
- RenderThreadImpl::current()->Send(
- new MediaStreamTrackMetricsHost_RemoveTrack(
- MakeUniqueId(track_id, stream_type)));
+ GetMediaStreamTrackMetricsHost()->RemoveTrack(
+ MakeUniqueId(track_id, stream_type));
}
}
}
@@ -399,4 +398,13 @@ uint64_t MediaStreamTrackMetrics::MakeUniqueId(const std::string& track_id,
stream_type);
}
+mojom::MediaStreamTrackMetricsHostPtr&
+MediaStreamTrackMetrics::GetMediaStreamTrackMetricsHost() {
+ if (!track_metrics_host_) {
+ ChildThreadImpl::current()->GetConnector()->BindInterface(
+ mojom::kBrowserServiceName, &track_metrics_host_);
+ }
+ return track_metrics_host_;
+}
+
} // namespace content
diff --git a/chromium/content/renderer/media/webrtc/media_stream_track_metrics.h b/chromium/content/renderer/media/webrtc/media_stream_track_metrics.h
index 1a09b4eee34..779318660ab 100644
--- a/chromium/content/renderer/media/webrtc/media_stream_track_metrics.h
+++ b/chromium/content/renderer/media/webrtc/media_stream_track_metrics.h
@@ -12,6 +12,7 @@
#include "base/sequence_checker.h"
#include "content/common/content_export.h"
+#include "content/common/media/media_stream.mojom.h"
#include "third_party/webrtc/api/peerconnectioninterface.h"
namespace webrtc {
@@ -92,6 +93,10 @@ class CONTENT_EXPORT MediaStreamTrackMetrics {
// track object and the PeerConnection it is attached to both exist.
uint64_t MakeUniqueId(const std::string& track, StreamType stream_type);
+ mojom::MediaStreamTrackMetricsHostPtr& GetMediaStreamTrackMetricsHost();
+
+ mojom::MediaStreamTrackMetricsHostPtr track_metrics_host_;
+
typedef std::vector<std::unique_ptr<MediaStreamTrackMetricsObserver>>
ObserverVector;
ObserverVector observers_;
diff --git a/chromium/content/renderer/media/webrtc/media_stream_video_webrtc_sink.h b/chromium/content/renderer/media/webrtc/media_stream_video_webrtc_sink.h
index 0ad93a50e7a..8ff0331d038 100644
--- a/chromium/content/renderer/media/webrtc/media_stream_video_webrtc_sink.h
+++ b/chromium/content/renderer/media/webrtc/media_stream_video_webrtc_sink.h
@@ -10,7 +10,7 @@
#include "base/threading/thread_checker.h"
#include "content/public/renderer/media_stream_video_sink.h"
#include "content/renderer/media/webrtc/webrtc_video_capturer_adapter.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
#include "third_party/webrtc/api/mediastreaminterface.h"
namespace base {
diff --git a/chromium/content/renderer/media/webrtc/media_stream_video_webrtc_sink_unittest.cc b/chromium/content/renderer/media/webrtc/media_stream_video_webrtc_sink_unittest.cc
index ea865a3751c..5265f9477fb 100644
--- a/chromium/content/renderer/media/webrtc/media_stream_video_webrtc_sink_unittest.cc
+++ b/chromium/content/renderer/media/webrtc/media_stream_video_webrtc_sink_unittest.cc
@@ -11,7 +11,7 @@
#include "content/renderer/media/stream/video_track_adapter.h"
#include "content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
namespace content {
namespace {
diff --git a/chromium/content/renderer/media/webrtc/mock_peer_connection_dependency_factory.cc b/chromium/content/renderer/media/webrtc/mock_peer_connection_dependency_factory.cc
index d88e5fee9ee..8a895d2ce41 100644
--- a/chromium/content/renderer/media/webrtc/mock_peer_connection_dependency_factory.cc
+++ b/chromium/content/renderer/media/webrtc/mock_peer_connection_dependency_factory.cc
@@ -10,7 +10,7 @@
#include "base/strings/utf_string_conversions.h"
#include "content/renderer/media/webrtc/mock_peer_connection_impl.h"
#include "content/renderer/media/webrtc/webrtc_video_capturer_adapter.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
#include "third_party/webrtc/api/mediastreaminterface.h"
#include "third_party/webrtc/rtc_base/scoped_ref_ptr.h"
@@ -40,7 +40,20 @@ static typename V::iterator FindTrack(V* vector,
return it;
};
-MockMediaStream::MockMediaStream(const std::string& label) : label_(label) {}
+MockWebRtcAudioSource::MockWebRtcAudioSource(bool is_remote)
+ : is_remote_(is_remote) {}
+void MockWebRtcAudioSource::RegisterObserver(ObserverInterface* observer) {}
+void MockWebRtcAudioSource::UnregisterObserver(ObserverInterface* observer) {}
+
+MockWebRtcAudioSource::SourceState MockWebRtcAudioSource::state() const {
+ return SourceState::kLive;
+}
+
+bool MockWebRtcAudioSource::remote() const {
+ return is_remote_;
+}
+
+MockMediaStream::MockMediaStream(const std::string& id) : id_(id) {}
bool MockMediaStream::AddTrack(AudioTrackInterface* track) {
audio_track_vector_.push_back(track);
@@ -74,8 +87,8 @@ bool MockMediaStream::RemoveTrack(VideoTrackInterface* track) {
return true;
}
-std::string MockMediaStream::label() const {
- return label_;
+std::string MockMediaStream::id() const {
+ return id_;
}
AudioTrackVector MockMediaStream::GetAudioTracks() {
@@ -125,6 +138,7 @@ scoped_refptr<MockWebRtcAudioTrack> MockWebRtcAudioTrack::Create(
MockWebRtcAudioTrack::MockWebRtcAudioTrack(const std::string& id)
: id_(id),
+ source_(new rtc::RefCountedObject<MockWebRtcAudioSource>(true)),
enabled_(true),
state_(webrtc::MediaStreamTrackInterface::kLive) {}
@@ -135,8 +149,7 @@ std::string MockWebRtcAudioTrack::kind() const {
}
webrtc::AudioSourceInterface* MockWebRtcAudioTrack::GetSource() const {
- NOTREACHED();
- return nullptr;
+ return source_.get();
}
std::string MockWebRtcAudioTrack::id() const {
diff --git a/chromium/content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h b/chromium/content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h
index 7a59178a02e..1736c90ff2d 100644
--- a/chromium/content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h
+++ b/chromium/content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h
@@ -20,6 +20,19 @@ namespace content {
typedef std::set<webrtc::ObserverInterface*> ObserverSet;
+class MockWebRtcAudioSource : public webrtc::AudioSourceInterface {
+ public:
+ MockWebRtcAudioSource(bool is_remote);
+ void RegisterObserver(webrtc::ObserverInterface* observer) override;
+ void UnregisterObserver(webrtc::ObserverInterface* observer) override;
+
+ SourceState state() const override;
+ bool remote() const override;
+
+ private:
+ const bool is_remote_;
+};
+
class MockWebRtcAudioTrack : public webrtc::AudioTrackInterface {
public:
static scoped_refptr<MockWebRtcAudioTrack> Create(const std::string& id);
@@ -45,7 +58,7 @@ class MockWebRtcAudioTrack : public webrtc::AudioTrackInterface {
private:
std::string id_;
- scoped_refptr<webrtc::VideoTrackSourceInterface> source_;
+ scoped_refptr<webrtc::AudioSourceInterface> source_;
bool enabled_;
TrackState state_;
ObserverSet observers_;
@@ -86,13 +99,13 @@ class MockWebRtcVideoTrack : public webrtc::VideoTrackInterface {
class MockMediaStream : public webrtc::MediaStreamInterface {
public:
- explicit MockMediaStream(const std::string& label);
+ explicit MockMediaStream(const std::string& id);
bool AddTrack(webrtc::AudioTrackInterface* track) override;
bool AddTrack(webrtc::VideoTrackInterface* track) override;
bool RemoveTrack(webrtc::AudioTrackInterface* track) override;
bool RemoveTrack(webrtc::VideoTrackInterface* track) override;
- std::string label() const override;
+ std::string id() const override;
webrtc::AudioTrackVector GetAudioTracks() override;
webrtc::VideoTrackVector GetVideoTracks() override;
rtc::scoped_refptr<webrtc::AudioTrackInterface> FindAudioTrack(
@@ -108,7 +121,7 @@ class MockMediaStream : public webrtc::MediaStreamInterface {
private:
void NotifyObservers();
- std::string label_;
+ std::string id_;
webrtc::AudioTrackVector audio_track_vector_;
webrtc::VideoTrackVector video_track_vector_;
diff --git a/chromium/content/renderer/media/webrtc/mock_peer_connection_impl.cc b/chromium/content/renderer/media/webrtc/mock_peer_connection_impl.cc
index 87fb40a3eb3..21616e414bb 100644
--- a/chromium/content/renderer/media/webrtc/mock_peer_connection_impl.cc
+++ b/chromium/content/renderer/media/webrtc/mock_peer_connection_impl.cc
@@ -31,9 +31,9 @@ class MockStreamCollection : public webrtc::StreamCollectionInterface {
public:
size_t count() override { return streams_.size(); }
MediaStreamInterface* at(size_t index) override { return streams_[index]; }
- MediaStreamInterface* find(const std::string& label) override {
+ MediaStreamInterface* find(const std::string& id) override {
for (size_t i = 0; i < streams_.size(); ++i) {
- if (streams_[i]->label() == label)
+ if (streams_[i]->id() == id)
return streams_[i];
}
return nullptr;
@@ -277,8 +277,8 @@ rtc::scoped_refptr<webrtc::RtpSenderInterface> MockPeerConnectionImpl::AddTrack(
return nullptr;
}
for (auto* stream : streams) {
- if (!local_streams_->find(stream->label())) {
- stream_label_ = stream->label();
+ if (!local_streams_->find(stream->id())) {
+ stream_label_ = stream->id();
local_streams_->AddStream(stream);
}
}
@@ -398,6 +398,18 @@ void MockPeerConnectionImpl::GetStats(
callback->OnStatsDelivered(stats_report_);
}
+void MockPeerConnectionImpl::GetStats(
+ rtc::scoped_refptr<webrtc::RtpSenderInterface> selector,
+ rtc::scoped_refptr<webrtc::RTCStatsCollectorCallback> callback) {
+ callback->OnStatsDelivered(stats_report_);
+}
+
+void MockPeerConnectionImpl::GetStats(
+ rtc::scoped_refptr<webrtc::RtpReceiverInterface> selector,
+ rtc::scoped_refptr<webrtc::RTCStatsCollectorCallback> callback) {
+ callback->OnStatsDelivered(stats_report_);
+}
+
void MockPeerConnectionImpl::SetGetStatsReport(webrtc::RTCStatsReport* report) {
stats_report_ = report;
}
diff --git a/chromium/content/renderer/media/webrtc/mock_peer_connection_impl.h b/chromium/content/renderer/media/webrtc/mock_peer_connection_impl.h
index f1fc772c77c..6b8e6f25597 100644
--- a/chromium/content/renderer/media/webrtc/mock_peer_connection_impl.h
+++ b/chromium/content/renderer/media/webrtc/mock_peer_connection_impl.h
@@ -103,6 +103,12 @@ class MockPeerConnectionImpl : public webrtc::PeerConnectionInterface {
webrtc::MediaStreamTrackInterface* track,
StatsOutputLevel level) override;
void GetStats(webrtc::RTCStatsCollectorCallback* callback) override;
+ void GetStats(
+ rtc::scoped_refptr<webrtc::RtpSenderInterface> selector,
+ rtc::scoped_refptr<webrtc::RTCStatsCollectorCallback> callback) override;
+ void GetStats(
+ rtc::scoped_refptr<webrtc::RtpReceiverInterface> selector,
+ rtc::scoped_refptr<webrtc::RTCStatsCollectorCallback> callback) override;
// Call this function to make sure next call to legacy GetStats fail.
void SetGetStatsResult(bool result) { getstats_result_ = result; }
diff --git a/chromium/content/renderer/media/webrtc/mock_web_rtc_peer_connection_handler_client.cc b/chromium/content/renderer/media/webrtc/mock_web_rtc_peer_connection_handler_client.cc
index e5fcc0a1b16..6d8afca21d7 100644
--- a/chromium/content/renderer/media/webrtc/mock_web_rtc_peer_connection_handler_client.cc
+++ b/chromium/content/renderer/media/webrtc/mock_web_rtc_peer_connection_handler_client.cc
@@ -5,9 +5,9 @@
#include "base/logging.h"
#include "base/strings/utf_string_conversions.h"
-#include "third_party/WebKit/public/platform/WebMediaStream.h"
-#include "third_party/WebKit/public/platform/WebRTCRtpReceiver.h"
-#include "third_party/WebKit/public/platform/WebString.h"
+#include "third_party/blink/public/platform/web_media_stream.h"
+#include "third_party/blink/public/platform/web_rtc_rtp_receiver.h"
+#include "third_party/blink/public/platform/web_string.h"
using testing::_;
diff --git a/chromium/content/renderer/media/webrtc/mock_web_rtc_peer_connection_handler_client.h b/chromium/content/renderer/media/webrtc/mock_web_rtc_peer_connection_handler_client.h
index 3838398ebe7..7b2fba5d5c5 100644
--- a/chromium/content/renderer/media/webrtc/mock_web_rtc_peer_connection_handler_client.h
+++ b/chromium/content/renderer/media/webrtc/mock_web_rtc_peer_connection_handler_client.h
@@ -10,10 +10,10 @@
#include "base/compiler_specific.h"
#include "base/macros.h"
#include "testing/gmock/include/gmock/gmock.h"
-#include "third_party/WebKit/public/platform/WebMediaStream.h"
-#include "third_party/WebKit/public/platform/WebRTCICECandidate.h"
-#include "third_party/WebKit/public/platform/WebRTCPeerConnectionHandlerClient.h"
-#include "third_party/WebKit/public/platform/WebRTCRtpReceiver.h"
+#include "third_party/blink/public/platform/web_media_stream.h"
+#include "third_party/blink/public/platform/web_rtc_ice_candidate.h"
+#include "third_party/blink/public/platform/web_rtc_peer_connection_handler_client.h"
+#include "third_party/blink/public/platform/web_rtc_rtp_receiver.h"
namespace content {
diff --git a/chromium/content/renderer/media/webrtc/peer_connection_dependency_factory.cc b/chromium/content/renderer/media/webrtc/peer_connection_dependency_factory.cc
index 6eb1b5e4db0..12f443e4e2f 100644
--- a/chromium/content/renderer/media/webrtc/peer_connection_dependency_factory.cc
+++ b/chromium/content/renderer/media/webrtc/peer_connection_dependency_factory.cc
@@ -16,18 +16,17 @@
#include "base/location.h"
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/field_trial.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/synchronization/waitable_event.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
+#include "content/public/common/buildflags.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/feature_h264_with_openh264_ffmpeg.h"
-#include "content/public/common/features.h"
#include "content/public/common/renderer_preferences.h"
#include "content/public/common/webrtc_ip_handling_policy.h"
#include "content/public/renderer/content_renderer_client.h"
@@ -53,16 +52,15 @@
#include "crypto/openssl_util.h"
#include "jingle/glue/thread_wrapper.h"
#include "media/base/media_permission.h"
-#include "media/filters/ffmpeg_glue.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "media/video/gpu_video_accelerator_factories.h"
-#include "third_party/WebKit/public/platform/WebMediaConstraints.h"
-#include "third_party/WebKit/public/platform/WebMediaStream.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "third_party/blink/public/platform/web_media_constraints.h"
+#include "third_party/blink/public/platform/web_media_stream.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
+#include "third_party/blink/public/platform/web_url.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/webrtc/api/mediaconstraintsinterface.h"
#include "third_party/webrtc/api/video_codecs/video_decoder_factory.h"
#include "third_party/webrtc/api/video_codecs/video_encoder_factory.h"
@@ -130,7 +128,7 @@ PeerConnectionDependencyFactory::CreateRTCPeerConnectionHandler(
// Save histogram data so we can see how much PeerConnetion is used.
// The histogram counts the number of calls to the JS API
// webKitRTCPeerConnection.
- UpdateWebRTCMethodCount(WEBKIT_RTC_PEER_CONNECTION);
+ UpdateWebRTCMethodCount(blink::WebRTCAPIName::kRTCPeerConnection);
return std::make_unique<RTCPeerConnectionHandler>(client, this, task_runner);
}
@@ -160,12 +158,8 @@ void PeerConnectionDependencyFactory::CreatePeerConnectionFactory() {
#if BUILDFLAG(RTC_USE_H264) && BUILDFLAG(ENABLE_FFMPEG_VIDEO_DECODERS)
// Building /w |rtc_use_h264|, is the corresponding run-time feature enabled?
- if (base::FeatureList::IsEnabled(kWebRtcH264WithOpenH264FFmpeg)) {
- // |H264DecoderImpl| may be used which depends on FFmpeg, therefore we need
- // to initialize FFmpeg before going further.
- media::FFmpegGlue::InitializeFFmpeg();
- } else {
- // Feature is to be disabled, no need to make sure FFmpeg is initialized.
+ if (!base::FeatureList::IsEnabled(kWebRtcH264WithOpenH264FFmpeg)) {
+ // Feature is to be disabled.
webrtc::DisableRtcUseH264();
}
#else
diff --git a/chromium/content/renderer/media/webrtc/peer_connection_dependency_factory_unittest.cc b/chromium/content/renderer/media/webrtc/peer_connection_dependency_factory_unittest.cc
index a6121ab38e4..79f3bcbc961 100644
--- a/chromium/content/renderer/media/webrtc/peer_connection_dependency_factory_unittest.cc
+++ b/chromium/content/renderer/media/webrtc/peer_connection_dependency_factory_unittest.cc
@@ -6,8 +6,8 @@
#include "content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h"
#include "content/renderer/media/webrtc/mock_web_rtc_peer_connection_handler_client.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebRTCPeerConnectionHandler.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/web_rtc_peer_connection_handler.h"
namespace content {
diff --git a/chromium/content/renderer/media/webrtc/peer_connection_tracker.cc b/chromium/content/renderer/media/webrtc/peer_connection_tracker.cc
index 3c37998c5bb..b9316272341 100644
--- a/chromium/content/renderer/media/webrtc/peer_connection_tracker.cc
+++ b/chromium/content/renderer/media/webrtc/peer_connection_tracker.cc
@@ -12,7 +12,6 @@
#include <utility>
#include <vector>
-#include "base/memory/ptr_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
@@ -21,17 +20,17 @@
#include "content/common/media/peer_connection_tracker_messages.h"
#include "content/renderer/media/webrtc/rtc_peer_connection_handler.h"
#include "content/renderer/render_thread_impl.h"
-#include "third_party/WebKit/public/platform/WebMediaConstraints.h"
-#include "third_party/WebKit/public/platform/WebMediaStream.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
-#include "third_party/WebKit/public/platform/WebRTCAnswerOptions.h"
-#include "third_party/WebKit/public/platform/WebRTCICECandidate.h"
-#include "third_party/WebKit/public/platform/WebRTCOfferOptions.h"
-#include "third_party/WebKit/public/platform/WebRTCPeerConnectionHandlerClient.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebUserMediaRequest.h"
+#include "third_party/blink/public/platform/web_media_constraints.h"
+#include "third_party/blink/public/platform/web_media_stream.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
+#include "third_party/blink/public/platform/web_rtc_answer_options.h"
+#include "third_party/blink/public/platform/web_rtc_ice_candidate.h"
+#include "third_party/blink/public/platform/web_rtc_offer_options.h"
+#include "third_party/blink/public/platform/web_rtc_peer_connection_handler_client.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_user_media_request.h"
using webrtc::MediaConstraintsInterface;
using webrtc::StatsReport;
@@ -460,11 +459,15 @@ void PeerConnectionTracker::RegisterPeerConnection(
const blink::WebMediaConstraints& constraints,
const blink::WebLocalFrame* frame) {
DCHECK(main_thread_.CalledOnValidThread());
+ DCHECK(pc_handler);
DCHECK_EQ(GetLocalIDForHandler(pc_handler), -1);
DVLOG(1) << "PeerConnectionTracker::RegisterPeerConnection()";
PeerConnectionInfo info;
info.lid = GetNextLocalID();
+ // RTCPeerConnection.id is guaranteed to be an ASCII string. The ID's origin
+ // is local, so this conversion is safe.
+ info.peer_connection_id = pc_handler->Id().Ascii();
info.rtc_configuration = SerializeConfiguration(config);
info.constraints = SerializeMediaConstraints(constraints);
diff --git a/chromium/content/renderer/media/webrtc/peer_connection_tracker.h b/chromium/content/renderer/media/webrtc/peer_connection_tracker.h
index 8a4171e00fb..0c35de2047e 100644
--- a/chromium/content/renderer/media/webrtc/peer_connection_tracker.h
+++ b/chromium/content/renderer/media/webrtc/peer_connection_tracker.h
@@ -14,9 +14,9 @@
#include "content/common/media/peer_connection_tracker.mojom.h"
#include "content/public/renderer/render_thread_observer.h"
#include "ipc/ipc_platform_file.h"
-#include "third_party/WebKit/public/platform/WebMediaStream.h"
-#include "third_party/WebKit/public/platform/WebRTCPeerConnectionHandlerClient.h"
-#include "third_party/WebKit/public/platform/WebRTCSessionDescription.h"
+#include "third_party/blink/public/platform/web_media_stream.h"
+#include "third_party/blink/public/platform/web_rtc_peer_connection_handler_client.h"
+#include "third_party/blink/public/platform/web_rtc_session_description.h"
#include "third_party/webrtc/api/peerconnectioninterface.h"
namespace blink {
diff --git a/chromium/content/renderer/media/webrtc/peer_connection_tracker_unittest.cc b/chromium/content/renderer/media/webrtc/peer_connection_tracker_unittest.cc
index cb0d1de9382..647a6462d8c 100644
--- a/chromium/content/renderer/media/webrtc/peer_connection_tracker_unittest.cc
+++ b/chromium/content/renderer/media/webrtc/peer_connection_tracker_unittest.cc
@@ -15,9 +15,9 @@
#include "mojo/public/cpp/bindings/associated_binding.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebMediaConstraints.h"
-#include "third_party/WebKit/public/platform/WebRTCOfferOptions.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/web_media_constraints.h"
+#include "third_party/blink/public/platform/web_rtc_offer_options.h"
using ::testing::_;
diff --git a/chromium/content/renderer/media/webrtc/rtc_certificate.h b/chromium/content/renderer/media/webrtc/rtc_certificate.h
index 0de9c846d09..5210e8f40db 100644
--- a/chromium/content/renderer/media/webrtc/rtc_certificate.h
+++ b/chromium/content/renderer/media/webrtc/rtc_certificate.h
@@ -10,7 +10,7 @@
#include "base/compiler_specific.h"
#include "base/macros.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebRTCCertificate.h"
+#include "third_party/blink/public/platform/web_rtc_certificate.h"
#include "third_party/webrtc/rtc_base/rtccertificate.h"
#include "third_party/webrtc/rtc_base/scoped_ref_ptr.h"
diff --git a/chromium/content/renderer/media/webrtc/rtc_certificate_generator.cc b/chromium/content/renderer/media/webrtc/rtc_certificate_generator.cc
index 0c29b6de5f2..4019d764e3a 100644
--- a/chromium/content/renderer/media/webrtc/rtc_certificate_generator.cc
+++ b/chromium/content/renderer/media/webrtc/rtc_certificate_generator.cc
@@ -8,14 +8,13 @@
#include <utility>
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
#include "content/renderer/media/webrtc/rtc_certificate.h"
#include "content/renderer/render_thread_impl.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "third_party/webrtc/rtc_base/rtccertificate.h"
#include "third_party/webrtc/rtc_base/rtccertificategenerator.h"
#include "third_party/webrtc/rtc_base/scoped_ref_ptr.h"
@@ -93,7 +92,9 @@ class RTCCertificateGeneratorRequest
FROM_HERE,
base::BindOnce(&RTCCertificateGeneratorRequest::DoCallbackOnMainThread,
this, std::move(observer),
- std::make_unique<RTCCertificate>(certificate)));
+ certificate
+ ? std::make_unique<RTCCertificate>(certificate)
+ : nullptr));
}
void DoCallbackOnMainThread(
diff --git a/chromium/content/renderer/media/webrtc/rtc_certificate_generator.h b/chromium/content/renderer/media/webrtc/rtc_certificate_generator.h
index 03cf5cdaf60..25abfe8dc1a 100644
--- a/chromium/content/renderer/media/webrtc/rtc_certificate_generator.h
+++ b/chromium/content/renderer/media/webrtc/rtc_certificate_generator.h
@@ -6,9 +6,9 @@
#define CONTENT_RENDERER_MEDIA_WEBRTC_RTC_CERTIFICATE_GENERATOR_H_
#include "base/macros.h"
-#include "third_party/WebKit/public/platform/WebRTCCertificate.h"
-#include "third_party/WebKit/public/platform/WebRTCCertificateGenerator.h"
-#include "third_party/WebKit/public/platform/WebRTCKeyParams.h"
+#include "third_party/blink/public/platform/web_rtc_certificate.h"
+#include "third_party/blink/public/platform/web_rtc_certificate_generator.h"
+#include "third_party/blink/public/platform/web_rtc_key_params.h"
#include "third_party/webrtc/api/optional.h"
namespace content {
diff --git a/chromium/content/renderer/media/webrtc/rtc_data_channel_handler.h b/chromium/content/renderer/media/webrtc/rtc_data_channel_handler.h
index 35221f8da90..be28abbf213 100644
--- a/chromium/content/renderer/media/webrtc/rtc_data_channel_handler.h
+++ b/chromium/content/renderer/media/webrtc/rtc_data_channel_handler.h
@@ -14,8 +14,8 @@
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_checker.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebRTCDataChannelHandler.h"
-#include "third_party/WebKit/public/platform/WebRTCDataChannelHandlerClient.h"
+#include "third_party/blink/public/platform/web_rtc_data_channel_handler.h"
+#include "third_party/blink/public/platform/web_rtc_data_channel_handler_client.h"
#include "third_party/webrtc/api/peerconnectioninterface.h"
namespace content {
diff --git a/chromium/content/renderer/media/webrtc/rtc_data_channel_handler_unittest.cc b/chromium/content/renderer/media/webrtc/rtc_data_channel_handler_unittest.cc
index 0b8cc8f0517..ad31b331391 100644
--- a/chromium/content/renderer/media/webrtc/rtc_data_channel_handler_unittest.cc
+++ b/chromium/content/renderer/media/webrtc/rtc_data_channel_handler_unittest.cc
@@ -11,7 +11,7 @@
#include "base/test/test_simple_task_runner.h"
#include "content/renderer/media/webrtc/mock_data_channel_impl.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebRTCDataChannelHandlerClient.h"
+#include "third_party/blink/public/platform/web_rtc_data_channel_handler_client.h"
namespace content {
diff --git a/chromium/content/renderer/media/webrtc/rtc_dtmf_sender_handler.h b/chromium/content/renderer/media/webrtc/rtc_dtmf_sender_handler.h
index e6387f8ead0..89f1c73d6d2 100644
--- a/chromium/content/renderer/media/webrtc/rtc_dtmf_sender_handler.h
+++ b/chromium/content/renderer/media/webrtc/rtc_dtmf_sender_handler.h
@@ -12,8 +12,8 @@
#include "base/memory/weak_ptr.h"
#include "base/sequence_checker.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebRTCDTMFSenderHandler.h"
-#include "third_party/WebKit/public/platform/WebRTCDTMFSenderHandlerClient.h"
+#include "third_party/blink/public/platform/web_rtc_dtmf_sender_handler.h"
+#include "third_party/blink/public/platform/web_rtc_dtmf_sender_handler_client.h"
#include "third_party/webrtc/api/dtmfsenderinterface.h"
namespace content {
diff --git a/chromium/content/renderer/media/webrtc/rtc_error.cc b/chromium/content/renderer/media/webrtc/rtc_error.cc
new file mode 100644
index 00000000000..4b79c809990
--- /dev/null
+++ b/chromium/content/renderer/media/webrtc/rtc_error.cc
@@ -0,0 +1,61 @@
+// Copyright (c) 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/renderer/media/webrtc/rtc_error.h"
+
+#include "third_party/webrtc/api/rtcerror.h"
+
+namespace content {
+
+blink::WebRTCError ConvertToWebKitRTCError(
+ const webrtc::RTCError& webrtc_error) {
+ blink::WebString message = blink::WebString::FromUTF8(
+ webrtc_error.message(), strlen(webrtc_error.message()));
+ switch (webrtc_error.type()) {
+ case webrtc::RTCErrorType::NONE:
+ return blink::WebRTCError(blink::WebRTCErrorType::kNone, message);
+ break;
+ case webrtc::RTCErrorType::UNSUPPORTED_PARAMETER:
+ return blink::WebRTCError(blink::WebRTCErrorType::kUnsupportedParameter,
+ message);
+ break;
+ case webrtc::RTCErrorType::INVALID_PARAMETER:
+ return blink::WebRTCError(blink::WebRTCErrorType::kInvalidParameter,
+ message);
+ break;
+ case webrtc::RTCErrorType::INVALID_RANGE:
+ return blink::WebRTCError(blink::WebRTCErrorType::kInvalidRange, message);
+ break;
+ case webrtc::RTCErrorType::SYNTAX_ERROR:
+ return blink::WebRTCError(blink::WebRTCErrorType::kSyntaxError, message);
+ break;
+ case webrtc::RTCErrorType::INVALID_STATE:
+ return blink::WebRTCError(blink::WebRTCErrorType::kInvalidState, message);
+ break;
+ case webrtc::RTCErrorType::INVALID_MODIFICATION:
+ return blink::WebRTCError(blink::WebRTCErrorType::kInvalidModification,
+ message);
+ break;
+ case webrtc::RTCErrorType::NETWORK_ERROR:
+ return blink::WebRTCError(blink::WebRTCErrorType::kNetworkError, message);
+ break;
+ case webrtc::RTCErrorType::INTERNAL_ERROR:
+ return blink::WebRTCError(blink::WebRTCErrorType::kInternalError,
+ message);
+ break;
+ default:
+ // If adding a new error type, need 3 CLs: One to add the enum to webrtc,
+ // one to update this mapping code, and one to start using the enum in
+ // webrtc.
+ NOTREACHED() << "webrtc::RTCErrorType "
+ << webrtc::ToString(webrtc_error.type())
+ << " not covered by switch statement.";
+ break;
+ }
+ NOTREACHED();
+ return blink::WebRTCError(blink::WebRTCErrorType::kInternalError,
+ "Impossible code path executed");
+}
+
+} // namespace content \ No newline at end of file
diff --git a/chromium/content/renderer/media/webrtc/rtc_error.h b/chromium/content/renderer/media/webrtc/rtc_error.h
new file mode 100644
index 00000000000..6183a4eabf5
--- /dev/null
+++ b/chromium/content/renderer/media/webrtc/rtc_error.h
@@ -0,0 +1,21 @@
+// Copyright (c) 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_RENDERER_MEDIA_WEBRTC_RTC_ERROR_H_
+#define CONTENT_RENDERER_MEDIA_WEBRTC_RTC_ERROR_H_
+
+#include "content/public/common/content_features.h"
+#include "content/public/common/content_switches.h"
+#include "third_party/blink/public/platform/web_rtc_error.h"
+
+namespace webrtc {
+class RTCError;
+}
+
+namespace content {
+blink::WebRTCError ConvertToWebKitRTCError(
+ const webrtc::RTCError& webrtc_error);
+}
+
+#endif // CONTENT_RENDERER_MEDIA_WEBRTC_RTC_ERROR_H_ \ No newline at end of file
diff --git a/chromium/content/renderer/media/webrtc/rtc_peer_connection_handler.cc b/chromium/content/renderer/media/webrtc/rtc_peer_connection_handler.cc
index 23d38be7b39..aba19e25317 100644
--- a/chromium/content/renderer/media/webrtc/rtc_peer_connection_handler.cc
+++ b/chromium/content/renderer/media/webrtc/rtc_peer_connection_handler.cc
@@ -4,8 +4,10 @@
#include "content/renderer/media/webrtc/rtc_peer_connection_handler.h"
+#include <ctype.h>
#include <string.h>
+#include <algorithm>
#include <memory>
#include <string>
#include <utility>
@@ -16,9 +18,11 @@
#include "base/logging.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
+#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/trace_event/trace_event.h"
+#include "base/unguessable_token.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/renderer/media/stream/media_stream_constraints_util.h"
@@ -28,6 +32,7 @@
#include "content/renderer/media/webrtc/rtc_certificate.h"
#include "content/renderer/media/webrtc/rtc_data_channel_handler.h"
#include "content/renderer/media/webrtc/rtc_dtmf_sender_handler.h"
+#include "content/renderer/media/webrtc/rtc_error.h"
#include "content/renderer/media/webrtc/rtc_event_log_output_sink.h"
#include "content/renderer/media/webrtc/rtc_event_log_output_sink_proxy.h"
#include "content/renderer/media/webrtc/rtc_stats.h"
@@ -37,19 +42,19 @@
#include "content/renderer/media/webrtc/webrtc_uma_histograms.h"
#include "content/renderer/render_thread_impl.h"
#include "media/base/media_switches.h"
-#include "third_party/WebKit/public/platform/WebMediaConstraints.h"
-#include "third_party/WebKit/public/platform/WebRTCAnswerOptions.h"
-#include "third_party/WebKit/public/platform/WebRTCConfiguration.h"
-#include "third_party/WebKit/public/platform/WebRTCDataChannelInit.h"
-#include "third_party/WebKit/public/platform/WebRTCError.h"
-#include "third_party/WebKit/public/platform/WebRTCICECandidate.h"
-#include "third_party/WebKit/public/platform/WebRTCLegacyStats.h"
-#include "third_party/WebKit/public/platform/WebRTCOfferOptions.h"
-#include "third_party/WebKit/public/platform/WebRTCRtpSender.h"
-#include "third_party/WebKit/public/platform/WebRTCSessionDescription.h"
-#include "third_party/WebKit/public/platform/WebRTCSessionDescriptionRequest.h"
-#include "third_party/WebKit/public/platform/WebRTCVoidRequest.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
+#include "third_party/blink/public/platform/web_media_constraints.h"
+#include "third_party/blink/public/platform/web_rtc_answer_options.h"
+#include "third_party/blink/public/platform/web_rtc_configuration.h"
+#include "third_party/blink/public/platform/web_rtc_data_channel_init.h"
+#include "third_party/blink/public/platform/web_rtc_error.h"
+#include "third_party/blink/public/platform/web_rtc_ice_candidate.h"
+#include "third_party/blink/public/platform/web_rtc_legacy_stats.h"
+#include "third_party/blink/public/platform/web_rtc_offer_options.h"
+#include "third_party/blink/public/platform/web_rtc_rtp_sender.h"
+#include "third_party/blink/public/platform/web_rtc_session_description.h"
+#include "third_party/blink/public/platform/web_rtc_session_description_request.h"
+#include "third_party/blink/public/platform/web_rtc_void_request.h"
+#include "third_party/blink/public/platform/web_url.h"
#include "third_party/webrtc/api/rtceventlogoutput.h"
#include "third_party/webrtc/pc/mediasession.h"
@@ -165,46 +170,6 @@ CreateWebKitSessionDescription(
return CreateWebKitSessionDescription(sdp, native_desc->type());
}
-void ConvertToWebKitRTCError(const webrtc::RTCError& webrtc_error,
- blink::WebRTCError* blink_error) {
- switch (webrtc_error.type()) {
- case webrtc::RTCErrorType::NONE:
- blink_error->SetType(blink::WebRTCErrorType::kNone);
- break;
- case webrtc::RTCErrorType::UNSUPPORTED_PARAMETER:
- blink_error->SetType(blink::WebRTCErrorType::kUnsupportedParameter);
- break;
- case webrtc::RTCErrorType::INVALID_PARAMETER:
- blink_error->SetType(blink::WebRTCErrorType::kInvalidParameter);
- break;
- case webrtc::RTCErrorType::INVALID_RANGE:
- blink_error->SetType(blink::WebRTCErrorType::kInvalidRange);
- break;
- case webrtc::RTCErrorType::SYNTAX_ERROR:
- blink_error->SetType(blink::WebRTCErrorType::kSyntaxError);
- break;
- case webrtc::RTCErrorType::INVALID_STATE:
- blink_error->SetType(blink::WebRTCErrorType::kInvalidState);
- break;
- case webrtc::RTCErrorType::INVALID_MODIFICATION:
- blink_error->SetType(blink::WebRTCErrorType::kInvalidModification);
- break;
- case webrtc::RTCErrorType::NETWORK_ERROR:
- blink_error->SetType(blink::WebRTCErrorType::kNetworkError);
- break;
- case webrtc::RTCErrorType::INTERNAL_ERROR:
- blink_error->SetType(blink::WebRTCErrorType::kInternalError);
- break;
- default:
- // If adding a new error type, need 3 CLs: One to add the enum to webrtc,
- // one to update this mapping code, and one to start using the enum in
- // webrtc.
- NOTREACHED() << "webrtc::RTCErrorType " << webrtc_error.type()
- << " not covered by switch statement.";
- break;
- }
-}
-
void RunClosureWithTrace(const base::Closure& closure,
const char* trace_event_name) {
TRACE_EVENT0("webrtc", trace_event_name);
@@ -295,8 +260,6 @@ void GetNativeRtcConfiguration(
switch (blink_config.sdp_semantics) {
case blink::WebRTCSdpSemantics::kDefault:
- webrtc_config->sdp_semantics = webrtc::SdpSemantics::kDefault;
- break;
case blink::WebRTCSdpSemantics::kPlanB:
webrtc_config->sdp_semantics = webrtc::SdpSemantics::kPlanB;
break;
@@ -398,11 +361,11 @@ class SessionDescriptionRequestTracker {
}
}
- void TrackOnFailure(const std::string& error) {
+ void TrackOnFailure(const webrtc::RTCError& error) {
DCHECK(thread_checker_.CalledOnValidThread());
if (handler_ && tracker_) {
- tracker_->TrackSessionDescriptionCallback(
- handler_.get(), action_, "OnFailure", error);
+ tracker_->TrackSessionDescriptionCallback(handler_.get(), action_,
+ "OnFailure", error.message());
}
}
@@ -442,16 +405,17 @@ class CreateSessionDescriptionRequest
webkit_request_.Reset();
delete desc;
}
- void OnFailure(const std::string& error) override {
+ void OnFailure(webrtc::RTCError error) override {
if (!main_thread_->BelongsToCurrentThread()) {
main_thread_->PostTask(
FROM_HERE, base::BindOnce(&CreateSessionDescriptionRequest::OnFailure,
- this, error));
+ this, std::move(error)));
return;
}
tracker_.TrackOnFailure(error);
- webkit_request_.RequestFailed(blink::WebString::FromUTF8(error));
+ // TODO(hta): Convert CreateSessionDescriptionRequest.OnFailure
+ webkit_request_.RequestFailed(ConvertToWebKitRTCError(error).message());
webkit_request_.Reset();
}
@@ -497,15 +461,15 @@ class SetLocalDescriptionRequest
webkit_request_.RequestSucceeded();
webkit_request_.Reset();
}
- void OnFailure(const std::string& error) override {
+ void OnFailure(webrtc::RTCError error) override {
if (!main_thread_->BelongsToCurrentThread()) {
main_thread_->PostTask(
- FROM_HERE,
- base::BindOnce(&SetLocalDescriptionRequest::OnFailure, this, error));
+ FROM_HERE, base::BindOnce(&SetLocalDescriptionRequest::OnFailure,
+ this, std::move(error)));
return;
}
tracker_.TrackOnFailure(error);
- webkit_request_.RequestFailed(blink::WebString::FromUTF8(error));
+ webkit_request_.RequestFailed(ConvertToWebKitRTCError(error));
webkit_request_.Reset();
}
@@ -732,52 +696,6 @@ void GetStatsOnSignalingThread(
}
}
-// A stats collector callback.
-// It is invoked on the WebRTC signaling thread and will post a task to invoke
-// |callback| on the thread given in the |main_thread| argument.
-// The argument to the callback will be a |blink::WebRTCStatsReport|.
-class GetRTCStatsCallback : public webrtc::RTCStatsCollectorCallback {
- public:
- static rtc::scoped_refptr<GetRTCStatsCallback> Create(
- const scoped_refptr<base::SingleThreadTaskRunner>& main_thread,
- std::unique_ptr<blink::WebRTCStatsReportCallback> callback) {
- return rtc::scoped_refptr<GetRTCStatsCallback>(
- new rtc::RefCountedObject<GetRTCStatsCallback>(
- main_thread, callback.release()));
- }
-
- void OnStatsDelivered(
- const rtc::scoped_refptr<const webrtc::RTCStatsReport>& report) override {
- main_thread_->PostTask(
- FROM_HERE,
- base::BindOnce(&GetRTCStatsCallback::OnStatsDeliveredOnMainThread, this,
- report));
- }
-
- protected:
- GetRTCStatsCallback(
- const scoped_refptr<base::SingleThreadTaskRunner>& main_thread,
- blink::WebRTCStatsReportCallback* callback)
- : main_thread_(main_thread),
- callback_(callback) {
- }
- ~GetRTCStatsCallback() override { DCHECK(!callback_); }
-
- void OnStatsDeliveredOnMainThread(
- const rtc::scoped_refptr<const webrtc::RTCStatsReport>& report) {
- DCHECK(main_thread_->BelongsToCurrentThread());
- DCHECK(report);
- DCHECK(callback_);
- callback_->OnStatsDelivered(std::unique_ptr<blink::WebRTCStatsReport>(
- new RTCStatsReport(base::WrapRefCounted(report.get()))));
- // Make sure the callback is destroyed in the main thread as well.
- callback_.reset();
- }
-
- const scoped_refptr<base::SingleThreadTaskRunner> main_thread_;
- std::unique_ptr<blink::WebRTCStatsReportCallback> callback_;
-};
-
void GetRTCStatsOnSignalingThread(
const scoped_refptr<base::SingleThreadTaskRunner>& main_thread,
scoped_refptr<webrtc::PeerConnectionInterface> native_peer_connection,
@@ -785,7 +703,7 @@ void GetRTCStatsOnSignalingThread(
TRACE_EVENT0("webrtc", "GetRTCStatsOnSignalingThread");
native_peer_connection->GetStats(
- GetRTCStatsCallback::Create(main_thread, std::move(callback)));
+ RTCStatsCollectorCallbackImpl::Create(main_thread, std::move(callback)));
}
class PeerConnectionUMAObserver : public webrtc::UMAObserver {
@@ -828,18 +746,24 @@ class PeerConnectionUMAObserver : public webrtc::UMAObserver {
static_cast<webrtc::KeyExchangeProtocolType>(counter),
webrtc::kEnumCounterKeyProtocolMax);
break;
- case webrtc::kEnumCounterSdpSemanticRequested:
- UMA_HISTOGRAM_ENUMERATION(
- "WebRTC.PeerConnection.SdpSemanticRequested",
- static_cast<webrtc::SdpSemanticRequested>(counter),
- webrtc::kSdpSemanticRequestMax);
- break;
case webrtc::kEnumCounterSdpSemanticNegotiated:
UMA_HISTOGRAM_ENUMERATION(
"WebRTC.PeerConnection.SdpSemanticNegotiated",
static_cast<webrtc::SdpSemanticNegotiated>(counter),
webrtc::kSdpSemanticNegotiatedMax);
break;
+ case webrtc::kEnumCounterKeyProtocolMediaType:
+ UMA_HISTOGRAM_ENUMERATION(
+ "WebRTC.PeerConnection.KeyProtocolByMedia",
+ static_cast<webrtc::KeyExchangeProtocolMedia>(counter),
+ webrtc::kEnumCounterKeyProtocolMediaTypeMax);
+ break;
+ case webrtc::kEnumCounterSdpFormatReceived:
+ UMA_HISTOGRAM_ENUMERATION(
+ "WebRTC.PeerConnection.SdpFormatReceived",
+ static_cast<webrtc::SdpFormatReceived>(counter),
+ webrtc::kSdpFormatReceivedMax);
+ break;
default:
// The default clause is expected to be reached when new enum types are
// added.
@@ -875,6 +799,14 @@ class PeerConnectionUMAObserver : public webrtc::UMAObserver {
base::UmaHistogramSparse("WebRTC.PeerConnection.SslCipherSuite.Data",
counter);
break;
+ case webrtc::kEnumCounterSrtpUnprotectError:
+ base::UmaHistogramSparse("WebRTC.PeerConnection.SrtpUnprotectError",
+ counter);
+ break;
+ case webrtc::kEnumCounterSrtcpUnprotectError:
+ base::UmaHistogramSparse("WebRTC.PeerConnection.SrtcpUnprotectError",
+ counter);
+ break;
default:
// The default clause is expected to reach when new enum types are
// added.
@@ -990,6 +922,27 @@ size_t GetRemoteStreamUsageCount(
return usage_count;
}
+enum SdpSemanticRequested {
+ kSdpSemanticRequestedDefault,
+ kSdpSemanticRequestedPlanB,
+ kSdpSemanticRequestedUnifiedPlan,
+ kSdpSemanticRequestedMax
+};
+
+SdpSemanticRequested GetSdpSemanticRequested(
+ blink::WebRTCSdpSemantics sdp_semantics) {
+ switch (sdp_semantics) {
+ case blink::WebRTCSdpSemantics::kDefault:
+ return kSdpSemanticRequestedDefault;
+ case blink::WebRTCSdpSemantics::kPlanB:
+ return kSdpSemanticRequestedPlanB;
+ case blink::WebRTCSdpSemantics::kUnifiedPlan:
+ return kSdpSemanticRequestedUnifiedPlan;
+ }
+ NOTREACHED();
+ return kSdpSemanticRequestedDefault;
+}
+
} // namespace
// Implementation of LocalRTCStatsRequest.
@@ -1052,9 +1005,7 @@ class RTCPeerConnectionHandler::WebRtcSetRemoteDescriptionObserverImpl
PeerConnectionTracker::ACTION_SET_REMOTE_DESCRIPTION, "OnFailure",
error.message());
}
- // TODO(hbos): Use |error.type()| to reject the promise with the
- // appropriate DOMException.
- web_request_.RequestFailed(blink::WebString::FromUTF8(error.message()));
+ web_request_.RequestFailed(ConvertToWebKitRTCError(error));
web_request_.Reset();
return;
}
@@ -1336,7 +1287,8 @@ RTCPeerConnectionHandler::RTCPeerConnectionHandler(
blink::WebRTCPeerConnectionHandlerClient* client,
PeerConnectionDependencyFactory* dependency_factory,
scoped_refptr<base::SingleThreadTaskRunner> task_runner)
- : initialize_called_(false),
+ : id_(base::ToUpperASCII(base::UnguessableToken::Create().ToString())),
+ initialize_called_(false),
client_(client),
is_closed_(false),
dependency_factory_(dependency_factory),
@@ -1349,6 +1301,7 @@ RTCPeerConnectionHandler::RTCPeerConnectionHandler(
task_runner_(std::move(task_runner)),
weak_factory_(this) {
CHECK(client_);
+
GetPeerConnectionHandlers()->insert(this);
}
@@ -1414,6 +1367,12 @@ bool RTCPeerConnectionHandler::Initialize(
uma_observer_ = new rtc::RefCountedObject<PeerConnectionUMAObserver>();
native_peer_connection_->RegisterUMAObserver(uma_observer_.get());
+
+ UMA_HISTOGRAM_ENUMERATION(
+ "WebRTC.PeerConnection.SdpSemanticRequested",
+ GetSdpSemanticRequested(server_configuration.sdp_semantics),
+ kSdpSemanticRequestedMax);
+
return true;
}
@@ -1556,7 +1515,9 @@ void RTCPeerConnectionHandler::SetLocalDescription(
reason_str.append(" ");
reason_str.append(error.description);
LOG(ERROR) << reason_str;
- request.RequestFailed(blink::WebString::FromUTF8(reason_str));
+ request.RequestFailed(
+ blink::WebRTCError(blink::WebRTCErrorType::kOperationError,
+ blink::WebString::FromUTF8(reason_str)));
if (peer_connection_tracker_) {
peer_connection_tracker_->TrackSessionDescriptionCallback(
this, PeerConnectionTracker::ACTION_SET_LOCAL_DESCRIPTION,
@@ -1614,7 +1575,9 @@ void RTCPeerConnectionHandler::SetRemoteDescription(
reason_str.append(" ");
reason_str.append(error.description);
LOG(ERROR) << reason_str;
- request.RequestFailed(blink::WebString::FromUTF8(reason_str));
+ request.RequestFailed(
+ blink::WebRTCError(blink::WebRTCErrorType::kOperationError,
+ blink::WebString::FromUTF8(reason_str)));
if (peer_connection_tracker_) {
peer_connection_tracker_->TrackSessionDescriptionCallback(
this, PeerConnectionTracker::ACTION_SET_REMOTE_DESCRIPTION,
@@ -1672,8 +1635,9 @@ blink::WebRTCSessionDescription RTCPeerConnectionHandler::LocalDescription() {
base::Bind(&webrtc::PeerConnectionInterface::local_description,
native_peer_connection_);
RunSynchronousClosureOnSignalingThread(
- base::Bind(&GetSdpAndTypeFromSessionDescription, description_cb,
- base::Unretained(&sdp), base::Unretained(&type)),
+ base::Bind(&GetSdpAndTypeFromSessionDescription,
+ std::move(description_cb), base::Unretained(&sdp),
+ base::Unretained(&type)),
"localDescription");
return CreateWebKitSessionDescription(sdp, type);
@@ -1691,8 +1655,9 @@ blink::WebRTCSessionDescription RTCPeerConnectionHandler::RemoteDescription() {
base::Bind(&webrtc::PeerConnectionInterface::remote_description,
native_peer_connection_);
RunSynchronousClosureOnSignalingThread(
- base::Bind(&GetSdpAndTypeFromSessionDescription, description_cb,
- base::Unretained(&sdp), base::Unretained(&type)),
+ base::Bind(&GetSdpAndTypeFromSessionDescription,
+ std::move(description_cb), base::Unretained(&sdp),
+ base::Unretained(&type)),
"remoteDescription");
return CreateWebKitSessionDescription(sdp, type);
@@ -1708,14 +1673,12 @@ blink::WebRTCErrorType RTCPeerConnectionHandler::SetConfiguration(
peer_connection_tracker_->TrackSetConfiguration(this, configuration_);
webrtc::RTCError webrtc_error;
- blink::WebRTCError blink_error;
bool ret =
native_peer_connection_->SetConfiguration(configuration_, &webrtc_error);
// The boolean return value is made redundant by the error output param; just
// DCHECK that they're consistent.
DCHECK_EQ(ret, webrtc_error.type() == webrtc::RTCErrorType::NONE);
- ConvertToWebKitRTCError(webrtc_error, &blink_error);
- return blink_error.GetType();
+ return ConvertToWebKitRTCError(webrtc_error).GetType();
}
bool RTCPeerConnectionHandler::AddICECandidate(
@@ -1770,8 +1733,9 @@ void RTCPeerConnectionHandler::OnaddICECandidateResult(
if (!result) {
// We don't have the actual error code from the libjingle, so for now
// using a generic error string.
- return webkit_request.RequestFailed(
- blink::WebString::FromUTF8("Error processing ICE candidate"));
+ return webkit_request.RequestFailed(blink::WebRTCError(
+ blink::WebRTCErrorType::kOperationError,
+ blink::WebString::FromUTF8("Error processing ICE candidate")));
}
return webkit_request.RequestSucceeded();
@@ -1857,8 +1821,8 @@ std::unique_ptr<blink::WebRTCRtpSender> RTCPeerConnectionHandler::AddTrack(
return nullptr;
DCHECK(FindSender(RTCRtpSender::getId(webrtc_sender)) == rtp_senders_.end());
rtp_senders_.push_back(std::make_unique<RTCRtpSender>(
- task_runner_, signaling_thread(), stream_adapter_map_,
- std::move(webrtc_sender), std::move(track_adapter),
+ native_peer_connection_, task_runner_, signaling_thread(),
+ stream_adapter_map_, std::move(webrtc_sender), std::move(track_adapter),
std::move(stream_adapters)));
for (const auto& stream_ref : rtp_senders_.back()->stream_refs()) {
if (GetLocalStreamUsageCount(rtp_senders_,
@@ -1998,6 +1962,10 @@ void RTCPeerConnectionHandler::Stop() {
is_closed_ = true;
}
+blink::WebString RTCPeerConnectionHandler::Id() const {
+ return blink::WebString::FromASCII(id_);
+}
+
void RTCPeerConnectionHandler::OnSignalingChange(
webrtc::PeerConnectionInterface::SignalingState new_state) {
DCHECK(thread_checker_.CalledOnValidThread());
@@ -2119,6 +2087,7 @@ void RTCPeerConnectionHandler::OnAddRemoteTrack(
.insert(std::make_pair(
receiver_id,
std::make_unique<RTCRtpReceiver>(
+ native_peer_connection_, task_runner_, signaling_thread(),
webrtc_receiver.get(), std::move(remote_track_adapter_ref),
std::move(remote_stream_adapter_refs))))
.first->second;
diff --git a/chromium/content/renderer/media/webrtc/rtc_peer_connection_handler.h b/chromium/content/renderer/media/webrtc/rtc_peer_connection_handler.h
index 768821fa21e..9a1af0d2f77 100644
--- a/chromium/content/renderer/media/webrtc/rtc_peer_connection_handler.h
+++ b/chromium/content/renderer/media/webrtc/rtc_peer_connection_handler.h
@@ -26,10 +26,10 @@
#include "content/renderer/media/webrtc/webrtc_media_stream_adapter_map.h"
#include "content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map.h"
#include "ipc/ipc_platform_file.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/WebRTCPeerConnectionHandler.h"
-#include "third_party/WebKit/public/platform/WebRTCStatsRequest.h"
-#include "third_party/WebKit/public/platform/WebRTCStatsResponse.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/platform/web_rtc_peer_connection_handler.h"
+#include "third_party/blink/public/platform/web_rtc_stats_request.h"
+#include "third_party/blink/public/platform/web_rtc_stats_response.h"
namespace blink {
class WebLocalFrame;
@@ -153,6 +153,7 @@ class CONTENT_EXPORT RTCPeerConnectionHandler
const blink::WebString& label,
const blink::WebRTCDataChannelInit& init) override;
void Stop() override;
+ blink::WebString Id() const override;
// Delegate functions to allow for mocking of WebKit interfaces.
// getStats takes ownership of request parameter.
@@ -244,6 +245,9 @@ class CONTENT_EXPORT RTCPeerConnectionHandler
void RunSynchronousClosureOnSignalingThread(const base::Closure& closure,
const char* trace_event_name);
+ // Corresponds to the experimental RTCPeerConnection.id read-only attribute.
+ const std::string id_;
+
// Initialize() is never expected to be called more than once, even if the
// first call fails.
bool initialize_called_;
diff --git a/chromium/content/renderer/media/webrtc/rtc_peer_connection_handler_unittest.cc b/chromium/content/renderer/media/webrtc/rtc_peer_connection_handler_unittest.cc
index 8462cc38b11..be6131649f3 100644
--- a/chromium/content/renderer/media/webrtc/rtc_peer_connection_handler_unittest.cc
+++ b/chromium/content/renderer/media/webrtc/rtc_peer_connection_handler_unittest.cc
@@ -5,6 +5,7 @@
#include "content/renderer/media/webrtc/rtc_peer_connection_handler.h"
#include <stddef.h>
+#include <string.h>
#include <map>
#include <memory>
@@ -38,25 +39,25 @@
#include "content/renderer/media/webrtc/rtc_stats.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebMediaConstraints.h"
-#include "third_party/WebKit/public/platform/WebMediaStream.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
-#include "third_party/WebKit/public/platform/WebRTCConfiguration.h"
-#include "third_party/WebKit/public/platform/WebRTCDTMFSenderHandler.h"
-#include "third_party/WebKit/public/platform/WebRTCDataChannelHandler.h"
-#include "third_party/WebKit/public/platform/WebRTCDataChannelInit.h"
-#include "third_party/WebKit/public/platform/WebRTCError.h"
-#include "third_party/WebKit/public/platform/WebRTCICECandidate.h"
-#include "third_party/WebKit/public/platform/WebRTCPeerConnectionHandlerClient.h"
-#include "third_party/WebKit/public/platform/WebRTCRtpReceiver.h"
-#include "third_party/WebKit/public/platform/WebRTCSessionDescription.h"
-#include "third_party/WebKit/public/platform/WebRTCSessionDescriptionRequest.h"
-#include "third_party/WebKit/public/platform/WebRTCStatsRequest.h"
-#include "third_party/WebKit/public/platform/WebRTCVoidRequest.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
-#include "third_party/WebKit/public/web/WebHeap.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/web_media_constraints.h"
+#include "third_party/blink/public/platform/web_media_stream.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
+#include "third_party/blink/public/platform/web_rtc_configuration.h"
+#include "third_party/blink/public/platform/web_rtc_data_channel_handler.h"
+#include "third_party/blink/public/platform/web_rtc_data_channel_init.h"
+#include "third_party/blink/public/platform/web_rtc_dtmf_sender_handler.h"
+#include "third_party/blink/public/platform/web_rtc_error.h"
+#include "third_party/blink/public/platform/web_rtc_ice_candidate.h"
+#include "third_party/blink/public/platform/web_rtc_peer_connection_handler_client.h"
+#include "third_party/blink/public/platform/web_rtc_rtp_receiver.h"
+#include "third_party/blink/public/platform/web_rtc_session_description.h"
+#include "third_party/blink/public/platform/web_rtc_session_description_request.h"
+#include "third_party/blink/public/platform/web_rtc_stats_request.h"
+#include "third_party/blink/public/platform/web_rtc_void_request.h"
+#include "third_party/blink/public/platform/web_url.h"
+#include "third_party/blink/public/web/web_heap.h"
#include "third_party/webrtc/api/peerconnectioninterface.h"
#include "third_party/webrtc/api/rtpreceiverinterface.h"
#include "third_party/webrtc/stats/test/rtcteststats.h"
@@ -270,9 +271,7 @@ class RTCPeerConnectionHandlerTest : public ::testing::Test {
void SetUp() override {
mock_client_.reset(new NiceMock<MockWebRTCPeerConnectionHandlerClient>());
mock_dependency_factory_.reset(new MockPeerConnectionDependencyFactory());
- pc_handler_.reset(
- new RTCPeerConnectionHandlerUnderTest(
- mock_client_.get(), mock_dependency_factory_.get()));
+ pc_handler_ = CreateRTCPeerConnectionHandlerUnderTest();
mock_tracker_.reset(new NiceMock<MockPeerConnectionTracker>());
blink::WebRTCConfiguration config;
blink::WebMediaConstraints constraints;
@@ -292,6 +291,12 @@ class RTCPeerConnectionHandlerTest : public ::testing::Test {
blink::WebHeap::CollectAllGarbageForTesting();
}
+ std::unique_ptr<RTCPeerConnectionHandlerUnderTest>
+ CreateRTCPeerConnectionHandlerUnderTest() {
+ return std::make_unique<RTCPeerConnectionHandlerUnderTest>(
+ mock_client_.get(), mock_dependency_factory_.get());
+ }
+
// Creates a WebKit local MediaStream.
blink::WebMediaStream CreateLocalMediaStream(
const std::string& stream_label) {
@@ -531,8 +536,8 @@ class RTCPeerConnectionHandlerTest : public ::testing::Test {
template <typename T>
void InvokeOnSignalingThread(T callback) {
- mock_dependency_factory_->GetWebRtcSignalingThread()->PostTask(FROM_HERE,
- callback);
+ mock_dependency_factory_->GetWebRtcSignalingThread()->PostTask(
+ FROM_HERE, std::move(callback));
RunMessageLoopsUntilIdle();
}
@@ -1542,4 +1547,16 @@ TEST_F(RTCPeerConnectionHandlerTest, CreateDataChannel) {
channel->SetClient(nullptr);
}
+TEST_F(RTCPeerConnectionHandlerTest, IdIsOfExpectedFormat) {
+ const std::string id = pc_handler_->Id().Ascii();
+ constexpr size_t expected_length = 32u;
+ EXPECT_EQ(id.length(), expected_length);
+ EXPECT_EQ(id.length(), strspn(id.c_str(), "0123456789ABCDEF"));
+}
+
+TEST_F(RTCPeerConnectionHandlerTest, IdIsNotRepeated) {
+ const auto other_pc_handler_ = CreateRTCPeerConnectionHandlerUnderTest();
+ EXPECT_NE(pc_handler_->Id(), other_pc_handler_->Id());
+}
+
} // namespace content
diff --git a/chromium/content/renderer/media/webrtc/rtc_rtp_contributing_source.h b/chromium/content/renderer/media/webrtc/rtc_rtp_contributing_source.h
index f287435e572..14395abf538 100644
--- a/chromium/content/renderer/media/webrtc/rtc_rtp_contributing_source.h
+++ b/chromium/content/renderer/media/webrtc/rtc_rtp_contributing_source.h
@@ -8,7 +8,7 @@
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebRTCRtpContributingSource.h"
+#include "third_party/blink/public/platform/web_rtc_rtp_contributing_source.h"
#include "third_party/webrtc/api/rtpreceiverinterface.h"
namespace content {
diff --git a/chromium/content/renderer/media/webrtc/rtc_rtp_parameters.cc b/chromium/content/renderer/media/webrtc/rtc_rtp_parameters.cc
new file mode 100644
index 00000000000..f3938c62d0f
--- /dev/null
+++ b/chromium/content/renderer/media/webrtc/rtc_rtp_parameters.cc
@@ -0,0 +1,158 @@
+// Copyright (c) 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/renderer/media/webrtc/rtc_rtp_parameters.h"
+
+#include <utility>
+
+namespace {
+
+// Relative weights for each priority as defined in RTCWEB-DATA
+// https://tools.ietf.org/html/draft-ietf-rtcweb-data-channel
+const double kPriorityWeightVeryLow = 0.5;
+const double kPriorityWeightLow = 1;
+const double kPriorityWeightMedium = 2;
+const double kPriorityWeightHigh = 4;
+
+template <typename T, typename F>
+base::Optional<T> ToBaseOptional(const rtc::Optional<F>& from) {
+ if (from)
+ return from.value();
+ return base::nullopt;
+}
+
+blink::WebRTCPriorityType PriorityFromDouble(double priority) {
+ // Find the middle point between 2 priority weights to match them to a
+ // WebRTC priority
+ const double very_low_upper_bound =
+ (kPriorityWeightVeryLow + kPriorityWeightLow) / 2;
+ const double low_upper_bound =
+ (kPriorityWeightLow + kPriorityWeightMedium) / 2;
+ const double medium_upper_bound =
+ (kPriorityWeightMedium + kPriorityWeightHigh) / 2;
+
+ if (priority < webrtc::kDefaultBitratePriority * very_low_upper_bound) {
+ return blink::WebRTCPriorityType::VeryLow;
+ }
+ if (priority < webrtc::kDefaultBitratePriority * low_upper_bound) {
+ return blink::WebRTCPriorityType::Low;
+ }
+ if (priority < webrtc::kDefaultBitratePriority * medium_upper_bound) {
+ return blink::WebRTCPriorityType::Medium;
+ }
+ return blink::WebRTCPriorityType::High;
+}
+
+base::Optional<blink::WebRTCDtxStatus> FromRTCDtxStatus(
+ rtc::Optional<webrtc::DtxStatus> status) {
+ if (!status)
+ return base::nullopt;
+
+ blink::WebRTCDtxStatus result;
+ switch (status.value()) {
+ case webrtc::DtxStatus::DISABLED:
+ result = blink::WebRTCDtxStatus::Disabled;
+ break;
+ case webrtc::DtxStatus::ENABLED:
+ result = blink::WebRTCDtxStatus::Enabled;
+ break;
+ default:
+ NOTREACHED();
+ }
+ return result;
+}
+
+base::Optional<blink::WebRTCDegradationPreference> FromRTCDegradationPreference(
+ rtc::Optional<webrtc::DegradationPreference> degradation_preference) {
+ if (!degradation_preference)
+ return base::nullopt;
+
+ blink::WebRTCDegradationPreference result;
+ switch (degradation_preference.value()) {
+ case webrtc::DegradationPreference::MAINTAIN_FRAMERATE:
+ result = blink::WebRTCDegradationPreference::MaintainFramerate;
+ break;
+ case webrtc::DegradationPreference::MAINTAIN_RESOLUTION:
+ result = blink::WebRTCDegradationPreference::MaintainResolution;
+ break;
+ case webrtc::DegradationPreference::BALANCED:
+ result = blink::WebRTCDegradationPreference::Balanced;
+ break;
+ default:
+ NOTREACHED();
+ }
+ return result;
+}
+
+} // namespace
+
+namespace content {
+
+blink::WebRTCRtpParameters GetWebRTCRtpParameters(
+ const webrtc::RtpParameters& parameters) {
+ blink::WebVector<blink::WebRTCRtpEncodingParameters> encodings;
+ encodings.reserve(parameters.encodings.size());
+ for (const auto& encoding_parameter : parameters.encodings) {
+ encodings.emplace_back(GetWebRTCRtpEncodingParameters(encoding_parameter));
+ }
+
+ blink::WebVector<blink::WebRTCRtpHeaderExtensionParameters> header_extensions;
+ header_extensions.reserve(parameters.header_extensions.size());
+ for (const auto& extension_parameter : parameters.header_extensions) {
+ header_extensions.emplace_back(
+ GetWebRTCRtpHeaderExtensionParameters(extension_parameter));
+ }
+
+ blink::WebVector<blink::WebRTCRtpCodecParameters> codec_parameters;
+ codec_parameters.reserve(parameters.codecs.size());
+ for (const auto& codec_parameter : parameters.codecs) {
+ codec_parameters.emplace_back(GetWebRTCRtpCodecParameters(codec_parameter));
+ }
+
+ return blink::WebRTCRtpParameters(
+ blink::WebString::FromASCII(parameters.transaction_id),
+ blink::WebRTCRtcpParameters(), std::move(encodings), header_extensions,
+ codec_parameters,
+ FromRTCDegradationPreference(parameters.degradation_preference));
+}
+
+blink::WebRTCRtpEncodingParameters GetWebRTCRtpEncodingParameters(
+ const webrtc::RtpEncodingParameters& encoding_parameters) {
+ return blink::WebRTCRtpEncodingParameters(
+ ToBaseOptional<uint8_t>(encoding_parameters.codec_payload_type),
+ FromRTCDtxStatus(encoding_parameters.dtx), encoding_parameters.active,
+ PriorityFromDouble(encoding_parameters.bitrate_priority),
+ ToBaseOptional<uint32_t>(encoding_parameters.ptime),
+ ToBaseOptional<uint32_t>(encoding_parameters.max_bitrate_bps),
+ ToBaseOptional<uint32_t>(encoding_parameters.max_framerate),
+ encoding_parameters.scale_framerate_down_by,
+ blink::WebString::FromASCII(encoding_parameters.rid));
+}
+
+blink::WebRTCRtpHeaderExtensionParameters GetWebRTCRtpHeaderExtensionParameters(
+ const webrtc::RtpHeaderExtensionParameters& extension_parameters) {
+ return blink::WebRTCRtpHeaderExtensionParameters(
+ blink::WebString::FromASCII(extension_parameters.uri),
+ extension_parameters.id, extension_parameters.encrypt);
+}
+
+// TODO(orphis): Copy the RTCP information
+// https://crbug.com/webrtc/7580
+blink::WebRTCRtcpParameters GetWebRTCRtcpParameters() {
+ return blink::WebRTCRtcpParameters();
+}
+
+blink::WebRTCRtpCodecParameters GetWebRTCRtpCodecParameters(
+ const webrtc::RtpCodecParameters& codec_parameters) {
+ return blink::WebRTCRtpCodecParameters(
+ codec_parameters.payload_type,
+ blink::WebString::FromASCII(codec_parameters.mime_type()),
+ ToBaseOptional<uint32_t>(codec_parameters.clock_rate),
+ ToBaseOptional<uint16_t>(codec_parameters.num_channels),
+ // TODO(orphis): Convert the parameters field to sdpFmtpLine
+ // https://crbug.com/webrtc/7580
+ blink::WebString());
+}
+
+} // namespace content
diff --git a/chromium/content/renderer/media/webrtc/rtc_rtp_parameters.h b/chromium/content/renderer/media/webrtc/rtc_rtp_parameters.h
new file mode 100644
index 00000000000..b8147eea16b
--- /dev/null
+++ b/chromium/content/renderer/media/webrtc/rtc_rtp_parameters.h
@@ -0,0 +1,33 @@
+// Copyright (c) 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_RENDERER_MEDIA_WEBRTC_RTC_RTP_PARAMETERS_H_
+#define CONTENT_RENDERER_MEDIA_WEBRTC_RTC_RTP_PARAMETERS_H_
+
+#include "base/memory/ref_counted.h"
+#include "content/common/content_export.h"
+#include "third_party/blink/public/platform/web_rtc_rtp_parameters.h"
+#include "third_party/webrtc/api/rtpparameters.h"
+
+namespace content {
+
+CONTENT_EXPORT blink::WebRTCRtpEncodingParameters
+GetWebRTCRtpEncodingParameters(
+ const webrtc::RtpEncodingParameters& encoding_parameters);
+
+CONTENT_EXPORT blink::WebRTCRtpHeaderExtensionParameters
+GetWebRTCRtpHeaderExtensionParameters(
+ const webrtc::RtpHeaderExtensionParameters& extension_parameters);
+
+CONTENT_EXPORT blink::WebRTCRtcpParameters GetWebRTCRtcpParameters();
+
+CONTENT_EXPORT blink::WebRTCRtpCodecParameters GetWebRTCRtpCodecParameters(
+ const webrtc::RtpCodecParameters& codec_parameters);
+
+CONTENT_EXPORT blink::WebRTCRtpParameters GetWebRTCRtpParameters(
+ const webrtc::RtpParameters& parameters);
+
+} // namespace content
+
+#endif // CONTENT_RENDERER_MEDIA_WEBRTC_RTC_RTP_PARAMETERS_H_
diff --git a/chromium/content/renderer/media/webrtc/rtc_rtp_parameters_unittest.cc b/chromium/content/renderer/media/webrtc/rtc_rtp_parameters_unittest.cc
new file mode 100644
index 00000000000..b1d1629e9ee
--- /dev/null
+++ b/chromium/content/renderer/media/webrtc/rtc_rtp_parameters_unittest.cc
@@ -0,0 +1,165 @@
+// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/renderer/media/webrtc/rtc_rtp_parameters.h"
+
+#include "testing/gtest/include/gtest/gtest.h"
+
+namespace content {
+
+TEST(RTCRtpParametersTest, Read) {
+ webrtc::RtpParameters webrtc_parameters;
+ webrtc_parameters.transaction_id = "transaction_id";
+ webrtc_parameters.degradation_preference =
+ webrtc::DegradationPreference::BALANCED;
+
+ webrtc_parameters.encodings.emplace_back();
+ webrtc::RtpEncodingParameters& webrtc_encoding =
+ webrtc_parameters.encodings.front();
+ webrtc_encoding.codec_payload_type = 42;
+ webrtc_encoding.dtx = webrtc::DtxStatus::ENABLED;
+ webrtc_encoding.active = true;
+ webrtc_encoding.bitrate_priority = webrtc::kDefaultBitratePriority;
+ webrtc_encoding.ptime = 1337;
+ webrtc_encoding.max_bitrate_bps = 1337000;
+ webrtc_encoding.max_framerate = 60;
+ webrtc_encoding.scale_resolution_down_by = 1.;
+ webrtc_encoding.rid = "rid";
+
+ webrtc_parameters.header_extensions.emplace_back();
+ webrtc::RtpHeaderExtensionParameters& webrtc_header_extension =
+ webrtc_parameters.header_extensions.front();
+ webrtc_header_extension.uri = "uri";
+ webrtc_header_extension.id = 33;
+ webrtc_header_extension.encrypt = true;
+
+ webrtc_parameters.codecs.emplace_back();
+ webrtc::RtpCodecParameters& webrtc_codec_parameter =
+ webrtc_parameters.codecs.front();
+ webrtc_codec_parameter.payload_type = 42;
+ webrtc_codec_parameter.clock_rate = 1234;
+ webrtc_codec_parameter.num_channels = 2;
+
+ blink::WebRTCRtpParameters parameters =
+ GetWebRTCRtpParameters(webrtc_parameters);
+ EXPECT_EQ(parameters.TransactionId(), "transaction_id");
+ EXPECT_EQ(parameters.DegradationPreference(),
+ blink::WebRTCDegradationPreference::Balanced);
+
+ ASSERT_EQ(parameters.Encodings().size(), 1u);
+ for (const auto& encoding : parameters.Encodings()) {
+ EXPECT_EQ(encoding.CodecPayloadType(), 42);
+ EXPECT_EQ(encoding.Dtx(), blink::WebRTCDtxStatus::Enabled);
+ EXPECT_EQ(encoding.Active(), true);
+ EXPECT_EQ(encoding.Priority(), blink::WebRTCPriorityType::Low);
+ EXPECT_EQ(encoding.Ptime(), 1337u);
+ EXPECT_EQ(encoding.MaxBitrate(), 1337000u);
+ EXPECT_EQ(encoding.MaxFramerate(), 60u);
+ EXPECT_EQ(encoding.ScaleResolutionDownBy(), 1.);
+ EXPECT_EQ(encoding.Rid(), "rid");
+ }
+
+ ASSERT_EQ(parameters.HeaderExtensions().size(), 1u);
+ for (const auto& header_extension : parameters.HeaderExtensions()) {
+ EXPECT_EQ(header_extension.URI(), "uri");
+ EXPECT_EQ(header_extension.Id(), 33);
+ EXPECT_EQ(header_extension.Encrypted(), true);
+ }
+
+ ASSERT_EQ(parameters.Codecs().size(), 1u);
+ for (const auto& codec : parameters.Codecs()) {
+ EXPECT_EQ(codec.PayloadType(), 42);
+ EXPECT_EQ(codec.ClockRate(), 1234u);
+ EXPECT_EQ(codec.Channels(), 2u);
+ }
+}
+
+TEST(RTCRtpParametersTest, CheckDtxStatusEnum) {
+ webrtc::RtpEncodingParameters webrtc_encoding_parameters;
+
+ {
+ webrtc_encoding_parameters.dtx = webrtc::DtxStatus::DISABLED;
+ blink::WebRTCRtpEncodingParameters encoding_parameters =
+ GetWebRTCRtpEncodingParameters(webrtc_encoding_parameters);
+ EXPECT_EQ(encoding_parameters.Dtx(), blink::WebRTCDtxStatus::Disabled);
+ }
+
+ {
+ webrtc_encoding_parameters.dtx = webrtc::DtxStatus::ENABLED;
+ blink::WebRTCRtpEncodingParameters encoding_parameters =
+ GetWebRTCRtpEncodingParameters(webrtc_encoding_parameters);
+ EXPECT_EQ(encoding_parameters.Dtx(), blink::WebRTCDtxStatus::Enabled);
+ }
+}
+
+TEST(RTCRtpParametersTest, CheckDegradationPreferenceEnum) {
+ webrtc::RtpParameters webrtc_parameters;
+
+ {
+ webrtc_parameters.degradation_preference =
+ webrtc::DegradationPreference::MAINTAIN_FRAMERATE;
+ blink::WebRTCRtpParameters parameters =
+ GetWebRTCRtpParameters(webrtc_parameters);
+ EXPECT_EQ(parameters.DegradationPreference(),
+ blink::WebRTCDegradationPreference::MaintainFramerate);
+ }
+
+ {
+ webrtc_parameters.degradation_preference =
+ webrtc::DegradationPreference::MAINTAIN_RESOLUTION;
+ blink::WebRTCRtpParameters parameters =
+ GetWebRTCRtpParameters(webrtc_parameters);
+ EXPECT_EQ(parameters.DegradationPreference(),
+ blink::WebRTCDegradationPreference::MaintainResolution);
+ }
+
+ {
+ webrtc_parameters.degradation_preference =
+ webrtc::DegradationPreference::BALANCED;
+ blink::WebRTCRtpParameters parameters =
+ GetWebRTCRtpParameters(webrtc_parameters);
+ EXPECT_EQ(parameters.DegradationPreference(),
+ blink::WebRTCDegradationPreference::Balanced);
+ }
+}
+
+TEST(RTCRtpParametersTest, CheckPriorityEnum) {
+ webrtc::RtpEncodingParameters webrtc_encoding_parameters;
+
+ {
+ webrtc_encoding_parameters.bitrate_priority =
+ webrtc::kDefaultBitratePriority / 2;
+ blink::WebRTCRtpEncodingParameters encoding_parameters =
+ GetWebRTCRtpEncodingParameters(webrtc_encoding_parameters);
+ EXPECT_EQ(encoding_parameters.Priority(),
+ blink::WebRTCPriorityType::VeryLow);
+ }
+
+ {
+ webrtc_encoding_parameters.bitrate_priority =
+ webrtc::kDefaultBitratePriority;
+ blink::WebRTCRtpEncodingParameters encoding_parameters =
+ GetWebRTCRtpEncodingParameters(webrtc_encoding_parameters);
+ EXPECT_EQ(encoding_parameters.Priority(), blink::WebRTCPriorityType::Low);
+ }
+
+ {
+ webrtc_encoding_parameters.bitrate_priority =
+ webrtc::kDefaultBitratePriority * 2;
+ blink::WebRTCRtpEncodingParameters encoding_parameters =
+ GetWebRTCRtpEncodingParameters(webrtc_encoding_parameters);
+ EXPECT_EQ(encoding_parameters.Priority(),
+ blink::WebRTCPriorityType::Medium);
+ }
+
+ {
+ webrtc_encoding_parameters.bitrate_priority =
+ webrtc::kDefaultBitratePriority * 4;
+ blink::WebRTCRtpEncodingParameters encoding_parameters =
+ GetWebRTCRtpEncodingParameters(webrtc_encoding_parameters);
+ EXPECT_EQ(encoding_parameters.Priority(), blink::WebRTCPriorityType::High);
+ }
+}
+
+} // namespace content
diff --git a/chromium/content/renderer/media/webrtc/rtc_rtp_receiver.cc b/chromium/content/renderer/media/webrtc/rtc_rtp_receiver.cc
index 5a5f854731d..a988bd10bb5 100644
--- a/chromium/content/renderer/media/webrtc/rtc_rtp_receiver.cc
+++ b/chromium/content/renderer/media/webrtc/rtc_rtp_receiver.cc
@@ -5,98 +5,213 @@
#include "content/renderer/media/webrtc/rtc_rtp_receiver.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "content/renderer/media/webrtc/rtc_rtp_contributing_source.h"
+#include "content/renderer/media/webrtc/rtc_stats.h"
#include "third_party/webrtc/rtc_base/scoped_ref_ptr.h"
namespace content {
+class RTCRtpReceiver::RTCRtpReceiverInternal
+ : public base::RefCountedThreadSafe<
+ RTCRtpReceiver::RTCRtpReceiverInternal,
+ RTCRtpReceiver::RTCRtpReceiverInternalTraits> {
+ public:
+ RTCRtpReceiverInternal(
+ scoped_refptr<webrtc::PeerConnectionInterface> native_peer_connection,
+ scoped_refptr<base::SingleThreadTaskRunner> main_thread,
+ scoped_refptr<base::SingleThreadTaskRunner> signaling_thread,
+ rtc::scoped_refptr<webrtc::RtpReceiverInterface> webrtc_receiver,
+ std::unique_ptr<WebRtcMediaStreamTrackAdapterMap::AdapterRef>
+ track_adapter,
+ std::vector<std::unique_ptr<WebRtcMediaStreamAdapterMap::AdapterRef>>
+ stream_adapter_refs)
+ : native_peer_connection_(std::move(native_peer_connection)),
+ main_thread_(std::move(main_thread)),
+ signaling_thread_(std::move(signaling_thread)),
+ webrtc_receiver_(std::move(webrtc_receiver)),
+ track_adapter_(std::move(track_adapter)),
+ stream_adapter_refs_(std::move(stream_adapter_refs)) {
+ DCHECK(webrtc_receiver_);
+ DCHECK(track_adapter_);
+ }
+
+ const blink::WebMediaStreamTrack& Track() const {
+ return track_adapter_->web_track();
+ }
+
+ blink::WebVector<blink::WebMediaStream> Streams() const {
+ blink::WebVector<blink::WebMediaStream> web_streams(
+ stream_adapter_refs_.size());
+ for (size_t i = 0; i < stream_adapter_refs_.size(); ++i)
+ web_streams[i] = stream_adapter_refs_[i]->adapter().web_stream();
+ return web_streams;
+ }
+
+ blink::WebVector<std::unique_ptr<blink::WebRTCRtpContributingSource>>
+ GetSources() {
+ auto webrtc_sources = webrtc_receiver_->GetSources();
+ blink::WebVector<std::unique_ptr<blink::WebRTCRtpContributingSource>>
+ sources(webrtc_sources.size());
+ for (size_t i = 0; i < webrtc_sources.size(); ++i) {
+ sources[i] =
+ std::make_unique<RTCRtpContributingSource>(webrtc_sources[i]);
+ }
+ return sources;
+ }
+
+ void GetStats(std::unique_ptr<blink::WebRTCStatsReportCallback> callback) {
+ signaling_thread_->PostTask(
+ FROM_HERE,
+ base::BindOnce(&RTCRtpReceiverInternal::GetStatsOnSignalingThread, this,
+ std::move(callback)));
+ }
+
+ webrtc::RtpReceiverInterface* webrtc_receiver() const {
+ return webrtc_receiver_.get();
+ }
+
+ const webrtc::MediaStreamTrackInterface& webrtc_track() const {
+ DCHECK(track_adapter_->webrtc_track());
+ return *track_adapter_->webrtc_track();
+ }
+
+ bool HasStream(const webrtc::MediaStreamInterface* webrtc_stream) const {
+ for (const auto& stream_adapter : stream_adapter_refs_) {
+ if (webrtc_stream == stream_adapter->adapter().webrtc_stream().get())
+ return true;
+ }
+ return false;
+ }
+
+ std::vector<std::unique_ptr<WebRtcMediaStreamAdapterMap::AdapterRef>>
+ StreamAdapterRefs() const {
+ std::vector<std::unique_ptr<WebRtcMediaStreamAdapterMap::AdapterRef>>
+ stream_adapter_copies;
+ stream_adapter_copies.reserve(stream_adapter_refs_.size());
+ for (const auto& stream_adapter : stream_adapter_refs_) {
+ stream_adapter_copies.push_back(stream_adapter->Copy());
+ }
+ return stream_adapter_copies;
+ }
+
+ private:
+ friend struct RTCRtpReceiver::RTCRtpReceiverInternalTraits;
+
+ ~RTCRtpReceiverInternal() { DCHECK(main_thread_->BelongsToCurrentThread()); }
+
+ void GetStatsOnSignalingThread(
+ std::unique_ptr<blink::WebRTCStatsReportCallback> callback) {
+ native_peer_connection_->GetStats(webrtc_receiver_,
+ RTCStatsCollectorCallbackImpl::Create(
+ main_thread_, std::move(callback)));
+ }
+
+ const scoped_refptr<webrtc::PeerConnectionInterface> native_peer_connection_;
+ const scoped_refptr<base::SingleThreadTaskRunner> main_thread_;
+ const scoped_refptr<base::SingleThreadTaskRunner> signaling_thread_;
+ const rtc::scoped_refptr<webrtc::RtpReceiverInterface> webrtc_receiver_;
+ // The track adapter is the glue between blink and webrtc layer tracks.
+ // Keeping a reference to the adapter ensures it is not disposed, as is
+ // required as long as the webrtc layer track is in use by the receiver.
+ std::unique_ptr<WebRtcMediaStreamTrackAdapterMap::AdapterRef> track_adapter_;
+ // Similarly, references needs to be kept to the stream adapters of streams
+ // associated with the receiver.
+ std::vector<std::unique_ptr<WebRtcMediaStreamAdapterMap::AdapterRef>>
+ stream_adapter_refs_;
+};
+
+struct RTCRtpReceiver::RTCRtpReceiverInternalTraits {
+ private:
+ friend class base::RefCountedThreadSafe<RTCRtpReceiverInternal,
+ RTCRtpReceiverInternalTraits>;
+
+ static void Destruct(const RTCRtpReceiverInternal* receiver) {
+ // RTCRtpReceiverInternal owns AdapterRefs which have to be destroyed on the
+ // main thread, this ensures delete always happens there.
+ if (!receiver->main_thread_->BelongsToCurrentThread()) {
+ receiver->main_thread_->PostTask(
+ FROM_HERE,
+ base::BindOnce(
+ &RTCRtpReceiver::RTCRtpReceiverInternalTraits::Destruct,
+ base::Unretained(receiver)));
+ return;
+ }
+ delete receiver;
+ }
+};
+
uintptr_t RTCRtpReceiver::getId(
const webrtc::RtpReceiverInterface* webrtc_rtp_receiver) {
return reinterpret_cast<uintptr_t>(webrtc_rtp_receiver);
}
RTCRtpReceiver::RTCRtpReceiver(
+ scoped_refptr<webrtc::PeerConnectionInterface> native_peer_connection,
+ scoped_refptr<base::SingleThreadTaskRunner> main_thread,
+ scoped_refptr<base::SingleThreadTaskRunner> signaling_thread,
rtc::scoped_refptr<webrtc::RtpReceiverInterface> webrtc_receiver,
std::unique_ptr<WebRtcMediaStreamTrackAdapterMap::AdapterRef> track_adapter,
std::vector<std::unique_ptr<WebRtcMediaStreamAdapterMap::AdapterRef>>
stream_adapter_refs)
- : webrtc_receiver_(std::move(webrtc_receiver)),
- track_adapter_(std::move(track_adapter)),
- stream_adapter_refs_(std::move(stream_adapter_refs)) {
- DCHECK(webrtc_receiver_);
- DCHECK(track_adapter_);
-}
+ : internal_(new RTCRtpReceiverInternal(std::move(native_peer_connection),
+ std::move(main_thread),
+ std::move(signaling_thread),
+ std::move(webrtc_receiver),
+ std::move(track_adapter),
+ std::move(stream_adapter_refs))) {}
+
+RTCRtpReceiver::RTCRtpReceiver(const RTCRtpReceiver& other)
+ : internal_(other.internal_) {}
RTCRtpReceiver::~RTCRtpReceiver() {}
+RTCRtpReceiver& RTCRtpReceiver::operator=(const RTCRtpReceiver& other) {
+ internal_ = other.internal_;
+ return *this;
+}
+
std::unique_ptr<RTCRtpReceiver> RTCRtpReceiver::ShallowCopy() const {
- std::vector<std::unique_ptr<WebRtcMediaStreamAdapterMap::AdapterRef>>
- stream_adapter_ref_copies(stream_adapter_refs_.size());
- for (size_t i = 0; i < stream_adapter_refs_.size(); ++i) {
- stream_adapter_ref_copies[i] = stream_adapter_refs_[i]->Copy();
- }
- return std::make_unique<RTCRtpReceiver>(webrtc_receiver_,
- track_adapter_->Copy(),
- std::move(stream_adapter_ref_copies));
+ return std::make_unique<RTCRtpReceiver>(*this);
}
uintptr_t RTCRtpReceiver::Id() const {
- return getId(webrtc_receiver_.get());
+ return getId(internal_->webrtc_receiver());
}
const blink::WebMediaStreamTrack& RTCRtpReceiver::Track() const {
- DCHECK(track_adapter_->webrtc_track() == webrtc_receiver_->track());
- return track_adapter_->web_track();
+ return internal_->Track();
}
blink::WebVector<blink::WebMediaStream> RTCRtpReceiver::Streams() const {
- blink::WebVector<blink::WebMediaStream> web_streams(
- stream_adapter_refs_.size());
- for (size_t i = 0; i < stream_adapter_refs_.size(); ++i)
- web_streams[i] = stream_adapter_refs_[i]->adapter().web_stream();
- return web_streams;
+ return internal_->Streams();
}
blink::WebVector<std::unique_ptr<blink::WebRTCRtpContributingSource>>
RTCRtpReceiver::GetSources() {
- auto webrtc_sources = webrtc_receiver_->GetSources();
- blink::WebVector<std::unique_ptr<blink::WebRTCRtpContributingSource>> sources(
- webrtc_sources.size());
- for (size_t i = 0; i < webrtc_sources.size(); ++i) {
- sources[i] = std::make_unique<RTCRtpContributingSource>(webrtc_sources[i]);
- }
- return sources;
+ return internal_->GetSources();
+}
+
+void RTCRtpReceiver::GetStats(
+ std::unique_ptr<blink::WebRTCStatsReportCallback> callback) {
+ internal_->GetStats(std::move(callback));
}
webrtc::RtpReceiverInterface* RTCRtpReceiver::webrtc_receiver() const {
- return webrtc_receiver_.get();
+ return internal_->webrtc_receiver();
}
const webrtc::MediaStreamTrackInterface& RTCRtpReceiver::webrtc_track() const {
- DCHECK(track_adapter_->webrtc_track() == webrtc_receiver_->track());
- DCHECK(track_adapter_->webrtc_track());
- return *track_adapter_->webrtc_track();
+ return internal_->webrtc_track();
}
bool RTCRtpReceiver::HasStream(
const webrtc::MediaStreamInterface* webrtc_stream) const {
- for (const auto& stream_adapter : stream_adapter_refs_) {
- if (webrtc_stream == stream_adapter->adapter().webrtc_stream().get())
- return true;
- }
- return false;
+ return internal_->HasStream(webrtc_stream);
}
std::vector<std::unique_ptr<WebRtcMediaStreamAdapterMap::AdapterRef>>
RTCRtpReceiver::StreamAdapterRefs() const {
- std::vector<std::unique_ptr<WebRtcMediaStreamAdapterMap::AdapterRef>>
- stream_adapter_copies;
- stream_adapter_copies.reserve(stream_adapter_refs_.size());
- for (const auto& stream_adapter : stream_adapter_refs_) {
- stream_adapter_copies.push_back(stream_adapter->Copy());
- }
- return stream_adapter_copies;
+ return internal_->StreamAdapterRefs();
}
} // namespace content
diff --git a/chromium/content/renderer/media/webrtc/rtc_rtp_receiver.h b/chromium/content/renderer/media/webrtc/rtc_rtp_receiver.h
index e9daa24dbb7..5d0c6b743ed 100644
--- a/chromium/content/renderer/media/webrtc/rtc_rtp_receiver.h
+++ b/chromium/content/renderer/media/webrtc/rtc_rtp_receiver.h
@@ -10,10 +10,11 @@
#include "content/common/content_export.h"
#include "content/renderer/media/webrtc/webrtc_media_stream_adapter_map.h"
#include "content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map.h"
-#include "third_party/WebKit/public/platform/WebMediaStream.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
-#include "third_party/WebKit/public/platform/WebRTCRtpReceiver.h"
+#include "third_party/blink/public/platform/web_media_stream.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
+#include "third_party/blink/public/platform/web_rtc_rtp_receiver.h"
#include "third_party/webrtc/api/mediastreaminterface.h"
+#include "third_party/webrtc/api/peerconnectioninterface.h"
#include "third_party/webrtc/api/rtpreceiverinterface.h"
namespace content {
@@ -27,13 +28,19 @@ class CONTENT_EXPORT RTCRtpReceiver : public blink::WebRTCRtpReceiver {
const webrtc::RtpReceiverInterface* webrtc_rtp_receiver);
RTCRtpReceiver(
+ scoped_refptr<webrtc::PeerConnectionInterface> native_peer_connection,
+ scoped_refptr<base::SingleThreadTaskRunner> main_thread,
+ scoped_refptr<base::SingleThreadTaskRunner> signaling_thread,
rtc::scoped_refptr<webrtc::RtpReceiverInterface> webrtc_receiver,
std::unique_ptr<WebRtcMediaStreamTrackAdapterMap::AdapterRef>
track_adapter,
std::vector<std::unique_ptr<WebRtcMediaStreamAdapterMap::AdapterRef>>
stream_adapter_refs);
+ RTCRtpReceiver(const RTCRtpReceiver& other);
~RTCRtpReceiver() override;
+ RTCRtpReceiver& operator=(const RTCRtpReceiver& other);
+
// Creates a shallow copy of the receiver, representing the same underlying
// webrtc receiver as the original.
std::unique_ptr<RTCRtpReceiver> ShallowCopy() const;
@@ -43,6 +50,7 @@ class CONTENT_EXPORT RTCRtpReceiver : public blink::WebRTCRtpReceiver {
blink::WebVector<blink::WebMediaStream> Streams() const override;
blink::WebVector<std::unique_ptr<blink::WebRTCRtpContributingSource>>
GetSources() override;
+ void GetStats(std::unique_ptr<blink::WebRTCStatsReportCallback>) override;
webrtc::RtpReceiverInterface* webrtc_receiver() const;
const webrtc::MediaStreamTrackInterface& webrtc_track() const;
@@ -51,18 +59,10 @@ class CONTENT_EXPORT RTCRtpReceiver : public blink::WebRTCRtpReceiver {
StreamAdapterRefs() const;
private:
- const rtc::scoped_refptr<webrtc::RtpReceiverInterface> webrtc_receiver_;
-
- // The track adapter is the glue between blink and webrtc layer tracks.
- // Keeping a reference to the adapter ensures it is not disposed, as is
- // required as long as the webrtc layer track is in use by the receiver.
- std::unique_ptr<WebRtcMediaStreamTrackAdapterMap::AdapterRef> track_adapter_;
- // Similarly, references needs to be kept to the stream adapters of streams
- // associated with the receiver.
- std::vector<std::unique_ptr<WebRtcMediaStreamAdapterMap::AdapterRef>>
- stream_adapter_refs_;
+ class RTCRtpReceiverInternal;
+ struct RTCRtpReceiverInternalTraits;
- DISALLOW_COPY_AND_ASSIGN(RTCRtpReceiver);
+ scoped_refptr<RTCRtpReceiverInternal> internal_;
};
} // namespace content
diff --git a/chromium/content/renderer/media/webrtc/rtc_rtp_receiver_unittest.cc b/chromium/content/renderer/media/webrtc/rtc_rtp_receiver_unittest.cc
new file mode 100644
index 00000000000..f55c2b22c4c
--- /dev/null
+++ b/chromium/content/renderer/media/webrtc/rtc_rtp_receiver_unittest.cc
@@ -0,0 +1,174 @@
+// Copyright (c) 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/renderer/media/webrtc/rtc_rtp_receiver.h"
+
+#include <memory>
+
+#include "base/logging.h"
+#include "base/memory/ref_counted.h"
+#include "base/message_loop/message_loop.h"
+#include "base/run_loop.h"
+#include "base/single_thread_task_runner.h"
+#include "base/synchronization/waitable_event.h"
+#include "content/child/child_process.h"
+#include "content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h"
+#include "content/renderer/media/webrtc/mock_peer_connection_impl.h"
+#include "content/renderer/media/webrtc/test/webrtc_stats_report_obtainer.h"
+#include "content/renderer/media/webrtc/webrtc_media_stream_adapter_map.h"
+#include "content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map.h"
+#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/web_rtc_stats.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/web/web_heap.h"
+#include "third_party/webrtc/api/stats/rtcstats_objects.h"
+#include "third_party/webrtc/api/stats/rtcstatsreport.h"
+#include "third_party/webrtc/api/test/mock_rtpreceiver.h"
+
+namespace content {
+
+class RTCRtpReceiverTest : public ::testing::Test {
+ public:
+ void SetUp() override {
+ dependency_factory_.reset(new MockPeerConnectionDependencyFactory());
+ main_thread_ = blink::scheduler::GetSingleThreadTaskRunnerForTesting();
+ stream_map_ = new WebRtcMediaStreamAdapterMap(
+ dependency_factory_.get(), main_thread_,
+ new WebRtcMediaStreamTrackAdapterMap(dependency_factory_.get(),
+ main_thread_));
+ peer_connection_ = new rtc::RefCountedObject<MockPeerConnectionImpl>(
+ dependency_factory_.get(), nullptr);
+ }
+
+ void TearDown() override {
+ receiver_.reset();
+ // Syncing up with the signaling thread ensures any pending operations on
+ // that thread are executed. If they post back to the main thread, such as
+ // the sender's destructor traits, this is allowed to execute before the
+ // test shuts down the threads.
+ SyncWithSignalingThread();
+ blink::WebHeap::CollectAllGarbageForTesting();
+ }
+
+ // Wait for the signaling thread to perform any queued tasks, executing tasks
+ // posted to the current thread in the meantime while waiting.
+ void SyncWithSignalingThread() const {
+ base::RunLoop run_loop;
+ dependency_factory_->GetWebRtcSignalingThread()->PostTask(
+ FROM_HERE, run_loop.QuitClosure());
+ run_loop.Run();
+ }
+
+ std::unique_ptr<RTCRtpReceiver> CreateReceiver(
+ scoped_refptr<webrtc::MediaStreamTrackInterface> webrtc_track) {
+ std::unique_ptr<WebRtcMediaStreamTrackAdapterMap::AdapterRef> track_adapter;
+ base::RunLoop run_loop;
+ dependency_factory_->GetWebRtcSignalingThread()->PostTask(
+ FROM_HERE,
+ base::BindOnce(&RTCRtpReceiverTest::CreateReceiverOnSignalingThread,
+ base::Unretained(this), std::move(webrtc_track),
+ base::Unretained(&track_adapter),
+ base::Unretained(&run_loop)));
+ run_loop.Run();
+ DCHECK(mock_webrtc_receiver_);
+ DCHECK(track_adapter);
+ return std::make_unique<RTCRtpReceiver>(
+ peer_connection_.get(), main_thread_,
+ dependency_factory_->GetWebRtcSignalingThread(),
+ mock_webrtc_receiver_.get(), std::move(track_adapter),
+ std::vector<
+ std::unique_ptr<WebRtcMediaStreamAdapterMap::AdapterRef>>());
+ }
+
+ scoped_refptr<WebRTCStatsReportObtainer> GetStats() {
+ scoped_refptr<WebRTCStatsReportObtainer> obtainer =
+ new WebRTCStatsReportObtainer();
+ receiver_->GetStats(obtainer->GetStatsCallbackWrapper());
+ return obtainer;
+ }
+
+ protected:
+ void CreateReceiverOnSignalingThread(
+ scoped_refptr<webrtc::MediaStreamTrackInterface> webrtc_track,
+ std::unique_ptr<WebRtcMediaStreamTrackAdapterMap::AdapterRef>*
+ track_adapter,
+ base::RunLoop* run_loop) {
+ mock_webrtc_receiver_ =
+ new rtc::RefCountedObject<webrtc::MockRtpReceiver>();
+ *track_adapter =
+ stream_map_->track_adapter_map()->GetOrCreateRemoteTrackAdapter(
+ webrtc_track);
+ run_loop->Quit();
+ }
+
+ // Message loop and child processes is needed for task queues and threading to
+ // work, as is necessary to create tracks and adapters.
+ base::MessageLoop message_loop_;
+ ChildProcess child_process_;
+
+ std::unique_ptr<MockPeerConnectionDependencyFactory> dependency_factory_;
+ scoped_refptr<base::SingleThreadTaskRunner> main_thread_;
+ scoped_refptr<WebRtcMediaStreamAdapterMap> stream_map_;
+ rtc::scoped_refptr<MockPeerConnectionImpl> peer_connection_;
+ rtc::scoped_refptr<webrtc::MockRtpReceiver> mock_webrtc_receiver_;
+ std::unique_ptr<RTCRtpReceiver> receiver_;
+};
+
+TEST_F(RTCRtpReceiverTest, CreateReceiver) {
+ scoped_refptr<MockWebRtcAudioTrack> webrtc_track =
+ MockWebRtcAudioTrack::Create("webrtc_track");
+ receiver_ = CreateReceiver(webrtc_track);
+ EXPECT_FALSE(receiver_->Track().IsNull());
+ EXPECT_EQ(receiver_->Track().Id().Utf8(), webrtc_track->id());
+ EXPECT_EQ(&receiver_->webrtc_track(), webrtc_track);
+}
+
+TEST_F(RTCRtpReceiverTest, ShallowCopy) {
+ scoped_refptr<MockWebRtcAudioTrack> webrtc_track =
+ MockWebRtcAudioTrack::Create("webrtc_track");
+ receiver_ = CreateReceiver(webrtc_track);
+ auto copy = receiver_->ShallowCopy();
+ EXPECT_EQ(&receiver_->webrtc_track(), webrtc_track);
+ auto* webrtc_receiver = receiver_->webrtc_receiver();
+ auto web_track_unique_id = receiver_->Track().UniqueId();
+ // Copy is identical to original.
+ EXPECT_EQ(copy->webrtc_receiver(), webrtc_receiver);
+ EXPECT_EQ(&copy->webrtc_track(), webrtc_track);
+ EXPECT_EQ(copy->Track().UniqueId(), web_track_unique_id);
+ // Copy keeps the internal state alive.
+ receiver_.reset();
+ EXPECT_EQ(copy->webrtc_receiver(), webrtc_receiver);
+ EXPECT_EQ(&copy->webrtc_track(), webrtc_track);
+ EXPECT_EQ(copy->Track().UniqueId(), web_track_unique_id);
+}
+
+TEST_F(RTCRtpReceiverTest, GetStats) {
+ scoped_refptr<MockWebRtcAudioTrack> webrtc_track =
+ MockWebRtcAudioTrack::Create("webrtc_track");
+ receiver_ = CreateReceiver(webrtc_track);
+
+ // Make the mock return a blink version of the |webtc_report|. The mock does
+ // not perform any stats filtering, we just set it to a dummy value.
+ rtc::scoped_refptr<webrtc::RTCStatsReport> webrtc_report =
+ webrtc::RTCStatsReport::Create(0u);
+ webrtc_report->AddStats(
+ std::make_unique<webrtc::RTCInboundRTPStreamStats>("stats-id", 1234u));
+ peer_connection_->SetGetStatsReport(webrtc_report);
+
+ auto obtainer = GetStats();
+ // Make sure the operation is async.
+ EXPECT_FALSE(obtainer->report());
+ // Wait for the report, this performs the necessary run-loop.
+ auto* report = obtainer->WaitForReport();
+ EXPECT_TRUE(report);
+
+ // Verify dummy value.
+ EXPECT_EQ(report->Size(), 1u);
+ auto stats = report->GetStats(blink::WebString::FromUTF8("stats-id"));
+ EXPECT_TRUE(stats);
+ EXPECT_EQ(stats->Timestamp(), 1.234);
+}
+
+} // namespace content
diff --git a/chromium/content/renderer/media/webrtc/rtc_rtp_sender.cc b/chromium/content/renderer/media/webrtc/rtc_rtp_sender.cc
index 40391dcb825..df886ddc560 100644
--- a/chromium/content/renderer/media/webrtc/rtc_rtp_sender.cc
+++ b/chromium/content/renderer/media/webrtc/rtc_rtp_sender.cc
@@ -4,8 +4,12 @@
#include "content/renderer/media/webrtc/rtc_rtp_sender.h"
+#include <utility>
+
#include "base/logging.h"
#include "content/renderer/media/webrtc/rtc_dtmf_sender_handler.h"
+#include "content/renderer/media/webrtc/rtc_rtp_parameters.h"
+#include "content/renderer/media/webrtc/rtc_stats.h"
namespace content {
@@ -18,22 +22,27 @@ void OnReplaceTrackCompleted(blink::WebRTCVoidRequest request, bool result) {
if (result)
request.RequestSucceeded();
else
- request.RequestFailed(blink::WebString());
+ request.RequestFailed(blink::WebRTCError(
+ blink::WebRTCErrorType::kInvalidModification, blink::WebString()));
}
} // namespace
class RTCRtpSender::RTCRtpSenderInternal
- : public base::RefCountedThreadSafe<RTCRtpSender::RTCRtpSenderInternal> {
+ : public base::RefCountedThreadSafe<
+ RTCRtpSender::RTCRtpSenderInternal,
+ RTCRtpSender::RTCRtpSenderInternalTraits> {
public:
RTCRtpSenderInternal(
+ scoped_refptr<webrtc::PeerConnectionInterface> native_peer_connection,
scoped_refptr<base::SingleThreadTaskRunner> main_thread,
scoped_refptr<base::SingleThreadTaskRunner> signaling_thread,
scoped_refptr<WebRtcMediaStreamAdapterMap> stream_map,
rtc::scoped_refptr<webrtc::RtpSenderInterface> webrtc_sender,
blink::WebMediaStreamTrack web_track,
std::vector<blink::WebMediaStream> web_streams)
- : main_thread_(std::move(main_thread)),
+ : native_peer_connection_(std::move(native_peer_connection)),
+ main_thread_(std::move(main_thread)),
signaling_thread_(std::move(signaling_thread)),
stream_map_(std::move(stream_map)),
webrtc_sender_(std::move(webrtc_sender)) {
@@ -55,6 +64,7 @@ class RTCRtpSender::RTCRtpSenderInternal
}
RTCRtpSenderInternal(
+ scoped_refptr<webrtc::PeerConnectionInterface> native_peer_connection,
scoped_refptr<base::SingleThreadTaskRunner> main_thread,
scoped_refptr<base::SingleThreadTaskRunner> signaling_thread,
scoped_refptr<WebRtcMediaStreamAdapterMap> stream_map,
@@ -62,7 +72,8 @@ class RTCRtpSender::RTCRtpSenderInternal
std::unique_ptr<WebRtcMediaStreamTrackAdapterMap::AdapterRef> track_ref,
std::vector<std::unique_ptr<WebRtcMediaStreamAdapterMap::AdapterRef>>
stream_refs)
- : main_thread_(std::move(main_thread)),
+ : native_peer_connection_(std::move(native_peer_connection)),
+ main_thread_(std::move(main_thread)),
signaling_thread_(std::move(signaling_thread)),
stream_map_(std::move(stream_map)),
webrtc_sender_(std::move(webrtc_sender)),
@@ -119,6 +130,20 @@ class RTCRtpSender::RTCRtpSenderInternal
return std::make_unique<RtcDtmfSenderHandler>(dtmf_sender);
}
+ std::unique_ptr<blink::WebRTCRtpParameters> GetParameters() const {
+ webrtc::RtpParameters parameters = webrtc_sender_->GetParameters();
+ return std::make_unique<blink::WebRTCRtpParameters>(
+ GetWebRTCRtpParameters(parameters));
+ }
+
+ void GetStats(std::unique_ptr<blink::WebRTCStatsReportCallback> callback) {
+ signaling_thread_->PostTask(
+ FROM_HERE,
+ base::BindOnce(
+ &RTCRtpSender::RTCRtpSenderInternal::GetStatsOnSignalingThread,
+ this, std::move(callback)));
+ }
+
bool RemoveFromPeerConnection(webrtc::PeerConnectionInterface* pc) {
if (!pc->RemoveTrack(webrtc_sender_))
return false;
@@ -131,8 +156,12 @@ class RTCRtpSender::RTCRtpSenderInternal
}
private:
- friend class base::RefCountedThreadSafe<RTCRtpSenderInternal>;
- virtual ~RTCRtpSenderInternal() {}
+ friend struct RTCRtpSender::RTCRtpSenderInternalTraits;
+
+ ~RTCRtpSenderInternal() {
+ // Ensured by destructor traits.
+ DCHECK(main_thread_->BelongsToCurrentThread());
+ }
// |webrtc_track| is passed as an argument because |track_ref->webrtc_track()|
// cannot be accessed on the signaling thread. https://crbug.com/756436
@@ -159,9 +188,17 @@ class RTCRtpSender::RTCRtpSenderInternal
std::move(callback).Run(result);
}
+ void GetStatsOnSignalingThread(
+ std::unique_ptr<blink::WebRTCStatsReportCallback> callback) {
+ native_peer_connection_->GetStats(webrtc_sender_,
+ RTCStatsCollectorCallbackImpl::Create(
+ main_thread_, std::move(callback)));
+ }
+
+ const scoped_refptr<webrtc::PeerConnectionInterface> native_peer_connection_;
const scoped_refptr<base::SingleThreadTaskRunner> main_thread_;
const scoped_refptr<base::SingleThreadTaskRunner> signaling_thread_;
- scoped_refptr<WebRtcMediaStreamAdapterMap> stream_map_;
+ const scoped_refptr<WebRtcMediaStreamAdapterMap> stream_map_;
const rtc::scoped_refptr<webrtc::RtpSenderInterface> webrtc_sender_;
// The track adapter is the glue between blink and webrtc layer tracks.
// Keeping a reference to the adapter ensures it is not disposed, as is
@@ -173,18 +210,39 @@ class RTCRtpSender::RTCRtpSenderInternal
stream_refs_;
};
+struct RTCRtpSender::RTCRtpSenderInternalTraits {
+ private:
+ friend class base::RefCountedThreadSafe<RTCRtpSenderInternal,
+ RTCRtpSenderInternalTraits>;
+
+ static void Destruct(const RTCRtpSenderInternal* sender) {
+ // RTCRtpSenderInternal owns AdapterRefs which have to be destroyed on the
+ // main thread, this ensures delete always happens there.
+ if (!sender->main_thread_->BelongsToCurrentThread()) {
+ sender->main_thread_->PostTask(
+ FROM_HERE,
+ base::BindOnce(&RTCRtpSender::RTCRtpSenderInternalTraits::Destruct,
+ base::Unretained(sender)));
+ return;
+ }
+ delete sender;
+ }
+};
+
uintptr_t RTCRtpSender::getId(const webrtc::RtpSenderInterface* webrtc_sender) {
return reinterpret_cast<uintptr_t>(webrtc_sender);
}
RTCRtpSender::RTCRtpSender(
+ scoped_refptr<webrtc::PeerConnectionInterface> native_peer_connection,
scoped_refptr<base::SingleThreadTaskRunner> main_thread,
scoped_refptr<base::SingleThreadTaskRunner> signaling_thread,
scoped_refptr<WebRtcMediaStreamAdapterMap> stream_map,
rtc::scoped_refptr<webrtc::RtpSenderInterface> webrtc_sender,
blink::WebMediaStreamTrack web_track,
std::vector<blink::WebMediaStream> web_streams)
- : internal_(new RTCRtpSenderInternal(std::move(main_thread),
+ : internal_(new RTCRtpSenderInternal(std::move(native_peer_connection),
+ std::move(main_thread),
std::move(signaling_thread),
std::move(stream_map),
std::move(webrtc_sender),
@@ -192,21 +250,7 @@ RTCRtpSender::RTCRtpSender(
std::move(web_streams))) {}
RTCRtpSender::RTCRtpSender(
- scoped_refptr<base::SingleThreadTaskRunner> main_thread,
- scoped_refptr<base::SingleThreadTaskRunner> signaling_thread,
- scoped_refptr<WebRtcMediaStreamAdapterMap> stream_map,
- rtc::scoped_refptr<webrtc::RtpSenderInterface> webrtc_sender,
- std::unique_ptr<WebRtcMediaStreamTrackAdapterMap::AdapterRef> track_ref)
- : RTCRtpSender(
- std::move(main_thread),
- std::move(signaling_thread),
- std::move(stream_map),
- std::move(webrtc_sender),
- std::move(track_ref),
- std::vector<
- std::unique_ptr<WebRtcMediaStreamAdapterMap::AdapterRef>>()) {}
-
-RTCRtpSender::RTCRtpSender(
+ scoped_refptr<webrtc::PeerConnectionInterface> native_peer_connection,
scoped_refptr<base::SingleThreadTaskRunner> main_thread,
scoped_refptr<base::SingleThreadTaskRunner> signaling_thread,
scoped_refptr<WebRtcMediaStreamAdapterMap> stream_map,
@@ -214,7 +258,8 @@ RTCRtpSender::RTCRtpSender(
std::unique_ptr<WebRtcMediaStreamTrackAdapterMap::AdapterRef> track_ref,
std::vector<std::unique_ptr<WebRtcMediaStreamAdapterMap::AdapterRef>>
stream_refs)
- : internal_(new RTCRtpSenderInternal(std::move(main_thread),
+ : internal_(new RTCRtpSenderInternal(std::move(native_peer_connection),
+ std::move(main_thread),
std::move(signaling_thread),
std::move(stream_map),
std::move(webrtc_sender),
@@ -256,6 +301,16 @@ std::unique_ptr<blink::WebRTCDTMFSenderHandler> RTCRtpSender::GetDtmfSender()
return internal_->GetDtmfSender();
}
+std::unique_ptr<blink::WebRTCRtpParameters> RTCRtpSender::GetParameters()
+ const {
+ return internal_->GetParameters();
+}
+
+void RTCRtpSender::GetStats(
+ std::unique_ptr<blink::WebRTCStatsReportCallback> callback) {
+ internal_->GetStats(std::move(callback));
+}
+
webrtc::RtpSenderInterface* RTCRtpSender::webrtc_sender() const {
return internal_->webrtc_sender();
}
diff --git a/chromium/content/renderer/media/webrtc/rtc_rtp_sender.h b/chromium/content/renderer/media/webrtc/rtc_rtp_sender.h
index a1f9f1c2025..f601e352184 100644
--- a/chromium/content/renderer/media/webrtc/rtc_rtp_sender.h
+++ b/chromium/content/renderer/media/webrtc/rtc_rtp_sender.h
@@ -12,8 +12,9 @@
#include "content/common/content_export.h"
#include "content/renderer/media/webrtc/webrtc_media_stream_adapter_map.h"
#include "content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
-#include "third_party/WebKit/public/platform/WebRTCRtpSender.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
+#include "third_party/blink/public/platform/web_rtc_rtp_sender.h"
+#include "third_party/blink/public/platform/web_rtc_stats.h"
#include "third_party/webrtc/api/peerconnectioninterface.h"
#include "third_party/webrtc/api/rtpsenderinterface.h"
#include "third_party/webrtc/rtc_base/scoped_ref_ptr.h"
@@ -27,22 +28,16 @@ class CONTENT_EXPORT RTCRtpSender : public blink::WebRTCRtpSender {
public:
static uintptr_t getId(const webrtc::RtpSenderInterface* webrtc_sender);
- RTCRtpSender(scoped_refptr<base::SingleThreadTaskRunner> main_thread,
- scoped_refptr<base::SingleThreadTaskRunner> signaling_thread,
- scoped_refptr<WebRtcMediaStreamAdapterMap> stream_map,
- rtc::scoped_refptr<webrtc::RtpSenderInterface> webrtc_sender,
- blink::WebMediaStreamTrack web_track,
- std::vector<blink::WebMediaStream> web_streams);
- // TODO(hbos): Remove these in favor of the above constructor that creates the
- // corresponding adapter refs. They won't be needed after
- // https://crbug.com/738929.
RTCRtpSender(
+ scoped_refptr<webrtc::PeerConnectionInterface> native_peer_connection,
scoped_refptr<base::SingleThreadTaskRunner> main_thread,
scoped_refptr<base::SingleThreadTaskRunner> signaling_thread,
scoped_refptr<WebRtcMediaStreamAdapterMap> stream_map,
rtc::scoped_refptr<webrtc::RtpSenderInterface> webrtc_sender,
- std::unique_ptr<WebRtcMediaStreamTrackAdapterMap::AdapterRef> track_ref);
+ blink::WebMediaStreamTrack web_track,
+ std::vector<blink::WebMediaStream> web_streams);
RTCRtpSender(
+ scoped_refptr<webrtc::PeerConnectionInterface> native_peer_connection,
scoped_refptr<base::SingleThreadTaskRunner> main_thread,
scoped_refptr<base::SingleThreadTaskRunner> signaling_thread,
scoped_refptr<WebRtcMediaStreamAdapterMap> stream_map,
@@ -67,6 +62,8 @@ class CONTENT_EXPORT RTCRtpSender : public blink::WebRTCRtpSender {
blink::WebRTCVoidRequest request) override;
std::unique_ptr<blink::WebRTCDTMFSenderHandler> GetDtmfSender()
const override;
+ std::unique_ptr<blink::WebRTCRtpParameters> GetParameters() const override;
+ void GetStats(std::unique_ptr<blink::WebRTCStatsReportCallback>) override;
webrtc::RtpSenderInterface* webrtc_sender() const;
const webrtc::MediaStreamTrackInterface* webrtc_track() const;
@@ -82,6 +79,7 @@ class CONTENT_EXPORT RTCRtpSender : public blink::WebRTCRtpSender {
private:
class RTCRtpSenderInternal;
+ struct RTCRtpSenderInternalTraits;
scoped_refptr<RTCRtpSenderInternal> internal_;
};
diff --git a/chromium/content/renderer/media/webrtc/rtc_rtp_sender_unittest.cc b/chromium/content/renderer/media/webrtc/rtc_rtp_sender_unittest.cc
index 0013eedbe1a..eb086d2e0d2 100644
--- a/chromium/content/renderer/media/webrtc/rtc_rtp_sender_unittest.cc
+++ b/chromium/content/renderer/media/webrtc/rtc_rtp_sender_unittest.cc
@@ -14,15 +14,20 @@
#include "content/child/child_process.h"
#include "content/renderer/media/stream/media_stream_audio_source.h"
#include "content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h"
+#include "content/renderer/media/webrtc/mock_peer_connection_impl.h"
+#include "content/renderer/media/webrtc/test/webrtc_stats_report_obtainer.h"
#include "content/renderer/media/webrtc/webrtc_media_stream_adapter_map.h"
#include "content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
-#include "third_party/WebKit/public/platform/WebRTCVoidRequest.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
-#include "third_party/WebKit/public/web/WebHeap.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
+#include "third_party/blink/public/platform/web_rtc_stats.h"
+#include "third_party/blink/public/platform/web_rtc_void_request.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/web/web_heap.h"
+#include "third_party/webrtc/api/stats/rtcstats_objects.h"
+#include "third_party/webrtc/api/stats/rtcstatsreport.h"
#include "third_party/webrtc/api/test/mock_rtpsender.h"
using ::testing::_;
@@ -39,10 +44,29 @@ class RTCRtpSenderTest : public ::testing::Test {
dependency_factory_.get(), main_thread_,
new WebRtcMediaStreamTrackAdapterMap(dependency_factory_.get(),
main_thread_));
+ peer_connection_ = new rtc::RefCountedObject<MockPeerConnectionImpl>(
+ dependency_factory_.get(), nullptr);
mock_webrtc_sender_ = new rtc::RefCountedObject<webrtc::MockRtpSender>();
}
- void TearDown() override { blink::WebHeap::CollectAllGarbageForTesting(); }
+ void TearDown() override {
+ sender_.reset();
+ // Syncing up with the signaling thread ensures any pending operations on
+ // that thread are executed. If they post back to the main thread, such as
+ // the sender's destructor traits, this is allowed to execute before the
+ // test shuts down the threads.
+ SyncWithSignalingThread();
+ blink::WebHeap::CollectAllGarbageForTesting();
+ }
+
+ // Wait for the signaling thread to perform any queued tasks, executing tasks
+ // posted to the current thread in the meantime while waiting.
+ void SyncWithSignalingThread() const {
+ base::RunLoop run_loop;
+ dependency_factory_->GetWebRtcSignalingThread()->PostTask(
+ FROM_HERE, run_loop.QuitClosure());
+ run_loop.Run();
+ }
blink::WebMediaStreamTrack CreateWebTrack(const std::string& id) {
blink::WebMediaStreamSource web_source;
@@ -61,8 +85,9 @@ class RTCRtpSenderTest : public ::testing::Test {
std::unique_ptr<RTCRtpSender> CreateSender(
blink::WebMediaStreamTrack web_track) {
return std::make_unique<RTCRtpSender>(
- main_thread_, dependency_factory_->GetWebRtcSignalingThread(),
- stream_map_, mock_webrtc_sender_.get(), std::move(web_track),
+ peer_connection_.get(), main_thread_,
+ dependency_factory_->GetWebRtcSignalingThread(), stream_map_,
+ mock_webrtc_sender_.get(), std::move(web_track),
std::vector<blink::WebMediaStream>());
}
@@ -86,6 +111,13 @@ class RTCRtpSenderTest : public ::testing::Test {
std::move(run_loop));
}
+ scoped_refptr<WebRTCStatsReportObtainer> CallGetStats() {
+ scoped_refptr<WebRTCStatsReportObtainer> obtainer =
+ new WebRTCStatsReportObtainer();
+ sender_->GetStats(obtainer->GetStatsCallbackWrapper());
+ return obtainer;
+ }
+
protected:
void CallbackOnComplete(bool* result_out,
base::RunLoop* run_loop,
@@ -108,6 +140,7 @@ class RTCRtpSenderTest : public ::testing::Test {
std::unique_ptr<MockPeerConnectionDependencyFactory> dependency_factory_;
scoped_refptr<base::SingleThreadTaskRunner> main_thread_;
scoped_refptr<WebRtcMediaStreamAdapterMap> stream_map_;
+ rtc::scoped_refptr<MockPeerConnectionImpl> peer_connection_;
rtc::scoped_refptr<webrtc::MockRtpSender> mock_webrtc_sender_;
std::unique_ptr<RTCRtpSender> sender_;
};
@@ -125,13 +158,6 @@ TEST_F(RTCRtpSenderTest, CreateSenderWithNullTrack) {
EXPECT_TRUE(sender_->Track().IsNull());
}
-// This test is flaky on Android and Linux.
-// See crbug.com/800465 for detail.
-#if defined(OS_ANDROID) || defined(OS_LINUX)
-#define MAYBE_ReplaceTrackSetsTrack DISABLED_ReplaceTrackSetsTrack
-#else
-#define MAYBE_ReplaceTrackSetsTrack ReplaceTrackSetsTrack
-#endif
TEST_F(RTCRtpSenderTest, ReplaceTrackSetsTrack) {
auto web_track1 = CreateWebTrack("track1");
sender_ = CreateSender(web_track1);
@@ -144,14 +170,7 @@ TEST_F(RTCRtpSenderTest, ReplaceTrackSetsTrack) {
EXPECT_EQ(web_track2.UniqueId(), sender_->Track().UniqueId());
}
-// This test is flaky on Android and Linux.
-// See crbug.com/803597 for detail.
-#if defined(OS_ANDROID) || defined(OS_LINUX)
-#define MAYBE_ReplaceTrackWithNullTrack DISABLED_ReplaceTrackWithNullTrack
-#else
-#define MAYBE_ReplaceTrackWithNullTrack ReplaceTrackWithNullTrack
-#endif
-TEST_F(RTCRtpSenderTest, MAYBE_ReplaceTrackWithNullTrack) {
+TEST_F(RTCRtpSenderTest, ReplaceTrackWithNullTrack) {
auto web_track = CreateWebTrack("track_id");
sender_ = CreateSender(web_track);
@@ -191,6 +210,32 @@ TEST_F(RTCRtpSenderTest, ReplaceTrackIsNotSetSynchronously) {
std::move(replaceTrackRunLoopAndGetResult).Run();
}
+TEST_F(RTCRtpSenderTest, GetStats) {
+ auto web_track = CreateWebTrack("track_id");
+ sender_ = CreateSender(web_track);
+
+ // Make the mock return a blink version of the |webtc_report|. The mock does
+ // not perform any stats filtering, we just set it to a dummy value.
+ rtc::scoped_refptr<webrtc::RTCStatsReport> webrtc_report =
+ webrtc::RTCStatsReport::Create(0u);
+ webrtc_report->AddStats(
+ std::make_unique<webrtc::RTCOutboundRTPStreamStats>("stats-id", 1234u));
+ peer_connection_->SetGetStatsReport(webrtc_report);
+
+ auto obtainer = CallGetStats();
+ // Make sure the operation is async.
+ EXPECT_FALSE(obtainer->report());
+ // Wait for the report, this performs the necessary run-loop.
+ auto* report = obtainer->WaitForReport();
+ EXPECT_TRUE(report);
+
+ // Verify dummy value.
+ EXPECT_EQ(report->Size(), 1u);
+ auto stats = report->GetStats(blink::WebString::FromUTF8("stats-id"));
+ EXPECT_TRUE(stats);
+ EXPECT_EQ(stats->Timestamp(), 1.234);
+}
+
TEST_F(RTCRtpSenderTest, CopiedSenderSharesInternalStates) {
auto web_track = CreateWebTrack("track_id");
sender_ = CreateSender(web_track);
diff --git a/chromium/content/renderer/media/webrtc/rtc_stats.cc b/chromium/content/renderer/media/webrtc/rtc_stats.cc
index 0092c627529..0c7478f8646 100644
--- a/chromium/content/renderer/media/webrtc/rtc_stats.cc
+++ b/chromium/content/renderer/media/webrtc/rtc_stats.cc
@@ -7,6 +7,7 @@
#include <set>
#include <string>
+#include "base/bind.h"
#include "base/logging.h"
#include "base/time/time.h"
#include "third_party/webrtc/api/stats/rtcstats_objects.h"
@@ -280,6 +281,45 @@ blink::WebVector<blink::WebString> RTCStatsMember::ValueSequenceString() const {
return web_sequence;
}
+// static
+rtc::scoped_refptr<RTCStatsCollectorCallbackImpl>
+RTCStatsCollectorCallbackImpl::Create(
+ scoped_refptr<base::SingleThreadTaskRunner> main_thread,
+ std::unique_ptr<blink::WebRTCStatsReportCallback> callback) {
+ return rtc::scoped_refptr<RTCStatsCollectorCallbackImpl>(
+ new rtc::RefCountedObject<RTCStatsCollectorCallbackImpl>(
+ std::move(main_thread), callback.release()));
+}
+
+RTCStatsCollectorCallbackImpl::RTCStatsCollectorCallbackImpl(
+ scoped_refptr<base::SingleThreadTaskRunner> main_thread,
+ blink::WebRTCStatsReportCallback* callback)
+ : main_thread_(std::move(main_thread)), callback_(callback) {}
+
+RTCStatsCollectorCallbackImpl::~RTCStatsCollectorCallbackImpl() {
+ DCHECK(!callback_);
+}
+
+void RTCStatsCollectorCallbackImpl::OnStatsDelivered(
+ const rtc::scoped_refptr<const webrtc::RTCStatsReport>& report) {
+ main_thread_->PostTask(
+ FROM_HERE,
+ base::BindOnce(
+ &RTCStatsCollectorCallbackImpl::OnStatsDeliveredOnMainThread, this,
+ report));
+}
+
+void RTCStatsCollectorCallbackImpl::OnStatsDeliveredOnMainThread(
+ rtc::scoped_refptr<const webrtc::RTCStatsReport> report) {
+ DCHECK(main_thread_->BelongsToCurrentThread());
+ DCHECK(report);
+ DCHECK(callback_);
+ callback_->OnStatsDelivered(std::unique_ptr<blink::WebRTCStatsReport>(
+ new RTCStatsReport(base::WrapRefCounted(report.get()))));
+ // Make sure the callback is destroyed in the main thread as well.
+ callback_.reset();
+}
+
void WhitelistStatsForTesting(const char* type) {
GetStatsWhitelist()->WhitelistStatsForTesting(type);
}
diff --git a/chromium/content/renderer/media/webrtc/rtc_stats.h b/chromium/content/renderer/media/webrtc/rtc_stats.h
index 006aa2e95bc..937cb25f3f0 100644
--- a/chromium/content/renderer/media/webrtc/rtc_stats.h
+++ b/chromium/content/renderer/media/webrtc/rtc_stats.h
@@ -6,9 +6,11 @@
#define CONTENT_RENDERER_MEDIA_WEBRTC_RTC_STATS_H_
#include "base/memory/ref_counted.h"
+#include "base/single_thread_task_runner.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebRTCStats.h"
+#include "third_party/blink/public/platform/web_rtc_stats.h"
#include "third_party/webrtc/api/stats/rtcstats.h"
+#include "third_party/webrtc/api/stats/rtcstatscollectorcallback.h"
#include "third_party/webrtc/api/stats/rtcstatsreport.h"
namespace content {
@@ -85,6 +87,32 @@ class CONTENT_EXPORT RTCStatsMember : public blink::WebRTCStatsMember {
const webrtc::RTCStatsMemberInterface* const member_;
};
+// A stats collector callback.
+// It is invoked on the WebRTC signaling thread and will post a task to invoke
+// |callback| on the thread given in the |main_thread| argument.
+// The argument to the callback will be a |blink::WebRTCStatsReport|.
+class RTCStatsCollectorCallbackImpl : public webrtc::RTCStatsCollectorCallback {
+ public:
+ static rtc::scoped_refptr<RTCStatsCollectorCallbackImpl> Create(
+ scoped_refptr<base::SingleThreadTaskRunner> main_thread,
+ std::unique_ptr<blink::WebRTCStatsReportCallback> callback);
+
+ void OnStatsDelivered(
+ const rtc::scoped_refptr<const webrtc::RTCStatsReport>& report) override;
+
+ protected:
+ RTCStatsCollectorCallbackImpl(
+ scoped_refptr<base::SingleThreadTaskRunner> main_thread,
+ blink::WebRTCStatsReportCallback* callback);
+ ~RTCStatsCollectorCallbackImpl() override;
+
+ void OnStatsDeliveredOnMainThread(
+ rtc::scoped_refptr<const webrtc::RTCStatsReport> report);
+
+ const scoped_refptr<base::SingleThreadTaskRunner> main_thread_;
+ std::unique_ptr<blink::WebRTCStatsReportCallback> callback_;
+};
+
CONTENT_EXPORT void WhitelistStatsForTesting(const char* type);
} // namespace content
diff --git a/chromium/content/renderer/media/webrtc/rtc_video_decoder_unittest.cc b/chromium/content/renderer/media/webrtc/rtc_video_decoder_unittest.cc
index d53798d0d12..cd52471379d 100644
--- a/chromium/content/renderer/media/webrtc/rtc_video_decoder_unittest.cc
+++ b/chromium/content/renderer/media/webrtc/rtc_video_decoder_unittest.cc
@@ -16,7 +16,7 @@
#include "media/video/mock_gpu_video_accelerator_factories.h"
#include "media/video/mock_video_decode_accelerator.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
#if defined(OS_WIN)
#include "base/command_line.h"
diff --git a/chromium/content/renderer/media/webrtc/rtc_video_encoder_factory.cc b/chromium/content/renderer/media/webrtc/rtc_video_encoder_factory.cc
index 25104c29dc2..3307c40e0b8 100644
--- a/chromium/content/renderer/media/webrtc/rtc_video_encoder_factory.cc
+++ b/chromium/content/renderer/media/webrtc/rtc_video_encoder_factory.cc
@@ -12,7 +12,7 @@
#include "content/public/common/content_switches.h"
#include "content/public/common/feature_h264_with_openh264_ffmpeg.h"
#include "content/renderer/media/webrtc/rtc_video_encoder.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "media/video/gpu_video_accelerator_factories.h"
#include "third_party/webrtc/common_video/h264/profile_level_id.h"
diff --git a/chromium/content/renderer/media/webrtc/rtc_video_encoder_unittest.cc b/chromium/content/renderer/media/webrtc/rtc_video_encoder_unittest.cc
index 581f76280a5..d3defba9124 100644
--- a/chromium/content/renderer/media/webrtc/rtc_video_encoder_unittest.cc
+++ b/chromium/content/renderer/media/webrtc/rtc_video_encoder_unittest.cc
@@ -5,7 +5,6 @@
#include <stdint.h>
#include "base/bind.h"
-#include "base/memory/ptr_util.h"
#include "base/single_thread_task_runner.h"
#include "base/synchronization/waitable_event.h"
#include "base/threading/thread.h"
diff --git a/chromium/content/renderer/media/webrtc/test/webrtc_stats_report_obtainer.cc b/chromium/content/renderer/media/webrtc/test/webrtc_stats_report_obtainer.cc
new file mode 100644
index 00000000000..c0c8e1522f3
--- /dev/null
+++ b/chromium/content/renderer/media/webrtc/test/webrtc_stats_report_obtainer.cc
@@ -0,0 +1,40 @@
+// Copyright (c) 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/renderer/media/webrtc/test/webrtc_stats_report_obtainer.h"
+
+namespace content {
+
+WebRTCStatsReportObtainer::CallbackWrapper::CallbackWrapper(
+ scoped_refptr<WebRTCStatsReportObtainer> obtainer)
+ : obtainer_(std::move(obtainer)) {}
+
+WebRTCStatsReportObtainer::CallbackWrapper::~CallbackWrapper() {}
+
+void WebRTCStatsReportObtainer::CallbackWrapper::OnStatsDelivered(
+ std::unique_ptr<blink::WebRTCStatsReport> report) {
+ obtainer_->report_ = std::move(report);
+ obtainer_->run_loop_.Quit();
+}
+
+WebRTCStatsReportObtainer::WebRTCStatsReportObtainer() {}
+
+WebRTCStatsReportObtainer::~WebRTCStatsReportObtainer() {}
+
+std::unique_ptr<blink::WebRTCStatsReportCallback>
+WebRTCStatsReportObtainer::GetStatsCallbackWrapper() {
+ return std::unique_ptr<blink::WebRTCStatsReportCallback>(
+ new CallbackWrapper(this));
+}
+
+blink::WebRTCStatsReport* WebRTCStatsReportObtainer::report() const {
+ return report_.get();
+}
+
+blink::WebRTCStatsReport* WebRTCStatsReportObtainer::WaitForReport() {
+ run_loop_.Run();
+ return report_.get();
+}
+
+} // namespace content
diff --git a/chromium/content/renderer/media/webrtc/test/webrtc_stats_report_obtainer.h b/chromium/content/renderer/media/webrtc/test/webrtc_stats_report_obtainer.h
new file mode 100644
index 00000000000..b617af668eb
--- /dev/null
+++ b/chromium/content/renderer/media/webrtc/test/webrtc_stats_report_obtainer.h
@@ -0,0 +1,58 @@
+// Copyright (c) 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_RENDERER_MEDIA_WEBRTC_TEST_WEBRTC_STATS_REPORT_OBTAINER_H_
+#define CONTENT_RENDERER_MEDIA_WEBRTC_TEST_WEBRTC_STATS_REPORT_OBTAINER_H_
+
+#include <memory>
+
+#include "base/memory/ref_counted.h"
+#include "base/run_loop.h"
+#include "third_party/blink/public/platform/web_rtc_stats.h"
+
+namespace content {
+
+// The obtainer is a test-only helper class capable of waiting for a GetStats()
+// callback to be called. It takes ownership of and exposes the resulting
+// blink::WebRTCStatsReport.
+// While WaitForReport() is waiting for the report, tasks posted on the current
+// thread are executed (see base::RunLoop::Run()) making it safe to wait on the
+// same thread that the stats report callback occurs on without blocking the
+// callback.
+class WebRTCStatsReportObtainer
+ : public base::RefCountedThreadSafe<WebRTCStatsReportObtainer> {
+ public:
+ WebRTCStatsReportObtainer();
+
+ std::unique_ptr<blink::WebRTCStatsReportCallback> GetStatsCallbackWrapper();
+
+ blink::WebRTCStatsReport* report() const;
+ blink::WebRTCStatsReport* WaitForReport();
+
+ private:
+ friend class base::RefCountedThreadSafe<WebRTCStatsReportObtainer>;
+ friend class CallbackWrapper;
+ virtual ~WebRTCStatsReportObtainer();
+
+ // A separate class is needed for OnStatsDelivered() because ownership of the
+ // callback has to be passed to GetStats().
+ class CallbackWrapper : public blink::WebRTCStatsReportCallback {
+ public:
+ CallbackWrapper(scoped_refptr<WebRTCStatsReportObtainer> obtainer);
+ ~CallbackWrapper() override;
+
+ void OnStatsDelivered(
+ std::unique_ptr<blink::WebRTCStatsReport> report) override;
+
+ private:
+ scoped_refptr<WebRTCStatsReportObtainer> obtainer_;
+ };
+
+ base::RunLoop run_loop_;
+ std::unique_ptr<blink::WebRTCStatsReport> report_;
+};
+
+} // namespace content
+
+#endif // CONTENT_RENDERER_MEDIA_WEBRTC_TEST_WEBRTC_STATS_REPORT_OBTAINER_H_
diff --git a/chromium/content/renderer/media/webrtc/webrtc_audio_device_impl.h b/chromium/content/renderer/media/webrtc/webrtc_audio_device_impl.h
index 151128ba7e0..3348f3747cd 100644
--- a/chromium/content/renderer/media/webrtc/webrtc_audio_device_impl.h
+++ b/chromium/content/renderer/media/webrtc/webrtc_audio_device_impl.h
@@ -237,10 +237,6 @@ class CONTENT_EXPORT WebRtcAudioDeviceImpl : public WebRtcAudioDeviceNotImpl,
// |recording_|, |microphone_volume_| and |playout_sinks_|.
mutable base::Lock lock_;
- // Used to protect the racing of calling OnData() since there can be more
- // than one input stream calling OnData().
- mutable base::Lock capture_callback_lock_;
-
bool initialized_;
bool playing_;
bool recording_;
diff --git a/chromium/content/renderer/media/webrtc/webrtc_audio_renderer.cc b/chromium/content/renderer/media/webrtc/webrtc_audio_renderer.cc
index 56cb8dc3669..6cd303ffbb3 100644
--- a/chromium/content/renderer/media/webrtc/webrtc_audio_renderer.cc
+++ b/chromium/content/renderer/media/webrtc/webrtc_audio_renderer.cc
@@ -22,7 +22,7 @@
#include "media/base/audio_latency.h"
#include "media/base/audio_parameters.h"
#include "media/base/sample_rates.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
#include "third_party/webrtc/api/mediastreaminterface.h"
#if defined(OS_WIN)
@@ -234,7 +234,8 @@ WebRtcAudioRenderer::CreateSharedAudioRendererProxy(
base::Bind(&WebRtcAudioRenderer::OnPlayStateChanged, this);
SharedAudioRenderer::OnPlayStateRemoved on_play_state_removed =
base::BindOnce(&WebRtcAudioRenderer::OnPlayStateRemoved, this);
- return new SharedAudioRenderer(this, media_stream, on_play_state_changed,
+ return new SharedAudioRenderer(this, media_stream,
+ std::move(on_play_state_changed),
std::move(on_play_state_removed));
}
diff --git a/chromium/content/renderer/media/webrtc/webrtc_audio_renderer.h b/chromium/content/renderer/media/webrtc/webrtc_audio_renderer.h
index 03d9888fece..9d42e00bc78 100644
--- a/chromium/content/renderer/media/webrtc/webrtc_audio_renderer.h
+++ b/chromium/content/renderer/media/webrtc/webrtc_audio_renderer.h
@@ -24,7 +24,7 @@
#include "media/base/audio_pull_fifo.h"
#include "media/base/audio_renderer_sink.h"
#include "media/base/channel_layout.h"
-#include "third_party/WebKit/public/platform/WebMediaStream.h"
+#include "third_party/blink/public/platform/web_media_stream.h"
namespace webrtc {
class AudioSourceInterface;
diff --git a/chromium/content/renderer/media/webrtc/webrtc_audio_renderer_unittest.cc b/chromium/content/renderer/media/webrtc/webrtc_audio_renderer_unittest.cc
index 8719d8b3f72..be938b0180d 100644
--- a/chromium/content/renderer/media/webrtc/webrtc_audio_renderer_unittest.cc
+++ b/chromium/content/renderer/media/webrtc/webrtc_audio_renderer_unittest.cc
@@ -19,10 +19,10 @@
#include "media/base/mock_audio_renderer_sink.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebMediaStream.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/web/WebHeap.h"
+#include "third_party/blink/public/platform/web_media_stream.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/web/web_heap.h"
#include "third_party/webrtc/api/mediastreaminterface.h"
using testing::Return;
diff --git a/chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter.cc b/chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter.cc
index dbe19c60927..835d6194e24 100644
--- a/chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter.cc
+++ b/chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter.cc
@@ -7,14 +7,13 @@
#include <utility>
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/renderer/media/stream/media_stream_audio_track.h"
#include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
#include "content/renderer/media/webrtc/webrtc_media_stream_track_adapter.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
namespace content {
@@ -203,7 +202,7 @@ RemoteWebRtcMediaStreamAdapter::RemoteWebRtcMediaStreamAdapter(
main_thread_->PostTask(
FROM_HERE,
base::BindOnce(&RemoteWebRtcMediaStreamAdapter::InitializeOnMainThread,
- weak_factory_.GetWeakPtr(), webrtc_stream_->label(),
+ weak_factory_.GetWeakPtr(), webrtc_stream_->id(),
std::move(adapter_refs),
webrtc_stream_->GetAudioTracks().size(),
webrtc_stream_->GetVideoTracks().size()));
diff --git a/chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter.h b/chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter.h
index 85dc842d0b6..e9e9147c765 100644
--- a/chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter.h
+++ b/chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter.h
@@ -16,7 +16,7 @@
#include "base/synchronization/lock.h"
#include "content/common/content_export.h"
#include "content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map.h"
-#include "third_party/WebKit/public/platform/WebMediaStream.h"
+#include "third_party/blink/public/platform/web_media_stream.h"
#include "third_party/webrtc/api/mediastreaminterface.h"
namespace content {
diff --git a/chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter_map.cc b/chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter_map.cc
index 9f8c9def6f8..dcf3844ecd6 100644
--- a/chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter_map.cc
+++ b/chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter_map.cc
@@ -199,8 +199,8 @@ WebRtcMediaStreamAdapterMap::GetOrCreateRemoteStreamAdapter(
base::BindOnce(
&WebRtcMediaStreamAdapterMap::OnRemoteStreamAdapterInitialized,
this,
- base::Passed(base::WrapUnique(new AdapterRef(
- this, AdapterRef::Type::kRemote, adapter_entry)))));
+ base::WrapUnique(new AdapterRef(this, AdapterRef::Type::kRemote,
+ adapter_entry))));
}
return base::WrapUnique(
new AdapterRef(this, AdapterRef::Type::kRemote, adapter_entry));
diff --git a/chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter_map.h b/chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter_map.h
index be9eac07599..1d9c40b6692 100644
--- a/chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter_map.h
+++ b/chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter_map.h
@@ -14,7 +14,7 @@
#include "content/common/content_export.h"
#include "content/renderer/media/webrtc/two_keys_adapter_map.h"
#include "content/renderer/media/webrtc/webrtc_media_stream_adapter.h"
-#include "third_party/WebKit/public/platform/WebMediaStream.h"
+#include "third_party/blink/public/platform/web_media_stream.h"
#include "third_party/webrtc/api/mediastreaminterface.h"
namespace content {
diff --git a/chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter_map_unittest.cc b/chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter_map_unittest.cc
index e40a905080c..87f0032a8bd 100644
--- a/chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter_map_unittest.cc
+++ b/chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter_map_unittest.cc
@@ -21,13 +21,13 @@
#include "content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h"
#include "content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebMediaStream.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebVector.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
-#include "third_party/WebKit/public/web/WebHeap.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/web_media_stream.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_vector.h"
+#include "third_party/blink/public/web/web_heap.h"
using ::testing::_;
diff --git a/chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter_unittest.cc b/chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter_unittest.cc
index 95ca41cf620..babc38f4ed7 100644
--- a/chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter_unittest.cc
+++ b/chromium/content/renderer/media/webrtc/webrtc_media_stream_adapter_unittest.cc
@@ -26,12 +26,12 @@
#include "content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebMediaStream.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
-#include "third_party/WebKit/public/platform/WebVector.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
-#include "third_party/WebKit/public/web/WebHeap.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/web_media_stream.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
+#include "third_party/blink/public/platform/web_vector.h"
+#include "third_party/blink/public/web/web_heap.h"
using ::testing::_;
@@ -250,7 +250,7 @@ TEST_F(LocalWebRtcMediaStreamAdapterTest, CreateStreamAdapter) {
EXPECT_TRUE(adapter->IsEqual(web_stream));
EXPECT_EQ(1u, adapter->webrtc_stream()->GetAudioTracks().size());
EXPECT_EQ(1u, adapter->webrtc_stream()->GetVideoTracks().size());
- EXPECT_EQ(web_stream.Id().Utf8(), adapter->webrtc_stream()->label());
+ EXPECT_EQ(web_stream.Id().Utf8(), adapter->webrtc_stream()->id());
}
TEST_F(LocalWebRtcMediaStreamAdapterTest,
@@ -263,7 +263,7 @@ TEST_F(LocalWebRtcMediaStreamAdapterTest,
EXPECT_TRUE(adapter->IsEqual(web_stream));
EXPECT_EQ(1u, adapter->webrtc_stream()->GetAudioTracks().size());
EXPECT_EQ(1u, adapter->webrtc_stream()->GetVideoTracks().size());
- EXPECT_EQ(web_stream.Id().Utf8(), adapter->webrtc_stream()->label());
+ EXPECT_EQ(web_stream.Id().Utf8(), adapter->webrtc_stream()->id());
}
// It should not crash if |MediaStream| is created in blink with an unknown
@@ -294,7 +294,7 @@ TEST_F(LocalWebRtcMediaStreamAdapterTest,
EXPECT_TRUE(adapter->IsEqual(web_stream));
EXPECT_EQ(0u, adapter->webrtc_stream()->GetAudioTracks().size());
EXPECT_EQ(0u, adapter->webrtc_stream()->GetVideoTracks().size());
- EXPECT_EQ(web_stream.Id().Utf8(), adapter->webrtc_stream()->label());
+ EXPECT_EQ(web_stream.Id().Utf8(), adapter->webrtc_stream()->id());
}
TEST_F(LocalWebRtcMediaStreamAdapterTest, RemoveAndAddTrack) {
@@ -306,7 +306,7 @@ TEST_F(LocalWebRtcMediaStreamAdapterTest, RemoveAndAddTrack) {
EXPECT_TRUE(adapter->IsEqual(web_stream));
EXPECT_EQ(1u, adapter->webrtc_stream()->GetAudioTracks().size());
EXPECT_EQ(1u, adapter->webrtc_stream()->GetVideoTracks().size());
- EXPECT_EQ(web_stream.Id().Utf8(), adapter->webrtc_stream()->label());
+ EXPECT_EQ(web_stream.Id().Utf8(), adapter->webrtc_stream()->id());
// Modify the web layer stream, make sure the webrtc layer stream is updated.
blink::WebVector<blink::WebMediaStreamTrack> audio_tracks;
diff --git a/chromium/content/renderer/media/webrtc/webrtc_media_stream_track_adapter.cc b/chromium/content/renderer/media/webrtc/webrtc_media_stream_track_adapter.cc
index 967ffd20fb7..165c22fd603 100644
--- a/chromium/content/renderer/media/webrtc/webrtc_media_stream_track_adapter.cc
+++ b/chromium/content/renderer/media/webrtc/webrtc_media_stream_track_adapter.cc
@@ -184,6 +184,11 @@ void WebRtcMediaStreamTrackAdapter::InitializeRemoteAudioTrack(
remote_audio_track_adapter_ =
new RemoteAudioTrackAdapter(main_thread_, webrtc_audio_track.get());
webrtc_track_ = webrtc_audio_track;
+ // Set the initial volume to zero. When the track is put in an audio tag for
+ // playout, its volume is set to that of the tag. Without this, we could end
+ // up playing out audio that's not attached to any tag, see:
+ // http://crbug.com/810848
+ webrtc_audio_track->GetSource()->SetVolume(0);
remote_track_can_complete_initialization_.Signal();
main_thread_->PostTask(
FROM_HERE,
diff --git a/chromium/content/renderer/media/webrtc/webrtc_media_stream_track_adapter.h b/chromium/content/renderer/media/webrtc/webrtc_media_stream_track_adapter.h
index 321de1f1cbe..722738c3950 100644
--- a/chromium/content/renderer/media/webrtc/webrtc_media_stream_track_adapter.h
+++ b/chromium/content/renderer/media/webrtc/webrtc_media_stream_track_adapter.h
@@ -14,8 +14,8 @@
#include "content/renderer/media/webrtc/media_stream_video_webrtc_sink.h"
#include "content/renderer/media/webrtc/webrtc_audio_sink.h"
#include "content/renderer/media/webrtc/webrtc_media_stream_track_adapter.h"
-#include "third_party/WebKit/public/platform/WebMediaStream.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
+#include "third_party/blink/public/platform/web_media_stream.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
#include "third_party/webrtc/api/mediastreaminterface.h"
namespace content {
diff --git a/chromium/content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map.h b/chromium/content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map.h
index 870d018c1f8..c7ef9ed9b92 100644
--- a/chromium/content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map.h
+++ b/chromium/content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map.h
@@ -13,7 +13,7 @@
#include "content/common/content_export.h"
#include "content/renderer/media/webrtc/two_keys_adapter_map.h"
#include "content/renderer/media/webrtc/webrtc_media_stream_track_adapter.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
#include "third_party/webrtc/api/mediastreaminterface.h"
namespace content {
diff --git a/chromium/content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map_unittest.cc b/chromium/content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map_unittest.cc
index 3b9bf333717..3504e3d6817 100644
--- a/chromium/content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map_unittest.cc
+++ b/chromium/content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map_unittest.cc
@@ -14,11 +14,11 @@
#include "content/renderer/media/stream/media_stream_audio_source.h"
#include "content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
-#include "third_party/WebKit/public/web/WebHeap.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/web/web_heap.h"
namespace content {
diff --git a/chromium/content/renderer/media/webrtc/webrtc_media_stream_track_adapter_unittest.cc b/chromium/content/renderer/media/webrtc/webrtc_media_stream_track_adapter_unittest.cc
index 14793d4edab..7ca513bc07f 100644
--- a/chromium/content/renderer/media/webrtc/webrtc_media_stream_track_adapter_unittest.cc
+++ b/chromium/content/renderer/media/webrtc/webrtc_media_stream_track_adapter_unittest.cc
@@ -18,11 +18,11 @@
#include "content/renderer/media/stream/mock_media_stream_video_source.h"
#include "content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
-#include "third_party/WebKit/public/web/WebHeap.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/web/web_heap.h"
namespace content {
diff --git a/chromium/content/renderer/media/webrtc/webrtc_set_remote_description_observer_unittest.cc b/chromium/content/renderer/media/webrtc/webrtc_set_remote_description_observer_unittest.cc
index 82ccfc93143..5b861458a11 100644
--- a/chromium/content/renderer/media/webrtc/webrtc_set_remote_description_observer_unittest.cc
+++ b/chromium/content/renderer/media/webrtc/webrtc_set_remote_description_observer_unittest.cc
@@ -19,8 +19,8 @@
#include "content/renderer/media/webrtc/webrtc_media_stream_adapter_map.h"
#include "content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
-#include "third_party/WebKit/public/web/WebHeap.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/web/web_heap.h"
#include "third_party/webrtc/api/peerconnectioninterface.h"
#include "third_party/webrtc/media/base/fakemediaengine.h"
#include "third_party/webrtc/pc/test/mock_peerconnection.h"
diff --git a/chromium/content/renderer/media/webrtc/webrtc_uma_histograms.cc b/chromium/content/renderer/media/webrtc/webrtc_uma_histograms.cc
index cb76b39cae9..2d4063d0ead 100644
--- a/chromium/content/renderer/media/webrtc/webrtc_uma_histograms.cc
+++ b/chromium/content/renderer/media/webrtc/webrtc_uma_histograms.cc
@@ -19,9 +19,11 @@ void LogUserMediaRequestResult(MediaStreamRequestResult result) {
NUM_MEDIA_REQUEST_RESULTS);
}
-void UpdateWebRTCMethodCount(JavaScriptAPIName api_name) {
- DVLOG(3) << "Incrementing WebRTC.webkitApiCount for " << api_name;
- UMA_HISTOGRAM_ENUMERATION("WebRTC.webkitApiCount", api_name, INVALID_NAME);
+void UpdateWebRTCMethodCount(blink::WebRTCAPIName api_name) {
+ DVLOG(3) << "Incrementing WebRTC.webkitApiCount for "
+ << static_cast<int>(api_name);
+ UMA_HISTOGRAM_ENUMERATION("WebRTC.webkitApiCount", api_name,
+ blink::WebRTCAPIName::kInvalidName);
PerSessionWebRTCAPIMetrics::GetInstance()->LogUsageOnlyOnce(api_name);
}
@@ -50,16 +52,18 @@ PerSessionWebRTCAPIMetrics::PerSessionWebRTCAPIMetrics() : num_streams_(0) {
ResetUsage();
}
-void PerSessionWebRTCAPIMetrics::LogUsage(JavaScriptAPIName api_name) {
- DVLOG(3) << "Incrementing WebRTC.webkitApiCountPerSession for " << api_name;
- UMA_HISTOGRAM_ENUMERATION("WebRTC.webkitApiCountPerSession",
- api_name, INVALID_NAME);
+void PerSessionWebRTCAPIMetrics::LogUsage(blink::WebRTCAPIName api_name) {
+ DVLOG(3) << "Incrementing WebRTC.webkitApiCountPerSession for "
+ << static_cast<int>(api_name);
+ UMA_HISTOGRAM_ENUMERATION("WebRTC.webkitApiCountPerSession", api_name,
+ blink::WebRTCAPIName::kInvalidName);
}
-void PerSessionWebRTCAPIMetrics::LogUsageOnlyOnce(JavaScriptAPIName api_name) {
+void PerSessionWebRTCAPIMetrics::LogUsageOnlyOnce(
+ blink::WebRTCAPIName api_name) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
- if (!has_used_api_[api_name]) {
- has_used_api_[api_name] = true;
+ if (!has_used_api_[static_cast<int>(api_name)]) {
+ has_used_api_[static_cast<int>(api_name)] = true;
LogUsage(api_name);
}
}
diff --git a/chromium/content/renderer/media/webrtc/webrtc_uma_histograms.h b/chromium/content/renderer/media/webrtc/webrtc_uma_histograms.h
index 65da3d6fc2a..70ebad20e8a 100644
--- a/chromium/content/renderer/media/webrtc/webrtc_uma_histograms.h
+++ b/chromium/content/renderer/media/webrtc/webrtc_uma_histograms.h
@@ -10,6 +10,7 @@
#include "base/sequence_checker.h"
#include "content/common/content_export.h"
#include "content/public/common/media_stream_request.h"
+#include "third_party/blink/public/platform/web_rtc_api_name.h"
namespace content {
@@ -30,20 +31,6 @@ enum MediaStreamRequestState {
void LogUserMediaRequestWithNoResult(MediaStreamRequestState state);
void LogUserMediaRequestResult(MediaStreamRequestResult result);
-// Helper enum used for histogramming calls to WebRTC APIs from JavaScript.
-// The entries are linked to UMA values and cannot be changed.
-enum JavaScriptAPIName {
- WEBKIT_GET_USER_MEDIA,
- WEBKIT_PEER_CONNECTION,
- WEBKIT_DEPRECATED_PEER_CONNECTION,
- WEBKIT_RTC_PEER_CONNECTION,
- WEBKIT_GET_MEDIA_DEVICES,
- WEBKIT_MEDIA_STREAM_RECORDER,
- WEBKIT_CANVAS_CAPTURE_STREAM,
- WEBKIT_VIDEO_CAPTURE_STREAM,
- INVALID_NAME
-};
-
// Helper method used to collect information about the number of times
// different WebRTC APIs are called from JavaScript.
//
@@ -55,7 +42,7 @@ enum JavaScriptAPIName {
// that gets incremented only once per "session" as established by the
// PerSessionWebRTCAPIMetrics singleton below. It can be viewed at
// chrome://histograms/WebRTC.webkitApiCountPerSession.
-void UpdateWebRTCMethodCount(JavaScriptAPIName api_name);
+void UpdateWebRTCMethodCount(blink::WebRTCAPIName api_name);
// A singleton that keeps track of the number of MediaStreams being
// sent over PeerConnections. It uses the transition to zero such
@@ -79,24 +66,24 @@ class CONTENT_EXPORT PerSessionWebRTCAPIMetrics {
protected:
friend struct base::DefaultSingletonTraits<PerSessionWebRTCAPIMetrics>;
- friend void UpdateWebRTCMethodCount(JavaScriptAPIName);
+ friend void UpdateWebRTCMethodCount(blink::WebRTCAPIName);
// Protected so that unit tests can test without this being a
// singleton.
PerSessionWebRTCAPIMetrics();
// Overridable by unit tests.
- virtual void LogUsage(JavaScriptAPIName api_name);
+ virtual void LogUsage(blink::WebRTCAPIName api_name);
// Called by UpdateWebRTCMethodCount above. Protected rather than
// private so that unit tests can call it.
- void LogUsageOnlyOnce(JavaScriptAPIName api_name);
+ void LogUsageOnlyOnce(blink::WebRTCAPIName api_name);
private:
void ResetUsage();
int num_streams_;
- bool has_used_api_[INVALID_NAME];
+ bool has_used_api_[static_cast<int>(blink::WebRTCAPIName::kInvalidName)];
SEQUENCE_CHECKER(sequence_checker_);
diff --git a/chromium/content/renderer/media/webrtc/webrtc_uma_histograms_unittest.cc b/chromium/content/renderer/media/webrtc/webrtc_uma_histograms_unittest.cc
index bcb5b10ddec..3f7a4fa4363 100644
--- a/chromium/content/renderer/media/webrtc/webrtc_uma_histograms_unittest.cc
+++ b/chromium/content/renderer/media/webrtc/webrtc_uma_histograms_unittest.cc
@@ -17,63 +17,67 @@ class MockPerSessionWebRTCAPIMetrics : public PerSessionWebRTCAPIMetrics {
using PerSessionWebRTCAPIMetrics::LogUsageOnlyOnce;
- MOCK_METHOD1(LogUsage, void(JavaScriptAPIName));
+ MOCK_METHOD1(LogUsage, void(blink::WebRTCAPIName));
};
TEST(PerSessionWebRTCAPIMetrics, NoCallOngoingGetUserMedia) {
MockPerSessionWebRTCAPIMetrics metrics;
EXPECT_CALL(metrics, LogUsage(_)).Times(1);
- metrics.LogUsageOnlyOnce(WEBKIT_GET_USER_MEDIA);
+ metrics.LogUsageOnlyOnce(blink::WebRTCAPIName::kGetUserMedia);
}
TEST(PerSessionWebRTCAPIMetrics, CallOngoingGetUserMedia) {
MockPerSessionWebRTCAPIMetrics metrics;
metrics.IncrementStreamCounter();
- EXPECT_CALL(metrics, LogUsage(WEBKIT_GET_USER_MEDIA)).Times(1);
- metrics.LogUsageOnlyOnce(WEBKIT_GET_USER_MEDIA);
+ EXPECT_CALL(metrics, LogUsage(blink::WebRTCAPIName::kGetUserMedia)).Times(1);
+ metrics.LogUsageOnlyOnce(blink::WebRTCAPIName::kGetUserMedia);
}
TEST(PerSessionWebRTCAPIMetrics, NoCallOngoingGetMediaDevices) {
MockPerSessionWebRTCAPIMetrics metrics;
EXPECT_CALL(metrics, LogUsage(_)).Times(1);
- metrics.LogUsageOnlyOnce(WEBKIT_GET_MEDIA_DEVICES);
+ metrics.LogUsageOnlyOnce(blink::WebRTCAPIName::kEnumerateDevices);
}
TEST(PerSessionWebRTCAPIMetrics, CallOngoingGetMediaDevices) {
MockPerSessionWebRTCAPIMetrics metrics;
metrics.IncrementStreamCounter();
- EXPECT_CALL(metrics, LogUsage(WEBKIT_GET_MEDIA_DEVICES)).Times(1);
- metrics.LogUsageOnlyOnce(WEBKIT_GET_MEDIA_DEVICES);
+ EXPECT_CALL(metrics, LogUsage(blink::WebRTCAPIName::kEnumerateDevices))
+ .Times(1);
+ metrics.LogUsageOnlyOnce(blink::WebRTCAPIName::kEnumerateDevices);
}
TEST(PerSessionWebRTCAPIMetrics, NoCallOngoingRTCPeerConnection) {
MockPerSessionWebRTCAPIMetrics metrics;
- EXPECT_CALL(metrics, LogUsage(WEBKIT_RTC_PEER_CONNECTION));
- metrics.LogUsageOnlyOnce(WEBKIT_RTC_PEER_CONNECTION);
+ EXPECT_CALL(metrics, LogUsage(blink::WebRTCAPIName::kRTCPeerConnection));
+ metrics.LogUsageOnlyOnce(blink::WebRTCAPIName::kRTCPeerConnection);
}
TEST(PerSessionWebRTCAPIMetrics, NoCallOngoingMultiplePC) {
MockPerSessionWebRTCAPIMetrics metrics;
- EXPECT_CALL(metrics, LogUsage(WEBKIT_RTC_PEER_CONNECTION)).Times(1);
- metrics.LogUsageOnlyOnce(WEBKIT_RTC_PEER_CONNECTION);
- metrics.LogUsageOnlyOnce(WEBKIT_RTC_PEER_CONNECTION);
- metrics.LogUsageOnlyOnce(WEBKIT_RTC_PEER_CONNECTION);
+ EXPECT_CALL(metrics, LogUsage(blink::WebRTCAPIName::kRTCPeerConnection))
+ .Times(1);
+ metrics.LogUsageOnlyOnce(blink::WebRTCAPIName::kRTCPeerConnection);
+ metrics.LogUsageOnlyOnce(blink::WebRTCAPIName::kRTCPeerConnection);
+ metrics.LogUsageOnlyOnce(blink::WebRTCAPIName::kRTCPeerConnection);
}
TEST(PerSessionWebRTCAPIMetrics, BeforeAfterCallMultiplePC) {
MockPerSessionWebRTCAPIMetrics metrics;
- EXPECT_CALL(metrics, LogUsage(WEBKIT_RTC_PEER_CONNECTION)).Times(1);
- metrics.LogUsageOnlyOnce(WEBKIT_RTC_PEER_CONNECTION);
- metrics.LogUsageOnlyOnce(WEBKIT_RTC_PEER_CONNECTION);
+ EXPECT_CALL(metrics, LogUsage(blink::WebRTCAPIName::kRTCPeerConnection))
+ .Times(1);
+ metrics.LogUsageOnlyOnce(blink::WebRTCAPIName::kRTCPeerConnection);
+ metrics.LogUsageOnlyOnce(blink::WebRTCAPIName::kRTCPeerConnection);
metrics.IncrementStreamCounter();
metrics.IncrementStreamCounter();
- metrics.LogUsageOnlyOnce(WEBKIT_RTC_PEER_CONNECTION);
+ metrics.LogUsageOnlyOnce(blink::WebRTCAPIName::kRTCPeerConnection);
metrics.DecrementStreamCounter();
- metrics.LogUsageOnlyOnce(WEBKIT_RTC_PEER_CONNECTION);
+ metrics.LogUsageOnlyOnce(blink::WebRTCAPIName::kRTCPeerConnection);
metrics.DecrementStreamCounter();
- EXPECT_CALL(metrics, LogUsage(WEBKIT_RTC_PEER_CONNECTION)).Times(1);
- metrics.LogUsageOnlyOnce(WEBKIT_RTC_PEER_CONNECTION);
- metrics.LogUsageOnlyOnce(WEBKIT_RTC_PEER_CONNECTION);
+ EXPECT_CALL(metrics, LogUsage(blink::WebRTCAPIName::kRTCPeerConnection))
+ .Times(1);
+ metrics.LogUsageOnlyOnce(blink::WebRTCAPIName::kRTCPeerConnection);
+ metrics.LogUsageOnlyOnce(blink::WebRTCAPIName::kRTCPeerConnection);
}
} // namespace content
diff --git a/chromium/content/renderer/media/webrtc/webrtc_video_capturer_adapter.h b/chromium/content/renderer/media/webrtc/webrtc_video_capturer_adapter.h
index bd81bff0f8e..f51e39593ab 100644
--- a/chromium/content/renderer/media/webrtc/webrtc_video_capturer_adapter.h
+++ b/chromium/content/renderer/media/webrtc/webrtc_video_capturer_adapter.h
@@ -16,7 +16,7 @@
#include "media/base/video_frame.h"
#include "media/base/video_frame_pool.h"
#include "media/capture/video_capture_types.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
#include "third_party/webrtc/media/base/videocapturer.h"
namespace content {
diff --git a/chromium/content/renderer/media/webrtc_local_audio_source_provider.cc b/chromium/content/renderer/media/webrtc_local_audio_source_provider.cc
index 68a4a9919b3..5785a4d3c33 100644
--- a/chromium/content/renderer/media/webrtc_local_audio_source_provider.cc
+++ b/chromium/content/renderer/media/webrtc_local_audio_source_provider.cc
@@ -9,9 +9,9 @@
#include "content/renderer/media/audio_device_factory.h"
#include "media/base/audio_fifo.h"
#include "media/base/audio_parameters.h"
-#include "third_party/WebKit/public/platform/WebAudioSourceProviderClient.h"
-#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "third_party/blink/public/platform/web_audio_source_provider_client.h"
+#include "third_party/blink/public/platform/web_security_origin.h"
+#include "third_party/blink/public/web/web_local_frame.h"
using blink::WebVector;
diff --git a/chromium/content/renderer/media/webrtc_local_audio_source_provider.h b/chromium/content/renderer/media/webrtc_local_audio_source_provider.h
index 6917cf2272e..44392806101 100644
--- a/chromium/content/renderer/media/webrtc_local_audio_source_provider.h
+++ b/chromium/content/renderer/media/webrtc_local_audio_source_provider.h
@@ -17,9 +17,9 @@
#include "content/common/content_export.h"
#include "content/public/renderer/media_stream_audio_sink.h"
#include "media/base/audio_converter.h"
-#include "third_party/WebKit/public/platform/WebAudioSourceProvider.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
-#include "third_party/WebKit/public/platform/WebVector.h"
+#include "third_party/blink/public/platform/web_audio_source_provider.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
+#include "third_party/blink/public/platform/web_vector.h"
namespace media {
class AudioBus;
diff --git a/chromium/content/renderer/media/webrtc_local_audio_source_provider_unittest.cc b/chromium/content/renderer/media/webrtc_local_audio_source_provider_unittest.cc
index 77da5cf9aa8..d318d41ac61 100644
--- a/chromium/content/renderer/media/webrtc_local_audio_source_provider_unittest.cc
+++ b/chromium/content/renderer/media/webrtc_local_audio_source_provider_unittest.cc
@@ -10,9 +10,9 @@
#include "media/base/audio_bus.h"
#include "media/base/audio_parameters.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/web/WebHeap.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/web/web_heap.h"
namespace content {
diff --git a/chromium/content/renderer/media_capture_from_element/canvas_capture_handler.cc b/chromium/content/renderer/media_capture_from_element/canvas_capture_handler.cc
index 9190dd70acf..cb0b8e983e1 100644
--- a/chromium/content/renderer/media_capture_from_element/canvas_capture_handler.cc
+++ b/chromium/content/renderer/media_capture_from_element/canvas_capture_handler.cc
@@ -21,9 +21,9 @@
#include "content/renderer/render_thread_impl.h"
#include "media/base/limits.h"
#include "skia/ext/texture_handle.h"
-#include "third_party/WebKit/public/platform/WebGraphicsContext3DProvider.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/WebString.h"
+#include "third_party/blink/public/platform/web_graphics_context_3d_provider.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/platform/web_string.h"
#include "third_party/libyuv/include/libyuv.h"
#include "third_party/skia/include/core/SkImage.h"
@@ -145,7 +145,7 @@ CanvasCaptureHandler::CreateCanvasCaptureHandler(
blink::WebMediaStreamTrack* track) {
// Save histogram data so we can see how much CanvasCapture is used.
// The histogram counts the number of calls to the JS API.
- UpdateWebRTCMethodCount(WEBKIT_CANVAS_CAPTURE_STREAM);
+ UpdateWebRTCMethodCount(blink::WebRTCAPIName::kCanvasCaptureStream);
return std::unique_ptr<CanvasCaptureHandler>(new CanvasCaptureHandler(
size, frame_rate, std::move(io_task_runner), track));
@@ -290,7 +290,6 @@ void CanvasCaptureHandler::ReadARGBPixelsAsync(
base::Bind(&CanvasCaptureHandler::OnARGBPixelsReadAsync,
weak_ptr_factory_.GetWeakPtr(), image, temp_argb_frame,
timestamp, surface_origin != kTopLeft_GrSurfaceOrigin));
- context_provider->InvalidateGrContext(kTextureBinding_GrGLBackendState);
}
void CanvasCaptureHandler::ReadYUVPixelsAsync(
@@ -331,8 +330,6 @@ void CanvasCaptureHandler::ReadYUVPixelsAsync(
base::Bind(&CanvasCaptureHandler::OnYUVPixelsReadAsync,
weak_ptr_factory_.GetWeakPtr(), image, output_frame,
timestamp));
- context_provider->InvalidateGrContext(
- viz::ReadbackYUVInterface::GetGrGLBackendStateChanges());
}
void CanvasCaptureHandler::OnARGBPixelsReadAsync(
diff --git a/chromium/content/renderer/media_capture_from_element/canvas_capture_handler.h b/chromium/content/renderer/media_capture_from_element/canvas_capture_handler.h
index d9f28613b51..8ff04562de5 100644
--- a/chromium/content/renderer/media_capture_from_element/canvas_capture_handler.h
+++ b/chromium/content/renderer/media_capture_from_element/canvas_capture_handler.h
@@ -18,9 +18,9 @@
#include "content/common/content_export.h"
#include "media/base/video_frame_pool.h"
#include "media/capture/video_capturer_source.h"
-#include "third_party/WebKit/public/platform/WebCanvasCaptureHandler.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
-#include "third_party/WebKit/public/platform/WebSize.h"
+#include "third_party/blink/public/platform/web_canvas_capture_handler.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
+#include "third_party/blink/public/platform/web_size.h"
#include "third_party/skia/include/core/SkImageInfo.h"
class SkImage;
diff --git a/chromium/content/renderer/media_capture_from_element/canvas_capture_handler_unittest.cc b/chromium/content/renderer/media_capture_from_element/canvas_capture_handler_unittest.cc
index 5ba5a1199f2..94b495d7b30 100644
--- a/chromium/content/renderer/media_capture_from_element/canvas_capture_handler_unittest.cc
+++ b/chromium/content/renderer/media_capture_from_element/canvas_capture_handler_unittest.cc
@@ -12,10 +12,10 @@
#include "media/base/limits.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
-#include "third_party/WebKit/public/platform/WebSize.h"
-#include "third_party/WebKit/public/web/WebHeap.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
+#include "third_party/blink/public/platform/web_size.h"
+#include "third_party/blink/public/web/web_heap.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/core/SkRefCnt.h"
@@ -181,7 +181,7 @@ TEST_P(CanvasCaptureHandlerTest, GetFormatsStartAndStop) {
EXPECT_CALL(*this, DoOnRunning(true)).Times(1);
EXPECT_CALL(*this, DoOnDeliverFrame(_, _))
.Times(1)
- .WillOnce(RunClosure(quit_closure));
+ .WillOnce(RunClosure(std::move(quit_closure)));
source->StartCapture(
params, base::Bind(&CanvasCaptureHandlerTest::OnDeliverFrame,
base::Unretained(this)),
diff --git a/chromium/content/renderer/media_capture_from_element/html_audio_element_capturer_source.cc b/chromium/content/renderer/media_capture_from_element/html_audio_element_capturer_source.cc
index d6bf00c5eb0..4711085149e 100644
--- a/chromium/content/renderer/media_capture_from_element/html_audio_element_capturer_source.cc
+++ b/chromium/content/renderer/media_capture_from_element/html_audio_element_capturer_source.cc
@@ -9,7 +9,7 @@
#include "media/base/audio_renderer_sink.h"
#include "media/blink/webaudiosourceprovider_impl.h"
#include "media/blink/webmediaplayer_impl.h"
-#include "third_party/WebKit/public/platform/WebMediaPlayer.h"
+#include "third_party/blink/public/platform/web_media_player.h"
namespace content {
diff --git a/chromium/content/renderer/media_capture_from_element/html_audio_element_capturer_source_unittest.cc b/chromium/content/renderer/media_capture_from_element/html_audio_element_capturer_source_unittest.cc
index 66106674512..f06640d7735 100644
--- a/chromium/content/renderer/media_capture_from_element/html_audio_element_capturer_source_unittest.cc
+++ b/chromium/content/renderer/media_capture_from_element/html_audio_element_capturer_source_unittest.cc
@@ -2,13 +2,13 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
+#include "content/renderer/media_capture_from_element/html_audio_element_capturer_source.h"
#include "base/memory/weak_ptr.h"
#include "base/run_loop.h"
#include "base/test/scoped_task_environment.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/public/renderer/media_stream_audio_sink.h"
#include "content/renderer/media/stream/media_stream_audio_track.h"
-#include "content/renderer/media_capture_from_element/html_audio_element_capturer_source.h"
#include "media/audio/null_audio_sink.h"
#include "media/base/audio_parameters.h"
#include "media/base/fake_audio_render_callback.h"
@@ -16,9 +16,9 @@
#include "media/blink/webaudiosourceprovider_impl.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
-#include "third_party/WebKit/public/web/WebHeap.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/web/web_heap.h"
using ::testing::_;
using ::testing::AllOf;
@@ -151,7 +151,7 @@ TEST_F(HTMLAudioElementCapturerSourceTest, CaptureAudio) {
kAudioTrackSamplesPerBuffer)),
_))
.Times(1)
- .WillOnce(RunClosure(quit_closure));
+ .WillOnce(RunClosure(std::move(quit_closure)));
std::unique_ptr<media::AudioBus> bus = media::AudioBus::Create(
kNumChannelsForTest, kAudioTrackSamplesPerBuffer);
diff --git a/chromium/content/renderer/media_capture_from_element/html_video_element_capturer_source.cc b/chromium/content/renderer/media_capture_from_element/html_video_element_capturer_source.cc
index 1da1f237f29..de6e209743c 100644
--- a/chromium/content/renderer/media_capture_from_element/html_video_element_capturer_source.cc
+++ b/chromium/content/renderer/media_capture_from_element/html_video_element_capturer_source.cc
@@ -16,9 +16,9 @@
#include "media/base/limits.h"
#include "media/blink/webmediaplayer_impl.h"
#include "skia/ext/platform_canvas.h"
-#include "third_party/WebKit/public/platform/WebMediaPlayer.h"
-#include "third_party/WebKit/public/platform/WebRect.h"
-#include "third_party/WebKit/public/platform/WebSize.h"
+#include "third_party/blink/public/platform/web_media_player.h"
+#include "third_party/blink/public/platform/web_rect.h"
+#include "third_party/blink/public/platform/web_size.h"
#include "third_party/libyuv/include/libyuv.h"
namespace {
@@ -35,7 +35,7 @@ HtmlVideoElementCapturerSource::CreateFromWebMediaPlayerImpl(
scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
// Save histogram data so we can see how much HTML Video capture is used.
// The histogram counts the number of calls to the JS API.
- UpdateWebRTCMethodCount(WEBKIT_VIDEO_CAPTURE_STREAM);
+ UpdateWebRTCMethodCount(blink::WebRTCAPIName::kVideoCaptureStream);
return base::WrapUnique(new HtmlVideoElementCapturerSource(
static_cast<media::WebMediaPlayerImpl*>(player)->AsWeakPtr(),
diff --git a/chromium/content/renderer/media_capture_from_element/html_video_element_capturer_source.h b/chromium/content/renderer/media_capture_from_element/html_video_element_capturer_source.h
index ffa02a319b3..0d9273e6dce 100644
--- a/chromium/content/renderer/media_capture_from_element/html_video_element_capturer_source.h
+++ b/chromium/content/renderer/media_capture_from_element/html_video_element_capturer_source.h
@@ -13,7 +13,7 @@
#include "media/base/video_frame_pool.h"
#include "media/base/video_types.h"
#include "media/capture/video_capturer_source.h"
-#include "third_party/WebKit/public/platform/WebSize.h"
+#include "third_party/blink/public/platform/web_size.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkRefCnt.h"
diff --git a/chromium/content/renderer/media_capture_from_element/html_video_element_capturer_source_unittest.cc b/chromium/content/renderer/media_capture_from_element/html_video_element_capturer_source_unittest.cc
index 539553512c8..bc7b05c6f10 100644
--- a/chromium/content/renderer/media_capture_from_element/html_video_element_capturer_source_unittest.cc
+++ b/chromium/content/renderer/media_capture_from_element/html_video_element_capturer_source_unittest.cc
@@ -11,9 +11,9 @@
#include "media/base/limits.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebMediaPlayer.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/web_media_player.h"
+#include "third_party/blink/public/platform/web_string.h"
using ::testing::_;
using ::testing::InSequence;
@@ -40,6 +40,7 @@ class MockWebMediaPlayer : public blink::WebMediaPlayer,
void SetRate(double) override {}
void SetVolume(double) override {}
void EnterPictureInPicture() override {}
+ void ExitPictureInPicture() override {}
blink::WebTimeRanges Buffered() const override {
return blink::WebTimeRanges();
}
@@ -146,7 +147,8 @@ TEST_F(HTMLVideoElementCapturerSourceTest, GetFormatsAndStartAndStop) {
EXPECT_CALL(*this, DoOnDeliverFrame(_, _)).WillOnce(SaveArg<0>(&first_frame));
EXPECT_CALL(*this, DoOnDeliverFrame(_, _))
.Times(1)
- .WillOnce(DoAll(SaveArg<0>(&second_frame), RunClosure(quit_closure)));
+ .WillOnce(DoAll(SaveArg<0>(&second_frame),
+ RunClosure(std::move(quit_closure))));
html_video_capturer_->StartCapture(
params, base::Bind(&HTMLVideoElementCapturerSourceTest::OnDeliverFrame,
diff --git a/chromium/content/renderer/media_recorder/audio_track_recorder.h b/chromium/content/renderer/media_recorder/audio_track_recorder.h
index eea054429a9..2ea641d4837 100644
--- a/chromium/content/renderer/media_recorder/audio_track_recorder.h
+++ b/chromium/content/renderer/media_recorder/audio_track_recorder.h
@@ -15,7 +15,7 @@
#include "base/time/time.h"
#include "content/public/renderer/media_stream_audio_sink.h"
#include "content/renderer/media_recorder/audio_track_encoder.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
namespace media {
class AudioBus;
diff --git a/chromium/content/renderer/media_recorder/audio_track_recorder_unittest.cc b/chromium/content/renderer/media_recorder/audio_track_recorder_unittest.cc
index 67f9efb1dbb..c3440cf2c51 100644
--- a/chromium/content/renderer/media_recorder/audio_track_recorder_unittest.cc
+++ b/chromium/content/renderer/media_recorder/audio_track_recorder_unittest.cc
@@ -20,8 +20,8 @@
#include "media/base/audio_sample_types.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/web/WebHeap.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/web/web_heap.h"
#include "third_party/opus/src/include/opus.h"
using ::testing::_;
@@ -308,7 +308,7 @@ TEST_P(AudioTrackRecorderTest, OnDataOpus) {
// Send audio with different params.
EXPECT_CALL(*this, DoOnEncodedAudio(_, _, _))
.Times(1)
- .WillOnce(RunClosure(quit_closure));
+ .WillOnce(RunClosure(std::move(quit_closure)));
audio_track_recorder_->OnData(*GetSecondSourceAudioBus(), TimeTicks::Now());
for (int i = 0; i < kRatioInputToOutputFrames - 1; ++i)
audio_track_recorder_->OnData(*GetSecondSourceAudioBus(), TimeTicks::Now());
@@ -329,7 +329,7 @@ TEST_P(AudioTrackRecorderTest, OnDataPcm) {
EXPECT_CALL(*this, DoOnEncodedAudio(_, _, _)).Times(5);
EXPECT_CALL(*this, DoOnEncodedAudio(_, _, _))
- .WillOnce(RunClosure(quit_closure));
+ .WillOnce(RunClosure(std::move(quit_closure)));
audio_track_recorder_->OnData(*GetFirstSourceAudioBus(), TimeTicks::Now());
for (int i = 0; i < kRatioInputToOutputFrames - 1; ++i)
@@ -359,7 +359,7 @@ TEST_P(AudioTrackRecorderTest, PauseResume) {
audio_track_recorder_->Resume();
EXPECT_CALL(*this, DoOnEncodedAudio(_, _, _))
.Times(1)
- .WillOnce(RunClosure(quit_closure));
+ .WillOnce(RunClosure(std::move(quit_closure)));
audio_track_recorder_->OnData(*GetFirstSourceAudioBus(), TimeTicks::Now());
for (int i = 0; i < kRatioInputToOutputFrames - 1; ++i)
audio_track_recorder_->OnData(*GetFirstSourceAudioBus(), TimeTicks::Now());
diff --git a/chromium/content/renderer/media_recorder/h264_encoder.h b/chromium/content/renderer/media_recorder/h264_encoder.h
index 524dd697def..7074ffb3a63 100644
--- a/chromium/content/renderer/media_recorder/h264_encoder.h
+++ b/chromium/content/renderer/media_recorder/h264_encoder.h
@@ -5,7 +5,7 @@
#ifndef CONTENT_RENDERER_MEDIA_RECORDER_H264_ENCODER_H_
#define CONTENT_RENDERER_MEDIA_RECORDER_H264_ENCODER_H_
-#include "content/public/common/features.h"
+#include "content/public/common/buildflags.h"
#if !BUILDFLAG(RTC_USE_H264)
#error RTC_USE_H264 should be defined.
diff --git a/chromium/content/renderer/media_recorder/media_recorder_handler.cc b/chromium/content/renderer/media_recorder/media_recorder_handler.cc
index 047c1dab594..f8e88b898de 100644
--- a/chromium/content/renderer/media_recorder/media_recorder_handler.cc
+++ b/chromium/content/renderer/media_recorder/media_recorder_handler.cc
@@ -26,10 +26,10 @@
#include "media/base/video_codecs.h"
#include "media/base/video_frame.h"
#include "media/muxers/webm_muxer.h"
-#include "third_party/WebKit/public/platform/WebMediaRecorderHandlerClient.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/modules/media_capabilities/WebMediaConfiguration.h"
+#include "third_party/blink/public/platform/modules/media_capabilities/web_media_configuration.h"
+#include "third_party/blink/public/platform/web_media_recorder_handler_client.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/platform/web_string.h"
using base::TimeDelta;
using base::TimeTicks;
@@ -190,7 +190,7 @@ bool MediaRecorderHandler::Initialize(
DCHECK(main_render_thread_checker_.CalledOnValidThread());
// Save histogram data so we can see how much MediaStream Recorder is used.
// The histogram counts the number of calls to the JS API.
- UpdateWebRTCMethodCount(WEBKIT_MEDIA_STREAM_RECORDER);
+ UpdateWebRTCMethodCount(blink::WebRTCAPIName::kMediaStreamRecorder);
if (!CanSupportMimeType(type, codecs)) {
DLOG(ERROR) << "Unsupported " << type.Utf8() << ";codecs=" << codecs.Utf8();
diff --git a/chromium/content/renderer/media_recorder/media_recorder_handler.h b/chromium/content/renderer/media_recorder/media_recorder_handler.h
index 24bad947560..e17fea43df1 100644
--- a/chromium/content/renderer/media_recorder/media_recorder_handler.h
+++ b/chromium/content/renderer/media_recorder/media_recorder_handler.h
@@ -15,8 +15,8 @@
#include "content/common/content_export.h"
#include "content/renderer/media_recorder/audio_track_recorder.h"
#include "content/renderer/media_recorder/video_track_recorder.h"
-#include "third_party/WebKit/public/platform/WebMediaRecorderHandler.h"
-#include "third_party/WebKit/public/platform/WebMediaStream.h"
+#include "third_party/blink/public/platform/web_media_recorder_handler.h"
+#include "third_party/blink/public/platform/web_media_stream.h"
namespace blink {
class WebMediaRecorderHandlerClient;
diff --git a/chromium/content/renderer/media_recorder/media_recorder_handler_unittest.cc b/chromium/content/renderer/media_recorder/media_recorder_handler_unittest.cc
index cc04cf33294..7cda7426677 100644
--- a/chromium/content/renderer/media_recorder/media_recorder_handler_unittest.cc
+++ b/chromium/content/renderer/media_recorder/media_recorder_handler_unittest.cc
@@ -19,10 +19,10 @@
#include "media/base/video_frame.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebMediaRecorderHandlerClient.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
-#include "third_party/WebKit/public/web/WebHeap.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/web_media_recorder_handler_client.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/web/web_heap.h"
using ::testing::_;
using ::testing::AtLeast;
@@ -258,7 +258,7 @@ TEST_P(MediaRecorderHandlerTest, EncodeVideoFrames) {
.Times(AtLeast(1));
EXPECT_CALL(*this, WriteData(_, Gt(kEncodedSizeThreshold), _, _))
.Times(1)
- .WillOnce(RunClosure(quit_closure));
+ .WillOnce(RunClosure(std::move(quit_closure)));
OnVideoFrameForTesting(video_frame);
run_loop.Run();
@@ -275,7 +275,7 @@ TEST_P(MediaRecorderHandlerTest, EncodeVideoFrames) {
.Times(AtLeast(1));
EXPECT_CALL(*this, WriteData(_, Gt(kEncodedSizeThreshold), _, _))
.Times(1)
- .WillOnce(RunClosure(quit_closure));
+ .WillOnce(RunClosure(std::move(quit_closure)));
OnVideoFrameForTesting(video_frame);
run_loop.Run();
@@ -301,7 +301,7 @@ TEST_P(MediaRecorderHandlerTest, EncodeVideoFrames) {
.Times(AtLeast(1));
EXPECT_CALL(*this, WriteData(_, Gt(kEncodedSizeThreshold), _, _))
.Times(1)
- .WillOnce(RunClosure(quit_closure));
+ .WillOnce(RunClosure(std::move(quit_closure)));
}
OnVideoFrameForTesting(alpha_frame);
@@ -354,7 +354,7 @@ TEST_P(MediaRecorderHandlerTest, OpusEncodeAudioFrames) {
.Times(AtLeast(1));
EXPECT_CALL(*this, WriteData(_, Gt(kEncodedSizeThreshold), _, _))
.Times(1)
- .WillOnce(RunClosure(quit_closure));
+ .WillOnce(RunClosure(std::move(quit_closure)));
for (int i = 0; i < kRatioOpusToTestAudioBuffers; ++i)
OnAudioBusForTesting(*audio_bus1);
@@ -371,7 +371,7 @@ TEST_P(MediaRecorderHandlerTest, OpusEncodeAudioFrames) {
.Times(AtLeast(1));
EXPECT_CALL(*this, WriteData(_, Gt(kEncodedSizeThreshold), _, _))
.Times(1)
- .WillOnce(RunClosure(quit_closure));
+ .WillOnce(RunClosure(std::move(quit_closure)));
for (int i = 0; i < kRatioOpusToTestAudioBuffers; ++i)
OnAudioBusForTesting(*audio_bus2);
@@ -410,7 +410,7 @@ TEST_P(MediaRecorderHandlerTest, WebmMuxerErrorWhileEncoding) {
EXPECT_CALL(*this, WriteData(_, _, _, _)).Times(AtLeast(1));
EXPECT_CALL(*this, WriteData(_, Gt(kEncodedSizeThreshold), _, _))
.Times(1)
- .WillOnce(RunClosure(quit_closure));
+ .WillOnce(RunClosure(std::move(quit_closure)));
OnVideoFrameForTesting(video_frame);
run_loop.Run();
@@ -422,7 +422,9 @@ TEST_P(MediaRecorderHandlerTest, WebmMuxerErrorWhileEncoding) {
base::RunLoop run_loop;
base::Closure quit_closure = run_loop.QuitClosure();
EXPECT_CALL(*this, WriteData(_, _, _, _)).Times(0);
- EXPECT_CALL(*this, OnError(_)).Times(1).WillOnce(RunClosure(quit_closure));
+ EXPECT_CALL(*this, OnError(_))
+ .Times(1)
+ .WillOnce(RunClosure(std::move(quit_closure)));
OnVideoFrameForTesting(video_frame);
run_loop.Run();
diff --git a/chromium/content/renderer/media_recorder/video_track_recorder.cc b/chromium/content/renderer/media_recorder/video_track_recorder.cc
index a67df176853..c1d672c52d6 100644
--- a/chromium/content/renderer/media_recorder/video_track_recorder.cc
+++ b/chromium/content/renderer/media_recorder/video_track_recorder.cc
@@ -9,7 +9,6 @@
#include "base/bind.h"
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/task_runner_util.h"
#include "base/threading/thread.h"
diff --git a/chromium/content/renderer/media_recorder/video_track_recorder.h b/chromium/content/renderer/media_recorder/video_track_recorder.h
index df288c0f09c..73160800518 100644
--- a/chromium/content/renderer/media_recorder/video_track_recorder.h
+++ b/chromium/content/renderer/media_recorder/video_track_recorder.h
@@ -12,10 +12,10 @@
#include "base/memory/weak_ptr.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_checker.h"
-#include "content/public/common/features.h"
+#include "content/public/common/buildflags.h"
#include "content/public/renderer/media_stream_video_sink.h"
#include "media/muxers/webm_muxer.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
#include "third_party/skia/include/core/SkBitmap.h"
namespace base {
diff --git a/chromium/content/renderer/media_recorder/video_track_recorder_unittest.cc b/chromium/content/renderer/media_recorder/video_track_recorder_unittest.cc
index 4c868f5849a..2eecab58c8c 100644
--- a/chromium/content/renderer/media_recorder/video_track_recorder_unittest.cc
+++ b/chromium/content/renderer/media_recorder/video_track_recorder_unittest.cc
@@ -23,9 +23,9 @@
#include "media/base/video_frame.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
-#include "third_party/WebKit/public/web/WebHeap.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/web/web_heap.h"
using media::VideoFrame;
using video_track_recorder::kVEAEncoderMinResolutionWidth;
@@ -219,7 +219,7 @@ TEST_P(VideoTrackRecorderTest, VideoEncoding) {
.Times(1)
.WillOnce(DoAll(SaveArg<1>(&third_frame_encoded_data),
SaveArg<2>(&third_frame_encoded_alpha),
- RunClosure(quit_closure)));
+ RunClosure(std::move(quit_closure))));
Encode(video_frame2, base::TimeTicks::Now());
run_loop.Run();
@@ -261,7 +261,7 @@ TEST_P(VideoTrackRecorderTest, EncodeFrameWithPaddedCodedSize) {
base::Closure quit_closure = run_loop.QuitClosure();
EXPECT_CALL(*this, DoOnEncodedVideo(_, _, _, _, true))
.Times(1)
- .WillOnce(RunClosure(quit_closure));
+ .WillOnce(RunClosure(std::move(quit_closure)));
Encode(video_frame, base::TimeTicks::Now());
run_loop.Run();
@@ -298,7 +298,7 @@ TEST_F(VideoTrackRecorderTest, ForceKeyframeOnAlphaSwitch) {
EXPECT_CALL(*this, DoOnEncodedVideo(_, _, _, _, false))
.Times(1)
.WillOnce(DoAll(SaveArg<2>(&third_frame_encoded_alpha),
- RunClosure(quit_closure)));
+ RunClosure(std::move(quit_closure))));
Encode(alpha_frame, base::TimeTicks::Now());
run_loop.Run();
@@ -330,7 +330,7 @@ TEST_F(VideoTrackRecorderTest, HandlesOnError) {
base::Closure quit_closure = run_loop.QuitClosure();
EXPECT_CALL(*this, DoOnEncodedVideo(_, _, _, _, true))
.Times(1)
- .WillOnce(RunClosure(quit_closure));
+ .WillOnce(RunClosure(std::move(quit_closure)));
Encode(video_frame, base::TimeTicks::Now());
run_loop.Run();
@@ -354,7 +354,7 @@ TEST_F(VideoTrackRecorderTest, ReleasesFrame) {
base::BindOnce(set_to_true, &frame_is_destroyed));
EXPECT_CALL(*this, DoOnEncodedVideo(_, _, _, _, true))
.Times(1)
- .WillOnce(RunClosure(quit_closure));
+ .WillOnce(RunClosure(std::move(quit_closure)));
Encode(video_frame, base::TimeTicks::Now());
video_frame = nullptr;
run_loop.Run();
diff --git a/chromium/content/renderer/media_recorder/vpx_encoder.h b/chromium/content/renderer/media_recorder/vpx_encoder.h
index 4175ab814a6..68db00c4c2a 100644
--- a/chromium/content/renderer/media_recorder/vpx_encoder.h
+++ b/chromium/content/renderer/media_recorder/vpx_encoder.h
@@ -8,14 +8,8 @@
#include <vector>
#include "content/renderer/media_recorder/video_track_recorder.h"
-
-extern "C" {
-// VPX_CODEC_DISABLE_COMPAT excludes parts of the libvpx API that provide
-// backwards compatibility for legacy applications using the library.
-#define VPX_CODEC_DISABLE_COMPAT 1
#include "third_party/libvpx/source/libvpx/vpx/vp8cx.h"
#include "third_party/libvpx/source/libvpx/vpx/vpx_encoder.h"
-}
namespace content {
diff --git a/chromium/content/renderer/mojo/blink_interface_provider_impl.h b/chromium/content/renderer/mojo/blink_interface_provider_impl.h
index 529c7fc8b4e..f4b7cee1e50 100644
--- a/chromium/content/renderer/mojo/blink_interface_provider_impl.h
+++ b/chromium/content/renderer/mojo/blink_interface_provider_impl.h
@@ -9,7 +9,7 @@
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "mojo/public/cpp/system/message_pipe.h"
-#include "third_party/WebKit/public/platform/InterfaceProvider.h"
+#include "third_party/blink/public/platform/interface_provider.h"
namespace base {
class SingleThreadTaskRunner;
diff --git a/chromium/content/renderer/mojo/blink_interface_registry_impl.h b/chromium/content/renderer/mojo/blink_interface_registry_impl.h
index 82960fd499d..103ab6b4c7f 100644
--- a/chromium/content/renderer/mojo/blink_interface_registry_impl.h
+++ b/chromium/content/renderer/mojo/blink_interface_registry_impl.h
@@ -9,7 +9,7 @@
#include "base/memory/weak_ptr.h"
#include "content/common/associated_interface_registry_impl.h"
#include "services/service_manager/public/cpp/binder_registry.h"
-#include "third_party/WebKit/public/platform/InterfaceRegistry.h"
+#include "third_party/blink/public/platform/interface_registry.h"
namespace content {
diff --git a/chromium/content/renderer/mouse_lock_dispatcher.cc b/chromium/content/renderer/mouse_lock_dispatcher.cc
index c4702c52166..0749c9c9c21 100644
--- a/chromium/content/renderer/mouse_lock_dispatcher.cc
+++ b/chromium/content/renderer/mouse_lock_dispatcher.cc
@@ -5,7 +5,7 @@
#include "content/renderer/mouse_lock_dispatcher.h"
#include "base/logging.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
namespace content {
diff --git a/chromium/content/renderer/mouse_lock_dispatcher_browsertest.cc b/chromium/content/renderer/mouse_lock_dispatcher_browsertest.cc
index e2ad5ca0706..8b26b1cf0ce 100644
--- a/chromium/content/renderer/mouse_lock_dispatcher_browsertest.cc
+++ b/chromium/content/renderer/mouse_lock_dispatcher_browsertest.cc
@@ -10,7 +10,7 @@
#include "content/renderer/render_view_impl.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebMouseEvent.h"
+#include "third_party/blink/public/platform/web_mouse_event.h"
using ::testing::_;
diff --git a/chromium/content/renderer/mus/BUILD.gn b/chromium/content/renderer/mus/BUILD.gn
index 2271a155d0c..559eae55f80 100644
--- a/chromium/content/renderer/mus/BUILD.gn
+++ b/chromium/content/renderer/mus/BUILD.gn
@@ -30,7 +30,7 @@ static_library("mus") {
"//services/service_manager/public/cpp",
"//services/ui/public/cpp",
"//services/ui/public/interfaces",
- "//third_party/WebKit/public:blink",
+ "//third_party/blink/public:blink",
"//ui/events:events",
"//ui/events:events_base",
"//ui/events/blink",
diff --git a/chromium/content/renderer/mus/mus_embedded_frame.cc b/chromium/content/renderer/mus/mus_embedded_frame.cc
index f3a089235b1..f6b3d1e439f 100644
--- a/chromium/content/renderer/mus/mus_embedded_frame.cc
+++ b/chromium/content/renderer/mus/mus_embedded_frame.cc
@@ -87,7 +87,8 @@ void MusEmbeddedFrame::CreateChildWindowAndEmbed(
window_tree()->AddWindow(GetAndAdvanceNextChangeId(),
renderer_window_tree_client_->root_window_id_,
window_id_);
- window_tree()->EmbedUsingToken(window_id_, token, 0, base::Bind(&OnEmbedAck));
+ window_tree()->EmbedUsingToken(window_id_, token, 0,
+ base::BindOnce(&OnEmbedAck));
}
void MusEmbeddedFrame::OnTreeAvailable() {
diff --git a/chromium/content/renderer/mus/render_widget_window_tree_client_factory.cc b/chromium/content/renderer/mus/render_widget_window_tree_client_factory.cc
index 8915f9beae3..bda28e54de3 100644
--- a/chromium/content/renderer/mus/render_widget_window_tree_client_factory.cc
+++ b/chromium/content/renderer/mus/render_widget_window_tree_client_factory.cc
@@ -8,7 +8,6 @@
#include "base/logging.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/sequenced_task_runner.h"
diff --git a/chromium/content/renderer/mus/renderer_window_tree_client.cc b/chromium/content/renderer/mus/renderer_window_tree_client.cc
index 6e55fdf7f5f..1a9d6b6454b 100644
--- a/chromium/content/renderer/mus/renderer_window_tree_client.cc
+++ b/chromium/content/renderer/mus/renderer_window_tree_client.cc
@@ -12,6 +12,7 @@
#include "components/viz/client/client_layer_tree_frame_sink.h"
#include "components/viz/client/hit_test_data_provider.h"
#include "components/viz/client/hit_test_data_provider_draw_quad.h"
+#include "components/viz/client/hit_test_data_provider_surface_layer.h"
#include "components/viz/client/local_surface_id_provider.h"
#include "components/viz/common/features.h"
#include "content/renderer/mus/mus_embedded_frame.h"
@@ -144,6 +145,9 @@ void RendererWindowTreeClient::RequestLayerTreeFrameSinkInternal(
params.hit_test_data_provider =
std::make_unique<viz::HitTestDataProviderDrawQuad>(
true /* should_ask_for_child_region */);
+ } else if (features::IsVizHitTestingSurfaceLayerEnabled()) {
+ params.hit_test_data_provider =
+ std::make_unique<viz::HitTestDataProviderSurfaceLayer>();
}
auto frame_sink = std::make_unique<viz::ClientLayerTreeFrameSink>(
std::move(context_provider), nullptr /* worker_context_provider */,
@@ -170,6 +174,16 @@ void RendererWindowTreeClient::Embed(uint32_t frame_routing_id,
CreateMusEmbeddedFrame(render_frame_proxy, token));
}
+void RendererWindowTreeClient::OnEmbedFromToken(
+ const base::UnguessableToken& token,
+ ui::mojom::WindowDataPtr root,
+ int64_t display_id,
+ const base::Optional<viz::LocalSurfaceId>& local_surface_id) {
+ // Renderers don't use ScheduleEmbedForExistingClient(), so this path should
+ // never be hit.
+ NOTREACHED();
+}
+
void RendererWindowTreeClient::DestroyFrame(uint32_t frame_routing_id) {
pending_frames_.erase(frame_routing_id);
}
@@ -336,27 +350,26 @@ void RendererWindowTreeClient::OnWindowSurfaceChanged(
void RendererWindowTreeClient::OnDragDropStart(
const std::unordered_map<std::string, std::vector<uint8_t>>& mime_data) {}
-void RendererWindowTreeClient::OnDragEnter(
- ui::Id window_id,
- uint32_t event_flags,
- const gfx::Point& position,
- uint32_t effect_bitmask,
- const OnDragEnterCallback& callback) {}
+void RendererWindowTreeClient::OnDragEnter(ui::Id window_id,
+ uint32_t event_flags,
+ const gfx::Point& position,
+ uint32_t effect_bitmask,
+ OnDragEnterCallback callback) {}
void RendererWindowTreeClient::OnDragOver(ui::Id window_id,
uint32_t event_flags,
const gfx::Point& position,
uint32_t effect_bitmask,
- const OnDragOverCallback& callback) {}
+ OnDragOverCallback callback) {}
void RendererWindowTreeClient::OnDragLeave(ui::Id window_id) {}
-void RendererWindowTreeClient::OnCompleteDrop(
- ui::Id window_id,
- uint32_t event_flags,
- const gfx::Point& position,
- uint32_t effect_bitmask,
- const OnCompleteDropCallback& callback) {}
+void RendererWindowTreeClient::OnCompleteDrop(ui::Id window_id,
+ uint32_t event_flags,
+ const gfx::Point& position,
+ uint32_t effect_bitmask,
+ OnCompleteDropCallback callback) {
+}
void RendererWindowTreeClient::OnPerformDragDropCompleted(
uint32_t change_id,
diff --git a/chromium/content/renderer/mus/renderer_window_tree_client.h b/chromium/content/renderer/mus/renderer_window_tree_client.h
index b0d7f539c44..b85fd04ae74 100644
--- a/chromium/content/renderer/mus/renderer_window_tree_client.h
+++ b/chromium/content/renderer/mus/renderer_window_tree_client.h
@@ -117,6 +117,11 @@ class RendererWindowTreeClient : public ui::mojom::WindowTreeClient,
ui::Id focused_window_id,
bool drawn,
const base::Optional<viz::LocalSurfaceId>& local_surface_id) override;
+ void OnEmbedFromToken(
+ const base::UnguessableToken& token,
+ ui::mojom::WindowDataPtr root,
+ int64_t display_id,
+ const base::Optional<viz::LocalSurfaceId>& local_surface_id) override;
void OnEmbeddedAppDisconnected(ui::Id window_id) override;
void OnUnembed(ui::Id window_id) override;
void OnCaptureChanged(ui::Id new_capture_window_id,
@@ -185,18 +190,18 @@ class RendererWindowTreeClient : public ui::mojom::WindowTreeClient,
uint32_t event_flags,
const gfx::Point& position,
uint32_t effect_bitmask,
- const OnDragEnterCallback& callback) override;
+ OnDragEnterCallback callback) override;
void OnDragOver(ui::Id window_id,
uint32_t event_flags,
const gfx::Point& position,
uint32_t effect_bitmask,
- const OnDragOverCallback& callback) override;
+ OnDragOverCallback callback) override;
void OnDragLeave(ui::Id window_id) override;
void OnCompleteDrop(ui::Id window_id,
uint32_t event_flags,
const gfx::Point& position,
uint32_t effect_bitmask,
- const OnCompleteDropCallback& callback) override;
+ OnCompleteDropCallback callback) override;
void OnPerformDragDropCompleted(uint32_t change_id,
bool success,
uint32_t action_taken) override;
diff --git a/chromium/content/renderer/net_info_helper.h b/chromium/content/renderer/net_info_helper.h
index cc876cae138..dfc6d10e3fa 100644
--- a/chromium/content/renderer/net_info_helper.h
+++ b/chromium/content/renderer/net_info_helper.h
@@ -6,7 +6,7 @@
#define CONTENT_RENDERER_NET_INFO_HELPER_H_
#include "net/base/network_change_notifier.h"
-#include "third_party/WebKit/public/platform/WebConnectionType.h"
+#include "third_party/blink/public/platform/web_connection_type.h"
namespace content {
diff --git a/chromium/content/renderer/notifications/notification_data_conversions.cc b/chromium/content/renderer/notifications/notification_data_conversions.cc
index 6f611563fc3..638a5e550ec 100644
--- a/chromium/content/renderer/notifications/notification_data_conversions.cc
+++ b/chromium/content/renderer/notifications/notification_data_conversions.cc
@@ -8,11 +8,11 @@
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
-#include "third_party/WebKit/public/platform/URLConversion.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
-#include "third_party/WebKit/public/platform/WebVector.h"
-#include "third_party/WebKit/public/platform/modules/notifications/WebNotificationAction.h"
+#include "third_party/blink/public/platform/modules/notifications/web_notification_action.h"
+#include "third_party/blink/public/platform/url_conversion.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_url.h"
+#include "third_party/blink/public/platform/web_vector.h"
using blink::WebNotificationData;
using blink::WebString;
diff --git a/chromium/content/renderer/notifications/notification_data_conversions.h b/chromium/content/renderer/notifications/notification_data_conversions.h
index 7adc1df192e..1d7c7a13346 100644
--- a/chromium/content/renderer/notifications/notification_data_conversions.h
+++ b/chromium/content/renderer/notifications/notification_data_conversions.h
@@ -7,7 +7,7 @@
#include "content/common/content_export.h"
#include "content/public/common/platform_notification_data.h"
-#include "third_party/WebKit/public/platform/modules/notifications/WebNotificationData.h"
+#include "third_party/blink/public/platform/modules/notifications/web_notification_data.h"
namespace content {
diff --git a/chromium/content/renderer/notifications/notification_data_conversions_unittest.cc b/chromium/content/renderer/notifications/notification_data_conversions_unittest.cc
index 2edc32e5204..7d5eb0cece1 100644
--- a/chromium/content/renderer/notifications/notification_data_conversions_unittest.cc
+++ b/chromium/content/renderer/notifications/notification_data_conversions_unittest.cc
@@ -12,9 +12,9 @@
#include "content/public/common/platform_notification_data.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
-#include "third_party/WebKit/public/platform/modules/notifications/WebNotificationData.h"
+#include "third_party/blink/public/platform/modules/notifications/web_notification_data.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_url.h"
namespace content {
diff --git a/chromium/content/renderer/notifications/notification_dispatcher.cc b/chromium/content/renderer/notifications/notification_dispatcher.cc
index 46b700fcee2..9508f95e778 100644
--- a/chromium/content/renderer/notifications/notification_dispatcher.cc
+++ b/chromium/content/renderer/notifications/notification_dispatcher.cc
@@ -11,8 +11,10 @@
namespace content {
NotificationDispatcher::NotificationDispatcher(
- ThreadSafeSender* thread_safe_sender)
- : WorkerThreadMessageFilter(thread_safe_sender) {}
+ ThreadSafeSender* thread_safe_sender,
+ scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner)
+ : WorkerThreadMessageFilter(thread_safe_sender,
+ std::move(main_thread_task_runner)) {}
NotificationDispatcher::~NotificationDispatcher() {}
diff --git a/chromium/content/renderer/notifications/notification_dispatcher.h b/chromium/content/renderer/notifications/notification_dispatcher.h
index dac26a1b418..15cdc4a03ee 100644
--- a/chromium/content/renderer/notifications/notification_dispatcher.h
+++ b/chromium/content/renderer/notifications/notification_dispatcher.h
@@ -15,7 +15,9 @@ namespace content {
class NotificationDispatcher : public WorkerThreadMessageFilter {
public:
- explicit NotificationDispatcher(ThreadSafeSender* thread_safe_sender);
+ NotificationDispatcher(
+ ThreadSafeSender* thread_safe_sender,
+ scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner);
// Generates and stores a new process-unique notification request ID mapped to
// |thread_id|, and returns the generated request ID. This method can be
diff --git a/chromium/content/renderer/notifications/notification_manager.cc b/chromium/content/renderer/notifications/notification_manager.cc
index 88e5373bf3d..44b927cc2d6 100644
--- a/chromium/content/renderer/notifications/notification_manager.cc
+++ b/chromium/content/renderer/notifications/notification_manager.cc
@@ -16,8 +16,8 @@
#include "content/renderer/notifications/notification_data_conversions.h"
#include "content/renderer/notifications/notification_dispatcher.h"
#include "content/renderer/service_worker/web_service_worker_registration_impl.h"
-#include "third_party/WebKit/public/platform/URLConversion.h"
-#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
+#include "third_party/blink/public/platform/url_conversion.h"
+#include "third_party/blink/public/platform/web_security_origin.h"
#include "url/origin.h"
using blink::WebString;
diff --git a/chromium/content/renderer/notifications/notification_manager.h b/chromium/content/renderer/notifications/notification_manager.h
index af5167ec8ab..72190e3fe3d 100644
--- a/chromium/content/renderer/notifications/notification_manager.h
+++ b/chromium/content/renderer/notifications/notification_manager.h
@@ -18,7 +18,7 @@
#include "content/common/platform_notification_messages.h"
#include "content/public/renderer/worker_thread.h"
#include "content/renderer/notifications/notification_dispatcher.h"
-#include "third_party/WebKit/public/platform/modules/notifications/WebNotificationManager.h"
+#include "third_party/blink/public/platform/modules/notifications/web_notification_manager.h"
namespace content {
diff --git a/chromium/content/renderer/origin_trials/web_trial_token_validator_impl.cc b/chromium/content/renderer/origin_trials/web_trial_token_validator_impl.cc
index 15e658885e6..b17913fde02 100644
--- a/chromium/content/renderer/origin_trials/web_trial_token_validator_impl.cc
+++ b/chromium/content/renderer/origin_trials/web_trial_token_validator_impl.cc
@@ -5,8 +5,8 @@
#include "content/renderer/origin_trials/web_trial_token_validator_impl.h"
#include "base/time/time.h"
-#include "third_party/WebKit/public/common/origin_trials/trial_token.h"
-#include "third_party/WebKit/public/common/origin_trials/trial_token_validator.h"
+#include "third_party/blink/public/common/origin_trials/trial_token.h"
+#include "third_party/blink/public/common/origin_trials/trial_token_validator.h"
namespace content {
diff --git a/chromium/content/renderer/origin_trials/web_trial_token_validator_impl.h b/chromium/content/renderer/origin_trials/web_trial_token_validator_impl.h
index 69f74d6b37e..4f33737f845 100644
--- a/chromium/content/renderer/origin_trials/web_trial_token_validator_impl.h
+++ b/chromium/content/renderer/origin_trials/web_trial_token_validator_impl.h
@@ -10,7 +10,7 @@
#include "base/compiler_specific.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebTrialTokenValidator.h"
+#include "third_party/blink/public/platform/web_trial_token_validator.h"
namespace blink {
class TrialTokenValidator;
diff --git a/chromium/content/renderer/p2p/ipc_network_manager.cc b/chromium/content/renderer/p2p/ipc_network_manager.cc
index 30a15e84c5c..430f61d6610 100644
--- a/chromium/content/renderer/p2p/ipc_network_manager.cc
+++ b/chromium/content/renderer/p2p/ipc_network_manager.cc
@@ -100,9 +100,15 @@ void IpcNetworkManager::OnNetworkListChanged(
DCHECK(!ip_address.IsNil());
rtc::IPAddress prefix = rtc::TruncateIP(ip_address, it->prefix_length);
- std::unique_ptr<rtc::Network> network(
- new rtc::Network(it->name, it->name, prefix, it->prefix_length,
- ConvertConnectionTypeToAdapterType(it->type)));
+ rtc::AdapterType adapter_type =
+ ConvertConnectionTypeToAdapterType(it->type);
+ // If the adapter type is unknown, try to guess it using WebRTC's string
+ // matching rules.
+ if (adapter_type == rtc::ADAPTER_TYPE_UNKNOWN) {
+ adapter_type = rtc::GetAdapterTypeFromName(it->name.c_str());
+ }
+ std::unique_ptr<rtc::Network> network(new rtc::Network(
+ it->name, it->name, prefix, it->prefix_length, adapter_type));
network->set_default_local_address_provider(this);
rtc::InterfaceAddress iface_addr;
diff --git a/chromium/content/renderer/p2p/ipc_network_manager_unittest.cc b/chromium/content/renderer/p2p/ipc_network_manager_unittest.cc
index a7071718944..06bb29c9bfe 100644
--- a/chromium/content/renderer/p2p/ipc_network_manager_unittest.cc
+++ b/chromium/content/renderer/p2p/ipc_network_manager_unittest.cc
@@ -104,9 +104,11 @@ TEST_F(IpcNetworkManagerTest, TestMergeNetworkList) {
// IPs should be in the same order as the list passed into
// OnNetworkListChanged.
EXPECT_TRUE(rtc::IPFromString(kIPv6PublicAddrString1, &ip_address));
- EXPECT_EQ((*network_with_two_ips)->GetIPs()[0], ip_address);
+ EXPECT_EQ((*network_with_two_ips)->GetIPs()[0],
+ rtc::InterfaceAddress(ip_address));
EXPECT_TRUE(rtc::IPFromString(kIPv6PublicAddrString2, &ip_address));
- EXPECT_EQ((*network_with_two_ips)->GetIPs()[1], ip_address);
+ EXPECT_EQ((*network_with_two_ips)->GetIPs()[1],
+ rtc::InterfaceAddress(ip_address));
// Verify the network with prefix length of 48 has 1 IP address.
auto network_with_one_ip = std::find_if(
networks.begin(), networks.end(),
@@ -114,7 +116,47 @@ TEST_F(IpcNetworkManagerTest, TestMergeNetworkList) {
ASSERT_NE(networks.end(), network_with_one_ip);
EXPECT_EQ(1uL, (*network_with_one_ip)->GetIPs().size());
EXPECT_TRUE(rtc::IPFromString(kIPv6PublicAddrString2, &ip_address));
- EXPECT_EQ((*network_with_one_ip)->GetIPs()[0], ip_address);
+ EXPECT_EQ((*network_with_one_ip)->GetIPs()[0],
+ rtc::InterfaceAddress(ip_address));
+}
+
+// Test that IpcNetworkManager will guess a network type from the interface
+// name when not otherwise available.
+TEST_F(IpcNetworkManagerTest, DeterminesNetworkTypeFromNameIfUnknown) {
+ net::NetworkInterfaceList list;
+ net::IPAddress ip;
+ std::vector<rtc::Network*> networks;
+ rtc::IPAddress ip_address;
+
+ // Add a "tun1" entry of type "unknown" and "tun2" entry of type Wi-Fi. The
+ // "tun1" entry (and only it) should have its type determined from its name,
+ // since its type is unknown.
+ EXPECT_TRUE(ip.AssignFromIPLiteral(kIPv6PublicAddrString1));
+ list.push_back(net::NetworkInterface(
+ "tun1", "tun1", 0, net::NetworkChangeNotifier::CONNECTION_UNKNOWN, ip, 64,
+ net::IP_ADDRESS_ATTRIBUTE_NONE));
+
+ EXPECT_TRUE(ip.AssignFromIPLiteral(kIPv6PublicAddrString2));
+ list.push_back(net::NetworkInterface(
+ "tun2", "tun2", 0, net::NetworkChangeNotifier::CONNECTION_WIFI, ip, 64,
+ net::IP_ADDRESS_ATTRIBUTE_NONE));
+
+ network_manager_->OnNetworkListChanged(list, net::IPAddress(),
+ net::IPAddress());
+ network_manager_->GetNetworks(&networks);
+ EXPECT_EQ(2uL, networks.size());
+
+ auto tun1 = std::find_if(
+ networks.begin(), networks.end(),
+ [](rtc::Network* network) { return network->name() == "tun1"; });
+ ASSERT_NE(networks.end(), tun1);
+ auto tun2 = std::find_if(
+ networks.begin(), networks.end(),
+ [](rtc::Network* network) { return network->name() == "tun2"; });
+ ASSERT_NE(networks.end(), tun1);
+
+ EXPECT_EQ(rtc::ADAPTER_TYPE_VPN, (*tun1)->type());
+ EXPECT_EQ(rtc::ADAPTER_TYPE_WIFI, (*tun2)->type());
}
} // namespace content
diff --git a/chromium/content/renderer/pepper/OWNERS b/chromium/content/renderer/pepper/OWNERS
index 6532e804d57..a032c224176 100644
--- a/chromium/content/renderer/pepper/OWNERS
+++ b/chromium/content/renderer/pepper/OWNERS
@@ -7,7 +7,6 @@ per-file usb_key_code_*=wez@chromium.org
# WebSocket
per-file *websocket*=ricea@chromium.org
-per-file *websocket*=tyoshino@chromium.org
per-file *websocket*=yhirano@chromium.org
# COMPONENT: Internals>Plugins>Pepper
diff --git a/chromium/content/renderer/pepper/content_decryptor_delegate.cc b/chromium/content/renderer/pepper/content_decryptor_delegate.cc
deleted file mode 100644
index ff461e108eb..00000000000
--- a/chromium/content/renderer/pepper/content_decryptor_delegate.cc
+++ /dev/null
@@ -1,1318 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "content/renderer/pepper/content_decryptor_delegate.h"
-
-#include <string.h>
-#include <utility>
-#include <vector>
-
-#include "base/callback_helpers.h"
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/metrics/histogram_functions.h"
-#include "base/numerics/safe_conversions.h"
-#include "base/trace_event/trace_event.h"
-#include "content/renderer/pepper/ppb_buffer_impl.h"
-#include "media/base/audio_decoder_config.h"
-#include "media/base/bind_to_current_loop.h"
-#include "media/base/cdm_key_information.h"
-#include "media/base/channel_layout.h"
-#include "media/base/data_buffer.h"
-#include "media/base/decoder_buffer.h"
-#include "media/base/decrypt_config.h"
-#include "media/base/key_systems.h"
-#include "media/base/limits.h"
-#include "media/base/video_decoder_config.h"
-#include "media/base/video_frame.h"
-#include "media/base/video_util.h"
-#include "ppapi/shared_impl/array_var.h"
-#include "ppapi/shared_impl/scoped_pp_resource.h"
-#include "ppapi/shared_impl/time_conversion.h"
-#include "ppapi/shared_impl/var.h"
-#include "ppapi/shared_impl/var_tracker.h"
-#include "ppapi/thunk/enter.h"
-#include "ppapi/thunk/ppb_buffer_api.h"
-#include "ui/gfx/geometry/rect.h"
-
-using media::CdmMessageType;
-using media::CdmPromise;
-using media::CdmSessionType;
-using media::ContentDecryptionModule;
-using media::Decryptor;
-using media::NewSessionCdmPromise;
-using media::SimpleCdmPromise;
-using ppapi::ArrayBufferVar;
-using ppapi::ArrayVar;
-using ppapi::PpapiGlobals;
-using ppapi::ScopedPPResource;
-using ppapi::StringVar;
-using ppapi::thunk::EnterResourceNoLock;
-using ppapi::thunk::PPB_Buffer_API;
-
-namespace content {
-
-namespace {
-
-// Fills |resource| with a PPB_Buffer_Impl and copies |data| into the buffer
-// resource. The |*resource|, if valid, will be in the ResourceTracker with a
-// reference-count of 0. If |data| is NULL, sets |*resource| to NULL. Returns
-// true upon success and false if any error happened.
-bool MakeBufferResource(PP_Instance instance,
- const std::vector<uint8_t>& data,
- scoped_refptr<PPB_Buffer_Impl>* resource) {
- TRACE_EVENT0("media", "ContentDecryptorDelegate - MakeBufferResource");
- DCHECK(resource);
-
- if (data.empty()) {
- resource = nullptr;
- return true;
- }
-
- scoped_refptr<PPB_Buffer_Impl> buffer(
- PPB_Buffer_Impl::CreateResource(instance, data.size()));
- if (!buffer.get())
- return false;
-
- BufferAutoMapper mapper(buffer.get());
- if (!mapper.data() || mapper.size() < data.size())
- return false;
- memcpy(mapper.data(), &data[0], data.size());
-
- *resource = buffer;
- return true;
-}
-
-// Copies the content of |str| into |array|.
-// Returns true if copy succeeded. Returns false if copy failed, e.g. if the
-// |array_size| is smaller than the |str| length.
-template <uint32_t array_size>
-bool CopyStringToArray(const std::string& str, uint8_t(&array)[array_size]) {
- if (array_size < str.size())
- return false;
-
- memcpy(array, str.data(), str.size());
- return true;
-}
-
-// Fills the |block_info| with information from |buffer|.
-//
-// Returns true if |block_info| is successfully filled. Returns false
-// otherwise.
-bool MakeEncryptedBlockInfo(const scoped_refptr<media::DecoderBuffer>& buffer,
- uint32_t request_id,
- PP_EncryptedBlockInfo* block_info) {
- // TODO(xhwang): Fix initialization of PP_EncryptedBlockInfo here and
- // anywhere else.
- memset(block_info, 0, sizeof(*block_info));
- block_info->tracking_info.request_id = request_id;
-
- // EOS buffers need a request ID and nothing more.
- if (buffer->end_of_stream())
- return true;
-
- DCHECK(buffer->data_size()) << "DecryptConfig is set on an empty buffer";
-
- block_info->tracking_info.timestamp = buffer->timestamp().InMicroseconds();
- block_info->data_size = buffer->data_size();
-
- const media::DecryptConfig* decrypt_config = buffer->decrypt_config();
- // There's no need to fill encryption related fields for unencrypted buffer.
- if (!decrypt_config)
- return true;
-
- if (!CopyStringToArray(decrypt_config->key_id(), block_info->key_id) ||
- !CopyStringToArray(decrypt_config->iv(), block_info->iv))
- return false;
-
- block_info->key_id_size = decrypt_config->key_id().size();
- block_info->iv_size = decrypt_config->iv().size();
-
- if (decrypt_config->subsamples().size() > arraysize(block_info->subsamples))
- return false;
-
- block_info->num_subsamples = decrypt_config->subsamples().size();
- for (uint32_t i = 0; i < block_info->num_subsamples; ++i) {
- block_info->subsamples[i].clear_bytes =
- decrypt_config->subsamples()[i].clear_bytes;
- block_info->subsamples[i].cipher_bytes =
- decrypt_config->subsamples()[i].cypher_bytes;
- }
-
- return true;
-}
-
-PP_HdcpVersion MediaHdcpVersionToPpHdcpVersion(
- media::HdcpVersion hdcp_version) {
- switch (hdcp_version) {
- case media::HdcpVersion::kHdcpVersionNone:
- return PP_HDCPVERSION_NONE;
- case media::HdcpVersion::kHdcpVersion1_0:
- return PP_HDCPVERSION_1_0;
- case media::HdcpVersion::kHdcpVersion1_1:
- return PP_HDCPVERSION_1_1;
- case media::HdcpVersion::kHdcpVersion1_2:
- return PP_HDCPVERSION_1_2;
- case media::HdcpVersion::kHdcpVersion1_3:
- return PP_HDCPVERSION_1_3;
- case media::HdcpVersion::kHdcpVersion1_4:
- return PP_HDCPVERSION_1_4;
- case media::HdcpVersion::kHdcpVersion2_0:
- return PP_HDCPVERSION_2_0;
- case media::HdcpVersion::kHdcpVersion2_1:
- return PP_HDCPVERSION_2_1;
- case media::HdcpVersion::kHdcpVersion2_2:
- return PP_HDCPVERSION_2_2;
- }
-
- NOTREACHED();
- return PP_HDCPVERSION_2_2;
-}
-
-PP_AudioCodec MediaAudioCodecToPpAudioCodec(media::AudioCodec codec) {
- switch (codec) {
- case media::kCodecVorbis:
- return PP_AUDIOCODEC_VORBIS;
- case media::kCodecAAC:
- return PP_AUDIOCODEC_AAC;
- default:
- return PP_AUDIOCODEC_UNKNOWN;
- }
-}
-
-PP_VideoCodec MediaVideoCodecToPpVideoCodec(media::VideoCodec codec) {
- switch (codec) {
- case media::kCodecVP8:
- return PP_VIDEOCODEC_VP8;
- case media::kCodecH264:
- return PP_VIDEOCODEC_H264;
- case media::kCodecVP9:
- return PP_VIDEOCODEC_VP9;
- default:
- return PP_VIDEOCODEC_UNKNOWN;
- }
-}
-
-PP_VideoCodecProfile MediaVideoCodecProfileToPpVideoCodecProfile(
- media::VideoCodecProfile profile) {
- switch (profile) {
- case media::VP8PROFILE_ANY:
- case media::VP9PROFILE_PROFILE0:
- case media::VP9PROFILE_PROFILE1:
- case media::VP9PROFILE_PROFILE2:
- case media::VP9PROFILE_PROFILE3:
- return PP_VIDEOCODECPROFILE_NOT_NEEDED;
- case media::H264PROFILE_BASELINE:
- return PP_VIDEOCODECPROFILE_H264_BASELINE;
- case media::H264PROFILE_MAIN:
- return PP_VIDEOCODECPROFILE_H264_MAIN;
- case media::H264PROFILE_EXTENDED:
- return PP_VIDEOCODECPROFILE_H264_EXTENDED;
- case media::H264PROFILE_HIGH:
- return PP_VIDEOCODECPROFILE_H264_HIGH;
- case media::H264PROFILE_HIGH10PROFILE:
- return PP_VIDEOCODECPROFILE_H264_HIGH_10;
- case media::H264PROFILE_HIGH422PROFILE:
- return PP_VIDEOCODECPROFILE_H264_HIGH_422;
- case media::H264PROFILE_HIGH444PREDICTIVEPROFILE:
- return PP_VIDEOCODECPROFILE_H264_HIGH_444_PREDICTIVE;
- default:
- return PP_VIDEOCODECPROFILE_UNKNOWN;
- }
-}
-
-PP_DecryptedFrameFormat MediaVideoFormatToPpDecryptedFrameFormat(
- media::VideoPixelFormat format) {
- switch (format) {
- case media::PIXEL_FORMAT_YV12:
- return PP_DECRYPTEDFRAMEFORMAT_YV12;
- case media::PIXEL_FORMAT_I420:
- return PP_DECRYPTEDFRAMEFORMAT_I420;
- default:
- return PP_DECRYPTEDFRAMEFORMAT_UNKNOWN;
- }
-}
-
-media::VideoPixelFormat PpDecryptedFrameFormatToMediaVideoFormat(
- PP_DecryptedFrameFormat format) {
- switch (format) {
- case PP_DECRYPTEDFRAMEFORMAT_YV12:
- return media::PIXEL_FORMAT_YV12;
- case PP_DECRYPTEDFRAMEFORMAT_I420:
- return media::PIXEL_FORMAT_I420;
- default:
- NOTREACHED() << "Unknown decrypted frame format: " << format;
- return media::PIXEL_FORMAT_UNKNOWN;
- }
-}
-
-Decryptor::Status PpDecryptResultToMediaDecryptorStatus(
- PP_DecryptResult result) {
- switch (result) {
- case PP_DECRYPTRESULT_SUCCESS:
- return Decryptor::kSuccess;
- case PP_DECRYPTRESULT_DECRYPT_NOKEY:
- return Decryptor::kNoKey;
- case PP_DECRYPTRESULT_NEEDMOREDATA:
- return Decryptor::kNeedMoreData;
- case PP_DECRYPTRESULT_DECRYPT_ERROR:
- return Decryptor::kError;
- case PP_DECRYPTRESULT_DECODE_ERROR:
- return Decryptor::kError;
- default:
- NOTREACHED();
- return Decryptor::kError;
- }
-}
-
-PP_DecryptorStreamType MediaDecryptorStreamTypeToPpStreamType(
- Decryptor::StreamType stream_type) {
- switch (stream_type) {
- case Decryptor::kAudio:
- return PP_DECRYPTORSTREAMTYPE_AUDIO;
- case Decryptor::kVideo:
- return PP_DECRYPTORSTREAMTYPE_VIDEO;
- default:
- NOTREACHED();
- return PP_DECRYPTORSTREAMTYPE_VIDEO;
- }
-}
-
-media::SampleFormat PpDecryptedSampleFormatToMediaSampleFormat(
- PP_DecryptedSampleFormat result) {
- switch (result) {
- case PP_DECRYPTEDSAMPLEFORMAT_U8:
- return media::kSampleFormatU8;
- case PP_DECRYPTEDSAMPLEFORMAT_S16:
- return media::kSampleFormatS16;
- case PP_DECRYPTEDSAMPLEFORMAT_S32:
- return media::kSampleFormatS32;
- case PP_DECRYPTEDSAMPLEFORMAT_F32:
- return media::kSampleFormatF32;
- case PP_DECRYPTEDSAMPLEFORMAT_PLANAR_S16:
- return media::kSampleFormatPlanarS16;
- case PP_DECRYPTEDSAMPLEFORMAT_PLANAR_F32:
- return media::kSampleFormatPlanarF32;
- default:
- NOTREACHED();
- return media::kUnknownSampleFormat;
- }
-}
-
-PP_SessionType MediaSessionTypeToPpSessionType(CdmSessionType session_type) {
- switch (session_type) {
- case CdmSessionType::TEMPORARY_SESSION:
- return PP_SESSIONTYPE_TEMPORARY;
- case CdmSessionType::PERSISTENT_LICENSE_SESSION:
- return PP_SESSIONTYPE_PERSISTENT_LICENSE;
- case CdmSessionType::PERSISTENT_RELEASE_MESSAGE_SESSION:
- return PP_SESSIONTYPE_PERSISTENT_RELEASE;
- default:
- NOTREACHED();
- return PP_SESSIONTYPE_TEMPORARY;
- }
-}
-
-PP_InitDataType MediaInitDataTypeToPpInitDataType(
- media::EmeInitDataType init_data_type) {
- switch (init_data_type) {
- case media::EmeInitDataType::CENC:
- return PP_INITDATATYPE_CENC;
- case media::EmeInitDataType::KEYIDS:
- return PP_INITDATATYPE_KEYIDS;
- case media::EmeInitDataType::WEBM:
- return PP_INITDATATYPE_WEBM;
- case media::EmeInitDataType::UNKNOWN:
- break;
- }
- NOTREACHED();
- return PP_INITDATATYPE_KEYIDS;
-}
-
-CdmPromise::Exception PpExceptionTypeToCdmPromiseException(
- PP_CdmExceptionCode exception_code) {
- switch (exception_code) {
- case PP_CDMEXCEPTIONCODE_NOTSUPPORTEDERROR:
- return CdmPromise::Exception::NOT_SUPPORTED_ERROR;
- case PP_CDMEXCEPTIONCODE_INVALIDSTATEERROR:
- return CdmPromise::Exception::INVALID_STATE_ERROR;
- case PP_CDMEXCEPTIONCODE_TYPEERROR:
- return CdmPromise::Exception::TYPE_ERROR;
- case PP_CDMEXCEPTIONCODE_QUOTAEXCEEDEDERROR:
- return CdmPromise::Exception::QUOTA_EXCEEDED_ERROR;
- default:
- NOTREACHED();
- return CdmPromise::Exception::NOT_SUPPORTED_ERROR;
- }
-}
-
-media::CdmKeyInformation::KeyStatus PpCdmKeyStatusToCdmKeyInformationKeyStatus(
- PP_CdmKeyStatus status) {
- switch (status) {
- case PP_CDMKEYSTATUS_USABLE:
- return media::CdmKeyInformation::USABLE;
- case PP_CDMKEYSTATUS_INVALID:
- return media::CdmKeyInformation::INTERNAL_ERROR;
- case PP_CDMKEYSTATUS_EXPIRED:
- return media::CdmKeyInformation::EXPIRED;
- case PP_CDMKEYSTATUS_OUTPUTRESTRICTED:
- return media::CdmKeyInformation::OUTPUT_RESTRICTED;
- case PP_CDMKEYSTATUS_OUTPUTDOWNSCALED:
- return media::CdmKeyInformation::OUTPUT_DOWNSCALED;
- case PP_CDMKEYSTATUS_STATUSPENDING:
- return media::CdmKeyInformation::KEY_STATUS_PENDING;
- case PP_CDMKEYSTATUS_RELEASED:
- return media::CdmKeyInformation::RELEASED;
- default:
- NOTREACHED();
- return media::CdmKeyInformation::INTERNAL_ERROR;
- }
-}
-
-CdmMessageType PpCdmMessageTypeToMediaMessageType(
- PP_CdmMessageType message_type) {
- switch (message_type) {
- case PP_CDMMESSAGETYPE_LICENSE_REQUEST:
- return CdmMessageType::LICENSE_REQUEST;
- case PP_CDMMESSAGETYPE_LICENSE_RENEWAL:
- return CdmMessageType::LICENSE_RENEWAL;
- case PP_CDMMESSAGETYPE_LICENSE_RELEASE:
- return CdmMessageType::LICENSE_RELEASE;
- default:
- NOTREACHED();
- return CdmMessageType::LICENSE_REQUEST;
- }
-}
-
-void ReportSystemCodeUMA(const std::string& key_system, uint32_t system_code) {
- base::UmaHistogramSparse(
- "Media.EME." + media::GetKeySystemNameForUMA(key_system) + ".SystemCode",
- system_code);
-}
-
-} // namespace
-
-ContentDecryptorDelegate::ContentDecryptorDelegate(
- PP_Instance pp_instance,
- const PPP_ContentDecryptor_Private* plugin_decryption_interface)
- : pp_instance_(pp_instance),
- plugin_decryption_interface_(plugin_decryption_interface),
- next_decryption_request_id_(1),
- audio_samples_per_second_(0),
- audio_channel_count_(0),
- audio_channel_layout_(media::CHANNEL_LAYOUT_NONE),
- pool_(new media::AudioBufferMemoryPool()),
- weak_ptr_factory_(this) {
- weak_this_ = weak_ptr_factory_.GetWeakPtr();
-}
-
-ContentDecryptorDelegate::~ContentDecryptorDelegate() {
- SatisfyAllPendingCallbacksOnError();
-}
-
-void ContentDecryptorDelegate::Initialize(
- const std::string& key_system,
- bool allow_distinctive_identifier,
- bool allow_persistent_state,
- const media::SessionMessageCB& session_message_cb,
- const media::SessionClosedCB& session_closed_cb,
- const media::SessionKeysChangeCB& session_keys_change_cb,
- const media::SessionExpirationUpdateCB& session_expiration_update_cb,
- const base::Closure& fatal_plugin_error_cb,
- std::unique_ptr<media::SimpleCdmPromise> promise) {
- DCHECK(!key_system.empty());
- DCHECK(key_system_.empty());
- key_system_ = key_system;
-
- session_message_cb_ = session_message_cb;
- session_closed_cb_ = session_closed_cb;
- session_keys_change_cb_ = session_keys_change_cb;
- session_expiration_update_cb_ = session_expiration_update_cb;
- fatal_plugin_error_cb_ = fatal_plugin_error_cb;
-
- uint32_t promise_id = cdm_promise_adapter_.SavePromise(std::move(promise));
- plugin_decryption_interface_->Initialize(
- pp_instance_, promise_id, StringVar::StringToPPVar(key_system_),
- PP_FromBool(allow_distinctive_identifier),
- PP_FromBool(allow_persistent_state));
-}
-
-void ContentDecryptorDelegate::InstanceCrashed() {
- fatal_plugin_error_cb_.Run();
- SatisfyAllPendingCallbacksOnError();
-}
-
-void ContentDecryptorDelegate::SetServerCertificate(
- const std::vector<uint8_t>& certificate,
- std::unique_ptr<media::SimpleCdmPromise> promise) {
- if (certificate.size() < media::limits::kMinCertificateLength ||
- certificate.size() > media::limits::kMaxCertificateLength) {
- promise->reject(CdmPromise::Exception::TYPE_ERROR, 0,
- "Incorrect certificate.");
- return;
- }
-
- uint32_t promise_id = cdm_promise_adapter_.SavePromise(std::move(promise));
- PP_Var certificate_array =
- PpapiGlobals::Get()->GetVarTracker()->MakeArrayBufferPPVar(
- base::checked_cast<uint32_t>(certificate.size()), certificate.data());
- plugin_decryption_interface_->SetServerCertificate(
- pp_instance_, promise_id, certificate_array);
-}
-
-void ContentDecryptorDelegate::GetStatusForPolicy(
- media::HdcpVersion min_hdcp_version,
- std::unique_ptr<media::KeyStatusCdmPromise> promise) {
- uint32_t promise_id = cdm_promise_adapter_.SavePromise(std::move(promise));
- plugin_decryption_interface_->GetStatusForPolicy(
- pp_instance_, promise_id,
- MediaHdcpVersionToPpHdcpVersion(min_hdcp_version));
-}
-
-void ContentDecryptorDelegate::CreateSessionAndGenerateRequest(
- CdmSessionType session_type,
- media::EmeInitDataType init_data_type,
- const std::vector<uint8_t>& init_data,
- std::unique_ptr<NewSessionCdmPromise> promise) {
- uint32_t promise_id = cdm_promise_adapter_.SavePromise(std::move(promise));
- PP_Var init_data_array =
- PpapiGlobals::Get()->GetVarTracker()->MakeArrayBufferPPVar(
- base::checked_cast<uint32_t>(init_data.size()), init_data.data());
- plugin_decryption_interface_->CreateSessionAndGenerateRequest(
- pp_instance_, promise_id, MediaSessionTypeToPpSessionType(session_type),
- MediaInitDataTypeToPpInitDataType(init_data_type), init_data_array);
-}
-
-void ContentDecryptorDelegate::LoadSession(
- CdmSessionType session_type,
- const std::string& session_id,
- std::unique_ptr<NewSessionCdmPromise> promise) {
- uint32_t promise_id = cdm_promise_adapter_.SavePromise(std::move(promise));
- plugin_decryption_interface_->LoadSession(
- pp_instance_, promise_id, MediaSessionTypeToPpSessionType(session_type),
- StringVar::StringToPPVar(session_id));
-}
-
-void ContentDecryptorDelegate::UpdateSession(
- const std::string& session_id,
- const std::vector<uint8_t>& response,
- std::unique_ptr<SimpleCdmPromise> promise) {
- uint32_t promise_id = cdm_promise_adapter_.SavePromise(std::move(promise));
- PP_Var response_array =
- PpapiGlobals::Get()->GetVarTracker()->MakeArrayBufferPPVar(
- base::checked_cast<uint32_t>(response.size()), response.data());
- plugin_decryption_interface_->UpdateSession(
- pp_instance_, promise_id, StringVar::StringToPPVar(session_id),
- response_array);
-}
-
-void ContentDecryptorDelegate::CloseSession(
- const std::string& session_id,
- std::unique_ptr<SimpleCdmPromise> promise) {
- if (session_id.length() > media::limits::kMaxSessionIdLength) {
- promise->reject(CdmPromise::Exception::TYPE_ERROR, 0, "Incorrect session.");
- return;
- }
-
- uint32_t promise_id = cdm_promise_adapter_.SavePromise(std::move(promise));
- plugin_decryption_interface_->CloseSession(
- pp_instance_, promise_id, StringVar::StringToPPVar(session_id));
-}
-
-void ContentDecryptorDelegate::RemoveSession(
- const std::string& session_id,
- std::unique_ptr<SimpleCdmPromise> promise) {
- if (session_id.length() > media::limits::kMaxSessionIdLength) {
- promise->reject(CdmPromise::Exception::TYPE_ERROR, 0, "Incorrect session.");
- return;
- }
-
- uint32_t promise_id = cdm_promise_adapter_.SavePromise(std::move(promise));
- plugin_decryption_interface_->RemoveSession(
- pp_instance_, promise_id, StringVar::StringToPPVar(session_id));
-}
-
-// TODO(xhwang): Remove duplication of code in Decrypt(),
-// DecryptAndDecodeAudio() and DecryptAndDecodeVideo().
-bool ContentDecryptorDelegate::Decrypt(
- Decryptor::StreamType stream_type,
- const scoped_refptr<media::DecoderBuffer>& encrypted_buffer,
- const Decryptor::DecryptCB& decrypt_cb) {
- DVLOG(3) << "Decrypt() - stream_type: " << stream_type;
-
- // |{audio|video}_input_resource_| is not being used by the plugin
- // now because there is only one pending audio/video decrypt request at any
- // time. This is enforced by the media pipeline.
- scoped_refptr<PPB_Buffer_Impl> encrypted_resource;
- if (!MakeMediaBufferResource(
- stream_type, encrypted_buffer, &encrypted_resource) ||
- !encrypted_resource.get()) {
- return false;
- }
- ScopedPPResource pp_resource(encrypted_resource.get());
-
- const uint32_t request_id = next_decryption_request_id_++;
- DVLOG(2) << "Decrypt() - request_id " << request_id;
-
- PP_EncryptedBlockInfo block_info = {};
- if (!MakeEncryptedBlockInfo(encrypted_buffer, request_id, &block_info)) {
- return false;
- }
-
- // There is only one pending decrypt request at any time per stream. This is
- // enforced by the media pipeline.
- switch (stream_type) {
- case Decryptor::kAudio:
- audio_decrypt_cb_.Set(request_id, decrypt_cb);
- break;
- case Decryptor::kVideo:
- video_decrypt_cb_.Set(request_id, decrypt_cb);
- break;
- default:
- NOTREACHED();
- return false;
- }
-
- SetBufferToFreeInTrackingInfo(&block_info.tracking_info);
-
- plugin_decryption_interface_->Decrypt(pp_instance_, pp_resource, &block_info);
- return true;
-}
-
-bool ContentDecryptorDelegate::CancelDecrypt(
- Decryptor::StreamType stream_type) {
- DVLOG(3) << "CancelDecrypt() - stream_type: " << stream_type;
-
- Decryptor::DecryptCB decrypt_cb;
- switch (stream_type) {
- case Decryptor::kAudio:
- // Release the shared memory as it can still be in use by the plugin.
- // The next Decrypt() call will need to allocate a new shared memory
- // buffer.
- audio_input_resource_ = nullptr;
- decrypt_cb = audio_decrypt_cb_.ResetAndReturn();
- break;
- case Decryptor::kVideo:
- // Release the shared memory as it can still be in use by the plugin.
- // The next Decrypt() call will need to allocate a new shared memory
- // buffer.
- video_input_resource_ = nullptr;
- decrypt_cb = video_decrypt_cb_.ResetAndReturn();
- break;
- default:
- NOTREACHED();
- return false;
- }
-
- if (!decrypt_cb.is_null())
- decrypt_cb.Run(Decryptor::kSuccess, nullptr);
-
- return true;
-}
-
-bool ContentDecryptorDelegate::InitializeAudioDecoder(
- const media::AudioDecoderConfig& decoder_config,
- const Decryptor::DecoderInitCB& init_cb) {
- PP_AudioDecoderConfig pp_decoder_config;
- pp_decoder_config.codec =
- MediaAudioCodecToPpAudioCodec(decoder_config.codec());
- pp_decoder_config.channel_count =
- media::ChannelLayoutToChannelCount(decoder_config.channel_layout());
- pp_decoder_config.bits_per_channel = decoder_config.bits_per_channel();
- pp_decoder_config.samples_per_second = decoder_config.samples_per_second();
- pp_decoder_config.request_id = next_decryption_request_id_++;
-
- audio_samples_per_second_ = pp_decoder_config.samples_per_second;
- audio_channel_count_ = pp_decoder_config.channel_count;
- audio_channel_layout_ = decoder_config.channel_layout();
-
- scoped_refptr<PPB_Buffer_Impl> extra_data_resource;
- if (!MakeBufferResource(pp_instance_,
- decoder_config.extra_data(),
- &extra_data_resource)) {
- return false;
- }
- ScopedPPResource pp_resource(extra_data_resource.get());
-
- audio_decoder_init_cb_.Set(pp_decoder_config.request_id, init_cb);
- plugin_decryption_interface_->InitializeAudioDecoder(
- pp_instance_, &pp_decoder_config, pp_resource);
- return true;
-}
-
-bool ContentDecryptorDelegate::InitializeVideoDecoder(
- const media::VideoDecoderConfig& decoder_config,
- const Decryptor::DecoderInitCB& init_cb) {
- PP_VideoDecoderConfig pp_decoder_config;
- pp_decoder_config.codec =
- MediaVideoCodecToPpVideoCodec(decoder_config.codec());
- pp_decoder_config.profile =
- MediaVideoCodecProfileToPpVideoCodecProfile(decoder_config.profile());
- pp_decoder_config.format =
- MediaVideoFormatToPpDecryptedFrameFormat(decoder_config.format());
- pp_decoder_config.width = decoder_config.coded_size().width();
- pp_decoder_config.height = decoder_config.coded_size().height();
- pp_decoder_config.request_id = next_decryption_request_id_++;
-
- scoped_refptr<PPB_Buffer_Impl> extra_data_resource;
- if (!MakeBufferResource(pp_instance_,
- decoder_config.extra_data(),
- &extra_data_resource)) {
- return false;
- }
- ScopedPPResource pp_resource(extra_data_resource.get());
-
- video_decoder_init_cb_.Set(pp_decoder_config.request_id, init_cb);
- natural_size_ = decoder_config.natural_size();
-
- plugin_decryption_interface_->InitializeVideoDecoder(
- pp_instance_, &pp_decoder_config, pp_resource);
- return true;
-}
-
-bool ContentDecryptorDelegate::DeinitializeDecoder(
- Decryptor::StreamType stream_type) {
- CancelDecode(stream_type);
-
- if (stream_type == Decryptor::kVideo)
- natural_size_ = gfx::Size();
-
- // TODO(tomfinegan): Add decoder deinitialize request tracking, and get
- // stream type from media stack.
- plugin_decryption_interface_->DeinitializeDecoder(
- pp_instance_, MediaDecryptorStreamTypeToPpStreamType(stream_type), 0);
- return true;
-}
-
-bool ContentDecryptorDelegate::ResetDecoder(Decryptor::StreamType stream_type) {
- CancelDecode(stream_type);
-
- // TODO(tomfinegan): Add decoder reset request tracking.
- plugin_decryption_interface_->ResetDecoder(
- pp_instance_, MediaDecryptorStreamTypeToPpStreamType(stream_type), 0);
- return true;
-}
-
-bool ContentDecryptorDelegate::DecryptAndDecodeAudio(
- const scoped_refptr<media::DecoderBuffer>& encrypted_buffer,
- const Decryptor::AudioDecodeCB& audio_decode_cb) {
- // |audio_input_resource_| is not being used by the plugin now
- // because there is only one pending audio decode request at any time.
- // This is enforced by the media pipeline.
- scoped_refptr<PPB_Buffer_Impl> encrypted_resource;
- if (!MakeMediaBufferResource(
- Decryptor::kAudio, encrypted_buffer, &encrypted_resource)) {
- return false;
- }
-
- // The resource should not be NULL for non-EOS buffer.
- if (!encrypted_buffer->end_of_stream() && !encrypted_resource.get())
- return false;
-
- const uint32_t request_id = next_decryption_request_id_++;
- DVLOG(2) << "DecryptAndDecodeAudio() - request_id " << request_id;
-
- PP_EncryptedBlockInfo block_info = {};
- if (!MakeEncryptedBlockInfo(encrypted_buffer, request_id, &block_info)) {
- return false;
- }
-
- SetBufferToFreeInTrackingInfo(&block_info.tracking_info);
-
- // There is only one pending audio decode request at any time. This is
- // enforced by the media pipeline. If this DCHECK is violated, our buffer
- // reuse policy is not valid, and we may have race problems for the shared
- // buffer.
- audio_decode_cb_.Set(request_id, audio_decode_cb);
-
- ScopedPPResource pp_resource(encrypted_resource.get());
- plugin_decryption_interface_->DecryptAndDecode(
- pp_instance_, PP_DECRYPTORSTREAMTYPE_AUDIO, pp_resource, &block_info);
- return true;
-}
-
-bool ContentDecryptorDelegate::DecryptAndDecodeVideo(
- const scoped_refptr<media::DecoderBuffer>& encrypted_buffer,
- const Decryptor::VideoDecodeCB& video_decode_cb) {
- // |video_input_resource_| is not being used by the plugin now
- // because there is only one pending video decode request at any time.
- // This is enforced by the media pipeline.
- scoped_refptr<PPB_Buffer_Impl> encrypted_resource;
- if (!MakeMediaBufferResource(
- Decryptor::kVideo, encrypted_buffer, &encrypted_resource)) {
- return false;
- }
-
- // The resource should not be 0 for non-EOS buffer.
- if (!encrypted_buffer->end_of_stream() && !encrypted_resource.get())
- return false;
-
- const uint32_t request_id = next_decryption_request_id_++;
- DVLOG(2) << "DecryptAndDecodeVideo() - request_id " << request_id;
- TRACE_EVENT_ASYNC_BEGIN0(
- "media", "ContentDecryptorDelegate::DecryptAndDecodeVideo", request_id);
-
- PP_EncryptedBlockInfo block_info = {};
- if (!MakeEncryptedBlockInfo(encrypted_buffer, request_id, &block_info)) {
- return false;
- }
-
- SetBufferToFreeInTrackingInfo(&block_info.tracking_info);
-
- // Only one pending video decode request at any time. This is enforced by the
- // media pipeline. If this DCHECK is violated, our buffer
- // reuse policy is not valid, and we may have race problems for the shared
- // buffer.
- video_decode_cb_.Set(request_id, video_decode_cb);
-
- // TODO(tomfinegan): Need to get stream type from media stack.
- ScopedPPResource pp_resource(encrypted_resource.get());
- plugin_decryption_interface_->DecryptAndDecode(
- pp_instance_, PP_DECRYPTORSTREAMTYPE_VIDEO, pp_resource, &block_info);
- return true;
-}
-
-void ContentDecryptorDelegate::OnPromiseResolved(uint32_t promise_id) {
- cdm_promise_adapter_.ResolvePromise(promise_id);
-}
-
-void ContentDecryptorDelegate::OnPromiseResolvedWithKeyStatus(
- uint32_t promise_id,
- PP_CdmKeyStatus key_status) {
- cdm_promise_adapter_.ResolvePromise(
- promise_id, PpCdmKeyStatusToCdmKeyInformationKeyStatus(key_status));
-}
-
-void ContentDecryptorDelegate::OnPromiseResolvedWithSession(uint32_t promise_id,
- PP_Var session_id) {
- StringVar* session_id_string = StringVar::FromPPVar(session_id);
- DCHECK(session_id_string);
- cdm_session_tracker_.AddSession(session_id_string->value());
- cdm_promise_adapter_.ResolvePromise(promise_id, session_id_string->value());
-}
-
-void ContentDecryptorDelegate::OnPromiseRejected(
- uint32_t promise_id,
- PP_CdmExceptionCode exception_code,
- uint32_t system_code,
- PP_Var error_description) {
- ReportSystemCodeUMA(key_system_, system_code);
-
- StringVar* error_description_string = StringVar::FromPPVar(error_description);
- DCHECK(error_description_string);
- cdm_promise_adapter_.RejectPromise(
- promise_id, PpExceptionTypeToCdmPromiseException(exception_code),
- system_code, error_description_string->value());
-}
-
-void ContentDecryptorDelegate::OnSessionMessage(PP_Var session_id,
- PP_CdmMessageType message_type,
- PP_Var message) {
- if (session_message_cb_.is_null())
- return;
-
- StringVar* session_id_string = StringVar::FromPPVar(session_id);
- DCHECK(session_id_string);
-
- ArrayBufferVar* message_array_buffer = ArrayBufferVar::FromPPVar(message);
- std::vector<uint8_t> message_vector;
- if (message_array_buffer) {
- const uint8_t* data =
- static_cast<const uint8_t*>(message_array_buffer->Map());
- message_vector.assign(data, data + message_array_buffer->ByteLength());
- }
-
- session_message_cb_.Run(session_id_string->value(),
- PpCdmMessageTypeToMediaMessageType(message_type),
- message_vector);
-}
-
-void ContentDecryptorDelegate::OnSessionKeysChange(
- PP_Var session_id,
- PP_Bool has_additional_usable_key,
- uint32_t key_count,
- const struct PP_KeyInformation key_information[]) {
- if (session_keys_change_cb_.is_null())
- return;
-
- StringVar* session_id_string = StringVar::FromPPVar(session_id);
- DCHECK(session_id_string);
-
- media::CdmKeysInfo keys_info;
- keys_info.reserve(key_count);
- for (uint32_t i = 0; i < key_count; ++i) {
- const auto& info = key_information[i];
- keys_info.push_back(std::make_unique<media::CdmKeyInformation>(
- info.key_id, info.key_id_size,
- PpCdmKeyStatusToCdmKeyInformationKeyStatus(info.key_status),
- info.system_code));
- }
-
- session_keys_change_cb_.Run(session_id_string->value(),
- PP_ToBool(has_additional_usable_key),
- std::move(keys_info));
-}
-
-void ContentDecryptorDelegate::OnSessionExpirationChange(
- PP_Var session_id,
- PP_Time new_expiry_time) {
- if (session_expiration_update_cb_.is_null())
- return;
-
- StringVar* session_id_string = StringVar::FromPPVar(session_id);
- DCHECK(session_id_string);
-
- // PPTimeToTime() converts exact 0 to base::Time::UnixEpoch, which is not
- // desired here. We want to convert 0.0 to a null base::Time.
- base::Time expiry_time;
- if (new_expiry_time != 0.0)
- expiry_time = ppapi::PPTimeToTime(new_expiry_time);
-
- session_expiration_update_cb_.Run(session_id_string->value(), expiry_time);
-}
-
-void ContentDecryptorDelegate::OnSessionClosed(PP_Var session_id) {
- StringVar* session_id_string = StringVar::FromPPVar(session_id);
- DCHECK(session_id_string);
-
- cdm_session_tracker_.RemoveSession(session_id_string->value());
- if (!session_closed_cb_.is_null())
- session_closed_cb_.Run(session_id_string->value());
-}
-
-void ContentDecryptorDelegate::DecoderInitializeDone(
- PP_DecryptorStreamType decoder_type,
- uint32_t request_id,
- PP_Bool success) {
- if (decoder_type == PP_DECRYPTORSTREAMTYPE_AUDIO) {
- // If the request ID is not valid or does not match what's saved, do
- // nothing.
- if (request_id == 0 || !audio_decoder_init_cb_.Matches(request_id))
- return;
-
- audio_decoder_init_cb_.ResetAndReturn().Run(PP_ToBool(success));
- } else {
- if (request_id == 0 || !video_decoder_init_cb_.Matches(request_id))
- return;
-
- if (!success)
- natural_size_ = gfx::Size();
-
- video_decoder_init_cb_.ResetAndReturn().Run(PP_ToBool(success));
- }
-}
-
-void ContentDecryptorDelegate::DecoderDeinitializeDone(
- PP_DecryptorStreamType decoder_type,
- uint32_t request_id) {
- // TODO(tomfinegan): Add decoder stop completion handling.
-}
-
-void ContentDecryptorDelegate::DecoderResetDone(
- PP_DecryptorStreamType decoder_type,
- uint32_t request_id) {
- // TODO(tomfinegan): Add decoder reset completion handling.
-}
-
-void ContentDecryptorDelegate::DeliverBlock(
- PP_Resource decrypted_block,
- const PP_DecryptedBlockInfo* block_info) {
- DCHECK(block_info);
-
- FreeBuffer(block_info->tracking_info.buffer_id);
-
- const uint32_t request_id = block_info->tracking_info.request_id;
- DVLOG(2) << "DeliverBlock() - request_id: " << request_id;
-
- // If the request ID is not valid or does not match what's saved, do nothing.
- if (request_id == 0) {
- DVLOG(1) << "DeliverBlock() - invalid request_id " << request_id;
- return;
- }
-
- Decryptor::DecryptCB decrypt_cb;
- if (audio_decrypt_cb_.Matches(request_id)) {
- decrypt_cb = audio_decrypt_cb_.ResetAndReturn();
- } else if (video_decrypt_cb_.Matches(request_id)) {
- decrypt_cb = video_decrypt_cb_.ResetAndReturn();
- } else {
- DVLOG(1) << "DeliverBlock() - request_id " << request_id << " not found";
- return;
- }
-
- Decryptor::Status status =
- PpDecryptResultToMediaDecryptorStatus(block_info->result);
- if (status != Decryptor::kSuccess) {
- decrypt_cb.Run(status, nullptr);
- return;
- }
-
- EnterResourceNoLock<PPB_Buffer_API> enter(decrypted_block, true);
- if (!enter.succeeded()) {
- decrypt_cb.Run(Decryptor::kError, nullptr);
- return;
- }
- BufferAutoMapper mapper(enter.object());
- if (!mapper.data() || !mapper.size() ||
- mapper.size() < block_info->data_size) {
- decrypt_cb.Run(Decryptor::kError, nullptr);
- return;
- }
-
- // TODO(tomfinegan): Find a way to take ownership of the shared memory
- // managed by the PPB_Buffer_Dev, and avoid the extra copy.
- scoped_refptr<media::DecoderBuffer> decrypted_buffer(
- media::DecoderBuffer::CopyFrom(static_cast<uint8_t*>(mapper.data()),
- block_info->data_size));
- decrypted_buffer->set_timestamp(
- base::TimeDelta::FromMicroseconds(block_info->tracking_info.timestamp));
- decrypt_cb.Run(Decryptor::kSuccess, decrypted_buffer);
-}
-
-// Use a non-class-member function here so that if for some reason
-// ContentDecryptorDelegate is destroyed before VideoFrame calls this callback,
-// we can still get the shared memory unmapped.
-static void BufferNoLongerNeeded(
- const scoped_refptr<PPB_Buffer_Impl>& ppb_buffer,
- base::Closure buffer_no_longer_needed_cb) {
- ppb_buffer->Unmap();
- buffer_no_longer_needed_cb.Run();
-}
-
-// Enters |resource|, maps shared memory and returns pointer of mapped data.
-// Returns NULL if any error occurs.
-static uint8_t* GetMappedBuffer(PP_Resource resource,
- scoped_refptr<PPB_Buffer_Impl>* ppb_buffer) {
- EnterResourceNoLock<PPB_Buffer_API> enter(resource, true);
- if (!enter.succeeded())
- return nullptr;
-
- uint8_t* mapped_data = static_cast<uint8_t*>(enter.object()->Map());
- if (!enter.object()->IsMapped() || !mapped_data)
- return nullptr;
-
- uint32_t mapped_size = 0;
- if (!enter.object()->Describe(&mapped_size) || !mapped_size) {
- enter.object()->Unmap();
- return nullptr;
- }
-
- *ppb_buffer = static_cast<PPB_Buffer_Impl*>(enter.object());
-
- return mapped_data;
-}
-
-void ContentDecryptorDelegate::DeliverFrame(
- PP_Resource decrypted_frame,
- const PP_DecryptedFrameInfo* frame_info) {
- DCHECK(frame_info);
-
- const uint32_t request_id = frame_info->tracking_info.request_id;
- DVLOG(2) << "DeliverFrame() - request_id: " << request_id;
-
- // If the request ID is not valid or does not match what's saved, do nothing.
- if (request_id == 0 || !video_decode_cb_.Matches(request_id)) {
- DVLOG(1) << "DeliverFrame() - request_id " << request_id << " not found";
- FreeBuffer(frame_info->tracking_info.buffer_id);
- return;
- }
-
- TRACE_EVENT_ASYNC_END0(
- "media", "ContentDecryptorDelegate::DecryptAndDecodeVideo", request_id);
-
- Decryptor::VideoDecodeCB video_decode_cb = video_decode_cb_.ResetAndReturn();
-
- Decryptor::Status status =
- PpDecryptResultToMediaDecryptorStatus(frame_info->result);
- if (status != Decryptor::kSuccess) {
- DCHECK(!frame_info->tracking_info.buffer_id);
- video_decode_cb.Run(status, nullptr);
- return;
- }
-
- scoped_refptr<PPB_Buffer_Impl> ppb_buffer;
- uint8_t* frame_data = GetMappedBuffer(decrypted_frame, &ppb_buffer);
- if (!frame_data) {
- FreeBuffer(frame_info->tracking_info.buffer_id);
- video_decode_cb.Run(Decryptor::kError, nullptr);
- return;
- }
-
- gfx::Size frame_size(frame_info->width, frame_info->height);
-
- media::VideoPixelFormat video_pixel_format =
- PpDecryptedFrameFormatToMediaVideoFormat(frame_info->format);
- if (video_pixel_format == media::PIXEL_FORMAT_UNKNOWN) {
- FreeBuffer(frame_info->tracking_info.buffer_id);
- video_decode_cb.Run(Decryptor::kError, nullptr);
- return;
- }
-
- scoped_refptr<media::VideoFrame> decoded_frame =
- media::VideoFrame::WrapExternalYuvData(
- video_pixel_format, frame_size, gfx::Rect(frame_size),
- natural_size_, frame_info->strides[PP_DECRYPTEDFRAMEPLANES_Y],
- frame_info->strides[PP_DECRYPTEDFRAMEPLANES_U],
- frame_info->strides[PP_DECRYPTEDFRAMEPLANES_V],
- frame_data + frame_info->plane_offsets[PP_DECRYPTEDFRAMEPLANES_Y],
- frame_data + frame_info->plane_offsets[PP_DECRYPTEDFRAMEPLANES_U],
- frame_data + frame_info->plane_offsets[PP_DECRYPTEDFRAMEPLANES_V],
- base::TimeDelta::FromMicroseconds(
- frame_info->tracking_info.timestamp));
- if (!decoded_frame) {
- FreeBuffer(frame_info->tracking_info.buffer_id);
- video_decode_cb.Run(Decryptor::kError, nullptr);
- return;
- }
- decoded_frame->AddDestructionObserver(
- media::BindToCurrentLoop(
- base::Bind(&BufferNoLongerNeeded,
- ppb_buffer,
- base::Bind(&ContentDecryptorDelegate::FreeBuffer,
- weak_this_,
- frame_info->tracking_info.buffer_id))));
-
- video_decode_cb.Run(Decryptor::kSuccess, decoded_frame);
-}
-
-void ContentDecryptorDelegate::DeliverSamples(
- PP_Resource audio_frames,
- const PP_DecryptedSampleInfo* sample_info) {
- DCHECK(sample_info);
-
- FreeBuffer(sample_info->tracking_info.buffer_id);
-
- const uint32_t request_id = sample_info->tracking_info.request_id;
- DVLOG(2) << "DeliverSamples() - request_id: " << request_id;
-
- // If the request ID is not valid or does not match what's saved, do nothing.
- if (request_id == 0 || !audio_decode_cb_.Matches(request_id)) {
- DVLOG(1) << "DeliverSamples() - request_id " << request_id << " not found";
- return;
- }
-
- Decryptor::AudioDecodeCB audio_decode_cb = audio_decode_cb_.ResetAndReturn();
-
- const Decryptor::AudioFrames empty_frames;
-
- Decryptor::Status status =
- PpDecryptResultToMediaDecryptorStatus(sample_info->result);
- if (status != Decryptor::kSuccess) {
- audio_decode_cb.Run(status, empty_frames);
- return;
- }
-
- media::SampleFormat sample_format =
- PpDecryptedSampleFormatToMediaSampleFormat(sample_info->format);
-
- Decryptor::AudioFrames audio_frame_list;
- if (!DeserializeAudioFrames(audio_frames,
- sample_info->data_size,
- sample_format,
- &audio_frame_list)) {
- NOTREACHED() << "CDM did not serialize the buffer correctly.";
- audio_decode_cb.Run(Decryptor::kError, empty_frames);
- return;
- }
-
- audio_decode_cb.Run(Decryptor::kSuccess, audio_frame_list);
-}
-
-// TODO(xhwang): Try to remove duplicate logic here and in CancelDecrypt().
-void ContentDecryptorDelegate::CancelDecode(Decryptor::StreamType stream_type) {
- switch (stream_type) {
- case Decryptor::kAudio:
- // Release the shared memory as it can still be in use by the plugin.
- // The next DecryptAndDecode() call will need to allocate a new shared
- // memory buffer.
- audio_input_resource_ = nullptr;
- if (!audio_decode_cb_.is_null())
- audio_decode_cb_.ResetAndReturn().Run(Decryptor::kSuccess,
- Decryptor::AudioFrames());
- break;
- case Decryptor::kVideo:
- // Release the shared memory as it can still be in use by the plugin.
- // The next DecryptAndDecode() call will need to allocate a new shared
- // memory buffer.
- video_input_resource_ = nullptr;
- if (!video_decode_cb_.is_null())
- video_decode_cb_.ResetAndReturn().Run(Decryptor::kSuccess, nullptr);
- break;
- default:
- NOTREACHED();
- }
-}
-
-bool ContentDecryptorDelegate::MakeMediaBufferResource(
- Decryptor::StreamType stream_type,
- const scoped_refptr<media::DecoderBuffer>& buffer,
- scoped_refptr<PPB_Buffer_Impl>* resource) {
- TRACE_EVENT0("media", "ContentDecryptorDelegate::MakeMediaBufferResource");
-
- // End of stream buffers are represented as null resources.
- if (buffer->end_of_stream()) {
- *resource = nullptr;
- return true;
- }
-
- DCHECK(stream_type == Decryptor::kAudio || stream_type == Decryptor::kVideo);
- scoped_refptr<PPB_Buffer_Impl>& media_resource =
- (stream_type == Decryptor::kAudio) ? audio_input_resource_
- : video_input_resource_;
-
- const size_t data_size = static_cast<size_t>(buffer->data_size());
- if (!media_resource.get() || media_resource->size() < data_size) {
- // Either the buffer hasn't been created yet, or we have one that isn't big
- // enough to fit |size| bytes.
-
- // Media resource size starts from |kMinimumMediaBufferSize| and grows
- // exponentially to avoid frequent re-allocation of PPB_Buffer_Impl,
- // which is usually expensive. Since input media buffers are compressed,
- // they are usually small (compared to outputs). The over-allocated memory
- // should be negligible.
- const uint32_t kMinimumMediaBufferSize = 1024;
- uint32_t media_resource_size =
- media_resource.get() ? media_resource->size() : kMinimumMediaBufferSize;
- while (media_resource_size < data_size)
- media_resource_size *= 2;
-
- DVLOG(2) << "Size of media buffer for "
- << ((stream_type == Decryptor::kAudio) ? "audio" : "video")
- << " stream bumped to " << media_resource_size
- << " bytes to fit input.";
- media_resource =
- PPB_Buffer_Impl::CreateResource(pp_instance_, media_resource_size);
- if (!media_resource.get())
- return false;
- }
-
- BufferAutoMapper mapper(media_resource.get());
- if (!mapper.data() || mapper.size() < data_size) {
- media_resource = nullptr;
- return false;
- }
- memcpy(mapper.data(), buffer->data(), data_size);
-
- *resource = media_resource;
- return true;
-}
-
-void ContentDecryptorDelegate::FreeBuffer(uint32_t buffer_id) {
- if (buffer_id)
- free_buffers_.push(buffer_id);
-}
-
-void ContentDecryptorDelegate::SetBufferToFreeInTrackingInfo(
- PP_DecryptTrackingInfo* tracking_info) {
- DCHECK_EQ(tracking_info->buffer_id, 0u);
-
- if (free_buffers_.empty())
- return;
-
- tracking_info->buffer_id = free_buffers_.front();
- free_buffers_.pop();
-}
-
-bool ContentDecryptorDelegate::DeserializeAudioFrames(
- PP_Resource audio_frames,
- size_t data_size,
- media::SampleFormat sample_format,
- Decryptor::AudioFrames* frames) {
- DCHECK(frames);
- EnterResourceNoLock<PPB_Buffer_API> enter(audio_frames, true);
- if (!enter.succeeded())
- return false;
-
- BufferAutoMapper mapper(enter.object());
- if (!mapper.data() || !mapper.size() ||
- mapper.size() < static_cast<uint32_t>(data_size))
- return false;
-
- // TODO(jrummell): Pass ownership of data() directly to AudioBuffer to avoid
- // the copy. Since it is possible to get multiple buffers, it would need to be
- // sliced and ref counted appropriately. http://crbug.com/255576.
- const uint8_t* cur = static_cast<uint8_t*>(mapper.data());
- size_t bytes_left = data_size;
-
- const int audio_bytes_per_frame =
- media::SampleFormatToBytesPerChannel(sample_format) *
- audio_channel_count_;
- if (audio_bytes_per_frame <= 0)
- return false;
-
- // Allocate space for the channel pointers given to AudioBuffer.
- std::vector<const uint8_t*> channel_ptrs(audio_channel_count_, nullptr);
- do {
- int64_t timestamp = 0;
- int64_t frame_size = -1;
- const size_t kHeaderSize = sizeof(timestamp) + sizeof(frame_size);
-
- if (bytes_left < kHeaderSize)
- return false;
-
- memcpy(&timestamp, cur, sizeof(timestamp));
- cur += sizeof(timestamp);
- bytes_left -= sizeof(timestamp);
-
- memcpy(&frame_size, cur, sizeof(frame_size));
- cur += sizeof(frame_size);
- bytes_left -= sizeof(frame_size);
-
- // We should *not* have empty frames in the list.
- if (frame_size <= 0 ||
- bytes_left < base::checked_cast<size_t>(frame_size)) {
- return false;
- }
-
- // Setup channel pointers. AudioBuffer::CopyFrom() will only use the first
- // one in the case of interleaved data.
- const int size_per_channel = frame_size / audio_channel_count_;
- for (int i = 0; i < audio_channel_count_; ++i)
- channel_ptrs[i] = cur + i * size_per_channel;
-
- const int frame_count = frame_size / audio_bytes_per_frame;
- scoped_refptr<media::AudioBuffer> frame = media::AudioBuffer::CopyFrom(
- sample_format, audio_channel_layout_, audio_channel_count_,
- audio_samples_per_second_, frame_count, &channel_ptrs[0],
- base::TimeDelta::FromMicroseconds(timestamp), pool_);
- frames->push_back(frame);
-
- cur += frame_size;
- bytes_left -= frame_size;
- } while (bytes_left > 0);
-
- return true;
-}
-
-void ContentDecryptorDelegate::SatisfyAllPendingCallbacksOnError() {
- if (!audio_decoder_init_cb_.is_null())
- audio_decoder_init_cb_.ResetAndReturn().Run(false);
-
- if (!video_decoder_init_cb_.is_null())
- video_decoder_init_cb_.ResetAndReturn().Run(false);
-
- audio_input_resource_ = nullptr;
- video_input_resource_ = nullptr;
-
- if (!audio_decrypt_cb_.is_null())
- audio_decrypt_cb_.ResetAndReturn().Run(media::Decryptor::kError, nullptr);
-
- if (!video_decrypt_cb_.is_null())
- video_decrypt_cb_.ResetAndReturn().Run(media::Decryptor::kError, nullptr);
-
- if (!audio_decode_cb_.is_null()) {
- const media::Decryptor::AudioFrames empty_frames;
- audio_decode_cb_.ResetAndReturn().Run(media::Decryptor::kError,
- empty_frames);
- }
-
- if (!video_decode_cb_.is_null())
- video_decode_cb_.ResetAndReturn().Run(media::Decryptor::kError, nullptr);
-
- cdm_promise_adapter_.Clear();
-
- cdm_session_tracker_.CloseRemainingSessions(session_closed_cb_);
-}
-
-} // namespace content
diff --git a/chromium/content/renderer/pepper/content_decryptor_delegate.h b/chromium/content/renderer/pepper/content_decryptor_delegate.h
deleted file mode 100644
index f8e41e6dac2..00000000000
--- a/chromium/content/renderer/pepper/content_decryptor_delegate.h
+++ /dev/null
@@ -1,261 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CONTENT_RENDERER_PEPPER_CONTENT_DECRYPTOR_DELEGATE_H_
-#define CONTENT_RENDERER_PEPPER_CONTENT_DECRYPTOR_DELEGATE_H_
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include <map>
-#include <string>
-#include <vector>
-
-#include "base/callback_helpers.h"
-#include "base/compiler_specific.h"
-#include "base/containers/queue.h"
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/memory/weak_ptr.h"
-#include "media/base/audio_buffer.h"
-#include "media/base/cdm_promise.h"
-#include "media/base/cdm_promise_adapter.h"
-#include "media/base/cdm_session_tracker.h"
-#include "media/base/channel_layout.h"
-#include "media/base/content_decryption_module.h"
-#include "media/base/decryptor.h"
-#include "media/base/sample_format.h"
-#include "ppapi/c/pp_time.h"
-#include "ppapi/c/private/pp_content_decryptor.h"
-#include "ppapi/c/private/ppp_content_decryptor_private.h"
-#include "ui/gfx/geometry/size.h"
-
-namespace media {
-class AudioDecoderConfig;
-class DecoderBuffer;
-class VideoDecoderConfig;
-}
-
-namespace content {
-
-class PPB_Buffer_Impl;
-
-class ContentDecryptorDelegate {
- public:
- // ContentDecryptorDelegate does not take ownership of
- // |plugin_decryption_interface|. Therefore |plugin_decryption_interface|
- // must outlive this object.
- ContentDecryptorDelegate(
- PP_Instance pp_instance,
- const PPP_ContentDecryptor_Private* plugin_decryption_interface);
- ~ContentDecryptorDelegate();
-
- // This object should not be accessed after |fatal_plugin_error_cb| is called.
- void Initialize(
- const std::string& key_system,
- bool allow_distinctive_identifier,
- bool allow_persistent_state,
- const media::SessionMessageCB& session_message_cb,
- const media::SessionClosedCB& session_closed_cb,
- const media::SessionKeysChangeCB& session_keys_change_cb,
- const media::SessionExpirationUpdateCB& session_expiration_update_cb,
- const base::Closure& fatal_plugin_error_cb,
- std::unique_ptr<media::SimpleCdmPromise> promise);
-
- void InstanceCrashed();
-
- // Provides access to PPP_ContentDecryptor_Private.
- void SetServerCertificate(const std::vector<uint8_t>& certificate,
- std::unique_ptr<media::SimpleCdmPromise> promise);
- void GetStatusForPolicy(media::HdcpVersion min_hdcp_version,
- std::unique_ptr<media::KeyStatusCdmPromise> promise);
- void CreateSessionAndGenerateRequest(
- media::CdmSessionType session_type,
- media::EmeInitDataType init_data_type,
- const std::vector<uint8_t>& init_data,
- std::unique_ptr<media::NewSessionCdmPromise> promise);
- void LoadSession(media::CdmSessionType session_type,
- const std::string& session_id,
- std::unique_ptr<media::NewSessionCdmPromise> promise);
- void UpdateSession(const std::string& session_id,
- const std::vector<uint8_t>& response,
- std::unique_ptr<media::SimpleCdmPromise> promise);
- void CloseSession(const std::string& session_id,
- std::unique_ptr<media::SimpleCdmPromise> promise);
- void RemoveSession(const std::string& session_id,
- std::unique_ptr<media::SimpleCdmPromise> promise);
- bool Decrypt(media::Decryptor::StreamType stream_type,
- const scoped_refptr<media::DecoderBuffer>& encrypted_buffer,
- const media::Decryptor::DecryptCB& decrypt_cb);
- bool CancelDecrypt(media::Decryptor::StreamType stream_type);
- bool InitializeAudioDecoder(
- const media::AudioDecoderConfig& decoder_config,
- const media::Decryptor::DecoderInitCB& decoder_init_cb);
- bool InitializeVideoDecoder(
- const media::VideoDecoderConfig& decoder_config,
- const media::Decryptor::DecoderInitCB& decoder_init_cb);
- // TODO(tomfinegan): Add callback args for DeinitializeDecoder() and
- // ResetDecoder()
- bool DeinitializeDecoder(media::Decryptor::StreamType stream_type);
- bool ResetDecoder(media::Decryptor::StreamType stream_type);
- // Note: These methods can be used with unencrypted data.
- bool DecryptAndDecodeAudio(
- const scoped_refptr<media::DecoderBuffer>& encrypted_buffer,
- const media::Decryptor::AudioDecodeCB& audio_decode_cb);
- bool DecryptAndDecodeVideo(
- const scoped_refptr<media::DecoderBuffer>& encrypted_buffer,
- const media::Decryptor::VideoDecodeCB& video_decode_cb);
-
- // PPB_ContentDecryptor_Private dispatching methods.
- void OnPromiseResolved(uint32_t promise_id);
- void OnPromiseResolvedWithKeyStatus(uint32_t promise_id,
- PP_CdmKeyStatus key_status);
- void OnPromiseResolvedWithSession(uint32_t promise_id, PP_Var session_id);
- void OnPromiseRejected(uint32_t promise_id,
- PP_CdmExceptionCode exception_code,
- uint32_t system_code,
- PP_Var error_description);
- void OnSessionMessage(PP_Var session_id,
- PP_CdmMessageType message_type,
- PP_Var message);
- void OnSessionKeysChange(PP_Var session_id,
- PP_Bool has_additional_usable_key,
- uint32_t key_count,
- const struct PP_KeyInformation key_information[]);
- void OnSessionExpirationChange(PP_Var session_id, PP_Time new_expiry_time);
- void OnSessionClosed(PP_Var session_id);
- void DeliverBlock(PP_Resource decrypted_block,
- const PP_DecryptedBlockInfo* block_info);
- void DecoderInitializeDone(PP_DecryptorStreamType decoder_type,
- uint32_t request_id,
- PP_Bool success);
- void DecoderDeinitializeDone(PP_DecryptorStreamType decoder_type,
- uint32_t request_id);
- void DecoderResetDone(PP_DecryptorStreamType decoder_type,
- uint32_t request_id);
- void DeliverFrame(PP_Resource decrypted_frame,
- const PP_DecryptedFrameInfo* frame_info);
- void DeliverSamples(PP_Resource audio_frames,
- const PP_DecryptedSampleInfo* sample_info);
-
- private:
- template <typename Callback>
- class TrackableCallback {
- public:
- TrackableCallback() : id_(0u) {}
- ~TrackableCallback() {
- // Callbacks must be satisfied.
- DCHECK_EQ(id_, 0u);
- DCHECK(is_null());
- };
-
- bool Matches(uint32_t id) const { return id == id_; }
-
- bool is_null() const { return cb_.is_null(); }
-
- void Set(uint32_t id, const Callback& cb) {
- DCHECK_EQ(id_, 0u);
- DCHECK(cb_.is_null());
- id_ = id;
- cb_ = cb;
- }
-
- Callback ResetAndReturn() {
- id_ = 0;
- return base::ResetAndReturn(&cb_);
- }
-
- private:
- uint32_t id_;
- Callback cb_;
- };
-
- // Cancels the pending decrypt-and-decode callback for |stream_type|.
- void CancelDecode(media::Decryptor::StreamType stream_type);
-
- // Fills |resource| with a PPB_Buffer_Impl and copies the data from
- // |encrypted_buffer| into the buffer resource. This method reuses
- // |audio_input_resource_| and |video_input_resource_| to reduce the latency
- // in requesting new PPB_Buffer_Impl resources. The caller must make sure that
- // |audio_input_resource_| or |video_input_resource_| is available before
- // calling this method.
- //
- // An end of stream |encrypted_buffer| is represented as a null |resource|.
- //
- // Returns true upon success and false if any error happened.
- bool MakeMediaBufferResource(
- media::Decryptor::StreamType stream_type,
- const scoped_refptr<media::DecoderBuffer>& encrypted_buffer,
- scoped_refptr<PPB_Buffer_Impl>* resource);
-
- void FreeBuffer(uint32_t buffer_id);
-
- void SetBufferToFreeInTrackingInfo(PP_DecryptTrackingInfo* tracking_info);
-
- // Deserializes audio data stored in |audio_frames| into individual audio
- // buffers in |frames|. Returns true upon success.
- bool DeserializeAudioFrames(PP_Resource audio_frames,
- size_t data_size,
- media::SampleFormat sample_format,
- media::Decryptor::AudioFrames* frames);
-
- void SatisfyAllPendingCallbacksOnError();
-
- const PP_Instance pp_instance_;
- const PPP_ContentDecryptor_Private* const plugin_decryption_interface_;
-
- // TODO(ddorwin): Remove after updating the Pepper API to not use key system.
- std::string key_system_;
-
- // Callbacks for firing session events.
- media::SessionMessageCB session_message_cb_;
- media::SessionClosedCB session_closed_cb_;
- media::SessionKeysChangeCB session_keys_change_cb_;
- media::SessionExpirationUpdateCB session_expiration_update_cb_;
-
- // Callback to notify that unexpected error happened and |this| should not
- // be used anymore.
- base::Closure fatal_plugin_error_cb_;
-
- gfx::Size natural_size_;
-
- // Request ID for tracking pending content decryption callbacks.
- // Note that zero indicates an invalid request ID.
- // TODO(xhwang): Add completion callbacks for Reset/Stop and remove the use
- // of request IDs.
- uint32_t next_decryption_request_id_;
-
- TrackableCallback<media::Decryptor::DecryptCB> audio_decrypt_cb_;
- TrackableCallback<media::Decryptor::DecryptCB> video_decrypt_cb_;
- TrackableCallback<media::Decryptor::DecoderInitCB> audio_decoder_init_cb_;
- TrackableCallback<media::Decryptor::DecoderInitCB> video_decoder_init_cb_;
- TrackableCallback<media::Decryptor::AudioDecodeCB> audio_decode_cb_;
- TrackableCallback<media::Decryptor::VideoDecodeCB> video_decode_cb_;
-
- // Cached audio and video input buffers. See MakeMediaBufferResource.
- scoped_refptr<PPB_Buffer_Impl> audio_input_resource_;
- scoped_refptr<PPB_Buffer_Impl> video_input_resource_;
-
- base::queue<uint32_t> free_buffers_;
-
- // Keep track of audio parameters.
- int audio_samples_per_second_;
- int audio_channel_count_;
- media::ChannelLayout audio_channel_layout_;
-
- media::CdmPromiseAdapter cdm_promise_adapter_;
-
- media::CdmSessionTracker cdm_session_tracker_;
-
- scoped_refptr<media::AudioBufferMemoryPool> pool_;
-
- base::WeakPtr<ContentDecryptorDelegate> weak_this_;
- base::WeakPtrFactory<ContentDecryptorDelegate> weak_ptr_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(ContentDecryptorDelegate);
-};
-
-} // namespace content
-
-#endif // CONTENT_RENDERER_PEPPER_CONTENT_DECRYPTOR_DELEGATE_H_
diff --git a/chromium/content/renderer/pepper/content_renderer_pepper_host_factory.cc b/chromium/content/renderer/pepper/content_renderer_pepper_host_factory.cc
index 06866d37468..c721ccd0e6d 100644
--- a/chromium/content/renderer/pepper/content_renderer_pepper_host_factory.cc
+++ b/chromium/content/renderer/pepper/content_renderer_pepper_host_factory.cc
@@ -33,16 +33,16 @@
#include "content/renderer/pepper/pepper_websocket_host.h"
#include "content/renderer/pepper/ppb_image_data_impl.h"
#include "content/renderer/pepper/renderer_ppapi_host_impl.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "ppapi/host/resource_host.h"
#include "ppapi/proxy/ppapi_message_utils.h"
#include "ppapi/proxy/ppapi_messages.h"
#include "ppapi/proxy/serialized_structs.h"
#include "ppapi/shared_impl/ppb_image_data_shared.h"
#include "services/service_manager/sandbox/switches.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebPluginContainer.h"
+#include "third_party/blink/public/platform/web_url.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_plugin_container.h"
#if defined(OS_WIN)
#include "base/win/windows_version.h"
diff --git a/chromium/content/renderer/pepper/event_conversion.cc b/chromium/content/renderer/pepper/event_conversion.cc
index ac0d7e8d5d0..7327a395dc4 100644
--- a/chromium/content/renderer/pepper/event_conversion.cc
+++ b/chromium/content/renderer/pepper/event_conversion.cc
@@ -23,11 +23,11 @@
#include "device/gamepad/public/cpp/gamepads.h"
#include "ppapi/c/pp_input_event.h"
#include "ppapi/shared_impl/ppb_input_event_shared.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
-#include "third_party/WebKit/public/platform/WebKeyboardEvent.h"
-#include "third_party/WebKit/public/platform/WebMouseWheelEvent.h"
-#include "third_party/WebKit/public/platform/WebPointerEvent.h"
-#include "third_party/WebKit/public/platform/WebTouchEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
+#include "third_party/blink/public/platform/web_keyboard_event.h"
+#include "third_party/blink/public/platform/web_mouse_wheel_event.h"
+#include "third_party/blink/public/platform/web_pointer_event.h"
+#include "third_party/blink/public/platform/web_touch_event.h"
#include "ui/events/keycodes/dom/keycode_converter.h"
#if defined(OS_WIN)
diff --git a/chromium/content/renderer/pepper/event_conversion.h b/chromium/content/renderer/pepper/event_conversion.h
index 414e868b19c..884e73ca124 100644
--- a/chromium/content/renderer/pepper/event_conversion.h
+++ b/chromium/content/renderer/pepper/event_conversion.h
@@ -10,7 +10,7 @@
#include "content/common/content_export.h"
#include "ppapi/c/ppb_input_event.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_input_event.h"
struct PP_InputEvent;
diff --git a/chromium/content/renderer/pepper/host_array_buffer_var.h b/chromium/content/renderer/pepper/host_array_buffer_var.h
index f26360d0d1d..5808d765594 100644
--- a/chromium/content/renderer/pepper/host_array_buffer_var.h
+++ b/chromium/content/renderer/pepper/host_array_buffer_var.h
@@ -12,7 +12,7 @@
#include "ppapi/c/pp_instance.h"
#include "ppapi/shared_impl/host_resource.h"
#include "ppapi/shared_impl/var.h"
-#include "third_party/WebKit/public/web/WebArrayBuffer.h"
+#include "third_party/blink/public/web/web_array_buffer.h"
namespace content {
diff --git a/chromium/content/renderer/pepper/host_dispatcher_wrapper.cc b/chromium/content/renderer/pepper/host_dispatcher_wrapper.cc
index 83832df65d6..b9c04fca4f0 100644
--- a/chromium/content/renderer/pepper/host_dispatcher_wrapper.cc
+++ b/chromium/content/renderer/pepper/host_dispatcher_wrapper.cc
@@ -14,8 +14,8 @@
#include "content/renderer/pepper/renderer_ppapi_host_impl.h"
#include "content/renderer/pepper/renderer_restrict_dispatch_group.h"
#include "content/renderer/render_frame_impl.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebPluginContainer.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_plugin_container.h"
namespace content {
diff --git a/chromium/content/renderer/pepper/host_globals.cc b/chromium/content/renderer/pepper/host_globals.cc
index 057ef4fd444..0b631a0f7db 100644
--- a/chromium/content/renderer/pepper/host_globals.cc
+++ b/chromium/content/renderer/pepper/host_globals.cc
@@ -11,6 +11,7 @@
#include "base/rand_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task_runner.h"
+#include "base/task_scheduler/post_task.h"
#include "content/public/common/content_switches.h"
#include "content/renderer/pepper/pepper_plugin_instance_impl.h"
#include "content/renderer/pepper/plugin_module.h"
@@ -18,11 +19,11 @@
#include "ppapi/shared_impl/api_id.h"
#include "ppapi/shared_impl/id_assignment.h"
#include "ppapi/shared_impl/proxy_lock.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/web/WebConsoleMessage.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebPluginContainer.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/web/web_console_message.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_plugin_container.h"
using ppapi::CheckIdType;
using ppapi::MakeTypedId;
@@ -190,7 +191,9 @@ void HostGlobals::BroadcastLogWithSource(PP_Module pp_module,
}
base::TaskRunner* HostGlobals::GetFileTaskRunner() {
- return RenderThreadImpl::current()->GetFileThreadTaskRunner().get();
+ if (!file_task_runner_)
+ file_task_runner_ = base::CreateTaskRunnerWithTraits({base::MayBlock()});
+ return file_task_runner_.get();
}
ppapi::MessageLoopShared* HostGlobals::GetCurrentMessageLoop() {
diff --git a/chromium/content/renderer/pepper/host_globals.h b/chromium/content/renderer/pepper/host_globals.h
index 0e554cbea1b..afd803aab62 100644
--- a/chromium/content/renderer/pepper/host_globals.h
+++ b/chromium/content/renderer/pepper/host_globals.h
@@ -104,6 +104,8 @@ class HostGlobals : public ppapi::PpapiGlobals {
typedef std::map<PP_Module, PluginModule*> ModuleMap;
ModuleMap module_map_;
+ scoped_refptr<base::TaskRunner> file_task_runner_;
+
DISALLOW_COPY_AND_ASSIGN(HostGlobals);
};
diff --git a/chromium/content/renderer/pepper/message_channel.cc b/chromium/content/renderer/pepper/message_channel.cc
index 4a9f3a03b26..219a0c76744 100644
--- a/chromium/content/renderer/pepper/message_channel.cc
+++ b/chromium/content/renderer/pepper/message_channel.cc
@@ -25,8 +25,8 @@
#include "ppapi/shared_impl/scoped_pp_var.h"
#include "ppapi/shared_impl/var.h"
#include "ppapi/shared_impl/var_tracker.h"
-#include "third_party/WebKit/public/web/WebDOMMessageEvent.h"
-#include "third_party/WebKit/public/web/WebPluginContainer.h"
+#include "third_party/blink/public/web/web_dom_message_event.h"
+#include "third_party/blink/public/web/web_plugin_container.h"
#include "v8/include/v8.h"
using ppapi::PpapiGlobals;
diff --git a/chromium/content/renderer/pepper/message_channel.h b/chromium/content/renderer/pepper/message_channel.h
index 41d6c9e6080..5d0c7e00a7a 100644
--- a/chromium/content/renderer/pepper/message_channel.h
+++ b/chromium/content/renderer/pepper/message_channel.h
@@ -17,7 +17,7 @@
#include "gin/wrappable.h"
#include "ppapi/proxy/host_dispatcher.h"
#include "ppapi/shared_impl/resource.h"
-#include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
+#include "third_party/blink/public/web/web_serialized_script_value.h"
#include "v8/include/v8-util.h"
#include "v8/include/v8.h"
diff --git a/chromium/content/renderer/pepper/pepper_compositor_host.cc b/chromium/content/renderer/pepper/pepper_compositor_host.cc
index a95a2984734..7bafb0143dc 100644
--- a/chromium/content/renderer/pepper/pepper_compositor_host.cc
+++ b/chromium/content/renderer/pepper/pepper_compositor_host.cc
@@ -320,13 +320,14 @@ void PepperCompositorHost::UpdateLayer(
->GetBitmapForSharedMemory(image_shm.get());
auto resource = viz::TransferableResource::MakeSoftware(
- bitmap->id(), bitmap->sequence_number(), PP_ToGfxSize(desc.size));
+ bitmap->id(), bitmap->sequence_number(), PP_ToGfxSize(desc.size),
+ viz::RGBA_8888);
image_layer->SetTransferableResource(
resource,
viz::SingleReleaseCallback::Create(base::BindOnce(
&PepperCompositorHost::ImageReleased, weak_factory_.GetWeakPtr(),
- new_layer->common.resource_id, base::Passed(&image_shm),
- base::Passed(&bitmap))));
+ new_layer->common.resource_id, std::move(image_shm),
+ std::move(bitmap))));
// TODO(penghuang): get a damage region from the application and
// pass it to SetNeedsDisplayRect().
image_layer->SetNeedsDisplay();
diff --git a/chromium/content/renderer/pepper/pepper_file_chooser_host.cc b/chromium/content/renderer/pepper/pepper_file_chooser_host.cc
index c305400f6f2..014049a6873 100644
--- a/chromium/content/renderer/pepper/pepper_file_chooser_host.cc
+++ b/chromium/content/renderer/pepper/pepper_file_chooser_host.cc
@@ -17,9 +17,9 @@
#include "ppapi/host/dispatch_host_message.h"
#include "ppapi/host/ppapi_host.h"
#include "ppapi/proxy/ppapi_messages.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebVector.h"
-#include "third_party/WebKit/public/web/WebFileChooserCompletion.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_vector.h"
+#include "third_party/blink/public/web/web_file_chooser_completion.h"
namespace content {
diff --git a/chromium/content/renderer/pepper/pepper_file_system_host.cc b/chromium/content/renderer/pepper/pepper_file_system_host.cc
index 75a255a52de..dcf0df79372 100644
--- a/chromium/content/renderer/pepper/pepper_file_system_host.cc
+++ b/chromium/content/renderer/pepper/pepper_file_system_host.cc
@@ -19,9 +19,9 @@
#include "ppapi/shared_impl/file_system_util.h"
#include "ppapi/shared_impl/file_type_conversion.h"
#include "storage/common/fileapi/file_system_util.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebView.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_view.h"
namespace content {
diff --git a/chromium/content/renderer/pepper/pepper_graphics_2d_host.cc b/chromium/content/renderer/pepper/pepper_graphics_2d_host.cc
index f8e5930c232..005c65438fe 100644
--- a/chromium/content/renderer/pepper/pepper_graphics_2d_host.cc
+++ b/chromium/content/renderer/pepper/pepper_graphics_2d_host.cc
@@ -17,9 +17,11 @@
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
#include "cc/paint/paint_flags.h"
-#include "components/viz/client/client_shared_bitmap_manager.h"
+#include "cc/resources/cross_thread_shared_bitmap.h"
#include "components/viz/common/gpu/context_provider.h"
#include "components/viz/common/quads/shared_bitmap.h"
+#include "components/viz/common/resources/bitmap_allocation.h"
+#include "components/viz/common/resources/resource_sizes.h"
#include "content/public/renderer/render_thread.h"
#include "content/public/renderer/renderer_ppapi_host.h"
#include "content/renderer/pepper/gfx_conversion.h"
@@ -325,7 +327,8 @@ bool PepperGraphics2DHost::BindToInstance(
new_instance->InvalidateRect(gfx::Rect());
}
- cached_bitmap_.reset();
+ cached_bitmap_ = nullptr;
+ cached_bitmap_registration_ = cc::SharedBitmapIdRegistration();
composited_output_modified_ = true;
bound_instance_ = new_instance;
@@ -407,7 +410,8 @@ gfx::Size PepperGraphics2DHost::Size() const {
}
void PepperGraphics2DHost::ClearCache() {
- cached_bitmap_.reset();
+ cached_bitmap_ = nullptr;
+ cached_bitmap_registration_ = cc::SharedBitmapIdRegistration();
}
int32_t PepperGraphics2DHost::OnHostMsgPaintImageData(
@@ -559,16 +563,18 @@ int32_t PepperGraphics2DHost::OnHostMsgReadImageData(
}
void PepperGraphics2DHost::ReleaseSoftwareCallback(
- std::unique_ptr<viz::SharedBitmap> bitmap,
- const gfx::Size& bitmap_size,
+ scoped_refptr<cc::CrossThreadSharedBitmap> bitmap,
+ cc::SharedBitmapIdRegistration registration,
const gpu::SyncToken& sync_token,
bool lost_resource) {
- cached_bitmap_.reset();
+ cached_bitmap_ = nullptr;
+ cached_bitmap_registration_ = cc::SharedBitmapIdRegistration();
// Only keep around a cached bitmap if the plugin is currently drawing (has
// need_flush_ack_ set).
- if (need_flush_ack_ && bound_instance_)
+ if (need_flush_ack_ && bound_instance_) {
cached_bitmap_ = std::move(bitmap);
- cached_bitmap_size_ = bitmap_size;
+ cached_bitmap_registration_ = std::move(registration);
+ }
}
// static
@@ -604,6 +610,7 @@ void PepperGraphics2DHost::ReleaseTextureCallback(
}
bool PepperGraphics2DHost::PrepareTransferableResource(
+ cc::SharedBitmapIdRegistrar* bitmap_registrar,
viz::TransferableResource* transferable_resource,
std::unique_ptr<viz::SingleReleaseCallback>* release_callback) {
// Reuse the |main_thread_context_| if it is not lost. If it is lost, we
@@ -750,30 +757,38 @@ bool PepperGraphics2DHost::PrepareTransferableResource(
}
gfx::Size pixel_image_size(image_data_->width(), image_data_->height());
- std::unique_ptr<viz::SharedBitmap> shared_bitmap;
+ scoped_refptr<cc::CrossThreadSharedBitmap> shared_bitmap;
+ cc::SharedBitmapIdRegistration registration;
if (cached_bitmap_) {
- if (cached_bitmap_size_ == pixel_image_size)
+ if (cached_bitmap_->size() == pixel_image_size) {
shared_bitmap = std::move(cached_bitmap_);
- else
- cached_bitmap_.reset();
+ registration = std::move(cached_bitmap_registration_);
+ } else {
+ cached_bitmap_ = nullptr;
+ cached_bitmap_registration_ = cc::SharedBitmapIdRegistration();
+ }
}
if (!shared_bitmap) {
- shared_bitmap = RenderThreadImpl::current()
- ->shared_bitmap_manager()
- ->AllocateSharedBitmap(pixel_image_size);
+ viz::SharedBitmapId id = viz::SharedBitmap::GenerateId();
+ std::unique_ptr<base::SharedMemory> shm =
+ viz::bitmap_allocation::AllocateMappedBitmap(pixel_image_size,
+ viz::RGBA_8888);
+ shared_bitmap = base::MakeRefCounted<cc::CrossThreadSharedBitmap>(
+ id, std::move(shm), pixel_image_size, viz::RGBA_8888);
+ registration = bitmap_registrar->RegisterSharedBitmapId(id, shared_bitmap);
}
- if (!shared_bitmap)
- return false;
void* src = image_data_->Map();
- memcpy(shared_bitmap->pixels(), src,
- viz::SharedBitmap::CheckedSizeInBytes(pixel_image_size));
+ memcpy(shared_bitmap->shared_memory()->memory(), src,
+ viz::ResourceSizes::CheckedSizeInBytes<size_t>(pixel_image_size,
+ viz::RGBA_8888));
image_data_->Unmap();
*transferable_resource = viz::TransferableResource::MakeSoftware(
- shared_bitmap->id(), shared_bitmap->sequence_number(), pixel_image_size);
+ shared_bitmap->id(), /*sequence_number=*/0, pixel_image_size,
+ viz::RGBA_8888);
*release_callback = viz::SingleReleaseCallback::Create(base::BindOnce(
&PepperGraphics2DHost::ReleaseSoftwareCallback, this->AsWeakPtr(),
- base::Passed(&shared_bitmap), pixel_image_size));
+ std::move(shared_bitmap), std::move(registration)));
composited_output_modified_ = false;
return true;
}
diff --git a/chromium/content/renderer/pepper/pepper_graphics_2d_host.h b/chromium/content/renderer/pepper/pepper_graphics_2d_host.h
index 069cd8de816..069a60c5a94 100644
--- a/chromium/content/renderer/pepper/pepper_graphics_2d_host.h
+++ b/chromium/content/renderer/pepper/pepper_graphics_2d_host.h
@@ -12,16 +12,21 @@
#include "base/compiler_specific.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
+#include "cc/resources/shared_bitmap_id_registrar.h"
#include "content/common/content_export.h"
#include "gpu/command_buffer/common/mailbox.h"
#include "ppapi/c/ppb_graphics_2d.h"
#include "ppapi/host/host_message_context.h"
#include "ppapi/host/resource_host.h"
-#include "third_party/WebKit/public/platform/WebCanvas.h"
+#include "third_party/blink/public/platform/web_canvas.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/size.h"
+namespace cc {
+class CrossThreadSharedBitmap;
+}
+
namespace gfx {
class Rect;
}
@@ -32,7 +37,6 @@ struct SyncToken;
namespace viz {
class ContextProvider;
-class SharedBitmap;
class SingleReleaseCallback;
struct TransferableResource;
}
@@ -75,6 +79,7 @@ class CONTENT_EXPORT PepperGraphics2DHost
const gfx::Rect& paint_rect);
bool PrepareTransferableResource(
+ cc::SharedBitmapIdRegistrar* bitmap_registrar,
viz::TransferableResource* transferable_resource,
std::unique_ptr<viz::SingleReleaseCallback>* release_callback);
void AttachedToNewLayer();
@@ -173,10 +178,11 @@ class CONTENT_EXPORT PepperGraphics2DHost
gfx::Point* delta);
// Callback when compositor is done with a software resource given to it.
- void ReleaseSoftwareCallback(std::unique_ptr<viz::SharedBitmap> bitmap,
- const gfx::Size& bitmap_size,
- const gpu::SyncToken& sync_token,
- bool lost_resource);
+ void ReleaseSoftwareCallback(
+ scoped_refptr<cc::CrossThreadSharedBitmap> bitmap,
+ cc::SharedBitmapIdRegistration registration,
+ const gpu::SyncToken& sync_token,
+ bool lost_resource);
// Callback when compositor is done with a gpu resource given to it. Static
// for speed. Just kidding, it's so this can clean up the texture if the host
// has been destroyed.
@@ -246,9 +252,11 @@ class CONTENT_EXPORT PepperGraphics2DHost
std::vector<TextureInfo> recycled_texture_copies_;
// This is a bitmap that was recently released by the compositor and may be
- // used to transfer bytes to the compositor again.
- std::unique_ptr<viz::SharedBitmap> cached_bitmap_;
- gfx::Size cached_bitmap_size_;
+ // used to transfer bytes to the compositor again, along with the registration
+ // of the SharedBitmapId that is kept alive as long as the bitmap is, in order
+ // to give the bitmap to the compositor.
+ scoped_refptr<cc::CrossThreadSharedBitmap> cached_bitmap_;
+ cc::SharedBitmapIdRegistration cached_bitmap_registration_;
friend class PepperGraphics2DHostTest;
DISALLOW_COPY_AND_ASSIGN(PepperGraphics2DHost);
diff --git a/chromium/content/renderer/pepper/pepper_media_device_manager.cc b/chromium/content/renderer/pepper/pepper_media_device_manager.cc
index e62a6e1f33b..2a1593afe48 100644
--- a/chromium/content/renderer/pepper/pepper_media_device_manager.cc
+++ b/chromium/content/renderer/pepper/pepper_media_device_manager.cc
@@ -15,7 +15,7 @@
#include "content/renderer/media/stream/media_stream_device_observer.h"
#include "content/renderer/pepper/renderer_ppapi_host_impl.h"
#include "content/renderer/render_frame_impl.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "ppapi/shared_impl/ppb_device_ref_shared.h"
#include "services/service_manager/public/cpp/interface_provider.h"
@@ -109,6 +109,7 @@ void PepperMediaDeviceManager::EnumerateDevices(
CHECK(request_audio_input || request_video_input || request_audio_output);
GetMediaDevicesDispatcher()->EnumerateDevices(
request_audio_input, request_video_input, request_audio_output,
+ false /* request_video_input_capabilities */,
base::BindOnce(&PepperMediaDeviceManager::DevicesEnumerated, AsWeakPtr(),
callback, ToMediaDeviceType(type)));
#else
@@ -271,13 +272,15 @@ void PepperMediaDeviceManager::OnDeviceOpened(int request_id,
OpenDeviceCallback callback = iter->second;
open_callbacks_.erase(iter);
- callback.Run(request_id, success, success ? label : std::string());
+ std::move(callback).Run(request_id, success, success ? label : std::string());
}
void PepperMediaDeviceManager::DevicesEnumerated(
const DevicesCallback& client_callback,
MediaDeviceType type,
- const std::vector<MediaDeviceInfoArray>& enumeration) {
+ const std::vector<MediaDeviceInfoArray>& enumeration,
+ std::vector<blink::mojom::VideoInputDeviceCapabilitiesPtr>
+ video_input_capabilities) {
client_callback.Run(FromMediaDeviceInfoArray(type, enumeration[type]));
}
diff --git a/chromium/content/renderer/pepper/pepper_media_device_manager.h b/chromium/content/renderer/pepper/pepper_media_device_manager.h
index 1367d35bcdd..dc9a19ee04a 100644
--- a/chromium/content/renderer/pepper/pepper_media_device_manager.h
+++ b/chromium/content/renderer/pepper/pepper_media_device_manager.h
@@ -19,7 +19,7 @@
#include "content/renderer/pepper/pepper_device_enumeration_host_helper.h"
#include "mojo/public/cpp/bindings/binding_set.h"
#include "ppapi/c/pp_instance.h"
-#include "third_party/WebKit/public/platform/modules/mediastream/media_devices.mojom.h"
+#include "third_party/blink/public/platform/modules/mediastream/media_devices.mojom.h"
namespace content {
class MediaStreamDeviceObserver;
@@ -86,9 +86,12 @@ class PepperMediaDeviceManager
const std::string& label,
const MediaStreamDevice& device);
- void DevicesEnumerated(const DevicesCallback& callback,
- MediaDeviceType type,
- const std::vector<MediaDeviceInfoArray>& enumeration);
+ void DevicesEnumerated(
+ const DevicesCallback& callback,
+ MediaDeviceType type,
+ const std::vector<MediaDeviceInfoArray>& enumeration,
+ std::vector<blink::mojom::VideoInputDeviceCapabilitiesPtr>
+ video_input_capabilities);
const mojom::MediaStreamDispatcherHostPtr& GetMediaStreamDispatcherHost();
MediaStreamDeviceObserver* GetMediaStreamDeviceObserver() const;
diff --git a/chromium/content/renderer/pepper/pepper_media_stream_audio_track_host.h b/chromium/content/renderer/pepper/pepper_media_stream_audio_track_host.h
index ab380d1fb83..862aa6274b1 100644
--- a/chromium/content/renderer/pepper/pepper_media_stream_audio_track_host.h
+++ b/chromium/content/renderer/pepper/pepper_media_stream_audio_track_host.h
@@ -20,7 +20,7 @@
#include "media/base/audio_parameters.h"
#include "ppapi/host/host_message_context.h"
#include "ppapi/shared_impl/media_stream_audio_track_shared.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
namespace base {
class SingleThreadTaskRunner;
diff --git a/chromium/content/renderer/pepper/pepper_media_stream_video_track_host.h b/chromium/content/renderer/pepper/pepper_media_stream_video_track_host.h
index e4e603c43cd..8d12264fa53 100644
--- a/chromium/content/renderer/pepper/pepper_media_stream_video_track_host.h
+++ b/chromium/content/renderer/pepper/pepper_media_stream_video_track_host.h
@@ -16,7 +16,7 @@
#include "media/base/video_frame.h"
#include "ppapi/c/ppb_video_frame.h"
#include "ppapi/shared_impl/media_stream_video_track_shared.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
#include "ui/gfx/geometry/size.h"
namespace content {
diff --git a/chromium/content/renderer/pepper/pepper_plugin_instance_impl.cc b/chromium/content/renderer/pepper/pepper_plugin_instance_impl.cc
index 88e7a2d45eb..1249b89a155 100644
--- a/chromium/content/renderer/pepper/pepper_plugin_instance_impl.cc
+++ b/chromium/content/renderer/pepper/pepper_plugin_instance_impl.cc
@@ -11,7 +11,6 @@
#include "base/callback_helpers.h"
#include "base/location.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
@@ -30,7 +29,6 @@
#include "content/public/common/content_constants.h"
#include "content/public/renderer/content_renderer_client.h"
#include "content/renderer/media/audio_device_factory.h"
-#include "content/renderer/pepper/content_decryptor_delegate.h"
#include "content/renderer/pepper/event_conversion.h"
#include "content/renderer/pepper/fullscreen_container.h"
#include "content/renderer/pepper/gfx_conversion.h"
@@ -95,36 +93,36 @@
#include "ppapi/shared_impl/var.h"
#include "ppapi/thunk/enter.h"
#include "ppapi/thunk/ppb_buffer_api.h"
-#include "printing/features/features.h"
+#include "printing/buildflags/buildflags.h"
#include "skia/ext/platform_canvas.h"
-#include "third_party/WebKit/public/platform/URLConversion.h"
-#include "third_party/WebKit/public/platform/WebCoalescedInputEvent.h"
-#include "third_party/WebKit/public/platform/WebCursorInfo.h"
-#include "third_party/WebKit/public/platform/WebFloatRect.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
-#include "third_party/WebKit/public/platform/WebKeyboardEvent.h"
-#include "third_party/WebKit/public/platform/WebMouseEvent.h"
-#include "third_party/WebKit/public/platform/WebPointerEvent.h"
-#include "third_party/WebKit/public/platform/WebRect.h"
-#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebTouchEvent.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
-#include "third_party/WebKit/public/platform/WebURLError.h"
-#include "third_party/WebKit/public/platform/WebURLRequest.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebDocumentLoader.h"
-#include "third_party/WebKit/public/web/WebImeTextSpan.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebPluginContainer.h"
-#include "third_party/WebKit/public/web/WebPluginScriptForbiddenScope.h"
-#include "third_party/WebKit/public/web/WebPrintParams.h"
-#include "third_party/WebKit/public/web/WebPrintPresetOptions.h"
-#include "third_party/WebKit/public/web/WebPrintScalingOption.h"
-#include "third_party/WebKit/public/web/WebScopedUserGesture.h"
-#include "third_party/WebKit/public/web/WebScriptSource.h"
-#include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
-#include "third_party/WebKit/public/web/WebView.h"
+#include "third_party/blink/public/platform/url_conversion.h"
+#include "third_party/blink/public/platform/web_coalesced_input_event.h"
+#include "third_party/blink/public/platform/web_cursor_info.h"
+#include "third_party/blink/public/platform/web_float_rect.h"
+#include "third_party/blink/public/platform/web_input_event.h"
+#include "third_party/blink/public/platform/web_keyboard_event.h"
+#include "third_party/blink/public/platform/web_mouse_event.h"
+#include "third_party/blink/public/platform/web_pointer_event.h"
+#include "third_party/blink/public/platform/web_rect.h"
+#include "third_party/blink/public/platform/web_security_origin.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_touch_event.h"
+#include "third_party/blink/public/platform/web_url.h"
+#include "third_party/blink/public/platform/web_url_error.h"
+#include "third_party/blink/public/platform/web_url_request.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_document_loader.h"
+#include "third_party/blink/public/web/web_ime_text_span.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_plugin_container.h"
+#include "third_party/blink/public/web/web_plugin_script_forbidden_scope.h"
+#include "third_party/blink/public/web/web_print_params.h"
+#include "third_party/blink/public/web/web_print_preset_options.h"
+#include "third_party/blink/public/web/web_print_scaling_option.h"
+#include "third_party/blink/public/web/web_scoped_user_gesture.h"
+#include "third_party/blink/public/web/web_script_source.h"
+#include "third_party/blink/public/web/web_user_gesture_indicator.h"
+#include "third_party/blink/public/web/web_view.h"
#include "third_party/khronos/GLES2/gl2.h"
#include "ui/events/blink/blink_event_util.h"
#include "ui/gfx/geometry/rect_conversions.h"
@@ -405,7 +403,7 @@ PepperPluginInstanceImpl* PepperPluginInstanceImpl::Create(
base::Callback<const void*(const char*)> get_plugin_interface_func =
base::Bind(&PluginModule::GetPluginInterface, module);
PPP_Instance_Combined* ppp_instance_combined =
- PPP_Instance_Combined::Create(get_plugin_interface_func);
+ PPP_Instance_Combined::Create(std::move(get_plugin_interface_func));
if (!ppp_instance_combined)
return nullptr;
@@ -855,11 +853,6 @@ void PepperPluginInstanceImpl::InstanceCrashed() {
BindGraphics(pp_instance(), 0);
InvalidateRect(gfx::Rect());
- if (content_decryptor_delegate_) {
- content_decryptor_delegate_->InstanceCrashed();
- content_decryptor_delegate_.reset();
- }
-
if (render_frame_)
render_frame_->PluginCrashed(module_->path(), module_->GetPeerProcessId());
UnSetAndDeleteLockTargetAdapter();
@@ -1031,7 +1024,8 @@ bool PepperPluginInstanceImpl::
// Set the composition target.
for (size_t i = 0; i < ime_text_spans.size(); ++i) {
- if (ime_text_spans[i].thick) {
+ if (ime_text_spans[i].thickness ==
+ ui::mojom::ImeTextSpanThickness::kThick) {
std::vector<uint32_t>::iterator it =
std::find(event.composition_segment_offsets.begin(),
event.composition_segment_offsets.end(),
@@ -1576,7 +1570,7 @@ void PepperPluginInstanceImpl::StopFind() {
}
bool PepperPluginInstanceImpl::LoadFindInterface() {
- if (!module_->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
+ if (!module_->permissions().HasPermission(ppapi::PERMISSION_PDF))
return false;
if (!plugin_find_interface_) {
plugin_find_interface_ = static_cast<const PPP_Find_Private*>(
@@ -2206,12 +2200,13 @@ void PepperPluginInstanceImpl::UpdateLayer(bool force_creation) {
}
bool PepperPluginInstanceImpl::PrepareTransferableResource(
+ cc::SharedBitmapIdRegistrar* bitmap_registrar,
viz::TransferableResource* transferable_resource,
std::unique_ptr<viz::SingleReleaseCallback>* release_callback) {
if (!bound_graphics_2d_platform_)
return false;
return bound_graphics_2d_platform_->PrepareTransferableResource(
- transferable_resource, release_callback);
+ bitmap_registrar, transferable_resource, release_callback);
}
void PepperPluginInstanceImpl::AccessibilityModeChanged() {
@@ -2357,7 +2352,7 @@ void PepperPluginInstanceImpl::SimulateImeSetCompositionEvent(
ime_text_span.start_offset = offsets[i];
ime_text_span.end_offset = offsets[i + 1];
if (input_event.composition_target_segment == static_cast<int32_t>(i - 2))
- ime_text_span.thick = true;
+ ime_text_span.thickness = ui::mojom::ImeTextSpanThickness::kThick;
ime_text_spans.push_back(ime_text_span);
}
@@ -2365,22 +2360,6 @@ void PepperPluginInstanceImpl::SimulateImeSetCompositionEvent(
offsets[0], offsets[1]);
}
-ContentDecryptorDelegate*
-PepperPluginInstanceImpl::GetContentDecryptorDelegate() {
- if (content_decryptor_delegate_)
- return content_decryptor_delegate_.get();
-
- const PPP_ContentDecryptor_Private* plugin_decryption_interface =
- static_cast<const PPP_ContentDecryptor_Private*>(
- module_->GetPluginInterface(PPP_CONTENTDECRYPTOR_PRIVATE_INTERFACE));
- if (!plugin_decryption_interface)
- return nullptr;
-
- content_decryptor_delegate_ = std::make_unique<ContentDecryptorDelegate>(
- pp_instance_, plugin_decryption_interface);
- return content_decryptor_delegate_.get();
-}
-
PP_Bool PepperPluginInstanceImpl::BindGraphics(PP_Instance instance,
PP_Resource device) {
TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::BindGraphics");
@@ -2582,128 +2561,6 @@ PP_Var PepperPluginInstanceImpl::GetDefaultCharSet(PP_Instance instance) {
render_frame_->render_view()->webkit_preferences().default_encoding);
}
-// These PPB_ContentDecryptor_Private calls are responses to
-// PPP_ContentDecryptor_Private calls made on |content_decryptor_delegate_|.
-// Therefore, |content_decryptor_delegate_| must have been initialized when
-// the following methods are called.
-void PepperPluginInstanceImpl::PromiseResolved(PP_Instance instance,
- uint32_t promise_id) {
- content_decryptor_delegate_->OnPromiseResolved(promise_id);
-}
-
-void PepperPluginInstanceImpl::PromiseResolvedWithKeyStatus(
- PP_Instance instance,
- uint32_t promise_id,
- PP_CdmKeyStatus key_status) {
- content_decryptor_delegate_->OnPromiseResolvedWithKeyStatus(promise_id,
- key_status);
-}
-
-void PepperPluginInstanceImpl::PromiseResolvedWithSession(
- PP_Instance instance,
- uint32_t promise_id,
- PP_Var session_id_var) {
- content_decryptor_delegate_->OnPromiseResolvedWithSession(promise_id,
- session_id_var);
-}
-
-void PepperPluginInstanceImpl::PromiseRejected(
- PP_Instance instance,
- uint32_t promise_id,
- PP_CdmExceptionCode exception_code,
- uint32_t system_code,
- PP_Var error_description_var) {
- content_decryptor_delegate_->OnPromiseRejected(
- promise_id, exception_code, system_code, error_description_var);
-}
-
-void PepperPluginInstanceImpl::SessionMessage(PP_Instance instance,
- PP_Var session_id_var,
- PP_CdmMessageType message_type,
- PP_Var message_var,
- PP_Var legacy_destination_url) {
- // |legacy_destination_url| is obsolete.
- content_decryptor_delegate_->OnSessionMessage(session_id_var, message_type,
- message_var);
-}
-
-void PepperPluginInstanceImpl::SessionKeysChange(
- PP_Instance instance,
- PP_Var session_id_var,
- PP_Bool has_additional_usable_key,
- uint32_t key_count,
- const struct PP_KeyInformation key_information[]) {
- content_decryptor_delegate_->OnSessionKeysChange(
- session_id_var, has_additional_usable_key, key_count, key_information);
-}
-
-void PepperPluginInstanceImpl::SessionExpirationChange(
- PP_Instance instance,
- PP_Var session_id_var,
- PP_Time new_expiry_time) {
- content_decryptor_delegate_->OnSessionExpirationChange(session_id_var,
- new_expiry_time);
-}
-
-void PepperPluginInstanceImpl::SessionClosed(PP_Instance instance,
- PP_Var session_id_var) {
- content_decryptor_delegate_->OnSessionClosed(session_id_var);
-}
-
-void PepperPluginInstanceImpl::LegacySessionError(
- PP_Instance instance,
- PP_Var session_id_var,
- PP_CdmExceptionCode exception_code,
- uint32_t system_code,
- PP_Var error_description_var) {
- // Obsolete.
-}
-
-void PepperPluginInstanceImpl::DeliverBlock(
- PP_Instance instance,
- PP_Resource decrypted_block,
- const PP_DecryptedBlockInfo* block_info) {
- content_decryptor_delegate_->DeliverBlock(decrypted_block, block_info);
-}
-
-void PepperPluginInstanceImpl::DecoderInitializeDone(
- PP_Instance instance,
- PP_DecryptorStreamType decoder_type,
- uint32_t request_id,
- PP_Bool success) {
- content_decryptor_delegate_->DecoderInitializeDone(
- decoder_type, request_id, success);
-}
-
-void PepperPluginInstanceImpl::DecoderDeinitializeDone(
- PP_Instance instance,
- PP_DecryptorStreamType decoder_type,
- uint32_t request_id) {
- content_decryptor_delegate_->DecoderDeinitializeDone(decoder_type,
- request_id);
-}
-
-void PepperPluginInstanceImpl::DecoderResetDone(
- PP_Instance instance,
- PP_DecryptorStreamType decoder_type,
- uint32_t request_id) {
- content_decryptor_delegate_->DecoderResetDone(decoder_type, request_id);
-}
-
-void PepperPluginInstanceImpl::DeliverFrame(
- PP_Instance instance,
- PP_Resource decrypted_frame,
- const PP_DecryptedFrameInfo* frame_info) {
- content_decryptor_delegate_->DeliverFrame(decrypted_frame, frame_info);
-}
-
-void PepperPluginInstanceImpl::DeliverSamples(
- PP_Instance instance,
- PP_Resource audio_frames,
- const PP_DecryptedSampleInfo* sample_info) {
- content_decryptor_delegate_->DeliverSamples(audio_frames, sample_info);
-}
-
void PepperPluginInstanceImpl::SetPluginToHandleFindRequests(
PP_Instance instance) {
if (!LoadFindInterface())
@@ -3076,7 +2933,7 @@ PP_ExternalPluginResult PepperPluginInstanceImpl::ResetAsProxied(
base::Callback<const void*(const char*)> get_plugin_interface_func =
base::Bind(&PluginModule::GetPluginInterface, module_);
PPP_Instance_Combined* ppp_instance_combined =
- PPP_Instance_Combined::Create(get_plugin_interface_func);
+ PPP_Instance_Combined::Create(std::move(get_plugin_interface_func));
if (!ppp_instance_combined) {
// The proxy must support at least one usable PPP_Instance interface.
// While this could be a failure to implement the interface in the NaCl
diff --git a/chromium/content/renderer/pepper/pepper_plugin_instance_impl.h b/chromium/content/renderer/pepper/pepper_plugin_instance_impl.h
index 5c3b02a7989..c1819eb3ab6 100644
--- a/chromium/content/renderer/pepper/pepper_plugin_instance_impl.h
+++ b/chromium/content/renderer/pepper/pepper_plugin_instance_impl.h
@@ -46,7 +46,6 @@
#include "ppapi/c/ppp_graphics_3d.h"
#include "ppapi/c/ppp_input_event.h"
#include "ppapi/c/ppp_mouse_lock.h"
-#include "ppapi/c/private/ppb_content_decryptor_private.h"
#include "ppapi/c/private/ppp_find_private.h"
#include "ppapi/c/private/ppp_instance_private.h"
#include "ppapi/c/private/ppp_pdf.h"
@@ -56,12 +55,12 @@
#include "ppapi/shared_impl/tracked_callback.h"
#include "ppapi/thunk/ppb_gamepad_api.h"
#include "ppapi/thunk/resource_creation_api.h"
-#include "third_party/WebKit/public/platform/WebCanvas.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebURLResponse.h"
-#include "third_party/WebKit/public/web/WebAssociatedURLLoaderClient.h"
-#include "third_party/WebKit/public/web/WebPlugin.h"
-#include "third_party/WebKit/public/web/WebUserGestureToken.h"
+#include "third_party/blink/public/platform/web_canvas.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_url_response.h"
+#include "third_party/blink/public/web/web_associated_url_loader_client.h"
+#include "third_party/blink/public/web/web_plugin.h"
+#include "third_party/blink/public/web/web_user_gesture_token.h"
#include "ui/base/ime/text_input_type.h"
#include "ui/gfx/geometry/rect.h"
#include "url/gurl.h"
@@ -107,7 +106,6 @@ class PdfMetafileSkia;
namespace content {
-class ContentDecryptorDelegate;
class FullscreenContainer;
class MessageChannel;
class PepperAudioController;
@@ -383,8 +381,6 @@ class CONTENT_EXPORT PepperPluginInstanceImpl
document_loader_ = loader;
}
- ContentDecryptorDelegate* GetContentDecryptorDelegate();
-
void SetGraphics2DTransform(const float& scale,
const gfx::PointF& translation);
@@ -490,59 +486,6 @@ class CONTENT_EXPORT PepperPluginInstanceImpl
PP_Var GetPluginReferrerURL(PP_Instance instance,
PP_URLComponents_Dev* components) override;
- // PPB_ContentDecryptor_Private implementation.
- void PromiseResolved(PP_Instance instance, uint32_t promise_id) override;
- void PromiseResolvedWithKeyStatus(PP_Instance instance,
- uint32_t promise_id,
- PP_CdmKeyStatus key_status) override;
- void PromiseResolvedWithSession(PP_Instance instance,
- uint32_t promise_id,
- PP_Var session_id_var) override;
- void PromiseRejected(PP_Instance instance,
- uint32_t promise_id,
- PP_CdmExceptionCode exception_code,
- uint32_t system_code,
- PP_Var error_description_var) override;
- void SessionMessage(PP_Instance instance,
- PP_Var session_id_var,
- PP_CdmMessageType message_type,
- PP_Var message_var,
- PP_Var legacy_destination_url) override;
- void SessionKeysChange(
- PP_Instance instance,
- PP_Var session_id_var,
- PP_Bool has_additional_usable_key,
- uint32_t key_count,
- const struct PP_KeyInformation key_information[]) override;
- void SessionExpirationChange(PP_Instance instance,
- PP_Var session_id_var,
- PP_Time new_expiry_time) override;
- void SessionClosed(PP_Instance instance, PP_Var session_id_var) override;
- void LegacySessionError(PP_Instance instance,
- PP_Var session_id_var,
- PP_CdmExceptionCode exception_code,
- uint32_t system_code,
- PP_Var error_description_var) override;
- void DeliverBlock(PP_Instance instance,
- PP_Resource decrypted_block,
- const PP_DecryptedBlockInfo* block_info) override;
- void DecoderInitializeDone(PP_Instance instance,
- PP_DecryptorStreamType decoder_type,
- uint32_t request_id,
- PP_Bool success) override;
- void DecoderDeinitializeDone(PP_Instance instance,
- PP_DecryptorStreamType decoder_type,
- uint32_t request_id) override;
- void DecoderResetDone(PP_Instance instance,
- PP_DecryptorStreamType decoder_type,
- uint32_t request_id) override;
- void DeliverFrame(PP_Instance instance,
- PP_Resource decrypted_frame,
- const PP_DecryptedFrameInfo* frame_info) override;
- void DeliverSamples(PP_Instance instance,
- PP_Resource audio_frames,
- const PP_DecryptedSampleInfo* sample_info) override;
-
// Reset this instance as proxied. Assigns the instance a new module, resets
// cached interfaces to point to the out-of-process proxy and re-sends
// DidCreate, DidChangeView, and HandleDocumentLoad (if necessary).
@@ -559,6 +502,7 @@ class CONTENT_EXPORT PepperPluginInstanceImpl
// cc::TextureLayerClient implementation.
bool PrepareTransferableResource(
+ cc::SharedBitmapIdRegistrar* bitmap_registrar,
viz::TransferableResource* transferable_resource,
std::unique_ptr<viz::SingleReleaseCallback>* release_callback) override;
@@ -942,10 +886,6 @@ class CONTENT_EXPORT PepperPluginInstanceImpl
std::unique_ptr<ExternalDocumentLoader> external_document_loader_;
bool external_document_load_;
- // The ContentDecryptorDelegate forwards PPP_ContentDecryptor_Private
- // calls and handles PPB_ContentDecryptor_Private calls.
- std::unique_ptr<ContentDecryptorDelegate> content_decryptor_delegate_;
-
// The link currently under the cursor.
base::string16 link_under_cursor_;
diff --git a/chromium/content/renderer/pepper/pepper_plugin_registry.cc b/chromium/content/renderer/pepper/pepper_plugin_registry.cc
index b91ba72ed35..6a885b4b1fa 100644
--- a/chromium/content/renderer/pepper/pepper_plugin_registry.cc
+++ b/chromium/content/renderer/pepper/pepper_plugin_registry.cc
@@ -45,8 +45,11 @@ const PepperPluginInfo* PepperPluginRegistry::GetInfoForPlugin(
return &plugin_list_.back();
}
-PluginModule* PepperPluginRegistry::GetLiveModule(const base::FilePath& path) {
- NonOwningModuleMap::iterator module_iter = live_modules_.find(path);
+PluginModule* PepperPluginRegistry::GetLiveModule(
+ const base::FilePath& path,
+ const base::Optional<url::Origin>& origin_lock) {
+ NonOwningModuleMap::iterator module_iter =
+ live_modules_.find({path, origin_lock});
if (module_iter == live_modules_.end())
return nullptr;
@@ -71,10 +74,12 @@ PluginModule* PepperPluginRegistry::GetLiveModule(const base::FilePath& path) {
return nullptr;
}
-void PepperPluginRegistry::AddLiveModule(const base::FilePath& path,
- PluginModule* module) {
- DCHECK(live_modules_.find(path) == live_modules_.end());
- live_modules_[path] = module;
+void PepperPluginRegistry::AddLiveModule(
+ const base::FilePath& path,
+ const base::Optional<url::Origin>& origin_lock,
+ PluginModule* module) {
+ DCHECK(live_modules_.find({path, origin_lock}) == live_modules_.end());
+ live_modules_[{path, origin_lock}] = module;
}
void PepperPluginRegistry::PluginModuleDead(PluginModule* dead_module) {
@@ -122,7 +127,7 @@ void PepperPluginRegistry::Initialize() {
current.version,
current.path,
ppapi::PpapiPermissions(current.permissions));
- AddLiveModule(current.path, module.get());
+ AddLiveModule(current.path, base::Optional<url::Origin>(), module.get());
if (current.is_internal) {
if (!module->InitAsInternalPlugin(current.internal_entry_points)) {
DVLOG(1) << "Failed to load pepper module: " << current.path.value();
diff --git a/chromium/content/renderer/pepper/pepper_plugin_registry.h b/chromium/content/renderer/pepper/pepper_plugin_registry.h
index ca53407812c..67a294190b7 100644
--- a/chromium/content/renderer/pepper/pepper_plugin_registry.h
+++ b/chromium/content/renderer/pepper/pepper_plugin_registry.h
@@ -10,7 +10,9 @@
#include "base/macros.h"
#include "base/memory/ref_counted.h"
+#include "base/optional.h"
#include "content/public/common/pepper_plugin_info.h"
+#include "url/origin.h"
namespace content {
class PluginModule;
@@ -34,15 +36,20 @@ class PepperPluginRegistry {
// Returns an existing loaded module for the given path. It will search for
// both preloaded in-process or currently active (non crashed) out-of-process
- // plugins matching the given name. Returns NULL if the plugin hasn't been
- // loaded.
- PluginModule* GetLiveModule(const base::FilePath& path);
+ // plugins matching the given name (and origin if supplied). Returns NULL if
+ // the plugin hasn't been loaded.
+ PluginModule* GetLiveModule(const base::FilePath& path,
+ const base::Optional<url::Origin>& origin_lock);
// Notifies the registry that a new non-preloaded module has been created.
// This is normally called for out-of-process plugins. Once this is called,
// the module is available to be returned by GetModule(). The module will
// automatically unregister itself by calling PluginModuleDestroyed().
- void AddLiveModule(const base::FilePath& path, PluginModule* module);
+ // |origin_lock| is used to segregate plugins by origin, omitted if the
+ // plugin is to handle content from all origins.
+ void AddLiveModule(const base::FilePath& path,
+ const base::Optional<url::Origin>& origin_lock,
+ PluginModule* module);
void PluginModuleDead(PluginModule* dead_module);
@@ -65,7 +72,9 @@ class PepperPluginRegistry {
// non-crashed modules. If an out-of-process module crashes, it may
// continue as long as there are WebKit references to it, but it will not
// appear in this list.
- typedef std::map<base::FilePath, PluginModule*> NonOwningModuleMap;
+ using NonOwningModuleMap =
+ std::map<std::pair<base::FilePath, base::Optional<url::Origin>>,
+ PluginModule*>;
NonOwningModuleMap live_modules_;
DISALLOW_COPY_AND_ASSIGN(PepperPluginRegistry);
diff --git a/chromium/content/renderer/pepper/pepper_url_loader_host.cc b/chromium/content/renderer/pepper/pepper_url_loader_host.cc
index 7fd6ab04687..269ac2300e0 100644
--- a/chromium/content/renderer/pepper/pepper_url_loader_host.cc
+++ b/chromium/content/renderer/pepper/pepper_url_loader_host.cc
@@ -6,7 +6,6 @@
#include <stddef.h>
-#include "base/memory/ptr_util.h"
#include "content/renderer/pepper/pepper_plugin_instance_impl.h"
#include "content/renderer/pepper/renderer_ppapi_host_impl.h"
#include "content/renderer/pepper/url_request_info_util.h"
@@ -18,17 +17,17 @@
#include "ppapi/host/ppapi_host.h"
#include "ppapi/proxy/ppapi_messages.h"
#include "ppapi/shared_impl/ppapi_globals.h"
-#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
-#include "third_party/WebKit/public/platform/WebURLError.h"
-#include "third_party/WebKit/public/platform/WebURLRequest.h"
-#include "third_party/WebKit/public/platform/WebURLResponse.h"
-#include "third_party/WebKit/public/web/WebAssociatedURLLoader.h"
-#include "third_party/WebKit/public/web/WebAssociatedURLLoaderOptions.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebElement.h"
-#include "third_party/WebKit/public/web/WebKit.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebPluginContainer.h"
+#include "third_party/blink/public/platform/web_security_origin.h"
+#include "third_party/blink/public/platform/web_url_error.h"
+#include "third_party/blink/public/platform/web_url_request.h"
+#include "third_party/blink/public/platform/web_url_response.h"
+#include "third_party/blink/public/web/blink.h"
+#include "third_party/blink/public/web/web_associated_url_loader.h"
+#include "third_party/blink/public/web/web_associated_url_loader_options.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_element.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_plugin_container.h"
using blink::WebAssociatedURLLoader;
using blink::WebAssociatedURLLoaderOptions;
@@ -309,11 +308,13 @@ int32_t PepperURLLoaderHost::OnHostMsgClose(
int32_t PepperURLLoaderHost::OnHostMsgGrantUniversalAccess(
ppapi::host::HostMessageContext* context) {
- // Only plugins with private permission can bypass same origin.
- if (!host()->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
- return PP_ERROR_FAILED;
- has_universal_access_ = true;
- return PP_OK;
+ // Only plugins with permission can bypass same origin.
+ if (host()->permissions().HasPermission(ppapi::PERMISSION_PDF) ||
+ host()->permissions().HasPermission(ppapi::PERMISSION_FLASH)) {
+ has_universal_access_ = true;
+ return PP_OK;
+ }
+ return PP_ERROR_FAILED;
}
void PepperURLLoaderHost::SendUpdateToPlugin(
diff --git a/chromium/content/renderer/pepper/pepper_url_loader_host.h b/chromium/content/renderer/pepper/pepper_url_loader_host.h
index 0181b7f5f65..a6ccb12b85e 100644
--- a/chromium/content/renderer/pepper/pepper_url_loader_host.h
+++ b/chromium/content/renderer/pepper/pepper_url_loader_host.h
@@ -17,7 +17,7 @@
#include "ppapi/proxy/resource_message_params.h"
#include "ppapi/shared_impl/url_request_info_data.h"
#include "ppapi/shared_impl/url_response_info_data.h"
-#include "third_party/WebKit/public/web/WebAssociatedURLLoaderClient.h"
+#include "third_party/blink/public/web/web_associated_url_loader_client.h"
namespace blink {
class WebAssociatedURLLoader;
diff --git a/chromium/content/renderer/pepper/pepper_url_request_unittest.cc b/chromium/content/renderer/pepper/pepper_url_request_unittest.cc
index fb49064e889..3d35e16725c 100644
--- a/chromium/content/renderer/pepper/pepper_url_request_unittest.cc
+++ b/chromium/content/renderer/pepper/pepper_url_request_unittest.cc
@@ -13,10 +13,10 @@
#include "ppapi/shared_impl/url_request_info_data.h"
#include "ppapi/thunk/thunk.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebURLRequest.h"
-#include "third_party/WebKit/public/web/WebFrameClient.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebView.h"
+#include "third_party/blink/public/platform/web_url_request.h"
+#include "third_party/blink/public/web/web_frame_client.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_view.h"
// This test is a end-to-end test from the resource to the WebKit request
// object. The actual resource implementation is so simple, it makes sense to
diff --git a/chromium/content/renderer/pepper/pepper_video_encoder_host.cc b/chromium/content/renderer/pepper/pepper_video_encoder_host.cc
index e696e2fcf0d..913820c20f3 100644
--- a/chromium/content/renderer/pepper/pepper_video_encoder_host.cc
+++ b/chromium/content/renderer/pepper/pepper_video_encoder_host.cc
@@ -7,7 +7,6 @@
#include <utility>
#include "base/bind.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/shared_memory.h"
#include "base/numerics/safe_math.h"
#include "base/threading/thread_task_runner_handle.h"
diff --git a/chromium/content/renderer/pepper/pepper_webplugin_impl.cc b/chromium/content/renderer/pepper/pepper_webplugin_impl.cc
index f3a35913d68..a45960809f5 100644
--- a/chromium/content/renderer/pepper/pepper_webplugin_impl.cc
+++ b/chromium/content/renderer/pepper/pepper_webplugin_impl.cc
@@ -22,20 +22,20 @@
#include "content/renderer/renderer_blink_platform_impl.h"
#include "ppapi/shared_impl/ppapi_globals.h"
#include "ppapi/shared_impl/var_tracker.h"
-#include "third_party/WebKit/public/platform/WebClipboard.h"
-#include "third_party/WebKit/public/platform/WebCoalescedInputEvent.h"
-#include "third_party/WebKit/public/platform/WebPoint.h"
-#include "third_party/WebKit/public/platform/WebRect.h"
-#include "third_party/WebKit/public/platform/WebSize.h"
-#include "third_party/WebKit/public/web/WebAssociatedURLLoaderClient.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebElement.h"
-#include "third_party/WebKit/public/web/WebFrame.h"
-#include "third_party/WebKit/public/web/WebPluginContainer.h"
-#include "third_party/WebKit/public/web/WebPluginParams.h"
-#include "third_party/WebKit/public/web/WebPrintParams.h"
-#include "third_party/WebKit/public/web/WebPrintPresetOptions.h"
-#include "third_party/WebKit/public/web/WebPrintScalingOption.h"
+#include "third_party/blink/public/platform/web_clipboard.h"
+#include "third_party/blink/public/platform/web_coalesced_input_event.h"
+#include "third_party/blink/public/platform/web_point.h"
+#include "third_party/blink/public/platform/web_rect.h"
+#include "third_party/blink/public/platform/web_size.h"
+#include "third_party/blink/public/web/web_associated_url_loader_client.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_element.h"
+#include "third_party/blink/public/web/web_frame.h"
+#include "third_party/blink/public/web/web_plugin_container.h"
+#include "third_party/blink/public/web/web_plugin_params.h"
+#include "third_party/blink/public/web/web_print_params.h"
+#include "third_party/blink/public/web/web_print_preset_options.h"
+#include "third_party/blink/public/web/web_print_scaling_option.h"
#include "url/gurl.h"
using ppapi::V8ObjectVar;
diff --git a/chromium/content/renderer/pepper/pepper_webplugin_impl.h b/chromium/content/renderer/pepper/pepper_webplugin_impl.h
index a6beea2747b..a53cb887bcf 100644
--- a/chromium/content/renderer/pepper/pepper_webplugin_impl.h
+++ b/chromium/content/renderer/pepper/pepper_webplugin_impl.h
@@ -13,7 +13,7 @@
#include "base/memory/weak_ptr.h"
#include "base/sequenced_task_runner_helpers.h"
#include "ppapi/c/pp_var.h"
-#include "third_party/WebKit/public/web/WebPlugin.h"
+#include "third_party/blink/public/web/web_plugin.h"
#include "ui/gfx/geometry/rect.h"
namespace blink {
diff --git a/chromium/content/renderer/pepper/pepper_webplugin_impl_browsertest.cc b/chromium/content/renderer/pepper/pepper_webplugin_impl_browsertest.cc
index 71c7f582968..36cbdd9bd3e 100644
--- a/chromium/content/renderer/pepper/pepper_webplugin_impl_browsertest.cc
+++ b/chromium/content/renderer/pepper/pepper_webplugin_impl_browsertest.cc
@@ -26,7 +26,7 @@
#include "ppapi/c/ppb_instance.h"
#include "ppapi/c/ppp_instance.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "third_party/blink/public/web/web_local_frame.h"
namespace content {
namespace {
diff --git a/chromium/content/renderer/pepper/pepper_websocket_host.cc b/chromium/content/renderer/pepper/pepper_websocket_host.cc
index 7d808410077..0a8e50abe68 100644
--- a/chromium/content/renderer/pepper/pepper_websocket_host.cc
+++ b/chromium/content/renderer/pepper/pepper_websocket_host.cc
@@ -14,11 +14,11 @@
#include "ppapi/host/host_message_context.h"
#include "ppapi/host/ppapi_host.h"
#include "ppapi/proxy/ppapi_messages.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
-#include "third_party/WebKit/public/web/WebArrayBuffer.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebPluginContainer.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_url.h"
+#include "third_party/blink/public/web/web_array_buffer.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_plugin_container.h"
using blink::WebArrayBuffer;
using blink::WebDocument;
diff --git a/chromium/content/renderer/pepper/pepper_websocket_host.h b/chromium/content/renderer/pepper/pepper_websocket_host.h
index dfeafcf1808..3c0699d27af 100644
--- a/chromium/content/renderer/pepper/pepper_websocket_host.h
+++ b/chromium/content/renderer/pepper/pepper_websocket_host.h
@@ -16,8 +16,8 @@
#include "ppapi/host/host_message_context.h"
#include "ppapi/host/resource_host.h"
#include "ppapi/proxy/resource_message_params.h"
-#include "third_party/WebKit/public/web/WebPepperSocket.h"
-#include "third_party/WebKit/public/web/WebPepperSocketClient.h"
+#include "third_party/blink/public/web/web_pepper_socket.h"
+#include "third_party/blink/public/web/web_pepper_socket_client.h"
namespace content {
diff --git a/chromium/content/renderer/pepper/plugin_instance_throttler_impl.cc b/chromium/content/renderer/pepper/plugin_instance_throttler_impl.cc
index 3c253220a15..867efb30634 100644
--- a/chromium/content/renderer/pepper/plugin_instance_throttler_impl.cc
+++ b/chromium/content/renderer/pepper/plugin_instance_throttler_impl.cc
@@ -12,12 +12,12 @@
#include "content/renderer/pepper/pepper_plugin_instance_impl.h"
#include "content/renderer/render_frame_impl.h"
#include "ppapi/shared_impl/ppapi_constants.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
-#include "third_party/WebKit/public/platform/WebRect.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebPluginContainer.h"
-#include "third_party/WebKit/public/web/WebPluginParams.h"
-#include "third_party/WebKit/public/web/WebView.h"
+#include "third_party/blink/public/platform/web_input_event.h"
+#include "third_party/blink/public/platform/web_rect.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_plugin_container.h"
+#include "third_party/blink/public/web/web_plugin_params.h"
+#include "third_party/blink/public/web/web_view.h"
#include "ui/gfx/color_utils.h"
#include "url/origin.h"
diff --git a/chromium/content/renderer/pepper/plugin_instance_throttler_impl_unittest.cc b/chromium/content/renderer/pepper/plugin_instance_throttler_impl_unittest.cc
index 2f04d788823..8dfd8c37cbe 100644
--- a/chromium/content/renderer/pepper/plugin_instance_throttler_impl_unittest.cc
+++ b/chromium/content/renderer/pepper/plugin_instance_throttler_impl_unittest.cc
@@ -15,9 +15,9 @@
#include "skia/ext/platform_canvas.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
-#include "third_party/WebKit/public/platform/WebMouseEvent.h"
-#include "third_party/WebKit/public/web/WebPluginParams.h"
+#include "third_party/blink/public/platform/web_input_event.h"
+#include "third_party/blink/public/platform/web_mouse_event.h"
+#include "third_party/blink/public/web/web_plugin_params.h"
#include "ui/events/base_event_utils.h"
#include "ui/gfx/canvas.h"
#include "url/gurl.h"
diff --git a/chromium/content/renderer/pepper/plugin_module.cc b/chromium/content/renderer/pepper/plugin_module.cc
index 5d2e3f264d0..8659dd80113 100644
--- a/chromium/content/renderer/pepper/plugin_module.cc
+++ b/chromium/content/renderer/pepper/plugin_module.cc
@@ -122,9 +122,7 @@
#include "ppapi/c/private/ppb_host_resolver_private.h"
#include "ppapi/c/private/ppb_instance_private.h"
#include "ppapi/c/private/ppb_isolated_file_system_private.h"
-#include "ppapi/c/private/ppb_output_protection_private.h"
#include "ppapi/c/private/ppb_pdf.h"
-#include "ppapi/c/private/ppb_platform_verification_private.h"
#include "ppapi/c/private/ppb_proxy_private.h"
#include "ppapi/c/private/ppb_tcp_server_socket_private.h"
#include "ppapi/c/private/ppb_tcp_socket_private.h"
@@ -406,6 +404,7 @@ const void* InternalGetInterface(const char* name) {
#include "ppapi/thunk/interfaces_ppb_private.h"
#include "ppapi/thunk/interfaces_ppb_private_flash.h"
#include "ppapi/thunk/interfaces_ppb_private_no_permissions.h"
+#include "ppapi/thunk/interfaces_ppb_private_pdf.h"
#include "ppapi/thunk/interfaces_ppb_public_dev.h"
#include "ppapi/thunk/interfaces_ppb_public_dev_channel.h"
#include "ppapi/thunk/interfaces_ppb_public_stable.h"
@@ -774,13 +773,14 @@ bool PluginModule::InitializeModule(
scoped_refptr<PluginModule> PluginModule::Create(
RenderFrameImpl* render_frame,
const WebPluginInfo& webplugin_info,
+ const base::Optional<url::Origin>& origin_lock,
bool* pepper_plugin_was_registered) {
*pepper_plugin_was_registered = true;
// See if a module has already been loaded for this plugin.
base::FilePath path(webplugin_info.path);
scoped_refptr<PluginModule> module =
- PepperPluginRegistry::GetInstance()->GetLiveModule(path);
+ PepperPluginRegistry::GetInstance()->GetLiveModule(path, origin_lock);
if (module.get()) {
if (!module->renderer_ppapi_host()) {
// If the module exists and no embedder state was associated with it,
@@ -809,7 +809,7 @@ scoped_refptr<PluginModule> PluginModule::Create(
base::ProcessId peer_pid = 0;
int plugin_child_id = 0;
render_frame->Send(new FrameHostMsg_OpenChannelToPepperPlugin(
- path, &channel_handle, &peer_pid, &plugin_child_id));
+ path, origin_lock, &channel_handle, &peer_pid, &plugin_child_id));
if (!channel_handle.is_mojo_channel_handle()) {
// Couldn't be initialized.
return scoped_refptr<PluginModule>();
@@ -820,7 +820,8 @@ scoped_refptr<PluginModule> PluginModule::Create(
// AddLiveModule must be called before any early returns since the
// module's destructor will remove itself.
module = new PluginModule(info->name, info->version, path, permissions);
- PepperPluginRegistry::GetInstance()->AddLiveModule(path, module.get());
+ PepperPluginRegistry::GetInstance()->AddLiveModule(path, origin_lock,
+ module.get());
if (!module->CreateOutOfProcessModule(render_frame,
path,
diff --git a/chromium/content/renderer/pepper/plugin_module.h b/chromium/content/renderer/pepper/plugin_module.h
index 41401d9c6ad..a8dcfab07ca 100644
--- a/chromium/content/renderer/pepper/plugin_module.h
+++ b/chromium/content/renderer/pepper/plugin_module.h
@@ -15,6 +15,7 @@
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/native_library.h"
+#include "base/optional.h"
#include "base/process/process.h"
#include "content/common/content_export.h"
#include "content/public/common/pepper_plugin_info.h"
@@ -23,6 +24,7 @@
#include "ppapi/c/ppb_core.h"
#include "ppapi/c/private/ppb_instance_private.h"
#include "ppapi/shared_impl/ppapi_permissions.h"
+#include "url/origin.h"
typedef void* NPIdentifier;
@@ -210,9 +212,11 @@ class CONTENT_EXPORT PluginModule : public base::RefCounted<PluginModule>,
// the second is that the plugin failed to initialize. In this case,
// |*pepper_plugin_was_registered| will be set to true and the caller should
// not fall back on any other plugin types.
- static scoped_refptr<PluginModule> Create(RenderFrameImpl* render_frame,
- const WebPluginInfo& webplugin_info,
- bool* pepper_plugin_was_registered);
+ static scoped_refptr<PluginModule> Create(
+ RenderFrameImpl* render_frame,
+ const WebPluginInfo& webplugin_info,
+ const base::Optional<url::Origin>& origin_lock,
+ bool* pepper_plugin_was_registered);
private:
friend class base::RefCounted<PluginModule>;
diff --git a/chromium/content/renderer/pepper/plugin_power_saver_helper.cc b/chromium/content/renderer/pepper/plugin_power_saver_helper.cc
index 2556c80423e..b16d1e11e3e 100644
--- a/chromium/content/renderer/pepper/plugin_power_saver_helper.cc
+++ b/chromium/content/renderer/pepper/plugin_power_saver_helper.cc
@@ -17,7 +17,7 @@
#include "content/public/renderer/render_frame.h"
#include "content/renderer/peripheral_content_heuristic.h"
#include "ppapi/shared_impl/ppapi_constants.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "third_party/blink/public/web/web_local_frame.h"
#include "ui/gfx/geometry/size.h"
namespace content {
diff --git a/chromium/content/renderer/pepper/plugin_power_saver_helper_browsertest.cc b/chromium/content/renderer/pepper/plugin_power_saver_helper_browsertest.cc
index 7a9dc820f9f..7b44d06a87c 100644
--- a/chromium/content/renderer/pepper/plugin_power_saver_helper_browsertest.cc
+++ b/chromium/content/renderer/pepper/plugin_power_saver_helper_browsertest.cc
@@ -16,9 +16,9 @@
#include "content/renderer/render_view_impl.h"
#include "content/test/test_render_frame.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebPluginParams.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_plugin_params.h"
#include "ui/gfx/geometry/size.h"
#include "url/gurl.h"
diff --git a/chromium/content/renderer/pepper/ppb_broker_impl.cc b/chromium/content/renderer/pepper/ppb_broker_impl.cc
index c5d8a5bf248..c9275e7a156 100644
--- a/chromium/content/renderer/pepper/ppb_broker_impl.cc
+++ b/chromium/content/renderer/pepper/ppb_broker_impl.cc
@@ -16,8 +16,8 @@
#include "content/renderer/render_view_impl.h"
#include "ppapi/c/pp_errors.h"
#include "ppapi/shared_impl/platform_file.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebPluginContainer.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_plugin_container.h"
using ppapi::PlatformFileToInt;
using ppapi::thunk::PPB_Broker_API;
diff --git a/chromium/content/renderer/pepper/ppb_flash_message_loop_impl.cc b/chromium/content/renderer/pepper/ppb_flash_message_loop_impl.cc
index 3de9ec4dff3..e5e4ed2e129 100644
--- a/chromium/content/renderer/pepper/ppb_flash_message_loop_impl.cc
+++ b/chromium/content/renderer/pepper/ppb_flash_message_loop_impl.cc
@@ -8,7 +8,7 @@
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "ppapi/c/pp_errors.h"
-#include "third_party/WebKit/public/web/WebView.h"
+#include "third_party/blink/public/web/web_view.h"
using ppapi::thunk::PPB_Flash_MessageLoop_API;
diff --git a/chromium/content/renderer/pepper/ppb_graphics_3d_impl.cc b/chromium/content/renderer/pepper/ppb_graphics_3d_impl.cc
index 31304f28e20..8d65ba893f2 100644
--- a/chromium/content/renderer/pepper/ppb_graphics_3d_impl.cc
+++ b/chromium/content/renderer/pepper/ppb_graphics_3d_impl.cc
@@ -28,11 +28,11 @@
#include "gpu/ipc/client/gpu_channel_host.h"
#include "ppapi/c/ppp_graphics_3d.h"
#include "ppapi/thunk/enter.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/web/WebConsoleMessage.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebPluginContainer.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/web/web_console_message.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_plugin_container.h"
#include "third_party/khronos/GLES2/gl2.h"
using ppapi::thunk::EnterResourceNoLock;
diff --git a/chromium/content/renderer/pepper/ppb_image_data_impl.cc b/chromium/content/renderer/pepper/ppb_image_data_impl.cc
index bb355c0888a..fa2b937dd1d 100644
--- a/chromium/content/renderer/pepper/ppb_image_data_impl.cc
+++ b/chromium/content/renderer/pepper/ppb_image_data_impl.cc
@@ -9,7 +9,6 @@
#include <memory>
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "content/common/pepper_file_util.h"
#include "content/common/view_messages.h"
#include "content/renderer/render_thread_impl.h"
diff --git a/chromium/content/renderer/pepper/ppb_var_deprecated_impl.cc b/chromium/content/renderer/pepper/ppb_var_deprecated_impl.cc
index f89cdc06388..e08f0a87445 100644
--- a/chromium/content/renderer/pepper/ppb_var_deprecated_impl.cc
+++ b/chromium/content/renderer/pepper/ppb_var_deprecated_impl.cc
@@ -19,11 +19,11 @@
#include "ppapi/c/dev/ppb_var_deprecated.h"
#include "ppapi/c/ppb_var.h"
#include "ppapi/shared_impl/ppb_var_shared.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebPluginContainer.h"
-#include "third_party/WebKit/public/web/WebPluginScriptForbiddenScope.h"
-#include "third_party/WebKit/public/web/WebScopedUserGesture.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_plugin_container.h"
+#include "third_party/blink/public/web/web_plugin_script_forbidden_scope.h"
+#include "third_party/blink/public/web/web_scoped_user_gesture.h"
using ppapi::V8ObjectVar;
using ppapi::PpapiGlobals;
diff --git a/chromium/content/renderer/pepper/renderer_ppapi_host_impl.cc b/chromium/content/renderer/pepper/renderer_ppapi_host_impl.cc
index 952ba132e6f..2e9658abdbf 100644
--- a/chromium/content/renderer/pepper/renderer_ppapi_host_impl.cc
+++ b/chromium/content/renderer/pepper/renderer_ppapi_host_impl.cc
@@ -26,10 +26,10 @@
#include "ipc/ipc_platform_file.h"
#include "ppapi/host/ppapi_host.h"
#include "ppapi/proxy/host_dispatcher.h"
-#include "third_party/WebKit/public/platform/WebRect.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebElement.h"
-#include "third_party/WebKit/public/web/WebPluginContainer.h"
+#include "third_party/blink/public/platform/web_rect.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_element.h"
+#include "third_party/blink/public/web/web_plugin_container.h"
#include "ui/gfx/geometry/point.h"
namespace content {
diff --git a/chromium/content/renderer/pepper/resource_converter.cc b/chromium/content/renderer/pepper/resource_converter.cc
index 4c33c05607e..ce072cd15fa 100644
--- a/chromium/content/renderer/pepper/resource_converter.cc
+++ b/chromium/content/renderer/pepper/resource_converter.cc
@@ -13,19 +13,19 @@
#include "content/renderer/pepper/pepper_media_stream_audio_track_host.h"
#include "content/renderer/pepper/pepper_media_stream_video_track_host.h"
#include "ipc/ipc_message.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "ppapi/host/ppapi_host.h"
#include "ppapi/host/resource_host.h"
#include "ppapi/proxy/ppapi_messages.h"
#include "ppapi/shared_impl/resource_var.h"
#include "ppapi/shared_impl/scoped_pp_var.h"
#include "storage/common/fileapi/file_system_util.h"
-#include "third_party/WebKit/public/platform/WebFileSystem.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
-#include "third_party/WebKit/public/web/WebDOMFileSystem.h"
-#include "third_party/WebKit/public/web/WebDOMMediaStreamTrack.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "third_party/blink/public/platform/web_file_system.h"
+#include "third_party/blink/public/platform/web_media_stream_source.h"
+#include "third_party/blink/public/platform/web_media_stream_track.h"
+#include "third_party/blink/public/web/web_dom_file_system.h"
+#include "third_party/blink/public/web/web_dom_media_stream_track.h"
+#include "third_party/blink/public/web/web_local_frame.h"
using ppapi::ResourceVar;
diff --git a/chromium/content/renderer/pepper/resource_creation_impl.cc b/chromium/content/renderer/pepper/resource_creation_impl.cc
index 6ace5f24adf..64c9d9dbaa5 100644
--- a/chromium/content/renderer/pepper/resource_creation_impl.cc
+++ b/chromium/content/renderer/pepper/resource_creation_impl.cc
@@ -283,16 +283,6 @@ PP_Resource ResourceCreationImpl::CreateNetworkMonitor(PP_Instance instance) {
return 0; // Not supported in-process.
}
-PP_Resource ResourceCreationImpl::CreateOutputProtectionPrivate(
- PP_Instance instance) {
- return 0; // Not supported in-process.
-}
-
-PP_Resource ResourceCreationImpl::CreatePlatformVerificationPrivate(
- PP_Instance instance) {
- return 0; // Not supported in-process.
-}
-
PP_Resource ResourceCreationImpl::CreateTCPServerSocketPrivate(
PP_Instance instance) {
return 0; // Not supported in-process.
diff --git a/chromium/content/renderer/pepper/resource_creation_impl.h b/chromium/content/renderer/pepper/resource_creation_impl.h
index f4d339ce1b3..df4c1fc07b5 100644
--- a/chromium/content/renderer/pepper/resource_creation_impl.h
+++ b/chromium/content/renderer/pepper/resource_creation_impl.h
@@ -113,8 +113,6 @@ class ResourceCreationImpl : public ppapi::thunk::ResourceCreationAPI {
PP_Instance instance,
const PP_NetAddress_Private& private_addr) override;
PP_Resource CreateNetworkMonitor(PP_Instance instance) override;
- PP_Resource CreatePlatformVerificationPrivate(PP_Instance instance) override;
- PP_Resource CreateOutputProtectionPrivate(PP_Instance instance) override;
PP_Resource CreateTCPServerSocketPrivate(PP_Instance instance) override;
PP_Resource CreateTCPSocket1_0(PP_Instance instance) override;
PP_Resource CreateTCPSocket(PP_Instance instance) override;
diff --git a/chromium/content/renderer/pepper/url_request_info_util.cc b/chromium/content/renderer/pepper/url_request_info_util.cc
index b50ab707b6d..dd7047665c1 100644
--- a/chromium/content/renderer/pepper/url_request_info_util.cc
+++ b/chromium/content/renderer/pepper/url_request_info_util.cc
@@ -24,13 +24,14 @@
#include "ppapi/shared_impl/url_request_info_data.h"
#include "ppapi/shared_impl/var.h"
#include "ppapi/thunk/enter.h"
-#include "third_party/WebKit/public/platform/FilePathConversion.h"
-#include "third_party/WebKit/public/platform/WebData.h"
-#include "third_party/WebKit/public/platform/WebHTTPBody.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
-#include "third_party/WebKit/public/platform/WebURLRequest.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "third_party/blink/public/platform/file_path_conversion.h"
+#include "third_party/blink/public/platform/web_data.h"
+#include "third_party/blink/public/platform/web_feature.mojom.h"
+#include "third_party/blink/public/platform/web_http_body.h"
+#include "third_party/blink/public/platform/web_url.h"
+#include "third_party/blink/public/platform/web_url_request.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_local_frame.h"
#include "url/gurl.h"
#include "url/url_util.h"
@@ -173,6 +174,11 @@ bool CreateWebURLRequest(PP_Instance instance,
dest->SetDownloadToFile(data->stream_to_file);
dest->SetReportUploadProgress(data->record_upload_progress);
+ if (data->stream_to_file) {
+ frame->BlinkFeatureUsageReport({static_cast<int>(
+ blink::mojom::WebFeature::kPPAPIURLRequestStreamToFile)});
+ }
+
if (!data->method.empty())
dest->SetHTTPMethod(WebString::FromUTF8(data->method));
diff --git a/chromium/content/renderer/pepper/url_response_info_util.cc b/chromium/content/renderer/pepper/url_response_info_util.cc
index 2cbbf570fea..e2e23fb308c 100644
--- a/chromium/content/renderer/pepper/url_response_info_util.cc
+++ b/chromium/content/renderer/pepper/url_response_info_util.cc
@@ -17,11 +17,11 @@
#include "ipc/ipc_message.h"
#include "ppapi/proxy/ppapi_messages.h"
#include "ppapi/shared_impl/url_response_info_data.h"
-#include "third_party/WebKit/public/platform/FilePathConversion.h"
-#include "third_party/WebKit/public/platform/WebHTTPHeaderVisitor.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
-#include "third_party/WebKit/public/platform/WebURLResponse.h"
+#include "third_party/blink/public/platform/file_path_conversion.h"
+#include "third_party/blink/public/platform/web_http_header_visitor.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_url.h"
+#include "third_party/blink/public/platform/web_url_response.h"
using blink::WebHTTPHeaderVisitor;
using blink::WebString;
diff --git a/chromium/content/renderer/pepper/v8_var_converter.cc b/chromium/content/renderer/pepper/v8_var_converter.cc
index aed50374e69..5c4319dca59 100644
--- a/chromium/content/renderer/pepper/v8_var_converter.cc
+++ b/chromium/content/renderer/pepper/v8_var_converter.cc
@@ -26,8 +26,8 @@
#include "ppapi/shared_impl/dictionary_var.h"
#include "ppapi/shared_impl/var.h"
#include "ppapi/shared_impl/var_tracker.h"
-#include "third_party/WebKit/public/web/WebArrayBuffer.h"
-#include "third_party/WebKit/public/web/WebArrayBufferConverter.h"
+#include "third_party/blink/public/web/web_array_buffer.h"
+#include "third_party/blink/public/web/web_array_buffer_converter.h"
using ppapi::ArrayBufferVar;
using ppapi::ArrayVar;
diff --git a/chromium/content/renderer/pepper/video_decoder_shim.cc b/chromium/content/renderer/pepper/video_decoder_shim.cc
index 62fc729c894..c6522e4f6cf 100644
--- a/chromium/content/renderer/pepper/video_decoder_shim.cc
+++ b/chromium/content/renderer/pepper/video_decoder_shim.cc
@@ -31,7 +31,7 @@
#include "media/base/video_decoder.h"
#include "media/filters/ffmpeg_video_decoder.h"
#include "media/filters/vpx_video_decoder.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "media/video/picture.h"
#include "media/video/video_decode_accelerator.h"
#include "ppapi/c/pp_errors.h"
@@ -40,11 +40,6 @@
namespace content {
-static const uint32_t kGrInvalidateState =
- kRenderTarget_GrGLBackendState | kTextureBinding_GrGLBackendState |
- kView_GrGLBackendState | kVertex_GrGLBackendState |
- kProgram_GrGLBackendState | kPixelStore_GrGLBackendState;
-
namespace {
bool IsCodecSupported(media::VideoCodec codec) {
@@ -355,8 +350,6 @@ bool VideoDecoderShim::YUVConverter::Initialize() {
gl_->TraceEndCHROMIUM();
- context_provider_->InvalidateGrContext(kGrInvalidateState);
-
return (program_ != 0);
}
@@ -587,8 +580,6 @@ void VideoDecoderShim::YUVConverter::Convert(
gl_->PixelStorei(GL_UNPACK_ROW_LENGTH_EXT, 0);
gl_->TraceEndCHROMIUM();
-
- context_provider_->InvalidateGrContext(kGrInvalidateState);
}
struct VideoDecoderShim::PendingDecode {
@@ -713,7 +704,8 @@ void VideoDecoderShim::DecoderImpl::Initialize(
base::Bind(&VideoDecoderShim::DecoderImpl::OnInitDone,
weak_ptr_factory_.GetWeakPtr()),
base::Bind(&VideoDecoderShim::DecoderImpl::OnOutputComplete,
- weak_ptr_factory_.GetWeakPtr()));
+ weak_ptr_factory_.GetWeakPtr()),
+ media::VideoDecoder::WaitingForDecryptionKeyCB());
#else
OnInitDone(false);
#endif // BUILDFLAG(ENABLE_LIBVPX) || BUILDFLAG(ENABLE_FFMPEG_VIDEO_DECODERS)
diff --git a/chromium/content/renderer/presentation/presentation_dispatcher.cc b/chromium/content/renderer/presentation/presentation_dispatcher.cc
index 5896933c853..5743fe82104 100644
--- a/chromium/content/renderer/presentation/presentation_dispatcher.cc
+++ b/chromium/content/renderer/presentation/presentation_dispatcher.cc
@@ -5,8 +5,8 @@
#include "content/renderer/presentation/presentation_dispatcher.h"
#include "content/public/renderer/render_frame.h"
-#include "third_party/WebKit/public/platform/modules/presentation/WebPresentationReceiver.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "third_party/blink/public/platform/modules/presentation/web_presentation_receiver.h"
+#include "third_party/blink/public/web/web_local_frame.h"
namespace content {
diff --git a/chromium/content/renderer/presentation/presentation_dispatcher.h b/chromium/content/renderer/presentation/presentation_dispatcher.h
index 7592e9a3884..294ff8c0b50 100644
--- a/chromium/content/renderer/presentation/presentation_dispatcher.h
+++ b/chromium/content/renderer/presentation/presentation_dispatcher.h
@@ -8,7 +8,7 @@
#include "base/macros.h"
#include "content/common/content_export.h"
#include "content/public/renderer/render_frame_observer.h"
-#include "third_party/WebKit/public/platform/modules/presentation/WebPresentationClient.h"
+#include "third_party/blink/public/platform/modules/presentation/web_presentation_client.h"
namespace blink {
class WebPresentationReceiver;
diff --git a/chromium/content/renderer/push_messaging/push_messaging_client.cc b/chromium/content/renderer/push_messaging/push_messaging_client.cc
index 95f4c71dbab..7ab8191e0be 100644
--- a/chromium/content/renderer/push_messaging/push_messaging_client.cc
+++ b/chromium/content/renderer/push_messaging/push_messaging_client.cc
@@ -17,14 +17,14 @@
#include "content/renderer/render_frame_impl.h"
#include "content/renderer/service_worker/web_service_worker_registration_impl.h"
#include "services/service_manager/public/cpp/connector.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/modules/manifest/manifest_manager.mojom.h"
-#include "third_party/WebKit/public/platform/modules/push_messaging/WebPushError.h"
-#include "third_party/WebKit/public/platform/modules/push_messaging/WebPushSubscription.h"
-#include "third_party/WebKit/public/platform/modules/push_messaging/WebPushSubscriptionOptions.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerRegistration.h"
-#include "third_party/WebKit/public/web/WebConsoleMessage.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "third_party/blink/public/platform/modules/manifest/manifest_manager.mojom.h"
+#include "third_party/blink/public/platform/modules/push_messaging/web_push_error.h"
+#include "third_party/blink/public/platform/modules/push_messaging/web_push_subscription.h"
+#include "third_party/blink/public/platform/modules/push_messaging/web_push_subscription_options.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_registration.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/web/web_console_message.h"
+#include "third_party/blink/public/web/web_local_frame.h"
#include "url/gurl.h"
namespace content {
diff --git a/chromium/content/renderer/push_messaging/push_messaging_client.h b/chromium/content/renderer/push_messaging/push_messaging_client.h
index 2740780ab0f..20142f3e8d8 100644
--- a/chromium/content/renderer/push_messaging/push_messaging_client.h
+++ b/chromium/content/renderer/push_messaging/push_messaging_client.h
@@ -14,8 +14,8 @@
#include "base/macros.h"
#include "content/common/push_messaging.mojom.h"
#include "content/public/renderer/render_frame_observer.h"
-#include "third_party/WebKit/public/platform/modules/manifest/manifest.mojom.h"
-#include "third_party/WebKit/public/platform/modules/push_messaging/WebPushClient.h"
+#include "third_party/blink/public/platform/modules/manifest/manifest.mojom.h"
+#include "third_party/blink/public/platform/modules/push_messaging/web_push_client.h"
class GURL;
diff --git a/chromium/content/renderer/push_messaging/push_provider.cc b/chromium/content/renderer/push_messaging/push_provider.cc
index 4493bac4179..3f3e6e6271c 100644
--- a/chromium/content/renderer/push_messaging/push_provider.cc
+++ b/chromium/content/renderer/push_messaging/push_provider.cc
@@ -17,9 +17,9 @@
#include "content/public/common/service_names.mojom.h"
#include "content/renderer/service_worker/web_service_worker_registration_impl.h"
#include "services/service_manager/public/cpp/connector.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/modules/push_messaging/WebPushSubscription.h"
-#include "third_party/WebKit/public/platform/modules/push_messaging/WebPushSubscriptionOptions.h"
+#include "third_party/blink/public/platform/modules/push_messaging/web_push_subscription.h"
+#include "third_party/blink/public/platform/modules/push_messaging/web_push_subscription_options.h"
+#include "third_party/blink/public/platform/web_string.h"
namespace content {
namespace {
diff --git a/chromium/content/renderer/push_messaging/push_provider.h b/chromium/content/renderer/push_messaging/push_provider.h
index d8fb5bcc2ae..223d4cbc8b1 100644
--- a/chromium/content/renderer/push_messaging/push_provider.h
+++ b/chromium/content/renderer/push_messaging/push_provider.h
@@ -15,8 +15,8 @@
#include "base/memory/ref_counted.h"
#include "content/common/push_messaging.mojom.h"
#include "content/public/renderer/worker_thread.h"
-#include "third_party/WebKit/public/platform/modules/push_messaging/WebPushError.h"
-#include "third_party/WebKit/public/platform/modules/push_messaging/WebPushProvider.h"
+#include "third_party/blink/public/platform/modules/push_messaging/web_push_error.h"
+#include "third_party/blink/public/platform/modules/push_messaging/web_push_provider.h"
class GURL;
diff --git a/chromium/content/renderer/render_frame_impl.cc b/chromium/content/renderer/render_frame_impl.cc
index 7fc7063d9f4..5efb96acfd7 100644
--- a/chromium/content/renderer/render_frame_impl.cc
+++ b/chromium/content/renderer/render_frame_impl.cc
@@ -4,7 +4,6 @@
#include "content/renderer/render_frame_impl.h"
-#include <string.h>
#include <algorithm>
#include <map>
#include <string>
@@ -38,6 +37,7 @@
#include "base/strings/string_piece.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task_runner_util.h"
+#include "base/task_scheduler/post_task.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "base/trace_event/trace_event.h"
@@ -144,6 +144,7 @@
#include "content/renderer/service_worker/worker_fetch_context_impl.h"
#include "content/renderer/shared_worker/shared_worker_repository.h"
#include "content/renderer/skia_benchmarking_extension.h"
+#include "content/renderer/speech_recognition_dispatcher.h"
#include "content/renderer/stats_collection_controller.h"
#include "content/renderer/v8_value_converter_impl.h"
#include "content/renderer/web_frame_utils.h"
@@ -157,65 +158,65 @@
#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_util.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/mojom/request_context_frame_type.mojom.h"
#include "services/service_manager/public/cpp/connector.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "services/service_manager/public/mojom/interface_provider.mojom.h"
#include "services/ui/public/cpp/gpu/context_provider_command_buffer.h"
-#include "third_party/WebKit/public/common/associated_interfaces/associated_interface_provider.h"
-#include "third_party/WebKit/public/common/frame/sandbox_flags.h"
-#include "third_party/WebKit/public/mojom/page/page_visibility_state.mojom.h"
-#include "third_party/WebKit/public/platform/FilePathConversion.h"
-#include "third_party/WebKit/public/platform/InterfaceProvider.h"
-#include "third_party/WebKit/public/platform/URLConversion.h"
-#include "third_party/WebKit/public/platform/WebData.h"
-#include "third_party/WebKit/public/platform/WebFocusType.h"
-#include "third_party/WebKit/public/platform/WebKeyboardEvent.h"
-#include "third_party/WebKit/public/platform/WebMediaPlayer.h"
-#include "third_party/WebKit/public/platform/WebMediaPlayerSource.h"
-#include "third_party/WebKit/public/platform/WebPoint.h"
-#include "third_party/WebKit/public/platform/WebScrollIntoViewParams.h"
-#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
-#include "third_party/WebKit/public/platform/WebURLError.h"
-#include "third_party/WebKit/public/platform/WebURLResponse.h"
-#include "third_party/WebKit/public/platform/WebVector.h"
-#include "third_party/WebKit/public/platform/modules/fetch/fetch_api_request.mojom-shared.h"
-#include "third_party/WebKit/public/platform/modules/permissions/permission.mojom.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerNetworkProvider.h"
-#include "third_party/WebKit/public/web/WebAutofillClient.h"
-#include "third_party/WebKit/public/web/WebConsoleMessage.h"
-#include "third_party/WebKit/public/web/WebContextFeatures.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebElementCollection.h"
-#include "third_party/WebKit/public/web/WebFindOptions.h"
-#include "third_party/WebKit/public/web/WebFrameOwnerProperties.h"
-#include "third_party/WebKit/public/web/WebFrameSerializer.h"
-#include "third_party/WebKit/public/web/WebFrameSerializerCacheControlPolicy.h"
-#include "third_party/WebKit/public/web/WebFrameWidget.h"
-#include "third_party/WebKit/public/web/WebInputMethodController.h"
-#include "third_party/WebKit/public/web/WebKit.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
-#include "third_party/WebKit/public/web/WebNavigationPolicy.h"
-#include "third_party/WebKit/public/web/WebPlugin.h"
-#include "third_party/WebKit/public/web/WebPluginContainer.h"
-#include "third_party/WebKit/public/web/WebPluginDocument.h"
-#include "third_party/WebKit/public/web/WebPluginParams.h"
-#include "third_party/WebKit/public/web/WebRange.h"
-#include "third_party/WebKit/public/web/WebScopedUserGesture.h"
-#include "third_party/WebKit/public/web/WebScriptSource.h"
-#include "third_party/WebKit/public/web/WebSearchableFormData.h"
-#include "third_party/WebKit/public/web/WebSecurityPolicy.h"
-#include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
-#include "third_party/WebKit/public/web/WebSettings.h"
-#include "third_party/WebKit/public/web/WebSurroundingText.h"
-#include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
-#include "third_party/WebKit/public/web/WebView.h"
-#include "third_party/WebKit/public/web/WebWidget.h"
+#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
+#include "third_party/blink/public/common/frame/sandbox_flags.h"
+#include "third_party/blink/public/mojom/page/page_visibility_state.mojom.h"
+#include "third_party/blink/public/platform/file_path_conversion.h"
+#include "third_party/blink/public/platform/interface_provider.h"
+#include "third_party/blink/public/platform/modules/fetch/fetch_api_request.mojom-shared.h"
+#include "third_party/blink/public/platform/modules/permissions/permission.mojom.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_network_provider.h"
+#include "third_party/blink/public/platform/url_conversion.h"
+#include "third_party/blink/public/platform/web_data.h"
+#include "third_party/blink/public/platform/web_focus_type.h"
+#include "third_party/blink/public/platform/web_keyboard_event.h"
+#include "third_party/blink/public/platform/web_media_player.h"
+#include "third_party/blink/public/platform/web_media_player_source.h"
+#include "third_party/blink/public/platform/web_point.h"
+#include "third_party/blink/public/platform/web_scroll_into_view_params.h"
+#include "third_party/blink/public/platform/web_security_origin.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_url.h"
+#include "third_party/blink/public/platform/web_url_error.h"
+#include "third_party/blink/public/platform/web_url_response.h"
+#include "third_party/blink/public/platform/web_vector.h"
+#include "third_party/blink/public/web/blink.h"
+#include "third_party/blink/public/web/web_autofill_client.h"
+#include "third_party/blink/public/web/web_console_message.h"
+#include "third_party/blink/public/web/web_context_features.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_element_collection.h"
+#include "third_party/blink/public/web/web_find_options.h"
+#include "third_party/blink/public/web/web_frame_owner_properties.h"
+#include "third_party/blink/public/web/web_frame_serializer.h"
+#include "third_party/blink/public/web/web_frame_serializer_cache_control_policy.h"
+#include "third_party/blink/public/web/web_frame_widget.h"
+#include "third_party/blink/public/web/web_input_method_controller.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_media_stream_registry.h"
+#include "third_party/blink/public/web/web_navigation_policy.h"
+#include "third_party/blink/public/web/web_plugin.h"
+#include "third_party/blink/public/web/web_plugin_container.h"
+#include "third_party/blink/public/web/web_plugin_document.h"
+#include "third_party/blink/public/web/web_plugin_params.h"
+#include "third_party/blink/public/web/web_range.h"
+#include "third_party/blink/public/web/web_scoped_user_gesture.h"
+#include "third_party/blink/public/web/web_script_source.h"
+#include "third_party/blink/public/web/web_searchable_form_data.h"
+#include "third_party/blink/public/web/web_security_policy.h"
+#include "third_party/blink/public/web/web_serialized_script_value.h"
+#include "third_party/blink/public/web/web_settings.h"
+#include "third_party/blink/public/web/web_surrounding_text.h"
+#include "third_party/blink/public/web/web_user_gesture_indicator.h"
+#include "third_party/blink/public/web/web_view.h"
+#include "third_party/blink/public/web/web_widget.h"
#include "ui/events/base_event_utils.h"
#include "url/origin.h"
#include "url/url_constants.h"
@@ -238,7 +239,7 @@
#include <cpu-features.h>
#include "content/renderer/java/gin_java_bridge_dispatcher.h"
-#include "third_party/WebKit/public/platform/WebFloatPoint.h"
+#include "third_party/blink/public/platform/web_float_point.h"
#endif
using base::Time;
@@ -322,7 +323,7 @@ struct PendingNavigationParams {
namespace {
const base::Feature kConsumeGestureOnNavigation = {
- "ConsumeGestureOnNavigation", base::FEATURE_DISABLED_BY_DEFAULT};
+ "ConsumeGestureOnNavigation", base::FEATURE_ENABLED_BY_DEFAULT};
const int kExtraCharsBeforeAndAfterSelection = 100;
@@ -465,6 +466,7 @@ WebURLRequest CreateURLRequestForNavigation(
extra_data->set_navigation_initiated_by_renderer(
request_params.nav_entry_id == 0);
request.SetExtraData(std::move(extra_data));
+ request.SetWasDiscarded(request_params.was_discarded);
// Set the ui timestamp for this navigation. Currently the timestamp here is
// only non empty when the navigation was triggered by an Android intent. The
@@ -675,17 +677,6 @@ class MHTMLPartsGenerationDelegate
return false;
}
- WebString GetContentID(WebFrame* frame) override {
- int routing_id = RenderFrame::GetRoutingIdForWebFrame(frame);
-
- auto it = params_.frame_routing_id_to_content_id.find(routing_id);
- if (it == params_.frame_routing_id_to_content_id.end())
- return WebString();
-
- const std::string& content_id = it->second;
- return WebString::FromUTF8(content_id);
- }
-
blink::WebFrameSerializerCacheControlPolicy CacheControlPolicy() override {
return params_.mhtml_cache_control_policy;
}
@@ -831,12 +822,9 @@ class RenderFrameImpl::FrameURLLoaderFactory
scoped_refptr<base::SingleThreadTaskRunner> task_runner) override {
// This should not be called if the frame is detached.
DCHECK(frame_);
- frame_->UpdatePeakMemoryStats();
mojom::KeepAliveHandlePtr keep_alive_handle;
- if (base::FeatureList::IsEnabled(
- features::kKeepAliveRendererForKeepaliveRequests) &&
- request.GetKeepalive()) {
+ if (request.GetKeepalive()) {
frame_->GetFrameHost()->IssueKeepAliveHandle(
mojo::MakeRequest(&keep_alive_handle));
}
@@ -862,7 +850,7 @@ NOINLINE void ExhaustMemory() {
} while (ptr);
}
-#if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
+#if defined(ADDRESS_SANITIZER)
NOINLINE void MaybeTriggerAsanError(const GURL& url) {
// NOTE(rogerm): We intentionally perform an invalid heap access here in
// order to trigger an Address Sanitizer (ASAN) error report.
@@ -878,7 +866,7 @@ NOINLINE void MaybeTriggerAsanError(const GURL& url) {
LOG(ERROR) << "Intentionally causing ASAN heap use-after-free"
<< " because user navigated to " << url.spec();
base::debug::AsanHeapUseAfterFree();
-#if defined(SYZYASAN)
+#if defined(OS_WIN)
} else if (url == kChromeUICrashCorruptHeapBlockURL) {
LOG(ERROR) << "Intentionally causing ASAN corrupt heap block"
<< " because user navigated to " << url.spec();
@@ -887,15 +875,10 @@ NOINLINE void MaybeTriggerAsanError(const GURL& url) {
LOG(ERROR) << "Intentionally causing ASAN corrupt heap"
<< " because user navigated to " << url.spec();
base::debug::AsanCorruptHeap();
- } else if (url == kChromeUICrashDcheckURL) {
- LOG(ERROR) << "Intentionally DCHECKING because user navigated to "
- << url.spec();
-
- DCHECK(false) << "Intentional DCHECK.";
-#endif
+#endif // OS_WIN
}
}
-#endif // ADDRESS_SANITIZER || SYZYASAN
+#endif // ADDRESS_SANITIZER
// Returns true if the URL is a debug URL, false otherwise. These URLs do not
// commit, though they are intentionally left in the address bar above the
@@ -942,9 +925,18 @@ void HandleChromeDebugURL(const GURL& url) {
CHECK(false);
}
-#if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
+#if DCHECK_IS_ON()
+ if (url == kChromeUICrashDcheckURL) {
+ LOG(ERROR) << "Intentionally causing DCHECK because user navigated to "
+ << url.spec();
+
+ DCHECK(false) << "Intentional DCHECK.";
+ }
+#endif
+
+#if defined(ADDRESS_SANITIZER)
MaybeTriggerAsanError(url);
-#endif // ADDRESS_SANITIZER || SYZYASAN
+#endif // ADDRESS_SANITIZER
}
struct RenderFrameImpl::PendingFileChooser {
@@ -1329,7 +1321,7 @@ RenderFrameImpl::RenderFrameImpl(CreateParams params)
pepper_last_mouse_event_target_(nullptr),
#endif
engagement_binding_(this),
- media_engagement_binding_(this),
+ autoplay_configuration_binding_(this),
frame_binding_(this),
host_zoom_binding_(this),
frame_bindings_control_binding_(this),
@@ -1374,9 +1366,6 @@ RenderFrameImpl::RenderFrameImpl(CreateParams params)
// Manages its own lifetime.
new ManifestChangeNotifier(this);
}
-
- memset(&peak_memory_metrics_, 0,
- sizeof(RenderThreadImpl::RendererMemoryMetrics));
}
mojom::FrameHost* RenderFrameImpl::GetFrameHost() {
@@ -1589,7 +1578,7 @@ RenderWidgetFullscreenPepper* RenderFrameImpl::CreatePepperFullscreenContainer(
// TODO(fsamuel): It's not clear if we should be passing in the
// web ScreenInfo or the original ScreenInfo here.
RenderWidgetFullscreenPepper* widget = RenderWidgetFullscreenPepper::Create(
- fullscreen_widget_routing_id, show_callback,
+ fullscreen_widget_routing_id, std::move(show_callback),
GetRenderWidget()->compositor_deps(), plugin, active_url,
GetRenderWidget()->GetWebScreenInfo(), std::move(widget_channel_request));
// TODO(nick): The show() handshake seems like unnecessary complexity here,
@@ -1824,8 +1813,8 @@ bool RenderFrameImpl::OnMessageReceived(const IPC::Message& msg) {
IPC_MESSAGE_HANDLER(FrameMsg_MixedContentFound, OnMixedContentFound)
IPC_MESSAGE_HANDLER(FrameMsg_SetOverlayRoutingToken,
OnSetOverlayRoutingToken)
- IPC_MESSAGE_HANDLER(FrameMsg_SetHasReceivedUserGesture,
- OnSetHasReceivedUserGesture)
+ IPC_MESSAGE_HANDLER(FrameMsg_NotifyUserActivation, OnNotifyUserActivation)
+
#if defined(OS_ANDROID)
IPC_MESSAGE_HANDLER(FrameMsg_ActivateNearestFindResult,
OnActivateNearestFindResult)
@@ -1868,17 +1857,19 @@ void RenderFrameImpl::BindFullscreen(
GetTaskRunner(blink::TaskType::kInternalIPC));
}
-void RenderFrameImpl::BindMediaEngagement(
- blink::mojom::MediaEngagementClientAssociatedRequest request) {
- media_engagement_binding_.Bind(std::move(request),
- GetTaskRunner(blink::TaskType::kInternalIPC));
+void RenderFrameImpl::BindAutoplayConfiguration(
+ blink::mojom::AutoplayConfigurationClientAssociatedRequest request) {
+ autoplay_configuration_binding_.Bind(
+ std::move(request), GetTaskRunner(blink::TaskType::kInternalIPC));
}
void RenderFrameImpl::BindFrame(
const service_manager::BindSourceInfo& browser_info,
mojom::FrameRequest request) {
browser_info_ = browser_info;
- frame_binding_.Bind(std::move(request));
+ frame_binding_.Bind(
+ std::move(request),
+ frame_ ? GetTaskRunner(blink::TaskType::kInternalIPC) : nullptr);
}
void RenderFrameImpl::BindFrameBindingsControl(
@@ -2406,9 +2397,10 @@ void RenderFrameImpl::OnSetAccessibilityMode(ui::AXMode new_mode) {
observer.AccessibilityModeChanged();
}
-void RenderFrameImpl::OnSnapshotAccessibilityTree(int callback_id) {
+void RenderFrameImpl::OnSnapshotAccessibilityTree(int callback_id,
+ ui::AXMode ax_mode) {
AXContentTreeUpdate response;
- RenderAccessibilityImpl::SnapshotAccessibilityTree(this, &response);
+ RenderAccessibilityImpl::SnapshotAccessibilityTree(this, &response, ax_mode);
Send(new AccessibilityHostMsg_SnapshotResponse(
routing_id_, callback_id, response));
}
@@ -2531,7 +2523,7 @@ void RenderFrameImpl::OnPostMessageEvent(
converter.SetDateAllowed(true);
converter.SetRegExpAllowed(true);
base::string16 data;
- data.resize(params.message->data.encoded_message.length() /
+ data.resize(params.message->data.encoded_message.size() /
sizeof(base::char16));
std::memcpy(&data[0], params.message->data.encoded_message.data(),
data.length() * sizeof(base::char16));
@@ -2584,7 +2576,6 @@ void RenderFrameImpl::OnTextSurroundingSelectionRequest(uint32_t max_length) {
bool RenderFrameImpl::RunJavaScriptDialog(JavaScriptDialogType type,
const base::string16& message,
const base::string16& default_value,
- const GURL& frame_url,
base::string16* result) {
// Don't allow further dialogs if we are waiting to swap out, since the
// ScopedPageLoadDeferrer in our stack prevents it.
@@ -2606,7 +2597,7 @@ bool RenderFrameImpl::RunJavaScriptDialog(JavaScriptDialogType type,
result = &result_temp;
Send(new FrameHostMsg_RunJavaScriptDialog(routing_id_, message, default_value,
- frame_url, type, &success, result));
+ type, &success, result));
return success;
}
@@ -2853,14 +2844,20 @@ blink::WebPlugin* RenderFrameImpl::CreatePlugin(
// |delegate| deletes itself.
BrowserPluginDelegate* delegate =
GetContentClient()->renderer()->CreateBrowserPluginDelegate(
- this, params.mime_type.Utf8(), GURL(params.url));
+ this, info, params.mime_type.Utf8(), GURL(params.url));
return BrowserPluginManager::Get()->CreateBrowserPlugin(
this, delegate->GetWeakPtr());
}
+ base::Optional<url::Origin> origin_lock;
+ if (base::FeatureList::IsEnabled(features::kPdfIsolation) &&
+ GetContentClient()->renderer()->IsOriginIsolatedPepperPlugin(info.path)) {
+ origin_lock = url::Origin::Create(GURL(params.url));
+ }
+
bool pepper_plugin_was_registered = false;
scoped_refptr<PluginModule> pepper_module(PluginModule::Create(
- this, info, &pepper_plugin_was_registered));
+ this, info, origin_lock, &pepper_plugin_was_registered));
if (pepper_plugin_was_registered) {
if (pepper_module.get()) {
return new PepperWebPluginImpl(
@@ -2918,13 +2915,14 @@ RenderFrameImpl::GetRemoteAssociatedInterfaces() {
mojom::AssociatedInterfaceProviderAssociatedPtr remote_interfaces;
thread->GetRemoteRouteProvider()->GetRoute(
routing_id_, mojo::MakeRequest(&remote_interfaces));
- remote_associated_interfaces_.reset(
- new AssociatedInterfaceProviderImpl(std::move(remote_interfaces)));
+ remote_associated_interfaces_.reset(new AssociatedInterfaceProviderImpl(
+ std::move(remote_interfaces),
+ GetTaskRunner(blink::TaskType::kInternalIPC)));
} else {
// In some tests the thread may be null,
// so set up a self-contained interface provider instead.
- remote_associated_interfaces_.reset(
- new AssociatedInterfaceProviderImpl());
+ remote_associated_interfaces_.reset(new AssociatedInterfaceProviderImpl(
+ GetTaskRunner(blink::TaskType::kInternalIPC)));
}
}
return remote_associated_interfaces_.get();
@@ -3047,10 +3045,18 @@ void RenderFrameImpl::RequestFullscreenVideoElement() {
}
}
-// blink::mojom::MediaEngagementClient implementation --------------------------
+// blink::mojom::AutoplayConfigurationClient implementation
+// --------------------------
-void RenderFrameImpl::SetHasHighMediaEngagement(const url::Origin& origin) {
- high_media_engagement_origin_ = origin;
+void RenderFrameImpl::AddAutoplayFlags(const url::Origin& origin,
+ const int32_t flags) {
+ // If the origin is the same as the previously stored flags then we should
+ // merge the two sets of flags together.
+ if (autoplay_flags_.first == origin) {
+ autoplay_flags_.second |= flags;
+ } else {
+ autoplay_flags_ = std::make_pair(origin, flags);
+ }
}
// mojom::Frame implementation -------------------------------------------------
@@ -3095,6 +3101,8 @@ void RenderFrameImpl::CommitNavigation(
const RequestNavigationParams& request_params,
network::mojom::URLLoaderClientEndpointsPtr url_loader_client_endpoints,
std::unique_ptr<URLLoaderFactoryBundleInfo> subresource_loader_factories,
+ base::Optional<std::vector<mojom::TransferrableURLLoaderPtr>>
+ subresource_overrides,
mojom::ControllerServiceWorkerInfoPtr controller_service_worker_info,
const base::UnguessableToken& devtools_navigation_token) {
DCHECK(!IsRendererDebugURL(common_params.url));
@@ -3124,7 +3132,8 @@ void RenderFrameImpl::CommitNavigation(
!base::FeatureList::IsEnabled(network::features::kNetworkService) ||
subresource_loader_factories);
- SetupLoaderFactoryBundle(std::move(subresource_loader_factories));
+ SetupLoaderFactoryBundle(std::move(subresource_loader_factories),
+ std::move(subresource_overrides));
// Clear pending navigations which weren't sent to the browser because we
// did not get a didStartProvisionalLoad() notification for them.
@@ -3247,7 +3256,8 @@ void RenderFrameImpl::CommitFailedNavigation(
GetContentClient()->SetActiveURL(
common_params.url, frame_->Top()->GetSecurityOrigin().ToString().Utf8());
- SetupLoaderFactoryBundle(std::move(subresource_loader_factories));
+ SetupLoaderFactoryBundle(std::move(subresource_loader_factories),
+ base::nullopt /* subresource_overrides */);
pending_navigation_params_.reset(new PendingNavigationParams(
common_params, request_params,
@@ -3256,7 +3266,7 @@ void RenderFrameImpl::CommitFailedNavigation(
// Send the provisional load failure.
WebURLError error(
- error_code,
+ error_code, 0,
has_stale_copy_in_cache ? WebURLError::HasCopyInCache::kTrue
: WebURLError::HasCopyInCache::kFalse,
WebURLError::IsWebSecurityViolation::kFalse, common_params.url);
@@ -3474,7 +3484,7 @@ blink::WebPlugin* RenderFrameImpl::CreatePlugin(
// |delegate| deletes itself.
BrowserPluginDelegate* delegate =
GetContentClient()->renderer()->CreateBrowserPluginDelegate(
- this, kBrowserPluginMimeType, GURL(params.url));
+ this, WebPluginInfo(), kBrowserPluginMimeType, GURL(params.url));
return BrowserPluginManager::Get()->CreateBrowserPlugin(
this, delegate->GetWeakPtr());
}
@@ -3566,7 +3576,7 @@ RenderFrameImpl::CreateWorkerFetchContext() {
}
RenderThreadImpl* render_thread = RenderThreadImpl::current();
- std::unique_ptr<SharedURLLoaderFactoryInfo>
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo>
direct_network_loader_factory_info;
// Could be null in tests.
if (render_thread) {
@@ -3647,8 +3657,7 @@ RenderFrameImpl::CreateServiceWorkerProvider() {
// The context can be null when the frame is sandboxed.
return nullptr;
}
- return std::make_unique<WebServiceWorkerProviderImpl>(
- ChildThreadImpl::current()->thread_safe_sender(), provider->context());
+ return std::make_unique<WebServiceWorkerProviderImpl>(provider->context());
}
service_manager::InterfaceProvider* RenderFrameImpl::GetInterfaceProvider() {
@@ -3739,7 +3748,8 @@ blink::WebLocalFrame* RenderFrameImpl::CreateChildFrame(
service_manager::mojom::InterfaceProviderPtr child_interface_provider;
child_interface_provider.Bind(
service_manager::mojom::InterfaceProviderPtrInfo(
- mojo::ScopedMessagePipeHandle(child_interface_provider_handle), 0u));
+ mojo::ScopedMessagePipeHandle(child_interface_provider_handle), 0u),
+ GetTaskRunner(blink::TaskType::kInternalIPC));
// This method is always called by local frames, never remote frames.
@@ -3970,15 +3980,15 @@ void RenderFrameImpl::DidAddMessageToConsole(
static_cast<int32_t>(source_line), source_name.Utf16()));
}
-void RenderFrameImpl::DownloadURL(const blink::WebURLRequest& request,
- const blink::WebString& suggested_name) {
+void RenderFrameImpl::DownloadURL(const blink::WebURLRequest& request) {
FrameHostMsg_DownloadUrl_Params params;
params.render_view_id = render_view_->GetRoutingID();
params.render_frame_id = GetRoutingID();
params.url = request.Url();
params.referrer = RenderViewImpl::GetReferrerFromRequest(frame_, request);
params.initiator_origin = request.RequestorOrigin();
- params.suggested_name = suggested_name.Utf16();
+ if (request.GetSuggestedFilename().has_value())
+ params.suggested_name = request.GetSuggestedFilename()->Utf16();
Send(new FrameHostMsg_DownloadUrl(params));
}
@@ -4053,7 +4063,7 @@ void RenderFrameImpl::DidCreateDocumentLoader(
// Set the navigation start time in blink.
document_loader->SetNavigationStartTime(
- ConvertToBlinkTime(navigation_state->common_params().navigation_start));
+ navigation_state->common_params().navigation_start);
// If an actual navigation took place, inform the document loader of what
// happened in the browser.
@@ -4061,12 +4071,12 @@ void RenderFrameImpl::DidCreateDocumentLoader(
.navigation_timing.fetch_start.is_null()) {
// Set timing of several events that happened during navigation.
// They will be used in blink for the Navigation Timing API.
- double redirect_start = ConvertToBlinkTime(
- navigation_state->request_params().navigation_timing.redirect_start);
- double redirect_end = ConvertToBlinkTime(
- navigation_state->request_params().navigation_timing.redirect_end);
- double fetch_start = ConvertToBlinkTime(
- navigation_state->request_params().navigation_timing.fetch_start);
+ base::TimeTicks redirect_start =
+ navigation_state->request_params().navigation_timing.redirect_start;
+ base::TimeTicks redirect_end =
+ navigation_state->request_params().navigation_timing.redirect_end;
+ base::TimeTicks fetch_start =
+ navigation_state->request_params().navigation_timing.fetch_start;
document_loader->UpdateNavigation(
redirect_start, redirect_end, fetch_start,
@@ -4095,7 +4105,7 @@ void RenderFrameImpl::DidCreateDocumentLoader(
return;
RenderThreadImpl* render_thread = RenderThreadImpl::current();
- scoped_refptr<SharedURLLoaderFactory> direct_network_loader_factory;
+ scoped_refptr<network::SharedURLLoaderFactory> direct_network_loader_factory;
if (render_thread) {
direct_network_loader_factory =
base::MakeRefCounted<PossiblyAssociatedWrapperSharedURLLoaderFactory>(
@@ -4137,6 +4147,8 @@ void RenderFrameImpl::DidStartProvisionalLoad(
info.source_location = pending_navigation_info_->source_location;
info.devtools_initiator_info =
pending_navigation_info_->devtools_initiator_info;
+ info.blob_url_token =
+ pending_navigation_info_->blob_url_token.PassInterface().PassHandle();
pending_navigation_info_.reset(nullptr);
BeginNavigation(info);
@@ -4421,6 +4433,17 @@ void RenderFrameImpl::DidReceiveTitle(const blink::WebString& title,
base::string16 shortened_title = title16.substr(0, kMaxTitleChars);
Send(new FrameHostMsg_UpdateTitle(routing_id_,
shortened_title, direction));
+ } else {
+ // Set process title for sub-frames in traces.
+ GURL loading_url = GetLoadingUrl();
+ if (!loading_url.host().empty() &&
+ loading_url.scheme() != url::kFileScheme) {
+ std::string subframe_title = "Subframe: " + loading_url.scheme() +
+ url::kStandardSchemeSeparator +
+ loading_url.host();
+ base::trace_event::TraceLog::GetInstance()->UpdateProcessLabel(
+ routing_id_, subframe_title);
+ }
}
// Also check whether we have new encoding name.
@@ -4428,14 +4451,19 @@ void RenderFrameImpl::DidReceiveTitle(const blink::WebString& title,
}
void RenderFrameImpl::DidChangeIcon(blink::WebIconURL::Type icon_type) {
- SendUpdateFaviconURL(icon_type);
+ SendUpdateFaviconURL();
}
-void RenderFrameImpl::SendUpdateFaviconURL(
- blink::WebIconURL::Type icon_types_mask) {
+void RenderFrameImpl::SendUpdateFaviconURL() {
if (frame_->Parent())
return;
+ blink::WebIconURL::Type icon_types_mask =
+ static_cast<blink::WebIconURL::Type>(
+ blink::WebIconURL::kTypeFavicon |
+ blink::WebIconURL::kTypeTouchPrecomposed |
+ blink::WebIconURL::kTypeTouch);
+
WebVector<blink::WebIconURL> icon_urls = frame_->IconURLs(icon_types_mask);
if (icon_urls.empty())
return;
@@ -4525,8 +4553,8 @@ void RenderFrameImpl::DidFailLoad(const WebURLError& error,
const WebURLRequest& failed_request = document_loader->GetRequest();
base::string16 error_description;
- GetContentClient()->renderer()->PrepareErrorPage(this, failed_request, error,
- nullptr, &error_description);
+ GetContentClient()->renderer()->GetErrorDescription(failed_request, error,
+ &error_description);
Send(new FrameHostMsg_DidFailLoadWithError(
routing_id_, failed_request.Url(), error.reason(), error_description));
}
@@ -4546,7 +4574,6 @@ void RenderFrameImpl::DidFinishLoad() {
Send(new FrameHostMsg_DidFinishLoad(routing_id_,
document_loader->GetRequest().Url()));
- ReportPeakMemoryStats();
if (!RenderThreadImpl::current())
return;
RenderThreadImpl::RendererMemoryMetrics memory_metrics;
@@ -4671,13 +4698,12 @@ bool RenderFrameImpl::HandleCurrentKeyboardEvent() {
void RenderFrameImpl::RunModalAlertDialog(const blink::WebString& message) {
RunJavaScriptDialog(JAVASCRIPT_DIALOG_TYPE_ALERT, message.Utf16(),
- base::string16(), frame_->GetDocument().Url(), nullptr);
+ base::string16(), nullptr);
}
bool RenderFrameImpl::RunModalConfirmDialog(const blink::WebString& message) {
return RunJavaScriptDialog(JAVASCRIPT_DIALOG_TYPE_CONFIRM, message.Utf16(),
- base::string16(), frame_->GetDocument().Url(),
- nullptr);
+ base::string16(), nullptr);
}
bool RenderFrameImpl::RunModalPromptDialog(
@@ -4686,8 +4712,7 @@ bool RenderFrameImpl::RunModalPromptDialog(
blink::WebString* actual_value) {
base::string16 result;
bool ok = RunJavaScriptDialog(JAVASCRIPT_DIALOG_TYPE_PROMPT, message.Utf16(),
- default_value.Utf16(),
- frame_->GetDocument().Url(), &result);
+ default_value.Utf16(), &result);
if (ok)
*actual_value = WebString::FromUTF16(result);
return ok;
@@ -4703,9 +4728,8 @@ bool RenderFrameImpl::RunModalBeforeUnloadDialog(bool is_reload) {
// This is an ignored return value, but is included so we can accept the same
// response as RunJavaScriptDialog.
base::string16 ignored_result;
- Send(new FrameHostMsg_RunBeforeUnloadConfirm(
- routing_id_, frame_->GetDocument().Url(), is_reload, &success,
- &ignored_result));
+ Send(new FrameHostMsg_RunBeforeUnloadConfirm(routing_id_, is_reload, &success,
+ &ignored_result));
return success;
}
@@ -4795,12 +4819,15 @@ void RenderFrameImpl::FrameRectsChanged(const blink::WebRect& frame_rect) {
}
void RenderFrameImpl::WillSendRequest(blink::WebURLRequest& request) {
+ if (render_view_->renderer_preferences_.enable_do_not_track)
+ request.SetHTTPHeaderField(blink::WebString::FromUTF8(kDoNotTrackHeader),
+ "1");
+
WebDocumentLoader* provisional_document_loader =
frame_->GetProvisionalDocumentLoader();
WebDocumentLoader* document_loader = provisional_document_loader
? provisional_document_loader
: frame_->GetDocumentLoader();
-
DocumentState* document_state =
DocumentState::FromDocumentLoader(document_loader);
DCHECK(document_state);
@@ -4816,10 +4843,17 @@ void RenderFrameImpl::WillSendRequest(blink::WebURLRequest& request) {
}
GURL new_url;
- if (GetContentClient()->renderer()->WillSendRequest(
- frame_, transition_type, request.Url(), &new_url)) {
+ bool attach_same_site_cookies = false;
+ base::Optional<url::Origin> initiator_origin =
+ request.RequestorOrigin().IsNull()
+ ? base::Optional<url::Origin>()
+ : base::Optional<url::Origin>(request.RequestorOrigin());
+ GetContentClient()->renderer()->WillSendRequest(
+ frame_, transition_type, request.Url(),
+ base::OptionalOrNullptr(initiator_origin), &new_url,
+ &attach_same_site_cookies);
+ if (!new_url.is_empty())
request.SetURL(WebURL(new_url));
- }
if (internal_data->is_cache_policy_override_set())
request.SetCacheMode(internal_data->cache_policy_override());
@@ -4877,7 +4911,6 @@ void RenderFrameImpl::WillSendRequest(blink::WebURLRequest& request) {
extra_data->set_requested_with(requested_with);
extra_data->set_render_frame_id(routing_id_);
extra_data->set_is_main_frame(!parent);
- extra_data->set_frame_origin(url::Origin(frame_document.GetSecurityOrigin()));
extra_data->set_allow_download(
navigation_state->common_params().allow_download);
extra_data->set_transition_type(transition_type);
@@ -4889,6 +4922,7 @@ void RenderFrameImpl::WillSendRequest(blink::WebURLRequest& request) {
extra_data->set_download_to_network_cache_only(
is_for_no_state_prefetch && resource_type != RESOURCE_TYPE_MAIN_FRAME);
extra_data->set_initiated_in_secure_context(frame_document.IsSecureContext());
+ extra_data->set_attach_same_site_cookies(attach_same_site_cookies);
// Renderer process transfers apply only to navigational requests.
bool is_navigational_request =
@@ -4911,7 +4945,7 @@ void RenderFrameImpl::WillSendRequest(blink::WebURLRequest& request) {
if (render_thread && render_thread->url_loader_throttle_provider()) {
extra_data->set_url_loader_throttles(
render_thread->url_loader_throttle_provider()->CreateThrottles(
- routing_id_, request.Url(), resource_type));
+ routing_id_, request, resource_type));
}
if (request.GetPreviewsState() == WebURLRequest::kPreviewsUnspecified) {
@@ -5117,6 +5151,12 @@ void RenderFrameImpl::DidObserveNewFeatureUsage(
observer.DidObserveNewFeatureUsage(feature);
}
+void RenderFrameImpl::DidObserveNewCssPropertyUsage(int css_property,
+ bool is_animated) {
+ for (auto& observer : observers_)
+ observer.DidObserveNewCssPropertyUsage(css_property, is_animated);
+}
+
bool RenderFrameImpl::ShouldTrackUseCounter(const blink::WebURL& url) {
return GetContentClient()->renderer()->ShouldTrackUseCounter(url);
}
@@ -5441,12 +5481,12 @@ RenderFrameImpl::MakeDidCommitProvisionalLoadParams(
params->post_id = -1;
params->nav_entry_id = navigation_state->request_params().nav_entry_id;
// We need to track the RenderViewHost routing_id because of downstream
- // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
- // ResourceDispatcherHostImpl, MediaStreamUIProxy,
- // SpeechRecognitionDispatcherHost and possibly others). They look up the view
- // based on the ID stored in the resource requests. Once those dependencies
- // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
- // client to be based on the routing_id of the RenderFrameHost.
+ // dependencies (https://crbug.com/392171 DownloadRequestHandle,
+ // SaveFileManager, ResourceDispatcherHostImpl, MediaStreamUIProxy and
+ // possibly others). They look up the view based on the ID stored in the
+ // resource requests. Once those dependencies are unwound or moved to
+ // RenderFrameHost (https://crbug.com/304341) we can move the client to be
+ // based on the routing_id of the RenderFrameHost.
params->render_view_routing_id = render_view_->routing_id();
// "Standard" commits from Blink create new NavigationEntries. We also treat
@@ -5723,12 +5763,17 @@ void RenderFrameImpl::UpdateStateForCommit(
engagement_level_.first = url::Origin();
}
- // Set the correct high media engagement bit on the frame, and wipe the cached
- // origin so this will not be reused accidentally.
- if (url::Origin(frame_->GetSecurityOrigin()) ==
- high_media_engagement_origin_) {
- frame_->SetHasHighMediaEngagement(true);
- high_media_engagement_origin_ = url::Origin();
+ // If we are a top frame navigation we should clear any existing autoplay
+ // flags on the Page. This is because flags are stored at the page level so
+ // subframes would only add to them.
+ if (!frame_->Parent())
+ render_view_->webview()->ClearAutoplayFlags();
+
+ // Set the correct autoplay flags on the Page and wipe the cached origin so
+ // this will not be used incorrectly.
+ if (url::Origin(frame_->GetSecurityOrigin()) == autoplay_flags_.first) {
+ render_view_->webview()->AddAutoplayFlags(autoplay_flags_.second);
+ autoplay_flags_.first = url::Origin();
}
}
@@ -5897,12 +5942,7 @@ void RenderFrameImpl::DidStopLoading() {
// this state anymore.
history_subframe_unique_names_.clear();
- blink::WebIconURL::Type icon_types_mask =
- static_cast<blink::WebIconURL::Type>(
- blink::WebIconURL::kTypeFavicon |
- blink::WebIconURL::kTypeTouchPrecomposed |
- blink::WebIconURL::kTypeTouch);
- SendUpdateFaviconURL(icon_types_mask);
+ SendUpdateFaviconURL();
render_view_->FrameDidStopLoading(frame_);
Send(new FrameHostMsg_DidStopLoading(routing_id_));
@@ -6046,6 +6086,46 @@ WebNavigationPolicy RenderFrameImpl::DecidePolicyForNavigation(
// See http://crbug.com/93517.
GURL old_url(frame_->GetDocumentLoader()->GetRequest().Url());
+ // Detect when a page is "forking" a new tab that can be safely rendered in
+ // its own process. This is done by sites like Gmail that try to open links
+ // in new windows without script connections back to the original page. We
+ // treat such cases as browser navigations (in which we will create a new
+ // renderer for a cross-site navigation), rather than WebKit navigations.
+ //
+ // We use the following heuristic to decide whether to fork a new page in its
+ // own process:
+ // The parent page must open a new tab to about:blank, set the new tab's
+ // window.opener to null, and then redirect the tab to a cross-site URL using
+ // JavaScript.
+ //
+ // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
+ // (see below).
+ bool is_fork =
+ // Must start from a tab showing about:blank, which is later redirected.
+ old_url == url::kAboutBlankURL &&
+ // Must be the first real navigation of the tab.
+ render_view_->HistoryBackListCount() < 1 &&
+ render_view_->HistoryForwardListCount() < 1 &&
+ // The parent page must have set the child's window.opener to null before
+ // redirecting to the desired URL.
+ frame_->Opener() == nullptr &&
+ // Must be a top-level frame.
+ frame_->Parent() == nullptr &&
+ // Must not have issued the request from this page.
+ is_content_initiated &&
+ // Must be targeted at the current tab.
+ info.default_policy == blink::kWebNavigationPolicyCurrentTab &&
+ // Must be a JavaScript navigation, which appears as "other".
+ info.navigation_type == blink::kWebNavigationTypeOther;
+
+ if (is_fork) {
+ // Open the URL via the browser, not via WebKit. Make sure the referrer is
+ // stripped.
+ OpenURL(info, /*send_referrer=*/false,
+ /*is_history_navigation_in_new_child=*/false);
+ return blink::kWebNavigationPolicyIgnore;
+ }
+
// Detect when we're crossing a permission-based boundary (e.g. into or out of
// an extension or app origin, leaving a WebUI page, etc). We only care about
// top-level navigations (not iframes). But we sometimes navigate to
@@ -6093,46 +6173,6 @@ WebNavigationPolicy RenderFrameImpl::DecidePolicyForNavigation(
}
}
- // Detect when a page is "forking" a new tab that can be safely rendered in
- // its own process. This is done by sites like Gmail that try to open links
- // in new windows without script connections back to the original page. We
- // treat such cases as browser navigations (in which we will create a new
- // renderer for a cross-site navigation), rather than WebKit navigations.
- //
- // We use the following heuristic to decide whether to fork a new page in its
- // own process:
- // The parent page must open a new tab to about:blank, set the new tab's
- // window.opener to null, and then redirect the tab to a cross-site URL using
- // JavaScript.
- //
- // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
- // (see below).
- bool is_fork =
- // Must start from a tab showing about:blank, which is later redirected.
- old_url == url::kAboutBlankURL &&
- // Must be the first real navigation of the tab.
- render_view_->HistoryBackListCount() < 1 &&
- render_view_->HistoryForwardListCount() < 1 &&
- // The parent page must have set the child's window.opener to null before
- // redirecting to the desired URL.
- frame_->Opener() == nullptr &&
- // Must be a top-level frame.
- frame_->Parent() == nullptr &&
- // Must not have issued the request from this page.
- is_content_initiated &&
- // Must be targeted at the current tab.
- info.default_policy == blink::kWebNavigationPolicyCurrentTab &&
- // Must be a JavaScript navigation, which appears as "other".
- info.navigation_type == blink::kWebNavigationTypeOther;
-
- if (is_fork) {
- // Open the URL via the browser, not via WebKit. Make sure the referrer is
- // stripped.
- OpenURL(info, /*send_referrer=*/false,
- /*is_history_navigation_in_new_child=*/false);
- return blink::kWebNavigationPolicyIgnore;
- }
-
bool should_dispatch_before_unload =
info.default_policy == blink::kWebNavigationPolicyCurrentTab &&
// There is no need to execute the BeforeUnload event during a redirect,
@@ -6174,31 +6214,24 @@ WebNavigationPolicy RenderFrameImpl::DecidePolicyForNavigation(
(info.archive_status == NavigationPolicyInfo::ArchiveStatus::Present) &&
!url.SchemeIs(url::kDataScheme);
- // If the navigation is not synchronous, send it to the browser. This
- // includes navigations with no request being sent to the network stack.
- if (info.url_request.CheckForBrowserSideNavigation() &&
- IsURLHandledByNetworkStack(url) && !use_archive) {
- if (info.default_policy == blink::kWebNavigationPolicyCurrentTab) {
- // The BeginNavigation() call happens in didStartProvisionalLoad(). We
- // need to save information about the navigation here.
+ if (info.default_policy == blink::kWebNavigationPolicyCurrentTab) {
+ // If the navigation is not synchronous, send it to the browser. This
+ // includes navigations with no request being sent to the network stack.
+ if (!use_archive && info.url_request.CheckForBrowserSideNavigation() &&
+ IsURLHandledByNetworkStack(url)) {
pending_navigation_info_.reset(new PendingNavigationInfo(info));
return blink::kWebNavigationPolicyHandledByClient;
- } else if (info.default_policy == blink::kWebNavigationPolicyDownload) {
- DownloadURL(info.url_request, blink::WebString());
- return blink::kWebNavigationPolicyIgnore;
} else {
- OpenURL(info, /*send_referrer=*/true,
- /*is_history_navigation_in_new_child=*/false);
- return blink::kWebNavigationPolicyIgnore;
+ return blink::kWebNavigationPolicyCurrentTab;
}
}
- if (info.default_policy == blink::kWebNavigationPolicyCurrentTab ||
- info.default_policy == blink::kWebNavigationPolicyDownload) {
- return info.default_policy;
+ if (info.default_policy == blink::kWebNavigationPolicyDownload) {
+ DownloadURL(info.url_request);
+ } else {
+ OpenURL(info, /*send_referrer=*/true,
+ /*is_history_navigation_in_new_child=*/false);
}
- OpenURL(info, /*send_referrer=*/true,
- /*is_history_navigation_in_new_child=*/false);
return blink::kWebNavigationPolicyIgnore;
}
@@ -6291,8 +6324,8 @@ void RenderFrameImpl::OnSerializeAsMHTML(
main_thread_use_time);
if (save_status == MhtmlSaveStatus::SUCCESS && has_some_data) {
- base::PostTaskAndReplyWithResult(
- RenderThreadImpl::current()->GetFileThreadTaskRunner().get(), FROM_HERE,
+ base::PostTaskWithTraitsAndReplyWithResult(
+ FROM_HERE, {base::MayBlock()},
base::Bind(&WriteMHTMLToDisk, base::Passed(&mhtml_contents),
base::Passed(&file)),
base::Bind(&RenderFrameImpl::OnWriteMHTMLToDiskComplete,
@@ -6518,14 +6551,10 @@ void RenderFrameImpl::OnSetOverlayRoutingToken(
pending_routing_token_callbacks_.clear();
}
-void RenderFrameImpl::OnSetHasReceivedUserGesture() {
- frame_->SetHasReceivedUserGesture();
-}
-
void RenderFrameImpl::RequestOverlayRoutingToken(
media::RoutingTokenCallback callback) {
if (overlay_routing_token_.has_value()) {
- callback.Run(overlay_routing_token_.value());
+ std::move(callback).Run(overlay_routing_token_.value());
return;
}
@@ -6533,7 +6562,11 @@ void RenderFrameImpl::RequestOverlayRoutingToken(
// arrives later.
Send(new FrameHostMsg_RequestOverlayRoutingToken(routing_id_));
- pending_routing_token_callbacks_.push_back(callback);
+ pending_routing_token_callbacks_.push_back(std::move(callback));
+}
+
+void RenderFrameImpl::OnNotifyUserActivation() {
+ frame_->NotifyUserActivation();
}
#if BUILDFLAG(USE_EXTERNAL_POPUP_MENU)
@@ -6541,6 +6574,8 @@ void RenderFrameImpl::RequestOverlayRoutingToken(
void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index) {
if (external_popup_menu_ == NULL)
return;
+
+ blink::WebScopedUserGesture gesture(frame_);
external_popup_menu_->DidSelectItem(selected_index);
external_popup_menu_.reset();
}
@@ -6555,6 +6590,7 @@ void RenderFrameImpl::OnSelectPopupMenuItems(
if (!external_popup_menu_)
return;
+ blink::WebScopedUserGesture gesture(frame_);
external_popup_menu_->DidSelectItems(canceled, selected_indices);
external_popup_menu_.reset();
}
@@ -6684,28 +6720,34 @@ ChildURLLoaderFactoryBundle* RenderFrameImpl::GetLoaderFactoryBundle() {
base::MakeRefCounted<TrackedChildURLLoaderFactoryBundle>(
std::move(bundle_info));
} else {
- SetupLoaderFactoryBundle(nullptr);
+ SetupLoaderFactoryBundle(nullptr,
+ base::nullopt /* subresource_overrides */);
}
}
return loader_factories_.get();
}
void RenderFrameImpl::SetupLoaderFactoryBundle(
- std::unique_ptr<URLLoaderFactoryBundleInfo> info) {
+ std::unique_ptr<URLLoaderFactoryBundleInfo> info,
+ base::Optional<std::vector<mojom::TransferrableURLLoaderPtr>>
+ subresource_overrides) {
RenderThreadImpl* render_thread = RenderThreadImpl::current();
- loader_factories_ = base::MakeRefCounted<HostChildURLLoaderFactoryBundle>();
+ loader_factories_ = base::MakeRefCounted<HostChildURLLoaderFactoryBundle>(
+ GetTaskRunner(blink::TaskType::kInternalLoading));
// In some tests |render_thread| could be null.
if (render_thread) {
loader_factories_->Update(render_thread->blink_platform_impl()
->CreateDefaultURLLoaderFactoryBundle()
- ->PassInterface());
+ ->PassInterface(),
+ base::nullopt);
}
if (info) {
- static_cast<URLLoaderFactoryBundle*>(loader_factories_.get())
- ->Update(std::move(info));
+ loader_factories_->Update(
+ std::make_unique<ChildURLLoaderFactoryBundleInfo>(std::move(info)),
+ std::move(subresource_overrides));
}
}
@@ -6792,8 +6834,11 @@ void RenderFrameImpl::ScrollFocusedEditableElementIntoRect(
return;
}
- if (!render_view_->webview()->ScrollFocusedEditableElementIntoView())
+ if (!frame_->LocalRoot()
+ ->FrameWidget()
+ ->ScrollFocusedEditableElementIntoView()) {
return;
+ }
rect_for_scrolled_focused_editable_node_ = rect;
has_scrolled_focused_editable_node_into_rect_ = true;
@@ -6816,7 +6861,8 @@ void RenderFrameImpl::InitializeUserMediaClient() {
DCHECK(!web_user_media_client_);
web_user_media_client_ = new UserMediaClientImpl(
this, RenderThreadImpl::current()->GetPeerConnectionDependencyFactory(),
- std::make_unique<MediaStreamDeviceObserver>(this));
+ std::make_unique<MediaStreamDeviceObserver>(this),
+ GetTaskRunner(blink::TaskType::kInternalMedia));
#endif
}
@@ -6932,6 +6978,15 @@ void RenderFrameImpl::BeginNavigation(const NavigationPolicyInfo& info) {
if (info.is_client_redirect)
client_side_redirect_url = frame_->GetDocument().Url();
+ blink::mojom::BlobURLTokenPtr blob_url_token;
+ if (info.blob_url_token.is_valid()) {
+ blink::mojom::BlobURLTokenPtr token(blink::mojom::BlobURLTokenPtrInfo(
+ mojo::ScopedMessagePipeHandle(info.blob_url_token.get()),
+ blink::mojom::BlobURLToken::Version_));
+ token->Clone(MakeRequest(&blob_url_token));
+ ignore_result(token.PassInterface().PassHandle().release());
+ }
+
int load_flags = GetLoadFlagsForWebURLRequest(info.url_request);
std::unique_ptr<base::DictionaryValue> initiator =
GetDevToolsInitiator(info.devtools_initiator_info);
@@ -6942,10 +6997,13 @@ void RenderFrameImpl::BeginNavigation(const NavigationPolicyInfo& info) {
GetRequestContextTypeForWebURLRequest(info.url_request),
GetMixedContentContextTypeForWebURLRequest(info.url_request),
is_form_submission, searchable_form_url, searchable_form_encoding,
- initiator_origin, client_side_redirect_url, std::move(initiator));
+ initiator_origin, client_side_redirect_url,
+ initiator ? base::make_optional<base::Value>(std::move(*initiator))
+ : base::nullopt);
GetFrameHost()->BeginNavigation(MakeCommonNavigationParams(info, load_flags),
- std::move(begin_navigation_params));
+ std::move(begin_navigation_params),
+ std::move(blob_url_token));
}
void RenderFrameImpl::LoadDataURL(
@@ -7010,8 +7068,8 @@ void RenderFrameImpl::SendFailedProvisionalLoad(
FrameHostMsg_DidFailProvisionalLoadWithError_Params params;
params.error_code = error.reason();
- GetContentClient()->renderer()->PrepareErrorPage(
- this, request, error, nullptr, &params.error_description);
+ GetContentClient()->renderer()->GetErrorDescription(
+ request, error, &params.error_description);
params.url = error.url(),
params.showing_repost_interstitial = show_repost_interstitial;
Send(new FrameHostMsg_DidFailProvisionalLoadWithError(routing_id_, params));
@@ -7180,7 +7238,7 @@ void RenderFrameImpl::RegisterMojoInterfaces() {
base::Bind(&RenderFrameImpl::BindEngagement, weak_factory_.GetWeakPtr()));
GetAssociatedInterfaceRegistry()->AddInterface(base::Bind(
- &RenderFrameImpl::BindMediaEngagement, weak_factory_.GetWeakPtr()));
+ &RenderFrameImpl::BindAutoplayConfiguration, weak_factory_.GetWeakPtr()));
GetAssociatedInterfaceRegistry()->AddInterface(base::Bind(
&RenderFrameImpl::BindFrameBindingsControl, weak_factory_.GetWeakPtr()));
@@ -7240,9 +7298,16 @@ void RenderFrameImpl::CheckIfAudioSinkExistsAndIsAuthorized(
blink::WebSetSinkIdCallbacks* web_callbacks) {
media::OutputDeviceStatusCB callback =
media::ConvertToOutputDeviceStatusCB(web_callbacks);
- callback.Run(AudioDeviceFactory::GetOutputDeviceInfo(
- GetRoutingID(), 0, sink_id.Utf8(), security_origin)
- .device_status());
+ std::move(callback).Run(
+ AudioDeviceFactory::GetOutputDeviceInfo(GetRoutingID(), 0, sink_id.Utf8(),
+ security_origin)
+ .device_status());
+}
+
+blink::WebSpeechRecognizer* RenderFrameImpl::SpeechRecognizer() {
+ if (!speech_recognition_dispatcher_)
+ speech_recognition_dispatcher_ = new SpeechRecognitionDispatcher(this);
+ return speech_recognition_dispatcher_;
}
blink::mojom::PageVisibilityState RenderFrameImpl::VisibilityState() const {
@@ -7303,15 +7368,21 @@ void RenderFrameImpl::FrameDidCallFocus() {
}
void RenderFrameImpl::OnPictureInPictureSurfaceIdUpdated(
- const viz::SurfaceId& surface_id) {
- GetFrameHost()->OnUpdatePictureInPictureSurfaceId(surface_id);
+ const viz::SurfaceId& surface_id,
+ const gfx::Size& natural_size) {
+ GetFrameHost()->OnUpdatePictureInPictureSurfaceId(surface_id, natural_size);
+}
+
+void RenderFrameImpl::OnExitPictureInPicture() {
+ GetFrameHost()->OnExitPictureInPicture();
}
void RenderFrameImpl::SetAccessibilityModeForTest(ui::AXMode new_mode) {
OnSetAccessibilityMode(new_mode);
}
-scoped_refptr<SharedURLLoaderFactory> RenderFrameImpl::GetURLLoaderFactory() {
+scoped_refptr<network::SharedURLLoaderFactory>
+RenderFrameImpl::GetURLLoaderFactory() {
return GetLoaderFactoryBundle();
}
@@ -7450,51 +7521,6 @@ void RenderFrameImpl::RenderWidgetWillHandleMouseEvent() {
#endif
}
-void RenderFrameImpl::UpdatePeakMemoryStats() {
- if (!base::FeatureList::IsEnabled(features::kReportRendererPeakMemoryStats))
- return;
-
- RenderThreadImpl::RendererMemoryMetrics memory_metrics;
- if (!RenderThreadImpl::current()->GetRendererMemoryMetrics(&memory_metrics))
- return;
- peak_memory_metrics_.partition_alloc_kb =
- std::max(peak_memory_metrics_.partition_alloc_kb,
- memory_metrics.partition_alloc_kb);
- peak_memory_metrics_.blink_gc_kb =
- std::max(peak_memory_metrics_.blink_gc_kb, memory_metrics.blink_gc_kb);
- peak_memory_metrics_.malloc_mb =
- std::max(peak_memory_metrics_.malloc_mb, memory_metrics.malloc_mb);
- peak_memory_metrics_.discardable_kb = std::max(
- peak_memory_metrics_.discardable_kb, memory_metrics.discardable_kb);
- peak_memory_metrics_.v8_main_thread_isolate_mb =
- std::max(peak_memory_metrics_.v8_main_thread_isolate_mb,
- memory_metrics.v8_main_thread_isolate_mb);
- peak_memory_metrics_.total_allocated_mb =
- std::max(peak_memory_metrics_.total_allocated_mb,
- memory_metrics.total_allocated_mb);
- peak_memory_metrics_.non_discardable_total_allocated_mb =
- std::max(peak_memory_metrics_.non_discardable_total_allocated_mb,
- memory_metrics.non_discardable_total_allocated_mb);
- peak_memory_metrics_.total_allocated_per_render_view_mb =
- std::max(peak_memory_metrics_.total_allocated_per_render_view_mb,
- memory_metrics.total_allocated_per_render_view_mb);
-}
-
-void RenderFrameImpl::ReportPeakMemoryStats() {
- if (!base::FeatureList::IsEnabled(features::kReportRendererPeakMemoryStats))
- return;
-
- RecordSuffixedRendererMemoryMetrics(peak_memory_metrics_, ".PeakDuringLoad");
- if (!IsMainFrame())
- return;
- RecordSuffixedRendererMemoryMetrics(peak_memory_metrics_,
- ".MainFrame.PeakDuringLoad");
- if (!IsControlledByServiceWorker())
- return;
- RecordSuffixedRendererMemoryMetrics(
- peak_memory_metrics_, ".ServiceWorkerControlledMainFrame.PeakDuringLoad");
-}
-
bool RenderFrameImpl::ConsumeGestureOnNavigation() const {
return is_main_frame_ &&
base::FeatureList::IsEnabled(kConsumeGestureOnNavigation);
@@ -7522,7 +7548,17 @@ RenderFrameImpl::PendingNavigationInfo::PendingNavigationInfo(
triggering_event_info(info.triggering_event_info),
form(info.form),
source_location(info.source_location),
- devtools_initiator_info(info.devtools_initiator_info) {}
+ devtools_initiator_info(info.devtools_initiator_info) {
+ if (info.blob_url_token.is_valid()) {
+ blink::mojom::BlobURLTokenPtr token(blink::mojom::BlobURLTokenPtrInfo(
+ mojo::ScopedMessagePipeHandle(info.blob_url_token.get()),
+ blink::mojom::BlobURLToken::Version_));
+ token->Clone(MakeRequest(&blob_url_token));
+ ignore_result(token.PassInterface().PassHandle().release());
+ }
+}
+
+RenderFrameImpl::PendingNavigationInfo::~PendingNavigationInfo() = default;
void RenderFrameImpl::BindWidget(mojom::WidgetRequest request) {
GetRenderWidget()->SetWidgetBinding(std::move(request));
diff --git a/chromium/content/renderer/render_frame_impl.h b/chromium/content/renderer/render_frame_impl.h
index 7d15f58e775..9acff93b62e 100644
--- a/chromium/content/renderer/render_frame_impl.h
+++ b/chromium/content/renderer/render_frame_impl.h
@@ -30,8 +30,8 @@
#include "base/unguessable_token.h"
#include "build/build_config.h"
#include "content/common/associated_interface_registry_impl.h"
+#include "content/common/buildflags.h"
#include "content/common/download/mhtml_save_status.h"
-#include "content/common/features.h"
#include "content/common/frame.mojom.h"
#include "content/common/frame_message_enums.h"
#include "content/common/host_zoom.mojom.h"
@@ -53,7 +53,6 @@
#include "content/renderer/input/input_target_client_impl.h"
#include "content/renderer/loader/child_url_loader_factory_bundle.h"
#include "content/renderer/media/media_factory.h"
-#include "content/renderer/render_thread_impl.h"
#include "content/renderer/renderer_webcookiejar_impl.h"
#include "ipc/ipc_message.h"
#include "ipc/ipc_platform_file.h"
@@ -62,40 +61,40 @@
#include "mojo/public/cpp/bindings/binding.h"
#include "mojo/public/cpp/bindings/binding_set.h"
#include "mojo/public/cpp/system/data_pipe.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
#include "services/service_manager/public/cpp/bind_source_info.h"
#include "services/service_manager/public/cpp/binder_registry.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "services/service_manager/public/mojom/connector.mojom.h"
#include "services/service_manager/public/mojom/interface_provider.mojom.h"
-#include "third_party/WebKit/public/common/feature_policy/feature_policy.h"
-#include "third_party/WebKit/public/mojom/page/page_visibility_state.mojom.h"
-#include "third_party/WebKit/public/platform/WebEffectiveConnectionType.h"
-#include "third_party/WebKit/public/platform/WebFocusType.h"
-#include "third_party/WebKit/public/platform/WebLoadingBehaviorFlag.h"
-#include "third_party/WebKit/public/platform/WebMediaPlayer.h"
-#include "third_party/WebKit/public/platform/media_engagement.mojom.h"
-#include "third_party/WebKit/public/platform/modules/manifest/manifest_manager.mojom.h"
-#include "third_party/WebKit/public/platform/site_engagement.mojom.h"
-#include "third_party/WebKit/public/web/WebAXObject.h"
-#include "third_party/WebKit/public/web/WebDocumentLoader.h"
-#include "third_party/WebKit/public/web/WebFrameClient.h"
-#include "third_party/WebKit/public/web/WebFrameLoadType.h"
-#include "third_party/WebKit/public/web/WebFrameSerializerClient.h"
-#include "third_party/WebKit/public/web/WebHistoryCommitType.h"
-#include "third_party/WebKit/public/web/WebIconURL.h"
-#include "third_party/WebKit/public/web/WebMeaningfulLayout.h"
-#include "third_party/WebKit/public/web/WebScriptExecutionCallback.h"
-#include "third_party/WebKit/public/web/WebTriggeringEventInfo.h"
-#include "third_party/WebKit/public/web/commit_result.mojom.h"
+#include "third_party/blink/public/common/feature_policy/feature_policy.h"
+#include "third_party/blink/public/mojom/page/page_visibility_state.mojom.h"
+#include "third_party/blink/public/platform/autoplay.mojom.h"
+#include "third_party/blink/public/platform/modules/manifest/manifest_manager.mojom.h"
+#include "third_party/blink/public/platform/site_engagement.mojom.h"
+#include "third_party/blink/public/platform/web_effective_connection_type.h"
+#include "third_party/blink/public/platform/web_focus_type.h"
+#include "third_party/blink/public/platform/web_loading_behavior_flag.h"
+#include "third_party/blink/public/platform/web_media_player.h"
+#include "third_party/blink/public/web/commit_result.mojom.h"
+#include "third_party/blink/public/web/web_ax_object.h"
+#include "third_party/blink/public/web/web_document_loader.h"
+#include "third_party/blink/public/web/web_frame_client.h"
+#include "third_party/blink/public/web/web_frame_load_type.h"
+#include "third_party/blink/public/web/web_frame_serializer_client.h"
+#include "third_party/blink/public/web/web_history_commit_type.h"
+#include "third_party/blink/public/web/web_icon_url.h"
+#include "third_party/blink/public/web/web_meaningful_layout.h"
+#include "third_party/blink/public/web/web_script_execution_callback.h"
+#include "third_party/blink/public/web/web_triggering_event_info.h"
#include "ui/accessibility/ax_modes.h"
#include "ui/gfx/range/range.h"
#include "url/gurl.h"
#include "url/origin.h"
#if defined(OS_MACOSX)
-#include "third_party/WebKit/public/mojom/clipboard/clipboard.mojom.h"
+#include "third_party/blink/public/mojom/clipboard/clipboard.mojom.h"
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
@@ -110,17 +109,18 @@ struct FrameMsg_TextTrackSettings_Params;
namespace blink {
class WebComputedAXTree;
class WebContentDecryptionModule;
+class WebLayerTreeView;
class WebLocalFrame;
class WebPresentationClient;
class WebPushClient;
+class WebRelatedAppsFetcher;
class WebSecurityOrigin;
-struct WebImeTextSpan;
+class WebSpeechRecognizer;
+struct FramePolicy;
struct WebContextMenuData;
struct WebCursorInfo;
struct WebFindOptions;
-class WebLayerTreeView;
-class WebRelatedAppsFetcher;
-struct FramePolicy;
+struct WebImeTextSpan;
struct WebScrollIntoViewParams;
} // namespace blink
@@ -168,6 +168,7 @@ class RenderViewImpl;
class RenderWidget;
class RenderWidgetFullscreenPepper;
class SharedWorkerRepository;
+class SpeechRecognitionDispatcher;
class UserMediaClientImpl;
struct CSPViolationParams;
struct CommonNavigationParams;
@@ -183,7 +184,7 @@ struct ScreenInfo;
class CONTENT_EXPORT RenderFrameImpl
: public RenderFrame,
blink::mojom::EngagementClient,
- blink::mojom::MediaEngagementClient,
+ blink::mojom::AutoplayConfigurationClient,
mojom::Frame,
mojom::FrameNavigationControl,
mojom::FullscreenVideoElementHandler,
@@ -498,14 +499,15 @@ class CONTENT_EXPORT RenderFrameImpl
blink::TaskType task_type) override;
int GetEnabledBindings() const override;
void SetAccessibilityModeForTest(ui::AXMode new_mode) override;
- scoped_refptr<SharedURLLoaderFactory> GetURLLoaderFactory() override;
+ scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory() override;
// blink::mojom::EngagementClient implementation:
void SetEngagementLevel(const url::Origin& origin,
blink::mojom::EngagementLevel level) override;
- // blink::mojom::MediaEngagementClient implementation:
- void SetHasHighMediaEngagement(const url::Origin& origin) override;
+ // blink::mojom::AutoplayConfigurationClient implementation:
+ void AddAutoplayFlags(const url::Origin& origin,
+ const int32_t flags) override;
// mojom::Frame implementation:
void GetInterfaceProvider(
@@ -529,6 +531,8 @@ class CONTENT_EXPORT RenderFrameImpl
const RequestNavigationParams& request_params,
network::mojom::URLLoaderClientEndpointsPtr url_loader_client_endpoints,
std::unique_ptr<URLLoaderFactoryBundleInfo> subresource_loaders,
+ base::Optional<std::vector<mojom::TransferrableURLLoaderPtr>>
+ subresource_overrides,
mojom::ControllerServiceWorkerInfoPtr controller_service_worker_info,
const base::UnguessableToken& devtools_navigation_token) override;
void CommitFailedNavigation(
@@ -620,8 +624,7 @@ class CONTENT_EXPORT RenderFrameImpl
const blink::WebString& source_name,
unsigned source_line,
const blink::WebString& stack_trace) override;
- void DownloadURL(const blink::WebURLRequest& request,
- const blink::WebString& suggested_name) override;
+ void DownloadURL(const blink::WebURLRequest& request) override;
void LoadErrorPage(int reason) override;
blink::WebNavigationPolicy DecidePolicyForNavigation(
const NavigationPolicyInfo& info) override;
@@ -698,6 +701,8 @@ class CONTENT_EXPORT RenderFrameImpl
void DidObserveLoadingBehavior(
blink::WebLoadingBehaviorFlag behavior) override;
void DidObserveNewFeatureUsage(blink::mojom::WebFeature feature) override;
+ void DidObserveNewCssPropertyUsage(int css_property,
+ bool is_animated) override;
bool ShouldTrackUseCounter(const blink::WebURL& url) override;
void DidCreateScriptContext(v8::Local<v8::Context> context,
int world_id) override;
@@ -747,6 +752,7 @@ class CONTENT_EXPORT RenderFrameImpl
const blink::WebString& sink_id,
const blink::WebSecurityOrigin& security_origin,
blink::WebSetSinkIdCallbacks* web_callbacks) override;
+ blink::WebSpeechRecognizer* SpeechRecognizer() override;
blink::mojom::PageVisibilityState VisibilityState() const override;
std::unique_ptr<blink::WebURLLoaderFactory> CreateURLLoaderFactory() override;
void DraggableRegionsChanged() override;
@@ -770,9 +776,9 @@ class CONTENT_EXPORT RenderFrameImpl
void BindFullscreen(
mojom::FullscreenVideoElementHandlerAssociatedRequest request);
- // Binds to the media engagement service in the browser.
- void BindMediaEngagement(
- blink::mojom::MediaEngagementClientAssociatedRequest request);
+ // Binds to the autoplay configuration service in the browser.
+ void BindAutoplayConfiguration(
+ blink::mojom::AutoplayConfigurationClientAssociatedRequest request);
// Binds to the FrameHost in the browser.
void BindFrame(const service_manager::BindSourceInfo& browser_info,
@@ -871,8 +877,13 @@ class CONTENT_EXPORT RenderFrameImpl
// frame.
void FrameDidCallFocus();
- // Send SurfaceId information to FrameHost to use for Picture-in-Picture.
- void OnPictureInPictureSurfaceIdUpdated(const viz::SurfaceId& surface_id);
+ // Send viz::SurfaceId and video information to FrameHost to use for
+ // Picture-in-Picture.
+ void OnPictureInPictureSurfaceIdUpdated(const viz::SurfaceId& surface_id,
+ const gfx::Size& natural_size);
+
+ // Send signal that Picture-in-Picture mode has ended.
+ void OnExitPictureInPicture();
protected:
explicit RenderFrameImpl(CreateParams params);
@@ -1038,7 +1049,7 @@ class CONTENT_EXPORT RenderFrameImpl
void OnReloadLoFiImages();
void OnTextSurroundingSelectionRequest(uint32_t max_length);
void OnSetAccessibilityMode(ui::AXMode new_mode);
- void OnSnapshotAccessibilityTree(int callback_id);
+ void OnSnapshotAccessibilityTree(int callback_id, ui::AXMode ax_mode);
void OnUpdateOpener(int opener_routing_id);
void OnDidUpdateFramePolicy(const blink::FramePolicy& frame_policy);
void OnSetFrameOwnerProperties(
@@ -1075,7 +1086,7 @@ class CONTENT_EXPORT RenderFrameImpl
void OnFindMatchRects(int current_version);
#endif
void OnSetOverlayRoutingToken(const base::UnguessableToken& token);
- void OnSetHasReceivedUserGesture();
+ void OnNotifyUserActivation();
#if BUILDFLAG(USE_EXTERNAL_POPUP_MENU)
#if defined(OS_MACOSX)
@@ -1119,7 +1130,9 @@ class CONTENT_EXPORT RenderFrameImpl
ChildURLLoaderFactoryBundle* GetLoaderFactoryBundle();
void SetupLoaderFactoryBundle(
- std::unique_ptr<URLLoaderFactoryBundleInfo> info);
+ std::unique_ptr<URLLoaderFactoryBundleInfo> info,
+ base::Optional<std::vector<mojom::TransferrableURLLoaderPtr>>
+ subresource_overrides);
// Update current main frame's encoding and send it to browser window.
// Since we want to let users see the right encoding info from menu
@@ -1140,7 +1153,6 @@ class CONTENT_EXPORT RenderFrameImpl
bool RunJavaScriptDialog(JavaScriptDialogType type,
const base::string16& message,
const base::string16& default_value,
- const GURL& frame_url,
base::string16* result);
// Loads the appropriate error page for the specified failure into the frame.
@@ -1260,10 +1272,8 @@ class CONTENT_EXPORT RenderFrameImpl
// Ask the host to send our AndroidOverlay routing token to us.
void RequestOverlayRoutingTokenFromHost();
- void SendUpdateFaviconURL(blink::WebIconURL::Type icon_types_mask);
+ void SendUpdateFaviconURL();
- void UpdatePeakMemoryStats();
- void ReportPeakMemoryStats();
void BindWidget(mojom::WidgetRequest request);
void ShowDeferredContextMenu(const ContextMenuParams& params);
@@ -1507,6 +1517,11 @@ class CONTENT_EXPORT RenderFrameImpl
// process.
std::unique_ptr<ManifestManager> manifest_manager_;
+ // The speech recognition dispatcher attached to this frame, lazily
+ // initialized. It is an observer of this frame, owning itself and managing
+ // its own lifetime.
+ SpeechRecognitionDispatcher* speech_recognition_dispatcher_ = nullptr;
+
// The current accessibility mode.
ui::AXMode accessibility_mode_;
@@ -1569,11 +1584,13 @@ class CONTENT_EXPORT RenderFrameImpl
HostZoomLevels host_zoom_levels_;
EngagementOriginAndLevel engagement_level_;
- url::Origin high_media_engagement_origin_;
+
+ using AutoplayOriginAndFlags = std::pair<url::Origin, int32_t>;
+ AutoplayOriginAndFlags autoplay_flags_;
mojo::AssociatedBinding<blink::mojom::EngagementClient> engagement_binding_;
- mojo::AssociatedBinding<blink::mojom::MediaEngagementClient>
- media_engagement_binding_;
+ mojo::AssociatedBinding<blink::mojom::AutoplayConfigurationClient>
+ autoplay_configuration_binding_;
mojo::Binding<mojom::Frame> frame_binding_;
mojo::AssociatedBinding<mojom::HostZoom> host_zoom_binding_;
mojo::AssociatedBinding<mojom::FrameBindingsControl>
@@ -1618,8 +1635,10 @@ class CONTENT_EXPORT RenderFrameImpl
blink::WebFormElement form;
blink::WebSourceLocation source_location;
blink::WebString devtools_initiator_info;
+ blink::mojom::BlobURLTokenPtr blob_url_token;
explicit PendingNavigationInfo(const NavigationPolicyInfo& info);
+ ~PendingNavigationInfo();
};
// Contains information about a pending navigation to be sent to the browser.
@@ -1653,8 +1672,6 @@ class CONTENT_EXPORT RenderFrameImpl
InputTargetClientImpl input_target_client_impl_;
- RenderThreadImpl::RendererMemoryMetrics peak_memory_metrics_;
-
// Used for devtools instrumentation and trace-ability. This token is
// used to tag calls and requests in order to attribute them to the context
// frame.
diff --git a/chromium/content/renderer/render_frame_impl_browsertest.cc b/chromium/content/renderer/render_frame_impl_browsertest.cc
index af58c099c6c..fb6a85c3b65 100644
--- a/chromium/content/renderer/render_frame_impl_browsertest.cc
+++ b/chromium/content/renderer/render_frame_impl_browsertest.cc
@@ -37,14 +37,14 @@
#include "services/service_manager/public/mojom/interface_provider.mojom.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebEffectiveConnectionType.h"
-#include "third_party/WebKit/public/platform/WebRuntimeFeatures.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
-#include "third_party/WebKit/public/platform/WebURLRequest.h"
-#include "third_party/WebKit/public/web/WebHistoryItem.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebView.h"
+#include "third_party/blink/public/platform/web_effective_connection_type.h"
+#include "third_party/blink/public/platform/web_runtime_features.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_url.h"
+#include "third_party/blink/public/platform/web_url_request.h"
+#include "third_party/blink/public/web/web_history_item.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_view.h"
#include "ui/native_theme/native_theme_features.h"
using blink::WebString;
@@ -59,6 +59,10 @@ constexpr int32_t kSubframeWidgetRouteId = 21;
constexpr int32_t kFrameProxyRouteId = 22;
constexpr int32_t kEmbeddedSubframeRouteId = 23;
+const char kParentFrameHTML[] = "Parent frame <iframe name='frame'></iframe>";
+
+const char kAutoplayTestOrigin[] = "https://www.google.com";
+
} // namespace
// RenderFrameImplTest creates a RenderFrameImpl that is a child of the
@@ -74,14 +78,17 @@ class RenderFrameImplTest : public RenderViewTest {
RenderViewTest::SetUp();
EXPECT_TRUE(GetMainRenderFrame()->is_main_frame_);
+ IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess());
+
+ LoadHTML(kParentFrameHTML);
+ LoadChildFrame();
+ }
+
+ void LoadChildFrame() {
mojom::CreateFrameWidgetParams widget_params;
widget_params.routing_id = kSubframeWidgetRouteId;
widget_params.hidden = false;
- IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess());
-
- LoadHTML("Parent frame <iframe name='frame'></iframe>");
-
FrameReplicationState frame_replication_state;
frame_replication_state.name = "frame";
frame_replication_state.unique_name = "frame-uniqueName";
@@ -132,6 +139,14 @@ class RenderFrameImplTest : public RenderViewTest {
return frame_->render_widget_.get();
}
+ static url::Origin GetOriginForFrame(TestRenderFrame* frame) {
+ return url::Origin(frame->GetWebFrame()->GetSecurityOrigin());
+ }
+
+ static int32_t AutoplayFlagsForFrame(TestRenderFrame* frame) {
+ return frame->render_view()->webview()->AutoplayFlagsForTest();
+ }
+
#if defined(OS_ANDROID)
void ReceiveOverlayRoutingToken(const base::UnguessableToken& token) {
overlay_routing_token_ = token;
@@ -559,6 +574,51 @@ TEST_F(RenderFrameImplTest, GetPreviewsStateForFrame) {
EXPECT_DCHECK_DEATH(frame()->GetPreviewsStateForFrame());
}
+TEST_F(RenderFrameImplTest, AutoplayFlags) {
+ // Add autoplay flags to the page.
+ GetMainRenderFrame()->AddAutoplayFlags(
+ url::Origin::Create(GURL(kAutoplayTestOrigin)),
+ blink::mojom::kAutoplayFlagHighMediaEngagement);
+
+ // Navigate the top frame.
+ LoadHTMLWithUrlOverride(kParentFrameHTML, kAutoplayTestOrigin);
+
+ // Check the flags have been set correctly.
+ EXPECT_EQ(blink::mojom::kAutoplayFlagHighMediaEngagement,
+ AutoplayFlagsForFrame(GetMainRenderFrame()));
+
+ // Navigate the child frame.
+ LoadChildFrame();
+
+ // Check the flags are set on both frames.
+ EXPECT_EQ(blink::mojom::kAutoplayFlagHighMediaEngagement,
+ AutoplayFlagsForFrame(GetMainRenderFrame()));
+ EXPECT_EQ(blink::mojom::kAutoplayFlagHighMediaEngagement,
+ AutoplayFlagsForFrame(frame()));
+
+ // Navigate the top frame.
+ LoadHTMLWithUrlOverride(kParentFrameHTML, "https://www.example.com");
+ LoadChildFrame();
+
+ // Check the flags have been cleared.
+ EXPECT_EQ(blink::mojom::kAutoplayFlagNone,
+ AutoplayFlagsForFrame(GetMainRenderFrame()));
+ EXPECT_EQ(blink::mojom::kAutoplayFlagNone, AutoplayFlagsForFrame(frame()));
+}
+
+TEST_F(RenderFrameImplTest, AutoplayFlags_WrongOrigin) {
+ // Add autoplay flags to the page.
+ GetMainRenderFrame()->AddAutoplayFlags(
+ url::Origin(), blink::mojom::kAutoplayFlagHighMediaEngagement);
+
+ // Navigate the top frame.
+ LoadHTMLWithUrlOverride(kParentFrameHTML, kAutoplayTestOrigin);
+
+ // Check the flags have been not been set.
+ EXPECT_EQ(blink::mojom::kAutoplayFlagNone,
+ AutoplayFlagsForFrame(GetMainRenderFrame()));
+}
+
// RenderFrameRemoteInterfacesTest ------------------------------------
namespace {
diff --git a/chromium/content/renderer/render_frame_metadata_observer_impl.cc b/chromium/content/renderer/render_frame_metadata_observer_impl.cc
index 58989b6cc68..5b5c8b82ae8 100644
--- a/chromium/content/renderer/render_frame_metadata_observer_impl.cc
+++ b/chromium/content/renderer/render_frame_metadata_observer_impl.cc
@@ -4,6 +4,8 @@
#include "content/renderer/render_frame_metadata_observer_impl.h"
+#include "cc/trees/frame_token_allocator.h"
+
namespace content {
RenderFrameMetadataObserverImpl::RenderFrameMetadataObserverImpl(
@@ -15,32 +17,72 @@ RenderFrameMetadataObserverImpl::RenderFrameMetadataObserverImpl(
RenderFrameMetadataObserverImpl::~RenderFrameMetadataObserverImpl() {}
-void RenderFrameMetadataObserverImpl::BindToCurrentThread() {
+void RenderFrameMetadataObserverImpl::BindToCurrentThread(
+ cc::FrameTokenAllocator* frame_token_allocator) {
DCHECK(request_.is_pending());
+ frame_token_allocator_ = frame_token_allocator;
render_frame_metadata_observer_binding_.Bind(std::move(request_));
render_frame_metadata_observer_client_.Bind(std::move(client_info_));
}
void RenderFrameMetadataObserverImpl::OnRenderFrameSubmission(
- const cc::RenderFrameMetadata& metadata) {
- bool metadata_changed = last_render_frame_metadata_ != metadata;
- last_render_frame_metadata_ = metadata;
+ cc::RenderFrameMetadata metadata) {
+ // By default only report metadata changes for fields which have a low
+ // frequency of change. However if there are changes in high frequency
+ // fields these can be reported while testing is enabled.
+ bool send_metadata = false;
+ if (render_frame_metadata_observer_client_) {
+ if (report_all_frame_submissions_for_testing_enabled_) {
+ last_frame_token_ = frame_token_allocator_->GetOrAllocateFrameToken();
+ render_frame_metadata_observer_client_->OnFrameSubmissionForTesting(
+ last_frame_token_);
+ send_metadata = !last_render_frame_metadata_ ||
+ *last_render_frame_metadata_ != metadata;
+ } else {
+ send_metadata = !last_render_frame_metadata_ ||
+ cc::RenderFrameMetadata::HasAlwaysUpdateMetadataChanged(
+ *last_render_frame_metadata_, metadata);
+ }
+ }
- if (!render_frame_metadata_observer_client_)
- return;
+ // Allways cache the full metadata, so that it can correctly be sent upon
+ // ReportAllFrameSubmissionsForTesting. This must only be done after we've
+ // compared the two for changes.
+ last_render_frame_metadata_ = metadata;
- if (report_all_frame_submissions_for_testing_enabled_)
- render_frame_metadata_observer_client_->OnFrameSubmissionForTesting();
+ // If the metadata is different, updates all the observers; or the metadata is
+ // generated for first time and same as the default value, update the default
+ // value to all the observers.
+ if (send_metadata && render_frame_metadata_observer_client_) {
+ // Sending |root_scroll_offset| outside of tests would leave the browser
+ // process with out of date information. It is an optional parameter
+ // which we clear here.
+ if (!report_all_frame_submissions_for_testing_enabled_)
+ metadata.root_scroll_offset = base::nullopt;
- if (metadata_changed) {
+ last_frame_token_ = frame_token_allocator_->GetOrAllocateFrameToken();
render_frame_metadata_observer_client_->OnRenderFrameMetadataChanged(
- metadata);
+ last_frame_token_, metadata);
}
+
+ // Always cache the initial frame token, so that if a test connects later on
+ // it can be notified of the initial state.
+ if (!last_frame_token_)
+ last_frame_token_ = frame_token_allocator_->GetOrAllocateFrameToken();
}
void RenderFrameMetadataObserverImpl::ReportAllFrameSubmissionsForTesting(
bool enabled) {
report_all_frame_submissions_for_testing_enabled_ = enabled;
+
+ if (!enabled || !last_frame_token_)
+ return;
+
+ // When enabled for testing send the cached metadata.
+ DCHECK(render_frame_metadata_observer_client_);
+ DCHECK(last_render_frame_metadata_.has_value());
+ render_frame_metadata_observer_client_->OnRenderFrameMetadataChanged(
+ last_frame_token_, *last_render_frame_metadata_);
}
} // namespace content
diff --git a/chromium/content/renderer/render_frame_metadata_observer_impl.h b/chromium/content/renderer/render_frame_metadata_observer_impl.h
index 0c888fdaca7..d7b159165da 100644
--- a/chromium/content/renderer/render_frame_metadata_observer_impl.h
+++ b/chromium/content/renderer/render_frame_metadata_observer_impl.h
@@ -10,6 +10,10 @@
#include "content/common/render_frame_metadata.mojom.h"
#include "mojo/public/cpp/bindings/binding.h"
+namespace cc {
+class FrameTokenAllocator;
+} // namespace cc
+
namespace content {
// Implementation of cc::RenderFrameMetadataObserver which exists in the
@@ -31,9 +35,9 @@ class RenderFrameMetadataObserverImpl
~RenderFrameMetadataObserverImpl() override;
// cc::RenderFrameMetadataObserver:
- void BindToCurrentThread() override;
- void OnRenderFrameSubmission(
- const cc::RenderFrameMetadata& metadata) override;
+ void BindToCurrentThread(
+ cc::FrameTokenAllocator* frame_token_allocator) override;
+ void OnRenderFrameSubmission(cc::RenderFrameMetadata metadata) override;
// mojom::RenderFrameMetadataObserver:
void ReportAllFrameSubmissionsForTesting(bool enabled) override;
@@ -43,7 +47,11 @@ class RenderFrameMetadataObserverImpl
// frame submissions.
bool report_all_frame_submissions_for_testing_enabled_ = false;
- cc::RenderFrameMetadata last_render_frame_metadata_;
+ uint32_t last_frame_token_ = 0;
+ base::Optional<cc::RenderFrameMetadata> last_render_frame_metadata_;
+
+ // Not owned.
+ cc::FrameTokenAllocator* frame_token_allocator_ = nullptr;
// These are destroyed when BindToCurrentThread() is called.
mojom::RenderFrameMetadataObserverRequest request_;
diff --git a/chromium/content/renderer/render_frame_proxy.cc b/chromium/content/renderer/render_frame_proxy.cc
index 0cc7391676f..515172448f0 100644
--- a/chromium/content/renderer/render_frame_proxy.cc
+++ b/chromium/content/renderer/render_frame_proxy.cc
@@ -22,6 +22,7 @@
#include "content/public/common/content_client.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/screen_info.h"
+#include "content/public/common/use_zoom_for_dsf_policy.h"
#include "content/public/renderer/content_renderer_client.h"
#include "content/renderer/child_frame_compositing_helper.h"
#include "content/renderer/frame_owner_properties.h"
@@ -32,18 +33,19 @@
#include "content/renderer/render_widget.h"
#include "content/renderer/resource_timing_info_conversions.h"
#include "ipc/ipc_message_macros.h"
-#include "printing/features/features.h"
-#include "third_party/WebKit/public/common/feature_policy/feature_policy.h"
-#include "third_party/WebKit/public/common/frame/frame_policy.h"
-#include "third_party/WebKit/public/platform/URLConversion.h"
-#include "third_party/WebKit/public/platform/WebRect.h"
-#include "third_party/WebKit/public/platform/WebResourceTimingInfo.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebTriggeringEventInfo.h"
-#include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
-#include "third_party/WebKit/public/web/WebView.h"
+#include "printing/buildflags/buildflags.h"
+#include "third_party/blink/public/common/feature_policy/feature_policy.h"
+#include "third_party/blink/public/common/frame/frame_policy.h"
+#include "third_party/blink/public/platform/url_conversion.h"
+#include "third_party/blink/public/platform/web_rect.h"
+#include "third_party/blink/public/platform/web_resource_timing_info.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_triggering_event_info.h"
+#include "third_party/blink/public/web/web_user_gesture_indicator.h"
+#include "third_party/blink/public/web/web_view.h"
#include "ui/base/ui_base_features.h"
+#include "ui/gfx/geometry/size_conversions.h"
#if defined(USE_AURA)
#include "content/renderer/mus/mus_embedded_frame.h"
@@ -367,8 +369,9 @@ void RenderFrameProxy::SetChildFrameSurface(
return;
if (!enable_surface_synchronization_) {
- compositing_helper_->SetPrimarySurfaceId(surface_info.id(),
- local_frame_size());
+ compositing_helper_->SetPrimarySurfaceId(
+ surface_info.id(), local_frame_size(),
+ cc::DeadlinePolicy::UseDefaultDeadline());
}
compositing_helper_->SetFallbackSurfaceId(surface_info.id(),
local_frame_size());
@@ -415,6 +418,8 @@ bool RenderFrameProxy::OnMessageReceived(const IPC::Message& msg) {
IPC_MESSAGE_HANDLER(FrameMsg_DidUpdateOrigin, OnDidUpdateOrigin)
IPC_MESSAGE_HANDLER(InputMsg_SetFocus, OnSetPageFocus)
IPC_MESSAGE_HANDLER(FrameMsg_ResizeDueToAutoResize, OnResizeDueToAutoResize)
+ IPC_MESSAGE_HANDLER(FrameMsg_EnableAutoResize, OnEnableAutoResize)
+ IPC_MESSAGE_HANDLER(FrameMsg_DisableAutoResize, OnDisableAutoResize)
IPC_MESSAGE_HANDLER(FrameMsg_SetFocusedFrame, OnSetFocusedFrame)
IPC_MESSAGE_HANDLER(FrameMsg_WillEnterFullscreen, OnWillEnterFullscreen)
IPC_MESSAGE_HANDLER(FrameMsg_SetHasReceivedUserGesture,
@@ -560,7 +565,20 @@ void RenderFrameProxy::OnScrollRectToVisible(
}
void RenderFrameProxy::OnResizeDueToAutoResize(uint64_t sequence_number) {
- pending_resize_params_.sequence_number = sequence_number;
+ pending_resize_params_.auto_resize_sequence_number = sequence_number;
+ WasResized();
+}
+
+void RenderFrameProxy::OnEnableAutoResize(const gfx::Size& min_size,
+ const gfx::Size& max_size) {
+ pending_resize_params_.auto_resize_enabled = true;
+ pending_resize_params_.min_size_for_auto_resize = min_size;
+ pending_resize_params_.max_size_for_auto_resize = max_size;
+ WasResized();
+}
+
+void RenderFrameProxy::OnDisableAutoResize() {
+ pending_resize_params_.auto_resize_enabled = false;
WasResized();
}
@@ -577,20 +595,30 @@ void RenderFrameProxy::WasResized() {
bool synchronized_params_changed =
!sent_resize_params_ ||
+ sent_resize_params_->auto_resize_enabled !=
+ pending_resize_params_.auto_resize_enabled ||
+ sent_resize_params_->min_size_for_auto_resize !=
+ pending_resize_params_.min_size_for_auto_resize ||
+ sent_resize_params_->max_size_for_auto_resize !=
+ pending_resize_params_.max_size_for_auto_resize ||
sent_resize_params_->local_frame_size !=
pending_resize_params_.local_frame_size ||
sent_resize_params_->screen_space_rect.size() !=
pending_resize_params_.screen_space_rect.size() ||
sent_resize_params_->screen_info != pending_resize_params_.screen_info ||
- sent_resize_params_->sequence_number !=
- pending_resize_params_.sequence_number;
+ sent_resize_params_->auto_resize_sequence_number !=
+ pending_resize_params_.auto_resize_sequence_number;
if (synchronized_params_changed)
local_surface_id_ = parent_local_surface_id_allocator_.GenerateId();
viz::SurfaceId surface_id(frame_sink_id_, local_surface_id_);
if (enable_surface_synchronization_) {
- compositing_helper_->SetPrimarySurfaceId(surface_id, local_frame_size());
+ // TODO(vmpstr): When capture_sequence_number is available, the deadline
+ // should be infinite if the sequence number has changed.
+ compositing_helper_->SetPrimarySurfaceId(
+ surface_id, local_frame_size(),
+ cc::DeadlinePolicy::UseDefaultDeadline());
}
bool rect_changed =
@@ -605,13 +633,20 @@ void RenderFrameProxy::WasResized() {
}
#endif
- if (resize_params_changed) {
- // Let the browser know about the updated view rect.
- Send(new FrameHostMsg_UpdateResizeParams(
- routing_id_, screen_space_rect(), local_frame_size(), screen_info(),
- auto_size_sequence_number(), surface_id));
- sent_resize_params_ = pending_resize_params_;
- }
+ if (!resize_params_changed)
+ return;
+
+ // Let the browser know about the updated view rect.
+ Send(new FrameHostMsg_UpdateResizeParams(routing_id_, surface_id,
+ pending_resize_params_));
+ sent_resize_params_ = pending_resize_params_;
+
+ // The visible rect that the OOPIF needs to raster depends partially on
+ // parameters that might have changed. If they affect the raster area, resend
+ // the intersection rects.
+ gfx::Rect new_compositor_visible_rect = web_frame_->GetCompositingRect();
+ if (new_compositor_visible_rect != last_compositor_visible_rect_)
+ UpdateRemoteViewportIntersection(last_intersection_rect_);
}
void RenderFrameProxy::OnSetHasReceivedUserGestureBeforeNavigation(bool value) {
@@ -731,9 +766,12 @@ void RenderFrameProxy::FrameRectsChanged(
}
void RenderFrameProxy::UpdateRemoteViewportIntersection(
- const blink::WebRect& viewportIntersection) {
+ const blink::WebRect& viewport_intersection) {
+ last_intersection_rect_ = viewport_intersection;
+ last_compositor_visible_rect_ = web_frame_->GetCompositingRect();
Send(new FrameHostMsg_UpdateViewportIntersection(
- routing_id_, gfx::Rect(viewportIntersection)));
+ routing_id_, gfx::Rect(viewport_intersection),
+ last_compositor_visible_rect_));
}
void RenderFrameProxy::VisibilityChanged(bool visible) {
diff --git a/chromium/content/renderer/render_frame_proxy.h b/chromium/content/renderer/render_frame_proxy.h
index e4d85693dcc..fde712e1477 100644
--- a/chromium/content/renderer/render_frame_proxy.h
+++ b/chromium/content/renderer/render_frame_proxy.h
@@ -10,16 +10,17 @@
#include "components/viz/common/surfaces/parent_local_surface_id_allocator.h"
#include "content/common/content_export.h"
#include "content/common/frame_messages.h"
+#include "content/common/frame_resize_params.h"
#include "content/public/common/screen_info.h"
#include "content/renderer/child_frame_compositor.h"
#include "ipc/ipc_listener.h"
#include "ipc/ipc_sender.h"
-#include "third_party/WebKit/public/common/feature_policy/feature_policy.h"
-#include "third_party/WebKit/public/platform/WebCanvas.h"
-#include "third_party/WebKit/public/platform/WebFocusType.h"
-#include "third_party/WebKit/public/platform/WebInsecureRequestPolicy.h"
-#include "third_party/WebKit/public/web/WebRemoteFrame.h"
-#include "third_party/WebKit/public/web/WebRemoteFrameClient.h"
+#include "third_party/blink/public/common/feature_policy/feature_policy.h"
+#include "third_party/blink/public/platform/web_canvas.h"
+#include "third_party/blink/public/platform/web_focus_type.h"
+#include "third_party/blink/public/platform/web_insecure_request_policy.h"
+#include "third_party/blink/public/web/web_remote_frame.h"
+#include "third_party/blink/public/web/web_remote_frame_client.h"
#include "url/origin.h"
#if defined(USE_AURA)
@@ -168,7 +169,7 @@ class CONTENT_EXPORT RenderFrameProxy : public IPC::Listener,
}
uint64_t auto_size_sequence_number() const {
- return pending_resize_params_.sequence_number;
+ return pending_resize_params_.auto_resize_sequence_number;
}
const viz::FrameSinkId& frame_sink_id() const { return frame_sink_id_; }
@@ -186,7 +187,7 @@ class CONTENT_EXPORT RenderFrameProxy : public IPC::Listener,
void FrameRectsChanged(const blink::WebRect& local_frame_rect,
const blink::WebRect& screen_space_rect) override;
void UpdateRemoteViewportIntersection(
- const blink::WebRect& viewportIntersection) override;
+ const blink::WebRect& viewport_intersection) override;
void VisibilityChanged(bool visible) override;
void SetIsInert(bool) override;
void UpdateRenderThrottlingStatus(bool is_throttled,
@@ -250,6 +251,8 @@ class CONTENT_EXPORT RenderFrameProxy : public IPC::Listener,
void OnScrollRectToVisible(const gfx::Rect& rect_to_scroll,
const blink::WebScrollIntoViewParams& params);
void OnResizeDueToAutoResize(uint64_t sequence_number);
+ void OnEnableAutoResize(const gfx::Size& min_size, const gfx::Size& max_size);
+ void OnDisableAutoResize();
void OnSetHasReceivedUserGestureBeforeNavigation(bool value);
#if defined(USE_AURA)
@@ -285,23 +288,15 @@ class CONTENT_EXPORT RenderFrameProxy : public IPC::Listener,
// defined by the browser and passed into Blink upon frame creation.
base::UnguessableToken devtools_frame_token_;
- // TODO(fsamuel): We might want to unify this with content::ResizeParams.
// TODO(fsamuel): Most RenderFrameProxys don't host viz::Surfaces and
// therefore don't care to synchronize ResizeParams with viz::LocalSurfaceIds.
// Perhaps this can be moved to ChildFrameCompositingHelper?
- struct ResizeParams {
- gfx::Rect screen_space_rect;
- gfx::Size local_frame_size;
- ScreenInfo screen_info;
- uint64_t sequence_number = 0lu;
- };
-
// The last ResizeParams sent to the browser process, if any.
- base::Optional<ResizeParams> sent_resize_params_;
+ base::Optional<FrameResizeParams> sent_resize_params_;
// The current set of ResizeParams. This may or may not match
// |sent_resize_params_|.
- ResizeParams pending_resize_params_;
+ FrameResizeParams pending_resize_params_;
bool crashed_ = false;
@@ -311,6 +306,9 @@ class CONTENT_EXPORT RenderFrameProxy : public IPC::Listener,
bool enable_surface_synchronization_ = false;
+ gfx::Rect last_intersection_rect_;
+ gfx::Rect last_compositor_visible_rect_;
+
#if defined(USE_AURA)
std::unique_ptr<MusEmbeddedFrame> mus_embedded_frame_;
#endif
diff --git a/chromium/content/renderer/render_process_impl.cc b/chromium/content/renderer/render_process_impl.cc
index 4f2e04156db..33800c023f5 100644
--- a/chromium/content/renderer/render_process_impl.cc
+++ b/chromium/content/renderer/render_process_impl.cc
@@ -34,9 +34,8 @@
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/renderer/content_renderer_client.h"
-#include "content/renderer/loader/site_isolation_stats_gatherer.h"
#include "services/service_manager/embedder/switches.h"
-#include "third_party/WebKit/public/web/WebFrame.h"
+#include "third_party/blink/public/web/web_frame.h"
#include "v8/include/v8.h"
#if defined(OS_WIN)
@@ -86,13 +85,13 @@ GetDefaultTaskSchedulerInitParams() {
kSuggestedReclaimTime));
}
-#if DCHECK_IS_ON() && defined(SYZYASAN)
+#if DCHECK_IS_CONFIGURABLE
void V8DcheckCallbackHandler(const char* file, int line, const char* message) {
// TODO(siggi): Set a crash key or a breadcrumb so the fact that we hit a
// V8 DCHECK gets out in the crash report.
::logging::LogMessage(file, line, logging::LOG_DCHECK).stream() << message;
}
-#endif // DCHECK_IS_ON() && defined(SYZYASAN)
+#endif // DCHECK_IS_CONFIGURABLE
} // namespace
@@ -102,31 +101,14 @@ RenderProcessImpl::RenderProcessImpl(
std::unique_ptr<base::TaskScheduler::InitParams> task_scheduler_init_params)
: RenderProcess("Renderer", std::move(task_scheduler_init_params)),
enabled_bindings_(0) {
-#if defined(OS_WIN)
- // HACK: See http://b/issue?id=1024307 for rationale.
- if (GetModuleHandle(L"LPK.DLL") == NULL) {
- // Makes sure lpk.dll is loaded by gdi32 to make sure ExtTextOut() works
- // when buffering into a EMF buffer for printing.
- typedef BOOL (__stdcall *GdiInitializeLanguagePack)(int LoadedShapingDLLs);
- GdiInitializeLanguagePack gdi_init_lpk =
- reinterpret_cast<GdiInitializeLanguagePack>(GetProcAddress(
- GetModuleHandle(L"GDI32.DLL"),
- "GdiInitializeLanguagePack"));
- DCHECK(gdi_init_lpk);
- if (gdi_init_lpk) {
- gdi_init_lpk(0);
- }
- }
-#endif
-
-#if DCHECK_IS_ON() && defined(SYZYASAN)
- // SyzyASAN official builds can ship with DCHECKs compiled in. Failing DCHECKs
- // then are either fatal or simply log the error, based on a feature flag.
+#if DCHECK_IS_CONFIGURABLE
+ // Some official builds ship with DCHECKs compiled in. Failing DCHECKs then
+ // are either fatal or simply log the error, based on a feature flag.
// Make sure V8 follows suit by setting a Dcheck handler that forwards to
// the Chrome base logging implementation.
v8::V8::SetDcheckErrorHandler(&V8DcheckCallbackHandler);
- if (!base::FeatureList::IsEnabled(base::kSyzyAsanDCheckIsFatalFeature)) {
+ if (!base::FeatureList::IsEnabled(base::kDCheckIsFatalFeature)) {
// These V8 flags default on in this build configuration. This triggers
// additional verification and code generation, which both slows down V8,
// and can lead to fatal CHECKs. Turn these flags down to get something
@@ -139,7 +121,7 @@ RenderProcessImpl::RenderProcessImpl(
v8::V8::SetFlagsFromString(kDisabledFlags, sizeof(kDisabledFlags));
}
-#endif // DCHECK_IS_ON() && defined(SYZYASAN)
+#endif // DCHECK_IS_CONFIGURABLE
if (base::SysInfo::IsLowEndDevice()) {
std::string optimize_flag("--optimize-for-size");
@@ -158,7 +140,6 @@ RenderProcessImpl::RenderProcessImpl(
SetV8FlagIfNotFeature(features::kAsmJsToWebAssembly, "--no-validate-asm");
SetV8FlagIfNotFeature(features::kWebAssembly,
"--wasm-disable-structured-cloning");
- SetV8FlagIfFeature(features::kV8BackgroundCompile, "--background-compile");
SetV8FlagIfFeature(features::kV8VmFuture, "--future");
SetV8FlagIfNotFeature(features::kV8VmFuture, "--no-future");
@@ -167,15 +148,15 @@ RenderProcessImpl::RenderProcessImpl(
SetV8FlagIfNotFeature(features::kSharedArrayBuffer,
"--no-harmony-sharedarraybuffer");
- SetV8FlagIfFeature(features::kWebAssemblyTrapHandler, "--wasm-trap-handler");
SetV8FlagIfNotFeature(features::kWebAssemblyTrapHandler,
"--no-wasm-trap-handler");
SetV8FlagIfFeature(features::kArrayPrototypeValues,
"--harmony-array-prototype-values");
SetV8FlagIfNotFeature(features::kArrayPrototypeValues,
- "--no-harmony-array-prototype-values");
+ "--no-harmony-array-prototype-values");
#if defined(OS_LINUX) && defined(ARCH_CPU_X86_64) && !defined(OS_ANDROID)
if (base::FeatureList::IsEnabled(features::kWebAssemblyTrapHandler)) {
+ bool use_v8_signal_handler = false;
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (!command_line->HasSwitch(
service_manager::switches::kDisableInProcessStackTraces)) {
@@ -187,8 +168,10 @@ RenderProcessImpl::RenderProcessImpl(
// in-process stack traces are disabled then there will be no signal
// handler. In this case, we fall back on V8's default handler
// (https://crbug.com/798150).
- v8::V8::RegisterDefaultSignalHandler();
+ use_v8_signal_handler = true;
}
+ // TODO(eholk): report UMA stat for how often this succeeds
+ v8::V8::EnableWebAssemblyTrapHandler(use_v8_signal_handler);
}
#endif
@@ -201,9 +184,6 @@ RenderProcessImpl::RenderProcessImpl(
v8::V8::SetFlagsFromString(flags.c_str(), static_cast<int>(flags.size()));
}
- SiteIsolationStatsGatherer::SetEnabled(
- GetContentClient()->renderer()->ShouldGatherSiteIsolationStats());
-
if (command_line.HasSwitch(switches::kDomAutomationController))
enabled_bindings_ |= BINDINGS_POLICY_DOM_AUTOMATION;
if (command_line.HasSwitch(switches::kStatsCollectionController))
diff --git a/chromium/content/renderer/render_thread_impl.cc b/chromium/content/renderer/render_thread_impl.cc
index 81d3f80db8e..089bc9a3188 100644
--- a/chromium/content/renderer/render_thread_impl.cc
+++ b/chromium/content/renderer/render_thread_impl.cc
@@ -18,7 +18,6 @@
#include "base/macros.h"
#include "base/memory/discardable_memory_allocator.h"
#include "base/memory/memory_coordinator_client_registry.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/shared_memory.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/field_trial.h"
@@ -54,15 +53,16 @@
#include "components/viz/client/client_shared_bitmap_manager.h"
#include "components/viz/client/hit_test_data_provider.h"
#include "components/viz/client/hit_test_data_provider_draw_quad.h"
+#include "components/viz/client/hit_test_data_provider_surface_layer.h"
#include "components/viz/client/local_surface_id_provider.h"
#include "components/viz/common/features.h"
#include "components/viz/common/frame_sinks/copy_output_request.h"
#include "content/child/memory/child_memory_coordinator_impl.h"
#include "content/child/runtime_features.h"
#include "content/child/thread_safe_sender.h"
+#include "content/common/buildflags.h"
#include "content/common/content_constants_internal.h"
#include "content/common/dom_storage/dom_storage_messages.h"
-#include "content/common/features.h"
#include "content/common/frame_messages.h"
#include "content/common/frame_owner_properties.h"
#include "content/common/gpu_stream_constants.h"
@@ -84,8 +84,6 @@
#include "content/renderer/appcache/appcache_dispatcher.h"
#include "content/renderer/appcache/appcache_frontend_impl.h"
#include "content/renderer/browser_plugin/browser_plugin_manager.h"
-#include "content/renderer/cache_storage/cache_storage_dispatcher.h"
-#include "content/renderer/cache_storage/cache_storage_message_filter.h"
#include "content/renderer/categorized_worker_pool.h"
#include "content/renderer/dom_storage/dom_storage_dispatcher.h"
#include "content/renderer/dom_storage/webstoragearea_impl.h"
@@ -137,7 +135,7 @@
#include "ipc/ipc_platform_file.h"
#include "media/base/media.h"
#include "media/base/media_switches.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "media/video/gpu_video_accelerator_factories.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "mojo/public/cpp/system/message_pipe.h"
@@ -145,7 +143,7 @@
#include "net/base/port_util.h"
#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
#include "net/base/url_util.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#include "services/metrics/public/cpp/mojo_ukm_recorder.h"
#include "services/service_manager/public/cpp/connector.h"
#include "services/service_manager/public/cpp/interface_provider.h"
@@ -154,21 +152,21 @@
#include "services/ui/public/interfaces/constants.mojom.h"
#include "skia/ext/event_tracer_impl.h"
#include "skia/ext/skia_memory_dump_provider.h"
-#include "third_party/WebKit/public/platform/WebCache.h"
-#include "third_party/WebKit/public/platform/WebImageGenerator.h"
-#include "third_party/WebKit/public/platform/WebMemoryCoordinator.h"
-#include "third_party/WebKit/public/platform/WebNetworkStateNotifier.h"
-#include "third_party/WebKit/public/platform/WebRuntimeFeatures.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebThread.h"
-#include "third_party/WebKit/public/platform/scheduler/child/webthread_base.h"
-#include "third_party/WebKit/public/platform/scheduler/renderer/renderer_scheduler.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebFrame.h"
-#include "third_party/WebKit/public/web/WebKit.h"
-#include "third_party/WebKit/public/web/WebScriptController.h"
-#include "third_party/WebKit/public/web/WebSecurityPolicy.h"
-#include "third_party/WebKit/public/web/WebView.h"
+#include "third_party/blink/public/platform/scheduler/child/webthread_base.h"
+#include "third_party/blink/public/platform/scheduler/web_main_thread_scheduler.h"
+#include "third_party/blink/public/platform/web_cache.h"
+#include "third_party/blink/public/platform/web_image_generator.h"
+#include "third_party/blink/public/platform/web_memory_coordinator.h"
+#include "third_party/blink/public/platform/web_network_state_notifier.h"
+#include "third_party/blink/public/platform/web_runtime_features.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_thread.h"
+#include "third_party/blink/public/web/blink.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_frame.h"
+#include "third_party/blink/public/web/web_script_controller.h"
+#include "third_party/blink/public/web/web_security_policy.h"
+#include "third_party/blink/public/web/web_view.h"
#include "third_party/boringssl/src/include/openssl/evp.h"
#include "third_party/skia/include/core/SkGraphics.h"
#include "ui/base/layout.h"
@@ -363,6 +361,7 @@ scoped_refptr<ui::ContextProviderCommandBuffer> CreateOffscreenContext(
bool support_gles2_interface,
bool support_raster_interface,
bool support_oop_rasterization,
+ bool support_grcontext,
ui::command_buffer_metrics::ContextType type,
int32_t stream_id,
gpu::SchedulingPriority stream_priority) {
@@ -385,13 +384,22 @@ scoped_refptr<ui::ContextProviderCommandBuffer> CreateOffscreenContext(
attributes.enable_raster_interface = support_raster_interface;
attributes.enable_oop_rasterization = support_oop_rasterization;
+ bool enable_raster_decoder =
+ base::CommandLine::ForCurrentProcess()->HasSwitch(
+ switches::kEnableRasterDecoder);
+ // --enable-raster-decoder supports raster interface, but not
+ // gles2 interface
+ attributes.enable_raster_decoder = enable_raster_decoder &&
+ support_raster_interface &&
+ !support_gles2_interface;
+
const bool automatic_flushes = false;
return base::MakeRefCounted<ui::ContextProviderCommandBuffer>(
std::move(gpu_channel_host), gpu_memory_buffer_manager, stream_id,
stream_priority, gpu::kNullSurfaceHandle,
GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext/" +
ui::command_buffer_metrics::ContextTypeToString(type)),
- automatic_flushes, support_locking, limits, attributes,
+ automatic_flushes, support_locking, support_grcontext, limits, attributes,
nullptr /* share_context */, type);
}
@@ -522,7 +530,8 @@ class ResourceUsageReporterImpl : public content::mojom::ResourceUsageReporter {
base::RepeatingClosure collect = base::BindRepeating(
&ResourceUsageReporterImpl::CollectOnWorkerThread,
base::ThreadTaskRunnerHandle::Get(), weak_factory_.GetWeakPtr());
- workers_to_go_ = RenderThread::Get()->PostTaskToAllWebWorkers(collect);
+ workers_to_go_ =
+ RenderThread::Get()->PostTaskToAllWebWorkers(std::move(collect));
if (workers_to_go_) {
// The guard task to send out partial stats
// in case some workers are not responsive.
@@ -660,22 +669,25 @@ bool RenderThreadImpl::HistogramCustomizer::IsAlexaTop10NonGoogleSite(
// static
RenderThreadImpl* RenderThreadImpl::Create(
- const InProcessChildThreadParams& params) {
+ const InProcessChildThreadParams& params,
+ base::MessageLoop* unowned_message_loop) {
TRACE_EVENT0("startup", "RenderThreadImpl::Create");
- std::unique_ptr<blink::scheduler::RendererScheduler> renderer_scheduler =
- blink::scheduler::RendererScheduler::Create();
+ std::unique_ptr<blink::scheduler::WebMainThreadScheduler>
+ main_thread_scheduler =
+ blink::scheduler::WebMainThreadScheduler::Create();
scoped_refptr<base::SingleThreadTaskRunner> test_task_counter;
- return new RenderThreadImpl(
- params, std::move(renderer_scheduler), test_task_counter);
+ return new RenderThreadImpl(params, std::move(main_thread_scheduler),
+ test_task_counter, unowned_message_loop);
}
// static
RenderThreadImpl* RenderThreadImpl::Create(
std::unique_ptr<base::MessageLoop> main_message_loop,
- std::unique_ptr<blink::scheduler::RendererScheduler> renderer_scheduler) {
+ std::unique_ptr<blink::scheduler::WebMainThreadScheduler>
+ main_thread_scheduler) {
TRACE_EVENT0("startup", "RenderThreadImpl::Create");
return new RenderThreadImpl(std::move(main_message_loop),
- std::move(renderer_scheduler));
+ std::move(main_thread_scheduler));
}
// static
@@ -722,8 +734,9 @@ RenderThreadImpl::DeprecatedGetMainTaskRunner() {
// the browser
RenderThreadImpl::RenderThreadImpl(
const InProcessChildThreadParams& params,
- std::unique_ptr<blink::scheduler::RendererScheduler> scheduler,
- const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue)
+ std::unique_ptr<blink::scheduler::WebMainThreadScheduler> scheduler,
+ const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue,
+ base::MessageLoop* unowned_message_loop)
: ChildThreadImpl(
Options::Builder()
.InBrowserProcess(params)
@@ -731,7 +744,8 @@ RenderThreadImpl::RenderThreadImpl(
.ConnectToBrowser(true)
.IPCTaskRunner(scheduler ? scheduler->IPCTaskRunner() : nullptr)
.Build()),
- renderer_scheduler_(std::move(scheduler)),
+ main_thread_scheduler_(std::move(scheduler)),
+ main_message_loop_(unowned_message_loop),
categorized_worker_pool_(new CategorizedWorkerPool()),
renderer_binding_(this),
client_id_(1),
@@ -743,16 +757,17 @@ RenderThreadImpl::RenderThreadImpl(
// When we run plugins in process, we actually run them on the render thread,
// which means that we need to make the render thread pump UI events.
RenderThreadImpl::RenderThreadImpl(
- std::unique_ptr<base::MessageLoop> main_message_loop,
- std::unique_ptr<blink::scheduler::RendererScheduler> scheduler)
+ std::unique_ptr<base::MessageLoop> owned_message_loop,
+ std::unique_ptr<blink::scheduler::WebMainThreadScheduler> scheduler)
: ChildThreadImpl(
Options::Builder()
.AutoStartServiceManagerConnection(false)
.ConnectToBrowser(true)
.IPCTaskRunner(scheduler ? scheduler->IPCTaskRunner() : nullptr)
.Build()),
- renderer_scheduler_(std::move(scheduler)),
- main_message_loop_(std::move(main_message_loop)),
+ main_thread_scheduler_(std::move(scheduler)),
+ owned_message_loop_(std::move(owned_message_loop)),
+ main_message_loop_(owned_message_loop_.get()),
categorized_worker_pool_(new CategorizedWorkerPool()),
is_scroll_animator_enabled_(false),
renderer_binding_(this),
@@ -771,6 +786,12 @@ void RenderThreadImpl::Init(
const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue) {
TRACE_EVENT0("startup", "RenderThreadImpl::Init");
+ // Whether owned or unowned, |main_message_loop_| needs to be initialized in
+ // all constructors.
+ DCHECK(main_message_loop_);
+
+ GetContentClient()->renderer()->PostIOThreadCreated(GetIOTaskRunner().get());
+
base::trace_event::TraceLog::GetInstance()->SetThreadSortIndex(
base::PlatformThread::CurrentId(),
kTraceEventRendererMainThreadSortIndex);
@@ -781,7 +802,7 @@ void RenderThreadImpl::Init(
#endif
lazy_tls.Pointer()->Set(this);
- g_main_task_runner.Get() = base::MessageLoop::current()->task_runner();
+ g_main_task_runner.Get() = main_message_loop_->task_runner();
// Register this object as the main thread.
ChildProcess::current()->set_main_thread(this);
@@ -806,8 +827,8 @@ void RenderThreadImpl::Init(
shared_bitmap_allocation_notifier_ptr.PassInterface(),
GetChannel()->ipc_task_runner_refptr()));
- notification_dispatcher_ =
- new NotificationDispatcher(thread_safe_sender());
+ notification_dispatcher_ = new NotificationDispatcher(
+ thread_safe_sender(), GetWebMainThreadScheduler()->IPCTaskRunner());
AddFilter(notification_dispatcher_->GetFilter());
resource_dispatcher_.reset(new ResourceDispatcher());
@@ -831,11 +852,9 @@ void RenderThreadImpl::Init(
registry->AddInterface(
base::BindRepeating(&AppCacheDispatcher::Bind,
base::Unretained(appcache_dispatcher())),
- GetRendererScheduler()->IPCTaskRunner());
+ GetWebMainThreadScheduler()->IPCTaskRunner());
dom_storage_dispatcher_.reset(new DomStorageDispatcher());
main_thread_indexed_db_dispatcher_.reset(new IndexedDBDispatcher());
- main_thread_cache_storage_dispatcher_.reset(
- new CacheStorageDispatcher(thread_safe_sender()));
file_system_dispatcher_.reset(new FileSystemDispatcher());
vc_manager_.reset(new VideoCaptureImplManager());
@@ -894,8 +913,6 @@ void RenderThreadImpl::Init(
midi_message_filter_ = new MidiMessageFilter(GetIOTaskRunner());
AddFilter(midi_message_filter_.get());
- AddFilter((new CacheStorageMessageFilter(thread_safe_sender()))->GetFilter());
-
#if defined(USE_AURA)
if (features::IsMusEnabled())
CreateRenderWidgetWindowTreeClientFactory(GetServiceManagerConnection());
@@ -994,17 +1011,6 @@ void RenderThreadImpl::Init(
gpu_rasterization_msaa_sample_count_ = -1;
}
- if (command_line.HasSwitch(switches::kDisableDistanceFieldText)) {
- is_distance_field_text_enabled_ = false;
- } else if (command_line.HasSwitch(switches::kEnableDistanceFieldText)) {
- is_distance_field_text_enabled_ = true;
- } else {
- is_distance_field_text_enabled_ = false;
- }
-
- WebRuntimeFeatures::EnableCompositorImageAnimations(
- command_line.HasSwitch(switches::kEnableCompositorImageAnimations));
-
// Note that under Linux, the media library will normally already have
// been initialized by the Zygote before this instance became a Renderer.
media::InitializeMediaLibrary();
@@ -1177,11 +1183,11 @@ bool RenderThreadImpl::Send(IPC::Message* msg) {
}
}
- std::unique_ptr<blink::scheduler::RendererScheduler::RendererPauseHandle>
+ std::unique_ptr<blink::scheduler::WebMainThreadScheduler::RendererPauseHandle>
renderer_paused_handle;
if (pumping_events) {
- renderer_paused_handle = renderer_scheduler_->PauseRenderer();
+ renderer_paused_handle = main_thread_scheduler_->PauseRenderer();
WebView::WillEnterModalLoop();
}
@@ -1283,12 +1289,13 @@ void RenderThreadImpl::SetResourceDispatcherDelegate(
}
void RenderThreadImpl::InitializeCompositorThread() {
- base::Thread::Options options;
+ blink::WebThreadCreationParams params(
+ blink::WebThreadType::kCompositorThread);
#if defined(OS_ANDROID)
- options.priority = base::ThreadPriority::DISPLAY;
+ params.thread_options.priority = base::ThreadPriority::DISPLAY;
#endif
compositor_thread_ =
- blink::scheduler::WebThreadBase::CreateCompositorThread(options);
+ blink::scheduler::WebThreadBase::CreateCompositorThread(params);
blink_platform_impl_->SetCompositorThread(compositor_thread_.get());
compositor_task_runner_ = compositor_thread_->GetTaskRunner();
compositor_task_runner_->PostTask(
@@ -1323,7 +1330,7 @@ void RenderThreadImpl::InitializeCompositorThread() {
input_event_filter_ = compositor_input_event_filter;
input_handler_manager_.reset(new InputHandlerManager(
compositor_task_runner_, input_handler_manager_client,
- synchronous_input_handler_proxy_client, renderer_scheduler_.get()));
+ synchronous_input_handler_proxy_client, main_thread_scheduler_.get()));
}
}
@@ -1341,7 +1348,7 @@ void RenderThreadImpl::InitializeWebKit(
#endif
blink_platform_impl_.reset(
- new RendererBlinkPlatformImpl(renderer_scheduler_.get()));
+ new RendererBlinkPlatformImpl(main_thread_scheduler_.get()));
SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line);
GetContentClient()
->renderer()
@@ -1351,10 +1358,10 @@ void RenderThreadImpl::InitializeWebKit(
v8::Isolate* isolate = blink::MainThreadIsolate();
isolate->SetCreateHistogramFunction(CreateHistogram);
isolate->SetAddHistogramSampleFunction(AddHistogramSample);
- renderer_scheduler_->SetRAILModeObserver(this);
+ main_thread_scheduler_->SetRAILModeObserver(this);
main_thread_compositor_task_runner_ =
- renderer_scheduler_->CompositorTaskRunner();
+ main_thread_scheduler_->CompositorTaskRunner();
main_input_callback_.Reset(
base::Bind(base::IgnoreResult(&RenderThreadImpl::OnMessageReceived),
@@ -1383,6 +1390,8 @@ void RenderThreadImpl::InitializeWebKit(
RenderMediaClient::Initialize();
+ idle_timer_.SetTaskRunner(GetWebMainThreadScheduler()->DefaultTaskRunner());
+
if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden()) {
ScheduleIdleHandler(kLongIdleHandlerDelayMs);
} else {
@@ -1391,11 +1400,11 @@ void RenderThreadImpl::InitializeWebKit(
isolate->IsolateInBackgroundNotification();
}
- service_worker_message_filter_ =
- new ServiceWorkerMessageFilter(thread_safe_sender());
+ service_worker_message_filter_ = new ServiceWorkerMessageFilter(
+ thread_safe_sender(), GetWebMainThreadScheduler()->IPCTaskRunner());
AddFilter(service_worker_message_filter_->GetFilter());
- renderer_scheduler_->SetStoppingWhenBackgroundedEnabled(
+ main_thread_scheduler_->SetStoppingWhenBackgroundedEnabled(
GetContentClient()->renderer()->AllowStoppingWhenProcessBackgrounded());
SkGraphics::SetResourceCacheSingleAllocationByteLimit(
@@ -1536,23 +1545,14 @@ media::GpuVideoAcceleratorFactories* RenderThreadImpl::GetGpuFactories() {
DCHECK(IsMainThread());
if (!gpu_factories_.empty()) {
- scoped_refptr<ui::ContextProviderCommandBuffer> shared_context_provider =
- gpu_factories_.back()->ContextProviderMainThread();
- if (shared_context_provider) {
- viz::ContextProvider::ScopedContextLock lock(
- shared_context_provider.get());
- if (lock.ContextGL()->GetGraphicsResetStatusKHR() == GL_NO_ERROR)
- return gpu_factories_.back().get();
-
- scoped_refptr<base::SingleThreadTaskRunner> media_task_runner =
- GetMediaThreadTaskRunner();
- media_task_runner->PostTask(
- FROM_HERE,
- base::BindOnce(
- base::IgnoreResult(
- &GpuVideoAcceleratorFactoriesImpl::CheckContextLost),
- base::Unretained(gpu_factories_.back().get())));
- }
+ if (!gpu_factories_.back()->CheckContextProviderLost())
+ return gpu_factories_.back().get();
+
+ GetMediaThreadTaskRunner()->PostTask(
+ FROM_HERE,
+ base::BindOnce(base::IgnoreResult(
+ &GpuVideoAcceleratorFactoriesImpl::CheckContextLost),
+ base::Unretained(gpu_factories_.back().get())));
}
const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
@@ -1564,22 +1564,19 @@ media::GpuVideoAcceleratorFactories* RenderThreadImpl::GetGpuFactories() {
// This context is only used to create textures and mailbox them, so
// use lower limits than the default.
gpu::SharedMemoryLimits limits = gpu::SharedMemoryLimits::ForMailboxContext();
- bool support_locking = true;
+ bool support_locking = false;
bool support_gles2_interface = true;
bool support_raster_interface = false;
bool support_oop_rasterization = false;
+ bool support_grcontext = false;
scoped_refptr<ui::ContextProviderCommandBuffer> media_context_provider =
- CreateOffscreenContext(
- gpu_channel_host, GetGpuMemoryBufferManager(), limits,
- support_locking, support_gles2_interface, support_raster_interface,
- support_oop_rasterization, ui::command_buffer_metrics::MEDIA_CONTEXT,
- kGpuStreamIdMedia, kGpuStreamPriorityMedia);
- auto result = media_context_provider->BindToCurrentThread();
- if (result != gpu::ContextResult::kSuccess)
- return nullptr;
+ CreateOffscreenContext(gpu_channel_host, GetGpuMemoryBufferManager(),
+ limits, support_locking, support_gles2_interface,
+ support_raster_interface,
+ support_oop_rasterization, support_grcontext,
+ ui::command_buffer_metrics::MEDIA_CONTEXT,
+ kGpuStreamIdMedia, kGpuStreamPriorityMedia);
- scoped_refptr<base::SingleThreadTaskRunner> media_task_runner =
- GetMediaThreadTaskRunner();
const bool enable_video_accelerator =
!cmd_line->HasSwitch(switches::kDisableAcceleratedVideoDecode) &&
(gpu_channel_host->gpu_feature_info()
@@ -1602,7 +1599,7 @@ media::GpuVideoAcceleratorFactories* RenderThreadImpl::GetGpuFactories() {
gpu_factories_.push_back(GpuVideoAcceleratorFactoriesImpl::Create(
std::move(gpu_channel_host), base::ThreadTaskRunnerHandle::Get(),
- media_task_runner, std::move(media_context_provider),
+ GetMediaThreadTaskRunner(), std::move(media_context_provider),
enable_gpu_memory_buffer_video_frames, enable_video_accelerator,
vea_provider.PassInterface()));
gpu_factories_.back()->SetRenderingColorSpace(rendering_color_space_);
@@ -1626,12 +1623,13 @@ RenderThreadImpl::SharedMainThreadContextProvider() {
bool support_locking = false;
bool support_gles2_interface = true;
- bool support_raster_interface = true;
+ bool support_raster_interface = false;
bool support_oop_rasterization = false;
+ bool support_grcontext = true;
shared_main_thread_contexts_ = CreateOffscreenContext(
std::move(gpu_channel_host), GetGpuMemoryBufferManager(),
gpu::SharedMemoryLimits(), support_locking, support_gles2_interface,
- support_raster_interface, support_oop_rasterization,
+ support_raster_interface, support_oop_rasterization, support_grcontext,
ui::command_buffer_metrics::RENDERER_MAINTHREAD_CONTEXT,
kGpuStreamIdDefault, kGpuStreamPriorityDefault);
auto result = shared_main_thread_contexts_->BindToCurrentThread();
@@ -1685,7 +1683,7 @@ int32_t RenderThreadImpl::GetClientId() {
void RenderThreadImpl::SetRendererProcessType(
blink::scheduler::RendererProcessType type) {
- renderer_scheduler_->SetRendererProcessType(type);
+ main_thread_scheduler_->SetRendererProcessType(type);
}
bool RenderThreadImpl::OnMessageReceived(const IPC::Message& msg) {
@@ -1720,10 +1718,6 @@ bool RenderThreadImpl::IsLcdTextEnabled() {
return is_lcd_text_enabled_;
}
-bool RenderThreadImpl::IsDistanceFieldTextEnabled() {
- return is_distance_field_text_enabled_;
-}
-
bool RenderThreadImpl::IsZeroCopyEnabled() {
return is_zero_copy_enabled_;
}
@@ -1754,8 +1748,9 @@ gpu::GpuMemoryBufferManager* RenderThreadImpl::GetGpuMemoryBufferManager() {
return gpu_->gpu_memory_buffer_manager();
}
-blink::scheduler::RendererScheduler* RenderThreadImpl::GetRendererScheduler() {
- return renderer_scheduler_.get();
+blink::scheduler::WebMainThreadScheduler*
+RenderThreadImpl::GetWebMainThreadScheduler() {
+ return main_thread_scheduler_.get();
}
std::unique_ptr<viz::SyntheticBeginFrameSource>
@@ -1835,7 +1830,7 @@ bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
}
void RenderThreadImpl::SetSchedulerKeepActive(bool keep_active) {
- renderer_scheduler_->SetSchedulerKeepActive(keep_active);
+ main_thread_scheduler_->SetSchedulerKeepActive(keep_active);
}
void RenderThreadImpl::SetProcessBackgrounded(bool backgrounded) {
@@ -1843,24 +1838,24 @@ void RenderThreadImpl::SetProcessBackgrounded(bool backgrounded) {
base::TimerSlack timer_slack = base::TIMER_SLACK_NONE;
if (backgrounded)
timer_slack = base::TIMER_SLACK_MAXIMUM;
- base::MessageLoop::current()->SetTimerSlack(timer_slack);
+ main_message_loop_->SetTimerSlack(timer_slack);
- renderer_scheduler_->SetRendererBackgrounded(backgrounded);
+ main_thread_scheduler_->SetRendererBackgrounded(backgrounded);
if (backgrounded) {
needs_to_record_first_active_paint_ = false;
- GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
+ GetWebMainThreadScheduler()->DefaultTaskRunner()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&RenderThreadImpl::RecordMemoryUsageAfterBackgrounded,
base::Unretained(this), "5min",
process_foregrounded_count_),
base::TimeDelta::FromMinutes(5));
- GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
+ GetWebMainThreadScheduler()->DefaultTaskRunner()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&RenderThreadImpl::RecordMemoryUsageAfterBackgrounded,
base::Unretained(this), "10min",
process_foregrounded_count_),
base::TimeDelta::FromMinutes(10));
- GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
+ GetWebMainThreadScheduler()->DefaultTaskRunner()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&RenderThreadImpl::RecordMemoryUsageAfterBackgrounded,
base::Unretained(this), "15min",
@@ -1887,19 +1882,19 @@ void RenderThreadImpl::ProcessPurgeAndSuspend() {
return;
purge_and_suspend_memory_metrics_ = memory_metrics;
- GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
+ GetWebMainThreadScheduler()->DefaultTaskRunner()->PostDelayedTask(
FROM_HERE,
base::BindOnce(
&RenderThreadImpl::RecordPurgeAndSuspendMemoryGrowthMetrics,
base::Unretained(this), "30min", process_foregrounded_count_),
base::TimeDelta::FromMinutes(30));
- GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
+ GetWebMainThreadScheduler()->DefaultTaskRunner()->PostDelayedTask(
FROM_HERE,
base::BindOnce(
&RenderThreadImpl::RecordPurgeAndSuspendMemoryGrowthMetrics,
base::Unretained(this), "60min", process_foregrounded_count_),
base::TimeDelta::FromMinutes(60));
- GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
+ GetWebMainThreadScheduler()->DefaultTaskRunner()->PostDelayedTask(
FROM_HERE,
base::BindOnce(
&RenderThreadImpl::RecordPurgeAndSuspendMemoryGrowthMetrics,
@@ -2095,6 +2090,9 @@ void RenderThreadImpl::RequestNewLayerTreeFrameSink(
params.hit_test_data_provider =
std::make_unique<viz::HitTestDataProviderDrawQuad>(
true /* should_ask_for_child_region */);
+ } else if (features::IsVizHitTestingSurfaceLayerEnabled()) {
+ params.hit_test_data_provider =
+ std::make_unique<viz::HitTestDataProviderSurfaceLayer>();
}
// The renderer runs animations and layout for animate_only BeginFrames.
@@ -2188,13 +2186,14 @@ void RenderThreadImpl::RequestNewLayerTreeFrameSink(
constexpr bool automatic_flushes = false;
constexpr bool support_locking = false;
+ constexpr bool support_grcontext = false;
scoped_refptr<ui::ContextProviderCommandBuffer> context_provider(
new ui::ContextProviderCommandBuffer(
gpu_channel_host, GetGpuMemoryBufferManager(), kGpuStreamIdDefault,
kGpuStreamPriorityDefault, gpu::kNullSurfaceHandle, url,
- automatic_flushes, support_locking, limits, attributes,
- nullptr /* share_context */,
+ automatic_flushes, support_locking, support_grcontext, limits,
+ attributes, nullptr /* share_context */,
ui::command_buffer_metrics::RENDER_COMPOSITOR_CONTEXT));
if (layout_test_deps_) {
@@ -2308,7 +2307,7 @@ void RenderThreadImpl::CreateView(mojom::CreateViewParamsPtr params) {
// When bringing in render_view, also bring in webkit's glue and jsbindings.
RenderViewImpl::Create(compositor_deps, std::move(params),
RenderWidget::ShowCallback(),
- GetRendererScheduler()->DefaultTaskRunner());
+ GetWebMainThreadScheduler()->DefaultTaskRunner());
}
void RenderThreadImpl::CreateFrame(mojom::CreateFrameParamsPtr params) {
@@ -2368,9 +2367,9 @@ void RenderThreadImpl::OnNetworkQualityChanged(
void RenderThreadImpl::SetWebKitSharedTimersSuspended(bool suspend) {
#if defined(OS_ANDROID)
if (suspend) {
- renderer_scheduler_->PauseTimersForAndroidWebView();
+ main_thread_scheduler_->PauseTimersForAndroidWebView();
} else {
- renderer_scheduler_->ResumeTimersForAndroidWebView();
+ main_thread_scheduler_->ResumeTimersForAndroidWebView();
}
webkit_shared_timer_suspended_ = suspend;
#else
@@ -2433,10 +2432,8 @@ void RenderThreadImpl::OnMemoryPressure(
static_cast<blink::WebMemoryPressureLevel>(memory_pressure_level));
}
if (memory_pressure_level ==
- base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) {
+ base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL)
ReleaseFreeMemory();
- ClearMemory();
- }
}
void RenderThreadImpl::OnMemoryStateChange(base::MemoryState state) {
@@ -2453,7 +2450,7 @@ void RenderThreadImpl::OnPurgeMemory() {
if (!GetRendererMemoryMetrics(&metrics))
return;
- GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
+ GetWebMainThreadScheduler()->DefaultTaskRunner()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&RenderThreadImpl::RecordPurgeMemory,
base::Unretained(this), std::move(metrics)),
@@ -2461,7 +2458,6 @@ void RenderThreadImpl::OnPurgeMemory() {
OnTrimMemoryImmediately();
ReleaseFreeMemory();
- ClearMemory();
if (blink_platform_impl_)
blink::WebMemoryCoordinator::OnPurgeMemory();
}
@@ -2478,18 +2474,6 @@ void RenderThreadImpl::RecordPurgeMemory(RendererMemoryMetrics before) {
mbytes);
}
-void RenderThreadImpl::ClearMemory() {
- // Do not call into blink if it is not initialized.
- if (blink_platform_impl_) {
- // Purge Skia font cache, resource cache, and image filter.
- SkGraphics::PurgeAllCaches();
- }
-}
-
-scoped_refptr<base::TaskRunner> RenderThreadImpl::GetFileThreadTaskRunner() {
- return blink_platform_impl_->BaseFileTaskRunner();
-}
-
scoped_refptr<base::SingleThreadTaskRunner>
RenderThreadImpl::GetMediaThreadTaskRunner() {
DCHECK(message_loop()->task_runner()->BelongsToCurrentThread());
@@ -2529,10 +2513,11 @@ RenderThreadImpl::SharedCompositorWorkerContextProvider() {
switches::kEnableOOPRasterization);
bool support_gles2_interface = !support_oop_rasterization;
bool support_raster_interface = true;
+ bool support_grcontext = !support_oop_rasterization;
shared_worker_context_provider_ = CreateOffscreenContext(
std::move(gpu_channel_host), GetGpuMemoryBufferManager(),
gpu::SharedMemoryLimits(), support_locking, support_gles2_interface,
- support_raster_interface, support_oop_rasterization,
+ support_raster_interface, support_oop_rasterization, support_grcontext,
ui::command_buffer_metrics::RENDER_WORKER_CONTEXT, kGpuStreamIdWorker,
kGpuStreamPriorityWorker);
auto result = shared_worker_context_provider_->BindToCurrentThread();
@@ -2587,7 +2572,7 @@ void RenderThreadImpl::OnRendererHidden() {
// scheduled by the RendererScheduler - http://crbug.com/469210.
if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
return;
- renderer_scheduler_->SetRendererHidden(true);
+ main_thread_scheduler_->SetRendererHidden(true);
ScheduleIdleHandler(kInitialIdleHandlerDelayMs);
}
@@ -2595,7 +2580,7 @@ void RenderThreadImpl::OnRendererVisible() {
blink::MainThreadIsolate()->IsolateInForegroundNotification();
if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
return;
- renderer_scheduler_->SetRendererHidden(false);
+ main_thread_scheduler_->SetRendererHidden(false);
ScheduleIdleHandler(kLongIdleHandlerDelayMs);
}
@@ -2603,8 +2588,12 @@ void RenderThreadImpl::ReleaseFreeMemory() {
base::allocator::ReleaseFreeMemory();
discardable_shared_memory_manager_->ReleaseFreeMemory();
- if (blink_platform_impl_)
+ // Do not call into blink if it is not initialized.
+ if (blink_platform_impl_) {
+ // Purge Skia font cache, resource cache, and image filter.
+ SkGraphics::PurgeAllCaches();
blink::DecommitFreeableMemory();
+ }
}
RenderThreadImpl::PendingFrameCreate::PendingFrameCreate(
@@ -2660,7 +2649,8 @@ void RenderThreadImpl::OnTrimMemoryImmediately() {
void RenderThreadImpl::OnRendererInterfaceRequest(
mojom::RendererAssociatedRequest request) {
DCHECK(!renderer_binding_.is_bound());
- renderer_binding_.Bind(std::move(request));
+ renderer_binding_.Bind(std::move(request),
+ GetWebMainThreadScheduler()->IPCTaskRunner());
}
bool RenderThreadImpl::NeedsToRecordFirstActivePaint(
diff --git a/chromium/content/renderer/render_thread_impl.h b/chromium/content/renderer/render_thread_impl.h
index 1fd04f42b95..b88425f8da9 100644
--- a/chromium/content/renderer/render_thread_impl.h
+++ b/chromium/content/renderer/render_thread_impl.h
@@ -49,7 +49,7 @@
#include "content/renderer/media/audio_output_ipc_factory.h"
#include "gpu/ipc/client/gpu_channel_host.h"
#include "ipc/ipc_sync_channel.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "mojo/public/cpp/bindings/associated_binding.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "mojo/public/cpp/bindings/thread_safe_interface_ptr.h"
@@ -59,13 +59,13 @@
#include "services/service_manager/public/cpp/bind_source_info.h"
#include "services/service_manager/public/cpp/binder_registry.h"
#include "services/viz/public/interfaces/compositing/compositing_mode_watcher.mojom.h"
-#include "third_party/WebKit/public/platform/WebConnectionType.h"
-#include "third_party/WebKit/public/platform/scheduler/renderer/renderer_scheduler.h"
-#include "third_party/WebKit/public/web/WebMemoryStatistics.h"
+#include "third_party/blink/public/platform/scheduler/web_main_thread_scheduler.h"
+#include "third_party/blink/public/platform/web_connection_type.h"
+#include "third_party/blink/public/web/web_memory_statistics.h"
#include "ui/gfx/native_widget_types.h"
#if defined(OS_MACOSX)
-#include "third_party/WebKit/public/platform/mac/WebScrollbarTheme.h"
+#include "third_party/blink/public/platform/mac/web_scrollbar_theme.h"
#endif
class SkBitmap;
@@ -133,7 +133,6 @@ class AecDumpMessageFilter;
class AudioMessageFilter;
class AudioRendererMixerManager;
class BrowserPluginManager;
-class CacheStorageDispatcher;
class CategorizedWorkerPool;
class DomStorageDispatcher;
class FileSystemDispatcher;
@@ -175,17 +174,19 @@ class SynchronousCompositorFilter;
class CONTENT_EXPORT RenderThreadImpl
: public RenderThread,
public ChildThreadImpl,
- public blink::scheduler::RendererScheduler::RAILModeObserver,
+ public blink::scheduler::WebMainThreadScheduler::RAILModeObserver,
public ChildMemoryCoordinatorDelegate,
public base::MemoryCoordinatorClient,
public mojom::Renderer,
public viz::mojom::CompositingModeWatcher,
public CompositorDependencies {
public:
- static RenderThreadImpl* Create(const InProcessChildThreadParams& params);
+ static RenderThreadImpl* Create(const InProcessChildThreadParams& params,
+ base::MessageLoop* unowned_message_loop);
static RenderThreadImpl* Create(
std::unique_ptr<base::MessageLoop> main_message_loop,
- std::unique_ptr<blink::scheduler::RendererScheduler> renderer_scheduler);
+ std::unique_ptr<blink::scheduler::WebMainThreadScheduler>
+ main_thread_scheduler);
static RenderThreadImpl* current();
static mojom::RenderMessageFilter* current_render_message_filter();
static RendererBlinkPlatformImpl* current_blink_platform_impl();
@@ -250,7 +251,6 @@ class CONTENT_EXPORT RenderThreadImpl
bool IsGpuRasterizationForced() override;
int GetGpuRasterizationMSAASampleCount() override;
bool IsLcdTextEnabled() override;
- bool IsDistanceFieldTextEnabled() override;
bool IsZeroCopyEnabled() override;
bool IsPartialRasterEnabled() override;
bool IsGpuMemoryBufferCompositorResourcesEnabled() override;
@@ -259,13 +259,14 @@ class CONTENT_EXPORT RenderThreadImpl
GetCompositorMainThreadTaskRunner() override;
scoped_refptr<base::SingleThreadTaskRunner>
GetCompositorImplThreadTaskRunner() override;
- blink::scheduler::RendererScheduler* GetRendererScheduler() override;
+ blink::scheduler::WebMainThreadScheduler* GetWebMainThreadScheduler()
+ override;
cc::TaskGraphRunner* GetTaskGraphRunner() override;
bool IsThreadedAnimationEnabled() override;
bool IsScrollAnimatorEnabled() override;
std::unique_ptr<cc::UkmRecorderFactory> CreateUkmRecorderFactory() override;
- // blink::scheduler::RendererScheduler::RAILModeObserver implementation.
+ // blink::scheduler::WebMainThreadScheduler::RAILModeObserver implementation.
void OnRAILModeChanged(v8::RAILMode rail_mode) override;
// viz::mojom::CompositingModeWatcher implementation.
@@ -406,11 +407,6 @@ class CONTENT_EXPORT RenderThreadImpl
gpu::GpuChannelHost* GetGpuChannel();
// Returns a SingleThreadTaskRunner instance corresponding to the message loop
- // of the thread on which file operations should be run. Must be called
- // on the renderer's main thread.
- scoped_refptr<base::TaskRunner> GetFileThreadTaskRunner();
-
- // Returns a SingleThreadTaskRunner instance corresponding to the message loop
// of the thread on which media operations should be run. Must be called
// on the renderer's main thread.
scoped_refptr<base::SingleThreadTaskRunner> GetMediaThreadTaskRunner();
@@ -540,11 +536,12 @@ class CONTENT_EXPORT RenderThreadImpl
protected:
RenderThreadImpl(
const InProcessChildThreadParams& params,
- std::unique_ptr<blink::scheduler::RendererScheduler> scheduler,
- const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue);
+ std::unique_ptr<blink::scheduler::WebMainThreadScheduler> scheduler,
+ const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue,
+ base::MessageLoop* unowned_message_loop);
RenderThreadImpl(
std::unique_ptr<base::MessageLoop> main_message_loop,
- std::unique_ptr<blink::scheduler::RendererScheduler> scheduler);
+ std::unique_ptr<blink::scheduler::WebMainThreadScheduler> scheduler);
private:
void OnProcessFinalRelease() override;
@@ -564,8 +561,6 @@ class CONTENT_EXPORT RenderThreadImpl
void RecordPurgeMemory(RendererMemoryMetrics before);
- void ClearMemory();
-
void Init(
const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue);
@@ -641,10 +636,10 @@ class CONTENT_EXPORT RenderThreadImpl
std::unique_ptr<AppCacheDispatcher> appcache_dispatcher_;
std::unique_ptr<DomStorageDispatcher> dom_storage_dispatcher_;
std::unique_ptr<IndexedDBDispatcher> main_thread_indexed_db_dispatcher_;
- std::unique_ptr<blink::scheduler::RendererScheduler> renderer_scheduler_;
+ std::unique_ptr<blink::scheduler::WebMainThreadScheduler>
+ main_thread_scheduler_;
std::unique_ptr<RendererBlinkPlatformImpl> blink_platform_impl_;
std::unique_ptr<ResourceDispatcher> resource_dispatcher_;
- std::unique_ptr<CacheStorageDispatcher> main_thread_cache_storage_dispatcher_;
std::unique_ptr<FileSystemDispatcher> file_system_dispatcher_;
std::unique_ptr<URLLoaderThrottleProvider> url_loader_throttle_provider_;
@@ -717,7 +712,11 @@ class CONTENT_EXPORT RenderThreadImpl
// The message loop of the renderer main thread.
// This message loop should be destructed before the RenderThreadImpl
// shuts down Blink.
- std::unique_ptr<base::MessageLoop> main_message_loop_;
+ // Some test users (e.g. InProcessRenderThread) own the MessageLoop used by
+ // their RenderThreadImpls. |main_message_loop_| is always non-nulll,
+ // |owned_message_loop_| is non-null if handed in at creation.
+ const std::unique_ptr<base::MessageLoop> owned_message_loop_;
+ base::MessageLoop* const main_message_loop_;
// May be null if overridden by ContentRendererClient.
std::unique_ptr<blink::scheduler::WebThreadBase> compositor_thread_;
@@ -770,7 +769,6 @@ class CONTENT_EXPORT RenderThreadImpl
bool is_gpu_rasterization_forced_;
int gpu_rasterization_msaa_sample_count_;
bool is_lcd_text_enabled_;
- bool is_distance_field_text_enabled_;
bool is_zero_copy_enabled_;
bool is_gpu_memory_buffer_compositor_resources_enabled_;
bool is_partial_raster_enabled_;
diff --git a/chromium/content/renderer/render_thread_impl_browsertest.cc b/chromium/content/renderer/render_thread_impl_browsertest.cc
index c53d8cf31b8..b649ae5669b 100644
--- a/chromium/content/renderer/render_thread_impl_browsertest.cc
+++ b/chromium/content/renderer/render_thread_impl_browsertest.cc
@@ -6,21 +6,25 @@
#include <stddef.h>
#include <stdint.h>
+
+#include <memory>
#include <utility>
#include "base/callback.h"
#include "base/command_line.h"
#include "base/debug/leak_annotations.h"
#include "base/location.h"
+#include "base/macros.h"
#include "base/memory/discardable_memory.h"
+#include "base/message_loop/message_loop.h"
#include "base/metrics/field_trial.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
+#include "base/task_scheduler/task_scheduler.h"
#include "base/test/scoped_feature_list.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "base/threading/thread_task_runner_handle.h"
-#include "build/build_config.h"
#include "content/app/mojo/mojo_init.h"
#include "content/common/in_process_child_thread_params.h"
#include "content/common/service_manager/child_connection.h"
@@ -37,10 +41,8 @@
#include "content/public/test/test_browser_thread_bundle.h"
#include "content/public/test/test_content_client_initializer.h"
#include "content/public/test/test_launcher.h"
-#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_service_manager_context.h"
#include "content/renderer/render_process_impl.h"
-#include "content/shell/browser/shell.h"
#include "content/test/mock_render_process.h"
#include "gpu/GLES2/gl2extchromium.h"
#include "gpu/command_buffer/client/gpu_memory_buffer_manager.h"
@@ -50,11 +52,10 @@
#include "ipc/ipc_channel_mojo.h"
#include "mojo/edk/embedder/embedder.h"
#include "mojo/edk/embedder/outgoing_broker_client_invitation.h"
-#include "net/dns/mock_host_resolver.h"
+#include "mojo/edk/embedder/scoped_ipc_support.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/scheduler/renderer/renderer_scheduler.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
-#include "third_party/skia/include/core/SkGraphics.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/scheduler/web_main_thread_scheduler.h"
#include "ui/base/ui_base_switches.h"
#include "ui/gfx/buffer_format_util.h"
@@ -131,9 +132,13 @@ class RenderThreadImplForTest : public RenderThreadImpl {
public:
RenderThreadImplForTest(
const InProcessChildThreadParams& params,
- std::unique_ptr<blink::scheduler::RendererScheduler> scheduler,
- scoped_refptr<base::SingleThreadTaskRunner>& test_task_counter)
- : RenderThreadImpl(params, std::move(scheduler), test_task_counter) {}
+ std::unique_ptr<blink::scheduler::WebMainThreadScheduler> scheduler,
+ scoped_refptr<base::SingleThreadTaskRunner>& test_task_counter,
+ base::MessageLoop* unowned_message_loop)
+ : RenderThreadImpl(params,
+ std::move(scheduler),
+ test_task_counter,
+ unowned_message_loop) {}
~RenderThreadImplForTest() override {}
};
@@ -170,18 +175,42 @@ class QuitOnTestMsgFilter : public IPC::MessageFilter {
class RenderThreadImplBrowserTest : public testing::Test {
public:
+ // Managing our own main MessageLoop also forces us to manage our own
+ // TaskScheduler. This ensures a basic TaskScheduler is in scope during this
+ // test.
+ class TestTaskScheduler {
+ public:
+ TestTaskScheduler() {
+ base::TaskScheduler::CreateAndStartWithDefaultParams(
+ "RenderThreadImplBrowserTest");
+ }
+
+ ~TestTaskScheduler() {
+ base::TaskScheduler::GetInstance()->Shutdown();
+ base::TaskScheduler::GetInstance()->JoinForTesting();
+ base::TaskScheduler::SetInstance(nullptr);
+ }
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(TestTaskScheduler);
+ };
+
RenderThreadImplBrowserTest() : field_trial_list_(nullptr) {}
void SetUp() override {
content_renderer_client_.reset(new ContentRendererClient());
SetRendererClientForTesting(content_renderer_client_.get());
+ main_message_loop_.reset(new base::MessageLoop(base::MessageLoop::TYPE_IO));
+ test_task_scheduler_.reset(new TestTaskScheduler);
browser_threads_.reset(
new TestBrowserThreadBundle(TestBrowserThreadBundle::IO_MAINLOOP));
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner =
blink::scheduler::GetSingleThreadTaskRunnerForTesting();
InitializeMojo();
+ mojo_ipc_support_.reset(new mojo::edk::ScopedIPCSupport(
+ io_task_runner, mojo::edk::ScopedIPCSupport::ShutdownPolicy::FAST));
shell_context_.reset(new TestServiceManagerContext);
mojo::edk::OutgoingBrokerClientInvitation invitation;
service_manager::Identity child_identity(
@@ -219,8 +248,9 @@ class RenderThreadImplBrowserTest : public testing::Test {
// in RenderThreadImpl::Init().
cmd->AppendSwitch(switches::kIgnoreGpuBlacklist);
- std::unique_ptr<blink::scheduler::RendererScheduler> renderer_scheduler =
- blink::scheduler::RendererScheduler::Create();
+ std::unique_ptr<blink::scheduler::WebMainThreadScheduler>
+ main_thread_scheduler =
+ blink::scheduler::WebMainThreadScheduler::Create();
scoped_refptr<base::SingleThreadTaskRunner> test_task_counter(
test_task_counter_.get());
@@ -229,7 +259,8 @@ class RenderThreadImplBrowserTest : public testing::Test {
thread_ = new RenderThreadImplForTest(
InProcessChildThreadParams(io_task_runner, &invitation,
child_connection_->service_token()),
- std::move(renderer_scheduler), test_task_counter);
+ std::move(main_thread_scheduler), test_task_counter,
+ main_message_loop_.get());
cmd->InitFromArgv(old_argv);
run_loop_ = std::make_unique<base::RunLoop>();
@@ -249,16 +280,20 @@ class RenderThreadImplBrowserTest : public testing::Test {
}
}
+ protected:
IPC::Sender* sender() { return channel_.get(); }
scoped_refptr<TestTaskCounter> test_task_counter_;
TestContentClientInitializer content_client_initializer_;
std::unique_ptr<ContentRendererClient> content_renderer_client_;
+ std::unique_ptr<base::MessageLoop> main_message_loop_;
+ std::unique_ptr<TestTaskScheduler> test_task_scheduler_;
std::unique_ptr<TestBrowserThreadBundle> browser_threads_;
std::unique_ptr<TestServiceManagerContext> shell_context_;
std::unique_ptr<ChildConnection> child_connection_;
std::unique_ptr<IPC::ChannelProxy> channel_;
+ std::unique_ptr<mojo::edk::ScopedIPCSupport> mojo_ipc_support_;
std::unique_ptr<MockRenderProcess> mock_process_;
scoped_refptr<QuitOnTestMsgFilter> test_msg_filter_;
@@ -267,6 +302,9 @@ class RenderThreadImplBrowserTest : public testing::Test {
base::FieldTrialList field_trial_list_;
std::unique_ptr<base::RunLoop> run_loop_;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(RenderThreadImplBrowserTest);
};
class RenderThreadImplMojoInputMessagesDisabledBrowserTest
@@ -418,38 +456,5 @@ INSTANTIATE_TEST_CASE_P(
gfx::BufferFormat::RGBA_8888,
gfx::BufferFormat::BGRA_8888,
gfx::BufferFormat::YVU_420)));
-
-class RenderThreadImplClearMemoryBrowserTest : public ContentBrowserTest {
- protected:
- void SetUpOnMainThread() override {
- host_resolver()->AddRule("*", "127.0.0.1");
- ASSERT_TRUE(embedded_test_server()->Start());
- }
-};
-
-#if defined(OS_ANDROID) || defined(OS_MACOSX) || defined(IS_CHROMECAST)
-#define MAYBE_ClearMemory DISABLED_ClearMemory
-#else
-#define MAYBE_ClearMemory ClearMemory
-#endif
-
-IN_PROC_BROWSER_TEST_F(RenderThreadImplClearMemoryBrowserTest,
- MAYBE_ClearMemory) {
- TestNavigationObserver observer(shell()->web_contents());
- GURL url(embedded_test_server()->GetURL("/simple_page.html"));
- NavigateToURL(shell(), url);
-
- EXPECT_GT(static_cast<int>(SkGraphics::GetFontCacheUsed()), 0);
- EXPECT_GT(SkGraphics::GetFontCacheCountUsed(), 0);
-
- // TODO(gyuyoung): How to call RenderThreadImpl::ClearMemory() from here?
- // Instead we call same function that RenderThreadImpl::ClearMemory() calls at
- // the moment.
- SkGraphics::PurgeAllCaches();
-
- EXPECT_EQ(static_cast<int>(SkGraphics::GetFontCacheUsed()), 0);
- EXPECT_EQ(SkGraphics::GetFontCacheCountUsed(), 0);
-}
-
} // namespace
} // namespace content
diff --git a/chromium/content/renderer/render_thread_impl_discardable_memory_browsertest.cc b/chromium/content/renderer/render_thread_impl_discardable_memory_browsertest.cc
index 2875aba5abf..724cd90b673 100644
--- a/chromium/content/renderer/render_thread_impl_discardable_memory_browsertest.cc
+++ b/chromium/content/renderer/render_thread_impl_discardable_memory_browsertest.cc
@@ -14,6 +14,7 @@
#include "base/bind.h"
#include "base/command_line.h"
#include "base/memory/discardable_memory.h"
+#include "base/memory/memory_pressure_listener.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "components/discardable_memory/client/client_discardable_shared_memory_manager.h"
@@ -22,8 +23,9 @@
#include "content/public/common/content_switches.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
+#include "content/public/test/test_utils.h"
#include "content/shell/browser/shell.h"
-#include "gpu/ipc/client/gpu_memory_buffer_impl.h"
+#include "gpu/ipc/common/gpu_memory_buffer_impl.h"
#include "ui/gfx/buffer_format_util.h"
#include "url/gurl.h"
@@ -138,5 +140,33 @@ IN_PROC_BROWSER_TEST_F(RenderThreadImplDiscardableMemoryBrowserTest,
EXPECT_LT(base::TimeTicks::Now(), end);
}
+IN_PROC_BROWSER_TEST_F(RenderThreadImplDiscardableMemoryBrowserTest,
+ ReleaseFreeMemory) {
+ const size_t kSize = 1024 * 1024; // 1MiB.
+
+ std::unique_ptr<base::DiscardableMemory> memory =
+ child_discardable_shared_memory_manager()
+ ->AllocateLockedDiscardableMemory(kSize);
+
+ EXPECT_TRUE(memory);
+ memory.reset();
+
+ EXPECT_GE(BrowserMainLoop::GetInstance()
+ ->discardable_shared_memory_manager()
+ ->GetBytesAllocated(),
+ kSize);
+
+ // Call RenderThreadImpl::ReleaseFreeMemory through a fake memory pressure
+ // notification.
+ base::MemoryPressureListener::SimulatePressureNotification(
+ base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL);
+ base::RunLoop().RunUntilIdle();
+ RunAllTasksUntilIdle();
+
+ EXPECT_EQ(0U, BrowserMainLoop::GetInstance()
+ ->discardable_shared_memory_manager()
+ ->GetBytesAllocated());
+}
+
} // namespace
} // namespace content
diff --git a/chromium/content/renderer/render_view_browsertest.cc b/chromium/content/renderer/render_view_browsertest.cc
index d5a2b7e7dd8..944d93eaefd 100644
--- a/chromium/content/renderer/render_view_browsertest.cc
+++ b/chromium/content/renderer/render_view_browsertest.cc
@@ -63,26 +63,26 @@
#include "services/network/public/cpp/resource_request_body.h"
#include "services/network/public/mojom/request_context_frame_type.mojom.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebData.h"
-#include "third_party/WebKit/public/platform/WebHTTPBody.h"
-#include "third_party/WebKit/public/platform/WebRuntimeFeatures.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebURLResponse.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerNetworkProvider.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
-#include "third_party/WebKit/public/web/WebDeviceEmulationParams.h"
-#include "third_party/WebKit/public/web/WebDocumentLoader.h"
-#include "third_party/WebKit/public/web/WebFrameContentDumper.h"
-#include "third_party/WebKit/public/web/WebGlobalObjectReusePolicy.h"
-#include "third_party/WebKit/public/web/WebHistoryCommitType.h"
-#include "third_party/WebKit/public/web/WebHistoryItem.h"
-#include "third_party/WebKit/public/web/WebInputMethodController.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebPerformance.h"
-#include "third_party/WebKit/public/web/WebScriptSource.h"
-#include "third_party/WebKit/public/web/WebSettings.h"
-#include "third_party/WebKit/public/web/WebView.h"
-#include "third_party/WebKit/public/web/WebWindowFeatures.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_network_provider.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/web_data.h"
+#include "third_party/blink/public/platform/web_http_body.h"
+#include "third_party/blink/public/platform/web_runtime_features.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_url_response.h"
+#include "third_party/blink/public/web/web_device_emulation_params.h"
+#include "third_party/blink/public/web/web_document_loader.h"
+#include "third_party/blink/public/web/web_frame_content_dumper.h"
+#include "third_party/blink/public/web/web_global_object_reuse_policy.h"
+#include "third_party/blink/public/web/web_history_commit_type.h"
+#include "third_party/blink/public/web/web_history_item.h"
+#include "third_party/blink/public/web/web_input_method_controller.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_performance.h"
+#include "third_party/blink/public/web/web_script_source.h"
+#include "third_party/blink/public/web/web_settings.h"
+#include "third_party/blink/public/web/web_view.h"
+#include "third_party/blink/public/web/web_window_features.h"
#include "ui/accessibility/ax_modes.h"
#include "ui/events/base_event_utils.h"
#include "ui/events/event.h"
@@ -92,10 +92,10 @@
#include "ui/native_theme/native_theme_features.h"
#if defined(OS_ANDROID)
-#include "third_party/WebKit/public/platform/WebCoalescedInputEvent.h"
-#include "third_party/WebKit/public/platform/WebGestureDevice.h"
-#include "third_party/WebKit/public/platform/WebGestureEvent.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
+#include "third_party/blink/public/platform/web_coalesced_input_event.h"
+#include "third_party/blink/public/platform/web_gesture_device.h"
+#include "third_party/blink/public/platform/web_gesture_event.h"
+#include "third_party/blink/public/platform/web_input_event.h"
#endif
#if defined(OS_WIN)
@@ -103,7 +103,6 @@
#endif
#if defined(USE_AURA) && defined(USE_X11)
-#include "base/memory/ptr_util.h"
#include "ui/events/event_constants.h"
#include "ui/events/keycodes/keyboard_code_conversion.h"
#include "ui/events/test/events_test_utils.h"
@@ -446,6 +445,10 @@ class RenderViewImplScaleFactorTest : public RenderViewImplBlinkSettingsTest {
params.new_size = gfx::Size(100, 100);
params.compositor_viewport_pixel_size = gfx::Size(200, 200);
params.visible_viewport_size = params.new_size;
+ params.auto_resize_enabled = view()->auto_resize_mode();
+ params.auto_resize_sequence_number = view()->auto_resize_sequence_number();
+ params.min_size_for_auto_resize = view()->min_size_for_auto_resize();
+ params.max_size_for_auto_resize = view()->max_size_for_auto_resize();
params.needs_resize_ack = false;
params.content_source_id = view()->GetContentSourceId();
view()->OnResize(params);
@@ -517,10 +520,9 @@ static blink::WebCoalescedInputEvent FatTap(int x,
int height) {
blink::WebGestureEvent event(
blink::WebInputEvent::kGestureTap, blink::WebInputEvent::kNoModifiers,
- blink::WebInputEvent::GetStaticTimeStampForTests());
- event.source_device = blink::kWebGestureDeviceTouchscreen;
- event.x = x;
- event.y = y;
+ blink::WebInputEvent::GetStaticTimeStampForTests(),
+ blink::kWebGestureDeviceTouchscreen);
+ event.SetPositionInWidget(gfx::PointF(x, y));
event.data.tap.width = width;
event.data.tap.height = height;
return blink::WebCoalescedInputEvent(event);
@@ -1524,8 +1526,7 @@ TEST_F(RenderViewImplTest, AndroidContextMenuSelectionOrdering) {
WebGestureEvent gesture_event(
WebInputEvent::kGestureLongPress, WebInputEvent::kNoModifiers,
ui::EventTimeStampToSeconds(ui::EventTimeForNow()));
- gesture_event.x = 250;
- gesture_event.y = 250;
+ gesture_event.SetPositionInWidget(gfx::PointF(250, 250));
SendWebGestureEvent(gesture_event);
@@ -2438,6 +2439,54 @@ TEST_F(RenderViewImplTest, DispatchBeforeUnloadCanDetachFrame) {
render_thread_->sink().RemoveFilter(callback_filter.get());
}
+// IPC Listener that runs a callback when a javascript modal dialog is
+// triggered.
+class AlertCallbackFilter : public IPC::Listener {
+ public:
+ explicit AlertCallbackFilter(
+ base::RepeatingCallback<void(const base::string16&)> callback)
+ : callback_(std::move(callback)) {}
+
+ bool OnMessageReceived(const IPC::Message& msg) override {
+ bool handled = true;
+ IPC_BEGIN_MESSAGE_MAP(AlertCallbackFilter, msg)
+ IPC_MESSAGE_HANDLER(FrameHostMsg_RunJavaScriptDialog,
+ OnRunJavaScriptDialog)
+ IPC_MESSAGE_UNHANDLED(handled = false)
+ IPC_END_MESSAGE_MAP()
+ return handled;
+ }
+
+ // Not really part of IPC::Listener but required to intercept a sync msg.
+ void Send(const IPC::Message* msg) { delete msg; }
+
+ void OnRunJavaScriptDialog(const base::string16& message,
+ const base::string16&,
+ JavaScriptDialogType,
+ bool*,
+ base::string16*) {
+ callback_.Run(message);
+ }
+
+ private:
+ base::RepeatingCallback<void(const base::string16&)> callback_;
+};
+
+// Test that invoking one of the modal dialogs doesn't crash.
+TEST_F(RenderViewImplTest, ModalDialogs) {
+ LoadHTML("<body></body>");
+
+ std::unique_ptr<AlertCallbackFilter> callback_filter(new AlertCallbackFilter(
+ base::BindRepeating([](const base::string16& msg) {
+ EXPECT_EQ(base::UTF8ToUTF16("Please don't crash"), msg);
+ })));
+ render_thread_->sink().AddFilter(callback_filter.get());
+
+ frame()->GetWebFrame()->Alert(WebString::FromUTF8("Please don't crash"));
+
+ render_thread_->sink().RemoveFilter(callback_filter.get());
+}
+
TEST_F(RenderViewImplBlinkSettingsTest, Default) {
DoSetUp();
EXPECT_FALSE(settings()->ViewportEnabled());
diff --git a/chromium/content/renderer/render_view_browsertest_mac.mm b/chromium/content/renderer/render_view_browsertest_mac.mm
index 21e28f801c8..9674a212aac 100644
--- a/chromium/content/renderer/render_view_browsertest_mac.mm
+++ b/chromium/content/renderer/render_view_browsertest_mac.mm
@@ -15,9 +15,9 @@
#include "content/public/test/render_view_test.h"
#include "content/renderer/render_view_impl.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/web/WebFrameContentDumper.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebView.h"
+#include "third_party/blink/public/web/web_frame_content_dumper.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_view.h"
#include <Carbon/Carbon.h> // for the kVK_* constants.
#include <Cocoa/Cocoa.h>
diff --git a/chromium/content/renderer/render_view_fuchsia.cc b/chromium/content/renderer/render_view_fuchsia.cc
index b01f139b488..eb11e5390fe 100644
--- a/chromium/content/renderer/render_view_fuchsia.cc
+++ b/chromium/content/renderer/render_view_fuchsia.cc
@@ -4,7 +4,7 @@
#include "content/renderer/render_view_impl.h"
-#include "third_party/WebKit/public/platform/WebFontRenderStyle.h"
+#include "third_party/blink/public/platform/web_font_render_style.h"
namespace content {
diff --git a/chromium/content/renderer/render_view_impl.cc b/chromium/content/renderer/render_view_impl.cc
index a9b91cdcc86..7a866ded50f 100644
--- a/chromium/content/renderer/render_view_impl.cc
+++ b/chromium/content/renderer/render_view_impl.cc
@@ -21,7 +21,6 @@
#include "base/json/json_writer.h"
#include "base/lazy_instance.h"
#include "base/location.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram_macros.h"
#include "base/process/kill.h"
@@ -93,12 +92,11 @@
#include "content/renderer/renderer_webapplicationcachehost_impl.h"
#include "content/renderer/resizing_mode_selector.h"
#include "content/renderer/savable_resources.h"
-#include "content/renderer/speech_recognition_dispatcher.h"
#include "content/renderer/v8_value_converter_impl.h"
#include "content/renderer/web_ui_extension_data.h"
#include "media/audio/audio_output_device.h"
#include "media/base/media_switches.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "media/renderers/audio_renderer_impl.h"
#include "media/video/gpu_video_accelerator_factories.h"
#include "net/base/data_url.h"
@@ -107,62 +105,62 @@
#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
#include "net/http/http_util.h"
#include "net/nqe/effective_connection_type.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#include "skia/ext/platform_canvas.h"
-#include "third_party/WebKit/public/common/associated_interfaces/associated_interface_provider.h"
-#include "third_party/WebKit/public/mojom/page/page_visibility_state.mojom.h"
-#include "third_party/WebKit/public/platform/FilePathConversion.h"
-#include "third_party/WebKit/public/platform/URLConversion.h"
-#include "third_party/WebKit/public/platform/WebConnectionType.h"
-#include "third_party/WebKit/public/platform/WebEffectiveConnectionType.h"
-#include "third_party/WebKit/public/platform/WebHTTPBody.h"
-#include "third_party/WebKit/public/platform/WebImage.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
-#include "third_party/WebKit/public/platform/WebInputEventResult.h"
-#include "third_party/WebKit/public/platform/WebNetworkStateNotifier.h"
-#include "third_party/WebKit/public/platform/WebPoint.h"
-#include "third_party/WebKit/public/platform/WebRect.h"
-#include "third_party/WebKit/public/platform/WebRuntimeFeatures.h"
-#include "third_party/WebKit/public/platform/WebSize.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
-#include "third_party/WebKit/public/platform/WebURLError.h"
-#include "third_party/WebKit/public/platform/WebURLRequest.h"
-#include "third_party/WebKit/public/platform/WebURLResponse.h"
-#include "third_party/WebKit/public/platform/WebVector.h"
-#include "third_party/WebKit/public/public_features.h"
-#include "third_party/WebKit/public/web/WebAXObject.h"
-#include "third_party/WebKit/public/web/WebAutofillClient.h"
-#include "third_party/WebKit/public/web/WebDOMEvent.h"
-#include "third_party/WebKit/public/web/WebDOMMessageEvent.h"
-#include "third_party/WebKit/public/web/WebDateTimeChooserCompletion.h"
-#include "third_party/WebKit/public/web/WebDateTimeChooserParams.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebElement.h"
-#include "third_party/WebKit/public/web/WebFileChooserParams.h"
-#include "third_party/WebKit/public/web/WebFormControlElement.h"
-#include "third_party/WebKit/public/web/WebFormElement.h"
-#include "third_party/WebKit/public/web/WebFrame.h"
-#include "third_party/WebKit/public/web/WebFrameContentDumper.h"
-#include "third_party/WebKit/public/web/WebFrameWidget.h"
-#include "third_party/WebKit/public/web/WebHistoryItem.h"
-#include "third_party/WebKit/public/web/WebHitTestResult.h"
-#include "third_party/WebKit/public/web/WebInputElement.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebMediaPlayerAction.h"
-#include "third_party/WebKit/public/web/WebNavigationPolicy.h"
-#include "third_party/WebKit/public/web/WebPageImportanceSignals.h"
-#include "third_party/WebKit/public/web/WebPlugin.h"
-#include "third_party/WebKit/public/web/WebPluginAction.h"
-#include "third_party/WebKit/public/web/WebRange.h"
-#include "third_party/WebKit/public/web/WebRenderTheme.h"
-#include "third_party/WebKit/public/web/WebScriptSource.h"
-#include "third_party/WebKit/public/web/WebSearchableFormData.h"
-#include "third_party/WebKit/public/web/WebSecurityPolicy.h"
-#include "third_party/WebKit/public/web/WebSettings.h"
-#include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
-#include "third_party/WebKit/public/web/WebView.h"
-#include "third_party/WebKit/public/web/WebWindowFeatures.h"
+#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
+#include "third_party/blink/public/mojom/page/page_visibility_state.mojom.h"
+#include "third_party/blink/public/platform/file_path_conversion.h"
+#include "third_party/blink/public/platform/url_conversion.h"
+#include "third_party/blink/public/platform/web_connection_type.h"
+#include "third_party/blink/public/platform/web_effective_connection_type.h"
+#include "third_party/blink/public/platform/web_http_body.h"
+#include "third_party/blink/public/platform/web_image.h"
+#include "third_party/blink/public/platform/web_input_event.h"
+#include "third_party/blink/public/platform/web_input_event_result.h"
+#include "third_party/blink/public/platform/web_network_state_notifier.h"
+#include "third_party/blink/public/platform/web_point.h"
+#include "third_party/blink/public/platform/web_rect.h"
+#include "third_party/blink/public/platform/web_runtime_features.h"
+#include "third_party/blink/public/platform/web_size.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_url.h"
+#include "third_party/blink/public/platform/web_url_error.h"
+#include "third_party/blink/public/platform/web_url_request.h"
+#include "third_party/blink/public/platform/web_url_response.h"
+#include "third_party/blink/public/platform/web_vector.h"
+#include "third_party/blink/public/public_buildflags.h"
+#include "third_party/blink/public/web/web_autofill_client.h"
+#include "third_party/blink/public/web/web_ax_object.h"
+#include "third_party/blink/public/web/web_date_time_chooser_completion.h"
+#include "third_party/blink/public/web/web_date_time_chooser_params.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_dom_event.h"
+#include "third_party/blink/public/web/web_dom_message_event.h"
+#include "third_party/blink/public/web/web_element.h"
+#include "third_party/blink/public/web/web_file_chooser_params.h"
+#include "third_party/blink/public/web/web_form_control_element.h"
+#include "third_party/blink/public/web/web_form_element.h"
+#include "third_party/blink/public/web/web_frame.h"
+#include "third_party/blink/public/web/web_frame_content_dumper.h"
+#include "third_party/blink/public/web/web_frame_widget.h"
+#include "third_party/blink/public/web/web_history_item.h"
+#include "third_party/blink/public/web/web_hit_test_result.h"
+#include "third_party/blink/public/web/web_input_element.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_media_player_action.h"
+#include "third_party/blink/public/web/web_navigation_policy.h"
+#include "third_party/blink/public/web/web_page_importance_signals.h"
+#include "third_party/blink/public/web/web_plugin.h"
+#include "third_party/blink/public/web/web_plugin_action.h"
+#include "third_party/blink/public/web/web_range.h"
+#include "third_party/blink/public/web/web_render_theme.h"
+#include "third_party/blink/public/web/web_script_source.h"
+#include "third_party/blink/public/web/web_searchable_form_data.h"
+#include "third_party/blink/public/web/web_security_policy.h"
+#include "third_party/blink/public/web/web_settings.h"
+#include "third_party/blink/public/web/web_user_gesture_indicator.h"
+#include "third_party/blink/public/web/web_view.h"
+#include "third_party/blink/public/web/web_window_features.h"
#include "third_party/icu/source/common/unicode/uchar.h"
#include "third_party/icu/source/common/unicode/uscript.h"
#include "third_party/skia/include/core/SkColor.h"
@@ -240,7 +238,6 @@ using blink::WebSecurityPolicy;
using blink::WebSettings;
using blink::WebSize;
using blink::WebString;
-using blink::WebTappedInfo;
using blink::WebTextDirection;
using blink::WebTouchEvent;
using blink::WebURL;
@@ -428,7 +425,8 @@ class AlwaysDrawSwapPromise : public cc::SwapPromise {
void DidActivate() override {}
- void WillSwap(viz::CompositorFrameMetadata* metadata) override {
+ void WillSwap(viz::CompositorFrameMetadata* metadata,
+ cc::FrameTokenAllocator* frame_token_allocator) override {
DCHECK(!latency_info_.terminated());
metadata->latency_info.push_back(latency_info_);
}
@@ -494,7 +492,6 @@ RenderViewImpl::RenderViewImpl(
page_zoom_level_(params.page_zoom_level),
main_render_frame_(nullptr),
frame_widget_(nullptr),
- speech_recognition_dispatcher_(nullptr),
#if defined(OS_ANDROID)
was_created_by_renderer_(false),
#endif
@@ -507,7 +504,8 @@ RenderViewImpl::RenderViewImpl(
void RenderViewImpl::Initialize(
mojom::CreateViewParamsPtr params,
- const RenderWidget::ShowCallback& show_callback) {
+ const RenderWidget::ShowCallback& show_callback,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
bool was_created_by_renderer = !show_callback.is_null();
#if defined(OS_ANDROID)
// TODO(sgurun): crbug.com/325351 Needed only for android webview's deprecated
@@ -614,17 +612,16 @@ void RenderViewImpl::Initialize(
UpdateWebViewWithDeviceScaleFactor();
OnSetRendererPrefs(params->renderer_preferences);
- if (!params->enable_auto_resize) {
- OnResize(params->initial_size);
- } else {
- OnEnableAutoResize(params->min_size, params->max_size);
- }
+ OnResize(params->initial_size);
idle_user_detector_.reset(new IdleUserDetector(this));
GetContentClient()->renderer()->RenderViewCreated(this);
page_zoom_level_ = params->page_zoom_level;
+
+ nav_state_sync_timer_.SetTaskRunner(task_runner);
+ check_preferred_size_timer_.SetTaskRunner(std::move(task_runner));
}
RenderViewImpl::~RenderViewImpl() {
@@ -740,6 +737,7 @@ void RenderView::ApplyWebPreferences(const WebPreferences& prefs,
prefs.application_cache_enabled);
settings->SetHistoryEntryRequiresUserGesture(
prefs.history_entry_requires_user_gesture);
+ settings->SetShouldThrottlePushState(!prefs.disable_pushstate_throttle);
settings->SetHyperlinkAuditingEnabled(prefs.hyperlink_auditing_enabled);
settings->SetCookieEnabled(prefs.cookie_enabled);
settings->SetNavigateOnDragDrop(prefs.navigate_on_drag_drop);
@@ -866,7 +864,6 @@ void RenderView::ApplyWebPreferences(const WebPreferences& prefs,
web_view->SetIgnoreViewportTagScaleLimits(prefs.force_enable_zoom);
settings->SetAutoZoomFocusedNodeToLegibleScale(true);
settings->SetDoubleTapToZoomEnabled(prefs.double_tap_to_zoom_enabled);
- settings->SetPictureInPictureEnabled(prefs.picture_in_picture_enabled);
settings->SetMediaPlaybackGestureWhitelistScope(
blink::WebString::FromUTF8(prefs.media_playback_gesture_whitelist_scope));
settings->SetDefaultVideoPosterURL(
@@ -893,7 +890,7 @@ void RenderView::ApplyWebPreferences(const WebPreferences& prefs,
settings->SetReportScreenSizeInPhysicalPixelsQuirk(
prefs.report_screen_size_in_physical_pixels_quirk);
settings->SetShouldReuseGlobalForUnownedMainFrame(
- prefs.resue_global_for_unowned_main_frame);
+ prefs.reuse_global_for_unowned_main_frame);
settings->SetPreferHiddenVolumeControls(true);
settings->SetSpellCheckEnabledByDefault(prefs.spellcheck_enabled_by_default);
@@ -958,6 +955,7 @@ void RenderView::ApplyWebPreferences(const WebPreferences& prefs,
settings->SetShowContextMenuOnMouseUp(prefs.context_menu_on_mouse_up);
settings->SetAlwaysShowContextMenuOnTouch(
prefs.always_show_context_menu_on_touch);
+ settings->SetSmoothScrollForFindEnabled(prefs.smooth_scroll_for_find_enabled);
settings->SetHideDownloadUI(prefs.hide_download_ui);
WebRuntimeFeatures::EnableBackgroundVideoTrackOptimization(
@@ -973,6 +971,8 @@ void RenderView::ApplyWebPreferences(const WebPreferences& prefs,
static_cast<blink::WebEffectiveConnectionType>(
prefs.low_priority_iframes_threshold));
+ settings->SetPictureInPictureEnabled(prefs.picture_in_picture_enabled);
+
#if defined(OS_MACOSX)
settings->SetDoubleTapToZoomEnabled(true);
web_view->SetMaximumLegibleScale(prefs.default_maximum_page_scale_factor);
@@ -996,7 +996,8 @@ RenderViewImpl* RenderViewImpl::Create(
else
render_view = new RenderViewImpl(compositor_deps, *params, task_runner);
- render_view->Initialize(std::move(params), show_callback);
+ render_view->Initialize(std::move(params), show_callback,
+ std::move(task_runner));
return render_view;
}
@@ -1025,35 +1026,6 @@ const blink::WebView* RenderViewImpl::webview() const {
return webview_;
}
-#if BUILDFLAG(ENABLE_PLUGINS)
-
-#if defined(OS_MACOSX)
-void RenderViewImpl::OnGetRenderedText() {
- if (!webview())
- return;
-
- if (!webview()->MainFrame()->IsWebLocalFrame())
- return;
-
- // Get rendered text from WebLocalFrame.
- // TODO: Currently IPC truncates any data that has a
- // size > kMaximumMessageSize. May be split the text into smaller chunks and
- // send back using multiple IPC. See http://crbug.com/393444.
- static const size_t kMaximumMessageSize = 8 * 1024 * 1024;
- // TODO(dglazkov): Using this API is wrong. It's not OOPIF-compatible and
- // sends text in the wrong order. See http://crbug.com/584798.
- // TODO(dglazkov): WebFrameContentDumper should only be used for
- // testing purposes. See http://crbug.com/585164.
- std::string text =
- WebFrameContentDumper::DumpWebViewAsText(webview(), kMaximumMessageSize)
- .Utf8();
-
- Send(new ViewMsg_GetRenderedTextCompleted(GetRoutingID(), text));
-}
-#endif // defined(OS_MACOSX)
-
-#endif // ENABLE_PLUGINS
-
// RenderWidgetInputHandlerDelegate -----------------------------------------
bool RenderViewImpl::RenderWidgetWillHandleMouseEvent(
@@ -1103,10 +1075,6 @@ bool RenderViewImpl::OnMessageReceived(const IPC::Message& message) {
IPC_MESSAGE_HANDLER(ViewMsg_SetBackgroundOpaque, OnSetBackgroundOpaque)
IPC_MESSAGE_HANDLER(ViewMsg_EnablePreferredSizeChangedMode,
OnEnablePreferredSizeChangedMode)
- IPC_MESSAGE_HANDLER(ViewMsg_EnableAutoResize, OnEnableAutoResize)
- IPC_MESSAGE_HANDLER(ViewMsg_DisableAutoResize, OnDisableAutoResize)
- IPC_MESSAGE_HANDLER(ViewMsg_SetLocalSurfaceIdForAutoResize,
- OnSetLocalSurfaceIdForAutoResize)
IPC_MESSAGE_HANDLER(ViewMsg_DisableScrollbarsForSmallWindows,
OnDisableScrollbarsForSmallWindows)
IPC_MESSAGE_HANDLER(ViewMsg_SetRendererPrefs, OnSetRendererPrefs)
@@ -1127,11 +1095,12 @@ bool RenderViewImpl::OnMessageReceived(const IPC::Message& message) {
IPC_MESSAGE_HANDLER(PageMsg_SetHistoryOffsetAndLength,
OnSetHistoryOffsetAndLength)
IPC_MESSAGE_HANDLER(PageMsg_AudioStateChanged, OnAudioStateChanged)
+ IPC_MESSAGE_HANDLER(PageMsg_PausePageScheduledTasks,
+ OnPausePageScheduledTasks)
IPC_MESSAGE_HANDLER(PageMsg_UpdateScreenInfo, OnUpdateScreenInfo)
+ IPC_MESSAGE_HANDLER(PageMsg_FreezePage, OnFreezePage)
#if defined(OS_MACOSX)
- IPC_MESSAGE_HANDLER(ViewMsg_GetRenderedText,
- OnGetRenderedText)
IPC_MESSAGE_HANDLER(ViewMsg_Close, OnClose)
#endif
// Adding a new message? Add platform independent ones first, then put the
@@ -1203,6 +1172,10 @@ void RenderViewImpl::OnAudioStateChanged(bool is_audio_playing) {
webview()->AudioStateChanged(is_audio_playing);
}
+void RenderViewImpl::OnPausePageScheduledTasks(bool paused) {
+ webview()->PausePageScheduledTasks(paused);
+}
+
///////////////////////////////////////////////////////////////////////////////
void RenderViewImpl::ShowCreatedPopupWidget(RenderWidget* popup_widget,
@@ -1368,7 +1341,7 @@ WebView* RenderViewImpl::CreateView(WebLocalFrame* creator,
base::Unretained(creator_frame), opened_by_user_gesture);
RenderViewImpl* view = RenderViewImpl::Create(
- compositor_deps_, std::move(view_params), show_callback,
+ compositor_deps_, std::move(view_params), std::move(show_callback),
creator->GetTaskRunner(blink::TaskType::kUnthrottled));
return view->webview();
@@ -1591,15 +1564,16 @@ void RenderViewImpl::DidUpdateLayout() {
void RenderViewImpl::NavigateBackForwardSoon(int offset) {
history_navigation_virtual_time_pauser_ =
RenderThreadImpl::current()
- ->GetRendererScheduler()
+ ->GetWebMainThreadScheduler()
->CreateWebScopedVirtualTimePauser(
+ "NavigateBackForwardSoon",
blink::WebScopedVirtualTimePauser::VirtualTaskDuration::kInstant);
- history_navigation_virtual_time_pauser_.PauseVirtualTime(true);
+ history_navigation_virtual_time_pauser_.PauseVirtualTime();
Send(new ViewHostMsg_GoToEntryAtOffset(GetRoutingID(), offset));
}
void RenderViewImpl::DidCommitProvisionalHistoryLoad() {
- history_navigation_virtual_time_pauser_.PauseVirtualTime(false);
+ history_navigation_virtual_time_pauser_.UnpauseVirtualTime();
}
int RenderViewImpl::HistoryBackListCount() {
@@ -1732,11 +1706,6 @@ void RenderViewImpl::SetTouchAction(blink::WebTouchAction touchAction) {
RenderWidget::SetTouchAction(touchAction);
}
-void RenderViewImpl::ShowUnhandledTapUIIfNeeded(
- const blink::WebTappedInfo& tappedInfo) {
- RenderWidget::ShowUnhandledTapUIIfNeeded(tappedInfo);
-}
-
blink::WebWidgetClient* RenderViewImpl::WidgetClient() {
return static_cast<RenderWidget*>(this);
}
@@ -1900,77 +1869,6 @@ void RenderViewImpl::OnEnumerateDirectoryResponse(
enumeration_completions_.erase(id);
}
-void RenderViewImpl::OnEnableAutoResize(const gfx::Size& min_size,
- const gfx::Size& max_size) {
- DCHECK(disable_scrollbars_size_limit_.IsEmpty());
- if (!webview())
- return;
-
- auto_resize_mode_ = true;
-
- if (IsUseZoomForDSFEnabled()) {
- webview()->EnableAutoResizeMode(
- gfx::ScaleToCeiledSize(min_size,
- GetWebScreenInfo().device_scale_factor),
- gfx::ScaleToCeiledSize(max_size,
- GetWebScreenInfo().device_scale_factor));
- } else {
- webview()->EnableAutoResizeMode(min_size, max_size);
- }
-}
-
-void RenderViewImpl::OnDisableAutoResize(const gfx::Size& new_size) {
- DCHECK(disable_scrollbars_size_limit_.IsEmpty());
- if (!webview())
- return;
- auto_resize_mode_ = false;
- auto_resize_ack_callback_.Cancel();
- need_resize_ack_for_auto_resize_ = false;
- webview()->DisableAutoResizeMode();
-
- if (!new_size.IsEmpty()) {
- ResizeParams resize_params;
- resize_params.screen_info = screen_info_;
- resize_params.new_size = new_size;
- resize_params.compositor_viewport_pixel_size =
- compositor_viewport_pixel_size_;
- resize_params.browser_controls_shrink_blink_size =
- browser_controls_shrink_blink_size_;
- resize_params.top_controls_height = top_controls_height_;
- resize_params.visible_viewport_size = visible_viewport_size_;
- resize_params.is_fullscreen_granted = is_fullscreen_granted();
- resize_params.display_mode = display_mode_;
- resize_params.needs_resize_ack = false;
- Resize(resize_params);
- }
-}
-
-void RenderViewImpl::OnSetLocalSurfaceIdForAutoResize(
- uint64_t sequence_number,
- const gfx::Size& min_size,
- const gfx::Size& max_size,
- const content::ScreenInfo& screen_info,
- uint32_t content_source_id,
- const viz::LocalSurfaceId& local_surface_id) {
- if (!auto_resize_mode_ || auto_resize_sequence_number_ != sequence_number) {
- DidResizeOrRepaintAck();
- return;
- }
-
- SetLocalSurfaceIdForAutoResize(sequence_number, screen_info,
- content_source_id, local_surface_id);
-
- if (IsUseZoomForDSFEnabled()) {
- webview()->EnableAutoResizeMode(
- gfx::ScaleToCeiledSize(min_size,
- GetWebScreenInfo().device_scale_factor),
- gfx::ScaleToCeiledSize(max_size,
- GetWebScreenInfo().device_scale_factor));
- } else {
- webview()->EnableAutoResizeMode(min_size, max_size);
- }
-}
-
void RenderViewImpl::OnEnablePreferredSizeChangedMode() {
if (send_preferred_size_changes_)
return;
@@ -2084,6 +1982,30 @@ void RenderViewImpl::OnResize(const ResizeParams& params) {
}
}
+ bool auto_resize_mode_changed =
+ auto_resize_mode_ != params.auto_resize_enabled;
+ auto_resize_mode_ = params.auto_resize_enabled;
+ min_size_for_auto_resize_ = params.min_size_for_auto_resize;
+ max_size_for_auto_resize_ = params.max_size_for_auto_resize;
+ if (auto_resize_mode_) {
+ if (IsUseZoomForDSFEnabled()) {
+ webview()->EnableAutoResizeMode(
+ gfx::ScaleToCeiledSize(params.min_size_for_auto_resize,
+ params.screen_info.device_scale_factor),
+ gfx::ScaleToCeiledSize(params.max_size_for_auto_resize,
+ params.screen_info.device_scale_factor));
+ } else {
+ webview()->EnableAutoResizeMode(params.min_size_for_auto_resize,
+ params.max_size_for_auto_resize);
+ }
+ } else if (auto_resize_mode_changed) {
+ auto_resize_ack_callback_.Cancel();
+ need_resize_ack_for_auto_resize_ = false;
+ webview()->DisableAutoResizeMode();
+ if (params.new_size.IsEmpty())
+ return;
+ }
+
browser_controls_shrink_blink_size_ =
params.browser_controls_shrink_blink_size;
top_controls_height_ = params.top_controls_height;
@@ -2099,8 +2021,14 @@ void RenderViewImpl::OnResize(const ResizeParams& params) {
RenderWidget::OnResize(params);
}
- if (params.scroll_focused_node_into_view)
- webview()->ScrollFocusedEditableElementIntoView();
+ if (!params.scroll_focused_node_into_view)
+ return;
+
+ if (WebLocalFrame* focused_frame = GetWebView()->FocusedFrame()) {
+ focused_frame->LocalRoot()
+ ->FrameWidget()
+ ->ScrollFocusedEditableElementIntoView();
+ }
}
void RenderViewImpl::OnSetBackgroundOpaque(bool opaque) {
@@ -2147,10 +2075,6 @@ void RenderViewImpl::Close() {
void RenderViewImpl::OnPageWasHidden() {
#if defined(OS_ANDROID)
SuspendVideoCaptureDevices(true);
-#if BUILDFLAG(ENABLE_WEBRTC)
- if (speech_recognition_dispatcher_)
- speech_recognition_dispatcher_->AbortAllRecognitions();
-#endif
#endif
if (webview()) {
@@ -2186,6 +2110,12 @@ void RenderViewImpl::OnUpdateScreenInfo(const ScreenInfo& screen_info) {
screen_info_ = screen_info;
}
+void RenderViewImpl::OnFreezePage() {
+ if (webview()) {
+ webview()->FreezePage();
+ }
+}
+
GURL RenderViewImpl::GetURLForGraphicsContext3D() {
DCHECK(webview());
WebFrame* main_frame = webview()->MainFrame();
@@ -2228,12 +2158,6 @@ void RenderViewImpl::SetScreenMetricsEmulationParameters(
}
}
-blink::WebSpeechRecognizer* RenderViewImpl::SpeechRecognizer() {
- if (!speech_recognition_dispatcher_)
- speech_recognition_dispatcher_ = new SpeechRecognitionDispatcher(this);
- return speech_recognition_dispatcher_;
-}
-
void RenderViewImpl::ZoomLimitsChanged(double minimum_level,
double maximum_level) {
// Round the double to avoid returning incorrect minimum/maximum zoom
@@ -2464,11 +2388,31 @@ void RenderViewImpl::UseSynchronousResizeModeForTesting(bool enable) {
void RenderViewImpl::EnableAutoResizeForTesting(const gfx::Size& min_size,
const gfx::Size& max_size) {
- OnEnableAutoResize(min_size, max_size);
+ ResizeParams resize_params;
+ resize_params.auto_resize_enabled = true;
+ resize_params.min_size_for_auto_resize = min_size;
+ resize_params.max_size_for_auto_resize = max_size;
+ OnResize(resize_params);
}
void RenderViewImpl::DisableAutoResizeForTesting(const gfx::Size& new_size) {
- OnDisableAutoResize(new_size);
+ if (!auto_resize_mode_)
+ return;
+
+ ResizeParams resize_params;
+ resize_params.auto_resize_enabled = false;
+ resize_params.screen_info = screen_info_;
+ resize_params.new_size = new_size;
+ resize_params.compositor_viewport_pixel_size =
+ compositor_viewport_pixel_size_;
+ resize_params.browser_controls_shrink_blink_size =
+ browser_controls_shrink_blink_size_;
+ resize_params.top_controls_height = top_controls_height_;
+ resize_params.visible_viewport_size = visible_viewport_size_;
+ resize_params.is_fullscreen_granted = is_fullscreen_granted();
+ resize_params.display_mode = display_mode_;
+ resize_params.needs_resize_ack = false;
+ OnResize(resize_params);
}
void RenderViewImpl::OnResolveTapDisambiguation(double timestamp_seconds,
diff --git a/chromium/content/renderer/render_view_impl.h b/chromium/content/renderer/render_view_impl.h
index ae80d437412..6862496a25e 100644
--- a/chromium/content/renderer/render_view_impl.h
+++ b/chromium/content/renderer/render_view_impl.h
@@ -41,17 +41,17 @@
#include "content/renderer/render_widget_owner_delegate.h"
#include "content/renderer/stats_collection_observer.h"
#include "ipc/ipc_platform_file.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
-#include "third_party/WebKit/public/platform/WebScopedVirtualTimePauser.h"
-#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
-#include "third_party/WebKit/public/web/WebAXObject.h"
-#include "third_party/WebKit/public/web/WebConsoleMessage.h"
-#include "third_party/WebKit/public/web/WebElement.h"
-#include "third_party/WebKit/public/web/WebFrameWidget.h"
-#include "third_party/WebKit/public/web/WebHistoryItem.h"
-#include "third_party/WebKit/public/web/WebNavigationType.h"
-#include "third_party/WebKit/public/web/WebNode.h"
-#include "third_party/WebKit/public/web/WebViewClient.h"
+#include "third_party/blink/public/platform/web_input_event.h"
+#include "third_party/blink/public/platform/web_scoped_virtual_time_pauser.h"
+#include "third_party/blink/public/platform/web_security_origin.h"
+#include "third_party/blink/public/web/web_ax_object.h"
+#include "third_party/blink/public/web/web_console_message.h"
+#include "third_party/blink/public/web/web_element.h"
+#include "third_party/blink/public/web/web_frame_widget.h"
+#include "third_party/blink/public/web/web_history_item.h"
+#include "third_party/blink/public/web/web_navigation_type.h"
+#include "third_party/blink/public/web/web_node.h"
+#include "third_party/blink/public/web/web_view_client.h"
#include "ui/base/window_open_disposition.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/rect_f.h"
@@ -72,8 +72,6 @@ namespace blink {
class WebDateTimeChooserCompletion;
class WebGestureEvent;
class WebMouseEvent;
-class WebSpeechRecognizer;
-class WebTappedInfo;
class WebURLRequest;
struct WebDateTimeChooserParams;
struct WebMediaPlayerAction;
@@ -92,7 +90,6 @@ class RendererDateTimePicker;
class RenderViewImplTest;
class RenderViewObserver;
class RenderViewTest;
-class SpeechRecognitionDispatcher;
struct FileChooserParams;
struct ResizeParams;
@@ -271,8 +268,6 @@ class CONTENT_EXPORT RenderViewImpl : public RenderWidget,
void SetToolTipText(const blink::WebString&,
blink::WebTextDirection hint) override;
void SetTouchAction(cc::TouchAction touchAction) override;
- void ShowUnhandledTapUIIfNeeded(
- const blink::WebTappedInfo& tappedInfo) override;
blink::WebWidgetClient* WidgetClient() override;
// blink::WebViewClient implementation --------------------------------------
@@ -315,7 +310,6 @@ class CONTENT_EXPORT RenderViewImpl : public RenderWidget,
void NavigateBackForwardSoon(int offset) override;
int HistoryBackListCount() override;
int HistoryForwardListCount() override;
- blink::WebSpeechRecognizer* SpeechRecognizer() override;
void ZoomLimitsChanged(double minimum_level, double maximum_level) override;
void PageScaleFactorChanged() override;
virtual double zoomLevelToZoomFactor(double zoom_level) const;
@@ -396,7 +390,8 @@ class CONTENT_EXPORT RenderViewImpl : public RenderWidget,
scoped_refptr<base::SingleThreadTaskRunner> task_runner);
void Initialize(mojom::CreateViewParamsPtr params,
- const RenderWidget::ShowCallback& show_callback);
+ const RenderWidget::ShowCallback& show_callback,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner);
void SetScreenMetricsEmulationParameters(
bool enabled,
const blink::WebDeviceEmulationParams& params) override;
@@ -512,15 +507,6 @@ class CONTENT_EXPORT RenderViewImpl : public RenderWidget,
void OnDisableScrollbarsForSmallWindows(
const gfx::Size& disable_scrollbars_size_limit);
void OnEnablePreferredSizeChangedMode();
- void OnEnableAutoResize(const gfx::Size& min_size, const gfx::Size& max_size);
- void OnDisableAutoResize(const gfx::Size& new_size);
- void OnSetLocalSurfaceIdForAutoResize(
- uint64_t sequence_number,
- const gfx::Size& min_size,
- const gfx::Size& max_size,
- const content::ScreenInfo& screen_info,
- uint32_t content_source_id,
- const viz::LocalSurfaceId& local_surface_id);
void OnEnumerateDirectoryResponse(int id,
const std::vector<base::FilePath>& paths);
void OnMediaPlayerActionAt(const gfx::Point& location,
@@ -545,9 +531,7 @@ class CONTENT_EXPORT RenderViewImpl : public RenderWidget,
void OnForceRedraw(const ui::LatencyInfo& latency_info);
void OnSelectWordAroundCaret();
void OnAudioStateChanged(bool is_audio_playing);
-#if defined(OS_MACOSX)
- void OnGetRenderedText();
-#endif
+ void OnPausePageScheduledTasks(bool paused);
// Page message handlers -----------------------------------------------------
void OnUpdateWindowScreenRect(gfx::Rect window_screen_rect);
@@ -555,6 +539,7 @@ class CONTENT_EXPORT RenderViewImpl : public RenderWidget,
void OnPageWasHidden();
void OnPageWasShown();
void OnUpdateScreenInfo(const ScreenInfo& screen_info);
+ void OnFreezePage();
// Adding a new message handler? Please add it in alphabetical order above
// and put it in the same position in the .cc file.
@@ -746,14 +731,6 @@ class CONTENT_EXPORT RenderViewImpl : public RenderWidget,
// "view", but it's also the RenderWidget for the main frame.
blink::WebFrameWidget* frame_widget_;
- // The next group of objects all implement RenderViewObserver, so are deleted
- // along with the RenderView automatically. This is why we just store
- // weak references.
-
- // The speech recognition dispatcher attached to this view, lazily
- // initialized.
- SpeechRecognitionDispatcher* speech_recognition_dispatcher_;
-
#if defined(OS_ANDROID)
// Android Specific ---------------------------------------------------------
diff --git a/chromium/content/renderer/render_view_impl_android.cc b/chromium/content/renderer/render_view_impl_android.cc
index 75a0c0b00fc..c77e4c6be57 100644
--- a/chromium/content/renderer/render_view_impl_android.cc
+++ b/chromium/content/renderer/render_view_impl_android.cc
@@ -9,7 +9,7 @@
#include "cc/trees/layer_tree_host.h"
#include "content/common/view_messages.h"
#include "content/renderer/gpu/render_widget_compositor.h"
-#include "third_party/WebKit/public/web/WebView.h"
+#include "third_party/blink/public/web/web_view.h"
namespace content {
diff --git a/chromium/content/renderer/render_view_linux.cc b/chromium/content/renderer/render_view_linux.cc
index 00800808ce4..ffcc1d4ccc9 100644
--- a/chromium/content/renderer/render_view_linux.cc
+++ b/chromium/content/renderer/render_view_linux.cc
@@ -5,7 +5,7 @@
#include "content/renderer/render_view_impl.h"
#include "content/public/common/renderer_preferences.h"
-#include "third_party/WebKit/public/platform/WebFontRenderStyle.h"
+#include "third_party/blink/public/platform/web_font_render_style.h"
#include "third_party/skia/include/core/SkFontLCDConfig.h"
#include "ui/gfx/font_render_params.h"
diff --git a/chromium/content/renderer/render_view_win.cc b/chromium/content/renderer/render_view_win.cc
index 126d5f4d3c2..1418e155db2 100644
--- a/chromium/content/renderer/render_view_win.cc
+++ b/chromium/content/renderer/render_view_win.cc
@@ -2,10 +2,10 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "content/public/common/renderer_preferences.h"
#include "content/child/webthemeengine_impl_default.h"
+#include "content/public/common/renderer_preferences.h"
#include "content/renderer/render_view_impl.h"
-#include "third_party/WebKit/public/web/win/WebFontRendering.h"
+#include "third_party/blink/public/web/win/web_font_rendering.h"
#include "third_party/skia/include/core/SkFontLCDConfig.h"
#include "ui/gfx/font_render_params.h"
diff --git a/chromium/content/renderer/render_widget.cc b/chromium/content/renderer/render_widget.cc
index 75ffccce6b2..5b535201d5d 100644
--- a/chromium/content/renderer/render_widget.cc
+++ b/chromium/content/renderer/render_widget.cc
@@ -69,33 +69,32 @@
#include "ipc/ipc_message_start.h"
#include "ipc/ipc_sync_message.h"
#include "ipc/ipc_sync_message_filter.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#include "skia/ext/platform_canvas.h"
-#include "third_party/WebKit/public/platform/FilePathConversion.h"
-#include "third_party/WebKit/public/platform/WebCursorInfo.h"
-#include "third_party/WebKit/public/platform/WebDragData.h"
-#include "third_party/WebKit/public/platform/WebDragOperation.h"
-#include "third_party/WebKit/public/platform/WebMouseEvent.h"
-#include "third_party/WebKit/public/platform/WebPoint.h"
-#include "third_party/WebKit/public/platform/WebRect.h"
-#include "third_party/WebKit/public/platform/WebRuntimeFeatures.h"
-#include "third_party/WebKit/public/platform/WebSize.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/scheduler/renderer/render_widget_scheduling_state.h"
-#include "third_party/WebKit/public/platform/scheduler/renderer/renderer_scheduler.h"
-#include "third_party/WebKit/public/web/WebAutofillClient.h"
-#include "third_party/WebKit/public/web/WebDeviceEmulationParams.h"
-#include "third_party/WebKit/public/web/WebFrameWidget.h"
-#include "third_party/WebKit/public/web/WebInputMethodController.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebNode.h"
-#include "third_party/WebKit/public/web/WebPagePopup.h"
-#include "third_party/WebKit/public/web/WebPopupMenuInfo.h"
-#include "third_party/WebKit/public/web/WebRange.h"
-#include "third_party/WebKit/public/web/WebSettings.h"
-#include "third_party/WebKit/public/web/WebTappedInfo.h"
-#include "third_party/WebKit/public/web/WebView.h"
-#include "third_party/WebKit/public/web/WebWidget.h"
+#include "third_party/blink/public/platform/file_path_conversion.h"
+#include "third_party/blink/public/platform/scheduler/web_main_thread_scheduler.h"
+#include "third_party/blink/public/platform/scheduler/web_render_widget_scheduling_state.h"
+#include "third_party/blink/public/platform/web_cursor_info.h"
+#include "third_party/blink/public/platform/web_drag_data.h"
+#include "third_party/blink/public/platform/web_drag_operation.h"
+#include "third_party/blink/public/platform/web_mouse_event.h"
+#include "third_party/blink/public/platform/web_point.h"
+#include "third_party/blink/public/platform/web_rect.h"
+#include "third_party/blink/public/platform/web_runtime_features.h"
+#include "third_party/blink/public/platform/web_size.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/web/web_autofill_client.h"
+#include "third_party/blink/public/web/web_device_emulation_params.h"
+#include "third_party/blink/public/web/web_frame_widget.h"
+#include "third_party/blink/public/web/web_input_method_controller.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_node.h"
+#include "third_party/blink/public/web/web_page_popup.h"
+#include "third_party/blink/public/web/web_popup_menu_info.h"
+#include "third_party/blink/public/web/web_range.h"
+#include "third_party/blink/public/web/web_settings.h"
+#include "third_party/blink/public/web/web_view.h"
+#include "third_party/blink/public/web/web_widget.h"
#include "third_party/skia/include/core/SkShader.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/base/ui_base_features.h"
@@ -149,7 +148,6 @@ using blink::WebRange;
using blink::WebRect;
using blink::WebSize;
using blink::WebString;
-using blink::WebTappedInfo;
using blink::WebTextDirection;
using blink::WebTouchEvent;
using blink::WebTouchPoint;
@@ -393,7 +391,6 @@ RenderWidget::RenderWidget(
closing_(false),
host_closing_(false),
is_swapped_out_(swapped_out),
- for_oopif_(false),
text_input_type_(ui::TEXT_INPUT_TYPE_NONE),
text_input_mode_(ui::TEXT_INPUT_MODE_DEFAULT),
text_input_flags_(0),
@@ -410,6 +407,7 @@ RenderWidget::RenderWidget(
has_host_context_menu_location_(false),
has_added_input_handler_(false),
has_focus_(false),
+ for_oopif_(false),
#if defined(OS_MACOSX)
text_input_client_observer_(new TextInputClientObserver(this)),
#endif
@@ -427,7 +425,7 @@ RenderWidget::RenderWidget(
// In tests there may not be a RenderThreadImpl.
if (RenderThreadImpl::current()) {
render_widget_scheduling_state_ = RenderThreadImpl::current()
- ->GetRendererScheduler()
+ ->GetWebMainThreadScheduler()
->NewRenderWidgetSchedulingState();
render_widget_scheduling_state_->SetHidden(is_hidden_);
}
@@ -488,7 +486,8 @@ RenderWidget* RenderWidget::CreateForPopup(
task_runner, std::move(widget_channel_request)));
ShowCallback opener_callback =
base::Bind(&RenderViewImpl::ShowCreatedPopupWidget, opener->GetWeakPtr());
- widget->Init(opener_callback, RenderWidget::CreateWebWidget(widget.get()));
+ widget->Init(std::move(opener_callback),
+ RenderWidget::CreateWebWidget(widget.get()));
DCHECK(!widget->HasOneRef()); // RenderWidget::Init() adds a reference.
return widget.get();
}
@@ -586,7 +585,7 @@ void RenderWidget::Init(const ShowCallback& show_callback,
render_thread_impl && compositor_
? render_thread_impl->compositor_task_runner()
: nullptr,
- render_thread_impl ? render_thread_impl->GetRendererScheduler()
+ render_thread_impl ? render_thread_impl->GetWebMainThreadScheduler()
: nullptr);
}
@@ -639,29 +638,6 @@ void RenderWidget::SetExternalPopupOriginAdjustmentsForEmulation(
}
#endif
-void RenderWidget::SetLocalSurfaceIdForAutoResize(
- uint64_t sequence_number,
- const content::ScreenInfo& screen_info,
- uint32_t content_source_id,
- const viz::LocalSurfaceId& local_surface_id) {
- // If the given LocalSurfaceId was generated before navigation, don't use it.
- // We should receive a new LocalSurfaceId later.
- viz::LocalSurfaceId new_local_surface_id =
- content_source_id != current_content_source_id_ ? viz::LocalSurfaceId()
- : local_surface_id;
- // TODO(ccameron): If there is a meaningful distinction between |size_| and
- // |compositor_viewport_pixel_size_| is it okay to ignore that distinction
- // here, and assume that |compositor_viewport_pixel_size_| is just |size_| in
- // pixels? Also note that the computation of
- // |new_compositor_viewport_pixel_size| does not appear to take into account
- // device emulation.
- float new_device_scale_factor = screen_info.device_scale_factor;
- gfx::Size new_compositor_viewport_pixel_size =
- gfx::ScaleToCeiledSize(size_, new_device_scale_factor);
- UpdateSurfaceAndScreenInfo(new_local_surface_id,
- new_compositor_viewport_pixel_size, screen_info);
-}
-
void RenderWidget::OnShowHostContextMenu(ContextMenuParams* params) {
if (screen_metrics_emulator_)
screen_metrics_emulator_->OnShowContextMenu(params);
@@ -692,8 +668,6 @@ bool RenderWidget::OnMessageReceived(const IPC::Message& message) {
IPC_MESSAGE_HANDLER(ViewMsg_ShowContextMenu, OnShowContextMenu)
IPC_MESSAGE_HANDLER(ViewMsg_Close, OnClose)
IPC_MESSAGE_HANDLER(ViewMsg_Resize, OnResize)
- IPC_MESSAGE_HANDLER(ViewMsg_SetLocalSurfaceIdForAutoResize,
- OnSetLocalSurfaceIdForAutoResize)
IPC_MESSAGE_HANDLER(ViewMsg_EnableDeviceEmulation,
OnEnableDeviceEmulation)
IPC_MESSAGE_HANDLER(ViewMsg_DisableDeviceEmulation,
@@ -833,23 +807,6 @@ void RenderWidget::OnResize(const ResizeParams& params) {
}
}
-void RenderWidget::OnSetLocalSurfaceIdForAutoResize(
- uint64_t sequence_number,
- const gfx::Size& min_size,
- const gfx::Size& max_size,
- const content::ScreenInfo& screen_info,
- uint32_t content_source_id,
- const viz::LocalSurfaceId& local_surface_id) {
- if (!auto_resize_mode_ || auto_resize_sequence_number_ != sequence_number) {
- DidResizeOrRepaintAck();
- return;
- }
- // TODO(ccameron): This does not appear to interact correctly with device
- // emulation (compare with the intercepting of ScreenInfo in OnResize).
- SetLocalSurfaceIdForAutoResize(sequence_number, screen_info,
- content_source_id, local_surface_id);
-}
-
void RenderWidget::OnEnableDeviceEmulation(
const blink::WebDeviceEmulationParams& params) {
if (!screen_metrics_emulator_) {
@@ -1064,11 +1021,6 @@ void RenderWidget::DidCommitAndDrawCompositorFrame() {
// tab_capture_performancetest.cc.
TRACE_EVENT0("gpu", "RenderWidget::DidCommitAndDrawCompositorFrame");
- // If we haven't commited yet, then this method was called as a response to a
- // previous commit and should not be used to ack the resize.
- if (did_commit_after_resize_)
- DidResizeOrRepaintAck();
-
for (auto& observer : render_frames_)
observer.DidCommitAndDrawCompositorFrame();
@@ -1077,7 +1029,7 @@ void RenderWidget::DidCommitAndDrawCompositorFrame() {
}
void RenderWidget::DidCommitCompositorFrame() {
- did_commit_after_resize_ = true;
+ DidResizeOrRepaintAck();
}
void RenderWidget::DidCompletePageScaleAnimation() {}
@@ -1320,7 +1272,7 @@ bool RenderWidget::WillHandleGestureEvent(const blink::WebGestureEvent& event) {
possible_drag_event_info_.event_source =
ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH;
possible_drag_event_info_.event_location =
- gfx::Point(event.global_x, event.global_y);
+ gfx::ToFlooredPoint(event.PositionInScreen());
return false;
}
@@ -1363,16 +1315,17 @@ gfx::Size RenderWidget::GetSizeForWebWidget() const {
}
void RenderWidget::Resize(const ResizeParams& params) {
+ if (params.auto_resize_enabled && auto_resize_mode_ &&
+ (!params.auto_resize_sequence_number ||
+ auto_resize_sequence_number_ != params.auto_resize_sequence_number)) {
+ DidResizeOrRepaintAck();
+ return;
+ }
+
// The content_source_id that the browser sends us should never be larger than
// |current_content_source_id_|.
DCHECK_GE(1u << 30, current_content_source_id_ - params.content_source_id);
- // If this resize needs to be acked, make sure we ack it only after we commit.
- // It is possible to get DidCommitAndDraw calls that belong to the previous
- // commit, in which case we should not ack this resize.
- if (params.needs_resize_ack)
- did_commit_after_resize_ = false;
-
// Inform the rendering thread of the color space indicate the presence of HDR
// capabilities.
RenderThreadImpl* render_thread = RenderThreadImpl::current();
@@ -1399,8 +1352,13 @@ void RenderWidget::Resize(const ResizeParams& params) {
params.content_source_id == current_content_source_id_) {
new_local_surface_id = *params.local_surface_id;
}
+ gfx::Size new_compositor_viewport_pixel_size =
+ params.auto_resize_enabled
+ ? gfx::ScaleToCeiledSize(size_,
+ params.screen_info.device_scale_factor)
+ : params.compositor_viewport_pixel_size;
UpdateSurfaceAndScreenInfo(new_local_surface_id,
- params.compositor_viewport_pixel_size,
+ new_compositor_viewport_pixel_size,
params.screen_info);
if (compositor_) {
// If surface synchronization is enabled, then this will use the provided
@@ -1418,6 +1376,9 @@ void RenderWidget::Resize(const ResizeParams& params) {
screen_info_.color_space.GetRasterColorSpace());
}
+ if (params.auto_resize_enabled)
+ return;
+
visible_viewport_size_ = params.visible_viewport_size;
// NOTE: We may have entered fullscreen mode without changing our size.
@@ -1530,8 +1491,8 @@ blink::WebLayerTreeView* RenderWidget::InitializeLayerTreeView() {
RenderThreadImpl* render_thread = RenderThreadImpl::current();
if (render_thread) {
input_event_queue_ = new MainThreadEventQueue(
- this, render_thread->GetRendererScheduler()->InputTaskRunner(),
- render_thread->GetRendererScheduler(), should_generate_frame_sink);
+ this, render_thread->GetWebMainThreadScheduler()->InputTaskRunner(),
+ render_thread->GetWebMainThreadScheduler(), should_generate_frame_sink);
InputHandlerManager* input_handler_manager =
render_thread->input_handler_manager();
@@ -1947,6 +1908,7 @@ void RenderWidget::UpdateSurfaceAndScreenInfo(
screen_info_ = new_screen_info;
if (compositor_) {
+ compositor_->SetViewportVisibleRect(ViewportVisibleRect());
// Note carefully that the DSF specified in |new_screen_info| is not the
// DSF used by the compositor during device emulation!
compositor_->SetViewportSizeAndScale(
@@ -2011,10 +1973,13 @@ void RenderWidget::OnUpdateWindowScreenRect(
}
void RenderWidget::OnSetViewportIntersection(
- const gfx::Rect& viewport_intersection) {
+ const gfx::Rect& viewport_intersection,
+ const gfx::Rect& compositor_visible_rect) {
if (auto* frame_widget = GetFrameWidget()) {
DCHECK_EQ(popup_type_, WebPopupType::kWebPopupTypeNone);
+ compositor_visible_rect_ = compositor_visible_rect;
frame_widget->SetRemoteViewportIntersection(viewport_intersection);
+ compositor_->SetViewportVisibleRect(ViewportVisibleRect());
}
}
@@ -2505,30 +2470,6 @@ blink::WebScreenInfo RenderWidget::GetScreenInfo() {
return web_screen_info;
}
-#if defined(OS_ANDROID)
-void RenderWidget::ShowUnhandledTapUIIfNeeded(
- const WebTappedInfo& tapped_info) {
- // Unpack tapped_info. TODO(donnd): inline unpacking.
- bool page_changed = tapped_info.PageChanged();
- const WebNode& tapped_node = tapped_info.GetNode();
- const WebPoint& tapped_position = tapped_info.Position();
- bool should_trigger = !page_changed && tapped_node.IsTextNode() &&
- !tapped_node.IsContentEditable() &&
- !tapped_node.IsInsideFocusableElementOrARIAWidget();
- if (should_trigger) {
- float x_px =
- IsUseZoomForDSFEnabled()
- ? tapped_position.x
- : tapped_position.x * GetWebScreenInfo().device_scale_factor;
- float y_px =
- IsUseZoomForDSFEnabled()
- ? tapped_position.y
- : tapped_position.y * GetWebScreenInfo().device_scale_factor;
- Send(new ViewHostMsg_ShowUnhandledTapUIIfNeeded(routing_id_, x_px, y_px));
- }
-}
-#endif
-
void RenderWidget::DidHandleGestureEvent(const WebGestureEvent& event,
bool event_cancelled) {
#if defined(OS_ANDROID) || defined(USE_AURA)
@@ -2707,9 +2648,10 @@ uint32_t RenderWidget::GetContentSourceId() {
}
void RenderWidget::DidNavigate() {
+ ++current_content_source_id_;
if (!compositor_)
return;
- compositor_->SetContentSourceId(++current_content_source_id_);
+ compositor_->SetContentSourceId(current_content_source_id_);
UpdateSurfaceAndScreenInfo(viz::LocalSurfaceId(),
compositor_viewport_pixel_size_, screen_info_);
@@ -2810,6 +2752,11 @@ PepperPluginInstanceImpl* RenderWidget::GetFocusedPepperPluginInsideWidget() {
}
#endif
+gfx::Rect RenderWidget::ViewportVisibleRect() {
+ return for_oopif_ ? compositor_visible_rect_
+ : gfx::Rect(compositor_viewport_pixel_size_);
+}
+
base::WeakPtr<RenderWidget> RenderWidget::AsWeakPtr() {
return weak_ptr_factory_.GetWeakPtr();
}
diff --git a/chromium/content/renderer/render_widget.h b/chromium/content/renderer/render_widget.h
index d5ec7da28bb..57d685870ba 100644
--- a/chromium/content/renderer/render_widget.h
+++ b/chromium/content/renderer/render_widget.h
@@ -26,11 +26,11 @@
#include "cc/input/overscroll_behavior.h"
#include "cc/input/touch_action.h"
#include "components/viz/common/surfaces/local_surface_id.h"
+#include "content/common/buildflags.h"
#include "content/common/content_export.h"
#include "content/common/cursors/webcursor.h"
#include "content/common/drag_event_source_info.h"
#include "content/common/edit_command.h"
-#include "content/common/features.h"
#include "content/common/widget.mojom.h"
#include "content/public/common/drop_data.h"
#include "content/public/common/screen_info.h"
@@ -46,17 +46,17 @@
#include "ipc/ipc_message.h"
#include "ipc/ipc_sender.h"
#include "mojo/public/cpp/bindings/binding.h"
-#include "ppapi/features/features.h"
-#include "third_party/WebKit/public/platform/WebDisplayMode.h"
-#include "third_party/WebKit/public/platform/WebInputEvent.h"
-#include "third_party/WebKit/public/platform/WebRect.h"
-#include "third_party/WebKit/public/platform/WebReferrerPolicy.h"
-#include "third_party/WebKit/public/platform/WebTextInputInfo.h"
-#include "third_party/WebKit/public/web/WebImeTextSpan.h"
-#include "third_party/WebKit/public/web/WebPopupType.h"
-#include "third_party/WebKit/public/web/WebTextDirection.h"
-#include "third_party/WebKit/public/web/WebWidget.h"
-#include "third_party/WebKit/public/web/WebWidgetClient.h"
+#include "ppapi/buildflags/buildflags.h"
+#include "third_party/blink/public/platform/web_display_mode.h"
+#include "third_party/blink/public/platform/web_input_event.h"
+#include "third_party/blink/public/platform/web_rect.h"
+#include "third_party/blink/public/platform/web_referrer_policy.h"
+#include "third_party/blink/public/platform/web_text_input_info.h"
+#include "third_party/blink/public/web/web_ime_text_span.h"
+#include "third_party/blink/public/web/web_popup_type.h"
+#include "third_party/blink/public/web/web_text_direction.h"
+#include "third_party/blink/public/web/web_widget.h"
+#include "third_party/blink/public/web/web_widget_client.h"
#include "ui/base/ime/text_input_mode.h"
#include "ui/base/ime/text_input_type.h"
#include "ui/base/ui_base_types.h"
@@ -74,7 +74,7 @@ class SyncMessageFilter;
namespace blink {
namespace scheduler {
-class RenderWidgetSchedulingState;
+class WebRenderWidgetSchedulingState;
}
struct WebDeviceEmulationParams;
class WebDragData;
@@ -84,7 +84,6 @@ class WebImage;
class WebInputMethodController;
class WebLocalFrame;
class WebMouseEvent;
-class WebTappedInfo;
struct WebPoint;
} // namespace blink
@@ -204,6 +203,9 @@ class CONTENT_EXPORT RenderWidget
gfx::Point host_context_menu_location() const {
return host_context_menu_location_;
}
+ const gfx::Size& visible_viewport_size() const {
+ return visible_viewport_size_;
+ }
void set_owner_delegate(RenderWidgetOwnerDelegate* owner_delegate) {
DCHECK(!owner_delegate_);
@@ -334,15 +336,6 @@ class CONTENT_EXPORT RenderWidget
// position.
virtual ui::TextInputType GetTextInputType();
-#if defined(OS_ANDROID)
- // Notifies that a tap was not consumed, so showing a UI for the unhandled
- // tap may be needed.
- // Performs various checks on the given WebTappedInfo to apply heuristics to
- // determine if triggering is appropriate.
- void ShowUnhandledTapUIIfNeeded(
- const blink::WebTappedInfo& tapped_info) override;
-#endif
-
// Begins the compositor's scheduler to start producing frames.
void StartCompositor();
@@ -422,6 +415,19 @@ class CONTENT_EXPORT RenderWidget
uint32_t GetContentSourceId();
void DidNavigate();
+ bool auto_resize_mode() const { return auto_resize_mode_; }
+
+ uint64_t auto_resize_sequence_number() const {
+ return auto_resize_sequence_number_;
+ }
+
+ const gfx::Size& min_size_for_auto_resize() const {
+ return min_size_for_auto_resize_;
+ }
+
+ const gfx::Size& max_size_for_auto_resize() const {
+ return max_size_for_auto_resize_;
+ }
// MainThreadEventQueueClient overrides.
// Requests a BeginMainFrame callback from the compositor.
@@ -544,12 +550,6 @@ class CONTENT_EXPORT RenderWidget
RenderWidgetScreenMetricsEmulator* emulator);
#endif
- void SetLocalSurfaceIdForAutoResize(
- uint64_t sequence_number,
- const content::ScreenInfo& screen_info,
- uint32_t content_source_id,
- const viz::LocalSurfaceId& local_surface_id);
-
// RenderWidget IPC message handlers
void OnHandleInputEvent(
const blink::WebInputEvent* event,
@@ -559,13 +559,6 @@ class CONTENT_EXPORT RenderWidget
void OnClose();
void OnCreatingNewAck();
virtual void OnResize(const ResizeParams& params);
- void OnSetLocalSurfaceIdForAutoResize(
- uint64_t sequence_number,
- const gfx::Size& min_size,
- const gfx::Size& max_size,
- const content::ScreenInfo& screen_info,
- uint32_t content_source_id,
- const viz::LocalSurfaceId& local_surface_id);
void OnEnableDeviceEmulation(const blink::WebDeviceEmulationParams& params);
void OnDisableDeviceEmulation();
virtual void OnWasHidden();
@@ -584,7 +577,8 @@ class CONTENT_EXPORT RenderWidget
void OnUpdateScreenRects(const gfx::Rect& view_screen_rect,
const gfx::Rect& window_screen_rect);
void OnUpdateWindowScreenRect(const gfx::Rect& window_screen_rect);
- void OnSetViewportIntersection(const gfx::Rect& viewport_intersection);
+ void OnSetViewportIntersection(const gfx::Rect& viewport_intersection,
+ const gfx::Rect& compositor_visible_rect);
void OnSetIsInert(bool);
void OnUpdateRenderThrottlingStatus(bool is_throttled,
bool subtree_throttled);
@@ -631,6 +625,11 @@ class CONTENT_EXPORT RenderWidget
void set_next_paint_is_repaint_ack();
void reset_next_paint_is_resize_ack();
+ // Returns a rect that the compositor needs to raster. For a main frame this
+ // is always the entire viewprot, but for out-of-process iframes this can be
+ // constrained to limit overdraw.
+ gfx::Rect ViewportVisibleRect();
+
// QueueMessage implementation extracted into a static method for easy
// testing.
static std::unique_ptr<cc::SwapPromise> QueueMessageImpl(
@@ -737,6 +736,12 @@ class CONTENT_EXPORT RenderWidget
// The sequence number used for the auto-resize request.
uint64_t auto_resize_sequence_number_ = 0;
+ // The minimum size to use for auto-resize.
+ gfx::Size min_size_for_auto_resize_;
+
+ // The maximum size to use for auto-resize.
+ gfx::Size max_size_for_auto_resize_;
+
// A pending ResizeOrRepaintAck callback in response to an auto-resize
// initiated by Blink. If auto-resize mode is canceled with an in-flight
// Ack, then the Ack will be canceled.
@@ -773,9 +778,6 @@ class CONTENT_EXPORT RenderWidget
// swapped out, the process can exit.
bool is_swapped_out_;
- // Whether this RenderWidget is for an out-of-process iframe or not.
- bool for_oopif_;
-
// Stores information about the current text input.
blink::WebTextInputInfo text_input_info_;
@@ -855,7 +857,7 @@ class CONTENT_EXPORT RenderWidget
bool has_host_context_menu_location_;
gfx::Point host_context_menu_location_;
- std::unique_ptr<blink::scheduler::RenderWidgetSchedulingState>
+ std::unique_ptr<blink::scheduler::WebRenderWidgetSchedulingState>
render_widget_scheduling_state_;
// Mouse Lock dispatcher attached to this view.
@@ -940,6 +942,9 @@ class CONTENT_EXPORT RenderWidget
// Indicates whether this widget has focus.
bool has_focus_;
+ // Whether this RenderWidget is for an out-of-process iframe or not.
+ bool for_oopif_;
+
// A callback into the creator/opener of this widget, to be executed when
// WebWidgetClient::show() occurs.
ShowCallback show_callback_;
@@ -981,10 +986,7 @@ class CONTENT_EXPORT RenderWidget
scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
- // Keep track of whether we committed after the latest resize that needs to be
- // acked was received. This helps us make sure we don't ack a resize before
- // it's committed.
- bool did_commit_after_resize_ = false;
+ gfx::Rect compositor_visible_rect_;
// Cache whether or not we have touch handlers, to reduce IPCs sent.
// Different consumers in the browser process makes different assumptions, so
diff --git a/chromium/content/renderer/render_widget_browsertest.cc b/chromium/content/renderer/render_widget_browsertest.cc
index ec774a6d757..713c6e6793b 100644
--- a/chromium/content/renderer/render_widget_browsertest.cc
+++ b/chromium/content/renderer/render_widget_browsertest.cc
@@ -9,12 +9,13 @@
#include "content/public/renderer/render_frame_visitor.h"
#include "content/public/test/render_view_test.h"
#include "content/renderer/render_frame_proxy.h"
+#include "content/renderer/render_thread_impl.h"
#include "content/renderer/render_view_impl.h"
#include "content/renderer/render_widget.h"
-#include "third_party/WebKit/public/web/WebFrameWidget.h"
-#include "third_party/WebKit/public/web/WebInputMethodController.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebRange.h"
+#include "third_party/blink/public/web/web_frame_widget.h"
+#include "third_party/blink/public/web/web_input_method_controller.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_range.h"
#include "ui/base/ime/text_input_type.h"
namespace content {
diff --git a/chromium/content/renderer/render_widget_fullscreen_pepper.cc b/chromium/content/renderer/render_widget_fullscreen_pepper.cc
index 04abd361a89..2a9d9a6fde7 100644
--- a/chromium/content/renderer/render_widget_fullscreen_pepper.cc
+++ b/chromium/content/renderer/render_widget_fullscreen_pepper.cc
@@ -19,13 +19,13 @@
#include "content/renderer/render_thread_impl.h"
#include "gpu/ipc/client/gpu_channel_host.h"
#include "skia/ext/platform_canvas.h"
-#include "third_party/WebKit/public/platform/WebCanvas.h"
-#include "third_party/WebKit/public/platform/WebCursorInfo.h"
-#include "third_party/WebKit/public/platform/WebGestureEvent.h"
-#include "third_party/WebKit/public/platform/WebLayer.h"
-#include "third_party/WebKit/public/platform/WebMouseWheelEvent.h"
-#include "third_party/WebKit/public/platform/WebSize.h"
-#include "third_party/WebKit/public/web/WebWidget.h"
+#include "third_party/blink/public/platform/web_canvas.h"
+#include "third_party/blink/public/platform/web_cursor_info.h"
+#include "third_party/blink/public/platform/web_gesture_event.h"
+#include "third_party/blink/public/platform/web_layer.h"
+#include "third_party/blink/public/platform/web_mouse_wheel_event.h"
+#include "third_party/blink/public/platform/web_size.h"
+#include "third_party/blink/public/web/web_widget.h"
#include "ui/gfx/geometry/dip_util.h"
#include "ui/gfx/geometry/size_conversions.h"
#include "ui/gl/gpu_preference.h"
@@ -71,7 +71,7 @@ WebMouseEvent WebMouseEventFromGestureEvent(const WebGestureEvent& gesture) {
// Only convert touch screen gesture events, do not convert
// touchpad/mouse wheel gesture events. (crbug.com/620974)
- if (gesture.source_device != blink::kWebGestureDeviceTouchscreen)
+ if (gesture.SourceDevice() != blink::kWebGestureDeviceTouchscreen)
return WebMouseEvent();
WebInputEvent::Type type = WebInputEvent::kUndefined;
@@ -103,8 +103,10 @@ WebMouseEvent WebMouseEventFromGestureEvent(const WebGestureEvent& gesture) {
mouse.click_count = (mouse.GetType() == WebInputEvent::kMouseDown ||
mouse.GetType() == WebInputEvent::kMouseUp);
- mouse.SetPositionInWidget(gesture.x, gesture.y);
- mouse.SetPositionInScreen(gesture.global_x, gesture.global_y);
+ mouse.SetPositionInWidget(gesture.PositionInWidget().x,
+ gesture.PositionInWidget().y);
+ mouse.SetPositionInScreen(gesture.PositionInScreen().x,
+ gesture.PositionInScreen().y);
return mouse;
}
@@ -177,9 +179,10 @@ class PepperWidget : public WebWidget {
WebMouseEvent mouse(WebInputEvent::kMouseMove,
gesture_event->GetModifiers(),
gesture_event->TimeStampSeconds());
- mouse.SetPositionInWidget(gesture_event->x, gesture_event->y);
- mouse.SetPositionInScreen(gesture_event->global_x,
- gesture_event->global_y);
+ mouse.SetPositionInWidget(gesture_event->PositionInWidget().x,
+ gesture_event->PositionInWidget().y);
+ mouse.SetPositionInScreen(gesture_event->PositionInScreen().x,
+ gesture_event->PositionInScreen().y);
mouse.movement_x = 0;
mouse.movement_y = 0;
result |= widget_->plugin()->HandleInputEvent(mouse, &cursor);
diff --git a/chromium/content/renderer/render_widget_fullscreen_pepper.h b/chromium/content/renderer/render_widget_fullscreen_pepper.h
index 03343b655e6..585270d4ccd 100644
--- a/chromium/content/renderer/render_widget_fullscreen_pepper.h
+++ b/chromium/content/renderer/render_widget_fullscreen_pepper.h
@@ -13,7 +13,7 @@
#include "content/renderer/mouse_lock_dispatcher.h"
#include "content/renderer/pepper/fullscreen_container.h"
#include "content/renderer/render_widget.h"
-#include "third_party/WebKit/public/web/WebWidget.h"
+#include "third_party/blink/public/web/web_widget.h"
#include "url/gurl.h"
namespace blink {
diff --git a/chromium/content/renderer/render_widget_mouse_lock_dispatcher.cc b/chromium/content/renderer/render_widget_mouse_lock_dispatcher.cc
index 1aac9927d0a..e05ea432aa5 100644
--- a/chromium/content/renderer/render_widget_mouse_lock_dispatcher.cc
+++ b/chromium/content/renderer/render_widget_mouse_lock_dispatcher.cc
@@ -7,10 +7,10 @@
#include "content/common/view_messages.h"
#include "content/renderer/render_view_impl.h"
#include "ipc/ipc_message.h"
-#include "third_party/WebKit/public/web/WebFrame.h"
-#include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
-#include "third_party/WebKit/public/web/WebView.h"
-#include "third_party/WebKit/public/web/WebWidget.h"
+#include "third_party/blink/public/web/web_frame.h"
+#include "third_party/blink/public/web/web_user_gesture_indicator.h"
+#include "third_party/blink/public/web/web_view.h"
+#include "third_party/blink/public/web/web_widget.h"
namespace content {
diff --git a/chromium/content/renderer/render_widget_unittest.cc b/chromium/content/renderer/render_widget_unittest.cc
index 5d1b919e33c..0dffdc9eb7d 100644
--- a/chromium/content/renderer/render_widget_unittest.cc
+++ b/chromium/content/renderer/render_widget_unittest.cc
@@ -29,9 +29,9 @@
#include "ipc/ipc_test_sink.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/platform/WebCoalescedInputEvent.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
-#include "third_party/WebKit/public/web/WebDeviceEmulationParams.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/web_coalesced_input_event.h"
+#include "third_party/blink/public/web/web_device_emulation_params.h"
#include "ui/events/base_event_utils.h"
#include "ui/events/blink/web_input_event_traits.h"
#include "ui/gfx/geometry/rect.h"
@@ -84,6 +84,8 @@ class MockWidgetInputHandlerHost : public mojom::WidgetInputHandlerHost {
MOCK_METHOD0(DidStopFlinging, void());
+ MOCK_METHOD0(DidStartScrollingViewport, void());
+
MOCK_METHOD0(ImeCancelComposition, void());
MOCK_METHOD2(ImeCompositionRangeChanged,
@@ -190,7 +192,7 @@ class InteractiveRenderWidget : public RenderWidget {
event.data.scroll_update.delta_y),
blink::WebFloatSize(event.data.scroll_update.delta_x,
event.data.scroll_update.delta_y),
- blink::WebFloatPoint(event.x, event.y),
+ event.PositionInWidget(),
blink::WebFloatSize(event.data.scroll_update.velocity_x,
event.data.scroll_update.velocity_y),
blink::WebOverscrollBehavior());
@@ -263,7 +265,7 @@ TEST_F(RenderWidgetUnittest, EventOverscroll) {
blink::WebInputEvent::kGestureScrollUpdate,
blink::WebInputEvent::kNoModifiers,
ui::EventTimeStampToSeconds(ui::EventTimeForNow()));
- scroll.x = -10;
+ scroll.SetPositionInWidget(gfx::PointF(-10, 0));
scroll.data.scroll_update.delta_y = 10;
MockHandledEventCallback handled_event;
@@ -444,9 +446,14 @@ TEST_F(RenderWidgetUnittest, SurfaceSynchronizationAutoResizeThrottling) {
// Send the LocalSurfaceId for the first Auto-Resize.
viz::ParentLocalSurfaceIdAllocator allocator;
- widget()->OnMessageReceived(ViewMsg_SetLocalSurfaceIdForAutoResize(
- widget()->routing_id(), auto_resize_sequence_number, auto_size,
- auto_size2, ScreenInfo(), 0u, allocator.GenerateId()));
+ content::ResizeParams resize_params;
+ resize_params.auto_resize_enabled = true;
+ resize_params.auto_resize_sequence_number = auto_resize_sequence_number;
+ resize_params.min_size_for_auto_resize = auto_size;
+ resize_params.max_size_for_auto_resize = auto_size2;
+ resize_params.local_surface_id = allocator.GenerateId();
+ widget()->OnMessageReceived(
+ ViewMsg_Resize(widget()->routing_id(), resize_params));
// The LocalSurfaceId should not take because there's another in-flight auto-
// resize operation.
diff --git a/chromium/content/renderer/renderer_blink_platform_impl.cc b/chromium/content/renderer/renderer_blink_platform_impl.cc
index 0affacaa029..c2c62bae127 100644
--- a/chromium/content/renderer/renderer_blink_platform_impl.cc
+++ b/chromium/content/renderer/renderer_blink_platform_impl.cc
@@ -4,8 +4,10 @@
#include "content/renderer/renderer_blink_platform_impl.h"
+#include <algorithm>
#include <memory>
#include <utility>
+#include <vector>
#include "base/command_line.h"
#include "base/feature_list.h"
@@ -15,7 +17,6 @@
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/memory_coordinator_client_registry.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/shared_memory.h"
#include "base/metrics/histogram_macros.h"
#include "base/numerics/safe_conversions.h"
@@ -79,7 +80,6 @@
#include "content/renderer/webpublicsuffixlist_impl.h"
#include "content/renderer/worker_thread_registry.h"
#include "device/gamepad/public/cpp/gamepads.h"
-#include "device/sensors/public/cpp/motion_data.h"
#include "gpu/command_buffer/client/gles2_interface.h"
#include "gpu/config/gpu_info.h"
#include "gpu/ipc/client/gpu_channel_host.h"
@@ -91,45 +91,47 @@
#include "mojo/public/cpp/bindings/strong_associated_binding.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "mojo/public/cpp/system/platform_handle.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
+#include "services/device/public/cpp/generic_sensor/motion_data.h"
#include "services/network/public/cpp/features.h"
#include "services/service_manager/public/cpp/connector.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "services/ui/public/cpp/gpu/context_provider_command_buffer.h"
#include "storage/common/database/database_identifier.h"
-#include "third_party/WebKit/public/common/origin_trials/trial_token_validator.h"
-#include "third_party/WebKit/public/platform/BlameContext.h"
-#include "third_party/WebKit/public/platform/FilePathConversion.h"
-#include "third_party/WebKit/public/platform/URLConversion.h"
-#include "third_party/WebKit/public/platform/WebAudioLatencyHint.h"
-#include "third_party/WebKit/public/platform/WebBlobRegistry.h"
-#include "third_party/WebKit/public/platform/WebFileInfo.h"
-#include "third_party/WebKit/public/platform/WebMediaRecorderHandler.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamCenter.h"
-#include "third_party/WebKit/public/platform/WebMediaStreamCenterClient.h"
-#include "third_party/WebKit/public/platform/WebPluginListBuilder.h"
-#include "third_party/WebKit/public/platform/WebRTCCertificateGenerator.h"
-#include "third_party/WebKit/public/platform/WebRTCPeerConnectionHandler.h"
-#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
-#include "third_party/WebKit/public/platform/WebSocketHandshakeThrottle.h"
-#include "third_party/WebKit/public/platform/WebThread.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
-#include "third_party/WebKit/public/platform/WebURLLoaderFactory.h"
-#include "third_party/WebKit/public/platform/WebURLRequest.h"
-#include "third_party/WebKit/public/platform/WebVector.h"
-#include "third_party/WebKit/public/platform/modules/device_orientation/WebDeviceMotionListener.h"
-#include "third_party/WebKit/public/platform/modules/device_orientation/WebDeviceOrientationListener.h"
-#include "third_party/WebKit/public/platform/modules/webmidi/WebMIDIAccessor.h"
-#include "third_party/WebKit/public/platform/scheduler/child/webthread_base.h"
-#include "third_party/WebKit/public/platform/scheduler/renderer/renderer_scheduler.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "third_party/blink/public/common/origin_trials/trial_token_validator.h"
+#include "third_party/blink/public/platform/blame_context.h"
+#include "third_party/blink/public/platform/file_path_conversion.h"
+#include "third_party/blink/public/platform/modules/device_orientation/web_device_motion_listener.h"
+#include "third_party/blink/public/platform/modules/device_orientation/web_device_orientation_listener.h"
+#include "third_party/blink/public/platform/modules/webmidi/web_midi_accessor.h"
+#include "third_party/blink/public/platform/scheduler/child/webthread_base.h"
+#include "third_party/blink/public/platform/scheduler/web_main_thread_scheduler.h"
+#include "third_party/blink/public/platform/url_conversion.h"
+#include "third_party/blink/public/platform/web_audio_latency_hint.h"
+#include "third_party/blink/public/platform/web_blob_registry.h"
+#include "third_party/blink/public/platform/web_file_info.h"
+#include "third_party/blink/public/platform/web_media_recorder_handler.h"
+#include "third_party/blink/public/platform/web_media_stream_center.h"
+#include "third_party/blink/public/platform/web_media_stream_center_client.h"
+#include "third_party/blink/public/platform/web_plugin_list_builder.h"
+#include "third_party/blink/public/platform/web_rtc_certificate_generator.h"
+#include "third_party/blink/public/platform/web_rtc_peer_connection_handler.h"
+#include "third_party/blink/public/platform/web_security_origin.h"
+#include "third_party/blink/public/platform/web_socket_handshake_throttle.h"
+#include "third_party/blink/public/platform/web_thread.h"
+#include "third_party/blink/public/platform/web_url.h"
+#include "third_party/blink/public/platform/web_url_loader_factory.h"
+#include "third_party/blink/public/platform/web_url_request.h"
+#include "third_party/blink/public/platform/web_vector.h"
+#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/sqlite/sqlite3.h"
#include "url/gurl.h"
#if defined(OS_MACOSX)
+#include "content/child/child_process_sandbox_support_impl_mac.h"
#include "content/common/mac/font_loader.h"
#include "content/renderer/webscrollbarbehavior_impl_mac.h"
-#include "third_party/WebKit/public/platform/mac/WebSandboxSupport.h"
+#include "third_party/blink/public/platform/mac/web_sandbox_support.h"
#endif
#if defined(OS_POSIX)
@@ -140,8 +142,8 @@
#include "base/synchronization/lock.h"
#include "content/child/child_process_sandbox_support_impl_linux.h"
-#include "third_party/WebKit/public/platform/linux/WebFallbackFont.h"
-#include "third_party/WebKit/public/platform/linux/WebSandboxSupport.h"
+#include "third_party/blink/public/platform/linux/web_fallback_font.h"
+#include "third_party/blink/public/platform/linux/web_sandbox_support.h"
#include "third_party/icu/source/common/unicode/utf16.h"
#endif
#endif
@@ -149,13 +151,14 @@
#if defined(USE_AURA)
#include "content/renderer/webscrollbarbehavior_impl_aura.h"
#elif !defined(OS_MACOSX)
-#include "third_party/WebKit/public/platform/WebScrollbarBehavior.h"
+#include "third_party/blink/public/platform/web_scrollbar_behavior.h"
#define WebScrollbarBehaviorImpl blink::WebScrollbarBehavior
#endif
#if BUILDFLAG(ENABLE_WEBRTC)
#include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
#include "content/renderer/media/webrtc/rtc_certificate_generator.h"
+#include "content/renderer/media/webrtc/webrtc_uma_histograms.h"
#endif
using blink::Platform;
@@ -212,6 +215,21 @@ network::mojom::URLLoaderFactoryPtr GetBlobURLLoaderFactoryGetter() {
return blob_loader_factory;
}
+gpu::ContextType ToGpuContextType(blink::Platform::ContextType type) {
+ switch (type) {
+ case blink::Platform::kWebGL1ContextType:
+ return gpu::CONTEXT_TYPE_WEBGL1;
+ case blink::Platform::kWebGL2ContextType:
+ return gpu::CONTEXT_TYPE_WEBGL2;
+ case blink::Platform::kGLES2ContextType:
+ return gpu::CONTEXT_TYPE_OPENGLES2;
+ case blink::Platform::kGLES3ContextType:
+ return gpu::CONTEXT_TYPE_OPENGLES3;
+ }
+ NOTREACHED();
+ return gpu::CONTEXT_TYPE_OPENGLES2;
+}
+
} // namespace
//------------------------------------------------------------------------------
@@ -235,7 +253,7 @@ class RendererBlinkPlatformImpl::FileUtilities : public WebFileUtilitiesImpl {
class RendererBlinkPlatformImpl::SandboxSupport
: public blink::WebSandboxSupport {
public:
- virtual ~SandboxSupport() {}
+ ~SandboxSupport() override {}
#if defined(OS_MACOSX)
bool LoadFont(CTFontRef src_font,
@@ -263,18 +281,18 @@ class RendererBlinkPlatformImpl::SandboxSupport
//------------------------------------------------------------------------------
RendererBlinkPlatformImpl::RendererBlinkPlatformImpl(
- blink::scheduler::RendererScheduler* renderer_scheduler)
- : BlinkPlatformImpl(renderer_scheduler->DefaultTaskRunner(),
+ blink::scheduler::WebMainThreadScheduler* main_thread_scheduler)
+ : BlinkPlatformImpl(main_thread_scheduler->DefaultTaskRunner(),
RenderThreadImpl::current()
? RenderThreadImpl::current()->GetIOTaskRunner()
: nullptr),
compositor_thread_(nullptr),
- main_thread_(renderer_scheduler->CreateMainThread()),
+ main_thread_(main_thread_scheduler->CreateMainThread()),
sudden_termination_disables_(0),
plugin_refresh_allowed_(true),
- default_task_runner_(renderer_scheduler->DefaultTaskRunner()),
+ default_task_runner_(main_thread_scheduler->DefaultTaskRunner()),
web_scrollbar_behavior_(new WebScrollbarBehaviorImpl),
- renderer_scheduler_(renderer_scheduler) {
+ main_thread_scheduler_(main_thread_scheduler) {
#if !defined(OS_ANDROID) && !defined(OS_WIN) && !defined(OS_FUCHSIA)
if (g_sandbox_enabled && sandboxEnabled()) {
sandbox_support_.reset(new RendererBlinkPlatformImpl::SandboxSupport);
@@ -307,7 +325,7 @@ RendererBlinkPlatformImpl::RendererBlinkPlatformImpl(
blink_interface_provider_.reset(
new BlinkInterfaceProviderImpl(connector_.get()));
top_level_blame_context_.Initialize();
- renderer_scheduler_->SetTopLevelBlameContext(&top_level_blame_context_);
+ main_thread_scheduler_->SetTopLevelBlameContext(&top_level_blame_context_);
GetInterfaceProvider()->GetInterface(
mojo::MakeRequest(&web_database_host_info_));
@@ -318,7 +336,7 @@ RendererBlinkPlatformImpl::RendererBlinkPlatformImpl(
RendererBlinkPlatformImpl::~RendererBlinkPlatformImpl() {
WebFileSystemImpl::DeleteThreadSpecificInstance();
- renderer_scheduler_->SetTopLevelBlameContext(nullptr);
+ main_thread_scheduler_->SetTopLevelBlameContext(nullptr);
shared_bitmap_manager_ = nullptr;
}
@@ -551,7 +569,7 @@ RendererBlinkPlatformImpl::CreateLocalStorageNamespace() {
if (!local_storage_cached_areas_) {
local_storage_cached_areas_.reset(new LocalStorageCachedAreas(
RenderThreadImpl::current()->GetStoragePartitionService(),
- renderer_scheduler_));
+ main_thread_scheduler_));
}
return std::make_unique<LocalStorageNamespace>(
local_storage_cached_areas_.get());
@@ -564,7 +582,7 @@ RendererBlinkPlatformImpl::CreateSessionStorageNamespace(
if (!local_storage_cached_areas_) {
local_storage_cached_areas_.reset(new LocalStorageCachedAreas(
RenderThreadImpl::current()->GetStoragePartitionService(),
- renderer_scheduler_));
+ main_thread_scheduler_));
}
return std::make_unique<SessionWebStorageNamespaceImpl>(
namespace_id.as_string(), local_storage_cached_areas_.get());
@@ -579,7 +597,7 @@ void RendererBlinkPlatformImpl::CloneSessionStorageNamespace(
if (!local_storage_cached_areas_) {
local_storage_cached_areas_.reset(new LocalStorageCachedAreas(
RenderThreadImpl::current()->GetStoragePartitionService(),
- renderer_scheduler_));
+ main_thread_scheduler_));
}
local_storage_cached_areas_->CloneNamespace(source_namespace,
destination_namespace);
@@ -595,9 +613,10 @@ WebIDBFactory* RendererBlinkPlatformImpl::IdbFactory() {
std::unique_ptr<blink::WebServiceWorkerCacheStorage>
RendererBlinkPlatformImpl::CreateCacheStorage(
- const blink::WebSecurityOrigin& security_origin) {
- return std::make_unique<WebServiceWorkerCacheStorageImpl>(
- thread_safe_sender_.get(), security_origin);
+ service_manager::InterfaceProvider* mojo_provider) {
+ // Requires the Interface Provider from ExecutionContext, because it can be
+ // different of RendererBlinkPlatformImpl::GetInterfaceProvider()
+ return std::make_unique<WebServiceWorkerCacheStorageImpl>(mojo_provider);
}
//------------------------------------------------------------------------------
@@ -635,33 +654,7 @@ bool RendererBlinkPlatformImpl::FileUtilities::GetFileInfo(
bool RendererBlinkPlatformImpl::SandboxSupport::LoadFont(CTFontRef src_font,
CGFontRef* out,
uint32_t* font_id) {
- uint32_t font_data_size;
- base::ScopedCFTypeRef<CFStringRef> name_ref(
- CTFontCopyPostScriptName(src_font));
- base::string16 font_name = SysCFStringRefToUTF16(name_ref);
- float font_point_size = CTFontGetSize(src_font);
- mojo::ScopedSharedBufferHandle font_data;
- if (!RenderThreadImpl::current()->render_message_filter()->LoadFont(
- font_name, font_point_size, &font_data_size, &font_data, font_id)) {
- *out = NULL;
- *font_id = 0;
- return false;
- }
-
- if (font_data_size == 0 || !font_data.is_valid() || *font_id == 0) {
- LOG(ERROR) << "Bad response from RenderProcessHostMsg_LoadFont() for "
- << font_name;
- *out = NULL;
- *font_id = 0;
- return false;
- }
-
- // TODO(jeremy): Need to call back into WebKit to make sure that the font
- // isn't already activated, based on the font id. If it's already
- // activated, don't reactivate it here - crbug.com/72727 .
-
- return FontLoader::CGFontRefFromBuffer(std::move(font_data), font_data_size,
- out);
+ return content::LoadFont(src_font, out, font_id);
}
#elif defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_FUCHSIA)
@@ -860,7 +853,8 @@ void RendererBlinkPlatformImpl::GetPluginList(
for (const WebPluginInfo& plugin : plugins) {
builder->AddPlugin(WebString::FromUTF16(plugin.name),
WebString::FromUTF16(plugin.desc),
- blink::FilePathToWebString(plugin.path.BaseName()));
+ blink::FilePathToWebString(plugin.path.BaseName()),
+ plugin.background_color);
for (const WebPluginMimeType& mime_type : plugin.mime_types) {
builder->AddMediaTypeToLastPlugin(
@@ -1028,6 +1022,8 @@ void RendererBlinkPlatformImpl::CreateHTMLAudioElementCapturer(
blink::WebMediaStreamSource::Capabilities capabilities;
capabilities.device_id = track_id;
capabilities.echo_cancellation = std::vector<bool>({false});
+ capabilities.auto_gain_control = std::vector<bool>({false});
+ capabilities.noise_suppression = std::vector<bool>({false});
web_media_stream_source.SetCapabilities(capabilities);
media_stream_source->ConnectToTrack(web_media_stream_track);
@@ -1046,6 +1042,13 @@ RendererBlinkPlatformImpl::CreateImageCaptureFrameGrabber() {
#endif // BUILDFLAG(ENABLE_WEBRTC)
}
+void RendererBlinkPlatformImpl::UpdateWebRTCAPICount(
+ blink::WebRTCAPIName api_name) {
+#if BUILDFLAG(ENABLE_WEBRTC)
+ UpdateWebRTCMethodCount(api_name);
+#endif
+}
+
//------------------------------------------------------------------------------
std::unique_ptr<blink::WebSocketHandshakeThrottle>
@@ -1141,12 +1144,8 @@ RendererBlinkPlatformImpl::CreateOffscreenGraphicsContext3DProvider(
attributes.fail_if_major_perf_caveat =
web_attributes.fail_if_major_performance_caveat;
- DCHECK_GT(web_attributes.web_gl_version, 0u);
- DCHECK_LE(web_attributes.web_gl_version, 2u);
- if (web_attributes.web_gl_version == 2)
- attributes.context_type = gpu::CONTEXT_TYPE_WEBGL2;
- else
- attributes.context_type = gpu::CONTEXT_TYPE_WEBGL1;
+
+ attributes.context_type = ToGpuContextType(web_attributes.context_type);
constexpr bool automatic_flushes = true;
constexpr bool support_locking = false;
@@ -1157,8 +1156,8 @@ RendererBlinkPlatformImpl::CreateOffscreenGraphicsContext3DProvider(
RenderThreadImpl::current()->GetGpuMemoryBufferManager(),
kGpuStreamIdDefault, kGpuStreamPriorityDefault,
gpu::kNullSurfaceHandle, GURL(top_document_web_url),
- automatic_flushes, support_locking, gpu::SharedMemoryLimits(),
- attributes, share_context,
+ automatic_flushes, support_locking, web_attributes.support_grcontext,
+ gpu::SharedMemoryLimits(), attributes, share_context,
ui::command_buffer_metrics::OFFSCREEN_CONTEXT_FOR_WEBGL));
return std::make_unique<WebGraphicsContext3DProviderImpl>(
std::move(provider), is_software_rendering);
@@ -1202,9 +1201,10 @@ RendererBlinkPlatformImpl::GetGpuMemoryBufferManager() {
//------------------------------------------------------------------------------
std::unique_ptr<viz::SharedBitmap>
-RendererBlinkPlatformImpl::AllocateSharedBitmap(const blink::WebSize& size) {
- return shared_bitmap_manager_
- ->AllocateSharedBitmap(gfx::Size(size.width, size.height));
+RendererBlinkPlatformImpl::AllocateSharedBitmap(const blink::WebSize& size,
+ viz::ResourceFormat format) {
+ return shared_bitmap_manager_->AllocateSharedBitmap(
+ gfx::Size(size.width, size.height), format);
}
//------------------------------------------------------------------------------
diff --git a/chromium/content/renderer/renderer_blink_platform_impl.h b/chromium/content/renderer/renderer_blink_platform_impl.h
index e8a4578009d..611b6b70f3c 100644
--- a/chromium/content/renderer/renderer_blink_platform_impl.h
+++ b/chromium/content/renderer/renderer_blink_platform_impl.h
@@ -25,9 +25,11 @@
#include "content/renderer/top_level_blame_context.h"
#include "content/renderer/webpublicsuffixlist_impl.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
-#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBFactory.h"
-#include "third_party/WebKit/public/platform/modules/screen_orientation/WebScreenOrientationType.h"
-#include "third_party/WebKit/public/platform/modules/webdatabase/web_database.mojom.h"
+#include "services/service_manager/public/cpp/interface_provider.h"
+#include "third_party/blink/public/platform/modules/cache_storage/cache_storage.mojom.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_factory.h"
+#include "third_party/blink/public/platform/modules/screen_orientation/web_screen_orientation_type.h"
+#include "third_party/blink/public/platform/modules/webdatabase/web_database.mojom.h"
namespace IPC {
class SyncMessageFilter;
@@ -35,7 +37,7 @@ class SyncMessageFilter;
namespace blink {
namespace scheduler {
-class RendererScheduler;
+class WebMainThreadScheduler;
class WebThreadBase;
}
class WebCanvasCaptureHandler;
@@ -45,7 +47,7 @@ class WebMediaRecorderHandler;
class WebMediaStream;
class WebSecurityOrigin;
class WebServiceWorkerCacheStorage;
-}
+} // namespace blink
namespace device {
class Gamepads;
@@ -53,10 +55,6 @@ class MotionData;
class OrientationData;
}
-namespace service_manager {
-class Connector;
-}
-
namespace content {
class BlinkInterfaceProviderImpl;
class ChildURLLoaderFactoryBundle;
@@ -69,7 +67,7 @@ class WebDatabaseObserverImpl;
class CONTENT_EXPORT RendererBlinkPlatformImpl : public BlinkPlatformImpl {
public:
explicit RendererBlinkPlatformImpl(
- blink::scheduler::RendererScheduler* renderer_scheduler);
+ blink::scheduler::WebMainThreadScheduler* main_thread_scheduler);
~RendererBlinkPlatformImpl() override;
// Shutdown must be called just prior to shutting down blink.
@@ -134,7 +132,7 @@ class CONTENT_EXPORT RendererBlinkPlatformImpl : public BlinkPlatformImpl {
blink::WebScrollbarBehavior* ScrollbarBehavior() override;
blink::WebIDBFactory* IdbFactory() override;
std::unique_ptr<blink::WebServiceWorkerCacheStorage> CreateCacheStorage(
- const blink::WebSecurityOrigin& security_origin) override;
+ service_manager::InterfaceProvider* mojo_provider) override;
blink::WebFileSystem* FileSystem() override;
blink::WebString FileSystemCreateOriginIdentifier(
const blink::WebSecurityOrigin& origin) override;
@@ -187,6 +185,7 @@ class CONTENT_EXPORT RendererBlinkPlatformImpl : public BlinkPlatformImpl {
blink::WebMediaPlayer* web_media_player) override;
std::unique_ptr<blink::WebImageCaptureFrameGrabber>
CreateImageCaptureFrameGrabber() override;
+ void UpdateWebRTCAPICount(blink::WebRTCAPIName api_name) override;
std::unique_ptr<blink::WebSocketHandshakeThrottle>
CreateWebSocketHandshakeThrottle() override;
std::unique_ptr<blink::WebGraphicsContext3DProvider>
@@ -199,7 +198,8 @@ class CONTENT_EXPORT RendererBlinkPlatformImpl : public BlinkPlatformImpl {
CreateSharedOffscreenGraphicsContext3DProvider() override;
gpu::GpuMemoryBufferManager* GetGpuMemoryBufferManager() override;
std::unique_ptr<viz::SharedBitmap> AllocateSharedBitmap(
- const blink::WebSize& size) override;
+ const blink::WebSize& size,
+ viz::ResourceFormat format) override;
blink::WebCompositorSupport* CompositorSupport() override;
blink::WebString ConvertIDNToUnicode(const blink::WebString& host) override;
service_manager::Connector* GetConnector() override;
@@ -334,7 +334,9 @@ class CONTENT_EXPORT RendererBlinkPlatformImpl : public BlinkPlatformImpl {
base::IDMap<std::unique_ptr<PlatformEventObserverBase>>
platform_event_observers_;
- blink::scheduler::RendererScheduler* renderer_scheduler_; // NOT OWNED
+ // NOT OWNED
+ blink::scheduler::WebMainThreadScheduler* main_thread_scheduler_;
+
TopLevelBlameContext top_level_blame_context_;
std::unique_ptr<LocalStorageCachedAreas> local_storage_cached_areas_;
diff --git a/chromium/content/renderer/renderer_main.cc b/chromium/content/renderer/renderer_main.cc
index 3d1a58c39be..43eb2aa4338 100644
--- a/chromium/content/renderer/renderer_main.cc
+++ b/chromium/content/renderer/renderer_main.cc
@@ -31,9 +31,9 @@
#include "content/renderer/render_process_impl.h"
#include "content/renderer/render_thread_impl.h"
#include "content/renderer/renderer_main_platform_delegate.h"
-#include "media/media_features.h"
-#include "ppapi/features/features.h"
-#include "third_party/WebKit/public/platform/scheduler/renderer/renderer_scheduler.h"
+#include "media/media_buildflags.h"
+#include "ppapi/buildflags/buildflags.h"
+#include "third_party/blink/public/platform/scheduler/web_main_thread_scheduler.h"
#include "third_party/skia/include/core/SkGraphics.h"
#include "ui/base/ui_base_switches.h"
@@ -56,7 +56,7 @@
#include "base/mac/scoped_nsautorelease_pool.h"
#include "base/message_loop/message_pump_mac.h"
-#include "third_party/WebKit/public/web/WebView.h"
+#include "third_party/blink/public/web/web_view.h"
#endif // OS_MACOSX
#if BUILDFLAG(ENABLE_PLUGINS)
@@ -67,10 +67,6 @@
#include "third_party/webrtc_overrides/init_webrtc.h" // nogncheck
#endif
-#if defined(USE_OZONE)
-#include "ui/ozone/public/client_native_pixmap_factory_ozone.h"
-#endif
-
namespace content {
namespace {
// This function provides some ways to test crash and assertion handling
@@ -98,6 +94,7 @@ int RendererMain(const MainFunctionParams& parameters) {
const base::CommandLine& command_line = parameters.command_line;
+ base::SamplingHeapProfiler::InitTLSSlot();
if (command_line.HasSwitch(switches::kSamplingHeapProfiler)) {
base::SamplingHeapProfiler* profiler =
base::SamplingHeapProfiler::GetInstance();
@@ -126,30 +123,45 @@ int RendererMain(const MainFunctionParams& parameters) {
}
#endif
+ const base::CommandLine& process_command_line =
+ *base::CommandLine::ForCurrentProcess();
+
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID) && \
!defined(OS_FUCHSIA)
// This call could already have been made from zygote_main_linux.cc. However
// we need to do it here if Zygote is disabled.
- if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kNoZygote)) {
+ if (process_command_line.HasSwitch(switches::kNoZygote)) {
SkFontConfigInterface::SetGlobal(new FontConfigIPC(GetSandboxFD()))
->unref();
}
#endif
- if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
- switches::kDisableSkiaRuntimeOpts)) {
+ if (!process_command_line.HasSwitch(switches::kDisableSkiaRuntimeOpts)) {
SkGraphics::Init();
}
-#if defined(OS_ANDROID)
const int kMB = 1024 * 1024;
- size_t font_cache_limit =
- base::SysInfo::IsLowEndDevice() ? kMB : 8 * kMB;
+ size_t font_cache_limit;
+#if defined(OS_ANDROID)
+ font_cache_limit = base::SysInfo::IsLowEndDevice() ? kMB : 8 * kMB;
SkGraphics::SetFontCacheLimit(font_cache_limit);
-#endif
+#else
+ if (process_command_line.HasSwitch(switches::kSkiaFontCacheLimitMb)) {
+ if (base::StringToSizeT(process_command_line.GetSwitchValueASCII(
+ switches::kSkiaFontCacheLimitMb),
+ &font_cache_limit)) {
+ SkGraphics::SetFontCacheLimit(font_cache_limit * kMB);
+ }
+ }
-#if defined(USE_OZONE)
- ui::CreateClientNativePixmapFactoryOzone();
+ size_t resource_cache_limit;
+ if (process_command_line.HasSwitch(switches::kSkiaResourceCacheLimitMb)) {
+ if (base::StringToSizeT(process_command_line.GetSwitchValueASCII(
+ switches::kSkiaResourceCacheLimitMb),
+ &resource_cache_limit)) {
+ SkGraphics::SetResourceCacheTotalByteLimit(resource_cache_limit * kMB);
+ }
+ }
#endif
// This function allows pausing execution using the --renderer-startup-dialog
@@ -189,8 +201,9 @@ int RendererMain(const MainFunctionParams& parameters) {
initial_virtual_time = base::Time::FromDoubleT(initial_time);
}
}
- std::unique_ptr<blink::scheduler::RendererScheduler> renderer_scheduler(
- blink::scheduler::RendererScheduler::Create(initial_virtual_time));
+ std::unique_ptr<blink::scheduler::WebMainThreadScheduler>
+ main_thread_scheduler(blink::scheduler::WebMainThreadScheduler::Create(
+ initial_virtual_time));
// PlatformInitialize uses FieldTrials, so this must happen later.
platform.PlatformInitialize();
@@ -213,7 +226,7 @@ int RendererMain(const MainFunctionParams& parameters) {
// instruction down.
auto render_process = RenderProcessImpl::Create();
RenderThreadImpl::Create(std::move(main_message_loop),
- std::move(renderer_scheduler));
+ std::move(main_thread_scheduler));
#endif
bool run_loop = true;
if (!no_sandbox)
@@ -221,7 +234,7 @@ int RendererMain(const MainFunctionParams& parameters) {
#if defined(OS_POSIX) && !defined(OS_MACOSX)
auto render_process = RenderProcessImpl::Create();
RenderThreadImpl::Create(std::move(main_message_loop),
- std::move(renderer_scheduler));
+ std::move(main_thread_scheduler));
#endif
base::HighResolutionTimerManager hi_res_timer_manager;
diff --git a/chromium/content/renderer/renderer_main_platform_delegate_android.cc b/chromium/content/renderer/renderer_main_platform_delegate_android.cc
index 44f2588dfb6..0929aabe15f 100644
--- a/chromium/content/renderer/renderer_main_platform_delegate_android.cc
+++ b/chromium/content/renderer/renderer_main_platform_delegate_android.cc
@@ -9,10 +9,9 @@
#include "base/trace_event/trace_event.h"
#include "content/renderer/seccomp_sandbox_status_android.h"
#include "sandbox/linux/seccomp-bpf-helpers/seccomp_starter_android.h"
-#include "sandbox/sandbox_features.h"
+#include "sandbox/sandbox_buildflags.h"
#if BUILDFLAG(USE_SECCOMP_BPF)
-#include "base/memory/ptr_util.h"
#include "sandbox/linux/seccomp-bpf-helpers/baseline_policy_android.h"
#endif
diff --git a/chromium/content/renderer/renderer_main_platform_delegate_win.cc b/chromium/content/renderer/renderer_main_platform_delegate_win.cc
index 52d6c358821..bb193916caf 100644
--- a/chromium/content/renderer/renderer_main_platform_delegate_win.cc
+++ b/chromium/content/renderer/renderer_main_platform_delegate_win.cc
@@ -20,8 +20,8 @@
#include "content/public/renderer/render_thread.h"
#include "content/renderer/render_thread_impl.h"
#include "sandbox/win/src/sandbox.h"
-#include "third_party/WebKit/public/platform/WebRuntimeFeatures.h"
-#include "third_party/WebKit/public/web/win/WebFontRendering.h"
+#include "third_party/blink/public/platform/web_runtime_features.h"
+#include "third_party/blink/public/web/win/web_font_rendering.h"
#include "third_party/icu/source/i18n/unicode/timezone.h"
#include "third_party/skia/include/ports/SkTypeface_win.h"
#include "ui/display/win/dpi.h"
diff --git a/chromium/content/renderer/renderer_webapplicationcachehost_impl.cc b/chromium/content/renderer/renderer_webapplicationcachehost_impl.cc
index 1208ef5fc96..785f6fe15be 100644
--- a/chromium/content/renderer/renderer_webapplicationcachehost_impl.cc
+++ b/chromium/content/renderer/renderer_webapplicationcachehost_impl.cc
@@ -8,9 +8,9 @@
#include "content/renderer/render_frame_impl.h"
#include "content/renderer/render_thread_impl.h"
#include "content/renderer/render_view_impl.h"
-#include "third_party/WebKit/public/web/WebFrame.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebView.h"
+#include "third_party/blink/public/web/web_frame.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_view.h"
using blink::WebApplicationCacheHostClient;
using blink::WebConsoleMessage;
diff --git a/chromium/content/renderer/renderer_webcookiejar_impl.h b/chromium/content/renderer/renderer_webcookiejar_impl.h
index f15b098cc60..cc43adaf252 100644
--- a/chromium/content/renderer/renderer_webcookiejar_impl.h
+++ b/chromium/content/renderer/renderer_webcookiejar_impl.h
@@ -6,7 +6,7 @@
#define CONTENT_RENDERER_RENDERER_WEBCOOKIEJAR_IMPL_H_
// TODO(darin): WebCookieJar.h is missing a WebString.h include!
-#include "third_party/WebKit/public/platform/WebCookieJar.h"
+#include "third_party/blink/public/platform/web_cookie_jar.h"
namespace content {
class RenderFrameImpl;
diff --git a/chromium/content/renderer/resource_timing_info_conversions.cc b/chromium/content/renderer/resource_timing_info_conversions.cc
index 6f9c67db862..4ca8cc15ce6 100644
--- a/chromium/content/renderer/resource_timing_info_conversions.cc
+++ b/chromium/content/renderer/resource_timing_info_conversions.cc
@@ -8,9 +8,9 @@
#include <vector>
#include "content/common/resource_timing_info.h"
-#include "third_party/WebKit/public/platform/WebResourceTimingInfo.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebVector.h"
+#include "third_party/blink/public/platform/web_resource_timing_info.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_vector.h"
namespace content {
diff --git a/chromium/content/renderer/resource_timing_info_conversions.h b/chromium/content/renderer/resource_timing_info_conversions.h
index e1a55e280b8..0a4f855d097 100644
--- a/chromium/content/renderer/resource_timing_info_conversions.h
+++ b/chromium/content/renderer/resource_timing_info_conversions.h
@@ -6,7 +6,7 @@
#define CONTENT_RENDERER_RESOURCE_TIMING_INFO_CONVERSIONS_H_
#include "content/common/resource_timing_info.h"
-#include "third_party/WebKit/public/platform/WebResourceTimingInfo.h"
+#include "third_party/blink/public/platform/web_resource_timing_info.h"
namespace content {
diff --git a/chromium/content/renderer/sad_plugin.h b/chromium/content/renderer/sad_plugin.h
index 412e8cb22a7..b14808b9f89 100644
--- a/chromium/content/renderer/sad_plugin.h
+++ b/chromium/content/renderer/sad_plugin.h
@@ -5,7 +5,7 @@
#ifndef CONTENT_RENDERER_SAD_PLUGIN_H_
#define CONTENT_RENDERER_SAD_PLUGIN_H_
-#include "third_party/WebKit/public/platform/WebCanvas.h"
+#include "third_party/blink/public/platform/web_canvas.h"
class SkBitmap;
diff --git a/chromium/content/renderer/savable_resources.cc b/chromium/content/renderer/savable_resources.cc
index 5f83331012d..79cf744b86c 100644
--- a/chromium/content/renderer/savable_resources.cc
+++ b/chromium/content/renderer/savable_resources.cc
@@ -11,15 +11,15 @@
#include "base/strings/string_util.h"
#include "content/public/common/url_utils.h"
#include "content/renderer/render_frame_impl.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebVector.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebElement.h"
-#include "third_party/WebKit/public/web/WebElementCollection.h"
-#include "third_party/WebKit/public/web/WebInputElement.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebNode.h"
-#include "third_party/WebKit/public/web/WebView.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_vector.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_element.h"
+#include "third_party/blink/public/web/web_element_collection.h"
+#include "third_party/blink/public/web/web_input_element.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_node.h"
+#include "third_party/blink/public/web/web_view.h"
using blink::WebDocument;
using blink::WebElement;
diff --git a/chromium/content/renderer/savable_resources.h b/chromium/content/renderer/savable_resources.h
index 2ccefe0fff8..984874bf336 100644
--- a/chromium/content/renderer/savable_resources.h
+++ b/chromium/content/renderer/savable_resources.h
@@ -11,7 +11,7 @@
#include "base/macros.h"
#include "content/common/content_export.h"
#include "content/common/savable_subframe.h"
-#include "third_party/WebKit/public/platform/WebReferrerPolicy.h"
+#include "third_party/blink/public/platform/web_referrer_policy.h"
#include "url/gurl.h"
namespace blink {
diff --git a/chromium/content/renderer/savable_resources_browsertest.cc b/chromium/content/renderer/savable_resources_browsertest.cc
index cbe4683a0f7..98757ceafc5 100644
--- a/chromium/content/renderer/savable_resources_browsertest.cc
+++ b/chromium/content/renderer/savable_resources_browsertest.cc
@@ -17,8 +17,8 @@
#include "net/base/filename_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/web/WebFrame.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "third_party/blink/public/web/web_frame.h"
+#include "third_party/blink/public/web/web_local_frame.h"
namespace content {
diff --git a/chromium/content/renderer/scheduler/OWNERS b/chromium/content/renderer/scheduler/OWNERS
deleted file mode 100644
index 9bf4416d843..00000000000
--- a/chromium/content/renderer/scheduler/OWNERS
+++ /dev/null
@@ -1,6 +0,0 @@
-alexclarke@chromium.org
-rmcilroy@chromium.org
-skyostil@chromium.org
-
-# TEAM: scheduler-dev@chromium.org
-# COMPONENT: Blink>Scheduling
diff --git a/chromium/content/renderer/service_worker/controller_service_worker_connector.cc b/chromium/content/renderer/service_worker/controller_service_worker_connector.cc
index beff4be85a2..b8bc7f4b0a6 100644
--- a/chromium/content/renderer/service_worker/controller_service_worker_connector.cc
+++ b/chromium/content/renderer/service_worker/controller_service_worker_connector.cc
@@ -6,7 +6,6 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
-#include "content/common/service_worker/service_worker_container.mojom.h"
#include "mojo/public/cpp/bindings/interface_request.h"
namespace content {
@@ -24,13 +23,14 @@ ControllerServiceWorkerConnector::ControllerServiceWorkerConnector(
}
mojom::ControllerServiceWorker*
-ControllerServiceWorkerConnector::GetControllerServiceWorker() {
+ControllerServiceWorkerConnector::GetControllerServiceWorker(
+ mojom::ControllerServiceWorkerPurpose purpose) {
switch (state_) {
case State::kDisconnected:
DCHECK(!controller_service_worker_);
DCHECK(container_host_);
- container_host_->GetControllerServiceWorker(
- mojo::MakeRequest(&controller_service_worker_));
+ container_host_->EnsureControllerServiceWorker(
+ mojo::MakeRequest(&controller_service_worker_), purpose);
controller_service_worker_.set_connection_error_handler(base::BindOnce(
&ControllerServiceWorkerConnector::OnControllerConnectionClosed,
base::Unretained(this)));
diff --git a/chromium/content/renderer/service_worker/controller_service_worker_connector.h b/chromium/content/renderer/service_worker/controller_service_worker_connector.h
index 05b72e1ca47..dbab8d8c557 100644
--- a/chromium/content/renderer/service_worker/controller_service_worker_connector.h
+++ b/chromium/content/renderer/service_worker/controller_service_worker_connector.h
@@ -10,6 +10,7 @@
#include "base/observer_list.h"
#include "content/common/content_export.h"
#include "content/common/service_worker/controller_service_worker.mojom.h"
+#include "content/common/service_worker/service_worker_container.mojom.h"
namespace content {
@@ -66,7 +67,8 @@ class CONTENT_EXPORT ControllerServiceWorkerConnector
// This may return nullptr if the connection to the ContainerHost (in the
// browser process) is already terminated.
- mojom::ControllerServiceWorker* GetControllerServiceWorker();
+ mojom::ControllerServiceWorker* GetControllerServiceWorker(
+ mojom::ControllerServiceWorkerPurpose purpose);
void AddObserver(Observer* observer);
void RemoveObserver(Observer* observer);
diff --git a/chromium/content/renderer/service_worker/embedded_worker_instance_client_impl.cc b/chromium/content/renderer/service_worker/embedded_worker_instance_client_impl.cc
index f47464c41ae..d1c2549f738 100644
--- a/chromium/content/renderer/service_worker/embedded_worker_instance_client_impl.cc
+++ b/chromium/content/renderer/service_worker/embedded_worker_instance_client_impl.cc
@@ -6,21 +6,20 @@
#include <memory>
-#include "base/memory/ptr_util.h"
+#include "base/metrics/histogram_macros.h"
#include "base/strings/utf_string_conversions.h"
#include "content/child/scoped_child_process_reference.h"
-#include "content/child/thread_safe_sender.h"
-#include "content/common/service_worker/embedded_worker_messages.h"
#include "content/common/service_worker/service_worker_utils.h"
#include "content/public/common/content_client.h"
+#include "content/renderer/render_thread_impl.h"
#include "content/renderer/service_worker/service_worker_context_client.h"
#include "content/renderer/service_worker/web_service_worker_installed_scripts_manager_impl.h"
-#include "third_party/WebKit/public/platform/WebContentSettingsClient.h"
-#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerInstalledScriptsManager.h"
-#include "third_party/WebKit/public/web/WebEmbeddedWorker.h"
-#include "third_party/WebKit/public/web/WebEmbeddedWorkerStartData.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_installed_scripts_manager.h"
+#include "third_party/blink/public/platform/web_content_settings_client.h"
+#include "third_party/blink/public/platform/web_security_origin.h"
+#include "third_party/blink/public/platform/web_url.h"
+#include "third_party/blink/public/web/web_embedded_worker.h"
+#include "third_party/blink/public/web/web_embedded_worker_start_data.h"
namespace content {
@@ -67,9 +66,19 @@ void EmbeddedWorkerInstanceClientImpl::StartWorker(
std::move(params->controller_request),
std::move(params->service_worker_host), std::move(params->instance_host),
std::move(params->provider_info), std::move(temporal_self_),
- ChildThreadImpl::current()->thread_safe_sender(), io_thread_runner_);
+ RenderThreadImpl::current()
+ ->GetWebMainThreadScheduler()
+ ->DefaultTaskRunner(),
+ io_thread_runner_);
client->set_blink_initialized_time(blink_initialized_time_);
client->set_start_worker_received_time(base::TimeTicks::Now());
+ // Record UMA to indicate StartWorker is received on renderer.
+ StartWorkerHistogramEnum metric =
+ params->is_installed ? StartWorkerHistogramEnum::RECEIVED_ON_INSTALLED
+ : StartWorkerHistogramEnum::RECEIVED_ON_UNINSTALLED;
+ UMA_HISTOGRAM_ENUMERATION(
+ "ServiceWorker.EmbeddedWorkerInstanceClient.StartWorker", metric,
+ StartWorkerHistogramEnum::NUM_TYPES);
wrapper_ = StartWorkerContext(std::move(params), std::move(client),
std::move(interface_provider));
}
diff --git a/chromium/content/renderer/service_worker/embedded_worker_instance_client_impl.h b/chromium/content/renderer/service_worker/embedded_worker_instance_client_impl.h
index 6f1dad296e9..e71ab87b7b9 100644
--- a/chromium/content/renderer/service_worker/embedded_worker_instance_client_impl.h
+++ b/chromium/content/renderer/service_worker/embedded_worker_instance_client_impl.h
@@ -12,8 +12,8 @@
#include "content/child/scoped_child_process_reference.h"
#include "content/common/service_worker/embedded_worker.mojom.h"
#include "mojo/public/cpp/bindings/associated_binding.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_installed_scripts_manager.mojom.h"
-#include "third_party/WebKit/public/web/worker_content_settings_proxy.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_installed_scripts_manager.mojom.h"
+#include "third_party/blink/public/web/worker_content_settings_proxy.mojom.h"
namespace blink {
@@ -45,6 +45,13 @@ class ServiceWorkerContextClient;
class EmbeddedWorkerInstanceClientImpl
: public mojom::EmbeddedWorkerInstanceClient {
public:
+ // Enum for UMA to record when StartWorker is received.
+ enum class StartWorkerHistogramEnum {
+ RECEIVED_ON_INSTALLED = 0,
+ RECEIVED_ON_UNINSTALLED = 1,
+ NUM_TYPES
+ };
+
// Creates a new EmbeddedWorkerInstanceClientImpl instance bound to
// |request|. The instance destroys itself when needed, see the class
// documentation.
diff --git a/chromium/content/renderer/service_worker/service_worker_context_client.cc b/chromium/content/renderer/service_worker/service_worker_context_client.cc
index c50636bde1e..9a1972a65a1 100644
--- a/chromium/content/renderer/service_worker/service_worker_context_client.cc
+++ b/chromium/content/renderer/service_worker/service_worker_context_client.cc
@@ -10,7 +10,6 @@
#include "base/lazy_instance.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_checker.h"
@@ -18,16 +17,14 @@
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "base/trace_event/trace_event.h"
-#include "content/child/thread_safe_sender.h"
-#include "content/common/service_worker/embedded_worker_messages.h"
#include "content/common/service_worker/service_worker_event_dispatcher.mojom.h"
#include "content/common/service_worker/service_worker_messages.h"
#include "content/common/service_worker/service_worker_status_code.h"
#include "content/common/service_worker/service_worker_utils.h"
-#include "content/common/weak_wrapper_shared_url_loader_factory.h"
#include "content/public/common/content_features.h"
#include "content/public/common/push_event_payload.h"
#include "content/public/common/referrer.h"
+#include "content/public/common/weak_wrapper_shared_url_loader_factory.h"
#include "content/public/renderer/content_renderer_client.h"
#include "content/public/renderer/document_state.h"
#include "content/public/renderer/worker_thread.h"
@@ -57,33 +54,33 @@
#include "net/http/http_response_headers.h"
#include "services/network/public/mojom/request_context_frame_type.mojom.h"
#include "storage/common/blob_storage/blob_handle.h"
-#include "third_party/WebKit/public/common/message_port/message_port_channel.h"
-#include "third_party/WebKit/public/mojom/blob/blob.mojom.h"
-#include "third_party/WebKit/public/mojom/blob/blob_registry.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_client.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_error_type.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_event_status.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
-#include "third_party/WebKit/public/platform/InterfaceProvider.h"
-#include "third_party/WebKit/public/platform/Platform.h"
-#include "third_party/WebKit/public/platform/URLConversion.h"
-#include "third_party/WebKit/public/platform/WebBlobRegistry.h"
-#include "third_party/WebKit/public/platform/WebReferrerPolicy.h"
-#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebURLResponse.h"
-#include "third_party/WebKit/public/platform/modules/background_fetch/WebBackgroundFetchSettledFetch.h"
-#include "third_party/WebKit/public/platform/modules/notifications/WebNotificationData.h"
-#include "third_party/WebKit/public/platform/modules/payments/WebPaymentHandlerResponse.h"
-#include "third_party/WebKit/public/platform/modules/payments/WebPaymentRequestEventData.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerClientQueryOptions.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerError.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerNetworkProvider.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerRequest.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerResponse.h"
-#include "third_party/WebKit/public/web/modules/serviceworker/WebServiceWorkerContextClient.h"
-#include "third_party/WebKit/public/web/modules/serviceworker/WebServiceWorkerContextProxy.h"
+#include "third_party/blink/public/common/message_port/message_port_channel.h"
+#include "third_party/blink/public/mojom/blob/blob.mojom.h"
+#include "third_party/blink/public/mojom/blob/blob_registry.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_client.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_error_type.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_event_status.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/platform/interface_provider.h"
+#include "third_party/blink/public/platform/modules/background_fetch/web_background_fetch_settled_fetch.h"
+#include "third_party/blink/public/platform/modules/notifications/web_notification_data.h"
+#include "third_party/blink/public/platform/modules/payments/web_payment_handler_response.h"
+#include "third_party/blink/public/platform/modules/payments/web_payment_request_event_data.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_client_query_options.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_error.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_network_provider.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_request.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_response.h"
+#include "third_party/blink/public/platform/platform.h"
+#include "third_party/blink/public/platform/url_conversion.h"
+#include "third_party/blink/public/platform/web_blob_registry.h"
+#include "third_party/blink/public/platform/web_referrer_policy.h"
+#include "third_party/blink/public/platform/web_security_origin.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_url_response.h"
+#include "third_party/blink/public/web/modules/serviceworker/web_service_worker_context_client.h"
+#include "third_party/blink/public/web/modules/serviceworker/web_service_worker_context_proxy.h"
using blink::WebURLRequest;
using blink::MessagePortChannel;
@@ -117,7 +114,7 @@ class WebServiceWorkerNetworkProviderImpl
}
std::unique_ptr<blink::WebURLLoader> CreateURLLoader(
- const blink::WebURLRequest& request,
+ const WebURLRequest& request,
scoped_refptr<base::SingleThreadTaskRunner> task_runner) override {
RenderThreadImpl* render_thread = RenderThreadImpl::current();
if (render_thread && provider_->script_loader_factory() &&
@@ -610,7 +607,6 @@ class ServiceWorkerContextClient::NavigationPreloadRequest final
void OnReceiveResponse(
const network::ResourceResponseHead& response_head,
- const base::Optional<net::SSLInfo>& ssl_info,
network::mojom::DownloadedTempFilePtr downloaded_file) override {
DCHECK(!response_);
DCHECK(!downloaded_file);
@@ -764,14 +760,13 @@ ServiceWorkerContextClient::ServiceWorkerContextClient(
mojom::EmbeddedWorkerInstanceHostAssociatedPtrInfo instance_host,
mojom::ServiceWorkerProviderInfoForStartWorkerPtr provider_info,
std::unique_ptr<EmbeddedWorkerInstanceClientImpl> embedded_worker_client,
- scoped_refptr<ThreadSafeSender> sender,
+ scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner,
scoped_refptr<base::SingleThreadTaskRunner> io_thread_task_runner)
: embedded_worker_id_(embedded_worker_id),
service_worker_version_id_(service_worker_version_id),
service_worker_scope_(service_worker_scope),
script_url_(script_url),
- sender_(sender),
- main_thread_task_runner_(base::ThreadTaskRunnerHandle::Get()),
+ main_thread_task_runner_(std::move(main_thread_task_runner)),
io_thread_task_runner_(io_thread_task_runner),
proxy_(nullptr),
pending_dispatcher_request_(std::move(dispatcher_request)),
@@ -785,7 +780,7 @@ ServiceWorkerContextClient::ServiceWorkerContextClient(
// Create a content::ServiceWorkerNetworkProvider for this data source so
// we can observe its requests.
pending_network_provider_ = ServiceWorkerNetworkProvider::CreateForController(
- std::move(provider_info), sender_);
+ std::move(provider_info));
provider_context_ = pending_network_provider_->context();
TRACE_EVENT_NESTABLE_ASYNC_BEGIN1("ServiceWorker",
@@ -895,7 +890,7 @@ void ServiceWorkerContextClient::WorkerContextStarted(
context_.reset(new WorkerContextData(this));
// Create ServiceWorkerDispatcher first for this worker thread to be used
// later by TakeRegistrationForServiceWorkerGlobalScope() etc.
- ServiceWorkerDispatcher::GetOrCreateThreadSpecificInstance(sender_.get())
+ ServiceWorkerDispatcher::GetOrCreateThreadSpecificInstance()
->SetIOThreadTaskRunner(io_thread_task_runner_);
DCHECK(pending_dispatcher_request_.is_pending());
@@ -927,7 +922,7 @@ void ServiceWorkerContextClient::WorkerContextStarted(
TRACE_EVENT_NESTABLE_ASYNC_BEGIN0("ServiceWorker", "EVALUATE_SCRIPT", this);
}
-void ServiceWorkerContextClient::DidEvaluateWorkerScript(bool success) {
+void ServiceWorkerContextClient::DidEvaluateClassicScript(bool success) {
DCHECK(worker_task_runner_->RunsTasksInCurrentSequence());
(*instance_host_)->OnScriptEvaluated(success);
@@ -997,9 +992,9 @@ void ServiceWorkerContextClient::WorkerContextDestroyed() {
std::move(embedded_worker_client_)));
}
-void ServiceWorkerContextClient::CountFeature(uint32_t feature) {
- Send(new EmbeddedWorkerHostMsg_CountFeature(service_worker_version_id_,
- feature));
+void ServiceWorkerContextClient::CountFeature(
+ blink::mojom::WebFeature feature) {
+ (*instance_host_)->CountFeature(feature);
}
void ServiceWorkerContextClient::ReportException(
@@ -1281,7 +1276,6 @@ void ServiceWorkerContextClient::DidHandlePaymentRequestEvent(
std::unique_ptr<blink::WebServiceWorkerNetworkProvider>
ServiceWorkerContextClient::CreateServiceWorkerNetworkProvider() {
DCHECK(main_thread_task_runner_->RunsTasksInCurrentSequence());
- // Blink is responsible for deleting the returned object.
return std::make_unique<WebServiceWorkerNetworkProviderImpl>(
std::move(pending_network_provider_));
}
@@ -1295,7 +1289,6 @@ ServiceWorkerContextClient::CreateServiceWorkerFetchContext() {
->blink_platform_impl()
->CreateDefaultURLLoaderFactoryBundle();
DCHECK(url_loader_factory_bundle);
- // Blink is responsible for deleting the returned object.
return std::make_unique<ServiceWorkerFetchContextImpl>(
script_url_, url_loader_factory_bundle->Clone(),
provider_context_->provider_id(),
@@ -1308,18 +1301,15 @@ ServiceWorkerContextClient::CreateServiceWorkerProvider() {
DCHECK(main_thread_task_runner_->RunsTasksInCurrentSequence());
DCHECK(provider_context_);
- // Blink is responsible for deleting the returned object.
return std::make_unique<WebServiceWorkerProviderImpl>(
- sender_.get(), provider_context_.get());
+ provider_context_.get());
}
void ServiceWorkerContextClient::PostMessageToClient(
const blink::WebString& uuid,
blink::TransferableMessage message) {
- Send(new ServiceWorkerHostMsg_PostMessageToClient(
- GetRoutingID(), uuid.Utf8(),
- new base::RefCountedData<blink::TransferableMessage>(
- std::move(message))));
+ (*context_->service_worker_host)
+ ->PostMessageToClient(uuid.Utf8(), std::move(message));
}
void ServiceWorkerContextClient::Focus(
@@ -1444,10 +1434,6 @@ void ServiceWorkerContextClient::DispatchPaymentRequestEvent(
proxy_->DispatchPaymentRequestEvent(event_id, webEventData);
}
-void ServiceWorkerContextClient::Send(IPC::Message* message) {
- sender_->Send(message);
-}
-
void ServiceWorkerContextClient::SendWorkerStarted() {
DCHECK(worker_task_runner_->RunsTasksInCurrentSequence());
mojom::EmbeddedWorkerStartTimingPtr timing =
diff --git a/chromium/content/renderer/service_worker/service_worker_context_client.h b/chromium/content/renderer/service_worker/service_worker_context_client.h
index 46de26ac4ca..f3f8557433f 100644
--- a/chromium/content/renderer/service_worker/service_worker_context_client.h
+++ b/chromium/content/renderer/service_worker/service_worker_context_client.h
@@ -27,15 +27,15 @@
#include "content/common/service_worker/service_worker_types.h"
#include "ipc/ipc_listener.h"
#include "mojo/public/cpp/bindings/binding.h"
-#include "third_party/WebKit/public/mojom/blob/blob_registry.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_client.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_event_status.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
-#include "third_party/WebKit/public/platform/modules/payments/payment_app.mojom.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerError.h"
-#include "third_party/WebKit/public/web/modules/serviceworker/WebServiceWorkerContextClient.h"
-#include "third_party/WebKit/public/web/modules/serviceworker/WebServiceWorkerContextProxy.h"
+#include "third_party/blink/public/mojom/blob/blob_registry.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_client.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_event_status.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/platform/modules/payments/payment_app.mojom.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_error.h"
+#include "third_party/blink/public/web/modules/serviceworker/web_service_worker_context_client.h"
+#include "third_party/blink/public/web/modules/serviceworker/web_service_worker_context_proxy.h"
#include "v8/include/v8.h"
namespace base {
@@ -64,7 +64,6 @@ class EmbeddedWorkerInstanceClientImpl;
class ServiceWorkerNetworkProvider;
class ServiceWorkerProviderContext;
class ServiceWorkerTimeoutTimer;
-class ThreadSafeSender;
class WebWorkerFetchContext;
// ServiceWorkerContextClient is a "client" of a service worker execution
@@ -98,7 +97,7 @@ class CONTENT_EXPORT ServiceWorkerContextClient
mojom::EmbeddedWorkerInstanceHostAssociatedPtrInfo instance_host,
mojom::ServiceWorkerProviderInfoForStartWorkerPtr provider_info,
std::unique_ptr<EmbeddedWorkerInstanceClientImpl> embedded_worker_client,
- scoped_refptr<ThreadSafeSender> sender,
+ scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner,
scoped_refptr<base::SingleThreadTaskRunner> io_thread_task_runner);
~ServiceWorkerContextClient() override;
@@ -133,11 +132,11 @@ class CONTENT_EXPORT ServiceWorkerContextClient
void WorkerScriptLoaded() override;
void WorkerContextStarted(
blink::WebServiceWorkerContextProxy* proxy) override;
- void DidEvaluateWorkerScript(bool success) override;
+ void DidEvaluateClassicScript(bool success) override;
void DidInitializeWorkerContext(v8::Local<v8::Context> context) override;
void WillDestroyWorkerContext(v8::Local<v8::Context> context) override;
void WorkerContextDestroyed() override;
- void CountFeature(uint32_t feature) override;
+ void CountFeature(blink::mojom::WebFeature feature) override;
void ReportException(const blink::WebString& error_message,
int line_number,
int column_number,
@@ -394,7 +393,6 @@ class CONTENT_EXPORT ServiceWorkerContextClient
const GURL service_worker_scope_;
const GURL script_url_;
- scoped_refptr<ThreadSafeSender> sender_;
scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner_;
scoped_refptr<base::SingleThreadTaskRunner> io_thread_task_runner_;
scoped_refptr<base::TaskRunner> worker_task_runner_;
diff --git a/chromium/content/renderer/service_worker/service_worker_context_client_unittest.cc b/chromium/content/renderer/service_worker/service_worker_context_client_unittest.cc
index f7ba94f3787..83f769be740 100644
--- a/chromium/content/renderer/service_worker/service_worker_context_client_unittest.cc
+++ b/chromium/content/renderer/service_worker/service_worker_context_client_unittest.cc
@@ -19,24 +19,23 @@
#include "content/renderer/service_worker/service_worker_dispatcher.h"
#include "content/renderer/service_worker/service_worker_timeout_timer.h"
#include "content/renderer/worker_thread_registry.h"
-#include "ipc/ipc_sync_message_filter.h"
-#include "ipc/ipc_test_sink.h"
#include "mojo/public/cpp/bindings/associated_interface_ptr.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/cpp/resource_request.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/common/message_port/message_port_channel.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
-#include "third_party/WebKit/public/platform/WebDataConsumerHandle.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebURLResponse.h"
-#include "third_party/WebKit/public/platform/modules/background_fetch/WebBackgroundFetchSettledFetch.h"
-#include "third_party/WebKit/public/platform/modules/notifications/WebNotificationData.h"
-#include "third_party/WebKit/public/platform/modules/payments/WebPaymentRequestEventData.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerClientsInfo.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerError.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerRequest.h"
-#include "third_party/WebKit/public/web/modules/serviceworker/WebServiceWorkerContextProxy.h"
+#include "third_party/blink/public/common/message_port/message_port_channel.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/platform/modules/background_fetch/web_background_fetch_settled_fetch.h"
+#include "third_party/blink/public/platform/modules/notifications/web_notification_data.h"
+#include "third_party/blink/public/platform/modules/payments/web_payment_request_event_data.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_clients_info.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_error.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_request.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/web_data_consumer_handle.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_url_response.h"
+#include "third_party/blink/public/web/modules/serviceworker/web_service_worker_context_proxy.h"
namespace content {
@@ -57,21 +56,6 @@ struct ContextClientPipes {
registration_host_request;
};
-class TestSender : public ThreadSafeSender {
- public:
- explicit TestSender(IPC::TestSink* ipc_sink)
- : ThreadSafeSender(nullptr, nullptr), ipc_sink_(ipc_sink) {}
-
- bool Send(IPC::Message* message) override { return ipc_sink_->Send(message); }
-
- private:
- ~TestSender() override = default;
-
- IPC::TestSink* ipc_sink_;
-
- DISALLOW_COPY_AND_ASSIGN(TestSender);
-};
-
class MockWebServiceWorkerContextProxy
: public blink::WebServiceWorkerContextProxy {
public:
@@ -209,14 +193,13 @@ class ServiceWorkerContextClientTest : public testing::Test {
void SetUp() override {
task_runner_ = base::MakeRefCounted<base::TestMockTimeTaskRunner>();
message_loop_.SetTaskRunner(task_runner_);
- sender_ = base::MakeRefCounted<TestSender>(&ipc_sink_);
// Use this thread as the worker thread.
WorkerThreadRegistry::Instance()->DidStartCurrentWorkerThread();
}
void TearDown() override {
ServiceWorkerContextClient::ResetThreadSpecificInstanceForTesting();
- ServiceWorkerDispatcher::GetOrCreateThreadSpecificInstance(sender_)
+ ServiceWorkerDispatcher::GetOrCreateThreadSpecificInstance()
->AllowReinstantiationForTesting();
// Unregister this thread from worker threads.
WorkerThreadRegistry::Instance()->WillStopCurrentWorkerThread();
@@ -256,7 +239,6 @@ class ServiceWorkerContextClientTest : public testing::Test {
mojom::EmbeddedWorkerInstanceHostAssociatedPtr embedded_worker_host_ptr;
out_pipes->embedded_worker_host_request =
mojo::MakeRequestAssociatedWithDedicatedPipe(&embedded_worker_host_ptr);
- EXPECT_TRUE(sender_);
return std::make_unique<ServiceWorkerContextClient>(
1 /* embeded_worker_id */, 1 /* service_worker_version_id */,
GURL("https://example.com") /* scope */,
@@ -266,7 +248,9 @@ class ServiceWorkerContextClientTest : public testing::Test {
embedded_worker_host_ptr.PassInterface(),
CreateProviderInfo(&out_pipes->registration_host_request,
&out_pipes->registration),
- nullptr /* embedded_worker_client */, sender_, io_task_runner());
+ nullptr /* embedded_worker_client */,
+ blink::scheduler::GetSingleThreadTaskRunnerForTesting(),
+ io_task_runner());
}
scoped_refptr<base::TestMockTimeTaskRunner> task_runner() const {
@@ -282,8 +266,6 @@ class ServiceWorkerContextClientTest : public testing::Test {
base::MessageLoop message_loop_;
scoped_refptr<base::TestMockTimeTaskRunner> task_runner_;
base::test::ScopedFeatureList feature_list_;
- IPC::TestSink ipc_sink_;
- scoped_refptr<TestSender> sender_;
};
TEST_F(ServiceWorkerContextClientTest, Ping) {
@@ -305,7 +287,7 @@ TEST_F(ServiceWorkerContextClientTest, DispatchFetchEvent) {
std::unique_ptr<ServiceWorkerContextClient> context_client;
context_client = CreateContextClient(&pipes);
context_client->WorkerContextStarted(&mock_proxy);
- context_client->DidEvaluateWorkerScript(true /* success */);
+ context_client->DidEvaluateClassicScript(true /* success */);
task_runner()->RunUntilIdle();
EXPECT_TRUE(mock_proxy.fetch_events().empty());
@@ -336,7 +318,7 @@ TEST_F(ServiceWorkerContextClientTest,
CreateContextClient(&pipes);
MockWebServiceWorkerContextProxy mock_proxy;
context_client->WorkerContextStarted(&mock_proxy);
- context_client->DidEvaluateWorkerScript(true /* success */);
+ context_client->DidEvaluateClassicScript(true /* success */);
task_runner()->RunUntilIdle();
EXPECT_TRUE(mock_proxy.fetch_events().empty());
@@ -375,7 +357,7 @@ TEST_F(ServiceWorkerContextClientTest,
CreateContextClient(&pipes);
MockWebServiceWorkerContextProxy mock_proxy;
context_client->WorkerContextStarted(&mock_proxy);
- context_client->DidEvaluateWorkerScript(true /* success */);
+ context_client->DidEvaluateClassicScript(true /* success */);
task_runner()->RunUntilIdle();
EXPECT_TRUE(mock_proxy.fetch_events().empty());
@@ -424,7 +406,7 @@ TEST_F(ServiceWorkerContextClientTest,
CreateContextClient(&pipes);
MockWebServiceWorkerContextProxy mock_proxy;
context_client->WorkerContextStarted(&mock_proxy);
- context_client->DidEvaluateWorkerScript(true /* success */);
+ context_client->DidEvaluateClassicScript(true /* success */);
task_runner()->RunUntilIdle();
EXPECT_TRUE(mock_proxy.fetch_events().empty());
bool is_idle = false;
diff --git a/chromium/content/renderer/service_worker/service_worker_dispatcher.cc b/chromium/content/renderer/service_worker/service_worker_dispatcher.cc
index b6ef8f6815b..24f00cae4e8 100644
--- a/chromium/content/renderer/service_worker/service_worker_dispatcher.cc
+++ b/chromium/content/renderer/service_worker/service_worker_dispatcher.cc
@@ -8,7 +8,6 @@
#include <utility>
#include "base/lazy_instance.h"
-#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/stl_util.h"
#include "base/threading/thread_local.h"
@@ -19,10 +18,10 @@
#include "content/public/common/content_constants.h"
#include "content/renderer/service_worker/service_worker_provider_context.h"
#include "content/renderer/service_worker/web_service_worker_impl.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_error_type.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerProviderClient.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_error_type.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_provider_client.h"
+#include "third_party/blink/public/platform/web_string.h"
#include "url/url_constants.h"
using blink::WebServiceWorkerError;
@@ -41,9 +40,7 @@ void* const kDeletedServiceWorkerDispatcherMarker =
} // namespace
-ServiceWorkerDispatcher::ServiceWorkerDispatcher(
- scoped_refptr<ThreadSafeSender> thread_safe_sender)
- : thread_safe_sender_(std::move(thread_safe_sender)) {
+ServiceWorkerDispatcher::ServiceWorkerDispatcher() {
g_dispatcher_tls.Pointer()->Set(static_cast<void*>(this));
}
@@ -70,8 +67,7 @@ void ServiceWorkerDispatcher::OnMessageReceived(const IPC::Message& msg) {
}
ServiceWorkerDispatcher*
-ServiceWorkerDispatcher::GetOrCreateThreadSpecificInstance(
- scoped_refptr<ThreadSafeSender> thread_safe_sender) {
+ServiceWorkerDispatcher::GetOrCreateThreadSpecificInstance() {
if (g_dispatcher_tls.Pointer()->Get() ==
kDeletedServiceWorkerDispatcherMarker) {
NOTREACHED() << "Re-instantiating TLS ServiceWorkerDispatcher.";
@@ -81,8 +77,7 @@ ServiceWorkerDispatcher::GetOrCreateThreadSpecificInstance(
return static_cast<ServiceWorkerDispatcher*>(
g_dispatcher_tls.Pointer()->Get());
- ServiceWorkerDispatcher* dispatcher =
- new ServiceWorkerDispatcher(std::move(thread_safe_sender));
+ ServiceWorkerDispatcher* dispatcher = new ServiceWorkerDispatcher();
if (WorkerThread::GetCurrentId())
WorkerThread::AddObserver(dispatcher);
return dispatcher;
@@ -126,10 +121,9 @@ ServiceWorkerDispatcher::GetOrCreateServiceWorker(
// worker thread.
DCHECK(io_thread_task_runner_);
return WebServiceWorkerImpl::CreateForServiceWorkerGlobalScope(
- std::move(info), thread_safe_sender_.get(), io_thread_task_runner_);
+ std::move(info), io_thread_task_runner_);
}
- return WebServiceWorkerImpl::CreateForServiceWorkerClient(
- std::move(info), thread_safe_sender_.get());
+ return WebServiceWorkerImpl::CreateForServiceWorkerClient(std::move(info));
}
void ServiceWorkerDispatcher::SetIOThreadTaskRunner(
diff --git a/chromium/content/renderer/service_worker/service_worker_dispatcher.h b/chromium/content/renderer/service_worker/service_worker_dispatcher.h
index ae1dddd06ba..79d2a6f53e9 100644
--- a/chromium/content/renderer/service_worker/service_worker_dispatcher.h
+++ b/chromium/content/renderer/service_worker/service_worker_dispatcher.h
@@ -16,16 +16,15 @@
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/strings/string16.h"
-#include "content/child/thread_safe_sender.h"
#include "content/common/service_worker/service_worker_types.h"
#include "content/public/renderer/worker_thread.h"
#include "mojo/public/cpp/system/message_pipe.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_state.mojom.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerError.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerProvider.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerRegistration.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_state.mojom.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_error.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_provider.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_registration.h"
namespace base {
class SingleThreadTaskRunner;
@@ -37,7 +36,6 @@ class Message;
namespace content {
-class ThreadSafeSender;
class WebServiceWorkerImpl;
// This class manages communication with the browser process about
@@ -45,8 +43,7 @@ class WebServiceWorkerImpl;
// scripts through methods like navigator.registerServiceWorker().
class CONTENT_EXPORT ServiceWorkerDispatcher : public WorkerThread::Observer {
public:
- explicit ServiceWorkerDispatcher(
- scoped_refptr<ThreadSafeSender> thread_safe_sender);
+ explicit ServiceWorkerDispatcher();
~ServiceWorkerDispatcher() override;
void OnMessageReceived(const IPC::Message& msg);
@@ -65,8 +62,7 @@ class CONTENT_EXPORT ServiceWorkerDispatcher : public WorkerThread::Observer {
void SetIOThreadTaskRunner(
scoped_refptr<base::SingleThreadTaskRunner> io_thread_task_runner);
- static ServiceWorkerDispatcher* GetOrCreateThreadSpecificInstance(
- scoped_refptr<ThreadSafeSender> thread_safe_sender);
+ static ServiceWorkerDispatcher* GetOrCreateThreadSpecificInstance();
// Unlike GetOrCreateThreadSpecificInstance() this doesn't create a new
// instance if thread-local instance doesn't exist.
@@ -98,7 +94,6 @@ class CONTENT_EXPORT ServiceWorkerDispatcher : public WorkerThread::Observer {
WorkerObjectMap service_workers_;
- scoped_refptr<ThreadSafeSender> thread_safe_sender_;
scoped_refptr<base::SingleThreadTaskRunner> io_thread_task_runner_;
DISALLOW_COPY_AND_ASSIGN(ServiceWorkerDispatcher);
diff --git a/chromium/content/renderer/service_worker/service_worker_dispatcher_unittest.cc b/chromium/content/renderer/service_worker/service_worker_dispatcher_unittest.cc
index e72a06422b7..ecf73fcddbe 100644
--- a/chromium/content/renderer/service_worker/service_worker_dispatcher_unittest.cc
+++ b/chromium/content/renderer/service_worker/service_worker_dispatcher_unittest.cc
@@ -12,8 +12,8 @@
#include "content/renderer/service_worker/web_service_worker_impl.h"
#include "mojo/public/cpp/bindings/associated_binding_set.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_error_type.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_error_type.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
namespace content {
@@ -38,8 +38,8 @@ class MockServiceWorkerObjectHost
private:
// Implements blink::mojom::ServiceWorkerObjectHost.
- void PostMessageToServiceWorker(::blink::TransferableMessage message,
- const url::Origin& source_origin) override {
+ void PostMessageToServiceWorker(
+ ::blink::TransferableMessage message) override {
NOTREACHED();
}
void TerminateForTesting(TerminateForTestingCallback callback) override {
@@ -58,8 +58,7 @@ class ServiceWorkerDispatcherTest : public testing::Test {
ServiceWorkerDispatcherTest() {}
void SetUp() override {
- dispatcher_ = std::make_unique<ServiceWorkerDispatcher>(
- nullptr /* thread_safe_sender */);
+ dispatcher_ = std::make_unique<ServiceWorkerDispatcher>();
}
bool ContainsServiceWorker(int handle_id) {
diff --git a/chromium/content/renderer/service_worker/service_worker_fetch_context_impl.cc b/chromium/content/renderer/service_worker/service_worker_fetch_context_impl.cc
index 3abf1555f4a..36a43de7375 100644
--- a/chromium/content/renderer/service_worker/service_worker_fetch_context_impl.cc
+++ b/chromium/content/renderer/service_worker/service_worker_fetch_context_impl.cc
@@ -18,7 +18,8 @@ namespace content {
ServiceWorkerFetchContextImpl::ServiceWorkerFetchContextImpl(
const GURL& worker_script_url,
- std::unique_ptr<SharedURLLoaderFactoryInfo> url_loader_factory_info,
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo>
+ url_loader_factory_info,
int service_worker_provider_id,
std::unique_ptr<URLLoaderThrottleProvider> throttle_provider)
: worker_script_url_(worker_script_url),
@@ -28,11 +29,19 @@ ServiceWorkerFetchContextImpl::ServiceWorkerFetchContextImpl(
ServiceWorkerFetchContextImpl::~ServiceWorkerFetchContextImpl() {}
+void ServiceWorkerFetchContextImpl::SetTerminateSyncLoadEvent(
+ base::WaitableEvent* terminate_sync_load_event) {
+ DCHECK(!terminate_sync_load_event_);
+ terminate_sync_load_event_ = terminate_sync_load_event;
+}
+
void ServiceWorkerFetchContextImpl::InitializeOnWorkerThread() {
resource_dispatcher_ = std::make_unique<ResourceDispatcher>();
+ resource_dispatcher_->set_terminate_sync_load_event(
+ terminate_sync_load_event_);
- url_loader_factory_ =
- SharedURLLoaderFactory::Create(std::move(url_loader_factory_info_));
+ url_loader_factory_ = network::SharedURLLoaderFactory::Create(
+ std::move(url_loader_factory_info_));
}
std::unique_ptr<blink::WebURLLoaderFactory>
@@ -61,7 +70,7 @@ void ServiceWorkerFetchContextImpl::WillSendRequest(
extra_data->set_initiated_in_secure_context(true);
if (throttle_provider_) {
extra_data->set_url_loader_throttles(throttle_provider_->CreateThrottles(
- MSG_ROUTING_NONE, request.Url(), WebURLRequestToResourceType(request)));
+ MSG_ROUTING_NONE, request, WebURLRequestToResourceType(request)));
}
request.SetExtraData(std::move(extra_data));
}
diff --git a/chromium/content/renderer/service_worker/service_worker_fetch_context_impl.h b/chromium/content/renderer/service_worker/service_worker_fetch_context_impl.h
index b3076777294..c231cdb09d4 100644
--- a/chromium/content/renderer/service_worker/service_worker_fetch_context_impl.h
+++ b/chromium/content/renderer/service_worker/service_worker_fetch_context_impl.h
@@ -5,8 +5,8 @@
#ifndef CONTENT_RENDERER_SERVICE_WORKER_SERVICE_WORKER_FETCH_CONTEXT_IMPL_H_
#define CONTENT_RENDERER_SERVICE_WORKER_SERVICE_WORKER_FETCH_CONTEXT_IMPL_H_
-#include "content/public/common/shared_url_loader_factory.h"
-#include "third_party/WebKit/public/platform/WebWorkerFetchContext.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
+#include "third_party/blink/public/platform/web_worker_fetch_context.h"
#include "url/gurl.h"
namespace content {
@@ -17,12 +17,14 @@ class ServiceWorkerFetchContextImpl : public blink::WebWorkerFetchContext {
public:
ServiceWorkerFetchContextImpl(
const GURL& worker_script_url,
- std::unique_ptr<SharedURLLoaderFactoryInfo> url_loader_factory_info,
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo>
+ url_loader_factory_info,
int service_worker_provider_id,
std::unique_ptr<URLLoaderThrottleProvider> throttle_provider);
~ServiceWorkerFetchContextImpl() override;
// blink::WebWorkerFetchContext implementation:
+ void SetTerminateSyncLoadEvent(base::WaitableEvent*) override;
void InitializeOnWorkerThread() override;
std::unique_ptr<blink::WebURLLoaderFactory> CreateURLLoaderFactory() override;
std::unique_ptr<blink::WebURLLoaderFactory> WrapURLLoaderFactory(
@@ -34,14 +36,18 @@ class ServiceWorkerFetchContextImpl : public blink::WebWorkerFetchContext {
private:
const GURL worker_script_url_;
// Consumed on the worker thread to create |url_loader_factory_|.
- std::unique_ptr<SharedURLLoaderFactoryInfo> url_loader_factory_info_;
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo> url_loader_factory_info_;
const int service_worker_provider_id_;
// Initialized on the worker thread when InitializeOnWorkerThread() is called.
std::unique_ptr<ResourceDispatcher> resource_dispatcher_;
- scoped_refptr<SharedURLLoaderFactory> url_loader_factory_;
+
+ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
std::unique_ptr<URLLoaderThrottleProvider> throttle_provider_;
+
+ // This is owned by ThreadedMessagingProxyBase on the main thread.
+ base::WaitableEvent* terminate_sync_load_event_ = nullptr;
};
} // namespace content
diff --git a/chromium/content/renderer/service_worker/service_worker_message_filter.cc b/chromium/content/renderer/service_worker/service_worker_message_filter.cc
index 97c828c9913..7d52fcc83dd 100644
--- a/chromium/content/renderer/service_worker/service_worker_message_filter.cc
+++ b/chromium/content/renderer/service_worker/service_worker_message_filter.cc
@@ -12,9 +12,10 @@
namespace content {
-ServiceWorkerMessageFilter::ServiceWorkerMessageFilter(ThreadSafeSender* sender)
- : WorkerThreadMessageFilter(sender) {
-}
+ServiceWorkerMessageFilter::ServiceWorkerMessageFilter(
+ ThreadSafeSender* sender,
+ scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner)
+ : WorkerThreadMessageFilter(sender, std::move(main_thread_task_runner)) {}
ServiceWorkerMessageFilter::~ServiceWorkerMessageFilter() {}
@@ -25,8 +26,7 @@ bool ServiceWorkerMessageFilter::ShouldHandleMessage(
void ServiceWorkerMessageFilter::OnFilteredMessageReceived(
const IPC::Message& msg) {
- ServiceWorkerDispatcher::GetOrCreateThreadSpecificInstance(
- thread_safe_sender())
+ ServiceWorkerDispatcher::GetOrCreateThreadSpecificInstance()
->OnMessageReceived(msg);
}
diff --git a/chromium/content/renderer/service_worker/service_worker_message_filter.h b/chromium/content/renderer/service_worker/service_worker_message_filter.h
index fcad144bd61..6b89375e2c2 100644
--- a/chromium/content/renderer/service_worker/service_worker_message_filter.h
+++ b/chromium/content/renderer/service_worker/service_worker_message_filter.h
@@ -14,7 +14,9 @@ namespace content {
class CONTENT_EXPORT ServiceWorkerMessageFilter
: public WorkerThreadMessageFilter {
public:
- explicit ServiceWorkerMessageFilter(ThreadSafeSender* thread_safe_sender);
+ ServiceWorkerMessageFilter(
+ ThreadSafeSender* thread_safe_sender,
+ scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner);
protected:
~ServiceWorkerMessageFilter() override;
diff --git a/chromium/content/renderer/service_worker/service_worker_network_provider.cc b/chromium/content/renderer/service_worker/service_worker_network_provider.cc
index 7dc121f5f3f..a81f33440e7 100644
--- a/chromium/content/renderer/service_worker/service_worker_network_provider.cc
+++ b/chromium/content/renderer/service_worker/service_worker_network_provider.cc
@@ -5,25 +5,25 @@
#include "content/renderer/service_worker/service_worker_network_provider.h"
#include "base/atomic_sequence_num.h"
-#include "content/child/thread_safe_sender.h"
#include "content/common/navigation_params.h"
#include "content/common/service_worker/service_worker_messages.h"
#include "content/common/service_worker/service_worker_provider_host_info.h"
#include "content/common/service_worker/service_worker_utils.h"
-#include "content/common/weak_wrapper_shared_url_loader_factory.h"
+#include "content/common/wrapper_shared_url_loader_factory.h"
#include "content/public/common/browser_side_navigation_policy.h"
-#include "content/public/common/shared_url_loader_factory.h"
+#include "content/public/common/weak_wrapper_shared_url_loader_factory.h"
#include "content/renderer/loader/request_extra_data.h"
#include "content/renderer/render_thread_impl.h"
+#include "content/renderer/renderer_blink_platform_impl.h"
#include "content/renderer/service_worker/service_worker_dispatcher.h"
-#include "content/renderer/service_worker/service_worker_provider_context.h"
#include "ipc/ipc_sync_channel.h"
#include "mojo/public/cpp/bindings/associated_group.h"
-#include "third_party/WebKit/public/common/frame/sandbox_flags.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
-#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerNetworkProvider.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
+#include "third_party/blink/public/common/frame/sandbox_flags.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_network_provider.h"
+#include "third_party/blink/public/platform/web_security_origin.h"
+#include "third_party/blink/public/web/web_local_frame.h"
namespace content {
@@ -100,32 +100,26 @@ class WebServiceWorkerNetworkProviderForFrame
return nullptr;
// S13nServiceWorker:
- // We only install our own URLLoader if Servicification is
- // enabled.
+ // We only install our own URLLoader if Servicification is enabled.
if (!ServiceWorkerUtils::IsServicificationEnabled())
return nullptr;
- // S13nServiceWorker:
- // We need SubresourceLoaderFactory populated in order to
- // create our own URLLoader for subresource loading.
+ // We need SubresourceLoaderFactory populated in order to create our own
+ // URLLoader for subresource loading.
if (!provider_->context() ||
!provider_->context()->GetSubresourceLoaderFactory())
return nullptr;
- // S13nServiceWorker:
- // If it's not for HTTP or HTTPS no need to intercept the
- // request.
+ // If it's not for HTTP or HTTPS, no need to intercept the request.
if (!GURL(request.Url()).SchemeIsHTTPOrHTTPS())
return nullptr;
- // S13nServiceWorker:
- // If GetSkipServiceWorker() returns true, no need to intercept the request.
+ // If GetSkipServiceWorker() returns true, do not intercept the request.
if (request.GetSkipServiceWorker())
return nullptr;
- // S13nServiceWorker:
- // Create our own SubresourceLoader to route the request
- // to the controller ServiceWorker.
+ // Create our own SubresourceLoader to route the request to the controller
+ // ServiceWorker.
// TODO(crbug.com/796425): Temporarily wrap the raw mojom::URLLoaderFactory
// pointer into SharedURLLoaderFactory.
return std::make_unique<WebURLLoaderImpl>(
@@ -149,81 +143,81 @@ ServiceWorkerNetworkProvider::CreateForNavigation(
blink::WebLocalFrame* frame,
bool content_initiated,
mojom::ControllerServiceWorkerInfoPtr controller_info,
- scoped_refptr<SharedURLLoaderFactory> default_loader_factory) {
- bool browser_side_navigation = IsBrowserSideNavigationEnabled();
- bool should_create_provider_for_window = false;
- int service_worker_provider_id = kInvalidServiceWorkerProviderId;
- std::unique_ptr<ServiceWorkerNetworkProvider> network_provider;
-
+ scoped_refptr<network::SharedURLLoaderFactory> default_loader_factory) {
// Determine if a ServiceWorkerNetworkProvider should be created and properly
// initialized for the navigation. A default ServiceWorkerNetworkProvider
// will always be created since it is expected in a certain number of places,
// however it will have an invalid id.
- // PlzNavigate: |service_worker_provider_id| can be sent by the browser, if
- // it already created the SeviceWorkerProviderHost.
- if (browser_side_navigation && !content_initiated) {
- should_create_provider_for_window =
- request_params.should_create_service_worker;
- service_worker_provider_id = request_params.service_worker_provider_id;
- DCHECK(ServiceWorkerUtils::IsBrowserAssignedProviderId(
- service_worker_provider_id) ||
- service_worker_provider_id == kInvalidServiceWorkerProviderId);
- } else {
- should_create_provider_for_window =
+ bool should_create_provider = false;
+ int provider_id = kInvalidServiceWorkerProviderId;
+ if (content_initiated) {
+ should_create_provider =
((frame->EffectiveSandboxFlags() & blink::WebSandboxFlags::kOrigin) !=
blink::WebSandboxFlags::kOrigin);
+ } else {
+ should_create_provider = request_params.should_create_service_worker;
+ provider_id = request_params.service_worker_provider_id;
}
- // Now create the ServiceWorkerNetworkProvider (with invalid id if needed).
- if (should_create_provider_for_window) {
- // Ideally Document::isSecureContext would be called here, but the document
- // is not created yet, and due to redirects the URL may change. So pass
- // is_parent_frame_secure to the browser process, so it can determine the
- // context security when deciding whether to allow a service worker to
- // control the document.
- const bool is_parent_frame_secure = IsFrameSecure(frame->Parent());
-
- if (service_worker_provider_id == kInvalidServiceWorkerProviderId) {
- network_provider = base::WrapUnique(new ServiceWorkerNetworkProvider(
- route_id, blink::mojom::ServiceWorkerProviderType::kForWindow,
- GetNextProviderId(), is_parent_frame_secure,
- std::move(controller_info), std::move(default_loader_factory)));
- } else {
- CHECK(browser_side_navigation);
- DCHECK(ServiceWorkerUtils::IsBrowserAssignedProviderId(
- service_worker_provider_id));
- network_provider = base::WrapUnique(new ServiceWorkerNetworkProvider(
- route_id, blink::mojom::ServiceWorkerProviderType::kForWindow,
- service_worker_provider_id, is_parent_frame_secure,
- std::move(controller_info), std::move(default_loader_factory)));
- }
- } else {
- network_provider = base::WrapUnique(new ServiceWorkerNetworkProvider());
+ // If we shouldn't create a real ServiceWorkerNetworkProvider, return one with
+ // an invalid id.
+ if (!should_create_provider) {
+ return std::make_unique<WebServiceWorkerNetworkProviderForFrame>(
+ base::WrapUnique(new ServiceWorkerNetworkProvider()));
}
+
+ // Otherwise, create the ServiceWorkerNetworkProvider.
+
+ // Ideally Document::IsSecureContext would be called here, but the document is
+ // not created yet, and due to redirects the URL may change. So pass
+ // is_parent_frame_secure to the browser process, so it can determine the
+ // context security when deciding whether to allow a service worker to control
+ // the document.
+ const bool is_parent_frame_secure = IsFrameSecure(frame->Parent());
+
+ // If the browser process did not assign a provider id already, assign one
+ // now (see class comments for content::ServiceWorkerProviderHost).
+ DCHECK(ServiceWorkerUtils::IsBrowserAssignedProviderId(provider_id) ||
+ provider_id == kInvalidServiceWorkerProviderId);
+ if (provider_id == kInvalidServiceWorkerProviderId)
+ provider_id = GetNextProviderId();
+
+ auto provider = base::WrapUnique(new ServiceWorkerNetworkProvider(
+ route_id, blink::mojom::ServiceWorkerProviderType::kForWindow,
+ provider_id, is_parent_frame_secure, std::move(controller_info),
+ std::move(default_loader_factory)));
return std::make_unique<WebServiceWorkerNetworkProviderForFrame>(
- std::move(network_provider));
+ std::move(provider));
}
// static
std::unique_ptr<ServiceWorkerNetworkProvider>
-ServiceWorkerNetworkProvider::CreateForSharedWorker() {
- // TODO(kinuko): Provide SharedURLLoaderFactory associated with the
- // SharedWorker.
+ServiceWorkerNetworkProvider::CreateForSharedWorker(
+ mojom::ServiceWorkerProviderInfoForSharedWorkerPtr info,
+ network::mojom::URLLoaderFactoryAssociatedPtrInfo
+ script_loader_factory_info,
+ scoped_refptr<network::SharedURLLoaderFactory> default_loader_factory) {
+ // S13nServiceWorker: |info| holds info about the precreated provider host.
+ if (info) {
+ DCHECK(ServiceWorkerUtils::IsServicificationEnabled());
+ return base::WrapUnique(new ServiceWorkerNetworkProvider(
+ std::move(info), std::move(script_loader_factory_info),
+ std::move(default_loader_factory)));
+ }
+
return base::WrapUnique(new ServiceWorkerNetworkProvider(
MSG_ROUTING_NONE,
blink::mojom::ServiceWorkerProviderType::kForSharedWorker,
GetNextProviderId(), true /* is_parent_frame_secure */,
nullptr /* controller_service_worker */,
- nullptr /* default_loader_factory*/));
+ std::move(default_loader_factory)));
}
// static
std::unique_ptr<ServiceWorkerNetworkProvider>
ServiceWorkerNetworkProvider::CreateForController(
- mojom::ServiceWorkerProviderInfoForStartWorkerPtr info,
- scoped_refptr<ThreadSafeSender> sender) {
- return base::WrapUnique(
- new ServiceWorkerNetworkProvider(std::move(info), std::move(sender)));
+ mojom::ServiceWorkerProviderInfoForStartWorkerPtr info) {
+ return base::WrapUnique(new ServiceWorkerNetworkProvider(std::move(info)));
}
// static
@@ -263,21 +257,17 @@ ServiceWorkerNetworkProvider::ServiceWorkerNetworkProvider() {}
ServiceWorkerNetworkProvider::ServiceWorkerNetworkProvider(
int route_id,
blink::mojom::ServiceWorkerProviderType provider_type,
- int browser_provider_id,
+ int provider_id,
bool is_parent_frame_secure,
mojom::ControllerServiceWorkerInfoPtr controller_info,
- scoped_refptr<SharedURLLoaderFactory> default_loader_factory) {
- if (browser_provider_id == kInvalidServiceWorkerProviderId)
- return;
-
- // We don't support dedicated worker (WORKER) as an independent service
- // worker client yet.
+ scoped_refptr<network::SharedURLLoaderFactory> default_loader_factory) {
+ DCHECK_NE(provider_id, kInvalidServiceWorkerProviderId);
DCHECK(provider_type == blink::mojom::ServiceWorkerProviderType::kForWindow ||
provider_type ==
blink::mojom::ServiceWorkerProviderType::kForSharedWorker);
- ServiceWorkerProviderHostInfo host_info(
- browser_provider_id, route_id, provider_type, is_parent_frame_secure);
+ ServiceWorkerProviderHostInfo host_info(provider_id, route_id, provider_type,
+ is_parent_frame_secure);
mojom::ServiceWorkerContainerAssociatedRequest client_request =
mojo::MakeRequest(&host_info.client_ptr_info);
mojom::ServiceWorkerContainerHostAssociatedPtrInfo host_ptr_info;
@@ -287,10 +277,9 @@ ServiceWorkerNetworkProvider::ServiceWorkerNetworkProvider(
// current() may be null in tests.
if (ChildThreadImpl::current()) {
- ServiceWorkerDispatcher::GetOrCreateThreadSpecificInstance(
- ChildThreadImpl::current()->thread_safe_sender());
+ ServiceWorkerDispatcher::GetOrCreateThreadSpecificInstance();
context_ = base::MakeRefCounted<ServiceWorkerProviderContext>(
- browser_provider_id, provider_type, std::move(client_request),
+ provider_id, provider_type, std::move(client_request),
std::move(host_ptr_info), std::move(controller_info),
std::move(default_loader_factory));
ChildThreadImpl::current()->channel()->GetRemoteAssociatedInterface(
@@ -298,19 +287,34 @@ ServiceWorkerNetworkProvider::ServiceWorkerNetworkProvider(
dispatcher_host_->OnProviderCreated(std::move(host_info));
} else {
context_ = base::MakeRefCounted<ServiceWorkerProviderContext>(
- browser_provider_id, provider_type, std::move(client_request),
+ provider_id, provider_type, std::move(client_request),
std::move(host_ptr_info), std::move(controller_info),
std::move(default_loader_factory));
}
}
+// Constructor for precreated shared worker.
+ServiceWorkerNetworkProvider::ServiceWorkerNetworkProvider(
+ mojom::ServiceWorkerProviderInfoForSharedWorkerPtr info,
+ network::mojom::URLLoaderFactoryAssociatedPtrInfo
+ script_loader_factory_info,
+ scoped_refptr<network::SharedURLLoaderFactory> default_loader_factory) {
+ ServiceWorkerDispatcher::GetOrCreateThreadSpecificInstance();
+ context_ = base::MakeRefCounted<ServiceWorkerProviderContext>(
+ info->provider_id,
+ blink::mojom::ServiceWorkerProviderType::kForSharedWorker,
+ std::move(info->client_request), std::move(info->host_ptr_info),
+ nullptr /* controller */, std::move(default_loader_factory));
+ if (script_loader_factory_info.is_valid())
+ script_loader_factory_.Bind(std::move(script_loader_factory_info));
+}
+
// Constructor for service worker execution contexts.
ServiceWorkerNetworkProvider::ServiceWorkerNetworkProvider(
- mojom::ServiceWorkerProviderInfoForStartWorkerPtr info,
- scoped_refptr<ThreadSafeSender> sender) {
+ mojom::ServiceWorkerProviderInfoForStartWorkerPtr info) {
// Initialize the provider context with info for
// ServiceWorkerGlobalScope#registration.
- ServiceWorkerDispatcher::GetOrCreateThreadSpecificInstance(sender);
+ ServiceWorkerDispatcher::GetOrCreateThreadSpecificInstance();
context_ = base::MakeRefCounted<ServiceWorkerProviderContext>(
info->provider_id, std::move(info->client_request),
std::move(info->host_ptr_info));
diff --git a/chromium/content/renderer/service_worker/service_worker_network_provider.h b/chromium/content/renderer/service_worker/service_worker_network_provider.h
index 937eae51d51..35e76fba855 100644
--- a/chromium/content/renderer/service_worker/service_worker_network_provider.h
+++ b/chromium/content/renderer/service_worker/service_worker_network_provider.h
@@ -18,13 +18,18 @@
#include "content/common/service_worker/controller_service_worker.mojom.h"
#include "content/common/service_worker/service_worker.mojom.h"
#include "content/common/service_worker/service_worker_provider.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_provider_type.mojom.h"
+#include "content/renderer/service_worker/service_worker_provider_context.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_provider_type.mojom.h"
namespace blink {
class WebLocalFrame;
class WebServiceWorkerNetworkProvider;
} // namespace blink
+namespace network {
+class SharedURLLoaderFactory;
+} // namespace network
+
namespace content {
namespace mojom {
@@ -33,8 +38,6 @@ class URLLoaderFactory;
struct RequestNavigationParams;
class ServiceWorkerProviderContext;
-class SharedURLLoaderFactory;
-class ThreadSafeSender;
// ServiceWorkerNetworkProvider enables the browser process to recognize
// resource requests from Blink that should be handled by service worker
@@ -71,19 +74,20 @@ class CONTENT_EXPORT ServiceWorkerNetworkProvider {
blink::WebLocalFrame* frame,
bool content_initiated,
mojom::ControllerServiceWorkerInfoPtr controller_info,
- scoped_refptr<SharedURLLoaderFactory> default_loader_factory);
+ scoped_refptr<network::SharedURLLoaderFactory> default_loader_factory);
// Creates a ServiceWorkerNetworkProvider for a shared worker (as a
// non-document service worker client).
- // TODO(kinuko): This should also take SharedURLLoaderFactory associated
- // with the SharedWorker.
- static std::unique_ptr<ServiceWorkerNetworkProvider> CreateForSharedWorker();
+ static std::unique_ptr<ServiceWorkerNetworkProvider> CreateForSharedWorker(
+ mojom::ServiceWorkerProviderInfoForSharedWorkerPtr info,
+ network::mojom::URLLoaderFactoryAssociatedPtrInfo
+ script_loader_factory_info,
+ scoped_refptr<network::SharedURLLoaderFactory> default_loader_factory);
// Creates a ServiceWorkerNetworkProvider for a "controller" (i.e.
// a service worker execution context).
static std::unique_ptr<ServiceWorkerNetworkProvider> CreateForController(
- mojom::ServiceWorkerProviderInfoForStartWorkerPtr info,
- scoped_refptr<ThreadSafeSender> sender);
+ mojom::ServiceWorkerProviderInfoForStartWorkerPtr info);
// Valid only for WebServiceWorkerNetworkProvider created by
// CreateForNavigation.
@@ -102,14 +106,13 @@ class CONTENT_EXPORT ServiceWorkerNetworkProvider {
bool IsControlledByServiceWorker() const;
private:
+ // Creates an invalid instance (provider_id() returns
+ // kInvalidServiceWorkerProviderId).
ServiceWorkerNetworkProvider();
- // This is for service worker clients (used in CreateForNavigation and
- // CreateForSharedWorker). |provider_id| is provided by the browser process
- // for navigations (with PlzNavigate, which is default).
- // |type| must be either one of SERVICE_WORKER_PROVIDER_FOR_{WINDOW,
- // SHARED_WORKER,WORKER} (while currently we don't have code for WORKER).
- // |is_parent_frame_secure| is only relevant when the |type| is WINDOW.
+ // This is for service worker clients (i.e., |type| must be kForWindow or
+ // kForSharedWorker). |is_parent_frame_secure| is only relevant when the
+ // |type| is kForWindow.
//
// For S13nServiceWorker:
// See the comment at CreateForNavigation() for |controller_info| and
@@ -120,15 +123,23 @@ class CONTENT_EXPORT ServiceWorkerNetworkProvider {
int provider_id,
bool is_parent_frame_secure,
mojom::ControllerServiceWorkerInfoPtr controller_info,
- scoped_refptr<SharedURLLoaderFactory> default_loader_factory);
+ scoped_refptr<network::SharedURLLoaderFactory> default_loader_factory);
+
+ ServiceWorkerNetworkProvider(
+ mojom::ServiceWorkerProviderInfoForSharedWorkerPtr info,
+ network::mojom::URLLoaderFactoryAssociatedPtrInfo
+ script_loader_factory_info,
+ scoped_refptr<network::SharedURLLoaderFactory> default_loader_factory);
// This is for controllers, used in CreateForController.
explicit ServiceWorkerNetworkProvider(
- mojom::ServiceWorkerProviderInfoForStartWorkerPtr info,
- scoped_refptr<ThreadSafeSender> sender);
+ mojom::ServiceWorkerProviderInfoForStartWorkerPtr info);
scoped_refptr<ServiceWorkerProviderContext> context_;
mojom::ServiceWorkerDispatcherHostAssociatedPtr dispatcher_host_;
+
+ // The URL loader factory for loading worker scripts, used for service workers
+ // and shared workers.
network::mojom::URLLoaderFactoryAssociatedPtr script_loader_factory_;
DISALLOW_COPY_AND_ASSIGN(ServiceWorkerNetworkProvider);
diff --git a/chromium/content/renderer/service_worker/service_worker_provider_context.cc b/chromium/content/renderer/service_worker/service_worker_provider_context.cc
index a53386d62c1..04c6639807d 100644
--- a/chromium/content/renderer/service_worker/service_worker_provider_context.cc
+++ b/chromium/content/renderer/service_worker/service_worker_provider_context.cc
@@ -17,7 +17,6 @@
#include "content/common/service_worker/service_worker_utils.h"
#include "content/public/common/browser_side_navigation_policy.h"
#include "content/public/common/service_names.mojom.h"
-#include "content/public/common/shared_url_loader_factory.h"
#include "content/renderer/service_worker/controller_service_worker_connector.h"
#include "content/renderer/service_worker/service_worker_dispatcher.h"
#include "content/renderer/service_worker/service_worker_subresource_loader.h"
@@ -26,18 +25,19 @@
#include "content/renderer/worker_thread_registry.h"
#include "mojo/public/cpp/bindings/strong_associated_binding.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
#include "services/service_manager/public/cpp/connector.h"
#include "services/service_manager/public/cpp/interface_provider.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
// Holds state for service worker clients.
struct ServiceWorkerProviderContext::ProviderStateForClient {
explicit ProviderStateForClient(
- scoped_refptr<SharedURLLoaderFactory> default_loader_factory)
+ scoped_refptr<network::SharedURLLoaderFactory> default_loader_factory)
: default_loader_factory(std::move(default_loader_factory)) {}
~ProviderStateForClient() = default;
@@ -53,7 +53,7 @@ struct ServiceWorkerProviderContext::ProviderStateForClient {
// S13nServiceWorker:
// Used when we create |subresource_loader_factory|.
- scoped_refptr<SharedURLLoaderFactory> default_loader_factory;
+ scoped_refptr<network::SharedURLLoaderFactory> default_loader_factory;
// Tracks feature usage for UseCounter.
std::set<blink::mojom::WebFeature> used_features;
@@ -100,7 +100,7 @@ ServiceWorkerProviderContext::ServiceWorkerProviderContext(
mojom::ServiceWorkerContainerAssociatedRequest request,
mojom::ServiceWorkerContainerHostAssociatedPtrInfo host_ptr_info,
mojom::ControllerServiceWorkerInfoPtr controller_info,
- scoped_refptr<SharedURLLoaderFactory> default_loader_factory)
+ scoped_refptr<network::SharedURLLoaderFactory> default_loader_factory)
: provider_type_(provider_type),
provider_id_(provider_id),
main_thread_task_runner_(base::ThreadTaskRunnerHandle::Get()),
@@ -199,9 +199,8 @@ ServiceWorkerProviderContext::GetSubresourceLoaderFactory() {
}
DCHECK(ServiceWorkerUtils::IsServicificationEnabled());
if (!state->subresource_loader_factory) {
- mojo::MakeStrongBinding(
- std::make_unique<ServiceWorkerSubresourceLoaderFactory>(
- state->controller_connector, state->default_loader_factory),
+ ServiceWorkerSubresourceLoaderFactory::Create(
+ state->controller_connector, state->default_loader_factory,
mojo::MakeRequest(&state->subresource_loader_factory));
}
return state->subresource_loader_factory.get();
@@ -282,6 +281,12 @@ void ServiceWorkerProviderContext::OnNetworkProviderDestroyed() {
state_for_client_->controller_connector->OnContainerHostConnectionClosed();
}
+void ServiceWorkerProviderContext::PingContainerHost(
+ base::OnceClosure callback) {
+ DCHECK(main_thread_task_runner_->RunsTasksInCurrentSequence());
+ container_host_->Ping(std::move(callback));
+}
+
void ServiceWorkerProviderContext::UnregisterWorkerFetchContext(
mojom::ServiceWorkerWorkerClient* client) {
DCHECK(main_thread_task_runner_->RunsTasksInCurrentSequence());
@@ -421,9 +426,7 @@ bool ServiceWorkerProviderContext::CanCreateSubresourceLoaderFactory() const {
// Expected that it is called only for clients.
DCHECK(state_for_client_);
// |state_for_client_->default_loader_factory| could be null
- // for SharedWorker case (which is not supported by S13nServiceWorker
- // yet, https://crbug.com/796819) and in unit tests, return early in such
- // cases too.
+ // in unit tests.
return (ServiceWorkerUtils::IsServicificationEnabled() &&
state_for_client_->default_loader_factory);
}
diff --git a/chromium/content/renderer/service_worker/service_worker_provider_context.h b/chromium/content/renderer/service_worker/service_worker_provider_context.h
index c18601ff938..aa6858d76a9 100644
--- a/chromium/content/renderer/service_worker/service_worker_provider_context.h
+++ b/chromium/content/renderer/service_worker/service_worker_provider_context.h
@@ -15,13 +15,13 @@
#include "content/common/service_worker/controller_service_worker.mojom.h"
#include "content/common/service_worker/service_worker_container.mojom.h"
#include "content/common/service_worker/service_worker_provider.mojom.h"
-#include "content/public/common/shared_url_loader_factory.h"
#include "content/renderer/service_worker/web_service_worker_provider_impl.h"
#include "mojo/public/cpp/bindings/associated_binding.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_provider_type.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerProviderClient.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_provider_type.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_provider_client.h"
namespace base {
class SingleThreadTaskRunner;
@@ -80,7 +80,7 @@ class CONTENT_EXPORT ServiceWorkerProviderContext
mojom::ServiceWorkerContainerAssociatedRequest request,
mojom::ServiceWorkerContainerHostAssociatedPtrInfo host_ptr_info,
mojom::ControllerServiceWorkerInfoPtr controller_info,
- scoped_refptr<SharedURLLoaderFactory> default_loader_factory);
+ scoped_refptr<network::SharedURLLoaderFactory> default_loader_factory);
// Constructor for service worker execution contexts.
ServiceWorkerProviderContext(
@@ -179,6 +179,10 @@ class CONTENT_EXPORT ServiceWorkerProviderContext
// see comments of |container_host_|.
mojom::ServiceWorkerContainerHost* container_host() const;
+ // Pings the container host and calls |callback| once a pong arrived. Useful
+ // for waiting for all messages the host sent thus far to arrive.
+ void PingContainerHost(base::OnceClosure callback);
+
private:
friend class base::DeleteHelper<ServiceWorkerProviderContext>;
friend class base::RefCountedThreadSafe<ServiceWorkerProviderContext,
diff --git a/chromium/content/renderer/service_worker/service_worker_provider_context_unittest.cc b/chromium/content/renderer/service_worker/service_worker_provider_context_unittest.cc
index 63b12ffbd22..8f4a26f9865 100644
--- a/chromium/content/renderer/service_worker/service_worker_provider_context_unittest.cc
+++ b/chromium/content/renderer/service_worker/service_worker_provider_context_unittest.cc
@@ -17,27 +17,25 @@
#include "content/common/wrapper_shared_url_loader_factory.h"
#include "content/public/common/content_features.h"
#include "content/public/common/resource_type.h"
-#include "content/public/common/shared_url_loader_factory.h"
#include "content/renderer/service_worker/controller_service_worker_connector.h"
#include "content/renderer/service_worker/service_worker_dispatcher.h"
#include "content/renderer/service_worker/service_worker_provider_context.h"
#include "content/renderer/service_worker/web_service_worker_impl.h"
#include "content/renderer/service_worker/web_service_worker_registration_impl.h"
-#include "ipc/ipc_sync_message_filter.h"
-#include "ipc/ipc_test_sink.h"
#include "mojo/public/cpp/bindings/associated_binding_set.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "services/network/public/cpp/features.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
#include "services/network/test/test_url_loader_client.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_error_type.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_provider_type.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerProviderClient.h"
-#include "third_party/WebKit/public/platform/scheduler/test/renderer_scheduler_test_support.h"
-#include "third_party/WebKit/public/platform/web_feature.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_error_type.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_provider_type.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_provider_client.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/web_feature.mojom.h"
namespace content {
namespace service_worker_provider_context_unittest {
@@ -61,8 +59,8 @@ class MockServiceWorkerObjectHost
private:
// Implements blink::mojom::ServiceWorkerObjectHost.
- void PostMessageToServiceWorker(::blink::TransferableMessage message,
- const url::Origin& source_origin) override {
+ void PostMessageToServiceWorker(
+ ::blink::TransferableMessage message) override {
NOTREACHED();
}
void TerminateForTesting(TerminateForTestingCallback callback) override {
@@ -186,21 +184,6 @@ class MockWebServiceWorkerProviderClientImpl
std::set<blink::mojom::WebFeature> used_features_;
};
-class ServiceWorkerTestSender : public ThreadSafeSender {
- public:
- explicit ServiceWorkerTestSender(IPC::TestSink* ipc_sink)
- : ThreadSafeSender(nullptr, nullptr), ipc_sink_(ipc_sink) {}
-
- bool Send(IPC::Message* message) override { return ipc_sink_->Send(message); }
-
- private:
- ~ServiceWorkerTestSender() override {}
-
- IPC::TestSink* ipc_sink_;
-
- DISALLOW_COPY_AND_ASSIGN(ServiceWorkerTestSender);
-};
-
// S13nServiceWorker: a fake URLLoaderFactory implementation that basically
// does nothing but records the requests.
class FakeURLLoaderFactory final : public network::mojom::URLLoaderFactory {
@@ -281,8 +264,7 @@ class ServiceWorkerProviderContextTest : public testing::Test {
ServiceWorkerProviderContextTest() = default;
void SetUp() override {
- sender_ = new ServiceWorkerTestSender(&ipc_sink_);
- dispatcher_ = std::make_unique<ServiceWorkerDispatcher>(sender_.get());
+ dispatcher_ = std::make_unique<ServiceWorkerDispatcher>();
}
void EnableS13nServiceWorker() {
@@ -315,19 +297,14 @@ class ServiceWorkerProviderContextTest : public testing::Test {
registration_id);
}
- ThreadSafeSender* thread_safe_sender() { return sender_.get(); }
- IPC::TestSink* ipc_sink() { return &ipc_sink_; }
-
protected:
base::MessageLoop message_loop_;
- IPC::TestSink ipc_sink_;
std::unique_ptr<ServiceWorkerDispatcher> dispatcher_;
- scoped_refptr<ServiceWorkerTestSender> sender_;
// S13nServiceWorker:
base::test::ScopedFeatureList scoped_feature_list_;
FakeURLLoaderFactory fake_loader_factory_;
- scoped_refptr<SharedURLLoaderFactory> loader_factory_;
+ scoped_refptr<network::SharedURLLoaderFactory> loader_factory_;
DISALLOW_COPY_AND_ASSIGN(ServiceWorkerProviderContextTest);
};
@@ -366,7 +343,6 @@ TEST_F(ServiceWorkerProviderContextTest,
// The passed references should be adopted and owned by the provider context.
provider_context->SetRegistrationForServiceWorkerGlobalScope(
std::move(registration_info));
- EXPECT_EQ(0UL, ipc_sink()->message_count());
// Destruction of the provider context should release references to the
// associated registration and its versions.
@@ -403,13 +379,11 @@ TEST_F(ServiceWorkerProviderContextTest, SetController) {
std::move(container_request), nullptr /* host_ptr_info */,
nullptr /* controller_info */, nullptr /* loader_factory*/);
- ipc_sink()->ClearMessages();
auto info = mojom::ControllerServiceWorkerInfo::New();
info->object_info = std::move(object_info);
container_ptr->SetController(std::move(info),
std::vector<blink::mojom::WebFeature>(), true);
base::RunLoop().RunUntilIdle();
- EXPECT_EQ(0UL, ipc_sink()->message_count());
// Destruction of the provider context should release references to the
// the controller.
@@ -417,7 +391,6 @@ TEST_F(ServiceWorkerProviderContextTest, SetController) {
base::RunLoop().RunUntilIdle();
// ServiceWorkerObjectHost Mojo connection got broken.
EXPECT_EQ(0, mock_service_worker_object_host->GetBindingCount());
- ipc_sink()->ClearMessages();
}
{
@@ -445,13 +418,12 @@ TEST_F(ServiceWorkerProviderContextTest, SetController) {
kProviderId, blink::mojom::ServiceWorkerProviderType::kForWindow,
std::move(container_request), std::move(host_ptr_info),
nullptr /* controller_info */, nullptr /* loader_factory*/);
- auto provider_impl = std::make_unique<WebServiceWorkerProviderImpl>(
- thread_safe_sender(), provider_context.get());
+ auto provider_impl =
+ std::make_unique<WebServiceWorkerProviderImpl>(provider_context.get());
auto client = std::make_unique<MockWebServiceWorkerProviderClientImpl>();
provider_impl->SetClient(client.get());
ASSERT_FALSE(client->was_set_controller_called());
- ipc_sink()->ClearMessages();
auto info = mojom::ControllerServiceWorkerInfo::New();
info->object_info = std::move(object_info);
container_ptr->SetController(std::move(info),
@@ -480,8 +452,8 @@ TEST_F(ServiceWorkerProviderContextTest, SetController_Null) {
kProviderId, blink::mojom::ServiceWorkerProviderType::kForWindow,
std::move(container_request), std::move(host_ptr_info),
nullptr /* controller_info */, nullptr /* loader_factory*/);
- auto provider_impl = std::make_unique<WebServiceWorkerProviderImpl>(
- thread_safe_sender(), provider_context.get());
+ auto provider_impl =
+ std::make_unique<WebServiceWorkerProviderImpl>(provider_context.get());
auto client = std::make_unique<MockWebServiceWorkerProviderClientImpl>();
provider_impl->SetClient(client.get());
@@ -520,9 +492,7 @@ TEST_F(ServiceWorkerProviderContextTest, SetControllerServiceWorker) {
kProviderId, blink::mojom::ServiceWorkerProviderType::kForWindow,
std::move(container_request), nullptr /* host_ptr_info */,
std::move(controller_info1), loader_factory_);
- ipc_sink()->ClearMessages();
base::RunLoop().RunUntilIdle();
- EXPECT_EQ(0UL, ipc_sink()->message_count());
// Subresource loader factory must be available.
auto* subresource_loader_factory1 =
@@ -554,9 +524,7 @@ TEST_F(ServiceWorkerProviderContextTest, SetControllerServiceWorker) {
// The controller is reset. References to the old controller must be
// released.
- ipc_sink()->ClearMessages();
base::RunLoop().RunUntilIdle();
- EXPECT_EQ(0UL, ipc_sink()->message_count());
EXPECT_EQ(0, object_host1->GetBindingCount());
// Subresource loader factory must be available, and should be the same
@@ -580,9 +548,7 @@ TEST_F(ServiceWorkerProviderContextTest, SetControllerServiceWorker) {
// The controller is reset. References to the old controller must be
// released.
- ipc_sink()->ClearMessages();
base::RunLoop().RunUntilIdle();
- EXPECT_EQ(0UL, ipc_sink()->message_count());
EXPECT_EQ(0, object_host2->GetBindingCount());
// Subresource loader factory must not be available.
@@ -616,9 +582,7 @@ TEST_F(ServiceWorkerProviderContextTest, SetControllerServiceWorker) {
controller_info4->endpoint = controller_ptr4.PassInterface();
container_ptr->SetController(std::move(controller_info4),
std::vector<blink::mojom::WebFeature>(), true);
- ipc_sink()->ClearMessages();
base::RunLoop().RunUntilIdle();
- EXPECT_EQ(0UL, ipc_sink()->message_count());
// Subresource loader factory must be available.
auto* subresource_loader_factory4 =
@@ -660,13 +624,12 @@ TEST_F(ServiceWorkerProviderContextTest, PostMessageToClient) {
kProviderId, blink::mojom::ServiceWorkerProviderType::kForWindow,
std::move(container_request), std::move(host_ptr_info),
nullptr /* controller_info */, nullptr /* loader_factory*/);
- auto provider_impl = std::make_unique<WebServiceWorkerProviderImpl>(
- thread_safe_sender(), provider_context.get());
+ auto provider_impl =
+ std::make_unique<WebServiceWorkerProviderImpl>(provider_context.get());
auto client = std::make_unique<MockWebServiceWorkerProviderClientImpl>();
provider_impl->SetClient(client.get());
ASSERT_FALSE(client->was_dispatch_message_event_called());
- ipc_sink()->ClearMessages();
container_ptr->PostMessageToClient(std::move(object_info),
blink::TransferableMessage());
base::RunLoop().RunUntilIdle();
@@ -691,8 +654,8 @@ TEST_F(ServiceWorkerProviderContextTest, CountFeature) {
kProviderId, blink::mojom::ServiceWorkerProviderType::kForWindow,
std::move(container_request), std::move(host_ptr_info),
nullptr /* controller_info */, nullptr /* loader_factory*/);
- auto provider_impl = std::make_unique<WebServiceWorkerProviderImpl>(
- thread_safe_sender(), provider_context.get());
+ auto provider_impl =
+ std::make_unique<WebServiceWorkerProviderImpl>(provider_context.get());
auto client = std::make_unique<MockWebServiceWorkerProviderClientImpl>();
container_ptr->CountFeature(blink::mojom::WebFeature::kWorkerStart);
@@ -746,7 +709,6 @@ TEST_F(ServiceWorkerProviderContextTest,
provider_context->SetRegistrationForServiceWorkerGlobalScope(
std::move(registration_info));
- EXPECT_EQ(0UL, ipc_sink()->message_count());
// Should return a newly created registration object which adopts all
// references to the remote instances of ServiceWorkerRegistrationObjectHost
@@ -757,12 +719,9 @@ TEST_F(ServiceWorkerProviderContextTest,
EXPECT_TRUE(registration);
EXPECT_EQ(registration_id, registration->RegistrationId());
EXPECT_EQ(1, mock_registration_object_host->GetBindingCount());
- ASSERT_EQ(0UL, ipc_sink()->message_count());
- ipc_sink()->ClearMessages();
// The registration dtor decrements the refcounts.
registration = nullptr;
- ASSERT_EQ(0UL, ipc_sink()->message_count());
base::RunLoop().RunUntilIdle();
// ServiceWorkerRegistrationObjectHost Mojo connection got broken.
EXPECT_EQ(0, mock_registration_object_host->GetBindingCount());
@@ -817,11 +776,8 @@ TEST_F(ServiceWorkerProviderContextTest, GetOrAdoptRegistration) {
EXPECT_TRUE(ContainsRegistration(provider_context.get(), registration_id));
EXPECT_EQ(registration_id, registration1->RegistrationId());
EXPECT_EQ(1, mock_registration_object_host->GetBindingCount());
- EXPECT_EQ(0UL, ipc_sink()->message_count());
}
- ipc_sink()->ClearMessages();
-
{
blink::mojom::ServiceWorkerRegistrationObjectInfoPtr registration_info =
mock_registration_object_host->CreateObjectInfo(
@@ -841,7 +797,6 @@ TEST_F(ServiceWorkerProviderContextTest, GetOrAdoptRegistration) {
EXPECT_TRUE(registration2);
EXPECT_EQ(registration1, registration2);
base::RunLoop().RunUntilIdle();
- ASSERT_EQ(0UL, ipc_sink()->message_count());
// The 2nd ServiceWorkerRegistrationObjectHost Mojo connection has been
// dropped.
EXPECT_EQ(1, mock_registration_object_host->GetBindingCount());
@@ -852,14 +807,11 @@ TEST_F(ServiceWorkerProviderContextTest, GetOrAdoptRegistration) {
EXPECT_EQ(1, installing_host->GetBindingCount());
}
- ipc_sink()->ClearMessages();
-
// The registration dtor decrements the refcounts.
registration1 = nullptr;
registration2 = nullptr;
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(ContainsRegistration(provider_context.get(), registration_id));
- ASSERT_EQ(0UL, ipc_sink()->message_count());
// The 1st ServiceWorkerRegistrationObjectHost Mojo connection got broken.
EXPECT_EQ(0, mock_registration_object_host->GetBindingCount());
// The corresponding ServiceWorkerObjectHost Mojo connections got broken.
diff --git a/chromium/content/renderer/service_worker/service_worker_subresource_loader.cc b/chromium/content/renderer/service_worker/service_worker_subresource_loader.cc
index d6e1525fb88..ee599353680 100644
--- a/chromium/content/renderer/service_worker/service_worker_subresource_loader.cc
+++ b/chromium/content/renderer/service_worker/service_worker_subresource_loader.cc
@@ -7,18 +7,16 @@
#include "base/atomic_sequence_num.h"
#include "base/callback.h"
#include "base/optional.h"
-#include "base/threading/thread_task_runner_handle.h"
#include "content/common/service_worker/service_worker_loader_helpers.h"
#include "content/common/service_worker/service_worker_types.h"
#include "content/common/service_worker/service_worker_utils.h"
#include "content/public/common/content_features.h"
-#include "content/public/common/shared_url_loader_factory.h"
#include "content/renderer/service_worker/controller_service_worker_connector.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
-#include "net/url_request/redirect_info.h"
#include "net/url_request/redirect_util.h"
#include "net/url_request/url_request.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "ui/base/page_transition_types.h"
namespace content {
@@ -36,53 +34,27 @@ network::ResourceResponseHead RewriteServiceWorkerTime(
}
// A wrapper URLLoaderClient that invokes the given RewriteHeaderCallback
-// whenever a response or redirect is received. It self-destructs when the Mojo
-// connection is closed.
+// whenever a response or redirect is received.
class HeaderRewritingURLLoaderClient : public network::mojom::URLLoaderClient {
public:
using RewriteHeaderCallback = base::Callback<network::ResourceResponseHead(
const network::ResourceResponseHead&)>;
- static network::mojom::URLLoaderClientPtr CreateAndBind(
- network::mojom::URLLoaderClientPtr url_loader_client,
- RewriteHeaderCallback rewrite_header_callback) {
- return (new HeaderRewritingURLLoaderClient(std::move(url_loader_client),
- rewrite_header_callback))
- ->CreateInterfacePtrAndBind();
- }
-
- ~HeaderRewritingURLLoaderClient() override {}
-
- private:
HeaderRewritingURLLoaderClient(
network::mojom::URLLoaderClientPtr url_loader_client,
RewriteHeaderCallback rewrite_header_callback)
: url_loader_client_(std::move(url_loader_client)),
- binding_(this),
rewrite_header_callback_(rewrite_header_callback) {}
+ ~HeaderRewritingURLLoaderClient() override {}
- network::mojom::URLLoaderClientPtr CreateInterfacePtrAndBind() {
- DCHECK(!binding_.is_bound());
- network::mojom::URLLoaderClientPtr ptr;
- binding_.Bind(mojo::MakeRequest(&ptr));
- binding_.set_connection_error_handler(
- base::BindOnce(&HeaderRewritingURLLoaderClient::OnClientConnectionError,
- base::Unretained(this)));
- return ptr;
- }
-
- void OnClientConnectionError() {
- base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this);
- }
-
+ private:
// network::mojom::URLLoaderClient implementation:
void OnReceiveResponse(
const network::ResourceResponseHead& response_head,
- const base::Optional<net::SSLInfo>& ssl_info,
network::mojom::DownloadedTempFilePtr downloaded_file) override {
DCHECK(url_loader_client_.is_bound());
url_loader_client_->OnReceiveResponse(
- rewrite_header_callback_.Run(response_head), ssl_info,
+ rewrite_header_callback_.Run(response_head),
std::move(downloaded_file));
}
@@ -129,7 +101,6 @@ class HeaderRewritingURLLoaderClient : public network::mojom::URLLoaderClient {
}
network::mojom::URLLoaderClientPtr url_loader_client_;
- mojo::Binding<network::mojom::URLLoaderClient> binding_;
RewriteHeaderCallback rewrite_header_callback_;
};
} // namespace
@@ -171,7 +142,7 @@ ServiceWorkerSubresourceLoader::ServiceWorkerSubresourceLoader(
network::mojom::URLLoaderClientPtr client,
const net::MutableNetworkTrafficAnnotationTag& traffic_annotation,
scoped_refptr<ControllerServiceWorkerConnector> controller_connector,
- scoped_refptr<SharedURLLoaderFactory> network_loader_factory)
+ scoped_refptr<network::SharedURLLoaderFactory> network_loader_factory)
: redirect_limit_(net::URLRequest::kMaxRedirects),
url_loader_client_(std::move(client)),
url_loader_binding_(this, std::move(request)),
@@ -190,8 +161,9 @@ ServiceWorkerSubresourceLoader::ServiceWorkerSubresourceLoader(
response_head_.load_timing.request_start = base::TimeTicks::Now();
response_head_.load_timing.request_start_time = base::Time::Now();
// base::Unretained() is safe since |url_loader_binding_| is owned by |this|.
- url_loader_binding_.set_connection_error_handler(base::BindOnce(
- &ServiceWorkerSubresourceLoader::DeleteSoon, base::Unretained(this)));
+ url_loader_binding_.set_connection_error_handler(
+ base::BindOnce(&ServiceWorkerSubresourceLoader::OnConnectionError,
+ base::Unretained(this)));
StartRequest(resource_request);
}
@@ -199,8 +171,8 @@ ServiceWorkerSubresourceLoader::~ServiceWorkerSubresourceLoader() {
SettleInflightFetchRequestIfNeeded();
};
-void ServiceWorkerSubresourceLoader::DeleteSoon() {
- base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this);
+void ServiceWorkerSubresourceLoader::OnConnectionError() {
+ delete this;
}
void ServiceWorkerSubresourceLoader::StartRequest(
@@ -231,7 +203,8 @@ void ServiceWorkerSubresourceLoader::DispatchFetchEvent() {
mojom::ServiceWorkerFetchResponseCallbackPtr response_callback_ptr;
response_callback_binding_.Bind(mojo::MakeRequest(&response_callback_ptr));
mojom::ControllerServiceWorker* controller =
- controller_connector_->GetControllerServiceWorker();
+ controller_connector_->GetControllerServiceWorker(
+ mojom::ControllerServiceWorkerPurpose::FETCH_SUB_RESOURCE);
// When |controller| is null, the network request will be aborted soon since
// the network provider has already been discarded. In that case, We don't
// need to return an error as the client must be shutting down.
@@ -245,7 +218,7 @@ void ServiceWorkerSubresourceLoader::DispatchFetchEvent() {
url_loader_binding_.Unbind(), routing_id_, request_id_, options_,
resource_request_, std::move(url_loader_client_),
traffic_annotation_);
- DeleteSoon();
+ delete this;
return;
}
DCHECK_EQ(ControllerServiceWorkerConnector::State::kNoContainerHost,
@@ -391,18 +364,20 @@ void ServiceWorkerSubresourceLoader::OnFallback(
}
// Hand over to the network loader.
+ network::mojom::URLLoaderClientPtr client;
+ auto client_impl = std::make_unique<HeaderRewritingURLLoaderClient>(
+ std::move(url_loader_client_),
+ base::BindRepeating(&RewriteServiceWorkerTime,
+ response_head_.service_worker_start_time,
+ response_head_.service_worker_ready_time));
+ mojo::MakeStrongBinding(std::move(client_impl), mojo::MakeRequest(&client));
+
network_loader_factory_->CreateLoaderAndStart(
url_loader_binding_.Unbind(), routing_id_, request_id_, options_,
- resource_request_,
- HeaderRewritingURLLoaderClient::CreateAndBind(
- std::move(url_loader_client_),
- base::BindRepeating(&RewriteServiceWorkerTime,
- response_head_.service_worker_start_time,
- response_head_.service_worker_ready_time)),
- traffic_annotation_);
+ resource_request_, std::move(client), traffic_annotation_);
// Per spec, redirects after this point are not intercepted by the service
// worker again (https://crbug.com/517364). So this loader is done.
- DeleteSoon();
+ delete this;
}
void ServiceWorkerSubresourceLoader::StartResponse(
@@ -481,7 +456,6 @@ void ServiceWorkerSubresourceLoader::CommitResponseHeaders() {
status_ = Status::kSentHeader;
// TODO(kinuko): Fill the ssl_info.
url_loader_client_->OnReceiveResponse(response_head_,
- base::nullopt /* ssl_info_ */,
nullptr /* downloaded_file */);
}
@@ -541,12 +515,27 @@ void ServiceWorkerSubresourceLoader::OnBlobReadingComplete(int net_error) {
// ServiceWorkerSubresourceLoaderFactory ------------------------------------
+// static
+void ServiceWorkerSubresourceLoaderFactory::Create(
+ scoped_refptr<ControllerServiceWorkerConnector> controller_connector,
+ scoped_refptr<network::SharedURLLoaderFactory> network_loader_factory,
+ network::mojom::URLLoaderFactoryRequest request) {
+ new ServiceWorkerSubresourceLoaderFactory(std::move(controller_connector),
+ std::move(network_loader_factory),
+ std::move(request));
+}
+
ServiceWorkerSubresourceLoaderFactory::ServiceWorkerSubresourceLoaderFactory(
scoped_refptr<ControllerServiceWorkerConnector> controller_connector,
- scoped_refptr<SharedURLLoaderFactory> network_loader_factory)
+ scoped_refptr<network::SharedURLLoaderFactory> network_loader_factory,
+ network::mojom::URLLoaderFactoryRequest request)
: controller_connector_(std::move(controller_connector)),
network_loader_factory_(std::move(network_loader_factory)) {
DCHECK(network_loader_factory_);
+ bindings_.AddBinding(this, std::move(request));
+ bindings_.set_connection_error_handler(base::BindRepeating(
+ &ServiceWorkerSubresourceLoaderFactory::OnConnectionError,
+ base::Unretained(this)));
}
ServiceWorkerSubresourceLoaderFactory::
@@ -572,7 +561,13 @@ void ServiceWorkerSubresourceLoaderFactory::CreateLoaderAndStart(
void ServiceWorkerSubresourceLoaderFactory::Clone(
network::mojom::URLLoaderFactoryRequest request) {
- NOTREACHED();
+ bindings_.AddBinding(this, std::move(request));
+}
+
+void ServiceWorkerSubresourceLoaderFactory::OnConnectionError() {
+ if (!bindings_.empty())
+ return;
+ delete this;
}
} // namespace content
diff --git a/chromium/content/renderer/service_worker/service_worker_subresource_loader.h b/chromium/content/renderer/service_worker/service_worker_subresource_loader.h
index 3f2a9bbf9d8..c232636340b 100644
--- a/chromium/content/renderer/service_worker/service_worker_subresource_loader.h
+++ b/chromium/content/renderer/service_worker/service_worker_subresource_loader.h
@@ -14,16 +14,20 @@
#include "content/common/service_worker/service_worker_status_code.h"
#include "content/renderer/service_worker/controller_service_worker_connector.h"
#include "mojo/public/cpp/bindings/binding.h"
+#include "mojo/public/cpp/bindings/binding_set.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "net/url_request/redirect_info.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
-#include "third_party/WebKit/public/mojom/blob/blob.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_event_status.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_stream_handle.mojom.h"
+#include "third_party/blink/public/mojom/blob/blob.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_event_status.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_stream_handle.mojom.h"
+
+namespace network {
+class SharedURLLoaderFactory;
+} // namespace network
namespace content {
-class SharedURLLoaderFactory;
class ControllerServiceWorkerConnector;
// S13nServiceWorker:
@@ -47,7 +51,7 @@ class CONTENT_EXPORT ServiceWorkerSubresourceLoader
network::mojom::URLLoaderClientPtr client,
const net::MutableNetworkTrafficAnnotationTag& traffic_annotation,
scoped_refptr<ControllerServiceWorkerConnector> controller_connector,
- scoped_refptr<SharedURLLoaderFactory> network_loader_factory);
+ scoped_refptr<network::SharedURLLoaderFactory> network_loader_factory);
~ServiceWorkerSubresourceLoader() override;
@@ -57,7 +61,7 @@ class CONTENT_EXPORT ServiceWorkerSubresourceLoader
private:
class StreamWaiter;
- void DeleteSoon();
+ void OnConnectionError();
void StartRequest(const network::ResourceRequest& resource_request);
void DispatchFetchEvent();
@@ -134,7 +138,7 @@ class CONTENT_EXPORT ServiceWorkerSubresourceLoader
std::unique_ptr<StreamWaiter> stream_waiter_;
// For network fallback.
- scoped_refptr<SharedURLLoaderFactory> network_loader_factory_;
+ scoped_refptr<network::SharedURLLoaderFactory> network_loader_factory_;
enum class Status {
kNotStarted,
@@ -152,6 +156,7 @@ class CONTENT_EXPORT ServiceWorkerSubresourceLoader
// S13nServiceWorker:
// A custom URLLoaderFactory implementation used by Service Worker controllees
// for loading subresources via the controller Service Worker.
+// Self destroys when no more bindings exist.
class CONTENT_EXPORT ServiceWorkerSubresourceLoaderFactory
: public network::mojom::URLLoaderFactory {
public:
@@ -161,9 +166,10 @@ class CONTENT_EXPORT ServiceWorkerSubresourceLoaderFactory
// default URLLoaderFactory for network fallback. This should be the
// URLLoaderFactory that directly goes to network without going through
// any custom URLLoader factories.
- ServiceWorkerSubresourceLoaderFactory(
+ static void Create(
scoped_refptr<ControllerServiceWorkerConnector> controller_connector,
- scoped_refptr<SharedURLLoaderFactory> network_loader_factory);
+ scoped_refptr<network::SharedURLLoaderFactory> network_loader_factory,
+ network::mojom::URLLoaderFactoryRequest request);
~ServiceWorkerSubresourceLoaderFactory() override;
@@ -179,11 +185,20 @@ class CONTENT_EXPORT ServiceWorkerSubresourceLoaderFactory
void Clone(network::mojom::URLLoaderFactoryRequest request) override;
private:
+ ServiceWorkerSubresourceLoaderFactory(
+ scoped_refptr<ControllerServiceWorkerConnector> controller_connector,
+ scoped_refptr<network::SharedURLLoaderFactory> network_loader_factory,
+ network::mojom::URLLoaderFactoryRequest request);
+
+ void OnConnectionError();
+
scoped_refptr<ControllerServiceWorkerConnector> controller_connector_;
// A URLLoaderFactory that directly goes to network, used when a request
// falls back to network.
- scoped_refptr<SharedURLLoaderFactory> network_loader_factory_;
+ scoped_refptr<network::SharedURLLoaderFactory> network_loader_factory_;
+
+ mojo::BindingSet<network::mojom::URLLoaderFactory> bindings_;
DISALLOW_COPY_AND_ASSIGN(ServiceWorkerSubresourceLoaderFactory);
};
diff --git a/chromium/content/renderer/service_worker/service_worker_subresource_loader_unittest.cc b/chromium/content/renderer/service_worker/service_worker_subresource_loader_unittest.cc
index 01555c1f761..0c04458d6ad 100644
--- a/chromium/content/renderer/service_worker/service_worker_subresource_loader_unittest.cc
+++ b/chromium/content/renderer/service_worker/service_worker_subresource_loader_unittest.cc
@@ -12,16 +12,16 @@
#include "content/common/wrapper_shared_url_loader_factory.h"
#include "content/public/common/content_features.h"
#include "content/public/common/resource_type.h"
-#include "content/public/common/shared_url_loader_factory.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "content/renderer/service_worker/controller_service_worker_connector.h"
-#include "mojo/common/data_pipe_utils.h"
#include "mojo/public/cpp/bindings/binding_set.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
+#include "mojo/public/cpp/system/data_pipe_utils.h"
#include "net/http/http_util.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "net/url_request/url_request.h"
#include "services/network/public/cpp/features.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/test/test_data_pipe_getter.h"
#include "services/network/test/test_url_loader_client.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -55,7 +55,7 @@ class FakeNetworkURLLoaderFactory final
network::ResourceResponseHead response;
response.headers = info.headers;
response.headers->GetMimeType(&response.mime_type);
- client->OnReceiveResponse(response, base::nullopt, nullptr);
+ client->OnReceiveResponse(response, nullptr);
std::string body = "this body came from the network";
uint32_t bytes_written = body.size();
@@ -125,7 +125,7 @@ class FakeControllerServiceWorker : public mojom::ControllerServiceWorker {
} else if (element.type() == network::DataElement::TYPE_DATA_PIPE) {
// Read the content into |data_pipe|.
mojo::DataPipe data_pipe;
- network::mojom::DataPipeGetterPtr ptr = element.ReleaseDataPipeGetter();
+ network::mojom::DataPipeGetterPtr ptr(element.ReleaseDataPipeGetter());
base::RunLoop run_loop;
ptr->Read(
std::move(data_pipe.producer_handle),
@@ -134,8 +134,8 @@ class FakeControllerServiceWorker : public mojom::ControllerServiceWorker {
run_loop.QuitClosure()));
run_loop.Run();
// Copy the content to |out_string|.
- mojo::common::BlockingCopyToString(std::move(data_pipe.consumer_handle),
- out_string);
+ mojo::BlockingCopyToString(std::move(data_pipe.consumer_handle),
+ out_string);
} else {
NOTREACHED();
}
@@ -302,8 +302,9 @@ class FakeServiceWorkerContainerHost
GetRegistrationForReadyCallback callback) override {
NOTIMPLEMENTED();
}
- void GetControllerServiceWorker(
- mojom::ControllerServiceWorkerRequest request) override {
+ void EnsureControllerServiceWorker(
+ mojom::ControllerServiceWorkerRequest request,
+ mojom::ControllerServiceWorkerPurpose purpose) override {
get_controller_service_worker_count_++;
if (!fake_controller_)
return;
@@ -313,6 +314,7 @@ class FakeServiceWorkerContainerHost
mojom::ServiceWorkerContainerHostRequest request) override {
NOTIMPLEMENTED();
}
+ void Ping(PingCallback callback) override { NOTIMPLEMENTED(); }
int get_controller_service_worker_count_ = 0;
FakeControllerServiceWorker* fake_controller_;
@@ -356,14 +358,16 @@ class ServiceWorkerSubresourceLoaderTest : public ::testing::Test {
std::move(fake_loader_factory));
}
- std::unique_ptr<ServiceWorkerSubresourceLoaderFactory>
- CreateSubresourceLoaderFactory() {
+ network::mojom::URLLoaderFactoryPtr CreateSubresourceLoaderFactory() {
if (!connector_) {
connector_ = base::MakeRefCounted<ControllerServiceWorkerConnector>(
&fake_container_host_);
}
- return std::make_unique<ServiceWorkerSubresourceLoaderFactory>(
- connector_, loader_factory_);
+ network::mojom::URLLoaderFactoryPtr service_worker_url_loader_factory;
+ ServiceWorkerSubresourceLoaderFactory::Create(
+ connector_, loader_factory_,
+ mojo::MakeRequest(&service_worker_url_loader_factory));
+ return service_worker_url_loader_factory;
}
// Starts |request| using |loader_factory| and sets |out_loader| and
@@ -372,7 +376,7 @@ class ServiceWorkerSubresourceLoaderTest : public ::testing::Test {
// completion. Calling fake_controller_->RunUntilFetchEvent() also advances
// the load to until |fake_controller_| receives the fetch event.
void StartRequest(
- ServiceWorkerSubresourceLoaderFactory* loader_factory,
+ const network::mojom::URLLoaderFactoryPtr& loader_factory,
const network::ResourceRequest& request,
network::mojom::URLLoaderPtr* out_loader,
std::unique_ptr<network::TestURLLoaderClient>* out_loader_client) {
@@ -419,7 +423,7 @@ class ServiceWorkerSubresourceLoaderTest : public ::testing::Test {
void RunFallbackWithRequestBodyTest(
scoped_refptr<network::ResourceRequestBody> request_body,
const std::string& expected_body) {
- std::unique_ptr<ServiceWorkerSubresourceLoaderFactory> factory =
+ network::mojom::URLLoaderFactoryPtr factory =
CreateSubresourceLoaderFactory();
// Create a request with the body.
@@ -435,7 +439,7 @@ class ServiceWorkerSubresourceLoaderTest : public ::testing::Test {
// Perform the request.
network::mojom::URLLoaderPtr loader;
std::unique_ptr<network::TestURLLoaderClient> client;
- StartRequest(factory.get(), request, &loader, &client);
+ StartRequest(factory, request, &loader, &client);
client->RunUntilComplete();
// Verify that the request body was passed to the fetch event.
@@ -451,7 +455,7 @@ class ServiceWorkerSubresourceLoaderTest : public ::testing::Test {
}
TestBrowserThreadBundle thread_bundle_;
- scoped_refptr<SharedURLLoaderFactory> loader_factory_;
+ scoped_refptr<network::SharedURLLoaderFactory> loader_factory_;
scoped_refptr<ControllerServiceWorkerConnector> connector_;
FakeServiceWorkerContainerHost fake_container_host_;
FakeControllerServiceWorker fake_controller_;
@@ -461,13 +465,13 @@ class ServiceWorkerSubresourceLoaderTest : public ::testing::Test {
};
TEST_F(ServiceWorkerSubresourceLoaderTest, Basic) {
- std::unique_ptr<ServiceWorkerSubresourceLoaderFactory> factory =
+ network::mojom::URLLoaderFactoryPtr factory =
CreateSubresourceLoaderFactory();
network::ResourceRequest request =
CreateRequest(GURL("https://www.example.com/foo.png"));
network::mojom::URLLoaderPtr loader;
std::unique_ptr<network::TestURLLoaderClient> client;
- StartRequest(factory.get(), request, &loader, &client);
+ StartRequest(factory, request, &loader, &client);
fake_controller_.RunUntilFetchEvent();
EXPECT_EQ(request.url, fake_controller_.fetch_event_request().url);
@@ -479,7 +483,7 @@ TEST_F(ServiceWorkerSubresourceLoaderTest, Basic) {
TEST_F(ServiceWorkerSubresourceLoaderTest, Abort) {
fake_controller_.AbortEventWithNoResponse();
- std::unique_ptr<ServiceWorkerSubresourceLoaderFactory> factory =
+ network::mojom::URLLoaderFactoryPtr factory =
CreateSubresourceLoaderFactory();
// Perform the request.
@@ -487,21 +491,21 @@ TEST_F(ServiceWorkerSubresourceLoaderTest, Abort) {
CreateRequest(GURL("https://www.example.com/foo.png"));
network::mojom::URLLoaderPtr loader;
std::unique_ptr<network::TestURLLoaderClient> client;
- StartRequest(factory.get(), request, &loader, &client);
+ StartRequest(factory, request, &loader, &client);
client->RunUntilComplete();
EXPECT_EQ(net::ERR_FAILED, client->completion_status().error_code);
}
TEST_F(ServiceWorkerSubresourceLoaderTest, DropController) {
- std::unique_ptr<ServiceWorkerSubresourceLoaderFactory> factory =
+ network::mojom::URLLoaderFactoryPtr factory =
CreateSubresourceLoaderFactory();
{
network::ResourceRequest request =
CreateRequest(GURL("https://www.example.com/foo.png"));
network::mojom::URLLoaderPtr loader;
std::unique_ptr<network::TestURLLoaderClient> client;
- StartRequest(factory.get(), request, &loader, &client);
+ StartRequest(factory, request, &loader, &client);
fake_controller_.RunUntilFetchEvent();
EXPECT_EQ(request.url, fake_controller_.fetch_event_request().url);
@@ -518,7 +522,7 @@ TEST_F(ServiceWorkerSubresourceLoaderTest, DropController) {
CreateRequest(GURL("https://www.example.com/foo2.png"));
network::mojom::URLLoaderPtr loader;
std::unique_ptr<network::TestURLLoaderClient> client;
- StartRequest(factory.get(), request, &loader, &client);
+ StartRequest(factory, request, &loader, &client);
fake_controller_.RunUntilFetchEvent();
EXPECT_EQ(request.url, fake_controller_.fetch_event_request().url);
@@ -537,7 +541,7 @@ TEST_F(ServiceWorkerSubresourceLoaderTest, DropController) {
CreateRequest(GURL("https://www.example.com/foo3.png"));
network::mojom::URLLoaderPtr loader;
std::unique_ptr<network::TestURLLoaderClient> client;
- StartRequest(factory.get(), request, &loader, &client);
+ StartRequest(factory, request, &loader, &client);
fake_controller_.RunUntilFetchEvent();
EXPECT_EQ(request.url, fake_controller_.fetch_event_request().url);
@@ -548,14 +552,14 @@ TEST_F(ServiceWorkerSubresourceLoaderTest, DropController) {
}
TEST_F(ServiceWorkerSubresourceLoaderTest, NoController) {
- std::unique_ptr<ServiceWorkerSubresourceLoaderFactory> factory =
+ network::mojom::URLLoaderFactoryPtr factory =
CreateSubresourceLoaderFactory();
{
network::ResourceRequest request =
CreateRequest(GURL("https://www.example.com/foo.png"));
network::mojom::URLLoaderPtr loader;
std::unique_ptr<network::TestURLLoaderClient> client;
- StartRequest(factory.get(), request, &loader, &client);
+ StartRequest(factory, request, &loader, &client);
fake_controller_.RunUntilFetchEvent();
EXPECT_EQ(request.url, fake_controller_.fetch_event_request().url);
@@ -574,7 +578,7 @@ TEST_F(ServiceWorkerSubresourceLoaderTest, NoController) {
CreateRequest(GURL("https://www.example.com/foo2.png"));
network::mojom::URLLoaderPtr loader;
std::unique_ptr<network::TestURLLoaderClient> client;
- StartRequest(factory.get(), request, &loader, &client);
+ StartRequest(factory, request, &loader, &client);
client->RunUntilComplete();
EXPECT_TRUE(client->has_received_completion());
@@ -586,7 +590,7 @@ TEST_F(ServiceWorkerSubresourceLoaderTest, NoController) {
}
TEST_F(ServiceWorkerSubresourceLoaderTest, DropController_RestartFetchEvent) {
- std::unique_ptr<ServiceWorkerSubresourceLoaderFactory> factory =
+ network::mojom::URLLoaderFactoryPtr factory =
CreateSubresourceLoaderFactory();
{
@@ -594,7 +598,7 @@ TEST_F(ServiceWorkerSubresourceLoaderTest, DropController_RestartFetchEvent) {
CreateRequest(GURL("https://www.example.com/foo.png"));
network::mojom::URLLoaderPtr loader;
std::unique_ptr<network::TestURLLoaderClient> client;
- StartRequest(factory.get(), request, &loader, &client);
+ StartRequest(factory, request, &loader, &client);
fake_controller_.RunUntilFetchEvent();
EXPECT_EQ(request.url, fake_controller_.fetch_event_request().url);
@@ -611,7 +615,7 @@ TEST_F(ServiceWorkerSubresourceLoaderTest, DropController_RestartFetchEvent) {
CreateRequest(GURL("https://www.example.com/foo2.png"));
network::mojom::URLLoaderPtr loader;
std::unique_ptr<network::TestURLLoaderClient> client;
- StartRequest(factory.get(), request, &loader, &client);
+ StartRequest(factory, request, &loader, &client);
fake_controller_.RunUntilFetchEvent();
EXPECT_EQ(request.url, fake_controller_.fetch_event_request().url);
@@ -624,7 +628,7 @@ TEST_F(ServiceWorkerSubresourceLoaderTest, DropController_RestartFetchEvent) {
CreateRequest(GURL("https://www.example.com/foo3.png"));
network::mojom::URLLoaderPtr loader;
std::unique_ptr<network::TestURLLoaderClient> client;
- StartRequest(factory.get(), request, &loader, &client);
+ StartRequest(factory, request, &loader, &client);
// Drop the connection to the ControllerServiceWorker.
fake_controller_.CloseAllBindings();
@@ -642,13 +646,13 @@ TEST_F(ServiceWorkerSubresourceLoaderTest, DropController_TooManyRestart) {
// Simulate the container host fails to start a service worker.
fake_container_host_.set_fake_controller(nullptr);
- std::unique_ptr<ServiceWorkerSubresourceLoaderFactory> factory =
+ network::mojom::URLLoaderFactoryPtr factory =
CreateSubresourceLoaderFactory();
network::ResourceRequest request =
CreateRequest(GURL("https://www.example.com/foo.png"));
network::mojom::URLLoaderPtr loader;
std::unique_ptr<network::TestURLLoaderClient> client;
- StartRequest(factory.get(), request, &loader, &client);
+ StartRequest(factory, request, &loader, &client);
// Try to dispatch fetch event to the bad worker.
base::RunLoop().RunUntilIdle();
@@ -668,7 +672,7 @@ TEST_F(ServiceWorkerSubresourceLoaderTest, StreamResponse) {
fake_controller_.RespondWithStream(mojo::MakeRequest(&stream_callback),
std::move(data_pipe.consumer_handle));
- std::unique_ptr<ServiceWorkerSubresourceLoaderFactory> factory =
+ network::mojom::URLLoaderFactoryPtr factory =
CreateSubresourceLoaderFactory();
// Perform the request.
@@ -676,7 +680,7 @@ TEST_F(ServiceWorkerSubresourceLoaderTest, StreamResponse) {
CreateRequest(GURL("https://www.example.com/foo.png"));
network::mojom::URLLoaderPtr loader;
std::unique_ptr<network::TestURLLoaderClient> client;
- StartRequest(factory.get(), request, &loader, &client);
+ StartRequest(factory, request, &loader, &client);
client->RunUntilResponseReceived();
const network::ResourceResponseHead& info = client->response_head();
@@ -697,8 +701,8 @@ TEST_F(ServiceWorkerSubresourceLoaderTest, StreamResponse) {
// Test the body.
std::string response;
EXPECT_TRUE(client->response_body().is_valid());
- EXPECT_TRUE(mojo::common::BlockingCopyToString(
- client->response_body_release(), &response));
+ EXPECT_TRUE(
+ mojo::BlockingCopyToString(client->response_body_release(), &response));
EXPECT_EQ(kResponseBody, response);
}
@@ -710,7 +714,7 @@ TEST_F(ServiceWorkerSubresourceLoaderTest, StreamResponse_Abort) {
fake_controller_.RespondWithStream(mojo::MakeRequest(&stream_callback),
std::move(data_pipe.consumer_handle));
- std::unique_ptr<ServiceWorkerSubresourceLoaderFactory> factory =
+ network::mojom::URLLoaderFactoryPtr factory =
CreateSubresourceLoaderFactory();
// Perform the request.
@@ -718,7 +722,7 @@ TEST_F(ServiceWorkerSubresourceLoaderTest, StreamResponse_Abort) {
CreateRequest(GURL("https://www.example.com/foo.txt"));
network::mojom::URLLoaderPtr loader;
std::unique_ptr<network::TestURLLoaderClient> client;
- StartRequest(factory.get(), request, &loader, &client);
+ StartRequest(factory, request, &loader, &client);
client->RunUntilResponseReceived();
const network::ResourceResponseHead& info = client->response_head();
@@ -739,8 +743,8 @@ TEST_F(ServiceWorkerSubresourceLoaderTest, StreamResponse_Abort) {
// Test the body.
std::string response;
EXPECT_TRUE(client->response_body().is_valid());
- EXPECT_TRUE(mojo::common::BlockingCopyToString(
- client->response_body_release(), &response));
+ EXPECT_TRUE(
+ mojo::BlockingCopyToString(client->response_body_release(), &response));
EXPECT_EQ(kResponseBody, response);
}
@@ -749,7 +753,7 @@ TEST_F(ServiceWorkerSubresourceLoaderTest, StreamResponse_Abort) {
TEST_F(ServiceWorkerSubresourceLoaderTest, FallbackResponse) {
fake_controller_.RespondWithFallback();
- std::unique_ptr<ServiceWorkerSubresourceLoaderFactory> factory =
+ network::mojom::URLLoaderFactoryPtr factory =
CreateSubresourceLoaderFactory();
// Perform the request.
@@ -757,7 +761,7 @@ TEST_F(ServiceWorkerSubresourceLoaderTest, FallbackResponse) {
CreateRequest(GURL("https://www.example.com/foo.png"));
network::mojom::URLLoaderPtr loader;
std::unique_ptr<network::TestURLLoaderClient> client;
- StartRequest(factory.get(), request, &loader, &client);
+ StartRequest(factory, request, &loader, &client);
client->RunUntilComplete();
// OnFallback() should complete the network request using network loader.
@@ -768,7 +772,7 @@ TEST_F(ServiceWorkerSubresourceLoaderTest, FallbackResponse) {
TEST_F(ServiceWorkerSubresourceLoaderTest, ErrorResponse) {
fake_controller_.RespondWithError();
- std::unique_ptr<ServiceWorkerSubresourceLoaderFactory> factory =
+ network::mojom::URLLoaderFactoryPtr factory =
CreateSubresourceLoaderFactory();
// Perform the request.
@@ -776,7 +780,7 @@ TEST_F(ServiceWorkerSubresourceLoaderTest, ErrorResponse) {
CreateRequest(GURL("https://www.example.com/foo.png"));
network::mojom::URLLoaderPtr loader;
std::unique_ptr<network::TestURLLoaderClient> client;
- StartRequest(factory.get(), request, &loader, &client);
+ StartRequest(factory, request, &loader, &client);
client->RunUntilComplete();
EXPECT_EQ(net::ERR_FAILED, client->completion_status().error_code);
@@ -785,7 +789,7 @@ TEST_F(ServiceWorkerSubresourceLoaderTest, ErrorResponse) {
TEST_F(ServiceWorkerSubresourceLoaderTest, RedirectResponse) {
fake_controller_.RespondWithRedirect("https://www.example.com/bar.png");
- std::unique_ptr<ServiceWorkerSubresourceLoaderFactory> factory =
+ network::mojom::URLLoaderFactoryPtr factory =
CreateSubresourceLoaderFactory();
// Perform the request.
@@ -793,7 +797,7 @@ TEST_F(ServiceWorkerSubresourceLoaderTest, RedirectResponse) {
CreateRequest(GURL("https://www.example.com/foo.png"));
network::mojom::URLLoaderPtr loader;
std::unique_ptr<network::TestURLLoaderClient> client;
- StartRequest(factory.get(), request, &loader, &client);
+ StartRequest(factory, request, &loader, &client);
client->RunUntilRedirectReceived();
EXPECT_EQ(net::OK, client->completion_status().error_code);
@@ -850,8 +854,8 @@ TEST_F(ServiceWorkerSubresourceLoaderTest, RedirectResponse) {
// Test the body.
std::string response;
EXPECT_TRUE(client->response_body().is_valid());
- EXPECT_TRUE(mojo::common::BlockingCopyToString(
- client->response_body_release(), &response));
+ EXPECT_TRUE(
+ mojo::BlockingCopyToString(client->response_body_release(), &response));
EXPECT_EQ(kResponseBody, response);
}
@@ -861,7 +865,7 @@ TEST_F(ServiceWorkerSubresourceLoaderTest, TooManyRedirects) {
std::string("https://www.example.com/redirect_") +
base::IntToString(count);
fake_controller_.RespondWithRedirect(redirect_location);
- std::unique_ptr<ServiceWorkerSubresourceLoaderFactory> factory =
+ network::mojom::URLLoaderFactoryPtr factory =
CreateSubresourceLoaderFactory();
// Perform the request.
@@ -869,7 +873,7 @@ TEST_F(ServiceWorkerSubresourceLoaderTest, TooManyRedirects) {
CreateRequest(GURL("https://www.example.com/foo.png"));
network::mojom::URLLoaderPtr loader;
std::unique_ptr<network::TestURLLoaderClient> client;
- StartRequest(factory.get(), request, &loader, &client);
+ StartRequest(factory, request, &loader, &client);
// The Fetch spec says: "If request’s redirect count is twenty, return a
// network error." https://fetch.spec.whatwg.org/#http-redirect-fetch
@@ -906,7 +910,7 @@ TEST_F(ServiceWorkerSubresourceLoaderTest, TooManyRedirects) {
TEST_F(ServiceWorkerSubresourceLoaderTest, CORSFallbackResponse) {
fake_controller_.RespondWithFallback();
- std::unique_ptr<ServiceWorkerSubresourceLoaderFactory> factory =
+ network::mojom::URLLoaderFactoryPtr factory =
CreateSubresourceLoaderFactory();
struct TestCase {
@@ -960,7 +964,7 @@ TEST_F(ServiceWorkerSubresourceLoaderTest, CORSFallbackResponse) {
request.request_initiator = test.request_initiator;
network::mojom::URLLoaderPtr loader;
std::unique_ptr<network::TestURLLoaderClient> client;
- StartRequest(factory.get(), request, &loader, &client);
+ StartRequest(factory, request, &loader, &client);
client->RunUntilResponseReceived();
const network::ResourceResponseHead& info = client->response_head();
diff --git a/chromium/content/renderer/service_worker/service_worker_timeout_timer.cc b/chromium/content/renderer/service_worker/service_worker_timeout_timer.cc
index b96842324aa..83b78f2fb59 100644
--- a/chromium/content/renderer/service_worker/service_worker_timeout_timer.cc
+++ b/chromium/content/renderer/service_worker/service_worker_timeout_timer.cc
@@ -32,13 +32,12 @@ constexpr base::TimeDelta ServiceWorkerTimeoutTimer::kUpdateInterval;
ServiceWorkerTimeoutTimer::ServiceWorkerTimeoutTimer(
base::RepeatingClosure idle_callback)
: ServiceWorkerTimeoutTimer(std::move(idle_callback),
- std::make_unique<base::DefaultTickClock>()) {}
+ base::DefaultTickClock::GetInstance()) {}
ServiceWorkerTimeoutTimer::ServiceWorkerTimeoutTimer(
base::RepeatingClosure idle_callback,
- std::unique_ptr<base::TickClock> tick_clock)
- : idle_callback_(std::move(idle_callback)),
- tick_clock_(std::move(tick_clock)) {
+ const base::TickClock* tick_clock)
+ : idle_callback_(std::move(idle_callback)), tick_clock_(tick_clock) {
// |idle_callback_| will be invoked if no event happens in |kIdleDelay|.
idle_time_ = tick_clock_->NowTicks() + kIdleDelay;
timer_.Start(FROM_HERE, kUpdateInterval,
diff --git a/chromium/content/renderer/service_worker/service_worker_timeout_timer.h b/chromium/content/renderer/service_worker/service_worker_timeout_timer.h
index 7356aaccb6a..484f7e156f5 100644
--- a/chromium/content/renderer/service_worker/service_worker_timeout_timer.h
+++ b/chromium/content/renderer/service_worker/service_worker_timeout_timer.h
@@ -47,7 +47,7 @@ class CONTENT_EXPORT ServiceWorkerTimeoutTimer {
explicit ServiceWorkerTimeoutTimer(base::RepeatingClosure idle_callback);
// For testing.
ServiceWorkerTimeoutTimer(base::RepeatingClosure idle_callback,
- std::unique_ptr<base::TickClock> tick_clock);
+ const base::TickClock* tick_clock);
~ServiceWorkerTimeoutTimer();
// StartEvent() should be called at the beginning of an event. It returns an
@@ -142,7 +142,8 @@ class CONTENT_EXPORT ServiceWorkerTimeoutTimer {
// |timer_| invokes UpdateEventStatus() periodically.
base::RepeatingTimer timer_;
- std::unique_ptr<base::TickClock> tick_clock_;
+ // |tick_clock_| outlives |this|.
+ const base::TickClock* const tick_clock_;
};
} // namespace content
diff --git a/chromium/content/renderer/service_worker/service_worker_timeout_timer_unittest.cc b/chromium/content/renderer/service_worker/service_worker_timeout_timer_unittest.cc
index c1c1946bc9c..540a9912af8 100644
--- a/chromium/content/renderer/service_worker/service_worker_timeout_timer_unittest.cc
+++ b/chromium/content/renderer/service_worker/service_worker_timeout_timer_unittest.cc
@@ -94,7 +94,7 @@ TEST_F(ServiceWorkerTimeoutTimerTest, IdleTimer) {
// Nothing happens since there is an inflight event.
EXPECT_FALSE(is_idle);
- int event_id_2 = timer.StartEvent(do_nothing_callback);
+ int event_id_2 = timer.StartEvent(std::move(do_nothing_callback));
task_runner()->FastForwardBy(kIdleInterval);
// Nothing happens since there are two inflight events.
EXPECT_FALSE(is_idle);
@@ -241,7 +241,7 @@ TEST_F(ServiceWorkerTimeoutTimerTest, SetIdleTimerDelayToZero) {
bool is_idle = false;
ServiceWorkerTimeoutTimer timer(CreateReceiverWithCalledFlag(&is_idle),
task_runner()->GetMockTickClock());
- int event_id = timer.StartEvent(base::BindRepeating([](int) {}));
+ int event_id = timer.StartEvent(base::BindOnce([](int) {}));
timer.SetIdleTimerDelayToZero();
// Nothing happens since there is an inflight event.
EXPECT_FALSE(is_idle);
@@ -255,8 +255,8 @@ TEST_F(ServiceWorkerTimeoutTimerTest, SetIdleTimerDelayToZero) {
bool is_idle = false;
ServiceWorkerTimeoutTimer timer(CreateReceiverWithCalledFlag(&is_idle),
task_runner()->GetMockTickClock());
- int event_id_1 = timer.StartEvent(base::BindRepeating([](int) {}));
- int event_id_2 = timer.StartEvent(base::BindRepeating([](int) {}));
+ int event_id_1 = timer.StartEvent(base::BindOnce([](int) {}));
+ int event_id_2 = timer.StartEvent(base::BindOnce([](int) {}));
timer.SetIdleTimerDelayToZero();
// Nothing happens since there are two inflight events.
EXPECT_FALSE(is_idle);
diff --git a/chromium/content/renderer/service_worker/service_worker_type_converters.h b/chromium/content/renderer/service_worker/service_worker_type_converters.h
index 6b209aa6e37..b5ea9ca7bcb 100644
--- a/chromium/content/renderer/service_worker/service_worker_type_converters.h
+++ b/chromium/content/renderer/service_worker/service_worker_type_converters.h
@@ -7,11 +7,11 @@
#include "content/common/service_worker/service_worker_event_dispatcher.mojom.h"
#include "content/common/service_worker/service_worker_status_code.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_event_status.mojom.h"
-#include "third_party/WebKit/public/platform/modules/payments/WebCanMakePaymentEventData.h"
-#include "third_party/WebKit/public/platform/modules/payments/WebPaymentRequestEventData.h"
-#include "third_party/WebKit/public/platform/modules/payments/payment_app.mojom.h"
-#include "third_party/WebKit/public/web/modules/serviceworker/WebServiceWorkerContextProxy.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_event_status.mojom.h"
+#include "third_party/blink/public/platform/modules/payments/payment_app.mojom.h"
+#include "third_party/blink/public/platform/modules/payments/web_can_make_payment_event_data.h"
+#include "third_party/blink/public/platform/modules/payments/web_payment_request_event_data.h"
+#include "third_party/blink/public/web/modules/serviceworker/web_service_worker_context_proxy.h"
namespace mojo {
diff --git a/chromium/content/renderer/service_worker/service_worker_type_util.cc b/chromium/content/renderer/service_worker/service_worker_type_util.cc
index 9dde56d109c..7741366348f 100644
--- a/chromium/content/renderer/service_worker/service_worker_type_util.cc
+++ b/chromium/content/renderer/service_worker/service_worker_type_util.cc
@@ -7,14 +7,13 @@
#include <memory>
#include <string>
-#include "base/memory/ptr_util.h"
#include "base/strings/utf_string_conversions.h"
#include "content/common/service_worker/service_worker_types.h"
#include "storage/common/blob_storage/blob_handle.h"
-#include "third_party/WebKit/public/platform/WebHTTPHeaderVisitor.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerRequest.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerResponse.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_request.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_response.h"
+#include "third_party/blink/public/platform/web_http_header_visitor.h"
+#include "third_party/blink/public/platform/web_string.h"
namespace content {
diff --git a/chromium/content/renderer/service_worker/thread_safe_script_container.h b/chromium/content/renderer/service_worker/thread_safe_script_container.h
index f7e055b332d..9e658ffe675 100644
--- a/chromium/content/renderer/service_worker/thread_safe_script_container.h
+++ b/chromium/content/renderer/service_worker/thread_safe_script_container.h
@@ -12,7 +12,7 @@
#include "base/synchronization/condition_variable.h"
#include "base/synchronization/lock.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerInstalledScriptsManager.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_installed_scripts_manager.h"
namespace content {
diff --git a/chromium/content/renderer/service_worker/web_service_worker_impl.cc b/chromium/content/renderer/service_worker/web_service_worker_impl.cc
index 2fcf2264538..268a705f45a 100644
--- a/chromium/content/renderer/service_worker/web_service_worker_impl.cc
+++ b/chromium/content/renderer/service_worker/web_service_worker_impl.cc
@@ -7,17 +7,13 @@
#include <utility>
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "content/child/thread_safe_sender.h"
#include "content/common/service_worker/service_worker_messages.h"
#include "content/renderer/service_worker/service_worker_dispatcher.h"
#include "content/renderer/service_worker/web_service_worker_provider_impl.h"
-#include "third_party/WebKit/public/platform/WebRuntimeFeatures.h"
-#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerProxy.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_proxy.h"
+#include "third_party/blink/public/platform/web_runtime_features.h"
+#include "third_party/blink/public/platform/web_string.h"
-using blink::WebSecurityOrigin;
using blink::WebString;
namespace content {
@@ -50,10 +46,9 @@ void OnTerminated(
scoped_refptr<WebServiceWorkerImpl>
WebServiceWorkerImpl::CreateForServiceWorkerGlobalScope(
blink::mojom::ServiceWorkerObjectInfoPtr info,
- ThreadSafeSender* thread_safe_sender,
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner) {
scoped_refptr<WebServiceWorkerImpl> impl =
- new WebServiceWorkerImpl(std::move(info), thread_safe_sender);
+ new WebServiceWorkerImpl(std::move(info));
impl->host_for_global_scope_ =
blink::mojom::ThreadSafeServiceWorkerObjectHostAssociatedPtr::Create(
std::move(impl->info_->host_ptr_info), io_task_runner);
@@ -63,10 +58,9 @@ WebServiceWorkerImpl::CreateForServiceWorkerGlobalScope(
// static
scoped_refptr<WebServiceWorkerImpl>
WebServiceWorkerImpl::CreateForServiceWorkerClient(
- blink::mojom::ServiceWorkerObjectInfoPtr info,
- ThreadSafeSender* thread_safe_sender) {
+ blink::mojom::ServiceWorkerObjectInfoPtr info) {
scoped_refptr<WebServiceWorkerImpl> impl =
- new WebServiceWorkerImpl(std::move(info), thread_safe_sender);
+ new WebServiceWorkerImpl(std::move(info));
impl->host_for_client_.Bind(std::move(impl->info_->host_ptr_info));
return impl;
}
@@ -98,10 +92,8 @@ blink::mojom::ServiceWorkerState WebServiceWorkerImpl::GetState() const {
}
void WebServiceWorkerImpl::PostMessageToServiceWorker(
- blink::TransferableMessage message,
- const WebSecurityOrigin& source_origin) {
- GetObjectHost()->PostMessageToServiceWorker(std::move(message),
- url::Origin(source_origin));
+ blink::TransferableMessage message) {
+ GetObjectHost()->PostMessageToServiceWorker(std::move(message));
}
void WebServiceWorkerImpl::TerminateForTesting(
@@ -119,12 +111,8 @@ WebServiceWorkerImpl::CreateHandle(scoped_refptr<WebServiceWorkerImpl> worker) {
}
WebServiceWorkerImpl::WebServiceWorkerImpl(
- blink::mojom::ServiceWorkerObjectInfoPtr info,
- ThreadSafeSender* thread_safe_sender)
- : info_(std::move(info)),
- state_(info_->state),
- thread_safe_sender_(thread_safe_sender),
- proxy_(nullptr) {
+ blink::mojom::ServiceWorkerObjectInfoPtr info)
+ : info_(std::move(info)), state_(info_->state), proxy_(nullptr) {
DCHECK_NE(blink::mojom::kInvalidServiceWorkerHandleId, info_->handle_id);
ServiceWorkerDispatcher* dispatcher =
ServiceWorkerDispatcher::GetThreadSpecificInstance();
diff --git a/chromium/content/renderer/service_worker/web_service_worker_impl.h b/chromium/content/renderer/service_worker/web_service_worker_impl.h
index 673742d5bf5..cbfbfce0c2b 100644
--- a/chromium/content/renderer/service_worker/web_service_worker_impl.h
+++ b/chromium/content/renderer/service_worker/web_service_worker_impl.h
@@ -13,9 +13,9 @@
#include "base/memory/ref_counted.h"
#include "base/strings/string16.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorker.h"
-#include "third_party/WebKit/public/web/WebFrame.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker.h"
+#include "third_party/blink/public/web/web_frame.h"
namespace base {
class SingleThreadTaskRunner;
@@ -27,8 +27,6 @@ class WebServiceWorkerProxy;
namespace content {
-class ThreadSafeSender;
-
// Each instance corresponds to one ServiceWorker object in JS context, and
// is held by ServiceWorker object in Blink's C++ layer via
// WebServiceWorker::Handle.
@@ -46,11 +44,9 @@ class CONTENT_EXPORT WebServiceWorkerImpl
// interface and needs to be bound on either the main or IO thread.
static scoped_refptr<WebServiceWorkerImpl> CreateForServiceWorkerGlobalScope(
blink::mojom::ServiceWorkerObjectInfoPtr info,
- ThreadSafeSender* thread_safe_sender,
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner);
static scoped_refptr<WebServiceWorkerImpl> CreateForServiceWorkerClient(
- blink::mojom::ServiceWorkerObjectInfoPtr info,
- ThreadSafeSender* thread_safe_sender);
+ blink::mojom::ServiceWorkerObjectInfoPtr info);
void OnStateChanged(blink::mojom::ServiceWorkerState new_state);
@@ -59,9 +55,7 @@ class CONTENT_EXPORT WebServiceWorkerImpl
blink::WebServiceWorkerProxy* Proxy() override;
blink::WebURL Url() const override;
blink::mojom::ServiceWorkerState GetState() const override;
- void PostMessageToServiceWorker(
- blink::TransferableMessage message,
- const blink::WebSecurityOrigin& source_origin) override;
+ void PostMessageToServiceWorker(blink::TransferableMessage message) override;
void TerminateForTesting(
std::unique_ptr<TerminateForTestingCallback> callback) override;
@@ -72,8 +66,7 @@ class CONTENT_EXPORT WebServiceWorkerImpl
private:
friend class base::RefCounted<WebServiceWorkerImpl>;
- WebServiceWorkerImpl(blink::mojom::ServiceWorkerObjectInfoPtr info,
- ThreadSafeSender* thread_safe_sender);
+ explicit WebServiceWorkerImpl(blink::mojom::ServiceWorkerObjectInfoPtr info);
~WebServiceWorkerImpl() override;
blink::mojom::ServiceWorkerObjectHost* GetObjectHost();
@@ -96,7 +89,6 @@ class CONTENT_EXPORT WebServiceWorkerImpl
blink::mojom::ServiceWorkerObjectInfoPtr info_;
blink::mojom::ServiceWorkerState state_;
- scoped_refptr<ThreadSafeSender> thread_safe_sender_;
blink::WebServiceWorkerProxy* proxy_;
DISALLOW_COPY_AND_ASSIGN(WebServiceWorkerImpl);
diff --git a/chromium/content/renderer/service_worker/web_service_worker_installed_scripts_manager_impl.cc b/chromium/content/renderer/service_worker/web_service_worker_installed_scripts_manager_impl.cc
index e14fbbe395e..8533648caaf 100644
--- a/chromium/content/renderer/service_worker/web_service_worker_installed_scripts_manager_impl.cc
+++ b/chromium/content/renderer/service_worker/web_service_worker_installed_scripts_manager_impl.cc
@@ -132,7 +132,7 @@ class BundledReceivers {
base::RepeatingClosure wait_all_closure =
base::BarrierClosure(2, std::move(callback));
meta_data_.Start(wait_all_closure);
- body_.Start(wait_all_closure);
+ body_.Start(std::move(wait_all_closure));
}
Receiver* meta_data() { return &meta_data_; }
diff --git a/chromium/content/renderer/service_worker/web_service_worker_installed_scripts_manager_impl.h b/chromium/content/renderer/service_worker/web_service_worker_installed_scripts_manager_impl.h
index 24d0455293d..0f3fdcc6aef 100644
--- a/chromium/content/renderer/service_worker/web_service_worker_installed_scripts_manager_impl.h
+++ b/chromium/content/renderer/service_worker/web_service_worker_installed_scripts_manager_impl.h
@@ -9,8 +9,8 @@
#include <vector>
#include "content/renderer/service_worker/thread_safe_script_container.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_installed_scripts_manager.mojom.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerInstalledScriptsManager.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_installed_scripts_manager.mojom.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_installed_scripts_manager.h"
namespace content {
diff --git a/chromium/content/renderer/service_worker/web_service_worker_provider_impl.cc b/chromium/content/renderer/service_worker/web_service_worker_provider_impl.cc
index 589643f5411..be48fadaaed 100644
--- a/chromium/content/renderer/service_worker/web_service_worker_provider_impl.cc
+++ b/chromium/content/renderer/service_worker/web_service_worker_provider_impl.cc
@@ -9,17 +9,16 @@
#include "base/strings/utf_string_conversions.h"
#include "base/trace_event/trace_event.h"
-#include "content/child/thread_safe_sender.h"
#include "content/common/service_worker/service_worker_utils.h"
#include "content/renderer/service_worker/service_worker_dispatcher.h"
#include "content/renderer/service_worker/service_worker_provider_context.h"
#include "content/renderer/service_worker/web_service_worker_impl.h"
#include "content/renderer/service_worker/web_service_worker_registration_impl.h"
-#include "third_party/WebKit/public/common/message_port/message_port_channel.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_provider_type.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerProviderClient.h"
+#include "third_party/blink/public/common/message_port/message_port_channel.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_provider_type.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_provider_client.h"
+#include "third_party/blink/public/platform/web_url.h"
using blink::WebURL;
@@ -33,12 +32,8 @@ const char kLostConnectionErrorMessage[] =
} // anonymous namespace
WebServiceWorkerProviderImpl::WebServiceWorkerProviderImpl(
- ThreadSafeSender* thread_safe_sender,
ServiceWorkerProviderContext* context)
- : thread_safe_sender_(thread_safe_sender),
- context_(context),
- provider_client_(nullptr),
- weak_factory_(this) {
+ : context_(context), provider_client_(nullptr), weak_factory_(this) {
DCHECK(context_);
switch (context_->provider_type()) {
case blink::mojom::ServiceWorkerProviderType::kForWindow:
diff --git a/chromium/content/renderer/service_worker/web_service_worker_provider_impl.h b/chromium/content/renderer/service_worker/web_service_worker_provider_impl.h
index d3dd36ab693..dd4ae8b5a63 100644
--- a/chromium/content/renderer/service_worker/web_service_worker_provider_impl.h
+++ b/chromium/content/renderer/service_worker/web_service_worker_provider_impl.h
@@ -12,11 +12,11 @@
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "content/common/service_worker/service_worker_types.h"
-#include "third_party/WebKit/public/common/message_port/transferable_message.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_error_type.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerProvider.h"
-#include "third_party/WebKit/public/platform/web_feature.mojom.h"
+#include "third_party/blink/public/common/message_port/transferable_message.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_error_type.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_provider.h"
+#include "third_party/blink/public/platform/web_feature.mojom.h"
namespace blink {
class WebURL;
@@ -27,15 +27,13 @@ namespace content {
class ServiceWorkerDispatcher;
class ServiceWorkerProviderContext;
-class ThreadSafeSender;
// This class corresponds to one ServiceWorkerContainer interface in
// JS context (i.e. navigator.serviceWorker).
class CONTENT_EXPORT WebServiceWorkerProviderImpl
: public blink::WebServiceWorkerProvider {
public:
- WebServiceWorkerProviderImpl(ThreadSafeSender* thread_safe_sender,
- ServiceWorkerProviderContext* context);
+ explicit WebServiceWorkerProviderImpl(ServiceWorkerProviderContext* context);
~WebServiceWorkerProviderImpl() override;
void SetClient(blink::WebServiceWorkerProviderClient* client) override;
@@ -100,7 +98,6 @@ class CONTENT_EXPORT WebServiceWorkerProviderImpl
callbacks,
blink::mojom::ServiceWorkerRegistrationObjectInfoPtr registration);
- scoped_refptr<ThreadSafeSender> thread_safe_sender_;
scoped_refptr<ServiceWorkerProviderContext> context_;
// |provider_client_| is implemented by blink::SWContainer and this pointer's
diff --git a/chromium/content/renderer/service_worker/web_service_worker_registration_impl.cc b/chromium/content/renderer/service_worker/web_service_worker_registration_impl.cc
index 06b3bc3aa24..553d4967a0e 100644
--- a/chromium/content/renderer/service_worker/web_service_worker_registration_impl.cc
+++ b/chromium/content/renderer/service_worker/web_service_worker_registration_impl.cc
@@ -9,7 +9,6 @@
#include "base/containers/id_map.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/child/child_process.h"
#include "content/common/service_worker/service_worker_types.h"
@@ -17,9 +16,9 @@
#include "content/renderer/service_worker/service_worker_provider_context.h"
#include "content/renderer/service_worker/web_service_worker_impl.h"
#include "content/renderer/service_worker/web_service_worker_provider_impl.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebNavigationPreloadState.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerError.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerRegistrationProxy.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_navigation_preload_state.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_error.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_registration_proxy.h"
namespace content {
diff --git a/chromium/content/renderer/service_worker/web_service_worker_registration_impl.h b/chromium/content/renderer/service_worker/web_service_worker_registration_impl.h
index 0ea30d447c6..3ea61a3a6bf 100644
--- a/chromium/content/renderer/service_worker/web_service_worker_registration_impl.h
+++ b/chromium/content/renderer/service_worker/web_service_worker_registration_impl.h
@@ -16,10 +16,10 @@
#include "base/memory/weak_ptr.h"
#include "content/common/content_export.h"
#include "mojo/public/cpp/bindings/associated_binding.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_error_type.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_registration.mojom.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerRegistration.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_error_type.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_registration.h"
namespace base {
class SingleThreadTaskRunner;
diff --git a/chromium/content/renderer/service_worker/worker_fetch_context_impl.cc b/chromium/content/renderer/service_worker/worker_fetch_context_impl.cc
index d0bec2283fc..ed9a4c4dcd0 100644
--- a/chromium/content/renderer/service_worker/worker_fetch_context_impl.cc
+++ b/chromium/content/renderer/service_worker/worker_fetch_context_impl.cc
@@ -22,15 +22,16 @@
#include "mojo/public/cpp/bindings/binding.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "services/service_manager/public/cpp/connector.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
namespace content {
class WorkerFetchContextImpl::URLLoaderFactoryImpl
: public blink::WebURLLoaderFactory {
public:
- URLLoaderFactoryImpl(base::WeakPtr<ResourceDispatcher> resource_dispatcher,
- scoped_refptr<SharedURLLoaderFactory> loader_factory)
+ URLLoaderFactoryImpl(
+ base::WeakPtr<ResourceDispatcher> resource_dispatcher,
+ scoped_refptr<network::SharedURLLoaderFactory> loader_factory)
: resource_dispatcher_(std::move(resource_dispatcher)),
loader_factory_(std::move(loader_factory)),
weak_ptr_factory_(this) {}
@@ -87,8 +88,9 @@ class WorkerFetchContextImpl::URLLoaderFactoryImpl
}
base::WeakPtr<ResourceDispatcher> resource_dispatcher_;
- scoped_refptr<SharedURLLoaderFactory> loader_factory_;
- scoped_refptr<SharedURLLoaderFactory> service_worker_url_loader_factory_;
+ scoped_refptr<network::SharedURLLoaderFactory> loader_factory_;
+ scoped_refptr<network::SharedURLLoaderFactory>
+ service_worker_url_loader_factory_;
base::WeakPtrFactory<URLLoaderFactoryImpl> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(URLLoaderFactoryImpl);
};
@@ -96,8 +98,10 @@ class WorkerFetchContextImpl::URLLoaderFactoryImpl
WorkerFetchContextImpl::WorkerFetchContextImpl(
mojom::ServiceWorkerWorkerClientRequest service_worker_client_request,
mojom::ServiceWorkerContainerHostPtrInfo service_worker_container_host_info,
- std::unique_ptr<SharedURLLoaderFactoryInfo> url_loader_factory_info,
- std::unique_ptr<SharedURLLoaderFactoryInfo> direct_network_factory_info,
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo>
+ url_loader_factory_info,
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo>
+ direct_network_factory_info,
std::unique_ptr<URLLoaderThrottleProvider> throttle_provider)
: binding_(this),
service_worker_client_request_(std::move(service_worker_client_request)),
@@ -117,14 +121,22 @@ WorkerFetchContextImpl::WorkerFetchContextImpl(
WorkerFetchContextImpl::~WorkerFetchContextImpl() {}
+void WorkerFetchContextImpl::SetTerminateSyncLoadEvent(
+ base::WaitableEvent* terminate_sync_load_event) {
+ DCHECK(!terminate_sync_load_event_);
+ terminate_sync_load_event_ = terminate_sync_load_event;
+}
+
void WorkerFetchContextImpl::InitializeOnWorkerThread() {
DCHECK(!resource_dispatcher_);
DCHECK(!binding_.is_bound());
resource_dispatcher_ = std::make_unique<ResourceDispatcher>();
+ resource_dispatcher_->set_terminate_sync_load_event(
+ terminate_sync_load_event_);
- shared_url_loader_factory_ =
- SharedURLLoaderFactory::Create(std::move(url_loader_factory_info_));
- direct_network_loader_factory_ = SharedURLLoaderFactory::Create(
+ shared_url_loader_factory_ = network::SharedURLLoaderFactory::Create(
+ std::move(url_loader_factory_info_));
+ direct_network_loader_factory_ = network::SharedURLLoaderFactory::Create(
std::move(direct_network_loader_factory_info_));
if (service_worker_client_request_.is_pending())
binding_.Bind(std::move(service_worker_client_request_));
@@ -173,7 +185,7 @@ void WorkerFetchContextImpl::WillSendRequest(blink::WebURLRequest& request) {
extra_data->set_initiated_in_secure_context(is_secure_context_);
if (throttle_provider_) {
extra_data->set_url_loader_throttles(throttle_provider_->CreateThrottles(
- parent_frame_id_, request.Url(), WebURLRequestToResourceType(request)));
+ parent_frame_id_, request, WebURLRequestToResourceType(request)));
}
request.SetExtraData(std::move(extra_data));
request.SetAppCacheHostID(appcache_host_id_);
@@ -285,11 +297,10 @@ void WorkerFetchContextImpl::ResetServiceWorkerURLLoaderFactory() {
return;
}
network::mojom::URLLoaderFactoryPtr service_worker_url_loader_factory;
- mojo::MakeStrongBinding(
- std::make_unique<ServiceWorkerSubresourceLoaderFactory>(
- base::MakeRefCounted<ControllerServiceWorkerConnector>(
- service_worker_container_host_.get()),
- direct_network_loader_factory_),
+ ServiceWorkerSubresourceLoaderFactory::Create(
+ base::MakeRefCounted<ControllerServiceWorkerConnector>(
+ service_worker_container_host_.get()),
+ direct_network_loader_factory_,
mojo::MakeRequest(&service_worker_url_loader_factory));
url_loader_factory_->SetServiceWorkerURLLoaderFactory(
std::move(service_worker_url_loader_factory));
diff --git a/chromium/content/renderer/service_worker/worker_fetch_context_impl.h b/chromium/content/renderer/service_worker/worker_fetch_context_impl.h
index 8137c70b16a..7983e5f6631 100644
--- a/chromium/content/renderer/service_worker/worker_fetch_context_impl.h
+++ b/chromium/content/renderer/service_worker/worker_fetch_context_impl.h
@@ -5,16 +5,17 @@
#ifndef CONTENT_RENDERER_SERVICE_WORKER_WORKER_FETCH_CONTEXT_IMPL_H_
#define CONTENT_RENDERER_SERVICE_WORKER_WORKER_FETCH_CONTEXT_IMPL_H_
+#include "base/synchronization/waitable_event.h"
#include "content/common/service_worker/service_worker_provider.mojom.h"
#include "content/common/service_worker/service_worker_types.h"
-#include "content/public/common/shared_url_loader_factory.h"
#include "ipc/ipc_message.h"
#include "mojo/public/cpp/bindings/binding.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
-#include "third_party/WebKit/public/mojom/blob/blob_registry.mojom.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
-#include "third_party/WebKit/public/platform/WebApplicationCacheHost.h"
-#include "third_party/WebKit/public/platform/WebWorkerFetchContext.h"
+#include "third_party/blink/public/mojom/blob/blob_registry.mojom.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/platform/web_application_cache_host.h"
+#include "third_party/blink/public/platform/web_worker_fetch_context.h"
#include "url/gurl.h"
namespace IPC {
@@ -45,12 +46,15 @@ class WorkerFetchContextImpl : public blink::WebWorkerFetchContext,
mojom::ServiceWorkerWorkerClientRequest service_worker_client_request,
mojom::ServiceWorkerContainerHostPtrInfo
service_worker_container_host_info,
- std::unique_ptr<SharedURLLoaderFactoryInfo> url_loader_factory_info,
- std::unique_ptr<SharedURLLoaderFactoryInfo> direct_network_factory_info,
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo>
+ url_loader_factory_info,
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo>
+ direct_network_factory_info,
std::unique_ptr<URLLoaderThrottleProvider> throttle_provider);
~WorkerFetchContextImpl() override;
// blink::WebWorkerFetchContext implementation:
+ void SetTerminateSyncLoadEvent(base::WaitableEvent*) override;
void InitializeOnWorkerThread() override;
std::unique_ptr<blink::WebURLLoaderFactory> CreateURLLoaderFactory() override;
std::unique_ptr<blink::WebURLLoaderFactory> WrapURLLoaderFactory(
@@ -104,9 +108,9 @@ class WorkerFetchContextImpl : public blink::WebWorkerFetchContext,
// Consumed on the worker thread to create |service_worker_container_host_|.
mojom::ServiceWorkerContainerHostPtrInfo service_worker_container_host_info_;
// Consumed on the worker thread to create |shared_url_loader_factory_|.
- std::unique_ptr<SharedURLLoaderFactoryInfo> url_loader_factory_info_;
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo> url_loader_factory_info_;
// Consumed on the worker thread to create |direct_network_loader_factory_|.
- std::unique_ptr<SharedURLLoaderFactoryInfo>
+ std::unique_ptr<network::SharedURLLoaderFactoryInfo>
direct_network_loader_factory_info_;
// Consumed on the worker thread to create |blob_registry_|.
blink::mojom::BlobRegistryPtrInfo blob_registry_ptr_info_;
@@ -127,8 +131,8 @@ class WorkerFetchContextImpl : public blink::WebWorkerFetchContext,
// specifically to initialize ServiceWorkerSubresourceLoader for network
// load that is controlled by a service worker (when this worker is a
// client of the service worker).
- scoped_refptr<SharedURLLoaderFactory> shared_url_loader_factory_;
- scoped_refptr<SharedURLLoaderFactory> direct_network_loader_factory_;
+ scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory_;
+ scoped_refptr<network::SharedURLLoaderFactory> direct_network_loader_factory_;
// S13nServiceWorker:
// Initialized on the worker thread when InitializeOnWorkerThread() is called.
@@ -149,6 +153,9 @@ class WorkerFetchContextImpl : public blink::WebWorkerFetchContext,
GURL origin_url_;
int appcache_host_id_ = blink::WebApplicationCacheHost::kAppCacheNoHostId;
+ // This is owned by ThreadedMessagingProxyBase on the main thread.
+ base::WaitableEvent* terminate_sync_load_event_ = nullptr;
+
// A weak ptr to blink::WebURLLoaderFactory which was created and passed to
// Blink by CreateURLLoaderFactory().
base::WeakPtr<URLLoaderFactoryImpl> url_loader_factory_;
diff --git a/chromium/content/renderer/shared_worker/embedded_shared_worker_stub.cc b/chromium/content/renderer/shared_worker/embedded_shared_worker_stub.cc
index 64aecd42e75..56478f058ec 100644
--- a/chromium/content/renderer/shared_worker/embedded_shared_worker_stub.cc
+++ b/chromium/content/renderer/shared_worker/embedded_shared_worker_stub.cc
@@ -16,6 +16,7 @@
#include "content/public/common/content_client.h"
#include "content/public/common/content_features.h"
#include "content/public/common/origin_util.h"
+#include "content/public/common/weak_wrapper_shared_url_loader_factory.h"
#include "content/public/renderer/content_renderer_client.h"
#include "content/renderer/appcache/appcache_dispatcher.h"
#include "content/renderer/appcache/web_application_cache_host_impl.h"
@@ -27,14 +28,14 @@
#include "content/renderer/service_worker/service_worker_provider_context.h"
#include "content/renderer/service_worker/worker_fetch_context_impl.h"
#include "ipc/ipc_message_macros.h"
-#include "third_party/WebKit/public/common/message_port/message_port_channel.h"
-#include "third_party/WebKit/public/mojom/service_worker/service_worker_object.mojom.h"
-#include "third_party/WebKit/public/platform/InterfaceProvider.h"
-#include "third_party/WebKit/public/platform/URLConversion.h"
-#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
-#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerNetworkProvider.h"
-#include "third_party/WebKit/public/web/WebSharedWorker.h"
-#include "third_party/WebKit/public/web/WebSharedWorkerClient.h"
+#include "third_party/blink/public/common/message_port/message_port_channel.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
+#include "third_party/blink/public/platform/interface_provider.h"
+#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_network_provider.h"
+#include "third_party/blink/public/platform/url_conversion.h"
+#include "third_party/blink/public/platform/web_security_origin.h"
+#include "third_party/blink/public/web/web_shared_worker.h"
+#include "third_party/blink/public/web/web_shared_worker_client.h"
#include "url/origin.h"
namespace content {
@@ -52,7 +53,7 @@ class SharedWorkerWebApplicationCacheHostImpl
kAppCacheNoHostId) {}
// Main resource loading is different for workers. The main resource is
- // loaded by the worker using WorkerScriptLoader.
+ // loaded by the worker using WorkerClassicScriptLoader.
// These overrides are stubbed out.
void WillStartMainResourceRequest(
const blink::WebURL& url,
@@ -115,8 +116,55 @@ class WebServiceWorkerNetworkProviderForSharedWorker
ServiceWorkerNetworkProvider* provider() { return provider_.get(); }
- // TODO(kinuko): Implement CreateURLLoader with provider_->context()->
- // subresource_loader if Servicification is enabled.
+ std::unique_ptr<blink::WebURLLoader> CreateURLLoader(
+ const blink::WebURLRequest& request,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner) override {
+ // S13nServiceWorker:
+ // We only install our own URLLoader if Servicification is enabled.
+ if (!ServiceWorkerUtils::IsServicificationEnabled())
+ return nullptr;
+
+ RenderThreadImpl* render_thread = RenderThreadImpl::current();
+ // RenderThreadImpl is nullptr in some tests.
+ if (!render_thread) {
+ return nullptr;
+ }
+ // If the request is for the main script, use the script_loader_factory.
+ if (provider_->script_loader_factory() &&
+ request.GetRequestContext() ==
+ blink::WebURLRequest::kRequestContextSharedWorker) {
+ // TODO(crbug.com/796425): Temporarily wrap the raw
+ // mojom::URLLoaderFactory pointer into SharedURLLoaderFactory.
+ return std::make_unique<WebURLLoaderImpl>(
+ render_thread->resource_dispatcher(), std::move(task_runner),
+ base::MakeRefCounted<WeakWrapperSharedURLLoaderFactory>(
+ provider_->script_loader_factory()));
+ }
+
+ // Otherwise, it's an importScript. Use the subresource loader factory.
+ if (!provider_->context() ||
+ !provider_->context()->GetSubresourceLoaderFactory()) {
+ return nullptr;
+ }
+
+ // If it's not for HTTP or HTTPS, no need to intercept the request.
+ if (!GURL(request.Url()).SchemeIsHTTPOrHTTPS())
+ return nullptr;
+
+ // If GetSkipServiceWorker() returns true, do not intercept the request.
+ if (request.GetSkipServiceWorker())
+ return nullptr;
+
+ // Create our own SubresourceLoader to route the request
+ // to the controller ServiceWorker.
+ // TODO(crbug.com/796425): Temporarily wrap the raw mojom::URLLoaderFactory
+ // pointer into SharedURLLoaderFactory.
+ return std::make_unique<WebURLLoaderImpl>(
+ RenderThreadImpl::current()->resource_dispatcher(),
+ std::move(task_runner),
+ base::MakeRefCounted<WeakWrapperSharedURLLoaderFactory>(
+ provider_->context()->GetSubresourceLoaderFactory()));
+ }
private:
std::unique_ptr<ServiceWorkerNetworkProvider> provider_;
@@ -130,6 +178,10 @@ EmbeddedSharedWorkerStub::EmbeddedSharedWorkerStub(
bool pause_on_start,
const base::UnguessableToken& devtools_worker_token,
blink::mojom::WorkerContentSettingsProxyPtr content_settings,
+ mojom::ServiceWorkerProviderInfoForSharedWorkerPtr
+ service_worker_provider_info,
+ network::mojom::URLLoaderFactoryAssociatedPtrInfo
+ script_loader_factory_info,
mojom::SharedWorkerHostPtr host,
mojom::SharedWorkerRequest request,
service_manager::mojom::InterfaceProviderPtr interface_provider)
@@ -143,6 +195,10 @@ EmbeddedSharedWorkerStub::EmbeddedSharedWorkerStub(
// is attached or explicit resume notification is received.
impl_->PauseWorkerContextOnStart();
}
+
+ service_worker_provider_info_ = std::move(service_worker_provider_info);
+ script_loader_factory_info_ = std::move(script_loader_factory_info);
+
impl_->StartWorkerContext(
url_, blink::WebString::FromUTF8(name_),
blink::WebString::FromUTF8(info->content_security_policy),
@@ -156,7 +212,8 @@ EmbeddedSharedWorkerStub::EmbeddedSharedWorkerStub(
}
EmbeddedSharedWorkerStub::~EmbeddedSharedWorkerStub() {
- DCHECK(!impl_);
+ // Destruction closes our connection to the host, triggering the host to
+ // cleanup and notify clients of this worker going away.
}
void EmbeddedSharedWorkerStub::WorkerReadyForInspection() {
@@ -175,7 +232,7 @@ void EmbeddedSharedWorkerStub::WorkerScriptLoaded() {
void EmbeddedSharedWorkerStub::WorkerScriptLoadFailed() {
host_->OnScriptLoadFailed();
pending_channels_.clear();
- Shutdown();
+ delete this;
}
void EmbeddedSharedWorkerStub::CountFeature(blink::mojom::WebFeature feature) {
@@ -187,7 +244,7 @@ void EmbeddedSharedWorkerStub::WorkerContextClosed() {
}
void EmbeddedSharedWorkerStub::WorkerContextDestroyed() {
- Shutdown();
+ delete this;
}
void EmbeddedSharedWorkerStub::SelectAppCacheID(long long app_cache_id) {
@@ -217,16 +274,35 @@ EmbeddedSharedWorkerStub::CreateApplicationCacheHost(
std::unique_ptr<blink::WebServiceWorkerNetworkProvider>
EmbeddedSharedWorkerStub::CreateServiceWorkerNetworkProvider() {
- // Create a content::ServiceWorkerNetworkProvider for this data source so
- // we can observe its requests.
- std::unique_ptr<ServiceWorkerNetworkProvider> provider(
- ServiceWorkerNetworkProvider::CreateForSharedWorker());
+ scoped_refptr<network::SharedURLLoaderFactory> direct_network_loader_factory;
+ // current() may be null in tests.
+ if (RenderThreadImpl* render_thread = RenderThreadImpl::current()) {
+ direct_network_loader_factory =
+ base::MakeRefCounted<PossiblyAssociatedWrapperSharedURLLoaderFactory>(
+ render_thread->blink_platform_impl()
+ ->CreateNetworkURLLoaderFactory());
+ }
- // Blink is responsible for deleting the returned object.
+ std::unique_ptr<ServiceWorkerNetworkProvider> provider =
+ ServiceWorkerNetworkProvider::CreateForSharedWorker(
+ std::move(service_worker_provider_info_),
+ std::move(script_loader_factory_info_),
+ std::move(direct_network_loader_factory));
return std::make_unique<WebServiceWorkerNetworkProviderForSharedWorker>(
std::move(provider), IsOriginSecure(url_));
}
+void EmbeddedSharedWorkerStub::WaitForServiceWorkerControllerInfo(
+ blink::WebServiceWorkerNetworkProvider* web_network_provider,
+ base::OnceClosure callback) {
+ ServiceWorkerProviderContext* context =
+ static_cast<WebServiceWorkerNetworkProviderForSharedWorker*>(
+ web_network_provider)
+ ->provider()
+ ->context();
+ context->PingContainerHost(std::move(callback));
+}
+
std::unique_ptr<blink::WebWorkerFetchContext>
EmbeddedSharedWorkerStub::CreateWorkerFetchContext(
blink::WebServiceWorkerNetworkProvider* web_network_provider) {
@@ -290,16 +366,6 @@ EmbeddedSharedWorkerStub::CreateWorkerFetchContext(
return std::move(worker_fetch_context);
}
-void EmbeddedSharedWorkerStub::Shutdown() {
- // WebSharedWorker must be already deleted in the blink side
- // when this is called.
- impl_ = nullptr;
-
- // This closes our connection to the host, triggering the host to cleanup and
- // notify clients of this worker going away.
- delete this;
-}
-
void EmbeddedSharedWorkerStub::ConnectToChannel(
int connection_request_id,
blink::MessagePortChannel channel) {
diff --git a/chromium/content/renderer/shared_worker/embedded_shared_worker_stub.h b/chromium/content/renderer/shared_worker/embedded_shared_worker_stub.h
index 31b282d9d87..25b8d13f4d8 100644
--- a/chromium/content/renderer/shared_worker/embedded_shared_worker_stub.h
+++ b/chromium/content/renderer/shared_worker/embedded_shared_worker_stub.h
@@ -11,19 +11,21 @@
#include "base/macros.h"
#include "base/unguessable_token.h"
#include "content/child/scoped_child_process_reference.h"
+#include "content/common/service_worker/service_worker_provider.mojom.h"
#include "content/common/shared_worker/shared_worker.mojom.h"
#include "content/common/shared_worker/shared_worker_host.mojom.h"
#include "content/common/shared_worker/shared_worker_info.mojom.h"
#include "content/renderer/child_message_filter.h"
#include "ipc/ipc_listener.h"
#include "mojo/public/cpp/bindings/binding.h"
+#include "services/network/public/mojom/url_loader_factory.mojom.h"
#include "services/service_manager/public/mojom/interface_provider.mojom.h"
-#include "third_party/WebKit/public/platform/WebContentSecurityPolicy.h"
-#include "third_party/WebKit/public/platform/WebContentSettingsClient.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/web/WebSharedWorkerClient.h"
-#include "third_party/WebKit/public/web/devtools_agent.mojom.h"
-#include "third_party/WebKit/public/web/worker_content_settings_proxy.mojom.h"
+#include "third_party/blink/public/platform/web_content_security_policy.h"
+#include "third_party/blink/public/platform/web_content_settings_client.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/web/devtools_agent.mojom.h"
+#include "third_party/blink/public/web/web_shared_worker_client.h"
+#include "third_party/blink/public/web/worker_content_settings_proxy.mojom.h"
#include "url/gurl.h"
namespace blink {
@@ -42,14 +44,13 @@ class WebApplicationCacheHostImpl;
// A stub class to receive IPC from browser process and talk to
// blink::WebSharedWorker. Implements blink::WebSharedWorkerClient.
-// This class is self-destruct (no one explicitly owns this), and
-// deletes itself (via private Shutdown() method) when either one of
-// following methods is called by blink::WebSharedWorker:
-// - workerScriptLoadFailed() or
-// - workerContextDestroyed()
+// This class is self-destructed (no one explicitly owns this). It deletes
+// itself when either one of following methods is called by
+// blink::WebSharedWorker:
+// - WorkerScriptLoadFailed() or
+// - WorkerContextDestroyed()
//
-// In either case the corresponding blink::WebSharedWorker also deletes
-// itself.
+// This class owns blink::WebSharedWorker.
class EmbeddedSharedWorkerStub : public blink::WebSharedWorkerClient,
public mojom::SharedWorker {
public:
@@ -58,6 +59,10 @@ class EmbeddedSharedWorkerStub : public blink::WebSharedWorkerClient,
bool pause_on_start,
const base::UnguessableToken& devtools_worker_token,
blink::mojom::WorkerContentSettingsProxyPtr content_settings,
+ mojom::ServiceWorkerProviderInfoForSharedWorkerPtr
+ service_worker_provider_info,
+ network::mojom::URLLoaderFactoryAssociatedPtrInfo
+ script_loader_factory_info,
mojom::SharedWorkerHostPtr host,
mojom::SharedWorkerRequest request,
service_manager::mojom::InterfaceProviderPtr interface_provider);
@@ -78,10 +83,11 @@ class EmbeddedSharedWorkerStub : public blink::WebSharedWorkerClient,
CreateServiceWorkerNetworkProvider() override;
std::unique_ptr<blink::WebWorkerFetchContext> CreateWorkerFetchContext(
blink::WebServiceWorkerNetworkProvider*) override;
+ void WaitForServiceWorkerControllerInfo(
+ blink::WebServiceWorkerNetworkProvider* web_network_provider,
+ base::OnceClosure callback) override;
private:
- void Shutdown();
-
// WebSharedWorker will own |channel|.
void ConnectToChannel(int connection_request_id,
blink::MessagePortChannel channel);
@@ -98,7 +104,7 @@ class EmbeddedSharedWorkerStub : public blink::WebSharedWorkerClient,
const std::string name_;
bool running_ = false;
GURL url_;
- blink::WebSharedWorker* impl_ = nullptr;
+ std::unique_ptr<blink::WebSharedWorker> impl_;
using PendingChannel =
std::pair<int /* connection_request_id */, blink::MessagePortChannel>;
@@ -106,6 +112,15 @@ class EmbeddedSharedWorkerStub : public blink::WebSharedWorkerClient,
ScopedChildProcessReference process_ref_;
WebApplicationCacheHostImpl* app_cache_host_ = nullptr; // Not owned.
+
+ // S13nServiceWorker: The info needed to connect to the
+ // ServiceWorkerProviderHost on the browser.
+ mojom::ServiceWorkerProviderInfoForSharedWorkerPtr
+ service_worker_provider_info_;
+ // NetworkService: The URLLoaderFactory used for loading the shared worker
+ // script.
+ network::mojom::URLLoaderFactoryAssociatedPtrInfo script_loader_factory_info_;
+
DISALLOW_COPY_AND_ASSIGN(EmbeddedSharedWorkerStub);
};
diff --git a/chromium/content/renderer/shared_worker/shared_worker_client_impl.cc b/chromium/content/renderer/shared_worker/shared_worker_client_impl.cc
index d3b4063464c..a628bdf7ff4 100644
--- a/chromium/content/renderer/shared_worker/shared_worker_client_impl.cc
+++ b/chromium/content/renderer/shared_worker/shared_worker_client_impl.cc
@@ -7,7 +7,7 @@
#include "content/child/child_thread_impl.h"
#include "content/common/view_messages.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
-#include "third_party/WebKit/public/platform/web_feature.mojom.h"
+#include "third_party/blink/public/platform/web_feature.mojom.h"
namespace content {
diff --git a/chromium/content/renderer/shared_worker/shared_worker_client_impl.h b/chromium/content/renderer/shared_worker/shared_worker_client_impl.h
index c6c53ec0d7f..c498d50fc8a 100644
--- a/chromium/content/renderer/shared_worker/shared_worker_client_impl.h
+++ b/chromium/content/renderer/shared_worker/shared_worker_client_impl.h
@@ -7,7 +7,7 @@
#include "base/macros.h"
#include "content/common/shared_worker/shared_worker_client.mojom.h"
-#include "third_party/WebKit/public/web/WebSharedWorkerConnectListener.h"
+#include "third_party/blink/public/web/web_shared_worker_connect_listener.h"
namespace content {
diff --git a/chromium/content/renderer/shared_worker/shared_worker_factory_impl.cc b/chromium/content/renderer/shared_worker/shared_worker_factory_impl.cc
index 2fa3f667526..3fe8d6c26b6 100644
--- a/chromium/content/renderer/shared_worker/shared_worker_factory_impl.cc
+++ b/chromium/content/renderer/shared_worker/shared_worker_factory_impl.cc
@@ -24,14 +24,19 @@ void SharedWorkerFactoryImpl::CreateSharedWorker(
bool pause_on_start,
const base::UnguessableToken& devtools_worker_token,
blink::mojom::WorkerContentSettingsProxyPtr content_settings,
+ mojom::ServiceWorkerProviderInfoForSharedWorkerPtr
+ service_worker_provider_info,
+ network::mojom::URLLoaderFactoryAssociatedPtrInfo
+ script_loader_factory_ptr_info,
mojom::SharedWorkerHostPtr host,
mojom::SharedWorkerRequest request,
service_manager::mojom::InterfaceProviderPtr interface_provider) {
// Bound to the lifetime of the underlying blink::WebSharedWorker instance.
new EmbeddedSharedWorkerStub(
std::move(info), pause_on_start, devtools_worker_token,
- std::move(content_settings), std::move(host), std::move(request),
- std::move(interface_provider));
+ std::move(content_settings), std::move(service_worker_provider_info),
+ std::move(script_loader_factory_ptr_info), std::move(host),
+ std::move(request), std::move(interface_provider));
}
} // namespace content
diff --git a/chromium/content/renderer/shared_worker/shared_worker_factory_impl.h b/chromium/content/renderer/shared_worker/shared_worker_factory_impl.h
index 880fb96af85..0fc2cfdf23c 100644
--- a/chromium/content/renderer/shared_worker/shared_worker_factory_impl.h
+++ b/chromium/content/renderer/shared_worker/shared_worker_factory_impl.h
@@ -6,7 +6,9 @@
#define CONTENT_RENDERER_SHARED_WORKER_SHARED_WORKER_FACTORY_IMPL_H_
#include "base/macros.h"
+#include "content/common/service_worker/service_worker_provider.mojom.h"
#include "content/common/shared_worker/shared_worker_factory.mojom.h"
+#include "services/network/public/mojom/url_loader_factory.mojom.h"
namespace content {
@@ -23,6 +25,10 @@ class SharedWorkerFactoryImpl : public mojom::SharedWorkerFactory {
bool pause_on_start,
const base::UnguessableToken& devtools_worker_token,
blink::mojom::WorkerContentSettingsProxyPtr content_settings,
+ mojom::ServiceWorkerProviderInfoForSharedWorkerPtr
+ service_worker_provider_info,
+ network::mojom::URLLoaderFactoryAssociatedPtrInfo
+ script_loader_factory_ptr_info,
mojom::SharedWorkerHostPtr host,
mojom::SharedWorkerRequest request,
service_manager::mojom::InterfaceProviderPtr interface_provider) override;
diff --git a/chromium/content/renderer/shared_worker/shared_worker_repository.cc b/chromium/content/renderer/shared_worker/shared_worker_repository.cc
index 28ef1ccd62a..562ef5b2e82 100644
--- a/chromium/content/renderer/shared_worker/shared_worker_repository.cc
+++ b/chromium/content/renderer/shared_worker/shared_worker_repository.cc
@@ -7,7 +7,7 @@
#include "content/common/view_messages.h"
#include "content/renderer/render_frame_impl.h"
#include "services/service_manager/public/cpp/interface_provider.h"
-#include "third_party/WebKit/public/web/WebSharedWorkerConnectListener.h"
+#include "third_party/blink/public/web/web_shared_worker_connect_listener.h"
namespace content {
diff --git a/chromium/content/renderer/shared_worker/shared_worker_repository.h b/chromium/content/renderer/shared_worker/shared_worker_repository.h
index 0b69c632f36..d0a8ce2c909 100644
--- a/chromium/content/renderer/shared_worker/shared_worker_repository.h
+++ b/chromium/content/renderer/shared_worker/shared_worker_repository.h
@@ -14,8 +14,8 @@
#include "content/renderer/shared_worker/shared_worker_client_impl.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "mojo/public/cpp/bindings/strong_binding_set.h"
-#include "third_party/WebKit/public/platform/WebContentSecurityPolicy.h"
-#include "third_party/WebKit/public/web/WebSharedWorkerRepositoryClient.h"
+#include "third_party/blink/public/platform/web_content_security_policy.h"
+#include "third_party/blink/public/web/web_shared_worker_repository_client.h"
namespace blink {
class MessagePortChannel;
diff --git a/chromium/content/renderer/skia_benchmarking_extension.cc b/chromium/content/renderer/skia_benchmarking_extension.cc
index 9d7c00dc6e5..40200bbf4b8 100644
--- a/chromium/content/renderer/skia_benchmarking_extension.cc
+++ b/chromium/content/renderer/skia_benchmarking_extension.cc
@@ -19,10 +19,10 @@
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "skia/ext/benchmarking_canvas.h"
-#include "third_party/WebKit/public/web/WebArrayBuffer.h"
-#include "third_party/WebKit/public/web/WebArrayBufferConverter.h"
-#include "third_party/WebKit/public/web/WebKit.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
+#include "third_party/blink/public/web/blink.h"
+#include "third_party/blink/public/web/web_array_buffer.h"
+#include "third_party/blink/public/web/web_array_buffer_converter.h"
+#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkColorPriv.h"
#include "third_party/skia/include/core/SkGraphics.h"
diff --git a/chromium/content/renderer/speech_recognition_dispatcher.cc b/chromium/content/renderer/speech_recognition_dispatcher.cc
index a542e88d287..e69f9e5e5aa 100644
--- a/chromium/content/renderer/speech_recognition_dispatcher.cc
+++ b/chromium/content/renderer/speech_recognition_dispatcher.cc
@@ -11,14 +11,14 @@
#include <utility>
#include "base/strings/utf_string_conversions.h"
+#include "build/build_config.h"
#include "content/common/speech_recognition_messages.h"
-#include "content/renderer/render_view_impl.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebVector.h"
-#include "third_party/WebKit/public/web/WebSpeechGrammar.h"
-#include "third_party/WebKit/public/web/WebSpeechRecognitionParams.h"
-#include "third_party/WebKit/public/web/WebSpeechRecognitionResult.h"
-#include "third_party/WebKit/public/web/WebSpeechRecognizerClient.h"
+#include "content/renderer/render_frame_impl.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_vector.h"
+#include "third_party/blink/public/web/web_speech_grammar.h"
+#include "third_party/blink/public/web/web_speech_recognition_params.h"
+#include "third_party/blink/public/web/web_speech_recognition_result.h"
using blink::WebVector;
using blink::WebString;
@@ -31,17 +31,11 @@ using blink::WebSpeechRecognizerClient;
namespace content {
SpeechRecognitionDispatcher::SpeechRecognitionDispatcher(
- RenderViewImpl* render_view)
- : RenderViewObserver(render_view),
- recognizer_client_(nullptr),
+ RenderFrame* render_frame)
+ : RenderFrameObserver(render_frame),
next_id_(1) {}
-SpeechRecognitionDispatcher::~SpeechRecognitionDispatcher() {}
-
-void SpeechRecognitionDispatcher::AbortAllRecognitions() {
- Send(new SpeechRecognitionHostMsg_AbortAllRequests(
- routing_id()));
-}
+SpeechRecognitionDispatcher::~SpeechRecognitionDispatcher() = default;
bool SpeechRecognitionDispatcher::OnMessageReceived(
const IPC::Message& message) {
@@ -65,11 +59,18 @@ void SpeechRecognitionDispatcher::OnDestruct() {
delete this;
}
+void SpeechRecognitionDispatcher::WasHidden() {
+#if defined(OS_ANDROID) && BUILDFLAG(ENABLE_WEBRTC)
+ Send(new SpeechRecognitionHostMsg_AbortAllRequests(routing_id()));
+#endif
+}
+
void SpeechRecognitionDispatcher::Start(
const WebSpeechRecognitionHandle& handle,
const WebSpeechRecognitionParams& params,
- WebSpeechRecognizerClient* recognizer_client) {
- DCHECK(!recognizer_client_ || recognizer_client_ == recognizer_client);
+ const WebSpeechRecognizerClient& recognizer_client) {
+ DCHECK(recognizer_client_.IsNull() ||
+ recognizer_client_ == recognizer_client);
recognizer_client_ = recognizer_client;
SpeechRecognitionHostMsg_StartRequest_Params msg_params;
@@ -82,7 +83,7 @@ void SpeechRecognitionDispatcher::Start(
msg_params.continuous = params.Continuous();
msg_params.interim_results = params.InterimResults();
msg_params.origin_url = params.Origin().ToString().Utf8();
- msg_params.render_view_id = routing_id();
+ msg_params.render_frame_id = routing_id();
msg_params.request_id = GetOrCreateIDForHandle(handle);
// The handle mapping will be removed in |OnRecognitionEnd|.
@@ -91,7 +92,7 @@ void SpeechRecognitionDispatcher::Start(
void SpeechRecognitionDispatcher::Stop(
const WebSpeechRecognitionHandle& handle,
- WebSpeechRecognizerClient* recognizer_client) {
+ const WebSpeechRecognizerClient& recognizer_client) {
// Ignore a |stop| issued without a matching |start|.
if (recognizer_client_ != recognizer_client || !HandleExists(handle))
return;
@@ -101,7 +102,7 @@ void SpeechRecognitionDispatcher::Stop(
void SpeechRecognitionDispatcher::Abort(
const WebSpeechRecognitionHandle& handle,
- WebSpeechRecognizerClient* recognizer_client) {
+ const WebSpeechRecognizerClient& recognizer_client) {
// Ignore an |abort| issued without a matching |start|.
if (recognizer_client_ != recognizer_client || !HandleExists(handle))
return;
@@ -110,23 +111,23 @@ void SpeechRecognitionDispatcher::Abort(
}
void SpeechRecognitionDispatcher::OnRecognitionStarted(int request_id) {
- recognizer_client_->DidStart(GetHandleFromID(request_id));
+ recognizer_client_.DidStart(GetHandleFromID(request_id));
}
void SpeechRecognitionDispatcher::OnAudioStarted(int request_id) {
- recognizer_client_->DidStartAudio(GetHandleFromID(request_id));
+ recognizer_client_.DidStartAudio(GetHandleFromID(request_id));
}
void SpeechRecognitionDispatcher::OnSoundStarted(int request_id) {
- recognizer_client_->DidStartSound(GetHandleFromID(request_id));
+ recognizer_client_.DidStartSound(GetHandleFromID(request_id));
}
void SpeechRecognitionDispatcher::OnSoundEnded(int request_id) {
- recognizer_client_->DidEndSound(GetHandleFromID(request_id));
+ recognizer_client_.DidEndSound(GetHandleFromID(request_id));
}
void SpeechRecognitionDispatcher::OnAudioEnded(int request_id) {
- recognizer_client_->DidEndAudio(GetHandleFromID(request_id));
+ recognizer_client_.DidEndAudio(GetHandleFromID(request_id));
}
static WebSpeechRecognizerClient::ErrorCode WebKitErrorCode(
@@ -162,13 +163,12 @@ static WebSpeechRecognizerClient::ErrorCode WebKitErrorCode(
void SpeechRecognitionDispatcher::OnErrorOccurred(
int request_id, const SpeechRecognitionError& error) {
if (error.code == SPEECH_RECOGNITION_ERROR_NO_MATCH) {
- recognizer_client_->DidReceiveNoMatch(GetHandleFromID(request_id),
- WebSpeechRecognitionResult());
+ recognizer_client_.DidReceiveNoMatch(GetHandleFromID(request_id),
+ WebSpeechRecognitionResult());
} else {
- recognizer_client_->DidReceiveError(
- GetHandleFromID(request_id),
- WebString(), // TODO(primiano): message?
- WebKitErrorCode(error.code));
+ recognizer_client_.DidReceiveError(GetHandleFromID(request_id),
+ WebString(), // TODO(primiano): message?
+ WebKitErrorCode(error.code));
}
}
@@ -185,7 +185,7 @@ void SpeechRecognitionDispatcher::OnRecognitionEnded(int request_id) {
// didEnd may call back synchronously to start a new recognition session,
// and we don't want to delete the handle from the map after that happens.
handle_map_.erase(request_id);
- recognizer_client_->DidEnd(handle);
+ recognizer_client_.DidEnd(handle);
}
}
@@ -216,8 +216,8 @@ void SpeechRecognitionDispatcher::OnResultsRetrieved(
webkit_result->Assign(transcripts, confidences, !result.is_provisional);
}
- recognizer_client_->DidReceiveResults(GetHandleFromID(request_id), final,
- provisional);
+ recognizer_client_.DidReceiveResults(GetHandleFromID(request_id), final,
+ provisional);
}
int SpeechRecognitionDispatcher::GetOrCreateIDForHandle(
diff --git a/chromium/content/renderer/speech_recognition_dispatcher.h b/chromium/content/renderer/speech_recognition_dispatcher.h
index 8251b45bd97..d9055e769bf 100644
--- a/chromium/content/renderer/speech_recognition_dispatcher.h
+++ b/chromium/content/renderer/speech_recognition_dispatcher.h
@@ -10,41 +10,39 @@
#include "base/macros.h"
#include "content/public/common/speech_recognition_result.h"
-#include "content/public/renderer/render_view_observer.h"
-#include "third_party/WebKit/public/web/WebSpeechRecognitionHandle.h"
-#include "third_party/WebKit/public/web/WebSpeechRecognizer.h"
+#include "content/public/renderer/render_frame_observer.h"
+#include "third_party/blink/public/web/web_speech_recognition_handle.h"
+#include "third_party/blink/public/web/web_speech_recognizer.h"
+#include "third_party/blink/public/web/web_speech_recognizer_client.h"
namespace content {
-class RenderViewImpl;
struct SpeechRecognitionError;
// SpeechRecognitionDispatcher is a delegate for methods used by WebKit for
// scripted JS speech APIs. It's the complement of
-// SpeechRecognitionDispatcherHost (owned by RenderViewHost).
-class SpeechRecognitionDispatcher : public RenderViewObserver,
+// SpeechRecognitionDispatcherHost (owned by RenderFrameHost).
+class SpeechRecognitionDispatcher : public RenderFrameObserver,
public blink::WebSpeechRecognizer {
public:
- explicit SpeechRecognitionDispatcher(RenderViewImpl* render_view);
+ explicit SpeechRecognitionDispatcher(RenderFrame* render_frame);
~SpeechRecognitionDispatcher() override;
- // Aborts all speech recognitions.
- void AbortAllRecognitions();
-
private:
using HandleMap = std::map<int, blink::WebSpeechRecognitionHandle>;
- // RenderViewObserver implementation.
+ // RenderFrameObserver implementation.
bool OnMessageReceived(const IPC::Message& message) override;
void OnDestruct() override;
+ void WasHidden() override;
// blink::WebSpeechRecognizer implementation.
void Start(const blink::WebSpeechRecognitionHandle&,
const blink::WebSpeechRecognitionParams&,
- blink::WebSpeechRecognizerClient*) override;
+ const blink::WebSpeechRecognizerClient&) override;
void Stop(const blink::WebSpeechRecognitionHandle&,
- blink::WebSpeechRecognizerClient*) override;
+ const blink::WebSpeechRecognizerClient&) override;
void Abort(const blink::WebSpeechRecognitionHandle&,
- blink::WebSpeechRecognizerClient*) override;
+ const blink::WebSpeechRecognizerClient&) override;
void OnRecognitionStarted(int request_id);
void OnAudioStarted(int request_id);
@@ -62,8 +60,8 @@ class SpeechRecognitionDispatcher : public RenderViewObserver,
const blink::WebSpeechRecognitionHandle& handle);
const blink::WebSpeechRecognitionHandle& GetHandleFromID(int handle_id);
- // The WebKit client class that we use to send events back to the JS world.
- blink::WebSpeechRecognizerClient* recognizer_client_;
+ // The Blink client class that we use to send events back to the JS world.
+ blink::WebSpeechRecognizerClient recognizer_client_;
// This maps between request id values and the Blink handle values.
HandleMap handle_map_;
diff --git a/chromium/content/renderer/stats_collection_controller.cc b/chromium/content/renderer/stats_collection_controller.cc
index ed3fc2e039f..d528f49e513 100644
--- a/chromium/content/renderer/stats_collection_controller.cc
+++ b/chromium/content/renderer/stats_collection_controller.cc
@@ -5,7 +5,6 @@
#include "content/renderer/stats_collection_controller.h"
#include "base/json/json_writer.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_base.h"
#include "base/metrics/histogram_macros.h"
#include "base/metrics/statistics_recorder.h"
@@ -17,9 +16,9 @@
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "services/service_manager/public/cpp/connector.h"
-#include "third_party/WebKit/public/web/WebKit.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebView.h"
+#include "third_party/blink/public/web/blink.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_view.h"
namespace content {
diff --git a/chromium/content/renderer/storage_util.cc b/chromium/content/renderer/storage_util.cc
index 91f94d05b9e..278ca243163 100644
--- a/chromium/content/renderer/storage_util.cc
+++ b/chromium/content/renderer/storage_util.cc
@@ -4,8 +4,8 @@
#include "content/renderer/storage_util.h"
-#include "third_party/WebKit/public/platform/URLConversion.h"
-#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
+#include "third_party/blink/public/platform/url_conversion.h"
+#include "third_party/blink/public/platform/web_security_origin.h"
#include "url/gurl.h"
#include "url/origin.h"
diff --git a/chromium/content/renderer/text_input_client_observer.cc b/chromium/content/renderer/text_input_client_observer.cc
index 5252466a68c..1cfa06220b4 100644
--- a/chromium/content/renderer/text_input_client_observer.cc
+++ b/chromium/content/renderer/text_input_client_observer.cc
@@ -15,16 +15,16 @@
#include "content/renderer/render_view_impl.h"
#include "content/renderer/render_widget.h"
#include "ipc/ipc_message.h"
-#include "ppapi/features/features.h"
-#include "third_party/WebKit/public/platform/WebPoint.h"
-#include "third_party/WebKit/public/platform/WebRect.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebView.h"
+#include "ppapi/buildflags/buildflags.h"
+#include "third_party/blink/public/platform/web_point.h"
+#include "third_party/blink/public/platform/web_rect.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_view.h"
#include "ui/gfx/geometry/rect.h"
#if defined(OS_MACOSX)
-#include "third_party/WebKit/public/web/mac/WebSubstringUtil.h"
+#include "third_party/blink/public/web/mac/web_substring_util.h"
#endif
namespace content {
diff --git a/chromium/content/renderer/text_input_client_observer.h b/chromium/content/renderer/text_input_client_observer.h
index e2ce697ea4c..c2c48556155 100644
--- a/chromium/content/renderer/text_input_client_observer.h
+++ b/chromium/content/renderer/text_input_client_observer.h
@@ -8,7 +8,7 @@
#include "base/macros.h"
#include "build/build_config.h"
#include "content/public/renderer/render_view_observer.h"
-#include "ppapi/features/features.h"
+#include "ppapi/buildflags/buildflags.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/range/range.h"
diff --git a/chromium/content/renderer/v8_value_converter_impl.cc b/chromium/content/renderer/v8_value_converter_impl.cc
index 39a916f9153..13f3e8a442a 100644
--- a/chromium/content/renderer/v8_value_converter_impl.cc
+++ b/chromium/content/renderer/v8_value_converter_impl.cc
@@ -16,7 +16,6 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/logging.h"
-#include "base/memory/ptr_util.h"
#include "base/values.h"
#include "v8/include/v8.h"
@@ -460,7 +459,7 @@ std::unique_ptr<base::Value> V8ValueConverterImpl::FromV8Array(
base::Unretained(this),
base::Unretained(state));
std::unique_ptr<base::Value> out;
- if (strategy_->FromV8Array(val, &out, isolate, callback))
+ if (strategy_->FromV8Array(val, &out, isolate, std::move(callback)))
return out;
}
@@ -540,7 +539,7 @@ std::unique_ptr<base::Value> V8ValueConverterImpl::FromV8Object(
base::Unretained(this),
base::Unretained(state));
std::unique_ptr<base::Value> out;
- if (strategy_->FromV8Object(val, &out, isolate, callback))
+ if (strategy_->FromV8Object(val, &out, isolate, std::move(callback)))
return out;
}
diff --git a/chromium/content/renderer/v8_value_converter_impl_unittest.cc b/chromium/content/renderer/v8_value_converter_impl_unittest.cc
index 65967091171..02eb80bcc97 100644
--- a/chromium/content/renderer/v8_value_converter_impl_unittest.cc
+++ b/chromium/content/renderer/v8_value_converter_impl_unittest.cc
@@ -11,7 +11,6 @@
#include <memory>
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/stl_util.h"
#include "base/test/scoped_task_environment.h"
#include "base/test/values_test_util.h"
diff --git a/chromium/content/renderer/web_database_observer_impl.cc b/chromium/content/renderer/web_database_observer_impl.cc
index ec6a6974995..087cf47ede2 100644
--- a/chromium/content/renderer/web_database_observer_impl.cc
+++ b/chromium/content/renderer/web_database_observer_impl.cc
@@ -11,8 +11,8 @@
#include "base/threading/thread_task_runner_handle.h"
#include "content/renderer/storage_util.h"
#include "storage/common/database/database_identifier.h"
-#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
-#include "third_party/WebKit/public/platform/WebString.h"
+#include "third_party/blink/public/platform/web_security_origin.h"
+#include "third_party/blink/public/platform/web_string.h"
#include "third_party/sqlite/sqlite3.h"
using blink::WebSecurityOrigin;
diff --git a/chromium/content/renderer/web_database_observer_impl.h b/chromium/content/renderer/web_database_observer_impl.h
index b2ddbef2ed0..df5c4c1eb2f 100644
--- a/chromium/content/renderer/web_database_observer_impl.h
+++ b/chromium/content/renderer/web_database_observer_impl.h
@@ -8,8 +8,8 @@
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "storage/common/database/database_connections.h"
-#include "third_party/WebKit/public/platform/WebDatabaseObserver.h"
-#include "third_party/WebKit/public/platform/modules/webdatabase/web_database.mojom.h"
+#include "third_party/blink/public/platform/modules/webdatabase/web_database.mojom.h"
+#include "third_party/blink/public/platform/web_database_observer.h"
namespace base {
class SingleThreadTaskRunner;
diff --git a/chromium/content/renderer/web_frame_utils.cc b/chromium/content/renderer/web_frame_utils.cc
index cf07d9848ca..cba1820c98f 100644
--- a/chromium/content/renderer/web_frame_utils.cc
+++ b/chromium/content/renderer/web_frame_utils.cc
@@ -7,9 +7,9 @@
#include "content/renderer/render_frame_impl.h"
#include "content/renderer/render_frame_proxy.h"
#include "ipc/ipc_message.h"
-#include "third_party/WebKit/public/web/WebFrame.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebRemoteFrame.h"
+#include "third_party/blink/public/web/web_frame.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_remote_frame.h"
namespace content {
diff --git a/chromium/content/renderer/web_ui_extension.cc b/chromium/content/renderer/web_ui_extension.cc
index 93ff2804839..eb05e6c365b 100644
--- a/chromium/content/renderer/web_ui_extension.cc
+++ b/chromium/content/renderer/web_ui_extension.cc
@@ -7,7 +7,6 @@
#include <memory>
#include <utility>
-#include "base/strings/string_util.h"
#include "base/values.h"
#include "content/common/frame_messages.h"
#include "content/public/common/bindings_policy.h"
@@ -20,11 +19,10 @@
#include "content/renderer/web_ui_extension_data.h"
#include "gin/arguments.h"
#include "gin/function_template.h"
-#include "third_party/WebKit/public/web/WebDocument.h"
-#include "third_party/WebKit/public/web/WebKit.h"
-#include "third_party/WebKit/public/web/WebLocalFrame.h"
-#include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
-#include "third_party/WebKit/public/web/WebView.h"
+#include "third_party/blink/public/web/blink.h"
+#include "third_party/blink/public/web/web_document.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_view.h"
#include "url/gurl.h"
#include "v8/include/v8.h"
@@ -98,13 +96,6 @@ void WebUIExtension::Send(gin::Arguments* args) {
return;
}
- if (base::EndsWith(message, "RequiringGesture",
- base::CompareCase::SENSITIVE) &&
- !blink::WebUserGestureIndicator::IsProcessingUserGesture(frame)) {
- NOTREACHED();
- return;
- }
-
// If they've provided an optional message parameter, convert that into a
// Value to send to the browser process.
std::unique_ptr<base::ListValue> content;
diff --git a/chromium/content/renderer/webfileutilities_impl.cc b/chromium/content/renderer/webfileutilities_impl.cc
index bcb86d527a5..c3cab39e2e0 100644
--- a/chromium/content/renderer/webfileutilities_impl.cc
+++ b/chromium/content/renderer/webfileutilities_impl.cc
@@ -9,10 +9,10 @@
#include "base/logging.h"
#include "content/renderer/file_info_util.h"
#include "net/base/filename_util.h"
-#include "third_party/WebKit/public/platform/FilePathConversion.h"
-#include "third_party/WebKit/public/platform/WebFileInfo.h"
-#include "third_party/WebKit/public/platform/WebString.h"
-#include "third_party/WebKit/public/platform/WebURL.h"
+#include "third_party/blink/public/platform/file_path_conversion.h"
+#include "third_party/blink/public/platform/web_file_info.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_url.h"
using blink::WebString;
diff --git a/chromium/content/renderer/webfileutilities_impl.h b/chromium/content/renderer/webfileutilities_impl.h
index 7a13e7d7584..00c573d758d 100644
--- a/chromium/content/renderer/webfileutilities_impl.h
+++ b/chromium/content/renderer/webfileutilities_impl.h
@@ -6,8 +6,8 @@
#define CONTENT_RENDERER_WEBFILEUTILITIES_IMPL_H_
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebFileInfo.h"
-#include "third_party/WebKit/public/platform/WebFileUtilities.h"
+#include "third_party/blink/public/platform/web_file_info.h"
+#include "third_party/blink/public/platform/web_file_utilities.h"
namespace content {
diff --git a/chromium/content/renderer/webgraphicscontext3d_provider_impl.cc b/chromium/content/renderer/webgraphicscontext3d_provider_impl.cc
index aacd43edcf2..db9fcf58a91 100644
--- a/chromium/content/renderer/webgraphicscontext3d_provider_impl.cc
+++ b/chromium/content/renderer/webgraphicscontext3d_provider_impl.cc
@@ -38,10 +38,6 @@ GrContext* WebGraphicsContext3DProviderImpl::GetGrContext() {
return provider_->GrContext();
}
-void WebGraphicsContext3DProviderImpl::InvalidateGrContext(uint32_t state) {
- return provider_->InvalidateGrContext(state);
-}
-
const gpu::Capabilities& WebGraphicsContext3DProviderImpl::GetCapabilities()
const {
return provider_->ContextCapabilities();
@@ -96,10 +92,9 @@ cc::ImageDecodeCache* WebGraphicsContext3DProviderImpl::ImageDecodeCache() {
// TransferCache is used only with OOP raster.
const bool use_transfer_cache = false;
- DCHECK(provider_->RasterInterface());
image_decode_cache_ = std::make_unique<cc::GpuImageDecodeCache>(
provider_.get(), use_transfer_cache, kN32_SkColorType,
- kMaxWorkingSetBytes);
+ kMaxWorkingSetBytes, provider_->ContextCapabilities().max_texture_size);
return image_decode_cache_.get();
}
diff --git a/chromium/content/renderer/webgraphicscontext3d_provider_impl.h b/chromium/content/renderer/webgraphicscontext3d_provider_impl.h
index 379988509b6..13742b62686 100644
--- a/chromium/content/renderer/webgraphicscontext3d_provider_impl.h
+++ b/chromium/content/renderer/webgraphicscontext3d_provider_impl.h
@@ -9,7 +9,7 @@
#include "base/memory/ref_counted.h"
#include "components/viz/common/gpu/context_provider.h"
#include "content/common/content_export.h"
-#include "third_party/WebKit/public/platform/WebGraphicsContext3DProvider.h"
+#include "third_party/blink/public/platform/web_graphics_context_3d_provider.h"
namespace cc {
class ImageDecodeCache;
@@ -44,7 +44,6 @@ class CONTENT_EXPORT WebGraphicsContext3DProviderImpl
bool BindToCurrentThread() override;
gpu::gles2::GLES2Interface* ContextGL() override;
GrContext* GetGrContext() override;
- void InvalidateGrContext(uint32_t state) override;
const gpu::Capabilities& GetCapabilities() const override;
const gpu::GpuFeatureInfo& GetGpuFeatureInfo() const override;
viz::GLHelper* GetGLHelper() override;
diff --git a/chromium/content/renderer/webpublicsuffixlist_impl.h b/chromium/content/renderer/webpublicsuffixlist_impl.h
index 959c5dba081..a38010e0de3 100644
--- a/chromium/content/renderer/webpublicsuffixlist_impl.h
+++ b/chromium/content/renderer/webpublicsuffixlist_impl.h
@@ -8,7 +8,7 @@
#include <stddef.h>
#include "base/compiler_specific.h"
-#include "third_party/WebKit/public/platform/WebPublicSuffixList.h"
+#include "third_party/blink/public/platform/web_public_suffix_list.h"
namespace content {
diff --git a/chromium/content/renderer/webscrollbarbehavior_impl_aura.cc b/chromium/content/renderer/webscrollbarbehavior_impl_aura.cc
index 2ef7f765c86..c6c15715a90 100644
--- a/chromium/content/renderer/webscrollbarbehavior_impl_aura.cc
+++ b/chromium/content/renderer/webscrollbarbehavior_impl_aura.cc
@@ -5,8 +5,8 @@
#include "content/renderer/webscrollbarbehavior_impl_aura.h"
#include "build/build_config.h"
-#include "third_party/WebKit/public/platform/WebPoint.h"
-#include "third_party/WebKit/public/platform/WebRect.h"
+#include "third_party/blink/public/platform/web_point.h"
+#include "third_party/blink/public/platform/web_rect.h"
namespace content {
diff --git a/chromium/content/renderer/webscrollbarbehavior_impl_aura.h b/chromium/content/renderer/webscrollbarbehavior_impl_aura.h
index 383b5f9d4f6..f06717ddc56 100644
--- a/chromium/content/renderer/webscrollbarbehavior_impl_aura.h
+++ b/chromium/content/renderer/webscrollbarbehavior_impl_aura.h
@@ -5,7 +5,7 @@
#ifndef CONTENT_RENDERER_WEBSCROLLBARBEHAVIOR_IMPL_AURA_H_
#define CONTENT_RENDERER_WEBSCROLLBARBEHAVIOR_IMPL_AURA_H_
-#include "third_party/WebKit/public/platform/WebScrollbarBehavior.h"
+#include "third_party/blink/public/platform/web_scrollbar_behavior.h"
namespace content {
diff --git a/chromium/content/renderer/webscrollbarbehavior_impl_mac.h b/chromium/content/renderer/webscrollbarbehavior_impl_mac.h
index 7334deb5147..c6303816875 100644
--- a/chromium/content/renderer/webscrollbarbehavior_impl_mac.h
+++ b/chromium/content/renderer/webscrollbarbehavior_impl_mac.h
@@ -5,7 +5,7 @@
#ifndef CONTENT_RENDERER_WEBSCROLLBARBEHAVIOR_IMPL_MAC_H_
#define CONTENT_RENDERER_WEBSCROLLBARBEHAVIOR_IMPL_MAC_H_
-#include "third_party/WebKit/public/platform/WebScrollbarBehavior.h"
+#include "third_party/blink/public/platform/web_scrollbar_behavior.h"
namespace content {
diff --git a/chromium/content/renderer/worker_thread_message_filter.cc b/chromium/content/renderer/worker_thread_message_filter.cc
index 81b24c2c286..081764da7f4 100644
--- a/chromium/content/renderer/worker_thread_message_filter.cc
+++ b/chromium/content/renderer/worker_thread_message_filter.cc
@@ -12,10 +12,10 @@
namespace content {
WorkerThreadMessageFilter::WorkerThreadMessageFilter(
- ThreadSafeSender* thread_safe_sender)
- : main_thread_task_runner_(base::ThreadTaskRunnerHandle::Get()),
- thread_safe_sender_(thread_safe_sender) {
-}
+ ThreadSafeSender* thread_safe_sender,
+ scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner)
+ : main_thread_task_runner_(std::move(main_thread_task_runner)),
+ thread_safe_sender_(thread_safe_sender) {}
WorkerThreadMessageFilter::~WorkerThreadMessageFilter() {
}
diff --git a/chromium/content/renderer/worker_thread_message_filter.h b/chromium/content/renderer/worker_thread_message_filter.h
index d08b47d8cba..64c0d47b896 100644
--- a/chromium/content/renderer/worker_thread_message_filter.h
+++ b/chromium/content/renderer/worker_thread_message_filter.h
@@ -19,7 +19,9 @@ class ThreadSafeSender;
// A base class for filtering IPC messages targeted for worker threads.
class WorkerThreadMessageFilter : public ChildMessageFilter {
public:
- explicit WorkerThreadMessageFilter(ThreadSafeSender* thread_safe_sender);
+ WorkerThreadMessageFilter(
+ ThreadSafeSender* thread_safe_sender,
+ scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner);
protected:
~WorkerThreadMessageFilter() override;
diff --git a/chromium/content/shell/BUILD.gn b/chromium/content/shell/BUILD.gn
index c52111a519c..744a78e7aa5 100644
--- a/chromium/content/shell/BUILD.gn
+++ b/chromium/content/shell/BUILD.gn
@@ -9,7 +9,7 @@ import("//build/config/win/console_app.gni")
import("//build/config/win/manifest.gni")
import("//media/media_options.gni")
import("//mojo/public/tools/bindings/mojom.gni")
-import("//ppapi/features/features.gni")
+import("//ppapi/buildflags/buildflags.gni")
import("//services/service_manager/public/service_manifest.gni")
import("//tools/grit/grit_rule.gni")
import("//tools/grit/repack.gni")
@@ -21,8 +21,6 @@ if (is_android) {
import("//build/mac/tweak_info_plist.gni")
import("//third_party/icu/config.gni")
import("//v8/gni/v8.gni")
-} else if (is_win) {
- import("//build/win/syzygy/syzygy.gni")
}
declare_args() {
@@ -37,10 +35,19 @@ config("content_shell_lib_warnings") {
}
}
-static_library("content_shell_lib") {
+source_set("android_shell_descriptors") {
testonly = true
sources = [
"android/shell_descriptors.h",
+ ]
+ public_deps = [
+ "//content/public/common:content_descriptors",
+ ]
+}
+
+static_library("content_shell_lib") {
+ testonly = true
+ sources = [
"android/shell_manager.cc",
"android/shell_manager.h",
"app/blink_test_platform_support.h",
@@ -60,6 +67,8 @@ static_library("content_shell_lib") {
"browser/layout_test/blink_test_controller.h",
"browser/layout_test/devtools_protocol_test_bindings.cc",
"browser/layout_test/devtools_protocol_test_bindings.h",
+ "browser/layout_test/fake_bluetooth_chooser.cc",
+ "browser/layout_test/fake_bluetooth_chooser.h",
"browser/layout_test/layout_test_bluetooth_adapter_provider.cc",
"browser/layout_test/layout_test_bluetooth_adapter_provider.h",
"browser/layout_test/layout_test_bluetooth_chooser_factory.cc",
@@ -207,6 +216,8 @@ static_library("content_shell_lib") {
defines = [ "CONTENT_SHELL_VERSION=\"$content_shell_version\"" ]
public_deps = [
+ ":android_shell_descriptors",
+
# This exposes all public content APIs.
"//content/public/app:both",
"//content/public/browser",
@@ -252,16 +263,15 @@ static_library("content_shell_lib") {
"//device/bluetooth:fake_bluetooth",
"//device/bluetooth:mocks",
"//device/geolocation/public/cpp:test_support",
- "//device/sensors/public/cpp:full",
"//gin",
"//gpu",
"//media",
"//media/capture",
- "//media/mojo:features",
+ "//media/mojo:buildflags",
"//net",
"//net:net_resources",
"//net:test_support",
- "//ppapi/features",
+ "//ppapi/buildflags",
"//sandbox",
"//services/device/public/mojom",
"//services/network/public/cpp",
@@ -272,11 +282,11 @@ static_library("content_shell_lib") {
"//storage/browser",
"//testing/gmock",
"//testing/gtest",
- "//third_party/WebKit/public:blink",
- "//third_party/WebKit/public:features",
- "//third_party/WebKit/public:image_resources",
- "//third_party/WebKit/public:resources",
- "//third_party/WebKit/public:test_support",
+ "//third_party/blink/public:blink",
+ "//third_party/blink/public:buildflags",
+ "//third_party/blink/public:image_resources",
+ "//third_party/blink/public:resources",
+ "//third_party/blink/public:test_support",
"//third_party/icu",
"//ui/base",
"//ui/base/ime",
@@ -451,8 +461,6 @@ group("resources") {
repack("pak") {
sources = [
- "$root_gen_dir/blink/public/resources/blink_resources.pak",
- "$root_gen_dir/blink/public/resources/blink_scaled_resources_100_percent.pak",
"$root_gen_dir/content/app/resources/content_resources_100_percent.pak",
"$root_gen_dir/content/app/strings/content_strings_en-US.pak",
"$root_gen_dir/content/browser/tracing/tracing_resources.pak",
@@ -460,6 +468,8 @@ repack("pak") {
"$root_gen_dir/content/shell/shell_resources.pak",
"$root_gen_dir/mojo/public/js/mojo_bindings_resources.pak",
"$root_gen_dir/net/net_resources.pak",
+ "$root_gen_dir/third_party/blink/public/resources/blink_resources.pak",
+ "$root_gen_dir/third_party/blink/public/resources/blink_scaled_resources_100_percent.pak",
"$root_gen_dir/ui/resources/ui_resources_100_percent.pak",
"$root_gen_dir/ui/resources/webui_resources.pak",
"$root_gen_dir/ui/strings/app_locale_settings_en-US.pak",
@@ -474,8 +484,8 @@ repack("pak") {
"//content/browser/tracing:resources",
"//mojo/public/js:resources",
"//net:net_resources",
- "//third_party/WebKit/public:resources",
- "//third_party/WebKit/public:scaled_resources_100_percent",
+ "//third_party/blink/public:resources",
+ "//third_party/blink/public:scaled_resources_100_percent",
"//ui/resources",
"//ui/strings",
]
@@ -604,19 +614,6 @@ if (is_android) {
}
}
-if (is_win) {
- if (is_syzyasan) {
- syzygy_asan("content_shell_syzyasan") {
- binary_name = "content_shell.exe"
- dest_dir = "$root_out_dir/syzygy"
- deps = [
- "//content/shell:content_shell",
- ]
- testonly = true
- }
- }
-}
-
if (is_mac) {
bundle_data("content_shell_framework_helpers") {
testonly = true
@@ -712,6 +709,13 @@ if (is_mac) {
output_name = content_shell_framework_name
+ framework_version = "C"
+
+ framework_contents = [
+ "Helpers",
+ "Resources",
+ ]
+
sources = [
"app/shell_content_main.cc",
"app/shell_content_main.h",
@@ -746,11 +750,11 @@ if (is_mac) {
if (is_component_build) {
# Set up the rpath for the framework so that it can find dylibs in the
# root output directory. The framework is at
- # Content Shell.app/Contents/Frameworks/Content Shell Framework.framework/Content Shell Framework
+ # Content Shell.app/Contents/Frameworks/Content Shell Framework.framework/Versions/C/Content Shell Framework
# so use loader_path to go back to the root output directory.
ldflags += [
"-rpath",
- "@loader_path/../../../..",
+ "@loader_path/../../../../../..",
]
}
@@ -817,11 +821,13 @@ if (is_mac) {
mojom("mojo_bindings") {
sources = [
"common/layout_test.mojom",
+ "common/layout_test/fake_bluetooth_chooser.mojom",
"common/layout_test/layout_test_bluetooth_fake_adapter_setter.mojom",
"common/power_monitor_test.mojom",
]
public_deps = [
- "//mojo/common:common_custom_types",
+ "//mojo/public/mojom/base",
+ "//skia/public/interfaces",
"//ui/gfx/geometry/mojo",
"//url/mojom:url_mojom_gurl",
]
diff --git a/chromium/content/shell/android/BUILD.gn b/chromium/content/shell/android/BUILD.gn
index 277d949e3e2..89dd771d675 100644
--- a/chromium/content/shell/android/BUILD.gn
+++ b/chromium/content/shell/android/BUILD.gn
@@ -6,6 +6,7 @@ import("//base/android/jni_generator/jni_exception_list.gni")
import("//build/config/android/config.gni")
import("//build/config/android/rules.gni")
import("//third_party/icu/config.gni")
+import("//tools/v8_context_snapshot/v8_context_snapshot.gni")
content_shell_manifest =
"$target_gen_dir/content_shell_manifest/AndroidManifest.xml"
@@ -43,7 +44,6 @@ shared_library("libcontent_shell_content_view") {
if (is_component_build) {
deps += [
"//device/gamepad",
- "//device/sensors",
"//media/midi",
]
}
@@ -64,7 +64,6 @@ android_library("content_shell_java") {
":content_shell_java_resources",
":content_shell_manifest",
"//base:base_java",
- "//base:base_java_test_support",
"//components/content_view:content_view_java",
"//content/public/android:content_java",
"//device/geolocation:geolocation_java",
@@ -144,8 +143,12 @@ android_assets("content_shell_assets") {
deps = [
"//content/shell:pak",
"//third_party/icu:icu_assets",
- "//v8:v8_external_startup_data_assets",
]
+ if (use_v8_context_snapshot) {
+ deps += [ "//tools/v8_context_snapshot:v8_context_snapshot_assets" ]
+ } else {
+ deps += [ "//v8:v8_external_startup_data_assets" ]
+ }
}
android_apk("content_shell_apk") {
@@ -196,9 +199,9 @@ android_library("content_shell_test_java") {
instrumentation_test_apk("content_shell_test_apk") {
deps = [
+ "//base:base_java_test_support",
"//base:base_javatests",
"//content/public/android:content_javatests",
- "//device/sensors:javatests",
"//net/android:net_javatests",
"//third_party/android_support_test_runner:runner_java",
]
@@ -291,7 +294,6 @@ if (current_cpu != "x64") {
if (is_component_build) {
deps += [
"//device/gamepad",
- "//device/sensors",
"//media/midi",
]
}
diff --git a/chromium/content/shell/common/layout_test.mojom b/chromium/content/shell/common/layout_test.mojom
index 7a085601a83..edf929138da 100644
--- a/chromium/content/shell/common/layout_test.mojom
+++ b/chromium/content/shell/common/layout_test.mojom
@@ -4,19 +4,20 @@
module content.mojom;
-import "mojo/common/file_path.mojom";
+import "mojo/public/mojom/base/file_path.mojom";
+import "skia/public/interfaces/bitmap.mojom";
import "ui/gfx/geometry/mojo/geometry.mojom";
import "url/mojom/url.mojom";
struct ShellTestConfiguration {
// The current working directory.
- mojo.common.mojom.FilePath current_working_directory;
+ mojo_base.mojom.FilePath current_working_directory;
// The temporary directory of the system.
- mojo.common.mojom.FilePath temp_path;
+ mojo_base.mojom.FilePath temp_path;
// The build directory.
- mojo.common.mojom.FilePath build_directory;
+ mojo_base.mojom.FilePath build_directory;
// The URL of the current layout test.
url.mojom.Url test_url;
@@ -34,7 +35,22 @@ struct ShellTestConfiguration {
gfx.mojom.Size initial_size;
};
+// Results of a CaptureDump call.
+struct LayoutTestDump {
+ // Audio dump.
+ array<uint8>? audio;
+
+ // Layout dump.
+ string? layout;
+
+ // Image dump.
+ skia.mojom.Bitmap? pixels;
+ string actual_pixel_hash;
+};
+
interface LayoutTestControl {
+ CaptureDump() => (LayoutTestDump result);
+
// Dumps the frame's contents into a string.
DumpFrameLayout() => (string frame_layout_dump);
diff --git a/chromium/content/shell/common/layout_test/OWNERS b/chromium/content/shell/common/layout_test/OWNERS
index 42444bcd16d..ef88cc78b08 100644
--- a/chromium/content/shell/common/layout_test/OWNERS
+++ b/chromium/content/shell/common/layout_test/OWNERS
@@ -1,2 +1,4 @@
per-file *_messages*.h=set noparent
per-file *_messages*.h=file://ipc/SECURITY_OWNERS
+per-file *.mojom=set noparent
+per-file *.mojom=file://ipc/SECURITY_OWNERS
diff --git a/chromium/content/shell/common/layout_test/fake_bluetooth_chooser.mojom b/chromium/content/shell/common/layout_test/fake_bluetooth_chooser.mojom
new file mode 100644
index 00000000000..7caf2e2982d
--- /dev/null
+++ b/chromium/content/shell/common/layout_test/fake_bluetooth_chooser.mojom
@@ -0,0 +1,68 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+module content.mojom;
+
+// This interface is being developed to support Web Platform Tests for Web
+// Bluetooth.
+// https://docs.google.com/document/d/1Nhv_oVDCodd1pEH_jj9k8gF4rPGb_84VYaZ9IG8M_WY
+//
+// These interfaces are not intended to be used directly.
+// `web-bluetooth-test.js` makes the Fake Bluetooth interface easier to work
+// with.
+// * Calls are synchronous.
+// * IDs are cached.
+//
+// If another C++ client intends to use FakeBluetooth a C++ wrapper similar to
+// `web-bluetooth-test.js` should be created.
+//
+// The implementation details of FakeBluetoothChooser can be found in the Web
+// Bluetooth Test Scanning design document.
+// https://docs.google.com/document/d/1XFl_4ZAgO8ddM6U53A9AfUuZeWgJnlYD5wtbXqEpzeg
+
+// Indicates the types of Bluetooth chooser events.
+enum ChooserEventType {
+ CHOOSER_OPENED,
+ SCAN_STARTED,
+ DEVICE_UPDATE,
+ ADAPTER_REMOVED,
+ ADAPTER_DISABLED,
+ ADAPTER_ENABLED,
+ DISCOVERY_FAILED_TO_START,
+ DISCOVERING,
+ DISCOVERY_IDLE,
+ ADD_DEVICE,
+};
+
+// FakeBluetoothChooser allows clients to control the global state of the
+// Bluetooth chooser during a layout test.
+interface FakeBluetoothChooser {
+ // Waits until at least |num_of_events| have been recorded before returning
+ // |num_of_events| FakeBluetoothChooserEvents.
+ WaitForEvents(
+ uint32 num_of_events) => (array<FakeBluetoothChooserEvent> events);
+
+ // Simulates a user selecting the given |peripheral_address| in the Bluetooth
+ // chooser.
+ SelectPeripheral(string peripheral_address) => ();
+
+ // Calls the event handler function with the CANCELLED event.
+ Cancel() => ();
+
+ // Calls the event handler function with the RESCAN event.
+ Rescan() => ();
+};
+
+// FakeBluetoothChooserEvent describes the type of chooser event that has been
+// produced by the FakeBluetoothChooser.
+struct FakeBluetoothChooserEvent {
+ ChooserEventType type;
+
+ // Describes the origin the chooser is currently displaying.
+ // This field will be used by the |CHOOSER_OPENED| event type.
+ string? origin;
+
+ // Describes the MAC address of the Bluetooth device.
+ string? peripheral_address;
+};
diff --git a/chromium/content/shell/common/layout_test/layout_test_messages.h b/chromium/content/shell/common/layout_test/layout_test_messages.h
index 9eeb1e208af..8ea62b62aa2 100644
--- a/chromium/content/shell/common/layout_test/layout_test_messages.h
+++ b/chromium/content/shell/common/layout_test/layout_test_messages.h
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// Multiply-included file, no traditional include guard.
+// no-include-guard-because-multiply-included
#include <string>
#include <vector>
@@ -11,7 +11,7 @@
#include "content/public/common/common_param_traits_macros.h"
#include "ipc/ipc_message_macros.h"
#include "ipc/ipc_platform_file.h"
-#include "third_party/WebKit/public/platform/modules/permissions/permission_status.mojom.h"
+#include "third_party/blink/public/platform/modules/permissions/permission_status.mojom.h"
#include "url/gurl.h"
#include "url/ipc/url_param_traits.h"
@@ -36,6 +36,7 @@ IPC_MESSAGE_ROUTED2(LayoutTestHostMsg_SimulateWebNotificationClose,
IPC_MESSAGE_ROUTED1(LayoutTestHostMsg_BlockThirdPartyCookies,
bool /* block */)
IPC_MESSAGE_ROUTED0(LayoutTestHostMsg_DeleteAllCookies)
+IPC_MESSAGE_ROUTED0(LayoutTestHostMsg_DeleteAllCookiesForNetworkService)
IPC_MESSAGE_ROUTED4(LayoutTestHostMsg_SetPermission,
std::string /* name */,
blink::mojom::PermissionStatus /* status */,
@@ -43,6 +44,8 @@ IPC_MESSAGE_ROUTED4(LayoutTestHostMsg_SetPermission,
GURL /* embedding_origin */)
IPC_MESSAGE_ROUTED0(LayoutTestHostMsg_ResetPermissions)
IPC_MESSAGE_ROUTED0(LayoutTestHostMsg_InspectSecondaryWindow)
+IPC_MESSAGE_ROUTED1(LayoutTestHostMsg_InitiateCaptureDump,
+ bool /* should dump navigation history */)
// Notifies the browser that one of renderers has changed layout test runtime
// flags (i.e. has set dump_as_text).
diff --git a/chromium/content/shell/common/shell_content_client.cc b/chromium/content/shell/common/shell_content_client.cc
index 292ddce1892..c73f4985237 100644
--- a/chromium/content/shell/common/shell_content_client.cc
+++ b/chromium/content/shell/common/shell_content_client.cc
@@ -7,7 +7,6 @@
#include "base/command_line.h"
#include "base/strings/string_piece.h"
#include "base/strings/utf_string_conversions.h"
-#include "blink/public/resources/grit/blink_image_resources.h"
#include "build/build_config.h"
#include "content/app/resources/grit/content_resources.h"
#include "content/app/strings/grit/content_strings.h"
@@ -15,6 +14,7 @@
#include "content/public/common/user_agent.h"
#include "content/shell/common/shell_switches.h"
#include "content/shell/grit/shell_resources.h"
+#include "third_party/blink/public/resources/grit/blink_image_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
diff --git a/chromium/content/shell/common/shell_messages.h b/chromium/content/shell/common/shell_messages.h
index d5c550b6b88..be22d21a605 100644
--- a/chromium/content/shell/common/shell_messages.h
+++ b/chromium/content/shell/common/shell_messages.h
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// Multiply-included file, no traditional include guard.
+// no-include-guard-because-multiply-included
#include <string>
#include <vector>
@@ -36,28 +36,12 @@ IPC_MESSAGE_ROUTED0(ShellViewMsg_TryLeakDetection)
IPC_MESSAGE_ROUTED1(ShellViewMsg_LayoutDumpCompleted,
std::string /* completed/stitched layout dump */)
-// Send a text dump of the WebContents to the render host.
-IPC_MESSAGE_ROUTED2(ShellViewHostMsg_TextDump,
- std::string /* dump */,
- bool /* should_dump_history */)
-
// Asks the browser process to perform a layout dump spanning all the
// (potentially cross-process) frames. This goes through multiple
// LayoutTestControl.DumpFrameLayout calls and ends with sending of
// ShellViewMsg_LayoutDumpCompleted.
IPC_MESSAGE_ROUTED0(ShellViewHostMsg_InitiateLayoutDump)
-// Send an image dump of the WebContents to the render host.
-IPC_MESSAGE_ROUTED2(ShellViewHostMsg_ImageDump,
- std::string /* actual pixel hash */,
- SkBitmap /* image */)
-
-// Send an audio dump to the render host.
-IPC_MESSAGE_ROUTED1(ShellViewHostMsg_AudioDump,
- std::vector<unsigned char> /* audio data */)
-
-IPC_MESSAGE_ROUTED0(ShellViewHostMsg_TestFinished)
-
IPC_MESSAGE_ROUTED0(ShellViewHostMsg_ResetDone)
// WebTestDelegate related.
diff --git a/chromium/content/shell/common/shell_switches.cc b/chromium/content/shell/common/shell_switches.cc
index 5f56df2a962..d196d3c6b22 100644
--- a/chromium/content/shell/common/shell_switches.cc
+++ b/chromium/content/shell/common/shell_switches.cc
@@ -42,6 +42,10 @@ const char kContentShellHostWindowSize[] = "content-shell-host-window-size";
// Hides toolbar from content_shell's host window.
const char kContentShellHideToolbar[] = "content-shell-hide-toolbar";
+// Forces all navigations to go through the browser process (in a
+// non-PlzNavigate way).
+const char kContentShellAlwaysFork[] = "content-shell-always-fork";
+
std::vector<std::string> GetSideloadFontFiles() {
std::vector<std::string> files;
const base::CommandLine& command_line =
diff --git a/chromium/content/shell/common/shell_switches.h b/chromium/content/shell/common/shell_switches.h
index 06554041014..a06d39e9d55 100644
--- a/chromium/content/shell/common/shell_switches.h
+++ b/chromium/content/shell/common/shell_switches.h
@@ -20,6 +20,7 @@ extern const char kIsolateSitesForTesting[];
extern const char kRegisterFontFiles[];
extern const char kContentShellHostWindowSize[];
extern const char kContentShellHideToolbar[];
+extern const char kContentShellAlwaysFork[];
// Returns list of extra font files to be made accessible to the renderer.
std::vector<std::string> GetSideloadFontFiles();
diff --git a/chromium/content/shell/shell_resources.grd b/chromium/content/shell/shell_resources.grd
index 4b447a807c0..f1843a2630f 100644
--- a/chromium/content/shell/shell_resources.grd
+++ b/chromium/content/shell/shell_resources.grd
@@ -9,6 +9,7 @@
<translations />
<release seq="1">
<includes>
+ <include name="IDR_CONTENT_SHELL_BROKEN_CANVAS" file="resources/brokenCanvas.png" type="BINDATA" />
<include name="IDR_CONTENT_SHELL_DEVTOOLS_DISCOVERY_PAGE" file="resources/shell_devtools_discovery_page.html" type="BINDATA" />
<include name="IDR_CONTENT_SHELL_MISSING_IMAGE_GIF" file="resources/missingImage.gif" type="BINDATA" />
<include name="IDR_CONTENT_SHELL_MISSING_IMAGE_PNG" file="resources/missingImage.png" type="BINDATA" />
diff --git a/chromium/content/shell/test_runner/BUILD.gn b/chromium/content/shell/test_runner/BUILD.gn
index ca1e81aa149..1beed186f2d 100644
--- a/chromium/content/shell/test_runner/BUILD.gn
+++ b/chromium/content/shell/test_runner/BUILD.gn
@@ -104,15 +104,15 @@ component("test_runner") {
"//content/public/renderer",
"//content/test:test_runner_support",
"//device/gamepad/public/cpp:shared_with_blink",
- "//device/sensors/public/cpp:full",
"//gin",
"//gpu",
"//gpu/command_buffer/client:gles2_interface",
"//media/midi:mojo",
"//net",
+ "//services/device/public/cpp/generic_sensor:shared_with_blink",
"//services/device/public/mojom",
"//skia",
- "//third_party/WebKit/public:blink",
+ "//third_party/blink/public:blink",
"//ui/display",
"//ui/events:dom_keycode_converter",
"//ui/events:events_base",
@@ -147,12 +147,11 @@ if (!is_mac) {
}
if (use_x11) {
copy("copy_x11_fonts") {
- # TODO(sergeyu): Move these fonts to third_party/content_shell_fonts .
+ # TODO(sergeyu): Move these fonts to third_party/test_fonts .
visibility = [ ":*" ]
sources = [
"//third_party/gardiner_mod/GardinerModBug.ttf",
"//third_party/gardiner_mod/GardinerModCat.ttf",
- "resources/fonts/fonts.conf",
]
outputs = [
"$root_out_dir/{{source_file_part}}",
@@ -167,7 +166,7 @@ if (is_android || is_fuchsia) {
"resources/fonts/android_main_fonts.xml",
]
outputs = [
- "$root_out_dir/content_shell_test_fonts/{{source_file_part}}",
+ "$root_out_dir/test_fonts/{{source_file_part}}",
]
}
}
@@ -205,7 +204,7 @@ group("resources") {
data_deps += [ ":copy_android_fonts_config" ]
}
if (is_android || is_linux || is_fuchsia) {
- deps += [ "//third_party/content_shell_fonts" ]
- data_deps += [ "//third_party/content_shell_fonts" ]
+ deps += [ "//third_party/test_fonts" ]
+ data_deps += [ "//third_party/test_fonts" ]
}
}
diff --git a/chromium/content/test/BUILD.gn b/chromium/content/test/BUILD.gn
index f5db0538c50..f8a43bd3ff1 100644
--- a/chromium/content/test/BUILD.gn
+++ b/chromium/content/test/BUILD.gn
@@ -12,11 +12,12 @@ import("//build/config/ui.gni")
import("//media/media_options.gni")
import("//net/features.gni")
import("//mojo/public/tools/bindings/mojom.gni")
-import("//ppapi/features/features.gni")
+import("//ppapi/buildflags/buildflags.gni")
import("//services/catalog/public/tools/catalog.gni")
import("//services/service_manager/public/service_manifest.gni")
import("//testing/test.gni")
-import("//third_party/WebKit/public/public_features.gni")
+import("//third_party/blink/public/public_features.gni")
+import("//tools/v8_context_snapshot/v8_context_snapshot.gni")
import("//v8/gni/v8.gni")
# Use a static library here because many test binaries depend on this but don't
@@ -43,12 +44,6 @@ jumbo_static_library("test_support") {
"../browser/background_fetch/background_fetch_test_browser_context.h",
"../browser/background_fetch/mock_background_fetch_delegate.cc",
"../browser/background_fetch/mock_background_fetch_delegate.h",
- "../browser/download/mock_download_file.cc",
- "../browser/download/mock_download_file.h",
- "../browser/download/mock_download_item_impl.cc",
- "../browser/download/mock_download_item_impl.h",
- "../browser/download/mock_download_job.cc",
- "../browser/download/mock_download_job.h",
"../browser/media/session/mock_media_session_observer.cc",
"../browser/media/session/mock_media_session_observer.h",
"../browser/service_worker/embedded_worker_test_helper.cc",
@@ -92,8 +87,6 @@ jumbo_static_library("test_support") {
"../public/test/memory_coordinator_test_utils.h",
"../public/test/mock_browsing_data_remover_delegate.cc",
"../public/test/mock_browsing_data_remover_delegate.h",
- "../public/test/mock_download_item.cc",
- "../public/test/mock_download_item.h",
"../public/test/mock_download_manager.cc",
"../public/test/mock_download_manager.h",
"../public/test/mock_notification_observer.cc",
@@ -116,8 +109,8 @@ jumbo_static_library("test_support") {
"../public/test/ppapi_test_utils.h",
"../public/test/render_view_test.cc",
"../public/test/render_view_test.h",
- "../public/test/scoped_overscroll_mode.cc",
- "../public/test/scoped_overscroll_mode.h",
+ "../public/test/scoped_overscroll_modes.cc",
+ "../public/test/scoped_overscroll_modes.h",
"../public/test/service_worker_test_helpers.cc",
"../public/test/service_worker_test_helpers.h",
"../public/test/simple_url_loader_test_helper.cc",
@@ -172,6 +165,8 @@ jumbo_static_library("test_support") {
"../public/test/text_input_test_utils.cc",
"../public/test/text_input_test_utils.h",
"../public/test/text_input_test_utils_mac.mm",
+ "../public/test/throttling_url_loader_test_util.cc",
+ "../public/test/throttling_url_loader_test_util.h",
"../public/test/unittest_test_suite.cc",
"../public/test/unittest_test_suite.h",
"../public/test/url_loader_interceptor.cc",
@@ -199,10 +194,10 @@ jumbo_static_library("test_support") {
"fake_plugin_service.h",
"fake_renderer_compositor_frame_sink.cc",
"fake_renderer_compositor_frame_sink.h",
+ "gpu_browsertest_helpers.cc",
+ "gpu_browsertest_helpers.h",
"mock_background_sync_controller.cc",
"mock_background_sync_controller.h",
- "mock_google_streaming_server.cc",
- "mock_google_streaming_server.h",
"mock_keyboard.cc",
"mock_keyboard.h",
"mock_keyboard_driver_win.cc",
@@ -216,8 +211,6 @@ jumbo_static_library("test_support") {
"mock_render_widget_host_delegate.h",
"mock_ssl_host_state_delegate.cc",
"mock_ssl_host_state_delegate.h",
- "mock_webassociatedurlloader.cc",
- "mock_webassociatedurlloader.h",
"mock_webblob_registry_impl.cc",
"mock_webblob_registry_impl.h",
"mock_webclipboard_impl.cc",
@@ -280,6 +273,7 @@ jumbo_static_library("test_support") {
]
public_deps = [
+ "//components/download/public/common:test_support",
"//components/variations:test_support",
"//content/public/app:both",
"//content/public/browser",
@@ -287,8 +281,8 @@ jumbo_static_library("test_support") {
"//ipc",
"//media/mojo/clients",
"//media/mojo/interfaces",
- "//third_party/WebKit/public:blink",
- "//third_party/WebKit/public:test_support",
+ "//third_party/blink/public:blink",
+ "//third_party/blink/public:test_support",
"//tools/v8_context_snapshot",
]
deps = [
@@ -297,8 +291,7 @@ jumbo_static_library("test_support") {
"//cc:test_support",
"//cc/blink",
"//cc/ipc",
- "//components/download/public/common:public",
- "//components/leveldb/public/interfaces",
+ "//components/services/leveldb/public/interfaces",
"//components/viz/host",
"//components/viz/service",
"//content/app:both_for_content_tests",
@@ -322,10 +315,11 @@ jumbo_static_library("test_support") {
"//ipc:test_support",
"//media",
"//media/capture",
- "//media/capture/mojo:image_capture",
- "//mojo/edk/system",
+ "//media/capture/mojom:image_capture",
+ "//mojo/edk",
"//net:test_support",
"//services/device/public/mojom",
+ "//services/ui/public/cpp/gpu",
# TODO(jam): remove this by adding a public header for the NetworkContext
# public testing method.
@@ -369,11 +363,10 @@ jumbo_static_library("test_support") {
]
if (is_android) {
- sources -= [
- "mock_google_streaming_server.cc",
- "mock_google_streaming_server.h",
+ deps += [
+ "//content/shell:android_shell_descriptors",
+ "//mojo/android:libsystem_java",
]
- deps += [ "//mojo/android:libsystem_java" ]
}
if (enable_plugins) {
@@ -404,6 +397,8 @@ jumbo_static_library("test_support") {
"../renderer/media/webrtc/mock_peer_connection_impl.h",
"../renderer/media/webrtc/mock_web_rtc_peer_connection_handler_client.cc",
"../renderer/media/webrtc/mock_web_rtc_peer_connection_handler_client.h",
+ "../renderer/media/webrtc/test/webrtc_stats_report_obtainer.cc",
+ "../renderer/media/webrtc/test/webrtc_stats_report_obtainer.h",
]
deps += [
@@ -459,6 +454,7 @@ jumbo_static_library("test_support") {
"//content:sandbox_helper_win",
"//third_party/iaccessible2",
]
+ libs = [ "oleacc.lib" ]
}
if (is_android) {
@@ -538,6 +534,10 @@ jumbo_static_library("browsertest_support") {
deps += [ "//content/public/browser" ]
}
+ if (use_aura && toolkit_views) {
+ deps += [ "//ui/views" ]
+ }
+
configs += [ "//v8:external_startup_data" ]
}
@@ -605,8 +605,8 @@ static_library("layouttest_support") {
"//content/shell/test_runner:test_runner",
"//device/bluetooth",
"//device/gamepad/public/cpp:shared_with_blink",
- "//device/sensors/public/cpp:full",
"//gpu/ipc/service",
+ "//services/device/public/cpp/generic_sensor",
"//services/ui/public/cpp/gpu",
"//skia",
"//ui/accessibility:ax_enums_mojo",
@@ -637,7 +637,7 @@ static_library("test_runner_support") {
deps = [
"//content/public/renderer",
"//content/renderer:for_content_tests",
- "//third_party/WebKit/public:blink",
+ "//third_party/blink/public:blink",
]
}
@@ -689,6 +689,7 @@ test("content_browsertests") {
"../browser/accessibility/accessibility_action_browsertest.cc",
"../browser/accessibility/accessibility_ipc_error_browsertest.cc",
"../browser/accessibility/accessibility_mode_browsertest.cc",
+ "../browser/accessibility/aom_browsertest.cc",
"../browser/accessibility/cross_platform_accessibility_browsertest.cc",
"../browser/accessibility/dump_accessibility_browsertest_base.cc",
"../browser/accessibility/dump_accessibility_browsertest_base.h",
@@ -715,9 +716,11 @@ test("content_browsertests") {
"../browser/cross_site_transfer_browsertest.cc",
"../browser/database_browsertest.cc",
"../browser/device_sensors/device_sensor_browsertest.cc",
+ "../browser/devtools/devtools_video_consumer_browsertest.cc",
"../browser/devtools/protocol/devtools_protocol_browsertest.cc",
"../browser/devtools/render_frame_devtools_agent_host_browsertest.cc",
"../browser/devtools/site_per_process_devtools_browsertest.cc",
+ "../browser/do_not_track_browsertest.cc",
"../browser/dom_storage/dom_storage_browsertest.cc",
"../browser/download/download_browsertest.cc",
"../browser/download/drag_download_file_browsertest.cc",
@@ -735,13 +738,15 @@ test("content_browsertests") {
"../browser/frame_host/render_frame_host_impl_browsertest.cc",
"../browser/frame_host/render_frame_host_manager_browsertest.cc",
"../browser/frame_host/render_frame_message_filter_browsertest.cc",
- "../browser/generic_sensor_browsertest.cc",
+ "../browser/generic_sensor/generic_sensor_browsertest.cc",
"../browser/gpu/gpu_ipc_browsertests.cc",
"../browser/gpu/in_process_gpu_thread_browsertests.cc",
"../browser/indexed_db/indexed_db_browsertest.cc",
"../browser/indexed_db/mock_browsertest_indexed_db_class_factory.cc",
"../browser/indexed_db/mock_browsertest_indexed_db_class_factory.h",
"../browser/isolated_origin_browsertest.cc",
+ "../browser/keyboard_lock_browsertest.cc",
+ "../browser/loader/cors_file_origin_browsertest.cc",
"../browser/loader/cross_site_document_blocking_browsertest.cc",
"../browser/loader/prefetch_browsertest.cc",
"../browser/loader/reload_cache_control_browsertest.cc",
@@ -780,10 +785,11 @@ test("content_browsertests") {
"../browser/power_monitor_browsertest.cc",
"../browser/presentation/presentation_browsertest.cc",
"../browser/renderer_host/input/composited_scrolling_browsertest.cc",
+ "../browser/renderer_host/input/compositor_event_ack_browsertest.cc",
+ "../browser/renderer_host/input/fling_browsertest.cc",
"../browser/renderer_host/input/interaction_mq_dynamic_browsertest.cc",
"../browser/renderer_host/input/main_thread_event_queue_browsertest.cc",
"../browser/renderer_host/input/mouse_latency_browsertest.cc",
- "../browser/renderer_host/input/non_blocking_event_browsertest.cc",
"../browser/renderer_host/input/scroll_latency_browsertest.cc",
"../browser/renderer_host/input/touch_action_browsertest.cc",
"../browser/renderer_host/input/touch_input_browsertest.cc",
@@ -795,6 +801,7 @@ test("content_browsertests") {
"../browser/renderer_host/render_widget_host_browsertest.cc",
"../browser/renderer_host/render_widget_host_view_browsertest.cc",
"../browser/renderer_host/render_widget_host_view_child_frame_browsertest.cc",
+ "../browser/renderer_host/render_widget_host_view_mac_browsertest.mm",
"../browser/resource_loading_browsertest.cc",
"../browser/screen_orientation/screen_orientation_browsertest.cc",
"../browser/security_exploit_browsertest.cc",
@@ -814,8 +821,7 @@ test("content_browsertests") {
"../browser/tracing/memory_instrumentation_browsertest.cc",
"../browser/tracing/memory_tracing_browsertest.cc",
"../browser/tracing/tracing_controller_browsertest.cc",
- "../browser/utility_process_host_impl_browsertest.cc",
- "../browser/utility_process_mojo_client_browsertest.cc",
+ "../browser/utility_process_host_browsertest.cc",
"../browser/vibration_browsertest.cc",
"../browser/wake_lock/wake_lock_browsertest.cc",
"../browser/web_contents/opened_by_dom_browsertest.cc",
@@ -828,7 +834,6 @@ test("content_browsertests") {
"../renderer/accessibility/render_accessibility_impl_browsertest.cc",
"../renderer/blink_platform_audio_hardware_browsertest.cc",
"../renderer/gin_browsertest.cc",
- "../renderer/loader/site_isolation_stats_gatherer_browsertest.cc",
"../renderer/media/renderer_webmediaplayer_delegate_browsertest.cc",
"../renderer/mouse_lock_dispatcher_browsertest.cc",
"../renderer/render_frame_impl_browsertest.cc",
@@ -867,6 +872,7 @@ test("content_browsertests") {
"//components/discardable_memory/service",
"//components/network_session_configurator/common",
"//components/payments/mojom",
+ "//components/url_formatter:url_formatter",
"//components/viz/test:test_support",
"//content:resources",
"//content/app:both_for_content_tests",
@@ -885,22 +891,21 @@ test("content_browsertests") {
"//content/shell:pak",
"//content/test:test_support",
"//device/base/synchronization",
- "//device/sensors",
- "//device/sensors/public/cpp:full",
"//gin",
"//gpu",
"//gpu/ipc/host",
"//ipc",
"//ipc:test_support",
"//media:test_support",
- "//mojo/edk/system",
+ "//mojo/edk",
"//mojo/public/cpp/bindings",
"//net:test_support",
- "//ppapi/features",
+ "//ppapi/buildflags",
"//services/audio/public/cpp",
"//services/catalog:lib",
"//services/device/public/cpp:device_features",
"//services/device/public/cpp/generic_sensor",
+ "//services/device/public/cpp/test:test_support",
"//services/device/public/mojom",
"//services/device/public/mojom:generic_sensor",
"//services/network:test_support",
@@ -913,7 +918,7 @@ test("content_browsertests") {
"//storage/browser",
"//testing/gmock",
"//testing/gtest",
- "//third_party/WebKit/public:blink",
+ "//third_party/blink/public:blink",
"//third_party/leveldatabase",
"//third_party/libaom:av1_features",
"//third_party/mesa:osmesa",
@@ -981,18 +986,19 @@ test("content_browsertests") {
}
if (is_win) {
- sources += [ "../browser/accessibility/accessibility_win_browsertest.cc" ]
+ sources += [
+ "../browser/accessibility/accessibility_win_browsertest.cc",
+ "../browser/renderer_host/direct_manipulation_browsertest.cc",
+ ]
deps += [
"//content/app/strings",
"//net:net_resources",
- "//third_party/WebKit/public:resources",
+ "//third_party/blink/public:resources",
"//third_party/iaccessible2",
"//third_party/isimpledom",
]
- libs = [ "oleacc.lib" ]
-
if (symbol_level != 0) {
data += [ "$root_out_dir/content_browsertests.exe.pdb" ]
}
@@ -1016,9 +1022,11 @@ test("content_browsertests") {
"../browser/android/render_widget_host_connector_browsertest.cc",
"../browser/android/render_widget_host_connector_browsertest.h",
"../browser/media/session/audio_focus_delegate_android_browsertest.cc",
+ "../browser/renderer_host/compositor_impl_android_browsertest.cc",
"../shell/android/browsertests_apk/content_browser_tests_jni_onload.cc",
]
sources -= [
+ "../browser/keyboard_lock_browsertest.cc",
"../browser/media/session/audio_focus_delegate_default_browsertest.cc",
"../browser/network_service_restart_browsertest.cc",
"../browser/pointer_lock_browsertest.cc",
@@ -1043,13 +1051,17 @@ test("content_browsertests") {
"../browser/speech/speech_recognition_browsertest.cc",
"../browser/zoom_browsertest.cc",
]
+ deps += [ "//content/browser/speech/proto" ]
}
# HID support is not available without udev.
is_linux_without_udev = is_linux && !use_udev
if (!is_linux_without_udev && !is_android) {
sources += [ "../browser/webauth/webauth_browsertest.cc" ]
- deps += [ "//device/fido:test_support" ]
+ deps += [
+ "//device/fido:mocks",
+ "//device/fido:test_support",
+ ]
}
if (is_mac) {
@@ -1099,13 +1111,14 @@ test("content_browsertests") {
"../browser/webrtc/webrtc_webcam_browsertest.h",
]
deps += [
- "//content/public/common:features",
+ "//content/public/common:buildflags",
"//testing/perf",
]
}
if (enable_plugins) {
sources += [
+ "../browser/plugin_service_impl_browsertest.cc",
"../renderer/pepper/fake_pepper_plugin_instance.cc",
"../renderer/pepper/fake_pepper_plugin_instance.h",
"../renderer/pepper/mock_renderer_ppapi_host.cc",
@@ -1252,21 +1265,15 @@ test("content_unittests") {
"../browser/compositor/software_browser_compositor_output_surface_unittest.cc",
"../browser/devtools/devtools_http_handler_unittest.cc",
"../browser/devtools/devtools_manager_unittest.cc",
+ "../browser/devtools/devtools_video_consumer_unittest.cc",
"../browser/devtools/protocol/tracing_handler_unittest.cc",
"../browser/dom_storage/dom_storage_area_unittest.cc",
"../browser/dom_storage/dom_storage_context_impl_unittest.cc",
"../browser/dom_storage/dom_storage_database_unittest.cc",
"../browser/dom_storage/local_storage_context_mojo_unittest.cc",
"../browser/dom_storage/session_storage_database_unittest.cc",
- "../browser/download/base_file_unittest.cc",
- "../browser/download/base_file_win_unittest.cc",
- "../browser/download/download_file_unittest.cc",
- "../browser/download/download_item_impl_unittest.cc",
- "../browser/download/download_job_unittest.cc",
"../browser/download/download_manager_impl_unittest.cc",
"../browser/download/download_request_core_unittest.cc",
- "../browser/download/parallel_download_job_unittest.cc",
- "../browser/download/parallel_download_utils_unittest.cc",
"../browser/download/save_package_unittest.cc",
"../browser/fileapi/browser_file_system_helper_unittest.cc",
"../browser/fileapi/file_system_operation_runner_unittest.cc",
@@ -1388,6 +1395,7 @@ test("content_unittests") {
"../browser/renderer_host/compositor_resize_lock_unittest.cc",
"../browser/renderer_host/cursor_manager_unittest.cc",
"../browser/renderer_host/dwrite_font_proxy_message_filter_win_unittest.cc",
+ "../browser/renderer_host/frame_token_message_queue_unittest.cc",
"../browser/renderer_host/input/fling_controller_unittest.cc",
"../browser/renderer_host/input/gesture_event_queue_unittest.cc",
"../browser/renderer_host/input/input_router_impl_unittest.cc",
@@ -1480,7 +1488,6 @@ test("content_unittests") {
"../browser/shared_worker/shared_worker_instance_unittest.cc",
"../browser/shared_worker/shared_worker_service_impl_unittest.cc",
"../browser/site_instance_impl_unittest.cc",
- "../browser/site_isolation_policy_unittest.cc",
"../browser/startup_task_runner_unittest.cc",
"../browser/storage_partition_impl_map_unittest.cc",
"../browser/storage_partition_impl_unittest.cc",
@@ -1489,6 +1496,7 @@ test("content_unittests") {
"../browser/tracing/background_memory_tracing_observer_unittest.cc",
"../browser/tracing/background_tracing_config_unittest.cc",
"../browser/tracing/tracing_ui_unittest.cc",
+ "../browser/web_contents/aura/gesture_nav_simple_unittest.cc",
"../browser/web_contents/aura/overscroll_navigation_overlay_unittest.cc",
"../browser/web_contents/aura/overscroll_window_animation_unittest.cc",
"../browser/web_contents/aura/overscroll_window_delegate_unittest.cc",
@@ -1500,7 +1508,10 @@ test("content_unittests") {
"../browser/web_contents/web_drag_dest_mac_unittest.mm",
"../browser/web_contents/web_drag_source_mac_unittest.mm",
"../browser/web_package/signed_exchange_cert_fetcher_unittest.cc",
+ "../browser/web_package/signed_exchange_certificate_chain_unittest.cc",
+ "../browser/web_package/signed_exchange_handler_unittest.cc",
"../browser/web_package/signed_exchange_header_parser_unittest.cc",
+ "../browser/web_package/signed_exchange_header_unittest.cc",
"../browser/web_package/signed_exchange_signature_verifier_unittest.cc",
"../browser/websockets/websocket_manager_unittest.cc",
"../browser/webui/url_data_manager_backend_unittest.cc",
@@ -1520,7 +1531,6 @@ test("content_unittests") {
"../common/content_security_policy/csp_source_list_unittest.cc",
"../common/content_security_policy/csp_source_unittest.cc",
"../common/content_switches_internal_unittest.cc",
- "../common/cross_site_document_classifier_unittest.cc",
"../common/cursors/webcursor_unittest.cc",
"../common/dom_storage/dom_storage_map_unittest.cc",
"../common/indexed_db/indexed_db_key_unittest.cc",
@@ -1530,6 +1540,7 @@ test("content_unittests") {
"../common/input/touch_event_stream_validator_unittest.cc",
"../common/inter_process_time_ticks_converter_unittest.cc",
"../common/mac/attributed_string_coder_unittest.mm",
+ "../common/manifest_share_target_util_unittest.cc",
"../common/manifest_util_unittest.cc",
"../common/media/media_devices_unittest.cc",
"../common/notifications/notification_struct_traits_unittest.cc",
@@ -1548,6 +1559,7 @@ test("content_unittests") {
"../common/throttling_url_loader_unittest.cc",
"../common/unique_name_helper_unittest.cc",
"../common/webplugininfo_unittest.cc",
+ "../public/browser/site_isolation_policy_unittest.cc",
# TODO(jam): move these network/ tests to services/network.
"../public/common/drop_data_unittest.cc",
@@ -1561,8 +1573,6 @@ test("content_unittests") {
"../renderer/child_frame_compositing_helper_unittest.cc",
"../renderer/device_sensors/device_motion_event_pump_unittest.cc",
"../renderer/device_sensors/device_orientation_event_pump_unittest.cc",
- "../renderer/device_sensors/fake_sensor_and_provider.cc",
- "../renderer/device_sensors/fake_sensor_and_provider.h",
"../renderer/dom_storage/dom_storage_cached_area_unittest.cc",
"../renderer/dom_storage/local_storage_cached_area_unittest.cc",
"../renderer/dom_storage/local_storage_cached_areas_unittest.cc",
@@ -1581,7 +1591,6 @@ test("content_unittests") {
"../renderer/input/main_thread_event_queue_unittest.cc",
"../renderer/loader/resource_dispatcher_unittest.cc",
"../renderer/loader/shared_memory_data_consumer_handle_unittest.cc",
- "../renderer/loader/site_isolation_stats_gatherer_unittest.cc",
"../renderer/loader/test_request_peer.cc",
"../renderer/loader/test_request_peer.h",
"../renderer/loader/url_loader_client_impl_unittest.cc",
@@ -1656,12 +1665,13 @@ test("content_unittests") {
"//cc",
"//cc:test_support",
"//cc/ipc",
- "//components/leveldb/public/cpp",
+ "//components/cbor",
"//components/network_session_configurator/browser",
"//components/network_session_configurator/common",
"//components/offline_pages/buildflags",
"//components/payments/mojom",
"//components/rappor:test_support",
+ "//components/services/leveldb/public/cpp",
"//components/ukm:test_support",
"//components/viz/client",
"//components/viz/common",
@@ -1691,7 +1701,6 @@ test("content_unittests") {
"//device/gamepad:test_helpers",
"//device/gamepad/public/cpp:shared_with_blink",
"//device/geolocation/public/cpp:test_support",
- "//device/sensors/public/cpp:shared_with_blink",
"//gin",
"//gpu",
"//gpu:test_support",
@@ -1703,16 +1712,17 @@ test("content_unittests") {
"//media/capture",
"//media/midi:midi",
"//media/midi:mojo",
- "//mojo/edk/system",
+ "//mojo/edk",
"//mojo/public/cpp/bindings",
"//mojo/public/cpp/test_support:test_utils",
"//net:extras",
"//net:test_support",
+ "//ppapi/buildflags",
"//ppapi/c",
- "//ppapi/features",
"//printing",
"//services/catalog:lib",
"//services/device/public/cpp/generic_sensor",
+ "//services/device/public/cpp/test:test_support",
"//services/device/public/mojom",
"//services/file:lib",
"//services/file/public/mojom",
@@ -1733,7 +1743,7 @@ test("content_unittests") {
"//storage/common",
"//testing/gmock",
"//testing/gtest",
- "//third_party/WebKit/public:blink",
+ "//third_party/blink/public:blink",
"//third_party/icu",
"//third_party/leveldatabase",
"//third_party/metrics_proto",
@@ -1758,12 +1768,12 @@ test("content_unittests") {
]
data_deps = [
- "//components/filesystem:filesystem",
+ "//components/services/filesystem:filesystem",
"//testing/buildbot/filters:content_unittests_filters",
"//third_party/mesa:osmesa",
]
- if (is_posix && !is_fuchsia) {
+ if (is_posix) {
sources += [ "../browser/posix_file_descriptor_info_impl_unittest.cc" ]
}
@@ -1812,7 +1822,7 @@ test("content_unittests") {
"../browser/renderer_host/p2p/socket_host_test_utils.cc",
"../browser/renderer_host/p2p/socket_host_test_utils.h",
"../browser/renderer_host/p2p/socket_host_udp_unittest.cc",
- "../browser/webrtc/webrtc_event_log_manager_unittest.cc",
+ "../browser/webrtc/webrtc_internals_message_handler_unittest.cc",
"../browser/webrtc/webrtc_internals_unittest.cc",
"../renderer/media/stream/media_stream_audio_processor_unittest.cc",
"../renderer/media/stream/media_stream_audio_unittest.cc",
@@ -1845,6 +1855,8 @@ test("content_unittests") {
"../renderer/media/webrtc/peer_connection_tracker_unittest.cc",
"../renderer/media/webrtc/rtc_data_channel_handler_unittest.cc",
"../renderer/media/webrtc/rtc_peer_connection_handler_unittest.cc",
+ "../renderer/media/webrtc/rtc_rtp_parameters_unittest.cc",
+ "../renderer/media/webrtc/rtc_rtp_receiver_unittest.cc",
"../renderer/media/webrtc/rtc_rtp_sender_unittest.cc",
"../renderer/media/webrtc/rtc_stats_unittest.cc",
"../renderer/media/webrtc/rtc_video_decoder_unittest.cc",
@@ -1977,9 +1989,14 @@ test("content_unittests") {
"//media/capture/content/android",
"//media/capture/content/android:screen_capture_java",
"//ui/android:android",
- "//v8:v8_external_startup_data_assets",
]
+ if (use_v8_context_snapshot) {
+ deps += [ "//tools/v8_context_snapshot:v8_context_snapshot_assets" ]
+ } else {
+ deps += [ "//v8:v8_external_startup_data_assets" ]
+ }
+
defines += [ "APPCACHE_USE_SIMPLE_CACHE" ]
} else {
# Non-Android.
@@ -2010,6 +2027,7 @@ test("content_unittests") {
} else {
sources -= [
"../browser/renderer_host/render_widget_host_view_aura_unittest.cc",
+ "../browser/web_contents/aura/gesture_nav_simple_unittest.cc",
"../browser/web_contents/aura/overscroll_navigation_overlay_unittest.cc",
"../browser/web_contents/aura/overscroll_window_animation_unittest.cc",
"../browser/web_contents/aura/overscroll_window_delegate_unittest.cc",
diff --git a/chromium/content/test/fuzzer/BUILD.gn b/chromium/content/test/fuzzer/BUILD.gn
index ff0becdaff1..7ca98f71ecb 100644
--- a/chromium/content/test/fuzzer/BUILD.gn
+++ b/chromium/content/test/fuzzer/BUILD.gn
@@ -33,7 +33,7 @@ fuzzer_test("origin_trial_token_fuzzer") {
"origin_trial_token_fuzzer.cc",
]
deps = [
- ":fuzzer_support",
+ "//content/test:test_support",
]
dict =
"//content/test/data/fuzzer_dictionaries/origin_trial_token_fuzzer.dict"
@@ -45,8 +45,7 @@ fuzzer_test("origin_manifest_parser_fuzzer") {
"origin_manifest_parser_fuzzer.cc",
]
deps = [
- ":fuzzer_support",
- "//content/browser:for_content_tests",
+ "//content/test:test_support",
]
dict = "//content/test/data/fuzzer_dictionaries/origin_manifest_parser_fuzzer.dict"
seed_corpus = "//content/test/data/fuzzer_corpus/origin_manifest_parser_data/"
@@ -76,9 +75,7 @@ fuzzer_test("clear_site_data_fuzzer") {
"clear_site_data_fuzzer.cc",
]
deps = [
- ":fuzzer_support",
- "//base",
- "//content/browser:for_content_tests",
+ "//content/test:test_support",
]
seed_corpus = "//content/test/data/fuzzer_corpus/clear_site_data/"
}
@@ -102,25 +99,69 @@ proto_library("html_tree_proto") {
testonly = true
}
+fuzzer_test("signed_exchange_header_fuzzer") {
+ sources = [
+ "signed_exchange_header_fuzzer.cc",
+ ]
+ deps = [
+ "//base:i18n",
+ "//content/test:test_support",
+ ]
+ seed_corpus = "//content/test/data/htxg/"
+}
+
fuzzer_test("signed_exchange_header_parser_fuzzer") {
sources = [
"signed_exchange_header_parser_fuzzer.cc",
]
deps = [
- ":fuzzer_support",
- "//content/browser:for_content_tests",
+ "//base:i18n",
+ "//content/test:test_support",
]
seed_corpus =
"//content/test/data/fuzzer_corpus/signed_exchange_header_parser_data/"
}
-fuzzer_test("signed_exchange_cert_fetcher_parser_fuzzer") {
+fuzzer_test("signed_exchange_certificate_chain_fuzzer") {
sources = [
- "signed_exchange_cert_fetcher_parser_fuzzer.cc",
+ "../../browser/web_package/signed_exchange_certificate_chain_fuzzer.cc",
]
deps = [
- ":fuzzer_support",
+ "//content/test:test_support",
+ ]
+ seed_corpus = "//content/test/data/fuzzer_corpus/signed_exchange_certificate_chain_data/"
+}
+
+fuzzer_test("appcache_manifest_parser_fuzzer") {
+ sources = [
+ "appcache_manifest_parser_fuzzer.cc",
+ ]
+ deps = [
+ "//base:i18n",
+ "//content/test:test_support",
+ ]
+ dict = "//content/test/data/fuzzer_dictionaries/appcache_manifest_parser_fuzzer.dict"
+ seed_corpus =
+ "//third_party/WebKit/LayoutTests/http/tests/appcache/resources/"
+}
+
+fuzzer_test("merkle_integrity_source_stream_fuzzer") {
+ sources = [
+ "merkle_integrity_source_stream_fuzzer.cc",
+ ]
+
+ # This fuzzer depends on net::FuzzedSourceStream, in net_fuzzer_test_support,
+ # but both it and //content:test_support set up similar globals. As
+ # MerkleIntegritySourceStream does not depend on anything in //content and
+ # will ultimately live in //net, use the //net one instead of the //content
+ # one.
+ deps = [
"//content/browser:for_content_tests",
+ "//content/renderer:for_content_tests",
+ "//content/shell:content_shell_lib",
+ "//content/test:test_support",
+ "//net:net_fuzzer_test_support",
+ "//net:test_support",
]
- seed_corpus = "//content/test/data/fuzzer_corpus/signed_exchange_cert_fetcher_parser_data/"
+ dict = "//content/test/data/fuzzer_dictionaries/merkle_integrity_source_stream_fuzzer.dict"
}
diff --git a/chromium/content/utility/BUILD.gn b/chromium/content/utility/BUILD.gn
index 1225b06bceb..1385f37f994 100644
--- a/chromium/content/utility/BUILD.gn
+++ b/chromium/content/utility/BUILD.gn
@@ -19,6 +19,8 @@ jumbo_source_set("utility") {
"in_process_utility_thread.h",
"utility_blink_platform_impl.cc",
"utility_blink_platform_impl.h",
+ "utility_blink_platform_with_sandbox_support_impl.cc",
+ "utility_blink_platform_with_sandbox_support_impl.h",
"utility_main.cc",
"utility_service_factory.cc",
"utility_service_factory.h",
@@ -34,7 +36,7 @@ jumbo_source_set("utility") {
"//content/child",
"//content/public/child:child_sources",
"//content/public/common:common_sources",
- "//media:media_features",
+ "//media:media_buildflags",
"//mojo/common",
"//mojo/public/cpp/bindings",
"//net:net_with_v8",
@@ -50,8 +52,8 @@ jumbo_source_set("utility") {
"//services/video_capture:lib",
"//services/video_capture/public/mojom:constants",
"//services/viz:lib",
- "//third_party/WebKit/public:blink_headers",
- "//third_party/WebKit/public:mojo_bindings",
+ "//third_party/blink/public:blink_headers",
+ "//third_party/blink/public:mojo_bindings",
"//url",
]
@@ -60,7 +62,7 @@ jumbo_source_set("utility") {
if (enable_library_cdms) {
deps += [
"//media",
- "//media/mojo:features",
+ "//media/mojo:buildflags",
"//media/mojo/interfaces:constants",
"//media/mojo/services",
]
diff --git a/chromium/content/utility/utility_blink_platform_impl.cc b/chromium/content/utility/utility_blink_platform_impl.cc
index 31e14731308..f2074986725 100644
--- a/chromium/content/utility/utility_blink_platform_impl.cc
+++ b/chromium/content/utility/utility_blink_platform_impl.cc
@@ -4,7 +4,7 @@
#include "content/utility/utility_blink_platform_impl.h"
-#include "third_party/WebKit/public/platform/scheduler/child/webthread_base.h"
+#include "third_party/blink/public/platform/scheduler/child/webthread_base.h"
namespace content {
diff --git a/chromium/content/utility/utility_blink_platform_with_sandbox_support_impl.cc b/chromium/content/utility/utility_blink_platform_with_sandbox_support_impl.cc
new file mode 100644
index 00000000000..3a06b3d4ddb
--- /dev/null
+++ b/chromium/content/utility/utility_blink_platform_with_sandbox_support_impl.cc
@@ -0,0 +1,120 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/utility/utility_blink_platform_with_sandbox_support_impl.h"
+
+#include "build/build_config.h"
+
+#if defined(OS_MACOSX)
+#include "base/mac/foundation_util.h"
+#include "content/child/child_process_sandbox_support_impl_mac.h"
+#include "third_party/blink/public/platform/mac/web_sandbox_support.h"
+#elif defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_FUCHSIA)
+#include "base/synchronization/lock.h"
+#include "content/child/child_process_sandbox_support_impl_linux.h"
+#include "third_party/blink/public/platform/linux/web_fallback_font.h"
+#include "third_party/blink/public/platform/linux/web_sandbox_support.h"
+#endif
+
+namespace blink {
+class WebSandboxSupport;
+struct WebFallbackFont;
+struct WebFontRenderStyle;
+} // namespace blink
+
+namespace content {
+
+#if defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_FUCHSIA)
+
+class UtilityBlinkPlatformWithSandboxSupportImpl::SandboxSupport
+ : public blink::WebSandboxSupport {
+ public:
+ ~SandboxSupport() override {}
+
+#if defined(OS_MACOSX)
+ bool LoadFont(CTFontRef srcFont, CGFontRef* out, uint32_t* fontID) override;
+#else
+ void GetFallbackFontForCharacter(
+ blink::WebUChar32 character,
+ const char* preferred_locale,
+ blink::WebFallbackFont* fallbackFont) override;
+ void GetWebFontRenderStyleForStrike(const char* family,
+ int sizeAndStyle,
+ blink::WebFontRenderStyle* out) override;
+
+ private:
+ // WebKit likes to ask us for the correct font family to use for a set of
+ // unicode code points. It needs this information frequently so we cache it
+ // here.
+ base::Lock unicode_font_families_mutex_;
+ // Maps unicode chars to their fallback fonts.
+ std::map<int32_t, blink::WebFallbackFont> unicode_font_families_;
+#endif // defined(OS_MACOSX)
+};
+
+#endif // defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_FUCHSIA)
+
+UtilityBlinkPlatformWithSandboxSupportImpl::
+ UtilityBlinkPlatformWithSandboxSupportImpl() {
+#if defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_FUCHSIA)
+ sandbox_support_ = std::make_unique<SandboxSupport>();
+#endif
+}
+
+UtilityBlinkPlatformWithSandboxSupportImpl::
+ ~UtilityBlinkPlatformWithSandboxSupportImpl() {}
+
+blink::WebSandboxSupport*
+UtilityBlinkPlatformWithSandboxSupportImpl::GetSandboxSupport() {
+#if defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_FUCHSIA)
+ return sandbox_support_.get();
+#else
+ return nullptr;
+#endif
+}
+
+#if defined(OS_MACOSX)
+
+bool UtilityBlinkPlatformWithSandboxSupportImpl::SandboxSupport::LoadFont(
+ CTFontRef src_font,
+ CGFontRef* out,
+ uint32_t* font_id) {
+ return content::LoadFont(src_font, out, font_id);
+}
+
+#elif defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_FUCHSIA)
+
+void UtilityBlinkPlatformWithSandboxSupportImpl::SandboxSupport::
+ GetFallbackFontForCharacter(blink::WebUChar32 character,
+ const char* preferred_locale,
+ blink::WebFallbackFont* fallback_font) {
+ base::AutoLock lock(unicode_font_families_mutex_);
+ const std::map<int32_t, blink::WebFallbackFont>::const_iterator iter =
+ unicode_font_families_.find(character);
+ if (iter != unicode_font_families_.end()) {
+ fallback_font->name = iter->second.name;
+ fallback_font->filename = iter->second.filename;
+ fallback_font->fontconfig_interface_id =
+ iter->second.fontconfig_interface_id;
+ fallback_font->ttc_index = iter->second.ttc_index;
+ fallback_font->is_bold = iter->second.is_bold;
+ fallback_font->is_italic = iter->second.is_italic;
+ return;
+ }
+
+ content::GetFallbackFontForCharacter(character, preferred_locale,
+ fallback_font);
+ unicode_font_families_.emplace(character, *fallback_font);
+}
+
+void UtilityBlinkPlatformWithSandboxSupportImpl::SandboxSupport::
+ GetWebFontRenderStyleForStrike(const char* family,
+ int size_and_style,
+ blink::WebFontRenderStyle* out) {
+ GetRenderStyleForStrike(family, size_and_style, out);
+}
+
+#endif
+
+} // namespace content
diff --git a/chromium/content/utility/utility_blink_platform_with_sandbox_support_impl.h b/chromium/content/utility/utility_blink_platform_with_sandbox_support_impl.h
new file mode 100644
index 00000000000..db4236a6c97
--- /dev/null
+++ b/chromium/content/utility/utility_blink_platform_with_sandbox_support_impl.h
@@ -0,0 +1,42 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CONTENT_UTILITY_UTILITY_BLINK_PLATFORM_WITH_SANDBOX_SUPPORT_IMPL_H_
+#define CONTENT_UTILITY_UTILITY_BLINK_PLATFORM_WITH_SANDBOX_SUPPORT_IMPL_H_
+
+#include <memory>
+
+#include "base/macros.h"
+#include "build/build_config.h"
+#include "content/utility/utility_blink_platform_impl.h"
+
+namespace blink {
+class WebSandboxSupport;
+}
+
+namespace content {
+
+// This class extends from UtilityBlinkPlatformImpl with added blink web
+// sandbox support.
+class UtilityBlinkPlatformWithSandboxSupportImpl
+ : public UtilityBlinkPlatformImpl {
+ public:
+ UtilityBlinkPlatformWithSandboxSupportImpl();
+ ~UtilityBlinkPlatformWithSandboxSupportImpl() override;
+
+ // BlinkPlatformImpl
+ blink::WebSandboxSupport* GetSandboxSupport() override;
+
+ private:
+#if defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_FUCHSIA)
+ class SandboxSupport;
+ std::unique_ptr<SandboxSupport> sandbox_support_;
+#endif
+
+ DISALLOW_COPY_AND_ASSIGN(UtilityBlinkPlatformWithSandboxSupportImpl);
+};
+
+} // namespace content
+
+#endif // CONTENT_UTILITY_UTILITY_BLINK_PLATFORM_WITH_SANDBOX_SUPPORT_IMPL_H_
diff --git a/chromium/content/utility/utility_service_factory.cc b/chromium/content/utility/utility_service_factory.cc
index 3641e79c965..290428ee04e 100644
--- a/chromium/content/utility/utility_service_factory.cc
+++ b/chromium/content/utility/utility_service_factory.cc
@@ -18,7 +18,7 @@
#include "content/public/utility/content_utility_client.h"
#include "content/public/utility/utility_thread.h"
#include "content/utility/utility_thread_impl.h"
-#include "media/media_features.h"
+#include "media/media_buildflags.h"
#include "services/data_decoder/data_decoder_service.h"
#include "services/data_decoder/public/mojom/constants.mojom.h"
#include "services/network/network_service.h"
diff --git a/chromium/content/utility/utility_thread_impl.cc b/chromium/content/utility/utility_thread_impl.cc
index 67bab57e113..767ee872b5e 100644
--- a/chromium/content/utility/utility_thread_impl.cc
+++ b/chromium/content/utility/utility_thread_impl.cc
@@ -14,6 +14,7 @@
#include "content/public/common/simple_connection_filter.h"
#include "content/public/utility/content_utility_client.h"
#include "content/utility/utility_blink_platform_impl.h"
+#include "content/utility/utility_blink_platform_with_sandbox_support_impl.h"
#include "content/utility/utility_service_factory.h"
#include "ipc/ipc_sync_channel.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
@@ -25,6 +26,12 @@
#include "net/proxy_resolution/proxy_resolver_v8.h"
#endif
+#if defined(OS_MACOSX)
+#include "content/common/font_loader_mac.mojom.h"
+#include "content/public/common/service_names.mojom.h"
+#include "services/service_manager/public/cpp/connector.h"
+#endif
+
namespace content {
#if !defined(OS_ANDROID)
@@ -81,14 +88,24 @@ void UtilityThreadImpl::ReleaseProcess() {
return;
}
- // Close the channel to cause the UtilityProcessHostImpl to be deleted. We
- // need to take a different code path than the multi-process case because
- // that case depends on the child process going away to close the channel,
- // but that can't happen when we're in single process mode.
+ // Close the channel to cause the UtilityProcessHost to be deleted. We need to
+ // take a different code path than the multi-process case because that case
+ // depends on the child process going away to close the channel, but that
+ // can't happen when we're in single process mode.
channel()->Close();
}
void UtilityThreadImpl::EnsureBlinkInitialized() {
+ EnsureBlinkInitializedInternal(/*sandbox_support=*/false);
+}
+
+#if defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_FUCHSIA)
+void UtilityThreadImpl::EnsureBlinkInitializedWithSandboxSupport() {
+ EnsureBlinkInitializedInternal(/*sandbox_support=*/true);
+}
+#endif
+
+void UtilityThreadImpl::EnsureBlinkInitializedInternal(bool sandbox_support) {
if (blink_platform_impl_)
return;
@@ -99,7 +116,10 @@ void UtilityThreadImpl::EnsureBlinkInitialized() {
if (IsInBrowserProcess())
return;
- blink_platform_impl_.reset(new UtilityBlinkPlatformImpl);
+ blink_platform_impl_ =
+ sandbox_support
+ ? std::make_unique<UtilityBlinkPlatformWithSandboxSupportImpl>()
+ : std::make_unique<UtilityBlinkPlatformImpl>();
blink::Platform::Initialize(blink_platform_impl_.get());
}
@@ -137,6 +157,21 @@ bool UtilityThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
return GetContentClient()->utility()->OnMessageReceived(msg);
}
+#if defined(OS_MACOSX)
+mojom::FontLoaderMac* UtilityThreadImpl::GetFontLoaderMac() {
+ DCHECK(font_loader_mac_ptr_);
+ return font_loader_mac_ptr_.get();
+}
+
+void UtilityThreadImpl::InitializeFontLoaderMac(
+ service_manager::Connector* connector) {
+ if (!font_loader_mac_ptr_) {
+ connector->BindInterface(content::mojom::kBrowserServiceName,
+ &font_loader_mac_ptr_);
+ }
+}
+#endif
+
void UtilityThreadImpl::BindServiceFactoryRequest(
service_manager::mojom::ServiceFactoryRequest request) {
DCHECK(service_factory_);
diff --git a/chromium/content/utility/utility_thread_impl.h b/chromium/content/utility/utility_thread_impl.h
index 54a07b05b94..618459cc875 100644
--- a/chromium/content/utility/utility_thread_impl.h
+++ b/chromium/content/utility/utility_thread_impl.h
@@ -9,6 +9,7 @@
#include "base/compiler_specific.h"
#include "base/macros.h"
+#include "build/build_config.h"
#include "content/child/child_thread_impl.h"
#include "content/public/utility/utility_thread.h"
#include "mojo/public/cpp/bindings/binding_set.h"
@@ -18,6 +19,10 @@ namespace content {
class UtilityBlinkPlatformImpl;
class UtilityServiceFactory;
+namespace mojom {
+class FontLoaderMac;
+}
+
#if defined(COMPILER_MSVC)
// See explanation for other RenderViewHostImpl which is the same issue.
#pragma warning(push)
@@ -37,12 +42,22 @@ class UtilityThreadImpl : public UtilityThread,
// UtilityThread:
void ReleaseProcess() override;
void EnsureBlinkInitialized() override;
+#if defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_FUCHSIA)
+ void EnsureBlinkInitializedWithSandboxSupport() override;
+#endif
+#if defined(OS_MACOSX)
+ void InitializeFontLoaderMac(service_manager::Connector* connector) override;
+#endif
private:
+ void EnsureBlinkInitializedInternal(bool sandbox_support);
void Init();
- // ChildThread:
+ // ChildThreadImpl:
bool OnControlMessageReceived(const IPC::Message& msg) override;
+#if defined(OS_MACOSX)
+ mojom::FontLoaderMac* GetFontLoaderMac() override;
+#endif
// Binds requests to our |service factory_|.
void BindServiceFactoryRequest(
@@ -59,6 +74,10 @@ class UtilityThreadImpl : public UtilityThread,
mojo::BindingSet<service_manager::mojom::ServiceFactory>
service_factory_bindings_;
+#if defined(OS_MACOSX)
+ content::mojom::FontLoaderMacPtr font_loader_mac_ptr_;
+#endif
+
DISALLOW_COPY_AND_ASSIGN(UtilityThreadImpl);
};
diff --git a/chromium/content/zygote/zygote_main_linux.cc b/chromium/content/zygote/zygote_main_linux.cc
index 4e424bdf621..12447a0daa2 100644
--- a/chromium/content/zygote/zygote_main_linux.cc
+++ b/chromium/content/zygote/zygote_main_linux.cc
@@ -23,7 +23,6 @@
#include "base/compiler_specific.h"
#include "base/memory/protected_memory.h"
#include "base/memory/protected_memory_cfi.h"
-#include "base/native_library.h"
#include "base/posix/eintr_wrapper.h"
#include "base/posix/unix_domain_socket.h"
#include "base/rand_util.h"
@@ -31,15 +30,12 @@
#include "base/strings/string_number_conversions.h"
#include "base/sys_info.h"
#include "build/build_config.h"
-#include "content/common/font_config_ipc_linux.h"
#include "content/common/zygote_commands_linux.h"
#include "content/public/common/common_sandbox_support_linux.h"
#include "content/public/common/content_descriptors.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/zygote_fork_delegate_linux.h"
#include "content/zygote/zygote_linux.h"
-#include "media/media_features.h"
-#include "ppapi/features/features.h"
#include "sandbox/linux/services/credentials.h"
#include "sandbox/linux/services/init_process_reaper.h"
#include "sandbox/linux/services/libc_interceptor.h"
@@ -49,27 +45,7 @@
#include "services/service_manager/sandbox/linux/sandbox_debug_handling_linux.h"
#include "services/service_manager/sandbox/linux/sandbox_linux.h"
#include "services/service_manager/sandbox/sandbox.h"
-#include "third_party/WebKit/public/platform/WebFontRenderStyle.h"
-#include "third_party/boringssl/src/include/openssl/crypto.h"
-#include "third_party/boringssl/src/include/openssl/rand.h"
#include "third_party/icu/source/i18n/unicode/timezone.h"
-#include "third_party/skia/include/ports/SkFontConfigInterface.h"
-#include "third_party/skia/include/ports/SkFontMgr.h"
-#include "third_party/skia/include/ports/SkFontMgr_android.h"
-
-#if BUILDFLAG(ENABLE_PLUGINS)
-#include "content/common/pepper_plugin_list.h"
-#include "content/public/common/pepper_plugin_info.h"
-#endif
-
-#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
-#include "content/public/common/cdm_info.h"
-#include "content/public/common/content_client.h"
-#endif
-
-#if BUILDFLAG(ENABLE_WEBRTC)
-#include "third_party/webrtc_overrides/init_webrtc.h" // nogncheck
-#endif
namespace content {
@@ -95,44 +71,6 @@ base::OnceClosure ClosureFromTwoClosures(base::OnceClosure one,
} // namespace
-#if BUILDFLAG(ENABLE_PLUGINS)
-// Loads the (native) libraries but does not initialize them (i.e., does not
-// call PPP_InitializeModule). This is needed by the zygote on Linux to get
-// access to the plugins before entering the sandbox.
-void PreloadPepperPlugins() {
- std::vector<PepperPluginInfo> plugins;
- ComputePepperPluginList(&plugins);
- for (const auto& plugin : plugins) {
- if (!plugin.is_internal) {
- base::NativeLibraryLoadError error;
- base::NativeLibrary library = base::LoadNativeLibrary(plugin.path,
- &error);
- VLOG_IF(1, !library) << "Unable to load plugin "
- << plugin.path.value() << " "
- << error.ToString();
-
- ignore_result(library); // Prevent release-mode warning.
- }
- }
-}
-#endif
-
-#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
-// Loads registered library CDMs but does not initialize them. This is needed by
-// the zygote on Linux to get access to the CDMs before entering the sandbox.
-void PreloadLibraryCdms() {
- std::vector<CdmInfo> cdms;
- GetContentClient()->AddContentDecryptionModules(&cdms, nullptr);
- for (const auto& cdm : cdms) {
- base::NativeLibraryLoadError error;
- base::NativeLibrary library = base::LoadNativeLibrary(cdm.path, &error);
- VLOG_IF(1, !library) << "Unable to load CDM " << cdm.path.value()
- << " (error: " << error.ToString() << ")";
- ignore_result(library); // Prevent release-mode warning.
- }
-}
-#endif // BUILDFLAG(ENABLE_LIBRARY_CDMS)
-
// This function triggers the static and lazy construction of objects that need
// to be created before imposing the sandbox.
static void ZygotePreSandboxInit() {
@@ -146,64 +84,6 @@ static void ZygotePreSandboxInit() {
// TimeZone::createDefault is called once here, the timezone ID is
// cached and there's no more need to access the file system.
std::unique_ptr<icu::TimeZone> zone(icu::TimeZone::createDefault());
-
-#if defined(ARCH_CPU_ARM_FAMILY)
- // On ARM, BoringSSL requires access to /proc/cpuinfo to determine processor
- // features. Query this before entering the sandbox.
- CRYPTO_library_init();
-#endif
-
- // Pass BoringSSL a copy of the /dev/urandom file descriptor so RAND_bytes
- // will work inside the sandbox.
- RAND_set_urandom_fd(base::GetUrandomFD());
-
-#if BUILDFLAG(ENABLE_PLUGINS)
- // Ensure access to the Pepper plugins before the sandbox is turned on.
- PreloadPepperPlugins();
-#endif
-#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
- // Ensure access to the library CDMs before the sandbox is turned on.
- PreloadLibraryCdms();
-#endif
-#if BUILDFLAG(ENABLE_WEBRTC)
- InitializeWebRtcModule();
-#endif
-
- SkFontConfigInterface::SetGlobal(new FontConfigIPC(GetSandboxFD()))->unref();
-
- // Set the android SkFontMgr for blink. We need to ensure this is done
- // before the sandbox is initialized to allow the font manager to access
- // font configuration files on disk.
- if (base::CommandLine::ForCurrentProcess()->HasSwitch(
- switches::kAndroidFontsPath)) {
- std::string android_fonts_dir =
- base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
- switches::kAndroidFontsPath);
-
- if (android_fonts_dir.size() > 0 && android_fonts_dir.back() != '/')
- android_fonts_dir += '/';
-
- SkFontMgr_Android_CustomFonts custom;
- custom.fSystemFontUse =
- SkFontMgr_Android_CustomFonts::SystemFontUse::kOnlyCustom;
- custom.fBasePath = android_fonts_dir.c_str();
-
- std::string font_config;
- std::string fallback_font_config;
- if (android_fonts_dir.find("kitkat") != std::string::npos) {
- font_config = android_fonts_dir + "system_fonts.xml";
- fallback_font_config = android_fonts_dir + "fallback_fonts.xml";
- custom.fFallbackFontsXml = fallback_font_config.c_str();
- } else {
- font_config = android_fonts_dir + "fonts.xml";
- custom.fFallbackFontsXml = nullptr;
- }
- custom.fFontsXml = font_config.c_str();
- custom.fIsolated = true;
-
- blink::WebFontRenderStyle::SetSkiaFontManager(
- SkFontMgr_New_Android(&custom));
- }
}
static bool CreateInitProcessReaper(